diff --git a/.env.example b/.env.example index 401c9020..b5fe50a3 100644 --- a/.env.example +++ b/.env.example @@ -1,26 +1,34 @@ SERVER_TYPE=http SERVER_PORT=8080 +# Server URL - Set your application url SERVER_URL=http://localhost:8080 +SENTRY_DSN= + +# Cors - * for all or set separate by commas - ex.: 'yourdomain1.com, yourdomain2.com' CORS_ORIGIN=* CORS_METHODS=GET,POST,PUT,DELETE CORS_CREDENTIALS=true -LOG_LEVEL=ERROR,WARN,DEBUG,INFO,LOG,VERBOSE,DARK,WEBHOOKS +# Determine the logs to be displayed +LOG_LEVEL=ERROR,WARN,DEBUG,INFO,LOG,VERBOSE,DARK,WEBHOOKS,WEBSOCKET LOG_COLOR=true +# Log Baileys - "fatal" | "error" | "warn" | "info" | "debug" | "trace" LOG_BAILEYS=error +# Determine how long the instance should be deleted from memory in case of no connection. +# Default time: 5 minutes +# If you don't even want an expiration, enter the value false DEL_INSTANCE=false -PROVIDER_ENABLED=false -PROVIDER_HOST=127.0.0.1 -PROVIDER_PORT=5656 -PROVIDER_PREFIX=evolution - -DATABASE_ENABLED=true +# Provider: postgresql | mysql DATABASE_PROVIDER=postgresql DATABASE_CONNECTION_URI='postgresql://user:pass@localhost:5432/evolution?schema=public' +# Client name for the database connection +# It is used to separate an API installation from another that uses the same database. DATABASE_CONNECTION_CLIENT_NAME=evolution_exchange + +# Choose the data you want to save in the application's database DATABASE_SAVE_DATA_INSTANCE=true DATABASE_SAVE_DATA_NEW_MESSAGE=true DATABASE_SAVE_MESSAGE_UPDATE=true @@ -28,11 +36,16 @@ DATABASE_SAVE_DATA_CONTACTS=true DATABASE_SAVE_DATA_CHATS=true DATABASE_SAVE_DATA_LABELS=true DATABASE_SAVE_DATA_HISTORIC=true +DATABASE_SAVE_IS_ON_WHATSAPP=true +DATABASE_SAVE_IS_ON_WHATSAPP_DAYS=7 +# RabbitMQ - Environment variables RABBITMQ_ENABLED=false RABBITMQ_URI=amqp://localhost RABBITMQ_EXCHANGE_NAME=evolution +# Global events - By enabling this variable, events from all instances are sent in the same event queue. RABBITMQ_GLOBAL_ENABLED=false +# Choose the events you want to send to RabbitMQ RABBITMQ_EVENTS_APPLICATION_STARTUP=false RABBITMQ_EVENTS_INSTANCE_CREATE=false RABBITMQ_EVENTS_INSTANCE_DELETE=false @@ -55,27 +68,38 @@ RABBITMQ_EVENTS_GROUPS_UPSERT=false RABBITMQ_EVENTS_GROUP_UPDATE=false RABBITMQ_EVENTS_GROUP_PARTICIPANTS_UPDATE=false RABBITMQ_EVENTS_CONNECTION_UPDATE=false +RABBITMQ_EVENTS_REMOVE_INSTANCE=false +RABBITMQ_EVENTS_LOGOUT_INSTANCE=false RABBITMQ_EVENTS_CALL=false RABBITMQ_EVENTS_TYPEBOT_START=false RABBITMQ_EVENTS_TYPEBOT_CHANGE_STATUS=false +# SQS - Environment variables SQS_ENABLED=false SQS_ACCESS_KEY_ID= SQS_SECRET_ACCESS_KEY= SQS_ACCOUNT_ID= SQS_REGION= +# Websocket - Environment variables WEBSOCKET_ENABLED=false WEBSOCKET_GLOBAL_EVENTS=false +# WhatsApp Business API - Environment variables +# Token used to validate the webhook on the Facebook APP WA_BUSINESS_TOKEN_WEBHOOK=evolution WA_BUSINESS_URL=https://graph.facebook.com -WA_BUSINESS_VERSION=v18.0 -WA_BUSINESS_LANGUAGE=pt_BR +WA_BUSINESS_VERSION=v20.0 +WA_BUSINESS_LANGUAGE=en_US -WEBHOOK_GLOBAL_URL='' +# Global Webhook Settings +# Each instance's Webhook URL and events will be requested at the time it is created WEBHOOK_GLOBAL_ENABLED=false +# Define a global webhook that will listen for enabled events from all instances +WEBHOOK_GLOBAL_URL='' +# With this option activated, you work with a url per webhook event, respecting the global url and the name of each event WEBHOOK_GLOBAL_WEBHOOK_BY_EVENTS=false +# Set the events you want to hear WEBHOOK_EVENTS_APPLICATION_STARTUP=false WEBHOOK_EVENTS_QRCODE_UPDATED=true WEBHOOK_EVENTS_MESSAGES_SET=true @@ -96,46 +120,75 @@ WEBHOOK_EVENTS_GROUPS_UPSERT=true WEBHOOK_EVENTS_GROUPS_UPDATE=true WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE=true WEBHOOK_EVENTS_CONNECTION_UPDATE=true +WEBHOOK_EVENTS_REMOVE_INSTANCE=false +WEBHOOK_EVENTS_LOGOUT_INSTANCE=false WEBHOOK_EVENTS_LABELS_EDIT=true WEBHOOK_EVENTS_LABELS_ASSOCIATION=true WEBHOOK_EVENTS_CALL=true +# This events is used with Typebot WEBHOOK_EVENTS_TYPEBOT_START=false WEBHOOK_EVENTS_TYPEBOT_CHANGE_STATUS=false +# This event is used to send errors WEBHOOK_EVENTS_ERRORS=false WEBHOOK_EVENTS_ERRORS_WEBHOOK= +# Name that will be displayed on smartphone connection CONFIG_SESSION_PHONE_CLIENT=Evolution API +# Browser Name = Chrome | Firefox | Edge | Opera | Safari CONFIG_SESSION_PHONE_NAME=Chrome +# Whatsapp Web version for baileys channel +# https://web.whatsapp.com/check-update?version=0&platform=web +CONFIG_SESSION_PHONE_VERSION=2.3000.1015901307 + +# Set qrcode display limit QRCODE_LIMIT=30 +# Color of the QRCode on base64 QRCODE_COLOR='#175197' +# Typebot - Environment variables TYPEBOT_ENABLED=false -TYPEBOT_SEND_MEDIA_BASE64=true +# old | latest TYPEBOT_API_VERSION=latest +# Chatwoot - Environment variables CHATWOOT_ENABLED=false -CHATWOOT_MESSAGE_READ=false -CHATWOOT_IMPORT_DATABASE_CONNECTION_URI=postgresql://user:pass@host:5432/dbname -CHATWOOT_IMPORT_PLACEHOLDER_MEDIA_MESSAGE=false +# If you leave this option as false, when deleting the message for everyone on WhatsApp, it will not be deleted on Chatwoot. +CHATWOOT_MESSAGE_READ=true +# If you leave this option as true, when sending a message in Chatwoot, the client's last message will be marked as read on WhatsApp. +CHATWOOT_MESSAGE_DELETE=true +# If you leave this option as true, a contact will be created on Chatwoot to provide the QR Code and update messages about the instance. +CHATWOOT_BOT_CONTACT=true +# This db connection is used to import messages from whatsapp to chatwoot database +CHATWOOT_IMPORT_DATABASE_CONNECTION_URI=postgresql://user:passwprd@host:5432/chatwoot?sslmode=disable +CHATWOOT_IMPORT_PLACEHOLDER_MEDIA_MESSAGE=true +# OpenAI - Environment variables OPENAI_ENABLED=false -OPENAI_API_KEY_GLOBAL= +# Dify - Environment variables DIFY_ENABLED=false +# Cache - Environment variables +# Redis Cache enabled CACHE_REDIS_ENABLED=true CACHE_REDIS_URI=redis://localhost:6379/6 +CACHE_REDIS_TTL=604800 +# Prefix serves to differentiate data from one installation to another that are using the same redis CACHE_REDIS_PREFIX_KEY=evolution +# Enabling this variable will save the connection information in Redis and not in the database. CACHE_REDIS_SAVE_INSTANCES=false +# Local Cache enabled CACHE_LOCAL_ENABLED=false +# Amazon S3 - Environment variables S3_ENABLED=false S3_ACCESS_KEY= S3_SECRET_KEY= S3_BUCKET=evolution S3_PORT=443 S3_ENDPOINT=s3.domain.com +S3_REGION=eu-west-3 S3_USE_SSL=true # AMAZON S3 - Environment variables @@ -144,6 +197,7 @@ S3_USE_SSL=true # S3_ACCESS_KEY=access_key_id # S3_SECRET_KEY=secret_access_key # S3_ENDPOINT=s3.amazonaws.com # region: s3.eu-west-3.amazonaws.com +# S3_REGION=eu-west-3 # MINIO Use SSL - Environment variables # S3_ENABLED=true @@ -153,7 +207,18 @@ S3_USE_SSL=true # S3_PORT=443 # S3_ENDPOINT=s3.domain.com # S3_USE_SSL=true +# S3_REGION=eu-south +# Define a global apikey to access all instances. +# OBS: This key must be inserted in the request header to create an instance. AUTHENTICATION_API_KEY=429683C4C977415CAAFCCE10F7D57E11 +# If you leave this option as true, the instances will be exposed in the fetch instances endpoint. AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES=true LANGUAGE=en + +# Define a global proxy to be used if the instance does not have one +# PROXY_HOST= +# PROXY_PORT=80 +# PROXY_PROTOCOL=http +# PROXY_USERNAME= +# PROXY_PASSWORD= \ No newline at end of file diff --git a/.eslintrc.js b/.eslintrc.js index f805da92..74a4c2ea 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,50 +1,42 @@ module.exports = { parser: '@typescript-eslint/parser', parserOptions: { - sourceType: 'CommonJS', + sourceType: 'CommonJS', }, - plugins: [ - '@typescript-eslint', - 'simple-import-sort', - 'import' - ], - extends: [ - 'eslint:recommended', - 'plugin:@typescript-eslint/recommended', - 'plugin:prettier/recommended' - ], + plugins: ['@typescript-eslint', 'simple-import-sort', 'import'], + extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended'], globals: { - Atomics: 'readonly', - SharedArrayBuffer: 'readonly', + Atomics: 'readonly', + SharedArrayBuffer: 'readonly', }, root: true, env: { - node: true, - jest: true, + node: true, + jest: true, }, ignorePatterns: ['.eslintrc.js'], rules: { - '@typescript-eslint/interface-name-prefix': 'off', - '@typescript-eslint/explicit-function-return-type': 'off', - '@typescript-eslint/explicit-module-boundary-types': 'off', - '@typescript-eslint/no-explicit-any': 'off', - '@typescript-eslint/no-empty-function': 'off', - '@typescript-eslint/no-non-null-assertion': 'off', - '@typescript-eslint/no-unused-vars': 'error', - 'import/first': 'error', - 'import/no-duplicates': 'error', - 'simple-import-sort/imports': 'error', - 'simple-import-sort/exports': 'error', - '@typescript-eslint/ban-types': [ - 'error', - { - extendDefaults: true, - types: { - '{}': false, - Object: false, - }, + '@typescript-eslint/interface-name-prefix': 'off', + '@typescript-eslint/explicit-function-return-type': 'off', + '@typescript-eslint/explicit-module-boundary-types': 'off', + '@typescript-eslint/no-explicit-any': 'off', + '@typescript-eslint/no-empty-function': 'off', + '@typescript-eslint/no-non-null-assertion': 'off', + '@typescript-eslint/no-unused-vars': 'error', + 'import/first': 'error', + 'import/no-duplicates': 'error', + 'simple-import-sort/imports': 'error', + 'simple-import-sort/exports': 'error', + '@typescript-eslint/ban-types': [ + 'error', + { + extendDefaults: true, + types: { + '{}': false, + Object: false, }, - ], - 'prettier/prettier': ['error', { endOfLine: 'auto' }], + }, + ], + 'prettier/prettier': ['error', { endOfLine: 'auto' }], }, -}; \ No newline at end of file +}; diff --git a/.gitignore b/.gitignore index 15dee235..3c511120 100644 --- a/.gitignore +++ b/.gitignore @@ -18,10 +18,9 @@ lerna-debug.log* /docker-compose-data /docker-data -docker-compose.yaml - # Package /yarn.lock +/pnpm-lock.yaml /package-lock.json # IDEs @@ -31,6 +30,7 @@ docker-compose.yaml !.vscode/launch.json !.vscode/extensions.json .nova/* +.idea/* # Project related /instances/* @@ -45,3 +45,5 @@ docker-compose.yaml .DS_Store *.DS_Store .tool-versions + +/prisma/migrations/* diff --git a/CHANGELOG.md b/CHANGELOG.md index e467485a..ad16f461 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,123 @@ +# 2.1.1 (2024-09-22 10:31) + +### Features + +* Define a global proxy to be used if the instance does not have one +* Save is on whatsapp on the database +* Add headers to the instance's webhook registration +* Debounce message break is now "\n" instead of white space +* Single view messages are now supported in chatwoot +* Chatbots can now send any type of media + +### Fixed + +* Validate if cache exists before accessing it +* Missing autoCreate chatwoot in instance create +* Fixed bugs in the frontend, on the event screens +* Fixed use chatwoot with evolution channel +* Fix chatwoot reply quote with Cloud API +* Use exchange name from .env on RabbitMQ +* Fixed chatwoot screen +* It is now possible to send images via the Evolution Channel +* Removed "version" from docker-compose as it is obsolete (https://dev.to/ajeetraina/do-we-still-use-version-in-compose-3inp) +* Fixed typebot ignoreJids being used only from default settings +* Fixed Chatwoot inbox creation on save +* Changed axios timeout for manager requests for 30s +* Update in Baileys version that fixes timeout when updating profile picture +* Fixed issue when sending links in markdown by chatbots like Dify +* Fixed issue with chatbots not respecting settings + +# 2.1.0 (2024-08-26 15:33) + +### Features + +* Improved layout manager +* Translation in manager: English, Portuguese, Spanish and French +* Evolution Bot Integration +* Option to disable chatwoot bot contact with CHATWOOT_BOT_CONTACT +* Added flowise integration +* Added evolution channel on instance create +* Change in license to Apache-2.0 +* Mark All in events + +### Fixed + +* Refactor integrations structure for modular system +* Fixed dify agent integration +* Update Baileys Version +* Fixed proxy config in manager +* Fixed send messages in groups +* S3 saving media sent from me +* Fixed duplication bot when use startTypebot + +### Break Changes + +* Payloads for events changed (create Instance and set events). Check postman to understand + +# 2.0.10 (2024-08-16 16:23) + +### Features + +* OpenAI send images when markdown +* Dify send images when markdown +* Sentry implemented + +### Fixed + +* Fix on get profilePicture +* Added S3_REGION on minio settings + +# 2.0.9 (2024-08-15 12:31) + +### Features + +* Added ignoreJids in chatwoot settings +* Dify now identifies images +* Openai now identifies images + +### Fixed + +* Path mapping & deps fix & bundler changed to tsup +* Improve database scripts to retrieve the provider from env file +* Update contacts database with unique index +* Save chat name +* Correction of media as attachments in chatwoot when using a Meta API Instance and not Baileys +* Update Baileys version 6.7.6 +* Deprecate buttons and list in new Baileys version +* Changed labels to be unique on the same instance +* Remove instance from redis even if using database +* Unified integration session system so they don't overlap +* Temporary fix for pictureUrl bug in groups +* Fix on migrations + +# 2.0.9-rc (2024-08-09 18:00) + +### Features + +* Added general session button in typebot, dify and openai in manager +* Added compatibility with mysql through prisma + +### Fixed + +* Import contacts with image in chatwoot +* Fix conversationId when is dify agent +* Fixed loading of selects in the manager +* Add restart button to sessions screen +* Adjustments to docker files +* StopBotFromMe working with chatwoot + +# 2.0.8-rc (2024-08-08 20:23) + +### Features + +* Variables passed to the input in dify +* OwnerJid passed to typebot +* Function for openai assistant added + +### Fixed + +* Adjusts in telemetry + # 2.0.7-rc (2024-08-03 14:04) ### Fixed diff --git a/Docker/.env.example b/Docker/.env.example deleted file mode 100644 index 32c44685..00000000 --- a/Docker/.env.example +++ /dev/null @@ -1,163 +0,0 @@ -# Server URL - Set your application url -SERVER_URL=http://localhost:8080 - -# Cors - * for all or set separate by commas - ex.: 'yourdomain1.com, yourdomain2.com' -CORS_ORIGIN=* -CORS_METHODS=POST,GET,PUT,DELETE -CORS_CREDENTIALS=true - -# Determine the logs to be displayed -LOG_LEVEL=ERROR,WARN,DEBUG,INFO,LOG,VERBOSE,DARK,WEBHOOKS -LOG_COLOR=true -# Log Baileys - "fatal" | "error" | "warn" | "info" | "debug" | "trace" -LOG_BAILEYS=error - -# Determine how long the instance should be deleted from memory in case of no connection. -# Default time: 5 minutes -# If you don't even want an expiration, enter the value false -DEL_INSTANCE=false -DEL_TEMP_INSTANCES=true # Delete instances with status closed on start - -# Temporary data storage -STORE_MESSAGES=true -STORE_MESSAGE_UP=true -STORE_CONTACTS=true -STORE_CHATS=true - -# Set Store Interval in Seconds (7200 = 2h) -CLEAN_STORE_CLEANING_INTERVAL=7200 -CLEAN_STORE_MESSAGES=true -CLEAN_STORE_MESSAGE_UP=true -CLEAN_STORE_CONTACTS=true -CLEAN_STORE_CHATS=true - -# Permanent data storage -DATABASE_ENABLED=false -DATABASE_CONNECTION_URI=mongodb://root:root@mongodb:27017/?authSource=admin&readPreference=primary&ssl=false&directConnection=true -DATABASE_CONNECTION_CLIENT_NAME=evdocker - -# Choose the data you want to save in the application's database or store -DATABASE_SAVE_DATA_INSTANCE=false -DATABASE_SAVE_DATA_NEW_MESSAGE=false -DATABASE_SAVE_MESSAGE_UPDATE=false -DATABASE_SAVE_DATA_CONTACTS=false -DATABASE_SAVE_DATA_CHATS=false - -RABBITMQ_ENABLED=false -RABBITMQ_URI=amqp://guest:guest@rabbitmq:5672 -RABBITMQ_EXCHANGE_NAME=evolution_exchange -RABBITMQ_GLOBAL_ENABLED=false -RABBITMQ_EVENTS_APPLICATION_STARTUP=false -RABBITMQ_EVENTS_QRCODE_UPDATED=true -RABBITMQ_EVENTS_MESSAGES_SET=true -RABBITMQ_EVENTS_MESSAGES_UPSERT=true -RABBITMQ_EVENTS_MESSAGES_EDITED=true -RABBITMQ_EVENTS_MESSAGES_UPDATE=true -RABBITMQ_EVENTS_MESSAGES_DELETE=true -RABBITMQ_EVENTS_SEND_MESSAGE=true -RABBITMQ_EVENTS_CONTACTS_SET=true -RABBITMQ_EVENTS_CONTACTS_UPSERT=true -RABBITMQ_EVENTS_CONTACTS_UPDATE=true -RABBITMQ_EVENTS_PRESENCE_UPDATE=true -RABBITMQ_EVENTS_CHATS_SET=true -RABBITMQ_EVENTS_CHATS_UPSERT=true -RABBITMQ_EVENTS_CHATS_UPDATE=true -RABBITMQ_EVENTS_CHATS_DELETE=true -RABBITMQ_EVENTS_GROUPS_UPSERT=true -RABBITMQ_EVENTS_GROUPS_UPDATE=true -RABBITMQ_EVENTS_GROUP_PARTICIPANTS_UPDATE=true -RABBITMQ_EVENTS_CONNECTION_UPDATE=true -RABBITMQ_EVENTS_LABELS_EDIT=true -RABBITMQ_EVENTS_LABELS_ASSOCIATION=true -RABBITMQ_EVENTS_CALL=true -RABBITMQ_EVENTS_TYPEBOT_START=false -RABBITMQ_EVENTS_TYPEBOT_CHANGE_STATUS=false - -WEBSOCKET_ENABLED=false -WEBSOCKET_GLOBAL_EVENTS=false - -WA_BUSINESS_TOKEN_WEBHOOK=evolution -WA_BUSINESS_URL=https://graph.facebook.com -WA_BUSINESS_VERSION=v18.0 -WA_BUSINESS_LANGUAGE=pt_BR - -SQS_ENABLED=false -SQS_ACCESS_KEY_ID= -SQS_SECRET_ACCESS_KEY= -SQS_ACCOUNT_ID= -SQS_REGION= - -# Global Webhook Settings -# Each instance's Webhook URL and events will be requested at the time it is created -## Define a global webhook that will listen for enabled events from all instances -WEBHOOK_GLOBAL_URL='' -WEBHOOK_GLOBAL_ENABLED=false -# With this option activated, you work with a url per webhook event, respecting the global url and the name of each event -WEBHOOK_GLOBAL_WEBHOOK_BY_EVENTS=false -## Set the events you want to hear -WEBHOOK_EVENTS_APPLICATION_STARTUP=false -WEBHOOK_EVENTS_QRCODE_UPDATED=true -WEBHOOK_EVENTS_MESSAGES_SET=true -WEBHOOK_EVENTS_MESSAGES_UPSERT=true -WEBHOOK_EVENTS_MESSAGES_EDITED=true -WEBHOOK_EVENTS_MESSAGES_UPDATE=true -WEBHOOK_EVENTS_MESSAGES_DELETE=true -WEBHOOK_EVENTS_SEND_MESSAGE=true -WEBHOOK_EVENTS_CONTACTS_SET=true -WEBHOOK_EVENTS_CONTACTS_UPSERT=true -WEBHOOK_EVENTS_CONTACTS_UPDATE=true -WEBHOOK_EVENTS_PRESENCE_UPDATE=true -WEBHOOK_EVENTS_CHATS_SET=true -WEBHOOK_EVENTS_CHATS_UPSERT=true -WEBHOOK_EVENTS_CHATS_UPDATE=true -WEBHOOK_EVENTS_CHATS_DELETE=true -WEBHOOK_EVENTS_GROUPS_UPSERT=true -WEBHOOK_EVENTS_GROUPS_UPDATE=true -WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE=true -WEBHOOK_EVENTS_CONNECTION_UPDATE=true -WEBHOOK_EVENTS_LABELS_EDIT=true -WEBHOOK_EVENTS_LABELS_ASSOCIATION=true -WEBHOOK_EVENTS_CALL=true -# This events is used with Typebot -WEBHOOK_EVENTS_TYPEBOT_START=false -WEBHOOK_EVENTS_TYPEBOT_CHANGE_STATUS=false -# This event is used to send errors -WEBHOOK_EVENTS_ERRORS=false -WEBHOOK_EVENTS_ERRORS_WEBHOOK= - -# Name that will be displayed on smartphone connection -CONFIG_SESSION_PHONE_CLIENT=EvolutionAPI -# Browser Name = Chrome | Firefox | Edge | Opera | Safari -CONFIG_SESSION_PHONE_NAME=Chrome - -# Set qrcode display limit -QRCODE_LIMIT=30 -QRCODE_COLOR='#198754' - -# old | latest -TYPEBOT_API_VERSION=latest -TYPEBOT_KEEP_OPEN=false - -#Chatwoot -# If you leave this option as false, when deleting the message for everyone on WhatsApp, it will not be deleted on Chatwoot. -CHATWOOT_MESSAGE_DELETE=false # false | true -# If you leave this option as true, when sending a message in Chatwoot, the client's last message will be marked as read on WhatsApp. -CHATWOOT_MESSAGE_READ=false # false | true -# This db connection is used to import messages from whatsapp to chatwoot database -CHATWOOT_IMPORT_DATABASE_CONNECTION_URI=postgres://user:password@hostname:port/dbname?sslmode=disable -CHATWOOT_IMPORT_DATABASE_PLACEHOLDER_MEDIA_MESSAGE=true - -CACHE_REDIS_ENABLED=false -CACHE_REDIS_URI=redis://redis:6379 -CACHE_REDIS_PREFIX_KEY=evolution -CACHE_REDIS_TTL=604800 -CACHE_REDIS_SAVE_INSTANCES=false -CACHE_LOCAL_ENABLED=false -CACHE_LOCAL_TTL=604800 - -## Define a global apikey to access all instances. -### OBS: This key must be inserted in the request header to create an instance. -AUTHENTICATION_API_KEY=B6D711FCDE4D4FD5936544120E713976 -AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES=true - -LANGUAGE=en # pt-BR, en diff --git a/Docker/docker-compose.yaml b/Docker/docker-compose.yaml deleted file mode 100644 index 4a2af41b..00000000 --- a/Docker/docker-compose.yaml +++ /dev/null @@ -1,22 +0,0 @@ -version: '3.3' - -services: - - api: - container_name: evolution_api - image: atendai/evolution-api - restart: always - ports: - - 8080:8080 - volumes: - - evolution_instances:/evolution/instances - - evolution_store:/evolution/store - env_file: - - .env - command: ['node', './dist/src/main.js'] - expose: - - 8080 - -volumes: - evolution_instances: - evolution_store: diff --git a/Docker/evolution-api-all-services/.env.example b/Docker/evolution-api-all-services/.env.example deleted file mode 100644 index 18fba6bd..00000000 --- a/Docker/evolution-api-all-services/.env.example +++ /dev/null @@ -1,101 +0,0 @@ -# Server URL - Set your application url -SERVER_URL='http://localhost:8080' - -# Cors - * for all or set separate by commas - ex.: 'yourdomain1.com, yourdomain2.com' -CORS_ORIGIN='*' -CORS_METHODS='POST,GET,PUT,DELETE' -CORS_CREDENTIALS=true - -# Determine the logs to be displayed -LOG_LEVEL='ERROR,WARN,DEBUG,INFO,LOG,VERBOSE,DARK,WEBHOOKS' -LOG_COLOR=true -# Log Baileys - "fatal" | "error" | "warn" | "info" | "debug" | "trace" -LOG_BAILEYS=error - -# Determine how long the instance should be deleted from memory in case of no connection. -# Default time: 5 minutes -# If you don't even want an expiration, enter the value false -DEL_INSTANCE=false -DEL_TEMP_INSTANCES=true # Delete instances with status closed on start - -# Temporary data storage -STORE_MESSAGES=true -STORE_MESSAGE_UP=true -STORE_CONTACTS=true -STORE_CHATS=true - -# Set Store Interval in Seconds (7200 = 2h) -CLEAN_STORE_CLEANING_INTERVAL=7200 -CLEAN_STORE_MESSAGES=true -CLEAN_STORE_MESSAGE_UP=true -CLEAN_STORE_CONTACTS=true -CLEAN_STORE_CHATS=true - -# Permanent data storage -DATABASE_ENABLED=true -DATABASE_CONNECTION_URI=mongodb://root:root@mongodb:27017/?authSource=admin & -readPreference=primary & -ssl=false & -directConnection=true -DATABASE_CONNECTION_CLIENT_NAME=evolution - -# Choose the data you want to save in the application's database or store -DATABASE_SAVE_DATA_INSTANCE=false -DATABASE_SAVE_DATA_NEW_MESSAGE=false -DATABASE_SAVE_MESSAGE_UPDATE=false -DATABASE_SAVE_DATA_CONTACTS=false -DATABASE_SAVE_DATA_CHATS=false - -# Global Webhook Settings -# Each instance's Webhook URL and events will be requested at the time it is created -## Define a global webhook that will listen for enabled events from all instances -WEBHOOK_GLOBAL_URL='' -WEBHOOK_GLOBAL_ENABLED=false -# With this option activated, you work with a url per webhook event, respecting the global url and the name of each event -WEBHOOK_GLOBAL_WEBHOOK_BY_EVENTS=false -## Set the events you want to hear -WEBHOOK_EVENTS_APPLICATION_STARTUP=false -WEBHOOK_EVENTS_QRCODE_UPDATED=true -WEBHOOK_EVENTS_MESSAGES_SET=true -WEBHOOK_EVENTS_MESSAGES_UPSERT=true -WEBHOOK_EVENTS_MESSAGES_EDITED=true -WEBHOOK_EVENTS_MESSAGES_UPDATE=true -WEBHOOK_EVENTS_MESSAGES_DELETE=true -WEBHOOK_EVENTS_SEND_MESSAGE=true -WEBHOOK_EVENTS_CONTACTS_SET=true -WEBHOOK_EVENTS_CONTACTS_UPSERT=true -WEBHOOK_EVENTS_CONTACTS_UPDATE=true -WEBHOOK_EVENTS_PRESENCE_UPDATE=true -WEBHOOK_EVENTS_CHATS_SET=true -WEBHOOK_EVENTS_CHATS_UPSERT=true -WEBHOOK_EVENTS_CHATS_UPDATE=true -WEBHOOK_EVENTS_CHATS_DELETE=true -WEBHOOK_EVENTS_GROUPS_UPSERT=true -WEBHOOK_EVENTS_GROUPS_UPDATE=true -WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE=true -WEBHOOK_EVENTS_CONNECTION_UPDATE=true -WEBHOOK_EVENTS_LABELS_EDIT=true -WEBHOOK_EVENTS_LABELS_ASSOCIATION=true - -# Name that will be displayed on smartphone connection -CONFIG_SESSION_PHONE_CLIENT='Evolution API' -# Browser Name = chrome | firefox | edge | opera | safari -CONFIG_SESSION_PHONE_NAME=chrome - -# Set qrcode display limit -QRCODE_LIMIT=30 - -CACHE_REDIS_ENABLED=false -CACHE_REDIS_URI=redis://redis:6379 -CACHE_REDIS_PREFIX_KEY=evolution -CACHE_REDIS_TTL=604800 -CACHE_REDIS_SAVE_INSTANCES=false -CACHE_LOCAL_ENABLED=false -CACHE_LOCAL_TTL=604800 - -## Define a global apikey to access all instances. -### OBS: This key must be inserted in the request header to create an instance. -AUTHENTICATION_API_KEY='B6D711FCDE4D4FD5936544120E713976' -AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES=true -# Set the instance name and webhook url to create an instance in init the application -# With this option activated, you work with a url per webhook event, respecting the local url and the name of each event diff --git a/Docker/evolution-api-all-services/docker-compose.yaml b/Docker/evolution-api-all-services/docker-compose.yaml deleted file mode 100644 index 5f936cd1..00000000 --- a/Docker/evolution-api-all-services/docker-compose.yaml +++ /dev/null @@ -1,91 +0,0 @@ -version: '3.3' - -services: - - mongodb: - container_name: mongodb - image: mongo - restart: on-failure - ports: - - 27017:27017 - environment: - - MONGO_INITDB_ROOT_USERNAME=root - - MONGO_INITDB_ROOT_PASSWORD=root - - PUID=1000 - - PGID=1000 - volumes: - - evolution_mongodb_data:/data/db - - evolution_mongodb_configdb:/data/configdb - expose: - - 27017 - - mongo-express: - container_name: mongodb-express - image: mongo-express - restart: on-failure - ports: - - 8081:8081 - depends_on: - - mongodb - environment: - ME_CONFIG_BASICAUTH_USERNAME: root - ME_CONFIG_BASICAUTH_PASSWORD: root - ME_CONFIG_MONGODB_SERVER: mongodb - ME_CONFIG_MONGODB_ADMINUSERNAME: root - ME_CONFIG_MONGODB_ADMINPASSWORD: root - links: - - mongodb - - redis: - container_name: redis - image: redis:latest - restart: on-failure - ports: - - 6379:6379 - command: > - redis-server - --port 6379 - --appendonly yes - volumes: - - evolution_redis:/data - - rebrow: - container_name: rebrow - image: marian/rebrow - restart: on-failure - depends_on: - - redis - ports: - - 5001:5001 - links: - - redis - - api: - container_name: evolution_api - image: atendai/evolution-api - restart: always - depends_on: - - mongodb - - redis - ports: - - 8080:8080 - volumes: - - evolution_instances:/evolution/instances - - evolution_store:/evolution/store - env_file: - - .env - command: ['node', './dist/src/main.js'] - expose: - - 8080 - -volumes: - evolution_mongodb_data: - evolution_mongodb_configdb: - evolution_redis: - evolution_instances: - evolution_store: - -networks: - evolution-net: - external: true - diff --git a/Docker/minio/docker-compose.yaml b/Docker/minio/docker-compose.yaml new file mode 100644 index 00000000..8791627a --- /dev/null +++ b/Docker/minio/docker-compose.yaml @@ -0,0 +1,31 @@ +version: '3.3' + +services: + minio: + container_name: minio + image: quay.io/minio/minio + networks: + - evolution-net + command: server /data --console-address ":9001" + restart: always + ports: + - 5432:5432 + environment: + - MINIO_ROOT_USER=USER + - MINIO_ROOT_PASSWORD=PASSWORD + - MINIO_BROWSER_REDIRECT_URL=http:/localhost:9001 + - MINIO_SERVER_URL=http://localhost:9000 + volumes: + - minio_data:/data + expose: + - 9000 + - 9001 + +volumes: + minio_data: + + +networks: + evolution-net: + name: evolution-net + driver: bridge diff --git a/Docker/mongodb/docker-compose.yaml b/Docker/mongodb/docker-compose.yaml deleted file mode 100644 index 01220c54..00000000 --- a/Docker/mongodb/docker-compose.yaml +++ /dev/null @@ -1,42 +0,0 @@ -version: '3.3' - -services: - mongodb: - container_name: mongodb - image: mongo - restart: always - ports: - - 27017:27017 - environment: - - MONGO_INITDB_ROOT_USERNAME=root - - MONGO_INITDB_ROOT_PASSWORD=root - - PUID=1000 - - PGID=1000 - volumes: - - evolution_mongodb_data:/data/db - - evolution_mongodb_configdb:/data/configdb - expose: - - 27017 - - mongo-express: - image: mongo-express - environment: - ME_CONFIG_BASICAUTH_USERNAME: root - ME_CONFIG_BASICAUTH_PASSWORD: root - ME_CONFIG_MONGODB_SERVER: mongodb - ME_CONFIG_MONGODB_ADMINUSERNAME: root - ME_CONFIG_MONGODB_ADMINPASSWORD: root - ports: - - 8081:8081 - links: - - mongodb - -volumes: - evolution_mongodb_data: - evolution_mongodb_configdb: - - -networks: - evolution-net: - name: evolution-net - driver: bridge diff --git a/Docker/mysql/docker-compose.yaml b/Docker/mysql/docker-compose.yaml new file mode 100644 index 00000000..2e213878 --- /dev/null +++ b/Docker/mysql/docker-compose.yaml @@ -0,0 +1,27 @@ +version: '3.3' + +services: + mysql: + container_name: mysql + image: percona/percona-server:8.0 + networks: + - evolution-net + restart: always + ports: + - 3306:3306 + environment: + - MYSQL_ROOT_PASSWORD=root + - TZ=America/Bahia + volumes: + - mysql_data:/var/lib/mysql + expose: + - 3306 + +volumes: + mysql_data: + + +networks: + evolution-net: + name: evolution-net + driver: bridge diff --git a/Docker/postgres/docker-compose.yaml b/Docker/postgres/docker-compose.yaml new file mode 100644 index 00000000..bf07a461 --- /dev/null +++ b/Docker/postgres/docker-compose.yaml @@ -0,0 +1,42 @@ +version: '3.3' + +services: + postgres: + container_name: postgres + image: postgres:15 + networks: + - evolution-net + command: ["postgres", "-c", "max_connections=1000"] + restart: always + ports: + - 5432:5432 + environment: + - POSTGRES_PASSWORD=PASSWORD + volumes: + - postgres_data:/var/lib/postgresql/data + expose: + - 5432 + + pgadmin: + image: dpage/pgadmin4:latest + networks: + - evolution-net + environment: + - PGADMIN_DEFAULT_EMAIL=EMAIL + - PGADMIN_DEFAULT_PASSWORD=PASSWORD + volumes: + - pgadmin_data:/var/lib/pgadmin + ports: + - 4000:80 + links: + - postgres + +volumes: + postgres_data: + pgadmin_data: + + +networks: + evolution-net: + name: evolution-net + driver: bridge diff --git a/Docker/rabbitmq/docker-compose.yaml b/Docker/rabbitmq/docker-compose.yaml new file mode 100644 index 00000000..b8c1ed6a --- /dev/null +++ b/Docker/rabbitmq/docker-compose.yaml @@ -0,0 +1,25 @@ +version: '3.3' + +services: + rabbitmq: + container_name: rabbitmq + image: rabbitmq:management + environment: + - RABBITMQ_ERLANG_COOKIE=33H2CdkzF5WrnJ4ud6nkUdRTKXvbCHeFjvVL71p + - RABBITMQ_DEFAULT_VHOST=default + - RABBITMQ_DEFAULT_USER=USER + - RABBITMQ_DEFAULT_PASS=PASSWORD + volumes: + - rabbitmq_data:/var/lib/rabbitmq/ + ports: + - 5672:5672 + - 15672:15672 + +volumes: + rabbitmq_data: + + +networks: + evolution-net: + name: evolution-net + driver: bridge diff --git a/Docker/redis/docker-compose.yaml b/Docker/redis/docker-compose.yaml index 297b11db..a9b4cf67 100644 --- a/Docker/redis/docker-compose.yaml +++ b/Docker/redis/docker-compose.yaml @@ -3,6 +3,8 @@ version: '3.3' services: redis: image: redis:latest + networks: + - evolution-net container_name: redis command: > redis-server --port 6379 --appendonly yes diff --git a/Docker/scripts/deploy_database.sh b/Docker/scripts/deploy_database.sh index c9a6813a..fde46d12 100755 --- a/Docker/scripts/deploy_database.sh +++ b/Docker/scripts/deploy_database.sh @@ -10,14 +10,16 @@ if [[ "$DATABASE_PROVIDER" == "postgresql" || "$DATABASE_PROVIDER" == "mysql" ]] export DATABASE_URL echo "Deploying migrations for $DATABASE_PROVIDER" echo "Database URL: $DATABASE_URL" - npx prisma migrate deploy --schema ./prisma/$DATABASE_PROVIDER-schema.prisma + # rm -rf ./prisma/migrations + # cp -r ./prisma/$DATABASE_PROVIDER-migrations ./prisma/migrations + npm run db:deploy if [ $? -ne 0 ]; then echo "Migration failed" exit 1 else echo "Migration succeeded" fi - npx prisma generate --schema ./prisma/$DATABASE_PROVIDER-schema.prisma + npm run db:generate if [ $? -ne 0 ]; then echo "Prisma generate failed" exit 1 diff --git a/Docker/scripts/generate_database.sh b/Docker/scripts/generate_database.sh index 570a60d8..892682ef 100644 --- a/Docker/scripts/generate_database.sh +++ b/Docker/scripts/generate_database.sh @@ -10,7 +10,7 @@ if [[ "$DATABASE_PROVIDER" == "postgresql" || "$DATABASE_PROVIDER" == "mysql" ]] export DATABASE_URL echo "Generating database for $DATABASE_PROVIDER" echo "Database URL: $DATABASE_URL" - npx prisma generate --schema=prisma/$DATABASE_PROVIDER-schema.prisma + npm run db:generate if [ $? -ne 0 ]; then echo "Prisma generate failed" exit 1 diff --git a/Docker/evolution_api_v2.yaml b/Docker/swarm/evolution_api_v2.yaml similarity index 95% rename from Docker/evolution_api_v2.yaml rename to Docker/swarm/evolution_api_v2.yaml index 7c2f3f90..679e7368 100644 --- a/Docker/evolution_api_v2.yaml +++ b/Docker/swarm/evolution_api_v2.yaml @@ -2,7 +2,7 @@ version: "3.7" services: evolution_v2: - image: atendai/evolution-api:v2.0.4-rc + image: atendai/evolution-api:v2.0.10 volumes: - evolution_instances:/evolution/instances networks: @@ -10,11 +10,6 @@ services: environment: - SERVER_URL=https://evo2.site.com - DEL_INSTANCE=false - - PROVIDER_ENABLED=false - - PROVIDER_HOST=127.0.0.1 - - PROVIDER_PORT=5656 - - PROVIDER_PREFIX=evolution_v2 - - DATABASE_ENABLED=true - DATABASE_PROVIDER=postgresql - DATABASE_CONNECTION_URI=postgresql://postgres:SENHA@postgres:5432/evolution - DATABASE_SAVE_DATA_INSTANCE=true @@ -97,7 +92,7 @@ services: - WEBHOOK_EVENTS_ERRORS_WEBHOOK= - CONFIG_SESSION_PHONE_CLIENT=Evolution API V2 - CONFIG_SESSION_PHONE_NAME=Chrome - - CONFIG_SESSION_PHONE_VERSION=2.2413.51 + - CONFIG_SESSION_PHONE_VERSION=2.3000.1015901307 - QRCODE_LIMIT=30 - OPENAI_ENABLED=true - DIFY_ENABLED=true diff --git a/Dockerfile b/Dockerfile index 1908743d..f9fa812c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,21 +3,23 @@ FROM node:20-alpine AS builder RUN apk update && \ apk add git ffmpeg wget curl bash -LABEL version="2.0.4-beta" description="Api to control whatsapp features through http requests." +LABEL version="2.1.1" description="Api to control whatsapp features through http requests." LABEL maintainer="Davidson Gomes" git="https://github.com/DavidsonGomes" -LABEL contact="contato@agenciadgcode.com" +LABEL contact="contato@atendai.com" WORKDIR /evolution COPY ./package.json ./tsconfig.json ./ -RUN npm install +RUN npm install -f COPY ./src ./src COPY ./public ./public COPY ./prisma ./prisma COPY ./manager ./manager COPY ./.env.example ./.env +COPY ./runWithProvider.js ./ +COPY ./tsup.config.ts ./ COPY ./Docker ./Docker @@ -39,14 +41,15 @@ WORKDIR /evolution COPY --from=builder /evolution/package.json ./package.json COPY --from=builder /evolution/package-lock.json ./package-lock.json -RUN npm install --omit=dev - +COPY --from=builder /evolution/node_modules ./node_modules COPY --from=builder /evolution/dist ./dist COPY --from=builder /evolution/prisma ./prisma COPY --from=builder /evolution/manager ./manager COPY --from=builder /evolution/public ./public COPY --from=builder /evolution/.env ./.env COPY --from=builder /evolution/Docker ./Docker +COPY --from=builder /evolution/runWithProvider.js ./runWithProvider.js +COPY --from=builder /evolution/tsup.config.ts ./tsup.config.ts ENV DOCKER_ENV=true diff --git a/Extras/appsmith/manager.json b/Extras/appsmith/manager.json deleted file mode 100644 index 94932864..00000000 --- a/Extras/appsmith/manager.json +++ /dev/null @@ -1 +0,0 @@ -{"clientSchemaVersion":1.0,"serverSchemaVersion":6.0,"exportedApplication":{"name":"manager","isPublic":true,"pages":[{"id":"Home","isDefault":true}],"publishedPages":[{"id":"Home","isDefault":true}],"viewMode":false,"appIsExample":false,"unreadCommentThreads":0.0,"clonedFromApplicationId":"64da025f98d1c41c0da60e90","color":"#F5D1D1","icon":"email","slug":"manager","unpublishedAppLayout":{"type":"FLUID"},"publishedAppLayout":{"type":"FLUID"},"unpublishedCustomJSLibs":[],"publishedCustomJSLibs":[],"evaluationVersion":2.0,"applicationVersion":2.0,"collapseInvisibleWidgets":true,"isManualUpdate":false,"deleted":false},"datasourceList":[],"customJSLibList":[],"pageList":[{"unpublishedPage":{"name":"Home","slug":"home","customSlug":"","layouts":[{"viewMode":false,"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":4896.0,"snapColumns":64.0,"detachFromLayout":true,"widgetId":"0","topRow":0.0,"bottomRow":470.0,"containerStyle":"none","snapRows":124.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"version":83.0,"minHeight":1292.0,"dynamicTriggerPathList":[],"parentColumnSpace":1.0,"dynamicBindingPathList":[],"leftColumn":0.0,"children":[{"boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}","borderColor":"#E0DEDE","isVisibleDownload":true,"iconSVG":"https://appcdn.appsmith.com/static/media/icon.24905525921dd6f5ff46d0dd843b9e12.svg","topRow":6.0,"isSortable":true,"type":"TABLE_WIDGET_V2","inlineEditingSaveOption":"ROW_LEVEL","animateLoading":true,"dynamicBindingPathList":[{"key":"tableData"},{"key":"primaryColumns.customColumn9.boxShadow"},{"key":"primaryColumns.customColumn9.borderRadius"},{"key":"primaryColumns.customColumn9.menuColor"},{"key":"primaryColumns.customColumn8.computedValue"},{"key":"primaryColumns.customColumn7.computedValue"},{"key":"primaryColumns.customColumn6.computedValue"},{"key":"primaryColumns.customColumn5.computedValue"},{"key":"primaryColumns.customColumn2.computedValue"},{"key":"primaryColumns.customColumn1.textColor"},{"key":"primaryColumns.customColumn1.cellBackground"},{"key":"primaryColumns.customColumn1.computedValue"},{"key":"primaryColumns.instance.computedValue"},{"key":"isVisible"},{"key":"accentColor"},{"key":"borderRadius"},{"key":"boxShadow"}],"needsHeightForContent":true,"leftColumn":14.0,"delimiter":",","defaultSelectedRowIndex":0.0,"showInlineEditingOptionDropdown":true,"accentColor":"{{appsmith.theme.colors.primaryColor}}","isVisibleFilters":true,"isVisible":"{{appsmith.store.api_key && appsmith.store.api_url ? true : false}}","enableClientSideSearch":true,"version":2.0,"totalRecordsCount":0.0,"isLoading":false,"childStylesheet":{"button":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"menuButton":{"menuColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"iconButton":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"editActions":{"saveButtonColor":"{{appsmith.theme.colors.primaryColor}}","saveBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","discardButtonColor":"{{appsmith.theme.colors.primaryColor}}","discardBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"}},"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","columnUpdatedAt":1.690746223636E12,"defaultSelectedRowIndices":[0.0],"mobileBottomRow":32.0,"widgetName":"TableInstances","defaultPageSize":0.0,"columnOrder":["instance","customColumn5","customColumn1","customColumn2","customColumn6","customColumn7","customColumn8","customColumn9"],"dynamicPropertyPathList":[{"key":"primaryColumns.customColumn1.cellBackground"},{"key":"isVisible"}],"displayName":"Table","bottomRow":42.0,"columnWidthMap":{"customColumn3":92.0,"customColumn2":340.0,"customColumn5":254.0,"customColumn9":60.0},"parentRowSpace":10.0,"hideCard":false,"mobileRightColumn":36.0,"parentColumnSpace":20.078125,"dynamicTriggerPathList":[{"key":"primaryColumns.customColumn9.menuItems.menuItemjfzsd8g6yr.onClick"},{"key":"primaryColumns.customColumn9.menuItems.menuItem4sqork5nmt.onClick"},{"key":"primaryColumns.customColumn9.menuItems.menuItemig6ua4ixjx.onClick"},{"key":"primaryColumns.customColumn9.menuItems.menuItemx9oyhys8cj.onClick"},{"key":"primaryColumns.customColumn9.menuItems.menuItemxk5jvvwwef.onClick"},{"key":"primaryColumns.customColumn9.menuItems.menuItem16ysonwzrq.onClick"},{"key":"primaryColumns.customColumn9.menuItems.menuItembtatfbml4y.onClick"}],"borderWidth":"1","primaryColumns":{"instance":{"allowCellWrapping":false,"allowSameOptionsInNewRow":true,"index":0.0,"width":150.0,"originalId":"instance","id":"instance","alias":"instance","horizontalAlignment":"LEFT","verticalAlignment":"CENTER","columnType":"text","textSize":"0.875rem","enableFilter":true,"enableSort":true,"isVisible":true,"isDisabled":false,"isCellEditable":false,"isEditable":false,"isCellVisible":true,"isDerived":false,"label":"Instance","isSaveVisible":true,"isDiscardVisible":true,"computedValue":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( currentRow.instance.instanceName))}}","sticky":"","validation":{}},"customColumn1":{"allowCellWrapping":false,"allowSameOptionsInNewRow":true,"index":1.0,"width":150.0,"originalId":"customColumn1","id":"customColumn1","alias":"Status","horizontalAlignment":"CENTER","verticalAlignment":"CENTER","columnType":"text","textSize":"0.875rem","enableFilter":true,"enableSort":true,"isVisible":true,"isDisabled":false,"isCellEditable":false,"isEditable":false,"isCellVisible":true,"isDerived":true,"label":"Status","isSaveVisible":true,"isDiscardVisible":true,"computedValue":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( currentRow.instance.status))}}","sticky":"","validation":{},"buttonStyle":"rgb(3, 179, 101)","labelColor":"#FFFFFF","cellBackground":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( currentRow.instance.status === \"open\" ? \"#499B51\" : currentRow.instance.status === \"close\" ? \"#DD524C\" : \"#2770FC\"))}}","textColor":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( (appsmith.theme.colors.backgroundColor)))}}"},"customColumn2":{"allowCellWrapping":false,"allowSameOptionsInNewRow":true,"index":2.0,"width":150.0,"originalId":"customColumn2","id":"customColumn2","alias":"Apikey","horizontalAlignment":"LEFT","verticalAlignment":"CENTER","columnType":"text","textSize":"0.875rem","enableFilter":true,"enableSort":true,"isVisible":true,"isDisabled":false,"isCellEditable":false,"isEditable":false,"isCellVisible":true,"isDerived":true,"label":"Apikey","isSaveVisible":true,"isDiscardVisible":true,"computedValue":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( currentRow.instance.apikey))}}","sticky":"","validation":{},"buttonStyle":"rgb(3, 179, 101)","labelColor":"#FFFFFF"},"customColumn5":{"allowCellWrapping":false,"allowSameOptionsInNewRow":true,"index":5.0,"width":150.0,"originalId":"customColumn5","id":"customColumn5","alias":"Owner","horizontalAlignment":"LEFT","verticalAlignment":"CENTER","columnType":"text","textSize":"0.875rem","enableFilter":true,"enableSort":true,"isVisible":true,"isDisabled":false,"isCellEditable":false,"isEditable":false,"isCellVisible":true,"isDerived":true,"label":"Owner","isSaveVisible":true,"isDiscardVisible":true,"computedValue":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( currentRow.instance.owner))}}","sticky":"","validation":{},"buttonStyle":"rgb(3, 179, 101)","labelColor":"#FFFFFF"},"customColumn6":{"allowCellWrapping":false,"allowSameOptionsInNewRow":true,"index":6.0,"width":150.0,"originalId":"customColumn6","id":"customColumn6","alias":"profilePictureUrl","horizontalAlignment":"LEFT","verticalAlignment":"CENTER","columnType":"text","textSize":"0.875rem","enableFilter":true,"enableSort":true,"isVisible":true,"isDisabled":false,"isCellEditable":false,"isEditable":false,"isCellVisible":false,"isDerived":true,"label":"profilePictureUrl","isSaveVisible":true,"isDiscardVisible":true,"computedValue":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( currentRow.instance.profilePictureUrl))}}","sticky":"","validation":{},"buttonStyle":"rgb(3, 179, 101)","labelColor":"#FFFFFF"},"customColumn7":{"allowCellWrapping":false,"allowSameOptionsInNewRow":true,"index":7.0,"width":150.0,"originalId":"customColumn7","id":"customColumn7","alias":"profileName","horizontalAlignment":"LEFT","verticalAlignment":"CENTER","columnType":"text","textSize":"0.875rem","enableFilter":true,"enableSort":true,"isVisible":true,"isDisabled":false,"isCellEditable":false,"isEditable":false,"isCellVisible":false,"isDerived":true,"label":"profileName","isSaveVisible":true,"isDiscardVisible":true,"computedValue":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( currentRow.instance.profileName))}}","sticky":"","validation":{},"buttonStyle":"rgb(3, 179, 101)","labelColor":"#FFFFFF"},"customColumn8":{"allowCellWrapping":false,"allowSameOptionsInNewRow":true,"index":8.0,"width":150.0,"originalId":"customColumn8","id":"customColumn8","alias":"profileStatus","horizontalAlignment":"LEFT","verticalAlignment":"CENTER","columnType":"text","textSize":"0.875rem","enableFilter":true,"enableSort":true,"isVisible":true,"isDisabled":false,"isCellEditable":false,"isEditable":false,"isCellVisible":false,"isDerived":true,"label":"profileStatus","isSaveVisible":true,"isDiscardVisible":true,"computedValue":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( currentRow.instance.profileStatus))}}","sticky":"","validation":{},"buttonStyle":"rgb(3, 179, 101)","labelColor":"#FFFFFF"},"customColumn9":{"allowCellWrapping":false,"allowSameOptionsInNewRow":true,"index":9.0,"width":150.0,"originalId":"customColumn9","id":"customColumn9","alias":"#","horizontalAlignment":"LEFT","verticalAlignment":"CENTER","columnType":"menuButton","textSize":"0.875rem","enableFilter":true,"enableSort":true,"isVisible":true,"isDisabled":false,"isCellEditable":false,"isEditable":false,"isCellVisible":true,"isDerived":true,"label":"#","isSaveVisible":true,"isDiscardVisible":true,"computedValue":"","sticky":"","validation":{},"buttonStyle":"rgb(3, 179, 101)","labelColor":"#FFFFFF","menuColor":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( (appsmith.theme.colors.primaryColor)))}}","borderRadius":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( (appsmith.theme.borderRadius.appBorderRadius)))}}","boxShadow":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( \"none\"))}}","customAlias":"","menuItemsSource":"STATIC","menuButtonLabel":" ","menuButtoniconName":"chevron-down","menuItems":{"menuItemjfzsd8g6yr":{"id":"menuItemjfzsd8g6yr","index":0.0,"label":"Webhook","widgetId":"vygcejtdun","isDisabled":false,"isVisible":true,"onClick":"{{Find_Webhook.run({\n //\"key\": \"value\",\n});\nshowModal('ModalWebhook');}}"},"menuItem4sqork5nmt":{"id":"menuItem4sqork5nmt","index":1.0,"label":"Settings","widgetId":"0hw8oqpwcj","isDisabled":false,"isVisible":true,"onClick":"{{Find_Settings.run();\nshowModal('ModalSettings');}}"},"menuItemx9oyhys8cj":{"id":"menuItemx9oyhys8cj","index":2.0,"label":"Websocket","widgetId":"j75a4k6ecq","isDisabled":false,"isVisible":true,"onClick":"{{Find_Websocket.run();\nshowModal('ModalWebsocket');}}"},"menuItemxk5jvvwwef":{"id":"menuItemxk5jvvwwef","index":3.0,"label":"Rabbitmq","widgetId":"3u94ov6qst","isDisabled":false,"isVisible":true,"onClick":"{{Find_Rabbitmq.run();\nshowModal('ModalRabbitmq');}}"},"menuItemig6ua4ixjx":{"id":"menuItemig6ua4ixjx","index":4.0,"label":"Chatwoot","widgetId":"fuq5dtgbqc","isDisabled":false,"isVisible":true,"onClick":"{{Find_Chatwoot.run()\nshowModal('ModalChatwoot');}}"},"menuItem16ysonwzrq":{"id":"menuItem16ysonwzrq","index":5.0,"label":"Set Typebot","widgetId":"fi9nb2bace","isDisabled":false,"isVisible":true,"onClick":"{{Find_Typebot.run()\nshowModal('ModalTypebot');}}"},"menuItembtatfbml4y":{"id":"menuItembtatfbml4y","index":6.0,"label":"TypeBot Set Session Status","widgetId":"7f6mg653ra","isDisabled":false,"isVisible":true,"onClick":"{{showModal('ModalTypebotChangeSessionStatu');}}"}}}},"key":"e3yxhhyeel","canFreezeColumn":true,"isDeprecated":false,"rightColumn":63.0,"textSize":"0.875rem","widgetId":"uupm7enu8u","minWidth":450.0,"tableData":"{{fetch_Instances.data}}","label":"Data","searchKey":"","parentId":"0","renderMode":"CANVAS","mobileTopRow":4.0,"horizontalAlignment":"LEFT","isVisibleSearch":true,"responsiveBehavior":"fill","mobileLeftColumn":2.0,"isVisiblePagination":true,"verticalAlignment":"CENTER"},{"resetFormOnClick":false,"boxShadow":"none","mobileBottomRow":5.0,"widgetName":"BtnNewInstance","onClick":"{{showModal('ModalInstance');}}","buttonColor":"rgb(3, 179, 101)","dynamicPropertyPathList":[{"key":"isVisible"}],"displayName":"Button","iconSVG":"/static/media/icon.7beb9123fb53027d9d6b778cdfe4caed.svg","searchTags":["click","submit"],"topRow":1.0,"bottomRow":5.0,"parentRowSpace":10.0,"type":"BUTTON_WIDGET","hideCard":false,"mobileRightColumn":8.0,"animateLoading":true,"parentColumnSpace":11.828125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":7.0,"dynamicBindingPathList":[{"key":"isVisible"},{"key":"borderRadius"}],"text":"New Instance","isDisabled":false,"key":"crzwqv3pdr","isDeprecated":false,"rightColumn":19.0,"isDefaultClickDisabled":true,"iconName":"add","widgetId":"84ei9q1ugm","minWidth":120.0,"isVisible":"{{appsmith.store.api_key && appsmith.store.api_url ? true : false}}","recaptchaType":"V3","version":1.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":1.0,"responsiveBehavior":"hug","disabledWhenInvalid":false,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":0.0,"buttonVariant":"PRIMARY","iconAlign":"left","placement":"CENTER"},{"boxShadow":"none","mobileBottomRow":74.0,"widgetName":"ModalQrcode","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":50.0,"bottomRow":500.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":45.0,"animateLoading":true,"parentColumnSpace":11.828125,"leftColumn":21.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas1","displayName":"Canvas","topRow":0.0,"bottomRow":450.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":240.0,"mobileRightColumn":283.875,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","mobileBottomRow":52.0,"widgetName":"ImageQrcode","displayName":"Image","iconSVG":"https://appcdn.appsmith.com/static/media/icon.30c8cbd442cce232b01ba2d434c53a53.svg","topRow":6.0,"bottomRow":43.0,"parentRowSpace":10.0,"type":"IMAGE_WIDGET","hideCard":false,"mobileRightColumn":55.0,"animateLoading":true,"parentColumnSpace":20.078125,"dynamicTriggerPathList":[],"imageShape":"RECTANGLE","leftColumn":2.0,"dynamicBindingPathList":[{"key":"borderRadius"},{"key":"image"}],"defaultImage":"https://manualnegocioonline.com.br/downloads/evolution-api-favicon2.png","key":"4chlj9l432","image":"{{Connect.data.base64}}","isDeprecated":false,"rightColumn":61.0,"objectFit":"contain","widgetId":"27dpgapd7q","isVisible":true,"version":1.0,"parentId":"we6j3r2byy","renderMode":"CANVAS","isLoading":false,"mobileTopRow":40.0,"maxZoomLevel":1.0,"enableDownload":false,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":43.0,"enableRotation":false},{"boxShadow":"none","mobileBottomRow":4.0,"widgetName":"IconButton1","onClick":"{{closeModal('ModalQrcode');\nfetch_Instances.run()}}","buttonColor":"{{appsmith.theme.colors.primaryColor}}","displayName":"Icon button","iconSVG":"/static/media/icon.80fc7466c0d7181ec0271de7fda795ec.svg","searchTags":["click","submit"],"topRow":0.0,"bottomRow":4.0,"type":"ICON_BUTTON_WIDGET","hideCard":false,"mobileRightColumn":64.0,"animateLoading":true,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":58.0,"dynamicBindingPathList":[{"key":"buttonColor"},{"key":"borderRadius"}],"iconSize":24.0,"isDisabled":false,"key":"pezy0hb491","isDeprecated":false,"rightColumn":64.0,"iconName":"cross","widgetId":"i1dw369dch","minWidth":50.0,"isVisible":true,"version":1.0,"parentId":"we6j3r2byy","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"hug","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":58.0,"buttonVariant":"TERTIARY"},{"mobileBottomRow":5.0,"widgetName":"Text1","displayName":"Text","iconSVG":"/static/media/icon.c3b6033f570046f8c6288d911333a827.svg","searchTags":["typography","paragraph","label"],"topRow":1.0,"bottomRow":5.0,"type":"TEXT_WIDGET","hideCard":false,"mobileRightColumn":41.0,"animateLoading":true,"overflow":"NONE","fontFamily":"{{appsmith.theme.fontFamily.appFont}}","dynamicTriggerPathList":[],"leftColumn":1.0,"dynamicBindingPathList":[{"key":"fontFamily"}],"shouldTruncate":false,"truncateButtonColor":"{{appsmith.theme.colors.primaryColor}}","text":"Qrcode","key":"9s8f10sepn","isDeprecated":false,"rightColumn":41.0,"textAlign":"LEFT","dynamicHeight":"AUTO_HEIGHT","widgetId":"mg2cqsi9fn","minWidth":450.0,"isVisible":true,"fontStyle":"BOLD","textColor":"#231F20","version":1.0,"parentId":"we6j3r2byy","renderMode":"CANVAS","isLoading":false,"mobileTopRow":1.0,"responsiveBehavior":"fill","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":1.0,"maxDynamicHeight":9000.0,"fontSize":"1.25rem","minDynamicHeight":4.0}],"isDisabled":false,"key":"e8r23nd8j4","isDeprecated":false,"rightColumn":283.875,"detachFromLayout":true,"widgetId":"we6j3r2byy","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"ljwryrjhy7","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"g8xx6ocuvi","height":450.0,"isDeprecated":false,"rightColumn":45.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"ljwryrjhy7","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":50.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":21.0,"maxDynamicHeight":9000.0,"width":456.0,"minDynamicHeight":24.0},{"resetFormOnClick":false,"boxShadow":"none","mobileBottomRow":5.0,"widgetName":"BtnConfig","onClick":"{{showModal('ModalConfig');}}","buttonColor":"#2563eb","dynamicPropertyPathList":[],"displayName":"Button","iconSVG":"/static/media/icon.7beb9123fb53027d9d6b778cdfe4caed.svg","searchTags":["click","submit"],"topRow":1.0,"bottomRow":5.0,"parentRowSpace":10.0,"type":"BUTTON_WIDGET","hideCard":false,"mobileRightColumn":30.0,"animateLoading":true,"parentColumnSpace":11.828125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":1.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"text":"Access","isDisabled":false,"key":"crzwqv3pdr","isDeprecated":false,"rightColumn":7.0,"isDefaultClickDisabled":true,"iconName":"user","widgetId":"uegjpy37i6","minWidth":120.0,"isVisible":true,"recaptchaType":"V3","version":1.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":1.0,"responsiveBehavior":"hug","disabledWhenInvalid":false,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":14.0,"buttonVariant":"PRIMARY","iconAlign":"left","placement":"CENTER"},{"boxShadow":"none","mobileBottomRow":73.0,"widgetName":"ModalConfig","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":49.0,"bottomRow":30.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":25.0,"minHeight":300.0,"animateLoading":true,"parentColumnSpace":11.75,"leftColumn":1.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas2","displayName":"Canvas","topRow":0.0,"bottomRow":300.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":300.0,"mobileRightColumn":282.0,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","mobileBottomRow":84.0,"borderColor":"#E0DEDE","widgetName":"FormConfig","isCanvas":true,"displayName":"Form","iconSVG":"/static/media/icon.5d6d2ac5cb1aa68bcd9b14f11c56b44a.svg","searchTags":["group"],"topRow":0.0,"bottomRow":28.0,"parentRowSpace":10.0,"type":"FORM_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":25.0,"animateLoading":true,"parentColumnSpace":11.828125,"dynamicTriggerPathList":[],"leftColumn":1.0,"dynamicBindingPathList":[],"children":[{"mobileBottomRow":400.0,"widgetName":"Canvas2Copy","displayName":"Canvas","topRow":0.0,"bottomRow":280.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":false,"hideCard":true,"minHeight":400.0,"mobileRightColumn":283.875,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"mobileBottomRow":5.0,"widgetName":"Text2","displayName":"Text","iconSVG":"/static/media/icon.c3b6033f570046f8c6288d911333a827.svg","searchTags":["typography","paragraph","label"],"topRow":1.0,"bottomRow":5.0,"type":"TEXT_WIDGET","hideCard":false,"mobileRightColumn":25.5,"animateLoading":true,"overflow":"NONE","fontFamily":"{{appsmith.theme.fontFamily.appFont}}","dynamicTriggerPathList":[],"leftColumn":1.5,"dynamicBindingPathList":[{"key":"fontFamily"}],"shouldTruncate":false,"truncateButtonColor":"{{appsmith.theme.colors.primaryColor}}","text":"Access Credentials","key":"9s8f10sepn","isDeprecated":false,"rightColumn":25.5,"textAlign":"LEFT","dynamicHeight":"AUTO_HEIGHT","widgetId":"tps5rw2lk9","minWidth":450.0,"isVisible":true,"fontStyle":"BOLD","textColor":"#231F20","version":1.0,"parentId":"lrtvcpswru","renderMode":"CANVAS","isLoading":false,"mobileTopRow":1.0,"responsiveBehavior":"fill","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":1.5,"maxDynamicHeight":9000.0,"fontSize":"1.25rem","minDynamicHeight":4.0},{"resetFormOnClick":true,"boxShadow":"none","mobileBottomRow":37.0,"widgetName":"Button1","onClick":"{{storeValue('api_url', FormConfig.data.InputApiUrl);\nstoreValue('api_key', FormConfig.data.InputGlobalApiKey);\nfetch_Instances.run().then(() => {\n showAlert('successful login', 'success');\n}).catch(() => {\n showAlert('Could not load instances', 'error');\n});\ncloseModal('ModalConfig').then(() => {});}}","buttonColor":"{{appsmith.theme.colors.primaryColor}}","dynamicPropertyPathList":[{"key":"isDisabled"}],"displayName":"Button","iconSVG":"/static/media/icon.7beb9123fb53027d9d6b778cdfe4caed.svg","searchTags":["click","submit"],"topRow":22.0,"bottomRow":26.0,"type":"BUTTON_WIDGET","hideCard":false,"mobileRightColumn":62.0,"animateLoading":true,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":51.0,"dynamicBindingPathList":[{"key":"buttonColor"},{"key":"borderRadius"}],"text":"Login","isDisabled":"","key":"crzwqv3pdr","isDeprecated":false,"rightColumn":63.0,"isDefaultClickDisabled":true,"iconName":"log-in","widgetId":"gzxvnsxk0y","minWidth":120.0,"isVisible":true,"recaptchaType":"V3","version":1.0,"parentId":"lrtvcpswru","renderMode":"CANVAS","isLoading":false,"mobileTopRow":33.0,"responsiveBehavior":"hug","disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":46.0,"buttonVariant":"PRIMARY","iconAlign":"left","placement":"CENTER"},{"resetFormOnClick":true,"boxShadow":"none","mobileBottomRow":37.0,"widgetName":"Button1Copy","onClick":"{{removeValue('api_url');\nremoveValue('api_key').then(() => {\n showAlert('successful logout', 'success');\n});}}","buttonColor":"#dc2626","dynamicPropertyPathList":[{"key":"isDisabled"}],"displayName":"Button","iconSVG":"/static/media/icon.7beb9123fb53027d9d6b778cdfe4caed.svg","searchTags":["click","submit"],"topRow":21.0,"bottomRow":25.0,"type":"BUTTON_WIDGET","hideCard":false,"mobileRightColumn":62.0,"animateLoading":true,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":2.0,"dynamicBindingPathList":[{"key":"isDisabled"},{"key":"borderRadius"}],"text":"Logout","isDisabled":"{{!appsmith.store.api_key && !appsmith.store.api_url ? true : false}}","key":"crzwqv3pdr","isDeprecated":false,"rightColumn":14.0,"isDefaultClickDisabled":true,"iconName":"log-out","widgetId":"f2i8tsbgx1","minWidth":120.0,"isVisible":true,"recaptchaType":"V3","version":1.0,"parentId":"lrtvcpswru","renderMode":"CANVAS","isLoading":false,"mobileTopRow":33.0,"responsiveBehavior":"hug","disabledWhenInvalid":false,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":46.0,"buttonVariant":"PRIMARY","iconAlign":"left","placement":"CENTER"},{"boxShadow":"none","iconSVG":"/static/media/icon.d0ce957b6c4640f8a7418ce846ee200e.svg","topRow":6.0,"labelWidth":5.0,"type":"INPUT_WIDGET_V2","animateLoading":true,"resetOnSubmit":true,"leftColumn":2.0,"dynamicBindingPathList":[{"key":"defaultText"},{"key":"accentColor"},{"key":"borderRadius"}],"labelStyle":"","inputType":"TEXT","placeholderText":"","isDisabled":false,"isRequired":true,"dynamicHeight":"FIXED","accentColor":"{{appsmith.theme.colors.primaryColor}}","showStepArrows":false,"isVisible":true,"version":2.0,"isLoading":false,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileBottomRow":13.0,"widgetName":"InputApiUrl","displayName":"Input","searchTags":["form","text input","number","textarea"],"bottomRow":13.0,"parentRowSpace":10.0,"autoFocus":false,"hideCard":false,"mobileRightColumn":22.0,"parentColumnSpace":5.047119140625,"dynamicTriggerPathList":[],"labelPosition":"Top","key":"r1hfat3ouf","labelTextSize":"0.875rem","isDeprecated":false,"rightColumn":63.0,"widgetId":"spgryrb5ao","minWidth":450.0,"label":"API URL","parentId":"lrtvcpswru","labelAlignment":"left","renderMode":"CANVAS","mobileTopRow":6.0,"responsiveBehavior":"fill","mobileLeftColumn":2.0,"maxDynamicHeight":9000.0,"isSpellCheck":false,"iconAlign":"left","defaultText":"{{appsmith.store.api_url || ''}}","minDynamicHeight":4.0},{"boxShadow":"none","iconSVG":"/static/media/icon.d0ce957b6c4640f8a7418ce846ee200e.svg","topRow":14.0,"labelWidth":5.0,"type":"INPUT_WIDGET_V2","animateLoading":true,"resetOnSubmit":true,"leftColumn":2.0,"dynamicBindingPathList":[{"key":"defaultText"},{"key":"accentColor"},{"key":"borderRadius"}],"labelStyle":"","inputType":"PASSWORD","isDisabled":false,"isRequired":true,"dynamicHeight":"FIXED","accentColor":"{{appsmith.theme.colors.primaryColor}}","showStepArrows":false,"isVisible":true,"version":2.0,"isLoading":false,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileBottomRow":13.0,"widgetName":"InputGlobalApiKey","displayName":"Input","searchTags":["form","text input","number","textarea"],"bottomRow":21.0,"parentRowSpace":10.0,"autoFocus":false,"hideCard":false,"mobileRightColumn":22.0,"parentColumnSpace":5.047119140625,"dynamicTriggerPathList":[],"labelPosition":"Top","key":"r1hfat3ouf","labelTextSize":"0.875rem","isDeprecated":false,"rightColumn":63.0,"widgetId":"v2vedr13py","minWidth":450.0,"label":"GLOBAL API KEY","parentId":"lrtvcpswru","labelAlignment":"left","renderMode":"CANVAS","mobileTopRow":6.0,"responsiveBehavior":"fill","mobileLeftColumn":2.0,"maxDynamicHeight":9000.0,"shouldAllowAutofill":true,"iconAlign":"left","defaultText":"{{appsmith.store.api_key || ''}}","minDynamicHeight":4.0},{"boxShadow":"none","mobileBottomRow":4.0,"widgetName":"IconButton2","onClick":"{{closeModal('ModalConfig');}}","buttonColor":"{{appsmith.theme.colors.primaryColor}}","displayName":"Icon button","iconSVG":"/static/media/icon.80fc7466c0d7181ec0271de7fda795ec.svg","searchTags":["click","submit"],"topRow":0.0,"bottomRow":4.0,"parentRowSpace":10.0,"type":"ICON_BUTTON_WIDGET","hideCard":false,"mobileRightColumn":64.0,"animateLoading":true,"parentColumnSpace":9.072265625,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":60.0,"dynamicBindingPathList":[{"key":"buttonColor"},{"key":"borderRadius"}],"isDisabled":false,"key":"pezy0hb491","isDeprecated":false,"rightColumn":64.0,"iconName":"cross","widgetId":"oaouelmhi1","minWidth":50.0,"isVisible":true,"version":1.0,"parentId":"lrtvcpswru","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"hug","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":60.0,"buttonVariant":"TERTIARY"}],"key":"e8r23nd8j4","isDeprecated":false,"rightColumn":283.875,"detachFromLayout":true,"widgetId":"lrtvcpswru","containerStyle":"none","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"h97rbttd5c","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"borderWidth":"0","positioning":"fixed","key":"dtzd07zsya","backgroundColor":"#FFFFFF","isDeprecated":false,"rightColumn":63.0,"dynamicHeight":"AUTO_HEIGHT","widgetId":"h97rbttd5c","minWidth":450.0,"isVisible":true,"parentId":"es5gsctogb","renderMode":"CANVAS","isLoading":false,"mobileTopRow":44.0,"responsiveBehavior":"fill","originalTopRow":0.0,"borderRadius":"0.375rem","mobileLeftColumn":1.0,"maxDynamicHeight":9000.0,"originalBottomRow":28.0,"minDynamicHeight":10.0}],"isDisabled":false,"key":"e8r23nd8j4","isDeprecated":false,"rightColumn":282.0,"detachFromLayout":true,"widgetId":"es5gsctogb","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"gneh33z88k","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"g8xx6ocuvi","height":300.0,"isDeprecated":false,"rightColumn":25.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"gneh33z88k","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":49.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":1.0,"maxDynamicHeight":9000.0,"width":632.0,"minDynamicHeight":24.0},{"boxShadow":"none","mobileBottomRow":66.0,"widgetName":"ModalInstance","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":42.0,"bottomRow":1892.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":37.0,"minHeight":1850.0,"animateLoading":true,"parentColumnSpace":11.828125,"leftColumn":13.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas3","displayName":"Canvas","topRow":0.0,"bottomRow":1850.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":1140.0,"mobileRightColumn":283.875,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","mobileBottomRow":4.0,"widgetName":"IconButton3Copy","onClick":"{{closeModal('ModalInstance');}}","buttonColor":"{{appsmith.theme.colors.primaryColor}}","displayName":"Icon button","iconSVG":"/static/media/icon.80fc7466c0d7181ec0271de7fda795ec.svg","searchTags":["click","submit"],"topRow":0.0,"bottomRow":4.0,"type":"ICON_BUTTON_WIDGET","hideCard":false,"mobileRightColumn":64.0,"animateLoading":true,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":57.0,"dynamicBindingPathList":[{"key":"buttonColor"},{"key":"borderRadius"}],"iconSize":24.0,"isDisabled":false,"key":"mr6bto7c8j","isDeprecated":false,"rightColumn":63.0,"iconName":"cross","widgetId":"xofakp4har","minWidth":50.0,"isVisible":true,"version":1.0,"parentId":"esgwuzqcwt","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"hug","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":58.0,"buttonVariant":"TERTIARY"},{"boxShadow":"none","borderColor":"#E0DEDE","iconSVG":"/static/media/icon.efac588608711d232f1c6c8a2144d2dd.svg","onSubmit":"{{Create_Instance.run().then(() => {\n showAlert('Instance created successfully', 'success');\n}).catch(() => {\n showAlert('Error creating instance', 'error');\n});\nfetch_Instances.run();\ncloseModal('ModalInstance');}}","topRow":4.0,"type":"JSON_FORM_WIDGET","animateLoading":true,"leftColumn":0.0,"dynamicBindingPathList":[{"key":"borderRadius"},{"key":"resetButtonStyles.buttonColor"},{"key":"schema.__root_schema__.defaultValue"},{"key":"schema.__root_schema__.borderRadius"},{"key":"schema.__root_schema__.children.webhook.defaultValue"},{"key":"schema.__root_schema__.children.webhook.borderRadius"},{"key":"schema.__root_schema__.cellBorderRadius"},{"key":"schema.__root_schema__.children.instance.defaultValue"},{"key":"schema.__root_schema__.children.instance.borderRadius"},{"key":"schema.__root_schema__.children.instance.cellBorderRadius"},{"key":"schema.__root_schema__.children.instance.children.instanceName.defaultValue"},{"key":"schema.__root_schema__.children.instance.children.instanceName.accentColor"},{"key":"schema.__root_schema__.children.instance.children.instanceName.borderRadius"},{"key":"schema.__root_schema__.children.instance.children.token.defaultValue"},{"key":"schema.__root_schema__.children.instance.children.token.accentColor"},{"key":"schema.__root_schema__.children.instance.children.token.borderRadius"},{"key":"schema.__root_schema__.children.webhook.cellBorderRadius"},{"key":"schema.__root_schema__.children.webhook.children.webhook.defaultValue"},{"key":"schema.__root_schema__.children.webhook.children.webhook.accentColor"},{"key":"schema.__root_schema__.children.webhook.children.webhook.borderRadius"},{"key":"schema.__root_schema__.children.webhook.children.events.defaultValue"},{"key":"schema.__root_schema__.children.webhook.children.events.accentColor"},{"key":"schema.__root_schema__.children.webhook.children.events.borderRadius"},{"key":"schema.__root_schema__.children.webhook.children.webhook_by_events.defaultValue"},{"key":"schema.__root_schema__.children.webhook.children.webhook_by_events.accentColor"},{"key":"schema.__root_schema__.children.settings.defaultValue"},{"key":"schema.__root_schema__.children.settings.borderRadius"},{"key":"schema.__root_schema__.children.settings.cellBorderRadius"},{"key":"schema.__root_schema__.children.settings.children.reject_call.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.reject_call.accentColor"},{"key":"schema.__root_schema__.children.settings.children.msg_call.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.msg_call.accentColor"},{"key":"schema.__root_schema__.children.settings.children.msg_call.borderRadius"},{"key":"schema.__root_schema__.children.settings.children.groups_ignore.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.groups_ignore.accentColor"},{"key":"schema.__root_schema__.children.settings.children.always_online.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.always_online.accentColor"},{"key":"schema.__root_schema__.children.settings.children.read_messages.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.read_messages.accentColor"},{"key":"schema.__root_schema__.children.settings.children.read_status.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.read_status.accentColor"},{"key":"schema.__root_schema__.children.chatwoot.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.borderRadius"},{"key":"schema.__root_schema__.children.chatwoot.cellBorderRadius"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_account_id.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_account_id.accentColor"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_account_id.borderRadius"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_token.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_token.accentColor"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_token.borderRadius"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_url.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_url.accentColor"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_url.borderRadius"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_sign_msg.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_sign_msg.accentColor"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_reopen_conversation.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_reopen_conversation.accentColor"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_conversation_pending.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_conversation_pending.accentColor"},{"key":"schema.__root_schema__.children.instance.children.qrcode.defaultValue"},{"key":"schema.__root_schema__.children.instance.children.qrcode.accentColor"},{"key":"schema.__root_schema__.children.websocket.defaultValue"},{"key":"schema.__root_schema__.children.websocket.borderRadius"},{"key":"schema.__root_schema__.children.websocket.cellBorderRadius"},{"key":"schema.__root_schema__.children.websocket.children.websocket_enabled.defaultValue"},{"key":"schema.__root_schema__.children.websocket.children.websocket_enabled.accentColor"},{"key":"schema.__root_schema__.children.websocket.children.websocket_events.defaultValue"},{"key":"schema.__root_schema__.children.websocket.children.websocket_events.accentColor"},{"key":"schema.__root_schema__.children.websocket.children.websocket_events.borderRadius"},{"key":"schema.__root_schema__.children.rabbitmq.defaultValue"},{"key":"schema.__root_schema__.children.rabbitmq.borderRadius"},{"key":"schema.__root_schema__.children.rabbitmq.cellBorderRadius"},{"key":"schema.__root_schema__.children.rabbitmq.children.rabbitmq_enabled.defaultValue"},{"key":"schema.__root_schema__.children.rabbitmq.children.rabbitmq_enabled.accentColor"},{"key":"schema.__root_schema__.children.rabbitmq.children.rabbitmq_events.defaultValue"},{"key":"schema.__root_schema__.children.rabbitmq.children.rabbitmq_events.accentColor"},{"key":"schema.__root_schema__.children.rabbitmq.children.rabbitmq_events.borderRadius"}],"showReset":true,"dynamicHeight":"AUTO_HEIGHT","autoGenerateForm":true,"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"SECONDARY","iconAlign":"left"},"isVisible":true,"version":1.0,"isLoading":false,"submitButtonLabel":"Create","childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}},"disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","originalBottomRow":183.0,"useSourceData":false,"schema":{"__root_schema__":{"children":{"webhook":{"children":{"webhook":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.webhook.webhook))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"webhook","identifier":"webhook","position":0.0,"originalIdentifier":"webhook","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Webhook"},"events":{"children":{},"dataType":"array","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.webhook.events))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Multiselect","sourceData":["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","CALL","NEW_JWT_TOKEN"],"isCustomField":false,"accessor":"events","identifier":"events","position":2.0,"originalIdentifier":"events","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Events","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n {\n \"label\": \"APPLICATION_STARTUP\",\n \"value\": \"APPLICATION_STARTUP\"\n },\n {\n \"label\": \"QRCODE_UPDATED\",\n \"value\": \"QRCODE_UPDATED\"\n },\n {\n \"label\": \"MESSAGES_SET\",\n \"value\": \"MESSAGES_SET\"\n },\n {\n \"label\": \"MESSAGES_UPSERT\",\n \"value\": \"MESSAGES_UPSERT\"\n },\n {\n \"label\": \"MESSAGES_UPDATE\",\n \"value\": \"MESSAGES_UPDATE\"\n },\n {\n \"label\": \"MESSAGES_DELETE\",\n \"value\": \"MESSAGES_DELETE\"\n },\n {\n \"label\": \"SEND_MESSAGE\",\n \"value\": \"SEND_MESSAGE\"\n },\n {\n \"label\": \"CONTACTS_SET\",\n \"value\": \"CONTACTS_SET\"\n },\n {\n \"label\": \"CONTACTS_UPSERT\",\n \"value\": \"CONTACTS_UPSERT\"\n },\n {\n \"label\": \"CONTACTS_UPDATE\",\n \"value\": \"CONTACTS_UPDATE\"\n },\n {\n \"label\": \"PRESENCE_UPDATE\",\n \"value\": \"PRESENCE_UPDATE\"\n },\n {\n \"label\": \"CHATS_SET\",\n \"value\": \"CHATS_SET\"\n },\n {\n \"label\": \"CHATS_UPSERT\",\n \"value\": \"CHATS_UPSERT\"\n },\n {\n \"label\": \"CHATS_UPDATE\",\n \"value\": \"CHATS_UPDATE\"\n },\n {\n \"label\": \"CHATS_DELETE\",\n \"value\": \"CHATS_DELETE\"\n },\n {\n \"label\": \"GROUPS_UPSERT\",\n \"value\": \"GROUPS_UPSERT\"\n },\n {\n \"label\": \"GROUP_UPDATE\",\n \"value\": \"GROUP_UPDATE\"\n },\n {\n \"label\": \"GROUP_PARTICIPANTS_UPDATE\",\n \"value\": \"GROUP_PARTICIPANTS_UPDATE\"\n },\n {\n \"label\": \"CONNECTION_UPDATE\",\n \"value\": \"CONNECTION_UPDATE\"\n },\n {\n \"label\": \"CALL\",\n \"value\": \"CALL\"\n },\n {\n \"label\": \"NEW_JWT_TOKEN\",\n \"value\": \"NEW_JWT_TOKEN\"\n }\n]"},"webhook_by_events":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.webhook.webhook_by_events))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"webhook_by_events","identifier":"webhook_by_events","position":2.0,"originalIdentifier":"webhook_by_events","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Webhook By Events"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.webhook))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Object","sourceData":{},"isCustomField":false,"accessor":"webhook","identifier":"webhook","position":1.0,"originalIdentifier":"webhook","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"1rem","label":"Webhook","labelStyle":"BOLD"},"instance":{"children":{"instanceName":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.instance.instanceName))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"instanceName","identifier":"instanceName","position":0.0,"originalIdentifier":"instanceName","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Instance Name"},"token":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.instance.token))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"token","identifier":"token","position":1.0,"originalIdentifier":"token","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Token"},"qrcode":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.instance.qrcode))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"qrcode","identifier":"qrcode","position":2.0,"originalIdentifier":"qrcode","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Qrcode"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.instance))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Object","sourceData":{},"isCustomField":false,"accessor":"instance","identifier":"instance","position":0.0,"originalIdentifier":"instance","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"1rem","label":"Instance","labelStyle":"BOLD"},"settings":{"children":{"reject_call":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.settings.reject_call))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"reject_call","identifier":"reject_call","position":0.0,"originalIdentifier":"reject_call","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Reject Call"},"msg_call":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.settings.msg_call))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"msg_call","identifier":"msg_call","position":1.0,"originalIdentifier":"msg_call","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Msg Call"},"groups_ignore":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.settings.groups_ignore))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"groups_ignore","identifier":"groups_ignore","position":2.0,"originalIdentifier":"groups_ignore","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Groups Ignore"},"always_online":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.settings.always_online))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"always_online","identifier":"always_online","position":3.0,"originalIdentifier":"always_online","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Always Online"},"read_messages":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.settings.read_messages))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"read_messages","identifier":"read_messages","position":4.0,"originalIdentifier":"read_messages","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Read Messages"},"read_status":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.settings.read_status))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"read_status","identifier":"read_status","position":5.0,"originalIdentifier":"read_status","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Read Status"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.settings))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Object","sourceData":{},"isCustomField":false,"accessor":"settings","identifier":"settings","position":2.0,"originalIdentifier":"settings","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"1rem","label":"Settings","labelStyle":"BOLD"},"chatwoot":{"children":{"chatwoot_account_id":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.chatwoot.chatwoot_account_id))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"chatwoot_account_id","identifier":"chatwoot_account_id","position":0.0,"originalIdentifier":"chatwoot_account_id","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Chatwoot Account Id"},"chatwoot_token":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.chatwoot.chatwoot_token))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Password Input","sourceData":"","isCustomField":false,"accessor":"chatwoot_token","identifier":"chatwoot_token","position":1.0,"originalIdentifier":"chatwoot_token","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Chatwoot Token","shouldAllowAutofill":true},"chatwoot_url":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.chatwoot.chatwoot_url))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"chatwoot_url","identifier":"chatwoot_url","position":2.0,"originalIdentifier":"chatwoot_url","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Chatwoot Url"},"chatwoot_sign_msg":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.chatwoot.chatwoot_sign_msg))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"chatwoot_sign_msg","identifier":"chatwoot_sign_msg","position":3.0,"originalIdentifier":"chatwoot_sign_msg","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Chatwoot Sign Msg"},"chatwoot_reopen_conversation":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.chatwoot.chatwoot_reopen_conversation))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"chatwoot_reopen_conversation","identifier":"chatwoot_reopen_conversation","position":4.0,"originalIdentifier":"chatwoot_reopen_conversation","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Chatwoot Reopen Conversation"},"chatwoot_conversation_pending":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.chatwoot.chatwoot_conversation_pending))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"chatwoot_conversation_pending","identifier":"chatwoot_conversation_pending","position":5.0,"originalIdentifier":"chatwoot_conversation_pending","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Chatwoot Conversation Pending"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.chatwoot))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Object","sourceData":{},"isCustomField":false,"accessor":"chatwoot","identifier":"chatwoot","position":5.0,"originalIdentifier":"chatwoot","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"1rem","label":"Chatwoot","labelStyle":"BOLD"},"websocket":{"children":{"websocket_enabled":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.websocket.websocket_enabled))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"websocket_enabled","identifier":"websocket_enabled","position":0.0,"originalIdentifier":"websocket_enabled","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Websocket Enabled"},"websocket_events":{"children":{},"dataType":"array","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.websocket.websocket_events))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Multiselect","sourceData":["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","CALL","NEW_JWT_TOKEN"],"isCustomField":false,"accessor":"websocket_events","identifier":"websocket_events","position":1.0,"originalIdentifier":"websocket_events","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Websocket Events","labelTextSize":"0.875rem","serverSideFiltering":false,"options":[{"label":"Blue","value":"BLUE"},{"label":"Green","value":"GREEN"},{"label":"Red","value":"RED"}]}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.websocket))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Object","sourceData":{},"isCustomField":false,"accessor":"websocket","identifier":"websocket","position":3.0,"originalIdentifier":"websocket","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"1rem","label":"Websocket","labelStyle":"BOLD"},"rabbitmq":{"children":{"rabbitmq_enabled":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.rabbitmq.rabbitmq_enabled))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"rabbitmq_enabled","identifier":"rabbitmq_enabled","position":1.0,"originalIdentifier":"rabbitmq_enabled","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Rabbitmq Enabled"},"rabbitmq_events":{"children":{},"dataType":"array","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.rabbitmq.rabbitmq_events))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Multiselect","sourceData":["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","CALL","NEW_JWT_TOKEN"],"isCustomField":false,"accessor":"rabbitmq_events","identifier":"rabbitmq_events","position":1.0,"originalIdentifier":"rabbitmq_events","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Rabbitmq Events","labelTextSize":"0.875rem","serverSideFiltering":false,"options":[{"label":"Blue","value":"BLUE"},{"label":"Green","value":"GREEN"},{"label":"Red","value":"RED"}]}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.rabbitmq))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Object","sourceData":{"websocket_enabled":false,"websocket_events":["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","CALL","NEW_JWT_TOKEN"]},"isCustomField":false,"accessor":"rabbitmq","identifier":"rabbitmq","position":4.0,"originalIdentifier":"rabbitmq","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"1rem","label":"Rabbitmq","labelStyle":"BOLD"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Object","sourceData":{"instanceName":"","token":"","webhook":"","webhook_by_events":false,"events":["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","CALL","NEW_JWT_TOKEN"],"reject_call":false,"msg_call":"","groups_ignore":false,"always_online":false,"read_messages":false,"read_status":false,"chatwoot_account_id":"","chatwoot_token":"","chatwoot_url":"","chatwoot_sign_msg":false,"chatwoot_reopen_conversation":false,"chatwoot_conversation_pending":false},"isCustomField":false,"accessor":"__root_schema__","identifier":"__root_schema__","position":-1.0,"originalIdentifier":"__root_schema__","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":""}},"mobileBottomRow":85.0,"widgetName":"FormInstance","submitButtonStyles":{"buttonColor":"rgb(3, 179, 101)","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.webhook.children.webhook_by_events.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.reject_call.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.groups_ignore.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.always_online.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.read_messages.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.read_status.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_sign_msg.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_reopen_conversation.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_conversation_pending.defaultValue"},{"key":"schema.__root_schema__.children.instance.children.qrcode.defaultValue"},{"key":"schema.__root_schema__.children.websocket.children.websocket_enabled.defaultValue"},{"key":"schema.__root_schema__.children.rabbitmq.children.rabbitmq_enabled.defaultValue"}],"displayName":"JSON Form","bottomRow":183.0,"fieldLimitExceeded":false,"parentRowSpace":10.0,"title":"New Instance","hideCard":false,"mobileRightColumn":22.0,"shouldScrollContents":true,"parentColumnSpace":17.9375,"dynamicTriggerPathList":[{"key":"onSubmit"}],"borderWidth":"0","sourceData":"{\n \"instance\": {\n\t\t\t\"instanceName\": \"\",\n \t\"token\": \"\",\n\t\t\t\"qrcode\": true\n\t\t},\n\t\t\"webhook\": {\n\t\t\t\"webhook\": \"\",\n\t\t\t\"events\": [\n\t\t\t\t\"APPLICATION_STARTUP\",\n\t\t\t\t\t\"QRCODE_UPDATED\",\n\t\t\t\t\t\"MESSAGES_SET\",\n\t\t\t\t\t\"MESSAGES_UPSERT\",\n\t\t\t\t\t\"MESSAGES_UPDATE\",\n\t\t\t\t\t\"MESSAGES_DELETE\",\n\t\t\t\t\t\"SEND_MESSAGE\",\n\t\t\t\t\t\"CONTACTS_SET\",\n\t\t\t\t\t\"CONTACTS_UPSERT\",\n\t\t\t\t\t\"CONTACTS_UPDATE\",\n\t\t\t\t\t\"PRESENCE_UPDATE\",\n\t\t\t\t\t\"CHATS_SET\",\n\t\t\t\t\t\"CHATS_UPSERT\",\n\t\t\t\t\t\"CHATS_UPDATE\",\n\t\t\t\t\t\"CHATS_DELETE\",\n\t\t\t\t\t\"GROUPS_UPSERT\",\n\t\t\t\t\t\"GROUP_UPDATE\",\n\t\t\t\t\t\"GROUP_PARTICIPANTS_UPDATE\",\n\t\t\t\t\t\"CONNECTION_UPDATE\",\n\t\t\t\t\t\"CALL\",\n\t\t\t\t\t\"NEW_JWT_TOKEN\"\n\t\t\t],\n\t\t\t\"webhook_by_events\": false\n\t\t},\n \"settings\": {\n\t\t\t\"reject_call\": false,\n\t\t\t\"msg_call\": \"\",\n\t\t\t\"groups_ignore\": false,\n\t\t\t\"always_online\": false,\n\t\t\t\"read_messages\": false,\n\t\t\t\"read_status\": false\n\t\t},\n\t\t\"websocket\": {\n\t\t\t\"websocket_enabled\": false,\n\t\t\t\"websocket_events\": [\n\t\t\t\t\"APPLICATION_STARTUP\",\n\t\t\t\t\t\"QRCODE_UPDATED\",\n\t\t\t\t\t\"MESSAGES_SET\",\n\t\t\t\t\t\"MESSAGES_UPSERT\",\n\t\t\t\t\t\"MESSAGES_UPDATE\",\n\t\t\t\t\t\"MESSAGES_DELETE\",\n\t\t\t\t\t\"SEND_MESSAGE\",\n\t\t\t\t\t\"CONTACTS_SET\",\n\t\t\t\t\t\"CONTACTS_UPSERT\",\n\t\t\t\t\t\"CONTACTS_UPDATE\",\n\t\t\t\t\t\"PRESENCE_UPDATE\",\n\t\t\t\t\t\"CHATS_SET\",\n\t\t\t\t\t\"CHATS_UPSERT\",\n\t\t\t\t\t\"CHATS_UPDATE\",\n\t\t\t\t\t\"CHATS_DELETE\",\n\t\t\t\t\t\"GROUPS_UPSERT\",\n\t\t\t\t\t\"GROUP_UPDATE\",\n\t\t\t\t\t\"GROUP_PARTICIPANTS_UPDATE\",\n\t\t\t\t\t\"CONNECTION_UPDATE\",\n\t\t\t\t\t\"CALL\",\n\t\t\t\t\t\"NEW_JWT_TOKEN\"\n\t\t\t]\n\t\t},\n\t\t\"rabbitmq\": {\n\t\t\t\"rabbitmq_enabled\": false,\n\t\t\t\"rabbitmq_events\": [\n\t\t\t\t\"APPLICATION_STARTUP\",\n\t\t\t\t\t\"QRCODE_UPDATED\",\n\t\t\t\t\t\"MESSAGES_SET\",\n\t\t\t\t\t\"MESSAGES_UPSERT\",\n\t\t\t\t\t\"MESSAGES_UPDATE\",\n\t\t\t\t\t\"MESSAGES_DELETE\",\n\t\t\t\t\t\"SEND_MESSAGE\",\n\t\t\t\t\t\"CONTACTS_SET\",\n\t\t\t\t\t\"CONTACTS_UPSERT\",\n\t\t\t\t\t\"CONTACTS_UPDATE\",\n\t\t\t\t\t\"PRESENCE_UPDATE\",\n\t\t\t\t\t\"CHATS_SET\",\n\t\t\t\t\t\"CHATS_UPSERT\",\n\t\t\t\t\t\"CHATS_UPDATE\",\n\t\t\t\t\t\"CHATS_DELETE\",\n\t\t\t\t\t\"GROUPS_UPSERT\",\n\t\t\t\t\t\"GROUP_UPDATE\",\n\t\t\t\t\t\"GROUP_PARTICIPANTS_UPDATE\",\n\t\t\t\t\t\"CONNECTION_UPDATE\",\n\t\t\t\t\t\"CALL\",\n\t\t\t\t\t\"NEW_JWT_TOKEN\"\n\t\t\t]\n\t\t},\n \"chatwoot\": {\n\t\t\t\"chatwoot_account_id\": \"\",\n\t\t\t\"chatwoot_token\": \"\",\n\t\t\t\"chatwoot_url\": \"\",\n\t\t\t\"chatwoot_sign_msg\": false,\n\t\t\t\"chatwoot_reopen_conversation\": false,\n\t\t\t\"chatwoot_conversation_pending\": false\n\t\t}\n}","resetButtonLabel":"Reset","key":"lgqqk5r1jk","backgroundColor":"#fff","isDeprecated":false,"rightColumn":63.0,"widgetId":"o0v8ypwnya","minWidth":450.0,"parentId":"esgwuzqcwt","renderMode":"CANVAS","mobileTopRow":44.0,"scrollContents":true,"responsiveBehavior":"fill","fixedFooter":true,"originalTopRow":4.0,"mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"minDynamicHeight":4.0}],"isDisabled":false,"key":"w17ra2a85u","isDeprecated":false,"rightColumn":283.875,"detachFromLayout":true,"widgetId":"esgwuzqcwt","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"rnttu90jzr","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"bkvkzj4d20","height":1850.0,"isDeprecated":false,"rightColumn":37.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"rnttu90jzr","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":42.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":13.0,"maxDynamicHeight":9000.0,"width":628.0,"minDynamicHeight":24.0},{"resetFormOnClick":false,"boxShadow":"none","mobileBottomRow":5.0,"widgetName":"ButtonRefreshData","onClick":"{{fetch_Instances.run()}}","buttonColor":"#60a5fa","dynamicPropertyPathList":[{"key":"isVisible"}],"displayName":"Button","iconSVG":"/static/media/icon.7beb9123fb53027d9d6b778cdfe4caed.svg","searchTags":["click","submit"],"topRow":1.0,"bottomRow":5.0,"parentRowSpace":10.0,"type":"BUTTON_WIDGET","hideCard":false,"mobileRightColumn":35.0,"animateLoading":true,"parentColumnSpace":11.828125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":19.0,"dynamicBindingPathList":[{"key":"isVisible"},{"key":"borderRadius"}],"text":"","isDisabled":false,"key":"k10nyfsas3","isDeprecated":false,"rightColumn":24.0,"isDefaultClickDisabled":true,"iconName":"refresh","widgetId":"dn1ehe3gvu","minWidth":120.0,"isVisible":"{{appsmith.store.api_key && appsmith.store.api_url ? true : false}}","recaptchaType":"V3","version":1.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":1.0,"responsiveBehavior":"hug","disabledWhenInvalid":false,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":19.0,"buttonVariant":"PRIMARY","iconAlign":"left","placement":"CENTER"},{"boxShadow":"none","mobileBottomRow":5.0,"widgetName":"ButtonGroup1","isCanvas":false,"dynamicPropertyPathList":[{"key":"isVisible"}],"displayName":"Button Group","iconSVG":"/static/media/icon.7c22979bacc83c8d84aedf56ea6c2022.svg","searchTags":["click","submit"],"topRow":1.0,"bottomRow":5.0,"parentRowSpace":10.0,"groupButtons":{"groupButton1":{"label":"Connect","iconName":"camera","id":"groupButton1","widgetId":"","buttonType":"SIMPLE","placement":"CENTER","isVisible":true,"isDisabled":false,"index":0.0,"menuItems":{},"buttonColor":"#16a34a","onClick":"{{Connect.run();\nfetch_Instances.run();\nshowModal('ModalQrcode');}}"},"groupButton2":{"label":"Restart","iconName":"reset","id":"groupButton2","buttonType":"SIMPLE","placement":"CENTER","widgetId":"","isVisible":true,"isDisabled":false,"index":1.0,"menuItems":{},"buttonColor":"#2563eb","onClick":"{{Restart.run().then(() => {\n showAlert('Instance restarted successfully', 'success');\n}).catch(() => {\n showAlert('Error restarting instance', 'error');\n});\nfetch_Instances.run();}}"},"groupButton3":{"label":"Logout","iconName":"log-in","id":"groupButton3","buttonType":"SIMPLE","placement":"CENTER","widgetId":"","isVisible":true,"isDisabled":false,"index":2.0,"menuItems":{"menuItem1":{"label":"First Option","backgroundColor":"#FFFFFF","id":"menuItem1","widgetId":"","onClick":"","isVisible":true,"isDisabled":false,"index":0.0},"menuItem2":{"label":"Second Option","backgroundColor":"#FFFFFF","id":"menuItem2","widgetId":"","onClick":"","isVisible":true,"isDisabled":false,"index":1.0},"menuItem3":{"label":"Delete","iconName":"trash","iconColor":"#FFFFFF","iconAlign":"right","textColor":"#FFFFFF","backgroundColor":"#DD4B34","id":"menuItem3","widgetId":"","onClick":"","isVisible":true,"isDisabled":false,"index":2.0}},"buttonColor":"#a16207","onClick":"{{Logout.run().then(() => {\n showAlert('Instance logout successfully', 'success');\n}).catch(() => {\n showAlert('Error logout instance', 'error');\n});\nfetch_Instances.run();}}"},"groupButtonmghcs8rd4g":{"id":"groupButtonmghcs8rd4g","index":3.0,"label":"Delete","menuItems":{},"buttonType":"SIMPLE","placement":"CENTER","widgetId":"v0qkg2pjo2","isDisabled":false,"isVisible":true,"buttonColor":"#ef4444","iconName":"cross","onClick":"{{Delete.run().then(() => {\n showAlert('Instance deleted successfully', 'success');\n}).catch(() => {\n showAlert('Error deleting instance', 'error');\n});\nfetch_Instances.run();}}"}},"type":"BUTTON_GROUP_WIDGET","hideCard":false,"mobileRightColumn":51.0,"animateLoading":true,"parentColumnSpace":11.828125,"dynamicTriggerPathList":[{"key":"groupButtons.groupButton1.onClick"},{"key":"groupButtons.groupButton2.onClick"},{"key":"groupButtons.groupButton3.onClick"},{"key":"groupButtons.groupButtonmghcs8rd4g.onClick"}],"leftColumn":27.0,"dynamicBindingPathList":[{"key":"isVisible"},{"key":"borderRadius"}],"isDisabled":false,"key":"za8m3k8x7w","orientation":"horizontal","isDeprecated":false,"rightColumn":63.0,"widgetId":"2s6fqi483g","minWidth":450.0,"isVisible":"{{appsmith.store.api_key && appsmith.store.api_url ? true : false}}","version":1.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":1.0,"responsiveBehavior":"fill","childStylesheet":{"button":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}"}},"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":27.0,"buttonVariant":"PRIMARY"},{"boxShadow":"none","mobileBottomRow":18.0,"widgetName":"ProfilePicture","dynamicPropertyPathList":[{"key":"isVisible"},{"key":"borderRadius"}],"displayName":"Image","iconSVG":"/static/media/icon.30c8cbd442cce232b01ba2d434c53a53.svg","topRow":6.0,"bottomRow":28.0,"parentRowSpace":10.0,"type":"IMAGE_WIDGET","hideCard":false,"mobileRightColumn":13.0,"animateLoading":true,"parentColumnSpace":11.828125,"dynamicTriggerPathList":[],"imageShape":"RECTANGLE","leftColumn":1.0,"dynamicBindingPathList":[{"key":"image"},{"key":"isVisible"}],"defaultImage":"https://th.bing.com/th/id/OIP.ruat7whad9-kcI8_1KH_tQHaGI?pid=ImgDet&rs=1","key":"bl30j21wwb","image":"{{TableInstances.selectedRow.profilePictureUrl}}","isDeprecated":false,"rightColumn":13.0,"objectFit":"contain","widgetId":"1sjznr31jo","isVisible":"{{appsmith.store.api_key && appsmith.store.api_url ? true : false}}","version":1.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":6.0,"maxZoomLevel":1.0,"enableDownload":false,"borderRadius":"0.335rem","mobileLeftColumn":1.0,"enableRotation":false},{"mobileBottomRow":22.0,"widgetName":"Text4","dynamicPropertyPathList":[{"key":"isVisible"}],"displayName":"Text","iconSVG":"/static/media/icon.c3b6033f570046f8c6288d911333a827.svg","searchTags":["typography","paragraph","label"],"topRow":36.0,"bottomRow":44.0,"parentRowSpace":10.0,"type":"TEXT_WIDGET","hideCard":false,"mobileRightColumn":11.0,"animateLoading":true,"overflow":"NONE","fontFamily":"{{appsmith.theme.fontFamily.appFont}}","parentColumnSpace":11.828125,"dynamicTriggerPathList":[],"leftColumn":1.0,"dynamicBindingPathList":[{"key":"text"},{"key":"isVisible"},{"key":"fontFamily"}],"shouldTruncate":false,"truncateButtonColor":"{{appsmith.theme.colors.primaryColor}}","text":"{{TableInstances.selectedRow.profileName || ''}}\n\n{{TableInstances.selectedRow.profileStatus || ''}}","key":"gqt8t28m33","isDeprecated":false,"rightColumn":13.0,"textAlign":"CENTER","dynamicHeight":"AUTO_HEIGHT","widgetId":"0c356c66hp","minWidth":450.0,"isVisible":"{{appsmith.store.api_key && appsmith.store.api_url ? true : false}}","fontStyle":"BOLD","textColor":"#231F20","version":1.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":18.0,"responsiveBehavior":"fill","originalTopRow":38.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"originalBottomRow":44.0,"fontSize":"0.875rem","minDynamicHeight":4.0},{"mobileBottomRow":41.0,"widgetName":"Text5","dynamicPropertyPathList":[{"key":"isVisible"}],"displayName":"Text","iconSVG":"/static/media/icon.c3b6033f570046f8c6288d911333a827.svg","searchTags":["typography","paragraph","label"],"topRow":32.0,"bottomRow":36.0,"parentRowSpace":10.0,"type":"TEXT_WIDGET","hideCard":false,"mobileRightColumn":9.0,"animateLoading":true,"overflow":"NONE","fontFamily":"{{appsmith.theme.fontFamily.appFont}}","parentColumnSpace":11.75,"dynamicTriggerPathList":[],"leftColumn":1.0,"dynamicBindingPathList":[{"key":"text"},{"key":"isVisible"},{"key":"fontFamily"}],"shouldTruncate":false,"truncateButtonColor":"{{appsmith.theme.colors.primaryColor}}","text":"{{TableInstances.selectedRow.instance || ''}}","key":"gqt8t28m33","isDeprecated":false,"rightColumn":13.0,"textAlign":"CENTER","dynamicHeight":"AUTO_HEIGHT","widgetId":"5qg2iscn1l","minWidth":450.0,"isVisible":"{{appsmith.store.api_key && appsmith.store.api_url ? true : false}}","fontStyle":"BOLD","textColor":"#231F20","version":1.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":37.0,"responsiveBehavior":"fill","originalTopRow":32.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"originalBottomRow":38.0,"fontSize":"1.25rem","minDynamicHeight":4.0},{"boxShadow":"none","mobileBottomRow":70.0,"widgetName":"ModalWebhook","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":46.0,"bottomRow":43.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":35.0,"minHeight":430.0,"animateLoading":true,"parentColumnSpace":17.9375,"leftColumn":11.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas4","displayName":"Canvas","topRow":0.0,"bottomRow":430.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":240.0,"mobileRightColumn":430.5,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","borderColor":"#E0DEDE","iconSVG":"/static/media/icon.efac588608711d232f1c6c8a2144d2dd.svg","onSubmit":"{{Set_Webhook.run().then(() => {\n showAlert('Webhook updated successfully', 'success');\n}).catch(() => {\n showAlert('Error updating webhook', 'error');\n});\ncloseModal('ModalWebhook');}}","topRow":0.0,"type":"JSON_FORM_WIDGET","animateLoading":true,"leftColumn":0.0,"dynamicBindingPathList":[{"key":"borderRadius"},{"key":"submitButtonStyles.buttonColor"},{"key":"schema.__root_schema__.defaultValue"},{"key":"schema.__root_schema__.borderRadius"},{"key":"schema.__root_schema__.cellBorderRadius"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.enabled.defaultValue"},{"key":"schema.__root_schema__.children.enabled.accentColor"},{"key":"schema.__root_schema__.children.url.defaultValue"},{"key":"schema.__root_schema__.children.url.accentColor"},{"key":"schema.__root_schema__.children.url.borderRadius"},{"key":"schema.__root_schema__.children.webhook_by_events.defaultValue"},{"key":"schema.__root_schema__.children.webhook_by_events.accentColor"},{"key":"schema.__root_schema__.children.events.defaultValue"},{"key":"schema.__root_schema__.children.events.accentColor"},{"key":"schema.__root_schema__.children.events.borderRadius"}],"showReset":false,"dynamicHeight":"AUTO_HEIGHT","autoGenerateForm":false,"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"SECONDARY"},"isVisible":true,"version":1.0,"isLoading":false,"submitButtonLabel":"Save","childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}},"disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","originalBottomRow":41.0,"useSourceData":false,"schema":{"__root_schema__":{"children":{"enabled":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.enabled))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"enabled","identifier":"enabled","position":0.0,"originalIdentifier":"enabled","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Enabled"},"url":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.url))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"url","identifier":"url","position":1.0,"originalIdentifier":"url","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Url"},"webhook_by_events":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.webhook_by_events))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"webhook_by_events","identifier":"webhook_by_events","position":2.0,"originalIdentifier":"webhook_by_events","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Webhook By Events"},"events":{"children":{},"dataType":"array","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.events))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","fieldType":"Multiselect","sourceData":[],"isCustomField":false,"accessor":"events","identifier":"events","position":3.0,"originalIdentifier":"events","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Events","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n\n {\n \"label\": \"APPLICATION_STARTUP\",\n \"value\": \"APPLICATION_STARTUP\"\n },\n {\n \"label\": \"QRCODE_UPDATED\",\n \"value\": \"QRCODE_UPDATED\"\n },\n {\n \"label\": \"MESSAGES_SET\",\n \"value\": \"MESSAGES_SET\"\n },\n {\n \"label\": \"MESSAGES_UPSERT\",\n \"value\": \"MESSAGES_UPSERT\"\n },\n {\n \"label\": \"MESSAGES_UPDATE\",\n \"value\": \"MESSAGES_UPDATE\"\n },\n {\n \"label\": \"MESSAGES_DELETE\",\n \"value\": \"MESSAGES_DELETE\"\n },\n {\n \"label\": \"SEND_MESSAGE\",\n \"value\": \"SEND_MESSAGE\"\n },\n {\n \"label\": \"CONTACTS_SET\",\n \"value\": \"CONTACTS_SET\"\n },\n {\n \"label\": \"CONTACTS_UPSERT\",\n \"value\": \"CONTACTS_UPSERT\"\n },\n {\n \"label\": \"CONTACTS_UPDATE\",\n \"value\": \"CONTACTS_UPDATE\"\n },\n {\n \"label\": \"PRESENCE_UPDATE\",\n \"value\": \"PRESENCE_UPDATE\"\n },\n {\n \"label\": \"CHATS_SET\",\n \"value\": \"CHATS_SET\"\n },\n {\n \"label\": \"CHATS_UPSERT\",\n \"value\": \"CHATS_UPSERT\"\n },\n {\n \"label\": \"CHATS_UPDATE\",\n \"value\": \"CHATS_UPDATE\"\n },\n {\n \"label\": \"CHATS_DELETE\",\n \"value\": \"CHATS_DELETE\"\n },\n {\n \"label\": \"GROUPS_UPSERT\",\n \"value\": \"GROUPS_UPSERT\"\n },\n {\n \"label\": \"GROUP_UPDATE\",\n \"value\": \"GROUP_UPDATE\"\n },\n {\n \"label\": \"GROUP_PARTICIPANTS_UPDATE\",\n \"value\": \"GROUP_PARTICIPANTS_UPDATE\"\n },\n {\n \"label\": \"CONNECTION_UPDATE\",\n \"value\": \"CONNECTION_UPDATE\"\n },\n {\n \"label\": \"CALL\",\n \"value\": \"CALL\"\n },\n {\n \"label\": \"NEW_JWT_TOKEN\",\n \"value\": \"NEW_JWT_TOKEN\"\n }\n]"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","fieldType":"Object","sourceData":{"enabled":false,"url":"","webhook_by_events":false,"events":[]},"isCustomField":false,"accessor":"__root_schema__","identifier":"__root_schema__","position":-1.0,"originalIdentifier":"__root_schema__","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":""}},"mobileBottomRow":41.0,"widgetName":"FormWebhook","submitButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.webhook_by_events.defaultValue"},{"key":"schema.__root_schema__.children.enabled.defaultValue"},{"key":"schema.__root_schema__.children.url.defaultValue"}],"displayName":"JSON Form","bottomRow":41.0,"fieldLimitExceeded":false,"parentRowSpace":10.0,"title":"Webhook","hideCard":false,"mobileRightColumn":25.0,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[{"key":"onSubmit"}],"borderWidth":"0","sourceData":"{\n\t\"enabled\": {{Find_Webhook.data.enabled || false}},\n\t\"url\": {{Find_Webhook.data.url}},\n \"webhook_by_events\": {{Find_Webhook.data.webhook_by_events}},\n \"events\": {{Find_Webhook.data.events || false}} \n}","resetButtonLabel":"Reset","key":"lgqqk5r1jk","backgroundColor":"#fff","isDeprecated":false,"rightColumn":63.0,"widgetId":"tb1ekur7fx","minWidth":450.0,"parentId":"mv02ta6pzr","renderMode":"CANVAS","mobileTopRow":0.0,"scrollContents":true,"responsiveBehavior":"fill","fixedFooter":true,"originalTopRow":0.0,"mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"minDynamicHeight":4.0}],"isDisabled":false,"key":"svq68rvpdn","isDeprecated":false,"rightColumn":430.5,"detachFromLayout":true,"widgetId":"mv02ta6pzr","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"0g8ql5hukz","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"6x3z5yow7u","height":430.0,"isDeprecated":false,"rightColumn":35.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"0g8ql5hukz","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":46.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":11.0,"maxDynamicHeight":9000.0,"width":456.0,"minDynamicHeight":24.0},{"boxShadow":"none","mobileBottomRow":70.0,"widgetName":"ModalWebsocket","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":42.0,"bottomRow":40.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":35.0,"minHeight":400.0,"animateLoading":true,"parentColumnSpace":17.9375,"leftColumn":11.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas4Copy1","displayName":"Canvas","topRow":0.0,"bottomRow":400.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":400.0,"mobileRightColumn":430.5,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","borderColor":"#E0DEDE","iconSVG":"/static/media/icon.efac588608711d232f1c6c8a2144d2dd.svg","onSubmit":"{{Set_Websocket.run().then(() => {\n showAlert('Websocket updated successfully', 'success');\n}).catch(() => {\n showAlert('Error updating websocket', 'error');\n});\ncloseModal('ModalWebsocket');}}","topRow":0.0,"type":"JSON_FORM_WIDGET","animateLoading":true,"leftColumn":0.0,"dynamicBindingPathList":[{"key":"borderRadius"},{"key":"submitButtonStyles.buttonColor"},{"key":"schema.__root_schema__.defaultValue"},{"key":"schema.__root_schema__.borderRadius"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.enabled.defaultValue"},{"key":"schema.__root_schema__.children.enabled.accentColor"},{"key":"schema.__root_schema__.children.url.defaultValue"},{"key":"schema.__root_schema__.children.url.accentColor"},{"key":"schema.__root_schema__.children.url.borderRadius"},{"key":"schema.__root_schema__.children.events.defaultValue"},{"key":"schema.__root_schema__.children.events.accentColor"},{"key":"schema.__root_schema__.children.events.borderRadius"},{"key":"schema.__root_schema__.cellBorderRadius"}],"showReset":false,"dynamicHeight":"AUTO_HEIGHT","autoGenerateForm":false,"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"SECONDARY"},"isVisible":true,"version":1.0,"isLoading":false,"submitButtonLabel":"Save","childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}},"disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","originalBottomRow":38.0,"useSourceData":false,"schema":{"__root_schema__":{"children":{"enabled":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.enabled))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","fieldType":"Switch","sourceData":true,"isCustomField":false,"accessor":"enabled","identifier":"enabled","position":0.0,"originalIdentifier":"enabled","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Enabled"},"url":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.url))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","fieldType":"Text Input","sourceData":"https://teste.com","isCustomField":false,"accessor":"url","identifier":"url","position":1.0,"originalIdentifier":"url","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Url"},"events":{"children":{},"dataType":"array","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.events))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","fieldType":"Multiselect","sourceData":["MESSAGES_UPSERT"],"isCustomField":false,"accessor":"events","identifier":"events","position":2.0,"originalIdentifier":"events","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Events","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n\n {\n \"label\": \"APPLICATION_STARTUP\",\n \"value\": \"APPLICATION_STARTUP\"\n },\n {\n \"label\": \"QRCODE_UPDATED\",\n \"value\": \"QRCODE_UPDATED\"\n },\n {\n \"label\": \"MESSAGES_SET\",\n \"value\": \"MESSAGES_SET\"\n },\n {\n \"label\": \"MESSAGES_UPSERT\",\n \"value\": \"MESSAGES_UPSERT\"\n },\n {\n \"label\": \"MESSAGES_UPDATE\",\n \"value\": \"MESSAGES_UPDATE\"\n },\n {\n \"label\": \"MESSAGES_DELETE\",\n \"value\": \"MESSAGES_DELETE\"\n },\n {\n \"label\": \"SEND_MESSAGE\",\n \"value\": \"SEND_MESSAGE\"\n },\n {\n \"label\": \"CONTACTS_SET\",\n \"value\": \"CONTACTS_SET\"\n },\n {\n \"label\": \"CONTACTS_UPSERT\",\n \"value\": \"CONTACTS_UPSERT\"\n },\n {\n \"label\": \"CONTACTS_UPDATE\",\n \"value\": \"CONTACTS_UPDATE\"\n },\n {\n \"label\": \"PRESENCE_UPDATE\",\n \"value\": \"PRESENCE_UPDATE\"\n },\n {\n \"label\": \"CHATS_SET\",\n \"value\": \"CHATS_SET\"\n },\n {\n \"label\": \"CHATS_UPSERT\",\n \"value\": \"CHATS_UPSERT\"\n },\n {\n \"label\": \"CHATS_UPDATE\",\n \"value\": \"CHATS_UPDATE\"\n },\n {\n \"label\": \"CHATS_DELETE\",\n \"value\": \"CHATS_DELETE\"\n },\n {\n \"label\": \"GROUPS_UPSERT\",\n \"value\": \"GROUPS_UPSERT\"\n },\n {\n \"label\": \"GROUP_UPDATE\",\n \"value\": \"GROUP_UPDATE\"\n },\n {\n \"label\": \"GROUP_PARTICIPANTS_UPDATE\",\n \"value\": \"GROUP_PARTICIPANTS_UPDATE\"\n },\n {\n \"label\": \"CONNECTION_UPDATE\",\n \"value\": \"CONNECTION_UPDATE\"\n },\n {\n \"label\": \"CALL\",\n \"value\": \"CALL\"\n },\n {\n \"label\": \"NEW_JWT_TOKEN\",\n \"value\": \"NEW_JWT_TOKEN\"\n }\n]"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","fieldType":"Object","sourceData":{"enabled":true,"url":"https://teste.com","events":["MESSAGES_UPSERT"]},"isCustomField":false,"accessor":"__root_schema__","identifier":"__root_schema__","position":-1.0,"originalIdentifier":"__root_schema__","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":""}},"mobileBottomRow":41.0,"widgetName":"FormWebsocket","submitButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.enabled.defaultValue"},{"key":"schema.__root_schema__.children.events.defaultValue"},{"key":"schema.__root_schema__.children.url.defaultValue"}],"displayName":"JSON Form","bottomRow":38.0,"fieldLimitExceeded":false,"parentRowSpace":10.0,"title":"Websocket","hideCard":false,"mobileRightColumn":25.0,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[{"key":"onSubmit"}],"borderWidth":"0","sourceData":"{\n\t\"enabled\": {{Find_Websocket.data.enabled || false}},\n \"url\": {{Find_Websocket.data.url}},\n \"events\": {{Find_Websocket.data.events}}\n\t\t\n }","resetButtonLabel":"Reset","key":"lgqqk5r1jk","backgroundColor":"#fff","isDeprecated":false,"rightColumn":63.0,"widgetId":"masqwth5vo","minWidth":450.0,"parentId":"gzf4hjxdo8","renderMode":"CANVAS","mobileTopRow":0.0,"scrollContents":true,"responsiveBehavior":"fill","fixedFooter":true,"originalTopRow":0.0,"mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"minDynamicHeight":4.0}],"isDisabled":false,"key":"svq68rvpdn","isDeprecated":false,"rightColumn":430.5,"detachFromLayout":true,"widgetId":"gzf4hjxdo8","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"9twyngcwej","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"6x3z5yow7u","height":400.0,"isDeprecated":false,"rightColumn":35.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"9twyngcwej","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":46.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":11.0,"maxDynamicHeight":9000.0,"width":456.0,"minDynamicHeight":24.0},{"boxShadow":"none","mobileBottomRow":70.0,"widgetName":"ModalRabbitmq","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":31.0,"bottomRow":32.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":35.0,"minHeight":320.0,"animateLoading":true,"parentColumnSpace":17.9375,"leftColumn":11.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas4Copy1Copy","displayName":"Canvas","topRow":0.0,"bottomRow":320.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":240.0,"mobileRightColumn":430.5,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","borderColor":"#E0DEDE","iconSVG":"/static/media/icon.efac588608711d232f1c6c8a2144d2dd.svg","onSubmit":"{{Set_Rabbitmq.run().then(() => {\n showAlert('Rabbitmq updated successfully', 'success');\n}).catch(() => {\n showAlert('Error updating rabbitmq', 'error');\n});\ncloseModal('ModalRabbitmq');}}","topRow":0.0,"type":"JSON_FORM_WIDGET","animateLoading":true,"leftColumn":0.0,"dynamicBindingPathList":[{"key":"borderRadius"},{"key":"submitButtonStyles.buttonColor"},{"key":"sourceData"},{"key":"schema.__root_schema__.defaultValue"},{"key":"schema.__root_schema__.borderRadius"},{"key":"schema.__root_schema__.children.enabled.defaultValue"},{"key":"schema.__root_schema__.children.enabled.accentColor"},{"key":"schema.__root_schema__.children.events.defaultValue"},{"key":"schema.__root_schema__.children.events.accentColor"},{"key":"schema.__root_schema__.children.events.borderRadius"},{"key":"schema.__root_schema__.cellBorderRadius"}],"showReset":false,"dynamicHeight":"AUTO_HEIGHT","autoGenerateForm":false,"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"SECONDARY"},"isVisible":true,"version":1.0,"isLoading":false,"submitButtonLabel":"Save","childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}},"disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","originalBottomRow":30.0,"useSourceData":false,"schema":{"__root_schema__":{"children":{"enabled":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.enabled))(FormRabbitmq.sourceData, FormRabbitmq.formData, FormRabbitmq.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"enabled","identifier":"enabled","position":0.0,"originalIdentifier":"enabled","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormRabbitmq.sourceData, FormRabbitmq.formData, FormRabbitmq.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Enabled"},"events":{"children":{},"dataType":"array","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.events))(FormRabbitmq.sourceData, FormRabbitmq.formData, FormRabbitmq.fieldState)}}","fieldType":"Multiselect","sourceData":[],"isCustomField":false,"accessor":"events","identifier":"events","position":1.0,"originalIdentifier":"events","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormRabbitmq.sourceData, FormRabbitmq.formData, FormRabbitmq.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormRabbitmq.sourceData, FormRabbitmq.formData, FormRabbitmq.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Events","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n\n {\n \"label\": \"APPLICATION_STARTUP\",\n \"value\": \"APPLICATION_STARTUP\"\n },\n {\n \"label\": \"QRCODE_UPDATED\",\n \"value\": \"QRCODE_UPDATED\"\n },\n {\n \"label\": \"MESSAGES_SET\",\n \"value\": \"MESSAGES_SET\"\n },\n {\n \"label\": \"MESSAGES_UPSERT\",\n \"value\": \"MESSAGES_UPSERT\"\n },\n {\n \"label\": \"MESSAGES_UPDATE\",\n \"value\": \"MESSAGES_UPDATE\"\n },\n {\n \"label\": \"MESSAGES_DELETE\",\n \"value\": \"MESSAGES_DELETE\"\n },\n {\n \"label\": \"SEND_MESSAGE\",\n \"value\": \"SEND_MESSAGE\"\n },\n {\n \"label\": \"CONTACTS_SET\",\n \"value\": \"CONTACTS_SET\"\n },\n {\n \"label\": \"CONTACTS_UPSERT\",\n \"value\": \"CONTACTS_UPSERT\"\n },\n {\n \"label\": \"CONTACTS_UPDATE\",\n \"value\": \"CONTACTS_UPDATE\"\n },\n {\n \"label\": \"PRESENCE_UPDATE\",\n \"value\": \"PRESENCE_UPDATE\"\n },\n {\n \"label\": \"CHATS_SET\",\n \"value\": \"CHATS_SET\"\n },\n {\n \"label\": \"CHATS_UPSERT\",\n \"value\": \"CHATS_UPSERT\"\n },\n {\n \"label\": \"CHATS_UPDATE\",\n \"value\": \"CHATS_UPDATE\"\n },\n {\n \"label\": \"CHATS_DELETE\",\n \"value\": \"CHATS_DELETE\"\n },\n {\n \"label\": \"GROUPS_UPSERT\",\n \"value\": \"GROUPS_UPSERT\"\n },\n {\n \"label\": \"GROUP_UPDATE\",\n \"value\": \"GROUP_UPDATE\"\n },\n {\n \"label\": \"GROUP_PARTICIPANTS_UPDATE\",\n \"value\": \"GROUP_PARTICIPANTS_UPDATE\"\n },\n {\n \"label\": \"CONNECTION_UPDATE\",\n \"value\": \"CONNECTION_UPDATE\"\n },\n {\n \"label\": \"CALL\",\n \"value\": \"CALL\"\n },\n {\n \"label\": \"NEW_JWT_TOKEN\",\n \"value\": \"NEW_JWT_TOKEN\"\n }\n]"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(FormRabbitmq.sourceData, FormRabbitmq.formData, FormRabbitmq.fieldState)}}","fieldType":"Object","sourceData":{"enabled":false,"events":[]},"isCustomField":false,"accessor":"__root_schema__","identifier":"__root_schema__","position":-1.0,"originalIdentifier":"__root_schema__","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormRabbitmq.sourceData, FormRabbitmq.formData, FormRabbitmq.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormRabbitmq.sourceData, FormRabbitmq.formData, FormRabbitmq.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":""}},"mobileBottomRow":41.0,"widgetName":"FormRabbitmq","submitButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.events.defaultValue"},{"key":"schema.__root_schema__.children.enabled.defaultValue"}],"displayName":"JSON Form","bottomRow":30.0,"fieldLimitExceeded":false,"parentRowSpace":10.0,"title":"Rabbitmq","hideCard":false,"mobileRightColumn":25.0,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[{"key":"onSubmit"}],"borderWidth":"0","sourceData":"{\n\t\"enabled\": {{Find_Rabbitmq.data.enabled || false}},\n \"events\": {{Find_Rabbitmq.data.events}}\n\t\t\n }","resetButtonLabel":"Reset","key":"lgqqk5r1jk","backgroundColor":"#fff","isDeprecated":false,"rightColumn":63.0,"widgetId":"gdkpog7ep5","minWidth":450.0,"parentId":"rkuaegvcin","renderMode":"CANVAS","mobileTopRow":0.0,"scrollContents":true,"responsiveBehavior":"fill","fixedFooter":true,"originalTopRow":0.0,"mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"minDynamicHeight":4.0}],"isDisabled":false,"key":"svq68rvpdn","isDeprecated":false,"rightColumn":430.5,"detachFromLayout":true,"widgetId":"rkuaegvcin","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"76vl08dr1n","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"6x3z5yow7u","height":320.0,"isDeprecated":false,"rightColumn":35.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"76vl08dr1n","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":46.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":11.0,"maxDynamicHeight":9000.0,"width":456.0,"minDynamicHeight":24.0},{"boxShadow":"none","mobileBottomRow":70.0,"widgetName":"ModalSettings","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":46.0,"bottomRow":47.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":35.0,"minHeight":470.0,"animateLoading":true,"parentColumnSpace":17.9375,"leftColumn":11.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas4Copy","displayName":"Canvas","topRow":0.0,"bottomRow":470.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":240.0,"mobileRightColumn":430.5,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","borderColor":"#E0DEDE","iconSVG":"/static/media/icon.efac588608711d232f1c6c8a2144d2dd.svg","onSubmit":"{{Set_Settings.run().then(() => {\n showAlert('Settings updated successfully', 'success');\n}).catch(() => {\n showAlert('Error updating Settings', 'error');\n});\ncloseModal('ModalSettings');}}","topRow":0.0,"type":"JSON_FORM_WIDGET","animateLoading":true,"leftColumn":1.0,"dynamicBindingPathList":[{"key":"schema.__root_schema__.children.read_status.accentColor"},{"key":"schema.__root_schema__.children.read_status.defaultValue"},{"key":"schema.__root_schema__.children.read_messages.accentColor"},{"key":"schema.__root_schema__.children.read_messages.defaultValue"},{"key":"schema.__root_schema__.children.always_online.accentColor"},{"key":"schema.__root_schema__.children.always_online.defaultValue"},{"key":"schema.__root_schema__.children.groups_ignore.accentColor"},{"key":"schema.__root_schema__.children.groups_ignore.defaultValue"},{"key":"schema.__root_schema__.children.msg_call.accentColor"},{"key":"schema.__root_schema__.children.msg_call.defaultValue"},{"key":"schema.__root_schema__.children.reject_call.accentColor"},{"key":"schema.__root_schema__.children.reject_call.defaultValue"},{"key":"borderRadius"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.msg_call.borderRadius"},{"key":"submitButtonStyles.buttonColor"}],"showReset":false,"dynamicHeight":"AUTO_HEIGHT","autoGenerateForm":true,"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"SECONDARY"},"isVisible":true,"version":1.0,"isLoading":false,"submitButtonLabel":"Save","childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}},"disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","originalBottomRow":45.0,"useSourceData":false,"schema":{"__root_schema__":{"children":{"reject_call":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.reject_call))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","fieldType":"Switch","sourceData":true,"isCustomField":false,"accessor":"reject_call","identifier":"reject_call","position":0.0,"originalIdentifier":"reject_call","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Reject Call"},"msg_call":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.msg_call))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","fieldType":"Text Input","sourceData":"Não aceitamos chamadas!","isCustomField":false,"accessor":"msg_call","identifier":"msg_call","position":1.0,"originalIdentifier":"msg_call","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Msg Call"},"groups_ignore":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.groups_ignore))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","fieldType":"Switch","sourceData":true,"isCustomField":false,"accessor":"groups_ignore","identifier":"groups_ignore","position":2.0,"originalIdentifier":"groups_ignore","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Groups Ignore"},"always_online":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.always_online))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","fieldType":"Switch","sourceData":true,"isCustomField":false,"accessor":"always_online","identifier":"always_online","position":3.0,"originalIdentifier":"always_online","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Always Online"},"read_messages":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.read_messages))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","fieldType":"Switch","sourceData":true,"isCustomField":false,"accessor":"read_messages","identifier":"read_messages","position":4.0,"originalIdentifier":"read_messages","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Read Messages"},"read_status":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.read_status))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"read_status","identifier":"read_status","position":5.0,"originalIdentifier":"read_status","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Read Status"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","fieldType":"Object","sourceData":{"name":"John","date_of_birth":"20/02/1990","employee_id":1001.0},"isCustomField":false,"accessor":"__root_schema__","identifier":"__root_schema__","position":-1.0,"originalIdentifier":"__root_schema__","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":""}},"mobileBottomRow":41.0,"widgetName":"FormSettings","submitButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.reject_call.defaultValue"},{"key":"schema.__root_schema__.children.groups_ignore.defaultValue"},{"key":"schema.__root_schema__.children.always_online.defaultValue"},{"key":"schema.__root_schema__.children.read_messages.defaultValue"},{"key":"schema.__root_schema__.children.read_status.defaultValue"},{"key":"schema.__root_schema__.children.msg_call.defaultValue"}],"displayName":"JSON Form","bottomRow":45.0,"fieldLimitExceeded":false,"parentRowSpace":10.0,"title":"Settings","hideCard":false,"mobileRightColumn":25.0,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[{"key":"onSubmit"}],"borderWidth":"0","sourceData":"{\n\t\"reject_call\": {{Find_Settings.data.reject_call || false}},\n \"msg_call\": {{Find_Settings.data.msg_call}},\n \"groups_ignore\": {{Find_Settings.data.groups_ignore || false}},\n \"always_online\": {{Find_Settings.data.always_online || false}},\n \"read_messages\": {{Find_Settings.data.read_messages || false}},\n \"read_status\": {{Find_Settings.data.read_status || false}}\n}","resetButtonLabel":"Reset","key":"lgqqk5r1jk","backgroundColor":"#fff","isDeprecated":false,"rightColumn":64.0,"widgetId":"3wajdobhry","minWidth":450.0,"parentId":"bj66ktxeor","renderMode":"CANVAS","mobileTopRow":0.0,"scrollContents":true,"responsiveBehavior":"fill","fixedFooter":true,"originalTopRow":0.0,"mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"minDynamicHeight":4.0}],"isDisabled":false,"key":"svq68rvpdn","isDeprecated":false,"rightColumn":430.5,"detachFromLayout":true,"widgetId":"bj66ktxeor","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"9pvl5efylb","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"6x3z5yow7u","height":470.0,"isDeprecated":false,"rightColumn":35.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"9pvl5efylb","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":46.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":11.0,"maxDynamicHeight":9000.0,"width":456.0,"minDynamicHeight":24.0},{"boxShadow":"none","mobileBottomRow":70.0,"widgetName":"ModalChatwoot","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":50.0,"bottomRow":780.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":35.0,"minHeight":730.0,"animateLoading":true,"parentColumnSpace":17.9375,"leftColumn":11.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas4CopyCopy","displayName":"Canvas","topRow":0.0,"bottomRow":730.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":730.0,"mobileRightColumn":430.5,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","borderColor":"#E0DEDE","iconSVG":"/static/media/icon.efac588608711d232f1c6c8a2144d2dd.svg","onSubmit":"{{Set_Chatwoot.run().then(() => {\n showAlert('Chatwoot updated successfully', 'success');\n}).catch(() => {\n showAlert('Error updating Chatwoot', 'error');\n});\ncloseModal('ModalChatwoot');}}","topRow":0.0,"type":"JSON_FORM_WIDGET","animateLoading":true,"leftColumn":0.0,"dynamicBindingPathList":[{"key":"schema.__root_schema__.children.conversation_pending.accentColor"},{"key":"schema.__root_schema__.children.conversation_pending.defaultValue"},{"key":"schema.__root_schema__.children.reopen_conversation.accentColor"},{"key":"schema.__root_schema__.children.reopen_conversation.defaultValue"},{"key":"schema.__root_schema__.children.sign_msg.accentColor"},{"key":"schema.__root_schema__.children.sign_msg.defaultValue"},{"key":"schema.__root_schema__.children.url.borderRadius"},{"key":"schema.__root_schema__.children.url.accentColor"},{"key":"schema.__root_schema__.children.url.defaultValue"},{"key":"schema.__root_schema__.children.token.borderRadius"},{"key":"schema.__root_schema__.children.token.accentColor"},{"key":"schema.__root_schema__.children.token.defaultValue"},{"key":"schema.__root_schema__.children.account_id.accentColor"},{"key":"schema.__root_schema__.children.account_id.defaultValue"},{"key":"schema.__root_schema__.children.enabled.accentColor"},{"key":"schema.__root_schema__.children.enabled.defaultValue"},{"key":"borderRadius"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.account_id.borderRadius"},{"key":"schema.__root_schema__.children.webhook_url.defaultValue"},{"key":"schema.__root_schema__.children.webhook_url.accentColor"},{"key":"schema.__root_schema__.children.webhook_url.borderRadius"},{"key":"schema.__root_schema__.defaultValue"},{"key":"schema.__root_schema__.borderRadius"},{"key":"schema.__root_schema__.cellBorderRadius"},{"key":"schema.__root_schema__.children.name_inbox.defaultValue"},{"key":"schema.__root_schema__.children.name_inbox.borderRadius"},{"key":"schema.__root_schema__.children.name_inbox.accentColor"},{"key":"submitButtonStyles.buttonColor"}],"showReset":false,"dynamicHeight":"AUTO_HEIGHT","autoGenerateForm":true,"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"SECONDARY"},"isVisible":true,"version":1.0,"isLoading":false,"submitButtonLabel":"Save","childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}},"disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","originalBottomRow":71.0,"useSourceData":false,"schema":{"__root_schema__":{"children":{"enabled":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.enabled))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","fieldType":"Switch","sourceData":true,"isCustomField":false,"accessor":"enabled","identifier":"enabled","position":0.0,"originalIdentifier":"enabled","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Enabled"},"account_id":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.account_id))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","fieldType":"Text Input","sourceData":"1","isCustomField":false,"accessor":"account_id","identifier":"account_id","position":1.0,"originalIdentifier":"account_id","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Account Id"},"token":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.token))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","fieldType":"Password Input","sourceData":"uHquVJgCdkee8JPJm9YBkdH6","isCustomField":false,"accessor":"token","identifier":"token","position":2.0,"originalIdentifier":"token","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Token","shouldAllowAutofill":true},"url":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.url))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","fieldType":"Text Input","sourceData":"https://chatwoot.evolution.dgcode.com.br","isCustomField":false,"accessor":"url","identifier":"url","position":3.0,"originalIdentifier":"url","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Url"},"sign_msg":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.sign_msg))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"sign_msg","identifier":"sign_msg","position":4.0,"originalIdentifier":"sign_msg","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Sign Msg"},"reopen_conversation":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.reopen_conversation))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","fieldType":"Switch","sourceData":true,"isCustomField":false,"accessor":"reopen_conversation","identifier":"reopen_conversation","position":5.0,"originalIdentifier":"reopen_conversation","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Reopen Conversation"},"conversation_pending":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.conversation_pending))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"conversation_pending","identifier":"conversation_pending","position":6.0,"originalIdentifier":"conversation_pending","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Conversation Pending"},"webhook_url":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.webhook_url))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","fieldType":"Text Input","sourceData":"https://api.evolution.dgcode.com.br/chatwoot/webhook/evolution-cwId-4","isCustomField":false,"accessor":"webhook_url","identifier":"webhook_url","position":8.0,"originalIdentifier":"webhook_url","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":true,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Webhook Url"},"name_inbox":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.name_inbox))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","fieldType":"Text Input","sourceData":"evolution-cwId-4","isCustomField":false,"accessor":"name_inbox","identifier":"name_inbox","position":7.0,"originalIdentifier":"name_inbox","accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":true,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Name Inbox"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","fieldType":"Object","sourceData":{"name":"John","date_of_birth":"20/02/1990","employee_id":1001.0},"isCustomField":false,"accessor":"__root_schema__","identifier":"__root_schema__","position":-1.0,"originalIdentifier":"__root_schema__","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":""}},"mobileBottomRow":41.0,"widgetName":"FormChatwoot","submitButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.enabled.defaultValue"},{"key":"schema.__root_schema__.children.sign_msg.defaultValue"},{"key":"schema.__root_schema__.children.reopen_conversation.defaultValue"},{"key":"schema.__root_schema__.children.conversation_pending.defaultValue"},{"key":"schema.__root_schema__.children.account_id.defaultValue"},{"key":"schema.__root_schema__.children.webhook_url.defaultValue"}],"displayName":"JSON Form","bottomRow":71.0,"fieldLimitExceeded":false,"parentRowSpace":10.0,"title":"Chatwoot","hideCard":false,"mobileRightColumn":25.0,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[{"key":"onSubmit"}],"borderWidth":"0","sourceData":"{\n\t\"enabled\": {{Find_Chatwoot.data.enabled || false}},\n\t\"account_id\": {{Find_Chatwoot.data.account_id}},\n \"token\": {{Find_Chatwoot.data.token}},\n \"url\": {{Find_Chatwoot.data.url}},\n \"sign_msg\": {{Find_Chatwoot.data.sign_msg || false}},\n \"reopen_conversation\": {{Find_Chatwoot.data.reopen_conversation || false}},\n \"conversation_pending\": {{Find_Chatwoot.data.conversation_pending || false}},\n\t\t\"name_inbox\": {{Find_Chatwoot.data.name_inbox}},\n\t\t\"webhook_url\": {{Find_Chatwoot.data.webhook_url}}\n}","resetButtonLabel":"Reset","key":"lgqqk5r1jk","backgroundColor":"#fff","isDeprecated":false,"rightColumn":63.0,"widgetId":"c5v1lwuyrk","minWidth":450.0,"parentId":"wqoo05rt9h","renderMode":"CANVAS","mobileTopRow":0.0,"scrollContents":true,"responsiveBehavior":"fill","fixedFooter":true,"originalTopRow":0.0,"mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"minDynamicHeight":4.0}],"isDisabled":false,"key":"svq68rvpdn","isDeprecated":false,"rightColumn":430.5,"detachFromLayout":true,"widgetId":"wqoo05rt9h","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"kekx3o71p4","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"6x3z5yow7u","height":730.0,"isDeprecated":false,"rightColumn":35.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"kekx3o71p4","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":46.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":11.0,"maxDynamicHeight":9000.0,"width":692.0,"minDynamicHeight":24.0},{"boxShadow":"none","mobileBottomRow":70.0,"widgetName":"ModalTypebot","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":45.0,"bottomRow":775.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":35.0,"minHeight":730.0,"animateLoading":true,"parentColumnSpace":17.9375,"leftColumn":11.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas4CopyCopyCopy","displayName":"Canvas","topRow":0.0,"bottomRow":730.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":730.0,"mobileRightColumn":430.5,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","borderColor":"#E0DEDE","iconSVG":"/static/media/icon.efac588608711d232f1c6c8a2144d2dd.svg","onSubmit":"{{Set_Typebot.run().then(() => {\n showAlert('Typebot updated successfully', 'success');\n}).catch(() => {\n showAlert('Error updating Typebot', 'error');\n});\ncloseModal('ModalTypebot');}}","topRow":1.0,"type":"JSON_FORM_WIDGET","animateLoading":true,"leftColumn":0.0,"dynamicBindingPathList":[{"key":"borderRadius"},{"key":"schema.__root_schema__.defaultValue"},{"key":"schema.__root_schema__.borderRadius"},{"key":"submitButtonStyles.buttonColor"},{"key":"schema.__root_schema__.cellBorderRadius"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.enabled.defaultValue"},{"key":"schema.__root_schema__.children.enabled.accentColor"},{"key":"schema.__root_schema__.children.url.defaultValue"},{"key":"schema.__root_schema__.children.url.accentColor"},{"key":"schema.__root_schema__.children.url.borderRadius"},{"key":"schema.__root_schema__.children.typebot.defaultValue"},{"key":"schema.__root_schema__.children.typebot.accentColor"},{"key":"schema.__root_schema__.children.typebot.borderRadius"},{"key":"schema.__root_schema__.children.expire.defaultValue"},{"key":"schema.__root_schema__.children.expire.accentColor"},{"key":"schema.__root_schema__.children.expire.borderRadius"},{"key":"schema.__root_schema__.children.keyword_finish.defaultValue"},{"key":"schema.__root_schema__.children.keyword_finish.accentColor"},{"key":"schema.__root_schema__.children.keyword_finish.borderRadius"},{"key":"schema.__root_schema__.children.delay_message.defaultValue"},{"key":"schema.__root_schema__.children.delay_message.accentColor"},{"key":"schema.__root_schema__.children.delay_message.borderRadius"},{"key":"schema.__root_schema__.children.unknown_message.defaultValue"},{"key":"schema.__root_schema__.children.unknown_message.accentColor"},{"key":"schema.__root_schema__.children.unknown_message.borderRadius"},{"key":"schema.__root_schema__.children.listening_from_me.defaultValue"},{"key":"schema.__root_schema__.children.listening_from_me.accentColor"}],"showReset":false,"dynamicHeight":"AUTO_HEIGHT","autoGenerateForm":true,"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"SECONDARY"},"isVisible":true,"version":1.0,"isLoading":false,"submitButtonLabel":"Save","childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}},"disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","originalBottomRow":71.0,"useSourceData":false,"schema":{"__root_schema__":{"children":{"enabled":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.enabled))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Switch","sourceData":true,"isCustomField":false,"accessor":"enabled","identifier":"enabled","position":0.0,"originalIdentifier":"enabled","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Enabled"},"url":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.url))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Text Input","sourceData":"https://bot.typebot.com","isCustomField":false,"accessor":"url","identifier":"url","position":1.0,"originalIdentifier":"url","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Url"},"typebot":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.typebot))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Text Input","sourceData":"felipe-final-sbkaa3s","isCustomField":false,"accessor":"typebot","identifier":"typebot","position":2.0,"originalIdentifier":"typebot","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Typebot"},"expire":{"children":{},"dataType":"number","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.expire))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Number Input","sourceData":45.0,"isCustomField":false,"accessor":"expire","identifier":"expire","position":3.0,"originalIdentifier":"expire","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Expire"},"keyword_finish":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.keyword_finish))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Text Input","sourceData":"#SAIR","isCustomField":false,"accessor":"keyword_finish","identifier":"keyword_finish","position":4.0,"originalIdentifier":"keyword_finish","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Keyword Finish"},"delay_message":{"children":{},"dataType":"number","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.delay_message))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Number Input","sourceData":2000.0,"isCustomField":false,"accessor":"delay_message","identifier":"delay_message","position":5.0,"originalIdentifier":"delay_message","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Delay Message"},"unknown_message":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.unknown_message))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"unknown_message","identifier":"unknown_message","position":6.0,"originalIdentifier":"unknown_message","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Unknown Message"},"listening_from_me":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.listening_from_me))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"listening_from_me","identifier":"listening_from_me","position":7.0,"originalIdentifier":"listening_from_me","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Listening From Me"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Object","sourceData":{"enabled":true,"url":"https://bot.typebot.com","typebot":"bot-typebot","expire":20.0,"keyword_finish":"#SAIR","delay_message":3000.0,"unknown_message":"Mensagem não reconhecida2"},"isCustomField":false,"accessor":"__root_schema__","identifier":"__root_schema__","position":-1.0,"originalIdentifier":"__root_schema__","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":""}},"mobileBottomRow":41.0,"widgetName":"FormTypebot","submitButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.sign_msg.defaultValue"},{"key":"schema.__root_schema__.children.reopen_conversation.defaultValue"},{"key":"schema.__root_schema__.children.conversation_pending.defaultValue"},{"key":"schema.__root_schema__.children.account_id.defaultValue"},{"key":"schema.__root_schema__.children.webhook_url.defaultValue"},{"key":"schema.__root_schema__.children.enabled.defaultValue"},{"key":"schema.__root_schema__.children.listening_from_me.defaultValue"}],"displayName":"JSON Form","bottomRow":71.0,"fieldLimitExceeded":false,"parentRowSpace":10.0,"title":"Set Typebot","hideCard":false,"mobileRightColumn":25.0,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[{"key":"onSubmit"}],"borderWidth":"0","sourceData":"{\n \"enabled\": {{Find_Typebot.data.enabled || false}},\n \"url\": {{Find_Typebot.data.url}},\n \"typebot\": {{Find_Typebot.data.typebot}},\n \"expire\": {{Find_Typebot.data.expire}},\n \"keyword_finish\": {{Find_Typebot.data.keyword_finish}},\n \"delay_message\": {{Find_Typebot.data.delay_message}},\n \"unknown_message\": {{Find_Typebot.data.unknown_message}},\n \"listening_from_me\": {{Find_Typebot.data.listening_from_me}}\n \n}","resetButtonLabel":"Reset","key":"lgqqk5r1jk","backgroundColor":"#fff","isDeprecated":false,"rightColumn":63.0,"widgetId":"fyu0oxvlx7","minWidth":450.0,"parentId":"bvxewkusbf","renderMode":"CANVAS","mobileTopRow":0.0,"scrollContents":true,"responsiveBehavior":"fill","fixedFooter":true,"originalTopRow":1.0,"mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"minDynamicHeight":4.0}],"isDisabled":false,"key":"svq68rvpdn","isDeprecated":false,"rightColumn":430.5,"detachFromLayout":true,"widgetId":"bvxewkusbf","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"4n3m0wo9tx","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"6x3z5yow7u","height":730.0,"isDeprecated":false,"rightColumn":35.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"4n3m0wo9tx","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":46.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":11.0,"maxDynamicHeight":9000.0,"width":692.0,"minDynamicHeight":24.0},{"boxShadow":"none","mobileBottomRow":70.0,"widgetName":"ModalTypebotChangeSessionStatu","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":45.0,"bottomRow":415.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":35.0,"minHeight":370.0,"animateLoading":true,"parentColumnSpace":17.9375,"leftColumn":11.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas4CopyCopyCopyCopy","displayName":"Canvas","topRow":0.0,"bottomRow":370.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":730.0,"mobileRightColumn":430.5,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","borderColor":"#E0DEDE","iconSVG":"/static/media/icon.efac588608711d232f1c6c8a2144d2dd.svg","onSubmit":"{{Set_TypebotChangeSessionStatus.run().then(() => {\n showAlert('Typebot Change Session updated successfully', 'success');\n}).catch(() => {\n showAlert('Error updating Session Typebot', 'error');\n});\ncloseModal('ModalTypebotChangeSessionStatu');}}","topRow":1.0,"type":"JSON_FORM_WIDGET","animateLoading":true,"leftColumn":0.0,"dynamicBindingPathList":[{"key":"borderRadius"},{"key":"schema.__root_schema__.defaultValue"},{"key":"schema.__root_schema__.borderRadius"},{"key":"submitButtonStyles.buttonColor"},{"key":"schema.__root_schema__.cellBorderRadius"},{"key":"schema.__root_schema__.children.remoteJid.defaultValue"},{"key":"schema.__root_schema__.children.remoteJid.accentColor"},{"key":"schema.__root_schema__.children.remoteJid.borderRadius"},{"key":"schema.__root_schema__.children.status.defaultValue"},{"key":"schema.__root_schema__.children.status.accentColor"},{"key":"schema.__root_schema__.children.status.borderRadius"}],"showReset":false,"dynamicHeight":"AUTO_HEIGHT","autoGenerateForm":true,"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"SECONDARY"},"isVisible":true,"version":1.0,"isLoading":false,"submitButtonLabel":"Save","childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}},"disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","originalBottomRow":35.0,"useSourceData":false,"schema":{"__root_schema__":{"children":{"remoteJid":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.remoteJid))(FormTypebotChangeSessionStatus.sourceData, FormTypebotChangeSessionStatus.formData, FormTypebotChangeSessionStatus.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"remoteJid","identifier":"remoteJid","position":0.0,"originalIdentifier":"remoteJid","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebotChangeSessionStatus.sourceData, FormTypebotChangeSessionStatus.formData, FormTypebotChangeSessionStatus.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebotChangeSessionStatus.sourceData, FormTypebotChangeSessionStatus.formData, FormTypebotChangeSessionStatus.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":true,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Remote Jid (WhatsApp. Ex: 5511968162699@s.whatsapp.net)"},"status":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.status))(FormTypebotChangeSessionStatus.sourceData, FormTypebotChangeSessionStatus.formData, FormTypebotChangeSessionStatus.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"status","identifier":"status","position":1.0,"originalIdentifier":"status","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebotChangeSessionStatus.sourceData, FormTypebotChangeSessionStatus.formData, FormTypebotChangeSessionStatus.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebotChangeSessionStatus.sourceData, FormTypebotChangeSessionStatus.formData, FormTypebotChangeSessionStatus.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Status (opened, paused or closed)"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Object","sourceData":{"enabled":true,"url":"https://bot.typebot.com","typebot":"bot-typebot","expire":20.0,"keyword_finish":"#SAIR","delay_message":3000.0,"unknown_message":"Mensagem não reconhecida2"},"isCustomField":false,"accessor":"__root_schema__","identifier":"__root_schema__","position":-1.0,"originalIdentifier":"__root_schema__","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":""}},"mobileBottomRow":41.0,"widgetName":"FormTypebotChangeSessionStatus","submitButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.sign_msg.defaultValue"},{"key":"schema.__root_schema__.children.reopen_conversation.defaultValue"},{"key":"schema.__root_schema__.children.conversation_pending.defaultValue"},{"key":"schema.__root_schema__.children.account_id.defaultValue"},{"key":"schema.__root_schema__.children.webhook_url.defaultValue"}],"displayName":"JSON Form","bottomRow":35.0,"fieldLimitExceeded":false,"parentRowSpace":10.0,"title":"Typebot Change Session Status","hideCard":false,"mobileRightColumn":25.0,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[{"key":"onSubmit"}],"borderWidth":"0","sourceData":"{\n \"remoteJid\": \"@s.whatsapp.net\",\n \"status\": \"\"\n}","resetButtonLabel":"Reset","key":"lgqqk5r1jk","backgroundColor":"#fff","isDeprecated":false,"rightColumn":63.0,"widgetId":"28lli5jdvr","minWidth":450.0,"parentId":"8m0yhclt7g","renderMode":"CANVAS","mobileTopRow":0.0,"scrollContents":true,"responsiveBehavior":"fill","fixedFooter":true,"originalTopRow":1.0,"mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"minDynamicHeight":4.0}],"isDisabled":false,"key":"svq68rvpdn","isDeprecated":false,"rightColumn":430.5,"detachFromLayout":true,"widgetId":"8m0yhclt7g","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"84rj87eew6","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"6x3z5yow7u","height":370.0,"isDeprecated":false,"rightColumn":35.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"84rj87eew6","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":46.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":11.0,"maxDynamicHeight":9000.0,"width":692.0,"minDynamicHeight":24.0},{"resetFormOnClick":false,"boxShadow":"none","mobileBottomRow":50.0,"widgetName":"Button2","onClick":"{{Fetch_Instance.run();\nFetch_PrivacySettings.run();\nshowModal('ModalProfile');}}","buttonColor":"#2770fc","dynamicPropertyPathList":[{"key":"isVisible"}],"displayName":"Button","iconSVG":"/static/media/icon.7beb9123fb53027d9d6b778cdfe4caed.svg","searchTags":["click","submit"],"topRow":28.0,"bottomRow":32.0,"parentRowSpace":10.0,"type":"BUTTON_WIDGET","hideCard":false,"mobileRightColumn":21.0,"animateLoading":true,"parentColumnSpace":17.9375,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":1.0,"dynamicBindingPathList":[{"key":"borderRadius"},{"key":"isVisible"}],"text":"Edit Profile","isDisabled":false,"key":"zhd9fobc1z","isDeprecated":false,"rightColumn":13.0,"isDefaultClickDisabled":true,"iconName":"edit","widgetId":"uh6430ysqy","minWidth":120.0,"isVisible":"{{appsmith.store.api_key && appsmith.store.api_url ? TableInstances.selectedRow.instance ? TableInstances.selectedRow.Status === 'open' ? true : false : false : false}}","recaptchaType":"V3","version":1.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":46.0,"responsiveBehavior":"hug","originalTopRow":51.0,"disabledWhenInvalid":false,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":5.0,"originalBottomRow":55.0,"buttonVariant":"PRIMARY","iconAlign":"left","placement":"CENTER"},{"boxShadow":"none","mobileBottomRow":59.0,"widgetName":"ModalProfile","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":35.0,"bottomRow":975.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":35.0,"minHeight":940.0,"animateLoading":true,"parentColumnSpace":17.9375,"leftColumn":11.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas5","displayName":"Canvas","topRow":0.0,"bottomRow":940.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":240.0,"mobileRightColumn":430.5,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","borderColor":"#E0DEDE","iconSVG":"/static/media/icon.efac588608711d232f1c6c8a2144d2dd.svg","onSubmit":"{{Update_ProfileName.run().then(() => {\n showAlert('ProfileName successfully saved!', 'success');\n}).catch(() => {\n showAlert('Error updating ProfileName', 'error');\n});\nUpdate_ProfilePicture.run().then(() => {\n showAlert('ProfilePicture successfully saved!', 'success');\n}).catch(() => {\n showAlert('Error updating ProfilePicture', 'error');\n});\nUpdate_ProfileStatus.run().then(() => {\n showAlert('ProfileStatus successfully saved!', 'success');\n}).catch(() => {\n showAlert('Error updating ProfileStatus', 'error');\n});\nUpdate_PrivacySettings.run().then(() => {\n showAlert('PrivacySttings successfully saved!', 'success');\n}).catch(() => {\n showAlert('Error updating PrivacySttings', 'error');\n});\nfetch_Instances.run();\ncloseModal('ModalProfile');}}","topRow":0.0,"type":"JSON_FORM_WIDGET","animateLoading":true,"leftColumn":0.0,"dynamicBindingPathList":[{"key":"borderRadius"},{"key":"submitButtonStyles.buttonColor"},{"key":"submitButtonStyles.borderRadius"},{"key":"resetButtonStyles.buttonColor"},{"key":"resetButtonStyles.borderRadius"},{"key":"schema.__root_schema__.defaultValue"},{"key":"schema.__root_schema__.borderRadius"},{"key":"schema.__root_schema__.cellBorderRadius"},{"key":"schema.__root_schema__.children.profileName.defaultValue"},{"key":"schema.__root_schema__.children.profileName.accentColor"},{"key":"schema.__root_schema__.children.profileName.borderRadius"},{"key":"schema.__root_schema__.children.profileStatus.defaultValue"},{"key":"schema.__root_schema__.children.profileStatus.accentColor"},{"key":"schema.__root_schema__.children.profileStatus.borderRadius"},{"key":"schema.__root_schema__.children.profilePictureUrl.defaultValue"},{"key":"schema.__root_schema__.children.profilePictureUrl.borderRadius"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.profilePictureUrl.accentColor"},{"key":"schema.__root_schema__.children.privacySettings.children.readreceipts.defaultValue"},{"key":"schema.__root_schema__.children.privacySettings.children.readreceipts.accentColor"},{"key":"schema.__root_schema__.children.privacySettings.children.readreceipts.borderRadius"},{"key":"schema.__root_schema__.children.privacySettings.children.profile.defaultValue"},{"key":"schema.__root_schema__.children.privacySettings.children.profile.accentColor"},{"key":"schema.__root_schema__.children.privacySettings.children.profile.borderRadius"},{"key":"schema.__root_schema__.children.privacySettings.children.status.defaultValue"},{"key":"schema.__root_schema__.children.privacySettings.children.status.accentColor"},{"key":"schema.__root_schema__.children.privacySettings.children.status.borderRadius"},{"key":"schema.__root_schema__.children.privacySettings.children.online.defaultValue"},{"key":"schema.__root_schema__.children.privacySettings.children.online.accentColor"},{"key":"schema.__root_schema__.children.privacySettings.children.online.borderRadius"},{"key":"schema.__root_schema__.children.privacySettings.children.last.defaultValue"},{"key":"schema.__root_schema__.children.privacySettings.children.last.accentColor"},{"key":"schema.__root_schema__.children.privacySettings.children.last.borderRadius"},{"key":"schema.__root_schema__.children.privacySettings.children.groupadd.defaultValue"},{"key":"schema.__root_schema__.children.privacySettings.children.groupadd.accentColor"},{"key":"schema.__root_schema__.children.privacySettings.children.groupadd.borderRadius"},{"key":"schema.__root_schema__.children.privacySettings.defaultValue"},{"key":"schema.__root_schema__.children.privacySettings.borderRadius"},{"key":"schema.__root_schema__.children.privacySettings.cellBorderRadius"}],"showReset":false,"dynamicHeight":"AUTO_HEIGHT","autoGenerateForm":true,"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"SECONDARY"},"isVisible":true,"version":1.0,"isLoading":false,"submitButtonLabel":"Save","childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}},"disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","originalBottomRow":92.0,"useSourceData":false,"schema":{"__root_schema__":{"children":{"profileName":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.profileName))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"profileName","identifier":"profileName","position":1.0,"originalIdentifier":"profileName","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Profile Name"},"profileStatus":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.profileStatus))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"profileStatus","identifier":"profileStatus","position":2.0,"originalIdentifier":"profileStatus","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Profile Status"},"profilePictureUrl":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.profilePictureUrl))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Text Input","sourceData":"https://pps.whatsapp.net/v/t61.24694-24/359816109_329991892684302_7466658594467953893_n.jpg?ccb=11-4&oh=01_AdTpgc4O-xiZDr2v0OLu_jssxaw8dsws819srLMOzUwEnw&oe=64D3C41E","isCustomField":false,"accessor":"profilePictureUrl","identifier":"profilePictureUrl","position":0.0,"originalIdentifier":"profilePictureUrl","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Profile Picture Url"},"privacySettings":{"children":{"readreceipts":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.privacySettings.readreceipts))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Select","sourceData":"all","isCustomField":false,"accessor":"readreceipts","identifier":"readreceipts","position":0.0,"originalIdentifier":"readreceipts","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Readreceipts","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n {\n \"label\": \"all\",\n \"value\": \"all\"\n },\n {\n \"label\": \"none\",\n \"value\": \"none\"\n }\n]"},"profile":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.privacySettings.profile))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Select","sourceData":"all","isCustomField":false,"accessor":"profile","identifier":"profile","position":1.0,"originalIdentifier":"profile","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Profile","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n {\n \"label\": \"all\",\n \"value\": \"all\"\n },\n {\n \"label\": \"contacts\",\n \"value\": \"contacts\"\n },\n {\n \"label\": \"contact_blacklist\",\n \"value\": \"contact_blacklist\"\n },\n {\n \"label\": \"none\",\n \"value\": \"none\"\n }\n]"},"status":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.privacySettings.status))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Select","sourceData":"contacts","isCustomField":false,"accessor":"status","identifier":"status","position":2.0,"originalIdentifier":"status","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Status","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n {\n \"label\": \"all\",\n \"value\": \"all\"\n },\n {\n \"label\": \"contacts\",\n \"value\": \"contacts\"\n },\n {\n \"label\": \"contact_blacklist\",\n \"value\": \"contact_blacklist\"\n },\n {\n \"label\": \"none\",\n \"value\": \"none\"\n }\n]"},"online":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.privacySettings.online))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Select","sourceData":"all","isCustomField":false,"accessor":"online","identifier":"online","position":3.0,"originalIdentifier":"online","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Online","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n {\n \"label\": \"all\",\n \"value\": \"all\"\n },\n {\n \"label\": \"match_last_seen\",\n \"value\": \"match_last_seen\"\n }\n]"},"last":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.privacySettings.last))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Select","sourceData":"contacts","isCustomField":false,"accessor":"last","identifier":"last","position":4.0,"originalIdentifier":"last","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Last","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n {\n \"label\": \"all\",\n \"value\": \"all\"\n },\n {\n \"label\": \"contacts\",\n \"value\": \"contacts\"\n },\n {\n \"label\": \"contact_blacklist\",\n \"value\": \"contact_blacklist\"\n },\n {\n \"label\": \"none\",\n \"value\": \"none\"\n }\n]"},"groupadd":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.privacySettings.groupadd))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Select","sourceData":"all","isCustomField":false,"accessor":"groupadd","identifier":"groupadd","position":5.0,"originalIdentifier":"groupadd","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Groupadd","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n {\n \"label\": \"all\",\n \"value\": \"all\"\n },\n {\n \"label\": \"contacts\",\n \"value\": \"contacts\"\n },\n {\n \"label\": \"contact_blacklist\",\n \"value\": \"contact_blacklist\"\n },\n {\n \"label\": \"none\",\n \"value\": \"none\"\n }\n]"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.privacySettings))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Object","sourceData":{"readreceipts":"all","profile":"all","status":"contacts","online":"all","last":"contacts","groupadd":"all"},"isCustomField":false,"accessor":"privacySettings","identifier":"privacySettings","position":3.0,"originalIdentifier":"privacySettings","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"1rem","label":"Privacy Settings","labelStyle":"BOLD"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Object","sourceData":{"name":"John","date_of_birth":"20/02/1990","employee_id":1001.0},"isCustomField":false,"accessor":"__root_schema__","identifier":"__root_schema__","position":-1.0,"originalIdentifier":"__root_schema__","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":""}},"mobileBottomRow":41.0,"widgetName":"FormProfile","submitButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[],"displayName":"JSON Form","bottomRow":92.0,"fieldLimitExceeded":false,"parentRowSpace":10.0,"title":"Edit Profile","hideCard":false,"mobileRightColumn":25.0,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[{"key":"onSubmit"}],"borderWidth":"0","sourceData":"{\n\t\"profilePictureUrl\": \"{{Fetch_Instance.data.instance.profilePictureUrl}}\",\n\t\"profileName\": \"{{Fetch_Instance.data.instance.profileName}}\",\n\t\"profileStatus\": \"{{Fetch_Instance.data.instance.profileStatus}}\",\n\t\"privacySettings\": {\n \"readreceipts\": {{Fetch_PrivacySettings.data.readreceipts}},\n \"profile\": {{Fetch_PrivacySettings.data.profile}},\n \"status\": {{Fetch_PrivacySettings.data.status}},\n \"online\": {{Fetch_PrivacySettings.data.online}},\n \"last\": {{Fetch_PrivacySettings.data.last}},\n \"groupadd\": {{Fetch_PrivacySettings.data.groupadd}}\n\t\t}\n}","resetButtonLabel":"","key":"72nqor459k","backgroundColor":"#fff","isDeprecated":false,"rightColumn":64.0,"widgetId":"hguxefink2","minWidth":450.0,"parentId":"basosxf5qt","renderMode":"CANVAS","mobileTopRow":0.0,"scrollContents":true,"responsiveBehavior":"fill","fixedFooter":true,"originalTopRow":0.0,"mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"minDynamicHeight":4.0}],"isDisabled":false,"key":"mepf0qsn1e","isDeprecated":false,"rightColumn":430.5,"detachFromLayout":true,"widgetId":"basosxf5qt","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"ss96aihlej","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"4ktj7iym0b","height":940.0,"isDeprecated":false,"rightColumn":35.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"ss96aihlej","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":35.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":11.0,"maxDynamicHeight":9000.0,"width":456.0,"minDynamicHeight":24.0},{"mobileBottomRow":47.0,"widgetName":"Text6","displayName":"Text","iconSVG":"/static/media/icon.a47d6d5dbbb718c4dc4b2eb4f218c1b7.svg","searchTags":["typography","paragraph","label"],"topRow":43.0,"bottomRow":47.0,"parentRowSpace":10.0,"type":"TEXT_WIDGET","hideCard":false,"mobileRightColumn":31.0,"animateLoading":true,"overflow":"NONE","fontFamily":"{{appsmith.theme.fontFamily.appFont}}","parentColumnSpace":12.3125,"dynamicTriggerPathList":[],"leftColumn":15.0,"dynamicBindingPathList":[{"key":"truncateButtonColor"},{"key":"fontFamily"},{"key":"borderRadius"}],"shouldTruncate":false,"truncateButtonColor":"{{appsmith.theme.colors.primaryColor}}","text":"This evolution api instance management panel is compatible from version 1.5 or higher\n","key":"vpoi1p6qvn","isDeprecated":false,"rightColumn":63.0,"textAlign":"LEFT","dynamicHeight":"AUTO_HEIGHT","widgetId":"yfenuu2x36","minWidth":450.0,"isVisible":true,"fontStyle":"BOLD","textColor":"#ef4444","version":1.0,"parentId":"0","tags":["Suggested","Content"],"renderMode":"CANVAS","isLoading":false,"mobileTopRow":43.0,"responsiveBehavior":"fill","originalTopRow":43.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":15.0,"maxDynamicHeight":9000.0,"originalBottomRow":48.0,"fontSize":"0.875rem","minDynamicHeight":4.0}]},"layoutOnLoadActions":[[{"id":"Home_Scripts.verifyConfig","name":"Scripts.verifyConfig","collectionId":"Home_Scripts","clientSideExecution":true,"confirmBeforeExecute":false,"pluginType":"JS","jsonPathKeys":[],"timeoutInMillisecond":10000.0}],[{"id":"Home_Find_Rabbitmq","name":"Find_Rabbitmq","confirmBeforeExecute":false,"pluginType":"API","jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"timeoutInMillisecond":10000.0},{"id":"Home_Find_Websocket","name":"Find_Websocket","confirmBeforeExecute":false,"pluginType":"API","jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"timeoutInMillisecond":10000.0}]],"layoutOnLoadActionErrors":[],"validOnPageLoadActions":true,"id":"Home","deleted":false,"policies":[],"userPermissions":[]}],"userPermissions":[],"policies":[],"isHidden":false},"publishedPage":{"name":"Home","slug":"home","customSlug":"","layouts":[{"viewMode":false,"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":4896.0,"snapColumns":64.0,"detachFromLayout":true,"widgetId":"0","topRow":0.0,"bottomRow":470.0,"containerStyle":"none","snapRows":124.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"version":83.0,"minHeight":1292.0,"dynamicTriggerPathList":[],"parentColumnSpace":1.0,"dynamicBindingPathList":[],"leftColumn":0.0,"children":[{"boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}","borderColor":"#E0DEDE","isVisibleDownload":true,"iconSVG":"https://appcdn.appsmith.com/static/media/icon.24905525921dd6f5ff46d0dd843b9e12.svg","topRow":6.0,"isSortable":true,"type":"TABLE_WIDGET_V2","inlineEditingSaveOption":"ROW_LEVEL","animateLoading":true,"dynamicBindingPathList":[{"key":"tableData"},{"key":"primaryColumns.customColumn9.boxShadow"},{"key":"primaryColumns.customColumn9.borderRadius"},{"key":"primaryColumns.customColumn9.menuColor"},{"key":"primaryColumns.customColumn8.computedValue"},{"key":"primaryColumns.customColumn7.computedValue"},{"key":"primaryColumns.customColumn6.computedValue"},{"key":"primaryColumns.customColumn5.computedValue"},{"key":"primaryColumns.customColumn2.computedValue"},{"key":"primaryColumns.customColumn1.textColor"},{"key":"primaryColumns.customColumn1.cellBackground"},{"key":"primaryColumns.customColumn1.computedValue"},{"key":"primaryColumns.instance.computedValue"},{"key":"isVisible"},{"key":"accentColor"},{"key":"borderRadius"},{"key":"boxShadow"}],"needsHeightForContent":true,"leftColumn":14.0,"delimiter":",","defaultSelectedRowIndex":0.0,"showInlineEditingOptionDropdown":true,"accentColor":"{{appsmith.theme.colors.primaryColor}}","isVisibleFilters":true,"isVisible":"{{appsmith.store.api_key && appsmith.store.api_url ? true : false}}","enableClientSideSearch":true,"version":2.0,"totalRecordsCount":0.0,"isLoading":false,"childStylesheet":{"button":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"menuButton":{"menuColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"iconButton":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"editActions":{"saveButtonColor":"{{appsmith.theme.colors.primaryColor}}","saveBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","discardButtonColor":"{{appsmith.theme.colors.primaryColor}}","discardBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"}},"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","columnUpdatedAt":1.690746223636E12,"defaultSelectedRowIndices":[0.0],"mobileBottomRow":32.0,"widgetName":"TableInstances","defaultPageSize":0.0,"columnOrder":["instance","customColumn5","customColumn1","customColumn2","customColumn6","customColumn7","customColumn8","customColumn9"],"dynamicPropertyPathList":[{"key":"primaryColumns.customColumn1.cellBackground"},{"key":"isVisible"}],"displayName":"Table","bottomRow":42.0,"columnWidthMap":{"customColumn3":92.0,"customColumn2":340.0,"customColumn5":254.0,"customColumn9":60.0},"parentRowSpace":10.0,"hideCard":false,"mobileRightColumn":36.0,"parentColumnSpace":20.078125,"dynamicTriggerPathList":[{"key":"primaryColumns.customColumn9.menuItems.menuItemjfzsd8g6yr.onClick"},{"key":"primaryColumns.customColumn9.menuItems.menuItem4sqork5nmt.onClick"},{"key":"primaryColumns.customColumn9.menuItems.menuItemig6ua4ixjx.onClick"},{"key":"primaryColumns.customColumn9.menuItems.menuItemx9oyhys8cj.onClick"},{"key":"primaryColumns.customColumn9.menuItems.menuItemxk5jvvwwef.onClick"},{"key":"primaryColumns.customColumn9.menuItems.menuItem16ysonwzrq.onClick"},{"key":"primaryColumns.customColumn9.menuItems.menuItembtatfbml4y.onClick"}],"borderWidth":"1","primaryColumns":{"instance":{"allowCellWrapping":false,"allowSameOptionsInNewRow":true,"index":0.0,"width":150.0,"originalId":"instance","id":"instance","alias":"instance","horizontalAlignment":"LEFT","verticalAlignment":"CENTER","columnType":"text","textSize":"0.875rem","enableFilter":true,"enableSort":true,"isVisible":true,"isDisabled":false,"isCellEditable":false,"isEditable":false,"isCellVisible":true,"isDerived":false,"label":"Instance","isSaveVisible":true,"isDiscardVisible":true,"computedValue":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( currentRow.instance.instanceName))}}","sticky":"","validation":{}},"customColumn1":{"allowCellWrapping":false,"allowSameOptionsInNewRow":true,"index":1.0,"width":150.0,"originalId":"customColumn1","id":"customColumn1","alias":"Status","horizontalAlignment":"CENTER","verticalAlignment":"CENTER","columnType":"text","textSize":"0.875rem","enableFilter":true,"enableSort":true,"isVisible":true,"isDisabled":false,"isCellEditable":false,"isEditable":false,"isCellVisible":true,"isDerived":true,"label":"Status","isSaveVisible":true,"isDiscardVisible":true,"computedValue":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( currentRow.instance.status))}}","sticky":"","validation":{},"buttonStyle":"rgb(3, 179, 101)","labelColor":"#FFFFFF","cellBackground":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( currentRow.instance.status === \"open\" ? \"#499B51\" : currentRow.instance.status === \"close\" ? \"#DD524C\" : \"#2770FC\"))}}","textColor":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( (appsmith.theme.colors.backgroundColor)))}}"},"customColumn2":{"allowCellWrapping":false,"allowSameOptionsInNewRow":true,"index":2.0,"width":150.0,"originalId":"customColumn2","id":"customColumn2","alias":"Apikey","horizontalAlignment":"LEFT","verticalAlignment":"CENTER","columnType":"text","textSize":"0.875rem","enableFilter":true,"enableSort":true,"isVisible":true,"isDisabled":false,"isCellEditable":false,"isEditable":false,"isCellVisible":true,"isDerived":true,"label":"Apikey","isSaveVisible":true,"isDiscardVisible":true,"computedValue":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( currentRow.instance.apikey))}}","sticky":"","validation":{},"buttonStyle":"rgb(3, 179, 101)","labelColor":"#FFFFFF"},"customColumn5":{"allowCellWrapping":false,"allowSameOptionsInNewRow":true,"index":5.0,"width":150.0,"originalId":"customColumn5","id":"customColumn5","alias":"Owner","horizontalAlignment":"LEFT","verticalAlignment":"CENTER","columnType":"text","textSize":"0.875rem","enableFilter":true,"enableSort":true,"isVisible":true,"isDisabled":false,"isCellEditable":false,"isEditable":false,"isCellVisible":true,"isDerived":true,"label":"Owner","isSaveVisible":true,"isDiscardVisible":true,"computedValue":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( currentRow.instance.owner))}}","sticky":"","validation":{},"buttonStyle":"rgb(3, 179, 101)","labelColor":"#FFFFFF"},"customColumn6":{"allowCellWrapping":false,"allowSameOptionsInNewRow":true,"index":6.0,"width":150.0,"originalId":"customColumn6","id":"customColumn6","alias":"profilePictureUrl","horizontalAlignment":"LEFT","verticalAlignment":"CENTER","columnType":"text","textSize":"0.875rem","enableFilter":true,"enableSort":true,"isVisible":true,"isDisabled":false,"isCellEditable":false,"isEditable":false,"isCellVisible":false,"isDerived":true,"label":"profilePictureUrl","isSaveVisible":true,"isDiscardVisible":true,"computedValue":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( currentRow.instance.profilePictureUrl))}}","sticky":"","validation":{},"buttonStyle":"rgb(3, 179, 101)","labelColor":"#FFFFFF"},"customColumn7":{"allowCellWrapping":false,"allowSameOptionsInNewRow":true,"index":7.0,"width":150.0,"originalId":"customColumn7","id":"customColumn7","alias":"profileName","horizontalAlignment":"LEFT","verticalAlignment":"CENTER","columnType":"text","textSize":"0.875rem","enableFilter":true,"enableSort":true,"isVisible":true,"isDisabled":false,"isCellEditable":false,"isEditable":false,"isCellVisible":false,"isDerived":true,"label":"profileName","isSaveVisible":true,"isDiscardVisible":true,"computedValue":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( currentRow.instance.profileName))}}","sticky":"","validation":{},"buttonStyle":"rgb(3, 179, 101)","labelColor":"#FFFFFF"},"customColumn8":{"allowCellWrapping":false,"allowSameOptionsInNewRow":true,"index":8.0,"width":150.0,"originalId":"customColumn8","id":"customColumn8","alias":"profileStatus","horizontalAlignment":"LEFT","verticalAlignment":"CENTER","columnType":"text","textSize":"0.875rem","enableFilter":true,"enableSort":true,"isVisible":true,"isDisabled":false,"isCellEditable":false,"isEditable":false,"isCellVisible":false,"isDerived":true,"label":"profileStatus","isSaveVisible":true,"isDiscardVisible":true,"computedValue":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( currentRow.instance.profileStatus))}}","sticky":"","validation":{},"buttonStyle":"rgb(3, 179, 101)","labelColor":"#FFFFFF"},"customColumn9":{"allowCellWrapping":false,"allowSameOptionsInNewRow":true,"index":9.0,"width":150.0,"originalId":"customColumn9","id":"customColumn9","alias":"#","horizontalAlignment":"LEFT","verticalAlignment":"CENTER","columnType":"menuButton","textSize":"0.875rem","enableFilter":true,"enableSort":true,"isVisible":true,"isDisabled":false,"isCellEditable":false,"isEditable":false,"isCellVisible":true,"isDerived":true,"label":"#","isSaveVisible":true,"isDiscardVisible":true,"computedValue":"","sticky":"","validation":{},"buttonStyle":"rgb(3, 179, 101)","labelColor":"#FFFFFF","menuColor":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( (appsmith.theme.colors.primaryColor)))}}","borderRadius":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( (appsmith.theme.borderRadius.appBorderRadius)))}}","boxShadow":"{{TableInstances.processedTableData.map((currentRow, currentIndex) => ( \"none\"))}}","customAlias":"","menuItemsSource":"STATIC","menuButtonLabel":" ","menuButtoniconName":"chevron-down","menuItems":{"menuItemjfzsd8g6yr":{"id":"menuItemjfzsd8g6yr","index":0.0,"label":"Webhook","widgetId":"vygcejtdun","isDisabled":false,"isVisible":true,"onClick":"{{Find_Webhook.run({\n //\"key\": \"value\",\n});\nshowModal('ModalWebhook');}}"},"menuItem4sqork5nmt":{"id":"menuItem4sqork5nmt","index":1.0,"label":"Settings","widgetId":"0hw8oqpwcj","isDisabled":false,"isVisible":true,"onClick":"{{Find_Settings.run();\nshowModal('ModalSettings');}}"},"menuItemx9oyhys8cj":{"id":"menuItemx9oyhys8cj","index":2.0,"label":"Websocket","widgetId":"j75a4k6ecq","isDisabled":false,"isVisible":true,"onClick":"{{Find_Websocket.run();\nshowModal('ModalWebsocket');}}"},"menuItemxk5jvvwwef":{"id":"menuItemxk5jvvwwef","index":3.0,"label":"Rabbitmq","widgetId":"3u94ov6qst","isDisabled":false,"isVisible":true,"onClick":"{{Find_Rabbitmq.run();\nshowModal('ModalRabbitmq');}}"},"menuItemig6ua4ixjx":{"id":"menuItemig6ua4ixjx","index":4.0,"label":"Chatwoot","widgetId":"fuq5dtgbqc","isDisabled":false,"isVisible":true,"onClick":"{{Find_Chatwoot.run()\nshowModal('ModalChatwoot');}}"},"menuItem16ysonwzrq":{"id":"menuItem16ysonwzrq","index":5.0,"label":"Set Typebot","widgetId":"fi9nb2bace","isDisabled":false,"isVisible":true,"onClick":"{{Find_Typebot.run()\nshowModal('ModalTypebot');}}"},"menuItembtatfbml4y":{"id":"menuItembtatfbml4y","index":6.0,"label":"TypeBot Set Session Status","widgetId":"7f6mg653ra","isDisabled":false,"isVisible":true,"onClick":"{{showModal('ModalTypebotChangeSessionStatu');}}"}}}},"key":"e3yxhhyeel","canFreezeColumn":true,"isDeprecated":false,"rightColumn":63.0,"textSize":"0.875rem","widgetId":"uupm7enu8u","minWidth":450.0,"tableData":"{{fetch_Instances.data}}","label":"Data","searchKey":"","parentId":"0","renderMode":"CANVAS","mobileTopRow":4.0,"horizontalAlignment":"LEFT","isVisibleSearch":true,"responsiveBehavior":"fill","mobileLeftColumn":2.0,"isVisiblePagination":true,"verticalAlignment":"CENTER"},{"resetFormOnClick":false,"boxShadow":"none","mobileBottomRow":5.0,"widgetName":"BtnNewInstance","onClick":"{{showModal('ModalInstance');}}","buttonColor":"rgb(3, 179, 101)","dynamicPropertyPathList":[{"key":"isVisible"}],"displayName":"Button","iconSVG":"/static/media/icon.7beb9123fb53027d9d6b778cdfe4caed.svg","searchTags":["click","submit"],"topRow":1.0,"bottomRow":5.0,"parentRowSpace":10.0,"type":"BUTTON_WIDGET","hideCard":false,"mobileRightColumn":8.0,"animateLoading":true,"parentColumnSpace":11.828125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":7.0,"dynamicBindingPathList":[{"key":"isVisible"},{"key":"borderRadius"}],"text":"New Instance","isDisabled":false,"key":"crzwqv3pdr","isDeprecated":false,"rightColumn":19.0,"isDefaultClickDisabled":true,"iconName":"add","widgetId":"84ei9q1ugm","minWidth":120.0,"isVisible":"{{appsmith.store.api_key && appsmith.store.api_url ? true : false}}","recaptchaType":"V3","version":1.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":1.0,"responsiveBehavior":"hug","disabledWhenInvalid":false,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":0.0,"buttonVariant":"PRIMARY","iconAlign":"left","placement":"CENTER"},{"boxShadow":"none","mobileBottomRow":74.0,"widgetName":"ModalQrcode","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":50.0,"bottomRow":500.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":45.0,"animateLoading":true,"parentColumnSpace":11.828125,"leftColumn":21.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas1","displayName":"Canvas","topRow":0.0,"bottomRow":450.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":240.0,"mobileRightColumn":283.875,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","mobileBottomRow":52.0,"widgetName":"ImageQrcode","displayName":"Image","iconSVG":"https://appcdn.appsmith.com/static/media/icon.30c8cbd442cce232b01ba2d434c53a53.svg","topRow":6.0,"bottomRow":43.0,"parentRowSpace":10.0,"type":"IMAGE_WIDGET","hideCard":false,"mobileRightColumn":55.0,"animateLoading":true,"parentColumnSpace":20.078125,"dynamicTriggerPathList":[],"imageShape":"RECTANGLE","leftColumn":2.0,"dynamicBindingPathList":[{"key":"borderRadius"},{"key":"image"}],"defaultImage":"https://manualnegocioonline.com.br/downloads/evolution-api-favicon2.png","key":"4chlj9l432","image":"{{Connect.data.base64}}","isDeprecated":false,"rightColumn":61.0,"objectFit":"contain","widgetId":"27dpgapd7q","isVisible":true,"version":1.0,"parentId":"we6j3r2byy","renderMode":"CANVAS","isLoading":false,"mobileTopRow":40.0,"maxZoomLevel":1.0,"enableDownload":false,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":43.0,"enableRotation":false},{"boxShadow":"none","mobileBottomRow":4.0,"widgetName":"IconButton1","onClick":"{{closeModal('ModalQrcode');\nfetch_Instances.run()}}","buttonColor":"{{appsmith.theme.colors.primaryColor}}","displayName":"Icon button","iconSVG":"/static/media/icon.80fc7466c0d7181ec0271de7fda795ec.svg","searchTags":["click","submit"],"topRow":0.0,"bottomRow":4.0,"type":"ICON_BUTTON_WIDGET","hideCard":false,"mobileRightColumn":64.0,"animateLoading":true,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":58.0,"dynamicBindingPathList":[{"key":"buttonColor"},{"key":"borderRadius"}],"iconSize":24.0,"isDisabled":false,"key":"pezy0hb491","isDeprecated":false,"rightColumn":64.0,"iconName":"cross","widgetId":"i1dw369dch","minWidth":50.0,"isVisible":true,"version":1.0,"parentId":"we6j3r2byy","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"hug","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":58.0,"buttonVariant":"TERTIARY"},{"mobileBottomRow":5.0,"widgetName":"Text1","displayName":"Text","iconSVG":"/static/media/icon.c3b6033f570046f8c6288d911333a827.svg","searchTags":["typography","paragraph","label"],"topRow":1.0,"bottomRow":5.0,"type":"TEXT_WIDGET","hideCard":false,"mobileRightColumn":41.0,"animateLoading":true,"overflow":"NONE","fontFamily":"{{appsmith.theme.fontFamily.appFont}}","dynamicTriggerPathList":[],"leftColumn":1.0,"dynamicBindingPathList":[{"key":"fontFamily"}],"shouldTruncate":false,"truncateButtonColor":"{{appsmith.theme.colors.primaryColor}}","text":"Qrcode","key":"9s8f10sepn","isDeprecated":false,"rightColumn":41.0,"textAlign":"LEFT","dynamicHeight":"AUTO_HEIGHT","widgetId":"mg2cqsi9fn","minWidth":450.0,"isVisible":true,"fontStyle":"BOLD","textColor":"#231F20","version":1.0,"parentId":"we6j3r2byy","renderMode":"CANVAS","isLoading":false,"mobileTopRow":1.0,"responsiveBehavior":"fill","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":1.0,"maxDynamicHeight":9000.0,"fontSize":"1.25rem","minDynamicHeight":4.0}],"isDisabled":false,"key":"e8r23nd8j4","isDeprecated":false,"rightColumn":283.875,"detachFromLayout":true,"widgetId":"we6j3r2byy","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"ljwryrjhy7","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"g8xx6ocuvi","height":450.0,"isDeprecated":false,"rightColumn":45.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"ljwryrjhy7","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":50.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":21.0,"maxDynamicHeight":9000.0,"width":456.0,"minDynamicHeight":24.0},{"resetFormOnClick":false,"boxShadow":"none","mobileBottomRow":5.0,"widgetName":"BtnConfig","onClick":"{{showModal('ModalConfig');}}","buttonColor":"#2563eb","dynamicPropertyPathList":[],"displayName":"Button","iconSVG":"/static/media/icon.7beb9123fb53027d9d6b778cdfe4caed.svg","searchTags":["click","submit"],"topRow":1.0,"bottomRow":5.0,"parentRowSpace":10.0,"type":"BUTTON_WIDGET","hideCard":false,"mobileRightColumn":30.0,"animateLoading":true,"parentColumnSpace":11.828125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":1.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"text":"Access","isDisabled":false,"key":"crzwqv3pdr","isDeprecated":false,"rightColumn":7.0,"isDefaultClickDisabled":true,"iconName":"user","widgetId":"uegjpy37i6","minWidth":120.0,"isVisible":true,"recaptchaType":"V3","version":1.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":1.0,"responsiveBehavior":"hug","disabledWhenInvalid":false,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":14.0,"buttonVariant":"PRIMARY","iconAlign":"left","placement":"CENTER"},{"boxShadow":"none","mobileBottomRow":73.0,"widgetName":"ModalConfig","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":49.0,"bottomRow":30.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":25.0,"minHeight":300.0,"animateLoading":true,"parentColumnSpace":11.75,"leftColumn":1.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas2","displayName":"Canvas","topRow":0.0,"bottomRow":300.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":300.0,"mobileRightColumn":282.0,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","mobileBottomRow":84.0,"borderColor":"#E0DEDE","widgetName":"FormConfig","isCanvas":true,"displayName":"Form","iconSVG":"/static/media/icon.5d6d2ac5cb1aa68bcd9b14f11c56b44a.svg","searchTags":["group"],"topRow":0.0,"bottomRow":28.0,"parentRowSpace":10.0,"type":"FORM_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":25.0,"animateLoading":true,"parentColumnSpace":11.828125,"dynamicTriggerPathList":[],"leftColumn":1.0,"dynamicBindingPathList":[],"children":[{"mobileBottomRow":400.0,"widgetName":"Canvas2Copy","displayName":"Canvas","topRow":0.0,"bottomRow":280.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":false,"hideCard":true,"minHeight":400.0,"mobileRightColumn":283.875,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"mobileBottomRow":5.0,"widgetName":"Text2","displayName":"Text","iconSVG":"/static/media/icon.c3b6033f570046f8c6288d911333a827.svg","searchTags":["typography","paragraph","label"],"topRow":1.0,"bottomRow":5.0,"type":"TEXT_WIDGET","hideCard":false,"mobileRightColumn":25.5,"animateLoading":true,"overflow":"NONE","fontFamily":"{{appsmith.theme.fontFamily.appFont}}","dynamicTriggerPathList":[],"leftColumn":1.5,"dynamicBindingPathList":[{"key":"fontFamily"}],"shouldTruncate":false,"truncateButtonColor":"{{appsmith.theme.colors.primaryColor}}","text":"Access Credentials","key":"9s8f10sepn","isDeprecated":false,"rightColumn":25.5,"textAlign":"LEFT","dynamicHeight":"AUTO_HEIGHT","widgetId":"tps5rw2lk9","minWidth":450.0,"isVisible":true,"fontStyle":"BOLD","textColor":"#231F20","version":1.0,"parentId":"lrtvcpswru","renderMode":"CANVAS","isLoading":false,"mobileTopRow":1.0,"responsiveBehavior":"fill","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":1.5,"maxDynamicHeight":9000.0,"fontSize":"1.25rem","minDynamicHeight":4.0},{"resetFormOnClick":true,"boxShadow":"none","mobileBottomRow":37.0,"widgetName":"Button1","onClick":"{{storeValue('api_url', FormConfig.data.InputApiUrl);\nstoreValue('api_key', FormConfig.data.InputGlobalApiKey);\nfetch_Instances.run().then(() => {\n showAlert('successful login', 'success');\n}).catch(() => {\n showAlert('Could not load instances', 'error');\n});\ncloseModal('ModalConfig').then(() => {});}}","buttonColor":"{{appsmith.theme.colors.primaryColor}}","dynamicPropertyPathList":[{"key":"isDisabled"}],"displayName":"Button","iconSVG":"/static/media/icon.7beb9123fb53027d9d6b778cdfe4caed.svg","searchTags":["click","submit"],"topRow":22.0,"bottomRow":26.0,"type":"BUTTON_WIDGET","hideCard":false,"mobileRightColumn":62.0,"animateLoading":true,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":51.0,"dynamicBindingPathList":[{"key":"buttonColor"},{"key":"borderRadius"}],"text":"Login","isDisabled":"","key":"crzwqv3pdr","isDeprecated":false,"rightColumn":63.0,"isDefaultClickDisabled":true,"iconName":"log-in","widgetId":"gzxvnsxk0y","minWidth":120.0,"isVisible":true,"recaptchaType":"V3","version":1.0,"parentId":"lrtvcpswru","renderMode":"CANVAS","isLoading":false,"mobileTopRow":33.0,"responsiveBehavior":"hug","disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":46.0,"buttonVariant":"PRIMARY","iconAlign":"left","placement":"CENTER"},{"resetFormOnClick":true,"boxShadow":"none","mobileBottomRow":37.0,"widgetName":"Button1Copy","onClick":"{{removeValue('api_url');\nremoveValue('api_key').then(() => {\n showAlert('successful logout', 'success');\n});}}","buttonColor":"#dc2626","dynamicPropertyPathList":[{"key":"isDisabled"}],"displayName":"Button","iconSVG":"/static/media/icon.7beb9123fb53027d9d6b778cdfe4caed.svg","searchTags":["click","submit"],"topRow":21.0,"bottomRow":25.0,"type":"BUTTON_WIDGET","hideCard":false,"mobileRightColumn":62.0,"animateLoading":true,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":2.0,"dynamicBindingPathList":[{"key":"isDisabled"},{"key":"borderRadius"}],"text":"Logout","isDisabled":"{{!appsmith.store.api_key && !appsmith.store.api_url ? true : false}}","key":"crzwqv3pdr","isDeprecated":false,"rightColumn":14.0,"isDefaultClickDisabled":true,"iconName":"log-out","widgetId":"f2i8tsbgx1","minWidth":120.0,"isVisible":true,"recaptchaType":"V3","version":1.0,"parentId":"lrtvcpswru","renderMode":"CANVAS","isLoading":false,"mobileTopRow":33.0,"responsiveBehavior":"hug","disabledWhenInvalid":false,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":46.0,"buttonVariant":"PRIMARY","iconAlign":"left","placement":"CENTER"},{"boxShadow":"none","iconSVG":"/static/media/icon.d0ce957b6c4640f8a7418ce846ee200e.svg","topRow":6.0,"labelWidth":5.0,"type":"INPUT_WIDGET_V2","animateLoading":true,"resetOnSubmit":true,"leftColumn":2.0,"dynamicBindingPathList":[{"key":"defaultText"},{"key":"accentColor"},{"key":"borderRadius"}],"labelStyle":"","inputType":"TEXT","placeholderText":"","isDisabled":false,"isRequired":true,"dynamicHeight":"FIXED","accentColor":"{{appsmith.theme.colors.primaryColor}}","showStepArrows":false,"isVisible":true,"version":2.0,"isLoading":false,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileBottomRow":13.0,"widgetName":"InputApiUrl","displayName":"Input","searchTags":["form","text input","number","textarea"],"bottomRow":13.0,"parentRowSpace":10.0,"autoFocus":false,"hideCard":false,"mobileRightColumn":22.0,"parentColumnSpace":5.047119140625,"dynamicTriggerPathList":[],"labelPosition":"Top","key":"r1hfat3ouf","labelTextSize":"0.875rem","isDeprecated":false,"rightColumn":63.0,"widgetId":"spgryrb5ao","minWidth":450.0,"label":"API URL","parentId":"lrtvcpswru","labelAlignment":"left","renderMode":"CANVAS","mobileTopRow":6.0,"responsiveBehavior":"fill","mobileLeftColumn":2.0,"maxDynamicHeight":9000.0,"isSpellCheck":false,"iconAlign":"left","defaultText":"{{appsmith.store.api_url || ''}}","minDynamicHeight":4.0},{"boxShadow":"none","iconSVG":"/static/media/icon.d0ce957b6c4640f8a7418ce846ee200e.svg","topRow":14.0,"labelWidth":5.0,"type":"INPUT_WIDGET_V2","animateLoading":true,"resetOnSubmit":true,"leftColumn":2.0,"dynamicBindingPathList":[{"key":"defaultText"},{"key":"accentColor"},{"key":"borderRadius"}],"labelStyle":"","inputType":"PASSWORD","isDisabled":false,"isRequired":true,"dynamicHeight":"FIXED","accentColor":"{{appsmith.theme.colors.primaryColor}}","showStepArrows":false,"isVisible":true,"version":2.0,"isLoading":false,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileBottomRow":13.0,"widgetName":"InputGlobalApiKey","displayName":"Input","searchTags":["form","text input","number","textarea"],"bottomRow":21.0,"parentRowSpace":10.0,"autoFocus":false,"hideCard":false,"mobileRightColumn":22.0,"parentColumnSpace":5.047119140625,"dynamicTriggerPathList":[],"labelPosition":"Top","key":"r1hfat3ouf","labelTextSize":"0.875rem","isDeprecated":false,"rightColumn":63.0,"widgetId":"v2vedr13py","minWidth":450.0,"label":"GLOBAL API KEY","parentId":"lrtvcpswru","labelAlignment":"left","renderMode":"CANVAS","mobileTopRow":6.0,"responsiveBehavior":"fill","mobileLeftColumn":2.0,"maxDynamicHeight":9000.0,"shouldAllowAutofill":true,"iconAlign":"left","defaultText":"{{appsmith.store.api_key || ''}}","minDynamicHeight":4.0},{"boxShadow":"none","mobileBottomRow":4.0,"widgetName":"IconButton2","onClick":"{{closeModal('ModalConfig');}}","buttonColor":"{{appsmith.theme.colors.primaryColor}}","displayName":"Icon button","iconSVG":"/static/media/icon.80fc7466c0d7181ec0271de7fda795ec.svg","searchTags":["click","submit"],"topRow":0.0,"bottomRow":4.0,"parentRowSpace":10.0,"type":"ICON_BUTTON_WIDGET","hideCard":false,"mobileRightColumn":64.0,"animateLoading":true,"parentColumnSpace":9.072265625,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":60.0,"dynamicBindingPathList":[{"key":"buttonColor"},{"key":"borderRadius"}],"isDisabled":false,"key":"pezy0hb491","isDeprecated":false,"rightColumn":64.0,"iconName":"cross","widgetId":"oaouelmhi1","minWidth":50.0,"isVisible":true,"version":1.0,"parentId":"lrtvcpswru","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"hug","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":60.0,"buttonVariant":"TERTIARY"}],"key":"e8r23nd8j4","isDeprecated":false,"rightColumn":283.875,"detachFromLayout":true,"widgetId":"lrtvcpswru","containerStyle":"none","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"h97rbttd5c","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"borderWidth":"0","positioning":"fixed","key":"dtzd07zsya","backgroundColor":"#FFFFFF","isDeprecated":false,"rightColumn":63.0,"dynamicHeight":"AUTO_HEIGHT","widgetId":"h97rbttd5c","minWidth":450.0,"isVisible":true,"parentId":"es5gsctogb","renderMode":"CANVAS","isLoading":false,"mobileTopRow":44.0,"responsiveBehavior":"fill","originalTopRow":0.0,"borderRadius":"0.375rem","mobileLeftColumn":1.0,"maxDynamicHeight":9000.0,"originalBottomRow":28.0,"minDynamicHeight":10.0}],"isDisabled":false,"key":"e8r23nd8j4","isDeprecated":false,"rightColumn":282.0,"detachFromLayout":true,"widgetId":"es5gsctogb","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"gneh33z88k","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"g8xx6ocuvi","height":300.0,"isDeprecated":false,"rightColumn":25.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"gneh33z88k","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":49.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":1.0,"maxDynamicHeight":9000.0,"width":632.0,"minDynamicHeight":24.0},{"boxShadow":"none","mobileBottomRow":66.0,"widgetName":"ModalInstance","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":42.0,"bottomRow":1892.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":37.0,"minHeight":1850.0,"animateLoading":true,"parentColumnSpace":11.828125,"leftColumn":13.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas3","displayName":"Canvas","topRow":0.0,"bottomRow":1850.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":1140.0,"mobileRightColumn":283.875,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","mobileBottomRow":4.0,"widgetName":"IconButton3Copy","onClick":"{{closeModal('ModalInstance');}}","buttonColor":"{{appsmith.theme.colors.primaryColor}}","displayName":"Icon button","iconSVG":"/static/media/icon.80fc7466c0d7181ec0271de7fda795ec.svg","searchTags":["click","submit"],"topRow":0.0,"bottomRow":4.0,"type":"ICON_BUTTON_WIDGET","hideCard":false,"mobileRightColumn":64.0,"animateLoading":true,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":57.0,"dynamicBindingPathList":[{"key":"buttonColor"},{"key":"borderRadius"}],"iconSize":24.0,"isDisabled":false,"key":"mr6bto7c8j","isDeprecated":false,"rightColumn":63.0,"iconName":"cross","widgetId":"xofakp4har","minWidth":50.0,"isVisible":true,"version":1.0,"parentId":"esgwuzqcwt","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"hug","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":58.0,"buttonVariant":"TERTIARY"},{"boxShadow":"none","borderColor":"#E0DEDE","iconSVG":"/static/media/icon.efac588608711d232f1c6c8a2144d2dd.svg","onSubmit":"{{Create_Instance.run().then(() => {\n showAlert('Instance created successfully', 'success');\n}).catch(() => {\n showAlert('Error creating instance', 'error');\n});\nfetch_Instances.run();\ncloseModal('ModalInstance');}}","topRow":4.0,"type":"JSON_FORM_WIDGET","animateLoading":true,"leftColumn":0.0,"dynamicBindingPathList":[{"key":"borderRadius"},{"key":"resetButtonStyles.buttonColor"},{"key":"schema.__root_schema__.defaultValue"},{"key":"schema.__root_schema__.borderRadius"},{"key":"schema.__root_schema__.children.webhook.defaultValue"},{"key":"schema.__root_schema__.children.webhook.borderRadius"},{"key":"schema.__root_schema__.cellBorderRadius"},{"key":"schema.__root_schema__.children.instance.defaultValue"},{"key":"schema.__root_schema__.children.instance.borderRadius"},{"key":"schema.__root_schema__.children.instance.cellBorderRadius"},{"key":"schema.__root_schema__.children.instance.children.instanceName.defaultValue"},{"key":"schema.__root_schema__.children.instance.children.instanceName.accentColor"},{"key":"schema.__root_schema__.children.instance.children.instanceName.borderRadius"},{"key":"schema.__root_schema__.children.instance.children.token.defaultValue"},{"key":"schema.__root_schema__.children.instance.children.token.accentColor"},{"key":"schema.__root_schema__.children.instance.children.token.borderRadius"},{"key":"schema.__root_schema__.children.webhook.cellBorderRadius"},{"key":"schema.__root_schema__.children.webhook.children.webhook.defaultValue"},{"key":"schema.__root_schema__.children.webhook.children.webhook.accentColor"},{"key":"schema.__root_schema__.children.webhook.children.webhook.borderRadius"},{"key":"schema.__root_schema__.children.webhook.children.events.defaultValue"},{"key":"schema.__root_schema__.children.webhook.children.events.accentColor"},{"key":"schema.__root_schema__.children.webhook.children.events.borderRadius"},{"key":"schema.__root_schema__.children.webhook.children.webhook_by_events.defaultValue"},{"key":"schema.__root_schema__.children.webhook.children.webhook_by_events.accentColor"},{"key":"schema.__root_schema__.children.settings.defaultValue"},{"key":"schema.__root_schema__.children.settings.borderRadius"},{"key":"schema.__root_schema__.children.settings.cellBorderRadius"},{"key":"schema.__root_schema__.children.settings.children.reject_call.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.reject_call.accentColor"},{"key":"schema.__root_schema__.children.settings.children.msg_call.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.msg_call.accentColor"},{"key":"schema.__root_schema__.children.settings.children.msg_call.borderRadius"},{"key":"schema.__root_schema__.children.settings.children.groups_ignore.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.groups_ignore.accentColor"},{"key":"schema.__root_schema__.children.settings.children.always_online.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.always_online.accentColor"},{"key":"schema.__root_schema__.children.settings.children.read_messages.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.read_messages.accentColor"},{"key":"schema.__root_schema__.children.settings.children.read_status.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.read_status.accentColor"},{"key":"schema.__root_schema__.children.chatwoot.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.borderRadius"},{"key":"schema.__root_schema__.children.chatwoot.cellBorderRadius"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_account_id.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_account_id.accentColor"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_account_id.borderRadius"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_token.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_token.accentColor"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_token.borderRadius"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_url.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_url.accentColor"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_url.borderRadius"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_sign_msg.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_sign_msg.accentColor"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_reopen_conversation.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_reopen_conversation.accentColor"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_conversation_pending.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_conversation_pending.accentColor"},{"key":"schema.__root_schema__.children.instance.children.qrcode.defaultValue"},{"key":"schema.__root_schema__.children.instance.children.qrcode.accentColor"},{"key":"schema.__root_schema__.children.websocket.defaultValue"},{"key":"schema.__root_schema__.children.websocket.borderRadius"},{"key":"schema.__root_schema__.children.websocket.cellBorderRadius"},{"key":"schema.__root_schema__.children.websocket.children.websocket_enabled.defaultValue"},{"key":"schema.__root_schema__.children.websocket.children.websocket_enabled.accentColor"},{"key":"schema.__root_schema__.children.websocket.children.websocket_events.defaultValue"},{"key":"schema.__root_schema__.children.websocket.children.websocket_events.accentColor"},{"key":"schema.__root_schema__.children.websocket.children.websocket_events.borderRadius"},{"key":"schema.__root_schema__.children.rabbitmq.defaultValue"},{"key":"schema.__root_schema__.children.rabbitmq.borderRadius"},{"key":"schema.__root_schema__.children.rabbitmq.cellBorderRadius"},{"key":"schema.__root_schema__.children.rabbitmq.children.rabbitmq_enabled.defaultValue"},{"key":"schema.__root_schema__.children.rabbitmq.children.rabbitmq_enabled.accentColor"},{"key":"schema.__root_schema__.children.rabbitmq.children.rabbitmq_events.defaultValue"},{"key":"schema.__root_schema__.children.rabbitmq.children.rabbitmq_events.accentColor"},{"key":"schema.__root_schema__.children.rabbitmq.children.rabbitmq_events.borderRadius"}],"showReset":true,"dynamicHeight":"AUTO_HEIGHT","autoGenerateForm":true,"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"SECONDARY","iconAlign":"left"},"isVisible":true,"version":1.0,"isLoading":false,"submitButtonLabel":"Create","childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}},"disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","originalBottomRow":183.0,"useSourceData":false,"schema":{"__root_schema__":{"children":{"webhook":{"children":{"webhook":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.webhook.webhook))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"webhook","identifier":"webhook","position":0.0,"originalIdentifier":"webhook","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Webhook"},"events":{"children":{},"dataType":"array","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.webhook.events))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Multiselect","sourceData":["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","CALL","NEW_JWT_TOKEN"],"isCustomField":false,"accessor":"events","identifier":"events","position":2.0,"originalIdentifier":"events","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Events","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n {\n \"label\": \"APPLICATION_STARTUP\",\n \"value\": \"APPLICATION_STARTUP\"\n },\n {\n \"label\": \"QRCODE_UPDATED\",\n \"value\": \"QRCODE_UPDATED\"\n },\n {\n \"label\": \"MESSAGES_SET\",\n \"value\": \"MESSAGES_SET\"\n },\n {\n \"label\": \"MESSAGES_UPSERT\",\n \"value\": \"MESSAGES_UPSERT\"\n },\n {\n \"label\": \"MESSAGES_UPDATE\",\n \"value\": \"MESSAGES_UPDATE\"\n },\n {\n \"label\": \"MESSAGES_DELETE\",\n \"value\": \"MESSAGES_DELETE\"\n },\n {\n \"label\": \"SEND_MESSAGE\",\n \"value\": \"SEND_MESSAGE\"\n },\n {\n \"label\": \"CONTACTS_SET\",\n \"value\": \"CONTACTS_SET\"\n },\n {\n \"label\": \"CONTACTS_UPSERT\",\n \"value\": \"CONTACTS_UPSERT\"\n },\n {\n \"label\": \"CONTACTS_UPDATE\",\n \"value\": \"CONTACTS_UPDATE\"\n },\n {\n \"label\": \"PRESENCE_UPDATE\",\n \"value\": \"PRESENCE_UPDATE\"\n },\n {\n \"label\": \"CHATS_SET\",\n \"value\": \"CHATS_SET\"\n },\n {\n \"label\": \"CHATS_UPSERT\",\n \"value\": \"CHATS_UPSERT\"\n },\n {\n \"label\": \"CHATS_UPDATE\",\n \"value\": \"CHATS_UPDATE\"\n },\n {\n \"label\": \"CHATS_DELETE\",\n \"value\": \"CHATS_DELETE\"\n },\n {\n \"label\": \"GROUPS_UPSERT\",\n \"value\": \"GROUPS_UPSERT\"\n },\n {\n \"label\": \"GROUP_UPDATE\",\n \"value\": \"GROUP_UPDATE\"\n },\n {\n \"label\": \"GROUP_PARTICIPANTS_UPDATE\",\n \"value\": \"GROUP_PARTICIPANTS_UPDATE\"\n },\n {\n \"label\": \"CONNECTION_UPDATE\",\n \"value\": \"CONNECTION_UPDATE\"\n },\n {\n \"label\": \"CALL\",\n \"value\": \"CALL\"\n },\n {\n \"label\": \"NEW_JWT_TOKEN\",\n \"value\": \"NEW_JWT_TOKEN\"\n }\n]"},"webhook_by_events":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.webhook.webhook_by_events))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"webhook_by_events","identifier":"webhook_by_events","position":2.0,"originalIdentifier":"webhook_by_events","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Webhook By Events"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.webhook))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Object","sourceData":{},"isCustomField":false,"accessor":"webhook","identifier":"webhook","position":1.0,"originalIdentifier":"webhook","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"1rem","label":"Webhook","labelStyle":"BOLD"},"instance":{"children":{"instanceName":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.instance.instanceName))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"instanceName","identifier":"instanceName","position":0.0,"originalIdentifier":"instanceName","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Instance Name"},"token":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.instance.token))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"token","identifier":"token","position":1.0,"originalIdentifier":"token","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Token"},"qrcode":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.instance.qrcode))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"qrcode","identifier":"qrcode","position":2.0,"originalIdentifier":"qrcode","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Qrcode"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.instance))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Object","sourceData":{},"isCustomField":false,"accessor":"instance","identifier":"instance","position":0.0,"originalIdentifier":"instance","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"1rem","label":"Instance","labelStyle":"BOLD"},"settings":{"children":{"reject_call":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.settings.reject_call))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"reject_call","identifier":"reject_call","position":0.0,"originalIdentifier":"reject_call","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Reject Call"},"msg_call":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.settings.msg_call))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"msg_call","identifier":"msg_call","position":1.0,"originalIdentifier":"msg_call","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Msg Call"},"groups_ignore":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.settings.groups_ignore))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"groups_ignore","identifier":"groups_ignore","position":2.0,"originalIdentifier":"groups_ignore","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Groups Ignore"},"always_online":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.settings.always_online))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"always_online","identifier":"always_online","position":3.0,"originalIdentifier":"always_online","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Always Online"},"read_messages":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.settings.read_messages))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"read_messages","identifier":"read_messages","position":4.0,"originalIdentifier":"read_messages","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Read Messages"},"read_status":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.settings.read_status))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"read_status","identifier":"read_status","position":5.0,"originalIdentifier":"read_status","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Read Status"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.settings))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Object","sourceData":{},"isCustomField":false,"accessor":"settings","identifier":"settings","position":2.0,"originalIdentifier":"settings","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"1rem","label":"Settings","labelStyle":"BOLD"},"chatwoot":{"children":{"chatwoot_account_id":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.chatwoot.chatwoot_account_id))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"chatwoot_account_id","identifier":"chatwoot_account_id","position":0.0,"originalIdentifier":"chatwoot_account_id","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Chatwoot Account Id"},"chatwoot_token":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.chatwoot.chatwoot_token))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Password Input","sourceData":"","isCustomField":false,"accessor":"chatwoot_token","identifier":"chatwoot_token","position":1.0,"originalIdentifier":"chatwoot_token","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Chatwoot Token","shouldAllowAutofill":true},"chatwoot_url":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.chatwoot.chatwoot_url))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"chatwoot_url","identifier":"chatwoot_url","position":2.0,"originalIdentifier":"chatwoot_url","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Chatwoot Url"},"chatwoot_sign_msg":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.chatwoot.chatwoot_sign_msg))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"chatwoot_sign_msg","identifier":"chatwoot_sign_msg","position":3.0,"originalIdentifier":"chatwoot_sign_msg","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Chatwoot Sign Msg"},"chatwoot_reopen_conversation":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.chatwoot.chatwoot_reopen_conversation))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"chatwoot_reopen_conversation","identifier":"chatwoot_reopen_conversation","position":4.0,"originalIdentifier":"chatwoot_reopen_conversation","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Chatwoot Reopen Conversation"},"chatwoot_conversation_pending":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.chatwoot.chatwoot_conversation_pending))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"chatwoot_conversation_pending","identifier":"chatwoot_conversation_pending","position":5.0,"originalIdentifier":"chatwoot_conversation_pending","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Chatwoot Conversation Pending"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.chatwoot))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Object","sourceData":{},"isCustomField":false,"accessor":"chatwoot","identifier":"chatwoot","position":5.0,"originalIdentifier":"chatwoot","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"1rem","label":"Chatwoot","labelStyle":"BOLD"},"websocket":{"children":{"websocket_enabled":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.websocket.websocket_enabled))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"websocket_enabled","identifier":"websocket_enabled","position":0.0,"originalIdentifier":"websocket_enabled","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Websocket Enabled"},"websocket_events":{"children":{},"dataType":"array","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.websocket.websocket_events))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Multiselect","sourceData":["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","CALL","NEW_JWT_TOKEN"],"isCustomField":false,"accessor":"websocket_events","identifier":"websocket_events","position":1.0,"originalIdentifier":"websocket_events","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Websocket Events","labelTextSize":"0.875rem","serverSideFiltering":false,"options":[{"label":"Blue","value":"BLUE"},{"label":"Green","value":"GREEN"},{"label":"Red","value":"RED"}]}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.websocket))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Object","sourceData":{},"isCustomField":false,"accessor":"websocket","identifier":"websocket","position":3.0,"originalIdentifier":"websocket","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"1rem","label":"Websocket","labelStyle":"BOLD"},"rabbitmq":{"children":{"rabbitmq_enabled":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.rabbitmq.rabbitmq_enabled))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"rabbitmq_enabled","identifier":"rabbitmq_enabled","position":1.0,"originalIdentifier":"rabbitmq_enabled","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Rabbitmq Enabled"},"rabbitmq_events":{"children":{},"dataType":"array","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.rabbitmq.rabbitmq_events))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Multiselect","sourceData":["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","CALL","NEW_JWT_TOKEN"],"isCustomField":false,"accessor":"rabbitmq_events","identifier":"rabbitmq_events","position":1.0,"originalIdentifier":"rabbitmq_events","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Rabbitmq Events","labelTextSize":"0.875rem","serverSideFiltering":false,"options":[{"label":"Blue","value":"BLUE"},{"label":"Green","value":"GREEN"},{"label":"Red","value":"RED"}]}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.rabbitmq))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Object","sourceData":{"websocket_enabled":false,"websocket_events":["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","CALL","NEW_JWT_TOKEN"]},"isCustomField":false,"accessor":"rabbitmq","identifier":"rabbitmq","position":4.0,"originalIdentifier":"rabbitmq","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"1rem","label":"Rabbitmq","labelStyle":"BOLD"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","fieldType":"Object","sourceData":{"instanceName":"","token":"","webhook":"","webhook_by_events":false,"events":["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","CALL","NEW_JWT_TOKEN"],"reject_call":false,"msg_call":"","groups_ignore":false,"always_online":false,"read_messages":false,"read_status":false,"chatwoot_account_id":"","chatwoot_token":"","chatwoot_url":"","chatwoot_sign_msg":false,"chatwoot_reopen_conversation":false,"chatwoot_conversation_pending":false},"isCustomField":false,"accessor":"__root_schema__","identifier":"__root_schema__","position":-1.0,"originalIdentifier":"__root_schema__","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormInstance.sourceData, FormInstance.formData, FormInstance.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":""}},"mobileBottomRow":85.0,"widgetName":"FormInstance","submitButtonStyles":{"buttonColor":"rgb(3, 179, 101)","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.webhook.children.webhook_by_events.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.reject_call.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.groups_ignore.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.always_online.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.read_messages.defaultValue"},{"key":"schema.__root_schema__.children.settings.children.read_status.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_sign_msg.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_reopen_conversation.defaultValue"},{"key":"schema.__root_schema__.children.chatwoot.children.chatwoot_conversation_pending.defaultValue"},{"key":"schema.__root_schema__.children.instance.children.qrcode.defaultValue"},{"key":"schema.__root_schema__.children.websocket.children.websocket_enabled.defaultValue"},{"key":"schema.__root_schema__.children.rabbitmq.children.rabbitmq_enabled.defaultValue"}],"displayName":"JSON Form","bottomRow":183.0,"fieldLimitExceeded":false,"parentRowSpace":10.0,"title":"New Instance","hideCard":false,"mobileRightColumn":22.0,"shouldScrollContents":true,"parentColumnSpace":17.9375,"dynamicTriggerPathList":[{"key":"onSubmit"}],"borderWidth":"0","sourceData":"{\n \"instance\": {\n\t\t\t\"instanceName\": \"\",\n \t\"token\": \"\",\n\t\t\t\"qrcode\": true\n\t\t},\n\t\t\"webhook\": {\n\t\t\t\"webhook\": \"\",\n\t\t\t\"events\": [\n\t\t\t\t\"APPLICATION_STARTUP\",\n\t\t\t\t\t\"QRCODE_UPDATED\",\n\t\t\t\t\t\"MESSAGES_SET\",\n\t\t\t\t\t\"MESSAGES_UPSERT\",\n\t\t\t\t\t\"MESSAGES_UPDATE\",\n\t\t\t\t\t\"MESSAGES_DELETE\",\n\t\t\t\t\t\"SEND_MESSAGE\",\n\t\t\t\t\t\"CONTACTS_SET\",\n\t\t\t\t\t\"CONTACTS_UPSERT\",\n\t\t\t\t\t\"CONTACTS_UPDATE\",\n\t\t\t\t\t\"PRESENCE_UPDATE\",\n\t\t\t\t\t\"CHATS_SET\",\n\t\t\t\t\t\"CHATS_UPSERT\",\n\t\t\t\t\t\"CHATS_UPDATE\",\n\t\t\t\t\t\"CHATS_DELETE\",\n\t\t\t\t\t\"GROUPS_UPSERT\",\n\t\t\t\t\t\"GROUP_UPDATE\",\n\t\t\t\t\t\"GROUP_PARTICIPANTS_UPDATE\",\n\t\t\t\t\t\"CONNECTION_UPDATE\",\n\t\t\t\t\t\"CALL\",\n\t\t\t\t\t\"NEW_JWT_TOKEN\"\n\t\t\t],\n\t\t\t\"webhook_by_events\": false\n\t\t},\n \"settings\": {\n\t\t\t\"reject_call\": false,\n\t\t\t\"msg_call\": \"\",\n\t\t\t\"groups_ignore\": false,\n\t\t\t\"always_online\": false,\n\t\t\t\"read_messages\": false,\n\t\t\t\"read_status\": false\n\t\t},\n\t\t\"websocket\": {\n\t\t\t\"websocket_enabled\": false,\n\t\t\t\"websocket_events\": [\n\t\t\t\t\"APPLICATION_STARTUP\",\n\t\t\t\t\t\"QRCODE_UPDATED\",\n\t\t\t\t\t\"MESSAGES_SET\",\n\t\t\t\t\t\"MESSAGES_UPSERT\",\n\t\t\t\t\t\"MESSAGES_UPDATE\",\n\t\t\t\t\t\"MESSAGES_DELETE\",\n\t\t\t\t\t\"SEND_MESSAGE\",\n\t\t\t\t\t\"CONTACTS_SET\",\n\t\t\t\t\t\"CONTACTS_UPSERT\",\n\t\t\t\t\t\"CONTACTS_UPDATE\",\n\t\t\t\t\t\"PRESENCE_UPDATE\",\n\t\t\t\t\t\"CHATS_SET\",\n\t\t\t\t\t\"CHATS_UPSERT\",\n\t\t\t\t\t\"CHATS_UPDATE\",\n\t\t\t\t\t\"CHATS_DELETE\",\n\t\t\t\t\t\"GROUPS_UPSERT\",\n\t\t\t\t\t\"GROUP_UPDATE\",\n\t\t\t\t\t\"GROUP_PARTICIPANTS_UPDATE\",\n\t\t\t\t\t\"CONNECTION_UPDATE\",\n\t\t\t\t\t\"CALL\",\n\t\t\t\t\t\"NEW_JWT_TOKEN\"\n\t\t\t]\n\t\t},\n\t\t\"rabbitmq\": {\n\t\t\t\"rabbitmq_enabled\": false,\n\t\t\t\"rabbitmq_events\": [\n\t\t\t\t\"APPLICATION_STARTUP\",\n\t\t\t\t\t\"QRCODE_UPDATED\",\n\t\t\t\t\t\"MESSAGES_SET\",\n\t\t\t\t\t\"MESSAGES_UPSERT\",\n\t\t\t\t\t\"MESSAGES_UPDATE\",\n\t\t\t\t\t\"MESSAGES_DELETE\",\n\t\t\t\t\t\"SEND_MESSAGE\",\n\t\t\t\t\t\"CONTACTS_SET\",\n\t\t\t\t\t\"CONTACTS_UPSERT\",\n\t\t\t\t\t\"CONTACTS_UPDATE\",\n\t\t\t\t\t\"PRESENCE_UPDATE\",\n\t\t\t\t\t\"CHATS_SET\",\n\t\t\t\t\t\"CHATS_UPSERT\",\n\t\t\t\t\t\"CHATS_UPDATE\",\n\t\t\t\t\t\"CHATS_DELETE\",\n\t\t\t\t\t\"GROUPS_UPSERT\",\n\t\t\t\t\t\"GROUP_UPDATE\",\n\t\t\t\t\t\"GROUP_PARTICIPANTS_UPDATE\",\n\t\t\t\t\t\"CONNECTION_UPDATE\",\n\t\t\t\t\t\"CALL\",\n\t\t\t\t\t\"NEW_JWT_TOKEN\"\n\t\t\t]\n\t\t},\n \"chatwoot\": {\n\t\t\t\"chatwoot_account_id\": \"\",\n\t\t\t\"chatwoot_token\": \"\",\n\t\t\t\"chatwoot_url\": \"\",\n\t\t\t\"chatwoot_sign_msg\": false,\n\t\t\t\"chatwoot_reopen_conversation\": false,\n\t\t\t\"chatwoot_conversation_pending\": false\n\t\t}\n}","resetButtonLabel":"Reset","key":"lgqqk5r1jk","backgroundColor":"#fff","isDeprecated":false,"rightColumn":63.0,"widgetId":"o0v8ypwnya","minWidth":450.0,"parentId":"esgwuzqcwt","renderMode":"CANVAS","mobileTopRow":44.0,"scrollContents":true,"responsiveBehavior":"fill","fixedFooter":true,"originalTopRow":4.0,"mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"minDynamicHeight":4.0}],"isDisabled":false,"key":"w17ra2a85u","isDeprecated":false,"rightColumn":283.875,"detachFromLayout":true,"widgetId":"esgwuzqcwt","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"rnttu90jzr","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"bkvkzj4d20","height":1850.0,"isDeprecated":false,"rightColumn":37.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"rnttu90jzr","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":42.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":13.0,"maxDynamicHeight":9000.0,"width":628.0,"minDynamicHeight":24.0},{"resetFormOnClick":false,"boxShadow":"none","mobileBottomRow":5.0,"widgetName":"ButtonRefreshData","onClick":"{{fetch_Instances.run()}}","buttonColor":"#60a5fa","dynamicPropertyPathList":[{"key":"isVisible"}],"displayName":"Button","iconSVG":"/static/media/icon.7beb9123fb53027d9d6b778cdfe4caed.svg","searchTags":["click","submit"],"topRow":1.0,"bottomRow":5.0,"parentRowSpace":10.0,"type":"BUTTON_WIDGET","hideCard":false,"mobileRightColumn":35.0,"animateLoading":true,"parentColumnSpace":11.828125,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":19.0,"dynamicBindingPathList":[{"key":"isVisible"},{"key":"borderRadius"}],"text":"","isDisabled":false,"key":"k10nyfsas3","isDeprecated":false,"rightColumn":24.0,"isDefaultClickDisabled":true,"iconName":"refresh","widgetId":"dn1ehe3gvu","minWidth":120.0,"isVisible":"{{appsmith.store.api_key && appsmith.store.api_url ? true : false}}","recaptchaType":"V3","version":1.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":1.0,"responsiveBehavior":"hug","disabledWhenInvalid":false,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":19.0,"buttonVariant":"PRIMARY","iconAlign":"left","placement":"CENTER"},{"boxShadow":"none","mobileBottomRow":5.0,"widgetName":"ButtonGroup1","isCanvas":false,"dynamicPropertyPathList":[{"key":"isVisible"}],"displayName":"Button Group","iconSVG":"/static/media/icon.7c22979bacc83c8d84aedf56ea6c2022.svg","searchTags":["click","submit"],"topRow":1.0,"bottomRow":5.0,"parentRowSpace":10.0,"groupButtons":{"groupButton1":{"label":"Connect","iconName":"camera","id":"groupButton1","widgetId":"","buttonType":"SIMPLE","placement":"CENTER","isVisible":true,"isDisabled":false,"index":0.0,"menuItems":{},"buttonColor":"#16a34a","onClick":"{{Connect.run();\nfetch_Instances.run();\nshowModal('ModalQrcode');}}"},"groupButton2":{"label":"Restart","iconName":"reset","id":"groupButton2","buttonType":"SIMPLE","placement":"CENTER","widgetId":"","isVisible":true,"isDisabled":false,"index":1.0,"menuItems":{},"buttonColor":"#2563eb","onClick":"{{Restart.run().then(() => {\n showAlert('Instance restarted successfully', 'success');\n}).catch(() => {\n showAlert('Error restarting instance', 'error');\n});\nfetch_Instances.run();}}"},"groupButton3":{"label":"Logout","iconName":"log-in","id":"groupButton3","buttonType":"SIMPLE","placement":"CENTER","widgetId":"","isVisible":true,"isDisabled":false,"index":2.0,"menuItems":{"menuItem1":{"label":"First Option","backgroundColor":"#FFFFFF","id":"menuItem1","widgetId":"","onClick":"","isVisible":true,"isDisabled":false,"index":0.0},"menuItem2":{"label":"Second Option","backgroundColor":"#FFFFFF","id":"menuItem2","widgetId":"","onClick":"","isVisible":true,"isDisabled":false,"index":1.0},"menuItem3":{"label":"Delete","iconName":"trash","iconColor":"#FFFFFF","iconAlign":"right","textColor":"#FFFFFF","backgroundColor":"#DD4B34","id":"menuItem3","widgetId":"","onClick":"","isVisible":true,"isDisabled":false,"index":2.0}},"buttonColor":"#a16207","onClick":"{{Logout.run().then(() => {\n showAlert('Instance logout successfully', 'success');\n}).catch(() => {\n showAlert('Error logout instance', 'error');\n});\nfetch_Instances.run();}}"},"groupButtonmghcs8rd4g":{"id":"groupButtonmghcs8rd4g","index":3.0,"label":"Delete","menuItems":{},"buttonType":"SIMPLE","placement":"CENTER","widgetId":"v0qkg2pjo2","isDisabled":false,"isVisible":true,"buttonColor":"#ef4444","iconName":"cross","onClick":"{{Delete.run().then(() => {\n showAlert('Instance deleted successfully', 'success');\n}).catch(() => {\n showAlert('Error deleting instance', 'error');\n});\nfetch_Instances.run();}}"}},"type":"BUTTON_GROUP_WIDGET","hideCard":false,"mobileRightColumn":51.0,"animateLoading":true,"parentColumnSpace":11.828125,"dynamicTriggerPathList":[{"key":"groupButtons.groupButton1.onClick"},{"key":"groupButtons.groupButton2.onClick"},{"key":"groupButtons.groupButton3.onClick"},{"key":"groupButtons.groupButtonmghcs8rd4g.onClick"}],"leftColumn":27.0,"dynamicBindingPathList":[{"key":"isVisible"},{"key":"borderRadius"}],"isDisabled":false,"key":"za8m3k8x7w","orientation":"horizontal","isDeprecated":false,"rightColumn":63.0,"widgetId":"2s6fqi483g","minWidth":450.0,"isVisible":"{{appsmith.store.api_key && appsmith.store.api_url ? true : false}}","version":1.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":1.0,"responsiveBehavior":"fill","childStylesheet":{"button":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}"}},"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":27.0,"buttonVariant":"PRIMARY"},{"boxShadow":"none","mobileBottomRow":18.0,"widgetName":"ProfilePicture","dynamicPropertyPathList":[{"key":"isVisible"},{"key":"borderRadius"}],"displayName":"Image","iconSVG":"/static/media/icon.30c8cbd442cce232b01ba2d434c53a53.svg","topRow":6.0,"bottomRow":28.0,"parentRowSpace":10.0,"type":"IMAGE_WIDGET","hideCard":false,"mobileRightColumn":13.0,"animateLoading":true,"parentColumnSpace":11.828125,"dynamicTriggerPathList":[],"imageShape":"RECTANGLE","leftColumn":1.0,"dynamicBindingPathList":[{"key":"image"},{"key":"isVisible"}],"defaultImage":"https://th.bing.com/th/id/OIP.ruat7whad9-kcI8_1KH_tQHaGI?pid=ImgDet&rs=1","key":"bl30j21wwb","image":"{{TableInstances.selectedRow.profilePictureUrl}}","isDeprecated":false,"rightColumn":13.0,"objectFit":"contain","widgetId":"1sjznr31jo","isVisible":"{{appsmith.store.api_key && appsmith.store.api_url ? true : false}}","version":1.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":6.0,"maxZoomLevel":1.0,"enableDownload":false,"borderRadius":"0.335rem","mobileLeftColumn":1.0,"enableRotation":false},{"mobileBottomRow":22.0,"widgetName":"Text4","dynamicPropertyPathList":[{"key":"isVisible"}],"displayName":"Text","iconSVG":"/static/media/icon.c3b6033f570046f8c6288d911333a827.svg","searchTags":["typography","paragraph","label"],"topRow":36.0,"bottomRow":44.0,"parentRowSpace":10.0,"type":"TEXT_WIDGET","hideCard":false,"mobileRightColumn":11.0,"animateLoading":true,"overflow":"NONE","fontFamily":"{{appsmith.theme.fontFamily.appFont}}","parentColumnSpace":11.828125,"dynamicTriggerPathList":[],"leftColumn":1.0,"dynamicBindingPathList":[{"key":"text"},{"key":"isVisible"},{"key":"fontFamily"}],"shouldTruncate":false,"truncateButtonColor":"{{appsmith.theme.colors.primaryColor}}","text":"{{TableInstances.selectedRow.profileName || ''}}\n\n{{TableInstances.selectedRow.profileStatus || ''}}","key":"gqt8t28m33","isDeprecated":false,"rightColumn":13.0,"textAlign":"CENTER","dynamicHeight":"AUTO_HEIGHT","widgetId":"0c356c66hp","minWidth":450.0,"isVisible":"{{appsmith.store.api_key && appsmith.store.api_url ? true : false}}","fontStyle":"BOLD","textColor":"#231F20","version":1.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":18.0,"responsiveBehavior":"fill","originalTopRow":38.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"originalBottomRow":44.0,"fontSize":"0.875rem","minDynamicHeight":4.0},{"mobileBottomRow":41.0,"widgetName":"Text5","dynamicPropertyPathList":[{"key":"isVisible"}],"displayName":"Text","iconSVG":"/static/media/icon.c3b6033f570046f8c6288d911333a827.svg","searchTags":["typography","paragraph","label"],"topRow":32.0,"bottomRow":36.0,"parentRowSpace":10.0,"type":"TEXT_WIDGET","hideCard":false,"mobileRightColumn":9.0,"animateLoading":true,"overflow":"NONE","fontFamily":"{{appsmith.theme.fontFamily.appFont}}","parentColumnSpace":11.75,"dynamicTriggerPathList":[],"leftColumn":1.0,"dynamicBindingPathList":[{"key":"text"},{"key":"isVisible"},{"key":"fontFamily"}],"shouldTruncate":false,"truncateButtonColor":"{{appsmith.theme.colors.primaryColor}}","text":"{{TableInstances.selectedRow.instance || ''}}","key":"gqt8t28m33","isDeprecated":false,"rightColumn":13.0,"textAlign":"CENTER","dynamicHeight":"AUTO_HEIGHT","widgetId":"5qg2iscn1l","minWidth":450.0,"isVisible":"{{appsmith.store.api_key && appsmith.store.api_url ? true : false}}","fontStyle":"BOLD","textColor":"#231F20","version":1.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":37.0,"responsiveBehavior":"fill","originalTopRow":32.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"originalBottomRow":38.0,"fontSize":"1.25rem","minDynamicHeight":4.0},{"boxShadow":"none","mobileBottomRow":70.0,"widgetName":"ModalWebhook","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":46.0,"bottomRow":43.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":35.0,"minHeight":430.0,"animateLoading":true,"parentColumnSpace":17.9375,"leftColumn":11.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas4","displayName":"Canvas","topRow":0.0,"bottomRow":430.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":240.0,"mobileRightColumn":430.5,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","borderColor":"#E0DEDE","iconSVG":"/static/media/icon.efac588608711d232f1c6c8a2144d2dd.svg","onSubmit":"{{Set_Webhook.run().then(() => {\n showAlert('Webhook updated successfully', 'success');\n}).catch(() => {\n showAlert('Error updating webhook', 'error');\n});\ncloseModal('ModalWebhook');}}","topRow":0.0,"type":"JSON_FORM_WIDGET","animateLoading":true,"leftColumn":0.0,"dynamicBindingPathList":[{"key":"borderRadius"},{"key":"submitButtonStyles.buttonColor"},{"key":"schema.__root_schema__.defaultValue"},{"key":"schema.__root_schema__.borderRadius"},{"key":"schema.__root_schema__.cellBorderRadius"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.enabled.defaultValue"},{"key":"schema.__root_schema__.children.enabled.accentColor"},{"key":"schema.__root_schema__.children.url.defaultValue"},{"key":"schema.__root_schema__.children.url.accentColor"},{"key":"schema.__root_schema__.children.url.borderRadius"},{"key":"schema.__root_schema__.children.webhook_by_events.defaultValue"},{"key":"schema.__root_schema__.children.webhook_by_events.accentColor"},{"key":"schema.__root_schema__.children.events.defaultValue"},{"key":"schema.__root_schema__.children.events.accentColor"},{"key":"schema.__root_schema__.children.events.borderRadius"}],"showReset":false,"dynamicHeight":"AUTO_HEIGHT","autoGenerateForm":false,"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"SECONDARY"},"isVisible":true,"version":1.0,"isLoading":false,"submitButtonLabel":"Save","childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}},"disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","originalBottomRow":41.0,"useSourceData":false,"schema":{"__root_schema__":{"children":{"enabled":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.enabled))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"enabled","identifier":"enabled","position":0.0,"originalIdentifier":"enabled","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Enabled"},"url":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.url))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"url","identifier":"url","position":1.0,"originalIdentifier":"url","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Url"},"webhook_by_events":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.webhook_by_events))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"webhook_by_events","identifier":"webhook_by_events","position":2.0,"originalIdentifier":"webhook_by_events","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Webhook By Events"},"events":{"children":{},"dataType":"array","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.events))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","fieldType":"Multiselect","sourceData":[],"isCustomField":false,"accessor":"events","identifier":"events","position":3.0,"originalIdentifier":"events","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Events","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n\n {\n \"label\": \"APPLICATION_STARTUP\",\n \"value\": \"APPLICATION_STARTUP\"\n },\n {\n \"label\": \"QRCODE_UPDATED\",\n \"value\": \"QRCODE_UPDATED\"\n },\n {\n \"label\": \"MESSAGES_SET\",\n \"value\": \"MESSAGES_SET\"\n },\n {\n \"label\": \"MESSAGES_UPSERT\",\n \"value\": \"MESSAGES_UPSERT\"\n },\n {\n \"label\": \"MESSAGES_UPDATE\",\n \"value\": \"MESSAGES_UPDATE\"\n },\n {\n \"label\": \"MESSAGES_DELETE\",\n \"value\": \"MESSAGES_DELETE\"\n },\n {\n \"label\": \"SEND_MESSAGE\",\n \"value\": \"SEND_MESSAGE\"\n },\n {\n \"label\": \"CONTACTS_SET\",\n \"value\": \"CONTACTS_SET\"\n },\n {\n \"label\": \"CONTACTS_UPSERT\",\n \"value\": \"CONTACTS_UPSERT\"\n },\n {\n \"label\": \"CONTACTS_UPDATE\",\n \"value\": \"CONTACTS_UPDATE\"\n },\n {\n \"label\": \"PRESENCE_UPDATE\",\n \"value\": \"PRESENCE_UPDATE\"\n },\n {\n \"label\": \"CHATS_SET\",\n \"value\": \"CHATS_SET\"\n },\n {\n \"label\": \"CHATS_UPSERT\",\n \"value\": \"CHATS_UPSERT\"\n },\n {\n \"label\": \"CHATS_UPDATE\",\n \"value\": \"CHATS_UPDATE\"\n },\n {\n \"label\": \"CHATS_DELETE\",\n \"value\": \"CHATS_DELETE\"\n },\n {\n \"label\": \"GROUPS_UPSERT\",\n \"value\": \"GROUPS_UPSERT\"\n },\n {\n \"label\": \"GROUP_UPDATE\",\n \"value\": \"GROUP_UPDATE\"\n },\n {\n \"label\": \"GROUP_PARTICIPANTS_UPDATE\",\n \"value\": \"GROUP_PARTICIPANTS_UPDATE\"\n },\n {\n \"label\": \"CONNECTION_UPDATE\",\n \"value\": \"CONNECTION_UPDATE\"\n },\n {\n \"label\": \"CALL\",\n \"value\": \"CALL\"\n },\n {\n \"label\": \"NEW_JWT_TOKEN\",\n \"value\": \"NEW_JWT_TOKEN\"\n }\n]"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","fieldType":"Object","sourceData":{"enabled":false,"url":"","webhook_by_events":false,"events":[]},"isCustomField":false,"accessor":"__root_schema__","identifier":"__root_schema__","position":-1.0,"originalIdentifier":"__root_schema__","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":""}},"mobileBottomRow":41.0,"widgetName":"FormWebhook","submitButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.webhook_by_events.defaultValue"},{"key":"schema.__root_schema__.children.enabled.defaultValue"},{"key":"schema.__root_schema__.children.url.defaultValue"}],"displayName":"JSON Form","bottomRow":41.0,"fieldLimitExceeded":false,"parentRowSpace":10.0,"title":"Webhook","hideCard":false,"mobileRightColumn":25.0,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[{"key":"onSubmit"}],"borderWidth":"0","sourceData":"{\n\t\"enabled\": {{Find_Webhook.data.enabled || false}},\n\t\"url\": {{Find_Webhook.data.url}},\n \"webhook_by_events\": {{Find_Webhook.data.webhook_by_events}},\n \"events\": {{Find_Webhook.data.events || false}} \n}","resetButtonLabel":"Reset","key":"lgqqk5r1jk","backgroundColor":"#fff","isDeprecated":false,"rightColumn":63.0,"widgetId":"tb1ekur7fx","minWidth":450.0,"parentId":"mv02ta6pzr","renderMode":"CANVAS","mobileTopRow":0.0,"scrollContents":true,"responsiveBehavior":"fill","fixedFooter":true,"originalTopRow":0.0,"mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"minDynamicHeight":4.0}],"isDisabled":false,"key":"svq68rvpdn","isDeprecated":false,"rightColumn":430.5,"detachFromLayout":true,"widgetId":"mv02ta6pzr","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"0g8ql5hukz","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"6x3z5yow7u","height":430.0,"isDeprecated":false,"rightColumn":35.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"0g8ql5hukz","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":46.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":11.0,"maxDynamicHeight":9000.0,"width":456.0,"minDynamicHeight":24.0},{"boxShadow":"none","mobileBottomRow":70.0,"widgetName":"ModalWebsocket","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":42.0,"bottomRow":40.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":35.0,"minHeight":400.0,"animateLoading":true,"parentColumnSpace":17.9375,"leftColumn":11.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas4Copy1","displayName":"Canvas","topRow":0.0,"bottomRow":400.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":400.0,"mobileRightColumn":430.5,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","borderColor":"#E0DEDE","iconSVG":"/static/media/icon.efac588608711d232f1c6c8a2144d2dd.svg","onSubmit":"{{Set_Websocket.run().then(() => {\n showAlert('Websocket updated successfully', 'success');\n}).catch(() => {\n showAlert('Error updating websocket', 'error');\n});\ncloseModal('ModalWebsocket');}}","topRow":0.0,"type":"JSON_FORM_WIDGET","animateLoading":true,"leftColumn":0.0,"dynamicBindingPathList":[{"key":"borderRadius"},{"key":"submitButtonStyles.buttonColor"},{"key":"schema.__root_schema__.defaultValue"},{"key":"schema.__root_schema__.borderRadius"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.enabled.defaultValue"},{"key":"schema.__root_schema__.children.enabled.accentColor"},{"key":"schema.__root_schema__.children.url.defaultValue"},{"key":"schema.__root_schema__.children.url.accentColor"},{"key":"schema.__root_schema__.children.url.borderRadius"},{"key":"schema.__root_schema__.children.events.defaultValue"},{"key":"schema.__root_schema__.children.events.accentColor"},{"key":"schema.__root_schema__.children.events.borderRadius"},{"key":"schema.__root_schema__.cellBorderRadius"}],"showReset":false,"dynamicHeight":"AUTO_HEIGHT","autoGenerateForm":false,"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"SECONDARY"},"isVisible":true,"version":1.0,"isLoading":false,"submitButtonLabel":"Save","childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}},"disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","originalBottomRow":38.0,"useSourceData":false,"schema":{"__root_schema__":{"children":{"enabled":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.enabled))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","fieldType":"Switch","sourceData":true,"isCustomField":false,"accessor":"enabled","identifier":"enabled","position":0.0,"originalIdentifier":"enabled","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Enabled"},"url":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.url))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","fieldType":"Text Input","sourceData":"https://teste.com","isCustomField":false,"accessor":"url","identifier":"url","position":1.0,"originalIdentifier":"url","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Url"},"events":{"children":{},"dataType":"array","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.events))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","fieldType":"Multiselect","sourceData":["MESSAGES_UPSERT"],"isCustomField":false,"accessor":"events","identifier":"events","position":2.0,"originalIdentifier":"events","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Events","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n\n {\n \"label\": \"APPLICATION_STARTUP\",\n \"value\": \"APPLICATION_STARTUP\"\n },\n {\n \"label\": \"QRCODE_UPDATED\",\n \"value\": \"QRCODE_UPDATED\"\n },\n {\n \"label\": \"MESSAGES_SET\",\n \"value\": \"MESSAGES_SET\"\n },\n {\n \"label\": \"MESSAGES_UPSERT\",\n \"value\": \"MESSAGES_UPSERT\"\n },\n {\n \"label\": \"MESSAGES_UPDATE\",\n \"value\": \"MESSAGES_UPDATE\"\n },\n {\n \"label\": \"MESSAGES_DELETE\",\n \"value\": \"MESSAGES_DELETE\"\n },\n {\n \"label\": \"SEND_MESSAGE\",\n \"value\": \"SEND_MESSAGE\"\n },\n {\n \"label\": \"CONTACTS_SET\",\n \"value\": \"CONTACTS_SET\"\n },\n {\n \"label\": \"CONTACTS_UPSERT\",\n \"value\": \"CONTACTS_UPSERT\"\n },\n {\n \"label\": \"CONTACTS_UPDATE\",\n \"value\": \"CONTACTS_UPDATE\"\n },\n {\n \"label\": \"PRESENCE_UPDATE\",\n \"value\": \"PRESENCE_UPDATE\"\n },\n {\n \"label\": \"CHATS_SET\",\n \"value\": \"CHATS_SET\"\n },\n {\n \"label\": \"CHATS_UPSERT\",\n \"value\": \"CHATS_UPSERT\"\n },\n {\n \"label\": \"CHATS_UPDATE\",\n \"value\": \"CHATS_UPDATE\"\n },\n {\n \"label\": \"CHATS_DELETE\",\n \"value\": \"CHATS_DELETE\"\n },\n {\n \"label\": \"GROUPS_UPSERT\",\n \"value\": \"GROUPS_UPSERT\"\n },\n {\n \"label\": \"GROUP_UPDATE\",\n \"value\": \"GROUP_UPDATE\"\n },\n {\n \"label\": \"GROUP_PARTICIPANTS_UPDATE\",\n \"value\": \"GROUP_PARTICIPANTS_UPDATE\"\n },\n {\n \"label\": \"CONNECTION_UPDATE\",\n \"value\": \"CONNECTION_UPDATE\"\n },\n {\n \"label\": \"CALL\",\n \"value\": \"CALL\"\n },\n {\n \"label\": \"NEW_JWT_TOKEN\",\n \"value\": \"NEW_JWT_TOKEN\"\n }\n]"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","fieldType":"Object","sourceData":{"enabled":true,"url":"https://teste.com","events":["MESSAGES_UPSERT"]},"isCustomField":false,"accessor":"__root_schema__","identifier":"__root_schema__","position":-1.0,"originalIdentifier":"__root_schema__","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebsocket.sourceData, FormWebsocket.formData, FormWebsocket.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":""}},"mobileBottomRow":41.0,"widgetName":"FormWebsocket","submitButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.enabled.defaultValue"},{"key":"schema.__root_schema__.children.events.defaultValue"},{"key":"schema.__root_schema__.children.url.defaultValue"}],"displayName":"JSON Form","bottomRow":38.0,"fieldLimitExceeded":false,"parentRowSpace":10.0,"title":"Websocket","hideCard":false,"mobileRightColumn":25.0,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[{"key":"onSubmit"}],"borderWidth":"0","sourceData":"{\n\t\"enabled\": {{Find_Websocket.data.enabled || false}},\n \"url\": {{Find_Websocket.data.url}},\n \"events\": {{Find_Websocket.data.events}}\n\t\t\n }","resetButtonLabel":"Reset","key":"lgqqk5r1jk","backgroundColor":"#fff","isDeprecated":false,"rightColumn":63.0,"widgetId":"masqwth5vo","minWidth":450.0,"parentId":"gzf4hjxdo8","renderMode":"CANVAS","mobileTopRow":0.0,"scrollContents":true,"responsiveBehavior":"fill","fixedFooter":true,"originalTopRow":0.0,"mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"minDynamicHeight":4.0}],"isDisabled":false,"key":"svq68rvpdn","isDeprecated":false,"rightColumn":430.5,"detachFromLayout":true,"widgetId":"gzf4hjxdo8","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"9twyngcwej","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"6x3z5yow7u","height":400.0,"isDeprecated":false,"rightColumn":35.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"9twyngcwej","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":46.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":11.0,"maxDynamicHeight":9000.0,"width":456.0,"minDynamicHeight":24.0},{"boxShadow":"none","mobileBottomRow":70.0,"widgetName":"ModalRabbitmq","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":31.0,"bottomRow":32.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":35.0,"minHeight":320.0,"animateLoading":true,"parentColumnSpace":17.9375,"leftColumn":11.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas4Copy1Copy","displayName":"Canvas","topRow":0.0,"bottomRow":320.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":240.0,"mobileRightColumn":430.5,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","borderColor":"#E0DEDE","iconSVG":"/static/media/icon.efac588608711d232f1c6c8a2144d2dd.svg","onSubmit":"{{Set_Rabbitmq.run().then(() => {\n showAlert('Rabbitmq updated successfully', 'success');\n}).catch(() => {\n showAlert('Error updating rabbitmq', 'error');\n});\ncloseModal('ModalRabbitmq');}}","topRow":0.0,"type":"JSON_FORM_WIDGET","animateLoading":true,"leftColumn":0.0,"dynamicBindingPathList":[{"key":"borderRadius"},{"key":"submitButtonStyles.buttonColor"},{"key":"sourceData"},{"key":"schema.__root_schema__.defaultValue"},{"key":"schema.__root_schema__.borderRadius"},{"key":"schema.__root_schema__.children.enabled.defaultValue"},{"key":"schema.__root_schema__.children.enabled.accentColor"},{"key":"schema.__root_schema__.children.events.defaultValue"},{"key":"schema.__root_schema__.children.events.accentColor"},{"key":"schema.__root_schema__.children.events.borderRadius"},{"key":"schema.__root_schema__.cellBorderRadius"}],"showReset":false,"dynamicHeight":"AUTO_HEIGHT","autoGenerateForm":false,"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"SECONDARY"},"isVisible":true,"version":1.0,"isLoading":false,"submitButtonLabel":"Save","childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}},"disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","originalBottomRow":30.0,"useSourceData":false,"schema":{"__root_schema__":{"children":{"enabled":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.enabled))(FormRabbitmq.sourceData, FormRabbitmq.formData, FormRabbitmq.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"enabled","identifier":"enabled","position":0.0,"originalIdentifier":"enabled","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormRabbitmq.sourceData, FormRabbitmq.formData, FormRabbitmq.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Enabled"},"events":{"children":{},"dataType":"array","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.events))(FormRabbitmq.sourceData, FormRabbitmq.formData, FormRabbitmq.fieldState)}}","fieldType":"Multiselect","sourceData":[],"isCustomField":false,"accessor":"events","identifier":"events","position":1.0,"originalIdentifier":"events","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormRabbitmq.sourceData, FormRabbitmq.formData, FormRabbitmq.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormRabbitmq.sourceData, FormRabbitmq.formData, FormRabbitmq.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Events","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n\n {\n \"label\": \"APPLICATION_STARTUP\",\n \"value\": \"APPLICATION_STARTUP\"\n },\n {\n \"label\": \"QRCODE_UPDATED\",\n \"value\": \"QRCODE_UPDATED\"\n },\n {\n \"label\": \"MESSAGES_SET\",\n \"value\": \"MESSAGES_SET\"\n },\n {\n \"label\": \"MESSAGES_UPSERT\",\n \"value\": \"MESSAGES_UPSERT\"\n },\n {\n \"label\": \"MESSAGES_UPDATE\",\n \"value\": \"MESSAGES_UPDATE\"\n },\n {\n \"label\": \"MESSAGES_DELETE\",\n \"value\": \"MESSAGES_DELETE\"\n },\n {\n \"label\": \"SEND_MESSAGE\",\n \"value\": \"SEND_MESSAGE\"\n },\n {\n \"label\": \"CONTACTS_SET\",\n \"value\": \"CONTACTS_SET\"\n },\n {\n \"label\": \"CONTACTS_UPSERT\",\n \"value\": \"CONTACTS_UPSERT\"\n },\n {\n \"label\": \"CONTACTS_UPDATE\",\n \"value\": \"CONTACTS_UPDATE\"\n },\n {\n \"label\": \"PRESENCE_UPDATE\",\n \"value\": \"PRESENCE_UPDATE\"\n },\n {\n \"label\": \"CHATS_SET\",\n \"value\": \"CHATS_SET\"\n },\n {\n \"label\": \"CHATS_UPSERT\",\n \"value\": \"CHATS_UPSERT\"\n },\n {\n \"label\": \"CHATS_UPDATE\",\n \"value\": \"CHATS_UPDATE\"\n },\n {\n \"label\": \"CHATS_DELETE\",\n \"value\": \"CHATS_DELETE\"\n },\n {\n \"label\": \"GROUPS_UPSERT\",\n \"value\": \"GROUPS_UPSERT\"\n },\n {\n \"label\": \"GROUP_UPDATE\",\n \"value\": \"GROUP_UPDATE\"\n },\n {\n \"label\": \"GROUP_PARTICIPANTS_UPDATE\",\n \"value\": \"GROUP_PARTICIPANTS_UPDATE\"\n },\n {\n \"label\": \"CONNECTION_UPDATE\",\n \"value\": \"CONNECTION_UPDATE\"\n },\n {\n \"label\": \"CALL\",\n \"value\": \"CALL\"\n },\n {\n \"label\": \"NEW_JWT_TOKEN\",\n \"value\": \"NEW_JWT_TOKEN\"\n }\n]"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(FormRabbitmq.sourceData, FormRabbitmq.formData, FormRabbitmq.fieldState)}}","fieldType":"Object","sourceData":{"enabled":false,"events":[]},"isCustomField":false,"accessor":"__root_schema__","identifier":"__root_schema__","position":-1.0,"originalIdentifier":"__root_schema__","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormRabbitmq.sourceData, FormRabbitmq.formData, FormRabbitmq.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormRabbitmq.sourceData, FormRabbitmq.formData, FormRabbitmq.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":""}},"mobileBottomRow":41.0,"widgetName":"FormRabbitmq","submitButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.events.defaultValue"},{"key":"schema.__root_schema__.children.enabled.defaultValue"}],"displayName":"JSON Form","bottomRow":30.0,"fieldLimitExceeded":false,"parentRowSpace":10.0,"title":"Rabbitmq","hideCard":false,"mobileRightColumn":25.0,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[{"key":"onSubmit"}],"borderWidth":"0","sourceData":"{\n\t\"enabled\": {{Find_Rabbitmq.data.enabled || false}},\n \"events\": {{Find_Rabbitmq.data.events}}\n\t\t\n }","resetButtonLabel":"Reset","key":"lgqqk5r1jk","backgroundColor":"#fff","isDeprecated":false,"rightColumn":63.0,"widgetId":"gdkpog7ep5","minWidth":450.0,"parentId":"rkuaegvcin","renderMode":"CANVAS","mobileTopRow":0.0,"scrollContents":true,"responsiveBehavior":"fill","fixedFooter":true,"originalTopRow":0.0,"mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"minDynamicHeight":4.0}],"isDisabled":false,"key":"svq68rvpdn","isDeprecated":false,"rightColumn":430.5,"detachFromLayout":true,"widgetId":"rkuaegvcin","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"76vl08dr1n","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"6x3z5yow7u","height":320.0,"isDeprecated":false,"rightColumn":35.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"76vl08dr1n","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":46.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":11.0,"maxDynamicHeight":9000.0,"width":456.0,"minDynamicHeight":24.0},{"boxShadow":"none","mobileBottomRow":70.0,"widgetName":"ModalSettings","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":46.0,"bottomRow":47.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":35.0,"minHeight":470.0,"animateLoading":true,"parentColumnSpace":17.9375,"leftColumn":11.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas4Copy","displayName":"Canvas","topRow":0.0,"bottomRow":470.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":240.0,"mobileRightColumn":430.5,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","borderColor":"#E0DEDE","iconSVG":"/static/media/icon.efac588608711d232f1c6c8a2144d2dd.svg","onSubmit":"{{Set_Settings.run().then(() => {\n showAlert('Settings updated successfully', 'success');\n}).catch(() => {\n showAlert('Error updating Settings', 'error');\n});\ncloseModal('ModalSettings');}}","topRow":0.0,"type":"JSON_FORM_WIDGET","animateLoading":true,"leftColumn":1.0,"dynamicBindingPathList":[{"key":"schema.__root_schema__.children.read_status.accentColor"},{"key":"schema.__root_schema__.children.read_status.defaultValue"},{"key":"schema.__root_schema__.children.read_messages.accentColor"},{"key":"schema.__root_schema__.children.read_messages.defaultValue"},{"key":"schema.__root_schema__.children.always_online.accentColor"},{"key":"schema.__root_schema__.children.always_online.defaultValue"},{"key":"schema.__root_schema__.children.groups_ignore.accentColor"},{"key":"schema.__root_schema__.children.groups_ignore.defaultValue"},{"key":"schema.__root_schema__.children.msg_call.accentColor"},{"key":"schema.__root_schema__.children.msg_call.defaultValue"},{"key":"schema.__root_schema__.children.reject_call.accentColor"},{"key":"schema.__root_schema__.children.reject_call.defaultValue"},{"key":"borderRadius"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.msg_call.borderRadius"},{"key":"submitButtonStyles.buttonColor"}],"showReset":false,"dynamicHeight":"AUTO_HEIGHT","autoGenerateForm":true,"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"SECONDARY"},"isVisible":true,"version":1.0,"isLoading":false,"submitButtonLabel":"Save","childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}},"disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","originalBottomRow":45.0,"useSourceData":false,"schema":{"__root_schema__":{"children":{"reject_call":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.reject_call))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","fieldType":"Switch","sourceData":true,"isCustomField":false,"accessor":"reject_call","identifier":"reject_call","position":0.0,"originalIdentifier":"reject_call","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Reject Call"},"msg_call":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.msg_call))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","fieldType":"Text Input","sourceData":"Não aceitamos chamadas!","isCustomField":false,"accessor":"msg_call","identifier":"msg_call","position":1.0,"originalIdentifier":"msg_call","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Msg Call"},"groups_ignore":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.groups_ignore))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","fieldType":"Switch","sourceData":true,"isCustomField":false,"accessor":"groups_ignore","identifier":"groups_ignore","position":2.0,"originalIdentifier":"groups_ignore","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Groups Ignore"},"always_online":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.always_online))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","fieldType":"Switch","sourceData":true,"isCustomField":false,"accessor":"always_online","identifier":"always_online","position":3.0,"originalIdentifier":"always_online","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Always Online"},"read_messages":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.read_messages))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","fieldType":"Switch","sourceData":true,"isCustomField":false,"accessor":"read_messages","identifier":"read_messages","position":4.0,"originalIdentifier":"read_messages","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Read Messages"},"read_status":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.read_status))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"read_status","identifier":"read_status","position":5.0,"originalIdentifier":"read_status","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormSettings.sourceData, FormSettings.formData, FormSettings.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Read Status"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","fieldType":"Object","sourceData":{"name":"John","date_of_birth":"20/02/1990","employee_id":1001.0},"isCustomField":false,"accessor":"__root_schema__","identifier":"__root_schema__","position":-1.0,"originalIdentifier":"__root_schema__","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":""}},"mobileBottomRow":41.0,"widgetName":"FormSettings","submitButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.reject_call.defaultValue"},{"key":"schema.__root_schema__.children.groups_ignore.defaultValue"},{"key":"schema.__root_schema__.children.always_online.defaultValue"},{"key":"schema.__root_schema__.children.read_messages.defaultValue"},{"key":"schema.__root_schema__.children.read_status.defaultValue"},{"key":"schema.__root_schema__.children.msg_call.defaultValue"}],"displayName":"JSON Form","bottomRow":45.0,"fieldLimitExceeded":false,"parentRowSpace":10.0,"title":"Settings","hideCard":false,"mobileRightColumn":25.0,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[{"key":"onSubmit"}],"borderWidth":"0","sourceData":"{\n\t\"reject_call\": {{Find_Settings.data.reject_call || false}},\n \"msg_call\": {{Find_Settings.data.msg_call}},\n \"groups_ignore\": {{Find_Settings.data.groups_ignore || false}},\n \"always_online\": {{Find_Settings.data.always_online || false}},\n \"read_messages\": {{Find_Settings.data.read_messages || false}},\n \"read_status\": {{Find_Settings.data.read_status || false}}\n}","resetButtonLabel":"Reset","key":"lgqqk5r1jk","backgroundColor":"#fff","isDeprecated":false,"rightColumn":64.0,"widgetId":"3wajdobhry","minWidth":450.0,"parentId":"bj66ktxeor","renderMode":"CANVAS","mobileTopRow":0.0,"scrollContents":true,"responsiveBehavior":"fill","fixedFooter":true,"originalTopRow":0.0,"mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"minDynamicHeight":4.0}],"isDisabled":false,"key":"svq68rvpdn","isDeprecated":false,"rightColumn":430.5,"detachFromLayout":true,"widgetId":"bj66ktxeor","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"9pvl5efylb","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"6x3z5yow7u","height":470.0,"isDeprecated":false,"rightColumn":35.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"9pvl5efylb","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":46.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":11.0,"maxDynamicHeight":9000.0,"width":456.0,"minDynamicHeight":24.0},{"boxShadow":"none","mobileBottomRow":70.0,"widgetName":"ModalChatwoot","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":50.0,"bottomRow":780.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":35.0,"minHeight":730.0,"animateLoading":true,"parentColumnSpace":17.9375,"leftColumn":11.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas4CopyCopy","displayName":"Canvas","topRow":0.0,"bottomRow":730.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":730.0,"mobileRightColumn":430.5,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","borderColor":"#E0DEDE","iconSVG":"/static/media/icon.efac588608711d232f1c6c8a2144d2dd.svg","onSubmit":"{{Set_Chatwoot.run().then(() => {\n showAlert('Chatwoot updated successfully', 'success');\n}).catch(() => {\n showAlert('Error updating Chatwoot', 'error');\n});\ncloseModal('ModalChatwoot');}}","topRow":0.0,"type":"JSON_FORM_WIDGET","animateLoading":true,"leftColumn":0.0,"dynamicBindingPathList":[{"key":"schema.__root_schema__.children.conversation_pending.accentColor"},{"key":"schema.__root_schema__.children.conversation_pending.defaultValue"},{"key":"schema.__root_schema__.children.reopen_conversation.accentColor"},{"key":"schema.__root_schema__.children.reopen_conversation.defaultValue"},{"key":"schema.__root_schema__.children.sign_msg.accentColor"},{"key":"schema.__root_schema__.children.sign_msg.defaultValue"},{"key":"schema.__root_schema__.children.url.borderRadius"},{"key":"schema.__root_schema__.children.url.accentColor"},{"key":"schema.__root_schema__.children.url.defaultValue"},{"key":"schema.__root_schema__.children.token.borderRadius"},{"key":"schema.__root_schema__.children.token.accentColor"},{"key":"schema.__root_schema__.children.token.defaultValue"},{"key":"schema.__root_schema__.children.account_id.accentColor"},{"key":"schema.__root_schema__.children.account_id.defaultValue"},{"key":"schema.__root_schema__.children.enabled.accentColor"},{"key":"schema.__root_schema__.children.enabled.defaultValue"},{"key":"borderRadius"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.account_id.borderRadius"},{"key":"schema.__root_schema__.children.webhook_url.defaultValue"},{"key":"schema.__root_schema__.children.webhook_url.accentColor"},{"key":"schema.__root_schema__.children.webhook_url.borderRadius"},{"key":"schema.__root_schema__.defaultValue"},{"key":"schema.__root_schema__.borderRadius"},{"key":"schema.__root_schema__.cellBorderRadius"},{"key":"schema.__root_schema__.children.name_inbox.defaultValue"},{"key":"schema.__root_schema__.children.name_inbox.borderRadius"},{"key":"schema.__root_schema__.children.name_inbox.accentColor"},{"key":"submitButtonStyles.buttonColor"}],"showReset":false,"dynamicHeight":"AUTO_HEIGHT","autoGenerateForm":true,"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"SECONDARY"},"isVisible":true,"version":1.0,"isLoading":false,"submitButtonLabel":"Save","childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}},"disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","originalBottomRow":71.0,"useSourceData":false,"schema":{"__root_schema__":{"children":{"enabled":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.enabled))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","fieldType":"Switch","sourceData":true,"isCustomField":false,"accessor":"enabled","identifier":"enabled","position":0.0,"originalIdentifier":"enabled","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Enabled"},"account_id":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.account_id))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","fieldType":"Text Input","sourceData":"1","isCustomField":false,"accessor":"account_id","identifier":"account_id","position":1.0,"originalIdentifier":"account_id","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Account Id"},"token":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.token))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","fieldType":"Password Input","sourceData":"uHquVJgCdkee8JPJm9YBkdH6","isCustomField":false,"accessor":"token","identifier":"token","position":2.0,"originalIdentifier":"token","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Token","shouldAllowAutofill":true},"url":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.url))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","fieldType":"Text Input","sourceData":"https://chatwoot.evolution.dgcode.com.br","isCustomField":false,"accessor":"url","identifier":"url","position":3.0,"originalIdentifier":"url","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Url"},"sign_msg":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.sign_msg))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"sign_msg","identifier":"sign_msg","position":4.0,"originalIdentifier":"sign_msg","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Sign Msg"},"reopen_conversation":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.reopen_conversation))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","fieldType":"Switch","sourceData":true,"isCustomField":false,"accessor":"reopen_conversation","identifier":"reopen_conversation","position":5.0,"originalIdentifier":"reopen_conversation","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Reopen Conversation"},"conversation_pending":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.conversation_pending))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"conversation_pending","identifier":"conversation_pending","position":6.0,"originalIdentifier":"conversation_pending","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Conversation Pending"},"webhook_url":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.webhook_url))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","fieldType":"Text Input","sourceData":"https://api.evolution.dgcode.com.br/chatwoot/webhook/evolution-cwId-4","isCustomField":false,"accessor":"webhook_url","identifier":"webhook_url","position":8.0,"originalIdentifier":"webhook_url","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":true,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Webhook Url"},"name_inbox":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.name_inbox))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","fieldType":"Text Input","sourceData":"evolution-cwId-4","isCustomField":false,"accessor":"name_inbox","identifier":"name_inbox","position":7.0,"originalIdentifier":"name_inbox","accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormChatwoot.sourceData, FormChatwoot.formData, FormChatwoot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":true,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Name Inbox"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","fieldType":"Object","sourceData":{"name":"John","date_of_birth":"20/02/1990","employee_id":1001.0},"isCustomField":false,"accessor":"__root_schema__","identifier":"__root_schema__","position":-1.0,"originalIdentifier":"__root_schema__","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormWebhook.sourceData, FormWebhook.formData, FormWebhook.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":""}},"mobileBottomRow":41.0,"widgetName":"FormChatwoot","submitButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.enabled.defaultValue"},{"key":"schema.__root_schema__.children.sign_msg.defaultValue"},{"key":"schema.__root_schema__.children.reopen_conversation.defaultValue"},{"key":"schema.__root_schema__.children.conversation_pending.defaultValue"},{"key":"schema.__root_schema__.children.account_id.defaultValue"},{"key":"schema.__root_schema__.children.webhook_url.defaultValue"}],"displayName":"JSON Form","bottomRow":71.0,"fieldLimitExceeded":false,"parentRowSpace":10.0,"title":"Chatwoot","hideCard":false,"mobileRightColumn":25.0,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[{"key":"onSubmit"}],"borderWidth":"0","sourceData":"{\n\t\"enabled\": {{Find_Chatwoot.data.enabled || false}},\n\t\"account_id\": {{Find_Chatwoot.data.account_id}},\n \"token\": {{Find_Chatwoot.data.token}},\n \"url\": {{Find_Chatwoot.data.url}},\n \"sign_msg\": {{Find_Chatwoot.data.sign_msg || false}},\n \"reopen_conversation\": {{Find_Chatwoot.data.reopen_conversation || false}},\n \"conversation_pending\": {{Find_Chatwoot.data.conversation_pending || false}},\n\t\t\"name_inbox\": {{Find_Chatwoot.data.name_inbox}},\n\t\t\"webhook_url\": {{Find_Chatwoot.data.webhook_url}}\n}","resetButtonLabel":"Reset","key":"lgqqk5r1jk","backgroundColor":"#fff","isDeprecated":false,"rightColumn":63.0,"widgetId":"c5v1lwuyrk","minWidth":450.0,"parentId":"wqoo05rt9h","renderMode":"CANVAS","mobileTopRow":0.0,"scrollContents":true,"responsiveBehavior":"fill","fixedFooter":true,"originalTopRow":0.0,"mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"minDynamicHeight":4.0}],"isDisabled":false,"key":"svq68rvpdn","isDeprecated":false,"rightColumn":430.5,"detachFromLayout":true,"widgetId":"wqoo05rt9h","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"kekx3o71p4","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"6x3z5yow7u","height":730.0,"isDeprecated":false,"rightColumn":35.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"kekx3o71p4","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":46.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":11.0,"maxDynamicHeight":9000.0,"width":692.0,"minDynamicHeight":24.0},{"boxShadow":"none","mobileBottomRow":70.0,"widgetName":"ModalTypebot","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":45.0,"bottomRow":775.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":35.0,"minHeight":730.0,"animateLoading":true,"parentColumnSpace":17.9375,"leftColumn":11.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas4CopyCopyCopy","displayName":"Canvas","topRow":0.0,"bottomRow":730.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":730.0,"mobileRightColumn":430.5,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","borderColor":"#E0DEDE","iconSVG":"/static/media/icon.efac588608711d232f1c6c8a2144d2dd.svg","onSubmit":"{{Set_Typebot.run().then(() => {\n showAlert('Typebot updated successfully', 'success');\n}).catch(() => {\n showAlert('Error updating Typebot', 'error');\n});\ncloseModal('ModalTypebot');}}","topRow":1.0,"type":"JSON_FORM_WIDGET","animateLoading":true,"leftColumn":0.0,"dynamicBindingPathList":[{"key":"borderRadius"},{"key":"schema.__root_schema__.defaultValue"},{"key":"schema.__root_schema__.borderRadius"},{"key":"submitButtonStyles.buttonColor"},{"key":"schema.__root_schema__.cellBorderRadius"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.enabled.defaultValue"},{"key":"schema.__root_schema__.children.enabled.accentColor"},{"key":"schema.__root_schema__.children.url.defaultValue"},{"key":"schema.__root_schema__.children.url.accentColor"},{"key":"schema.__root_schema__.children.url.borderRadius"},{"key":"schema.__root_schema__.children.typebot.defaultValue"},{"key":"schema.__root_schema__.children.typebot.accentColor"},{"key":"schema.__root_schema__.children.typebot.borderRadius"},{"key":"schema.__root_schema__.children.expire.defaultValue"},{"key":"schema.__root_schema__.children.expire.accentColor"},{"key":"schema.__root_schema__.children.expire.borderRadius"},{"key":"schema.__root_schema__.children.keyword_finish.defaultValue"},{"key":"schema.__root_schema__.children.keyword_finish.accentColor"},{"key":"schema.__root_schema__.children.keyword_finish.borderRadius"},{"key":"schema.__root_schema__.children.delay_message.defaultValue"},{"key":"schema.__root_schema__.children.delay_message.accentColor"},{"key":"schema.__root_schema__.children.delay_message.borderRadius"},{"key":"schema.__root_schema__.children.unknown_message.defaultValue"},{"key":"schema.__root_schema__.children.unknown_message.accentColor"},{"key":"schema.__root_schema__.children.unknown_message.borderRadius"},{"key":"schema.__root_schema__.children.listening_from_me.defaultValue"},{"key":"schema.__root_schema__.children.listening_from_me.accentColor"}],"showReset":false,"dynamicHeight":"AUTO_HEIGHT","autoGenerateForm":true,"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"SECONDARY"},"isVisible":true,"version":1.0,"isLoading":false,"submitButtonLabel":"Save","childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}},"disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","originalBottomRow":71.0,"useSourceData":false,"schema":{"__root_schema__":{"children":{"enabled":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.enabled))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Switch","sourceData":true,"isCustomField":false,"accessor":"enabled","identifier":"enabled","position":0.0,"originalIdentifier":"enabled","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Enabled"},"url":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.url))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Text Input","sourceData":"https://bot.typebot.com","isCustomField":false,"accessor":"url","identifier":"url","position":1.0,"originalIdentifier":"url","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Url"},"typebot":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.typebot))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Text Input","sourceData":"felipe-final-sbkaa3s","isCustomField":false,"accessor":"typebot","identifier":"typebot","position":2.0,"originalIdentifier":"typebot","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Typebot"},"expire":{"children":{},"dataType":"number","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.expire))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Number Input","sourceData":45.0,"isCustomField":false,"accessor":"expire","identifier":"expire","position":3.0,"originalIdentifier":"expire","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Expire"},"keyword_finish":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.keyword_finish))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Text Input","sourceData":"#SAIR","isCustomField":false,"accessor":"keyword_finish","identifier":"keyword_finish","position":4.0,"originalIdentifier":"keyword_finish","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Keyword Finish"},"delay_message":{"children":{},"dataType":"number","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.delay_message))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Number Input","sourceData":2000.0,"isCustomField":false,"accessor":"delay_message","identifier":"delay_message","position":5.0,"originalIdentifier":"delay_message","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Delay Message"},"unknown_message":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.unknown_message))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"unknown_message","identifier":"unknown_message","position":6.0,"originalIdentifier":"unknown_message","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Unknown Message"},"listening_from_me":{"children":{},"dataType":"boolean","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.listening_from_me))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Switch","sourceData":false,"isCustomField":false,"accessor":"listening_from_me","identifier":"listening_from_me","position":7.0,"originalIdentifier":"listening_from_me","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","alignWidget":"LEFT","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Listening From Me"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Object","sourceData":{"enabled":true,"url":"https://bot.typebot.com","typebot":"bot-typebot","expire":20.0,"keyword_finish":"#SAIR","delay_message":3000.0,"unknown_message":"Mensagem não reconhecida2"},"isCustomField":false,"accessor":"__root_schema__","identifier":"__root_schema__","position":-1.0,"originalIdentifier":"__root_schema__","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":""}},"mobileBottomRow":41.0,"widgetName":"FormTypebot","submitButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.sign_msg.defaultValue"},{"key":"schema.__root_schema__.children.reopen_conversation.defaultValue"},{"key":"schema.__root_schema__.children.conversation_pending.defaultValue"},{"key":"schema.__root_schema__.children.account_id.defaultValue"},{"key":"schema.__root_schema__.children.webhook_url.defaultValue"},{"key":"schema.__root_schema__.children.enabled.defaultValue"},{"key":"schema.__root_schema__.children.listening_from_me.defaultValue"}],"displayName":"JSON Form","bottomRow":71.0,"fieldLimitExceeded":false,"parentRowSpace":10.0,"title":"Set Typebot","hideCard":false,"mobileRightColumn":25.0,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[{"key":"onSubmit"}],"borderWidth":"0","sourceData":"{\n \"enabled\": {{Find_Typebot.data.enabled || false}},\n \"url\": {{Find_Typebot.data.url}},\n \"typebot\": {{Find_Typebot.data.typebot}},\n \"expire\": {{Find_Typebot.data.expire}},\n \"keyword_finish\": {{Find_Typebot.data.keyword_finish}},\n \"delay_message\": {{Find_Typebot.data.delay_message}},\n \"unknown_message\": {{Find_Typebot.data.unknown_message}},\n \"listening_from_me\": {{Find_Typebot.data.listening_from_me}}\n \n}","resetButtonLabel":"Reset","key":"lgqqk5r1jk","backgroundColor":"#fff","isDeprecated":false,"rightColumn":63.0,"widgetId":"fyu0oxvlx7","minWidth":450.0,"parentId":"bvxewkusbf","renderMode":"CANVAS","mobileTopRow":0.0,"scrollContents":true,"responsiveBehavior":"fill","fixedFooter":true,"originalTopRow":1.0,"mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"minDynamicHeight":4.0}],"isDisabled":false,"key":"svq68rvpdn","isDeprecated":false,"rightColumn":430.5,"detachFromLayout":true,"widgetId":"bvxewkusbf","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"4n3m0wo9tx","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"6x3z5yow7u","height":730.0,"isDeprecated":false,"rightColumn":35.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"4n3m0wo9tx","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":46.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":11.0,"maxDynamicHeight":9000.0,"width":692.0,"minDynamicHeight":24.0},{"boxShadow":"none","mobileBottomRow":70.0,"widgetName":"ModalTypebotChangeSessionStatu","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":45.0,"bottomRow":415.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":35.0,"minHeight":370.0,"animateLoading":true,"parentColumnSpace":17.9375,"leftColumn":11.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas4CopyCopyCopyCopy","displayName":"Canvas","topRow":0.0,"bottomRow":370.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":730.0,"mobileRightColumn":430.5,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","borderColor":"#E0DEDE","iconSVG":"/static/media/icon.efac588608711d232f1c6c8a2144d2dd.svg","onSubmit":"{{Set_TypebotChangeSessionStatus.run().then(() => {\n showAlert('Typebot Change Session updated successfully', 'success');\n}).catch(() => {\n showAlert('Error updating Session Typebot', 'error');\n});\ncloseModal('ModalTypebotChangeSessionStatu');}}","topRow":1.0,"type":"JSON_FORM_WIDGET","animateLoading":true,"leftColumn":0.0,"dynamicBindingPathList":[{"key":"borderRadius"},{"key":"schema.__root_schema__.defaultValue"},{"key":"schema.__root_schema__.borderRadius"},{"key":"submitButtonStyles.buttonColor"},{"key":"schema.__root_schema__.cellBorderRadius"},{"key":"schema.__root_schema__.children.remoteJid.defaultValue"},{"key":"schema.__root_schema__.children.remoteJid.accentColor"},{"key":"schema.__root_schema__.children.remoteJid.borderRadius"},{"key":"schema.__root_schema__.children.status.defaultValue"},{"key":"schema.__root_schema__.children.status.accentColor"},{"key":"schema.__root_schema__.children.status.borderRadius"}],"showReset":false,"dynamicHeight":"AUTO_HEIGHT","autoGenerateForm":true,"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"SECONDARY"},"isVisible":true,"version":1.0,"isLoading":false,"submitButtonLabel":"Save","childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}},"disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","originalBottomRow":35.0,"useSourceData":false,"schema":{"__root_schema__":{"children":{"remoteJid":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.remoteJid))(FormTypebotChangeSessionStatus.sourceData, FormTypebotChangeSessionStatus.formData, FormTypebotChangeSessionStatus.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"remoteJid","identifier":"remoteJid","position":0.0,"originalIdentifier":"remoteJid","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebotChangeSessionStatus.sourceData, FormTypebotChangeSessionStatus.formData, FormTypebotChangeSessionStatus.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebotChangeSessionStatus.sourceData, FormTypebotChangeSessionStatus.formData, FormTypebotChangeSessionStatus.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":true,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Remote Jid (WhatsApp. Ex: 5511968162699@s.whatsapp.net)"},"status":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.status))(FormTypebotChangeSessionStatus.sourceData, FormTypebotChangeSessionStatus.formData, FormTypebotChangeSessionStatus.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"status","identifier":"status","position":1.0,"originalIdentifier":"status","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormTypebotChangeSessionStatus.sourceData, FormTypebotChangeSessionStatus.formData, FormTypebotChangeSessionStatus.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebotChangeSessionStatus.sourceData, FormTypebotChangeSessionStatus.formData, FormTypebotChangeSessionStatus.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Status (opened, paused or closed)"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","fieldType":"Object","sourceData":{"enabled":true,"url":"https://bot.typebot.com","typebot":"bot-typebot","expire":20.0,"keyword_finish":"#SAIR","delay_message":3000.0,"unknown_message":"Mensagem não reconhecida2"},"isCustomField":false,"accessor":"__root_schema__","identifier":"__root_schema__","position":-1.0,"originalIdentifier":"__root_schema__","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormTypebot.sourceData, FormTypebot.formData, FormTypebot.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":""}},"mobileBottomRow":41.0,"widgetName":"FormTypebotChangeSessionStatus","submitButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[{"key":"schema.__root_schema__.children.sign_msg.defaultValue"},{"key":"schema.__root_schema__.children.reopen_conversation.defaultValue"},{"key":"schema.__root_schema__.children.conversation_pending.defaultValue"},{"key":"schema.__root_schema__.children.account_id.defaultValue"},{"key":"schema.__root_schema__.children.webhook_url.defaultValue"}],"displayName":"JSON Form","bottomRow":35.0,"fieldLimitExceeded":false,"parentRowSpace":10.0,"title":"Typebot Change Session Status","hideCard":false,"mobileRightColumn":25.0,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[{"key":"onSubmit"}],"borderWidth":"0","sourceData":"{\n \"remoteJid\": \"@s.whatsapp.net\",\n \"status\": \"\"\n}","resetButtonLabel":"Reset","key":"lgqqk5r1jk","backgroundColor":"#fff","isDeprecated":false,"rightColumn":63.0,"widgetId":"28lli5jdvr","minWidth":450.0,"parentId":"8m0yhclt7g","renderMode":"CANVAS","mobileTopRow":0.0,"scrollContents":true,"responsiveBehavior":"fill","fixedFooter":true,"originalTopRow":1.0,"mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"minDynamicHeight":4.0}],"isDisabled":false,"key":"svq68rvpdn","isDeprecated":false,"rightColumn":430.5,"detachFromLayout":true,"widgetId":"8m0yhclt7g","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"84rj87eew6","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"6x3z5yow7u","height":370.0,"isDeprecated":false,"rightColumn":35.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"84rj87eew6","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":46.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":11.0,"maxDynamicHeight":9000.0,"width":692.0,"minDynamicHeight":24.0},{"resetFormOnClick":false,"boxShadow":"none","mobileBottomRow":50.0,"widgetName":"Button2","onClick":"{{Fetch_Instance.run();\nFetch_PrivacySettings.run();\nshowModal('ModalProfile');}}","buttonColor":"#2770fc","dynamicPropertyPathList":[{"key":"isVisible"}],"displayName":"Button","iconSVG":"/static/media/icon.7beb9123fb53027d9d6b778cdfe4caed.svg","searchTags":["click","submit"],"topRow":28.0,"bottomRow":32.0,"parentRowSpace":10.0,"type":"BUTTON_WIDGET","hideCard":false,"mobileRightColumn":21.0,"animateLoading":true,"parentColumnSpace":17.9375,"dynamicTriggerPathList":[{"key":"onClick"}],"leftColumn":1.0,"dynamicBindingPathList":[{"key":"borderRadius"},{"key":"isVisible"}],"text":"Edit Profile","isDisabled":false,"key":"zhd9fobc1z","isDeprecated":false,"rightColumn":13.0,"isDefaultClickDisabled":true,"iconName":"edit","widgetId":"uh6430ysqy","minWidth":120.0,"isVisible":"{{appsmith.store.api_key && appsmith.store.api_url ? TableInstances.selectedRow.instance ? TableInstances.selectedRow.Status === 'open' ? true : false : false : false}}","recaptchaType":"V3","version":1.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":46.0,"responsiveBehavior":"hug","originalTopRow":51.0,"disabledWhenInvalid":false,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":5.0,"originalBottomRow":55.0,"buttonVariant":"PRIMARY","iconAlign":"left","placement":"CENTER"},{"boxShadow":"none","mobileBottomRow":59.0,"widgetName":"ModalProfile","isCanvas":true,"displayName":"Modal","iconSVG":"/static/media/icon.d2ab7de0666eaef853cc2d330f86887b.svg","searchTags":["dialog","popup","notification"],"topRow":35.0,"bottomRow":975.0,"parentRowSpace":10.0,"type":"MODAL_WIDGET","hideCard":false,"shouldScrollContents":true,"mobileRightColumn":35.0,"minHeight":940.0,"animateLoading":true,"parentColumnSpace":17.9375,"leftColumn":11.0,"dynamicBindingPathList":[{"key":"borderRadius"}],"children":[{"mobileBottomRow":240.0,"widgetName":"Canvas5","displayName":"Canvas","topRow":0.0,"bottomRow":940.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"hideCard":true,"shouldScrollContents":false,"minHeight":240.0,"mobileRightColumn":430.5,"parentColumnSpace":1.0,"leftColumn":0.0,"dynamicBindingPathList":[],"children":[{"boxShadow":"none","borderColor":"#E0DEDE","iconSVG":"/static/media/icon.efac588608711d232f1c6c8a2144d2dd.svg","onSubmit":"{{Update_ProfileName.run().then(() => {\n showAlert('ProfileName successfully saved!', 'success');\n}).catch(() => {\n showAlert('Error updating ProfileName', 'error');\n});\nUpdate_ProfilePicture.run().then(() => {\n showAlert('ProfilePicture successfully saved!', 'success');\n}).catch(() => {\n showAlert('Error updating ProfilePicture', 'error');\n});\nUpdate_ProfileStatus.run().then(() => {\n showAlert('ProfileStatus successfully saved!', 'success');\n}).catch(() => {\n showAlert('Error updating ProfileStatus', 'error');\n});\nUpdate_PrivacySettings.run().then(() => {\n showAlert('PrivacySttings successfully saved!', 'success');\n}).catch(() => {\n showAlert('Error updating PrivacySttings', 'error');\n});\nfetch_Instances.run();\ncloseModal('ModalProfile');}}","topRow":0.0,"type":"JSON_FORM_WIDGET","animateLoading":true,"leftColumn":0.0,"dynamicBindingPathList":[{"key":"borderRadius"},{"key":"submitButtonStyles.buttonColor"},{"key":"submitButtonStyles.borderRadius"},{"key":"resetButtonStyles.buttonColor"},{"key":"resetButtonStyles.borderRadius"},{"key":"schema.__root_schema__.defaultValue"},{"key":"schema.__root_schema__.borderRadius"},{"key":"schema.__root_schema__.cellBorderRadius"},{"key":"schema.__root_schema__.children.profileName.defaultValue"},{"key":"schema.__root_schema__.children.profileName.accentColor"},{"key":"schema.__root_schema__.children.profileName.borderRadius"},{"key":"schema.__root_schema__.children.profileStatus.defaultValue"},{"key":"schema.__root_schema__.children.profileStatus.accentColor"},{"key":"schema.__root_schema__.children.profileStatus.borderRadius"},{"key":"schema.__root_schema__.children.profilePictureUrl.defaultValue"},{"key":"schema.__root_schema__.children.profilePictureUrl.borderRadius"},{"key":"sourceData"},{"key":"schema.__root_schema__.children.profilePictureUrl.accentColor"},{"key":"schema.__root_schema__.children.privacySettings.children.readreceipts.defaultValue"},{"key":"schema.__root_schema__.children.privacySettings.children.readreceipts.accentColor"},{"key":"schema.__root_schema__.children.privacySettings.children.readreceipts.borderRadius"},{"key":"schema.__root_schema__.children.privacySettings.children.profile.defaultValue"},{"key":"schema.__root_schema__.children.privacySettings.children.profile.accentColor"},{"key":"schema.__root_schema__.children.privacySettings.children.profile.borderRadius"},{"key":"schema.__root_schema__.children.privacySettings.children.status.defaultValue"},{"key":"schema.__root_schema__.children.privacySettings.children.status.accentColor"},{"key":"schema.__root_schema__.children.privacySettings.children.status.borderRadius"},{"key":"schema.__root_schema__.children.privacySettings.children.online.defaultValue"},{"key":"schema.__root_schema__.children.privacySettings.children.online.accentColor"},{"key":"schema.__root_schema__.children.privacySettings.children.online.borderRadius"},{"key":"schema.__root_schema__.children.privacySettings.children.last.defaultValue"},{"key":"schema.__root_schema__.children.privacySettings.children.last.accentColor"},{"key":"schema.__root_schema__.children.privacySettings.children.last.borderRadius"},{"key":"schema.__root_schema__.children.privacySettings.children.groupadd.defaultValue"},{"key":"schema.__root_schema__.children.privacySettings.children.groupadd.accentColor"},{"key":"schema.__root_schema__.children.privacySettings.children.groupadd.borderRadius"},{"key":"schema.__root_schema__.children.privacySettings.defaultValue"},{"key":"schema.__root_schema__.children.privacySettings.borderRadius"},{"key":"schema.__root_schema__.children.privacySettings.cellBorderRadius"}],"showReset":false,"dynamicHeight":"AUTO_HEIGHT","autoGenerateForm":true,"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"SECONDARY"},"isVisible":true,"version":1.0,"isLoading":false,"submitButtonLabel":"Save","childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}},"disabledWhenInvalid":true,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","originalBottomRow":92.0,"useSourceData":false,"schema":{"__root_schema__":{"children":{"profileName":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.profileName))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"profileName","identifier":"profileName","position":1.0,"originalIdentifier":"profileName","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Profile Name"},"profileStatus":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.profileStatus))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Text Input","sourceData":"","isCustomField":false,"accessor":"profileStatus","identifier":"profileStatus","position":2.0,"originalIdentifier":"profileStatus","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Profile Status"},"profilePictureUrl":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.profilePictureUrl))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Text Input","sourceData":"https://pps.whatsapp.net/v/t61.24694-24/359816109_329991892684302_7466658594467953893_n.jpg?ccb=11-4&oh=01_AdTpgc4O-xiZDr2v0OLu_jssxaw8dsws819srLMOzUwEnw&oe=64D3C41E","isCustomField":false,"accessor":"profilePictureUrl","identifier":"profilePictureUrl","position":0.0,"originalIdentifier":"profilePictureUrl","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","iconAlign":"left","isDisabled":false,"isRequired":false,"isSpellCheck":false,"isVisible":true,"labelTextSize":"0.875rem","label":"Profile Picture Url"},"privacySettings":{"children":{"readreceipts":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.privacySettings.readreceipts))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Select","sourceData":"all","isCustomField":false,"accessor":"readreceipts","identifier":"readreceipts","position":0.0,"originalIdentifier":"readreceipts","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Readreceipts","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n {\n \"label\": \"all\",\n \"value\": \"all\"\n },\n {\n \"label\": \"none\",\n \"value\": \"none\"\n }\n]"},"profile":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.privacySettings.profile))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Select","sourceData":"all","isCustomField":false,"accessor":"profile","identifier":"profile","position":1.0,"originalIdentifier":"profile","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Profile","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n {\n \"label\": \"all\",\n \"value\": \"all\"\n },\n {\n \"label\": \"contacts\",\n \"value\": \"contacts\"\n },\n {\n \"label\": \"contact_blacklist\",\n \"value\": \"contact_blacklist\"\n },\n {\n \"label\": \"none\",\n \"value\": \"none\"\n }\n]"},"status":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.privacySettings.status))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Select","sourceData":"contacts","isCustomField":false,"accessor":"status","identifier":"status","position":2.0,"originalIdentifier":"status","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Status","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n {\n \"label\": \"all\",\n \"value\": \"all\"\n },\n {\n \"label\": \"contacts\",\n \"value\": \"contacts\"\n },\n {\n \"label\": \"contact_blacklist\",\n \"value\": \"contact_blacklist\"\n },\n {\n \"label\": \"none\",\n \"value\": \"none\"\n }\n]"},"online":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.privacySettings.online))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Select","sourceData":"all","isCustomField":false,"accessor":"online","identifier":"online","position":3.0,"originalIdentifier":"online","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Online","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n {\n \"label\": \"all\",\n \"value\": \"all\"\n },\n {\n \"label\": \"match_last_seen\",\n \"value\": \"match_last_seen\"\n }\n]"},"last":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.privacySettings.last))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Select","sourceData":"contacts","isCustomField":false,"accessor":"last","identifier":"last","position":4.0,"originalIdentifier":"last","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Last","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n {\n \"label\": \"all\",\n \"value\": \"all\"\n },\n {\n \"label\": \"contacts\",\n \"value\": \"contacts\"\n },\n {\n \"label\": \"contact_blacklist\",\n \"value\": \"contact_blacklist\"\n },\n {\n \"label\": \"none\",\n \"value\": \"none\"\n }\n]"},"groupadd":{"children":{},"dataType":"string","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.privacySettings.groupadd))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Select","sourceData":"all","isCustomField":false,"accessor":"groupadd","identifier":"groupadd","position":5.0,"originalIdentifier":"groupadd","accentColor":"{{((sourceData, formData, fieldState) => ((appsmith.theme.colors.primaryColor)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","isDisabled":false,"isFilterable":false,"isRequired":false,"isVisible":true,"label":"Groupadd","labelTextSize":"0.875rem","serverSideFiltering":false,"options":"[\n {\n \"label\": \"all\",\n \"value\": \"all\"\n },\n {\n \"label\": \"contacts\",\n \"value\": \"contacts\"\n },\n {\n \"label\": \"contact_blacklist\",\n \"value\": \"contact_blacklist\"\n },\n {\n \"label\": \"none\",\n \"value\": \"none\"\n }\n]"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData.privacySettings))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Object","sourceData":{"readreceipts":"all","profile":"all","status":"contacts","online":"all","last":"contacts","groupadd":"all"},"isCustomField":false,"accessor":"privacySettings","identifier":"privacySettings","position":3.0,"originalIdentifier":"privacySettings","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"1rem","label":"Privacy Settings","labelStyle":"BOLD"}},"dataType":"object","defaultValue":"{{((sourceData, formData, fieldState) => (sourceData))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","fieldType":"Object","sourceData":{"name":"John","date_of_birth":"20/02/1990","employee_id":1001.0},"isCustomField":false,"accessor":"__root_schema__","identifier":"__root_schema__","position":-1.0,"originalIdentifier":"__root_schema__","borderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","boxShadow":"none","cellBorderRadius":"{{((sourceData, formData, fieldState) => ((appsmith.theme.borderRadius.appBorderRadius)))(FormProfile.sourceData, FormProfile.formData, FormProfile.fieldState)}}","cellBoxShadow":"none","isDisabled":false,"isRequired":false,"isVisible":true,"labelTextSize":"0.875rem","label":""}},"mobileBottomRow":41.0,"widgetName":"FormProfile","submitButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","buttonVariant":"PRIMARY"},"dynamicPropertyPathList":[],"displayName":"JSON Form","bottomRow":92.0,"fieldLimitExceeded":false,"parentRowSpace":10.0,"title":"Edit Profile","hideCard":false,"mobileRightColumn":25.0,"parentColumnSpace":6.9375,"dynamicTriggerPathList":[{"key":"onSubmit"}],"borderWidth":"0","sourceData":"{\n\t\"profilePictureUrl\": \"{{Fetch_Instance.data.instance.profilePictureUrl}}\",\n\t\"profileName\": \"{{Fetch_Instance.data.instance.profileName}}\",\n\t\"profileStatus\": \"{{Fetch_Instance.data.instance.profileStatus}}\",\n\t\"privacySettings\": {\n \"readreceipts\": {{Fetch_PrivacySettings.data.readreceipts}},\n \"profile\": {{Fetch_PrivacySettings.data.profile}},\n \"status\": {{Fetch_PrivacySettings.data.status}},\n \"online\": {{Fetch_PrivacySettings.data.online}},\n \"last\": {{Fetch_PrivacySettings.data.last}},\n \"groupadd\": {{Fetch_PrivacySettings.data.groupadd}}\n\t\t}\n}","resetButtonLabel":"","key":"72nqor459k","backgroundColor":"#fff","isDeprecated":false,"rightColumn":64.0,"widgetId":"hguxefink2","minWidth":450.0,"parentId":"basosxf5qt","renderMode":"CANVAS","mobileTopRow":0.0,"scrollContents":true,"responsiveBehavior":"fill","fixedFooter":true,"originalTopRow":0.0,"mobileLeftColumn":0.0,"maxDynamicHeight":9000.0,"minDynamicHeight":4.0}],"isDisabled":false,"key":"mepf0qsn1e","isDeprecated":false,"rightColumn":430.5,"detachFromLayout":true,"widgetId":"basosxf5qt","minWidth":450.0,"isVisible":true,"version":1.0,"parentId":"ss96aihlej","renderMode":"CANVAS","isLoading":false,"mobileTopRow":0.0,"responsiveBehavior":"fill","mobileLeftColumn":0.0,"flexLayers":[]}],"key":"4ktj7iym0b","height":940.0,"isDeprecated":false,"rightColumn":35.0,"detachFromLayout":true,"dynamicHeight":"AUTO_HEIGHT","widgetId":"ss96aihlej","canOutsideClickClose":true,"canEscapeKeyClose":true,"version":2.0,"parentId":"0","renderMode":"CANVAS","isLoading":false,"mobileTopRow":35.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":11.0,"maxDynamicHeight":9000.0,"width":456.0,"minDynamicHeight":24.0},{"mobileBottomRow":47.0,"widgetName":"Text6","displayName":"Text","iconSVG":"/static/media/icon.a47d6d5dbbb718c4dc4b2eb4f218c1b7.svg","searchTags":["typography","paragraph","label"],"topRow":43.0,"bottomRow":47.0,"parentRowSpace":10.0,"type":"TEXT_WIDGET","hideCard":false,"mobileRightColumn":31.0,"animateLoading":true,"overflow":"NONE","fontFamily":"{{appsmith.theme.fontFamily.appFont}}","parentColumnSpace":12.3125,"dynamicTriggerPathList":[],"leftColumn":15.0,"dynamicBindingPathList":[{"key":"truncateButtonColor"},{"key":"fontFamily"},{"key":"borderRadius"}],"shouldTruncate":false,"truncateButtonColor":"{{appsmith.theme.colors.primaryColor}}","text":"This evolution api instance management panel is compatible from version 1.5 or higher\n","key":"vpoi1p6qvn","isDeprecated":false,"rightColumn":63.0,"textAlign":"LEFT","dynamicHeight":"AUTO_HEIGHT","widgetId":"yfenuu2x36","minWidth":450.0,"isVisible":true,"fontStyle":"BOLD","textColor":"#ef4444","version":1.0,"parentId":"0","tags":["Suggested","Content"],"renderMode":"CANVAS","isLoading":false,"mobileTopRow":43.0,"responsiveBehavior":"fill","originalTopRow":43.0,"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","mobileLeftColumn":15.0,"maxDynamicHeight":9000.0,"originalBottomRow":48.0,"fontSize":"0.875rem","minDynamicHeight":4.0}]},"layoutOnLoadActions":[[{"id":"Home_Scripts.verifyConfig","name":"Scripts.verifyConfig","collectionId":"Home_Scripts","clientSideExecution":true,"confirmBeforeExecute":false,"pluginType":"JS","jsonPathKeys":[],"timeoutInMillisecond":10000.0}],[{"id":"Home_Find_Rabbitmq","name":"Find_Rabbitmq","confirmBeforeExecute":false,"pluginType":"API","jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"timeoutInMillisecond":10000.0},{"id":"Home_Find_Websocket","name":"Find_Websocket","confirmBeforeExecute":false,"pluginType":"API","jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"timeoutInMillisecond":10000.0}]],"layoutOnLoadActionErrors":[],"validOnPageLoadActions":true,"id":"Home","deleted":false,"policies":[],"userPermissions":[]}],"userPermissions":[],"policies":[],"isHidden":false},"deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b37fa2945b083c5bc7b0"}],"actionList":[{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Restart","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/instance/restart/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{appsmith.store.api_key}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"","bodyFormData":[],"httpMethod":"PUT","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url","appsmith.store.api_key"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T03:01:05Z"},"publishedAction":{"name":"Restart","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/instance/restart/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{appsmith.store.api_key}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"","bodyFormData":[],"httpMethod":"PUT","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url","appsmith.store.api_key"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T03:01:05Z"},"id":"Home_Restart","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b37fa2945b083c5bc7b4"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Create_Instance","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/instance/create","headers":[{"key":"apikey","value":"{{appsmith.store.api_key}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\t{\n\t\t\"instanceName\": FormInstance.formData.instance.instanceName,\n\t\t\"token\": FormInstance.formData.instance.token,\n\t\t\"qrcode\": FormInstance.formData.instance.qrcode,\n\t\t\"webhook\": FormInstance.formData.webhook.webhook,\n\t\t\"webhook_by_events\": FormInstance.formData.webhook.webhook_by_events,\n\t\t\"websocket_enabled\": FormInstance.formData.websocket.websocket_enabled,\n\t\t\"websocket_events\": FormInstance.formData.websocket.websocket_events,\n\t\t\"rabbitmq_enabled\": FormInstance.formData.websocket.rabbitmq_enabled,\n\t\t\"rabbitmq_events\": FormInstance.formData.websocket.rabbitmq_events,\n\t\t\"events\": FormInstance.formData.webhook.events,\n\t\t\"reject_call\": FormInstance.formData.settings.reject_call,\n\t\t\"msg_call\": FormInstance.formData.settings.msg_call,\n\t\t\"groups_ignore\": FormInstance.formData.settings.groups_ignore,\n\t\t\"always_online\": FormInstance.formData.settings.always_online,\n\t\t\"read_messages\": FormInstance.formData.settings.read_messages,\n\t\t\"read_status\": FormInstance.formData.settings.read_status,\n\t\t\"chatwoot_account_id\": FormInstance.formData.chatwoot.chatwoot_account_id,\n\t\t\"chatwoot_token\": FormInstance.formData.chatwoot.chatwoot_token,\n\t\t\"chatwoot_url\": FormInstance.formData.chatwoot.chatwoot_url,\n\t\t\"chatwoot_sign_msg\": FormInstance.formData.chatwoot.chatwoot_sign_msg,\n\t\t\"chatwoot_reopen_conversation\": FormInstance.formData.chatwoot.chatwoot_reopen_conversation,\n\t\t\"chatwoot_conversation_pending\": FormInstance.formData.chatwoot.chatwoot_conversation_pending\n\t}\n}}","bodyFormData":[{"key":"instanceName","value":"{{FormInstance.data.InputNewInstanceName}}"},{"key":"token","value":"{{FormInstance.data.InputNewInstanceToken}}"}],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"application/json"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"},{"key":"bodyFormData[0].value"},{"key":"bodyFormData[1].value"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["\n\t{\n\t\t\"instanceName\": FormInstance.formData.instance.instanceName,\n\t\t\"token\": FormInstance.formData.instance.token,\n\t\t\"qrcode\": FormInstance.formData.instance.qrcode,\n\t\t\"webhook\": FormInstance.formData.webhook.webhook,\n\t\t\"webhook_by_events\": FormInstance.formData.webhook.webhook_by_events,\n\t\t\"websocket_enabled\": FormInstance.formData.websocket.websocket_enabled,\n\t\t\"websocket_events\": FormInstance.formData.websocket.websocket_events,\n\t\t\"rabbitmq_enabled\": FormInstance.formData.websocket.rabbitmq_enabled,\n\t\t\"rabbitmq_events\": FormInstance.formData.websocket.rabbitmq_events,\n\t\t\"events\": FormInstance.formData.webhook.events,\n\t\t\"reject_call\": FormInstance.formData.settings.reject_call,\n\t\t\"msg_call\": FormInstance.formData.settings.msg_call,\n\t\t\"groups_ignore\": FormInstance.formData.settings.groups_ignore,\n\t\t\"always_online\": FormInstance.formData.settings.always_online,\n\t\t\"read_messages\": FormInstance.formData.settings.read_messages,\n\t\t\"read_status\": FormInstance.formData.settings.read_status,\n\t\t\"chatwoot_account_id\": FormInstance.formData.chatwoot.chatwoot_account_id,\n\t\t\"chatwoot_token\": FormInstance.formData.chatwoot.chatwoot_token,\n\t\t\"chatwoot_url\": FormInstance.formData.chatwoot.chatwoot_url,\n\t\t\"chatwoot_sign_msg\": FormInstance.formData.chatwoot.chatwoot_sign_msg,\n\t\t\"chatwoot_reopen_conversation\": FormInstance.formData.chatwoot.chatwoot_reopen_conversation,\n\t\t\"chatwoot_conversation_pending\": FormInstance.formData.chatwoot.chatwoot_conversation_pending\n\t}\n","FormInstance.data.InputNewInstanceName","FormInstance.data.InputNewInstanceToken","appsmith.store.api_url","appsmith.store.api_key"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T03:22:09Z"},"publishedAction":{"name":"Create_Instance","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/instance/create","headers":[{"key":"apikey","value":"{{appsmith.store.api_key}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\t{\n\t\t\"instanceName\": FormInstance.formData.instance.instanceName,\n\t\t\"token\": FormInstance.formData.instance.token,\n\t\t\"qrcode\": FormInstance.formData.instance.qrcode,\n\t\t\"webhook\": FormInstance.formData.webhook.webhook,\n\t\t\"webhook_by_events\": FormInstance.formData.webhook.webhook_by_events,\n\t\t\"websocket_enabled\": FormInstance.formData.websocket.websocket_enabled,\n\t\t\"websocket_events\": FormInstance.formData.websocket.websocket_events,\n\t\t\"rabbitmq_enabled\": FormInstance.formData.websocket.rabbitmq_enabled,\n\t\t\"rabbitmq_events\": FormInstance.formData.websocket.rabbitmq_events,\n\t\t\"events\": FormInstance.formData.webhook.events,\n\t\t\"reject_call\": FormInstance.formData.settings.reject_call,\n\t\t\"msg_call\": FormInstance.formData.settings.msg_call,\n\t\t\"groups_ignore\": FormInstance.formData.settings.groups_ignore,\n\t\t\"always_online\": FormInstance.formData.settings.always_online,\n\t\t\"read_messages\": FormInstance.formData.settings.read_messages,\n\t\t\"read_status\": FormInstance.formData.settings.read_status,\n\t\t\"chatwoot_account_id\": FormInstance.formData.chatwoot.chatwoot_account_id,\n\t\t\"chatwoot_token\": FormInstance.formData.chatwoot.chatwoot_token,\n\t\t\"chatwoot_url\": FormInstance.formData.chatwoot.chatwoot_url,\n\t\t\"chatwoot_sign_msg\": FormInstance.formData.chatwoot.chatwoot_sign_msg,\n\t\t\"chatwoot_reopen_conversation\": FormInstance.formData.chatwoot.chatwoot_reopen_conversation,\n\t\t\"chatwoot_conversation_pending\": FormInstance.formData.chatwoot.chatwoot_conversation_pending\n\t}\n}}","bodyFormData":[{"key":"instanceName","value":"{{FormInstance.data.InputNewInstanceName}}"},{"key":"token","value":"{{FormInstance.data.InputNewInstanceToken}}"}],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"application/json"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"},{"key":"bodyFormData[0].value"},{"key":"bodyFormData[1].value"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["\n\t{\n\t\t\"instanceName\": FormInstance.formData.instance.instanceName,\n\t\t\"token\": FormInstance.formData.instance.token,\n\t\t\"qrcode\": FormInstance.formData.instance.qrcode,\n\t\t\"webhook\": FormInstance.formData.webhook.webhook,\n\t\t\"webhook_by_events\": FormInstance.formData.webhook.webhook_by_events,\n\t\t\"websocket_enabled\": FormInstance.formData.websocket.websocket_enabled,\n\t\t\"websocket_events\": FormInstance.formData.websocket.websocket_events,\n\t\t\"rabbitmq_enabled\": FormInstance.formData.websocket.rabbitmq_enabled,\n\t\t\"rabbitmq_events\": FormInstance.formData.websocket.rabbitmq_events,\n\t\t\"events\": FormInstance.formData.webhook.events,\n\t\t\"reject_call\": FormInstance.formData.settings.reject_call,\n\t\t\"msg_call\": FormInstance.formData.settings.msg_call,\n\t\t\"groups_ignore\": FormInstance.formData.settings.groups_ignore,\n\t\t\"always_online\": FormInstance.formData.settings.always_online,\n\t\t\"read_messages\": FormInstance.formData.settings.read_messages,\n\t\t\"read_status\": FormInstance.formData.settings.read_status,\n\t\t\"chatwoot_account_id\": FormInstance.formData.chatwoot.chatwoot_account_id,\n\t\t\"chatwoot_token\": FormInstance.formData.chatwoot.chatwoot_token,\n\t\t\"chatwoot_url\": FormInstance.formData.chatwoot.chatwoot_url,\n\t\t\"chatwoot_sign_msg\": FormInstance.formData.chatwoot.chatwoot_sign_msg,\n\t\t\"chatwoot_reopen_conversation\": FormInstance.formData.chatwoot.chatwoot_reopen_conversation,\n\t\t\"chatwoot_conversation_pending\": FormInstance.formData.chatwoot.chatwoot_conversation_pending\n\t}\n","FormInstance.data.InputNewInstanceName","FormInstance.data.InputNewInstanceToken","appsmith.store.api_url","appsmith.store.api_key"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T03:22:09Z"},"id":"Home_Create_Instance","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b37fa2945b083c5bc7b3"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Find_Chatwoot","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/chatwoot/find/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":true,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T19:49:33Z"},"publishedAction":{"name":"Find_Chatwoot","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/chatwoot/find/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":true,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T19:49:33Z"},"id":"Home_Find_Chatwoot","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b37fa2945b083c5bc7b5"},{"pluginType":"JS","pluginId":"js-plugin","unpublishedAction":{"name":"verifyConfig","fullyQualifiedName":"Scripts.verifyConfig","datasource":{"name":"UNUSED_DATASOURCE","pluginId":"js-plugin","invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","collectionId":"Home_Scripts","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","encodeParamsToggle":true,"body":"async function () {\n const api_url = await appsmith.store.api_url;\n const api_key = await appsmith.store.api_key;\n if (!api_url && !api_key) {\n showModal('ModalConfig');\n return false;\n }\n fetch_Instances.run();\n Find_Webhook.run();\n Find_Settings.run();\n Find_Chatwoot.run();\n return true;\n}","selfReferencingDataPaths":[],"jsArguments":[],"isAsync":true},"executeOnLoad":true,"clientSideExecution":true,"dynamicBindingPathList":[{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":[],"userSetOnLoad":true,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-29T16:12:42Z"},"publishedAction":{"name":"verifyConfig","fullyQualifiedName":"Scripts.verifyConfig","datasource":{"name":"UNUSED_DATASOURCE","pluginId":"js-plugin","invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","collectionId":"Home_Scripts","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","encodeParamsToggle":true,"body":"async function () {\n const api_url = await appsmith.store.api_url;\n const api_key = await appsmith.store.api_key;\n if (!api_url && !api_key) {\n showModal('ModalConfig');\n return false;\n }\n fetch_Instances.run();\n Find_Webhook.run();\n Find_Settings.run();\n Find_Chatwoot.run();\n return true;\n}","selfReferencingDataPaths":[],"jsArguments":[],"isAsync":true},"executeOnLoad":true,"clientSideExecution":true,"dynamicBindingPathList":[{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":[],"userSetOnLoad":true,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-29T16:12:42Z"},"id":"Home_Scripts.verifyConfig","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b37fa2945b083c5bc7b2"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Find_Settings","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/settings/find/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":true,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T19:48:45Z"},"publishedAction":{"name":"Find_Settings","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/settings/find/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":true,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T19:48:45Z"},"id":"Home_Find_Settings","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b37fa2945b083c5bc7b9"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"fetch_Instances","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/instance/fetchInstances","headers":[{"key":"apikey","value":"{{appsmith.store.api_key}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["appsmith.store.api_url","appsmith.store.api_key"],"userSetOnLoad":true,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-29T16:12:42Z"},"publishedAction":{"name":"fetch_Instances","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/instance/fetchInstances","headers":[{"key":"apikey","value":"{{appsmith.store.api_key}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["appsmith.store.api_url","appsmith.store.api_key"],"userSetOnLoad":true,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-29T16:12:42Z"},"id":"Home_fetch_Instances","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b37fa2945b083c5bc7b6"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Connect","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/instance/connect/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{appsmith.store.api_key}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url","appsmith.store.api_key"],"userSetOnLoad":true,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-29T16:12:42Z"},"publishedAction":{"name":"Connect","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/instance/connect/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{appsmith.store.api_key}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url","appsmith.store.api_key"],"userSetOnLoad":true,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-29T16:12:42Z"},"id":"Home_Connect","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b37fa2945b083c5bc7ba"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Delete","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/instance/delete/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{appsmith.store.api_key}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"","bodyFormData":[],"httpMethod":"DELETE","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url","appsmith.store.api_key"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T03:02:32Z"},"publishedAction":{"name":"Delete","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/instance/delete/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{appsmith.store.api_key}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"","bodyFormData":[],"httpMethod":"DELETE","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url","appsmith.store.api_key"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T03:02:32Z"},"id":"Home_Delete","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b37fa2945b083c5bc7b7"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Logout","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/instance/logout/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{appsmith.store.api_key}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"","bodyFormData":[],"httpMethod":"DELETE","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url","appsmith.store.api_key"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T03:02:00Z"},"publishedAction":{"name":"Logout","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/instance/logout/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{appsmith.store.api_key}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"","bodyFormData":[],"httpMethod":"DELETE","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url","appsmith.store.api_key"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T03:02:00Z"},"id":"Home_Logout","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b37fa2945b083c5bc7b8"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Find_Webhook","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/webhook/find/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":true,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T19:46:50Z"},"publishedAction":{"name":"Find_Webhook","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/webhook/find/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":true,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T19:46:50Z"},"id":"Home_Find_Webhook","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b37fa2945b083c5bc7c5"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Find_Rabbitmq","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/rabbitmq/find/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":true,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-09-20T22:28:47Z"},"publishedAction":{"name":"Find_Rabbitmq","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/rabbitmq/find/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":true,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-09-20T22:28:47Z"},"id":"Home_Find_Rabbitmq","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b37fa2945b083c5bc7c1"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Set_Websocket","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/websocket/set/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\tFormWebsocket.formData\n}}","bodyFormData":[],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","\n\tFormWebsocket.formData\n","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-08-03T00:55:30Z"},"publishedAction":{"name":"Set_Websocket","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/websocket/set/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\tFormWebsocket.formData\n}}","bodyFormData":[],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","\n\tFormWebsocket.formData\n","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-08-03T00:55:30Z"},"id":"Home_Set_Websocket","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b37fa2945b083c5bc7bd"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Update_ProfileName","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/chat/updateProfileName/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\t{\n\t\t\"name\": FormProfile.formData.profileName\n\t}\n}}","bodyFormData":[],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","\n\t{\n\t\t\"name\": FormProfile.formData.profileName\n\t}\n","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-31T12:22:45Z"},"publishedAction":{"name":"Update_ProfileName","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/chat/updateProfileName/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\t{\n\t\t\"name\": FormProfile.formData.profileName\n\t}\n}}","bodyFormData":[],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","\n\t{\n\t\t\"name\": FormProfile.formData.profileName\n\t}\n","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-31T12:22:45Z"},"id":"Home_Update_ProfileName","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b37fa2945b083c5bc7bb"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Update_ProfileStatus","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/chat/updateProfileStatus/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\t{\n\t\t\"status\": FormProfile.formData.profileStatus\n\t}\n}}","bodyFormData":[],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"application/json"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"body"},{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","\n\t{\n\t\t\"status\": FormProfile.formData.profileStatus\n\t}\n","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-31T12:25:00Z"},"publishedAction":{"name":"Update_ProfileStatus","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/chat/updateProfileStatus/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\t{\n\t\t\"status\": FormProfile.formData.profileStatus\n\t}\n}}","bodyFormData":[],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"application/json"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"body"},{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","\n\t{\n\t\t\"status\": FormProfile.formData.profileStatus\n\t}\n","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-31T12:25:00Z"},"id":"Home_Update_ProfileStatus","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b37fa2945b083c5bc7c6"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Set_Settings","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/settings/set/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\tFormSettings.formData\n}}","bodyFormData":[],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"application/json"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url","\n\tFormSettings.formData\n"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T20:13:25Z"},"publishedAction":{"name":"Set_Settings","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/settings/set/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\tFormSettings.formData\n}}","bodyFormData":[],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"application/json"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url","\n\tFormSettings.formData\n"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T20:13:25Z"},"id":"Home_Set_Settings","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b380a2945b083c5bc7ce"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Set_Chatwoot","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/chatwoot/set/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\t{\n\t\t\"enabled\": FormChatwoot.formData.enabled,\n\t\t\"account_id\": String(FormChatwoot.formData.account_id),\n\t\t\"token\": FormChatwoot.formData.token,\n\t\t\"url\": FormChatwoot.formData.url,\n\t\t\"sign_msg\": FormChatwoot.formData.sign_msg,\n\t\t\"reopen_conversation\": FormChatwoot.formData.reopen_conversation,\n\t\t\"conversation_pending\": FormChatwoot.formData.conversation_pending\n\t}\n}}","bodyFormData":[],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","\n\t{\n\t\t\"enabled\": FormChatwoot.formData.enabled,\n\t\t\"account_id\": String(FormChatwoot.formData.account_id),\n\t\t\"token\": FormChatwoot.formData.token,\n\t\t\"url\": FormChatwoot.formData.url,\n\t\t\"sign_msg\": FormChatwoot.formData.sign_msg,\n\t\t\"reopen_conversation\": FormChatwoot.formData.reopen_conversation,\n\t\t\"conversation_pending\": FormChatwoot.formData.conversation_pending\n\t}\n","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T20:15:01Z"},"publishedAction":{"name":"Set_Chatwoot","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/chatwoot/set/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\t{\n\t\t\"enabled\": FormChatwoot.formData.enabled,\n\t\t\"account_id\": String(FormChatwoot.formData.account_id),\n\t\t\"token\": FormChatwoot.formData.token,\n\t\t\"url\": FormChatwoot.formData.url,\n\t\t\"sign_msg\": FormChatwoot.formData.sign_msg,\n\t\t\"reopen_conversation\": FormChatwoot.formData.reopen_conversation,\n\t\t\"conversation_pending\": FormChatwoot.formData.conversation_pending\n\t}\n}}","bodyFormData":[],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","\n\t{\n\t\t\"enabled\": FormChatwoot.formData.enabled,\n\t\t\"account_id\": String(FormChatwoot.formData.account_id),\n\t\t\"token\": FormChatwoot.formData.token,\n\t\t\"url\": FormChatwoot.formData.url,\n\t\t\"sign_msg\": FormChatwoot.formData.sign_msg,\n\t\t\"reopen_conversation\": FormChatwoot.formData.reopen_conversation,\n\t\t\"conversation_pending\": FormChatwoot.formData.conversation_pending\n\t}\n","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T20:15:01Z"},"id":"Home_Set_Chatwoot","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b380a2945b083c5bc7d0"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Fetch_Instance","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/instance/fetchInstances","headers":[{"key":"apikey","value":"{{appsmith.store.api_key}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[{"key":"instanceName","value":"{{TableInstances.selectedRow.instance}}"}],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"queryParameters[0].value"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["appsmith.store.api_url","appsmith.store.api_key","TableInstances.selectedRow.instance"],"userSetOnLoad":true,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-31T12:16:40Z"},"publishedAction":{"name":"Fetch_Instance","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/instance/fetchInstances","headers":[{"key":"apikey","value":"{{appsmith.store.api_key}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[{"key":"instanceName","value":"{{TableInstances.selectedRow.instance}}"}],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"queryParameters[0].value"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["appsmith.store.api_url","appsmith.store.api_key","TableInstances.selectedRow.instance"],"userSetOnLoad":true,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-31T12:16:40Z"},"id":"Home_Fetch_Instance","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b380a2945b083c5bc7cf"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Remove_ProfilePicture","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/chat/removeProfilePicture/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"","bodyFormData":[],"httpMethod":"DELETE","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-31T12:27:20Z"},"publishedAction":{"name":"Remove_ProfilePicture","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/chat/removeProfilePicture/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"","bodyFormData":[],"httpMethod":"DELETE","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-31T12:27:20Z"},"id":"Home_Remove_ProfilePicture","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b380a2945b083c5bc7d4"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Set_Webhook","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/webhook/set/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\tFormWebhook.formData\n}}","bodyFormData":[],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","\n\tFormWebhook.formData\n","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T20:10:19Z"},"publishedAction":{"name":"Set_Webhook","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/webhook/set/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\tFormWebhook.formData\n}}","bodyFormData":[],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","\n\tFormWebhook.formData\n","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-30T20:10:19Z"},"id":"Home_Set_Webhook","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b380a2945b083c5bc7d5"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Update_ProfilePicture","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/chat/updateProfilePicture/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\t{\n\t\t\"picture\": FormProfile.formData.profilePictureUrl\n\t}\n}}","bodyFormData":[],"httpMethod":"PUT","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","\n\t{\n\t\t\"picture\": FormProfile.formData.profilePictureUrl\n\t}\n","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-31T12:25:56Z"},"publishedAction":{"name":"Update_ProfilePicture","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/chat/updateProfilePicture/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\t{\n\t\t\"picture\": FormProfile.formData.profilePictureUrl\n\t}\n}}","bodyFormData":[],"httpMethod":"PUT","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","\n\t{\n\t\t\"picture\": FormProfile.formData.profilePictureUrl\n\t}\n","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-31T12:25:56Z"},"id":"Home_Update_ProfilePicture","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b380a2945b083c5bc7d1"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Set_TypebotChangeSessionStatus","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/typebot/changeStatus/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n{\n \"remoteJid\": FormTypebotChangeSessionStatus.formData.remoteJid,\n \"status\": FormTypebotChangeSessionStatus.formData.status\n}\n}}","bodyFormData":[],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"headers[0].value"},{"key":"path"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","\n{\n \"remoteJid\": FormTypebotChangeSessionStatus.formData.remoteJid,\n \"status\": FormTypebotChangeSessionStatus.formData.status\n}\n","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-08-19T11:28:01Z"},"publishedAction":{"name":"Set_TypebotChangeSessionStatus","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/typebot/changeStatus/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n{\n \"remoteJid\": FormTypebotChangeSessionStatus.formData.remoteJid,\n \"status\": FormTypebotChangeSessionStatus.formData.status\n}\n}}","bodyFormData":[],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"headers[0].value"},{"key":"path"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","\n{\n \"remoteJid\": FormTypebotChangeSessionStatus.formData.remoteJid,\n \"status\": FormTypebotChangeSessionStatus.formData.status\n}\n","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-08-19T11:28:01Z"},"id":"Home_Set_TypebotChangeSessionStatus","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b380a2945b083c5bc7d2"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Set_Typebot","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/typebot/set/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\t{\n\t\t\"enabled\": FormTypebot.formData.enabled,\n\t\t\"url\": (FormTypebot.formData.url),\n\t\t\"typebot\": FormTypebot.formData.typebot,\n\t\t\"expire\": FormTypebot.formData.expire,\n\t\t\"keyword_finish\": FormTypebot.formData.keyword_finish,\n\t\t\"delay_message\": FormTypebot.formData.delay_message,\n\t\t\"unknown_message\": FormTypebot.formData.unknown_message,\n\t\t\"listening_from_me\": FormTypebot.formData.listening_from_me\n\t}\n}}","bodyFormData":[],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"headers[0].value"},{"key":"path"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","\n\t{\n\t\t\"enabled\": FormTypebot.formData.enabled,\n\t\t\"url\": (FormTypebot.formData.url),\n\t\t\"typebot\": FormTypebot.formData.typebot,\n\t\t\"expire\": FormTypebot.formData.expire,\n\t\t\"keyword_finish\": FormTypebot.formData.keyword_finish,\n\t\t\"delay_message\": FormTypebot.formData.delay_message,\n\t\t\"unknown_message\": FormTypebot.formData.unknown_message,\n\t\t\"listening_from_me\": FormTypebot.formData.listening_from_me\n\t}\n","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-08-19T05:00:46Z"},"publishedAction":{"name":"Set_Typebot","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/typebot/set/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\t{\n\t\t\"enabled\": FormTypebot.formData.enabled,\n\t\t\"url\": (FormTypebot.formData.url),\n\t\t\"typebot\": FormTypebot.formData.typebot,\n\t\t\"expire\": FormTypebot.formData.expire,\n\t\t\"keyword_finish\": FormTypebot.formData.keyword_finish,\n\t\t\"delay_message\": FormTypebot.formData.delay_message,\n\t\t\"unknown_message\": FormTypebot.formData.unknown_message,\n\t\t\"listening_from_me\": FormTypebot.formData.listening_from_me\n\t}\n}}","bodyFormData":[],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"headers[0].value"},{"key":"path"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","\n\t{\n\t\t\"enabled\": FormTypebot.formData.enabled,\n\t\t\"url\": (FormTypebot.formData.url),\n\t\t\"typebot\": FormTypebot.formData.typebot,\n\t\t\"expire\": FormTypebot.formData.expire,\n\t\t\"keyword_finish\": FormTypebot.formData.keyword_finish,\n\t\t\"delay_message\": FormTypebot.formData.delay_message,\n\t\t\"unknown_message\": FormTypebot.formData.unknown_message,\n\t\t\"listening_from_me\": FormTypebot.formData.listening_from_me\n\t}\n","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-08-19T05:00:46Z"},"id":"Home_Set_Typebot","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b380a2945b083c5bc7d9"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Find_Websocket","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/websocket/find/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":true,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-09-20T22:28:47Z"},"publishedAction":{"name":"Find_Websocket","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/websocket/find/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":true,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-09-20T22:28:47Z"},"id":"Home_Find_Websocket","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b380a2945b083c5bc7d8"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Fetch_PrivacySettings","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/chat/fetchPrivacySettings/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":true,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-31T12:27:52Z"},"publishedAction":{"name":"Fetch_PrivacySettings","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/chat/fetchPrivacySettings/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":true,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-31T12:27:52Z"},"id":"Home_Fetch_PrivacySettings","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b380a2945b083c5bc7dd"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Set_Rabbitmq","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/rabbitmq/set/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\tFormRabbitmq.formData\n}}","bodyFormData":[],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","\n\tFormRabbitmq.formData\n","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-08-03T00:56:01Z"},"publishedAction":{"name":"Set_Rabbitmq","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/rabbitmq/set/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\tFormRabbitmq.formData\n}}","bodyFormData":[],"httpMethod":"POST","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"},{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","\n\tFormRabbitmq.formData\n","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-08-03T00:56:01Z"},"id":"Home_Set_Rabbitmq","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b380a2945b083c5bc7de"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Update_PrivacySettings","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/chat/updatePrivacySettings/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\t{\n \"privacySettings\": {\n \"readreceipts\": FormProfile.formData.privacySettings.readreceipts,\n \"profile\": FormProfile.formData.privacySettings.profile,\n \"status\": FormProfile.formData.privacySettings.status,\n \"online\": FormProfile.formData.privacySettings.online,\n \"last\": FormProfile.formData.privacySettings.last,\n \"groupadd\": FormProfile.formData.privacySettings.groupadd\n\t\t}\n\t}\n}}","bodyFormData":[],"httpMethod":"PUT","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"headers[0].value"},{"key":"body"},{"key":"path"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","\n\t{\n \"privacySettings\": {\n \"readreceipts\": FormProfile.formData.privacySettings.readreceipts,\n \"profile\": FormProfile.formData.privacySettings.profile,\n \"status\": FormProfile.formData.privacySettings.status,\n \"online\": FormProfile.formData.privacySettings.online,\n \"last\": FormProfile.formData.privacySettings.last,\n \"groupadd\": FormProfile.formData.privacySettings.groupadd\n\t\t}\n\t}\n","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-31T12:28:39Z"},"publishedAction":{"name":"Update_PrivacySettings","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/chat/updatePrivacySettings/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[{"key":"content-type","value":"application/json"}],"encodeParamsToggle":true,"queryParameters":[],"body":"{{\n\t{\n \"privacySettings\": {\n \"readreceipts\": FormProfile.formData.privacySettings.readreceipts,\n \"profile\": FormProfile.formData.privacySettings.profile,\n \"status\": FormProfile.formData.privacySettings.status,\n \"online\": FormProfile.formData.privacySettings.online,\n \"last\": FormProfile.formData.privacySettings.last,\n \"groupadd\": FormProfile.formData.privacySettings.groupadd\n\t\t}\n\t}\n}}","bodyFormData":[],"httpMethod":"PUT","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"headers[0].value"},{"key":"body"},{"key":"path"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","\n\t{\n \"privacySettings\": {\n \"readreceipts\": FormProfile.formData.privacySettings.readreceipts,\n \"profile\": FormProfile.formData.privacySettings.profile,\n \"status\": FormProfile.formData.privacySettings.status,\n \"online\": FormProfile.formData.privacySettings.online,\n \"last\": FormProfile.formData.privacySettings.last,\n \"groupadd\": FormProfile.formData.privacySettings.groupadd\n\t\t}\n\t}\n","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-07-31T12:28:39Z"},"id":"Home_Update_PrivacySettings","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b380a2945b083c5bc7db"},{"pluginType":"API","pluginId":"restapi-plugin","unpublishedAction":{"name":"Find_Typebot","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/typebot/find/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":true,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-08-19T03:57:40Z"},"publishedAction":{"name":"Find_Typebot","datasource":{"name":"DEFAULT_REST_DATASOURCE","pluginId":"restapi-plugin","datasourceConfiguration":{"url":""},"invalids":[],"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Home","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","path":"{{appsmith.store.api_url}}/typebot/find/{{encodeURIComponent(TableInstances.selectedRow.instance)}}","headers":[{"key":"apikey","value":"{{TableInstances.selectedRow.Apikey}}"}],"autoGeneratedHeaders":[],"encodeParamsToggle":true,"queryParameters":[],"bodyFormData":[],"httpMethod":"GET","selfReferencingDataPaths":[],"pluginSpecifiedTemplates":[{"value":true}],"formData":{"apiContentType":"none"}},"executeOnLoad":false,"dynamicBindingPathList":[{"key":"path"},{"key":"headers[0].value"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["TableInstances.selectedRow.Apikey","encodeURIComponent(TableInstances.selectedRow.instance)","appsmith.store.api_url"],"userSetOnLoad":true,"confirmBeforeExecute":false,"policies":[],"userPermissions":[],"createdAt":"2023-08-19T03:57:40Z"},"id":"Home_Find_Typebot","deleted":false,"gitSyncId":"64e0b37fa2945b083c5bc7ac_64e0b380a2945b083c5bc7e3"}],"actionCollectionList":[{"unpublishedCollection":{"name":"Scripts","pageId":"Home","pluginId":"js-plugin","pluginType":"JS","actions":[],"archivedActions":[],"body":"export default {\n\tmyVar1: [],\n\tmyVar2: {},\n\tasync verifyConfig () {\n\t\tconst api_url = await appsmith.store.api_url;\n\t\tconst api_key = await appsmith.store.api_key;\n\t\tif(!api_url && !api_key){\n\t\t\tshowModal('ModalConfig');\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tfetch_Instances.run();\n\t\tFind_Webhook.run();\n\t\tFind_Settings.run();\n\t\tFind_Chatwoot.run();\n\t\treturn true;\n\t}\n}","variables":[{"name":"myVar1","value":"[]"},{"name":"myVar2","value":"{}"}],"userPermissions":[]},"publishedCollection":{"name":"Scripts","pageId":"Home","pluginId":"js-plugin","pluginType":"JS","actions":[],"archivedActions":[],"body":"export default {\n\tmyVar1: [],\n\tmyVar2: {},\n\tasync verifyConfig () {\n\t\tconst api_url = await appsmith.store.api_url;\n\t\tconst api_key = await appsmith.store.api_key;\n\t\tif(!api_url && !api_key){\n\t\t\tshowModal('ModalConfig');\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tfetch_Instances.run();\n\t\tFind_Webhook.run();\n\t\tFind_Settings.run();\n\t\tFind_Chatwoot.run();\n\t\treturn true;\n\t}\n}","variables":[{"name":"myVar1","value":"[]"},{"name":"myVar2","value":"{}"}],"userPermissions":[]},"id":"Home_Scripts","deleted":false,"gitSyncId":"64c534835ebbd221b60b4c54_64c5372a5dd3482b9ab5e11e"}],"updatedResources":{"customJSLibList":[],"actionList":["Scripts.verifyConfig##ENTITY_SEPARATOR##Home","Logout##ENTITY_SEPARATOR##Home","Fetch_Instance##ENTITY_SEPARATOR##Home","Set_Websocket##ENTITY_SEPARATOR##Home","Update_ProfileName##ENTITY_SEPARATOR##Home","Set_Chatwoot##ENTITY_SEPARATOR##Home","Create_Instance##ENTITY_SEPARATOR##Home","Update_ProfileStatus##ENTITY_SEPARATOR##Home","Find_Webhook##ENTITY_SEPARATOR##Home","Update_ProfilePicture##ENTITY_SEPARATOR##Home","Find_Settings##ENTITY_SEPARATOR##Home","Set_Settings##ENTITY_SEPARATOR##Home","Set_Typebot##ENTITY_SEPARATOR##Home","Update_PrivacySettings##ENTITY_SEPARATOR##Home","Find_Typebot##ENTITY_SEPARATOR##Home","Delete##ENTITY_SEPARATOR##Home","Find_Websocket##ENTITY_SEPARATOR##Home","Find_Chatwoot##ENTITY_SEPARATOR##Home","Connect##ENTITY_SEPARATOR##Home","Remove_ProfilePicture##ENTITY_SEPARATOR##Home","Fetch_PrivacySettings##ENTITY_SEPARATOR##Home","Restart##ENTITY_SEPARATOR##Home","Set_Rabbitmq##ENTITY_SEPARATOR##Home","fetch_Instances##ENTITY_SEPARATOR##Home","Find_Rabbitmq##ENTITY_SEPARATOR##Home","Set_Webhook##ENTITY_SEPARATOR##Home","Set_TypebotChangeSessionStatus##ENTITY_SEPARATOR##Home"],"pageList":["Home"],"actionCollectionList":["Scripts##ENTITY_SEPARATOR##Home"]},"editModeTheme":{"name":"Default","displayName":"Modern","config":{"colors":{"primaryColor":"#553DE9","backgroundColor":"#F8FAFC"},"borderRadius":{"appBorderRadius":{"none":"0px","M":"0.375rem","L":"1.5rem"}},"boxShadow":{"appBoxShadow":{"none":"none","S":"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)","M":"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)","L":"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)"}},"fontFamily":{"appFont":["System Default","Nunito Sans","Poppins","Inter","Montserrat","Noto Sans","Open Sans","Roboto","Rubik","Ubuntu"]}},"properties":{"colors":{"primaryColor":"#16a34a","backgroundColor":"#F8FAFC"},"borderRadius":{"appBorderRadius":"0.375rem"},"boxShadow":{"appBoxShadow":"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)"},"fontFamily":{"appFont":"Nunito Sans"}},"stylesheet":{"AUDIO_RECORDER_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"BUTTON_WIDGET":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"BUTTON_GROUP_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","childStylesheet":{"button":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}"}}},"CAMERA_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"CHART_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}","accentColor":"{{appsmith.theme.colors.primaryColor}}","fontFamily":"{{appsmith.theme.fontFamily.appFont}}"},"CHECKBOX_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CHECKBOX_GROUP_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CONTAINER_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}"},"CIRCULAR_PROGRESS_WIDGET":{"fillColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_INPUT_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATE_PICKER_WIDGET2":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"FILE_PICKER_WIDGET_V2":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"FORM_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}"},"FORM_BUTTON_WIDGET":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"ICON_BUTTON_WIDGET":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"IFRAME_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}"},"IMAGE_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"INPUT_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"INPUT_WIDGET_V2":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"JSON_FORM_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}","submitButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}}},"LIST_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}"},"MAP_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}"},"MAP_CHART_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}","fontFamily":"{{appsmith.theme.fontFamily.appFont}}"},"MENU_BUTTON_WIDGET":{"menuColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MODAL_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTI_SELECT_TREE_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTI_SELECT_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTI_SELECT_WIDGET_V2":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DROP_DOWN_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PROGRESSBAR_WIDGET":{"fillColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"PROGRESS_WIDGET":{"fillColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CODE_SCANNER_WIDGET":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RATE_WIDGET":{"activeColor":"{{appsmith.theme.colors.primaryColor}}"},"RADIO_GROUP_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"RICH_TEXT_EDITOR_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}"},"STATBOX_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}"},"SWITCH_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SWITCH_GROUP_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}"},"SELECT_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"TABLE_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}","childStylesheet":{"button":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"menuButton":{"menuColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"iconButton":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}}},"TABLE_WIDGET_V2":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}","childStylesheet":{"button":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"menuButton":{"menuColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"iconButton":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"editActions":{"saveButtonColor":"{{appsmith.theme.colors.primaryColor}}","saveBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","discardButtonColor":"{{appsmith.theme.colors.primaryColor}}","discardBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"}}},"TABS_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}"},"TEXT_WIDGET":{"truncateButtonColor":"{{appsmith.theme.colors.primaryColor}}","fontFamily":"{{appsmith.theme.fontFamily.appFont}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"VIDEO_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}"},"SINGLE_SELECT_TREE_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"CATEGORY_SLIDER_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}"},"NUMBER_SLIDER_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}"},"RANGE_SLIDER_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}"}},"isSystemTheme":false,"deleted":false},"publishedTheme":{"name":"Default","displayName":"Modern","config":{"colors":{"primaryColor":"#553DE9","backgroundColor":"#F8FAFC"},"borderRadius":{"appBorderRadius":{"none":"0px","M":"0.375rem","L":"1.5rem"}},"boxShadow":{"appBoxShadow":{"none":"none","S":"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)","M":"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)","L":"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)"}},"fontFamily":{"appFont":["System Default","Nunito Sans","Poppins","Inter","Montserrat","Noto Sans","Open Sans","Roboto","Rubik","Ubuntu"]}},"properties":{"colors":{"primaryColor":"#16a34a","backgroundColor":"#F8FAFC"},"borderRadius":{"appBorderRadius":"0.375rem"},"boxShadow":{"appBoxShadow":"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)"},"fontFamily":{"appFont":"Nunito Sans"}},"stylesheet":{"AUDIO_RECORDER_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"BUTTON_WIDGET":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"BUTTON_GROUP_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","childStylesheet":{"button":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}"}}},"CAMERA_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"CHART_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}","accentColor":"{{appsmith.theme.colors.primaryColor}}","fontFamily":"{{appsmith.theme.fontFamily.appFont}}"},"CHECKBOX_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CHECKBOX_GROUP_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CONTAINER_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}"},"CIRCULAR_PROGRESS_WIDGET":{"fillColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_INPUT_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATE_PICKER_WIDGET2":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"FILE_PICKER_WIDGET_V2":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"FORM_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}"},"FORM_BUTTON_WIDGET":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"ICON_BUTTON_WIDGET":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"IFRAME_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}"},"IMAGE_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"INPUT_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"INPUT_WIDGET_V2":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"JSON_FORM_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}","submitButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"resetButtonStyles":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"childStylesheet":{"ARRAY":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"OBJECT":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none","cellBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","cellBoxShadow":"none"},"CHECKBOX":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CURRENCY_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DATEPICKER":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"EMAIL_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTISELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTILINE_TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PASSWORD_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PHONE_NUMBER_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RADIO_GROUP":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SELECT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"SWITCH":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"TEXT_INPUT":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}}},"LIST_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}"},"MAP_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}"},"MAP_CHART_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}","fontFamily":"{{appsmith.theme.fontFamily.appFont}}"},"MENU_BUTTON_WIDGET":{"menuColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MODAL_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTI_SELECT_TREE_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTI_SELECT_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"MULTI_SELECT_WIDGET_V2":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"DROP_DOWN_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"PROGRESSBAR_WIDGET":{"fillColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"PROGRESS_WIDGET":{"fillColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"CODE_SCANNER_WIDGET":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"RATE_WIDGET":{"activeColor":"{{appsmith.theme.colors.primaryColor}}"},"RADIO_GROUP_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"RICH_TEXT_EDITOR_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}"},"STATBOX_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}"},"SWITCH_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","boxShadow":"none"},"SWITCH_GROUP_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}"},"SELECT_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"TABLE_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}","childStylesheet":{"button":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"menuButton":{"menuColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"iconButton":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"}}},"TABLE_WIDGET_V2":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}","childStylesheet":{"button":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"menuButton":{"menuColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"iconButton":{"buttonColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"editActions":{"saveButtonColor":"{{appsmith.theme.colors.primaryColor}}","saveBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","discardButtonColor":"{{appsmith.theme.colors.primaryColor}}","discardBorderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"}}},"TABS_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}"},"TEXT_WIDGET":{"truncateButtonColor":"{{appsmith.theme.colors.primaryColor}}","fontFamily":"{{appsmith.theme.fontFamily.appFont}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}"},"VIDEO_WIDGET":{"borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"{{appsmith.theme.boxShadow.appBoxShadow}}"},"SINGLE_SELECT_TREE_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}","borderRadius":"{{appsmith.theme.borderRadius.appBorderRadius}}","boxShadow":"none"},"CATEGORY_SLIDER_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}"},"NUMBER_SLIDER_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}"},"RANGE_SLIDER_WIDGET":{"accentColor":"{{appsmith.theme.colors.primaryColor}}"}},"isSystemTheme":false,"deleted":false}} diff --git a/Extras/typebot/typebot-example.json b/Extras/typebot/typebot-example.json deleted file mode 100644 index c45cd509..00000000 --- a/Extras/typebot/typebot-example.json +++ /dev/null @@ -1 +0,0 @@ -{"id":"l27ft2bq9a7tke15i7m64d9o","version":"3","createdAt":"2023-08-04T17:27:18.072Z","updatedAt":"2023-08-20T13:35:33.073Z","icon":null,"name":"[Dgcode] [whatsapp] Pesquisa Satisfacao","folderId":"cll1fzkfy0008pa65kgz3tm86","groups":[{"id":"c76ucoughhenpernmadu7ibg","title":"Start","blocks":[{"id":"qn40kjwtw1he3l1bujt3bnje","type":"start","label":"Start","groupId":"c76ucoughhenpernmadu7ibg","outgoingEdgeId":"aovnigvk665gzhyzg7bxhvn0"}],"graphCoordinates":{"x":-126.43,"y":220.29}},{"id":"nog2woqmvhssnnjlcpwd41k5","title":"Apresentação","blocks":[{"id":"potdr8jwrn6mnkjipynqjmhh","type":"Set variable","groupId":"nog2woqmvhssnnjlcpwd41k5","options":{"type":"Random ID","variableId":"vsu5or5sxes9lyuhsgcl3cuyd"}},{"id":"mcpyoq8x28bnwp23g7h1dbc1","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Olá! {{pushName}} Bem-vindo(a) à nossa "},{"bold":true,"text":"pesquisa de satisfação"},{"text":"."}]}]},"groupId":"nog2woqmvhssnnjlcpwd41k5"},{"id":"o0731ch0epj2vm2c5aoxyvw1","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Meu nome é "},{"bold":true,"text":"🤖 Mike"},{"text":", estou aqui para ouvir sua opinião e experiência com nossos serviços."}]}]},"groupId":"nog2woqmvhssnnjlcpwd41k5"},{"id":"twx683ok814enh3bwlaexe0t","type":"Wait","groupId":"nog2woqmvhssnnjlcpwd41k5","options":{"secondsToWaitFor":"5"}},{"id":"hgqbj5kmosz64cb435xqh0am","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Sua opinião é fundamental para nos ajudar a melhorar!"}]}]},"groupId":"nog2woqmvhssnnjlcpwd41k5"},{"id":"cbvgdo0jknjyzmvwe6o614ni","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Vamos começar?"}]}]},"groupId":"nog2woqmvhssnnjlcpwd41k5"},{"id":"vpj58atr9o534tjhhu0l0t0b","type":"Wait","groupId":"nog2woqmvhssnnjlcpwd41k5","options":{"secondsToWaitFor":"5"}},{"id":"nmhkn4jod3evk08tbq5vw3s3","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Qual o seu nome?"}]}]},"groupId":"nog2woqmvhssnnjlcpwd41k5"},{"id":"o8ijci5gdfsp6fpv07kwh8br","type":"text input","groupId":"nog2woqmvhssnnjlcpwd41k5","options":{"isLong":false,"labels":{"button":"Enviar","placeholder":"Digite o seu nome"},"variableId":"vo40px5r6wg9vhs9fixd45kzn"},"outgoingEdgeId":"vwx6ofz1ur8maxcbw8fk66x9"}],"graphCoordinates":{"x":771.26,"y":213}},{"id":"j5co2kcotxafuxhzlj7u0qnn","title":"Qual seu email?","blocks":[{"id":"he1367t9ssao735kidd86mna","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Muito bem {{name}}, agora me informe seu endereço de email?"}]}]},"groupId":"j5co2kcotxafuxhzlj7u0qnn"},{"id":"qb8nwfs52g168tmnvp257b44","type":"email input","groupId":"j5co2kcotxafuxhzlj7u0qnn","options":{"labels":{"button":"Enviar","placeholder":"Digite o seu email"},"variableId":"vr75l1drc5uoxvisje0hio5ph","retryMessageContent":"Email incorreto!"},"outgoingEdgeId":"v53mvhejcapb4a1zq98swq5b"}],"graphCoordinates":{"x":1236.92,"y":204.84}},{"id":"wtd0o382phaji7i7u2n8pody","title":"Pergunta 1","blocks":[{"id":"zr69lw3bcmmkgahqq8og7shw","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Em uma escala de 0 a 10, qual é o seu nível de satisfação geral com os serviços que nossa empresa fornece?"}]}]},"groupId":"wtd0o382phaji7i7u2n8pody"},{"id":"ku0zpu43cbbnd7y0ai71ptde","type":"rating input","groupId":"wtd0o382phaji7i7u2n8pody","options":{"labels":{"button":"Send"},"length":10,"buttonType":"Numbers","customIcon":{"isEnabled":false},"variableId":"vbfl3sqze2wzicn9l1n9ckjs4"},"outgoingEdgeId":"ed1x8zan90zvrpo9xk9moroe"}],"graphCoordinates":{"x":1692.4,"y":194.19}},{"id":"ylerbfc1l2o62j68g8ghegxt","title":"Pergunta 2","blocks":[{"id":"l19jgtpln9al473dudr0gbzn","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Em uma escala de 0 a 10, em que medida nossa empresa atendeu às suas expectativas em termos de qualidade do serviço prestado?"}]}]},"groupId":"ylerbfc1l2o62j68g8ghegxt"},{"id":"kfxuc6p58cdzy1xcyp4i4ra7","type":"rating input","groupId":"ylerbfc1l2o62j68g8ghegxt","options":{"labels":{"button":"Send"},"length":10,"buttonType":"Numbers","customIcon":{"isEnabled":false},"variableId":"vkgl2bfdbyms1dyc1s6efx678"},"outgoingEdgeId":"iy61ajcfl6ubbj7zghxeu6f7"}],"graphCoordinates":{"x":2156.14,"y":190.76}},{"id":"lbieknd0qp42pogsby5l82ww","title":"Pergunta 3","blocks":[{"id":"y43s12dnoxh772c9o3pmnhxf","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Você teve alguma dificuldade em se comunicar com nossa equipe de suporte ao cliente?"}]},{"type":"p","children":[{"text":""}]},{"type":"p","children":[{"text":"1 - Sim"}]},{"type":"p","children":[{"text":"2 - Não"}]}]},"groupId":"lbieknd0qp42pogsby5l82ww"},{"id":"fb6ckchqp8vx9ypig07we6q4","type":"text input","groupId":"lbieknd0qp42pogsby5l82ww","options":{"isLong":false,"labels":{"button":"Enviar","placeholder":"Responda com uma das opções"},"variableId":"vzhsu0uc4suqoz38kv3q891ma"}},{"id":"b538q1mt18l6oddo397nh1m4","type":"Condition","items":[{"id":"dwhc3ptqvktlgfvl17xg79s5","type":1,"blockId":"b538q1mt18l6oddo397nh1m4","content":{"comparisons":[{"id":"rln6ido55pzqyr9ihqp3r0oe","value":"^([Ss][IiÍí][Mm]|1)$","variableId":"vzhsu0uc4suqoz38kv3q891ma","comparisonOperator":"Matches regex"}],"logicalOperator":"OR"},"outgoingEdgeId":"w6ao5pi6wt0966tobkned56m"},{"id":"cod3tkt16ry8ixm5u7rwxzm9","type":1,"blockId":"b538q1mt18l6oddo397nh1m4","content":{"comparisons":[{"id":"n0dm7n4vyowa9bftkmu0ypud","value":"^([Nn][AaÃã][Oo]|2)$","variableId":"vzhsu0uc4suqoz38kv3q891ma","comparisonOperator":"Matches regex"}],"logicalOperator":"OR"},"outgoingEdgeId":"wlfmh2g3j5avj75sa9q6rsab"}],"groupId":"lbieknd0qp42pogsby5l82ww","outgoingEdgeId":"ehcwqdrkc4025pui2y1s9390"}],"graphCoordinates":{"x":2605.34,"y":189.93}},{"id":"qzhp25b9f2lvt4yeniqvjkav","title":"Pergunta 4","blocks":[{"id":"pos7njae2r35r29kcbyxtz2j","type":"text","content":{"richText":[{"type":"p","children":[{"text":"{{name}}, por favor, descreva o problema para que possamos melhorar."}]}]},"groupId":"qzhp25b9f2lvt4yeniqvjkav"},{"id":"ce2eodve0e4f2rubk4wv5jf1","type":"text input","groupId":"qzhp25b9f2lvt4yeniqvjkav","options":{"isLong":false,"labels":{"button":"Enviar","placeholder":"Descreva o problema"},"variableId":"vd6fm2i9shcdjz8bhhwbsdh6t"},"outgoingEdgeId":"i11xudmpsb1tbsss7qoge6cm"}],"graphCoordinates":{"x":3041.23,"y":187.11}},{"id":"c8kh8eee1m3wyy372v4n6m1i","title":"Pergunta 5","blocks":[{"id":"txqi87lwinpa0p5of0xmqxu6","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Em uma escala de 0 a 10, como você avalia a capacidade da nossa empresa de cumprir os prazos acordados?"}]}]},"groupId":"c8kh8eee1m3wyy372v4n6m1i"},{"id":"mg2tmcmwnx3tap0hs4b7e0la","type":"rating input","groupId":"c8kh8eee1m3wyy372v4n6m1i","options":{"labels":{"button":"Enviar"},"length":10,"buttonType":"Numbers","customIcon":{"isEnabled":false},"variableId":"vz6lvahwo15dosvckdtkxduly"},"outgoingEdgeId":"c9nrzzcxt8w4dgk2sfez53n5"}],"graphCoordinates":{"x":3501.8,"y":179.58}},{"id":"tn8bcyughy9dsxhmjngrosvj","title":"Pergunta 6","blocks":[{"id":"aema350m33n9dljopcsxn8q5","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Você recomendaria nossos serviços para outras pessoas ou empresas?"}]},{"type":"p","children":[{"text":""}]},{"type":"p","children":[{"text":"1 - Sim"}]},{"type":"p","children":[{"text":"2 - Não"}]}]},"groupId":"tn8bcyughy9dsxhmjngrosvj"},{"id":"wk4bkxbxcfu9skrzn8p8077u","type":"text input","groupId":"tn8bcyughy9dsxhmjngrosvj","options":{"isLong":false,"labels":{"button":"Enviar","placeholder":"Responda com uma das opções"},"variableId":"vndjnalmnb3ez9beeon5tzrgq"}},{"id":"n3j2dxaalkljl020o0o61ef9","type":"Condition","items":[{"id":"ifhm8cj8lsulhrarnfda2oal","type":1,"blockId":"n3j2dxaalkljl020o0o61ef9","content":{"comparisons":[{"id":"rln6ido55pzqyr9ihqp3r0oe","value":"^([Ss][IiÍí][Mm]|1)$","variableId":"vndjnalmnb3ez9beeon5tzrgq","comparisonOperator":"Matches regex"}],"logicalOperator":"OR"},"outgoingEdgeId":"yu9762ttf5jn3bmhd6uzrsv8"},{"id":"gxp6j3ouga4r0t8364tn8axs","type":1,"blockId":"n3j2dxaalkljl020o0o61ef9","content":{"comparisons":[{"id":"n0dm7n4vyowa9bftkmu0ypud","value":"^([Nn][AaÃã][Oo]|2)$","variableId":"vndjnalmnb3ez9beeon5tzrgq","comparisonOperator":"Matches regex"}],"logicalOperator":"OR"},"outgoingEdgeId":"ji1y2o1hldhemto0ymwou09c"}],"groupId":"tn8bcyughy9dsxhmjngrosvj","outgoingEdgeId":"d3u83fikqplfy9ntva3sm7eg"}],"graphCoordinates":{"x":3926.41,"y":186.15}},{"id":"nzkhdw3hdv550aepsxvk2a0u","title":"Pergunta 7","blocks":[{"id":"io90onrpfrokejgkps94r3dj","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Que pena {{name}}, por gentileza, nos conte o motivo?"}]}]},"groupId":"nzkhdw3hdv550aepsxvk2a0u"},{"id":"dj7dbgyjqk0a5u3jn6kzykb2","type":"text input","groupId":"nzkhdw3hdv550aepsxvk2a0u","options":{"isLong":false,"labels":{"button":"Enviar","placeholder":"Digite o motivo"},"variableId":"vept0w6tr0w7eyyi52hgq1r3c"},"outgoingEdgeId":"k7vrrf5cfxopvmhsbf35bt3m"}],"graphCoordinates":{"x":4352.64,"y":194.04}},{"id":"jdz9w8vrz09vefk4wqrf0vwl","title":"Pergunta 8","blocks":[{"id":"hndzyb58fqxudykajr22skla","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Existe alguma sugestão que você gostaria de nos dar para melhorar nossos serviços?"}]},{"type":"p","children":[{"text":""}]},{"type":"p","children":[{"text":"1 - Sim"}]},{"type":"p","children":[{"text":"2 - Não"}]}]},"groupId":"jdz9w8vrz09vefk4wqrf0vwl"},{"id":"ol9l8fdb3q65auykrn383q6d","type":"text input","groupId":"jdz9w8vrz09vefk4wqrf0vwl","options":{"isLong":false,"labels":{"button":"Enviar","placeholder":"Responda com uma das opções"},"variableId":"vy5it60mewmth7mayzhlgmzf0"}},{"id":"zderh9hqjkpuz58p79szfa1i","type":"Condition","items":[{"id":"lur26nqa8dv7m4jmmljpyyf1","type":1,"blockId":"zderh9hqjkpuz58p79szfa1i","content":{"comparisons":[{"id":"rln6ido55pzqyr9ihqp3r0oe","value":"^([Ss][IiÍí][Mm]|1)$","variableId":"vy5it60mewmth7mayzhlgmzf0","comparisonOperator":"Matches regex"}],"logicalOperator":"OR"},"outgoingEdgeId":"x2fzu1uuukp9cgmdzecp7mgk"},{"id":"aoj7e49zimwxng4o7bd6u00s","type":1,"blockId":"zderh9hqjkpuz58p79szfa1i","content":{"comparisons":[{"id":"n0dm7n4vyowa9bftkmu0ypud","value":"^([Nn][AaÃã][Oo]|2)$","variableId":"vy5it60mewmth7mayzhlgmzf0","comparisonOperator":"Matches regex"}],"logicalOperator":"OR"},"outgoingEdgeId":"mb1fg83gijikrafud2ml6zbn"}],"groupId":"jdz9w8vrz09vefk4wqrf0vwl","outgoingEdgeId":"amyrx4i2rm3cjksym5zvwd50"}],"graphCoordinates":{"x":4768.69,"y":201.49}},{"id":"c4k1ftb4rbynkb01ulwuh4qh","title":"Pergunta 9","blocks":[{"id":"jqn5de3i29ygjyf6usbj117t","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Qual seria a sua sugestão?"}]}]},"groupId":"c4k1ftb4rbynkb01ulwuh4qh"},{"id":"wfucksh3yaeq21l7mnlnsx75","type":"text input","groupId":"c4k1ftb4rbynkb01ulwuh4qh","options":{"isLong":false,"labels":{"button":"Enviar","placeholder":"Deixe sua sugestão"},"variableId":"vhygxyvhu5l6r2uws1cbthmxm"},"outgoingEdgeId":"u8c55of7l95fnz25gf7swt1m"}],"graphCoordinates":{"x":5233.77,"y":205.27}},{"id":"vvyooiddvdbon0t21bvzdr7q","title":"Finalização","blocks":[{"id":"efk089lhks1ev4khy38caner","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Então {{name}}, agradecemos muito por dedicar um tempo para nos fornecer seu feedback."}]}]},"groupId":"vvyooiddvdbon0t21bvzdr7q"},{"id":"pvu3g8vpqdi3aecu2u0in2d0","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Sua opinião é muito importante para nós, e trabalharemos arduamente para melhorar ainda mais nossos serviços!"}]}]},"groupId":"vvyooiddvdbon0t21bvzdr7q"},{"id":"wqe9r1ivjf0ikubqichufzsg","type":"Webhook","groupId":"vvyooiddvdbon0t21bvzdr7q","options":{"isCustomBody":true,"isAdvancedConfig":true,"variablesForTest":[],"responseVariableMapping":[]},"webhookId":"i3g1959ev6fl9s61ir8hn1we"}],"graphCoordinates":{"x":7067.06,"y":231.55}},{"id":"ffm0s2y4head3auw808hwfnx","title":"Retorna Pergunta 3","blocks":[{"id":"ox70407atqtf1kwrszis4cix","type":"Set variable","groupId":"ffm0s2y4head3auw808hwfnx","options":{"type":"Empty","variableId":"vzhsu0uc4suqoz38kv3q891ma"}},{"id":"bcwkrcxtsc8drzwynb2igu0g","type":"Jump","groupId":"ffm0s2y4head3auw808hwfnx","options":{"groupId":"lbieknd0qp42pogsby5l82ww"}}],"graphCoordinates":{"x":3040.8,"y":772.28}},{"id":"cf8r0wx0sgw6c9v79ebja1tj","title":"Retorna Pergunta 6","blocks":[{"id":"e02yfpbpj298m1q9y4tb905i","type":"Set variable","groupId":"cf8r0wx0sgw6c9v79ebja1tj","options":{"type":"Empty","variableId":"vndjnalmnb3ez9beeon5tzrgq"}},{"id":"wjfe41oxiik0jgwcye7sczeu","type":"Jump","groupId":"cf8r0wx0sgw6c9v79ebja1tj","options":{"groupId":"tn8bcyughy9dsxhmjngrosvj"}}],"graphCoordinates":{"x":4360.16,"y":732.74}},{"id":"b7zfnwcxvu28s98ii03isdae","title":"Retorna Pergunta 8","blocks":[{"id":"j1xmpy60ggf162ej9a0rti4f","type":"Set variable","groupId":"b7zfnwcxvu28s98ii03isdae","options":{"type":"Empty","variableId":"vy5it60mewmth7mayzhlgmzf0"}},{"id":"lk06yb9dvrctn2u9tx35n12c","type":"Jump","groupId":"b7zfnwcxvu28s98ii03isdae","options":{"groupId":"jdz9w8vrz09vefk4wqrf0vwl"}}],"graphCoordinates":{"x":5213.21,"y":778}},{"id":"z0idhsnqisrd695z0j1tnqvw","title":"Retorna Pergunta 10","blocks":[{"id":"gs96ig682082mj4igcjjuh76","type":"Set variable","groupId":"z0idhsnqisrd695z0j1tnqvw","options":{"type":"Empty","variableId":"vx6p4ivk4mnssvbhl30c5zng9"}},{"id":"tihlp1xm8mvpdm3d0dqkwwx6","type":"Jump","groupId":"z0idhsnqisrd695z0j1tnqvw","options":{"groupId":"cs5kjnrcsh4bjiuvwf99agho"}}],"graphCoordinates":{"x":6100.86,"y":819.65}},{"id":"qsrkmfsr04kayulair47gmn0","title":"Gera QRCODE pix","blocks":[{"id":"qs1uxqm8jqla9uui43ofms65","type":"Webhook","groupId":"qsrkmfsr04kayulair47gmn0","options":{"isCustomBody":true,"isAdvancedConfig":true,"variablesForTest":[],"responseVariableMapping":[{"id":"gcia6kdba4yydt14klsg8h6x","bodyPath":"data.qrcode_base64","variableId":"vamn8ortov9nk1y04vczo375h"}]},"webhookId":"ajx8mv7trd50mbv2uj6fr3x5"},{"id":"sz447ty7t4vreto9bf07h52i","type":"Set variable","groupId":"qsrkmfsr04kayulair47gmn0","options":{"type":"Custom","variableId":"vamn8ortov9nk1y04vczo375h","expressionToEvaluate":"if({{remoteJid}}){\n return {{qrcode}}.replace('data:image/png;base64,', ''); \n}else{\n return {{qrcode}}\n}\n"}},{"id":"c3wp5ic2wx9emj6kkii42xpj","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Aqui está qrcode para sua contribuição de R$ {{question11}}, caso tenha dificuldade na leitura utilize a nossa chave:"}]},{"type":"p","children":[{"text":""}]},{"type":"p","children":[{"text":"Telefone: 7499879409"}]},{"type":"p","children":[{"text":"Em nome de: Davidson Oliveira Gomes"}]}]},"groupId":"qsrkmfsr04kayulair47gmn0"},{"id":"jncggap4fivalzgntw3bfaom","type":"image","content":{"url":"{{qrcode}}"},"groupId":"qsrkmfsr04kayulair47gmn0"},{"id":"chiz9utw18jvui4c2r0vsiqp","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Muito obrigado pela sua contribuição!"}]}]},"groupId":"qsrkmfsr04kayulair47gmn0","outgoingEdgeId":"cwlt91vwhr7gvgx0qx2mnxtr"}],"graphCoordinates":{"x":6607.75,"y":229.53}},{"id":"cs5kjnrcsh4bjiuvwf99agho","title":"Pergunta 10","blocks":[{"id":"axpk3aoauusbiy8av70fc2fo","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Gostaria de fazer uma contribuição?"}]},{"type":"p","children":[{"text":""}]},{"type":"p","children":[{"text":"1 - Sim"}]},{"type":"p","children":[{"text":"2 - Não"}]}]},"groupId":"cs5kjnrcsh4bjiuvwf99agho"},{"id":"q136n37ja1g5dyhdeisur4rg","type":"text input","groupId":"cs5kjnrcsh4bjiuvwf99agho","options":{"isLong":false,"labels":{"button":"Enviar","placeholder":"Deixe sua resposta"},"variableId":"vx6p4ivk4mnssvbhl30c5zng9"}},{"id":"xza6e0p4hgkfz1wvwcjss48s","type":"Condition","items":[{"id":"m5mvt5ecw81eevl428n56aji","type":1,"blockId":"xza6e0p4hgkfz1wvwcjss48s","content":{"comparisons":[{"id":"rln6ido55pzqyr9ihqp3r0oe","value":"^([Ss][IiÍí][Mm]|1)$","variableId":"vx6p4ivk4mnssvbhl30c5zng9","comparisonOperator":"Matches regex"}],"logicalOperator":"OR"},"outgoingEdgeId":"fe1wk4fc1xzt7mefasb2qzqz"},{"id":"bpcidulg0g7v8pwh3w9my880","type":1,"blockId":"xza6e0p4hgkfz1wvwcjss48s","content":{"comparisons":[{"id":"n0dm7n4vyowa9bftkmu0ypud","value":"^([Nn][AaÃã][Oo]|2)$","variableId":"vx6p4ivk4mnssvbhl30c5zng9","comparisonOperator":"Matches regex"}],"logicalOperator":"OR"},"outgoingEdgeId":"xg1zkpvob8ilx2r8p0kv604d"}],"groupId":"cs5kjnrcsh4bjiuvwf99agho","outgoingEdgeId":"o746eh96sq2j7juionfql73t"}],"graphCoordinates":{"x":5708.94,"y":210.9}},{"id":"tq60r6azxrmn17b4y7mjovf5","title":"Pergunta 11","blocks":[{"id":"o5fspfge731wt6m781nzjsll","type":"text","content":{"richText":[{"type":"p","children":[{"text":"Muito bem {{name}}, quanto você deseja contribuir?"}]}]},"groupId":"tq60r6azxrmn17b4y7mjovf5"},{"id":"khncvmg5fcjsmu8tlmf8in6m","type":"number input","groupId":"tq60r6azxrmn17b4y7mjovf5","options":{"max":5000,"min":1,"step":1,"labels":{"button":"Enviar","placeholder":"Digite um numero"},"variableId":"vhoqah2c0blbx92bfmd4gjnyx"},"outgoingEdgeId":"ns2kch8n15uklzwf8kn4m0lb"}],"graphCoordinates":{"x":6158.94,"y":224.91}},{"id":"h0svx6gyzgjsclr9hbpo04v6","title":"Configurações Iniciais","blocks":[{"id":"na4zglpatkg8ejqcap8lcv69","type":"Set variable","groupId":"h0svx6gyzgjsclr9hbpo04v6","options":{"variableId":"vp1ask55v2r58ukom5lek5hej","expressionToEvaluate":"https://d715-45-39-187-135.ngrok-free.app"}},{"id":"t2bdxy8x8fsn29yijk02ti43","type":"Set variable","groupId":"h0svx6gyzgjsclr9hbpo04v6","options":{"variableId":"vtsldvs2u8ui93tktazy77djw","expressionToEvaluate":"0f1c6e17-5a6a-4989-8c12-a7e7350870fe"}},{"id":"rt5h0lk6jaoh5hzag0s5hidd","type":"Set variable","groupId":"h0svx6gyzgjsclr9hbpo04v6","options":{"variableId":"vkg1qlinovziltaloqhso2cw7","expressionToEvaluate":"https://pix.dgcode.com.br"}},{"id":"mh758b8y8288t56s6wz73mht","type":"Set variable","groupId":"h0svx6gyzgjsclr9hbpo04v6","options":{"variableId":"vpjyy2e2ha6mu5x10q0nowuz3","expressionToEvaluate":"Davidson Oliveira Gomes"}},{"id":"ri9kv80djsej7r51m8xfjhuk","type":"Set variable","groupId":"h0svx6gyzgjsclr9hbpo04v6","options":{"variableId":"vicsm3nkvhssvfhgss2xce2ad","expressionToEvaluate":"Telefone"}},{"id":"ye4teva02mnxph0rvfszdnsn","type":"Set variable","groupId":"h0svx6gyzgjsclr9hbpo04v6","options":{"variableId":"vlmflx32cjlz457h0uzdi706g","expressionToEvaluate":"74999879409"}},{"id":"hfz4hqzfe6wgje96ezb5kann","type":"Set variable","groupId":"h0svx6gyzgjsclr9hbpo04v6","options":{"variableId":"veesfw943copg17w2qzdln9be","expressionToEvaluate":"Irece"}},{"id":"nd3yk369k7j73kws6exos0jw","type":"Set variable","groupId":"h0svx6gyzgjsclr9hbpo04v6","options":{"variableId":"vavwvk4wgst506zdioplg4u8p","expressionToEvaluate":"TypeBot"},"outgoingEdgeId":"mb90csrzzep8qz2opcxmw736"}],"graphCoordinates":{"x":312.08,"y":218.28}}],"variables":[{"id":"vo40px5r6wg9vhs9fixd45kzn","name":"name"},{"id":"vr75l1drc5uoxvisje0hio5ph","name":"email"},{"id":"vzhsu0uc4suqoz38kv3q891ma","name":"question3"},{"id":"vbfl3sqze2wzicn9l1n9ckjs4","name":"question1"},{"id":"vkgl2bfdbyms1dyc1s6efx678","name":"question2"},{"id":"vd6fm2i9shcdjz8bhhwbsdh6t","name":"question4"},{"id":"vz6lvahwo15dosvckdtkxduly","name":"question5"},{"id":"vndjnalmnb3ez9beeon5tzrgq","name":"question6"},{"id":"vept0w6tr0w7eyyi52hgq1r3c","name":"question7"},{"id":"vy5it60mewmth7mayzhlgmzf0","name":"question8"},{"id":"vhygxyvhu5l6r2uws1cbthmxm","name":"question9"},{"id":"vrdwfo2lpoei2fzlzazh4pp61","name":"pushName"},{"id":"vz1uq7t77aivpi5crwy6ifact","name":"remoteJid"},{"id":"vsu5or5sxes9lyuhsgcl3cuyd","name":"ID"},{"id":"vamn8ortov9nk1y04vczo375h","name":"qrcode"},{"id":"vx6p4ivk4mnssvbhl30c5zng9","name":"question10"},{"id":"vhoqah2c0blbx92bfmd4gjnyx","name":"question11"},{"id":"vpjyy2e2ha6mu5x10q0nowuz3","name":"me"},{"id":"vicsm3nkvhssvfhgss2xce2ad","name":"typePIX"},{"id":"vavwvk4wgst506zdioplg4u8p","name":"reference"},{"id":"vlmflx32cjlz457h0uzdi706g","name":"keyPIX"},{"id":"vkg1qlinovziltaloqhso2cw7","name":"apiURL"},{"id":"veesfw943copg17w2qzdln9be","name":"city"},{"id":"vp1ask55v2r58ukom5lek5hej","name":"evolutionURL"},{"id":"vtsldvs2u8ui93tktazy77djw","name":"evolutionToken"},{"id":"vpoyfwgfw4tbt4l4iy4homfoq","name":"instanceName"}],"edges":[{"id":"w6ao5pi6wt0966tobkned56m","to":{"groupId":"qzhp25b9f2lvt4yeniqvjkav"},"from":{"itemId":"dwhc3ptqvktlgfvl17xg79s5","blockId":"b538q1mt18l6oddo397nh1m4","groupId":"lbieknd0qp42pogsby5l82ww"}},{"id":"wlfmh2g3j5avj75sa9q6rsab","to":{"groupId":"tn8bcyughy9dsxhmjngrosvj"},"from":{"itemId":"cod3tkt16ry8ixm5u7rwxzm9","blockId":"b538q1mt18l6oddo397nh1m4","groupId":"lbieknd0qp42pogsby5l82ww"}},{"id":"yu9762ttf5jn3bmhd6uzrsv8","to":{"groupId":"jdz9w8vrz09vefk4wqrf0vwl"},"from":{"itemId":"ifhm8cj8lsulhrarnfda2oal","blockId":"n3j2dxaalkljl020o0o61ef9","groupId":"tn8bcyughy9dsxhmjngrosvj"}},{"id":"ji1y2o1hldhemto0ymwou09c","to":{"groupId":"nzkhdw3hdv550aepsxvk2a0u"},"from":{"itemId":"gxp6j3ouga4r0t8364tn8axs","blockId":"n3j2dxaalkljl020o0o61ef9","groupId":"tn8bcyughy9dsxhmjngrosvj"}},{"id":"x2fzu1uuukp9cgmdzecp7mgk","to":{"groupId":"c4k1ftb4rbynkb01ulwuh4qh"},"from":{"itemId":"lur26nqa8dv7m4jmmljpyyf1","blockId":"zderh9hqjkpuz58p79szfa1i","groupId":"jdz9w8vrz09vefk4wqrf0vwl"}},{"id":"d3u83fikqplfy9ntva3sm7eg","to":{"groupId":"cf8r0wx0sgw6c9v79ebja1tj"},"from":{"blockId":"n3j2dxaalkljl020o0o61ef9","groupId":"tn8bcyughy9dsxhmjngrosvj"}},{"id":"ehcwqdrkc4025pui2y1s9390","to":{"groupId":"ffm0s2y4head3auw808hwfnx"},"from":{"blockId":"b538q1mt18l6oddo397nh1m4","groupId":"lbieknd0qp42pogsby5l82ww"}},{"id":"mb1fg83gijikrafud2ml6zbn","to":{"groupId":"cs5kjnrcsh4bjiuvwf99agho"},"from":{"itemId":"aoj7e49zimwxng4o7bd6u00s","blockId":"zderh9hqjkpuz58p79szfa1i","groupId":"jdz9w8vrz09vefk4wqrf0vwl"}},{"id":"amyrx4i2rm3cjksym5zvwd50","to":{"groupId":"b7zfnwcxvu28s98ii03isdae"},"from":{"blockId":"zderh9hqjkpuz58p79szfa1i","groupId":"jdz9w8vrz09vefk4wqrf0vwl"}},{"id":"o746eh96sq2j7juionfql73t","to":{"groupId":"z0idhsnqisrd695z0j1tnqvw"},"from":{"blockId":"xza6e0p4hgkfz1wvwcjss48s","groupId":"cs5kjnrcsh4bjiuvwf99agho"}},{"id":"fe1wk4fc1xzt7mefasb2qzqz","to":{"groupId":"tq60r6azxrmn17b4y7mjovf5"},"from":{"itemId":"m5mvt5ecw81eevl428n56aji","blockId":"xza6e0p4hgkfz1wvwcjss48s","groupId":"cs5kjnrcsh4bjiuvwf99agho"}},{"id":"xg1zkpvob8ilx2r8p0kv604d","to":{"groupId":"vvyooiddvdbon0t21bvzdr7q"},"from":{"itemId":"bpcidulg0g7v8pwh3w9my880","blockId":"xza6e0p4hgkfz1wvwcjss48s","groupId":"cs5kjnrcsh4bjiuvwf99agho"}},{"id":"cwlt91vwhr7gvgx0qx2mnxtr","to":{"groupId":"vvyooiddvdbon0t21bvzdr7q"},"from":{"blockId":"chiz9utw18jvui4c2r0vsiqp","groupId":"qsrkmfsr04kayulair47gmn0"}},{"id":"aovnigvk665gzhyzg7bxhvn0","to":{"groupId":"h0svx6gyzgjsclr9hbpo04v6"},"from":{"blockId":"qn40kjwtw1he3l1bujt3bnje","groupId":"c76ucoughhenpernmadu7ibg"}},{"id":"mb90csrzzep8qz2opcxmw736","to":{"groupId":"nog2woqmvhssnnjlcpwd41k5"},"from":{"blockId":"nd3yk369k7j73kws6exos0jw","groupId":"h0svx6gyzgjsclr9hbpo04v6"}},{"id":"vwx6ofz1ur8maxcbw8fk66x9","to":{"groupId":"j5co2kcotxafuxhzlj7u0qnn"},"from":{"blockId":"o8ijci5gdfsp6fpv07kwh8br","groupId":"nog2woqmvhssnnjlcpwd41k5"}},{"id":"v53mvhejcapb4a1zq98swq5b","to":{"groupId":"wtd0o382phaji7i7u2n8pody"},"from":{"blockId":"qb8nwfs52g168tmnvp257b44","groupId":"j5co2kcotxafuxhzlj7u0qnn"}},{"id":"ed1x8zan90zvrpo9xk9moroe","to":{"groupId":"ylerbfc1l2o62j68g8ghegxt"},"from":{"blockId":"ku0zpu43cbbnd7y0ai71ptde","groupId":"wtd0o382phaji7i7u2n8pody"}},{"id":"iy61ajcfl6ubbj7zghxeu6f7","to":{"groupId":"lbieknd0qp42pogsby5l82ww"},"from":{"blockId":"kfxuc6p58cdzy1xcyp4i4ra7","groupId":"ylerbfc1l2o62j68g8ghegxt"}},{"id":"i11xudmpsb1tbsss7qoge6cm","to":{"groupId":"c8kh8eee1m3wyy372v4n6m1i"},"from":{"blockId":"ce2eodve0e4f2rubk4wv5jf1","groupId":"qzhp25b9f2lvt4yeniqvjkav"}},{"id":"c9nrzzcxt8w4dgk2sfez53n5","to":{"groupId":"tn8bcyughy9dsxhmjngrosvj"},"from":{"blockId":"mg2tmcmwnx3tap0hs4b7e0la","groupId":"c8kh8eee1m3wyy372v4n6m1i"}},{"id":"k7vrrf5cfxopvmhsbf35bt3m","to":{"groupId":"jdz9w8vrz09vefk4wqrf0vwl"},"from":{"blockId":"dj7dbgyjqk0a5u3jn6kzykb2","groupId":"nzkhdw3hdv550aepsxvk2a0u"}},{"id":"u8c55of7l95fnz25gf7swt1m","to":{"groupId":"cs5kjnrcsh4bjiuvwf99agho"},"from":{"blockId":"wfucksh3yaeq21l7mnlnsx75","groupId":"c4k1ftb4rbynkb01ulwuh4qh"}},{"id":"ns2kch8n15uklzwf8kn4m0lb","to":{"groupId":"qsrkmfsr04kayulair47gmn0"},"from":{"blockId":"khncvmg5fcjsmu8tlmf8in6m","groupId":"tq60r6azxrmn17b4y7mjovf5"}}],"theme":{"chat":{"inputs":{"color":"#ffffff","backgroundColor":"#1e293b","placeholderColor":"#9095A0"},"buttons":{"color":"#ffffff","backgroundColor":"#1a5fff"},"roundness":"large","hostAvatar":{"isEnabled":true},"guestAvatar":{"isEnabled":false},"hostBubbles":{"color":"#ffffff","backgroundColor":"#1e293b"},"guestBubbles":{"color":"#FFFFFF","backgroundColor":"#FF8E21"}},"general":{"font":"Open Sans","background":{"type":"Color","content":"#171923"}}},"selectedThemeTemplateId":"typebot-dark","settings":{"general":{"isBrandingEnabled":false},"metadata":{"imageUrl":"https://i.imgur.com/48TjKBb.jpg","description":"Sua opinião é fundamental para nos ajudar a melhorar!"},"typingEmulation":{"speed":300,"enabled":true,"maxDelay":1.5}},"publicId":"dgcode-pesquisa-satisfacao-whatsapp-7m64d9o","customDomain":null,"workspaceId":"clktt8c1y0001qa66zyg5tt23","resultsTablePreferences":null,"isArchived":false,"isClosed":false} \ No newline at end of file diff --git a/LICENSE b/LICENSE index 0da2f519..84d8e909 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,22 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 +# Evolution API License - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. +Evolution API is licensed under the Apache License 2.0, with the following additional conditions: - Preamble +1. Evolution API may be utilized commercially, including as a backend service for other applications or as an application development platform for enterprises. Should the conditions below be met, a commercial license must be obtained from the producer: - The GNU General Public License is a free, copyleft license for -software and other kinds of works. +a. Multi-tenant SaaS service: Unless explicitly authorized in writing, you may not use the Evolution API source code to operate a multi-tenant environment. + - Tenant Definition: Within the context of Evolution API, one tenant corresponds to one workspace. The workspace provides a separated area for each tenant's data and configurations. - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. +b. LOGO and copyright information: In the process of using Evolution 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 API that do not involve its frontend components. - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. +Please contact contato@atendai.com to inquire about licensing matters. - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. +2. As a contributor, you should agree that: - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. +a. The producer can adjust the open-source agreement to be more strict or relaxed as deemed necessary. +b. Your contributed code may be used for commercial purposes, including but not limited to its cloud business operations. - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. +Apart from the specific conditions mentioned above, all other rights and restrictions follow the Apache License 2.0. Detailed information about the Apache License 2.0 can be found at http://www.apache.org/licenses/LICENSE-2.0. - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. +© 2024 AtendAI - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. \ No newline at end of file diff --git a/README.md b/README.md index a20f5387..431d58a3 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,9 @@ [![Discord Community](https://img.shields.io/badge/Discord-Community-blue)](https://evolution-api.com/discord) [![Postman Collection](https://img.shields.io/badge/Postman-Collection-orange)](https://evolution-api.com/postman) [![Documentation](https://img.shields.io/badge/Documentation-Official-green)](https://doc.evolution-api.com) -[![License](https://img.shields.io/badge/license-GPL--3.0-orange)](./LICENSE) +[![License](https://img.shields.io/badge/license-Apache--2.0-blue)](./LICENSE) [![Support](https://img.shields.io/badge/Donation-picpay-green)](https://app.picpay.com/user/davidsongomes1998) -[![Support](https://img.shields.io/badge/Buy%20me-coffe-orange)](https://bmc.link/evolutionapi) +[![Sponsors](https://img.shields.io/badge/Github-sponsor-orange)](https://github.com/sponsors/EvolutionAPI) @@ -79,6 +79,10 @@ Join our Evolution Pro community for expert support and a weekly call to answer # Donate to the project. +#### Github Sponsors + +https://github.com/sponsors/EvolutionAPI + #### PicPay
@@ -90,9 +94,7 @@ Join our Evolution Pro community for expert support and a weekly call to answer #### Buy me coffe - PIX
- - - +

CHAVE PIX (Telefone): (74)99987-9409

@@ -115,4 +117,21 @@ We are proud to collaborate with the following content creators who have contrib - [Comunidade Hub Connect](https://youtube.com/@comunidadehubconnect) - [dSantana Automações](https://www.youtube.com/channel/UCG7DjUmAxtYyURlOGAIryNQ?view_as=subscriber) - [Edison Martins](https://www.youtube.com/@edisonmartinsmkt) -- [Astra Online](https://www.youtube.com/@astraonlineweb) \ No newline at end of file +- [Astra Online](https://www.youtube.com/@astraonlineweb) +- [MKT Seven Automações](https://www.youtube.com/@sevenautomacoes) +- [Vamos automatizar](https://www.youtube.com/vamosautomatizar) + +## License + +Evolution API is licensed under the Apache License 2.0, with the following additional conditions: + +1. **Multi-tenant SaaS service**: Unless explicitly authorized in writing, you may not use the Evolution API source code to operate a multi-tenant environment. + - Tenant Definition: Within the context of Evolution API, one tenant corresponds to one workspace. The workspace provides a separated area for each tenant's data and configurations. + +2. **LOGO and copyright information**: In the process of using Evolution 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 API that do not involve its frontend components. + +Please contact contato@atendai.com to inquire about licensing matters. + +Apart from the specific conditions mentioned above, all other rights and restrictions follow the Apache License 2.0. Detailed information about the Apache License 2.0 can be found at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0). + +© 2024 AtendAI \ No newline at end of file diff --git a/docker-compose.yaml.example b/docker-compose.dev.yaml similarity index 73% rename from docker-compose.yaml.example rename to docker-compose.dev.yaml index d0a75a5d..2ca3424e 100644 --- a/docker-compose.yaml.example +++ b/docker-compose.dev.yaml @@ -1,5 +1,3 @@ -version: '3.3' - services: api: container_name: evolution_api @@ -10,18 +8,16 @@ services: - 8080:8080 volumes: - evolution_instances:/evolution/instances - - evolution_store:/evolution/store networks: - evolution-net env_file: - - ./Docker/.env - command: ['node', './dist/src/main.js'] + - .env expose: - 8080 volumes: evolution_instances: - evolution_store: + networks: evolution-net: diff --git a/docker-compose.yaml.example.dockerhub b/docker-compose.yaml similarity index 65% rename from docker-compose.yaml.example.dockerhub rename to docker-compose.yaml index b33e8f4a..21dcf5d0 100644 --- a/docker-compose.yaml.example.dockerhub +++ b/docker-compose.yaml @@ -1,26 +1,22 @@ -version: '3.3' - services: api: container_name: evolution_api - image: atendai/evolution-api:latest + image: atendai/evolution-api:v2.0.9-rc restart: always ports: - 8080:8080 volumes: - evolution_instances:/evolution/instances - - evolution_store:/evolution/store networks: - evolution-net env_file: - - ./Docker/.env - command: ['node', './dist/src/main.js'] + - .env expose: - 8080 volumes: evolution_instances: - evolution_store: + networks: evolution-net: diff --git a/docker-compose.yaml.example.complete b/docker-compose.yaml.example.complete deleted file mode 100644 index de13de57..00000000 --- a/docker-compose.yaml.example.complete +++ /dev/null @@ -1,80 +0,0 @@ -version: '3.3' - -services: - api: - container_name: evolution_api - image: evolution/api:local - build: . - restart: always - ports: - - 8080:8080 - volumes: - - evolution_instances:/evolution/instances - - evolution_store:/evolution/store - networks: - - evolution-net - env_file: - - ./Docker/.env - command: ['node', './dist/src/main.js'] - expose: - - 8080 - - mongodb: - container_name: mongodb - image: mongo - restart: always - ports: - - 27017:27017 - environment: - - MONGO_INITDB_ROOT_USERNAME=root - - MONGO_INITDB_ROOT_PASSWORD=root - - PUID=1000 - - PGID=1000 - volumes: - - evolution_mongodb_data:/data/db - - evolution_mongodb_configdb:/data/configdb - networks: - - evolution-net - expose: - - 27017 - - mongo-express: - image: mongo-express - networks: - - evolution-net - environment: - ME_CONFIG_BASICAUTH_USERNAME: root - ME_CONFIG_BASICAUTH_PASSWORD: root - ME_CONFIG_MONGODB_SERVER: mongodb - ME_CONFIG_MONGODB_ADMINUSERNAME: root - ME_CONFIG_MONGODB_ADMINPASSWORD: root - ports: - - 8081:8081 - links: - - mongodb - - redis: - image: redis:latest - container_name: redis - command: > - redis-server - --port 6379 - --appendonly yes - volumes: - - evolution_redis:/data - networks: - - evolution-net - ports: - - 6379:6379 - -volumes: - evolution_instances: - evolution_store: - evolution_mongodb_data: - evolution_mongodb_configdb: - evolution_redis: - -networks: - evolution-net: - name: evolution-net - driver: bridge diff --git a/manager/dist/assets/index-DNOCacL_.css b/manager/dist/assets/index-DNOCacL_.css new file mode 100644 index 00000000..667e50cd --- /dev/null +++ b/manager/dist/assets/index-DNOCacL_.css @@ -0,0 +1 @@ +@import"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap";*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}:root{--gradient: #093028;--background: 178 98.4% 98.22%;--foreground: 178 6.800000000000001% .44%;--muted: 178 6.800000000000001% 91.1%;--muted-foreground: 178 3.4000000000000004% 41.1%;--popover: 178 35.599999999999994% 91.1%;--popover-foreground: 178 6.800000000000001% .55%;--card: 178 35.599999999999994% 91.1%;--card-foreground: 178 6.800000000000001% .55%;--border: 178 11.8% 89.44%;--input: 178 11.8% 89.44%;--primary: 178 68% 11%;--primary-foreground: 178 1.36% 91.1%;--secondary: 178 3.4000000000000004% 95.55%;--secondary-foreground: 178 5.08% 11.1%;--accent: 178 3.4000000000000004% 95.55%;--accent-foreground: 178 5.08% 11.1%;--destructive: 0 84.2% 60.2%;--destructive-foreground: 0 0% 98%;--ring: 178 68% 11%;--radius: .5rem}.dark{--gradient: #189d68;--background: 166 47.449999999999996% 2.88%;--foreground: 166 7.3% 96.8%;--muted: 166 36.5% 10.799999999999999%;--muted-foreground: 166 7.3% 53.6%;--popover: 166 50.4% 4.68%;--popover-foreground: 166 7.3% 96.8%;--card: 166 50.4% 4.68%;--card-foreground: 166 7.3% 96.8%;--border: 166 36.5% 10.799999999999999%;--input: 166 36.5% 10.799999999999999%;--primary: 166 73% 36%;--primary-foreground: 166 7.3% 96.8%;--secondary: 166 36.5% 10.799999999999999%;--secondary-foreground: 166 7.3% 96.8%;--accent: 166 36.5% 10.799999999999999%;--accent-foreground: 166 7.3% 96.8%;--destructive: 0 62.8% 30.6%;--destructive-foreground: 166 7.3% 96.8%;--ring: 166 73% 36%}*{border-color:hsl(var(--border))}body{background-color:hsl(var(--background));color:hsl(var(--foreground));font-family:Inter,sans-serif;scrollbar-width:thin;scrollbar-color:transparent transparent}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{top:0;right:0;bottom:0;left:0}.bottom-0{bottom:0}.bottom-3{bottom:.75rem}.left-2{left:.5rem}.left-3{left:.75rem}.right-3{right:.75rem}.right-4{right:1rem}.top-0{top:0}.top-4{top:1rem}.z-10{z-index:10}.z-50{z-index:50}.m-4{margin:1rem}.-mx-1{margin-left:-.25rem;margin-right:-.25rem}.mx-4{margin-left:1rem;margin-right:1rem}.mx-auto{margin-left:auto;margin-right:auto}.my-0\.5{margin-top:.125rem;margin-bottom:.125rem}.my-1{margin-top:.25rem;margin-bottom:.25rem}.my-2{margin-top:.5rem;margin-bottom:.5rem}.my-4{margin-top:1rem;margin-bottom:1rem}.my-6{margin-top:1.5rem;margin-bottom:1.5rem}.mb-1{margin-bottom:.25rem}.mb-4{margin-bottom:1rem}.ml-2{margin-left:.5rem}.ml-6{margin-left:1.5rem}.ml-auto{margin-left:auto}.mr-1{margin-right:.25rem}.mr-16{margin-right:4rem}.mr-2{margin-right:.5rem}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.mt-5{margin-top:1.25rem}.mt-auto{margin-top:auto}.block{display:block}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.aspect-square{aspect-ratio:1 / 1}.aspect-video{aspect-ratio:16 / 9}.h-10{height:2.5rem}.h-11{height:2.75rem}.h-12{height:3rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-24{height:6rem}.h-3\.5{height:.875rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-\[1\.2rem\]{height:1.2rem}.h-\[1px\]{height:1px}.h-\[var\(--radix-select-trigger-height\)\]{height:var(--radix-select-trigger-height)}.h-auto{height:auto}.h-full{height:100%}.h-px{height:1px}.h-screen{height:100vh}.max-h-96{max-height:24rem}.max-h-\[240px\]{max-height:240px}.max-h-\[300px\]{max-height:300px}.min-h-\[48px\]{min-height:48px}.min-h-\[80px\]{min-height:80px}.min-h-\[calc\(100vh_-_56px\)\]{min-height:calc(100vh - 56px)}.min-h-screen{min-height:100vh}.w-0{width:0px}.w-1{width:.25rem}.w-10{width:2.5rem}.w-11{width:2.75rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-7{width:1.75rem}.w-72{width:18rem}.w-8{width:2rem}.w-\[1\.2rem\]{width:1.2rem}.w-\[1px\]{width:1px}.w-\[350px\]{width:350px}.w-full{width:100%}.w-px{width:1px}.min-w-0{min-width:0px}.min-w-\[8rem\]{min-width:8rem}.min-w-\[var\(--radix-select-trigger-width\)\]{min-width:var(--radix-select-trigger-width)}.max-w-2xl{max-width:42rem}.max-w-4xl{max-width:56rem}.max-w-\[300px\]{max-width:300px}.max-w-lg{max-width:32rem}.flex-1{flex:1 1 0%}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.caption-bottom{caption-side:bottom}.translate-y-1{--tw-translate-y: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-0{--tw-rotate: 0deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-90{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-0{--tw-scale-x: 0;--tw-scale-y: 0;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-100{--tw-scale-x: 1;--tw-scale-y: 1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.touch-none{touch-action:none}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-none{resize:none}.grid-cols-\[repeat\(auto-fit\,_minmax\(15rem\,_1fr\)\)\]{grid-template-columns:repeat(auto-fit,minmax(15rem,1fr))}.flex-row{flex-direction:row}.flex-row-reverse{flex-direction:row-reverse}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.flex-wrap{flex-wrap:wrap}.place-items-center{place-items:center}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.items-stretch{align-items:stretch}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.divide-x>:not([hidden])~:not([hidden]){--tw-divide-x-reverse: 0;border-right-width:calc(1px * var(--tw-divide-x-reverse));border-left-width:calc(1px * calc(1 - var(--tw-divide-x-reverse)))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.self-end{align-self:flex-end}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-visible{overflow:visible}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.text-ellipsis{text-overflow:ellipsis}.whitespace-nowrap{white-space:nowrap}.text-wrap{text-wrap:wrap}.break-all{word-break:break-all}.rounded-3xl{border-radius:1.5rem}.rounded-\[2px\]{border-radius:2px}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-\[1\.5px\]{border-width:1.5px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-none{border-style:none}.border-\[--color-border\]{border-color:var(--color-border)}.border-amber-500\/20{border-color:#f59e0b33}.border-black{--tw-border-opacity: 1;border-color:rgb(0 0 0 / var(--tw-border-opacity))}.border-border{border-color:hsl(var(--border))}.border-border\/50{border-color:hsl(var(--border) / .5)}.border-emerald-500\/20{border-color:#10b98133}.border-gray-600\/50{border-color:#4b556380}.border-input{border-color:hsl(var(--input))}.border-muted{border-color:hsl(var(--muted))}.border-red-500\/20{border-color:#ef444433}.border-sky-500\/20{border-color:#0ea5e933}.border-transparent{border-color:transparent}.border-zinc-500\/20{border-color:#71717a33}.border-l-transparent{border-left-color:transparent}.border-t-transparent{border-top-color:transparent}.bg-\[--color-bg\]{background-color:var(--color-bg)}.bg-amber-50\/50{background-color:#fffbeb80}.bg-amber-600{--tw-bg-opacity: 1;background-color:rgb(217 119 6 / var(--tw-bg-opacity))}.bg-background{background-color:hsl(var(--background))}.bg-background\/80{background-color:hsl(var(--background) / .8)}.bg-border{background-color:hsl(var(--border))}.bg-card{background-color:hsl(var(--card))}.bg-destructive{background-color:hsl(var(--destructive))}.bg-emerald-50\/50{background-color:#ecfdf580}.bg-muted{background-color:hsl(var(--muted))}.bg-muted\/50{background-color:hsl(var(--muted) / .5)}.bg-popover{background-color:hsl(var(--popover))}.bg-primary{background-color:hsl(var(--primary))}.bg-primary\/20{background-color:hsl(var(--primary) / .2)}.bg-primary\/30{background-color:hsl(var(--primary) / .3)}.bg-red-50\/50{background-color:#fef2f280}.bg-secondary{background-color:hsl(var(--secondary))}.bg-sky-50\/50{background-color:#f0f9ff80}.bg-transparent{background-color:transparent}.bg-zinc-50\/50{background-color:#fafafa80}.fill-current{fill:currentColor}.p-0{padding:0}.p-1{padding:.25rem}.p-2{padding:.5rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.p-\[1px\]{padding:1px}.px-1{padding-left:.25rem;padding-right:.25rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.pb-3{padding-bottom:.75rem}.pl-12{padding-left:3rem}.pl-2{padding-left:.5rem}.pl-3{padding-left:.75rem}.pl-8{padding-left:2rem}.pr-16{padding-right:4rem}.pr-2{padding-right:.5rem}.pr-4{padding-right:1rem}.pt-0{padding-top:0}.pt-2{padding-top:.5rem}.pt-3{padding-top:.75rem}.pt-5{padding-top:1.25rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.tabular-nums{--tw-numeric-spacing: tabular-nums;font-variant-numeric:var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)}.leading-none{line-height:1}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.tracking-widest{letter-spacing:.1em}.text-amber-100{--tw-text-opacity: 1;color:rgb(254 243 199 / var(--tw-text-opacity))}.text-amber-900{--tw-text-opacity: 1;color:rgb(120 53 15 / var(--tw-text-opacity))}.text-card-foreground{color:hsl(var(--card-foreground))}.text-destructive-foreground{color:hsl(var(--destructive-foreground))}.text-emerald-900{--tw-text-opacity: 1;color:rgb(6 78 59 / var(--tw-text-opacity))}.text-foreground{color:hsl(var(--foreground))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity))}.text-muted-foreground{color:hsl(var(--muted-foreground))}.text-muted-foreground\/80{color:hsl(var(--muted-foreground) / .8)}.text-popover-foreground{color:hsl(var(--popover-foreground))}.text-primary{color:hsl(var(--primary))}.text-primary-foreground{color:hsl(var(--primary-foreground))}.text-red-900{--tw-text-opacity: 1;color:rgb(127 29 29 / var(--tw-text-opacity))}.text-rose-600{--tw-text-opacity: 1;color:rgb(225 29 72 / var(--tw-text-opacity))}.text-secondary-foreground{color:hsl(var(--secondary-foreground))}.text-sky-900{--tw-text-opacity: 1;color:rgb(12 74 110 / var(--tw-text-opacity))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity))}.text-zinc-900{--tw-text-opacity: 1;color:rgb(24 24 27 / var(--tw-text-opacity))}.underline-offset-4{text-underline-offset:4px}.caret-transparent{caret-color:transparent}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-none{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.ring-0{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-muted-foreground{--tw-ring-color: hsl(var(--muted-foreground))}.ring-offset-background{--tw-ring-offset-color: hsl(var(--background))}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}@keyframes enter{0%{opacity:var(--tw-enter-opacity, 1);transform:translate3d(var(--tw-enter-translate-x, 0),var(--tw-enter-translate-y, 0),0) scale3d(var(--tw-enter-scale, 1),var(--tw-enter-scale, 1),var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity, 1);transform:translate3d(var(--tw-exit-translate-x, 0),var(--tw-exit-translate-y, 0),0) scale3d(var(--tw-exit-scale, 1),var(--tw-exit-scale, 1),var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0))}}.duration-200{animation-duration:.2s}.paused{animation-play-state:paused}.file\:border-0::file-selector-button{border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\:font-medium::file-selector-button{font-weight:500}.placeholder\:text-muted-foreground::-moz-placeholder{color:hsl(var(--muted-foreground))}.placeholder\:text-muted-foreground::placeholder{color:hsl(var(--muted-foreground))}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:inset-y-0:after{content:var(--tw-content);top:0;bottom:0}.after\:left-1\/2:after{content:var(--tw-content);left:50%}.after\:w-1:after{content:var(--tw-content);width:.25rem}.after\:-translate-x-1\/2:after{content:var(--tw-content);--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.after\:bg-border:after{content:var(--tw-content);background-color:hsl(var(--border))}.hover\:bg-accent:hover{background-color:hsl(var(--accent))}.hover\:bg-amber-600\/80:hover{background-color:#d97706cc}.hover\:bg-amber-600\/90:hover{background-color:#d97706e6}.hover\:bg-destructive\/80:hover{background-color:hsl(var(--destructive) / .8)}.hover\:bg-destructive\/90:hover{background-color:hsl(var(--destructive) / .9)}.hover\:bg-muted\/50:hover{background-color:hsl(var(--muted) / .5)}.hover\:bg-primary\/80:hover{background-color:hsl(var(--primary) / .8)}.hover\:bg-primary\/90:hover{background-color:hsl(var(--primary) / .9)}.hover\:bg-secondary\/80:hover{background-color:hsl(var(--secondary) / .8)}.hover\:bg-transparent:hover{background-color:transparent}.hover\:stroke-destructive:hover{stroke:hsl(var(--destructive))}.hover\:text-accent-foreground:hover{color:hsl(var(--accent-foreground))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.focus\:bg-accent:focus{background-color:hsl(var(--accent))}.focus\:text-accent-foreground:focus{color:hsl(var(--accent-foreground))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-ring:focus{--tw-ring-color: hsl(var(--ring))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus-visible\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\:ring-1:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-ring:focus-visible{--tw-ring-color: hsl(var(--ring))}.focus-visible\:ring-offset-1:focus-visible{--tw-ring-offset-width: 1px}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.focus-visible\:ring-offset-background:focus-visible{--tw-ring-offset-color: hsl(var(--background))}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.peer:disabled~.peer-disabled\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\:opacity-70{opacity:.7}.aria-selected\:bg-accent[aria-selected=true]{background-color:hsl(var(--accent))}.aria-selected\:text-accent-foreground[aria-selected=true]{color:hsl(var(--accent-foreground))}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[panel-group-direction\=vertical\]\:h-px[data-panel-group-direction=vertical]{height:1px}.data-\[panel-group-direction\=vertical\]\:w-full[data-panel-group-direction=vertical]{width:100%}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=checked\]\:translate-x-5[data-state=checked]{--tw-translate-x: 1.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked]{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[panel-group-direction\=vertical\]\:flex-col[data-panel-group-direction=vertical]{flex-direction:column}.data-\[state\=active\]\:bg-background[data-state=active]{background-color:hsl(var(--background))}.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:hsl(var(--primary))}.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:hsl(var(--accent))}.data-\[state\=open\]\:bg-muted[data-state=open],.data-\[state\=selected\]\:bg-muted[data-state=selected]{background-color:hsl(var(--muted))}.data-\[state\=unchecked\]\:bg-slate-400[data-state=unchecked]{--tw-bg-opacity: 1;background-color:rgb(148 163 184 / var(--tw-bg-opacity))}.data-\[state\=active\]\:text-foreground[data-state=active]{color:hsl(var(--foreground))}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:hsl(var(--muted-foreground))}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[state\=active\]\:shadow-sm[data-state=active]{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.data-\[state\=open\]\:animate-in[data-state=open]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.data-\[state\=closed\]\:animate-out[data-state=closed]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: -.5rem}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: .5rem}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: -.5rem}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: .5rem}.data-\[state\=closed\]\:slide-out-to-left-1\/2[data-state=closed]{--tw-exit-translate-x: -50%}.data-\[state\=closed\]\:slide-out-to-top-\[48\%\][data-state=closed]{--tw-exit-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-left-1\/2[data-state=open]{--tw-enter-translate-x: -50%}.data-\[state\=open\]\:slide-in-from-top-\[48\%\][data-state=open]{--tw-enter-translate-y: -48%}.data-\[panel-group-direction\=vertical\]\:after\:left-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);left:0}.data-\[panel-group-direction\=vertical\]\:after\:h-1[data-panel-group-direction=vertical]:after{content:var(--tw-content);height:.25rem}.data-\[panel-group-direction\=vertical\]\:after\:w-full[data-panel-group-direction=vertical]:after{content:var(--tw-content);width:100%}.data-\[panel-group-direction\=vertical\]\:after\:-translate-y-1\/2[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[panel-group-direction\=vertical\]\:after\:translate-x-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dark\:-rotate-90:is(.dark *){--tw-rotate: -90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dark\:rotate-0:is(.dark *){--tw-rotate: 0deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dark\:scale-0:is(.dark *){--tw-scale-x: 0;--tw-scale-y: 0;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dark\:scale-100:is(.dark *){--tw-scale-x: 1;--tw-scale-y: 1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dark\:border-amber-500\/30:is(.dark *){border-color:#f59e0b4d}.dark\:border-emerald-500\/30:is(.dark *){border-color:#10b9814d}.dark\:border-red-500\/30:is(.dark *){border-color:#ef44444d}.dark\:border-sky-500\/30:is(.dark *){border-color:#0ea5e94d}.dark\:border-zinc-500\/30:is(.dark *){border-color:#71717a4d}.dark\:bg-amber-500\/10:is(.dark *){background-color:#f59e0b1a}.dark\:bg-emerald-500\/10:is(.dark *){background-color:#10b9811a}.dark\:bg-red-500\/10:is(.dark *){background-color:#ef44441a}.dark\:bg-sky-500\/10:is(.dark *){background-color:#0ea5e91a}.dark\:bg-zinc-500\/10:is(.dark *){background-color:#71717a1a}.dark\:text-amber-200:is(.dark *){--tw-text-opacity: 1;color:rgb(253 230 138 / var(--tw-text-opacity))}.dark\:text-emerald-200:is(.dark *){--tw-text-opacity: 1;color:rgb(167 243 208 / var(--tw-text-opacity))}.dark\:text-red-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity))}.dark\:text-sky-200:is(.dark *){--tw-text-opacity: 1;color:rgb(186 230 253 / var(--tw-text-opacity))}.dark\:text-zinc-300:is(.dark *){--tw-text-opacity: 1;color:rgb(212 212 216 / var(--tw-text-opacity))}@media (min-width: 640px){.sm\:m-4{margin:1rem}.sm\:inline{display:inline}.sm\:max-h-\[600px\]{max-height:600px}.sm\:max-w-\[650px\]{max-width:650px}.sm\:max-w-\[740px\]{max-width:740px}.sm\:max-w-\[950px\]{max-width:950px}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-\[10rem_1fr_10rem\]{grid-template-columns:10rem 1fr 10rem}.sm\:flex-row{flex-direction:row}.sm\:justify-end{justify-content:flex-end}.sm\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:rounded-lg{border-radius:var(--radius)}.sm\:text-left{text-align:left}}@media (min-width: 768px){.md\:inline{display:inline}.md\:flex{display:flex}.md\:w-64{width:16rem}.md\:w-full{width:100%}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:flex-row{flex-direction:row}.md\:gap-8{gap:2rem}}@media (min-width: 1024px){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}@media (min-width: 1280px){.xl\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}.\[\&\:has\(\[role\=checkbox\]\)\]\:pr-0:has([role=checkbox]){padding-right:0}.\[\&\>\*\]\:p-4>*{padding:1rem}.\[\&\>\*\]\:px-4>*{padding-left:1rem;padding-right:1rem}.\[\&\>\*\]\:py-2>*{padding-top:.5rem;padding-bottom:.5rem}.\[\&\>div\[style\]\]\:\!block>div[style]{display:block!important}.\[\&\>div\[style\]\]\:h-full>div[style]{height:100%}.\[\&\>span\]\:line-clamp-1>span{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\[\&\>svg\+div\]\:translate-y-\[-3px\]>svg+div{--tw-translate-y: -3px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\[\&\>svg\]\:absolute>svg{position:absolute}.\[\&\>svg\]\:left-4>svg{left:1rem}.\[\&\>svg\]\:top-4>svg{top:1rem}.\[\&\>svg\]\:h-2\.5>svg{height:.625rem}.\[\&\>svg\]\:h-3>svg{height:.75rem}.\[\&\>svg\]\:w-2\.5>svg{width:.625rem}.\[\&\>svg\]\:w-3>svg{width:.75rem}.\[\&\>svg\]\:fill-rose-600>svg{fill:#e11d48}.\[\&\>svg\]\:text-amber-500>svg{--tw-text-opacity: 1;color:rgb(245 158 11 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-emerald-600>svg{--tw-text-opacity: 1;color:rgb(5 150 105 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-foreground>svg{color:hsl(var(--foreground))}.\[\&\>svg\]\:text-muted-foreground>svg{color:hsl(var(--muted-foreground))}.\[\&\>svg\]\:text-red-600>svg{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-sky-500>svg{--tw-text-opacity: 1;color:rgb(14 165 233 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-zinc-400>svg{--tw-text-opacity: 1;color:rgb(161 161 170 / var(--tw-text-opacity))}.hover\:\[\&\>svg\]\:fill-rose-700>svg:hover{fill:#be123c}.dark\:\[\&\>svg\]\:text-emerald-400\/80>svg:is(.dark *){color:#34d399cc}.dark\:\[\&\>svg\]\:text-red-400\/80>svg:is(.dark *){color:#f87171cc}.dark\:\[\&\>svg\]\:text-zinc-300>svg:is(.dark *){--tw-text-opacity: 1;color:rgb(212 212 216 / var(--tw-text-opacity))}.\[\&\>svg\~\*\]\:pl-7>svg~*{padding-left:1.75rem}.\[\&\>tr\]\:last\:border-b-0:last-child>tr{border-bottom-width:0px}.\[\&\[data-panel-group-direction\=vertical\]\>div\]\:rotate-90[data-panel-group-direction=vertical]>div{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\[\&_\.recharts-cartesian-axis-tick_text\]\:fill-muted-foreground .recharts-cartesian-axis-tick text{fill:hsl(var(--muted-foreground))}.\[\&_\.recharts-cartesian-grid_line\[stroke\=\'\#ccc\'\]\]\:stroke-border\/50 .recharts-cartesian-grid line[stroke="#ccc"]{stroke:hsl(var(--border) / .5)}.\[\&_\.recharts-curve\.recharts-tooltip-cursor\]\:stroke-border .recharts-curve.recharts-tooltip-cursor{stroke:hsl(var(--border))}.\[\&_\.recharts-dot\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-dot[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-layer\]\:outline-none .recharts-layer{outline:2px solid transparent;outline-offset:2px}.\[\&_\.recharts-polar-grid_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-polar-grid [stroke="#ccc"]{stroke:hsl(var(--border))}.\[\&_\.recharts-radial-bar-background-sector\]\:fill-muted .recharts-radial-bar-background-sector,.\[\&_\.recharts-rectangle\.recharts-tooltip-cursor\]\:fill-muted .recharts-rectangle.recharts-tooltip-cursor{fill:hsl(var(--muted))}.\[\&_\.recharts-reference-line_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-reference-line [stroke="#ccc"]{stroke:hsl(var(--border))}.\[\&_\.recharts-sector\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-sector[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-sector\]\:outline-none .recharts-sector,.\[\&_\.recharts-surface\]\:outline-none .recharts-surface{outline:2px solid transparent;outline-offset:2px}.\[\&_\[cmdk-group-heading\]\]\:px-2 [cmdk-group-heading]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-group-heading\]\]\:py-1\.5 [cmdk-group-heading]{padding-top:.375rem;padding-bottom:.375rem}.\[\&_\[cmdk-group-heading\]\]\:text-xs [cmdk-group-heading]{font-size:.75rem;line-height:1rem}.\[\&_\[cmdk-group-heading\]\]\:font-medium [cmdk-group-heading]{font-weight:500}.\[\&_\[cmdk-group-heading\]\]\:text-muted-foreground [cmdk-group-heading]{color:hsl(var(--muted-foreground))}.\[\&_\[cmdk-group\]\:not\(\[hidden\]\)_\~\[cmdk-group\]\]\:pt-0 [cmdk-group]:not([hidden])~[cmdk-group]{padding-top:0}.\[\&_\[cmdk-group\]\]\:px-2 [cmdk-group]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-input-wrapper\]_svg\]\:h-5 [cmdk-input-wrapper] svg{height:1.25rem}.\[\&_\[cmdk-input-wrapper\]_svg\]\:w-5 [cmdk-input-wrapper] svg{width:1.25rem}.\[\&_\[cmdk-input\]\]\:h-12 [cmdk-input]{height:3rem}.\[\&_\[cmdk-item\]\]\:px-2 [cmdk-item]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-item\]\]\:py-3 [cmdk-item]{padding-top:.75rem;padding-bottom:.75rem}.\[\&_\[cmdk-item\]_svg\]\:h-5 [cmdk-item] svg{height:1.25rem}.\[\&_\[cmdk-item\]_svg\]\:w-5 [cmdk-item] svg{width:1.25rem}.\[\&_p\]\:leading-relaxed p{line-height:1.625}.\[\&_strong\]\:text-foreground strong{color:hsl(var(--foreground))}.\[\&_tr\:last-child\]\:border-0 tr:last-child{border-width:0px}.\[\&_tr\]\:border-b tr{border-bottom-width:1px}:root{--toastify-color-light: #fff;--toastify-color-dark: #121212;--toastify-color-info: #3498db;--toastify-color-success: #07bc0c;--toastify-color-warning: #f1c40f;--toastify-color-error: #e74c3c;--toastify-color-transparent: rgba(255, 255, 255, .7);--toastify-icon-color-info: var(--toastify-color-info);--toastify-icon-color-success: var(--toastify-color-success);--toastify-icon-color-warning: var(--toastify-color-warning);--toastify-icon-color-error: var(--toastify-color-error);--toastify-toast-width: 320px;--toastify-toast-offset: 16px;--toastify-toast-top: max(var(--toastify-toast-offset), env(safe-area-inset-top));--toastify-toast-right: max(var(--toastify-toast-offset), env(safe-area-inset-right));--toastify-toast-left: max(var(--toastify-toast-offset), env(safe-area-inset-left));--toastify-toast-bottom: max(var(--toastify-toast-offset), env(safe-area-inset-bottom));--toastify-toast-background: #fff;--toastify-toast-min-height: 64px;--toastify-toast-max-height: 800px;--toastify-toast-bd-radius: 6px;--toastify-font-family: sans-serif;--toastify-z-index: 9999;--toastify-text-color-light: #757575;--toastify-text-color-dark: #fff;--toastify-text-color-info: #fff;--toastify-text-color-success: #fff;--toastify-text-color-warning: #fff;--toastify-text-color-error: #fff;--toastify-spinner-color: #616161;--toastify-spinner-color-empty-area: #e0e0e0;--toastify-color-progress-light: linear-gradient( to right, #4cd964, #5ac8fa, #007aff, #34aadc, #5856d6, #ff2d55 );--toastify-color-progress-dark: #bb86fc;--toastify-color-progress-info: var(--toastify-color-info);--toastify-color-progress-success: var(--toastify-color-success);--toastify-color-progress-warning: var(--toastify-color-warning);--toastify-color-progress-error: var(--toastify-color-error);--toastify-color-progress-bgo: .2}.Toastify__toast-container{z-index:var(--toastify-z-index);-webkit-transform:translate3d(0,0,var(--toastify-z-index));position:fixed;padding:4px;width:var(--toastify-toast-width);box-sizing:border-box;color:#fff}.Toastify__toast-container--top-left{top:var(--toastify-toast-top);left:var(--toastify-toast-left)}.Toastify__toast-container--top-center{top:var(--toastify-toast-top);left:50%;transform:translate(-50%)}.Toastify__toast-container--top-right{top:var(--toastify-toast-top);right:var(--toastify-toast-right)}.Toastify__toast-container--bottom-left{bottom:var(--toastify-toast-bottom);left:var(--toastify-toast-left)}.Toastify__toast-container--bottom-center{bottom:var(--toastify-toast-bottom);left:50%;transform:translate(-50%)}.Toastify__toast-container--bottom-right{bottom:var(--toastify-toast-bottom);right:var(--toastify-toast-right)}@media only screen and (max-width : 480px){.Toastify__toast-container{width:100vw;padding:0;left:env(safe-area-inset-left);margin:0}.Toastify__toast-container--top-left,.Toastify__toast-container--top-center,.Toastify__toast-container--top-right{top:env(safe-area-inset-top);transform:translate(0)}.Toastify__toast-container--bottom-left,.Toastify__toast-container--bottom-center,.Toastify__toast-container--bottom-right{bottom:env(safe-area-inset-bottom);transform:translate(0)}.Toastify__toast-container--rtl{right:env(safe-area-inset-right);left:initial}}.Toastify__toast{--y: 0;position:relative;touch-action:none;min-height:var(--toastify-toast-min-height);box-sizing:border-box;margin-bottom:1rem;padding:8px;border-radius:var(--toastify-toast-bd-radius);box-shadow:0 4px 12px #0000001a;display:flex;justify-content:space-between;max-height:var(--toastify-toast-max-height);font-family:var(--toastify-font-family);cursor:default;direction:ltr;z-index:0;overflow:hidden}.Toastify__toast--stacked{position:absolute;width:100%;transform:translate3d(0,var(--y),0) scale(var(--s));transition:transform .3s}.Toastify__toast--stacked[data-collapsed] .Toastify__toast-body,.Toastify__toast--stacked[data-collapsed] .Toastify__close-button{transition:opacity .1s}.Toastify__toast--stacked[data-collapsed=false]{overflow:visible}.Toastify__toast--stacked[data-collapsed=true]:not(:last-child)>*{opacity:0}.Toastify__toast--stacked:after{content:"";position:absolute;left:0;right:0;height:calc(var(--g) * 1px);bottom:100%}.Toastify__toast--stacked[data-pos=top]{top:0}.Toastify__toast--stacked[data-pos=bot]{bottom:0}.Toastify__toast--stacked[data-pos=bot].Toastify__toast--stacked:before{transform-origin:top}.Toastify__toast--stacked[data-pos=top].Toastify__toast--stacked:before{transform-origin:bottom}.Toastify__toast--stacked:before{content:"";position:absolute;left:0;right:0;bottom:0;height:100%;transform:scaleY(3);z-index:-1}.Toastify__toast--rtl{direction:rtl}.Toastify__toast--close-on-click{cursor:pointer}.Toastify__toast-body{margin:auto 0;flex:1 1 auto;padding:6px;display:flex;align-items:center}.Toastify__toast-body>div:last-child{word-break:break-word;flex:1}.Toastify__toast-icon{margin-inline-end:10px;width:20px;flex-shrink:0;display:flex}.Toastify--animate{animation-fill-mode:both;animation-duration:.5s}.Toastify--animate-icon{animation-fill-mode:both;animation-duration:.3s}@media only screen and (max-width : 480px){.Toastify__toast{margin-bottom:0;border-radius:0}}.Toastify__toast-theme--dark{background:var(--toastify-color-dark);color:var(--toastify-text-color-dark)}.Toastify__toast-theme--light,.Toastify__toast-theme--colored.Toastify__toast--default{background:var(--toastify-color-light);color:var(--toastify-text-color-light)}.Toastify__toast-theme--colored.Toastify__toast--info{color:var(--toastify-text-color-info);background:var(--toastify-color-info)}.Toastify__toast-theme--colored.Toastify__toast--success{color:var(--toastify-text-color-success);background:var(--toastify-color-success)}.Toastify__toast-theme--colored.Toastify__toast--warning{color:var(--toastify-text-color-warning);background:var(--toastify-color-warning)}.Toastify__toast-theme--colored.Toastify__toast--error{color:var(--toastify-text-color-error);background:var(--toastify-color-error)}.Toastify__progress-bar-theme--light{background:var(--toastify-color-progress-light)}.Toastify__progress-bar-theme--dark{background:var(--toastify-color-progress-dark)}.Toastify__progress-bar--info{background:var(--toastify-color-progress-info)}.Toastify__progress-bar--success{background:var(--toastify-color-progress-success)}.Toastify__progress-bar--warning{background:var(--toastify-color-progress-warning)}.Toastify__progress-bar--error{background:var(--toastify-color-progress-error)}.Toastify__progress-bar-theme--colored.Toastify__progress-bar--info,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--success,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--warning,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--error{background:var(--toastify-color-transparent)}.Toastify__close-button{color:#fff;background:transparent;outline:none;border:none;padding:0;cursor:pointer;opacity:.7;transition:.3s ease;align-self:flex-start;z-index:1}.Toastify__close-button--light{color:#000;opacity:.3}.Toastify__close-button>svg{fill:currentColor;height:16px;width:14px}.Toastify__close-button:hover,.Toastify__close-button:focus{opacity:1}@keyframes Toastify__trackProgress{0%{transform:scaleX(1)}to{transform:scaleX(0)}}.Toastify__progress-bar{position:absolute;bottom:0;left:0;width:100%;height:100%;z-index:var(--toastify-z-index);opacity:.7;transform-origin:left;border-bottom-left-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--animated{animation:Toastify__trackProgress linear 1 forwards}.Toastify__progress-bar--controlled{transition:transform .2s}.Toastify__progress-bar--rtl{right:0;left:initial;transform-origin:right;border-bottom-left-radius:initial;border-bottom-right-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--wrp{position:absolute;bottom:0;left:0;width:100%;height:5px;border-bottom-left-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--wrp[data-hidden=true]{opacity:0}.Toastify__progress-bar--bg{opacity:var(--toastify-color-progress-bgo);width:100%;height:100%}.Toastify__spinner{width:20px;height:20px;box-sizing:border-box;border:2px solid;border-radius:100%;border-color:var(--toastify-spinner-color-empty-area);border-right-color:var(--toastify-spinner-color);animation:Toastify__spin .65s linear infinite}@keyframes Toastify__bounceInRight{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(3000px,0,0)}60%{opacity:1;transform:translate3d(-25px,0,0)}75%{transform:translate3d(10px,0,0)}90%{transform:translate3d(-5px,0,0)}to{transform:none}}@keyframes Toastify__bounceOutRight{20%{opacity:1;transform:translate3d(-20px,var(--y),0)}to{opacity:0;transform:translate3d(2000px,var(--y),0)}}@keyframes Toastify__bounceInLeft{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(-3000px,0,0)}60%{opacity:1;transform:translate3d(25px,0,0)}75%{transform:translate3d(-10px,0,0)}90%{transform:translate3d(5px,0,0)}to{transform:none}}@keyframes Toastify__bounceOutLeft{20%{opacity:1;transform:translate3d(20px,var(--y),0)}to{opacity:0;transform:translate3d(-2000px,var(--y),0)}}@keyframes Toastify__bounceInUp{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(0,3000px,0)}60%{opacity:1;transform:translate3d(0,-20px,0)}75%{transform:translate3d(0,10px,0)}90%{transform:translate3d(0,-5px,0)}to{transform:translateZ(0)}}@keyframes Toastify__bounceOutUp{20%{transform:translate3d(0,calc(var(--y) - 10px),0)}40%,45%{opacity:1;transform:translate3d(0,calc(var(--y) + 20px),0)}to{opacity:0;transform:translate3d(0,-2000px,0)}}@keyframes Toastify__bounceInDown{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(0,-3000px,0)}60%{opacity:1;transform:translate3d(0,25px,0)}75%{transform:translate3d(0,-10px,0)}90%{transform:translate3d(0,5px,0)}to{transform:none}}@keyframes Toastify__bounceOutDown{20%{transform:translate3d(0,calc(var(--y) - 10px),0)}40%,45%{opacity:1;transform:translate3d(0,calc(var(--y) + 20px),0)}to{opacity:0;transform:translate3d(0,2000px,0)}}.Toastify__bounce-enter--top-left,.Toastify__bounce-enter--bottom-left{animation-name:Toastify__bounceInLeft}.Toastify__bounce-enter--top-right,.Toastify__bounce-enter--bottom-right{animation-name:Toastify__bounceInRight}.Toastify__bounce-enter--top-center{animation-name:Toastify__bounceInDown}.Toastify__bounce-enter--bottom-center{animation-name:Toastify__bounceInUp}.Toastify__bounce-exit--top-left,.Toastify__bounce-exit--bottom-left{animation-name:Toastify__bounceOutLeft}.Toastify__bounce-exit--top-right,.Toastify__bounce-exit--bottom-right{animation-name:Toastify__bounceOutRight}.Toastify__bounce-exit--top-center{animation-name:Toastify__bounceOutUp}.Toastify__bounce-exit--bottom-center{animation-name:Toastify__bounceOutDown}@keyframes Toastify__zoomIn{0%{opacity:0;transform:scale3d(.3,.3,.3)}50%{opacity:1}}@keyframes Toastify__zoomOut{0%{opacity:1}50%{opacity:0;transform:translate3d(0,var(--y),0) scale3d(.3,.3,.3)}to{opacity:0}}.Toastify__zoom-enter{animation-name:Toastify__zoomIn}.Toastify__zoom-exit{animation-name:Toastify__zoomOut}@keyframes Toastify__flipIn{0%{transform:perspective(400px) rotateX(90deg);animation-timing-function:ease-in;opacity:0}40%{transform:perspective(400px) rotateX(-20deg);animation-timing-function:ease-in}60%{transform:perspective(400px) rotateX(10deg);opacity:1}80%{transform:perspective(400px) rotateX(-5deg)}to{transform:perspective(400px)}}@keyframes Toastify__flipOut{0%{transform:translate3d(0,var(--y),0) perspective(400px)}30%{transform:translate3d(0,var(--y),0) perspective(400px) rotateX(-20deg);opacity:1}to{transform:translate3d(0,var(--y),0) perspective(400px) rotateX(90deg);opacity:0}}.Toastify__flip-enter{animation-name:Toastify__flipIn}.Toastify__flip-exit{animation-name:Toastify__flipOut}@keyframes Toastify__slideInRight{0%{transform:translate3d(110%,0,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInLeft{0%{transform:translate3d(-110%,0,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInUp{0%{transform:translate3d(0,110%,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInDown{0%{transform:translate3d(0,-110%,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideOutRight{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(110%,var(--y),0)}}@keyframes Toastify__slideOutLeft{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(-110%,var(--y),0)}}@keyframes Toastify__slideOutDown{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(0,500px,0)}}@keyframes Toastify__slideOutUp{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(0,-500px,0)}}.Toastify__slide-enter--top-left,.Toastify__slide-enter--bottom-left{animation-name:Toastify__slideInLeft}.Toastify__slide-enter--top-right,.Toastify__slide-enter--bottom-right{animation-name:Toastify__slideInRight}.Toastify__slide-enter--top-center{animation-name:Toastify__slideInDown}.Toastify__slide-enter--bottom-center{animation-name:Toastify__slideInUp}.Toastify__slide-exit--top-left,.Toastify__slide-exit--bottom-left{animation-name:Toastify__slideOutLeft;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--top-right,.Toastify__slide-exit--bottom-right{animation-name:Toastify__slideOutRight;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--top-center{animation-name:Toastify__slideOutUp;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--bottom-center{animation-name:Toastify__slideOutDown;animation-timing-function:ease-in;animation-duration:.3s}@keyframes Toastify__spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.tabs-chat{background-color:transparent;width:100%;border-radius:0}.chat-item{display:flex;padding:10px;cursor:pointer;background-color:hsl(var(--background))}.chat-item:hover,.chat-item.active{background-color:#2f2f2f}.bubble{border-radius:16px;padding:12px;word-wrap:break-word}.bubble-right .bubble{background-color:#0a0a0a;text-align:right;max-width:100%}.bubble-left .bubble{background-color:#1b1b1b;max-width:100%}.bubble-right{align-self:flex-end;display:flex;justify-content:flex-end;width:80%}.bubble-left{align-self:flex-start;display:flex;justify-content:flex-start;width:80%}.input-message textarea{background-color:#2f2f2f;padding-left:48px}.input-message textarea:focus{outline:none;border:none;box-shadow:none}.message-container{flex:1;overflow-y:auto;max-height:calc(100vh - 110px);padding-top:50px} diff --git a/manager/dist/assets/index-DZ0gaAHg.css b/manager/dist/assets/index-DZ0gaAHg.css deleted file mode 100644 index 463a8154..00000000 --- a/manager/dist/assets/index-DZ0gaAHg.css +++ /dev/null @@ -1 +0,0 @@ -@import"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap";*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}:root{--background: 0 0% 100%;--foreground: 222.2 84% 4.9%;--card: 0 0% 100%;--card-foreground: 222.2 84% 4.9%;--popover: 0 0% 100%;--popover-foreground: 222.2 84% 4.9%;--primary: 222.2 47.4% 11.2%;--primary-foreground: 210 40% 98%;--secondary: 210 40% 96.1%;--secondary-foreground: 222.2 47.4% 11.2%;--muted: 210 40% 96.1%;--muted-foreground: 215.4 16.3% 46.9%;--accent: 210 40% 96.1%;--accent-foreground: 222.2 47.4% 11.2%;--destructive: 0 84.2% 60.2%;--destructive-foreground: 210 40% 98%;--border: 214.3 31.8% 91.4%;--input: 214.3 31.8% 91.4%;--ring: 222.2 84% 4.9%;--radius: .5rem;--chart-1: 12 76% 61%;--chart-2: 173 58% 39%;--chart-3: 197 37% 24%;--chart-4: 43 74% 66%;--chart-5: 27 87% 67%}.dark{--background: 220, 4%, 13%;--foreground: 210 40% 98%;--header: 120, 3%, 7%;--card: 220, 4%, 13%;--card-foreground: 210 40% 98%;--popover: 220, 4%, 13%;--popover-foreground: 210 40% 98%;--primary: 152.8 77.1% 38.8%;--primary-foreground: 229, 9%, 23%;--secondary: 217.2 32.6% 17.5%;--secondary-foreground: 210 40% 98%;--muted: 217.2 32.6% 17.5%;--muted-foreground: 215 20.2% 65.1%;--accent: 217.2 32.6% 17.5%;--accent-foreground: 210 40% 98%;--destructive: 0 62.8% 30.6%;--destructive-foreground: 210 40% 98%;--border: 217.2 32.6% 17.5%;--input: 217.2 32.6% 17.5%;--ring: 212.7 26.8% 83.9%;--chart-1: 220 70% 50%;--chart-2: 160 60% 45%;--chart-3: 30 80% 55%;--chart-4: 280 65% 60%;--chart-5: 340 75% 55%}*{border-color:hsl(var(--border))}body{background-color:hsl(var(--background));color:hsl(var(--foreground));font-family:Inter,sans-serif;scrollbar-width:thin;scrollbar-color:transparent transparent}header{display:flex;justify-content:space-between;align-items:center;padding:1rem 2rem;background-color:hsl(var(--header-background))}.header-logo{display:flex;align-items:center}.header-logo img{height:30px;margin-right:1rem}.header-title{font-size:1rem;color:hsl(var(--secondary-foreground))}.header-buttons{display:flex;align-items:center}.header-buttons button{margin-left:1rem}.exit-button{background-color:hsl(var(--destructive));padding:.5rem;border-radius:50%;border:none;cursor:pointer;display:flex;justify-content:center;align-items:center}.exit-button:hover{background-color:hsl(var(--muted))}.profile-button{background-color:#fff;border-radius:50%;border:none;cursor:pointer;display:flex;justify-content:center;align-items:center}.profile-picture{width:32px;height:32px;border-radius:50%;-o-object-fit:cover;object-fit:cover}.layout{display:flex;flex-direction:column;height:100%;background-color:hsl(var(--header))}.content{height:calc(100vh - 66px)}footer{display:flex;justify-content:space-between;align-items:center;padding:1.5rem;color:hsl(var(--secondary-foreground));position:fixed;width:100%;bottom:0;background-color:hsl(var(--header))}.footer-buttons{display:flex;gap:.5rem}.footer-buttons button{background-color:hsl(var(--header));padding:.5rem .8rem;border:none;border-radius:.25rem;cursor:pointer}.footer-buttons button a{font-size:.7rem}.footer-info{font-size:.75rem}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{top:0;right:0;bottom:0;left:0}.bottom-0{bottom:0}.bottom-3{bottom:.75rem}.left-2{left:.5rem}.left-3{left:.75rem}.left-\[50\%\]{left:50%}.right-2{right:.5rem}.right-3{right:.75rem}.right-4{right:1rem}.top-0{top:0}.top-2{top:.5rem}.top-4{top:1rem}.top-\[50\%\]{top:50%}.z-10{z-index:10}.z-50{z-index:50}.z-\[100\]{z-index:100}.col-span-3{grid-column:span 3 / span 3}.-mx-1{margin-left:-.25rem;margin-right:-.25rem}.mx-auto{margin-left:auto;margin-right:auto}.my-0\.5{margin-top:.125rem;margin-bottom:.125rem}.my-1{margin-top:.25rem;margin-bottom:.25rem}.my-4{margin-top:1rem;margin-bottom:1rem}.mb-1{margin-bottom:.25rem}.mb-4{margin-bottom:1rem}.ml-2{margin-left:.5rem}.ml-4{margin-left:1rem}.ml-5{margin-left:1.25rem}.ml-auto{margin-left:auto}.mr-2{margin-right:.5rem}.mr-5{margin-right:1.25rem}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.block{display:block}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.aspect-square{aspect-ratio:1 / 1}.aspect-video{aspect-ratio:16 / 9}.h-10{height:2.5rem}.h-11{height:2.75rem}.h-12{height:3rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-24{height:6rem}.h-3\.5{height:.875rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-\[1\.2rem\]{height:1.2rem}.h-\[1px\]{height:1px}.h-\[var\(--radix-select-trigger-height\)\]{height:var(--radix-select-trigger-height)}.h-full{height:100%}.h-px{height:1px}.max-h-96{max-height:24rem}.max-h-\[240px\]{max-height:240px}.max-h-\[300px\]{max-height:300px}.max-h-screen{max-height:100vh}.min-h-\[48px\]{min-height:48px}.min-h-\[80px\]{min-height:80px}.min-h-screen{min-height:100vh}.w-0{width:0px}.w-1{width:.25rem}.w-10{width:2.5rem}.w-11{width:2.75rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-7{width:1.75rem}.w-72{width:18rem}.w-8{width:2rem}.w-\[1\.2rem\]{width:1.2rem}.w-\[1px\]{width:1px}.w-\[350px\]{width:350px}.w-full{width:100%}.w-px{width:1px}.min-w-0{min-width:0px}.min-w-\[8rem\]{min-width:8rem}.min-w-\[var\(--radix-select-trigger-width\)\]{min-width:var(--radix-select-trigger-width)}.max-w-2xl{max-width:42rem}.max-w-4xl{max-width:56rem}.max-w-\[300px\]{max-width:300px}.max-w-lg{max-width:32rem}.max-w-sm{max-width:24rem}.flex-1{flex:1 1 0%}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.caption-bottom{caption-side:bottom}.translate-x-\[-50\%\]{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-1{--tw-translate-y: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-\[-50\%\]{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-0{--tw-rotate: 0deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-90{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-0{--tw-scale-x: 0;--tw-scale-y: 0;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-100{--tw-scale-x: 1;--tw-scale-y: 1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.touch-none{touch-action:none}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-none{resize:none}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.items-stretch{align-items:stretch}.justify-start{justify-content:flex-start}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-4{gap:1rem}.gap-8{gap:2rem}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.self-end{align-self:flex-end}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-visible{overflow:visible}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.text-ellipsis{text-overflow:ellipsis}.whitespace-nowrap{white-space:nowrap}.rounded-3xl{border-radius:1.5rem}.rounded-\[2px\]{border-radius:2px}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-\[1\.5px\]{border-width:1.5px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-none{border-style:none}.border-\[--color-border\]{border-color:var(--color-border)}.border-black{--tw-border-opacity: 1;border-color:rgb(0 0 0 / var(--tw-border-opacity))}.border-border\/50{border-color:hsl(var(--border) / .5)}.border-destructive{border-color:hsl(var(--destructive))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity))}.border-gray-600{--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity))}.border-gray-600\/50{border-color:#4b556380}.border-gray-700{--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity))}.border-input{border-color:hsl(var(--input))}.border-muted{border-color:hsl(var(--muted))}.border-transparent{border-color:transparent}.border-l-transparent{border-left-color:transparent}.border-t-transparent{border-top-color:transparent}.bg-\[--color-bg\]{background-color:var(--color-bg)}.bg-background{background-color:hsl(var(--background))}.bg-black\/80{background-color:#000c}.bg-blue-400{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity))}.bg-border{background-color:hsl(var(--border))}.bg-card{background-color:hsl(var(--card))}.bg-destructive{background-color:hsl(var(--destructive))}.bg-muted{background-color:hsl(var(--muted))}.bg-muted\/50{background-color:hsl(var(--muted) / .5)}.bg-popover{background-color:hsl(var(--popover))}.bg-primary{background-color:hsl(var(--primary))}.bg-red-400{--tw-bg-opacity: 1;background-color:rgb(248 113 113 / var(--tw-bg-opacity))}.bg-secondary{background-color:hsl(var(--secondary))}.bg-transparent{background-color:transparent}.fill-current{fill:currentColor}.p-0{padding:0}.p-1{padding:.25rem}.p-2{padding:.5rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-\[1px\]{padding:1px}.px-1{padding-left:.25rem;padding-right:.25rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.pb-3{padding-bottom:.75rem}.pb-4{padding-bottom:1rem}.pl-12{padding-left:3rem}.pl-8{padding-left:2rem}.pr-16{padding-right:4rem}.pr-2{padding-right:.5rem}.pr-8{padding-right:2rem}.pt-0{padding-top:0}.pt-2{padding-top:.5rem}.pt-3{padding-top:.75rem}.pt-5{padding-top:1.25rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-medium{font-weight:500}.font-semibold{font-weight:600}.tabular-nums{--tw-numeric-spacing: tabular-nums;font-variant-numeric:var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)}.leading-none{line-height:1}.tracking-tight{letter-spacing:-.025em}.tracking-widest{letter-spacing:.1em}.text-card-foreground{color:hsl(var(--card-foreground))}.text-destructive{color:hsl(var(--destructive))}.text-destructive-foreground{color:hsl(var(--destructive-foreground))}.text-foreground{color:hsl(var(--foreground))}.text-foreground\/50{color:hsl(var(--foreground) / .5)}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity))}.text-muted-foreground{color:hsl(var(--muted-foreground))}.text-muted-foreground\/80{color:hsl(var(--muted-foreground) / .8)}.text-popover-foreground{color:hsl(var(--popover-foreground))}.text-primary{color:hsl(var(--primary))}.text-primary-foreground{color:hsl(var(--primary-foreground))}.text-secondary-foreground{color:hsl(var(--secondary-foreground))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity))}.underline-offset-4{text-underline-offset:4px}.caret-transparent{caret-color:transparent}.opacity-0{opacity:0}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-90{opacity:.9}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.ring-0{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-muted-foreground{--tw-ring-color: hsl(var(--muted-foreground))}.ring-offset-background{--tw-ring-offset-color: hsl(var(--background))}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}@keyframes enter{0%{opacity:var(--tw-enter-opacity, 1);transform:translate3d(var(--tw-enter-translate-x, 0),var(--tw-enter-translate-y, 0),0) scale3d(var(--tw-enter-scale, 1),var(--tw-enter-scale, 1),var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity, 1);transform:translate3d(var(--tw-exit-translate-x, 0),var(--tw-exit-translate-y, 0),0) scale3d(var(--tw-exit-scale, 1),var(--tw-exit-scale, 1),var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0))}}.duration-200{animation-duration:.2s}.paused{animation-play-state:paused}.file\:border-0::file-selector-button{border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\:font-medium::file-selector-button{font-weight:500}.placeholder\:text-muted-foreground::-moz-placeholder{color:hsl(var(--muted-foreground))}.placeholder\:text-muted-foreground::placeholder{color:hsl(var(--muted-foreground))}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:inset-y-0:after{content:var(--tw-content);top:0;bottom:0}.after\:left-1\/2:after{content:var(--tw-content);left:50%}.after\:w-1:after{content:var(--tw-content);width:.25rem}.after\:-translate-x-1\/2:after{content:var(--tw-content);--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:bg-accent:hover{background-color:hsl(var(--accent))}.hover\:bg-blue-600:hover{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity))}.hover\:bg-destructive\/80:hover{background-color:hsl(var(--destructive) / .8)}.hover\:bg-destructive\/90:hover{background-color:hsl(var(--destructive) / .9)}.hover\:bg-muted\/50:hover{background-color:hsl(var(--muted) / .5)}.hover\:bg-primary\/80:hover{background-color:hsl(var(--primary) / .8)}.hover\:bg-primary\/90:hover{background-color:hsl(var(--primary) / .9)}.hover\:bg-red-600:hover{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity))}.hover\:bg-secondary:hover{background-color:hsl(var(--secondary))}.hover\:bg-secondary\/80:hover{background-color:hsl(var(--secondary) / .8)}.hover\:bg-transparent:hover{background-color:transparent}.hover\:stroke-destructive:hover{stroke:hsl(var(--destructive))}.hover\:text-accent-foreground:hover{color:hsl(var(--accent-foreground))}.hover\:text-foreground:hover{color:hsl(var(--foreground))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.focus\:bg-accent:focus{background-color:hsl(var(--accent))}.focus\:text-accent-foreground:focus{color:hsl(var(--accent-foreground))}.focus\:opacity-100:focus{opacity:1}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-ring:focus{--tw-ring-color: hsl(var(--ring))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus-visible\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\:ring-1:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-ring:focus-visible{--tw-ring-color: hsl(var(--ring))}.focus-visible\:ring-offset-1:focus-visible{--tw-ring-offset-width: 1px}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.focus-visible\:ring-offset-background:focus-visible{--tw-ring-offset-color: hsl(var(--background))}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.group:hover .group-hover\:opacity-100{opacity:1}.group.destructive .group-\[\.destructive\]\:border-muted\/40{border-color:hsl(var(--muted) / .4)}.group.destructive .group-\[\.destructive\]\:text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity))}.group.destructive .group-\[\.destructive\]\:hover\:border-destructive\/30:hover{border-color:hsl(var(--destructive) / .3)}.group.destructive .group-\[\.destructive\]\:hover\:bg-destructive:hover{background-color:hsl(var(--destructive))}.group.destructive .group-\[\.destructive\]\:hover\:text-destructive-foreground:hover{color:hsl(var(--destructive-foreground))}.group.destructive .group-\[\.destructive\]\:hover\:text-red-50:hover{--tw-text-opacity: 1;color:rgb(254 242 242 / var(--tw-text-opacity))}.group.destructive .group-\[\.destructive\]\:focus\:ring-destructive:focus{--tw-ring-color: hsl(var(--destructive))}.group.destructive .group-\[\.destructive\]\:focus\:ring-red-400:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(248 113 113 / var(--tw-ring-opacity))}.group.destructive .group-\[\.destructive\]\:focus\:ring-offset-red-600:focus{--tw-ring-offset-color: #dc2626}.peer:disabled~.peer-disabled\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\:opacity-70{opacity:.7}.aria-selected\:bg-accent[aria-selected=true]{background-color:hsl(var(--accent))}.aria-selected\:text-accent-foreground[aria-selected=true]{color:hsl(var(--accent-foreground))}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[panel-group-direction\=vertical\]\:h-px[data-panel-group-direction=vertical]{height:1px}.data-\[panel-group-direction\=vertical\]\:w-full[data-panel-group-direction=vertical]{width:100%}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=checked\]\:translate-x-5[data-state=checked]{--tw-translate-x: 1.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked],.data-\[swipe\=cancel\]\:translate-x-0[data-swipe=cancel]{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[swipe\=end\]\:translate-x-\[var\(--radix-toast-swipe-end-x\)\][data-swipe=end]{--tw-translate-x: var(--radix-toast-swipe-end-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[swipe\=move\]\:translate-x-\[var\(--radix-toast-swipe-move-x\)\][data-swipe=move]{--tw-translate-x: var(--radix-toast-swipe-move-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[panel-group-direction\=vertical\]\:flex-col[data-panel-group-direction=vertical]{flex-direction:column}.data-\[state\=active\]\:bg-background[data-state=active]{background-color:hsl(var(--background))}.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:hsl(var(--primary))}.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:hsl(var(--accent))}.data-\[state\=open\]\:bg-muted[data-state=open],.data-\[state\=selected\]\:bg-muted[data-state=selected]{background-color:hsl(var(--muted))}.data-\[state\=unchecked\]\:bg-slate-400[data-state=unchecked]{--tw-bg-opacity: 1;background-color:rgb(148 163 184 / var(--tw-bg-opacity))}.data-\[state\=active\]\:text-foreground[data-state=active]{color:hsl(var(--foreground))}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:hsl(var(--muted-foreground))}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[state\=active\]\:shadow-sm[data-state=active]{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.data-\[swipe\=move\]\:transition-none[data-swipe=move]{transition-property:none}.data-\[state\=open\]\:animate-in[data-state=open]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.data-\[state\=closed\]\:animate-out[data-state=closed],.data-\[swipe\=end\]\:animate-out[data-swipe=end]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0}.data-\[state\=closed\]\:fade-out-80[data-state=closed]{--tw-exit-opacity: .8}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: -.5rem}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: .5rem}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: -.5rem}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: .5rem}.data-\[state\=closed\]\:slide-out-to-left-1\/2[data-state=closed]{--tw-exit-translate-x: -50%}.data-\[state\=closed\]\:slide-out-to-right-full[data-state=closed]{--tw-exit-translate-x: 100%}.data-\[state\=closed\]\:slide-out-to-top-\[48\%\][data-state=closed]{--tw-exit-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-left-1\/2[data-state=open]{--tw-enter-translate-x: -50%}.data-\[state\=open\]\:slide-in-from-top-\[48\%\][data-state=open]{--tw-enter-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-top-full[data-state=open]{--tw-enter-translate-y: -100%}.data-\[panel-group-direction\=vertical\]\:after\:left-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);left:0}.data-\[panel-group-direction\=vertical\]\:after\:h-1[data-panel-group-direction=vertical]:after{content:var(--tw-content);height:.25rem}.data-\[panel-group-direction\=vertical\]\:after\:w-full[data-panel-group-direction=vertical]:after{content:var(--tw-content);width:100%}.data-\[panel-group-direction\=vertical\]\:after\:-translate-y-1\/2[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[panel-group-direction\=vertical\]\:after\:translate-x-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dark\:-rotate-90:is(.dark *){--tw-rotate: -90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dark\:rotate-0:is(.dark *){--tw-rotate: 0deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dark\:scale-0:is(.dark *){--tw-scale-x: 0;--tw-scale-y: 0;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dark\:scale-100:is(.dark *){--tw-scale-x: 1;--tw-scale-y: 1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@media (min-width: 640px){.sm\:bottom-0{bottom:0}.sm\:right-0{right:0}.sm\:top-auto{top:auto}.sm\:max-h-\[600px\]{max-height:600px}.sm\:max-w-\[650px\]{max-width:650px}.sm\:max-w-\[740px\]{max-width:740px}.sm\:max-w-\[950px\]{max-width:950px}.sm\:flex-row{flex-direction:row}.sm\:flex-col{flex-direction:column}.sm\:justify-end{justify-content:flex-end}.sm\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:rounded-lg{border-radius:var(--radius)}.sm\:text-left{text-align:left}.data-\[state\=open\]\:sm\:slide-in-from-bottom-full[data-state=open]{--tw-enter-translate-y: 100%}}@media (min-width: 768px){.md\:flex{display:flex}.md\:max-w-\[420px\]{max-width:420px}}.\[\&\:has\(\[role\=checkbox\]\)\]\:pr-0:has([role=checkbox]){padding-right:0}.\[\&\>span\]\:line-clamp-1>span{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\[\&\>svg\]\:h-2\.5>svg{height:.625rem}.\[\&\>svg\]\:h-3>svg{height:.75rem}.\[\&\>svg\]\:w-2\.5>svg{width:.625rem}.\[\&\>svg\]\:w-3>svg{width:.75rem}.\[\&\>svg\]\:text-muted-foreground>svg{color:hsl(var(--muted-foreground))}.\[\&\>tr\]\:last\:border-b-0:last-child>tr{border-bottom-width:0px}.\[\&\[data-panel-group-direction\=vertical\]\>div\]\:rotate-90[data-panel-group-direction=vertical]>div{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\[\&_\.recharts-cartesian-axis-tick_text\]\:fill-muted-foreground .recharts-cartesian-axis-tick text{fill:hsl(var(--muted-foreground))}.\[\&_\.recharts-cartesian-grid_line\[stroke\=\'\#ccc\'\]\]\:stroke-border\/50 .recharts-cartesian-grid line[stroke="#ccc"]{stroke:hsl(var(--border) / .5)}.\[\&_\.recharts-curve\.recharts-tooltip-cursor\]\:stroke-border .recharts-curve.recharts-tooltip-cursor{stroke:hsl(var(--border))}.\[\&_\.recharts-dot\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-dot[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-layer\]\:outline-none .recharts-layer{outline:2px solid transparent;outline-offset:2px}.\[\&_\.recharts-polar-grid_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-polar-grid [stroke="#ccc"]{stroke:hsl(var(--border))}.\[\&_\.recharts-radial-bar-background-sector\]\:fill-muted .recharts-radial-bar-background-sector,.\[\&_\.recharts-rectangle\.recharts-tooltip-cursor\]\:fill-muted .recharts-rectangle.recharts-tooltip-cursor{fill:hsl(var(--muted))}.\[\&_\.recharts-reference-line_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-reference-line [stroke="#ccc"]{stroke:hsl(var(--border))}.\[\&_\.recharts-sector\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-sector[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-sector\]\:outline-none .recharts-sector,.\[\&_\.recharts-surface\]\:outline-none .recharts-surface{outline:2px solid transparent;outline-offset:2px}.\[\&_\[cmdk-group-heading\]\]\:px-2 [cmdk-group-heading]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-group-heading\]\]\:py-1\.5 [cmdk-group-heading]{padding-top:.375rem;padding-bottom:.375rem}.\[\&_\[cmdk-group-heading\]\]\:text-xs [cmdk-group-heading]{font-size:.75rem;line-height:1rem}.\[\&_\[cmdk-group-heading\]\]\:font-medium [cmdk-group-heading]{font-weight:500}.\[\&_\[cmdk-group-heading\]\]\:text-muted-foreground [cmdk-group-heading]{color:hsl(var(--muted-foreground))}.\[\&_\[cmdk-group\]\:not\(\[hidden\]\)_\~\[cmdk-group\]\]\:pt-0 [cmdk-group]:not([hidden])~[cmdk-group]{padding-top:0}.\[\&_\[cmdk-group\]\]\:px-2 [cmdk-group]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-input-wrapper\]_svg\]\:h-5 [cmdk-input-wrapper] svg{height:1.25rem}.\[\&_\[cmdk-input-wrapper\]_svg\]\:w-5 [cmdk-input-wrapper] svg{width:1.25rem}.\[\&_\[cmdk-input\]\]\:h-12 [cmdk-input]{height:3rem}.\[\&_\[cmdk-item\]\]\:px-2 [cmdk-item]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-item\]\]\:py-3 [cmdk-item]{padding-top:.75rem;padding-bottom:.75rem}.\[\&_\[cmdk-item\]_svg\]\:h-5 [cmdk-item] svg{height:1.25rem}.\[\&_\[cmdk-item\]_svg\]\:w-5 [cmdk-item] svg{width:1.25rem}.\[\&_tr\:last-child\]\:border-0 tr:last-child{border-width:0px}.\[\&_tr\]\:border-b tr{border-bottom-width:1px}body{margin:0;padding:0;height:100%;display:flex;flex-direction:column;font-family:Inter,sans-serif;background-color:hsl(var(--header))!important}.layout-general{margin:.5rem;border-radius:.5rem;background-color:hsl(var(--background))}.instance-layout{display:flex;height:calc(100vh - 66px);width:100%}.sidebar{height:100%;background-color:#1a1a1c;color:#cecece;padding:1rem .2rem;overflow-y:auto;border-radius:.5rem 0 0 .5rem;border-right:1px solid #0e0e0e}.sidebar-nav{list-style:none;padding:0;margin:0}.nav-item{margin:.2rem 0;padding:0 .5rem}.nav-item button{display:flex;align-items:center;padding:.3rem 1rem;background:none;border:none;width:100%;text-align:left;cursor:pointer;color:#cecece;border-radius:.5rem}.nav-item button.active,.nav-item button:hover{background-color:#3a3b41}.nav-icon{margin-right:.5rem}.nav-title{font-size:.8rem}.nav-label{font-size:.75rem;margin-left:1.4rem}.main-content{flex:1;padding:2rem;overflow-y:auto;max-width:900px;margin:0 auto}.main-table{flex:1;overflow-y:auto;margin:0 auto}body,html{margin:0;padding:0;height:100%}header{display:flex;justify-content:space-between;align-items:center;padding:.5rem 2rem;background-color:hsl(var(--header));color:hsl(var(--secondary-foreground))}.toolbar{display:flex;justify-content:space-between;align-items:center;width:100%;padding:1rem 2rem}.toolbar-title h2{margin:0;font-size:1.5rem;font-weight:500}.toolbar-buttons{display:flex;gap:.5rem}.toolbar-buttons .refresh-button,.toolbar-buttons .new-instance-button{display:flex;align-items:center;gap:.25rem;border:none}.search{display:flex;justify-content:space-between;align-items:center;padding-left:1rem}.search-bar{flex:5;width:100%;padding:1rem}.search-bar input{width:100%;padding:.5rem;border-radius:.25rem;background-color:#181818}.status-dropdown{position:relative}.dropdown-button{padding:.5rem 1.5rem;margin-right:2rem;border-radius:.25rem;cursor:pointer;display:flex;align-items:center;gap:.5rem}.dropdown-menu{position:absolute;top:100%;right:10;background-color:#2b2c32;border-radius:.8rem;box-shadow:0 .5rem 1rem #0000001a;z-index:1000;color:#cecece;font-size:.8rem;padding:.1rem}.dropdown-menu .active{background-color:#ffffff27}.dropdown-item{margin:.5rem;padding:.3rem .5rem;cursor:pointer;text-align:left;white-space:nowrap;display:flex;align-items:center;width:calc(100% - 1rem);border-radius:.5rem}.dropdown-item:hover{background-color:#ffffff27}.instance-cards{display:grid;grid-template-columns:repeat(3,1fr);gap:1rem;padding:2rem;width:100%;max-height:80vh;overflow-y:auto;padding:10px}.instance-card{background-color:hsl(var(--primary-foreground));display:flex;flex-direction:column;justify-content:space-between;padding:.7rem;border-radius:.5rem;border:none}.card-header{display:flex;justify-content:space-between;align-items:center}.card-id{display:flex;align-items:center;background-color:#202020;color:#8b8b8b;padding:.25rem .5rem;border-radius:.25rem;font-size:.75rem}.card-icon{margin-left:.8rem;cursor:pointer}.card-body{display:flex;justify-content:space-between;margin:1rem 0}.card-details{flex:1}.card-contact{flex:1;text-align:right;font-size:.9rem}.card-footer{display:flex;justify-content:space-between;align-items:center}.card-stats{display:flex;gap:1rem}.stat{display:flex;align-items:center;gap:.25rem;font-size:.8rem}.stat-icon{font-size:1.25rem}.card-actions{display:flex;gap:1rem}.btn{padding:.5rem 1rem;border:none;border-radius:.25rem;font-size:.8rem}.connected{background-color:#2c2c2c;color:#fff}.disconnect{background-color:#c43333;color:#fff;cursor:pointer}.disconnect.disabled{background-color:#ac8f8f;color:#fff;cursor:not-allowed}.status-connected{width:10px;height:10px;border-radius:50%;display:inline-block;margin-left:.5rem;background-color:green}.status-connecting{width:10px;height:10px;border-radius:50%;display:inline-block;margin-left:.5rem;background-color:orange}.status-disconnected{width:10px;height:10px;border-radius:50%;display:inline-block;margin-left:.5rem;background-color:red}.instance-name{font-size:rem;font-weight:500}.instance-description{font-size:.7rem;color:#8b8b8b}:root{--toastify-color-light: #fff;--toastify-color-dark: #121212;--toastify-color-info: #3498db;--toastify-color-success: #07bc0c;--toastify-color-warning: #f1c40f;--toastify-color-error: #e74c3c;--toastify-color-transparent: rgba(255, 255, 255, .7);--toastify-icon-color-info: var(--toastify-color-info);--toastify-icon-color-success: var(--toastify-color-success);--toastify-icon-color-warning: var(--toastify-color-warning);--toastify-icon-color-error: var(--toastify-color-error);--toastify-toast-width: 320px;--toastify-toast-offset: 16px;--toastify-toast-top: max(var(--toastify-toast-offset), env(safe-area-inset-top));--toastify-toast-right: max(var(--toastify-toast-offset), env(safe-area-inset-right));--toastify-toast-left: max(var(--toastify-toast-offset), env(safe-area-inset-left));--toastify-toast-bottom: max(var(--toastify-toast-offset), env(safe-area-inset-bottom));--toastify-toast-background: #fff;--toastify-toast-min-height: 64px;--toastify-toast-max-height: 800px;--toastify-toast-bd-radius: 6px;--toastify-font-family: sans-serif;--toastify-z-index: 9999;--toastify-text-color-light: #757575;--toastify-text-color-dark: #fff;--toastify-text-color-info: #fff;--toastify-text-color-success: #fff;--toastify-text-color-warning: #fff;--toastify-text-color-error: #fff;--toastify-spinner-color: #616161;--toastify-spinner-color-empty-area: #e0e0e0;--toastify-color-progress-light: linear-gradient( to right, #4cd964, #5ac8fa, #007aff, #34aadc, #5856d6, #ff2d55 );--toastify-color-progress-dark: #bb86fc;--toastify-color-progress-info: var(--toastify-color-info);--toastify-color-progress-success: var(--toastify-color-success);--toastify-color-progress-warning: var(--toastify-color-warning);--toastify-color-progress-error: var(--toastify-color-error);--toastify-color-progress-bgo: .2}.Toastify__toast-container{z-index:var(--toastify-z-index);-webkit-transform:translate3d(0,0,var(--toastify-z-index));position:fixed;padding:4px;width:var(--toastify-toast-width);box-sizing:border-box;color:#fff}.Toastify__toast-container--top-left{top:var(--toastify-toast-top);left:var(--toastify-toast-left)}.Toastify__toast-container--top-center{top:var(--toastify-toast-top);left:50%;transform:translate(-50%)}.Toastify__toast-container--top-right{top:var(--toastify-toast-top);right:var(--toastify-toast-right)}.Toastify__toast-container--bottom-left{bottom:var(--toastify-toast-bottom);left:var(--toastify-toast-left)}.Toastify__toast-container--bottom-center{bottom:var(--toastify-toast-bottom);left:50%;transform:translate(-50%)}.Toastify__toast-container--bottom-right{bottom:var(--toastify-toast-bottom);right:var(--toastify-toast-right)}@media only screen and (max-width : 480px){.Toastify__toast-container{width:100vw;padding:0;left:env(safe-area-inset-left);margin:0}.Toastify__toast-container--top-left,.Toastify__toast-container--top-center,.Toastify__toast-container--top-right{top:env(safe-area-inset-top);transform:translate(0)}.Toastify__toast-container--bottom-left,.Toastify__toast-container--bottom-center,.Toastify__toast-container--bottom-right{bottom:env(safe-area-inset-bottom);transform:translate(0)}.Toastify__toast-container--rtl{right:env(safe-area-inset-right);left:initial}}.Toastify__toast{--y: 0;position:relative;touch-action:none;min-height:var(--toastify-toast-min-height);box-sizing:border-box;margin-bottom:1rem;padding:8px;border-radius:var(--toastify-toast-bd-radius);box-shadow:0 4px 12px #0000001a;display:flex;justify-content:space-between;max-height:var(--toastify-toast-max-height);font-family:var(--toastify-font-family);cursor:default;direction:ltr;z-index:0;overflow:hidden}.Toastify__toast--stacked{position:absolute;width:100%;transform:translate3d(0,var(--y),0) scale(var(--s));transition:transform .3s}.Toastify__toast--stacked[data-collapsed] .Toastify__toast-body,.Toastify__toast--stacked[data-collapsed] .Toastify__close-button{transition:opacity .1s}.Toastify__toast--stacked[data-collapsed=false]{overflow:visible}.Toastify__toast--stacked[data-collapsed=true]:not(:last-child)>*{opacity:0}.Toastify__toast--stacked:after{content:"";position:absolute;left:0;right:0;height:calc(var(--g) * 1px);bottom:100%}.Toastify__toast--stacked[data-pos=top]{top:0}.Toastify__toast--stacked[data-pos=bot]{bottom:0}.Toastify__toast--stacked[data-pos=bot].Toastify__toast--stacked:before{transform-origin:top}.Toastify__toast--stacked[data-pos=top].Toastify__toast--stacked:before{transform-origin:bottom}.Toastify__toast--stacked:before{content:"";position:absolute;left:0;right:0;bottom:0;height:100%;transform:scaleY(3);z-index:-1}.Toastify__toast--rtl{direction:rtl}.Toastify__toast--close-on-click{cursor:pointer}.Toastify__toast-body{margin:auto 0;flex:1 1 auto;padding:6px;display:flex;align-items:center}.Toastify__toast-body>div:last-child{word-break:break-word;flex:1}.Toastify__toast-icon{margin-inline-end:10px;width:20px;flex-shrink:0;display:flex}.Toastify--animate{animation-fill-mode:both;animation-duration:.5s}.Toastify--animate-icon{animation-fill-mode:both;animation-duration:.3s}@media only screen and (max-width : 480px){.Toastify__toast{margin-bottom:0;border-radius:0}}.Toastify__toast-theme--dark{background:var(--toastify-color-dark);color:var(--toastify-text-color-dark)}.Toastify__toast-theme--light,.Toastify__toast-theme--colored.Toastify__toast--default{background:var(--toastify-color-light);color:var(--toastify-text-color-light)}.Toastify__toast-theme--colored.Toastify__toast--info{color:var(--toastify-text-color-info);background:var(--toastify-color-info)}.Toastify__toast-theme--colored.Toastify__toast--success{color:var(--toastify-text-color-success);background:var(--toastify-color-success)}.Toastify__toast-theme--colored.Toastify__toast--warning{color:var(--toastify-text-color-warning);background:var(--toastify-color-warning)}.Toastify__toast-theme--colored.Toastify__toast--error{color:var(--toastify-text-color-error);background:var(--toastify-color-error)}.Toastify__progress-bar-theme--light{background:var(--toastify-color-progress-light)}.Toastify__progress-bar-theme--dark{background:var(--toastify-color-progress-dark)}.Toastify__progress-bar--info{background:var(--toastify-color-progress-info)}.Toastify__progress-bar--success{background:var(--toastify-color-progress-success)}.Toastify__progress-bar--warning{background:var(--toastify-color-progress-warning)}.Toastify__progress-bar--error{background:var(--toastify-color-progress-error)}.Toastify__progress-bar-theme--colored.Toastify__progress-bar--info,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--success,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--warning,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--error{background:var(--toastify-color-transparent)}.Toastify__close-button{color:#fff;background:transparent;outline:none;border:none;padding:0;cursor:pointer;opacity:.7;transition:.3s ease;align-self:flex-start;z-index:1}.Toastify__close-button--light{color:#000;opacity:.3}.Toastify__close-button>svg{fill:currentColor;height:16px;width:14px}.Toastify__close-button:hover,.Toastify__close-button:focus{opacity:1}@keyframes Toastify__trackProgress{0%{transform:scaleX(1)}to{transform:scaleX(0)}}.Toastify__progress-bar{position:absolute;bottom:0;left:0;width:100%;height:100%;z-index:var(--toastify-z-index);opacity:.7;transform-origin:left;border-bottom-left-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--animated{animation:Toastify__trackProgress linear 1 forwards}.Toastify__progress-bar--controlled{transition:transform .2s}.Toastify__progress-bar--rtl{right:0;left:initial;transform-origin:right;border-bottom-left-radius:initial;border-bottom-right-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--wrp{position:absolute;bottom:0;left:0;width:100%;height:5px;border-bottom-left-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--wrp[data-hidden=true]{opacity:0}.Toastify__progress-bar--bg{opacity:var(--toastify-color-progress-bgo);width:100%;height:100%}.Toastify__spinner{width:20px;height:20px;box-sizing:border-box;border:2px solid;border-radius:100%;border-color:var(--toastify-spinner-color-empty-area);border-right-color:var(--toastify-spinner-color);animation:Toastify__spin .65s linear infinite}@keyframes Toastify__bounceInRight{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(3000px,0,0)}60%{opacity:1;transform:translate3d(-25px,0,0)}75%{transform:translate3d(10px,0,0)}90%{transform:translate3d(-5px,0,0)}to{transform:none}}@keyframes Toastify__bounceOutRight{20%{opacity:1;transform:translate3d(-20px,var(--y),0)}to{opacity:0;transform:translate3d(2000px,var(--y),0)}}@keyframes Toastify__bounceInLeft{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(-3000px,0,0)}60%{opacity:1;transform:translate3d(25px,0,0)}75%{transform:translate3d(-10px,0,0)}90%{transform:translate3d(5px,0,0)}to{transform:none}}@keyframes Toastify__bounceOutLeft{20%{opacity:1;transform:translate3d(20px,var(--y),0)}to{opacity:0;transform:translate3d(-2000px,var(--y),0)}}@keyframes Toastify__bounceInUp{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(0,3000px,0)}60%{opacity:1;transform:translate3d(0,-20px,0)}75%{transform:translate3d(0,10px,0)}90%{transform:translate3d(0,-5px,0)}to{transform:translateZ(0)}}@keyframes Toastify__bounceOutUp{20%{transform:translate3d(0,calc(var(--y) - 10px),0)}40%,45%{opacity:1;transform:translate3d(0,calc(var(--y) + 20px),0)}to{opacity:0;transform:translate3d(0,-2000px,0)}}@keyframes Toastify__bounceInDown{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(0,-3000px,0)}60%{opacity:1;transform:translate3d(0,25px,0)}75%{transform:translate3d(0,-10px,0)}90%{transform:translate3d(0,5px,0)}to{transform:none}}@keyframes Toastify__bounceOutDown{20%{transform:translate3d(0,calc(var(--y) - 10px),0)}40%,45%{opacity:1;transform:translate3d(0,calc(var(--y) + 20px),0)}to{opacity:0;transform:translate3d(0,2000px,0)}}.Toastify__bounce-enter--top-left,.Toastify__bounce-enter--bottom-left{animation-name:Toastify__bounceInLeft}.Toastify__bounce-enter--top-right,.Toastify__bounce-enter--bottom-right{animation-name:Toastify__bounceInRight}.Toastify__bounce-enter--top-center{animation-name:Toastify__bounceInDown}.Toastify__bounce-enter--bottom-center{animation-name:Toastify__bounceInUp}.Toastify__bounce-exit--top-left,.Toastify__bounce-exit--bottom-left{animation-name:Toastify__bounceOutLeft}.Toastify__bounce-exit--top-right,.Toastify__bounce-exit--bottom-right{animation-name:Toastify__bounceOutRight}.Toastify__bounce-exit--top-center{animation-name:Toastify__bounceOutUp}.Toastify__bounce-exit--bottom-center{animation-name:Toastify__bounceOutDown}@keyframes Toastify__zoomIn{0%{opacity:0;transform:scale3d(.3,.3,.3)}50%{opacity:1}}@keyframes Toastify__zoomOut{0%{opacity:1}50%{opacity:0;transform:translate3d(0,var(--y),0) scale3d(.3,.3,.3)}to{opacity:0}}.Toastify__zoom-enter{animation-name:Toastify__zoomIn}.Toastify__zoom-exit{animation-name:Toastify__zoomOut}@keyframes Toastify__flipIn{0%{transform:perspective(400px) rotateX(90deg);animation-timing-function:ease-in;opacity:0}40%{transform:perspective(400px) rotateX(-20deg);animation-timing-function:ease-in}60%{transform:perspective(400px) rotateX(10deg);opacity:1}80%{transform:perspective(400px) rotateX(-5deg)}to{transform:perspective(400px)}}@keyframes Toastify__flipOut{0%{transform:translate3d(0,var(--y),0) perspective(400px)}30%{transform:translate3d(0,var(--y),0) perspective(400px) rotateX(-20deg);opacity:1}to{transform:translate3d(0,var(--y),0) perspective(400px) rotateX(90deg);opacity:0}}.Toastify__flip-enter{animation-name:Toastify__flipIn}.Toastify__flip-exit{animation-name:Toastify__flipOut}@keyframes Toastify__slideInRight{0%{transform:translate3d(110%,0,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInLeft{0%{transform:translate3d(-110%,0,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInUp{0%{transform:translate3d(0,110%,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInDown{0%{transform:translate3d(0,-110%,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideOutRight{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(110%,var(--y),0)}}@keyframes Toastify__slideOutLeft{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(-110%,var(--y),0)}}@keyframes Toastify__slideOutDown{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(0,500px,0)}}@keyframes Toastify__slideOutUp{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(0,-500px,0)}}.Toastify__slide-enter--top-left,.Toastify__slide-enter--bottom-left{animation-name:Toastify__slideInLeft}.Toastify__slide-enter--top-right,.Toastify__slide-enter--bottom-right{animation-name:Toastify__slideInRight}.Toastify__slide-enter--top-center{animation-name:Toastify__slideInDown}.Toastify__slide-enter--bottom-center{animation-name:Toastify__slideInUp}.Toastify__slide-exit--top-left,.Toastify__slide-exit--bottom-left{animation-name:Toastify__slideOutLeft;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--top-right,.Toastify__slide-exit--bottom-right{animation-name:Toastify__slideOutRight;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--top-center{animation-name:Toastify__slideOutUp;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--bottom-center{animation-name:Toastify__slideOutDown;animation-timing-function:ease-in;animation-duration:.3s}@keyframes Toastify__spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.tabs-chat{background-color:transparent;width:100%;border-radius:0}.chat-item{display:flex;padding:10px;cursor:pointer;background-color:hsl(var(--background))}.chat-item:hover,.chat-item.active{background-color:#2f2f2f}.bubble{border-radius:16px;padding:12px;word-wrap:break-word}.bubble-right .bubble{background-color:#0a0a0a;text-align:right;max-width:100%}.bubble-left .bubble{background-color:#1b1b1b;max-width:100%}.bubble-right{align-self:flex-end;display:flex;justify-content:flex-end;width:80%}.bubble-left{align-self:flex-start;display:flex;justify-content:flex-start;width:80%}.input-message textarea{background-color:#2f2f2f;padding-left:48px}.input-message textarea:focus{outline:none;border:none;box-shadow:none}.message-container{flex:1;overflow-y:auto;max-height:calc(100vh - 110px);padding-top:50px}.main-content{height:calc(100vh - 4rem);display:flex;flex-direction:column;padding:1rem}.form-container{flex:1;overflow-y:auto;padding:1rem}.dashboard-instance{padding:20px}.dashboard-card{display:flex;align-items:center;justify-content:space-between;padding:20px;border-radius:8px;margin-bottom:20px;border:1px solid #333;background-color:#1a1a1c}.dashboard-info{display:flex;flex-direction:column;justify-content:flex-start}.dashboard-status{display:flex;align-items:center}.status-icon{width:10px;height:10px;border-radius:50%;margin-right:10px}.status-icon.disconnected{background-color:red}.status-icon.connected{background-color:green}.status-icon.connecting{background-color:orange}.status-text{color:#fff;font-weight:700;font-size:.7rem}.dashboard-name{color:#fff;font-family:monospace;margin-top:10px;font-size:2rem}.dashboard-actions{display:flex;gap:10px;align-items:center}.action-button{background-color:#007bff;color:#fff;border:none;padding:10px 15px;border-radius:4px;cursor:pointer}.action-button.disabled{background-color:#555;cursor:not-allowed}.connection-warning{display:flex;align-items:center;justify-content:space-between;background-color:#cf5228;padding:20px;border-radius:8px;color:#fff;margin-top:10px}.connect-button{background-color:#000;color:#fff;border:none;padding:10px 15px;border-radius:4px;cursor:pointer;margin-left:10px}.connect-code-button{background-color:#2a2a2a;color:#fff;border:none;padding:10px 15px;border-radius:4px;cursor:pointer;margin-left:10px}.pairing-code{font-family:monospace;font-size:1.5rem;padding-top:10px}.tagsClass{margin-top:.7rem;display:block;border:1px solid #444;border-radius:4px;padding:8px;background-color:#2d2d2d}.tagInputClass{flex:1;min-width:200px}.tagInputFieldClass{width:100%;padding:8px;margin-top:4px;background-color:#1a1a1a;border:none;color:#fff}.selectedClass{display:flex;align-items:center;background-color:transparent;border-radius:4px;margin:4px}.tagClass{background-color:#616161;color:#fff;padding:4px 8px;border-radius:4px;display:flex;align-items:center;margin:8px}.removeClass{margin-left:8px;cursor:pointer;color:#ff5252}.suggestionsClass{background-color:#2d2d2d;border:1px solid #444;border-radius:4px;max-height:200px;overflow-y:auto;color:#fff}.activeSuggestionClass{background-color:#616161}.editTagInputClass,.editTagInputFieldClass,.clearAllClass{display:none}body,html{height:100%;margin:0;overflow:hidden}.main-table{height:100%;display:flex;flex-direction:column}.table{width:100%;height:100%;border-collapse:collapse;margin-top:1rem}.table-item{padding:1rem;width:100%;border-radius:.5rem}.table-item:hover{background-color:#3a3b41;cursor:pointer}.table-item.selected{background-color:#3a3b41}.table-item-title{font-size:.9rem;font-weight:600;margin-bottom:.1rem}.table-item-description{font-size:.85rem;color:#aeaeae}.form{height:calc(100vh - 10rem)!important;padding:1rem 2rem;border-radius:.5rem;overflow-y:auto}.logo{margin:auto;height:40px}.root{display:flex;justify-content:center;align-items:center;height:calc(100vh - 50px);padding:2rem}.no-border{border:none;box-shadow:none} diff --git a/manager/dist/assets/index-Do1bGWiz.js b/manager/dist/assets/index-Do1bGWiz.js new file mode 100644 index 00000000..e47d726f --- /dev/null +++ b/manager/dist/assets/index-Do1bGWiz.js @@ -0,0 +1,381 @@ +var Ww=e=>{throw TypeError(e)};var qI=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var sm=(e,t,n)=>t.has(e)||Ww("Cannot "+n);var R=(e,t,n)=>(sm(e,t,"read from private field"),n?n.call(e):t.get(e)),Ie=(e,t,n)=>t.has(e)?Ww("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),xe=(e,t,n,r)=>(sm(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Je=(e,t,n)=>(sm(e,t,"access private method"),n);var uf=(e,t,n,r)=>({set _(s){xe(e,t,s,n)},get _(){return R(e,t,r)}});var kse=qI((ao,io)=>{function jE(e,t){for(var n=0;nr[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const a of o.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(s){if(s.ep)return;s.ep=!0;const o=n(s);fetch(s.href,o)}})();function jb(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var RE={exports:{}},Ph={},OE={exports:{}},ot={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Dd=Symbol.for("react.element"),WI=Symbol.for("react.portal"),GI=Symbol.for("react.fragment"),JI=Symbol.for("react.strict_mode"),QI=Symbol.for("react.profiler"),ZI=Symbol.for("react.provider"),YI=Symbol.for("react.context"),XI=Symbol.for("react.forward_ref"),eD=Symbol.for("react.suspense"),tD=Symbol.for("react.memo"),nD=Symbol.for("react.lazy"),Gw=Symbol.iterator;function rD(e){return e===null||typeof e!="object"?null:(e=Gw&&e[Gw]||e["@@iterator"],typeof e=="function"?e:null)}var NE={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},PE=Object.assign,ME={};function iu(e,t,n){this.props=e,this.context=t,this.refs=ME,this.updater=n||NE}iu.prototype.isReactComponent={};iu.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};iu.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function IE(){}IE.prototype=iu.prototype;function Rb(e,t,n){this.props=e,this.context=t,this.refs=ME,this.updater=n||NE}var Ob=Rb.prototype=new IE;Ob.constructor=Rb;PE(Ob,iu.prototype);Ob.isPureReactComponent=!0;var Jw=Array.isArray,DE=Object.prototype.hasOwnProperty,Nb={current:null},AE={key:!0,ref:!0,__self:!0,__source:!0};function FE(e,t,n){var r,s={},o=null,a=null;if(t!=null)for(r in t.ref!==void 0&&(a=t.ref),t.key!==void 0&&(o=""+t.key),t)DE.call(t,r)&&!AE.hasOwnProperty(r)&&(s[r]=t[r]);var i=arguments.length-2;if(i===1)s.children=n;else if(1{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Kl=typeof window>"u"||"Deno"in globalThis;function Pr(){}function hD(e,t){return typeof e=="function"?e(t):e}function Tv(e){return typeof e=="number"&&e>=0&&e!==1/0}function BE(e,t){return Math.max(e+(t||0)-Date.now(),0)}function bl(e,t){return typeof e=="function"?e(t):e}function Qr(e,t){return typeof e=="function"?e(t):e}function Zw(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:o,queryKey:a,stale:i}=e;if(a){if(r){if(t.queryHash!==Mb(a,t.options))return!1}else if(!Dc(t.queryKey,a))return!1}if(n!=="all"){const c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof i=="boolean"&&t.isStale()!==i||s&&s!==t.state.fetchStatus||o&&!o(t))}function Yw(e,t){const{exact:n,status:r,predicate:s,mutationKey:o}=e;if(o){if(!t.options.mutationKey)return!1;if(n){if(gi(t.options.mutationKey)!==gi(o))return!1}else if(!Dc(t.options.mutationKey,o))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Mb(e,t){return((t==null?void 0:t.queryKeyHashFn)||gi)(e)}function gi(e){return JSON.stringify(e,(t,n)=>kv(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function Dc(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!Dc(e[n],t[n])):!1}function zE(e,t){if(e===t)return e;const n=Xw(e)&&Xw(t);if(n||kv(e)&&kv(t)){const r=n?e:Object.keys(e),s=r.length,o=n?t:Object.keys(t),a=o.length,i=n?[]:{};let c=0;for(let l=0;l{setTimeout(t,e)})}function _v(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?zE(e,t):t}function mD(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function vD(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var UE=Symbol();function VE(e,t){return!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===UE?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var ei,Ko,Pl,yE,yD=(yE=class extends lu{constructor(){super();Ie(this,ei);Ie(this,Ko);Ie(this,Pl);xe(this,Pl,t=>{if(!Kl&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){R(this,Ko)||this.setEventListener(R(this,Pl))}onUnsubscribe(){var t;this.hasListeners()||((t=R(this,Ko))==null||t.call(this),xe(this,Ko,void 0))}setEventListener(t){var n;xe(this,Pl,t),(n=R(this,Ko))==null||n.call(this),xe(this,Ko,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){R(this,ei)!==t&&(xe(this,ei,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof R(this,ei)=="boolean"?R(this,ei):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ei=new WeakMap,Ko=new WeakMap,Pl=new WeakMap,yE),Ib=new yD,Ml,qo,Il,bE,bD=(bE=class extends lu{constructor(){super();Ie(this,Ml,!0);Ie(this,qo);Ie(this,Il);xe(this,Il,t=>{if(!Kl&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){R(this,qo)||this.setEventListener(R(this,Il))}onUnsubscribe(){var t;this.hasListeners()||((t=R(this,qo))==null||t.call(this),xe(this,qo,void 0))}setEventListener(t){var n;xe(this,Il,t),(n=R(this,qo))==null||n.call(this),xe(this,qo,t(this.setOnline.bind(this)))}setOnline(t){R(this,Ml)!==t&&(xe(this,Ml,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return R(this,Ml)}},Ml=new WeakMap,qo=new WeakMap,Il=new WeakMap,bE),kp=new bD;function xD(e){return Math.min(1e3*2**e,3e4)}function HE(e){return(e??"online")==="online"?kp.isOnline():!0}var KE=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function am(e){return e instanceof KE}function qE(e){let t=!1,n=0,r=!1,s,o,a;const i=new Promise((b,y)=>{o=b,a=y}),c=b=>{var y;r||(g(new KE(b)),(y=e.abort)==null||y.call(e))},l=()=>{t=!0},d=()=>{t=!1},p=()=>Ib.isFocused()&&(e.networkMode==="always"||kp.isOnline())&&e.canRun(),f=()=>HE(e.networkMode)&&e.canRun(),h=b=>{var y;r||(r=!0,(y=e.onSuccess)==null||y.call(e,b),s==null||s(),o(b))},g=b=>{var y;r||(r=!0,(y=e.onError)==null||y.call(e,b),s==null||s(),a(b))},m=()=>new Promise(b=>{var y;s=w=>{(r||p())&&b(w)},(y=e.onPause)==null||y.call(e)}).then(()=>{var b;s=void 0,r||(b=e.onContinue)==null||b.call(e)}),x=()=>{if(r)return;let b;const y=n===0?e.initialPromise:void 0;try{b=y??e.fn()}catch(w){b=Promise.reject(w)}Promise.resolve(b).then(h).catch(w=>{var T;if(r)return;const S=e.retry??(Kl?0:3),E=e.retryDelay??xD,C=typeof E=="function"?E(n,w):E,k=S===!0||typeof S=="number"&&np()?void 0:m()).then(()=>{t?g(w):x()})})};return{promise:i,cancel:c,continue:()=>(s==null||s(),i),cancelRetry:l,continueRetry:d,canStart:f,start:()=>(f()?x():m().then(x),i)}}function wD(){let e=[],t=0,n=f=>{f()},r=f=>{f()},s=f=>setTimeout(f,0);const o=f=>{s=f},a=f=>{let h;t++;try{h=f()}finally{t--,t||l()}return h},i=f=>{t?e.push(f):s(()=>{n(f)})},c=f=>(...h)=>{i(()=>{f(...h)})},l=()=>{const f=e;e=[],f.length&&s(()=>{r(()=>{f.forEach(h=>{n(h)})})})};return{batch:a,batchCalls:c,schedule:i,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:o}}var cn=wD(),ti,xE,WE=(xE=class{constructor(){Ie(this,ti)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Tv(this.gcTime)&&xe(this,ti,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Kl?1/0:5*60*1e3))}clearGcTimeout(){R(this,ti)&&(clearTimeout(R(this,ti)),xe(this,ti,void 0))}},ti=new WeakMap,xE),Dl,Al,Nr,Pn,Nd,ni,Wr,Js,wE,SD=(wE=class extends WE{constructor(t){super();Ie(this,Wr);Ie(this,Dl);Ie(this,Al);Ie(this,Nr);Ie(this,Pn);Ie(this,Nd);Ie(this,ni);xe(this,ni,!1),xe(this,Nd,t.defaultOptions),this.setOptions(t.options),this.observers=[],xe(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,xe(this,Dl,CD(this.options)),this.state=t.state??R(this,Dl),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=R(this,Pn))==null?void 0:t.promise}setOptions(t){this.options={...R(this,Nd),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&R(this,Nr).remove(this)}setData(t,n){const r=_v(this.state.data,t,this.options);return Je(this,Wr,Js).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){Je(this,Wr,Js).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,s;const n=(r=R(this,Pn))==null?void 0:r.promise;return(s=R(this,Pn))==null||s.cancel(t),n?n.then(Pr).catch(Pr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(R(this,Dl))}isActive(){return this.observers.some(t=>Qr(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated?!0:this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0}isStaleByTime(t=0){return this.state.isInvalidated||this.state.data===void 0||!BE(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=R(this,Pn))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=R(this,Pn))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),R(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(R(this,Pn)&&(R(this,ni)?R(this,Pn).cancel({revert:!0}):R(this,Pn).cancelRetry()),this.scheduleGc()),R(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Je(this,Wr,Js).call(this,{type:"invalidate"})}fetch(t,n){var c,l,d;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(R(this,Pn))return R(this,Pn).continueRetry(),R(this,Pn).promise}if(t&&this.setOptions(t),!this.options.queryFn){const p=this.observers.find(f=>f.options.queryFn);p&&this.setOptions(p.options)}const r=new AbortController,s=p=>{Object.defineProperty(p,"signal",{enumerable:!0,get:()=>(xe(this,ni,!0),r.signal)})},o=()=>{const p=VE(this.options,n),f={queryKey:this.queryKey,meta:this.meta};return s(f),xe(this,ni,!1),this.options.persister?this.options.persister(p,f,this):p(f)},a={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:o};s(a),(c=this.options.behavior)==null||c.onFetch(a,this),xe(this,Al,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((l=a.fetchOptions)==null?void 0:l.meta))&&Je(this,Wr,Js).call(this,{type:"fetch",meta:(d=a.fetchOptions)==null?void 0:d.meta});const i=p=>{var f,h,g,m;am(p)&&p.silent||Je(this,Wr,Js).call(this,{type:"error",error:p}),am(p)||((h=(f=R(this,Nr).config).onError)==null||h.call(f,p,this),(m=(g=R(this,Nr).config).onSettled)==null||m.call(g,this.state.data,p,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return xe(this,Pn,qE({initialPromise:n==null?void 0:n.initialPromise,fn:a.fetchFn,abort:r.abort.bind(r),onSuccess:p=>{var f,h,g,m;if(p===void 0){i(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(p)}catch(x){i(x);return}(h=(f=R(this,Nr).config).onSuccess)==null||h.call(f,p,this),(m=(g=R(this,Nr).config).onSettled)==null||m.call(g,p,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:i,onFail:(p,f)=>{Je(this,Wr,Js).call(this,{type:"failed",failureCount:p,error:f})},onPause:()=>{Je(this,Wr,Js).call(this,{type:"pause"})},onContinue:()=>{Je(this,Wr,Js).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0})),R(this,Pn).start()}},Dl=new WeakMap,Al=new WeakMap,Nr=new WeakMap,Pn=new WeakMap,Nd=new WeakMap,ni=new WeakMap,Wr=new WeakSet,Js=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...GE(r.data,this.options),fetchMeta:t.meta??null};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const s=t.error;return am(s)&&s.revert&&R(this,Al)?{...R(this,Al),fetchStatus:"idle"}:{...r,error:s,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:s,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),cn.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),R(this,Nr).notify({query:this,type:"updated",action:t})})},wE);function GE(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:HE(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function CD(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Ss,SE,ED=(SE=class extends lu{constructor(t={}){super();Ie(this,Ss);this.config=t,xe(this,Ss,new Map)}build(t,n,r){const s=n.queryKey,o=n.queryHash??Mb(s,n);let a=this.get(o);return a||(a=new SD({cache:this,queryKey:s,queryHash:o,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(a)),a}add(t){R(this,Ss).has(t.queryHash)||(R(this,Ss).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=R(this,Ss).get(t.queryHash);n&&(t.destroy(),n===t&&R(this,Ss).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){cn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return R(this,Ss).get(t)}getAll(){return[...R(this,Ss).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Zw(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Zw(t,r)):n}notify(t){cn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){cn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){cn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ss=new WeakMap,SE),Cs,Ln,ri,Es,Ao,CE,TD=(CE=class extends WE{constructor(t){super();Ie(this,Es);Ie(this,Cs);Ie(this,Ln);Ie(this,ri);this.mutationId=t.mutationId,xe(this,Ln,t.mutationCache),xe(this,Cs,[]),this.state=t.state||JE(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){R(this,Cs).includes(t)||(R(this,Cs).push(t),this.clearGcTimeout(),R(this,Ln).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){xe(this,Cs,R(this,Cs).filter(n=>n!==t)),this.scheduleGc(),R(this,Ln).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){R(this,Cs).length||(this.state.status==="pending"?this.scheduleGc():R(this,Ln).remove(this))}continue(){var t;return((t=R(this,ri))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var s,o,a,i,c,l,d,p,f,h,g,m,x,b,y,w,S,E,C,k;xe(this,ri,qE({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(T,O)=>{Je(this,Es,Ao).call(this,{type:"failed",failureCount:T,error:O})},onPause:()=>{Je(this,Es,Ao).call(this,{type:"pause"})},onContinue:()=>{Je(this,Es,Ao).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>R(this,Ln).canRun(this)}));const n=this.state.status==="pending",r=!R(this,ri).canStart();try{if(!n){Je(this,Es,Ao).call(this,{type:"pending",variables:t,isPaused:r}),await((o=(s=R(this,Ln).config).onMutate)==null?void 0:o.call(s,t,this));const O=await((i=(a=this.options).onMutate)==null?void 0:i.call(a,t));O!==this.state.context&&Je(this,Es,Ao).call(this,{type:"pending",context:O,variables:t,isPaused:r})}const T=await R(this,ri).start();return await((l=(c=R(this,Ln).config).onSuccess)==null?void 0:l.call(c,T,t,this.state.context,this)),await((p=(d=this.options).onSuccess)==null?void 0:p.call(d,T,t,this.state.context)),await((h=(f=R(this,Ln).config).onSettled)==null?void 0:h.call(f,T,null,this.state.variables,this.state.context,this)),await((m=(g=this.options).onSettled)==null?void 0:m.call(g,T,null,t,this.state.context)),Je(this,Es,Ao).call(this,{type:"success",data:T}),T}catch(T){try{throw await((b=(x=R(this,Ln).config).onError)==null?void 0:b.call(x,T,t,this.state.context,this)),await((w=(y=this.options).onError)==null?void 0:w.call(y,T,t,this.state.context)),await((E=(S=R(this,Ln).config).onSettled)==null?void 0:E.call(S,void 0,T,this.state.variables,this.state.context,this)),await((k=(C=this.options).onSettled)==null?void 0:k.call(C,void 0,T,t,this.state.context)),T}finally{Je(this,Es,Ao).call(this,{type:"error",error:T})}}finally{R(this,Ln).runNext(this)}}},Cs=new WeakMap,Ln=new WeakMap,ri=new WeakMap,Es=new WeakSet,Ao=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),cn.batch(()=>{R(this,Cs).forEach(r=>{r.onMutationUpdate(t)}),R(this,Ln).notify({mutation:this,type:"updated",action:t})})},CE);function JE(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var lr,Pd,EE,kD=(EE=class extends lu{constructor(t={}){super();Ie(this,lr);Ie(this,Pd);this.config=t,xe(this,lr,new Map),xe(this,Pd,Date.now())}build(t,n,r){const s=new TD({mutationCache:this,mutationId:++uf(this,Pd)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){const n=df(t),r=R(this,lr).get(n)??[];r.push(t),R(this,lr).set(n,r),this.notify({type:"added",mutation:t})}remove(t){var r;const n=df(t);if(R(this,lr).has(n)){const s=(r=R(this,lr).get(n))==null?void 0:r.filter(o=>o!==t);s&&(s.length===0?R(this,lr).delete(n):R(this,lr).set(n,s))}this.notify({type:"removed",mutation:t})}canRun(t){var r;const n=(r=R(this,lr).get(df(t)))==null?void 0:r.find(s=>s.state.status==="pending");return!n||n===t}runNext(t){var r;const n=(r=R(this,lr).get(df(t)))==null?void 0:r.find(s=>s!==t&&s.state.isPaused);return(n==null?void 0:n.continue())??Promise.resolve()}clear(){cn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}getAll(){return[...R(this,lr).values()].flat()}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Yw(n,r))}findAll(t={}){return this.getAll().filter(n=>Yw(t,n))}notify(t){cn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return cn.batch(()=>Promise.all(t.map(n=>n.continue().catch(Pr))))}},lr=new WeakMap,Pd=new WeakMap,EE);function df(e){var t;return((t=e.options.scope)==null?void 0:t.id)??String(e.mutationId)}function _D(e){return{onFetch:(t,n)=>{const r=async()=>{var g,m,x,b,y;const s=t.options,o=(x=(m=(g=t.fetchOptions)==null?void 0:g.meta)==null?void 0:m.fetchMore)==null?void 0:x.direction,a=((b=t.state.data)==null?void 0:b.pages)||[],i=((y=t.state.data)==null?void 0:y.pageParams)||[],c={pages:[],pageParams:[]};let l=!1;const d=w=>{Object.defineProperty(w,"signal",{enumerable:!0,get:()=>(t.signal.aborted?l=!0:t.signal.addEventListener("abort",()=>{l=!0}),t.signal)})},p=VE(t.options,t.fetchOptions),f=async(w,S,E)=>{if(l)return Promise.reject();if(S==null&&w.pages.length)return Promise.resolve(w);const C={queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};d(C);const k=await p(C),{maxPages:T}=t.options,O=E?vD:mD;return{pages:O(w.pages,k,T),pageParams:O(w.pageParams,S,T)}};let h;if(o&&a.length){const w=o==="backward",S=w?jD:tS,E={pages:a,pageParams:i},C=S(s,E);h=await f(E,C,w)}else{h=await f(c,i[0]??s.initialPageParam);const w=e??a.length;for(let S=1;S{var s,o;return(o=(s=t.options).persister)==null?void 0:o.call(s,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function tS(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function jD(e,{pages:t,pageParams:n}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n):void 0}var Ht,Wo,Go,Fl,Ll,Jo,$l,Bl,TE,RD=(TE=class{constructor(e={}){Ie(this,Ht);Ie(this,Wo);Ie(this,Go);Ie(this,Fl);Ie(this,Ll);Ie(this,Jo);Ie(this,$l);Ie(this,Bl);xe(this,Ht,e.queryCache||new ED),xe(this,Wo,e.mutationCache||new kD),xe(this,Go,e.defaultOptions||{}),xe(this,Fl,new Map),xe(this,Ll,new Map),xe(this,Jo,0)}mount(){uf(this,Jo)._++,R(this,Jo)===1&&(xe(this,$l,Ib.subscribe(async e=>{e&&(await this.resumePausedMutations(),R(this,Ht).onFocus())})),xe(this,Bl,kp.subscribe(async e=>{e&&(await this.resumePausedMutations(),R(this,Ht).onOnline())})))}unmount(){var e,t;uf(this,Jo)._--,R(this,Jo)===0&&((e=R(this,$l))==null||e.call(this),xe(this,$l,void 0),(t=R(this,Bl))==null||t.call(this),xe(this,Bl,void 0))}isFetching(e){return R(this,Ht).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return R(this,Wo).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=R(this,Ht).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);if(t===void 0)return this.fetchQuery(e);{const n=this.defaultQueryOptions(e),r=R(this,Ht).build(this,n);return e.revalidateIfStale&&r.isStaleByTime(bl(n.staleTime,r))&&this.prefetchQuery(n),Promise.resolve(t)}}getQueriesData(e){return R(this,Ht).findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),s=R(this,Ht).get(r.queryHash),o=s==null?void 0:s.state.data,a=hD(t,o);if(a!==void 0)return R(this,Ht).build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return cn.batch(()=>R(this,Ht).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=R(this,Ht).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=R(this,Ht);cn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=R(this,Ht),r={type:"active",...e};return cn.batch(()=>(n.findAll(e).forEach(s=>{s.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=cn.batch(()=>R(this,Ht).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Pr).catch(Pr)}invalidateQueries(e={},t={}){return cn.batch(()=>{if(R(this,Ht).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=cn.batch(()=>R(this,Ht).findAll(e).filter(s=>!s.isDisabled()).map(s=>{let o=s.fetch(void 0,n);return n.throwOnError||(o=o.catch(Pr)),s.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(r).then(Pr)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=R(this,Ht).build(this,t);return n.isStaleByTime(bl(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Pr).catch(Pr)}fetchInfiniteQuery(e){return e.behavior=_D(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Pr).catch(Pr)}resumePausedMutations(){return kp.isOnline()?R(this,Wo).resumePausedMutations():Promise.resolve()}getQueryCache(){return R(this,Ht)}getMutationCache(){return R(this,Wo)}getDefaultOptions(){return R(this,Go)}setDefaultOptions(e){xe(this,Go,e)}setQueryDefaults(e,t){R(this,Fl).set(gi(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...R(this,Fl).values()];let n={};return t.forEach(r=>{Dc(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){R(this,Ll).set(gi(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...R(this,Ll).values()];let n={};return t.forEach(r=>{Dc(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...R(this,Go).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Mb(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.enabled!==!0&&t.queryFn===UE&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...R(this,Go).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){R(this,Ht).clear(),R(this,Wo).clear()}},Ht=new WeakMap,Wo=new WeakMap,Go=new WeakMap,Fl=new WeakMap,Ll=new WeakMap,Jo=new WeakMap,$l=new WeakMap,Bl=new WeakMap,TE),Qn,at,Md,$n,si,zl,Ts,Id,Ul,Vl,oi,ai,Qo,Hl,gt,oc,jv,Rv,Ov,Nv,Pv,Mv,Iv,QE,kE,OD=(kE=class extends lu{constructor(t,n){super();Ie(this,gt);Ie(this,Qn);Ie(this,at);Ie(this,Md);Ie(this,$n);Ie(this,si);Ie(this,zl);Ie(this,Ts);Ie(this,Id);Ie(this,Ul);Ie(this,Vl);Ie(this,oi);Ie(this,ai);Ie(this,Qo);Ie(this,Hl,new Set);this.options=n,xe(this,Qn,t),xe(this,Ts,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(R(this,at).addObserver(this),nS(R(this,at),this.options)?Je(this,gt,oc).call(this):this.updateResult(),Je(this,gt,Nv).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Dv(R(this,at),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Dv(R(this,at),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Je(this,gt,Pv).call(this),Je(this,gt,Mv).call(this),R(this,at).removeObserver(this)}setOptions(t,n){const r=this.options,s=R(this,at);if(this.options=R(this,Qn).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Qr(this.options.enabled,R(this,at))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Je(this,gt,Iv).call(this),R(this,at).setOptions(this.options),r._defaulted&&!Tp(this.options,r)&&R(this,Qn).getQueryCache().notify({type:"observerOptionsUpdated",query:R(this,at),observer:this});const o=this.hasListeners();o&&rS(R(this,at),s,this.options,r)&&Je(this,gt,oc).call(this),this.updateResult(n),o&&(R(this,at)!==s||Qr(this.options.enabled,R(this,at))!==Qr(r.enabled,R(this,at))||bl(this.options.staleTime,R(this,at))!==bl(r.staleTime,R(this,at)))&&Je(this,gt,jv).call(this);const a=Je(this,gt,Rv).call(this);o&&(R(this,at)!==s||Qr(this.options.enabled,R(this,at))!==Qr(r.enabled,R(this,at))||a!==R(this,Qo))&&Je(this,gt,Ov).call(this,a)}getOptimisticResult(t){const n=R(this,Qn).getQueryCache().build(R(this,Qn),t),r=this.createResult(n,t);return PD(this,r)&&(xe(this,$n,r),xe(this,zl,this.options),xe(this,si,R(this,at).state)),r}getCurrentResult(){return R(this,$n)}trackResult(t,n){const r={};return Object.keys(t).forEach(s=>{Object.defineProperty(r,s,{configurable:!1,enumerable:!0,get:()=>(this.trackProp(s),n==null||n(s),t[s])})}),r}trackProp(t){R(this,Hl).add(t)}getCurrentQuery(){return R(this,at)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=R(this,Qn).defaultQueryOptions(t),r=R(this,Qn).getQueryCache().build(R(this,Qn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return Je(this,gt,oc).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),R(this,$n)))}createResult(t,n){var k;const r=R(this,at),s=this.options,o=R(this,$n),a=R(this,si),i=R(this,zl),l=t!==r?t.state:R(this,Md),{state:d}=t;let p={...d},f=!1,h;if(n._optimisticResults){const T=this.hasListeners(),O=!T&&nS(t,n),M=T&&rS(t,r,n,s);(O||M)&&(p={...p,...GE(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:g,errorUpdatedAt:m,status:x}=p;if(n.select&&p.data!==void 0)if(o&&p.data===(a==null?void 0:a.data)&&n.select===R(this,Id))h=R(this,Ul);else try{xe(this,Id,n.select),h=n.select(p.data),h=_v(o==null?void 0:o.data,h,n),xe(this,Ul,h),xe(this,Ts,null)}catch(T){xe(this,Ts,T)}else h=p.data;if(n.placeholderData!==void 0&&h===void 0&&x==="pending"){let T;if(o!=null&&o.isPlaceholderData&&n.placeholderData===(i==null?void 0:i.placeholderData))T=o.data;else if(T=typeof n.placeholderData=="function"?n.placeholderData((k=R(this,Vl))==null?void 0:k.state.data,R(this,Vl)):n.placeholderData,n.select&&T!==void 0)try{T=n.select(T),xe(this,Ts,null)}catch(O){xe(this,Ts,O)}T!==void 0&&(x="success",h=_v(o==null?void 0:o.data,T,n),f=!0)}R(this,Ts)&&(g=R(this,Ts),h=R(this,Ul),m=Date.now(),x="error");const b=p.fetchStatus==="fetching",y=x==="pending",w=x==="error",S=y&&b,E=h!==void 0;return{status:x,fetchStatus:p.fetchStatus,isPending:y,isSuccess:x==="success",isError:w,isInitialLoading:S,isLoading:S,data:h,dataUpdatedAt:p.dataUpdatedAt,error:g,errorUpdatedAt:m,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:p.dataUpdateCount>0||p.errorUpdateCount>0,isFetchedAfterMount:p.dataUpdateCount>l.dataUpdateCount||p.errorUpdateCount>l.errorUpdateCount,isFetching:b,isRefetching:b&&!y,isLoadingError:w&&!E,isPaused:p.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:w&&E,isStale:Db(t,n),refetch:this.refetch}}updateResult(t){const n=R(this,$n),r=this.createResult(R(this,at),this.options);if(xe(this,si,R(this,at).state),xe(this,zl,this.options),R(this,si).data!==void 0&&xe(this,Vl,R(this,at)),Tp(r,n))return;xe(this,$n,r);const s={},o=()=>{if(!n)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!R(this,Hl).size)return!0;const c=new Set(i??R(this,Hl));return this.options.throwOnError&&c.add("error"),Object.keys(R(this,$n)).some(l=>{const d=l;return R(this,$n)[d]!==n[d]&&c.has(d)})};(t==null?void 0:t.listeners)!==!1&&o()&&(s.listeners=!0),Je(this,gt,QE).call(this,{...s,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Je(this,gt,Nv).call(this)}},Qn=new WeakMap,at=new WeakMap,Md=new WeakMap,$n=new WeakMap,si=new WeakMap,zl=new WeakMap,Ts=new WeakMap,Id=new WeakMap,Ul=new WeakMap,Vl=new WeakMap,oi=new WeakMap,ai=new WeakMap,Qo=new WeakMap,Hl=new WeakMap,gt=new WeakSet,oc=function(t){Je(this,gt,Iv).call(this);let n=R(this,at).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Pr)),n},jv=function(){Je(this,gt,Pv).call(this);const t=bl(this.options.staleTime,R(this,at));if(Kl||R(this,$n).isStale||!Tv(t))return;const r=BE(R(this,$n).dataUpdatedAt,t)+1;xe(this,oi,setTimeout(()=>{R(this,$n).isStale||this.updateResult()},r))},Rv=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(R(this,at)):this.options.refetchInterval)??!1},Ov=function(t){Je(this,gt,Mv).call(this),xe(this,Qo,t),!(Kl||Qr(this.options.enabled,R(this,at))===!1||!Tv(R(this,Qo))||R(this,Qo)===0)&&xe(this,ai,setInterval(()=>{(this.options.refetchIntervalInBackground||Ib.isFocused())&&Je(this,gt,oc).call(this)},R(this,Qo)))},Nv=function(){Je(this,gt,jv).call(this),Je(this,gt,Ov).call(this,Je(this,gt,Rv).call(this))},Pv=function(){R(this,oi)&&(clearTimeout(R(this,oi)),xe(this,oi,void 0))},Mv=function(){R(this,ai)&&(clearInterval(R(this,ai)),xe(this,ai,void 0))},Iv=function(){const t=R(this,Qn).getQueryCache().build(R(this,Qn),this.options);if(t===R(this,at))return;const n=R(this,at);xe(this,at,t),xe(this,Md,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},QE=function(t){cn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(R(this,$n))}),R(this,Qn).getQueryCache().notify({query:R(this,at),type:"observerResultsUpdated"})})},kE);function ND(e,t){return Qr(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function nS(e,t){return ND(e,t)||e.state.data!==void 0&&Dv(e,t,t.refetchOnMount)}function Dv(e,t,n){if(Qr(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Db(e,t)}return!1}function rS(e,t,n,r){return(e!==t||Qr(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Db(e,n)}function Db(e,t){return Qr(t.enabled,e)!==!1&&e.isStaleByTime(bl(t.staleTime,e))}function PD(e,t){return!Tp(e.getCurrentResult(),t)}var Zo,Yo,Zn,to,co,Xf,Av,_E,MD=(_E=class extends lu{constructor(n,r){super();Ie(this,co);Ie(this,Zo);Ie(this,Yo);Ie(this,Zn);Ie(this,to);xe(this,Zo,n),this.setOptions(r),this.bindMethods(),Je(this,co,Xf).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(n){var s;const r=this.options;this.options=R(this,Zo).defaultMutationOptions(n),Tp(this.options,r)||R(this,Zo).getMutationCache().notify({type:"observerOptionsUpdated",mutation:R(this,Zn),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&gi(r.mutationKey)!==gi(this.options.mutationKey)?this.reset():((s=R(this,Zn))==null?void 0:s.state.status)==="pending"&&R(this,Zn).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=R(this,Zn))==null||n.removeObserver(this)}onMutationUpdate(n){Je(this,co,Xf).call(this),Je(this,co,Av).call(this,n)}getCurrentResult(){return R(this,Yo)}reset(){var n;(n=R(this,Zn))==null||n.removeObserver(this),xe(this,Zn,void 0),Je(this,co,Xf).call(this),Je(this,co,Av).call(this)}mutate(n,r){var s;return xe(this,to,r),(s=R(this,Zn))==null||s.removeObserver(this),xe(this,Zn,R(this,Zo).getMutationCache().build(R(this,Zo),this.options)),R(this,Zn).addObserver(this),R(this,Zn).execute(n)}},Zo=new WeakMap,Yo=new WeakMap,Zn=new WeakMap,to=new WeakMap,co=new WeakSet,Xf=function(){var r;const n=((r=R(this,Zn))==null?void 0:r.state)??JE();xe(this,Yo,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},Av=function(n){cn.batch(()=>{var r,s,o,a,i,c,l,d;if(R(this,to)&&this.hasListeners()){const p=R(this,Yo).variables,f=R(this,Yo).context;(n==null?void 0:n.type)==="success"?((s=(r=R(this,to)).onSuccess)==null||s.call(r,n.data,p,f),(a=(o=R(this,to)).onSettled)==null||a.call(o,n.data,null,p,f)):(n==null?void 0:n.type)==="error"&&((c=(i=R(this,to)).onError)==null||c.call(i,n.error,p,f),(d=(l=R(this,to)).onSettled)==null||d.call(l,void 0,n.error,p,f))}this.listeners.forEach(p=>{p(R(this,Yo))})})},_E),ZE=v.createContext(void 0),Ab=e=>{const t=v.useContext(ZE);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},ID=({client:e,children:t})=>(v.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),u.jsx(ZE.Provider,{value:e,children:t})),YE=v.createContext(!1),DD=()=>v.useContext(YE);YE.Provider;function AD(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var FD=v.createContext(AD()),LD=()=>v.useContext(FD);function XE(e,t){return typeof e=="function"?e(...t):!!e}function $D(){}var BD=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},zD=e=>{v.useEffect(()=>{e.clearReset()},[e])},UD=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&XE(n,[e.error,r]),VD=e=>{e.suspense&&(typeof e.staleTime!="number"&&(e.staleTime=1e3),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3)))},HD=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,KD=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function qD(e,t,n){var l,d,p,f;const r=Ab(),s=DD(),o=LD(),a=r.defaultQueryOptions(e);(d=(l=r.getDefaultOptions().queries)==null?void 0:l._experimental_beforeQuery)==null||d.call(l,a),a._optimisticResults=s?"isRestoring":"optimistic",VD(a),BD(a,o),zD(o);const[i]=v.useState(()=>new t(r,a)),c=i.getOptimisticResult(a);if(v.useSyncExternalStore(v.useCallback(h=>{const g=s?()=>{}:i.subscribe(cn.batchCalls(h));return i.updateResult(),g},[i,s]),()=>i.getCurrentResult(),()=>i.getCurrentResult()),v.useEffect(()=>{i.setOptions(a,{listeners:!1})},[a,i]),HD(a,c))throw KD(a,i,o);if(UD({result:c,errorResetBoundary:o,throwOnError:a.throwOnError,query:r.getQueryCache().get(a.queryHash)}))throw c.error;return(f=(p=r.getDefaultOptions().queries)==null?void 0:p._experimental_afterQuery)==null||f.call(p,a,c),a.notifyOnChangeProps?c:i.trackResult(c)}function lt(e,t){return qD(e,OD)}function WD(e,t){const n=Ab(),[r]=v.useState(()=>new MD(n,e));v.useEffect(()=>{r.setOptions(e)},[r,e]);const s=v.useSyncExternalStore(v.useCallback(a=>r.subscribe(cn.batchCalls(a)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=v.useCallback((a,i)=>{r.mutate(a,i).catch($D)},[r]);if(s.error&&XE(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:o,mutateAsync:s.mutate}}var Fv={},eT={exports:{}},Cr={},tT={exports:{}},nT={};/** + * @license React + * scheduler.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */(function(e){function t(F,A){var Y=F.length;F.push(A);e:for(;0>>1,z=F[de];if(0>>1;des(ie,Y))oes(W,ie)?(F[de]=W,F[oe]=Y,de=oe):(F[de]=ie,F[ne]=Y,de=ne);else if(oes(W,Y))F[de]=W,F[oe]=Y,de=oe;else break e}}return A}function s(F,A){var Y=F.sortIndex-A.sortIndex;return Y!==0?Y:F.id-A.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var a=Date,i=a.now();e.unstable_now=function(){return a.now()-i}}var c=[],l=[],d=1,p=null,f=3,h=!1,g=!1,m=!1,x=typeof setTimeout=="function"?setTimeout:null,b=typeof clearTimeout=="function"?clearTimeout:null,y=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function w(F){for(var A=n(l);A!==null;){if(A.callback===null)r(l);else if(A.startTime<=F)r(l),A.sortIndex=A.expirationTime,t(c,A);else break;A=n(l)}}function S(F){if(m=!1,w(F),!g)if(n(c)!==null)g=!0,ee(E);else{var A=n(l);A!==null&&q(S,A.startTime-F)}}function E(F,A){g=!1,m&&(m=!1,b(T),T=-1),h=!0;var Y=f;try{for(w(A),p=n(c);p!==null&&(!(p.expirationTime>A)||F&&!U());){var de=p.callback;if(typeof de=="function"){p.callback=null,f=p.priorityLevel;var z=de(p.expirationTime<=A);A=e.unstable_now(),typeof z=="function"?p.callback=z:p===n(c)&&r(c),w(A)}else r(c);p=n(c)}if(p!==null)var se=!0;else{var ne=n(l);ne!==null&&q(S,ne.startTime-A),se=!1}return se}finally{p=null,f=Y,h=!1}}var C=!1,k=null,T=-1,O=5,M=-1;function U(){return!(e.unstable_now()-MF||125de?(F.sortIndex=Y,t(l,F),n(c)===null&&F===n(l)&&(m?(b(T),T=-1):m=!0,q(S,Y-de))):(F.sortIndex=z,t(c,F),g||h||(g=!0,ee(E))),F},e.unstable_shouldYield=U,e.unstable_wrapCallback=function(F){var A=f;return function(){var Y=f;f=A;try{return F.apply(this,arguments)}finally{f=Y}}}})(nT);tT.exports=nT;var GD=tT.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var JD=v,br=GD;function te(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Lv=Object.prototype.hasOwnProperty,QD=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,sS={},oS={};function ZD(e){return Lv.call(oS,e)?!0:Lv.call(sS,e)?!1:QD.test(e)?oS[e]=!0:(sS[e]=!0,!1)}function YD(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function XD(e,t,n,r){if(t===null||typeof t>"u"||YD(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Wn(e,t,n,r,s,o,a){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=o,this.removeEmptyString=a}var Tn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Tn[e]=new Wn(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Tn[t]=new Wn(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Tn[e]=new Wn(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Tn[e]=new Wn(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Tn[e]=new Wn(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Tn[e]=new Wn(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Tn[e]=new Wn(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Tn[e]=new Wn(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Tn[e]=new Wn(e,5,!1,e.toLowerCase(),null,!1,!1)});var Fb=/[\-:]([a-z])/g;function Lb(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Fb,Lb);Tn[t]=new Wn(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Fb,Lb);Tn[t]=new Wn(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Fb,Lb);Tn[t]=new Wn(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Tn[e]=new Wn(e,1,!1,e.toLowerCase(),null,!1,!1)});Tn.xlinkHref=new Wn("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Tn[e]=new Wn(e,1,!1,e.toLowerCase(),null,!0,!0)});function $b(e,t,n,r){var s=Tn.hasOwnProperty(t)?Tn[t]:null;(s!==null?s.type!==0:r||!(2i||s[a]!==o[i]){var c=` +`+s[a].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}while(1<=a&&0<=i);break}}}finally{lm=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?ac(e):""}function eA(e){switch(e.tag){case 5:return ac(e.type);case 16:return ac("Lazy");case 13:return ac("Suspense");case 19:return ac("SuspenseList");case 0:case 2:case 15:return e=um(e.type,!1),e;case 11:return e=um(e.type.render,!1),e;case 1:return e=um(e.type,!0),e;default:return""}}function Uv(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case sl:return"Fragment";case rl:return"Portal";case $v:return"Profiler";case Bb:return"StrictMode";case Bv:return"Suspense";case zv:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case oT:return(e.displayName||"Context")+".Consumer";case sT:return(e._context.displayName||"Context")+".Provider";case zb:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Ub:return t=e.displayName||null,t!==null?t:Uv(e.type)||"Memo";case $o:t=e._payload,e=e._init;try{return Uv(e(t))}catch{}}return null}function tA(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Uv(t);case 8:return t===Bb?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function da(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function iT(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function nA(e){var t=iT(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,o=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(a){r=""+a,o.call(this,a)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(a){r=""+a},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function pf(e){e._valueTracker||(e._valueTracker=nA(e))}function lT(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=iT(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function _p(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Vv(e,t){var n=t.checked;return Bt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function iS(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=da(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function uT(e,t){t=t.checked,t!=null&&$b(e,"checked",t,!1)}function Hv(e,t){uT(e,t);var n=da(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Kv(e,t.type,n):t.hasOwnProperty("defaultValue")&&Kv(e,t.type,da(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function lS(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Kv(e,t,n){(t!=="number"||_p(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var ic=Array.isArray;function xl(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=hf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Fc(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var yc={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},rA=["Webkit","ms","Moz","O"];Object.keys(yc).forEach(function(e){rA.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),yc[t]=yc[e]})});function pT(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||yc.hasOwnProperty(e)&&yc[e]?(""+t).trim():t+"px"}function hT(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=pT(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var sA=Bt({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Gv(e,t){if(t){if(sA[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(te(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(te(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(te(61))}if(t.style!=null&&typeof t.style!="object")throw Error(te(62))}}function Jv(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Qv=null;function Vb(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Zv=null,wl=null,Sl=null;function dS(e){if(e=Ld(e)){if(typeof Zv!="function")throw Error(te(280));var t=e.stateNode;t&&(t=Lh(t),Zv(e.stateNode,e.type,t))}}function gT(e){wl?Sl?Sl.push(e):Sl=[e]:wl=e}function mT(){if(wl){var e=wl,t=Sl;if(Sl=wl=null,dS(e),t)for(e=0;e>>=0,e===0?32:31-(gA(e)/mA|0)|0}var gf=64,mf=4194304;function lc(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Np(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,o=e.pingedLanes,a=n&268435455;if(a!==0){var i=a&~s;i!==0?r=lc(i):(o&=a,o!==0&&(r=lc(o)))}else a=n&~s,a!==0?r=lc(a):o!==0&&(r=lc(o));if(r===0)return 0;if(t!==0&&t!==r&&!(t&s)&&(s=r&-r,o=t&-t,s>=o||s===16&&(o&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Ad(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-ts(t),e[t]=n}function xA(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=xc),xS=" ",wS=!1;function AT(e,t){switch(e){case"keyup":return GA.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function FT(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var ol=!1;function QA(e,t){switch(e){case"compositionend":return FT(t);case"keypress":return t.which!==32?null:(wS=!0,xS);case"textInput":return e=t.data,e===xS&&wS?null:e;default:return null}}function ZA(e,t){if(ol)return e==="compositionend"||!Zb&&AT(e,t)?(e=IT(),tp=Gb=Xo=null,ol=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=TS(n)}}function zT(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?zT(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function UT(){for(var e=window,t=_p();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=_p(e.document)}return t}function Yb(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function aF(e){var t=UT(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&zT(n.ownerDocument.documentElement,n)){if(r!==null&&Yb(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=n.textContent.length,o=Math.min(r.start,s);r=r.end===void 0?o:Math.min(r.end,s),!e.extend&&o>r&&(s=r,r=o,o=s),s=kS(n,o);var a=kS(n,r);s&&a&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),o>r?(e.addRange(t),e.extend(a.node,a.offset)):(t.setEnd(a.node,a.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,al=null,ry=null,Sc=null,sy=!1;function _S(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;sy||al==null||al!==_p(r)||(r=al,"selectionStart"in r&&Yb(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Sc&&Vc(Sc,r)||(Sc=r,r=Ip(ry,"onSelect"),0ul||(e.current=cy[ul],cy[ul]=null,ul--)}function Et(e,t){ul++,cy[ul]=e.current,e.current=t}var fa={},In=Ea(fa),tr=Ea(!1),mi=fa;function Wl(e,t){var n=e.type.contextTypes;if(!n)return fa;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},o;for(o in n)s[o]=t[o];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function nr(e){return e=e.childContextTypes,e!=null}function Ap(){Ot(tr),Ot(In)}function IS(e,t,n){if(In.current!==fa)throw Error(te(168));Et(In,t),Et(tr,n)}function ZT(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(te(108,tA(e)||"Unknown",s));return Bt({},n,r)}function Fp(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||fa,mi=In.current,Et(In,e),Et(tr,tr.current),!0}function DS(e,t,n){var r=e.stateNode;if(!r)throw Error(te(169));n?(e=ZT(e,t,mi),r.__reactInternalMemoizedMergedChildContext=e,Ot(tr),Ot(In),Et(In,e)):Ot(tr),Et(tr,n)}var eo=null,$h=!1,Cm=!1;function YT(e){eo===null?eo=[e]:eo.push(e)}function yF(e){$h=!0,YT(e)}function Ta(){if(!Cm&&eo!==null){Cm=!0;var e=0,t=vt;try{var n=eo;for(vt=1;e>=a,s-=a,ro=1<<32-ts(t)+s|n<T?(O=k,k=null):O=k.sibling;var M=f(b,k,w[T],S);if(M===null){k===null&&(k=O);break}e&&k&&M.alternate===null&&t(b,k),y=o(M,y,T),C===null?E=M:C.sibling=M,C=M,k=O}if(T===w.length)return n(b,k),Pt&&$a(b,T),E;if(k===null){for(;TT?(O=k,k=null):O=k.sibling;var U=f(b,k,M.value,S);if(U===null){k===null&&(k=O);break}e&&k&&U.alternate===null&&t(b,k),y=o(U,y,T),C===null?E=U:C.sibling=U,C=U,k=O}if(M.done)return n(b,k),Pt&&$a(b,T),E;if(k===null){for(;!M.done;T++,M=w.next())M=p(b,M.value,S),M!==null&&(y=o(M,y,T),C===null?E=M:C.sibling=M,C=M);return Pt&&$a(b,T),E}for(k=r(b,k);!M.done;T++,M=w.next())M=h(k,b,T,M.value,S),M!==null&&(e&&M.alternate!==null&&k.delete(M.key===null?T:M.key),y=o(M,y,T),C===null?E=M:C.sibling=M,C=M);return e&&k.forEach(function(I){return t(b,I)}),Pt&&$a(b,T),E}function x(b,y,w,S){if(typeof w=="object"&&w!==null&&w.type===sl&&w.key===null&&(w=w.props.children),typeof w=="object"&&w!==null){switch(w.$$typeof){case ff:e:{for(var E=w.key,C=y;C!==null;){if(C.key===E){if(E=w.type,E===sl){if(C.tag===7){n(b,C.sibling),y=s(C,w.props.children),y.return=b,b=y;break e}}else if(C.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===$o&&LS(E)===C.type){n(b,C.sibling),y=s(C,w.props),y.ref=Uu(b,C,w),y.return=b,b=y;break e}n(b,C);break}else t(b,C);C=C.sibling}w.type===sl?(y=li(w.props.children,b.mode,S,w.key),y.return=b,b=y):(S=up(w.type,w.key,w.props,null,b.mode,S),S.ref=Uu(b,y,w),S.return=b,b=S)}return a(b);case rl:e:{for(C=w.key;y!==null;){if(y.key===C)if(y.tag===4&&y.stateNode.containerInfo===w.containerInfo&&y.stateNode.implementation===w.implementation){n(b,y.sibling),y=s(y,w.children||[]),y.return=b,b=y;break e}else{n(b,y);break}else t(b,y);y=y.sibling}y=Nm(w,b.mode,S),y.return=b,b=y}return a(b);case $o:return C=w._init,x(b,y,C(w._payload),S)}if(ic(w))return g(b,y,w,S);if(Fu(w))return m(b,y,w,S);Cf(b,w)}return typeof w=="string"&&w!==""||typeof w=="number"?(w=""+w,y!==null&&y.tag===6?(n(b,y.sibling),y=s(y,w),y.return=b,b=y):(n(b,y),y=Om(w,b.mode,S),y.return=b,b=y),a(b)):n(b,y)}return x}var Jl=nk(!0),rk=nk(!1),Bp=Ea(null),zp=null,fl=null,nx=null;function rx(){nx=fl=zp=null}function sx(e){var t=Bp.current;Ot(Bp),e._currentValue=t}function py(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function El(e,t){zp=e,nx=fl=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(er=!0),e.firstContext=null)}function Br(e){var t=e._currentValue;if(nx!==e)if(e={context:e,memoizedValue:t,next:null},fl===null){if(zp===null)throw Error(te(308));fl=e,zp.dependencies={lanes:0,firstContext:e}}else fl=fl.next=e;return t}var Ha=null;function ox(e){Ha===null?Ha=[e]:Ha.push(e)}function sk(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,ox(t)):(n.next=s.next,s.next=n),t.interleaved=n,ho(e,r)}function ho(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Bo=!1;function ax(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function ok(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function lo(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function ia(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,ct&2){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,ho(e,n)}return s=r.interleaved,s===null?(t.next=t,ox(r)):(t.next=s.next,s.next=t),r.interleaved=t,ho(e,n)}function rp(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Kb(e,n)}}function $S(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,o=null;if(n=n.firstBaseUpdate,n!==null){do{var a={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};o===null?s=o=a:o=o.next=a,n=n.next}while(n!==null);o===null?s=o=t:o=o.next=t}else s=o=t;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:o,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Up(e,t,n,r){var s=e.updateQueue;Bo=!1;var o=s.firstBaseUpdate,a=s.lastBaseUpdate,i=s.shared.pending;if(i!==null){s.shared.pending=null;var c=i,l=c.next;c.next=null,a===null?o=l:a.next=l,a=c;var d=e.alternate;d!==null&&(d=d.updateQueue,i=d.lastBaseUpdate,i!==a&&(i===null?d.firstBaseUpdate=l:i.next=l,d.lastBaseUpdate=c))}if(o!==null){var p=s.baseState;a=0,d=l=c=null,i=o;do{var f=i.lane,h=i.eventTime;if((r&f)===f){d!==null&&(d=d.next={eventTime:h,lane:0,tag:i.tag,payload:i.payload,callback:i.callback,next:null});e:{var g=e,m=i;switch(f=t,h=n,m.tag){case 1:if(g=m.payload,typeof g=="function"){p=g.call(h,p,f);break e}p=g;break e;case 3:g.flags=g.flags&-65537|128;case 0:if(g=m.payload,f=typeof g=="function"?g.call(h,p,f):g,f==null)break e;p=Bt({},p,f);break e;case 2:Bo=!0}}i.callback!==null&&i.lane!==0&&(e.flags|=64,f=s.effects,f===null?s.effects=[i]:f.push(i))}else h={eventTime:h,lane:f,tag:i.tag,payload:i.payload,callback:i.callback,next:null},d===null?(l=d=h,c=p):d=d.next=h,a|=f;if(i=i.next,i===null){if(i=s.shared.pending,i===null)break;f=i,i=f.next,f.next=null,s.lastBaseUpdate=f,s.shared.pending=null}}while(!0);if(d===null&&(c=p),s.baseState=c,s.firstBaseUpdate=l,s.lastBaseUpdate=d,t=s.shared.interleaved,t!==null){s=t;do a|=s.lane,s=s.next;while(s!==t)}else o===null&&(s.shared.lanes=0);bi|=a,e.lanes=a,e.memoizedState=p}}function BS(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Tm.transition;Tm.transition={};try{e(!1),t()}finally{vt=n,Tm.transition=r}}function Sk(){return zr().memoizedState}function SF(e,t,n){var r=ua(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Ck(e))Ek(t,n);else if(n=sk(e,t,n,r),n!==null){var s=Hn();ns(n,e,r,s),Tk(n,t,r)}}function CF(e,t,n){var r=ua(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ck(e))Ek(t,s);else{var o=e.alternate;if(e.lanes===0&&(o===null||o.lanes===0)&&(o=t.lastRenderedReducer,o!==null))try{var a=t.lastRenderedState,i=o(a,n);if(s.hasEagerState=!0,s.eagerState=i,us(i,a)){var c=t.interleaved;c===null?(s.next=s,ox(t)):(s.next=c.next,c.next=s),t.interleaved=s;return}}catch{}finally{}n=sk(e,t,s,r),n!==null&&(s=Hn(),ns(n,e,r,s),Tk(n,t,r))}}function Ck(e){var t=e.alternate;return e===Lt||t!==null&&t===Lt}function Ek(e,t){Cc=Hp=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Tk(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Kb(e,n)}}var Kp={readContext:Br,useCallback:jn,useContext:jn,useEffect:jn,useImperativeHandle:jn,useInsertionEffect:jn,useLayoutEffect:jn,useMemo:jn,useReducer:jn,useRef:jn,useState:jn,useDebugValue:jn,useDeferredValue:jn,useTransition:jn,useMutableSource:jn,useSyncExternalStore:jn,useId:jn,unstable_isNewReconciler:!1},EF={readContext:Br,useCallback:function(e,t){return ws().memoizedState=[e,t===void 0?null:t],e},useContext:Br,useEffect:US,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,op(4194308,4,vk.bind(null,t,e),n)},useLayoutEffect:function(e,t){return op(4194308,4,e,t)},useInsertionEffect:function(e,t){return op(4,2,e,t)},useMemo:function(e,t){var n=ws();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ws();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=SF.bind(null,Lt,e),[r.memoizedState,e]},useRef:function(e){var t=ws();return e={current:e},t.memoizedState=e},useState:zS,useDebugValue:hx,useDeferredValue:function(e){return ws().memoizedState=e},useTransition:function(){var e=zS(!1),t=e[0];return e=wF.bind(null,e[1]),ws().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Lt,s=ws();if(Pt){if(n===void 0)throw Error(te(407));n=n()}else{if(n=t(),vn===null)throw Error(te(349));yi&30||uk(r,t,n)}s.memoizedState=n;var o={value:n,getSnapshot:t};return s.queue=o,US(dk.bind(null,r,o,e),[e]),r.flags|=2048,Zc(9,ck.bind(null,r,o,n,t),void 0,null),n},useId:function(){var e=ws(),t=vn.identifierPrefix;if(Pt){var n=so,r=ro;n=(r&~(1<<32-ts(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Jc++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=a.createElement(n,{is:r.is}):(e=a.createElement(n),n==="select"&&(a=e,r.multiple?a.multiple=!0:r.size&&(a.size=r.size))):e=a.createElementNS(e,n),e[ks]=t,e[qc]=r,Dk(e,t,!1,!1),t.stateNode=e;e:{switch(a=Jv(n,r),n){case"dialog":jt("cancel",e),jt("close",e),s=r;break;case"iframe":case"object":case"embed":jt("load",e),s=r;break;case"video":case"audio":for(s=0;sYl&&(t.flags|=128,r=!0,Vu(o,!1),t.lanes=4194304)}else{if(!r)if(e=Vp(a),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Vu(o,!0),o.tail===null&&o.tailMode==="hidden"&&!a.alternate&&!Pt)return Rn(t),null}else 2*Jt()-o.renderingStartTime>Yl&&n!==1073741824&&(t.flags|=128,r=!0,Vu(o,!1),t.lanes=4194304);o.isBackwards?(a.sibling=t.child,t.child=a):(n=o.last,n!==null?n.sibling=a:t.child=a,o.last=a)}return o.tail!==null?(t=o.tail,o.rendering=t,o.tail=t.sibling,o.renderingStartTime=Jt(),t.sibling=null,n=Ft.current,Et(Ft,r?n&1|2:n&1),t):(Rn(t),null);case 22:case 23:return xx(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?cr&1073741824&&(Rn(t),t.subtreeFlags&6&&(t.flags|=8192)):Rn(t),null;case 24:return null;case 25:return null}throw Error(te(156,t.tag))}function PF(e,t){switch(ex(t),t.tag){case 1:return nr(t.type)&&Ap(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ql(),Ot(tr),Ot(In),ux(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return lx(t),null;case 13:if(Ot(Ft),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(te(340));Gl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Ot(Ft),null;case 4:return Ql(),null;case 10:return sx(t.type._context),null;case 22:case 23:return xx(),null;case 24:return null;default:return null}}var Tf=!1,Mn=!1,MF=typeof WeakSet=="function"?WeakSet:Set,we=null;function pl(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Kt(e,t,r)}else n.current=null}function Sy(e,t,n){try{n()}catch(r){Kt(e,t,r)}}var XS=!1;function IF(e,t){if(oy=Pp,e=UT(),Yb(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break e}var a=0,i=-1,c=-1,l=0,d=0,p=e,f=null;t:for(;;){for(var h;p!==n||s!==0&&p.nodeType!==3||(i=a+s),p!==o||r!==0&&p.nodeType!==3||(c=a+r),p.nodeType===3&&(a+=p.nodeValue.length),(h=p.firstChild)!==null;)f=p,p=h;for(;;){if(p===e)break t;if(f===n&&++l===s&&(i=a),f===o&&++d===r&&(c=a),(h=p.nextSibling)!==null)break;p=f,f=p.parentNode}p=h}n=i===-1||c===-1?null:{start:i,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(ay={focusedElem:e,selectionRange:n},Pp=!1,we=t;we!==null;)if(t=we,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,we=e;else for(;we!==null;){t=we;try{var g=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(g!==null){var m=g.memoizedProps,x=g.memoizedState,b=t.stateNode,y=b.getSnapshotBeforeUpdate(t.elementType===t.type?m:qr(t.type,m),x);b.__reactInternalSnapshotBeforeUpdate=y}break;case 3:var w=t.stateNode.containerInfo;w.nodeType===1?w.textContent="":w.nodeType===9&&w.documentElement&&w.removeChild(w.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(te(163))}}catch(S){Kt(t,t.return,S)}if(e=t.sibling,e!==null){e.return=t.return,we=e;break}we=t.return}return g=XS,XS=!1,g}function Ec(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var o=s.destroy;s.destroy=void 0,o!==void 0&&Sy(t,n,o)}s=s.next}while(s!==r)}}function Uh(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Cy(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Lk(e){var t=e.alternate;t!==null&&(e.alternate=null,Lk(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[ks],delete t[qc],delete t[uy],delete t[mF],delete t[vF])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function $k(e){return e.tag===5||e.tag===3||e.tag===4}function e0(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||$k(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Ey(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Dp));else if(r!==4&&(e=e.child,e!==null))for(Ey(e,t,n),e=e.sibling;e!==null;)Ey(e,t,n),e=e.sibling}function Ty(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ty(e,t,n),e=e.sibling;e!==null;)Ty(e,t,n),e=e.sibling}var Sn=null,Gr=!1;function No(e,t,n){for(n=n.child;n!==null;)Bk(e,t,n),n=n.sibling}function Bk(e,t,n){if(Ds&&typeof Ds.onCommitFiberUnmount=="function")try{Ds.onCommitFiberUnmount(Ih,n)}catch{}switch(n.tag){case 5:Mn||pl(n,t);case 6:var r=Sn,s=Gr;Sn=null,No(e,t,n),Sn=r,Gr=s,Sn!==null&&(Gr?(e=Sn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Sn.removeChild(n.stateNode));break;case 18:Sn!==null&&(Gr?(e=Sn,n=n.stateNode,e.nodeType===8?Sm(e.parentNode,n):e.nodeType===1&&Sm(e,n),zc(e)):Sm(Sn,n.stateNode));break;case 4:r=Sn,s=Gr,Sn=n.stateNode.containerInfo,Gr=!0,No(e,t,n),Sn=r,Gr=s;break;case 0:case 11:case 14:case 15:if(!Mn&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var o=s,a=o.destroy;o=o.tag,a!==void 0&&(o&2||o&4)&&Sy(n,t,a),s=s.next}while(s!==r)}No(e,t,n);break;case 1:if(!Mn&&(pl(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(i){Kt(n,t,i)}No(e,t,n);break;case 21:No(e,t,n);break;case 22:n.mode&1?(Mn=(r=Mn)||n.memoizedState!==null,No(e,t,n),Mn=r):No(e,t,n);break;default:No(e,t,n)}}function t0(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new MF),t.forEach(function(r){var s=VF.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function Kr(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=a),r&=~o}if(r=s,r=Jt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*AF(r/1960))-r,10e?16:e,ea===null)var r=!1;else{if(e=ea,ea=null,Gp=0,ct&6)throw Error(te(331));var s=ct;for(ct|=4,we=e.current;we!==null;){var o=we,a=o.child;if(we.flags&16){var i=o.deletions;if(i!==null){for(var c=0;cJt()-yx?ii(e,0):vx|=n),rr(e,t)}function Gk(e,t){t===0&&(e.mode&1?(t=mf,mf<<=1,!(mf&130023424)&&(mf=4194304)):t=1);var n=Hn();e=ho(e,t),e!==null&&(Ad(e,t,n),rr(e,n))}function UF(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Gk(e,n)}function VF(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(te(314))}r!==null&&r.delete(t),Gk(e,n)}var Jk;Jk=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||tr.current)er=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return er=!1,OF(e,t,n);er=!!(e.flags&131072)}else er=!1,Pt&&t.flags&1048576&&XT(t,$p,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;ap(e,t),e=t.pendingProps;var s=Wl(t,In.current);El(t,n),s=dx(null,t,r,e,s,n);var o=fx();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,nr(r)?(o=!0,Fp(t)):o=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,ax(t),s.updater=zh,t.stateNode=s,s._reactInternals=t,gy(t,r,e,n),t=yy(null,t,r,!0,o,n)):(t.tag=0,Pt&&o&&Xb(t),zn(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(ap(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=KF(r),e=qr(r,e),s){case 0:t=vy(null,t,r,e,n);break e;case 1:t=QS(null,t,r,e,n);break e;case 11:t=GS(null,t,r,e,n);break e;case 14:t=JS(null,t,r,qr(r.type,e),n);break e}throw Error(te(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:qr(r,s),vy(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:qr(r,s),QS(e,t,r,s,n);case 3:e:{if(Pk(t),e===null)throw Error(te(387));r=t.pendingProps,o=t.memoizedState,s=o.element,ok(e,t),Up(t,r,null,n);var a=t.memoizedState;if(r=a.element,o.isDehydrated)if(o={element:r,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){s=Zl(Error(te(423)),t),t=ZS(e,t,r,n,s);break e}else if(r!==s){s=Zl(Error(te(424)),t),t=ZS(e,t,r,n,s);break e}else for(hr=aa(t.stateNode.containerInfo.firstChild),mr=t,Pt=!0,Zr=null,n=rk(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Gl(),r===s){t=go(e,t,n);break e}zn(e,t,r,n)}t=t.child}return t;case 5:return ak(t),e===null&&fy(t),r=t.type,s=t.pendingProps,o=e!==null?e.memoizedProps:null,a=s.children,iy(r,s)?a=null:o!==null&&iy(r,o)&&(t.flags|=32),Nk(e,t),zn(e,t,a,n),t.child;case 6:return e===null&&fy(t),null;case 13:return Mk(e,t,n);case 4:return ix(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Jl(t,null,r,n):zn(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:qr(r,s),GS(e,t,r,s,n);case 7:return zn(e,t,t.pendingProps,n),t.child;case 8:return zn(e,t,t.pendingProps.children,n),t.child;case 12:return zn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,o=t.memoizedProps,a=s.value,Et(Bp,r._currentValue),r._currentValue=a,o!==null)if(us(o.value,a)){if(o.children===s.children&&!tr.current){t=go(e,t,n);break e}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var i=o.dependencies;if(i!==null){a=o.child;for(var c=i.firstContext;c!==null;){if(c.context===r){if(o.tag===1){c=lo(-1,n&-n),c.tag=2;var l=o.updateQueue;if(l!==null){l=l.shared;var d=l.pending;d===null?c.next=c:(c.next=d.next,d.next=c),l.pending=c}}o.lanes|=n,c=o.alternate,c!==null&&(c.lanes|=n),py(o.return,n,t),i.lanes|=n;break}c=c.next}}else if(o.tag===10)a=o.type===t.type?null:o.child;else if(o.tag===18){if(a=o.return,a===null)throw Error(te(341));a.lanes|=n,i=a.alternate,i!==null&&(i.lanes|=n),py(a,n,t),a=o.sibling}else a=o.child;if(a!==null)a.return=o;else for(a=o;a!==null;){if(a===t){a=null;break}if(o=a.sibling,o!==null){o.return=a.return,a=o;break}a=a.return}o=a}zn(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,El(t,n),s=Br(s),r=r(s),t.flags|=1,zn(e,t,r,n),t.child;case 14:return r=t.type,s=qr(r,t.pendingProps),s=qr(r.type,s),JS(e,t,r,s,n);case 15:return Rk(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:qr(r,s),ap(e,t),t.tag=1,nr(r)?(e=!0,Fp(t)):e=!1,El(t,n),kk(t,r,s),gy(t,r,s,n),yy(null,t,r,!0,e,n);case 19:return Ik(e,t,n);case 22:return Ok(e,t,n)}throw Error(te(156,t.tag))};function Qk(e,t){return CT(e,t)}function HF(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ar(e,t,n,r){return new HF(e,t,n,r)}function Sx(e){return e=e.prototype,!(!e||!e.isReactComponent)}function KF(e){if(typeof e=="function")return Sx(e)?1:0;if(e!=null){if(e=e.$$typeof,e===zb)return 11;if(e===Ub)return 14}return 2}function ca(e,t){var n=e.alternate;return n===null?(n=Ar(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function up(e,t,n,r,s,o){var a=2;if(r=e,typeof e=="function")Sx(e)&&(a=1);else if(typeof e=="string")a=5;else e:switch(e){case sl:return li(n.children,s,o,t);case Bb:a=8,s|=8;break;case $v:return e=Ar(12,n,t,s|2),e.elementType=$v,e.lanes=o,e;case Bv:return e=Ar(13,n,t,s),e.elementType=Bv,e.lanes=o,e;case zv:return e=Ar(19,n,t,s),e.elementType=zv,e.lanes=o,e;case aT:return Hh(n,s,o,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case sT:a=10;break e;case oT:a=9;break e;case zb:a=11;break e;case Ub:a=14;break e;case $o:a=16,r=null;break e}throw Error(te(130,e==null?e:typeof e,""))}return t=Ar(a,n,t,s),t.elementType=e,t.type=r,t.lanes=o,t}function li(e,t,n,r){return e=Ar(7,e,r,t),e.lanes=n,e}function Hh(e,t,n,r){return e=Ar(22,e,r,t),e.elementType=aT,e.lanes=n,e.stateNode={isHidden:!1},e}function Om(e,t,n){return e=Ar(6,e,null,t),e.lanes=n,e}function Nm(e,t,n){return t=Ar(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function qF(e,t,n,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=dm(0),this.expirationTimes=dm(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=dm(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function Cx(e,t,n,r,s,o,a,i,c){return e=new qF(e,t,n,i,c),t===1?(t=1,o===!0&&(t|=8)):t=0,o=Ar(3,null,null,t),e.current=o,o.stateNode=e,o.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},ax(o),e}function WF(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e_)}catch(e){console.error(e)}}e_(),eT.exports=Cr;var ka=eT.exports;const t_=jb(ka),YF=jE({__proto__:null,default:t_},[ka]);var u0=ka;Fv.createRoot=u0.createRoot,Fv.hydrateRoot=u0.hydrateRoot;const XF=(...e)=>{console!=null&&console.warn&&(ui(e[0])&&(e[0]=`react-i18next:: ${e[0]}`),console.warn(...e))},c0={},Oy=(...e)=>{ui(e[0])&&c0[e[0]]||(ui(e[0])&&(c0[e[0]]=new Date),XF(...e))},n_=(e,t)=>()=>{if(e.isInitialized)t();else{const n=()=>{setTimeout(()=>{e.off("initialized",n)},0),t()};e.on("initialized",n)}},d0=(e,t,n)=>{e.loadNamespaces(t,n_(e,n))},f0=(e,t,n,r)=>{ui(n)&&(n=[n]),n.forEach(s=>{e.options.ns.indexOf(s)<0&&e.options.ns.push(s)}),e.loadLanguages(t,n_(e,r))},e2=(e,t,n={})=>!t.languages||!t.languages.length?(Oy("i18n.languages were undefined or empty",t.languages),!0):t.hasLoadedNamespace(e,{lng:n.lng,precheck:(r,s)=>{var o;if(((o=n.bindI18n)==null?void 0:o.indexOf("languageChanging"))>-1&&r.services.backendConnector.backend&&r.isLanguageChangingTo&&!s(r.isLanguageChangingTo,e))return!1}}),ui=e=>typeof e=="string",t2=e=>typeof e=="object"&&e!==null,n2=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,r2={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","'":"'","'":"'",""":'"',""":'"'," ":" "," ":" ","©":"©","©":"©","®":"®","®":"®","…":"…","…":"…","/":"/","/":"/"},s2=e=>r2[e],o2=e=>e.replace(n2,s2);let Ny={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:o2};const a2=(e={})=>{Ny={...Ny,...e}},i2=()=>Ny;let r_;const l2=e=>{r_=e},u2=()=>r_,c2={type:"3rdParty",init(e){a2(e.options.react),l2(e)}},s_=v.createContext();class d2{constructor(){this.usedNamespaces={}}addUsedNamespaces(t){t.forEach(n=>{var r;(r=this.usedNamespaces)[n]??(r[n]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}const f2=(e,t)=>{const n=v.useRef();return v.useEffect(()=>{n.current=e},[e,t]),n.current},o_=(e,t,n,r)=>e.getFixedT(t,n,r),p2=(e,t,n,r)=>v.useCallback(o_(e,t,n,r),[e,t,n,r]),ze=(e,t={})=>{var S,E,C,k;const{i18n:n}=t,{i18n:r,defaultNS:s}=v.useContext(s_)||{},o=n||r||u2();if(o&&!o.reportNamespaces&&(o.reportNamespaces=new d2),!o){Oy("You will need to pass in an i18next instance by using initReactI18next");const T=(M,U)=>ui(U)?U:t2(U)&&ui(U.defaultValue)?U.defaultValue:Array.isArray(M)?M[M.length-1]:M,O=[T,{},!1];return O.t=T,O.i18n={},O.ready=!1,O}(S=o.options.react)!=null&&S.wait&&Oy("It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.");const a={...i2(),...o.options.react,...t},{useSuspense:i,keyPrefix:c}=a;let l=s||((E=o.options)==null?void 0:E.defaultNS);l=ui(l)?[l]:l||["translation"],(k=(C=o.reportNamespaces).addUsedNamespaces)==null||k.call(C,l);const d=(o.isInitialized||o.initializedStoreOnce)&&l.every(T=>e2(T,o,a)),p=p2(o,t.lng||null,a.nsMode==="fallback"?l:l[0],c),f=()=>p,h=()=>o_(o,t.lng||null,a.nsMode==="fallback"?l:l[0],c),[g,m]=v.useState(f);let x=l.join();t.lng&&(x=`${t.lng}${x}`);const b=f2(x),y=v.useRef(!0);v.useEffect(()=>{const{bindI18n:T,bindI18nStore:O}=a;y.current=!0,!d&&!i&&(t.lng?f0(o,t.lng,l,()=>{y.current&&m(h)}):d0(o,l,()=>{y.current&&m(h)})),d&&b&&b!==x&&y.current&&m(h);const M=()=>{y.current&&m(h)};return T&&(o==null||o.on(T,M)),O&&(o==null||o.store.on(O,M)),()=>{y.current=!1,o&&(T==null||T.split(" ").forEach(U=>o.off(U,M))),O&&o&&O.split(" ").forEach(U=>o.store.off(U,M))}},[o,x]),v.useEffect(()=>{y.current&&d&&m(f)},[o,c,d]);const w=[g,o,d];if(w.t=g,w.i18n=o,w.ready=d,d||!d&&!i)return w;throw new Promise(T=>{t.lng?f0(o,t.lng,l,()=>T()):d0(o,l,()=>T())})};function h2({i18n:e,defaultNS:t,children:n}){const r=v.useMemo(()=>({i18n:e,defaultNS:t}),[e,t]);return v.createElement(s_.Provider,{value:r},n)}/** + * @remix-run/router v1.18.0 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function At(){return At=Object.assign?Object.assign.bind():function(e){for(var t=1;t"u")throw new Error(t)}function Xl(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function m2(){return Math.random().toString(36).substr(2,8)}function h0(e,t){return{usr:e.state,key:e.key,idx:t}}function Xc(e,t,n,r){return n===void 0&&(n=null),At({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?_a(t):t,{state:n,key:t&&t.key||r||m2()})}function wi(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function _a(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function v2(e,t,n,r){r===void 0&&(r={});let{window:s=document.defaultView,v5Compat:o=!1}=r,a=s.history,i=en.Pop,c=null,l=d();l==null&&(l=0,a.replaceState(At({},a.state,{idx:l}),""));function d(){return(a.state||{idx:null}).idx}function p(){i=en.Pop;let x=d(),b=x==null?null:x-l;l=x,c&&c({action:i,location:m.location,delta:b})}function f(x,b){i=en.Push;let y=Xc(m.location,x,b);l=d()+1;let w=h0(y,l),S=m.createHref(y);try{a.pushState(w,"",S)}catch(E){if(E instanceof DOMException&&E.name==="DataCloneError")throw E;s.location.assign(S)}o&&c&&c({action:i,location:m.location,delta:1})}function h(x,b){i=en.Replace;let y=Xc(m.location,x,b);l=d();let w=h0(y,l),S=m.createHref(y);a.replaceState(w,"",S),o&&c&&c({action:i,location:m.location,delta:0})}function g(x){let b=s.location.origin!=="null"?s.location.origin:s.location.href,y=typeof x=="string"?x:wi(x);return y=y.replace(/ $/,"%20"),Ze(b,"No window.location.(origin|href) available to create URL for href: "+y),new URL(y,b)}let m={get action(){return i},get location(){return e(s,a)},listen(x){if(c)throw new Error("A history only accepts one active listener");return s.addEventListener(p0,p),c=x,()=>{s.removeEventListener(p0,p),c=null}},createHref(x){return t(s,x)},createURL:g,encodeLocation(x){let b=g(x);return{pathname:b.pathname,search:b.search,hash:b.hash}},push:f,replace:h,go(x){return a.go(x)}};return m}var Ct;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(Ct||(Ct={}));const y2=new Set(["lazy","caseSensitive","path","id","index","children"]);function b2(e){return e.index===!0}function ed(e,t,n,r){return n===void 0&&(n=[]),r===void 0&&(r={}),e.map((s,o)=>{let a=[...n,String(o)],i=typeof s.id=="string"?s.id:a.join("-");if(Ze(s.index!==!0||!s.children,"Cannot specify children on an index route"),Ze(!r[i],'Found a route id collision on id "'+i+`". Route id's must be globally unique within Data Router usages`),b2(s)){let c=At({},s,t(s),{id:i});return r[i]=c,c}else{let c=At({},s,t(s),{id:i,children:void 0});return r[i]=c,s.children&&(c.children=ed(s.children,t,a,r)),c}})}function Ua(e,t,n){return n===void 0&&(n="/"),cp(e,t,n,!1)}function cp(e,t,n,r){let s=typeof t=="string"?_a(t):t,o=du(s.pathname||"/",n);if(o==null)return null;let a=a_(e);w2(a);let i=null;for(let c=0;i==null&&c{let c={relativePath:i===void 0?o.path||"":i,caseSensitive:o.caseSensitive===!0,childrenIndex:a,route:o};c.relativePath.startsWith("/")&&(Ze(c.relativePath.startsWith(r),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(r.length));let l=uo([r,c.relativePath]),d=n.concat(c);o.children&&o.children.length>0&&(Ze(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+l+'".')),a_(o.children,t,d,l)),!(o.path==null&&!o.index)&&t.push({path:l,score:j2(l,o.index),routesMeta:d})};return e.forEach((o,a)=>{var i;if(o.path===""||!((i=o.path)!=null&&i.includes("?")))s(o,a);else for(let c of i_(o.path))s(o,a,c)}),t}function i_(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,s=n.endsWith("?"),o=n.replace(/\?$/,"");if(r.length===0)return s?[o,""]:[o];let a=i_(r.join("/")),i=[];return i.push(...a.map(c=>c===""?o:[o,c].join("/"))),s&&i.push(...a),i.map(c=>e.startsWith("/")&&c===""?"/":c)}function w2(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:R2(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const S2=/^:[\w-]+$/,C2=3,E2=2,T2=1,k2=10,_2=-2,g0=e=>e==="*";function j2(e,t){let n=e.split("/"),r=n.length;return n.some(g0)&&(r+=_2),t&&(r+=E2),n.filter(s=>!g0(s)).reduce((s,o)=>s+(S2.test(o)?C2:o===""?T2:k2),r)}function R2(e,t){return e.length===t.length&&e.slice(0,-1).every((r,s)=>r===t[s])?e[e.length-1]-t[t.length-1]:0}function O2(e,t,n){n===void 0&&(n=!1);let{routesMeta:r}=e,s={},o="/",a=[];for(let i=0;i{let{paramName:f,isOptional:h}=d;if(f==="*"){let m=i[p]||"";a=o.slice(0,o.length-m.length).replace(/(.)\/+$/,"$1")}const g=i[p];return h&&!g?l[f]=void 0:l[f]=(g||"").replace(/%2F/g,"/"),l},{}),pathname:o,pathnameBase:a,pattern:e}}function N2(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Xl(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],s="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,i,c)=>(r.push({paramName:i,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),s+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?s+="\\/*$":e!==""&&e!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,t?void 0:"i"),r]}function P2(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Xl(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function du(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function M2(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:s=""}=typeof e=="string"?_a(e):e;return{pathname:n?n.startsWith("/")?n:I2(n,t):t,search:A2(r),hash:F2(s)}}function I2(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(s=>{s===".."?n.length>1&&n.pop():s!=="."&&n.push(s)}),n.length>1?n.join("/"):"/"}function Pm(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function l_(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Jh(e,t){let n=l_(e);return t?n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function Qh(e,t,n,r){r===void 0&&(r=!1);let s;typeof e=="string"?s=_a(e):(s=At({},e),Ze(!s.pathname||!s.pathname.includes("?"),Pm("?","pathname","search",s)),Ze(!s.pathname||!s.pathname.includes("#"),Pm("#","pathname","hash",s)),Ze(!s.search||!s.search.includes("#"),Pm("#","search","hash",s)));let o=e===""||s.pathname==="",a=o?"/":s.pathname,i;if(a==null)i=n;else{let p=t.length-1;if(!r&&a.startsWith("..")){let f=a.split("/");for(;f[0]==="..";)f.shift(),p-=1;s.pathname=f.join("/")}i=p>=0?t[p]:"/"}let c=M2(s,i),l=a&&a!=="/"&&a.endsWith("/"),d=(o||a===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(l||d)&&(c.pathname+="/"),c}const uo=e=>e.join("/").replace(/\/\/+/g,"/"),D2=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),A2=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,F2=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;class _x{constructor(t,n,r,s){s===void 0&&(s=!1),this.status=t,this.statusText=n||"",this.internal=s,r instanceof Error?(this.data=r.toString(),this.error=r):this.data=r}}function Zh(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const u_=["post","put","patch","delete"],L2=new Set(u_),$2=["get",...u_],B2=new Set($2),z2=new Set([301,302,303,307,308]),U2=new Set([307,308]),Mm={state:"idle",location:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},V2={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},Ku={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},jx=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,H2=e=>({hasErrorBoundary:!!e.hasErrorBoundary}),c_="remix-router-transitions";function K2(e){const t=e.window?e.window:typeof window<"u"?window:void 0,n=typeof t<"u"&&typeof t.document<"u"&&typeof t.document.createElement<"u",r=!n;Ze(e.routes.length>0,"You must provide a non-empty routes array to createRouter");let s;if(e.mapRouteProperties)s=e.mapRouteProperties;else if(e.detectErrorBoundary){let N=e.detectErrorBoundary;s=P=>({hasErrorBoundary:N(P)})}else s=H2;let o={},a=ed(e.routes,s,void 0,o),i,c=e.basename||"/",l=e.unstable_dataStrategy||Q2,d=e.unstable_patchRoutesOnMiss,p=At({v7_fetcherPersist:!1,v7_normalizeFormMethod:!1,v7_partialHydration:!1,v7_prependBasename:!1,v7_relativeSplatPath:!1,v7_skipActionErrorRevalidation:!1},e.future),f=null,h=new Set,g=null,m=null,x=null,b=e.hydrationData!=null,y=Ua(a,e.history.location,c),w=null;if(y==null&&!d){let N=Bn(404,{pathname:e.history.location.pathname}),{matches:P,route:L}=k0(a);y=P,w={[L.id]:N}}y&&d&&!e.hydrationData&&rm(y,a,e.history.location.pathname).active&&(y=null);let S;if(!y)S=!1,y=[];else if(y.some(N=>N.route.lazy))S=!1;else if(!y.some(N=>N.route.loader))S=!0;else if(p.v7_partialHydration){let N=e.hydrationData?e.hydrationData.loaderData:null,P=e.hydrationData?e.hydrationData.errors:null,L=H=>H.route.loader?typeof H.route.loader=="function"&&H.route.loader.hydrate===!0?!1:N&&N[H.route.id]!==void 0||P&&P[H.route.id]!==void 0:!0;if(P){let H=y.findIndex(ye=>P[ye.route.id]!==void 0);S=y.slice(0,H+1).every(L)}else S=y.every(L)}else S=e.hydrationData!=null;let E,C={historyAction:e.history.action,location:e.history.location,matches:y,initialized:S,navigation:Mm,restoreScrollPosition:e.hydrationData!=null?!1:null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||w,fetchers:new Map,blockers:new Map},k=en.Pop,T=!1,O,M=!1,U=new Map,I=null,J=!1,V=!1,G=[],ee=[],q=new Map,F=0,A=-1,Y=new Map,de=new Set,z=new Map,se=new Map,ne=new Set,ie=new Map,oe=new Map,W=new Map,Ce=!1;function Re(){if(f=e.history.listen(N=>{let{action:P,location:L,delta:H}=N;if(Ce){Ce=!1;return}Xl(oe.size===0||H!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let ye=Ro({currentLocation:C.location,nextLocation:L,historyAction:P});if(ye&&H!=null){Ce=!0,e.history.go(H*-1),ms(ye,{state:"blocked",location:L,proceed(){ms(ye,{state:"proceeding",proceed:void 0,reset:void 0,location:L}),e.history.go(H)},reset(){let ke=new Map(C.blockers);ke.set(ye,Ku),me({blockers:ke})}});return}return Wt(P,L)}),n){uL(t,U);let N=()=>cL(t,U);t.addEventListener("pagehide",N),I=()=>t.removeEventListener("pagehide",N)}return C.initialized||Wt(en.Pop,C.location,{initialHydration:!0}),E}function Le(){f&&f(),I&&I(),h.clear(),O&&O.abort(),C.fetchers.forEach((N,P)=>gs(P)),C.blockers.forEach((N,P)=>_n(P))}function Oe(N){return h.add(N),()=>h.delete(N)}function me(N,P){P===void 0&&(P={}),C=At({},C,N);let L=[],H=[];p.v7_fetcherPersist&&C.fetchers.forEach((ye,ke)=>{ye.state==="idle"&&(ne.has(ke)?H.push(ke):L.push(ke))}),[...h].forEach(ye=>ye(C,{deletedFetchers:H,unstable_viewTransitionOpts:P.viewTransitionOpts,unstable_flushSync:P.flushSync===!0})),p.v7_fetcherPersist&&(L.forEach(ye=>C.fetchers.delete(ye)),H.forEach(ye=>gs(ye)))}function rt(N,P,L){var H,ye;let{flushSync:ke}=L===void 0?{}:L,$e=C.actionData!=null&&C.navigation.formMethod!=null&&Jr(C.navigation.formMethod)&&C.navigation.state==="loading"&&((H=N.state)==null?void 0:H._isRedirect)!==!0,fe;P.actionData?Object.keys(P.actionData).length>0?fe=P.actionData:fe=null:$e?fe=C.actionData:fe=null;let qe=P.loaderData?E0(C.loaderData,P.loaderData,P.matches||[],P.errors):C.loaderData,je=C.blockers;je.size>0&&(je=new Map(je),je.forEach((mt,bt)=>je.set(bt,Ku)));let Ne=T===!0||C.navigation.formMethod!=null&&Jr(C.navigation.formMethod)&&((ye=N.state)==null?void 0:ye._isRedirect)!==!0;i&&(a=i,i=void 0),J||k===en.Pop||(k===en.Push?e.history.push(N,N.state):k===en.Replace&&e.history.replace(N,N.state));let yt;if(k===en.Pop){let mt=U.get(C.location.pathname);mt&&mt.has(N.pathname)?yt={currentLocation:C.location,nextLocation:N}:U.has(N.pathname)&&(yt={currentLocation:N,nextLocation:C.location})}else if(M){let mt=U.get(C.location.pathname);mt?mt.add(N.pathname):(mt=new Set([N.pathname]),U.set(C.location.pathname,mt)),yt={currentLocation:C.location,nextLocation:N}}me(At({},P,{actionData:fe,loaderData:qe,historyAction:k,location:N,initialized:!0,navigation:Mm,revalidation:"idle",restoreScrollPosition:Kw(N,P.matches||C.matches),preventScrollReset:Ne,blockers:je}),{viewTransitionOpts:yt,flushSync:ke===!0}),k=en.Pop,T=!1,M=!1,J=!1,V=!1,G=[],ee=[]}async function It(N,P){if(typeof N=="number"){e.history.go(N);return}let L=Py(C.location,C.matches,c,p.v7_prependBasename,N,p.v7_relativeSplatPath,P==null?void 0:P.fromRouteId,P==null?void 0:P.relative),{path:H,submission:ye,error:ke}=v0(p.v7_normalizeFormMethod,!1,L,P),$e=C.location,fe=Xc(C.location,H,P&&P.state);fe=At({},fe,e.history.encodeLocation(fe));let qe=P&&P.replace!=null?P.replace:void 0,je=en.Push;qe===!0?je=en.Replace:qe===!1||ye!=null&&Jr(ye.formMethod)&&ye.formAction===C.location.pathname+C.location.search&&(je=en.Replace);let Ne=P&&"preventScrollReset"in P?P.preventScrollReset===!0:void 0,yt=(P&&P.unstable_flushSync)===!0,mt=Ro({currentLocation:$e,nextLocation:fe,historyAction:je});if(mt){ms(mt,{state:"blocked",location:fe,proceed(){ms(mt,{state:"proceeding",proceed:void 0,reset:void 0,location:fe}),It(N,P)},reset(){let bt=new Map(C.blockers);bt.set(mt,Ku),me({blockers:bt})}});return}return await Wt(je,fe,{submission:ye,pendingError:ke,preventScrollReset:Ne,replace:P&&P.replace,enableViewTransition:P&&P.unstable_viewTransition,flushSync:yt})}function Zt(){if(hn(),me({revalidation:"loading"}),C.navigation.state!=="submitting"){if(C.navigation.state==="idle"){Wt(C.historyAction,C.location,{startUninterruptedRevalidation:!0});return}Wt(k||C.historyAction,C.navigation.location,{overrideNavigation:C.navigation})}}async function Wt(N,P,L){O&&O.abort(),O=null,k=N,J=(L&&L.startUninterruptedRevalidation)===!0,UI(C.location,C.matches),T=(L&&L.preventScrollReset)===!0,M=(L&&L.enableViewTransition)===!0;let H=i||a,ye=L&&L.overrideNavigation,ke=Ua(H,P,c),$e=(L&&L.flushSync)===!0,fe=rm(ke,H,P.pathname);if(fe.active&&fe.matches&&(ke=fe.matches),!ke){let{error:pt,notFoundMatches:bn,route:Yt}=Iu(P.pathname);rt(P,{matches:bn,loaderData:{},errors:{[Yt.id]:pt}},{flushSync:$e});return}if(C.initialized&&!V&&nL(C.location,P)&&!(L&&L.submission&&Jr(L.submission.formMethod))){rt(P,{matches:ke},{flushSync:$e});return}O=new AbortController;let qe=Hi(e.history,P,O.signal,L&&L.submission),je;if(L&&L.pendingError)je=[gl(ke).route.id,{type:Ct.error,error:L.pendingError}];else if(L&&L.submission&&Jr(L.submission.formMethod)){let pt=await an(qe,P,L.submission,ke,fe.active,{replace:L.replace,flushSync:$e});if(pt.shortCircuited)return;if(pt.pendingActionResult){let[bn,Yt]=pt.pendingActionResult;if(fr(Yt)&&Zh(Yt.error)&&Yt.error.status===404){O=null,rt(P,{matches:pt.matches,loaderData:{},errors:{[bn]:Yt.error}});return}}ke=pt.matches||ke,je=pt.pendingActionResult,ye=Im(P,L.submission),$e=!1,fe.active=!1,qe=Hi(e.history,qe.url,qe.signal)}let{shortCircuited:Ne,matches:yt,loaderData:mt,errors:bt}=await j(qe,P,ke,fe.active,ye,L&&L.submission,L&&L.fetcherSubmission,L&&L.replace,L&&L.initialHydration===!0,$e,je);Ne||(O=null,rt(P,At({matches:yt||ke},T0(je),{loaderData:mt,errors:bt})))}async function an(N,P,L,H,ye,ke){ke===void 0&&(ke={}),hn();let $e=iL(P,L);if(me({navigation:$e},{flushSync:ke.flushSync===!0}),ye){let je=await sf(H,P.pathname,N.signal);if(je.type==="aborted")return{shortCircuited:!0};if(je.type==="error"){let{boundaryId:Ne,error:yt}=$i(P.pathname,je);return{matches:je.partialMatches,pendingActionResult:[Ne,{type:Ct.error,error:yt}]}}else if(je.matches)H=je.matches;else{let{notFoundMatches:Ne,error:yt,route:mt}=Iu(P.pathname);return{matches:Ne,pendingActionResult:[mt.id,{type:Ct.error,error:yt}]}}}let fe,qe=cc(H,P);if(!qe.route.action&&!qe.route.lazy)fe={type:Ct.error,error:Bn(405,{method:N.method,pathname:P.pathname,routeId:qe.route.id})};else if(fe=(await et("action",N,[qe],H))[0],N.signal.aborted)return{shortCircuited:!0};if(Wa(fe)){let je;return ke&&ke.replace!=null?je=ke.replace:je=w0(fe.response.headers.get("Location"),new URL(N.url),c)===C.location.pathname+C.location.search,await Ee(N,fe,{submission:L,replace:je}),{shortCircuited:!0}}if(qa(fe))throw Bn(400,{type:"defer-action"});if(fr(fe)){let je=gl(H,qe.route.id);return(ke&&ke.replace)!==!0&&(k=en.Push),{matches:H,pendingActionResult:[je.route.id,fe]}}return{matches:H,pendingActionResult:[qe.route.id,fe]}}async function j(N,P,L,H,ye,ke,$e,fe,qe,je,Ne){let yt=ye||Im(P,ke),mt=ke||$e||R0(yt),bt=!J&&(!p.v7_partialHydration||!qe);if(H){if(bt){let Vt=D(Ne);me(At({navigation:yt},Vt!==void 0?{actionData:Vt}:{}),{flushSync:je})}let Ge=await sf(L,P.pathname,N.signal);if(Ge.type==="aborted")return{shortCircuited:!0};if(Ge.type==="error"){let{boundaryId:Vt,error:ar}=$i(P.pathname,Ge);return{matches:Ge.partialMatches,loaderData:{},errors:{[Vt]:ar}}}else if(Ge.matches)L=Ge.matches;else{let{error:Vt,notFoundMatches:ar,route:Nt}=Iu(P.pathname);return{matches:ar,loaderData:{},errors:{[Nt.id]:Vt}}}}let pt=i||a,[bn,Yt]=y0(e.history,C,L,mt,P,p.v7_partialHydration&&qe===!0,p.v7_skipActionErrorRevalidation,V,G,ee,ne,z,de,pt,c,Ne);if(vs(Ge=>!(L&&L.some(Vt=>Vt.route.id===Ge))||bn&&bn.some(Vt=>Vt.route.id===Ge)),A=++F,bn.length===0&&Yt.length===0){let Ge=Ue();return rt(P,At({matches:L,loaderData:{},errors:Ne&&fr(Ne[1])?{[Ne[0]]:Ne[1].error}:null},T0(Ne),Ge?{fetchers:new Map(C.fetchers)}:{}),{flushSync:je}),{shortCircuited:!0}}if(bt){let Ge={};if(!H){Ge.navigation=yt;let Vt=D(Ne);Vt!==void 0&&(Ge.actionData=Vt)}Yt.length>0&&(Ge.fetchers=B(Yt)),me(Ge,{flushSync:je})}Yt.forEach(Ge=>{q.has(Ge.key)&&Fn(Ge.key),Ge.controller&&q.set(Ge.key,Ge.controller)});let Au=()=>Yt.forEach(Ge=>Fn(Ge.key));O&&O.signal.addEventListener("abort",Au);let{loaderResults:Oo,fetcherResults:Bi}=await kt(C.matches,L,bn,Yt,N);if(N.signal.aborted)return{shortCircuited:!0};O&&O.signal.removeEventListener("abort",Au),Yt.forEach(Ge=>q.delete(Ge.key));let zi=_0([...Oo,...Bi]);if(zi){if(zi.idx>=bn.length){let Ge=Yt[zi.idx-bn.length].key;de.add(Ge)}return await Ee(N,zi.result,{replace:fe}),{shortCircuited:!0}}let{loaderData:Ui,errors:ys}=C0(C,L,bn,Oo,Ne,Yt,Bi,ie);ie.forEach((Ge,Vt)=>{Ge.subscribe(ar=>{(ar||Ge.done)&&ie.delete(Vt)})}),p.v7_partialHydration&&qe&&C.errors&&Object.entries(C.errors).filter(Ge=>{let[Vt]=Ge;return!bn.some(ar=>ar.route.id===Vt)}).forEach(Ge=>{let[Vt,ar]=Ge;ys=Object.assign(ys||{},{[Vt]:ar})});let of=Ue(),af=St(A),lf=of||af||Yt.length>0;return At({matches:L,loaderData:Ui,errors:ys},lf?{fetchers:new Map(C.fetchers)}:{})}function D(N){if(N&&!fr(N[1]))return{[N[0]]:N[1].data};if(C.actionData)return Object.keys(C.actionData).length===0?null:C.actionData}function B(N){return N.forEach(P=>{let L=C.fetchers.get(P.key),H=qu(void 0,L?L.data:void 0);C.fetchers.set(P.key,H)}),new Map(C.fetchers)}function pe(N,P,L,H){if(r)throw new Error("router.fetch() was called during the server render, but it shouldn't be. You are likely calling a useFetcher() method in the body of your component. Try moving it to a useEffect or a callback.");q.has(N)&&Fn(N);let ye=(H&&H.unstable_flushSync)===!0,ke=i||a,$e=Py(C.location,C.matches,c,p.v7_prependBasename,L,p.v7_relativeSplatPath,P,H==null?void 0:H.relative),fe=Ua(ke,$e,c),qe=rm(fe,ke,$e);if(qe.active&&qe.matches&&(fe=qe.matches),!fe){gn(N,P,Bn(404,{pathname:$e}),{flushSync:ye});return}let{path:je,submission:Ne,error:yt}=v0(p.v7_normalizeFormMethod,!0,$e,H);if(yt){gn(N,P,yt,{flushSync:ye});return}let mt=cc(fe,je);if(T=(H&&H.preventScrollReset)===!0,Ne&&Jr(Ne.formMethod)){le(N,P,je,mt,fe,qe.active,ye,Ne);return}z.set(N,{routeId:P,path:je}),ae(N,P,je,mt,fe,qe.active,ye,Ne)}async function le(N,P,L,H,ye,ke,$e,fe){hn(),z.delete(N);function qe(Nt){if(!Nt.route.action&&!Nt.route.lazy){let Ks=Bn(405,{method:fe.formMethod,pathname:L,routeId:P});return gn(N,P,Ks,{flushSync:$e}),!0}return!1}if(!ke&&qe(H))return;let je=C.fetchers.get(N);yn(N,lL(fe,je),{flushSync:$e});let Ne=new AbortController,yt=Hi(e.history,L,Ne.signal,fe);if(ke){let Nt=await sf(ye,L,yt.signal);if(Nt.type==="aborted")return;if(Nt.type==="error"){let{error:Ks}=$i(L,Nt);gn(N,P,Ks,{flushSync:$e});return}else if(Nt.matches){if(ye=Nt.matches,H=cc(ye,L),qe(H))return}else{gn(N,P,Bn(404,{pathname:L}),{flushSync:$e});return}}q.set(N,Ne);let mt=F,pt=(await et("action",yt,[H],ye))[0];if(yt.signal.aborted){q.get(N)===Ne&&q.delete(N);return}if(p.v7_fetcherPersist&&ne.has(N)){if(Wa(pt)||fr(pt)){yn(N,Fo(void 0));return}}else{if(Wa(pt))if(q.delete(N),A>mt){yn(N,Fo(void 0));return}else return de.add(N),yn(N,qu(fe)),Ee(yt,pt,{fetcherSubmission:fe});if(fr(pt)){gn(N,P,pt.error);return}}if(qa(pt))throw Bn(400,{type:"defer-action"});let bn=C.navigation.location||C.location,Yt=Hi(e.history,bn,Ne.signal),Au=i||a,Oo=C.navigation.state!=="idle"?Ua(Au,C.navigation.location,c):C.matches;Ze(Oo,"Didn't find any matches after fetcher action");let Bi=++F;Y.set(N,Bi);let zi=qu(fe,pt.data);C.fetchers.set(N,zi);let[Ui,ys]=y0(e.history,C,Oo,fe,bn,!1,p.v7_skipActionErrorRevalidation,V,G,ee,ne,z,de,Au,c,[H.route.id,pt]);ys.filter(Nt=>Nt.key!==N).forEach(Nt=>{let Ks=Nt.key,qw=C.fetchers.get(Ks),KI=qu(void 0,qw?qw.data:void 0);C.fetchers.set(Ks,KI),q.has(Ks)&&Fn(Ks),Nt.controller&&q.set(Ks,Nt.controller)}),me({fetchers:new Map(C.fetchers)});let of=()=>ys.forEach(Nt=>Fn(Nt.key));Ne.signal.addEventListener("abort",of);let{loaderResults:af,fetcherResults:lf}=await kt(C.matches,Oo,Ui,ys,Yt);if(Ne.signal.aborted)return;Ne.signal.removeEventListener("abort",of),Y.delete(N),q.delete(N),ys.forEach(Nt=>q.delete(Nt.key));let Ge=_0([...af,...lf]);if(Ge){if(Ge.idx>=Ui.length){let Nt=ys[Ge.idx-Ui.length].key;de.add(Nt)}return Ee(Yt,Ge.result)}let{loaderData:Vt,errors:ar}=C0(C,C.matches,Ui,af,void 0,ys,lf,ie);if(C.fetchers.has(N)){let Nt=Fo(pt.data);C.fetchers.set(N,Nt)}St(Bi),C.navigation.state==="loading"&&Bi>A?(Ze(k,"Expected pending action"),O&&O.abort(),rt(C.navigation.location,{matches:Oo,loaderData:Vt,errors:ar,fetchers:new Map(C.fetchers)})):(me({errors:ar,loaderData:E0(C.loaderData,Vt,Oo,ar),fetchers:new Map(C.fetchers)}),V=!1)}async function ae(N,P,L,H,ye,ke,$e,fe){let qe=C.fetchers.get(N);yn(N,qu(fe,qe?qe.data:void 0),{flushSync:$e});let je=new AbortController,Ne=Hi(e.history,L,je.signal);if(ke){let pt=await sf(ye,L,Ne.signal);if(pt.type==="aborted")return;if(pt.type==="error"){let{error:bn}=$i(L,pt);gn(N,P,bn,{flushSync:$e});return}else if(pt.matches)ye=pt.matches,H=cc(ye,L);else{gn(N,P,Bn(404,{pathname:L}),{flushSync:$e});return}}q.set(N,je);let yt=F,bt=(await et("loader",Ne,[H],ye))[0];if(qa(bt)&&(bt=await g_(bt,Ne.signal,!0)||bt),q.get(N)===je&&q.delete(N),!Ne.signal.aborted){if(ne.has(N)){yn(N,Fo(void 0));return}if(Wa(bt))if(A>yt){yn(N,Fo(void 0));return}else{de.add(N),await Ee(Ne,bt);return}if(fr(bt)){gn(N,P,bt.error);return}Ze(!qa(bt),"Unhandled fetcher deferred data"),yn(N,Fo(bt.data))}}async function Ee(N,P,L){let{submission:H,fetcherSubmission:ye,replace:ke}=L===void 0?{}:L;P.response.headers.has("X-Remix-Revalidate")&&(V=!0);let $e=P.response.headers.get("Location");Ze($e,"Expected a Location header on the redirect Response"),$e=w0($e,new URL(N.url),c);let fe=Xc(C.location,$e,{_isRedirect:!0});if(n){let bt=!1;if(P.response.headers.has("X-Remix-Reload-Document"))bt=!0;else if(jx.test($e)){const pt=e.history.createURL($e);bt=pt.origin!==t.location.origin||du(pt.pathname,c)==null}if(bt){ke?t.location.replace($e):t.location.assign($e);return}}O=null;let qe=ke===!0?en.Replace:en.Push,{formMethod:je,formAction:Ne,formEncType:yt}=C.navigation;!H&&!ye&&je&&Ne&&yt&&(H=R0(C.navigation));let mt=H||ye;if(U2.has(P.response.status)&&mt&&Jr(mt.formMethod))await Wt(qe,fe,{submission:At({},mt,{formAction:$e}),preventScrollReset:T});else{let bt=Im(fe,H);await Wt(qe,fe,{overrideNavigation:bt,fetcherSubmission:ye,preventScrollReset:T})}}async function et(N,P,L,H){try{let ye=await Z2(l,N,P,L,H,o,s);return await Promise.all(ye.map((ke,$e)=>{if(sL(ke)){let fe=ke.result;return{type:Ct.redirect,response:eL(fe,P,L[$e].route.id,H,c,p.v7_relativeSplatPath)}}return X2(ke)}))}catch(ye){return L.map(()=>({type:Ct.error,error:ye}))}}async function kt(N,P,L,H,ye){let[ke,...$e]=await Promise.all([L.length?et("loader",ye,L,P):[],...H.map(fe=>{if(fe.matches&&fe.match&&fe.controller){let qe=Hi(e.history,fe.path,fe.controller.signal);return et("loader",qe,[fe.match],fe.matches).then(je=>je[0])}else return Promise.resolve({type:Ct.error,error:Bn(404,{pathname:fe.path})})})]);return await Promise.all([j0(N,L,ke,ke.map(()=>ye.signal),!1,C.loaderData),j0(N,H.map(fe=>fe.match),$e,H.map(fe=>fe.controller?fe.controller.signal:null),!0)]),{loaderResults:ke,fetcherResults:$e}}function hn(){V=!0,G.push(...vs()),z.forEach((N,P)=>{q.has(P)&&(ee.push(P),Fn(P))})}function yn(N,P,L){L===void 0&&(L={}),C.fetchers.set(N,P),me({fetchers:new Map(C.fetchers)},{flushSync:(L&&L.flushSync)===!0})}function gn(N,P,L,H){H===void 0&&(H={});let ye=gl(C.matches,P);gs(N),me({errors:{[ye.route.id]:L},fetchers:new Map(C.fetchers)},{flushSync:(H&&H.flushSync)===!0})}function jo(N){return p.v7_fetcherPersist&&(se.set(N,(se.get(N)||0)+1),ne.has(N)&&ne.delete(N)),C.fetchers.get(N)||V2}function gs(N){let P=C.fetchers.get(N);q.has(N)&&!(P&&P.state==="loading"&&Y.has(N))&&Fn(N),z.delete(N),Y.delete(N),de.delete(N),ne.delete(N),C.fetchers.delete(N)}function Aa(N){if(p.v7_fetcherPersist){let P=(se.get(N)||0)-1;P<=0?(se.delete(N),ne.add(N)):se.set(N,P)}else gs(N);me({fetchers:new Map(C.fetchers)})}function Fn(N){let P=q.get(N);Ze(P,"Expected fetch controller: "+N),P.abort(),q.delete(N)}function ue(N){for(let P of N){let L=jo(P),H=Fo(L.data);C.fetchers.set(P,H)}}function Ue(){let N=[],P=!1;for(let L of de){let H=C.fetchers.get(L);Ze(H,"Expected fetcher: "+L),H.state==="loading"&&(de.delete(L),N.push(L),P=!0)}return ue(N),P}function St(N){let P=[];for(let[L,H]of Y)if(H0}function dt(N,P){let L=C.blockers.get(N)||Ku;return oe.get(N)!==P&&oe.set(N,P),L}function _n(N){C.blockers.delete(N),oe.delete(N)}function ms(N,P){let L=C.blockers.get(N)||Ku;Ze(L.state==="unblocked"&&P.state==="blocked"||L.state==="blocked"&&P.state==="blocked"||L.state==="blocked"&&P.state==="proceeding"||L.state==="blocked"&&P.state==="unblocked"||L.state==="proceeding"&&P.state==="unblocked","Invalid blocker state transition: "+L.state+" -> "+P.state);let H=new Map(C.blockers);H.set(N,P),me({blockers:H})}function Ro(N){let{currentLocation:P,nextLocation:L,historyAction:H}=N;if(oe.size===0)return;oe.size>1&&Xl(!1,"A router only supports one blocker at a time");let ye=Array.from(oe.entries()),[ke,$e]=ye[ye.length-1],fe=C.blockers.get(ke);if(!(fe&&fe.state==="proceeding")&&$e({currentLocation:P,nextLocation:L,historyAction:H}))return ke}function Iu(N){let P=Bn(404,{pathname:N}),L=i||a,{matches:H,route:ye}=k0(L);return vs(),{notFoundMatches:H,route:ye,error:P}}function $i(N,P){return{boundaryId:gl(P.partialMatches).route.id,error:Bn(400,{type:"route-discovery",pathname:N,message:P.error!=null&&"message"in P.error?P.error:String(P.error)})}}function vs(N){let P=[];return ie.forEach((L,H)=>{(!N||N(H))&&(L.cancel(),P.push(H),ie.delete(H))}),P}function Du(N,P,L){if(g=N,x=P,m=L||null,!b&&C.navigation===Mm){b=!0;let H=Kw(C.location,C.matches);H!=null&&me({restoreScrollPosition:H})}return()=>{g=null,x=null,m=null}}function Hw(N,P){return m&&m(N,P.map(H=>x2(H,C.loaderData)))||N.key}function UI(N,P){if(g&&x){let L=Hw(N,P);g[L]=x()}}function Kw(N,P){if(g){let L=Hw(N,P),H=g[L];if(typeof H=="number")return H}return null}function rm(N,P,L){if(d)if(N){let H=N[N.length-1].route;if(H.path&&(H.path==="*"||H.path.endsWith("/*")))return{active:!0,matches:cp(P,L,c,!0)}}else return{active:!0,matches:cp(P,L,c,!0)||[]};return{active:!1,matches:null}}async function sf(N,P,L){let H=N,ye=H.length>0?H[H.length-1].route:null;for(;;){let ke=i==null,$e=i||a;try{await J2(d,P,H,$e,o,s,W,L)}catch(Ne){return{type:"error",error:Ne,partialMatches:H}}finally{ke&&(a=[...a])}if(L.aborted)return{type:"aborted"};let fe=Ua($e,P,c),qe=!1;if(fe){let Ne=fe[fe.length-1].route;if(Ne.index)return{type:"success",matches:fe};if(Ne.path&&Ne.path.length>0)if(Ne.path==="*")qe=!0;else return{type:"success",matches:fe}}let je=cp($e,P,c,!0);if(!je||H.map(Ne=>Ne.route.id).join("-")===je.map(Ne=>Ne.route.id).join("-"))return{type:"success",matches:qe?fe:null};if(H=je,ye=H[H.length-1].route,ye.path==="*")return{type:"success",matches:H}}}function VI(N){o={},i=ed(N,s,void 0,o)}function HI(N,P){let L=i==null;f_(N,P,i||a,o,s),L&&(a=[...a],me({}))}return E={get basename(){return c},get future(){return p},get state(){return C},get routes(){return a},get window(){return t},initialize:Re,subscribe:Oe,enableScrollRestoration:Du,navigate:It,fetch:pe,revalidate:Zt,createHref:N=>e.history.createHref(N),encodeLocation:N=>e.history.encodeLocation(N),getFetcher:jo,deleteFetcher:Aa,dispose:Le,getBlocker:dt,deleteBlocker:_n,patchRoutes:HI,_internalFetchControllers:q,_internalActiveDeferreds:ie,_internalSetRoutes:VI},E}function q2(e){return e!=null&&("formData"in e&&e.formData!=null||"body"in e&&e.body!==void 0)}function Py(e,t,n,r,s,o,a,i){let c,l;if(a){c=[];for(let p of t)if(c.push(p),p.route.id===a){l=p;break}}else c=t,l=t[t.length-1];let d=Qh(s||".",Jh(c,o),du(e.pathname,n)||e.pathname,i==="path");return s==null&&(d.search=e.search,d.hash=e.hash),(s==null||s===""||s===".")&&l&&l.route.index&&!Rx(d.search)&&(d.search=d.search?d.search.replace(/^\?/,"?index&"):"?index"),r&&n!=="/"&&(d.pathname=d.pathname==="/"?n:uo([n,d.pathname])),wi(d)}function v0(e,t,n,r){if(!r||!q2(r))return{path:n};if(r.formMethod&&!aL(r.formMethod))return{path:n,error:Bn(405,{method:r.formMethod})};let s=()=>({path:n,error:Bn(400,{type:"invalid-body"})}),o=r.formMethod||"get",a=e?o.toUpperCase():o.toLowerCase(),i=p_(n);if(r.body!==void 0){if(r.formEncType==="text/plain"){if(!Jr(a))return s();let f=typeof r.body=="string"?r.body:r.body instanceof FormData||r.body instanceof URLSearchParams?Array.from(r.body.entries()).reduce((h,g)=>{let[m,x]=g;return""+h+m+"="+x+` +`},""):String(r.body);return{path:n,submission:{formMethod:a,formAction:i,formEncType:r.formEncType,formData:void 0,json:void 0,text:f}}}else if(r.formEncType==="application/json"){if(!Jr(a))return s();try{let f=typeof r.body=="string"?JSON.parse(r.body):r.body;return{path:n,submission:{formMethod:a,formAction:i,formEncType:r.formEncType,formData:void 0,json:f,text:void 0}}}catch{return s()}}}Ze(typeof FormData=="function","FormData is not available in this environment");let c,l;if(r.formData)c=My(r.formData),l=r.formData;else if(r.body instanceof FormData)c=My(r.body),l=r.body;else if(r.body instanceof URLSearchParams)c=r.body,l=S0(c);else if(r.body==null)c=new URLSearchParams,l=new FormData;else try{c=new URLSearchParams(r.body),l=S0(c)}catch{return s()}let d={formMethod:a,formAction:i,formEncType:r&&r.formEncType||"application/x-www-form-urlencoded",formData:l,json:void 0,text:void 0};if(Jr(d.formMethod))return{path:n,submission:d};let p=_a(n);return t&&p.search&&Rx(p.search)&&c.append("index",""),p.search="?"+c,{path:wi(p),submission:d}}function W2(e,t){let n=e;if(t){let r=e.findIndex(s=>s.route.id===t);r>=0&&(n=e.slice(0,r))}return n}function y0(e,t,n,r,s,o,a,i,c,l,d,p,f,h,g,m){let x=m?fr(m[1])?m[1].error:m[1].data:void 0,b=e.createURL(t.location),y=e.createURL(s),w=m&&fr(m[1])?m[0]:void 0,S=w?W2(n,w):n,E=m?m[1].statusCode:void 0,C=a&&E&&E>=400,k=S.filter((O,M)=>{let{route:U}=O;if(U.lazy)return!0;if(U.loader==null)return!1;if(o)return typeof U.loader!="function"||U.loader.hydrate?!0:t.loaderData[U.id]===void 0&&(!t.errors||t.errors[U.id]===void 0);if(G2(t.loaderData,t.matches[M],O)||c.some(V=>V===O.route.id))return!0;let I=t.matches[M],J=O;return b0(O,At({currentUrl:b,currentParams:I.params,nextUrl:y,nextParams:J.params},r,{actionResult:x,actionStatus:E,defaultShouldRevalidate:C?!1:i||b.pathname+b.search===y.pathname+y.search||b.search!==y.search||d_(I,J)}))}),T=[];return p.forEach((O,M)=>{if(o||!n.some(G=>G.route.id===O.routeId)||d.has(M))return;let U=Ua(h,O.path,g);if(!U){T.push({key:M,routeId:O.routeId,path:O.path,matches:null,match:null,controller:null});return}let I=t.fetchers.get(M),J=cc(U,O.path),V=!1;f.has(M)?V=!1:l.includes(M)?V=!0:I&&I.state!=="idle"&&I.data===void 0?V=i:V=b0(J,At({currentUrl:b,currentParams:t.matches[t.matches.length-1].params,nextUrl:y,nextParams:n[n.length-1].params},r,{actionResult:x,actionStatus:E,defaultShouldRevalidate:C?!1:i})),V&&T.push({key:M,routeId:O.routeId,path:O.path,matches:U,match:J,controller:new AbortController})}),[k,T]}function G2(e,t,n){let r=!t||n.route.id!==t.route.id,s=e[n.route.id]===void 0;return r||s}function d_(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith("*")&&e.params["*"]!==t.params["*"]}function b0(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n=="boolean")return n}return t.defaultShouldRevalidate}async function J2(e,t,n,r,s,o,a,i){let c=[t,...n.map(l=>l.route.id)].join("-");try{let l=a.get(c);l||(l=e({path:t,matches:n,patch:(d,p)=>{i.aborted||f_(d,p,r,s,o)}}),a.set(c,l)),l&&rL(l)&&await l}finally{a.delete(c)}}function f_(e,t,n,r,s){if(e){var o;let a=r[e];Ze(a,"No route found to patch children into: routeId = "+e);let i=ed(t,s,[e,"patch",String(((o=a.children)==null?void 0:o.length)||"0")],r);a.children?a.children.push(...i):a.children=i}else{let a=ed(t,s,["patch",String(n.length||"0")],r);n.push(...a)}}async function x0(e,t,n){if(!e.lazy)return;let r=await e.lazy();if(!e.lazy)return;let s=n[e.id];Ze(s,"No route found in manifest");let o={};for(let a in r){let c=s[a]!==void 0&&a!=="hasErrorBoundary";Xl(!c,'Route "'+s.id+'" has a static property "'+a+'" defined but its lazy function is also returning a value for this property. '+('The lazy route property "'+a+'" will be ignored.')),!c&&!y2.has(a)&&(o[a]=r[a])}Object.assign(s,o),Object.assign(s,At({},t(s),{lazy:void 0}))}function Q2(e){return Promise.all(e.matches.map(t=>t.resolve()))}async function Z2(e,t,n,r,s,o,a,i){let c=r.reduce((p,f)=>p.add(f.route.id),new Set),l=new Set,d=await e({matches:s.map(p=>{let f=c.has(p.route.id);return At({},p,{shouldLoad:f,resolve:g=>(l.add(p.route.id),f?Y2(t,n,p,o,a,g,i):Promise.resolve({type:Ct.data,result:void 0}))})}),request:n,params:s[0].params,context:i});return s.forEach(p=>Ze(l.has(p.route.id),'`match.resolve()` was not called for route id "'+p.route.id+'". You must call `match.resolve()` on every match passed to `dataStrategy` to ensure all routes are properly loaded.')),d.filter((p,f)=>c.has(s[f].route.id))}async function Y2(e,t,n,r,s,o,a){let i,c,l=d=>{let p,f=new Promise((m,x)=>p=x);c=()=>p(),t.signal.addEventListener("abort",c);let h=m=>typeof d!="function"?Promise.reject(new Error("You cannot call the handler for a route which defines a boolean "+('"'+e+'" [routeId: '+n.route.id+"]"))):d({request:t,params:n.params,context:a},...m!==void 0?[m]:[]),g;return o?g=o(m=>h(m)):g=(async()=>{try{return{type:"data",result:await h()}}catch(m){return{type:"error",result:m}}})(),Promise.race([g,f])};try{let d=n.route[e];if(n.route.lazy)if(d){let p,[f]=await Promise.all([l(d).catch(h=>{p=h}),x0(n.route,s,r)]);if(p!==void 0)throw p;i=f}else if(await x0(n.route,s,r),d=n.route[e],d)i=await l(d);else if(e==="action"){let p=new URL(t.url),f=p.pathname+p.search;throw Bn(405,{method:t.method,pathname:f,routeId:n.route.id})}else return{type:Ct.data,result:void 0};else if(d)i=await l(d);else{let p=new URL(t.url),f=p.pathname+p.search;throw Bn(404,{pathname:f})}Ze(i.result!==void 0,"You defined "+(e==="action"?"an action":"a loader")+" for route "+('"'+n.route.id+"\" but didn't return anything from your `"+e+"` ")+"function. Please return a value or `null`.")}catch(d){return{type:Ct.error,result:d}}finally{c&&t.signal.removeEventListener("abort",c)}return i}async function X2(e){let{result:t,type:n,status:r}=e;if(h_(t)){let a;try{let i=t.headers.get("Content-Type");i&&/\bapplication\/json\b/.test(i)?t.body==null?a=null:a=await t.json():a=await t.text()}catch(i){return{type:Ct.error,error:i}}return n===Ct.error?{type:Ct.error,error:new _x(t.status,t.statusText,a),statusCode:t.status,headers:t.headers}:{type:Ct.data,data:a,statusCode:t.status,headers:t.headers}}if(n===Ct.error)return{type:Ct.error,error:t,statusCode:Zh(t)?t.status:r};if(oL(t)){var s,o;return{type:Ct.deferred,deferredData:t,statusCode:(s=t.init)==null?void 0:s.status,headers:((o=t.init)==null?void 0:o.headers)&&new Headers(t.init.headers)}}return{type:Ct.data,data:t,statusCode:r}}function eL(e,t,n,r,s,o){let a=e.headers.get("Location");if(Ze(a,"Redirects returned/thrown from loaders/actions must have a Location header"),!jx.test(a)){let i=r.slice(0,r.findIndex(c=>c.route.id===n)+1);a=Py(new URL(t.url),i,s,!0,a,o),e.headers.set("Location",a)}return e}function w0(e,t,n){if(jx.test(e)){let r=e,s=r.startsWith("//")?new URL(t.protocol+r):new URL(r),o=du(s.pathname,n)!=null;if(s.origin===t.origin&&o)return s.pathname+s.search+s.hash}return e}function Hi(e,t,n,r){let s=e.createURL(p_(t)).toString(),o={signal:n};if(r&&Jr(r.formMethod)){let{formMethod:a,formEncType:i}=r;o.method=a.toUpperCase(),i==="application/json"?(o.headers=new Headers({"Content-Type":i}),o.body=JSON.stringify(r.json)):i==="text/plain"?o.body=r.text:i==="application/x-www-form-urlencoded"&&r.formData?o.body=My(r.formData):o.body=r.formData}return new Request(s,o)}function My(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r=="string"?r:r.name);return t}function S0(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function tL(e,t,n,r,s,o){let a={},i=null,c,l=!1,d={},p=r&&fr(r[1])?r[1].error:void 0;return n.forEach((f,h)=>{let g=t[h].route.id;if(Ze(!Wa(f),"Cannot handle redirect results in processLoaderData"),fr(f)){let m=f.error;p!==void 0&&(m=p,p=void 0),i=i||{};{let x=gl(e,g);i[x.route.id]==null&&(i[x.route.id]=m)}a[g]=void 0,l||(l=!0,c=Zh(f.error)?f.error.status:500),f.headers&&(d[g]=f.headers)}else qa(f)?(s.set(g,f.deferredData),a[g]=f.deferredData.data,f.statusCode!=null&&f.statusCode!==200&&!l&&(c=f.statusCode),f.headers&&(d[g]=f.headers)):(a[g]=f.data,f.statusCode&&f.statusCode!==200&&!l&&(c=f.statusCode),f.headers&&(d[g]=f.headers))}),p!==void 0&&r&&(i={[r[0]]:p},a[r[0]]=void 0),{loaderData:a,errors:i,statusCode:c||200,loaderHeaders:d}}function C0(e,t,n,r,s,o,a,i){let{loaderData:c,errors:l}=tL(t,n,r,s,i);for(let d=0;dr.route.id===t)+1):[...e]).reverse().find(r=>r.route.hasErrorBoundary===!0)||e[0]}function k0(e){let t=e.length===1?e[0]:e.find(n=>n.index||!n.path||n.path==="/")||{id:"__shim-error-route__"};return{matches:[{params:{},pathname:"",pathnameBase:"",route:t}],route:t}}function Bn(e,t){let{pathname:n,routeId:r,method:s,type:o,message:a}=t===void 0?{}:t,i="Unknown Server Error",c="Unknown @remix-run/router error";return e===400?(i="Bad Request",o==="route-discovery"?c='Unable to match URL "'+n+'" - the `unstable_patchRoutesOnMiss()` '+(`function threw the following error: +`+a):s&&n&&r?c="You made a "+s+' request to "'+n+'" but '+('did not provide a `loader` for route "'+r+'", ')+"so there is no way to handle the request.":o==="defer-action"?c="defer() is not supported in actions":o==="invalid-body"&&(c="Unable to encode submission body")):e===403?(i="Forbidden",c='Route "'+r+'" does not match URL "'+n+'"'):e===404?(i="Not Found",c='No route matches URL "'+n+'"'):e===405&&(i="Method Not Allowed",s&&n&&r?c="You made a "+s.toUpperCase()+' request to "'+n+'" but '+('did not provide an `action` for route "'+r+'", ')+"so there is no way to handle the request.":s&&(c='Invalid request method "'+s.toUpperCase()+'"')),new _x(e||500,i,new Error(c),!0)}function _0(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(Wa(n))return{result:n,idx:t}}}function p_(e){let t=typeof e=="string"?_a(e):e;return wi(At({},t,{hash:""}))}function nL(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===""?t.hash!=="":e.hash===t.hash?!0:t.hash!==""}function rL(e){return typeof e=="object"&&e!=null&&"then"in e}function sL(e){return h_(e.result)&&z2.has(e.result.status)}function qa(e){return e.type===Ct.deferred}function fr(e){return e.type===Ct.error}function Wa(e){return(e&&e.type)===Ct.redirect}function oL(e){let t=e;return t&&typeof t=="object"&&typeof t.data=="object"&&typeof t.subscribe=="function"&&typeof t.cancel=="function"&&typeof t.resolveData=="function"}function h_(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.headers=="object"&&typeof e.body<"u"}function aL(e){return B2.has(e.toLowerCase())}function Jr(e){return L2.has(e.toLowerCase())}async function j0(e,t,n,r,s,o){for(let a=0;ap.route.id===c.route.id),d=l!=null&&!d_(l,c)&&(o&&o[c.route.id])!==void 0;if(qa(i)&&(s||d)){let p=r[a];Ze(p,"Expected an AbortSignal for revalidating fetcher deferred result"),await g_(i,p,s).then(f=>{f&&(n[a]=f||n[a])})}}}async function g_(e,t,n){if(n===void 0&&(n=!1),!await e.deferredData.resolveData(t)){if(n)try{return{type:Ct.data,data:e.deferredData.unwrappedData}}catch(s){return{type:Ct.error,error:s}}return{type:Ct.data,data:e.deferredData.data}}}function Rx(e){return new URLSearchParams(e).getAll("index").some(t=>t==="")}function cc(e,t){let n=typeof t=="string"?_a(t).search:t.search;if(e[e.length-1].route.index&&Rx(n||""))return e[e.length-1];let r=l_(e);return r[r.length-1]}function R0(e){let{formMethod:t,formAction:n,formEncType:r,text:s,formData:o,json:a}=e;if(!(!t||!n||!r)){if(s!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:s};if(o!=null)return{formMethod:t,formAction:n,formEncType:r,formData:o,json:void 0,text:void 0};if(a!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:a,text:void 0}}}function Im(e,t){return t?{state:"loading",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}:{state:"loading",location:e,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function iL(e,t){return{state:"submitting",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}function qu(e,t){return e?{state:"loading",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:"loading",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function lL(e,t){return{state:"submitting",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function Fo(e){return{state:"idle",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function uL(e,t){try{let n=e.sessionStorage.getItem(c_);if(n){let r=JSON.parse(n);for(let[s,o]of Object.entries(r||{}))o&&Array.isArray(o)&&t.set(s,new Set(o||[]))}}catch{}}function cL(e,t){if(t.size>0){let n={};for(let[r,s]of t)n[r]=[...s];try{e.sessionStorage.setItem(c_,JSON.stringify(n))}catch(r){Xl(!1,"Failed to save applied view transitions in sessionStorage ("+r+").")}}}/** + * React Router v6.25.1 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function Zp(){return Zp=Object.assign?Object.assign.bind():function(e){for(var t=1;t{i.current=!0}),v.useCallback(function(l,d){if(d===void 0&&(d={}),!i.current)return;if(typeof l=="number"){r.go(l);return}let p=Qh(l,JSON.parse(a),o,d.relative==="path");e==null&&t!=="/"&&(p.pathname=p.pathname==="/"?t:uo([t,p.pathname])),(d.replace?r.replace:r.push)(p,d.state,d)},[t,r,a,o,e])}function So(){let{matches:e}=v.useContext(wo),t=e[e.length-1];return t?t.params:{}}function b_(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=v.useContext(ja),{matches:s}=v.useContext(wo),{pathname:o}=pu(),a=JSON.stringify(Jh(s,r.v7_relativeSplatPath));return v.useMemo(()=>Qh(e,JSON.parse(a),o,n==="path"),[e,a,o,n])}function pL(e,t,n,r){fu()||Ze(!1);let{navigator:s}=v.useContext(ja),{matches:o}=v.useContext(wo),a=o[o.length-1],i=a?a.params:{};a&&a.pathname;let c=a?a.pathnameBase:"/";a&&a.route;let l=pu(),d;d=l;let p=d.pathname||"/",f=p;if(c!=="/"){let m=c.replace(/^\//,"").split("/");f="/"+p.replace(/^\//,"").split("/").slice(m.length).join("/")}let h=Ua(e,{pathname:f});return yL(h&&h.map(m=>Object.assign({},m,{params:Object.assign({},i,m.params),pathname:uo([c,s.encodeLocation?s.encodeLocation(m.pathname).pathname:m.pathname]),pathnameBase:m.pathnameBase==="/"?c:uo([c,s.encodeLocation?s.encodeLocation(m.pathnameBase).pathname:m.pathnameBase])})),o,n,r)}function hL(){let e=SL(),t=Zh(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,s={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return v.createElement(v.Fragment,null,v.createElement("h2",null,"Unexpected Application Error!"),v.createElement("h3",{style:{fontStyle:"italic"}},t),n?v.createElement("pre",{style:s},n):null,null)}const gL=v.createElement(hL,null);class mL extends v.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?v.createElement(wo.Provider,{value:this.props.routeContext},v.createElement(v_.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function vL(e){let{routeContext:t,match:n,children:r}=e,s=v.useContext(Yh);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),v.createElement(wo.Provider,{value:t},r)}function yL(e,t,n,r){var s;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var o;if((o=n)!=null&&o.errors)e=n.matches;else return null}let a=e,i=(s=n)==null?void 0:s.errors;if(i!=null){let d=a.findIndex(p=>p.route.id&&(i==null?void 0:i[p.route.id])!==void 0);d>=0||Ze(!1),a=a.slice(0,Math.min(a.length,d+1))}let c=!1,l=-1;if(n&&r&&r.v7_partialHydration)for(let d=0;d=0?a=a.slice(0,l+1):a=[a[0]];break}}}return a.reduceRight((d,p,f)=>{let h,g=!1,m=null,x=null;n&&(h=i&&p.route.id?i[p.route.id]:void 0,m=p.route.errorElement||gL,c&&(l<0&&f===0?(EL("route-fallback"),g=!0,x=null):l===f&&(g=!0,x=p.route.hydrateFallbackElement||null)));let b=t.concat(a.slice(0,f+1)),y=()=>{let w;return h?w=m:g?w=x:p.route.Component?w=v.createElement(p.route.Component,null):p.route.element?w=p.route.element:w=d,v.createElement(vL,{match:p,routeContext:{outlet:d,matches:b,isDataRoute:n!=null},children:w})};return n&&(p.route.ErrorBoundary||p.route.errorElement||f===0)?v.createElement(mL,{location:n.location,revalidation:n.revalidation,component:m,error:h,children:y(),routeContext:{outlet:null,matches:b,isDataRoute:!0}}):y()},null)}var x_=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(x_||{}),Yp=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(Yp||{});function bL(e){let t=v.useContext(Yh);return t||Ze(!1),t}function xL(e){let t=v.useContext(m_);return t||Ze(!1),t}function wL(e){let t=v.useContext(wo);return t||Ze(!1),t}function w_(e){let t=wL(),n=t.matches[t.matches.length-1];return n.route.id||Ze(!1),n.route.id}function SL(){var e;let t=v.useContext(v_),n=xL(Yp.UseRouteError),r=w_(Yp.UseRouteError);return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function CL(){let{router:e}=bL(x_.UseNavigateStable),t=w_(Yp.UseNavigateStable),n=v.useRef(!1);return y_(()=>{n.current=!0}),v.useCallback(function(s,o){o===void 0&&(o={}),n.current&&(typeof s=="number"?e.navigate(s):e.navigate(s,Zp({fromRouteId:t},o)))},[e,t])}const O0={};function EL(e,t,n){O0[e]||(O0[e]=!0)}function S_(e){let{to:t,replace:n,state:r,relative:s}=e;fu()||Ze(!1);let{future:o,static:a}=v.useContext(ja),{matches:i}=v.useContext(wo),{pathname:c}=pu(),l=An(),d=Qh(t,Jh(i,o.v7_relativeSplatPath),c,s==="path"),p=JSON.stringify(d);return v.useEffect(()=>l(JSON.parse(p),{replace:n,state:r,relative:s}),[l,p,s,n,r]),null}function TL(e){let{basename:t="/",children:n=null,location:r,navigationType:s=en.Pop,navigator:o,static:a=!1,future:i}=e;fu()&&Ze(!1);let c=t.replace(/^\/*/,"/"),l=v.useMemo(()=>({basename:c,navigator:o,static:a,future:Zp({v7_relativeSplatPath:!1},i)}),[c,i,o,a]);typeof r=="string"&&(r=_a(r));let{pathname:d="/",search:p="",hash:f="",state:h=null,key:g="default"}=r,m=v.useMemo(()=>{let x=du(d,c);return x==null?null:{location:{pathname:x,search:p,hash:f,state:h,key:g},navigationType:s}},[c,d,p,f,h,g,s]);return m==null?null:v.createElement(ja.Provider,{value:l},v.createElement(Ox.Provider,{children:n,value:m}))}new Promise(()=>{});function kL(e){let t={hasErrorBoundary:e.ErrorBoundary!=null||e.errorElement!=null};return e.Component&&Object.assign(t,{element:v.createElement(e.Component),Component:void 0}),e.HydrateFallback&&Object.assign(t,{hydrateFallbackElement:v.createElement(e.HydrateFallback),HydrateFallback:void 0}),e.ErrorBoundary&&Object.assign(t,{errorElement:v.createElement(e.ErrorBoundary),ErrorBoundary:void 0}),t}/** + * React Router DOM v6.25.1 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function td(){return td=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0)&&(n[s]=e[s]);return n}function jL(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function RL(e,t){return e.button===0&&(!t||t==="_self")&&!jL(e)}const OL=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","unstable_viewTransition"],NL="6";try{window.__reactRouterVersion=NL}catch{}function PL(e,t){return K2({basename:void 0,future:td({},void 0,{v7_prependBasename:!0}),history:g2({window:void 0}),hydrationData:ML(),routes:e,mapRouteProperties:kL,unstable_dataStrategy:void 0,unstable_patchRoutesOnMiss:void 0,window:void 0}).initialize()}function ML(){var e;let t=(e=window)==null?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=td({},t,{errors:IL(t.errors)})),t}function IL(e){if(!e)return null;let t=Object.entries(e),n={};for(let[r,s]of t)if(s&&s.__type==="RouteErrorResponse")n[r]=new _x(s.status,s.statusText,s.data,s.internal===!0);else if(s&&s.__type==="Error"){if(s.__subType){let o=window[s.__subType];if(typeof o=="function")try{let a=new o(s.message);a.stack="",n[r]=a}catch{}}if(n[r]==null){let o=new Error(s.message);o.stack="",n[r]=o}}else n[r]=s;return n}const DL=v.createContext({isTransitioning:!1}),AL=v.createContext(new Map),FL="startTransition",N0=Mh[FL],LL="flushSync",P0=YF[LL];function $L(e){N0?N0(e):e()}function Wu(e){P0?P0(e):e()}class BL{constructor(){this.status="pending",this.promise=new Promise((t,n)=>{this.resolve=r=>{this.status==="pending"&&(this.status="resolved",t(r))},this.reject=r=>{this.status==="pending"&&(this.status="rejected",n(r))}})}}function zL(e){let{fallbackElement:t,router:n,future:r}=e,[s,o]=v.useState(n.state),[a,i]=v.useState(),[c,l]=v.useState({isTransitioning:!1}),[d,p]=v.useState(),[f,h]=v.useState(),[g,m]=v.useState(),x=v.useRef(new Map),{v7_startTransition:b}=r||{},y=v.useCallback(T=>{b?$L(T):T()},[b]),w=v.useCallback((T,O)=>{let{deletedFetchers:M,unstable_flushSync:U,unstable_viewTransitionOpts:I}=O;M.forEach(V=>x.current.delete(V)),T.fetchers.forEach((V,G)=>{V.data!==void 0&&x.current.set(G,V.data)});let J=n.window==null||n.window.document==null||typeof n.window.document.startViewTransition!="function";if(!I||J){U?Wu(()=>o(T)):y(()=>o(T));return}if(U){Wu(()=>{f&&(d&&d.resolve(),f.skipTransition()),l({isTransitioning:!0,flushSync:!0,currentLocation:I.currentLocation,nextLocation:I.nextLocation})});let V=n.window.document.startViewTransition(()=>{Wu(()=>o(T))});V.finished.finally(()=>{Wu(()=>{p(void 0),h(void 0),i(void 0),l({isTransitioning:!1})})}),Wu(()=>h(V));return}f?(d&&d.resolve(),f.skipTransition(),m({state:T,currentLocation:I.currentLocation,nextLocation:I.nextLocation})):(i(T),l({isTransitioning:!0,flushSync:!1,currentLocation:I.currentLocation,nextLocation:I.nextLocation}))},[n.window,f,d,x,y]);v.useLayoutEffect(()=>n.subscribe(w),[n,w]),v.useEffect(()=>{c.isTransitioning&&!c.flushSync&&p(new BL)},[c]),v.useEffect(()=>{if(d&&a&&n.window){let T=a,O=d.promise,M=n.window.document.startViewTransition(async()=>{y(()=>o(T)),await O});M.finished.finally(()=>{p(void 0),h(void 0),i(void 0),l({isTransitioning:!1})}),h(M)}},[y,a,d,n.window]),v.useEffect(()=>{d&&a&&s.location.key===a.location.key&&d.resolve()},[d,f,s.location,a]),v.useEffect(()=>{!c.isTransitioning&&g&&(i(g.state),l({isTransitioning:!0,flushSync:!1,currentLocation:g.currentLocation,nextLocation:g.nextLocation}),m(void 0))},[c.isTransitioning,g]),v.useEffect(()=>{},[]);let S=v.useMemo(()=>({createHref:n.createHref,encodeLocation:n.encodeLocation,go:T=>n.navigate(T),push:(T,O,M)=>n.navigate(T,{state:O,preventScrollReset:M==null?void 0:M.preventScrollReset}),replace:(T,O,M)=>n.navigate(T,{replace:!0,state:O,preventScrollReset:M==null?void 0:M.preventScrollReset})}),[n]),E=n.basename||"/",C=v.useMemo(()=>({router:n,navigator:S,static:!1,basename:E}),[n,S,E]),k=v.useMemo(()=>({v7_relativeSplatPath:n.future.v7_relativeSplatPath}),[n.future.v7_relativeSplatPath]);return v.createElement(v.Fragment,null,v.createElement(Yh.Provider,{value:C},v.createElement(m_.Provider,{value:s},v.createElement(AL.Provider,{value:x.current},v.createElement(DL.Provider,{value:c},v.createElement(TL,{basename:E,location:s.location,navigationType:s.historyAction,navigator:S,future:k},s.initialized||n.future.v7_partialHydration?v.createElement(UL,{routes:n.routes,future:n.future,state:s}):t))))),null)}const UL=v.memo(VL);function VL(e){let{routes:t,future:n,state:r}=e;return pL(t,void 0,r,n)}const HL=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",KL=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,nd=v.forwardRef(function(t,n){let{onClick:r,relative:s,reloadDocument:o,replace:a,state:i,target:c,to:l,preventScrollReset:d,unstable_viewTransition:p}=t,f=_L(t,OL),{basename:h}=v.useContext(ja),g,m=!1;if(typeof l=="string"&&KL.test(l)&&(g=l,HL))try{let w=new URL(window.location.href),S=l.startsWith("//")?new URL(w.protocol+l):new URL(l),E=du(S.pathname,h);S.origin===w.origin&&E!=null?l=E+S.search+S.hash:m=!0}catch{}let x=dL(l,{relative:s}),b=qL(l,{replace:a,state:i,target:c,preventScrollReset:d,relative:s,unstable_viewTransition:p});function y(w){r&&r(w),w.defaultPrevented||b(w)}return v.createElement("a",td({},f,{href:g||x,onClick:m||o?r:y,ref:n,target:c}))});var M0;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(M0||(M0={}));var I0;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(I0||(I0={}));function qL(e,t){let{target:n,replace:r,state:s,preventScrollReset:o,relative:a,unstable_viewTransition:i}=t===void 0?{}:t,c=An(),l=pu(),d=b_(e,{relative:a});return v.useCallback(p=>{if(RL(p,n)){p.preventDefault();let f=r!==void 0?r:wi(l)===wi(d);c(e,{replace:f,state:s,preventScrollReset:o,relative:a,unstable_viewTransition:i})}},[l,c,d,r,s,n,e,o,a,i])}function C_(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(t=0;ttypeof e=="number"&&!isNaN(e),ci=e=>typeof e=="string",gr=e=>typeof e=="function",dp=e=>ci(e)||gr(e)?e:null,Iy=e=>v.isValidElement(e)||ci(e)||gr(e)||rd(e);function WL(e,t,n){n===void 0&&(n=300);const{scrollHeight:r,style:s}=e;requestAnimationFrame(()=>{s.minHeight="initial",s.height=r+"px",s.transition=`all ${n}ms`,requestAnimationFrame(()=>{s.height="0",s.padding="0",s.margin="0",setTimeout(t,n)})})}function Xh(e){let{enter:t,exit:n,appendPosition:r=!1,collapse:s=!0,collapseDuration:o=300}=e;return function(a){let{children:i,position:c,preventExitTransition:l,done:d,nodeRef:p,isIn:f,playToast:h}=a;const g=r?`${t}--${c}`:t,m=r?`${n}--${c}`:n,x=v.useRef(0);return v.useLayoutEffect(()=>{const b=p.current,y=g.split(" "),w=S=>{S.target===p.current&&(h(),b.removeEventListener("animationend",w),b.removeEventListener("animationcancel",w),x.current===0&&S.type!=="animationcancel"&&b.classList.remove(...y))};b.classList.add(...y),b.addEventListener("animationend",w),b.addEventListener("animationcancel",w)},[]),v.useEffect(()=>{const b=p.current,y=()=>{b.removeEventListener("animationend",y),s?WL(b,d,o):d()};f||(l?y():(x.current=1,b.className+=` ${m}`,b.addEventListener("animationend",y)))},[f]),Te.createElement(Te.Fragment,null,i)}}function D0(e,t){return e!=null?{content:e.content,containerId:e.props.containerId,id:e.props.toastId,theme:e.props.theme,type:e.props.type,data:e.props.data||{},isLoading:e.props.isLoading,icon:e.props.icon,status:t}:{}}const Vn=new Map;let sd=[];const Dy=new Set,GL=e=>Dy.forEach(t=>t(e)),E_=()=>Vn.size>0;function T_(e,t){var n;if(t)return!((n=Vn.get(t))==null||!n.isToastActive(e));let r=!1;return Vn.forEach(s=>{s.isToastActive(e)&&(r=!0)}),r}function k_(e,t){Iy(e)&&(E_()||sd.push({content:e,options:t}),Vn.forEach(n=>{n.buildToast(e,t)}))}function A0(e,t){Vn.forEach(n=>{t!=null&&t!=null&&t.containerId?(t==null?void 0:t.containerId)===n.id&&n.toggle(e,t==null?void 0:t.id):n.toggle(e,t==null?void 0:t.id)})}function JL(e){const{subscribe:t,getSnapshot:n,setProps:r}=v.useRef(function(o){const a=o.containerId||1;return{subscribe(i){const c=function(d,p,f){let h=1,g=0,m=[],x=[],b=[],y=p;const w=new Map,S=new Set,E=()=>{b=Array.from(w.values()),S.forEach(T=>T())},C=T=>{x=T==null?[]:x.filter(O=>O!==T),E()},k=T=>{const{toastId:O,onOpen:M,updateId:U,children:I}=T.props,J=U==null;T.staleId&&w.delete(T.staleId),w.set(O,T),x=[...x,T.props.toastId].filter(V=>V!==T.staleId),E(),f(D0(T,J?"added":"updated")),J&&gr(M)&&M(v.isValidElement(I)&&I.props)};return{id:d,props:y,observe:T=>(S.add(T),()=>S.delete(T)),toggle:(T,O)=>{w.forEach(M=>{O!=null&&O!==M.props.toastId||gr(M.toggle)&&M.toggle(T)})},removeToast:C,toasts:w,clearQueue:()=>{g-=m.length,m=[]},buildToast:(T,O)=>{if((z=>{let{containerId:se,toastId:ne,updateId:ie}=z;const oe=se?se!==d:d!==1,W=w.has(ne)&&ie==null;return oe||W})(O))return;const{toastId:M,updateId:U,data:I,staleId:J,delay:V}=O,G=()=>{C(M)},ee=U==null;ee&&g++;const q={...y,style:y.toastStyle,key:h++,...Object.fromEntries(Object.entries(O).filter(z=>{let[se,ne]=z;return ne!=null})),toastId:M,updateId:U,data:I,closeToast:G,isIn:!1,className:dp(O.className||y.toastClassName),bodyClassName:dp(O.bodyClassName||y.bodyClassName),progressClassName:dp(O.progressClassName||y.progressClassName),autoClose:!O.isLoading&&(F=O.autoClose,A=y.autoClose,F===!1||rd(F)&&F>0?F:A),deleteToast(){const z=w.get(M),{onClose:se,children:ne}=z.props;gr(se)&&se(v.isValidElement(ne)&&ne.props),f(D0(z,"removed")),w.delete(M),g--,g<0&&(g=0),m.length>0?k(m.shift()):E()}};var F,A;q.closeButton=y.closeButton,O.closeButton===!1||Iy(O.closeButton)?q.closeButton=O.closeButton:O.closeButton===!0&&(q.closeButton=!Iy(y.closeButton)||y.closeButton);let Y=T;v.isValidElement(T)&&!ci(T.type)?Y=v.cloneElement(T,{closeToast:G,toastProps:q,data:I}):gr(T)&&(Y=T({closeToast:G,toastProps:q,data:I}));const de={content:Y,props:q,staleId:J};y.limit&&y.limit>0&&g>y.limit&&ee?m.push(de):rd(V)?setTimeout(()=>{k(de)},V):k(de)},setProps(T){y=T},setToggle:(T,O)=>{w.get(T).toggle=O},isToastActive:T=>x.some(O=>O===T),getSnapshot:()=>y.newestOnTop?b.reverse():b}}(a,o,GL);Vn.set(a,c);const l=c.observe(i);return sd.forEach(d=>k_(d.content,d.options)),sd=[],()=>{l(),Vn.delete(a)}},setProps(i){var c;(c=Vn.get(a))==null||c.setProps(i)},getSnapshot(){var i;return(i=Vn.get(a))==null?void 0:i.getSnapshot()}}}(e)).current;r(e);const s=v.useSyncExternalStore(t,n,n);return{getToastToRender:function(o){if(!s)return[];const a=new Map;return s.forEach(i=>{const{position:c}=i.props;a.has(c)||a.set(c,[]),a.get(c).push(i)}),Array.from(a,i=>o(i[0],i[1]))},isToastActive:T_,count:s==null?void 0:s.length}}function QL(e){const[t,n]=v.useState(!1),[r,s]=v.useState(!1),o=v.useRef(null),a=v.useRef({start:0,delta:0,removalDistance:0,canCloseOnClick:!0,canDrag:!1,didMove:!1}).current,{autoClose:i,pauseOnHover:c,closeToast:l,onClick:d,closeOnClick:p}=e;var f,h;function g(){n(!0)}function m(){n(!1)}function x(w){const S=o.current;a.canDrag&&S&&(a.didMove=!0,t&&m(),a.delta=e.draggableDirection==="x"?w.clientX-a.start:w.clientY-a.start,a.start!==w.clientX&&(a.canCloseOnClick=!1),S.style.transform=`translate3d(${e.draggableDirection==="x"?`${a.delta}px, var(--y)`:`0, calc(${a.delta}px + var(--y))`},0)`,S.style.opacity=""+(1-Math.abs(a.delta/a.removalDistance)))}function b(){document.removeEventListener("pointermove",x),document.removeEventListener("pointerup",b);const w=o.current;if(a.canDrag&&a.didMove&&w){if(a.canDrag=!1,Math.abs(a.delta)>a.removalDistance)return s(!0),e.closeToast(),void e.collapseAll();w.style.transition="transform 0.2s, opacity 0.2s",w.style.removeProperty("transform"),w.style.removeProperty("opacity")}}(h=Vn.get((f={id:e.toastId,containerId:e.containerId,fn:n}).containerId||1))==null||h.setToggle(f.id,f.fn),v.useEffect(()=>{if(e.pauseOnFocusLoss)return document.hasFocus()||m(),window.addEventListener("focus",g),window.addEventListener("blur",m),()=>{window.removeEventListener("focus",g),window.removeEventListener("blur",m)}},[e.pauseOnFocusLoss]);const y={onPointerDown:function(w){if(e.draggable===!0||e.draggable===w.pointerType){a.didMove=!1,document.addEventListener("pointermove",x),document.addEventListener("pointerup",b);const S=o.current;a.canCloseOnClick=!0,a.canDrag=!0,S.style.transition="none",e.draggableDirection==="x"?(a.start=w.clientX,a.removalDistance=S.offsetWidth*(e.draggablePercent/100)):(a.start=w.clientY,a.removalDistance=S.offsetHeight*(e.draggablePercent===80?1.5*e.draggablePercent:e.draggablePercent)/100)}},onPointerUp:function(w){const{top:S,bottom:E,left:C,right:k}=o.current.getBoundingClientRect();w.nativeEvent.type!=="touchend"&&e.pauseOnHover&&w.clientX>=C&&w.clientX<=k&&w.clientY>=S&&w.clientY<=E?m():g()}};return i&&c&&(y.onMouseEnter=m,e.stacked||(y.onMouseLeave=g)),p&&(y.onClick=w=>{d&&d(w),a.canCloseOnClick&&l()}),{playToast:g,pauseToast:m,isRunning:t,preventExitTransition:r,toastRef:o,eventHandlers:y}}function ZL(e){let{delay:t,isRunning:n,closeToast:r,type:s="default",hide:o,className:a,style:i,controlledProgress:c,progress:l,rtl:d,isIn:p,theme:f}=e;const h=o||c&&l===0,g={...i,animationDuration:`${t}ms`,animationPlayState:n?"running":"paused"};c&&(g.transform=`scaleX(${l})`);const m=oo("Toastify__progress-bar",c?"Toastify__progress-bar--controlled":"Toastify__progress-bar--animated",`Toastify__progress-bar-theme--${f}`,`Toastify__progress-bar--${s}`,{"Toastify__progress-bar--rtl":d}),x=gr(a)?a({rtl:d,type:s,defaultClassName:m}):oo(m,a),b={[c&&l>=1?"onTransitionEnd":"onAnimationEnd"]:c&&l<1?null:()=>{p&&r()}};return Te.createElement("div",{className:"Toastify__progress-bar--wrp","data-hidden":h},Te.createElement("div",{className:`Toastify__progress-bar--bg Toastify__progress-bar-theme--${f} Toastify__progress-bar--${s}`}),Te.createElement("div",{role:"progressbar","aria-hidden":h?"true":"false","aria-label":"notification timer",className:x,style:g,...b}))}let YL=1;const __=()=>""+YL++;function XL(e){return e&&(ci(e.toastId)||rd(e.toastId))?e.toastId:__()}function _c(e,t){return k_(e,t),t.toastId}function Xp(e,t){return{...t,type:t&&t.type||e,toastId:XL(t)}}function jf(e){return(t,n)=>_c(t,Xp(e,n))}function X(e,t){return _c(e,Xp("default",t))}X.loading=(e,t)=>_c(e,Xp("default",{isLoading:!0,autoClose:!1,closeOnClick:!1,closeButton:!1,draggable:!1,...t})),X.promise=function(e,t,n){let r,{pending:s,error:o,success:a}=t;s&&(r=ci(s)?X.loading(s,n):X.loading(s.render,{...n,...s}));const i={isLoading:null,autoClose:null,closeOnClick:null,closeButton:null,draggable:null},c=(d,p,f)=>{if(p==null)return void X.dismiss(r);const h={type:d,...i,...n,data:f},g=ci(p)?{render:p}:p;return r?X.update(r,{...h,...g}):X(g.render,{...h,...g}),f},l=gr(e)?e():e;return l.then(d=>c("success",a,d)).catch(d=>c("error",o,d)),l},X.success=jf("success"),X.info=jf("info"),X.error=jf("error"),X.warning=jf("warning"),X.warn=X.warning,X.dark=(e,t)=>_c(e,Xp("default",{theme:"dark",...t})),X.dismiss=function(e){(function(t){var n;if(E_()){if(t==null||ci(n=t)||rd(n))Vn.forEach(r=>{r.removeToast(t)});else if(t&&("containerId"in t||"id"in t)){const r=Vn.get(t.containerId);r?r.removeToast(t.id):Vn.forEach(s=>{s.removeToast(t.id)})}}else sd=sd.filter(r=>t!=null&&r.options.toastId!==t)})(e)},X.clearWaitingQueue=function(e){e===void 0&&(e={}),Vn.forEach(t=>{!t.props.limit||e.containerId&&t.id!==e.containerId||t.clearQueue()})},X.isActive=T_,X.update=function(e,t){t===void 0&&(t={});const n=((r,s)=>{var o;let{containerId:a}=s;return(o=Vn.get(a||1))==null?void 0:o.toasts.get(r)})(e,t);if(n){const{props:r,content:s}=n,o={delay:100,...r,...t,toastId:t.toastId||e,updateId:__()};o.toastId!==e&&(o.staleId=e);const a=o.render||s;delete o.render,_c(a,o)}},X.done=e=>{X.update(e,{progress:1})},X.onChange=function(e){return Dy.add(e),()=>{Dy.delete(e)}},X.play=e=>A0(!0,e),X.pause=e=>A0(!1,e);const e$=typeof window<"u"?v.useLayoutEffect:v.useEffect,Rf=e=>{let{theme:t,type:n,isLoading:r,...s}=e;return Te.createElement("svg",{viewBox:"0 0 24 24",width:"100%",height:"100%",fill:t==="colored"?"currentColor":`var(--toastify-icon-color-${n})`,...s})},Dm={info:function(e){return Te.createElement(Rf,{...e},Te.createElement("path",{d:"M12 0a12 12 0 1012 12A12.013 12.013 0 0012 0zm.25 5a1.5 1.5 0 11-1.5 1.5 1.5 1.5 0 011.5-1.5zm2.25 13.5h-4a1 1 0 010-2h.75a.25.25 0 00.25-.25v-4.5a.25.25 0 00-.25-.25h-.75a1 1 0 010-2h1a2 2 0 012 2v4.75a.25.25 0 00.25.25h.75a1 1 0 110 2z"}))},warning:function(e){return Te.createElement(Rf,{...e},Te.createElement("path",{d:"M23.32 17.191L15.438 2.184C14.728.833 13.416 0 11.996 0c-1.42 0-2.733.833-3.443 2.184L.533 17.448a4.744 4.744 0 000 4.368C1.243 23.167 2.555 24 3.975 24h16.05C22.22 24 24 22.044 24 19.632c0-.904-.251-1.746-.68-2.44zm-9.622 1.46c0 1.033-.724 1.823-1.698 1.823s-1.698-.79-1.698-1.822v-.043c0-1.028.724-1.822 1.698-1.822s1.698.79 1.698 1.822v.043zm.039-12.285l-.84 8.06c-.057.581-.408.943-.897.943-.49 0-.84-.367-.896-.942l-.84-8.065c-.057-.624.25-1.095.779-1.095h1.91c.528.005.84.476.784 1.1z"}))},success:function(e){return Te.createElement(Rf,{...e},Te.createElement("path",{d:"M12 0a12 12 0 1012 12A12.014 12.014 0 0012 0zm6.927 8.2l-6.845 9.289a1.011 1.011 0 01-1.43.188l-4.888-3.908a1 1 0 111.25-1.562l4.076 3.261 6.227-8.451a1 1 0 111.61 1.183z"}))},error:function(e){return Te.createElement(Rf,{...e},Te.createElement("path",{d:"M11.983 0a12.206 12.206 0 00-8.51 3.653A11.8 11.8 0 000 12.207 11.779 11.779 0 0011.8 24h.214A12.111 12.111 0 0024 11.791 11.766 11.766 0 0011.983 0zM10.5 16.542a1.476 1.476 0 011.449-1.53h.027a1.527 1.527 0 011.523 1.47 1.475 1.475 0 01-1.449 1.53h-.027a1.529 1.529 0 01-1.523-1.47zM11 12.5v-6a1 1 0 012 0v6a1 1 0 11-2 0z"}))},spinner:function(){return Te.createElement("div",{className:"Toastify__spinner"})}},t$=e=>{const{isRunning:t,preventExitTransition:n,toastRef:r,eventHandlers:s,playToast:o}=QL(e),{closeButton:a,children:i,autoClose:c,onClick:l,type:d,hideProgressBar:p,closeToast:f,transition:h,position:g,className:m,style:x,bodyClassName:b,bodyStyle:y,progressClassName:w,progressStyle:S,updateId:E,role:C,progress:k,rtl:T,toastId:O,deleteToast:M,isIn:U,isLoading:I,closeOnClick:J,theme:V}=e,G=oo("Toastify__toast",`Toastify__toast-theme--${V}`,`Toastify__toast--${d}`,{"Toastify__toast--rtl":T},{"Toastify__toast--close-on-click":J}),ee=gr(m)?m({rtl:T,position:g,type:d,defaultClassName:G}):oo(G,m),q=function(de){let{theme:z,type:se,isLoading:ne,icon:ie}=de,oe=null;const W={theme:z,type:se};return ie===!1||(gr(ie)?oe=ie({...W,isLoading:ne}):v.isValidElement(ie)?oe=v.cloneElement(ie,W):ne?oe=Dm.spinner():(Ce=>Ce in Dm)(se)&&(oe=Dm[se](W))),oe}(e),F=!!k||!c,A={closeToast:f,type:d,theme:V};let Y=null;return a===!1||(Y=gr(a)?a(A):v.isValidElement(a)?v.cloneElement(a,A):function(de){let{closeToast:z,theme:se,ariaLabel:ne="close"}=de;return Te.createElement("button",{className:`Toastify__close-button Toastify__close-button--${se}`,type:"button",onClick:ie=>{ie.stopPropagation(),z(ie)},"aria-label":ne},Te.createElement("svg",{"aria-hidden":"true",viewBox:"0 0 14 16"},Te.createElement("path",{fillRule:"evenodd",d:"M7.71 8.23l3.75 3.75-1.48 1.48-3.75-3.75-3.75 3.75L1 11.98l3.75-3.75L1 4.48 2.48 3l3.75 3.75L9.98 3l1.48 1.48-3.75 3.75z"})))}(A)),Te.createElement(h,{isIn:U,done:M,position:g,preventExitTransition:n,nodeRef:r,playToast:o},Te.createElement("div",{id:O,onClick:l,"data-in":U,className:ee,...s,style:x,ref:r},Te.createElement("div",{...U&&{role:C},className:gr(b)?b({type:d}):oo("Toastify__toast-body",b),style:y},q!=null&&Te.createElement("div",{className:oo("Toastify__toast-icon",{"Toastify--animate-icon Toastify__zoom-enter":!I})},q),Te.createElement("div",null,i)),Y,Te.createElement(ZL,{...E&&!F?{key:`pb-${E}`}:{},rtl:T,theme:V,delay:c,isRunning:t,isIn:U,closeToast:f,hide:p,type:d,style:S,className:w,controlledProgress:F,progress:k||0})))},eg=function(e,t){return t===void 0&&(t=!1),{enter:`Toastify--animate Toastify__${e}-enter`,exit:`Toastify--animate Toastify__${e}-exit`,appendPosition:t}},n$=Xh(eg("bounce",!0));Xh(eg("slide",!0));Xh(eg("zoom"));Xh(eg("flip"));const r$={position:"top-right",transition:n$,autoClose:5e3,closeButton:!0,pauseOnHover:!0,pauseOnFocusLoss:!0,draggable:"touch",draggablePercent:80,draggableDirection:"x",role:"alert",theme:"light"};function s$(e){let t={...r$,...e};const n=e.stacked,[r,s]=v.useState(!0),o=v.useRef(null),{getToastToRender:a,isToastActive:i,count:c}=JL(t),{className:l,style:d,rtl:p,containerId:f}=t;function h(m){const x=oo("Toastify__toast-container",`Toastify__toast-container--${m}`,{"Toastify__toast-container--rtl":p});return gr(l)?l({position:m,rtl:p,defaultClassName:x}):oo(x,dp(l))}function g(){n&&(s(!0),X.play())}return e$(()=>{if(n){var m;const x=o.current.querySelectorAll('[data-in="true"]'),b=12,y=(m=t.position)==null?void 0:m.includes("top");let w=0,S=0;Array.from(x).reverse().forEach((E,C)=>{const k=E;k.classList.add("Toastify__toast--stacked"),C>0&&(k.dataset.collapsed=`${r}`),k.dataset.pos||(k.dataset.pos=y?"top":"bot");const T=w*(r?.2:1)+(r?0:b*C);k.style.setProperty("--y",`${y?T:-1*T}px`),k.style.setProperty("--g",`${b}`),k.style.setProperty("--s",""+(1-(r?S:0))),w+=k.offsetHeight,S+=.025})}},[r,c,n]),Te.createElement("div",{ref:o,className:"Toastify",id:f,onMouseEnter:()=>{n&&(s(!1),X.pause())},onMouseLeave:g},a((m,x)=>{const b=x.length?{...d}:{...d,pointerEvents:"none"};return Te.createElement("div",{className:h(m),style:b,key:`container-${m}`},x.map(y=>{let{content:w,props:S}=y;return Te.createElement(t$,{...S,stacked:n,collapseAll:g,isIn:i(S.toastId,S.containerId),style:S.style,key:`toast-${S.key}`},w)}))}))}const o$={theme:"system",setTheme:()=>null},j_=v.createContext(o$);function a$({children:e,defaultTheme:t="system",storageKey:n="vite-ui-theme",...r}){const[s,o]=v.useState(()=>localStorage.getItem(n)||t);v.useEffect(()=>{const i=window.document.documentElement;if(i.classList.remove("light","dark"),s==="system"){const c=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";i.classList.add(c);return}i.classList.add(s)},[s]);const a={theme:s,setTheme:i=>{localStorage.setItem(n,i),o(i)}};return u.jsx(j_.Provider,{...r,value:a,children:e})}const R_=()=>{const e=v.useContext(j_);if(e===void 0)throw new Error("useTheme must be used within a ThemeProvider");return e};let Am=!1;const i$=new RD({defaultOptions:{queries:{staleTime:1e3*60*5,retry(e){return e>=3?(Am===!1&&(Am=!0,X.error("The application is taking longer than expected to load, please try again in a few minutes.",{onClose:()=>{Am=!1}})),!1):!0}}}});var rs=(e=>(e.API_URL="apiUrl",e.TOKEN="token",e.VERSION="version",e.FACEBOOK_APP_ID="facebookAppId",e.FACEBOOK_CONFIG_ID="facebookConfigId",e.FACEBOOK_USER_TOKEN="facebookUserToken",e.CLIENT_NAME="clientName",e))(rs||{});const O_=async e=>{if(e.url){const t=e.url.endsWith("/")?e.url.slice(0,-1):e.url;localStorage.setItem("apiUrl",t)}e.token&&localStorage.setItem("token",e.token),e.version&&localStorage.setItem("version",e.version),e.facebookAppId&&localStorage.setItem("facebookAppId",e.facebookAppId),e.facebookConfigId&&localStorage.setItem("facebookConfigId",e.facebookConfigId),e.facebookUserToken&&localStorage.setItem("facebookUserToken",e.facebookUserToken),e.clientName&&localStorage.setItem("clientName",e.clientName)},N_=()=>{localStorage.removeItem("apiUrl"),localStorage.removeItem("token"),localStorage.removeItem("version"),localStorage.removeItem("facebookAppId"),localStorage.removeItem("facebookConfigId"),localStorage.removeItem("facebookUserToken"),localStorage.removeItem("clientName")},Fs=e=>localStorage.getItem(e),Gt=({children:e})=>{const t=Fs(rs.API_URL),n=Fs(rs.TOKEN),r=Fs(rs.VERSION);return!t||!n||!r?u.jsx(S_,{to:"/manager/login"}):e},l$=({children:e})=>{const t=Fs(rs.API_URL),n=Fs(rs.TOKEN),r=Fs(rs.VERSION);return t&&n&&r?u.jsx(S_,{to:"/"}):e};function P_(e,t){return function(){return e.apply(t,arguments)}}const{toString:u$}=Object.prototype,{getPrototypeOf:Nx}=Object,tg=(e=>t=>{const n=u$.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),fs=e=>(e=e.toLowerCase(),t=>tg(t)===e),ng=e=>t=>typeof t===e,{isArray:hu}=Array,od=ng("undefined");function c$(e){return e!==null&&!od(e)&&e.constructor!==null&&!od(e.constructor)&&Lr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const M_=fs("ArrayBuffer");function d$(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&M_(e.buffer),t}const f$=ng("string"),Lr=ng("function"),I_=ng("number"),rg=e=>e!==null&&typeof e=="object",p$=e=>e===!0||e===!1,fp=e=>{if(tg(e)!=="object")return!1;const t=Nx(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},h$=fs("Date"),g$=fs("File"),m$=fs("Blob"),v$=fs("FileList"),y$=e=>rg(e)&&Lr(e.pipe),b$=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Lr(e.append)&&((t=tg(e))==="formdata"||t==="object"&&Lr(e.toString)&&e.toString()==="[object FormData]"))},x$=fs("URLSearchParams"),[w$,S$,C$,E$]=["ReadableStream","Request","Response","Headers"].map(fs),T$=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Bd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,s;if(typeof e!="object"&&(e=[e]),hu(e))for(r=0,s=e.length;r0;)if(s=n[r],t===s.toLowerCase())return s;return null}const A_=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,F_=e=>!od(e)&&e!==A_;function Ay(){const{caseless:e}=F_(this)&&this||{},t={},n=(r,s)=>{const o=e&&D_(t,s)||s;fp(t[o])&&fp(r)?t[o]=Ay(t[o],r):fp(r)?t[o]=Ay({},r):hu(r)?t[o]=r.slice():t[o]=r};for(let r=0,s=arguments.length;r(Bd(t,(s,o)=>{n&&Lr(s)?e[o]=P_(s,n):e[o]=s},{allOwnKeys:r}),e),_$=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),j$=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},R$=(e,t,n,r)=>{let s,o,a;const i={};if(t=t||{},e==null)return t;do{for(s=Object.getOwnPropertyNames(e),o=s.length;o-- >0;)a=s[o],(!r||r(a,e,t))&&!i[a]&&(t[a]=e[a],i[a]=!0);e=n!==!1&&Nx(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},O$=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},N$=e=>{if(!e)return null;if(hu(e))return e;let t=e.length;if(!I_(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},P$=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Nx(Uint8Array)),M$=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let s;for(;(s=r.next())&&!s.done;){const o=s.value;t.call(e,o[0],o[1])}},I$=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},D$=fs("HTMLFormElement"),A$=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,s){return r.toUpperCase()+s}),F0=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),F$=fs("RegExp"),L_=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Bd(n,(s,o)=>{let a;(a=t(s,o,e))!==!1&&(r[o]=a||s)}),Object.defineProperties(e,r)},L$=e=>{L_(e,(t,n)=>{if(Lr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Lr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},$$=(e,t)=>{const n={},r=s=>{s.forEach(o=>{n[o]=!0})};return hu(e)?r(e):r(String(e).split(t)),n},B$=()=>{},z$=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,Fm="abcdefghijklmnopqrstuvwxyz",L0="0123456789",$_={DIGIT:L0,ALPHA:Fm,ALPHA_DIGIT:Fm+Fm.toUpperCase()+L0},U$=(e=16,t=$_.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function V$(e){return!!(e&&Lr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const H$=e=>{const t=new Array(10),n=(r,s)=>{if(rg(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[s]=r;const o=hu(r)?[]:{};return Bd(r,(a,i)=>{const c=n(a,s+1);!od(c)&&(o[i]=c)}),t[s]=void 0,o}}return r};return n(e,0)},K$=fs("AsyncFunction"),q$=e=>e&&(rg(e)||Lr(e))&&Lr(e.then)&&Lr(e.catch),$={isArray:hu,isArrayBuffer:M_,isBuffer:c$,isFormData:b$,isArrayBufferView:d$,isString:f$,isNumber:I_,isBoolean:p$,isObject:rg,isPlainObject:fp,isReadableStream:w$,isRequest:S$,isResponse:C$,isHeaders:E$,isUndefined:od,isDate:h$,isFile:g$,isBlob:m$,isRegExp:F$,isFunction:Lr,isStream:y$,isURLSearchParams:x$,isTypedArray:P$,isFileList:v$,forEach:Bd,merge:Ay,extend:k$,trim:T$,stripBOM:_$,inherits:j$,toFlatObject:R$,kindOf:tg,kindOfTest:fs,endsWith:O$,toArray:N$,forEachEntry:M$,matchAll:I$,isHTMLForm:D$,hasOwnProperty:F0,hasOwnProp:F0,reduceDescriptors:L_,freezeMethods:L$,toObjectSet:$$,toCamelCase:A$,noop:B$,toFiniteNumber:z$,findKey:D_,global:A_,isContextDefined:F_,ALPHABET:$_,generateString:U$,isSpecCompliantForm:V$,toJSONObject:H$,isAsyncFn:K$,isThenable:q$};function He(e,t,n,r,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),s&&(this.response=s)}$.inherits(He,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:$.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const B_=He.prototype,z_={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{z_[e]={value:e}});Object.defineProperties(He,z_);Object.defineProperty(B_,"isAxiosError",{value:!0});He.from=(e,t,n,r,s,o)=>{const a=Object.create(B_);return $.toFlatObject(e,a,function(c){return c!==Error.prototype},i=>i!=="isAxiosError"),He.call(a,e.message,t,n,r,s),a.cause=e,a.name=e.name,o&&Object.assign(a,o),a};const W$=null;function Fy(e){return $.isPlainObject(e)||$.isArray(e)}function U_(e){return $.endsWith(e,"[]")?e.slice(0,-2):e}function $0(e,t,n){return e?e.concat(t).map(function(s,o){return s=U_(s),!n&&o?"["+s+"]":s}).join(n?".":""):t}function G$(e){return $.isArray(e)&&!e.some(Fy)}const J$=$.toFlatObject($,{},null,function(t){return/^is[A-Z]/.test(t)});function sg(e,t,n){if(!$.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=$.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,x){return!$.isUndefined(x[m])});const r=n.metaTokens,s=n.visitor||d,o=n.dots,a=n.indexes,c=(n.Blob||typeof Blob<"u"&&Blob)&&$.isSpecCompliantForm(t);if(!$.isFunction(s))throw new TypeError("visitor must be a function");function l(g){if(g===null)return"";if($.isDate(g))return g.toISOString();if(!c&&$.isBlob(g))throw new He("Blob is not supported. Use a Buffer instead.");return $.isArrayBuffer(g)||$.isTypedArray(g)?c&&typeof Blob=="function"?new Blob([g]):Buffer.from(g):g}function d(g,m,x){let b=g;if(g&&!x&&typeof g=="object"){if($.endsWith(m,"{}"))m=r?m:m.slice(0,-2),g=JSON.stringify(g);else if($.isArray(g)&&G$(g)||($.isFileList(g)||$.endsWith(m,"[]"))&&(b=$.toArray(g)))return m=U_(m),b.forEach(function(w,S){!($.isUndefined(w)||w===null)&&t.append(a===!0?$0([m],S,o):a===null?m:m+"[]",l(w))}),!1}return Fy(g)?!0:(t.append($0(x,m,o),l(g)),!1)}const p=[],f=Object.assign(J$,{defaultVisitor:d,convertValue:l,isVisitable:Fy});function h(g,m){if(!$.isUndefined(g)){if(p.indexOf(g)!==-1)throw Error("Circular reference detected in "+m.join("."));p.push(g),$.forEach(g,function(b,y){(!($.isUndefined(b)||b===null)&&s.call(t,b,$.isString(y)?y.trim():y,m,f))===!0&&h(b,m?m.concat(y):[y])}),p.pop()}}if(!$.isObject(e))throw new TypeError("data must be an object");return h(e),t}function B0(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function Px(e,t){this._pairs=[],e&&sg(e,this,t)}const V_=Px.prototype;V_.append=function(t,n){this._pairs.push([t,n])};V_.toString=function(t){const n=t?function(r){return t.call(this,r,B0)}:B0;return this._pairs.map(function(s){return n(s[0])+"="+n(s[1])},"").join("&")};function Q$(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function H_(e,t,n){if(!t)return e;const r=n&&n.encode||Q$,s=n&&n.serialize;let o;if(s?o=s(t,n):o=$.isURLSearchParams(t)?t.toString():new Px(t,n).toString(r),o){const a=e.indexOf("#");a!==-1&&(e=e.slice(0,a)),e+=(e.indexOf("?")===-1?"?":"&")+o}return e}class z0{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){$.forEach(this.handlers,function(r){r!==null&&t(r)})}}const K_={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Z$=typeof URLSearchParams<"u"?URLSearchParams:Px,Y$=typeof FormData<"u"?FormData:null,X$=typeof Blob<"u"?Blob:null,e4={isBrowser:!0,classes:{URLSearchParams:Z$,FormData:Y$,Blob:X$},protocols:["http","https","file","blob","url","data"]},Mx=typeof window<"u"&&typeof document<"u",t4=(e=>Mx&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),n4=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",r4=Mx&&window.location.href||"http://localhost",s4=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Mx,hasStandardBrowserEnv:t4,hasStandardBrowserWebWorkerEnv:n4,origin:r4},Symbol.toStringTag,{value:"Module"})),ss={...s4,...e4};function o4(e,t){return sg(e,new ss.classes.URLSearchParams,Object.assign({visitor:function(n,r,s,o){return ss.isNode&&$.isBuffer(n)?(this.append(r,n.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)}},t))}function a4(e){return $.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function i4(e){const t={},n=Object.keys(e);let r;const s=n.length;let o;for(r=0;r=n.length;return a=!a&&$.isArray(s)?s.length:a,c?($.hasOwnProp(s,a)?s[a]=[s[a],r]:s[a]=r,!i):((!s[a]||!$.isObject(s[a]))&&(s[a]=[]),t(n,r,s[a],o)&&$.isArray(s[a])&&(s[a]=i4(s[a])),!i)}if($.isFormData(e)&&$.isFunction(e.entries)){const n={};return $.forEachEntry(e,(r,s)=>{t(a4(r),s,n,0)}),n}return null}function l4(e,t,n){if($.isString(e))try{return(t||JSON.parse)(e),$.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const zd={transitional:K_,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",s=r.indexOf("application/json")>-1,o=$.isObject(t);if(o&&$.isHTMLForm(t)&&(t=new FormData(t)),$.isFormData(t))return s?JSON.stringify(q_(t)):t;if($.isArrayBuffer(t)||$.isBuffer(t)||$.isStream(t)||$.isFile(t)||$.isBlob(t)||$.isReadableStream(t))return t;if($.isArrayBufferView(t))return t.buffer;if($.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let i;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return o4(t,this.formSerializer).toString();if((i=$.isFileList(t))||r.indexOf("multipart/form-data")>-1){const c=this.env&&this.env.FormData;return sg(i?{"files[]":t}:t,c&&new c,this.formSerializer)}}return o||s?(n.setContentType("application/json",!1),l4(t)):t}],transformResponse:[function(t){const n=this.transitional||zd.transitional,r=n&&n.forcedJSONParsing,s=this.responseType==="json";if($.isResponse(t)||$.isReadableStream(t))return t;if(t&&$.isString(t)&&(r&&!this.responseType||s)){const a=!(n&&n.silentJSONParsing)&&s;try{return JSON.parse(t)}catch(i){if(a)throw i.name==="SyntaxError"?He.from(i,He.ERR_BAD_RESPONSE,this,null,this.response):i}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ss.classes.FormData,Blob:ss.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};$.forEach(["delete","get","head","post","put","patch"],e=>{zd.headers[e]={}});const u4=$.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),c4=e=>{const t={};let n,r,s;return e&&e.split(` +`).forEach(function(a){s=a.indexOf(":"),n=a.substring(0,s).trim().toLowerCase(),r=a.substring(s+1).trim(),!(!n||t[n]&&u4[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},U0=Symbol("internals");function Gu(e){return e&&String(e).trim().toLowerCase()}function pp(e){return e===!1||e==null?e:$.isArray(e)?e.map(pp):String(e)}function d4(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const f4=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Lm(e,t,n,r,s){if($.isFunction(r))return r.call(this,t,n);if(s&&(t=n),!!$.isString(t)){if($.isString(r))return t.indexOf(r)!==-1;if($.isRegExp(r))return r.test(t)}}function p4(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function h4(e,t){const n=$.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(s,o,a){return this[r].call(this,t,s,o,a)},configurable:!0})})}let sr=class{constructor(t){t&&this.set(t)}set(t,n,r){const s=this;function o(i,c,l){const d=Gu(c);if(!d)throw new Error("header name must be a non-empty string");const p=$.findKey(s,d);(!p||s[p]===void 0||l===!0||l===void 0&&s[p]!==!1)&&(s[p||c]=pp(i))}const a=(i,c)=>$.forEach(i,(l,d)=>o(l,d,c));if($.isPlainObject(t)||t instanceof this.constructor)a(t,n);else if($.isString(t)&&(t=t.trim())&&!f4(t))a(c4(t),n);else if($.isHeaders(t))for(const[i,c]of t.entries())o(c,i,r);else t!=null&&o(n,t,r);return this}get(t,n){if(t=Gu(t),t){const r=$.findKey(this,t);if(r){const s=this[r];if(!n)return s;if(n===!0)return d4(s);if($.isFunction(n))return n.call(this,s,r);if($.isRegExp(n))return n.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=Gu(t),t){const r=$.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||Lm(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let s=!1;function o(a){if(a=Gu(a),a){const i=$.findKey(r,a);i&&(!n||Lm(r,r[i],i,n))&&(delete r[i],s=!0)}}return $.isArray(t)?t.forEach(o):o(t),s}clear(t){const n=Object.keys(this);let r=n.length,s=!1;for(;r--;){const o=n[r];(!t||Lm(this,this[o],o,t,!0))&&(delete this[o],s=!0)}return s}normalize(t){const n=this,r={};return $.forEach(this,(s,o)=>{const a=$.findKey(r,o);if(a){n[a]=pp(s),delete n[o];return}const i=t?p4(o):String(o).trim();i!==o&&delete n[o],n[i]=pp(s),r[i]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return $.forEach(this,(r,s)=>{r!=null&&r!==!1&&(n[s]=t&&$.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(s=>r.set(s)),r}static accessor(t){const r=(this[U0]=this[U0]={accessors:{}}).accessors,s=this.prototype;function o(a){const i=Gu(a);r[i]||(h4(s,a),r[i]=!0)}return $.isArray(t)?t.forEach(o):o(t),this}};sr.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);$.reduceDescriptors(sr.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});$.freezeMethods(sr);function $m(e,t){const n=this||zd,r=t||n,s=sr.from(r.headers);let o=r.data;return $.forEach(e,function(i){o=i.call(n,o,s.normalize(),t?t.status:void 0)}),s.normalize(),o}function W_(e){return!!(e&&e.__CANCEL__)}function gu(e,t,n){He.call(this,e??"canceled",He.ERR_CANCELED,t,n),this.name="CanceledError"}$.inherits(gu,He,{__CANCEL__:!0});function G_(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new He("Request failed with status code "+n.status,[He.ERR_BAD_REQUEST,He.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function g4(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function m4(e,t){e=e||10;const n=new Array(e),r=new Array(e);let s=0,o=0,a;return t=t!==void 0?t:1e3,function(c){const l=Date.now(),d=r[o];a||(a=l),n[s]=c,r[s]=l;let p=o,f=0;for(;p!==s;)f+=n[p++],p=p%e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),l-ar)return s&&(clearTimeout(s),s=null),n=i,e.apply(null,arguments);s||(s=setTimeout(()=>(s=null,n=Date.now(),e.apply(null,arguments)),r-(i-n)))}}const eh=(e,t,n=3)=>{let r=0;const s=m4(50,250);return v4(o=>{const a=o.loaded,i=o.lengthComputable?o.total:void 0,c=a-r,l=s(c),d=a<=i;r=a;const p={loaded:a,total:i,progress:i?a/i:void 0,bytes:c,rate:l||void 0,estimated:l&&i&&d?(i-a)/l:void 0,event:o,lengthComputable:i!=null};p[t?"download":"upload"]=!0,e(p)},n)},y4=ss.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function s(o){let a=o;return t&&(n.setAttribute("href",a),a=n.href),n.setAttribute("href",a),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=s(window.location.href),function(a){const i=$.isString(a)?s(a):a;return i.protocol===r.protocol&&i.host===r.host}}():function(){return function(){return!0}}(),b4=ss.hasStandardBrowserEnv?{write(e,t,n,r,s,o){const a=[e+"="+encodeURIComponent(t)];$.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),$.isString(r)&&a.push("path="+r),$.isString(s)&&a.push("domain="+s),o===!0&&a.push("secure"),document.cookie=a.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function x4(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function w4(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function J_(e,t){return e&&!x4(t)?w4(e,t):t}const V0=e=>e instanceof sr?{...e}:e;function Si(e,t){t=t||{};const n={};function r(l,d,p){return $.isPlainObject(l)&&$.isPlainObject(d)?$.merge.call({caseless:p},l,d):$.isPlainObject(d)?$.merge({},d):$.isArray(d)?d.slice():d}function s(l,d,p){if($.isUndefined(d)){if(!$.isUndefined(l))return r(void 0,l,p)}else return r(l,d,p)}function o(l,d){if(!$.isUndefined(d))return r(void 0,d)}function a(l,d){if($.isUndefined(d)){if(!$.isUndefined(l))return r(void 0,l)}else return r(void 0,d)}function i(l,d,p){if(p in t)return r(l,d);if(p in e)return r(void 0,l)}const c={url:o,method:o,data:o,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:i,headers:(l,d)=>s(V0(l),V0(d),!0)};return $.forEach(Object.keys(Object.assign({},e,t)),function(d){const p=c[d]||s,f=p(e[d],t[d],d);$.isUndefined(f)&&p!==i||(n[d]=f)}),n}const Q_=e=>{const t=Si({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:i}=t;t.headers=a=sr.from(a),t.url=H_(J_(t.baseURL,t.url),e.params,e.paramsSerializer),i&&a.set("Authorization","Basic "+btoa((i.username||"")+":"+(i.password?unescape(encodeURIComponent(i.password)):"")));let c;if($.isFormData(n)){if(ss.hasStandardBrowserEnv||ss.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if((c=a.getContentType())!==!1){const[l,...d]=c?c.split(";").map(p=>p.trim()).filter(Boolean):[];a.setContentType([l||"multipart/form-data",...d].join("; "))}}if(ss.hasStandardBrowserEnv&&(r&&$.isFunction(r)&&(r=r(t)),r||r!==!1&&y4(t.url))){const l=s&&o&&b4.read(o);l&&a.set(s,l)}return t},S4=typeof XMLHttpRequest<"u",C4=S4&&function(e){return new Promise(function(n,r){const s=Q_(e);let o=s.data;const a=sr.from(s.headers).normalize();let{responseType:i}=s,c;function l(){s.cancelToken&&s.cancelToken.unsubscribe(c),s.signal&&s.signal.removeEventListener("abort",c)}let d=new XMLHttpRequest;d.open(s.method.toUpperCase(),s.url,!0),d.timeout=s.timeout;function p(){if(!d)return;const h=sr.from("getAllResponseHeaders"in d&&d.getAllResponseHeaders()),m={data:!i||i==="text"||i==="json"?d.responseText:d.response,status:d.status,statusText:d.statusText,headers:h,config:e,request:d};G_(function(b){n(b),l()},function(b){r(b),l()},m),d=null}"onloadend"in d?d.onloadend=p:d.onreadystatechange=function(){!d||d.readyState!==4||d.status===0&&!(d.responseURL&&d.responseURL.indexOf("file:")===0)||setTimeout(p)},d.onabort=function(){d&&(r(new He("Request aborted",He.ECONNABORTED,s,d)),d=null)},d.onerror=function(){r(new He("Network Error",He.ERR_NETWORK,s,d)),d=null},d.ontimeout=function(){let g=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const m=s.transitional||K_;s.timeoutErrorMessage&&(g=s.timeoutErrorMessage),r(new He(g,m.clarifyTimeoutError?He.ETIMEDOUT:He.ECONNABORTED,s,d)),d=null},o===void 0&&a.setContentType(null),"setRequestHeader"in d&&$.forEach(a.toJSON(),function(g,m){d.setRequestHeader(m,g)}),$.isUndefined(s.withCredentials)||(d.withCredentials=!!s.withCredentials),i&&i!=="json"&&(d.responseType=s.responseType),typeof s.onDownloadProgress=="function"&&d.addEventListener("progress",eh(s.onDownloadProgress,!0)),typeof s.onUploadProgress=="function"&&d.upload&&d.upload.addEventListener("progress",eh(s.onUploadProgress)),(s.cancelToken||s.signal)&&(c=h=>{d&&(r(!h||h.type?new gu(null,e,d):h),d.abort(),d=null)},s.cancelToken&&s.cancelToken.subscribe(c),s.signal&&(s.signal.aborted?c():s.signal.addEventListener("abort",c)));const f=g4(s.url);if(f&&ss.protocols.indexOf(f)===-1){r(new He("Unsupported protocol "+f+":",He.ERR_BAD_REQUEST,e));return}d.send(o||null)})},E4=(e,t)=>{let n=new AbortController,r;const s=function(c){if(!r){r=!0,a();const l=c instanceof Error?c:this.reason;n.abort(l instanceof He?l:new gu(l instanceof Error?l.message:l))}};let o=t&&setTimeout(()=>{s(new He(`timeout ${t} of ms exceeded`,He.ETIMEDOUT))},t);const a=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(c=>{c&&(c.removeEventListener?c.removeEventListener("abort",s):c.unsubscribe(s))}),e=null)};e.forEach(c=>c&&c.addEventListener&&c.addEventListener("abort",s));const{signal:i}=n;return i.unsubscribe=a,[i,()=>{o&&clearTimeout(o),o=null}]},T4=function*(e,t){let n=e.byteLength;if(!t||n{const o=k4(e,t,s);let a=0;return new ReadableStream({type:"bytes",async pull(i){const{done:c,value:l}=await o.next();if(c){i.close(),r();return}let d=l.byteLength;n&&n(a+=d),i.enqueue(new Uint8Array(l))},cancel(i){return r(i),o.return()}},{highWaterMark:2})},K0=(e,t)=>{const n=e!=null;return r=>setTimeout(()=>t({lengthComputable:n,total:e,loaded:r}))},og=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",Z_=og&&typeof ReadableStream=="function",Ly=og&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),_4=Z_&&(()=>{let e=!1;const t=new Request(ss.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})(),q0=64*1024,$y=Z_&&!!(()=>{try{return $.isReadableStream(new Response("").body)}catch{}})(),th={stream:$y&&(e=>e.body)};og&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!th[t]&&(th[t]=$.isFunction(e[t])?n=>n[t]():(n,r)=>{throw new He(`Response type '${t}' is not supported`,He.ERR_NOT_SUPPORT,r)})})})(new Response);const j4=async e=>{if(e==null)return 0;if($.isBlob(e))return e.size;if($.isSpecCompliantForm(e))return(await new Request(e).arrayBuffer()).byteLength;if($.isArrayBufferView(e))return e.byteLength;if($.isURLSearchParams(e)&&(e=e+""),$.isString(e))return(await Ly(e)).byteLength},R4=async(e,t)=>{const n=$.toFiniteNumber(e.getContentLength());return n??j4(t)},O4=og&&(async e=>{let{url:t,method:n,data:r,signal:s,cancelToken:o,timeout:a,onDownloadProgress:i,onUploadProgress:c,responseType:l,headers:d,withCredentials:p="same-origin",fetchOptions:f}=Q_(e);l=l?(l+"").toLowerCase():"text";let[h,g]=s||o||a?E4([s,o],a):[],m,x;const b=()=>{!m&&setTimeout(()=>{h&&h.unsubscribe()}),m=!0};let y;try{if(c&&_4&&n!=="get"&&n!=="head"&&(y=await R4(d,r))!==0){let C=new Request(t,{method:"POST",body:r,duplex:"half"}),k;$.isFormData(r)&&(k=C.headers.get("content-type"))&&d.setContentType(k),C.body&&(r=H0(C.body,q0,K0(y,eh(c)),null,Ly))}$.isString(p)||(p=p?"cors":"omit"),x=new Request(t,{...f,signal:h,method:n.toUpperCase(),headers:d.normalize().toJSON(),body:r,duplex:"half",withCredentials:p});let w=await fetch(x);const S=$y&&(l==="stream"||l==="response");if($y&&(i||S)){const C={};["status","statusText","headers"].forEach(T=>{C[T]=w[T]});const k=$.toFiniteNumber(w.headers.get("content-length"));w=new Response(H0(w.body,q0,i&&K0(k,eh(i,!0)),S&&b,Ly),C)}l=l||"text";let E=await th[$.findKey(th,l)||"text"](w,e);return!S&&b(),g&&g(),await new Promise((C,k)=>{G_(C,k,{data:E,headers:sr.from(w.headers),status:w.status,statusText:w.statusText,config:e,request:x})})}catch(w){throw b(),w&&w.name==="TypeError"&&/fetch/i.test(w.message)?Object.assign(new He("Network Error",He.ERR_NETWORK,e,x),{cause:w.cause||w}):He.from(w,w&&w.code,e,x)}}),By={http:W$,xhr:C4,fetch:O4};$.forEach(By,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const W0=e=>`- ${e}`,N4=e=>$.isFunction(e)||e===null||e===!1,Y_={getAdapter:e=>{e=$.isArray(e)?e:[e];const{length:t}=e;let n,r;const s={};for(let o=0;o`adapter ${i} `+(c===!1?"is not supported by the environment":"is not available in the build"));let a=t?o.length>1?`since : +`+o.map(W0).join(` +`):" "+W0(o[0]):"as no adapter specified";throw new He("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return r},adapters:By};function Bm(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new gu(null,e)}function G0(e){return Bm(e),e.headers=sr.from(e.headers),e.data=$m.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Y_.getAdapter(e.adapter||zd.adapter)(e).then(function(r){return Bm(e),r.data=$m.call(e,e.transformResponse,r),r.headers=sr.from(r.headers),r},function(r){return W_(r)||(Bm(e),r&&r.response&&(r.response.data=$m.call(e,e.transformResponse,r.response),r.response.headers=sr.from(r.response.headers))),Promise.reject(r)})}const X_="1.7.2",Ix={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Ix[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const J0={};Ix.transitional=function(t,n,r){function s(o,a){return"[Axios v"+X_+"] Transitional option '"+o+"'"+a+(r?". "+r:"")}return(o,a,i)=>{if(t===!1)throw new He(s(a," has been removed"+(n?" in "+n:"")),He.ERR_DEPRECATED);return n&&!J0[a]&&(J0[a]=!0,console.warn(s(a," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(o,a,i):!0}};function P4(e,t,n){if(typeof e!="object")throw new He("options must be an object",He.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let s=r.length;for(;s-- >0;){const o=r[s],a=t[o];if(a){const i=e[o],c=i===void 0||a(i,o,e);if(c!==!0)throw new He("option "+o+" must be "+c,He.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new He("Unknown option "+o,He.ERR_BAD_OPTION)}}const zy={assertOptions:P4,validators:Ix},Po=zy.validators;let di=class{constructor(t){this.defaults=t,this.interceptors={request:new z0,response:new z0}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let s;Error.captureStackTrace?Error.captureStackTrace(s={}):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";try{r.stack?o&&!String(r.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(r.stack+=` +`+o):r.stack=o}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Si(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&zy.assertOptions(r,{silentJSONParsing:Po.transitional(Po.boolean),forcedJSONParsing:Po.transitional(Po.boolean),clarifyTimeoutError:Po.transitional(Po.boolean)},!1),s!=null&&($.isFunction(s)?n.paramsSerializer={serialize:s}:zy.assertOptions(s,{encode:Po.function,serialize:Po.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let a=o&&$.merge(o.common,o[n.method]);o&&$.forEach(["delete","get","head","post","put","patch","common"],g=>{delete o[g]}),n.headers=sr.concat(a,o);const i=[];let c=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(c=c&&m.synchronous,i.unshift(m.fulfilled,m.rejected))});const l=[];this.interceptors.response.forEach(function(m){l.push(m.fulfilled,m.rejected)});let d,p=0,f;if(!c){const g=[G0.bind(this),void 0];for(g.unshift.apply(g,i),g.push.apply(g,l),f=g.length,d=Promise.resolve(n);p{if(!r._listeners)return;let o=r._listeners.length;for(;o-- >0;)r._listeners[o](s);r._listeners=null}),this.promise.then=s=>{let o;const a=new Promise(i=>{r.subscribe(i),o=i}).then(s);return a.cancel=function(){r.unsubscribe(o)},a},t(function(o,a,i){r.reason||(r.reason=new gu(o,a,i),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ej(function(s){t=s}),cancel:t}}};function I4(e){return function(n){return e.apply(null,n)}}function D4(e){return $.isObject(e)&&e.isAxiosError===!0}const Uy={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Uy).forEach(([e,t])=>{Uy[t]=e});function tj(e){const t=new di(e),n=P_(di.prototype.request,t);return $.extend(n,di.prototype,t,{allOwnKeys:!0}),$.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return tj(Si(e,s))},n}const zt=tj(zd);zt.Axios=di;zt.CanceledError=gu;zt.CancelToken=M4;zt.isCancel=W_;zt.VERSION=X_;zt.toFormData=sg;zt.AxiosError=He;zt.Cancel=zt.CanceledError;zt.all=function(t){return Promise.all(t)};zt.spread=I4;zt.isAxiosError=D4;zt.mergeConfig=Si;zt.AxiosHeaders=sr;zt.formToJSON=e=>q_($.isHTMLForm(e)?new FormData(e):e);zt.getAdapter=Y_.getAdapter;zt.HttpStatusCode=Uy;zt.default=zt;const{Axios:Nse,AxiosError:Pse,CanceledError:Mse,isCancel:Ise,CancelToken:Dse,VERSION:Ase,all:Fse,Cancel:Lse,isAxiosError:A4,spread:$se,toFormData:Bse,AxiosHeaders:zse,HttpStatusCode:Use,formToJSON:Vse,getAdapter:Hse,mergeConfig:Kse}=zt,F4=e=>["auth","verifyServer",JSON.stringify(e)],nj=async({url:e})=>(await zt.get(`${e}/`)).data,L4=e=>{const{url:t,...n}=e;return lt({...n,queryKey:F4({url:t}),queryFn:()=>nj({url:t}),enabled:!!t})};function $4(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function ag(...e){return t=>e.forEach(n=>$4(n,t))}function it(...e){return v.useCallback(ag(...e),e)}var mo=v.forwardRef((e,t)=>{const{children:n,...r}=e,s=v.Children.toArray(n),o=s.find(z4);if(o){const a=o.props.children,i=s.map(c=>c===o?v.Children.count(a)>1?v.Children.only(null):v.isValidElement(a)?a.props.children:null:c);return u.jsx(Vy,{...r,ref:t,children:v.isValidElement(a)?v.cloneElement(a,void 0,i):null})}return u.jsx(Vy,{...r,ref:t,children:n})});mo.displayName="Slot";var Vy=v.forwardRef((e,t)=>{const{children:n,...r}=e;if(v.isValidElement(n)){const s=V4(n);return v.cloneElement(n,{...U4(r,n.props),ref:t?ag(t,s):s})}return v.Children.count(n)>1?v.Children.only(null):null});Vy.displayName="SlotClone";var B4=({children:e})=>u.jsx(u.Fragment,{children:e});function z4(e){return v.isValidElement(e)&&e.type===B4}function U4(e,t){const n={...t};for(const r in t){const s=e[r],o=t[r];/^on[A-Z]/.test(r)?s&&o?n[r]=(...i)=>{o(...i),s(...i)}:s&&(n[r]=s):r==="style"?n[r]={...s,...o}:r==="className"&&(n[r]=[s,o].filter(Boolean).join(" "))}return{...e,...n}}function V4(e){var r,s;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function rj(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;ttypeof e=="boolean"?"".concat(e):e===0?"0":e,Z0=H4,ig=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return Z0(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:s,defaultVariants:o}=t,a=Object.keys(s).map(l=>{const d=n==null?void 0:n[l],p=o==null?void 0:o[l];if(d===null)return null;const f=Q0(d)||Q0(p);return s[l][f]}),i=n&&Object.entries(n).reduce((l,d)=>{let[p,f]=d;return f===void 0||(l[p]=f),l},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((l,d)=>{let{class:p,className:f,...h}=d;return Object.entries(h).every(g=>{let[m,x]=g;return Array.isArray(x)?x.includes({...o,...i}[m]):{...o,...i}[m]===x})?[...l,p,f]:l},[]);return Z0(e,a,c,n==null?void 0:n.class,n==null?void 0:n.className)},Dx="-";function K4(e){const t=W4(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;function s(a){const i=a.split(Dx);return i[0]===""&&i.length!==1&&i.shift(),sj(i,t)||q4(a)}function o(a,i){const c=n[a]||[];return i&&r[a]?[...c,...r[a]]:c}return{getClassGroupId:s,getConflictingClassGroupIds:o}}function sj(e,t){var a;if(e.length===0)return t.classGroupId;const n=e[0],r=t.nextPart.get(n),s=r?sj(e.slice(1),r):void 0;if(s)return s;if(t.validators.length===0)return;const o=e.join(Dx);return(a=t.validators.find(({validator:i})=>i(o)))==null?void 0:a.classGroupId}const Y0=/^\[(.+)\]$/;function q4(e){if(Y0.test(e)){const t=Y0.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function W4(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return J4(Object.entries(e.classGroups),n).forEach(([o,a])=>{Hy(a,r,o,t)}),r}function Hy(e,t,n,r){e.forEach(s=>{if(typeof s=="string"){const o=s===""?t:X0(t,s);o.classGroupId=n;return}if(typeof s=="function"){if(G4(s)){Hy(s(r),t,n,r);return}t.validators.push({validator:s,classGroupId:n});return}Object.entries(s).forEach(([o,a])=>{Hy(a,X0(t,o),n,r)})})}function X0(e,t){let n=e;return t.split(Dx).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function G4(e){return e.isThemeGetter}function J4(e,t){return t?e.map(([n,r])=>{const s=r.map(o=>typeof o=="string"?t+o:typeof o=="object"?Object.fromEntries(Object.entries(o).map(([a,i])=>[t+a,i])):o);return[n,s]}):e}function Q4(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function s(o,a){n.set(o,a),t++,t>e&&(t=0,r=n,n=new Map)}return{get(o){let a=n.get(o);if(a!==void 0)return a;if((a=r.get(o))!==void 0)return s(o,a),a},set(o,a){n.has(o)?n.set(o,a):s(o,a)}}}const oj="!";function Z4(e){const{separator:t,experimentalParseClassName:n}=e,r=t.length===1,s=t[0],o=t.length;function a(i){const c=[];let l=0,d=0,p;for(let x=0;xd?p-d:void 0;return{modifiers:c,hasImportantModifier:h,baseClassName:g,maybePostfixModifierPosition:m}}return n?function(c){return n({className:c,parseClassName:a})}:a}function Y4(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function X4(e){return{cache:Q4(e.cacheSize),parseClassName:Z4(e),...K4(e)}}const e3=/\s+/;function t3(e,t){const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:s}=t,o=new Set;return e.trim().split(e3).map(a=>{const{modifiers:i,hasImportantModifier:c,baseClassName:l,maybePostfixModifierPosition:d}=n(a);let p=!!d,f=r(p?l.substring(0,d):l);if(!f){if(!p)return{isTailwindClass:!1,originalClassName:a};if(f=r(l),!f)return{isTailwindClass:!1,originalClassName:a};p=!1}const h=Y4(i).join(":");return{isTailwindClass:!0,modifierId:c?h+oj:h,classGroupId:f,originalClassName:a,hasPostfixModifier:p}}).reverse().filter(a=>{if(!a.isTailwindClass)return!0;const{modifierId:i,classGroupId:c,hasPostfixModifier:l}=a,d=i+c;return o.has(d)?!1:(o.add(d),s(c,l).forEach(p=>o.add(i+p)),!0)}).reverse().map(a=>a.originalClassName).join(" ")}function n3(){let e=0,t,n,r="";for(;ep(d),e());return n=X4(l),r=n.cache.get,s=n.cache.set,o=i,i(c)}function i(c){const l=r(c);if(l)return l;const d=t3(c,n);return s(c,d),d}return function(){return o(n3.apply(null,arguments))}}function _t(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const ij=/^\[(?:([a-z-]+):)?(.+)\]$/i,s3=/^\d+\/\d+$/,o3=new Set(["px","full","screen"]),a3=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,i3=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,l3=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,u3=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,c3=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function qs(e){return Ga(e)||o3.has(e)||s3.test(e)}function Mo(e){return mu(e,"length",y3)}function Ga(e){return!!e&&!Number.isNaN(Number(e))}function Of(e){return mu(e,"number",Ga)}function Ju(e){return!!e&&Number.isInteger(Number(e))}function d3(e){return e.endsWith("%")&&Ga(e.slice(0,-1))}function We(e){return ij.test(e)}function Io(e){return a3.test(e)}const f3=new Set(["length","size","percentage"]);function p3(e){return mu(e,f3,lj)}function h3(e){return mu(e,"position",lj)}const g3=new Set(["image","url"]);function m3(e){return mu(e,g3,x3)}function v3(e){return mu(e,"",b3)}function Qu(){return!0}function mu(e,t,n){const r=ij.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function y3(e){return i3.test(e)&&!l3.test(e)}function lj(){return!1}function b3(e){return u3.test(e)}function x3(e){return c3.test(e)}function w3(){const e=_t("colors"),t=_t("spacing"),n=_t("blur"),r=_t("brightness"),s=_t("borderColor"),o=_t("borderRadius"),a=_t("borderSpacing"),i=_t("borderWidth"),c=_t("contrast"),l=_t("grayscale"),d=_t("hueRotate"),p=_t("invert"),f=_t("gap"),h=_t("gradientColorStops"),g=_t("gradientColorStopPositions"),m=_t("inset"),x=_t("margin"),b=_t("opacity"),y=_t("padding"),w=_t("saturate"),S=_t("scale"),E=_t("sepia"),C=_t("skew"),k=_t("space"),T=_t("translate"),O=()=>["auto","contain","none"],M=()=>["auto","hidden","clip","visible","scroll"],U=()=>["auto",We,t],I=()=>[We,t],J=()=>["",qs,Mo],V=()=>["auto",Ga,We],G=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],ee=()=>["solid","dashed","dotted","double","none"],q=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],F=()=>["start","end","center","between","around","evenly","stretch"],A=()=>["","0",We],Y=()=>["auto","avoid","all","avoid-page","page","left","right","column"],de=()=>[Ga,Of],z=()=>[Ga,We];return{cacheSize:500,separator:":",theme:{colors:[Qu],spacing:[qs,Mo],blur:["none","",Io,We],brightness:de(),borderColor:[e],borderRadius:["none","","full",Io,We],borderSpacing:I(),borderWidth:J(),contrast:de(),grayscale:A(),hueRotate:z(),invert:A(),gap:I(),gradientColorStops:[e],gradientColorStopPositions:[d3,Mo],inset:U(),margin:U(),opacity:de(),padding:I(),saturate:de(),scale:de(),sepia:A(),skew:z(),space:I(),translate:I()},classGroups:{aspect:[{aspect:["auto","square","video",We]}],container:["container"],columns:[{columns:[Io]}],"break-after":[{"break-after":Y()}],"break-before":[{"break-before":Y()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...G(),We]}],overflow:[{overflow:M()}],"overflow-x":[{"overflow-x":M()}],"overflow-y":[{"overflow-y":M()}],overscroll:[{overscroll:O()}],"overscroll-x":[{"overscroll-x":O()}],"overscroll-y":[{"overscroll-y":O()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[m]}],"inset-x":[{"inset-x":[m]}],"inset-y":[{"inset-y":[m]}],start:[{start:[m]}],end:[{end:[m]}],top:[{top:[m]}],right:[{right:[m]}],bottom:[{bottom:[m]}],left:[{left:[m]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Ju,We]}],basis:[{basis:U()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",We]}],grow:[{grow:A()}],shrink:[{shrink:A()}],order:[{order:["first","last","none",Ju,We]}],"grid-cols":[{"grid-cols":[Qu]}],"col-start-end":[{col:["auto",{span:["full",Ju,We]},We]}],"col-start":[{"col-start":V()}],"col-end":[{"col-end":V()}],"grid-rows":[{"grid-rows":[Qu]}],"row-start-end":[{row:["auto",{span:[Ju,We]},We]}],"row-start":[{"row-start":V()}],"row-end":[{"row-end":V()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",We]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",We]}],gap:[{gap:[f]}],"gap-x":[{"gap-x":[f]}],"gap-y":[{"gap-y":[f]}],"justify-content":[{justify:["normal",...F()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...F(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...F(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[y]}],px:[{px:[y]}],py:[{py:[y]}],ps:[{ps:[y]}],pe:[{pe:[y]}],pt:[{pt:[y]}],pr:[{pr:[y]}],pb:[{pb:[y]}],pl:[{pl:[y]}],m:[{m:[x]}],mx:[{mx:[x]}],my:[{my:[x]}],ms:[{ms:[x]}],me:[{me:[x]}],mt:[{mt:[x]}],mr:[{mr:[x]}],mb:[{mb:[x]}],ml:[{ml:[x]}],"space-x":[{"space-x":[k]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[k]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",We,t]}],"min-w":[{"min-w":[We,t,"min","max","fit"]}],"max-w":[{"max-w":[We,t,"none","full","min","max","fit","prose",{screen:[Io]},Io]}],h:[{h:[We,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[We,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[We,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[We,t,"auto","min","max","fit"]}],"font-size":[{text:["base",Io,Mo]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Of]}],"font-family":[{font:[Qu]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",We]}],"line-clamp":[{"line-clamp":["none",Ga,Of]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",qs,We]}],"list-image":[{"list-image":["none",We]}],"list-style-type":[{list:["none","disc","decimal",We]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[b]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[b]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ee(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",qs,Mo]}],"underline-offset":[{"underline-offset":["auto",qs,We]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:I()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",We]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",We]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[b]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...G(),h3]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",p3]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},m3]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[h]}],"gradient-via":[{via:[h]}],"gradient-to":[{to:[h]}],rounded:[{rounded:[o]}],"rounded-s":[{"rounded-s":[o]}],"rounded-e":[{"rounded-e":[o]}],"rounded-t":[{"rounded-t":[o]}],"rounded-r":[{"rounded-r":[o]}],"rounded-b":[{"rounded-b":[o]}],"rounded-l":[{"rounded-l":[o]}],"rounded-ss":[{"rounded-ss":[o]}],"rounded-se":[{"rounded-se":[o]}],"rounded-ee":[{"rounded-ee":[o]}],"rounded-es":[{"rounded-es":[o]}],"rounded-tl":[{"rounded-tl":[o]}],"rounded-tr":[{"rounded-tr":[o]}],"rounded-br":[{"rounded-br":[o]}],"rounded-bl":[{"rounded-bl":[o]}],"border-w":[{border:[i]}],"border-w-x":[{"border-x":[i]}],"border-w-y":[{"border-y":[i]}],"border-w-s":[{"border-s":[i]}],"border-w-e":[{"border-e":[i]}],"border-w-t":[{"border-t":[i]}],"border-w-r":[{"border-r":[i]}],"border-w-b":[{"border-b":[i]}],"border-w-l":[{"border-l":[i]}],"border-opacity":[{"border-opacity":[b]}],"border-style":[{border:[...ee(),"hidden"]}],"divide-x":[{"divide-x":[i]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[i]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[b]}],"divide-style":[{divide:ee()}],"border-color":[{border:[s]}],"border-color-x":[{"border-x":[s]}],"border-color-y":[{"border-y":[s]}],"border-color-t":[{"border-t":[s]}],"border-color-r":[{"border-r":[s]}],"border-color-b":[{"border-b":[s]}],"border-color-l":[{"border-l":[s]}],"divide-color":[{divide:[s]}],"outline-style":[{outline:["",...ee()]}],"outline-offset":[{"outline-offset":[qs,We]}],"outline-w":[{outline:[qs,Mo]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:J()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[b]}],"ring-offset-w":[{"ring-offset":[qs,Mo]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Io,v3]}],"shadow-color":[{shadow:[Qu]}],opacity:[{opacity:[b]}],"mix-blend":[{"mix-blend":[...q(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":q()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",Io,We]}],grayscale:[{grayscale:[l]}],"hue-rotate":[{"hue-rotate":[d]}],invert:[{invert:[p]}],saturate:[{saturate:[w]}],sepia:[{sepia:[E]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[l]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[d]}],"backdrop-invert":[{"backdrop-invert":[p]}],"backdrop-opacity":[{"backdrop-opacity":[b]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[E]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[a]}],"border-spacing-x":[{"border-spacing-x":[a]}],"border-spacing-y":[{"border-spacing-y":[a]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",We]}],duration:[{duration:z()}],ease:[{ease:["linear","in","out","in-out",We]}],delay:[{delay:z()}],animate:[{animate:["none","spin","ping","pulse","bounce",We]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[S]}],"scale-x":[{"scale-x":[S]}],"scale-y":[{"scale-y":[S]}],rotate:[{rotate:[Ju,We]}],"translate-x":[{"translate-x":[T]}],"translate-y":[{"translate-y":[T]}],"skew-x":[{"skew-x":[C]}],"skew-y":[{"skew-y":[C]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",We]}],accent:[{accent:["auto",e]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",We]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":I()}],"scroll-mx":[{"scroll-mx":I()}],"scroll-my":[{"scroll-my":I()}],"scroll-ms":[{"scroll-ms":I()}],"scroll-me":[{"scroll-me":I()}],"scroll-mt":[{"scroll-mt":I()}],"scroll-mr":[{"scroll-mr":I()}],"scroll-mb":[{"scroll-mb":I()}],"scroll-ml":[{"scroll-ml":I()}],"scroll-p":[{"scroll-p":I()}],"scroll-px":[{"scroll-px":I()}],"scroll-py":[{"scroll-py":I()}],"scroll-ps":[{"scroll-ps":I()}],"scroll-pe":[{"scroll-pe":I()}],"scroll-pt":[{"scroll-pt":I()}],"scroll-pr":[{"scroll-pr":I()}],"scroll-pb":[{"scroll-pb":I()}],"scroll-pl":[{"scroll-pl":I()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",We]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[qs,Mo,Of]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}}const S3=r3(w3);function ge(...e){return S3(oo(e))}const C3=ig("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",warning:"bg-amber-600 shadow-sm hover:bg-amber-600/90 data-active:bg-amber-600/90 text-foreground",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),K=v.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...s},o)=>{const a=r?mo:"button";return u.jsx(a,{className:ge(C3({variant:t,size:n,className:e})),ref:o,...s})});K.displayName="Button";function Ax(){const{t:e}=ze(),t=Fs(rs.API_URL),{data:n}=L4({url:t}),r=v.useMemo(()=>n==null?void 0:n.clientName,[n]),s=v.useMemo(()=>n==null?void 0:n.version,[n]),o=[{name:"Discord",url:"https://evolution-api.com/discord"},{name:"Postman",url:"https://evolution-api.com/postman"},{name:"GitHub",url:"https://github.com/EvolutionAPI/evolution-api"},{name:"Docs",url:"https://doc.evolution-api.com"}];return u.jsxs("footer",{className:"flex w-full flex-col items-center justify-between p-6 text-xs text-secondary-foreground sm:flex-row",children:[u.jsxs("div",{className:"flex items-center space-x-3 divide-x",children:[r&&r!==""&&u.jsxs("span",{children:[e("footer.clientName"),": ",u.jsx("strong",{children:r})]}),s&&s!==""&&u.jsxs("span",{className:"pl-3",children:[e("footer.version"),": ",u.jsx("strong",{children:s})]})]}),u.jsx("div",{className:"flex gap-2",children:o.map(a=>u.jsx(K,{variant:"link",asChild:!0,size:"sm",className:"text-xs",children:u.jsx("a",{href:a.url,target:"_blank",rel:"noopener noreferrer",children:a.name})},a.url))})]})}/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const E3=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),uj=(...e)=>e.filter((t,n,r)=>!!t&&r.indexOf(t)===n).join(" ");/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */var T3={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const k3=v.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:s="",children:o,iconNode:a,...i},c)=>v.createElement("svg",{ref:c,...T3,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:uj("lucide",s),...i},[...a.map(([l,d])=>v.createElement(l,d)),...Array.isArray(o)?o:[o]]));/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Xe=(e,t)=>{const n=v.forwardRef(({className:r,...s},o)=>v.createElement(k3,{ref:o,iconNode:t,className:uj(`lucide-${E3(e)}`,r),...s}));return n.displayName=`${e}`,n};/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const _3=Xe("ArrowUpDown",[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const j3=Xe("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const cj=Xe("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const lg=Xe("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const R3=Xe("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const O3=Xe("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const N3=Xe("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const P3=Xe("CircleHelp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ud=Xe("CircleStop",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{width:"6",height:"6",x:"9",y:"9",key:"1wrtvo"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const dj=Xe("CircleUser",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662",key:"154egf"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const M3=Xe("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Pi=Xe("Cog",[["path",{d:"M12 20a8 8 0 1 0 0-16 8 8 0 0 0 0 16Z",key:"sobvz5"}],["path",{d:"M12 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z",key:"11i496"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 22v-2",key:"1osdcq"}],["path",{d:"m17 20.66-1-1.73",key:"eq3orb"}],["path",{d:"M11 10.27 7 3.34",key:"16pf9h"}],["path",{d:"m20.66 17-1.73-1",key:"sg0v6f"}],["path",{d:"m3.34 7 1.73 1",key:"1ulond"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"m20.66 7-1.73 1",key:"1ow05n"}],["path",{d:"m3.34 17 1.73-1",key:"nuk764"}],["path",{d:"m17 3.34-1 1.73",key:"2wel8s"}],["path",{d:"m11 13.73-4 6.93",key:"794ttg"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const I3=Xe("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Vd=Xe("Delete",[["path",{d:"M10 5a2 2 0 0 0-1.344.519l-6.328 5.74a1 1 0 0 0 0 1.481l6.328 5.741A2 2 0 0 0 10 19h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2z",key:"1yo7s0"}],["path",{d:"m12 9 6 6",key:"anjzzh"}],["path",{d:"m18 9-6 6",key:"1fp51s"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const D3=Xe("DoorOpen",[["path",{d:"M13 4h3a2 2 0 0 1 2 2v14",key:"hrm0s9"}],["path",{d:"M2 20h3",key:"1gaodv"}],["path",{d:"M13 20h9",key:"s90cdi"}],["path",{d:"M10 12v.01",key:"vx6srw"}],["path",{d:"M13 4.562v16.157a1 1 0 0 1-1.242.97L5 20V5.562a2 2 0 0 1 1.515-1.94l4-1A2 2 0 0 1 13 4.561Z",key:"199qr4"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const vu=Xe("Ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const A3=Xe("EyeOff",[["path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24",key:"1jxqfv"}],["path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68",key:"9wicm4"}],["path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61",key:"1jreej"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const F3=Xe("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const L3=Xe("FileQuestion",[["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const $3=Xe("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const B3=Xe("IterationCcw",[["path",{d:"M20 10c0-4.4-3.6-8-8-8s-8 3.6-8 8 3.6 8 8 8h8",key:"4znkd0"}],["polyline",{points:"16 14 20 18 16 22",key:"11njsm"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const z3=Xe("Languages",[["path",{d:"m5 8 6 6",key:"1wu5hv"}],["path",{d:"m4 14 6-6 2-3",key:"1k1g8d"}],["path",{d:"M2 5h12",key:"or177f"}],["path",{d:"M7 2h1",key:"1t2jsx"}],["path",{d:"m22 22-5-10-5 10",key:"don7ne"}],["path",{d:"M14 18h6",key:"1m8k6r"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const U3=Xe("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const V3=Xe("LifeBuoy",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.93 4.93 4.24 4.24",key:"1ymg45"}],["path",{d:"m14.83 9.17 4.24-4.24",key:"1cb5xl"}],["path",{d:"m14.83 14.83 4.24 4.24",key:"q42g0n"}],["path",{d:"m9.17 14.83-4.24 4.24",key:"bqpfvv"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Hd=Xe("ListCollapse",[["path",{d:"m3 10 2.5-2.5L3 5",key:"i6eama"}],["path",{d:"m3 19 2.5-2.5L3 14",key:"w2gmor"}],["path",{d:"M10 6h11",key:"c7qv1k"}],["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 18h11",key:"11hvi2"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const H3=Xe("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ug=Xe("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const K3=Xe("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const q3=Xe("Paperclip",[["path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48",key:"1u3ebp"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Kd=Xe("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const qd=Xe("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Mi=Xe("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const fj=Xe("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Wd=Xe("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const W3=Xe("Sparkle",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const G3=Xe("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const J3=Xe("UsersRound",[["path",{d:"M18 21a8 8 0 0 0-16 0",key:"3ypg7q"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M22 20c0-3.37-2-6.5-4-8a5 5 0 0 0-.45-8.3",key:"10s06x"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Q3=Xe("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const pj=Xe("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]),he=zt.create({timeout:3e4});he.interceptors.request.use(async e=>{const t=Fs(rs.API_URL);if(t&&(e.baseURL=t.toString()),!e.headers.apiKey||e.headers.apiKey===""){const n=Fs(rs.TOKEN);n&&(e.headers.apikey=`${n}`)}return e},e=>Promise.reject(e));const Z3=e=>["instance","fetchInstance",JSON.stringify(e)],Y3=async({instanceId:e})=>{const t=await he.get("/instance/fetchInstances",{params:{instanceId:e}});return Array.isArray(t.data)?t.data[0]:t.data},hj=e=>{const{instanceId:t,...n}=e;return lt({...n,queryKey:Z3({instanceId:t}),queryFn:()=>Y3({instanceId:t}),enabled:!!t})};function Se(e,t,{checkForDefaultPrevented:n=!0}={}){return function(s){if(e==null||e(s),n===!1||!s.defaultPrevented)return t==null?void 0:t(s)}}function X3(e,t){const n=v.createContext(t);function r(o){const{children:a,...i}=o,c=v.useMemo(()=>i,Object.values(i));return u.jsx(n.Provider,{value:c,children:a})}function s(o){const a=v.useContext(n);if(a)return a;if(t!==void 0)return t;throw new Error(`\`${o}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,s]}function Vr(e,t=[]){let n=[];function r(o,a){const i=v.createContext(a),c=n.length;n=[...n,a];function l(p){const{scope:f,children:h,...g}=p,m=(f==null?void 0:f[e][c])||i,x=v.useMemo(()=>g,Object.values(g));return u.jsx(m.Provider,{value:x,children:h})}function d(p,f){const h=(f==null?void 0:f[e][c])||i,g=v.useContext(h);if(g)return g;if(a!==void 0)return a;throw new Error(`\`${p}\` must be used within \`${o}\``)}return l.displayName=o+"Provider",[l,d]}const s=()=>{const o=n.map(a=>v.createContext(a));return function(i){const c=(i==null?void 0:i[e])||o;return v.useMemo(()=>({[`__scope${e}`]:{...i,[e]:c}}),[i,c])}};return s.scopeName=e,[r,eB(s,...t)]}function eB(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(o){const a=r.reduce((i,{useScope:c,scopeName:l})=>{const p=c(o)[`__scope${l}`];return{...i,...p}},{});return v.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}function nn(e){const t=v.useRef(e);return v.useEffect(()=>{t.current=e}),v.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function pa({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,s]=tB({defaultProp:t,onChange:n}),o=e!==void 0,a=o?e:r,i=nn(n),c=v.useCallback(l=>{if(o){const p=typeof l=="function"?l(e):l;p!==e&&i(p)}else s(l)},[o,e,s,i]);return[a,c]}function tB({defaultProp:e,onChange:t}){const n=v.useState(e),[r]=n,s=v.useRef(r),o=nn(t);return v.useEffect(()=>{s.current!==r&&(o(r),s.current=r)},[r,s,o]),n}var nB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Me=nB.reduce((e,t)=>{const n=v.forwardRef((r,s)=>{const{asChild:o,...a}=r,i=o?mo:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(i,{...a,ref:s})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function gj(e,t){e&&ka.flushSync(()=>e.dispatchEvent(t))}function Fx(e){const t=e+"CollectionProvider",[n,r]=Vr(t),[s,o]=n(t,{collectionRef:{current:null},itemMap:new Map}),a=h=>{const{scope:g,children:m}=h,x=Te.useRef(null),b=Te.useRef(new Map).current;return u.jsx(s,{scope:g,itemMap:b,collectionRef:x,children:m})};a.displayName=t;const i=e+"CollectionSlot",c=Te.forwardRef((h,g)=>{const{scope:m,children:x}=h,b=o(i,m),y=it(g,b.collectionRef);return u.jsx(mo,{ref:y,children:x})});c.displayName=i;const l=e+"CollectionItemSlot",d="data-radix-collection-item",p=Te.forwardRef((h,g)=>{const{scope:m,children:x,...b}=h,y=Te.useRef(null),w=it(g,y),S=o(l,m);return Te.useEffect(()=>(S.itemMap.set(y,{ref:y,...b}),()=>void S.itemMap.delete(y))),u.jsx(mo,{[d]:"",ref:w,children:x})});p.displayName=l;function f(h){const g=o(e+"CollectionConsumer",h);return Te.useCallback(()=>{const x=g.collectionRef.current;if(!x)return[];const b=Array.from(x.querySelectorAll(`[${d}]`));return Array.from(g.itemMap.values()).sort((S,E)=>b.indexOf(S.ref.current)-b.indexOf(E.ref.current))},[g.collectionRef,g.itemMap])}return[{Provider:a,Slot:c,ItemSlot:p},f,r]}var rB=v.createContext(void 0);function Gd(e){const t=v.useContext(rB);return e||t||"ltr"}function sB(e,t=globalThis==null?void 0:globalThis.document){const n=nn(e);v.useEffect(()=>{const r=s=>{s.key==="Escape"&&n(s)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var oB="DismissableLayer",Ky="dismissableLayer.update",aB="dismissableLayer.pointerDownOutside",iB="dismissableLayer.focusOutside",e1,mj=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),cg=v.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:o,onInteractOutside:a,onDismiss:i,...c}=e,l=v.useContext(mj),[d,p]=v.useState(null),f=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,h]=v.useState({}),g=it(t,k=>p(k)),m=Array.from(l.layers),[x]=[...l.layersWithOutsidePointerEventsDisabled].slice(-1),b=m.indexOf(x),y=d?m.indexOf(d):-1,w=l.layersWithOutsidePointerEventsDisabled.size>0,S=y>=b,E=cB(k=>{const T=k.target,O=[...l.branches].some(M=>M.contains(T));!S||O||(s==null||s(k),a==null||a(k),k.defaultPrevented||i==null||i())},f),C=dB(k=>{const T=k.target;[...l.branches].some(M=>M.contains(T))||(o==null||o(k),a==null||a(k),k.defaultPrevented||i==null||i())},f);return sB(k=>{y===l.layers.size-1&&(r==null||r(k),!k.defaultPrevented&&i&&(k.preventDefault(),i()))},f),v.useEffect(()=>{if(d)return n&&(l.layersWithOutsidePointerEventsDisabled.size===0&&(e1=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),l.layersWithOutsidePointerEventsDisabled.add(d)),l.layers.add(d),t1(),()=>{n&&l.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=e1)}},[d,f,n,l]),v.useEffect(()=>()=>{d&&(l.layers.delete(d),l.layersWithOutsidePointerEventsDisabled.delete(d),t1())},[d,l]),v.useEffect(()=>{const k=()=>h({});return document.addEventListener(Ky,k),()=>document.removeEventListener(Ky,k)},[]),u.jsx(Me.div,{...c,ref:g,style:{pointerEvents:w?S?"auto":"none":void 0,...e.style},onFocusCapture:Se(e.onFocusCapture,C.onFocusCapture),onBlurCapture:Se(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:Se(e.onPointerDownCapture,E.onPointerDownCapture)})});cg.displayName=oB;var lB="DismissableLayerBranch",uB=v.forwardRef((e,t)=>{const n=v.useContext(mj),r=v.useRef(null),s=it(t,r);return v.useEffect(()=>{const o=r.current;if(o)return n.branches.add(o),()=>{n.branches.delete(o)}},[n.branches]),u.jsx(Me.div,{...e,ref:s})});uB.displayName=lB;function cB(e,t=globalThis==null?void 0:globalThis.document){const n=nn(e),r=v.useRef(!1),s=v.useRef(()=>{});return v.useEffect(()=>{const o=i=>{if(i.target&&!r.current){let c=function(){vj(aB,n,l,{discrete:!0})};const l={originalEvent:i};i.pointerType==="touch"?(t.removeEventListener("click",s.current),s.current=c,t.addEventListener("click",s.current,{once:!0})):c()}else t.removeEventListener("click",s.current);r.current=!1},a=window.setTimeout(()=>{t.addEventListener("pointerdown",o)},0);return()=>{window.clearTimeout(a),t.removeEventListener("pointerdown",o),t.removeEventListener("click",s.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function dB(e,t=globalThis==null?void 0:globalThis.document){const n=nn(e),r=v.useRef(!1);return v.useEffect(()=>{const s=o=>{o.target&&!r.current&&vj(iB,n,{originalEvent:o},{discrete:!1})};return t.addEventListener("focusin",s),()=>t.removeEventListener("focusin",s)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function t1(){const e=new CustomEvent(Ky);document.dispatchEvent(e)}function vj(e,t,n,{discrete:r}){const s=n.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&s.addEventListener(e,t,{once:!0}),r?gj(s,o):s.dispatchEvent(o)}var zm=0;function Lx(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??n1()),document.body.insertAdjacentElement("beforeend",e[1]??n1()),zm++,()=>{zm===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),zm--}},[])}function n1(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Um="focusScope.autoFocusOnMount",Vm="focusScope.autoFocusOnUnmount",r1={bubbles:!1,cancelable:!0},fB="FocusScope",dg=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:s,onUnmountAutoFocus:o,...a}=e,[i,c]=v.useState(null),l=nn(s),d=nn(o),p=v.useRef(null),f=it(t,m=>c(m)),h=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let m=function(w){if(h.paused||!i)return;const S=w.target;i.contains(S)?p.current=S:Lo(p.current,{select:!0})},x=function(w){if(h.paused||!i)return;const S=w.relatedTarget;S!==null&&(i.contains(S)||Lo(p.current,{select:!0}))},b=function(w){if(document.activeElement===document.body)for(const E of w)E.removedNodes.length>0&&Lo(i)};document.addEventListener("focusin",m),document.addEventListener("focusout",x);const y=new MutationObserver(b);return i&&y.observe(i,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",x),y.disconnect()}}},[r,i,h.paused]),v.useEffect(()=>{if(i){o1.add(h);const m=document.activeElement;if(!i.contains(m)){const b=new CustomEvent(Um,r1);i.addEventListener(Um,l),i.dispatchEvent(b),b.defaultPrevented||(pB(yB(yj(i)),{select:!0}),document.activeElement===m&&Lo(i))}return()=>{i.removeEventListener(Um,l),setTimeout(()=>{const b=new CustomEvent(Vm,r1);i.addEventListener(Vm,d),i.dispatchEvent(b),b.defaultPrevented||Lo(m??document.body,{select:!0}),i.removeEventListener(Vm,d),o1.remove(h)},0)}}},[i,l,d,h]);const g=v.useCallback(m=>{if(!n&&!r||h.paused)return;const x=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,b=document.activeElement;if(x&&b){const y=m.currentTarget,[w,S]=hB(y);w&&S?!m.shiftKey&&b===S?(m.preventDefault(),n&&Lo(w,{select:!0})):m.shiftKey&&b===w&&(m.preventDefault(),n&&Lo(S,{select:!0})):b===y&&m.preventDefault()}},[n,r,h.paused]);return u.jsx(Me.div,{tabIndex:-1,...a,ref:f,onKeyDown:g})});dg.displayName=fB;function pB(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Lo(r,{select:t}),document.activeElement!==n)return}function hB(e){const t=yj(e),n=s1(t,e),r=s1(t.reverse(),e);return[n,r]}function yj(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const s=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||s?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function s1(e,t){for(const n of e)if(!gB(n,{upTo:t}))return n}function gB(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function mB(e){return e instanceof HTMLInputElement&&"select"in e}function Lo(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&mB(e)&&t&&e.select()}}var o1=vB();function vB(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=a1(e,t),e.unshift(t)},remove(t){var n;e=a1(e,t),(n=e[0])==null||n.resume()}}}function a1(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function yB(e){return e.filter(t=>t.tagName!=="A")}var fn=globalThis!=null&&globalThis.document?v.useLayoutEffect:()=>{},bB=Mh.useId||(()=>{}),xB=0;function os(e){const[t,n]=v.useState(bB());return fn(()=>{n(r=>r??String(xB++))},[e]),t?`radix-${t}`:""}const wB=["top","right","bottom","left"],Ns=Math.min,pr=Math.max,nh=Math.round,Nf=Math.floor,ha=e=>({x:e,y:e}),SB={left:"right",right:"left",bottom:"top",top:"bottom"},CB={start:"end",end:"start"};function qy(e,t,n){return pr(e,Ns(t,n))}function vo(e,t){return typeof e=="function"?e(t):e}function yo(e){return e.split("-")[0]}function yu(e){return e.split("-")[1]}function $x(e){return e==="x"?"y":"x"}function Bx(e){return e==="y"?"height":"width"}function ga(e){return["top","bottom"].includes(yo(e))?"y":"x"}function zx(e){return $x(ga(e))}function EB(e,t,n){n===void 0&&(n=!1);const r=yu(e),s=zx(e),o=Bx(s);let a=s==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[o]>t.floating[o]&&(a=rh(a)),[a,rh(a)]}function TB(e){const t=rh(e);return[Wy(e),t,Wy(t)]}function Wy(e){return e.replace(/start|end/g,t=>CB[t])}function kB(e,t,n){const r=["left","right"],s=["right","left"],o=["top","bottom"],a=["bottom","top"];switch(e){case"top":case"bottom":return n?t?s:r:t?r:s;case"left":case"right":return t?o:a;default:return[]}}function _B(e,t,n,r){const s=yu(e);let o=kB(yo(e),n==="start",r);return s&&(o=o.map(a=>a+"-"+s),t&&(o=o.concat(o.map(Wy)))),o}function rh(e){return e.replace(/left|right|bottom|top/g,t=>SB[t])}function jB(e){return{top:0,right:0,bottom:0,left:0,...e}}function bj(e){return typeof e!="number"?jB(e):{top:e,right:e,bottom:e,left:e}}function sh(e){const{x:t,y:n,width:r,height:s}=e;return{width:r,height:s,top:n,left:t,right:t+r,bottom:n+s,x:t,y:n}}function i1(e,t,n){let{reference:r,floating:s}=e;const o=ga(t),a=zx(t),i=Bx(a),c=yo(t),l=o==="y",d=r.x+r.width/2-s.width/2,p=r.y+r.height/2-s.height/2,f=r[i]/2-s[i]/2;let h;switch(c){case"top":h={x:d,y:r.y-s.height};break;case"bottom":h={x:d,y:r.y+r.height};break;case"right":h={x:r.x+r.width,y:p};break;case"left":h={x:r.x-s.width,y:p};break;default:h={x:r.x,y:r.y}}switch(yu(t)){case"start":h[a]-=f*(n&&l?-1:1);break;case"end":h[a]+=f*(n&&l?-1:1);break}return h}const RB=async(e,t,n)=>{const{placement:r="bottom",strategy:s="absolute",middleware:o=[],platform:a}=n,i=o.filter(Boolean),c=await(a.isRTL==null?void 0:a.isRTL(t));let l=await a.getElementRects({reference:e,floating:t,strategy:s}),{x:d,y:p}=i1(l,r,c),f=r,h={},g=0;for(let m=0;m({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:s,rects:o,platform:a,elements:i,middlewareData:c}=t,{element:l,padding:d=0}=vo(e,t)||{};if(l==null)return{};const p=bj(d),f={x:n,y:r},h=zx(s),g=Bx(h),m=await a.getDimensions(l),x=h==="y",b=x?"top":"left",y=x?"bottom":"right",w=x?"clientHeight":"clientWidth",S=o.reference[g]+o.reference[h]-f[h]-o.floating[g],E=f[h]-o.reference[h],C=await(a.getOffsetParent==null?void 0:a.getOffsetParent(l));let k=C?C[w]:0;(!k||!await(a.isElement==null?void 0:a.isElement(C)))&&(k=i.floating[w]||o.floating[g]);const T=S/2-E/2,O=k/2-m[g]/2-1,M=Ns(p[b],O),U=Ns(p[y],O),I=M,J=k-m[g]-U,V=k/2-m[g]/2+T,G=qy(I,V,J),ee=!c.arrow&&yu(s)!=null&&V!==G&&o.reference[g]/2-(VV<=0)){var U,I;const V=(((U=o.flip)==null?void 0:U.index)||0)+1,G=k[V];if(G)return{data:{index:V,overflows:M},reset:{placement:G}};let ee=(I=M.filter(q=>q.overflows[0]<=0).sort((q,F)=>q.overflows[1]-F.overflows[1])[0])==null?void 0:I.placement;if(!ee)switch(h){case"bestFit":{var J;const q=(J=M.filter(F=>{if(C){const A=ga(F.placement);return A===y||A==="y"}return!0}).map(F=>[F.placement,F.overflows.filter(A=>A>0).reduce((A,Y)=>A+Y,0)]).sort((F,A)=>F[1]-A[1])[0])==null?void 0:J[0];q&&(ee=q);break}case"initialPlacement":ee=i;break}if(s!==ee)return{reset:{placement:ee}}}return{}}}};function l1(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function u1(e){return wB.some(t=>e[t]>=0)}const PB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...s}=vo(e,t);switch(r){case"referenceHidden":{const o=await ad(t,{...s,elementContext:"reference"}),a=l1(o,n.reference);return{data:{referenceHiddenOffsets:a,referenceHidden:u1(a)}}}case"escaped":{const o=await ad(t,{...s,altBoundary:!0}),a=l1(o,n.floating);return{data:{escapedOffsets:a,escaped:u1(a)}}}default:return{}}}}};async function MB(e,t){const{placement:n,platform:r,elements:s}=e,o=await(r.isRTL==null?void 0:r.isRTL(s.floating)),a=yo(n),i=yu(n),c=ga(n)==="y",l=["left","top"].includes(a)?-1:1,d=o&&c?-1:1,p=vo(t,e);let{mainAxis:f,crossAxis:h,alignmentAxis:g}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...p};return i&&typeof g=="number"&&(h=i==="end"?g*-1:g),c?{x:h*d,y:f*l}:{x:f*l,y:h*d}}const IB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:s,y:o,placement:a,middlewareData:i}=t,c=await MB(t,e);return a===((n=i.offset)==null?void 0:n.placement)&&(r=i.arrow)!=null&&r.alignmentOffset?{}:{x:s+c.x,y:o+c.y,data:{...c,placement:a}}}}},DB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:s}=t,{mainAxis:o=!0,crossAxis:a=!1,limiter:i={fn:x=>{let{x:b,y}=x;return{x:b,y}}},...c}=vo(e,t),l={x:n,y:r},d=await ad(t,c),p=ga(yo(s)),f=$x(p);let h=l[f],g=l[p];if(o){const x=f==="y"?"top":"left",b=f==="y"?"bottom":"right",y=h+d[x],w=h-d[b];h=qy(y,h,w)}if(a){const x=p==="y"?"top":"left",b=p==="y"?"bottom":"right",y=g+d[x],w=g-d[b];g=qy(y,g,w)}const m=i.fn({...t,[f]:h,[p]:g});return{...m,data:{x:m.x-n,y:m.y-r}}}}},AB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:s,rects:o,middlewareData:a}=t,{offset:i=0,mainAxis:c=!0,crossAxis:l=!0}=vo(e,t),d={x:n,y:r},p=ga(s),f=$x(p);let h=d[f],g=d[p];const m=vo(i,t),x=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(c){const w=f==="y"?"height":"width",S=o.reference[f]-o.floating[w]+x.mainAxis,E=o.reference[f]+o.reference[w]-x.mainAxis;hE&&(h=E)}if(l){var b,y;const w=f==="y"?"width":"height",S=["top","left"].includes(yo(s)),E=o.reference[p]-o.floating[w]+(S&&((b=a.offset)==null?void 0:b[p])||0)+(S?0:x.crossAxis),C=o.reference[p]+o.reference[w]+(S?0:((y=a.offset)==null?void 0:y[p])||0)-(S?x.crossAxis:0);gC&&(g=C)}return{[f]:h,[p]:g}}}},FB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:s,elements:o}=t,{apply:a=()=>{},...i}=vo(e,t),c=await ad(t,i),l=yo(n),d=yu(n),p=ga(n)==="y",{width:f,height:h}=r.floating;let g,m;l==="top"||l==="bottom"?(g=l,m=d===(await(s.isRTL==null?void 0:s.isRTL(o.floating))?"start":"end")?"left":"right"):(m=l,g=d==="end"?"top":"bottom");const x=h-c.top-c.bottom,b=f-c.left-c.right,y=Ns(h-c[g],x),w=Ns(f-c[m],b),S=!t.middlewareData.shift;let E=y,C=w;if(p?C=d||S?Ns(w,b):b:E=d||S?Ns(y,x):x,S&&!d){const T=pr(c.left,0),O=pr(c.right,0),M=pr(c.top,0),U=pr(c.bottom,0);p?C=f-2*(T!==0||O!==0?T+O:pr(c.left,c.right)):E=h-2*(M!==0||U!==0?M+U:pr(c.top,c.bottom))}await a({...t,availableWidth:C,availableHeight:E});const k=await s.getDimensions(o.floating);return f!==k.width||h!==k.height?{reset:{rects:!0}}:{}}}};function bu(e){return xj(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Co(e){var t;return(t=(xj(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function xj(e){return e instanceof Node||e instanceof vr(e).Node}function $s(e){return e instanceof Element||e instanceof vr(e).Element}function Bs(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function c1(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Jd(e){const{overflow:t,overflowX:n,overflowY:r,display:s}=cs(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(s)}function LB(e){return["table","td","th"].includes(bu(e))}function fg(e){return[":popover-open",":modal"].some(t=>{try{return e.matches(t)}catch{return!1}})}function Ux(e){const t=Vx(),n=cs(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function $B(e){let t=ma(e);for(;Bs(t)&&!eu(t);){if(fg(t))return null;if(Ux(t))return t;t=ma(t)}return null}function Vx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function eu(e){return["html","body","#document"].includes(bu(e))}function cs(e){return vr(e).getComputedStyle(e)}function pg(e){return $s(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function ma(e){if(bu(e)==="html")return e;const t=e.assignedSlot||e.parentNode||c1(e)&&e.host||Co(e);return c1(t)?t.host:t}function wj(e){const t=ma(e);return eu(t)?e.ownerDocument?e.ownerDocument.body:e.body:Bs(t)&&Jd(t)?t:wj(t)}function id(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const s=wj(e),o=s===((r=e.ownerDocument)==null?void 0:r.body),a=vr(s);return o?t.concat(a,a.visualViewport||[],Jd(s)?s:[],a.frameElement&&n?id(a.frameElement):[]):t.concat(s,id(s,[],n))}function Sj(e){const t=cs(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const s=Bs(e),o=s?e.offsetWidth:n,a=s?e.offsetHeight:r,i=nh(n)!==o||nh(r)!==a;return i&&(n=o,r=a),{width:n,height:r,$:i}}function Hx(e){return $s(e)?e:e.contextElement}function kl(e){const t=Hx(e);if(!Bs(t))return ha(1);const n=t.getBoundingClientRect(),{width:r,height:s,$:o}=Sj(t);let a=(o?nh(n.width):n.width)/r,i=(o?nh(n.height):n.height)/s;return(!a||!Number.isFinite(a))&&(a=1),(!i||!Number.isFinite(i))&&(i=1),{x:a,y:i}}const BB=ha(0);function Cj(e){const t=vr(e);return!Vx()||!t.visualViewport?BB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function zB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Ci(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const s=e.getBoundingClientRect(),o=Hx(e);let a=ha(1);t&&(r?$s(r)&&(a=kl(r)):a=kl(e));const i=zB(o,n,r)?Cj(o):ha(0);let c=(s.left+i.x)/a.x,l=(s.top+i.y)/a.y,d=s.width/a.x,p=s.height/a.y;if(o){const f=vr(o),h=r&&$s(r)?vr(r):r;let g=f,m=g.frameElement;for(;m&&r&&h!==g;){const x=kl(m),b=m.getBoundingClientRect(),y=cs(m),w=b.left+(m.clientLeft+parseFloat(y.paddingLeft))*x.x,S=b.top+(m.clientTop+parseFloat(y.paddingTop))*x.y;c*=x.x,l*=x.y,d*=x.x,p*=x.y,c+=w,l+=S,g=vr(m),m=g.frameElement}}return sh({width:d,height:p,x:c,y:l})}function UB(e){let{elements:t,rect:n,offsetParent:r,strategy:s}=e;const o=s==="fixed",a=Co(r),i=t?fg(t.floating):!1;if(r===a||i&&o)return n;let c={scrollLeft:0,scrollTop:0},l=ha(1);const d=ha(0),p=Bs(r);if((p||!p&&!o)&&((bu(r)!=="body"||Jd(a))&&(c=pg(r)),Bs(r))){const f=Ci(r);l=kl(r),d.x=f.x+r.clientLeft,d.y=f.y+r.clientTop}return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+d.x,y:n.y*l.y-c.scrollTop*l.y+d.y}}function VB(e){return Array.from(e.getClientRects())}function Ej(e){return Ci(Co(e)).left+pg(e).scrollLeft}function HB(e){const t=Co(e),n=pg(e),r=e.ownerDocument.body,s=pr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),o=pr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let a=-n.scrollLeft+Ej(e);const i=-n.scrollTop;return cs(r).direction==="rtl"&&(a+=pr(t.clientWidth,r.clientWidth)-s),{width:s,height:o,x:a,y:i}}function KB(e,t){const n=vr(e),r=Co(e),s=n.visualViewport;let o=r.clientWidth,a=r.clientHeight,i=0,c=0;if(s){o=s.width,a=s.height;const l=Vx();(!l||l&&t==="fixed")&&(i=s.offsetLeft,c=s.offsetTop)}return{width:o,height:a,x:i,y:c}}function qB(e,t){const n=Ci(e,!0,t==="fixed"),r=n.top+e.clientTop,s=n.left+e.clientLeft,o=Bs(e)?kl(e):ha(1),a=e.clientWidth*o.x,i=e.clientHeight*o.y,c=s*o.x,l=r*o.y;return{width:a,height:i,x:c,y:l}}function d1(e,t,n){let r;if(t==="viewport")r=KB(e,n);else if(t==="document")r=HB(Co(e));else if($s(t))r=qB(t,n);else{const s=Cj(e);r={...t,x:t.x-s.x,y:t.y-s.y}}return sh(r)}function Tj(e,t){const n=ma(e);return n===t||!$s(n)||eu(n)?!1:cs(n).position==="fixed"||Tj(n,t)}function WB(e,t){const n=t.get(e);if(n)return n;let r=id(e,[],!1).filter(i=>$s(i)&&bu(i)!=="body"),s=null;const o=cs(e).position==="fixed";let a=o?ma(e):e;for(;$s(a)&&!eu(a);){const i=cs(a),c=Ux(a);!c&&i.position==="fixed"&&(s=null),(o?!c&&!s:!c&&i.position==="static"&&!!s&&["absolute","fixed"].includes(s.position)||Jd(a)&&!c&&Tj(e,a))?r=r.filter(d=>d!==a):s=i,a=ma(a)}return t.set(e,r),r}function GB(e){let{element:t,boundary:n,rootBoundary:r,strategy:s}=e;const a=[...n==="clippingAncestors"?fg(t)?[]:WB(t,this._c):[].concat(n),r],i=a[0],c=a.reduce((l,d)=>{const p=d1(t,d,s);return l.top=pr(p.top,l.top),l.right=Ns(p.right,l.right),l.bottom=Ns(p.bottom,l.bottom),l.left=pr(p.left,l.left),l},d1(t,i,s));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function JB(e){const{width:t,height:n}=Sj(e);return{width:t,height:n}}function QB(e,t,n){const r=Bs(t),s=Co(t),o=n==="fixed",a=Ci(e,!0,o,t);let i={scrollLeft:0,scrollTop:0};const c=ha(0);if(r||!r&&!o)if((bu(t)!=="body"||Jd(s))&&(i=pg(t)),r){const p=Ci(t,!0,o,t);c.x=p.x+t.clientLeft,c.y=p.y+t.clientTop}else s&&(c.x=Ej(s));const l=a.left+i.scrollLeft-c.x,d=a.top+i.scrollTop-c.y;return{x:l,y:d,width:a.width,height:a.height}}function Hm(e){return cs(e).position==="static"}function f1(e,t){return!Bs(e)||cs(e).position==="fixed"?null:t?t(e):e.offsetParent}function kj(e,t){const n=vr(e);if(fg(e))return n;if(!Bs(e)){let s=ma(e);for(;s&&!eu(s);){if($s(s)&&!Hm(s))return s;s=ma(s)}return n}let r=f1(e,t);for(;r&&LB(r)&&Hm(r);)r=f1(r,t);return r&&eu(r)&&Hm(r)&&!Ux(r)?n:r||$B(e)||n}const ZB=async function(e){const t=this.getOffsetParent||kj,n=this.getDimensions,r=await n(e.floating);return{reference:QB(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function YB(e){return cs(e).direction==="rtl"}const XB={convertOffsetParentRelativeRectToViewportRelativeRect:UB,getDocumentElement:Co,getClippingRect:GB,getOffsetParent:kj,getElementRects:ZB,getClientRects:VB,getDimensions:JB,getScale:kl,isElement:$s,isRTL:YB};function ez(e,t){let n=null,r;const s=Co(e);function o(){var i;clearTimeout(r),(i=n)==null||i.disconnect(),n=null}function a(i,c){i===void 0&&(i=!1),c===void 0&&(c=1),o();const{left:l,top:d,width:p,height:f}=e.getBoundingClientRect();if(i||t(),!p||!f)return;const h=Nf(d),g=Nf(s.clientWidth-(l+p)),m=Nf(s.clientHeight-(d+f)),x=Nf(l),y={rootMargin:-h+"px "+-g+"px "+-m+"px "+-x+"px",threshold:pr(0,Ns(1,c))||1};let w=!0;function S(E){const C=E[0].intersectionRatio;if(C!==c){if(!w)return a();C?a(!1,C):r=setTimeout(()=>{a(!1,1e-7)},1e3)}w=!1}try{n=new IntersectionObserver(S,{...y,root:s.ownerDocument})}catch{n=new IntersectionObserver(S,y)}n.observe(e)}return a(!0),o}function tz(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:s=!0,ancestorResize:o=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:i=typeof IntersectionObserver=="function",animationFrame:c=!1}=r,l=Hx(e),d=s||o?[...l?id(l):[],...id(t)]:[];d.forEach(b=>{s&&b.addEventListener("scroll",n,{passive:!0}),o&&b.addEventListener("resize",n)});const p=l&&i?ez(l,n):null;let f=-1,h=null;a&&(h=new ResizeObserver(b=>{let[y]=b;y&&y.target===l&&h&&(h.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var w;(w=h)==null||w.observe(t)})),n()}),l&&!c&&h.observe(l),h.observe(t));let g,m=c?Ci(e):null;c&&x();function x(){const b=Ci(e);m&&(b.x!==m.x||b.y!==m.y||b.width!==m.width||b.height!==m.height)&&n(),m=b,g=requestAnimationFrame(x)}return n(),()=>{var b;d.forEach(y=>{s&&y.removeEventListener("scroll",n),o&&y.removeEventListener("resize",n)}),p==null||p(),(b=h)==null||b.disconnect(),h=null,c&&cancelAnimationFrame(g)}}const nz=IB,rz=DB,sz=NB,oz=FB,az=PB,p1=OB,iz=AB,lz=(e,t,n)=>{const r=new Map,s={platform:XB,...n},o={...s.platform,_c:r};return RB(e,t,{...s,platform:o})};var hp=typeof document<"u"?v.useLayoutEffect:v.useEffect;function oh(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,s;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!oh(e[r],t[r]))return!1;return!0}if(s=Object.keys(e),n=s.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,s[r]))return!1;for(r=n;r--!==0;){const o=s[r];if(!(o==="_owner"&&e.$$typeof)&&!oh(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}function _j(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function h1(e,t){const n=_j(e);return Math.round(t*n)/n}function g1(e){const t=v.useRef(e);return hp(()=>{t.current=e}),t}function uz(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:s,elements:{reference:o,floating:a}={},transform:i=!0,whileElementsMounted:c,open:l}=e,[d,p]=v.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,h]=v.useState(r);oh(f,r)||h(r);const[g,m]=v.useState(null),[x,b]=v.useState(null),y=v.useCallback(q=>{q!==C.current&&(C.current=q,m(q))},[]),w=v.useCallback(q=>{q!==k.current&&(k.current=q,b(q))},[]),S=o||g,E=a||x,C=v.useRef(null),k=v.useRef(null),T=v.useRef(d),O=c!=null,M=g1(c),U=g1(s),I=v.useCallback(()=>{if(!C.current||!k.current)return;const q={placement:t,strategy:n,middleware:f};U.current&&(q.platform=U.current),lz(C.current,k.current,q).then(F=>{const A={...F,isPositioned:!0};J.current&&!oh(T.current,A)&&(T.current=A,ka.flushSync(()=>{p(A)}))})},[f,t,n,U]);hp(()=>{l===!1&&T.current.isPositioned&&(T.current.isPositioned=!1,p(q=>({...q,isPositioned:!1})))},[l]);const J=v.useRef(!1);hp(()=>(J.current=!0,()=>{J.current=!1}),[]),hp(()=>{if(S&&(C.current=S),E&&(k.current=E),S&&E){if(M.current)return M.current(S,E,I);I()}},[S,E,I,M,O]);const V=v.useMemo(()=>({reference:C,floating:k,setReference:y,setFloating:w}),[y,w]),G=v.useMemo(()=>({reference:S,floating:E}),[S,E]),ee=v.useMemo(()=>{const q={position:n,left:0,top:0};if(!G.floating)return q;const F=h1(G.floating,d.x),A=h1(G.floating,d.y);return i?{...q,transform:"translate("+F+"px, "+A+"px)",..._j(G.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:F,top:A}},[n,i,G.floating,d.x,d.y]);return v.useMemo(()=>({...d,update:I,refs:V,elements:G,floatingStyles:ee}),[d,I,V,G,ee])}const cz=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:s}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?p1({element:r.current,padding:s}).fn(n):{}:r?p1({element:r,padding:s}).fn(n):{}}}},dz=(e,t)=>({...nz(e),options:[e,t]}),fz=(e,t)=>({...rz(e),options:[e,t]}),pz=(e,t)=>({...iz(e),options:[e,t]}),hz=(e,t)=>({...sz(e),options:[e,t]}),gz=(e,t)=>({...oz(e),options:[e,t]}),mz=(e,t)=>({...az(e),options:[e,t]}),vz=(e,t)=>({...cz(e),options:[e,t]});var yz="Arrow",jj=v.forwardRef((e,t)=>{const{children:n,width:r=10,height:s=5,...o}=e;return u.jsx(Me.svg,{...o,ref:t,width:r,height:s,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:u.jsx("polygon",{points:"0,0 30,0 15,10"})})});jj.displayName=yz;var bz=jj;function Rj(e){const[t,n]=v.useState(void 0);return fn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;const o=s[0];let a,i;if("borderBoxSize"in o){const c=o.borderBoxSize,l=Array.isArray(c)?c[0]:c;a=l.inlineSize,i=l.blockSize}else a=e.offsetWidth,i=e.offsetHeight;n({width:a,height:i})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var Kx="Popper",[Oj,hg]=Vr(Kx),[xz,Nj]=Oj(Kx),Pj=e=>{const{__scopePopper:t,children:n}=e,[r,s]=v.useState(null);return u.jsx(xz,{scope:t,anchor:r,onAnchorChange:s,children:n})};Pj.displayName=Kx;var Mj="PopperAnchor",Ij=v.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...s}=e,o=Nj(Mj,n),a=v.useRef(null),i=it(t,a);return v.useEffect(()=>{o.onAnchorChange((r==null?void 0:r.current)||a.current)}),r?null:u.jsx(Me.div,{...s,ref:i})});Ij.displayName=Mj;var qx="PopperContent",[wz,Sz]=Oj(qx),Dj=v.forwardRef((e,t)=>{var W,Ce,Re,Le,Oe,me;const{__scopePopper:n,side:r="bottom",sideOffset:s=0,align:o="center",alignOffset:a=0,arrowPadding:i=0,avoidCollisions:c=!0,collisionBoundary:l=[],collisionPadding:d=0,sticky:p="partial",hideWhenDetached:f=!1,updatePositionStrategy:h="optimized",onPlaced:g,...m}=e,x=Nj(qx,n),[b,y]=v.useState(null),w=it(t,rt=>y(rt)),[S,E]=v.useState(null),C=Rj(S),k=(C==null?void 0:C.width)??0,T=(C==null?void 0:C.height)??0,O=r+(o!=="center"?"-"+o:""),M=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},U=Array.isArray(l)?l:[l],I=U.length>0,J={padding:M,boundary:U.filter(Ez),altBoundary:I},{refs:V,floatingStyles:G,placement:ee,isPositioned:q,middlewareData:F}=uz({strategy:"fixed",placement:O,whileElementsMounted:(...rt)=>tz(...rt,{animationFrame:h==="always"}),elements:{reference:x.anchor},middleware:[dz({mainAxis:s+T,alignmentAxis:a}),c&&fz({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?pz():void 0,...J}),c&&hz({...J}),gz({...J,apply:({elements:rt,rects:It,availableWidth:Zt,availableHeight:Wt})=>{const{width:an,height:j}=It.reference,D=rt.floating.style;D.setProperty("--radix-popper-available-width",`${Zt}px`),D.setProperty("--radix-popper-available-height",`${Wt}px`),D.setProperty("--radix-popper-anchor-width",`${an}px`),D.setProperty("--radix-popper-anchor-height",`${j}px`)}}),S&&vz({element:S,padding:i}),Tz({arrowWidth:k,arrowHeight:T}),f&&mz({strategy:"referenceHidden",...J})]}),[A,Y]=Lj(ee),de=nn(g);fn(()=>{q&&(de==null||de())},[q,de]);const z=(W=F.arrow)==null?void 0:W.x,se=(Ce=F.arrow)==null?void 0:Ce.y,ne=((Re=F.arrow)==null?void 0:Re.centerOffset)!==0,[ie,oe]=v.useState();return fn(()=>{b&&oe(window.getComputedStyle(b).zIndex)},[b]),u.jsx("div",{ref:V.setFloating,"data-radix-popper-content-wrapper":"",style:{...G,transform:q?G.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ie,"--radix-popper-transform-origin":[(Le=F.transformOrigin)==null?void 0:Le.x,(Oe=F.transformOrigin)==null?void 0:Oe.y].join(" "),...((me=F.hide)==null?void 0:me.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(wz,{scope:n,placedSide:A,onArrowChange:E,arrowX:z,arrowY:se,shouldHideArrow:ne,children:u.jsx(Me.div,{"data-side":A,"data-align":Y,...m,ref:w,style:{...m.style,animation:q?void 0:"none"}})})})});Dj.displayName=qx;var Aj="PopperArrow",Cz={top:"bottom",right:"left",bottom:"top",left:"right"},Fj=v.forwardRef(function(t,n){const{__scopePopper:r,...s}=t,o=Sz(Aj,r),a=Cz[o.placedSide];return u.jsx("span",{ref:o.onArrowChange,style:{position:"absolute",left:o.arrowX,top:o.arrowY,[a]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[o.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[o.placedSide],visibility:o.shouldHideArrow?"hidden":void 0},children:u.jsx(bz,{...s,ref:n,style:{...s.style,display:"block"}})})});Fj.displayName=Aj;function Ez(e){return e!==null}var Tz=e=>({name:"transformOrigin",options:e,fn(t){var x,b,y;const{placement:n,rects:r,middlewareData:s}=t,a=((x=s.arrow)==null?void 0:x.centerOffset)!==0,i=a?0:e.arrowWidth,c=a?0:e.arrowHeight,[l,d]=Lj(n),p={start:"0%",center:"50%",end:"100%"}[d],f=(((b=s.arrow)==null?void 0:b.x)??0)+i/2,h=(((y=s.arrow)==null?void 0:y.y)??0)+c/2;let g="",m="";return l==="bottom"?(g=a?p:`${f}px`,m=`${-c}px`):l==="top"?(g=a?p:`${f}px`,m=`${r.floating.height+c}px`):l==="right"?(g=`${-c}px`,m=a?p:`${h}px`):l==="left"&&(g=`${r.floating.width+c}px`,m=a?p:`${h}px`),{data:{x:g,y:m}}}});function Lj(e){const[t,n="center"]=e.split("-");return[t,n]}var $j=Pj,Bj=Ij,zj=Dj,Uj=Fj,kz="Portal",gg=v.forwardRef((e,t)=>{var i;const{container:n,...r}=e,[s,o]=v.useState(!1);fn(()=>o(!0),[]);const a=n||s&&((i=globalThis==null?void 0:globalThis.document)==null?void 0:i.body);return a?t_.createPortal(u.jsx(Me.div,{...r,ref:t}),a):null});gg.displayName=kz;function _z(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var or=e=>{const{present:t,children:n}=e,r=jz(t),s=typeof n=="function"?n({present:r.isPresent}):v.Children.only(n),o=it(r.ref,Rz(s));return typeof n=="function"||r.isPresent?v.cloneElement(s,{ref:o}):null};or.displayName="Presence";function jz(e){const[t,n]=v.useState(),r=v.useRef({}),s=v.useRef(e),o=v.useRef("none"),a=e?"mounted":"unmounted",[i,c]=_z(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const l=Pf(r.current);o.current=i==="mounted"?l:"none"},[i]),fn(()=>{const l=r.current,d=s.current;if(d!==e){const f=o.current,h=Pf(l);e?c("MOUNT"):h==="none"||(l==null?void 0:l.display)==="none"?c("UNMOUNT"):c(d&&f!==h?"ANIMATION_OUT":"UNMOUNT"),s.current=e}},[e,c]),fn(()=>{if(t){const l=p=>{const h=Pf(r.current).includes(p.animationName);p.target===t&&h&&ka.flushSync(()=>c("ANIMATION_END"))},d=p=>{p.target===t&&(o.current=Pf(r.current))};return t.addEventListener("animationstart",d),t.addEventListener("animationcancel",l),t.addEventListener("animationend",l),()=>{t.removeEventListener("animationstart",d),t.removeEventListener("animationcancel",l),t.removeEventListener("animationend",l)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(i),ref:v.useCallback(l=>{l&&(r.current=getComputedStyle(l)),n(l)},[])}}function Pf(e){return(e==null?void 0:e.animationName)||"none"}function Rz(e){var r,s;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Km="rovingFocusGroup.onEntryFocus",Oz={bubbles:!1,cancelable:!0},mg="RovingFocusGroup",[Gy,Vj,Nz]=Fx(mg),[Pz,vg]=Vr(mg,[Nz]),[Mz,Iz]=Pz(mg),Hj=v.forwardRef((e,t)=>u.jsx(Gy.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Gy.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Dz,{...e,ref:t})})}));Hj.displayName=mg;var Dz=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:s=!1,dir:o,currentTabStopId:a,defaultCurrentTabStopId:i,onCurrentTabStopIdChange:c,onEntryFocus:l,preventScrollOnEntryFocus:d=!1,...p}=e,f=v.useRef(null),h=it(t,f),g=Gd(o),[m=null,x]=pa({prop:a,defaultProp:i,onChange:c}),[b,y]=v.useState(!1),w=nn(l),S=Vj(n),E=v.useRef(!1),[C,k]=v.useState(0);return v.useEffect(()=>{const T=f.current;if(T)return T.addEventListener(Km,w),()=>T.removeEventListener(Km,w)},[w]),u.jsx(Mz,{scope:n,orientation:r,dir:g,loop:s,currentTabStopId:m,onItemFocus:v.useCallback(T=>x(T),[x]),onItemShiftTab:v.useCallback(()=>y(!0),[]),onFocusableItemAdd:v.useCallback(()=>k(T=>T+1),[]),onFocusableItemRemove:v.useCallback(()=>k(T=>T-1),[]),children:u.jsx(Me.div,{tabIndex:b||C===0?-1:0,"data-orientation":r,...p,ref:h,style:{outline:"none",...e.style},onMouseDown:Se(e.onMouseDown,()=>{E.current=!0}),onFocus:Se(e.onFocus,T=>{const O=!E.current;if(T.target===T.currentTarget&&O&&!b){const M=new CustomEvent(Km,Oz);if(T.currentTarget.dispatchEvent(M),!M.defaultPrevented){const U=S().filter(ee=>ee.focusable),I=U.find(ee=>ee.active),J=U.find(ee=>ee.id===m),G=[I,J,...U].filter(Boolean).map(ee=>ee.ref.current);Wj(G,d)}}E.current=!1}),onBlur:Se(e.onBlur,()=>y(!1))})})}),Kj="RovingFocusGroupItem",qj=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:s=!1,tabStopId:o,...a}=e,i=os(),c=o||i,l=Iz(Kj,n),d=l.currentTabStopId===c,p=Vj(n),{onFocusableItemAdd:f,onFocusableItemRemove:h}=l;return v.useEffect(()=>{if(r)return f(),()=>h()},[r,f,h]),u.jsx(Gy.ItemSlot,{scope:n,id:c,focusable:r,active:s,children:u.jsx(Me.span,{tabIndex:d?0:-1,"data-orientation":l.orientation,...a,ref:t,onMouseDown:Se(e.onMouseDown,g=>{r?l.onItemFocus(c):g.preventDefault()}),onFocus:Se(e.onFocus,()=>l.onItemFocus(c)),onKeyDown:Se(e.onKeyDown,g=>{if(g.key==="Tab"&&g.shiftKey){l.onItemShiftTab();return}if(g.target!==g.currentTarget)return;const m=Lz(g,l.orientation,l.dir);if(m!==void 0){if(g.metaKey||g.ctrlKey||g.altKey||g.shiftKey)return;g.preventDefault();let b=p().filter(y=>y.focusable).map(y=>y.ref.current);if(m==="last")b.reverse();else if(m==="prev"||m==="next"){m==="prev"&&b.reverse();const y=b.indexOf(g.currentTarget);b=l.loop?$z(b,y+1):b.slice(y+1)}setTimeout(()=>Wj(b))}})})})});qj.displayName=Kj;var Az={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Fz(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Lz(e,t,n){const r=Fz(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Az[r]}function Wj(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function $z(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Gj=Hj,Jj=qj,Bz=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Ki=new WeakMap,Mf=new WeakMap,If={},qm=0,Qj=function(e){return e&&(e.host||Qj(e.parentNode))},zz=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=Qj(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},Uz=function(e,t,n,r){var s=zz(t,Array.isArray(e)?e:[e]);If[n]||(If[n]=new WeakMap);var o=If[n],a=[],i=new Set,c=new Set(s),l=function(p){!p||i.has(p)||(i.add(p),l(p.parentNode))};s.forEach(l);var d=function(p){!p||c.has(p)||Array.prototype.forEach.call(p.children,function(f){if(i.has(f))d(f);else try{var h=f.getAttribute(r),g=h!==null&&h!=="false",m=(Ki.get(f)||0)+1,x=(o.get(f)||0)+1;Ki.set(f,m),o.set(f,x),a.push(f),m===1&&g&&Mf.set(f,!0),x===1&&f.setAttribute(n,"true"),g||f.setAttribute(r,"true")}catch(b){console.error("aria-hidden: cannot operate on ",f,b)}})};return d(t),i.clear(),qm++,function(){a.forEach(function(p){var f=Ki.get(p)-1,h=o.get(p)-1;Ki.set(p,f),o.set(p,h),f||(Mf.has(p)||p.removeAttribute(r),Mf.delete(p)),h||p.removeAttribute(n)}),qm--,qm||(Ki=new WeakMap,Ki=new WeakMap,Mf=new WeakMap,If={})}},Wx=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),s=Bz(e);return s?(r.push.apply(r,Array.from(s.querySelectorAll("[aria-live]"))),Uz(r,s,n,"aria-hidden")):function(){return null}},_s=function(){return _s=Object.assign||function(t){for(var n,r=1,s=arguments.length;r"u")return oU;var t=aU(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},lU=eR(),_l="data-scroll-locked",uU=function(e,t,n,r){var s=e.left,o=e.top,a=e.right,i=e.gap;return n===void 0&&(n="margin"),` + .`.concat(Hz,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(i,"px ").concat(r,`; + } + body[`).concat(_l,`] { + overflow: hidden `).concat(r,`; + overscroll-behavior: contain; + `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&` + padding-left: `.concat(s,`px; + padding-top: `).concat(o,`px; + padding-right: `).concat(a,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(i,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(i,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(gp,` { + right: `).concat(i,"px ").concat(r,`; + } + + .`).concat(mp,` { + margin-right: `).concat(i,"px ").concat(r,`; + } + + .`).concat(gp," .").concat(gp,` { + right: 0 `).concat(r,`; + } + + .`).concat(mp," .").concat(mp,` { + margin-right: 0 `).concat(r,`; + } + + body[`).concat(_l,`] { + `).concat(Kz,": ").concat(i,`px; + } +`)},v1=function(){var e=parseInt(document.body.getAttribute(_l)||"0",10);return isFinite(e)?e:0},cU=function(){v.useEffect(function(){return document.body.setAttribute(_l,(v1()+1).toString()),function(){var e=v1()-1;e<=0?document.body.removeAttribute(_l):document.body.setAttribute(_l,e.toString())}},[])},dU=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,s=r===void 0?"margin":r;cU();var o=v.useMemo(function(){return iU(s)},[s]);return v.createElement(lU,{styles:uU(o,!t,s,n?"":"!important")})},Jy=!1;if(typeof window<"u")try{var Df=Object.defineProperty({},"passive",{get:function(){return Jy=!0,!0}});window.addEventListener("test",Df,Df),window.removeEventListener("test",Df,Df)}catch{Jy=!1}var qi=Jy?{passive:!1}:!1,fU=function(e){return e.tagName==="TEXTAREA"},tR=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!fU(e)&&n[t]==="visible")},pU=function(e){return tR(e,"overflowY")},hU=function(e){return tR(e,"overflowX")},y1=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var s=nR(e,r);if(s){var o=rR(e,r),a=o[1],i=o[2];if(a>i)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},gU=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},mU=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},nR=function(e,t){return e==="v"?pU(t):hU(t)},rR=function(e,t){return e==="v"?gU(t):mU(t)},vU=function(e,t){return e==="h"&&t==="rtl"?-1:1},yU=function(e,t,n,r,s){var o=vU(e,window.getComputedStyle(t).direction),a=o*r,i=n.target,c=t.contains(i),l=!1,d=a>0,p=0,f=0;do{var h=rR(e,i),g=h[0],m=h[1],x=h[2],b=m-x-o*g;(g||b)&&nR(e,i)&&(p+=b,f+=g),i instanceof ShadowRoot?i=i.host:i=i.parentNode}while(!c&&i!==document.body||c&&(t.contains(i)||t===i));return(d&&(Math.abs(p)<1||!s)||!d&&(Math.abs(f)<1||!s))&&(l=!0),l},Af=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},b1=function(e){return[e.deltaX,e.deltaY]},x1=function(e){return e&&"current"in e?e.current:e},bU=function(e,t){return e[0]===t[0]&&e[1]===t[1]},xU=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},wU=0,Wi=[];function SU(e){var t=v.useRef([]),n=v.useRef([0,0]),r=v.useRef(),s=v.useState(wU++)[0],o=v.useState(eR)[0],a=v.useRef(e);v.useEffect(function(){a.current=e},[e]),v.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(s));var m=Vz([e.lockRef.current],(e.shards||[]).map(x1),!0).filter(Boolean);return m.forEach(function(x){return x.classList.add("allow-interactivity-".concat(s))}),function(){document.body.classList.remove("block-interactivity-".concat(s)),m.forEach(function(x){return x.classList.remove("allow-interactivity-".concat(s))})}}},[e.inert,e.lockRef.current,e.shards]);var i=v.useCallback(function(m,x){if("touches"in m&&m.touches.length===2)return!a.current.allowPinchZoom;var b=Af(m),y=n.current,w="deltaX"in m?m.deltaX:y[0]-b[0],S="deltaY"in m?m.deltaY:y[1]-b[1],E,C=m.target,k=Math.abs(w)>Math.abs(S)?"h":"v";if("touches"in m&&k==="h"&&C.type==="range")return!1;var T=y1(k,C);if(!T)return!0;if(T?E=k:(E=k==="v"?"h":"v",T=y1(k,C)),!T)return!1;if(!r.current&&"changedTouches"in m&&(w||S)&&(r.current=E),!E)return!0;var O=r.current||E;return yU(O,x,m,O==="h"?w:S,!0)},[]),c=v.useCallback(function(m){var x=m;if(!(!Wi.length||Wi[Wi.length-1]!==o)){var b="deltaY"in x?b1(x):Af(x),y=t.current.filter(function(E){return E.name===x.type&&(E.target===x.target||x.target===E.shadowParent)&&bU(E.delta,b)})[0];if(y&&y.should){x.cancelable&&x.preventDefault();return}if(!y){var w=(a.current.shards||[]).map(x1).filter(Boolean).filter(function(E){return E.contains(x.target)}),S=w.length>0?i(x,w[0]):!a.current.noIsolation;S&&x.cancelable&&x.preventDefault()}}},[]),l=v.useCallback(function(m,x,b,y){var w={name:m,delta:x,target:b,should:y,shadowParent:CU(b)};t.current.push(w),setTimeout(function(){t.current=t.current.filter(function(S){return S!==w})},1)},[]),d=v.useCallback(function(m){n.current=Af(m),r.current=void 0},[]),p=v.useCallback(function(m){l(m.type,b1(m),m.target,i(m,e.lockRef.current))},[]),f=v.useCallback(function(m){l(m.type,Af(m),m.target,i(m,e.lockRef.current))},[]);v.useEffect(function(){return Wi.push(o),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:f}),document.addEventListener("wheel",c,qi),document.addEventListener("touchmove",c,qi),document.addEventListener("touchstart",d,qi),function(){Wi=Wi.filter(function(m){return m!==o}),document.removeEventListener("wheel",c,qi),document.removeEventListener("touchmove",c,qi),document.removeEventListener("touchstart",d,qi)}},[]);var h=e.removeScrollBar,g=e.inert;return v.createElement(v.Fragment,null,g?v.createElement(o,{styles:xU(s)}):null,h?v.createElement(dU,{gapMode:e.gapMode}):null)}function CU(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const EU=Yz(Xj,SU);var bg=v.forwardRef(function(e,t){return v.createElement(yg,_s({},e,{ref:t,sideCar:EU}))});bg.classNames=yg.classNames;var Qy=["Enter"," "],TU=["ArrowDown","PageUp","Home"],sR=["ArrowUp","PageDown","End"],kU=[...TU,...sR],_U={ltr:[...Qy,"ArrowRight"],rtl:[...Qy,"ArrowLeft"]},jU={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Qd="Menu",[ld,RU,OU]=Fx(Qd),[Ii,oR]=Vr(Qd,[OU,hg,vg]),xg=hg(),aR=vg(),[NU,Di]=Ii(Qd),[PU,Zd]=Ii(Qd),iR=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:s,onOpenChange:o,modal:a=!0}=e,i=xg(t),[c,l]=v.useState(null),d=v.useRef(!1),p=nn(o),f=Gd(s);return v.useEffect(()=>{const h=()=>{d.current=!0,document.addEventListener("pointerdown",g,{capture:!0,once:!0}),document.addEventListener("pointermove",g,{capture:!0,once:!0})},g=()=>d.current=!1;return document.addEventListener("keydown",h,{capture:!0}),()=>{document.removeEventListener("keydown",h,{capture:!0}),document.removeEventListener("pointerdown",g,{capture:!0}),document.removeEventListener("pointermove",g,{capture:!0})}},[]),u.jsx($j,{...i,children:u.jsx(NU,{scope:t,open:n,onOpenChange:p,content:c,onContentChange:l,children:u.jsx(PU,{scope:t,onClose:v.useCallback(()=>p(!1),[p]),isUsingKeyboardRef:d,dir:f,modal:a,children:r})})})};iR.displayName=Qd;var MU="MenuAnchor",Gx=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,s=xg(n);return u.jsx(Bj,{...s,...r,ref:t})});Gx.displayName=MU;var Jx="MenuPortal",[IU,lR]=Ii(Jx,{forceMount:void 0}),uR=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:s}=e,o=Di(Jx,t);return u.jsx(IU,{scope:t,forceMount:n,children:u.jsx(or,{present:n||o.open,children:u.jsx(gg,{asChild:!0,container:s,children:r})})})};uR.displayName=Jx;var $r="MenuContent",[DU,Qx]=Ii($r),cR=v.forwardRef((e,t)=>{const n=lR($r,e.__scopeMenu),{forceMount:r=n.forceMount,...s}=e,o=Di($r,e.__scopeMenu),a=Zd($r,e.__scopeMenu);return u.jsx(ld.Provider,{scope:e.__scopeMenu,children:u.jsx(or,{present:r||o.open,children:u.jsx(ld.Slot,{scope:e.__scopeMenu,children:a.modal?u.jsx(AU,{...s,ref:t}):u.jsx(FU,{...s,ref:t})})})})}),AU=v.forwardRef((e,t)=>{const n=Di($r,e.__scopeMenu),r=v.useRef(null),s=it(t,r);return v.useEffect(()=>{const o=r.current;if(o)return Wx(o)},[]),u.jsx(Zx,{...e,ref:s,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Se(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),FU=v.forwardRef((e,t)=>{const n=Di($r,e.__scopeMenu);return u.jsx(Zx,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),Zx=v.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:s,onOpenAutoFocus:o,onCloseAutoFocus:a,disableOutsidePointerEvents:i,onEntryFocus:c,onEscapeKeyDown:l,onPointerDownOutside:d,onFocusOutside:p,onInteractOutside:f,onDismiss:h,disableOutsideScroll:g,...m}=e,x=Di($r,n),b=Zd($r,n),y=xg(n),w=aR(n),S=RU(n),[E,C]=v.useState(null),k=v.useRef(null),T=it(t,k,x.onContentChange),O=v.useRef(0),M=v.useRef(""),U=v.useRef(0),I=v.useRef(null),J=v.useRef("right"),V=v.useRef(0),G=g?bg:v.Fragment,ee=g?{as:mo,allowPinchZoom:!0}:void 0,q=A=>{var W,Ce;const Y=M.current+A,de=S().filter(Re=>!Re.disabled),z=document.activeElement,se=(W=de.find(Re=>Re.ref.current===z))==null?void 0:W.textValue,ne=de.map(Re=>Re.textValue),ie=JU(ne,Y,se),oe=(Ce=de.find(Re=>Re.textValue===ie))==null?void 0:Ce.ref.current;(function Re(Le){M.current=Le,window.clearTimeout(O.current),Le!==""&&(O.current=window.setTimeout(()=>Re(""),1e3))})(Y),oe&&setTimeout(()=>oe.focus())};v.useEffect(()=>()=>window.clearTimeout(O.current),[]),Lx();const F=v.useCallback(A=>{var de,z;return J.current===((de=I.current)==null?void 0:de.side)&&ZU(A,(z=I.current)==null?void 0:z.area)},[]);return u.jsx(DU,{scope:n,searchRef:M,onItemEnter:v.useCallback(A=>{F(A)&&A.preventDefault()},[F]),onItemLeave:v.useCallback(A=>{var Y;F(A)||((Y=k.current)==null||Y.focus(),C(null))},[F]),onTriggerLeave:v.useCallback(A=>{F(A)&&A.preventDefault()},[F]),pointerGraceTimerRef:U,onPointerGraceIntentChange:v.useCallback(A=>{I.current=A},[]),children:u.jsx(G,{...ee,children:u.jsx(dg,{asChild:!0,trapped:s,onMountAutoFocus:Se(o,A=>{var Y;A.preventDefault(),(Y=k.current)==null||Y.focus({preventScroll:!0})}),onUnmountAutoFocus:a,children:u.jsx(cg,{asChild:!0,disableOutsidePointerEvents:i,onEscapeKeyDown:l,onPointerDownOutside:d,onFocusOutside:p,onInteractOutside:f,onDismiss:h,children:u.jsx(Gj,{asChild:!0,...w,dir:b.dir,orientation:"vertical",loop:r,currentTabStopId:E,onCurrentTabStopIdChange:C,onEntryFocus:Se(c,A=>{b.isUsingKeyboardRef.current||A.preventDefault()}),preventScrollOnEntryFocus:!0,children:u.jsx(zj,{role:"menu","aria-orientation":"vertical","data-state":kR(x.open),"data-radix-menu-content":"",dir:b.dir,...y,...m,ref:T,style:{outline:"none",...m.style},onKeyDown:Se(m.onKeyDown,A=>{const de=A.target.closest("[data-radix-menu-content]")===A.currentTarget,z=A.ctrlKey||A.altKey||A.metaKey,se=A.key.length===1;de&&(A.key==="Tab"&&A.preventDefault(),!z&&se&&q(A.key));const ne=k.current;if(A.target!==ne||!kU.includes(A.key))return;A.preventDefault();const oe=S().filter(W=>!W.disabled).map(W=>W.ref.current);sR.includes(A.key)&&oe.reverse(),WU(oe)}),onBlur:Se(e.onBlur,A=>{A.currentTarget.contains(A.target)||(window.clearTimeout(O.current),M.current="")}),onPointerMove:Se(e.onPointerMove,ud(A=>{const Y=A.target,de=V.current!==A.clientX;if(A.currentTarget.contains(Y)&&de){const z=A.clientX>V.current?"right":"left";J.current=z,V.current=A.clientX}}))})})})})})})});cR.displayName=$r;var LU="MenuGroup",Yx=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(Me.div,{role:"group",...r,ref:t})});Yx.displayName=LU;var $U="MenuLabel",dR=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(Me.div,{...r,ref:t})});dR.displayName=$U;var ah="MenuItem",w1="menu.itemSelect",wg=v.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...s}=e,o=v.useRef(null),a=Zd(ah,e.__scopeMenu),i=Qx(ah,e.__scopeMenu),c=it(t,o),l=v.useRef(!1),d=()=>{const p=o.current;if(!n&&p){const f=new CustomEvent(w1,{bubbles:!0,cancelable:!0});p.addEventListener(w1,h=>r==null?void 0:r(h),{once:!0}),gj(p,f),f.defaultPrevented?l.current=!1:a.onClose()}};return u.jsx(fR,{...s,ref:c,disabled:n,onClick:Se(e.onClick,d),onPointerDown:p=>{var f;(f=e.onPointerDown)==null||f.call(e,p),l.current=!0},onPointerUp:Se(e.onPointerUp,p=>{var f;l.current||(f=p.currentTarget)==null||f.click()}),onKeyDown:Se(e.onKeyDown,p=>{const f=i.searchRef.current!=="";n||f&&p.key===" "||Qy.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});wg.displayName=ah;var fR=v.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:s,...o}=e,a=Qx(ah,n),i=aR(n),c=v.useRef(null),l=it(t,c),[d,p]=v.useState(!1),[f,h]=v.useState("");return v.useEffect(()=>{const g=c.current;g&&h((g.textContent??"").trim())},[o.children]),u.jsx(ld.ItemSlot,{scope:n,disabled:r,textValue:s??f,children:u.jsx(Jj,{asChild:!0,...i,focusable:!r,children:u.jsx(Me.div,{role:"menuitem","data-highlighted":d?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...o,ref:l,onPointerMove:Se(e.onPointerMove,ud(g=>{r?a.onItemLeave(g):(a.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Se(e.onPointerLeave,ud(g=>a.onItemLeave(g))),onFocus:Se(e.onFocus,()=>p(!0)),onBlur:Se(e.onBlur,()=>p(!1))})})})}),BU="MenuCheckboxItem",pR=v.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...s}=e;return u.jsx(yR,{scope:e.__scopeMenu,checked:n,children:u.jsx(wg,{role:"menuitemcheckbox","aria-checked":ih(n)?"mixed":n,...s,ref:t,"data-state":ew(n),onSelect:Se(s.onSelect,()=>r==null?void 0:r(ih(n)?!0:!n),{checkForDefaultPrevented:!1})})})});pR.displayName=BU;var hR="MenuRadioGroup",[zU,UU]=Ii(hR,{value:void 0,onValueChange:()=>{}}),gR=v.forwardRef((e,t)=>{const{value:n,onValueChange:r,...s}=e,o=nn(r);return u.jsx(zU,{scope:e.__scopeMenu,value:n,onValueChange:o,children:u.jsx(Yx,{...s,ref:t})})});gR.displayName=hR;var mR="MenuRadioItem",vR=v.forwardRef((e,t)=>{const{value:n,...r}=e,s=UU(mR,e.__scopeMenu),o=n===s.value;return u.jsx(yR,{scope:e.__scopeMenu,checked:o,children:u.jsx(wg,{role:"menuitemradio","aria-checked":o,...r,ref:t,"data-state":ew(o),onSelect:Se(r.onSelect,()=>{var a;return(a=s.onValueChange)==null?void 0:a.call(s,n)},{checkForDefaultPrevented:!1})})})});vR.displayName=mR;var Xx="MenuItemIndicator",[yR,VU]=Ii(Xx,{checked:!1}),bR=v.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...s}=e,o=VU(Xx,n);return u.jsx(or,{present:r||ih(o.checked)||o.checked===!0,children:u.jsx(Me.span,{...s,ref:t,"data-state":ew(o.checked)})})});bR.displayName=Xx;var HU="MenuSeparator",xR=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(Me.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});xR.displayName=HU;var KU="MenuArrow",wR=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,s=xg(n);return u.jsx(Uj,{...s,...r,ref:t})});wR.displayName=KU;var qU="MenuSub",[qse,SR]=Ii(qU),dc="MenuSubTrigger",CR=v.forwardRef((e,t)=>{const n=Di(dc,e.__scopeMenu),r=Zd(dc,e.__scopeMenu),s=SR(dc,e.__scopeMenu),o=Qx(dc,e.__scopeMenu),a=v.useRef(null),{pointerGraceTimerRef:i,onPointerGraceIntentChange:c}=o,l={__scopeMenu:e.__scopeMenu},d=v.useCallback(()=>{a.current&&window.clearTimeout(a.current),a.current=null},[]);return v.useEffect(()=>d,[d]),v.useEffect(()=>{const p=i.current;return()=>{window.clearTimeout(p),c(null)}},[i,c]),u.jsx(Gx,{asChild:!0,...l,children:u.jsx(fR,{id:s.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":s.contentId,"data-state":kR(n.open),...e,ref:ag(t,s.onTriggerChange),onClick:p=>{var f;(f=e.onClick)==null||f.call(e,p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Se(e.onPointerMove,ud(p=>{o.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!a.current&&(o.onPointerGraceIntentChange(null),a.current=window.setTimeout(()=>{n.onOpenChange(!0),d()},100))})),onPointerLeave:Se(e.onPointerLeave,ud(p=>{var h,g;d();const f=(h=n.content)==null?void 0:h.getBoundingClientRect();if(f){const m=(g=n.content)==null?void 0:g.dataset.side,x=m==="right",b=x?-5:5,y=f[x?"left":"right"],w=f[x?"right":"left"];o.onPointerGraceIntentChange({area:[{x:p.clientX+b,y:p.clientY},{x:y,y:f.top},{x:w,y:f.top},{x:w,y:f.bottom},{x:y,y:f.bottom}],side:m}),window.clearTimeout(i.current),i.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(p),p.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:Se(e.onKeyDown,p=>{var h;const f=o.searchRef.current!=="";e.disabled||f&&p.key===" "||_U[r.dir].includes(p.key)&&(n.onOpenChange(!0),(h=n.content)==null||h.focus(),p.preventDefault())})})})});CR.displayName=dc;var ER="MenuSubContent",TR=v.forwardRef((e,t)=>{const n=lR($r,e.__scopeMenu),{forceMount:r=n.forceMount,...s}=e,o=Di($r,e.__scopeMenu),a=Zd($r,e.__scopeMenu),i=SR(ER,e.__scopeMenu),c=v.useRef(null),l=it(t,c);return u.jsx(ld.Provider,{scope:e.__scopeMenu,children:u.jsx(or,{present:r||o.open,children:u.jsx(ld.Slot,{scope:e.__scopeMenu,children:u.jsx(Zx,{id:i.contentId,"aria-labelledby":i.triggerId,...s,ref:l,align:"start",side:a.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:d=>{var p;a.isUsingKeyboardRef.current&&((p=c.current)==null||p.focus()),d.preventDefault()},onCloseAutoFocus:d=>d.preventDefault(),onFocusOutside:Se(e.onFocusOutside,d=>{d.target!==i.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:Se(e.onEscapeKeyDown,d=>{a.onClose(),d.preventDefault()}),onKeyDown:Se(e.onKeyDown,d=>{var h;const p=d.currentTarget.contains(d.target),f=jU[a.dir].includes(d.key);p&&f&&(o.onOpenChange(!1),(h=i.trigger)==null||h.focus(),d.preventDefault())})})})})})});TR.displayName=ER;function kR(e){return e?"open":"closed"}function ih(e){return e==="indeterminate"}function ew(e){return ih(e)?"indeterminate":e?"checked":"unchecked"}function WU(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function GU(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function JU(e,t,n){const s=t.length>1&&Array.from(t).every(l=>l===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let a=GU(e,Math.max(o,0));s.length===1&&(a=a.filter(l=>l!==n));const c=a.find(l=>l.toLowerCase().startsWith(s.toLowerCase()));return c!==n?c:void 0}function QU(e,t){const{x:n,y:r}=e;let s=!1;for(let o=0,a=t.length-1;or!=d>r&&n<(l-i)*(r-c)/(d-c)+i&&(s=!s)}return s}function ZU(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return QU(n,t)}function ud(e){return t=>t.pointerType==="mouse"?e(t):void 0}var YU=iR,XU=Gx,e5=uR,t5=cR,n5=Yx,r5=dR,s5=wg,o5=pR,a5=gR,i5=vR,l5=bR,u5=xR,c5=wR,d5=CR,f5=TR,tw="DropdownMenu",[p5,Wse]=Vr(tw,[oR]),Gn=oR(),[h5,_R]=p5(tw),nw=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:s,defaultOpen:o,onOpenChange:a,modal:i=!0}=e,c=Gn(t),l=v.useRef(null),[d=!1,p]=pa({prop:s,defaultProp:o,onChange:a});return u.jsx(h5,{scope:t,triggerId:os(),triggerRef:l,contentId:os(),open:d,onOpenChange:p,onOpenToggle:v.useCallback(()=>p(f=>!f),[p]),modal:i,children:u.jsx(YU,{...c,open:d,onOpenChange:p,dir:r,modal:i,children:n})})};nw.displayName=tw;var jR="DropdownMenuTrigger",rw=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...s}=e,o=_R(jR,n),a=Gn(n);return u.jsx(XU,{asChild:!0,...a,children:u.jsx(Me.button,{type:"button",id:o.triggerId,"aria-haspopup":"menu","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":o.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...s,ref:ag(t,o.triggerRef),onPointerDown:Se(e.onPointerDown,i=>{!r&&i.button===0&&i.ctrlKey===!1&&(o.onOpenToggle(),o.open||i.preventDefault())}),onKeyDown:Se(e.onKeyDown,i=>{r||(["Enter"," "].includes(i.key)&&o.onOpenToggle(),i.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(i.key)&&i.preventDefault())})})})});rw.displayName=jR;var g5="DropdownMenuPortal",RR=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Gn(t);return u.jsx(e5,{...r,...n})};RR.displayName=g5;var OR="DropdownMenuContent",NR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=_R(OR,n),o=Gn(n),a=v.useRef(!1);return u.jsx(t5,{id:s.contentId,"aria-labelledby":s.triggerId,...o,...r,ref:t,onCloseAutoFocus:Se(e.onCloseAutoFocus,i=>{var c;a.current||(c=s.triggerRef.current)==null||c.focus(),a.current=!1,i.preventDefault()}),onInteractOutside:Se(e.onInteractOutside,i=>{const c=i.detail.originalEvent,l=c.button===0&&c.ctrlKey===!0,d=c.button===2||l;(!s.modal||d)&&(a.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});NR.displayName=OR;var m5="DropdownMenuGroup",v5=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(n5,{...s,...r,ref:t})});v5.displayName=m5;var y5="DropdownMenuLabel",PR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(r5,{...s,...r,ref:t})});PR.displayName=y5;var b5="DropdownMenuItem",MR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(s5,{...s,...r,ref:t})});MR.displayName=b5;var x5="DropdownMenuCheckboxItem",IR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(o5,{...s,...r,ref:t})});IR.displayName=x5;var w5="DropdownMenuRadioGroup",S5=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(a5,{...s,...r,ref:t})});S5.displayName=w5;var C5="DropdownMenuRadioItem",DR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(i5,{...s,...r,ref:t})});DR.displayName=C5;var E5="DropdownMenuItemIndicator",AR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(l5,{...s,...r,ref:t})});AR.displayName=E5;var T5="DropdownMenuSeparator",FR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(u5,{...s,...r,ref:t})});FR.displayName=T5;var k5="DropdownMenuArrow",_5=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(c5,{...s,...r,ref:t})});_5.displayName=k5;var j5="DropdownMenuSubTrigger",LR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(d5,{...s,...r,ref:t})});LR.displayName=j5;var R5="DropdownMenuSubContent",$R=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(f5,{...s,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});$R.displayName=R5;var O5=nw,N5=rw,P5=RR,BR=NR,zR=PR,UR=MR,VR=IR,HR=DR,KR=AR,Ra=FR,qR=LR,WR=$R;const Eo=O5,To=N5,M5=v.forwardRef(({className:e,inset:t,children:n,...r},s)=>u.jsxs(qR,{ref:s,className:ge("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",e),...r,children:[n,u.jsx(R3,{className:"ml-auto h-4 w-4"})]}));M5.displayName=qR.displayName;const I5=v.forwardRef(({className:e,...t},n)=>u.jsx(WR,{ref:n,className:ge("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));I5.displayName=WR.displayName;const ps=v.forwardRef(({className:e,sideOffset:t=4,...n},r)=>u.jsx(P5,{children:u.jsx(BR,{ref:r,sideOffset:t,className:ge("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})}));ps.displayName=BR.displayName;const ft=v.forwardRef(({className:e,inset:t,...n},r)=>u.jsx(UR,{ref:r,className:ge("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));ft.displayName=UR.displayName;const GR=v.forwardRef(({className:e,children:t,checked:n,...r},s)=>u.jsxs(VR,{ref:s,className:ge("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(KR,{children:u.jsx(cj,{className:"h-4 w-4"})})}),t]}));GR.displayName=VR.displayName;const D5=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(HR,{ref:r,className:ge("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(KR,{children:u.jsx(M3,{className:"h-2 w-2 fill-current"})})}),t]}));D5.displayName=HR.displayName;const Ai=v.forwardRef(({className:e,inset:t,...n},r)=>u.jsx(zR,{ref:r,className:ge("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));Ai.displayName=zR.displayName;const Oa=v.forwardRef(({className:e,...t},n)=>u.jsx(Ra,{ref:n,className:ge("-mx-1 my-1 h-px bg-muted",e),...t}));Oa.displayName=Ra.displayName;function A5(){const{t:e,i18n:t}=ze(),n=r=>{t.changeLanguage(r),localStorage.setItem("i18nextLng",r),window.location.reload()};return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(K,{variant:"outline",size:"icon",children:[u.jsx(z3,{className:"h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all"}),u.jsx("span",{className:"sr-only",children:e("header.theme.label")})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(ft,{className:t.language==="pt-BR"?"font-bold":"",onClick:()=>n("pt-BR"),children:e("header.language.portuguese")}),u.jsx(ft,{className:t.language==="en-US"?"font-bold":"",onClick:()=>n("en-US"),children:e("header.language.english")}),u.jsx(ft,{className:t.language==="es-ES"?"font-bold":"",onClick:()=>n("es-ES"),children:e("header.language.spanish")}),u.jsx(ft,{className:t.language==="fr-FR"?"font-bold":"",onClick:()=>n("fr-FR"),children:e("header.language.french")})]})]})}function F5(){const{t:e}=ze(),{setTheme:t}=R_();return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(K,{variant:"outline",size:"icon",children:[u.jsx(G3,{className:"h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),u.jsx(K3,{className:"absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),u.jsx("span",{className:"sr-only",children:e("header.theme.label")})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(ft,{onClick:()=>t("light"),children:e("header.theme.light")}),u.jsx(ft,{onClick:()=>t("dark"),children:e("header.theme.dark")}),u.jsx(ft,{onClick:()=>t("system"),children:e("header.theme.system")})]})]})}var sw="Avatar",[L5,Gse]=Vr(sw),[$5,JR]=L5(sw),QR=v.forwardRef((e,t)=>{const{__scopeAvatar:n,...r}=e,[s,o]=v.useState("idle");return u.jsx($5,{scope:n,imageLoadingStatus:s,onImageLoadingStatusChange:o,children:u.jsx(Me.span,{...r,ref:t})})});QR.displayName=sw;var ZR="AvatarImage",YR=v.forwardRef((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:s=()=>{},...o}=e,a=JR(ZR,n),i=B5(r),c=nn(l=>{s(l),a.onImageLoadingStatusChange(l)});return fn(()=>{i!=="idle"&&c(i)},[i,c]),i==="loaded"?u.jsx(Me.img,{...o,ref:t,src:r}):null});YR.displayName=ZR;var XR="AvatarFallback",eO=v.forwardRef((e,t)=>{const{__scopeAvatar:n,delayMs:r,...s}=e,o=JR(XR,n),[a,i]=v.useState(r===void 0);return v.useEffect(()=>{if(r!==void 0){const c=window.setTimeout(()=>i(!0),r);return()=>window.clearTimeout(c)}},[r]),a&&o.imageLoadingStatus!=="loaded"?u.jsx(Me.span,{...s,ref:t}):null});eO.displayName=XR;function B5(e){const[t,n]=v.useState("idle");return fn(()=>{if(!e){n("error");return}let r=!0;const s=new window.Image,o=a=>()=>{r&&n(a)};return n("loading"),s.onload=o("loaded"),s.onerror=o("error"),s.src=e,()=>{r=!1}},[e]),t}var tO=QR,nO=YR,rO=eO;const Sg=v.forwardRef(({className:e,...t},n)=>u.jsx(tO,{ref:n,className:ge("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));Sg.displayName=tO.displayName;const Cg=v.forwardRef(({className:e,...t},n)=>u.jsx(nO,{ref:n,className:ge("aspect-square h-full w-full",e),...t}));Cg.displayName=nO.displayName;const z5=v.forwardRef(({className:e,...t},n)=>u.jsx(rO,{ref:n,className:ge("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));z5.displayName=rO.displayName;var ow="Dialog",[sO,Jse]=Vr(ow),[U5,hs]=sO(ow),oO=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:s,onOpenChange:o,modal:a=!0}=e,i=v.useRef(null),c=v.useRef(null),[l=!1,d]=pa({prop:r,defaultProp:s,onChange:o});return u.jsx(U5,{scope:t,triggerRef:i,contentRef:c,contentId:os(),titleId:os(),descriptionId:os(),open:l,onOpenChange:d,onOpenToggle:v.useCallback(()=>d(p=>!p),[d]),modal:a,children:n})};oO.displayName=ow;var aO="DialogTrigger",iO=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=hs(aO,n),o=it(t,s.triggerRef);return u.jsx(Me.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":lw(s.open),...r,ref:o,onClick:Se(e.onClick,s.onOpenToggle)})});iO.displayName=aO;var aw="DialogPortal",[V5,lO]=sO(aw,{forceMount:void 0}),uO=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:s}=e,o=hs(aw,t);return u.jsx(V5,{scope:t,forceMount:n,children:v.Children.map(r,a=>u.jsx(or,{present:n||o.open,children:u.jsx(gg,{asChild:!0,container:s,children:a})}))})};uO.displayName=aw;var lh="DialogOverlay",cO=v.forwardRef((e,t)=>{const n=lO(lh,e.__scopeDialog),{forceMount:r=n.forceMount,...s}=e,o=hs(lh,e.__scopeDialog);return o.modal?u.jsx(or,{present:r||o.open,children:u.jsx(H5,{...s,ref:t})}):null});cO.displayName=lh;var H5=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=hs(lh,n);return u.jsx(bg,{as:mo,allowPinchZoom:!0,shards:[s.contentRef],children:u.jsx(Me.div,{"data-state":lw(s.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Ei="DialogContent",dO=v.forwardRef((e,t)=>{const n=lO(Ei,e.__scopeDialog),{forceMount:r=n.forceMount,...s}=e,o=hs(Ei,e.__scopeDialog);return u.jsx(or,{present:r||o.open,children:o.modal?u.jsx(K5,{...s,ref:t}):u.jsx(q5,{...s,ref:t})})});dO.displayName=Ei;var K5=v.forwardRef((e,t)=>{const n=hs(Ei,e.__scopeDialog),r=v.useRef(null),s=it(t,n.contentRef,r);return v.useEffect(()=>{const o=r.current;if(o)return Wx(o)},[]),u.jsx(fO,{...e,ref:s,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Se(e.onCloseAutoFocus,o=>{var a;o.preventDefault(),(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:Se(e.onPointerDownOutside,o=>{const a=o.detail.originalEvent,i=a.button===0&&a.ctrlKey===!0;(a.button===2||i)&&o.preventDefault()}),onFocusOutside:Se(e.onFocusOutside,o=>o.preventDefault())})}),q5=v.forwardRef((e,t)=>{const n=hs(Ei,e.__scopeDialog),r=v.useRef(!1),s=v.useRef(!1);return u.jsx(fO,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var a,i;(a=e.onCloseAutoFocus)==null||a.call(e,o),o.defaultPrevented||(r.current||(i=n.triggerRef.current)==null||i.focus(),o.preventDefault()),r.current=!1,s.current=!1},onInteractOutside:o=>{var c,l;(c=e.onInteractOutside)==null||c.call(e,o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(s.current=!0));const a=o.target;((l=n.triggerRef.current)==null?void 0:l.contains(a))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&s.current&&o.preventDefault()}})}),fO=v.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:s,onCloseAutoFocus:o,...a}=e,i=hs(Ei,n),c=v.useRef(null),l=it(t,c);return Lx(),u.jsxs(u.Fragment,{children:[u.jsx(dg,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:s,onUnmountAutoFocus:o,children:u.jsx(cg,{role:"dialog",id:i.contentId,"aria-describedby":i.descriptionId,"aria-labelledby":i.titleId,"data-state":lw(i.open),...a,ref:l,onDismiss:()=>i.onOpenChange(!1)})}),u.jsxs(u.Fragment,{children:[u.jsx(W5,{titleId:i.titleId}),u.jsx(J5,{contentRef:c,descriptionId:i.descriptionId})]})]})}),iw="DialogTitle",pO=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=hs(iw,n);return u.jsx(Me.h2,{id:s.titleId,...r,ref:t})});pO.displayName=iw;var hO="DialogDescription",gO=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=hs(hO,n);return u.jsx(Me.p,{id:s.descriptionId,...r,ref:t})});gO.displayName=hO;var mO="DialogClose",vO=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=hs(mO,n);return u.jsx(Me.button,{type:"button",...r,ref:t,onClick:Se(e.onClick,()=>s.onOpenChange(!1))})});vO.displayName=mO;function lw(e){return e?"open":"closed"}var yO="DialogTitleWarning",[Qse,bO]=X3(yO,{contentName:Ei,titleName:iw,docsSlug:"dialog"}),W5=({titleId:e})=>{const t=bO(yO),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users. + +If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component. + +For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return v.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},G5="DialogDescriptionWarning",J5=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${bO(G5).contentName}}.`;return v.useEffect(()=>{var o;const s=(o=e.current)==null?void 0:o.getAttribute("aria-describedby");t&&s&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},Q5=oO,Z5=iO,Y5=uO,xO=cO,wO=dO,SO=pO,CO=gO,EO=vO;const Tt=Q5,Mt=Z5,X5=Y5,TO=EO,kO=v.forwardRef(({className:e,...t},n)=>u.jsx(xO,{ref:n,className:ge("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));kO.displayName=xO.displayName;const xt=v.forwardRef(({className:e,children:t,closeBtn:n=!0,...r},s)=>u.jsx(X5,{children:u.jsx(kO,{className:"fixed inset-0 grid place-items-center overflow-y-auto",children:u.jsxs(wO,{ref:s,className:ge("relative z-50 grid w-full max-w-lg gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:m-4 sm:rounded-lg md:w-full",e),...r,children:[t,n&&u.jsxs(EO,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[u.jsx(Q3,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})})}));xt.displayName=wO.displayName;const wt=({className:e,...t})=>u.jsx("div",{className:ge("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});wt.displayName="DialogHeader";const rn=({className:e,...t})=>u.jsx("div",{className:ge("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});rn.displayName="DialogFooter";const Ut=v.forwardRef(({className:e,...t},n)=>u.jsx(SO,{ref:n,className:ge("text-lg font-semibold leading-none tracking-tight",e),...t}));Ut.displayName=SO.displayName;const Fi=v.forwardRef(({className:e,...t},n)=>u.jsx(CO,{ref:n,className:ge("text-sm text-muted-foreground",e),...t}));Fi.displayName=CO.displayName;function _O({instanceId:e}){const[t,n]=v.useState(!1),r=An(),s=()=>{N_(),r("/manager/login")},o=()=>{r("/manager/")},{data:a}=hj({instanceId:e});return u.jsxs("header",{className:"flex items-center justify-between px-4 py-2",children:[u.jsxs(nd,{to:"/manager",onClick:o,className:"flex h-8 items-center gap-4",children:[u.jsx("img",{src:"/assets/images/evolution-logo.png",alt:"Logo",className:"h-full"}),u.jsx("span",{children:"Evolution Manager"})]}),u.jsxs("div",{className:"flex items-center gap-4",children:[e&&u.jsx(Sg,{className:"h-8 w-8",children:u.jsx(Cg,{src:(a==null?void 0:a.profilePicUrl)||"/assets/images/evolution-logo.png",alt:a==null?void 0:a.name})}),u.jsx(A5,{}),u.jsx(F5,{}),u.jsx(K,{onClick:()=>n(!0),variant:"destructive",size:"icon",children:u.jsx(D3,{size:"18"})})]}),t&&u.jsx(Tt,{onOpenChange:n,open:t,children:u.jsxs(xt,{children:[u.jsx(TO,{}),u.jsx(wt,{children:"Deseja realmente sair?"}),u.jsx(rn,{children:u.jsxs("div",{className:"flex items-center gap-4",children:[u.jsx(K,{onClick:()=>n(!1),size:"sm",variant:"outline",children:"Cancelar"}),u.jsx(K,{onClick:s,variant:"destructive",children:"Sair"})]})})]})})]})}const jO=v.createContext(null),nt=()=>{const e=v.useContext(jO);if(!e)throw new Error("useInstance must be used within an InstanceProvider");return e},eV=({children:e})=>{const t=So(),[n,r]=v.useState(null),{data:s,refetch:o}=hj({instanceId:n});return v.useEffect(()=>{t.instanceId?r(t.instanceId):r(null)},[t]),u.jsx(jO.Provider,{value:{instance:s??null,reloadInstance:async()=>{await o()}},children:e})};var uw="Collapsible",[tV,Zse]=Vr(uw),[nV,cw]=tV(uw),RO=v.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:s,disabled:o,onOpenChange:a,...i}=e,[c=!1,l]=pa({prop:r,defaultProp:s,onChange:a});return u.jsx(nV,{scope:n,disabled:o,contentId:os(),open:c,onOpenToggle:v.useCallback(()=>l(d=>!d),[l]),children:u.jsx(Me.div,{"data-state":fw(c),"data-disabled":o?"":void 0,...i,ref:t})})});RO.displayName=uw;var OO="CollapsibleTrigger",NO=v.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,s=cw(OO,n);return u.jsx(Me.button,{type:"button","aria-controls":s.contentId,"aria-expanded":s.open||!1,"data-state":fw(s.open),"data-disabled":s.disabled?"":void 0,disabled:s.disabled,...r,ref:t,onClick:Se(e.onClick,s.onOpenToggle)})});NO.displayName=OO;var dw="CollapsibleContent",PO=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=cw(dw,e.__scopeCollapsible);return u.jsx(or,{present:n||s.open,children:({present:o})=>u.jsx(rV,{...r,ref:t,present:o})})});PO.displayName=dw;var rV=v.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:s,...o}=e,a=cw(dw,n),[i,c]=v.useState(r),l=v.useRef(null),d=it(t,l),p=v.useRef(0),f=p.current,h=v.useRef(0),g=h.current,m=a.open||i,x=v.useRef(m),b=v.useRef();return v.useEffect(()=>{const y=requestAnimationFrame(()=>x.current=!1);return()=>cancelAnimationFrame(y)},[]),fn(()=>{const y=l.current;if(y){b.current=b.current||{transitionDuration:y.style.transitionDuration,animationName:y.style.animationName},y.style.transitionDuration="0s",y.style.animationName="none";const w=y.getBoundingClientRect();p.current=w.height,h.current=w.width,x.current||(y.style.transitionDuration=b.current.transitionDuration,y.style.animationName=b.current.animationName),c(r)}},[a.open,r]),u.jsx(Me.div,{"data-state":fw(a.open),"data-disabled":a.disabled?"":void 0,id:a.contentId,hidden:!m,...o,ref:d,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...e.style},children:m&&s})});function fw(e){return e?"open":"closed"}var sV=RO;const oV=sV,aV=NO,iV=PO;function lV(){const{t:e}=ze(),t=v.useMemo(()=>[{id:"dashboard",title:e("sidebar.dashboard"),icon:U3,path:"dashboard"},{navLabel:!0,title:e("sidebar.configurations"),icon:Pi,children:[{id:"settings",title:e("sidebar.settings"),path:"settings"},{id:"proxy",title:e("sidebar.proxy"),path:"proxy"}]},{title:e("sidebar.events"),icon:B3,children:[{id:"webhook",title:e("sidebar.webhook"),path:"webhook"},{id:"websocket",title:e("sidebar.websocket"),path:"websocket"},{id:"rabbitmq",title:e("sidebar.rabbitmq"),path:"rabbitmq"},{id:"sqs",title:e("sidebar.sqs"),path:"sqs"}]},{title:e("sidebar.integrations"),icon:pj,children:[{id:"evolutionBot",title:e("sidebar.evolutionBot"),path:"evolutionBot"},{id:"chatwoot",title:e("sidebar.chatwoot"),path:"chatwoot"},{id:"typebot",title:e("sidebar.typebot"),path:"typebot"},{id:"openai",title:e("sidebar.openai"),path:"openai"},{id:"dify",title:e("sidebar.dify"),path:"dify"},{id:"flowise",title:e("sidebar.flowise"),path:"flowise"}]},{id:"documentation",title:e("sidebar.documentation"),icon:L3,link:"https://doc.evolution-api.com",divider:!0},{id:"postman",title:e("sidebar.postman"),icon:P3,link:"https://evolution-api.com/postman"},{id:"discord",title:e("sidebar.discord"),icon:ug,link:"https://evolution-api.com/discord"},{id:"support-premium",title:e("sidebar.supportPremium"),icon:V3,link:"https://evolution-api.com/suporte-pro"}],[e]),n=An(),{pathname:r}=pu(),{instance:s}=nt(),o=i=>{!i||!s||(i.path&&n(`/manager/instance/${s.id}/${i.path}`),i.link&&window.open(i.link,"_blank"))},a=v.useMemo(()=>t.map(i=>{var c;return{...i,children:"children"in i?(c=i.children)==null?void 0:c.map(l=>({...l,isActive:"path"in l?r.includes(l.path):!1})):void 0,isActive:"path"in i&&i.path?r.includes(i.path):!1}}).map(i=>{var c;return{...i,isActive:i.isActive||"children"in i&&((c=i.children)==null?void 0:c.some(l=>l.isActive))}}),[t,r]);return u.jsx("ul",{className:"flex h-full w-full flex-col gap-2 border-r border-border px-2",children:a.map(i=>u.jsx("li",{className:"divider"in i?"mt-auto":void 0,children:i.children?u.jsxs(oV,{defaultOpen:i.isActive,children:[u.jsx(aV,{asChild:!0,children:u.jsxs(K,{className:ge("flex w-full items-center justify-start gap-2"),variant:i.isActive?"secondary":"link",children:[i.icon&&u.jsx(i.icon,{size:"15"}),u.jsx("span",{children:i.title}),u.jsx(lg,{size:"15",className:"ml-auto"})]})}),u.jsx(iV,{children:u.jsx("ul",{className:"my-4 ml-6 flex flex-col gap-2 text-sm",children:i.children.map(c=>u.jsx("li",{children:u.jsx("button",{onClick:()=>o(c),className:ge(c.isActive?"text-foreground":"text-muted-foreground"),children:u.jsx("span",{className:"nav-label",children:c.title})})},c.id))})})]}):u.jsxs(K,{className:ge("relative flex w-full items-center justify-start gap-2",i.isActive&&"pointer-events-none"),variant:i.isActive?"secondary":"link",children:["link"in i&&u.jsx("a",{href:i.link,target:"_blank",rel:"noreferrer",className:"absolute inset-0 h-full w-full"}),"path"in i&&u.jsx(nd,{to:`/manager/instance/${s==null?void 0:s.id}/${i.path}`,className:"absolute inset-0 h-full w-full"}),i.icon&&u.jsx(i.icon,{size:"15"}),u.jsx("span",{children:i.title})]})},i.title))})}function Zy(e,[t,n]){return Math.min(n,Math.max(t,e))}function uV(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var pw="ScrollArea",[MO,Yse]=Vr(pw),[cV,Hr]=MO(pw),IO=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:s,scrollHideDelay:o=600,...a}=e,[i,c]=v.useState(null),[l,d]=v.useState(null),[p,f]=v.useState(null),[h,g]=v.useState(null),[m,x]=v.useState(null),[b,y]=v.useState(0),[w,S]=v.useState(0),[E,C]=v.useState(!1),[k,T]=v.useState(!1),O=it(t,U=>c(U)),M=Gd(s);return u.jsx(cV,{scope:n,type:r,dir:M,scrollHideDelay:o,scrollArea:i,viewport:l,onViewportChange:d,content:p,onContentChange:f,scrollbarX:h,onScrollbarXChange:g,scrollbarXEnabled:E,onScrollbarXEnabledChange:C,scrollbarY:m,onScrollbarYChange:x,scrollbarYEnabled:k,onScrollbarYEnabledChange:T,onCornerWidthChange:y,onCornerHeightChange:S,children:u.jsx(Me.div,{dir:M,...a,ref:O,style:{position:"relative","--radix-scroll-area-corner-width":b+"px","--radix-scroll-area-corner-height":w+"px",...e.style}})})});IO.displayName=pw;var DO="ScrollAreaViewport",AO=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:s,...o}=e,a=Hr(DO,n),i=v.useRef(null),c=it(t,i,a.onViewportChange);return u.jsxs(u.Fragment,{children:[u.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:s}),u.jsx(Me.div,{"data-radix-scroll-area-viewport":"",...o,ref:c,style:{overflowX:a.scrollbarXEnabled?"scroll":"hidden",overflowY:a.scrollbarYEnabled?"scroll":"hidden",...e.style},children:u.jsx("div",{ref:a.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});AO.displayName=DO;var Hs="ScrollAreaScrollbar",hw=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=Hr(Hs,e.__scopeScrollArea),{onScrollbarXEnabledChange:o,onScrollbarYEnabledChange:a}=s,i=e.orientation==="horizontal";return v.useEffect(()=>(i?o(!0):a(!0),()=>{i?o(!1):a(!1)}),[i,o,a]),s.type==="hover"?u.jsx(dV,{...r,ref:t,forceMount:n}):s.type==="scroll"?u.jsx(fV,{...r,ref:t,forceMount:n}):s.type==="auto"?u.jsx(FO,{...r,ref:t,forceMount:n}):s.type==="always"?u.jsx(gw,{...r,ref:t}):null});hw.displayName=Hs;var dV=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=Hr(Hs,e.__scopeScrollArea),[o,a]=v.useState(!1);return v.useEffect(()=>{const i=s.scrollArea;let c=0;if(i){const l=()=>{window.clearTimeout(c),a(!0)},d=()=>{c=window.setTimeout(()=>a(!1),s.scrollHideDelay)};return i.addEventListener("pointerenter",l),i.addEventListener("pointerleave",d),()=>{window.clearTimeout(c),i.removeEventListener("pointerenter",l),i.removeEventListener("pointerleave",d)}}},[s.scrollArea,s.scrollHideDelay]),u.jsx(or,{present:n||o,children:u.jsx(FO,{"data-state":o?"visible":"hidden",...r,ref:t})})}),fV=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=Hr(Hs,e.__scopeScrollArea),o=e.orientation==="horizontal",a=Tg(()=>c("SCROLL_END"),100),[i,c]=uV("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return v.useEffect(()=>{if(i==="idle"){const l=window.setTimeout(()=>c("HIDE"),s.scrollHideDelay);return()=>window.clearTimeout(l)}},[i,s.scrollHideDelay,c]),v.useEffect(()=>{const l=s.viewport,d=o?"scrollLeft":"scrollTop";if(l){let p=l[d];const f=()=>{const h=l[d];p!==h&&(c("SCROLL"),a()),p=h};return l.addEventListener("scroll",f),()=>l.removeEventListener("scroll",f)}},[s.viewport,o,c,a]),u.jsx(or,{present:n||i!=="hidden",children:u.jsx(gw,{"data-state":i==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:Se(e.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:Se(e.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),FO=v.forwardRef((e,t)=>{const n=Hr(Hs,e.__scopeScrollArea),{forceMount:r,...s}=e,[o,a]=v.useState(!1),i=e.orientation==="horizontal",c=Tg(()=>{if(n.viewport){const l=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,s=Hr(Hs,e.__scopeScrollArea),o=v.useRef(null),a=v.useRef(0),[i,c]=v.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),l=UO(i.viewport,i.content),d={...r,sizes:i,onSizesChange:c,hasThumb:l>0&&l<1,onThumbChange:f=>o.current=f,onThumbPointerUp:()=>a.current=0,onThumbPointerDown:f=>a.current=f};function p(f,h){return yV(f,a.current,i,h)}return n==="horizontal"?u.jsx(pV,{...d,ref:t,onThumbPositionChange:()=>{if(s.viewport&&o.current){const f=s.viewport.scrollLeft,h=S1(f,i,s.dir);o.current.style.transform=`translate3d(${h}px, 0, 0)`}},onWheelScroll:f=>{s.viewport&&(s.viewport.scrollLeft=f)},onDragScroll:f=>{s.viewport&&(s.viewport.scrollLeft=p(f,s.dir))}}):n==="vertical"?u.jsx(hV,{...d,ref:t,onThumbPositionChange:()=>{if(s.viewport&&o.current){const f=s.viewport.scrollTop,h=S1(f,i);o.current.style.transform=`translate3d(0, ${h}px, 0)`}},onWheelScroll:f=>{s.viewport&&(s.viewport.scrollTop=f)},onDragScroll:f=>{s.viewport&&(s.viewport.scrollTop=p(f))}}):null}),pV=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...s}=e,o=Hr(Hs,e.__scopeScrollArea),[a,i]=v.useState(),c=v.useRef(null),l=it(t,c,o.onScrollbarXChange);return v.useEffect(()=>{c.current&&i(getComputedStyle(c.current))},[c]),u.jsx($O,{"data-orientation":"horizontal",...s,ref:l,sizes:n,style:{bottom:0,left:o.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:o.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Eg(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,p)=>{if(o.viewport){const f=o.viewport.scrollLeft+d.deltaX;e.onWheelScroll(f),HO(f,p)&&d.preventDefault()}},onResize:()=>{c.current&&o.viewport&&a&&r({content:o.viewport.scrollWidth,viewport:o.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:ch(a.paddingLeft),paddingEnd:ch(a.paddingRight)}})}})}),hV=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...s}=e,o=Hr(Hs,e.__scopeScrollArea),[a,i]=v.useState(),c=v.useRef(null),l=it(t,c,o.onScrollbarYChange);return v.useEffect(()=>{c.current&&i(getComputedStyle(c.current))},[c]),u.jsx($O,{"data-orientation":"vertical",...s,ref:l,sizes:n,style:{top:0,right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Eg(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,p)=>{if(o.viewport){const f=o.viewport.scrollTop+d.deltaY;e.onWheelScroll(f),HO(f,p)&&d.preventDefault()}},onResize:()=>{c.current&&o.viewport&&a&&r({content:o.viewport.scrollHeight,viewport:o.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:ch(a.paddingTop),paddingEnd:ch(a.paddingBottom)}})}})}),[gV,LO]=MO(Hs),$O=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:s,onThumbChange:o,onThumbPointerUp:a,onThumbPointerDown:i,onThumbPositionChange:c,onDragScroll:l,onWheelScroll:d,onResize:p,...f}=e,h=Hr(Hs,n),[g,m]=v.useState(null),x=it(t,O=>m(O)),b=v.useRef(null),y=v.useRef(""),w=h.viewport,S=r.content-r.viewport,E=nn(d),C=nn(c),k=Tg(p,10);function T(O){if(b.current){const M=O.clientX-b.current.left,U=O.clientY-b.current.top;l({x:M,y:U})}}return v.useEffect(()=>{const O=M=>{const U=M.target;(g==null?void 0:g.contains(U))&&E(M,S)};return document.addEventListener("wheel",O,{passive:!1}),()=>document.removeEventListener("wheel",O,{passive:!1})},[w,g,S,E]),v.useEffect(C,[r,C]),tu(g,k),tu(h.content,k),u.jsx(gV,{scope:n,scrollbar:g,hasThumb:s,onThumbChange:nn(o),onThumbPointerUp:nn(a),onThumbPositionChange:C,onThumbPointerDown:nn(i),children:u.jsx(Me.div,{...f,ref:x,style:{position:"absolute",...f.style},onPointerDown:Se(e.onPointerDown,O=>{O.button===0&&(O.target.setPointerCapture(O.pointerId),b.current=g.getBoundingClientRect(),y.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",h.viewport&&(h.viewport.style.scrollBehavior="auto"),T(O))}),onPointerMove:Se(e.onPointerMove,T),onPointerUp:Se(e.onPointerUp,O=>{const M=O.target;M.hasPointerCapture(O.pointerId)&&M.releasePointerCapture(O.pointerId),document.body.style.webkitUserSelect=y.current,h.viewport&&(h.viewport.style.scrollBehavior=""),b.current=null})})})}),uh="ScrollAreaThumb",BO=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=LO(uh,e.__scopeScrollArea);return u.jsx(or,{present:n||s.hasThumb,children:u.jsx(mV,{ref:t,...r})})}),mV=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...s}=e,o=Hr(uh,n),a=LO(uh,n),{onThumbPositionChange:i}=a,c=it(t,p=>a.onThumbChange(p)),l=v.useRef(),d=Tg(()=>{l.current&&(l.current(),l.current=void 0)},100);return v.useEffect(()=>{const p=o.viewport;if(p){const f=()=>{if(d(),!l.current){const h=bV(p,i);l.current=h,i()}};return i(),p.addEventListener("scroll",f),()=>p.removeEventListener("scroll",f)}},[o.viewport,d,i]),u.jsx(Me.div,{"data-state":a.hasThumb?"visible":"hidden",...s,ref:c,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:Se(e.onPointerDownCapture,p=>{const h=p.target.getBoundingClientRect(),g=p.clientX-h.left,m=p.clientY-h.top;a.onThumbPointerDown({x:g,y:m})}),onPointerUp:Se(e.onPointerUp,a.onThumbPointerUp)})});BO.displayName=uh;var mw="ScrollAreaCorner",zO=v.forwardRef((e,t)=>{const n=Hr(mw,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?u.jsx(vV,{...e,ref:t}):null});zO.displayName=mw;var vV=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,s=Hr(mw,n),[o,a]=v.useState(0),[i,c]=v.useState(0),l=!!(o&&i);return tu(s.scrollbarX,()=>{var p;const d=((p=s.scrollbarX)==null?void 0:p.offsetHeight)||0;s.onCornerHeightChange(d),c(d)}),tu(s.scrollbarY,()=>{var p;const d=((p=s.scrollbarY)==null?void 0:p.offsetWidth)||0;s.onCornerWidthChange(d),a(d)}),l?u.jsx(Me.div,{...r,ref:t,style:{width:o,height:i,position:"absolute",right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function ch(e){return e?parseInt(e,10):0}function UO(e,t){const n=e/t;return isNaN(n)?0:n}function Eg(e){const t=UO(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function yV(e,t,n,r="ltr"){const s=Eg(n),o=s/2,a=t||o,i=s-a,c=n.scrollbar.paddingStart+a,l=n.scrollbar.size-n.scrollbar.paddingEnd-i,d=n.content-n.viewport,p=r==="ltr"?[0,d]:[d*-1,0];return VO([c,l],p)(e)}function S1(e,t,n="ltr"){const r=Eg(t),s=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,o=t.scrollbar.size-s,a=t.content-t.viewport,i=o-r,c=n==="ltr"?[0,a]:[a*-1,0],l=Zy(e,c);return VO([0,a],[0,i])(l)}function VO(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function HO(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function s(){const o={left:e.scrollLeft,top:e.scrollTop},a=n.left!==o.left,i=n.top!==o.top;(a||i)&&t(),n=o,r=window.requestAnimationFrame(s)}(),()=>window.cancelAnimationFrame(r)};function Tg(e,t){const n=nn(e),r=v.useRef(0);return v.useEffect(()=>()=>window.clearTimeout(r.current),[]),v.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function tu(e,t){const n=nn(t);fn(()=>{let r=0;if(e){const s=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return s.observe(e),()=>{window.cancelAnimationFrame(r),s.unobserve(e)}}},[e,n])}var KO=IO,xV=AO,wV=zO;const Yy=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(KO,{ref:r,className:ge("relative overflow-hidden",e),...n,children:[u.jsx(xV,{className:"h-full w-full rounded-[inherit] [&>div[style]]:!block [&>div[style]]:h-full",children:t}),u.jsx(qO,{}),u.jsx(wV,{})]}));Yy.displayName=KO.displayName;const qO=v.forwardRef(({className:e,orientation:t="vertical",...n},r)=>u.jsx(hw,{ref:r,orientation:t,className:ge("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 border-t border-t-transparent p-[1px]",e),...n,children:u.jsx(BO,{className:ge("relative rounded-full bg-border",t==="vertical"&&"flex-1")})}));qO.displayName=hw.displayName;function Xt({children:e}){const{instanceId:t}=So();return u.jsx(eV,{children:u.jsxs("div",{className:"flex h-screen flex-col",children:[u.jsx(_O,{instanceId:t}),u.jsxs("div",{className:"flex min-h-[calc(100vh_-_56px)] flex-1 flex-col md:flex-row",children:[u.jsx(Yy,{className:"mr-2 py-6 md:w-64",children:u.jsx("div",{className:"flex h-full",children:u.jsx(lV,{})})}),u.jsx(Yy,{className:"w-full",children:u.jsxs("div",{className:"flex h-full flex-col",children:[u.jsx("div",{className:"my-6 flex flex-1 flex-col gap-2 pl-2 pr-4",children:e}),u.jsx(Ax,{})]})})]})]})})}function SV({children:e}){return u.jsxs("div",{className:"flex h-full min-h-screen flex-col",children:[u.jsx(_O,{}),u.jsx("main",{className:"flex-1",children:e}),u.jsx(Ax,{})]})}const CV=ig("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",warning:"border-transparent bg-amber-600 text-amber-100 hover:bg-amber-600/80"}},defaultVariants:{variant:"default"}});function Ff({className:e,variant:t,...n}){return u.jsx("div",{className:ge(CV({variant:t}),e),...n})}function WO({status:e}){const{t}=ze();return e?e==="open"?u.jsx(Ff,{children:t("status.open")}):e==="connecting"?u.jsx(Ff,{variant:"warning",children:t("status.connecting")}):e==="close"||e==="closed"?u.jsx(Ff,{variant:"destructive",children:t("status.closed")}):u.jsx(Ff,{variant:"secondary",children:e}):null}const EV=e=>{navigator.clipboard.writeText(e),X.success("Copiado para a área de transferência")};function GO({token:e,className:t}){const[n,r]=v.useState(!1);return u.jsxs("div",{className:ge("flex items-center gap-3 truncate rounded-sm bg-primary/20 px-2 py-1",t),children:[u.jsx("pre",{className:"block truncate text-xs",children:n?e:e==null?void 0:e.replace(/\w/g,"*")}),u.jsx(K,{variant:"ghost",size:"icon",onClick:()=>{EV(e)},children:u.jsx(I3,{size:"15"})}),u.jsx(K,{variant:"ghost",size:"icon",onClick:()=>{r(s=>!s)},children:n?u.jsx(A3,{size:"15"}):u.jsx(F3,{size:"15"})})]})}const Ja=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ge("flex flex-col rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));Ja.displayName="Card";const Qa=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ge("flex flex-col space-y-1.5 p-6",e),...t}));Qa.displayName="CardHeader";const jc=v.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:ge("text-2xl font-semibold leading-none tracking-tight",e),...t}));jc.displayName="CardTitle";const JO=v.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:ge("text-sm text-muted-foreground",e),...t}));JO.displayName="CardDescription";const Za=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ge("p-6 pt-0",e),...t}));Za.displayName="CardContent";const kg=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ge("flex items-center p-6 pt-0",e),...t}));kg.displayName="CardFooter";const QO="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",Q=v.forwardRef(({className:e,type:t,...n},r)=>u.jsx("input",{type:t,className:ge(QO,e),ref:r,...n}));Q.displayName="Input";const TV=["instance","fetchInstances"],kV=async()=>(await he.get("/instance/fetchInstances")).data,_V=e=>lt({...e,queryKey:TV,queryFn:()=>kV()});function Ye(e,t){const n=Ab(),r=WD({mutationFn:e});return(s,o)=>r.mutateAsync(s,{onSuccess:async(a,i,c)=>{var l;t!=null&&t.invalidateKeys&&await Promise.all(t.invalidateKeys.map(d=>n.invalidateQueries({queryKey:d}))),(l=o==null?void 0:o.onSuccess)==null||l.call(o,a,i,c)},onError(a,i,c){var l;(l=o==null?void 0:o.onError)==null||l.call(o,a,i,c)},onSettled(a,i,c,l){var d;(d=o==null?void 0:o.onSettled)==null||d.call(o,a,i,c,l)}})}const jV=async e=>(await he.post("/instance/create",e)).data,RV=async e=>(await he.post(`/instance/restart/${e}`)).data,OV=async e=>(await he.delete(`/instance/logout/${e}`)).data,NV=async e=>(await he.delete(`/instance/delete/${e}`)).data,PV=async({instanceName:e,token:t,number:n})=>(await he.get(`/instance/connect/${e}`,{headers:{apikey:t},params:{number:n}})).data,MV=async({instanceName:e,token:t,data:n})=>(await he.post(`/settings/set/${e}`,n,{headers:{apikey:t}})).data;function _g(){const e=Ye(PV,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),t=Ye(MV,{invalidateKeys:[["instance","fetchSettings"]]}),n=Ye(NV,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),r=Ye(OV,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),s=Ye(RV,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),o=Ye(jV,{invalidateKeys:[["instance","fetchInstances"]]});return{connect:e,updateSettings:t,deleteInstance:n,logout:r,restart:s,createInstance:o}}var Yd=e=>e.type==="checkbox",ml=e=>e instanceof Date,Un=e=>e==null;const ZO=e=>typeof e=="object";var pn=e=>!Un(e)&&!Array.isArray(e)&&ZO(e)&&!ml(e),YO=e=>pn(e)&&e.target?Yd(e.target)?e.target.checked:e.target.value:e,IV=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,XO=(e,t)=>e.has(IV(t)),DV=e=>{const t=e.constructor&&e.constructor.prototype;return pn(t)&&t.hasOwnProperty("isPrototypeOf")},vw=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Jn(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(vw&&(e instanceof Blob||e instanceof FileList))&&(n||pn(e)))if(t=n?[]:{},!n&&!DV(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=Jn(e[r]));else return e;return t}var jg=e=>Array.isArray(e)?e.filter(Boolean):[],qt=e=>e===void 0,ce=(e,t,n)=>{if(!t||!pn(e))return n;const r=jg(t.split(/[,[\].]+?/)).reduce((s,o)=>Un(s)?s:s[o],e);return qt(r)||r===e?qt(e[t])?n:e[t]:r},js=e=>typeof e=="boolean",yw=e=>/^\w*$/.test(e),eN=e=>jg(e.replace(/["|']|\]/g,"").split(/\.|\[/)),ht=(e,t,n)=>{let r=-1;const s=yw(t)?[t]:eN(t),o=s.length,a=o-1;for(;++rTe.useContext(tN),Tr=e=>{const{children:t,...n}=e;return Te.createElement(tN.Provider,{value:n},t)};var nN=(e,t,n,r=!0)=>{const s={defaultValues:t._defaultValues};for(const o in e)Object.defineProperty(s,o,{get:()=>{const a=o;return t._proxyFormState[a]!==Yr.all&&(t._proxyFormState[a]=!r||Yr.all),n&&(n[a]=!0),e[a]}});return s},ur=e=>pn(e)&&!Object.keys(e).length,rN=(e,t,n,r)=>{n(e);const{name:s,...o}=e;return ur(o)||Object.keys(o).length>=Object.keys(t).length||Object.keys(o).find(a=>t[a]===(!r||Yr.all))},Rc=e=>Array.isArray(e)?e:[e],sN=(e,t,n)=>!e||!t||e===t||Rc(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function bw(e){const t=Te.useRef(e);t.current=e,Te.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function AV(e){const t=Rg(),{control:n=t.control,disabled:r,name:s,exact:o}=e||{},[a,i]=Te.useState(n._formState),c=Te.useRef(!0),l=Te.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1}),d=Te.useRef(s);return d.current=s,bw({disabled:r,next:p=>c.current&&sN(d.current,p.name,o)&&rN(p,l.current,n._updateFormState)&&i({...n._formState,...p}),subject:n._subjects.state}),Te.useEffect(()=>(c.current=!0,l.current.isValid&&n._updateValid(!0),()=>{c.current=!1}),[n]),nN(a,n,l.current,!1)}var Ps=e=>typeof e=="string",oN=(e,t,n,r,s)=>Ps(e)?(r&&t.watch.add(e),ce(n,e,s)):Array.isArray(e)?e.map(o=>(r&&t.watch.add(o),ce(n,o))):(r&&(t.watchAll=!0),n);function FV(e){const t=Rg(),{control:n=t.control,name:r,defaultValue:s,disabled:o,exact:a}=e||{},i=Te.useRef(r);i.current=r,bw({disabled:o,subject:n._subjects.values,next:d=>{sN(i.current,d.name,a)&&l(Jn(oN(i.current,n._names,d.values||n._formValues,!1,s)))}});const[c,l]=Te.useState(n._getWatch(r,s));return Te.useEffect(()=>n._removeUnmounted()),c}function LV(e){const t=Rg(),{name:n,disabled:r,control:s=t.control,shouldUnregister:o}=e,a=XO(s._names.array,n),i=FV({control:s,name:n,defaultValue:ce(s._formValues,n,ce(s._defaultValues,n,e.defaultValue)),exact:!0}),c=AV({control:s,name:n}),l=Te.useRef(s.register(n,{...e.rules,value:i,...js(e.disabled)?{disabled:e.disabled}:{}}));return Te.useEffect(()=>{const d=s._options.shouldUnregister||o,p=(f,h)=>{const g=ce(s._fields,f);g&&g._f&&(g._f.mount=h)};if(p(n,!0),d){const f=Jn(ce(s._options.defaultValues,n));ht(s._defaultValues,n,f),qt(ce(s._formValues,n))&&ht(s._formValues,n,f)}return()=>{(a?d&&!s._state.action:d)?s.unregister(n):p(n,!1)}},[n,s,a,o]),Te.useEffect(()=>{ce(s._fields,n)&&s._updateDisabledField({disabled:r,fields:s._fields,name:n,value:ce(s._fields,n)._f.value})},[r,n,s]),{field:{name:n,value:i,...js(r)||c.disabled?{disabled:c.disabled||r}:{},onChange:Te.useCallback(d=>l.current.onChange({target:{value:YO(d),name:n},type:dh.CHANGE}),[n]),onBlur:Te.useCallback(()=>l.current.onBlur({target:{value:ce(s._formValues,n),name:n},type:dh.BLUR}),[n,s]),ref:d=>{const p=ce(s._fields,n);p&&d&&(p._f.ref={focus:()=>d.focus(),select:()=>d.select(),setCustomValidity:f=>d.setCustomValidity(f),reportValidity:()=>d.reportValidity()})}},formState:c,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ce(c.errors,n)},isDirty:{enumerable:!0,get:()=>!!ce(c.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ce(c.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!ce(c.validatingFields,n)},error:{enumerable:!0,get:()=>ce(c.errors,n)}})}}const $V=e=>e.render(LV(e));var aN=(e,t,n,r,s)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:s||!0}}:{},C1=e=>({isOnSubmit:!e||e===Yr.onSubmit,isOnBlur:e===Yr.onBlur,isOnChange:e===Yr.onChange,isOnAll:e===Yr.all,isOnTouch:e===Yr.onTouched}),E1=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const Oc=(e,t,n,r)=>{for(const s of n||Object.keys(e)){const o=ce(e,s);if(o){const{_f:a,...i}=o;if(a){if(a.refs&&a.refs[0]&&t(a.refs[0],s)&&!r)break;if(a.ref&&t(a.ref,a.name)&&!r)break;Oc(i,t)}else pn(i)&&Oc(i,t)}}};var BV=(e,t,n)=>{const r=Rc(ce(e,n));return ht(r,"root",t[n]),ht(e,n,r),e},xw=e=>e.type==="file",ta=e=>typeof e=="function",fh=e=>{if(!vw)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},vp=e=>Ps(e),ww=e=>e.type==="radio",ph=e=>e instanceof RegExp;const T1={value:!1,isValid:!1},k1={value:!0,isValid:!0};var iN=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!qt(e[0].attributes.value)?qt(e[0].value)||e[0].value===""?k1:{value:e[0].value,isValid:!0}:k1:T1}return T1};const _1={isValid:!1,value:null};var lN=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,_1):_1;function j1(e,t,n="validate"){if(vp(e)||Array.isArray(e)&&e.every(vp)||js(e)&&!e)return{type:n,message:vp(e)?e:"",ref:t}}var Gi=e=>pn(e)&&!ph(e)?e:{value:e,message:""},R1=async(e,t,n,r,s)=>{const{ref:o,refs:a,required:i,maxLength:c,minLength:l,min:d,max:p,pattern:f,validate:h,name:g,valueAsNumber:m,mount:x,disabled:b}=e._f,y=ce(t,g);if(!x||b)return{};const w=a?a[0]:o,S=I=>{r&&w.reportValidity&&(w.setCustomValidity(js(I)?"":I||""),w.reportValidity())},E={},C=ww(o),k=Yd(o),T=C||k,O=(m||xw(o))&&qt(o.value)&&qt(y)||fh(o)&&o.value===""||y===""||Array.isArray(y)&&!y.length,M=aN.bind(null,g,n,E),U=(I,J,V,G=Ws.maxLength,ee=Ws.minLength)=>{const q=I?J:V;E[g]={type:I?G:ee,message:q,ref:o,...M(I?G:ee,q)}};if(s?!Array.isArray(y)||!y.length:i&&(!T&&(O||Un(y))||js(y)&&!y||k&&!iN(a).isValid||C&&!lN(a).isValid)){const{value:I,message:J}=vp(i)?{value:!!i,message:i}:Gi(i);if(I&&(E[g]={type:Ws.required,message:J,ref:w,...M(Ws.required,J)},!n))return S(J),E}if(!O&&(!Un(d)||!Un(p))){let I,J;const V=Gi(p),G=Gi(d);if(!Un(y)&&!isNaN(y)){const ee=o.valueAsNumber||y&&+y;Un(V.value)||(I=ee>V.value),Un(G.value)||(J=eenew Date(new Date().toDateString()+" "+Y),F=o.type=="time",A=o.type=="week";Ps(V.value)&&y&&(I=F?q(y)>q(V.value):A?y>V.value:ee>new Date(V.value)),Ps(G.value)&&y&&(J=F?q(y)+I.value,G=!Un(J.value)&&y.length<+J.value;if((V||G)&&(U(V,I.message,J.message),!n))return S(E[g].message),E}if(f&&!O&&Ps(y)){const{value:I,message:J}=Gi(f);if(ph(I)&&!y.match(I)&&(E[g]={type:Ws.pattern,message:J,ref:o,...M(Ws.pattern,J)},!n))return S(J),E}if(h){if(ta(h)){const I=await h(y,t),J=j1(I,w);if(J&&(E[g]={...J,...M(Ws.validate,J.message)},!n))return S(J.message),E}else if(pn(h)){let I={};for(const J in h){if(!ur(I)&&!n)break;const V=j1(await h[J](y,t),w,J);V&&(I={...V,...M(J,V.message)},S(V.message),n&&(E[g]=I))}if(!ur(I)&&(E[g]={ref:w,...I},!n))return E}}return S(!0),E};function zV(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{let e=[];return{get observers(){return e},next:s=>{for(const o of e)o.next&&o.next(s)},subscribe:s=>(e.push(s),{unsubscribe:()=>{e=e.filter(o=>o!==s)}}),unsubscribe:()=>{e=[]}}},hh=e=>Un(e)||!ZO(e);function Ya(e,t){if(hh(e)||hh(t))return e===t;if(ml(e)&&ml(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const s of n){const o=e[s];if(!r.includes(s))return!1;if(s!=="ref"){const a=t[s];if(ml(o)&&ml(a)||pn(o)&&pn(a)||Array.isArray(o)&&Array.isArray(a)?!Ya(o,a):o!==a)return!1}}return!0}var uN=e=>e.type==="select-multiple",VV=e=>ww(e)||Yd(e),Zm=e=>fh(e)&&e.isConnected,cN=e=>{for(const t in e)if(ta(e[t]))return!0;return!1};function gh(e,t={}){const n=Array.isArray(e);if(pn(e)||n)for(const r in e)Array.isArray(e[r])||pn(e[r])&&!cN(e[r])?(t[r]=Array.isArray(e[r])?[]:{},gh(e[r],t[r])):Un(e[r])||(t[r]=!0);return t}function dN(e,t,n){const r=Array.isArray(e);if(pn(e)||r)for(const s in e)Array.isArray(e[s])||pn(e[s])&&!cN(e[s])?qt(t)||hh(n[s])?n[s]=Array.isArray(e[s])?gh(e[s],[]):{...gh(e[s])}:dN(e[s],Un(t)?{}:t[s],n[s]):n[s]=!Ya(e[s],t[s]);return n}var Lf=(e,t)=>dN(e,t,gh(t)),fN=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>qt(e)?e:t?e===""?NaN:e&&+e:n&&Ps(e)?new Date(e):r?r(e):e;function Ym(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return xw(t)?t.files:ww(t)?lN(e.refs).value:uN(t)?[...t.selectedOptions].map(({value:n})=>n):Yd(t)?iN(e.refs).value:fN(qt(t.value)?e.ref.value:t.value,e)}var HV=(e,t,n,r)=>{const s={};for(const o of e){const a=ce(t,o);a&&ht(s,o,a._f)}return{criteriaMode:n,names:[...e],fields:s,shouldUseNativeValidation:r}},Zu=e=>qt(e)?e:ph(e)?e.source:pn(e)?ph(e.value)?e.value.source:e.value:e,KV=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function O1(e,t,n){const r=ce(e,n);if(r||yw(n))return{error:r,name:n};const s=n.split(".");for(;s.length;){const o=s.join("."),a=ce(t,o),i=ce(e,o);if(a&&!Array.isArray(a)&&n!==o)return{name:n};if(i&&i.type)return{name:o,error:i};s.pop()}return{name:n}}var qV=(e,t,n,r,s)=>s.isOnAll?!1:!n&&s.isOnTouch?!(t||e):(n?r.isOnBlur:s.isOnBlur)?!e:(n?r.isOnChange:s.isOnChange)?e:!0,WV=(e,t)=>!jg(ce(e,t)).length&&ln(e,t);const GV={mode:Yr.onSubmit,reValidateMode:Yr.onChange,shouldFocusError:!0};function JV(e={}){let t={...GV,...e},n={submitCount:0,isDirty:!1,isLoading:ta(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},r={},s=pn(t.defaultValues)||pn(t.values)?Jn(t.defaultValues||t.values)||{}:{},o=t.shouldUnregister?{}:Jn(s),a={action:!1,mount:!1,watch:!1},i={mount:new Set,unMount:new Set,array:new Set,watch:new Set},c,l=0;const d={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},p={values:Qm(),array:Qm(),state:Qm()},f=C1(t.mode),h=C1(t.reValidateMode),g=t.criteriaMode===Yr.all,m=j=>D=>{clearTimeout(l),l=setTimeout(j,D)},x=async j=>{if(d.isValid||j){const D=t.resolver?ur((await T()).errors):await M(r,!0);D!==n.isValid&&p.state.next({isValid:D})}},b=(j,D)=>{(d.isValidating||d.validatingFields)&&((j||Array.from(i.mount)).forEach(B=>{B&&(D?ht(n.validatingFields,B,D):ln(n.validatingFields,B))}),p.state.next({validatingFields:n.validatingFields,isValidating:!ur(n.validatingFields)}))},y=(j,D=[],B,pe,le=!0,ae=!0)=>{if(pe&&B){if(a.action=!0,ae&&Array.isArray(ce(r,j))){const Ee=B(ce(r,j),pe.argA,pe.argB);le&&ht(r,j,Ee)}if(ae&&Array.isArray(ce(n.errors,j))){const Ee=B(ce(n.errors,j),pe.argA,pe.argB);le&&ht(n.errors,j,Ee),WV(n.errors,j)}if(d.touchedFields&&ae&&Array.isArray(ce(n.touchedFields,j))){const Ee=B(ce(n.touchedFields,j),pe.argA,pe.argB);le&&ht(n.touchedFields,j,Ee)}d.dirtyFields&&(n.dirtyFields=Lf(s,o)),p.state.next({name:j,isDirty:I(j,D),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else ht(o,j,D)},w=(j,D)=>{ht(n.errors,j,D),p.state.next({errors:n.errors})},S=j=>{n.errors=j,p.state.next({errors:n.errors,isValid:!1})},E=(j,D,B,pe)=>{const le=ce(r,j);if(le){const ae=ce(o,j,qt(B)?ce(s,j):B);qt(ae)||pe&&pe.defaultChecked||D?ht(o,j,D?ae:Ym(le._f)):G(j,ae),a.mount&&x()}},C=(j,D,B,pe,le)=>{let ae=!1,Ee=!1;const et={name:j},kt=!!(ce(r,j)&&ce(r,j)._f&&ce(r,j)._f.disabled);if(!B||pe){d.isDirty&&(Ee=n.isDirty,n.isDirty=et.isDirty=I(),ae=Ee!==et.isDirty);const hn=kt||Ya(ce(s,j),D);Ee=!!(!kt&&ce(n.dirtyFields,j)),hn||kt?ln(n.dirtyFields,j):ht(n.dirtyFields,j,!0),et.dirtyFields=n.dirtyFields,ae=ae||d.dirtyFields&&Ee!==!hn}if(B){const hn=ce(n.touchedFields,j);hn||(ht(n.touchedFields,j,B),et.touchedFields=n.touchedFields,ae=ae||d.touchedFields&&hn!==B)}return ae&&le&&p.state.next(et),ae?et:{}},k=(j,D,B,pe)=>{const le=ce(n.errors,j),ae=d.isValid&&js(D)&&n.isValid!==D;if(e.delayError&&B?(c=m(()=>w(j,B)),c(e.delayError)):(clearTimeout(l),c=null,B?ht(n.errors,j,B):ln(n.errors,j)),(B?!Ya(le,B):le)||!ur(pe)||ae){const Ee={...pe,...ae&&js(D)?{isValid:D}:{},errors:n.errors,name:j};n={...n,...Ee},p.state.next(Ee)}},T=async j=>{b(j,!0);const D=await t.resolver(o,t.context,HV(j||i.mount,r,t.criteriaMode,t.shouldUseNativeValidation));return b(j),D},O=async j=>{const{errors:D}=await T(j);if(j)for(const B of j){const pe=ce(D,B);pe?ht(n.errors,B,pe):ln(n.errors,B)}else n.errors=D;return D},M=async(j,D,B={valid:!0})=>{for(const pe in j){const le=j[pe];if(le){const{_f:ae,...Ee}=le;if(ae){const et=i.array.has(ae.name);b([pe],!0);const kt=await R1(le,o,g,t.shouldUseNativeValidation&&!D,et);if(b([pe]),kt[ae.name]&&(B.valid=!1,D))break;!D&&(ce(kt,ae.name)?et?BV(n.errors,kt,ae.name):ht(n.errors,ae.name,kt[ae.name]):ln(n.errors,ae.name))}Ee&&await M(Ee,D,B)}}return B.valid},U=()=>{for(const j of i.unMount){const D=ce(r,j);D&&(D._f.refs?D._f.refs.every(B=>!Zm(B)):!Zm(D._f.ref))&&oe(j)}i.unMount=new Set},I=(j,D)=>(j&&D&&ht(o,j,D),!Ya(de(),s)),J=(j,D,B)=>oN(j,i,{...a.mount?o:qt(D)?s:Ps(j)?{[j]:D}:D},B,D),V=j=>jg(ce(a.mount?o:s,j,e.shouldUnregister?ce(s,j,[]):[])),G=(j,D,B={})=>{const pe=ce(r,j);let le=D;if(pe){const ae=pe._f;ae&&(!ae.disabled&&ht(o,j,fN(D,ae)),le=fh(ae.ref)&&Un(D)?"":D,uN(ae.ref)?[...ae.ref.options].forEach(Ee=>Ee.selected=le.includes(Ee.value)):ae.refs?Yd(ae.ref)?ae.refs.length>1?ae.refs.forEach(Ee=>(!Ee.defaultChecked||!Ee.disabled)&&(Ee.checked=Array.isArray(le)?!!le.find(et=>et===Ee.value):le===Ee.value)):ae.refs[0]&&(ae.refs[0].checked=!!le):ae.refs.forEach(Ee=>Ee.checked=Ee.value===le):xw(ae.ref)?ae.ref.value="":(ae.ref.value=le,ae.ref.type||p.values.next({name:j,values:{...o}})))}(B.shouldDirty||B.shouldTouch)&&C(j,le,B.shouldTouch,B.shouldDirty,!0),B.shouldValidate&&Y(j)},ee=(j,D,B)=>{for(const pe in D){const le=D[pe],ae=`${j}.${pe}`,Ee=ce(r,ae);(i.array.has(j)||!hh(le)||Ee&&!Ee._f)&&!ml(le)?ee(ae,le,B):G(ae,le,B)}},q=(j,D,B={})=>{const pe=ce(r,j),le=i.array.has(j),ae=Jn(D);ht(o,j,ae),le?(p.array.next({name:j,values:{...o}}),(d.isDirty||d.dirtyFields)&&B.shouldDirty&&p.state.next({name:j,dirtyFields:Lf(s,o),isDirty:I(j,ae)})):pe&&!pe._f&&!Un(ae)?ee(j,ae,B):G(j,ae,B),E1(j,i)&&p.state.next({...n}),p.values.next({name:a.mount?j:void 0,values:{...o}})},F=async j=>{a.mount=!0;const D=j.target;let B=D.name,pe=!0;const le=ce(r,B),ae=()=>D.type?Ym(le._f):YO(j),Ee=et=>{pe=Number.isNaN(et)||et===ce(o,B,et)};if(le){let et,kt;const hn=ae(),yn=j.type===dh.BLUR||j.type===dh.FOCUS_OUT,gn=!KV(le._f)&&!t.resolver&&!ce(n.errors,B)&&!le._f.deps||qV(yn,ce(n.touchedFields,B),n.isSubmitted,h,f),jo=E1(B,i,yn);ht(o,B,hn),yn?(le._f.onBlur&&le._f.onBlur(j),c&&c(0)):le._f.onChange&&le._f.onChange(j);const gs=C(B,hn,yn,!1),Aa=!ur(gs)||jo;if(!yn&&p.values.next({name:B,type:j.type,values:{...o}}),gn)return d.isValid&&x(),Aa&&p.state.next({name:B,...jo?{}:gs});if(!yn&&jo&&p.state.next({...n}),t.resolver){const{errors:Fn}=await T([B]);if(Ee(hn),pe){const ue=O1(n.errors,r,B),Ue=O1(Fn,r,ue.name||B);et=Ue.error,B=Ue.name,kt=ur(Fn)}}else b([B],!0),et=(await R1(le,o,g,t.shouldUseNativeValidation))[B],b([B]),Ee(hn),pe&&(et?kt=!1:d.isValid&&(kt=await M(r,!0)));pe&&(le._f.deps&&Y(le._f.deps),k(B,kt,et,gs))}},A=(j,D)=>{if(ce(n.errors,D)&&j.focus)return j.focus(),1},Y=async(j,D={})=>{let B,pe;const le=Rc(j);if(t.resolver){const ae=await O(qt(j)?j:le);B=ur(ae),pe=j?!le.some(Ee=>ce(ae,Ee)):B}else j?(pe=(await Promise.all(le.map(async ae=>{const Ee=ce(r,ae);return await M(Ee&&Ee._f?{[ae]:Ee}:Ee)}))).every(Boolean),!(!pe&&!n.isValid)&&x()):pe=B=await M(r);return p.state.next({...!Ps(j)||d.isValid&&B!==n.isValid?{}:{name:j},...t.resolver||!j?{isValid:B}:{},errors:n.errors}),D.shouldFocus&&!pe&&Oc(r,A,j?le:i.mount),pe},de=j=>{const D={...a.mount?o:s};return qt(j)?D:Ps(j)?ce(D,j):j.map(B=>ce(D,B))},z=(j,D)=>({invalid:!!ce((D||n).errors,j),isDirty:!!ce((D||n).dirtyFields,j),error:ce((D||n).errors,j),isValidating:!!ce(n.validatingFields,j),isTouched:!!ce((D||n).touchedFields,j)}),se=j=>{j&&Rc(j).forEach(D=>ln(n.errors,D)),p.state.next({errors:j?n.errors:{}})},ne=(j,D,B)=>{const pe=(ce(r,j,{_f:{}})._f||{}).ref,le=ce(n.errors,j)||{},{ref:ae,message:Ee,type:et,...kt}=le;ht(n.errors,j,{...kt,...D,ref:pe}),p.state.next({name:j,errors:n.errors,isValid:!1}),B&&B.shouldFocus&&pe&&pe.focus&&pe.focus()},ie=(j,D)=>ta(j)?p.values.subscribe({next:B=>j(J(void 0,D),B)}):J(j,D,!0),oe=(j,D={})=>{for(const B of j?Rc(j):i.mount)i.mount.delete(B),i.array.delete(B),D.keepValue||(ln(r,B),ln(o,B)),!D.keepError&&ln(n.errors,B),!D.keepDirty&&ln(n.dirtyFields,B),!D.keepTouched&&ln(n.touchedFields,B),!D.keepIsValidating&&ln(n.validatingFields,B),!t.shouldUnregister&&!D.keepDefaultValue&&ln(s,B);p.values.next({values:{...o}}),p.state.next({...n,...D.keepDirty?{isDirty:I()}:{}}),!D.keepIsValid&&x()},W=({disabled:j,name:D,field:B,fields:pe,value:le})=>{if(js(j)&&a.mount||j){const ae=j?void 0:qt(le)?Ym(B?B._f:ce(pe,D)._f):le;ht(o,D,ae),C(D,ae,!1,!1,!0)}},Ce=(j,D={})=>{let B=ce(r,j);const pe=js(D.disabled);return ht(r,j,{...B||{},_f:{...B&&B._f?B._f:{ref:{name:j}},name:j,mount:!0,...D}}),i.mount.add(j),B?W({field:B,disabled:D.disabled,name:j,value:D.value}):E(j,!0,D.value),{...pe?{disabled:D.disabled}:{},...t.progressive?{required:!!D.required,min:Zu(D.min),max:Zu(D.max),minLength:Zu(D.minLength),maxLength:Zu(D.maxLength),pattern:Zu(D.pattern)}:{},name:j,onChange:F,onBlur:F,ref:le=>{if(le){Ce(j,D),B=ce(r,j);const ae=qt(le.value)&&le.querySelectorAll&&le.querySelectorAll("input,select,textarea")[0]||le,Ee=VV(ae),et=B._f.refs||[];if(Ee?et.find(kt=>kt===ae):ae===B._f.ref)return;ht(r,j,{_f:{...B._f,...Ee?{refs:[...et.filter(Zm),ae,...Array.isArray(ce(s,j))?[{}]:[]],ref:{type:ae.type,name:j}}:{ref:ae}}}),E(j,!1,void 0,ae)}else B=ce(r,j,{}),B._f&&(B._f.mount=!1),(t.shouldUnregister||D.shouldUnregister)&&!(XO(i.array,j)&&a.action)&&i.unMount.add(j)}}},Re=()=>t.shouldFocusError&&Oc(r,A,i.mount),Le=j=>{js(j)&&(p.state.next({disabled:j}),Oc(r,(D,B)=>{const pe=ce(r,B);pe&&(D.disabled=pe._f.disabled||j,Array.isArray(pe._f.refs)&&pe._f.refs.forEach(le=>{le.disabled=pe._f.disabled||j}))},0,!1))},Oe=(j,D)=>async B=>{let pe;B&&(B.preventDefault&&B.preventDefault(),B.persist&&B.persist());let le=Jn(o);if(p.state.next({isSubmitting:!0}),t.resolver){const{errors:ae,values:Ee}=await T();n.errors=ae,le=Ee}else await M(r);if(ln(n.errors,"root"),ur(n.errors)){p.state.next({errors:{}});try{await j(le,B)}catch(ae){pe=ae}}else D&&await D({...n.errors},B),Re(),setTimeout(Re);if(p.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:ur(n.errors)&&!pe,submitCount:n.submitCount+1,errors:n.errors}),pe)throw pe},me=(j,D={})=>{ce(r,j)&&(qt(D.defaultValue)?q(j,Jn(ce(s,j))):(q(j,D.defaultValue),ht(s,j,Jn(D.defaultValue))),D.keepTouched||ln(n.touchedFields,j),D.keepDirty||(ln(n.dirtyFields,j),n.isDirty=D.defaultValue?I(j,Jn(ce(s,j))):I()),D.keepError||(ln(n.errors,j),d.isValid&&x()),p.state.next({...n}))},rt=(j,D={})=>{const B=j?Jn(j):s,pe=Jn(B),le=ur(j),ae=le?s:pe;if(D.keepDefaultValues||(s=B),!D.keepValues){if(D.keepDirtyValues)for(const Ee of i.mount)ce(n.dirtyFields,Ee)?ht(ae,Ee,ce(o,Ee)):q(Ee,ce(ae,Ee));else{if(vw&&qt(j))for(const Ee of i.mount){const et=ce(r,Ee);if(et&&et._f){const kt=Array.isArray(et._f.refs)?et._f.refs[0]:et._f.ref;if(fh(kt)){const hn=kt.closest("form");if(hn){hn.reset();break}}}}r={}}o=e.shouldUnregister?D.keepDefaultValues?Jn(s):{}:Jn(ae),p.array.next({values:{...ae}}),p.values.next({values:{...ae}})}i={mount:D.keepDirtyValues?i.mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},a.mount=!d.isValid||!!D.keepIsValid||!!D.keepDirtyValues,a.watch=!!e.shouldUnregister,p.state.next({submitCount:D.keepSubmitCount?n.submitCount:0,isDirty:le?!1:D.keepDirty?n.isDirty:!!(D.keepDefaultValues&&!Ya(j,s)),isSubmitted:D.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:le?{}:D.keepDirtyValues?D.keepDefaultValues&&o?Lf(s,o):n.dirtyFields:D.keepDefaultValues&&j?Lf(s,j):D.keepDirty?n.dirtyFields:{},touchedFields:D.keepTouched?n.touchedFields:{},errors:D.keepErrors?n.errors:{},isSubmitSuccessful:D.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},It=(j,D)=>rt(ta(j)?j(o):j,D);return{control:{register:Ce,unregister:oe,getFieldState:z,handleSubmit:Oe,setError:ne,_executeSchema:T,_getWatch:J,_getDirty:I,_updateValid:x,_removeUnmounted:U,_updateFieldArray:y,_updateDisabledField:W,_getFieldArray:V,_reset:rt,_resetDefaultValues:()=>ta(t.defaultValues)&&t.defaultValues().then(j=>{It(j,t.resetOptions),p.state.next({isLoading:!1})}),_updateFormState:j=>{n={...n,...j}},_disableForm:Le,_subjects:p,_proxyFormState:d,_setErrors:S,get _fields(){return r},get _formValues(){return o},get _state(){return a},set _state(j){a=j},get _defaultValues(){return s},get _names(){return i},set _names(j){i=j},get _formState(){return n},set _formState(j){n=j},get _options(){return t},set _options(j){t={...t,...j}}},trigger:Y,register:Ce,handleSubmit:Oe,watch:ie,setValue:q,getValues:de,reset:It,resetField:me,clearErrors:se,unregister:oe,setError:ne,setFocus:(j,D={})=>{const B=ce(r,j),pe=B&&B._f;if(pe){const le=pe.refs?pe.refs[0]:pe.ref;le.focus&&(le.focus(),D.shouldSelect&&le.select())}},getFieldState:z}}function sn(e={}){const t=Te.useRef(),n=Te.useRef(),[r,s]=Te.useState({isDirty:!1,isValidating:!1,isLoading:ta(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1,defaultValues:ta(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...JV(e),formState:r});const o=t.current.control;return o._options=e,bw({subject:o._subjects.state,next:a=>{rN(a,o._proxyFormState,o._updateFormState,!0)&&s({...o._formState})}}),Te.useEffect(()=>o._disableForm(e.disabled),[o,e.disabled]),Te.useEffect(()=>{if(o._proxyFormState.isDirty){const a=o._getDirty();a!==r.isDirty&&o._subjects.state.next({isDirty:a})}},[o,r.isDirty]),Te.useEffect(()=>{e.values&&!Ya(e.values,n.current)?(o._reset(e.values,o._options.resetOptions),n.current=e.values,s(a=>({...a}))):o._resetDefaultValues()},[e.values,o]),Te.useEffect(()=>{e.errors&&o._setErrors(e.errors)},[e.errors,o]),Te.useEffect(()=>{o._state.mount||(o._updateValid(),o._state.mount=!0),o._state.watch&&(o._state.watch=!1,o._subjects.state.next({...o._formState})),o._removeUnmounted()}),Te.useEffect(()=>{e.shouldUnregister&&o._subjects.values.next({values:o._getWatch()})},[e.shouldUnregister,o]),t.current.formState=nN(r,o),t.current}const N1=(e,t,n)=>{if(e&&"reportValidity"in e){const r=ce(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},pN=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?N1(r.ref,n,e):r.refs&&r.refs.forEach(s=>N1(s,n,e))}},QV=(e,t)=>{t.shouldUseNativeValidation&&pN(e,t);const n={};for(const r in e){const s=ce(t.fields,r),o=Object.assign(e[r]||{},{ref:s&&s.ref});if(ZV(t.names||Object.keys(e),r)){const a=Object.assign({},ce(n,r));ht(a,"root",o),ht(n,r,a)}else ht(n,r,o)}return n},ZV=(e,t)=>e.some(n=>n.startsWith(t+"."));var YV=function(e,t){for(var n={};e.length;){var r=e[0],s=r.code,o=r.message,a=r.path.join(".");if(!n[a])if("unionErrors"in r){var i=r.unionErrors[0].errors[0];n[a]={message:i.message,type:i.code}}else n[a]={message:o,type:s};if("unionErrors"in r&&r.unionErrors.forEach(function(d){return d.errors.forEach(function(p){return e.push(p)})}),t){var c=n[a].types,l=c&&c[r.code];n[a]=aN(a,t,n,s,l?[].concat(l,r.message):r.message)}e.shift()}return n},on=function(e,t,n){return n===void 0&&(n={}),function(r,s,o){try{return Promise.resolve(function(a,i){try{var c=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(l){return o.shouldUseNativeValidation&&pN({},o),{errors:{},values:n.raw?r:l}})}catch(l){return i(l)}return c&&c.then?c.then(void 0,i):c}(0,function(a){if(function(i){return Array.isArray(i==null?void 0:i.errors)}(a))return{values:{},errors:QV(YV(a.errors,!o.shouldUseNativeValidation&&o.criteriaMode==="all"),o)};throw a}))}catch(a){return Promise.reject(a)}}},xn=[];for(var Xm=0;Xm<256;++Xm)xn.push((Xm+256).toString(16).slice(1));function XV(e,t=0){return(xn[e[t+0]]+xn[e[t+1]]+xn[e[t+2]]+xn[e[t+3]]+"-"+xn[e[t+4]]+xn[e[t+5]]+"-"+xn[e[t+6]]+xn[e[t+7]]+"-"+xn[e[t+8]]+xn[e[t+9]]+"-"+xn[e[t+10]]+xn[e[t+11]]+xn[e[t+12]]+xn[e[t+13]]+xn[e[t+14]]+xn[e[t+15]]).toLowerCase()}var $f,e6=new Uint8Array(16);function t6(){if(!$f&&($f=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!$f))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return $f(e6)}var n6=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const P1={randomUUID:n6};function M1(e,t,n){if(P1.randomUUID&&!t&&!e)return P1.randomUUID();e=e||{};var r=e.random||(e.rng||t6)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,XV(r)}var ut;(function(e){e.assertEqual=s=>s;function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{const o={};for(const a of s)o[a]=a;return o},e.getValidEnumValues=s=>{const o=e.objectKeys(s).filter(i=>typeof s[s[i]]!="number"),a={};for(const i of o)a[i]=s[i];return e.objectValues(a)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&o.push(a);return o},e.find=(s,o)=>{for(const a of s)if(o(a))return a},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(ut||(ut={}));var Xy;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Xy||(Xy={}));const be=ut.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Vo=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},re=ut.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),r6=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class yr extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(o){return o.message},r={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let i=r,c=0;for(;cn.message){const n={},r=[];for(const s of this.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}yr.create=e=>new yr(e);const nu=(e,t)=>{let n;switch(e.code){case re.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case re.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,ut.jsonStringifyReplacer)}`;break;case re.unrecognized_keys:n=`Unrecognized key(s) in object: ${ut.joinValues(e.keys,", ")}`;break;case re.invalid_union:n="Invalid input";break;case re.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ut.joinValues(e.options)}`;break;case re.invalid_enum_value:n=`Invalid enum value. Expected ${ut.joinValues(e.options)}, received '${e.received}'`;break;case re.invalid_arguments:n="Invalid function arguments";break;case re.invalid_return_type:n="Invalid function return type";break;case re.invalid_date:n="Invalid date";break;case re.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:ut.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case re.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case re.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case re.custom:n="Invalid input";break;case re.invalid_intersection_types:n="Intersection results could not be merged";break;case re.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case re.not_finite:n="Number must be finite";break;default:n=t.defaultError,ut.assertNever(e)}return{message:n}};let hN=nu;function s6(e){hN=e}function mh(){return hN}const vh=e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],a={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let i="";const c=r.filter(l=>!!l).slice().reverse();for(const l of c)i=l(a,{data:t,defaultError:i}).message;return{...s,path:o,message:i}},o6=[];function ve(e,t){const n=mh(),r=vh({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===nu?void 0:nu].filter(s=>!!s)});e.common.issues.push(r)}class Dn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const s of n){if(s.status==="aborted")return Be;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const s of n){const o=await s.key,a=await s.value;r.push({key:o,value:a})}return Dn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const s of n){const{key:o,value:a}=s;if(o.status==="aborted"||a.status==="aborted")return Be;o.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[o.value]=a.value)}return{status:t.value,value:r}}}const Be=Object.freeze({status:"aborted"}),vl=e=>({status:"dirty",value:e}),Kn=e=>({status:"valid",value:e}),eb=e=>e.status==="aborted",tb=e=>e.status==="dirty",cd=e=>e.status==="valid",dd=e=>typeof Promise<"u"&&e instanceof Promise;function yh(e,t,n,r){if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function gN(e,t,n,r,s){if(typeof t=="function"?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var _e;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(_e||(_e={}));var fc,pc;class zs{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const I1=(e,t)=>{if(cd(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new yr(e.common.issues);return this._error=n,this._error}}};function Ke(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(a,i)=>{var c,l;const{message:d}=e;return a.code==="invalid_enum_value"?{message:d??i.defaultError}:typeof i.data>"u"?{message:(c=d??r)!==null&&c!==void 0?c:i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:(l=d??n)!==null&&l!==void 0?l:i.defaultError}},description:s}}class Qe{constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return Vo(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Vo(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Dn,ctx:{common:t.parent.common,data:t.data,parsedType:Vo(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(dd(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const s={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Vo(t)},o=this._parseSync({data:t,path:s.path,parent:s});return I1(s,o)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Vo(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(dd(s)?s:Promise.resolve(s));return I1(r,o)}refine(t,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{const a=t(s),i=()=>o.addIssue({code:re.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(i(),!1)):a?!0:(i(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new ds({schema:this,typeName:Fe.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return Ls.create(this,this._def)}nullable(){return xa.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return as.create(this,this._def)}promise(){return su.create(this,this._def)}or(t){return gd.create([this,t],this._def)}and(t){return md.create(this,t,this._def)}transform(t){return new ds({...Ke(this._def),schema:this,typeName:Fe.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new wd({...Ke(this._def),innerType:this,defaultValue:n,typeName:Fe.ZodDefault})}brand(){return new Sw({typeName:Fe.ZodBranded,type:this,...Ke(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Sd({...Ke(this._def),innerType:this,catchValue:n,typeName:Fe.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Xd.create(this,t)}readonly(){return Cd.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const a6=/^c[^\s-]{8,}$/i,i6=/^[0-9a-z]+$/,l6=/^[0-9A-HJKMNP-TV-Z]{26}$/,u6=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,c6=/^[a-z0-9_-]{21}$/i,d6=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,f6=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,p6="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ev;const h6=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,g6=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,m6=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,mN="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",v6=new RegExp(`^${mN}$`);function vN(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`),t}function y6(e){return new RegExp(`^${vN(e)}$`)}function yN(e){let t=`${mN}T${vN(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function b6(e,t){return!!((t==="v4"||!t)&&h6.test(e)||(t==="v6"||!t)&&g6.test(e))}class es extends Qe{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const o=this._getOrReturnCtx(t);return ve(o,{code:re.invalid_type,expected:be.string,received:o.parsedType}),Be}const r=new Dn;let s;for(const o of this._def.checks)if(o.kind==="min")t.data.lengtho.value&&(s=this._getOrReturnCtx(t,s),ve(s,{code:re.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){const a=t.data.length>o.value,i=t.data.lengtht.test(s),{validation:n,code:re.invalid_string,..._e.errToObj(r)})}_addCheck(t){return new es({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",..._e.errToObj(t)})}url(t){return this._addCheck({kind:"url",..._e.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",..._e.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",..._e.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",..._e.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",..._e.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",..._e.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",..._e.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",..._e.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",..._e.errToObj(t)})}datetime(t){var n,r;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,local:(r=t==null?void 0:t.local)!==null&&r!==void 0?r:!1,..._e.errToObj(t==null?void 0:t.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,..._e.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",..._e.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,..._e.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,..._e.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,..._e.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,..._e.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,..._e.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,..._e.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,..._e.errToObj(n)})}nonempty(t){return this.min(1,_e.errToObj(t))}trim(){return new es({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new es({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new es({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new es({checks:[],typeName:Fe.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Ke(e)})};function x6(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,o=parseInt(e.toFixed(s).replace(".","")),a=parseInt(t.toFixed(s).replace(".",""));return o%a/Math.pow(10,s)}class va extends Qe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==be.number){const o=this._getOrReturnCtx(t);return ve(o,{code:re.invalid_type,expected:be.number,received:o.parsedType}),Be}let r;const s=new Dn;for(const o of this._def.checks)o.kind==="int"?ut.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),ve(r,{code:re.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.datao.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),ve(r,{code:re.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?x6(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),ve(r,{code:re.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),ve(r,{code:re.not_finite,message:o.message}),s.dirty()):ut.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,_e.toString(n))}gt(t,n){return this.setLimit("min",t,!1,_e.toString(n))}lte(t,n){return this.setLimit("max",t,!0,_e.toString(n))}lt(t,n){return this.setLimit("max",t,!1,_e.toString(n))}setLimit(t,n,r,s){return new va({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:_e.toString(s)}]})}_addCheck(t){return new va({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:_e.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:_e.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:_e.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:_e.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:_e.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:_e.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:_e.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:_e.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:_e.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&ut.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.valuenew va({checks:[],typeName:Fe.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Ke(e)});class ya extends Qe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==be.bigint){const o=this._getOrReturnCtx(t);return ve(o,{code:re.invalid_type,expected:be.bigint,received:o.parsedType}),Be}let r;const s=new Dn;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?t.datao.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),ve(r,{code:re.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),ve(r,{code:re.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):ut.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,_e.toString(n))}gt(t,n){return this.setLimit("min",t,!1,_e.toString(n))}lte(t,n){return this.setLimit("max",t,!0,_e.toString(n))}lt(t,n){return this.setLimit("max",t,!1,_e.toString(n))}setLimit(t,n,r,s){return new ya({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:_e.toString(s)}]})}_addCheck(t){return new ya({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:_e.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:_e.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:_e.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:_e.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:_e.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new ya({checks:[],typeName:Fe.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Ke(e)})};class fd extends Qe{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return ve(r,{code:re.invalid_type,expected:be.boolean,received:r.parsedType}),Be}return Kn(t.data)}}fd.create=e=>new fd({typeName:Fe.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Ke(e)});class Ti extends Qe{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const o=this._getOrReturnCtx(t);return ve(o,{code:re.invalid_type,expected:be.date,received:o.parsedType}),Be}if(isNaN(t.data.getTime())){const o=this._getOrReturnCtx(t);return ve(o,{code:re.invalid_date}),Be}const r=new Dn;let s;for(const o of this._def.checks)o.kind==="min"?t.data.getTime()o.value&&(s=this._getOrReturnCtx(t,s),ve(s,{code:re.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):ut.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Ti({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:_e.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:_e.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew Ti({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:Fe.ZodDate,...Ke(e)});class bh extends Qe{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return ve(r,{code:re.invalid_type,expected:be.symbol,received:r.parsedType}),Be}return Kn(t.data)}}bh.create=e=>new bh({typeName:Fe.ZodSymbol,...Ke(e)});class pd extends Qe{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return ve(r,{code:re.invalid_type,expected:be.undefined,received:r.parsedType}),Be}return Kn(t.data)}}pd.create=e=>new pd({typeName:Fe.ZodUndefined,...Ke(e)});class hd extends Qe{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return ve(r,{code:re.invalid_type,expected:be.null,received:r.parsedType}),Be}return Kn(t.data)}}hd.create=e=>new hd({typeName:Fe.ZodNull,...Ke(e)});class ru extends Qe{constructor(){super(...arguments),this._any=!0}_parse(t){return Kn(t.data)}}ru.create=e=>new ru({typeName:Fe.ZodAny,...Ke(e)});class fi extends Qe{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Kn(t.data)}}fi.create=e=>new fi({typeName:Fe.ZodUnknown,...Ke(e)});class bo extends Qe{_parse(t){const n=this._getOrReturnCtx(t);return ve(n,{code:re.invalid_type,expected:be.never,received:n.parsedType}),Be}}bo.create=e=>new bo({typeName:Fe.ZodNever,...Ke(e)});class xh extends Qe{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return ve(r,{code:re.invalid_type,expected:be.void,received:r.parsedType}),Be}return Kn(t.data)}}xh.create=e=>new xh({typeName:Fe.ZodVoid,...Ke(e)});class as extends Qe{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==be.array)return ve(n,{code:re.invalid_type,expected:be.array,received:n.parsedType}),Be;if(s.exactLength!==null){const a=n.data.length>s.exactLength.value,i=n.data.lengths.maxLength.value&&(ve(n,{code:re.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,i)=>s.type._parseAsync(new zs(n,a,n.path,i)))).then(a=>Dn.mergeArray(r,a));const o=[...n.data].map((a,i)=>s.type._parseSync(new zs(n,a,n.path,i)));return Dn.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new as({...this._def,minLength:{value:t,message:_e.toString(n)}})}max(t,n){return new as({...this._def,maxLength:{value:t,message:_e.toString(n)}})}length(t,n){return new as({...this._def,exactLength:{value:t,message:_e.toString(n)}})}nonempty(t){return this.min(1,t)}}as.create=(e,t)=>new as({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Fe.ZodArray,...Ke(t)});function tl(e){if(e instanceof Dt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Ls.create(tl(r))}return new Dt({...e._def,shape:()=>t})}else return e instanceof as?new as({...e._def,type:tl(e.element)}):e instanceof Ls?Ls.create(tl(e.unwrap())):e instanceof xa?xa.create(tl(e.unwrap())):e instanceof Us?Us.create(e.items.map(t=>tl(t))):e}class Dt extends Qe{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=ut.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const l=this._getOrReturnCtx(t);return ve(l,{code:re.invalid_type,expected:be.object,received:l.parsedType}),Be}const{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof bo&&this._def.unknownKeys==="strip"))for(const l in s.data)a.includes(l)||i.push(l);const c=[];for(const l of a){const d=o[l],p=s.data[l];c.push({key:{status:"valid",value:l},value:d._parse(new zs(s,p,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof bo){const l=this._def.unknownKeys;if(l==="passthrough")for(const d of i)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(l==="strict")i.length>0&&(ve(s,{code:re.unrecognized_keys,keys:i}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const d of i){const p=s.data[d];c.push({key:{status:"valid",value:d},value:l._parse(new zs(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const l=[];for(const d of c){const p=await d.key,f=await d.value;l.push({key:p,value:f,alwaysSet:d.alwaysSet})}return l}).then(l=>Dn.mergeObjectSync(r,l)):Dn.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return _e.errToObj,new Dt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,o,a,i;const c=(a=(o=(s=this._def).errorMap)===null||o===void 0?void 0:o.call(s,n,r).message)!==null&&a!==void 0?a:r.defaultError;return n.code==="unrecognized_keys"?{message:(i=_e.errToObj(t).message)!==null&&i!==void 0?i:c}:{message:c}}}:{}})}strip(){return new Dt({...this._def,unknownKeys:"strip"})}passthrough(){return new Dt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Dt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Dt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Fe.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Dt({...this._def,catchall:t})}pick(t){const n={};return ut.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Dt({...this._def,shape:()=>n})}omit(t){const n={};return ut.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Dt({...this._def,shape:()=>n})}deepPartial(){return tl(this)}partial(t){const n={};return ut.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}),new Dt({...this._def,shape:()=>n})}required(t){const n={};return ut.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Ls;)o=o._def.innerType;n[r]=o}}),new Dt({...this._def,shape:()=>n})}keyof(){return bN(ut.objectKeys(this.shape))}}Dt.create=(e,t)=>new Dt({shape:()=>e,unknownKeys:"strip",catchall:bo.create(),typeName:Fe.ZodObject,...Ke(t)});Dt.strictCreate=(e,t)=>new Dt({shape:()=>e,unknownKeys:"strict",catchall:bo.create(),typeName:Fe.ZodObject,...Ke(t)});Dt.lazycreate=(e,t)=>new Dt({shape:e,unknownKeys:"strip",catchall:bo.create(),typeName:Fe.ZodObject,...Ke(t)});class gd extends Qe{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(const i of o)if(i.result.status==="valid")return i.result;for(const i of o)if(i.result.status==="dirty")return n.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(i=>new yr(i.ctx.common.issues));return ve(n,{code:re.invalid_union,unionErrors:a}),Be}if(n.common.async)return Promise.all(r.map(async o=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let o;const a=[];for(const c of r){const l={...n,common:{...n.common,issues:[]},parent:null},d=c._parseSync({data:n.data,path:n.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(c=>new yr(c));return ve(n,{code:re.invalid_union,unionErrors:i}),Be}}get options(){return this._def.options}}gd.create=(e,t)=>new gd({options:e,typeName:Fe.ZodUnion,...Ke(t)});const Qs=e=>e instanceof yd?Qs(e.schema):e instanceof ds?Qs(e.innerType()):e instanceof bd?[e.value]:e instanceof ba?e.options:e instanceof xd?ut.objectValues(e.enum):e instanceof wd?Qs(e._def.innerType):e instanceof pd?[void 0]:e instanceof hd?[null]:e instanceof Ls?[void 0,...Qs(e.unwrap())]:e instanceof xa?[null,...Qs(e.unwrap())]:e instanceof Sw||e instanceof Cd?Qs(e.unwrap()):e instanceof Sd?Qs(e._def.innerType):[];class Og extends Qe{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return ve(n,{code:re.invalid_type,expected:be.object,received:n.parsedType}),Be;const r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(ve(n,{code:re.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Be)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const s=new Map;for(const o of n){const a=Qs(o.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const i of a){if(s.has(i))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(i)}`);s.set(i,o)}}return new Og({typeName:Fe.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...Ke(r)})}}function nb(e,t){const n=Vo(e),r=Vo(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const s=ut.objectKeys(t),o=ut.objectKeys(e).filter(i=>s.indexOf(i)!==-1),a={...e,...t};for(const i of o){const c=nb(e[i],t[i]);if(!c.valid)return{valid:!1};a[i]=c.data}return{valid:!0,data:a}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let o=0;o{if(eb(o)||eb(a))return Be;const i=nb(o.value,a.value);return i.valid?((tb(o)||tb(a))&&n.dirty(),{status:n.value,value:i.data}):(ve(r,{code:re.invalid_intersection_types}),Be)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,a])=>s(o,a)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}md.create=(e,t,n)=>new md({left:e,right:t,typeName:Fe.ZodIntersection,...Ke(n)});class Us extends Qe{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return ve(r,{code:re.invalid_type,expected:be.array,received:r.parsedType}),Be;if(r.data.lengththis._def.items.length&&(ve(r,{code:re.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const o=[...r.data].map((a,i)=>{const c=this._def.items[i]||this._def.rest;return c?c._parse(new zs(r,a,r.path,i)):null}).filter(a=>!!a);return r.common.async?Promise.all(o).then(a=>Dn.mergeArray(n,a)):Dn.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new Us({...this._def,rest:t})}}Us.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Us({items:e,typeName:Fe.ZodTuple,rest:null,...Ke(t)})};class vd extends Qe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.object)return ve(r,{code:re.invalid_type,expected:be.object,received:r.parsedType}),Be;const s=[],o=this._def.keyType,a=this._def.valueType;for(const i in r.data)s.push({key:o._parse(new zs(r,i,r.path,i)),value:a._parse(new zs(r,r.data[i],r.path,i)),alwaysSet:i in r.data});return r.common.async?Dn.mergeObjectAsync(n,s):Dn.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof Qe?new vd({keyType:t,valueType:n,typeName:Fe.ZodRecord,...Ke(r)}):new vd({keyType:es.create(),valueType:t,typeName:Fe.ZodRecord,...Ke(n)})}}class wh extends Qe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.map)return ve(r,{code:re.invalid_type,expected:be.map,received:r.parsedType}),Be;const s=this._def.keyType,o=this._def.valueType,a=[...r.data.entries()].map(([i,c],l)=>({key:s._parse(new zs(r,i,r.path,[l,"key"])),value:o._parse(new zs(r,c,r.path,[l,"value"]))}));if(r.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const c of a){const l=await c.key,d=await c.value;if(l.status==="aborted"||d.status==="aborted")return Be;(l.status==="dirty"||d.status==="dirty")&&n.dirty(),i.set(l.value,d.value)}return{status:n.value,value:i}})}else{const i=new Map;for(const c of a){const l=c.key,d=c.value;if(l.status==="aborted"||d.status==="aborted")return Be;(l.status==="dirty"||d.status==="dirty")&&n.dirty(),i.set(l.value,d.value)}return{status:n.value,value:i}}}}wh.create=(e,t,n)=>new wh({valueType:t,keyType:e,typeName:Fe.ZodMap,...Ke(n)});class ki extends Qe{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return ve(r,{code:re.invalid_type,expected:be.set,received:r.parsedType}),Be;const s=this._def;s.minSize!==null&&r.data.sizes.maxSize.value&&(ve(r,{code:re.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const o=this._def.valueType;function a(c){const l=new Set;for(const d of c){if(d.status==="aborted")return Be;d.status==="dirty"&&n.dirty(),l.add(d.value)}return{status:n.value,value:l}}const i=[...r.data.values()].map((c,l)=>o._parse(new zs(r,c,r.path,l)));return r.common.async?Promise.all(i).then(c=>a(c)):a(i)}min(t,n){return new ki({...this._def,minSize:{value:t,message:_e.toString(n)}})}max(t,n){return new ki({...this._def,maxSize:{value:t,message:_e.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}ki.create=(e,t)=>new ki({valueType:e,minSize:null,maxSize:null,typeName:Fe.ZodSet,...Ke(t)});class jl extends Qe{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return ve(n,{code:re.invalid_type,expected:be.function,received:n.parsedType}),Be;function r(i,c){return vh({data:i,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,mh(),nu].filter(l=>!!l),issueData:{code:re.invalid_arguments,argumentsError:c}})}function s(i,c){return vh({data:i,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,mh(),nu].filter(l=>!!l),issueData:{code:re.invalid_return_type,returnTypeError:c}})}const o={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof su){const i=this;return Kn(async function(...c){const l=new yr([]),d=await i._def.args.parseAsync(c,o).catch(h=>{throw l.addIssue(r(c,h)),l}),p=await Reflect.apply(a,this,d);return await i._def.returns._def.type.parseAsync(p,o).catch(h=>{throw l.addIssue(s(p,h)),l})})}else{const i=this;return Kn(function(...c){const l=i._def.args.safeParse(c,o);if(!l.success)throw new yr([r(c,l.error)]);const d=Reflect.apply(a,this,l.data),p=i._def.returns.safeParse(d,o);if(!p.success)throw new yr([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new jl({...this._def,args:Us.create(t).rest(fi.create())})}returns(t){return new jl({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new jl({args:t||Us.create([]).rest(fi.create()),returns:n||fi.create(),typeName:Fe.ZodFunction,...Ke(r)})}}class yd extends Qe{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}yd.create=(e,t)=>new yd({getter:e,typeName:Fe.ZodLazy,...Ke(t)});class bd extends Qe{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return ve(n,{received:n.data,code:re.invalid_literal,expected:this._def.value}),Be}return{status:"valid",value:t.data}}get value(){return this._def.value}}bd.create=(e,t)=>new bd({value:e,typeName:Fe.ZodLiteral,...Ke(t)});function bN(e,t){return new ba({values:e,typeName:Fe.ZodEnum,...Ke(t)})}class ba extends Qe{constructor(){super(...arguments),fc.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return ve(n,{expected:ut.joinValues(r),received:n.parsedType,code:re.invalid_type}),Be}if(yh(this,fc)||gN(this,fc,new Set(this._def.values)),!yh(this,fc).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return ve(n,{received:n.data,code:re.invalid_enum_value,options:r}),Be}return Kn(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return ba.create(t,{...this._def,...n})}exclude(t,n=this._def){return ba.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}fc=new WeakMap;ba.create=bN;class xd extends Qe{constructor(){super(...arguments),pc.set(this,void 0)}_parse(t){const n=ut.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const s=ut.objectValues(n);return ve(r,{expected:ut.joinValues(s),received:r.parsedType,code:re.invalid_type}),Be}if(yh(this,pc)||gN(this,pc,new Set(ut.getValidEnumValues(this._def.values))),!yh(this,pc).has(t.data)){const s=ut.objectValues(n);return ve(r,{received:r.data,code:re.invalid_enum_value,options:s}),Be}return Kn(t.data)}get enum(){return this._def.values}}pc=new WeakMap;xd.create=(e,t)=>new xd({values:e,typeName:Fe.ZodNativeEnum,...Ke(t)});class su extends Qe{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return ve(n,{code:re.invalid_type,expected:be.promise,received:n.parsedType}),Be;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return Kn(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}su.create=(e,t)=>new su({type:e,typeName:Fe.ZodPromise,...Ke(t)});class ds extends Qe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Fe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,o={addIssue:a=>{ve(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const a=s.transform(r.data,o);if(r.common.async)return Promise.resolve(a).then(async i=>{if(n.value==="aborted")return Be;const c=await this._def.schema._parseAsync({data:i,path:r.path,parent:r});return c.status==="aborted"?Be:c.status==="dirty"||n.value==="dirty"?vl(c.value):c});{if(n.value==="aborted")return Be;const i=this._def.schema._parseSync({data:a,path:r.path,parent:r});return i.status==="aborted"?Be:i.status==="dirty"||n.value==="dirty"?vl(i.value):i}}if(s.type==="refinement"){const a=i=>{const c=s.refinement(i,o);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Be:(i.status==="dirty"&&n.dirty(),a(i.value),{status:n.value,value:i.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>i.status==="aborted"?Be:(i.status==="dirty"&&n.dirty(),a(i.value).then(()=>({status:n.value,value:i.value}))))}if(s.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!cd(a))return a;const i=s.transform(a.value,o);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:i}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>cd(a)?Promise.resolve(s.transform(a.value,o)).then(i=>({status:n.value,value:i})):a);ut.assertNever(s)}}ds.create=(e,t,n)=>new ds({schema:e,typeName:Fe.ZodEffects,effect:t,...Ke(n)});ds.createWithPreprocess=(e,t,n)=>new ds({schema:t,effect:{type:"preprocess",transform:e},typeName:Fe.ZodEffects,...Ke(n)});class Ls extends Qe{_parse(t){return this._getType(t)===be.undefined?Kn(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Ls.create=(e,t)=>new Ls({innerType:e,typeName:Fe.ZodOptional,...Ke(t)});class xa extends Qe{_parse(t){return this._getType(t)===be.null?Kn(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}xa.create=(e,t)=>new xa({innerType:e,typeName:Fe.ZodNullable,...Ke(t)});class wd extends Qe{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}wd.create=(e,t)=>new wd({innerType:e,typeName:Fe.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ke(t)});class Sd extends Qe{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return dd(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new yr(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new yr(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Sd.create=(e,t)=>new Sd({innerType:e,typeName:Fe.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ke(t)});class Sh extends Qe{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return ve(r,{code:re.invalid_type,expected:be.nan,received:r.parsedType}),Be}return{status:"valid",value:t.data}}}Sh.create=e=>new Sh({typeName:Fe.ZodNaN,...Ke(e)});const w6=Symbol("zod_brand");class Sw extends Qe{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class Xd extends Qe{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Be:o.status==="dirty"?(n.dirty(),vl(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?Be:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new Xd({in:t,out:n,typeName:Fe.ZodPipeline})}}class Cd extends Qe{_parse(t){const n=this._def.innerType._parse(t),r=s=>(cd(s)&&(s.value=Object.freeze(s.value)),s);return dd(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}Cd.create=(e,t)=>new Cd({innerType:e,typeName:Fe.ZodReadonly,...Ke(t)});function xN(e,t={},n){return e?ru.create().superRefine((r,s)=>{var o,a;if(!e(r)){const i=typeof t=="function"?t(r):typeof t=="string"?{message:t}:t,c=(a=(o=i.fatal)!==null&&o!==void 0?o:n)!==null&&a!==void 0?a:!0,l=typeof i=="string"?{message:i}:i;s.addIssue({code:"custom",...l,fatal:c})}}):ru.create()}const S6={object:Dt.lazycreate};var Fe;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(Fe||(Fe={}));const C6=(e,t={message:`Input not instance of ${e.name}`})=>xN(n=>n instanceof e,t),wN=es.create,SN=va.create,E6=Sh.create,T6=ya.create,CN=fd.create,k6=Ti.create,_6=bh.create,j6=pd.create,R6=hd.create,O6=ru.create,N6=fi.create,P6=bo.create,M6=xh.create,I6=as.create,D6=Dt.create,A6=Dt.strictCreate,F6=gd.create,L6=Og.create,$6=md.create,B6=Us.create,z6=vd.create,U6=wh.create,V6=ki.create,H6=jl.create,K6=yd.create,q6=bd.create,W6=ba.create,G6=xd.create,J6=su.create,D1=ds.create,Q6=Ls.create,Z6=xa.create,Y6=ds.createWithPreprocess,X6=Xd.create,e8=()=>wN().optional(),t8=()=>SN().optional(),n8=()=>CN().optional(),r8={string:e=>es.create({...e,coerce:!0}),number:e=>va.create({...e,coerce:!0}),boolean:e=>fd.create({...e,coerce:!0}),bigint:e=>ya.create({...e,coerce:!0}),date:e=>Ti.create({...e,coerce:!0})},s8=Be;var _=Object.freeze({__proto__:null,defaultErrorMap:nu,setErrorMap:s6,getErrorMap:mh,makeIssue:vh,EMPTY_PATH:o6,addIssueToContext:ve,ParseStatus:Dn,INVALID:Be,DIRTY:vl,OK:Kn,isAborted:eb,isDirty:tb,isValid:cd,isAsync:dd,get util(){return ut},get objectUtil(){return Xy},ZodParsedType:be,getParsedType:Vo,ZodType:Qe,datetimeRegex:yN,ZodString:es,ZodNumber:va,ZodBigInt:ya,ZodBoolean:fd,ZodDate:Ti,ZodSymbol:bh,ZodUndefined:pd,ZodNull:hd,ZodAny:ru,ZodUnknown:fi,ZodNever:bo,ZodVoid:xh,ZodArray:as,ZodObject:Dt,ZodUnion:gd,ZodDiscriminatedUnion:Og,ZodIntersection:md,ZodTuple:Us,ZodRecord:vd,ZodMap:wh,ZodSet:ki,ZodFunction:jl,ZodLazy:yd,ZodLiteral:bd,ZodEnum:ba,ZodNativeEnum:xd,ZodPromise:su,ZodEffects:ds,ZodTransformer:ds,ZodOptional:Ls,ZodNullable:xa,ZodDefault:wd,ZodCatch:Sd,ZodNaN:Sh,BRAND:w6,ZodBranded:Sw,ZodPipeline:Xd,ZodReadonly:Cd,custom:xN,Schema:Qe,ZodSchema:Qe,late:S6,get ZodFirstPartyTypeKind(){return Fe},coerce:r8,any:O6,array:I6,bigint:T6,boolean:CN,date:k6,discriminatedUnion:L6,effect:D1,enum:W6,function:H6,instanceof:C6,intersection:$6,lazy:K6,literal:q6,map:U6,nan:E6,nativeEnum:G6,never:P6,null:R6,nullable:Z6,number:SN,object:D6,oboolean:n8,onumber:t8,optional:Q6,ostring:e8,pipeline:X6,preprocess:Y6,promise:J6,record:z6,set:V6,strictObject:A6,string:wN,symbol:_6,transformer:D1,tuple:B6,undefined:j6,union:F6,unknown:N6,void:M6,NEVER:s8,ZodIssueCode:re,quotelessJson:r6,ZodError:yr}),EN=v.createContext({dragDropManager:void 0}),Dr;(function(e){e.SOURCE="SOURCE",e.TARGET="TARGET"})(Dr||(Dr={}));function Ve(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),s=2;s-1})}var u8={type:Cw,payload:{clientOffset:null,sourceClientOffset:null}};function c8(e){return function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{publishSource:!0},s=r.publishSource,o=s===void 0?!0:s,a=r.clientOffset,i=r.getSourceClientOffset,c=e.getMonitor(),l=e.getRegistry();e.dispatch(A1(a)),d8(n,c,l);var d=h8(n,c);if(d===null){e.dispatch(u8);return}var p=null;if(a){if(!i)throw new Error("getSourceClientOffset must be defined");f8(i),p=i(d)}e.dispatch(A1(a,p));var f=l.getSource(d),h=f.beginDrag(c,d);if(h!=null){p8(h),l.pinSource(d);var g=l.getSourceType(d);return{type:Ng,payload:{itemType:g,item:h,sourceId:d,clientOffset:a||null,sourceClientOffset:p||null,isSourcePublic:!!o}}}}}function d8(e,t,n){Ve(!t.isDragging(),"Cannot call beginDrag while dragging."),e.forEach(function(r){Ve(n.getSource(r),"Expected sourceIds to be registered.")})}function f8(e){Ve(typeof e=="function","When clientOffset is provided, getSourceClientOffset must be a function.")}function p8(e){Ve(TN(e),"Item must be an object.")}function h8(e,t){for(var n=null,r=e.length-1;r>=0;r--)if(t.canDragSource(e[r])){n=e[r];break}return n}function g8(e){return function(){var n=e.getMonitor();if(n.isDragging())return{type:Ew}}}function rb(e,t){return t===null?e===null:Array.isArray(e)?e.some(function(n){return n===t}):e===t}function m8(e){return function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=r.clientOffset;v8(n);var o=n.slice(0),a=e.getMonitor(),i=e.getRegistry();y8(o,a,i);var c=a.getItemType();return b8(o,i,c),x8(o,a,i),{type:Pg,payload:{targetIds:o,clientOffset:s||null}}}}function v8(e){Ve(Array.isArray(e),"Expected targetIds to be an array.")}function y8(e,t,n){Ve(t.isDragging(),"Cannot call hover while not dragging."),Ve(!t.didDrop(),"Cannot call hover after drop.");for(var r=0;r=0;r--){var s=e[r],o=t.getTargetType(s);rb(o,n)||e.splice(r,1)}}function x8(e,t,n){e.forEach(function(r){var s=n.getTarget(r);s.hover(t,r)})}function F1(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function L1(e){for(var t=1;t0&&arguments[0]!==void 0?arguments[0]:{},r=e.getMonitor(),s=e.getRegistry();C8(r);var o=k8(r);o.forEach(function(a,i){var c=E8(a,i,s,r),l={type:Mg,payload:{dropResult:L1(L1({},n),c)}};e.dispatch(l)})}}function C8(e){Ve(e.isDragging(),"Cannot call drop while not dragging."),Ve(!e.didDrop(),"Cannot call drop twice during one drag operation.")}function E8(e,t,n,r){var s=n.getTarget(e),o=s?s.drop(r,e):void 0;return T8(o),typeof o>"u"&&(o=t===0?{}:r.getDropResult()),o}function T8(e){Ve(typeof e>"u"||TN(e),"Drop result must either be an object or undefined.")}function k8(e){var t=e.getTargetIds().filter(e.canDropOnTarget,e);return t.reverse(),t}function _8(e){return function(){var n=e.getMonitor(),r=e.getRegistry();j8(n);var s=n.getSourceId();if(s!=null){var o=r.getSource(s,!0);o.endDrag(n,s),r.unpinSource()}return{type:Ig}}}function j8(e){Ve(e.isDragging(),"Cannot call endDrag while not dragging.")}function R8(e){return{beginDrag:c8(e),publishDragSource:g8(e),hover:m8(e),drop:S8(e),endDrag:_8(e)}}function O8(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function N8(e,t){for(var n=0;n0;r.backend&&(s&&!r.isSetUp?(r.backend.setup(),r.isSetUp=!0):!s&&r.isSetUp&&(r.backend.teardown(),r.isSetUp=!1))}),this.store=t,this.monitor=n,t.subscribe(this.handleRefCountChange)}return P8(e,[{key:"receiveBackend",value:function(n){this.backend=n}},{key:"getMonitor",value:function(){return this.monitor}},{key:"getBackend",value:function(){return this.backend}},{key:"getRegistry",value:function(){return this.monitor.registry}},{key:"getActions",value:function(){var n=this,r=this.store.dispatch;function s(a){return function(){for(var i=arguments.length,c=new Array(i),l=0;l"u"&&(n=t,t=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(_r(1));return n(kN)(e,t)}if(typeof e!="function")throw new Error(_r(2));var s=e,o=t,a=[],i=a,c=!1;function l(){i===a&&(i=a.slice())}function d(){if(c)throw new Error(_r(3));return o}function p(m){if(typeof m!="function")throw new Error(_r(4));if(c)throw new Error(_r(5));var x=!0;return l(),i.push(m),function(){if(x){if(c)throw new Error(_r(6));x=!1,l();var y=i.indexOf(m);i.splice(y,1),a=null}}}function f(m){if(!I8(m))throw new Error(_r(7));if(typeof m.type>"u")throw new Error(_r(8));if(c)throw new Error(_r(9));try{c=!0,o=s(o,m)}finally{c=!1}for(var x=a=i,b=0;b2&&arguments[2]!==void 0?arguments[2]:D8;if(e.length!==t.length)return!1;for(var r=0;r0&&arguments[0]!==void 0?arguments[0]:V1,t=arguments.length>1?arguments[1]:void 0,n=t.payload;switch(t.type){case Cw:case Ng:return{initialSourceClientOffset:n.sourceClientOffset,initialClientOffset:n.clientOffset,clientOffset:n.clientOffset};case Pg:return A8(e.clientOffset,n.clientOffset)?e:U1(U1({},e),{},{clientOffset:n.clientOffset});case Ig:case Mg:return V1;default:return e}}var Tw="dnd-core/ADD_SOURCE",kw="dnd-core/ADD_TARGET",_w="dnd-core/REMOVE_SOURCE",Dg="dnd-core/REMOVE_TARGET";function B8(e){return{type:Tw,payload:{sourceId:e}}}function z8(e){return{type:kw,payload:{targetId:e}}}function U8(e){return{type:_w,payload:{sourceId:e}}}function V8(e){return{type:Dg,payload:{targetId:e}}}function H1(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function jr(e){for(var t=1;t0&&arguments[0]!==void 0?arguments[0]:K8,t=arguments.length>1?arguments[1]:void 0,n=t.payload;switch(t.type){case Ng:return jr(jr({},e),{},{itemType:n.itemType,item:n.item,sourceId:n.sourceId,isSourcePublic:n.isSourcePublic,dropResult:null,didDrop:!1});case Ew:return jr(jr({},e),{},{isSourcePublic:!0});case Pg:return jr(jr({},e),{},{targetIds:n.targetIds});case Dg:return e.targetIds.indexOf(n.targetId)===-1?e:jr(jr({},e),{},{targetIds:a8(e.targetIds,n.targetId)});case Mg:return jr(jr({},e),{},{dropResult:n.dropResult,didDrop:!0,targetIds:[]});case Ig:return jr(jr({},e),{},{itemType:null,item:null,sourceId:null,dropResult:null,didDrop:!1,isSourcePublic:null,targetIds:[]});default:return e}}function W8(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,t=arguments.length>1?arguments[1]:void 0;switch(t.type){case Tw:case kw:return e+1;case _w:case Dg:return e-1;default:return e}}var Ch=[],jw=[];Ch.__IS_NONE__=!0;jw.__IS_ALL__=!0;function G8(e,t){if(e===Ch)return!1;if(e===jw||typeof t>"u")return!0;var n=l8(t,e);return n.length>0}function J8(){var e=arguments.length>1?arguments[1]:void 0;switch(e.type){case Pg:break;case Tw:case kw:case Dg:case _w:return Ch;case Ng:case Ew:case Ig:case Mg:default:return jw}var t=e.payload,n=t.targetIds,r=n===void 0?[]:n,s=t.prevTargetIds,o=s===void 0?[]:s,a=i8(r,o),i=a.length>0||!F8(r,o);if(!i)return Ch;var c=o[o.length-1],l=r[r.length-1];return c!==l&&(c&&a.push(c),l&&a.push(l)),a}function Q8(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return e+1}function K1(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function q1(e){for(var t=1;t0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;return{dirtyHandlerIds:J8(e.dirtyHandlerIds,{type:t.type,payload:q1(q1({},t.payload),{},{prevTargetIds:o8(e,"dragOperation.targetIds",[])})}),dragOffset:$8(e.dragOffset,t),refCount:W8(e.refCount,t),dragOperation:q8(e.dragOperation,t),stateId:Q8(e.stateId)}}function X8(e,t){return{x:e.x+t.x,y:e.y+t.y}}function _N(e,t){return{x:e.x-t.x,y:e.y-t.y}}function eH(e){var t=e.clientOffset,n=e.initialClientOffset,r=e.initialSourceClientOffset;return!t||!n||!r?null:_N(X8(t,r),n)}function tH(e){var t=e.clientOffset,n=e.initialClientOffset;return!t||!n?null:_N(t,n)}function nH(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function rH(e,t){for(var n=0;n1&&arguments[1]!==void 0?arguments[1]:{handlerIds:void 0},o=s.handlerIds;Ve(typeof n=="function","listener must be a function."),Ve(typeof o>"u"||Array.isArray(o),"handlerIds, when specified, must be an array of strings.");var a=this.store.getState().stateId,i=function(){var l=r.store.getState(),d=l.stateId;try{var p=d===a||d===a+1&&!G8(l.dirtyHandlerIds,o);p||n()}finally{a=d}};return this.store.subscribe(i)}},{key:"subscribeToOffsetChange",value:function(n){var r=this;Ve(typeof n=="function","listener must be a function.");var s=this.store.getState().dragOffset,o=function(){var i=r.store.getState().dragOffset;i!==s&&(s=i,n())};return this.store.subscribe(o)}},{key:"canDragSource",value:function(n){if(!n)return!1;var r=this.registry.getSource(n);return Ve(r,"Expected to find a valid source. sourceId=".concat(n)),this.isDragging()?!1:r.canDrag(this,n)}},{key:"canDropOnTarget",value:function(n){if(!n)return!1;var r=this.registry.getTarget(n);if(Ve(r,"Expected to find a valid target. targetId=".concat(n)),!this.isDragging()||this.didDrop())return!1;var s=this.registry.getTargetType(n),o=this.getItemType();return rb(s,o)&&r.canDrop(this,n)}},{key:"isDragging",value:function(){return!!this.getItemType()}},{key:"isDraggingSource",value:function(n){if(!n)return!1;var r=this.registry.getSource(n,!0);if(Ve(r,"Expected to find a valid source. sourceId=".concat(n)),!this.isDragging()||!this.isSourcePublic())return!1;var s=this.registry.getSourceType(n),o=this.getItemType();return s!==o?!1:r.isDragging(this,n)}},{key:"isOverTarget",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shallow:!1};if(!n)return!1;var s=r.shallow;if(!this.isDragging())return!1;var o=this.registry.getTargetType(n),a=this.getItemType();if(a&&!rb(o,a))return!1;var i=this.getTargetIds();if(!i.length)return!1;var c=i.indexOf(n);return s?c===i.length-1:c>-1}},{key:"getItemType",value:function(){return this.store.getState().dragOperation.itemType}},{key:"getItem",value:function(){return this.store.getState().dragOperation.item}},{key:"getSourceId",value:function(){return this.store.getState().dragOperation.sourceId}},{key:"getTargetIds",value:function(){return this.store.getState().dragOperation.targetIds}},{key:"getDropResult",value:function(){return this.store.getState().dragOperation.dropResult}},{key:"didDrop",value:function(){return this.store.getState().dragOperation.didDrop}},{key:"isSourcePublic",value:function(){return!!this.store.getState().dragOperation.isSourcePublic}},{key:"getInitialClientOffset",value:function(){return this.store.getState().dragOffset.initialClientOffset}},{key:"getInitialSourceClientOffset",value:function(){return this.store.getState().dragOffset.initialSourceClientOffset}},{key:"getClientOffset",value:function(){return this.store.getState().dragOffset.clientOffset}},{key:"getSourceClientOffset",value:function(){return eH(this.store.getState().dragOffset)}},{key:"getDifferenceFromInitialOffset",value:function(){return tH(this.store.getState().dragOffset)}}]),e}(),aH=0;function iH(){return aH++}function bp(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?bp=function(n){return typeof n}:bp=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},bp(e)}function lH(e){Ve(typeof e.canDrag=="function","Expected canDrag to be a function."),Ve(typeof e.beginDrag=="function","Expected beginDrag to be a function."),Ve(typeof e.endDrag=="function","Expected endDrag to be a function.")}function uH(e){Ve(typeof e.canDrop=="function","Expected canDrop to be a function."),Ve(typeof e.hover=="function","Expected hover to be a function."),Ve(typeof e.drop=="function","Expected beginDrag to be a function.")}function sb(e,t){if(t&&Array.isArray(e)){e.forEach(function(n){return sb(n,!1)});return}Ve(typeof e=="string"||bp(e)==="symbol",t?"Type can only be a string, a symbol, or an array of either.":"Type can only be a string or a symbol.")}const G1=typeof global<"u"?global:self,jN=G1.MutationObserver||G1.WebKitMutationObserver;function RN(e){return function(){const n=setTimeout(s,0),r=setInterval(s,50);function s(){clearTimeout(n),clearInterval(r),e()}}}function cH(e){let t=1;const n=new jN(e),r=document.createTextNode("");return n.observe(r,{characterData:!0}),function(){t=-t,r.data=t}}const dH=typeof jN=="function"?cH:RN;class fH{enqueueTask(t){const{queue:n,requestFlush:r}=this;n.length||(r(),this.flushing=!0),n[n.length]=t}constructor(){this.queue=[],this.pendingErrors=[],this.flushing=!1,this.index=0,this.capacity=1024,this.flush=()=>{const{queue:t}=this;for(;this.indexthis.capacity){for(let r=0,s=t.length-this.index;r{this.pendingErrors.push(t),this.requestErrorThrow()},this.requestFlush=dH(this.flush),this.requestErrorThrow=RN(()=>{if(this.pendingErrors.length)throw this.pendingErrors.shift()})}}class pH{call(){try{this.task&&this.task()}catch(t){this.onError(t)}finally{this.task=null,this.release(this)}}constructor(t,n){this.onError=t,this.release=n,this.task=null}}class hH{create(t){const n=this.freeTasks,r=n.length?n.pop():new pH(this.onError,s=>n[n.length]=s);return r.task=t,r}constructor(t){this.onError=t,this.freeTasks=[]}}const ON=new fH,gH=new hH(ON.registerPendingError);function mH(e){ON.enqueueTask(gH.create(e))}function vH(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function yH(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n1&&arguments[1]!==void 0?arguments[1]:!1;Ve(this.isSourceId(n),"Expected a valid source ID.");var s=r&&n===this.pinnedSourceId,o=s?this.pinnedSource:this.dragSources.get(n);return o}},{key:"getTarget",value:function(n){return Ve(this.isTargetId(n),"Expected a valid target ID."),this.dropTargets.get(n)}},{key:"getSourceType",value:function(n){return Ve(this.isSourceId(n),"Expected a valid source ID."),this.types.get(n)}},{key:"getTargetType",value:function(n){return Ve(this.isTargetId(n),"Expected a valid target ID."),this.types.get(n)}},{key:"isSourceId",value:function(n){var r=Q1(n);return r===Dr.SOURCE}},{key:"isTargetId",value:function(n){var r=Q1(n);return r===Dr.TARGET}},{key:"removeSource",value:function(n){var r=this;Ve(this.getSource(n),"Expected an existing source."),this.store.dispatch(U8(n)),mH(function(){r.dragSources.delete(n),r.types.delete(n)})}},{key:"removeTarget",value:function(n){Ve(this.getTarget(n),"Expected an existing target."),this.store.dispatch(V8(n)),this.dropTargets.delete(n),this.types.delete(n)}},{key:"pinSource",value:function(n){var r=this.getSource(n);Ve(r,"Expected an existing source."),this.pinnedSourceId=n,this.pinnedSource=r}},{key:"unpinSource",value:function(){Ve(this.pinnedSource,"No source is pinned at the time."),this.pinnedSourceId=null,this.pinnedSource=null}},{key:"addHandler",value:function(n,r,s){var o=TH(n);return this.types.set(o,r),n===Dr.SOURCE?this.dragSources.set(o,s):n===Dr.TARGET&&this.dropTargets.set(o,s),o}}]),e}();function _H(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=jH(r),o=new oH(s,new kH(s)),a=new M8(s,o),i=e(a,t,n);return a.receiveBackend(i),a}function jH(e){var t=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION__;return kN(Y8,e&&t&&t({name:"dnd-core",instanceId:"dnd-core"}))}var RH=["children"];function OH(e,t){return IH(e)||MH(e,t)||PH(e,t)||NH()}function NH(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function PH(e,t){if(e){if(typeof e=="string")return Y1(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Y1(e,t)}}function Y1(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function AH(e,t){if(e==null)return{};var n={},r=Object.keys(e),s,o;for(o=0;o=0)&&(n[s]=e[s]);return n}var X1=0,xp=Symbol.for("__REACT_DND_CONTEXT_INSTANCE__"),FH=v.memo(function(t){var n=t.children,r=DH(t,RH),s=LH(r),o=OH(s,2),a=o[0],i=o[1];return v.useEffect(function(){if(i){var c=NN();return++X1,function(){--X1===0&&(c[xp]=null)}}},[]),u.jsx(EN.Provider,Object.assign({value:a},{children:n}),void 0)});function LH(e){if("manager"in e){var t={dragDropManager:e.manager};return[t,!1]}var n=$H(e.backend,e.context,e.options,e.debugMode),r=!e.context;return[n,r]}function $H(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:NN(),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3?arguments[3]:void 0,s=t;return s[xp]||(s[xp]={dragDropManager:_H(e,t,n,r)}),s[xp]}function NN(){return typeof global<"u"?global:window}function BH(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function zH(e,t){for(var n=0;n, or turn it into a ")+"drag source or a drop target itself.")}}function JH(e){return function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;if(!v.isValidElement(t)){var r=t;return e(r,n),r}var s=t;GH(s);var o=n?function(a){return e(a,n)}:e;return QH(s,o)}}function PN(e){var t={};return Object.keys(e).forEach(function(n){var r=e[n];if(n.endsWith("Ref"))t[n]=e[n];else{var s=JH(r);t[n]=function(){return s}}}),t}function nC(e,t){typeof e=="function"?e(t):e.current=t}function QH(e,t){var n=e.ref;return Ve(typeof n!="string","Cannot connect React DnD to an element with an existing string ref. Please convert it to use a callback ref instead, or wrap it into a or
. Read more: https://reactjs.org/docs/refs-and-the-dom.html#callback-refs"),n?v.cloneElement(e,{ref:function(s){nC(n,s),nC(t,s)}}):v.cloneElement(e,{ref:t})}function wp(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?wp=function(n){return typeof n}:wp=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},wp(e)}function ob(e){return e!==null&&wp(e)==="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function ab(e,t,n,r){var s=void 0;if(s!==void 0)return!!s;if(e===t)return!0;if(typeof e!="object"||!e||typeof t!="object"||!t)return!1;var o=Object.keys(e),a=Object.keys(t);if(o.length!==a.length)return!1;for(var i=Object.prototype.hasOwnProperty.bind(t),c=0;ce.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n0}},{key:"leave",value:function(n){var r=this.entered.length;return this.entered=oK(this.entered.filter(this.isNodeInDocument),n),r>0&&this.entered.length===0}},{key:"reset",value:function(){this.entered=[]}}]),e}(),dK=DN(function(){return/firefox/i.test(navigator.userAgent)}),AN=DN(function(){return!!window.safari});function fK(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function pK(e,t){for(var n=0;nn)d=p-1;else return s[p]}c=Math.max(0,d);var h=n-r[c],g=h*h;return s[c]+o[c]*h+a[c]*g+i[c]*h*g}}]),e}(),gK=1;function FN(e){var t=e.nodeType===gK?e:e.parentElement;if(!t)return null;var n=t.getBoundingClientRect(),r=n.top,s=n.left;return{x:s,y:r}}function Bf(e){return{x:e.clientX,y:e.clientY}}function mK(e){var t;return e.nodeName==="IMG"&&(dK()||!((t=document.documentElement)!==null&&t!==void 0&&t.contains(e)))}function vK(e,t,n,r){var s=e?t.width:n,o=e?t.height:r;return AN()&&e&&(o/=window.devicePixelRatio,s/=window.devicePixelRatio),{dragPreviewWidth:s,dragPreviewHeight:o}}function yK(e,t,n,r,s){var o=mK(t),a=o?e:t,i=FN(a),c={x:n.x-i.x,y:n.y-i.y},l=e.offsetWidth,d=e.offsetHeight,p=r.anchorX,f=r.anchorY,h=vK(o,t,l,d),g=h.dragPreviewWidth,m=h.dragPreviewHeight,x=function(){var k=new uC([0,.5,1],[c.y,c.y/d*m,c.y+m-d]),T=k.interpolate(f);return AN()&&o&&(T+=(window.devicePixelRatio-1)*m),T},b=function(){var k=new uC([0,.5,1],[c.x,c.x/l*g,c.x+g-l]);return k.interpolate(p)},y=s.offsetX,w=s.offsetY,S=y===0||y,E=w===0||w;return{x:S?y:b(),y:E?w:x()}}var LN="__NATIVE_FILE__",$N="__NATIVE_URL__",BN="__NATIVE_TEXT__",zN="__NATIVE_HTML__";const cC=Object.freeze(Object.defineProperty({__proto__:null,FILE:LN,HTML:zN,TEXT:BN,URL:$N},Symbol.toStringTag,{value:"Module"}));function av(e,t,n){var r=t.reduce(function(s,o){return s||e.getData(o)},"");return r??n}var Qi;function zf(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var lb=(Qi={},zf(Qi,LN,{exposeProperties:{files:function(t){return Array.prototype.slice.call(t.files)},items:function(t){return t.items},dataTransfer:function(t){return t}},matchesTypes:["Files"]}),zf(Qi,zN,{exposeProperties:{html:function(t,n){return av(t,n,"")},dataTransfer:function(t){return t}},matchesTypes:["Html","text/html"]}),zf(Qi,$N,{exposeProperties:{urls:function(t,n){return av(t,n,"").split(` +`)},dataTransfer:function(t){return t}},matchesTypes:["Url","text/uri-list"]}),zf(Qi,BN,{exposeProperties:{text:function(t,n){return av(t,n,"")},dataTransfer:function(t){return t}},matchesTypes:["Text","text/plain"]}),Qi);function bK(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function xK(e,t){for(var n=0;n-1})})[0]||null}function EK(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function TK(e,t){for(var n=0;n0&&s.actions.hover(a,{clientOffset:Bf(o)});var i=a.some(function(c){return s.monitor.canDropOnTarget(c)});i&&(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect=s.getCurrentDropEffect()))}}),st(this,"handleTopDragOverCapture",function(){s.dragOverTargetIds=[]}),st(this,"handleTopDragOver",function(o){var a=s.dragOverTargetIds;if(s.dragOverTargetIds=[],!s.monitor.isDragging()){o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="none");return}s.altKeyPressed=o.altKey,s.lastClientOffset=Bf(o),s.hoverRafId===null&&typeof requestAnimationFrame<"u"&&(s.hoverRafId=requestAnimationFrame(function(){s.monitor.isDragging()&&s.actions.hover(a||[],{clientOffset:s.lastClientOffset}),s.hoverRafId=null}));var i=(a||[]).some(function(c){return s.monitor.canDropOnTarget(c)});i?(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect=s.getCurrentDropEffect())):s.isDraggingNativeItem()?o.preventDefault():(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="none"))}),st(this,"handleTopDragLeaveCapture",function(o){s.isDraggingNativeItem()&&o.preventDefault();var a=s.enterLeaveCounter.leave(o.target);a&&s.isDraggingNativeItem()&&setTimeout(function(){return s.endDragNativeItem()},0)}),st(this,"handleTopDropCapture",function(o){if(s.dropTargetIds=[],s.isDraggingNativeItem()){var a;o.preventDefault(),(a=s.currentNativeSource)===null||a===void 0||a.loadDataTransfer(o.dataTransfer)}else iv(o.dataTransfer)&&o.preventDefault();s.enterLeaveCounter.reset()}),st(this,"handleTopDrop",function(o){var a=s.dropTargetIds;s.dropTargetIds=[],s.actions.hover(a,{clientOffset:Bf(o)}),s.actions.drop({dropEffect:s.getCurrentDropEffect()}),s.isDraggingNativeItem()?s.endDragNativeItem():s.monitor.isDragging()&&s.actions.endDrag()}),st(this,"handleSelectStart",function(o){var a=o.target;typeof a.dragDrop=="function"&&(a.tagName==="INPUT"||a.tagName==="SELECT"||a.tagName==="TEXTAREA"||a.isContentEditable||(o.preventDefault(),a.dragDrop()))}),this.options=new _K(n,r),this.actions=t.getActions(),this.monitor=t.getMonitor(),this.registry=t.getRegistry(),this.enterLeaveCounter=new cK(this.isNodeInDocument)}return OK(e,[{key:"profile",value:function(){var n,r;return{sourcePreviewNodes:this.sourcePreviewNodes.size,sourcePreviewNodeOptions:this.sourcePreviewNodeOptions.size,sourceNodeOptions:this.sourceNodeOptions.size,sourceNodes:this.sourceNodes.size,dragStartSourceIds:((n=this.dragStartSourceIds)===null||n===void 0?void 0:n.length)||0,dropTargetIds:this.dropTargetIds.length,dragEnterTargetIds:this.dragEnterTargetIds.length,dragOverTargetIds:((r=this.dragOverTargetIds)===null||r===void 0?void 0:r.length)||0}}},{key:"window",get:function(){return this.options.window}},{key:"document",get:function(){return this.options.document}},{key:"rootElement",get:function(){return this.options.rootElement}},{key:"setup",value:function(){var n=this.rootElement;if(n!==void 0){if(n.__isReactDndBackendSetUp)throw new Error("Cannot have two HTML5 backends at the same time.");n.__isReactDndBackendSetUp=!0,this.addEventListeners(n)}}},{key:"teardown",value:function(){var n=this.rootElement;if(n!==void 0&&(n.__isReactDndBackendSetUp=!1,this.removeEventListeners(this.rootElement),this.clearCurrentDragSourceNode(),this.asyncEndDragFrameId)){var r;(r=this.window)===null||r===void 0||r.cancelAnimationFrame(this.asyncEndDragFrameId)}}},{key:"connectDragPreview",value:function(n,r,s){var o=this;return this.sourcePreviewNodeOptions.set(n,s),this.sourcePreviewNodes.set(n,r),function(){o.sourcePreviewNodes.delete(n),o.sourcePreviewNodeOptions.delete(n)}}},{key:"connectDragSource",value:function(n,r,s){var o=this;this.sourceNodes.set(n,r),this.sourceNodeOptions.set(n,s);var a=function(l){return o.handleDragStart(l,n)},i=function(l){return o.handleSelectStart(l)};return r.setAttribute("draggable","true"),r.addEventListener("dragstart",a),r.addEventListener("selectstart",i),function(){o.sourceNodes.delete(n),o.sourceNodeOptions.delete(n),r.removeEventListener("dragstart",a),r.removeEventListener("selectstart",i),r.setAttribute("draggable","false")}}},{key:"connectDropTarget",value:function(n,r){var s=this,o=function(l){return s.handleDragEnter(l,n)},a=function(l){return s.handleDragOver(l,n)},i=function(l){return s.handleDrop(l,n)};return r.addEventListener("dragenter",o),r.addEventListener("dragover",a),r.addEventListener("drop",i),function(){r.removeEventListener("dragenter",o),r.removeEventListener("dragover",a),r.removeEventListener("drop",i)}}},{key:"addEventListeners",value:function(n){n.addEventListener&&(n.addEventListener("dragstart",this.handleTopDragStart),n.addEventListener("dragstart",this.handleTopDragStartCapture,!0),n.addEventListener("dragend",this.handleTopDragEndCapture,!0),n.addEventListener("dragenter",this.handleTopDragEnter),n.addEventListener("dragenter",this.handleTopDragEnterCapture,!0),n.addEventListener("dragleave",this.handleTopDragLeaveCapture,!0),n.addEventListener("dragover",this.handleTopDragOver),n.addEventListener("dragover",this.handleTopDragOverCapture,!0),n.addEventListener("drop",this.handleTopDrop),n.addEventListener("drop",this.handleTopDropCapture,!0))}},{key:"removeEventListeners",value:function(n){n.removeEventListener&&(n.removeEventListener("dragstart",this.handleTopDragStart),n.removeEventListener("dragstart",this.handleTopDragStartCapture,!0),n.removeEventListener("dragend",this.handleTopDragEndCapture,!0),n.removeEventListener("dragenter",this.handleTopDragEnter),n.removeEventListener("dragenter",this.handleTopDragEnterCapture,!0),n.removeEventListener("dragleave",this.handleTopDragLeaveCapture,!0),n.removeEventListener("dragover",this.handleTopDragOver),n.removeEventListener("dragover",this.handleTopDragOverCapture,!0),n.removeEventListener("drop",this.handleTopDrop),n.removeEventListener("drop",this.handleTopDropCapture,!0))}},{key:"getCurrentSourceNodeOptions",value:function(){var n=this.monitor.getSourceId(),r=this.sourceNodeOptions.get(n);return pC({dropEffect:this.altKeyPressed?"copy":"move"},r||{})}},{key:"getCurrentDropEffect",value:function(){return this.isDraggingNativeItem()?"copy":this.getCurrentSourceNodeOptions().dropEffect}},{key:"getCurrentSourcePreviewNodeOptions",value:function(){var n=this.monitor.getSourceId(),r=this.sourcePreviewNodeOptions.get(n);return pC({anchorX:.5,anchorY:.5,captureDraggingState:!1},r||{})}},{key:"isDraggingNativeItem",value:function(){var n=this.monitor.getItemType();return Object.keys(cC).some(function(r){return cC[r]===n})}},{key:"beginDragNativeItem",value:function(n,r){this.clearCurrentDragSourceNode(),this.currentNativeSource=CK(n,r),this.currentNativeHandle=this.registry.addSource(n,this.currentNativeSource),this.actions.beginDrag([this.currentNativeHandle])}},{key:"setCurrentDragSourceNode",value:function(n){var r=this;this.clearCurrentDragSourceNode(),this.currentDragSourceNode=n;var s=1e3;this.mouseMoveTimeoutTimer=setTimeout(function(){var o;return(o=r.rootElement)===null||o===void 0?void 0:o.addEventListener("mousemove",r.endDragIfSourceWasRemovedFromDOM,!0)},s)}},{key:"clearCurrentDragSourceNode",value:function(){if(this.currentDragSourceNode){if(this.currentDragSourceNode=null,this.rootElement){var n;(n=this.window)===null||n===void 0||n.clearTimeout(this.mouseMoveTimeoutTimer||void 0),this.rootElement.removeEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0)}return this.mouseMoveTimeoutTimer=null,!0}return!1}},{key:"handleDragStart",value:function(n,r){n.defaultPrevented||(this.dragStartSourceIds||(this.dragStartSourceIds=[]),this.dragStartSourceIds.unshift(r))}},{key:"handleDragEnter",value:function(n,r){this.dragEnterTargetIds.unshift(r)}},{key:"handleDragOver",value:function(n,r){this.dragOverTargetIds===null&&(this.dragOverTargetIds=[]),this.dragOverTargetIds.unshift(r)}},{key:"handleDrop",value:function(n,r){this.dropTargetIds.unshift(r)}}]),e}(),PK=function(t,n,r){return new NK(t,n,r)},MK=Object.create,UN=Object.defineProperty,IK=Object.getOwnPropertyDescriptor,VN=Object.getOwnPropertyNames,DK=Object.getPrototypeOf,AK=Object.prototype.hasOwnProperty,FK=(e,t)=>function(){return t||(0,e[VN(e)[0]])((t={exports:{}}).exports,t),t.exports},LK=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of VN(t))!AK.call(e,s)&&s!==n&&UN(e,s,{get:()=>t[s],enumerable:!(r=IK(t,s))||r.enumerable});return e},HN=(e,t,n)=>(n=e!=null?MK(DK(e)):{},LK(UN(n,"default",{value:e,enumerable:!0}),e)),KN=FK({"node_modules/classnames/index.js"(e,t){(function(){var n={}.hasOwnProperty;function r(){for(var s=[],o=0;o-1}var Wq=qq,Gq=9007199254740991,Jq=/^(?:0|[1-9]\d*)$/;function Qq(e,t){var n=typeof e;return t=t??Gq,!!t&&(n=="number"||n!="symbol"&&Jq.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=Xq}var YN=eW;function tW(e){return e!=null&&YN(e.length)&&!QN(e)}var nW=tW,rW=Object.prototype;function sW(e){var t=e&&e.constructor,n=typeof t=="function"&&t.prototype||rW;return e===n}var oW=sW;function aW(e,t){for(var n=-1,r=Array(e);++n-1}var FG=AG;function LG(e,t){var n=this.__data__,r=Ag(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}var $G=LG;function Eu(e){var t=-1,n=e==null?0:e.length;for(this.clear();++ti))return!1;var l=o.get(e),d=o.get(t);if(l&&d)return l==t&&d==e;var p=-1,f=!0,h=n&q9?new oP:void 0;for(o.set(e,t),o.set(t,e);++p":">",'"':""","'":"'"},TJ=s9(EJ),kJ=TJ,uP=/[&<>"']/g,_J=RegExp(uP.source);function jJ(e){return e=sP(e),e&&_J.test(e)?e.replace(uP,kJ):e}var RJ=jJ,cP=/[\\^$.*+?()[\]{}|]/g,OJ=RegExp(cP.source);function NJ(e){return e=sP(e),e&&OJ.test(e)?e.replace(cP,"\\$&"):e}var PJ=NJ;function MJ(e,t){return wJ(e,t)}var IJ=MJ,DJ=1/0,AJ=Ol&&1/Rw(new Ol([,-0]))[1]==DJ?function(e){return new Ol(e)}:Fq,FJ=AJ,LJ=200;function $J(e,t,n){var r=-1,s=Wq,o=e.length,a=!0,i=[],c=i;if(n)a=!1,s=CJ;else if(o>=LJ){var l=t?null:FJ(e);if(l)return Rw(l);a=!1,s=aP,c=new oP}else c=t?[]:i;e:for(;++ru.jsx("button",{className:e.classNames.clearAll,onClick:e.onClick,children:"Clear all"}),HJ=VJ,KJ=(e,t)=>{const n=t.offsetHeight,r=e.offsetHeight,s=e.offsetTop-t.scrollTop;s+r>=n?t.scrollTop+=s-n+r:s<0&&(t.scrollTop+=s)},pb=(e,t,n,r)=>typeof r=="function"?r(e):e.length>=t&&n,qJ=e=>{const t=v.createRef(),{labelField:n,minQueryLength:r,isFocused:s,classNames:o,selectedIndex:a,query:i}=e;v.useEffect(()=>{if(!t.current)return;const p=t.current.querySelector(`.${o.activeSuggestion}`);p&&KJ(p,t.current)},[a]);const c=(p,f)=>{const h=f.trim().replace(/[-\\^$*+?.()|[\]{}]/g,"\\$&"),{[n]:g}=p;return{__html:g.replace(RegExp(h,"gi"),m=>`${RJ(m)}`)}},l=(p,f)=>typeof e.renderSuggestion=="function"?e.renderSuggestion(p,f):u.jsx("span",{dangerouslySetInnerHTML:c(p,f)}),d=e.suggestions.map((p,f)=>u.jsx("li",{onMouseDown:e.handleClick.bind(null,f),onTouchStart:e.handleClick.bind(null,f),onMouseOver:e.handleHover.bind(null,f),className:f===e.selectedIndex?e.classNames.activeSuggestion:"",children:l(p,e.query)},f));return d.length===0||!pb(i,r||2,s,e.shouldRenderSuggestions)?null:u.jsx("div",{ref:t,className:o.suggestions,"data-testid":"suggestions",children:u.jsxs("ul",{children:[" ",d," "]})})},WJ=(e,t)=>{const{query:n,minQueryLength:r=2,isFocused:s,suggestions:o}=t;return!!(e.isFocused===s&&IJ(e.suggestions,o)&&pb(n,r,s,t.shouldRenderSuggestions)===pb(e.query,e.minQueryLength??2,e.isFocused,e.shouldRenderSuggestions)&&e.selectedIndex===t.selectedIndex)},GJ=v.memo(qJ,WJ),JJ=GJ,QJ=HN(KN()),ZJ=HN(KN());function YJ(e){const t=e.map(r=>{const s=r-48*Math.floor(r/48);return String.fromCharCode(96<=r?s:r)}).join(""),n=PJ(t);return new RegExp(`[${n}]+`)}function XJ(e){switch(e){case Rs.ENTER:return[10,13];case Rs.TAB:return 9;case Rs.COMMA:return 188;case Rs.SPACE:return 32;case Rs.SEMICOLON:return 186;default:return 0}}function $C(e){const{moveTag:t,readOnly:n,allowDragDrop:r}=e;return t!==void 0&&!n&&r}function eQ(e){const{readOnly:t,allowDragDrop:n}=e;return!t&&n}var tQ=e=>{const{readOnly:t,removeComponent:n,onRemove:r,className:s,tag:o,index:a}=e,i=l=>{if(Rl.ENTER.includes(l.keyCode)||l.keyCode===Rl.SPACE){l.preventDefault(),l.stopPropagation();return}l.keyCode===Rl.BACKSPACE&&r(l)};if(t)return u.jsx("span",{});const c=`Tag at index ${a} with value ${o.id} focussed. Press backspace to remove`;if(n){const l=n;return u.jsx(l,{"data-testid":"remove",onRemove:r,onKeyDown:i,className:s,"aria-label":c,tag:o,index:a})}return u.jsx("button",{"data-testid":"remove",onClick:r,onKeyDown:i,className:s,type:"button","aria-label":c,children:u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",height:"12",width:"12",fill:"#fff",children:u.jsx("path",{d:"M376.6 84.5c11.3-13.6 9.5-33.8-4.1-45.1s-33.8-9.5-45.1 4.1L192 206 56.6 43.5C45.3 29.9 25.1 28.1 11.5 39.4S-3.9 70.9 7.4 84.5L150.3 256 7.4 427.5c-11.3 13.6-9.5 33.8 4.1 45.1s33.8 9.5 45.1-4.1L192 306 327.4 468.5c11.3 13.6 31.5 15.4 45.1 4.1s15.4-31.5 4.1-45.1L233.7 256 376.6 84.5z"})})})},nQ=tQ,BC={TAG:"tag"},rQ=e=>{const t=v.useRef(null),{readOnly:n=!1,tag:r,classNames:s,index:o,moveTag:a,allowDragDrop:i=!0,labelField:c="text",tags:l}=e,[{isDragging:d},p]=U7(()=>({type:BC.TAG,collect:x=>({isDragging:!!x.isDragging()}),item:e,canDrag:()=>$C({moveTag:a,readOnly:n,allowDragDrop:i})}),[l]),[,f]=sK(()=>({accept:BC.TAG,drop:x=>{var w;const b=x.index,y=o;b!==y&&((w=e==null?void 0:e.moveTag)==null||w.call(e,b,y))},canDrop:x=>eQ(x)}),[l]);p(f(t));const h=e.tag[c],{className:g=""}=r,m=d?0:1;return u.jsxs("span",{ref:t,className:(0,ZJ.default)("tag-wrapper",s.tag,g),style:{opacity:m,cursor:$C({moveTag:a,readOnly:n,allowDragDrop:i})?"move":"auto"},"data-testid":"tag",onClick:e.onTagClicked,onTouchStart:e.onTagClicked,children:[h,u.jsx(nQ,{tag:e.tag,className:s.remove,removeComponent:e.removeComponent,onRemove:e.onDelete,readOnly:n,index:o})]})},sQ=e=>{const{autofocus:t,autoFocus:n,readOnly:r,labelField:s,allowDeleteFromEmptyInput:o,allowAdditionFromPaste:a,allowDragDrop:i,minQueryLength:c,shouldRenderSuggestions:l,removeComponent:d,autocomplete:p,inline:f,maxTags:h,allowUnique:g,editable:m,placeholder:x,delimiters:b,separators:y,tags:w,inputFieldPosition:S,inputProps:E,classNames:C,maxLength:k,inputValue:T,clearAll:O}=e,[M,U]=v.useState(e.suggestions),[I,J]=v.useState(""),[V,G]=v.useState(!1),[ee,q]=v.useState(-1),[F,A]=v.useState(!1),[Y,de]=v.useState(""),[z,se]=v.useState(-1),[ne,ie]=v.useState(""),oe=v.createRef(),W=v.useRef(null),Ce=v.useRef(null);v.useEffect(()=>{b.length&&console.warn("[Deprecation] The delimiters prop is deprecated and will be removed in v7.x.x, please use separators instead. If you have any concerns regarding this, please share your thoughts in https://github.com/react-tags/react-tags/issues/960")},[]),v.useEffect(()=>{typeof f<"u"&&console.warn("[Deprecation] The inline attribute is deprecated and will be removed in v7.x.x, please use inputFieldPosition instead.")},[f]),v.useEffect(()=>{typeof t<"u"&&console.warn("[Deprecated] autofocus prop will be removed in 7.x so please migrate to autoFocus prop."),(t||n&&t!==!1)&&!r&&Oe()},[n,n,r]),v.useEffect(()=>{Wt()},[I,e.suggestions]);const Re=ue=>{let Ue=e.suggestions.slice();if(g){const _n=w.map(ms=>ms.id.trim().toLowerCase());Ue=Ue.filter(ms=>!_n.includes(ms.id.toLowerCase()))}if(e.handleFilterSuggestions)return e.handleFilterSuggestions(ue,Ue);const St=Ue.filter(_n=>Le(ue,_n)===0),dt=Ue.filter(_n=>Le(ue,_n)>0);return St.concat(dt)},Le=(ue,Ue)=>Ue[s].toLowerCase().indexOf(ue.toLowerCase()),Oe=()=>{J(""),W.current&&(W.current.value="",W.current.focus())},me=(ue,Ue)=>{var dt;Ue.preventDefault(),Ue.stopPropagation();const St=w.slice();St.length!==0&&(ie(""),(dt=e==null?void 0:e.handleDelete)==null||dt.call(e,ue,Ue),rt(ue,St))},rt=(ue,Ue)=>{var _n;if(!(oe!=null&&oe.current))return;const St=oe.current.querySelectorAll(".ReactTags__remove");let dt="";ue===0&&Ue.length>1?(dt=`Tag at index ${ue} with value ${Ue[ue].id} deleted. Tag at index 0 with value ${Ue[1].id} focussed. Press backspace to remove`,St[0].focus()):ue>0?(dt=`Tag at index ${ue} with value ${Ue[ue].id} deleted. Tag at index ${ue-1} with value ${Ue[ue-1].id} focussed. Press backspace to remove`,St[ue-1].focus()):(dt=`Tag at index ${ue} with value ${Ue[ue].id} deleted. Input focussed. Press enter to add a new tag`,(_n=W.current)==null||_n.focus()),de(dt)},It=(ue,Ue,St)=>{var dt,_n;r||(m&&(se(ue),J(Ue[s]),(dt=Ce.current)==null||dt.focus()),(_n=e.handleTagClick)==null||_n.call(e,ue,St))},Zt=ue=>{e.handleInputChange&&e.handleInputChange(ue.target.value,ue);const Ue=ue.target.value.trim();J(Ue)},Wt=()=>{const ue=Re(I);U(ue),q(ee>=ue.length?ue.length-1:ee)},an=ue=>{const Ue=ue.target.value;e.handleInputFocus&&e.handleInputFocus(Ue,ue),G(!0)},j=ue=>{const Ue=ue.target.value;e.handleInputBlur&&(e.handleInputBlur(Ue,ue),W.current&&(W.current.value="")),G(!1),se(-1)},D=ue=>{if(ue.key==="Escape"&&(ue.preventDefault(),ue.stopPropagation(),q(-1),A(!1),U([]),se(-1)),(y.indexOf(ue.key)!==-1||b.indexOf(ue.keyCode)!==-1)&&!ue.shiftKey){(ue.keyCode!==Rl.TAB||I!=="")&&ue.preventDefault();const Ue=F&&ee!==-1?M[ee]:{id:I.trim(),[s]:I.trim(),className:""};Object.keys(Ue)&&le(Ue)}ue.key==="Backspace"&&I===""&&(o||S===ec.INLINE)&&me(w.length-1,ue),ue.keyCode===Rl.UP_ARROW&&(ue.preventDefault(),q(ee<=0?M.length-1:ee-1),A(!0)),ue.keyCode===Rl.DOWN_ARROW&&(ue.preventDefault(),A(!0),M.length===0?q(-1):q((ee+1)%M.length))},B=()=>h&&w.length>=h,pe=ue=>{if(!a)return;if(B()){ie(gC.TAG_LIMIT),Oe();return}ie(""),ue.preventDefault();const Ue=ue.clipboardData||window.clipboardData,St=Ue.getData("text"),{maxLength:dt=St.length}=e,_n=Math.min(dt,St.length),ms=Ue.getData("text").substr(0,_n);let Ro=b;y.length&&(Ro=[],y.forEach(vs=>{const Du=XJ(vs);Array.isArray(Du)?Ro=[...Ro,...Du]:Ro.push(Du)}));const Iu=YJ(Ro),$i=ms.split(Iu).map(vs=>vs.trim());UJ($i).forEach(vs=>le({id:vs.trim(),[s]:vs.trim(),className:""}))},le=ue=>{var St;if(!ue.id||!ue[s])return;if(z===-1){if(B()){ie(gC.TAG_LIMIT),Oe();return}ie("")}const Ue=w.map(dt=>dt.id.toLowerCase());if(!(g&&Ue.indexOf(ue.id.trim().toLowerCase())>=0)){if(p){const dt=Re(ue[s]);console.warn("[Deprecation] The autocomplete prop will be removed in 7.x to simplify the integration and make it more intutive. If you have any concerns regarding this, please share your thoughts in https://github.com/react-tags/react-tags/issues/949"),(p===1&&dt.length===1||p===!0&&dt.length)&&(ue=dt[0])}z!==-1&&e.onTagUpdate?e.onTagUpdate(z,ue):(St=e==null?void 0:e.handleAddition)==null||St.call(e,ue),J(""),A(!1),q(-1),se(-1),Oe()}},ae=ue=>{le(M[ue])},Ee=()=>{e.onClearAll&&e.onClearAll(),ie(""),Oe()},et=ue=>{q(ue),A(!0)},kt=(ue,Ue)=>{var dt;const St=w[ue];(dt=e==null?void 0:e.handleDrag)==null||dt.call(e,St,ue,Ue)},yn=(()=>{const ue={...hC,...e.classNames};return w.map((Ue,St)=>u.jsx(v.Fragment,{children:z===St?u.jsx("div",{className:ue.editTagInput,children:u.jsx("input",{ref:dt=>{Ce.current=dt},onFocus:an,value:I,onChange:Zt,onKeyDown:D,onBlur:j,className:ue.editTagInputField,onPaste:pe,"data-testid":"tag-edit"})}):u.jsx(rQ,{index:St,tag:Ue,tags:w,labelField:s,onDelete:dt=>me(St,dt),moveTag:i?kt:void 0,removeComponent:d,onTagClicked:dt=>It(St,Ue,dt),readOnly:r,classNames:ue,allowDragDrop:i})},St))})(),gn={...hC,...C},{name:jo,id:gs}=e,Aa=f===!1?ec.BOTTOM:S,Fn=r?null:u.jsxs("div",{className:gn.tagInput,children:[u.jsx("input",{...E,ref:ue=>{W.current=ue},className:gn.tagInputField,type:"text",placeholder:x,"aria-label":x,onFocus:an,onBlur:j,onChange:Zt,onKeyDown:D,onPaste:pe,name:jo,id:gs,maxLength:k,value:T,"data-automation":"input","data-testid":"input"}),u.jsx(JJ,{query:I.trim(),suggestions:M,labelField:s,selectedIndex:ee,handleClick:ae,handleHover:et,minQueryLength:c,shouldRenderSuggestions:l,isFocused:V,classNames:gn,renderSuggestion:e.renderSuggestion}),O&&w.length>0&&u.jsx(HJ,{classNames:gn,onClick:Ee}),ne&&u.jsxs("div",{"data-testid":"error",className:"ReactTags__error",children:[u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",height:"24",width:"24",fill:"#e03131",children:u.jsx("path",{d:"M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224a32 32 0 1 0 -64 0 32 32 0 1 0 64 0z"})}),ne]})]});return u.jsxs("div",{className:(0,QJ.default)(gn.tags,"react-tags-wrapper"),ref:oe,children:[u.jsx("p",{role:"alert",className:"sr-only",style:{position:"absolute",overflow:"hidden",clip:"rect(0 0 0 0)",margin:"-1px",padding:0,width:"1px",height:"1px",border:0},children:Y}),Aa===ec.TOP&&Fn,u.jsxs("div",{className:gn.selected,children:[yn,Aa===ec.INLINE&&Fn]}),Aa===ec.BOTTOM&&Fn]})},oQ=sQ,aQ=e=>{var ne;const{placeholder:t=$K,labelField:n=BK,suggestions:r=[],delimiters:s=[],separators:o=(ne=e.delimiters)!=null&&ne.length?[]:[Rs.ENTER,Rs.TAB],autofocus:a,autoFocus:i=!0,inline:c,inputFieldPosition:l="inline",allowDeleteFromEmptyInput:d=!1,allowAdditionFromPaste:p=!0,autocomplete:f=!1,readOnly:h=!1,allowUnique:g=!0,allowDragDrop:m=!0,tags:x=[],inputProps:b={},editable:y=!1,clearAll:w=!1,handleDelete:S,handleAddition:E,onTagUpdate:C,handleDrag:k,handleFilterSuggestions:T,handleTagClick:O,handleInputChange:M,handleInputFocus:U,handleInputBlur:I,minQueryLength:J,shouldRenderSuggestions:V,removeComponent:G,onClearAll:ee,classNames:q,name:F,id:A,maxLength:Y,inputValue:de,maxTags:z,renderSuggestion:se}=e;return u.jsx(oQ,{placeholder:t,labelField:n,suggestions:r,delimiters:s,separators:o,autofocus:a,autoFocus:i,inline:c,inputFieldPosition:l,allowDeleteFromEmptyInput:d,allowAdditionFromPaste:p,autocomplete:f,readOnly:h,allowUnique:g,allowDragDrop:m,tags:x,inputProps:b,editable:y,clearAll:w,handleDelete:S,handleAddition:E,onTagUpdate:C,handleDrag:k,handleFilterSuggestions:T,handleTagClick:O,handleInputChange:M,handleInputFocus:U,handleInputBlur:I,minQueryLength:J,shouldRenderSuggestions:V,removeComponent:G,onClearAll:ee,classNames:q,name:F,id:A,maxLength:Y,inputValue:de,maxTags:z,renderSuggestion:se})},iQ=({...e})=>u.jsx(FH,{backend:PK,children:u.jsx(aQ,{...e})});/*! Bundled license information: + +classnames/index.js: + (*! + Copyright (c) 2018 Jed Watson. + Licensed under the MIT License (MIT), see + http://jedwatson.github.io/classnames + *) + +lodash-es/lodash.js: + (** + * @license + * Lodash (Custom Build) + * Build: `lodash modularize exports="es" -o ./` + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + *) +*/var lQ="Label",dP=v.forwardRef((e,t)=>u.jsx(Me.label,{...e,ref:t,onMouseDown:n=>{var s;n.target.closest("button, input, select, textarea")||((s=e.onMouseDown)==null||s.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));dP.displayName=lQ;var fP=dP;const uQ=ig("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),pP=v.forwardRef(({className:e,...t},n)=>u.jsx(fP,{ref:n,className:ge(uQ(),e),...t}));pP.displayName=fP.displayName;function hP(e){const t=v.useRef({value:e,previous:e});return v.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var cQ="VisuallyHidden",gP=v.forwardRef((e,t)=>u.jsx(Me.span,{...e,ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}));gP.displayName=cQ;var dQ=[" ","Enter","ArrowUp","ArrowDown"],fQ=[" ","Enter"],ef="Select",[$g,Bg,pQ]=Fx(ef),[_u,Xse]=Vr(ef,[pQ,hg]),zg=hg(),[hQ,Na]=_u(ef),[gQ,mQ]=_u(ef),mP=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:s,onOpenChange:o,value:a,defaultValue:i,onValueChange:c,dir:l,name:d,autoComplete:p,disabled:f,required:h}=e,g=zg(t),[m,x]=v.useState(null),[b,y]=v.useState(null),[w,S]=v.useState(!1),E=Gd(l),[C=!1,k]=pa({prop:r,defaultProp:s,onChange:o}),[T,O]=pa({prop:a,defaultProp:i,onChange:c}),M=v.useRef(null),U=m?!!m.closest("form"):!0,[I,J]=v.useState(new Set),V=Array.from(I).map(G=>G.props.value).join(";");return u.jsx($j,{...g,children:u.jsxs(hQ,{required:h,scope:t,trigger:m,onTriggerChange:x,valueNode:b,onValueNodeChange:y,valueNodeHasChildren:w,onValueNodeHasChildrenChange:S,contentId:os(),value:T,onValueChange:O,open:C,onOpenChange:k,dir:E,triggerPointerDownPosRef:M,disabled:f,children:[u.jsx($g.Provider,{scope:t,children:u.jsx(gQ,{scope:e.__scopeSelect,onNativeOptionAdd:v.useCallback(G=>{J(ee=>new Set(ee).add(G))},[]),onNativeOptionRemove:v.useCallback(G=>{J(ee=>{const q=new Set(ee);return q.delete(G),q})},[]),children:n})}),U?u.jsxs(zP,{"aria-hidden":!0,required:h,tabIndex:-1,name:d,autoComplete:p,value:T,onChange:G=>O(G.target.value),disabled:f,children:[T===void 0?u.jsx("option",{value:""}):null,Array.from(I)]},V):null]})})};mP.displayName=ef;var vP="SelectTrigger",yP=v.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...s}=e,o=zg(n),a=Na(vP,n),i=a.disabled||r,c=it(t,a.onTriggerChange),l=Bg(n),[d,p,f]=UP(g=>{const m=l().filter(y=>!y.disabled),x=m.find(y=>y.value===a.value),b=VP(m,g,x);b!==void 0&&a.onValueChange(b.value)}),h=()=>{i||(a.onOpenChange(!0),f())};return u.jsx(Bj,{asChild:!0,...o,children:u.jsx(Me.button,{type:"button",role:"combobox","aria-controls":a.contentId,"aria-expanded":a.open,"aria-required":a.required,"aria-autocomplete":"none",dir:a.dir,"data-state":a.open?"open":"closed",disabled:i,"data-disabled":i?"":void 0,"data-placeholder":BP(a.value)?"":void 0,...s,ref:c,onClick:Se(s.onClick,g=>{g.currentTarget.focus()}),onPointerDown:Se(s.onPointerDown,g=>{const m=g.target;m.hasPointerCapture(g.pointerId)&&m.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&(h(),a.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)},g.preventDefault())}),onKeyDown:Se(s.onKeyDown,g=>{const m=d.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&p(g.key),!(m&&g.key===" ")&&dQ.includes(g.key)&&(h(),g.preventDefault())})})})});yP.displayName=vP;var bP="SelectValue",xP=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,children:o,placeholder:a="",...i}=e,c=Na(bP,n),{onValueNodeHasChildrenChange:l}=c,d=o!==void 0,p=it(t,c.onValueNodeChange);return fn(()=>{l(d)},[l,d]),u.jsx(Me.span,{...i,ref:p,style:{pointerEvents:"none"},children:BP(c.value)?u.jsx(u.Fragment,{children:a}):o})});xP.displayName=bP;var vQ="SelectIcon",wP=v.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...s}=e;return u.jsx(Me.span,{"aria-hidden":!0,...s,ref:t,children:r||"▼"})});wP.displayName=vQ;var yQ="SelectPortal",SP=e=>u.jsx(gg,{asChild:!0,...e});SP.displayName=yQ;var ji="SelectContent",CP=v.forwardRef((e,t)=>{const n=Na(ji,e.__scopeSelect),[r,s]=v.useState();if(fn(()=>{s(new DocumentFragment)},[]),!n.open){const o=r;return o?ka.createPortal(u.jsx(EP,{scope:e.__scopeSelect,children:u.jsx($g.Slot,{scope:e.__scopeSelect,children:u.jsx("div",{children:e.children})})}),o):null}return u.jsx(TP,{...e,ref:t})});CP.displayName=ji;var Ys=10,[EP,Pa]=_u(ji),bQ="SelectContentImpl",TP=v.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:s,onEscapeKeyDown:o,onPointerDownOutside:a,side:i,sideOffset:c,align:l,alignOffset:d,arrowPadding:p,collisionBoundary:f,collisionPadding:h,sticky:g,hideWhenDetached:m,avoidCollisions:x,...b}=e,y=Na(ji,n),[w,S]=v.useState(null),[E,C]=v.useState(null),k=it(t,W=>S(W)),[T,O]=v.useState(null),[M,U]=v.useState(null),I=Bg(n),[J,V]=v.useState(!1),G=v.useRef(!1);v.useEffect(()=>{if(w)return Wx(w)},[w]),Lx();const ee=v.useCallback(W=>{const[Ce,...Re]=I().map(me=>me.ref.current),[Le]=Re.slice(-1),Oe=document.activeElement;for(const me of W)if(me===Oe||(me==null||me.scrollIntoView({block:"nearest"}),me===Ce&&E&&(E.scrollTop=0),me===Le&&E&&(E.scrollTop=E.scrollHeight),me==null||me.focus(),document.activeElement!==Oe))return},[I,E]),q=v.useCallback(()=>ee([T,w]),[ee,T,w]);v.useEffect(()=>{J&&q()},[J,q]);const{onOpenChange:F,triggerPointerDownPosRef:A}=y;v.useEffect(()=>{if(w){let W={x:0,y:0};const Ce=Le=>{var Oe,me;W={x:Math.abs(Math.round(Le.pageX)-(((Oe=A.current)==null?void 0:Oe.x)??0)),y:Math.abs(Math.round(Le.pageY)-(((me=A.current)==null?void 0:me.y)??0))}},Re=Le=>{W.x<=10&&W.y<=10?Le.preventDefault():w.contains(Le.target)||F(!1),document.removeEventListener("pointermove",Ce),A.current=null};return A.current!==null&&(document.addEventListener("pointermove",Ce),document.addEventListener("pointerup",Re,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Ce),document.removeEventListener("pointerup",Re,{capture:!0})}}},[w,F,A]),v.useEffect(()=>{const W=()=>F(!1);return window.addEventListener("blur",W),window.addEventListener("resize",W),()=>{window.removeEventListener("blur",W),window.removeEventListener("resize",W)}},[F]);const[Y,de]=UP(W=>{const Ce=I().filter(Oe=>!Oe.disabled),Re=Ce.find(Oe=>Oe.ref.current===document.activeElement),Le=VP(Ce,W,Re);Le&&setTimeout(()=>Le.ref.current.focus())}),z=v.useCallback((W,Ce,Re)=>{const Le=!G.current&&!Re;(y.value!==void 0&&y.value===Ce||Le)&&(O(W),Le&&(G.current=!0))},[y.value]),se=v.useCallback(()=>w==null?void 0:w.focus(),[w]),ne=v.useCallback((W,Ce,Re)=>{const Le=!G.current&&!Re;(y.value!==void 0&&y.value===Ce||Le)&&U(W)},[y.value]),ie=r==="popper"?hb:kP,oe=ie===hb?{side:i,sideOffset:c,align:l,alignOffset:d,arrowPadding:p,collisionBoundary:f,collisionPadding:h,sticky:g,hideWhenDetached:m,avoidCollisions:x}:{};return u.jsx(EP,{scope:n,content:w,viewport:E,onViewportChange:C,itemRefCallback:z,selectedItem:T,onItemLeave:se,itemTextRefCallback:ne,focusSelectedItem:q,selectedItemText:M,position:r,isPositioned:J,searchRef:Y,children:u.jsx(bg,{as:mo,allowPinchZoom:!0,children:u.jsx(dg,{asChild:!0,trapped:y.open,onMountAutoFocus:W=>{W.preventDefault()},onUnmountAutoFocus:Se(s,W=>{var Ce;(Ce=y.trigger)==null||Ce.focus({preventScroll:!0}),W.preventDefault()}),children:u.jsx(cg,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:a,onFocusOutside:W=>W.preventDefault(),onDismiss:()=>y.onOpenChange(!1),children:u.jsx(ie,{role:"listbox",id:y.contentId,"data-state":y.open?"open":"closed",dir:y.dir,onContextMenu:W=>W.preventDefault(),...b,...oe,onPlaced:()=>V(!0),ref:k,style:{display:"flex",flexDirection:"column",outline:"none",...b.style},onKeyDown:Se(b.onKeyDown,W=>{const Ce=W.ctrlKey||W.altKey||W.metaKey;if(W.key==="Tab"&&W.preventDefault(),!Ce&&W.key.length===1&&de(W.key),["ArrowUp","ArrowDown","Home","End"].includes(W.key)){let Le=I().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(W.key)&&(Le=Le.slice().reverse()),["ArrowUp","ArrowDown"].includes(W.key)){const Oe=W.target,me=Le.indexOf(Oe);Le=Le.slice(me+1)}setTimeout(()=>ee(Le)),W.preventDefault()}})})})})})})});TP.displayName=bQ;var xQ="SelectItemAlignedPosition",kP=v.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...s}=e,o=Na(ji,n),a=Pa(ji,n),[i,c]=v.useState(null),[l,d]=v.useState(null),p=it(t,k=>d(k)),f=Bg(n),h=v.useRef(!1),g=v.useRef(!0),{viewport:m,selectedItem:x,selectedItemText:b,focusSelectedItem:y}=a,w=v.useCallback(()=>{if(o.trigger&&o.valueNode&&i&&l&&m&&x&&b){const k=o.trigger.getBoundingClientRect(),T=l.getBoundingClientRect(),O=o.valueNode.getBoundingClientRect(),M=b.getBoundingClientRect();if(o.dir!=="rtl"){const Oe=M.left-T.left,me=O.left-Oe,rt=k.left-me,It=k.width+rt,Zt=Math.max(It,T.width),Wt=window.innerWidth-Ys,an=Zy(me,[Ys,Wt-Zt]);i.style.minWidth=It+"px",i.style.left=an+"px"}else{const Oe=T.right-M.right,me=window.innerWidth-O.right-Oe,rt=window.innerWidth-k.right-me,It=k.width+rt,Zt=Math.max(It,T.width),Wt=window.innerWidth-Ys,an=Zy(me,[Ys,Wt-Zt]);i.style.minWidth=It+"px",i.style.right=an+"px"}const U=f(),I=window.innerHeight-Ys*2,J=m.scrollHeight,V=window.getComputedStyle(l),G=parseInt(V.borderTopWidth,10),ee=parseInt(V.paddingTop,10),q=parseInt(V.borderBottomWidth,10),F=parseInt(V.paddingBottom,10),A=G+ee+J+F+q,Y=Math.min(x.offsetHeight*5,A),de=window.getComputedStyle(m),z=parseInt(de.paddingTop,10),se=parseInt(de.paddingBottom,10),ne=k.top+k.height/2-Ys,ie=I-ne,oe=x.offsetHeight/2,W=x.offsetTop+oe,Ce=G+ee+W,Re=A-Ce;if(Ce<=ne){const Oe=x===U[U.length-1].ref.current;i.style.bottom="0px";const me=l.clientHeight-m.offsetTop-m.offsetHeight,rt=Math.max(ie,oe+(Oe?se:0)+me+q),It=Ce+rt;i.style.height=It+"px"}else{const Oe=x===U[0].ref.current;i.style.top="0px";const rt=Math.max(ne,G+m.offsetTop+(Oe?z:0)+oe)+Re;i.style.height=rt+"px",m.scrollTop=Ce-ne+m.offsetTop}i.style.margin=`${Ys}px 0`,i.style.minHeight=Y+"px",i.style.maxHeight=I+"px",r==null||r(),requestAnimationFrame(()=>h.current=!0)}},[f,o.trigger,o.valueNode,i,l,m,x,b,o.dir,r]);fn(()=>w(),[w]);const[S,E]=v.useState();fn(()=>{l&&E(window.getComputedStyle(l).zIndex)},[l]);const C=v.useCallback(k=>{k&&g.current===!0&&(w(),y==null||y(),g.current=!1)},[w,y]);return u.jsx(SQ,{scope:n,contentWrapper:i,shouldExpandOnScrollRef:h,onScrollButtonChange:C,children:u.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:S},children:u.jsx(Me.div,{...s,ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...s.style}})})})});kP.displayName=xQ;var wQ="SelectPopperPosition",hb=v.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:s=Ys,...o}=e,a=zg(n);return u.jsx(zj,{...a,...o,ref:t,align:r,collisionPadding:s,style:{boxSizing:"border-box",...o.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});hb.displayName=wQ;var[SQ,Ow]=_u(ji,{}),gb="SelectViewport",_P=v.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...s}=e,o=Pa(gb,n),a=Ow(gb,n),i=it(t,o.onViewportChange),c=v.useRef(0);return u.jsxs(u.Fragment,{children:[u.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),u.jsx($g.Slot,{scope:n,children:u.jsx(Me.div,{"data-radix-select-viewport":"",role:"presentation",...s,ref:i,style:{position:"relative",flex:1,overflow:"auto",...s.style},onScroll:Se(s.onScroll,l=>{const d=l.currentTarget,{contentWrapper:p,shouldExpandOnScrollRef:f}=a;if(f!=null&&f.current&&p){const h=Math.abs(c.current-d.scrollTop);if(h>0){const g=window.innerHeight-Ys*2,m=parseFloat(p.style.minHeight),x=parseFloat(p.style.height),b=Math.max(m,x);if(b0?S:0,p.style.justifyContent="flex-end")}}}c.current=d.scrollTop})})})]})});_P.displayName=gb;var jP="SelectGroup",[CQ,EQ]=_u(jP),TQ=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=os();return u.jsx(CQ,{scope:n,id:s,children:u.jsx(Me.div,{role:"group","aria-labelledby":s,...r,ref:t})})});TQ.displayName=jP;var RP="SelectLabel",OP=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=EQ(RP,n);return u.jsx(Me.div,{id:s.id,...r,ref:t})});OP.displayName=RP;var Th="SelectItem",[kQ,NP]=_u(Th),PP=v.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:s=!1,textValue:o,...a}=e,i=Na(Th,n),c=Pa(Th,n),l=i.value===r,[d,p]=v.useState(o??""),[f,h]=v.useState(!1),g=it(t,b=>{var y;return(y=c.itemRefCallback)==null?void 0:y.call(c,b,r,s)}),m=os(),x=()=>{s||(i.onValueChange(r),i.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return u.jsx(kQ,{scope:n,value:r,disabled:s,textId:m,isSelected:l,onItemTextChange:v.useCallback(b=>{p(y=>y||((b==null?void 0:b.textContent)??"").trim())},[]),children:u.jsx($g.ItemSlot,{scope:n,value:r,disabled:s,textValue:d,children:u.jsx(Me.div,{role:"option","aria-labelledby":m,"data-highlighted":f?"":void 0,"aria-selected":l&&f,"data-state":l?"checked":"unchecked","aria-disabled":s||void 0,"data-disabled":s?"":void 0,tabIndex:s?void 0:-1,...a,ref:g,onFocus:Se(a.onFocus,()=>h(!0)),onBlur:Se(a.onBlur,()=>h(!1)),onPointerUp:Se(a.onPointerUp,x),onPointerMove:Se(a.onPointerMove,b=>{var y;s?(y=c.onItemLeave)==null||y.call(c):b.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Se(a.onPointerLeave,b=>{var y;b.currentTarget===document.activeElement&&((y=c.onItemLeave)==null||y.call(c))}),onKeyDown:Se(a.onKeyDown,b=>{var w;((w=c.searchRef)==null?void 0:w.current)!==""&&b.key===" "||(fQ.includes(b.key)&&x(),b.key===" "&&b.preventDefault())})})})})});PP.displayName=Th;var hc="SelectItemText",MP=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,...o}=e,a=Na(hc,n),i=Pa(hc,n),c=NP(hc,n),l=mQ(hc,n),[d,p]=v.useState(null),f=it(t,b=>p(b),c.onItemTextChange,b=>{var y;return(y=i.itemTextRefCallback)==null?void 0:y.call(i,b,c.value,c.disabled)}),h=d==null?void 0:d.textContent,g=v.useMemo(()=>u.jsx("option",{value:c.value,disabled:c.disabled,children:h},c.value),[c.disabled,c.value,h]),{onNativeOptionAdd:m,onNativeOptionRemove:x}=l;return fn(()=>(m(g),()=>x(g)),[m,x,g]),u.jsxs(u.Fragment,{children:[u.jsx(Me.span,{id:c.textId,...o,ref:f}),c.isSelected&&a.valueNode&&!a.valueNodeHasChildren?ka.createPortal(o.children,a.valueNode):null]})});MP.displayName=hc;var IP="SelectItemIndicator",DP=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return NP(IP,n).isSelected?u.jsx(Me.span,{"aria-hidden":!0,...r,ref:t}):null});DP.displayName=IP;var mb="SelectScrollUpButton",AP=v.forwardRef((e,t)=>{const n=Pa(mb,e.__scopeSelect),r=Ow(mb,e.__scopeSelect),[s,o]=v.useState(!1),a=it(t,r.onScrollButtonChange);return fn(()=>{if(n.viewport&&n.isPositioned){let i=function(){const l=c.scrollTop>0;o(l)};const c=n.viewport;return i(),c.addEventListener("scroll",i),()=>c.removeEventListener("scroll",i)}},[n.viewport,n.isPositioned]),s?u.jsx(LP,{...e,ref:a,onAutoScroll:()=>{const{viewport:i,selectedItem:c}=n;i&&c&&(i.scrollTop=i.scrollTop-c.offsetHeight)}}):null});AP.displayName=mb;var vb="SelectScrollDownButton",FP=v.forwardRef((e,t)=>{const n=Pa(vb,e.__scopeSelect),r=Ow(vb,e.__scopeSelect),[s,o]=v.useState(!1),a=it(t,r.onScrollButtonChange);return fn(()=>{if(n.viewport&&n.isPositioned){let i=function(){const l=c.scrollHeight-c.clientHeight,d=Math.ceil(c.scrollTop)c.removeEventListener("scroll",i)}},[n.viewport,n.isPositioned]),s?u.jsx(LP,{...e,ref:a,onAutoScroll:()=>{const{viewport:i,selectedItem:c}=n;i&&c&&(i.scrollTop=i.scrollTop+c.offsetHeight)}}):null});FP.displayName=vb;var LP=v.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...s}=e,o=Pa("SelectScrollButton",n),a=v.useRef(null),i=Bg(n),c=v.useCallback(()=>{a.current!==null&&(window.clearInterval(a.current),a.current=null)},[]);return v.useEffect(()=>()=>c(),[c]),fn(()=>{var d;const l=i().find(p=>p.ref.current===document.activeElement);(d=l==null?void 0:l.ref.current)==null||d.scrollIntoView({block:"nearest"})},[i]),u.jsx(Me.div,{"aria-hidden":!0,...s,ref:t,style:{flexShrink:0,...s.style},onPointerDown:Se(s.onPointerDown,()=>{a.current===null&&(a.current=window.setInterval(r,50))}),onPointerMove:Se(s.onPointerMove,()=>{var l;(l=o.onItemLeave)==null||l.call(o),a.current===null&&(a.current=window.setInterval(r,50))}),onPointerLeave:Se(s.onPointerLeave,()=>{c()})})}),_Q="SelectSeparator",$P=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u.jsx(Me.div,{"aria-hidden":!0,...r,ref:t})});$P.displayName=_Q;var yb="SelectArrow",jQ=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=zg(n),o=Na(yb,n),a=Pa(yb,n);return o.open&&a.position==="popper"?u.jsx(Uj,{...s,...r,ref:t}):null});jQ.displayName=yb;function BP(e){return e===""||e===void 0}var zP=v.forwardRef((e,t)=>{const{value:n,...r}=e,s=v.useRef(null),o=it(t,s),a=hP(n);return v.useEffect(()=>{const i=s.current,c=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value").set;if(a!==n&&d){const p=new Event("change",{bubbles:!0});d.call(i,n),i.dispatchEvent(p)}},[a,n]),u.jsx(gP,{asChild:!0,children:u.jsx("select",{...r,ref:o,defaultValue:n})})});zP.displayName="BubbleSelect";function UP(e){const t=nn(e),n=v.useRef(""),r=v.useRef(0),s=v.useCallback(a=>{const i=n.current+a;t(i),function c(l){n.current=l,window.clearTimeout(r.current),l!==""&&(r.current=window.setTimeout(()=>c(""),1e3))}(i)},[t]),o=v.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return v.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,s,o]}function VP(e,t,n){const s=t.length>1&&Array.from(t).every(l=>l===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let a=RQ(e,Math.max(o,0));s.length===1&&(a=a.filter(l=>l!==n));const c=a.find(l=>l.textValue.toLowerCase().startsWith(s.toLowerCase()));return c!==n?c:void 0}function RQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var OQ=mP,HP=yP,NQ=xP,PQ=wP,MQ=SP,KP=CP,IQ=_P,qP=OP,WP=PP,DQ=MP,AQ=DP,GP=AP,JP=FP,QP=$P;const FQ=OQ,LQ=NQ,ZP=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(HP,{ref:r,className:ge("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,u.jsx(PQ,{asChild:!0,children:u.jsx(lg,{className:"h-4 w-4 opacity-50"})})]}));ZP.displayName=HP.displayName;const YP=v.forwardRef(({className:e,...t},n)=>u.jsx(GP,{ref:n,className:ge("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(O3,{className:"h-4 w-4"})}));YP.displayName=GP.displayName;const XP=v.forwardRef(({className:e,...t},n)=>u.jsx(JP,{ref:n,className:ge("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(lg,{className:"h-4 w-4"})}));XP.displayName=JP.displayName;const eM=v.forwardRef(({className:e,children:t,position:n="popper",...r},s)=>u.jsx(MQ,{children:u.jsxs(KP,{ref:s,className:ge("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[u.jsx(YP,{}),u.jsx(IQ,{className:ge("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),u.jsx(XP,{})]})}));eM.displayName=KP.displayName;const $Q=v.forwardRef(({className:e,...t},n)=>u.jsx(qP,{ref:n,className:ge("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));$Q.displayName=qP.displayName;const tM=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(WP,{ref:r,className:ge("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(AQ,{children:u.jsx(cj,{className:"h-4 w-4"})})}),u.jsx(DQ,{children:t})]}));tM.displayName=WP.displayName;const BQ=v.forwardRef(({className:e,...t},n)=>u.jsx(QP,{ref:n,className:ge("-mx-1 my-1 h-px bg-muted",e),...t}));BQ.displayName=QP.displayName;var Nw="Switch",[zQ,eoe]=Vr(Nw),[UQ,VQ]=zQ(Nw),nM=v.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:s,defaultChecked:o,required:a,disabled:i,value:c="on",onCheckedChange:l,...d}=e,[p,f]=v.useState(null),h=it(t,y=>f(y)),g=v.useRef(!1),m=p?!!p.closest("form"):!0,[x=!1,b]=pa({prop:s,defaultProp:o,onChange:l});return u.jsxs(UQ,{scope:n,checked:x,disabled:i,children:[u.jsx(Me.button,{type:"button",role:"switch","aria-checked":x,"aria-required":a,"data-state":oM(x),"data-disabled":i?"":void 0,disabled:i,value:c,...d,ref:h,onClick:Se(e.onClick,y=>{b(w=>!w),m&&(g.current=y.isPropagationStopped(),g.current||y.stopPropagation())})}),m&&u.jsx(HQ,{control:p,bubbles:!g.current,name:r,value:c,checked:x,required:a,disabled:i,style:{transform:"translateX(-100%)"}})]})});nM.displayName=Nw;var rM="SwitchThumb",sM=v.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,s=VQ(rM,n);return u.jsx(Me.span,{"data-state":oM(s.checked),"data-disabled":s.disabled?"":void 0,...r,ref:t})});sM.displayName=rM;var HQ=e=>{const{control:t,checked:n,bubbles:r=!0,...s}=e,o=v.useRef(null),a=hP(n),i=Rj(t);return v.useEffect(()=>{const c=o.current,l=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(l,"checked").set;if(a!==n&&p){const f=new Event("click",{bubbles:r});p.call(c,n),c.dispatchEvent(f)}},[a,n,r]),u.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...s,tabIndex:-1,ref:o,style:{...e.style,...i,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})};function oM(e){return e?"checked":"unchecked"}var aM=nM,KQ=sM;const ju=v.forwardRef(({className:e,...t},n)=>u.jsx(aM,{className:ge("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-slate-400",e),...t,ref:n,children:u.jsx(KQ,{className:ge("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));ju.displayName=aM.displayName;const Ma=Tr,iM=v.createContext({}),Ia=({...e})=>u.jsx(iM.Provider,{value:{name:e.name},children:u.jsx($V,{...e})}),Ug=()=>{const e=v.useContext(iM),t=v.useContext(lM),{getFieldState:n,formState:r}=Rg(),s=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:o}=t;return{id:o,name:e.name,formItemId:`${o}-form-item`,formDescriptionId:`${o}-form-item-description`,formMessageId:`${o}-form-item-message`,...s}},lM=v.createContext({}),_o=v.forwardRef(({className:e,...t},n)=>{const r=v.useId();return u.jsx(lM.Provider,{value:{id:r},children:u.jsx("div",{ref:n,className:ge("space-y-2",e),...t})})});_o.displayName="FormItem";const xr=v.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:s}=Ug();return u.jsx(pP,{ref:n,className:ge(r&&"text-rose-600",e),htmlFor:s,...t})});xr.displayName="FormLabel";const Vs=v.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:s,formMessageId:o}=Ug();return u.jsx(mo,{ref:t,id:r,"aria-describedby":n?`${s} ${o}`:`${s}`,"aria-invalid":!!n,...e})});Vs.displayName="FormControl";const Vg=v.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=Ug();return u.jsx("p",{ref:n,id:r,className:ge("text-sm text-muted-foreground",e),...t})});Vg.displayName="FormDescription";const tf=v.forwardRef(({className:e,children:t,...n},r)=>{const{error:s,formMessageId:o}=Ug(),a=s?String(s==null?void 0:s.message):t;return a?u.jsx("p",{ref:r,id:o,className:ge("text-sm font-medium text-rose-600",e),...n,children:a}):null});tf.displayName="FormMessage";const Z=({name:e,label:t,children:n,required:r,readOnly:s,className:o,...a})=>u.jsx(Ia,{...a,name:e,render:({field:i})=>u.jsxs(_o,{className:o,children:[t&&u.jsxs(xr,{children:[t,r&&u.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),u.jsx(Vs,{children:v.isValidElement(n)&&v.cloneElement(n,{...i,value:i.value??"",required:r,readOnly:s,checked:i.value,onCheckedChange:i.onChange})}),u.jsx(tf,{})]})}),Pe=({name:e,label:t,required:n,className:r,helper:s,reverse:o,...a})=>u.jsx(Ia,{...a,name:e,render:({field:i})=>u.jsxs(_o,{className:ge("flex items-center gap-3",o&&"flex-row-reverse justify-end",r),children:[u.jsx("div",{className:"flex flex-col gap-2",children:t&&u.jsxs(xr,{children:[u.jsxs("p",{className:"break-all",children:[t,n&&u.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),s&&u.jsx(Vg,{className:"mt-2",children:s})]})}),u.jsx(Vs,{children:u.jsx(ju,{checked:i.value,onCheckedChange:i.onChange,required:n})}),u.jsx(tf,{})]})}),Qt=({name:e,label:t,helper:n,required:r,options:s,placeholder:o,...a})=>u.jsx(Ia,{...a,name:e,render:({field:i})=>u.jsxs(_o,{children:[t&&u.jsxs(xr,{children:[t,r&&u.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),u.jsx(Vs,{children:u.jsxs(FQ,{onValueChange:i.onChange,defaultValue:i.value,children:[u.jsx(Vs,{children:u.jsx(ZP,{children:u.jsx(LQ,{placeholder:o})})}),u.jsx(eM,{children:s.map(c=>u.jsx(tM,{value:c.value,children:c.label},c.value))})]})}),n&&u.jsx(Vg,{children:n}),u.jsx(tf,{})]})}),Ru=({name:e,label:t,helper:n,required:r,placeholder:s,...o})=>u.jsx(Ia,{...o,name:e,render:({field:a})=>{let i=[];return Array.isArray(a.value)&&(i=a.value),u.jsxs(_o,{children:[t&&u.jsxs(xr,{children:[t,r&&u.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),u.jsx(Vs,{children:u.jsx(iQ,{tags:i.map(c=>({id:c,text:c,className:""})),handleDelete:c=>a.onChange(i.filter((l,d)=>d!==c)),handleAddition:c=>a.onChange([...i,c.id]),inputFieldPosition:"bottom",placeholder:s,autoFocus:!1,allowDragDrop:!1,separators:[Rs.ENTER,Rs.TAB,Rs.COMMA],classNames:{tags:"tagsClass",tagInput:"tagInputClass",tagInputField:QO,selected:"my-2 flex flex-wrap gap-2",tag:"flex items-center gap-2 px-2 py-1 bg-primary/30 rounded-md text-xs",remove:"[&>svg]:fill-rose-600 hover:[&>svg]:fill-rose-700",suggestions:"suggestionsClass",activeSuggestion:"activeSuggestionClass",editTagInput:"editTagInputClass",editTagInputField:"editTagInputFieldClass",clearAll:"clearAllClass"}})}),n&&u.jsx(Vg,{children:n}),u.jsx(tf,{})]})}}),pv=_.string().optional().transform(e=>e===""?void 0:e),qQ=_.object({name:_.string(),token:pv,number:pv,businessId:pv,integration:_.enum(["WHATSAPP-BUSINESS","WHATSAPP-BAILEYS","EVOLUTION"])});function WQ({resetTable:e}){const{t}=ze(),{createInstance:n}=_g(),[r,s]=v.useState(!1),o=[{value:"WHATSAPP-BAILEYS",label:t("instance.form.integration.baileys")},{value:"WHATSAPP-BUSINESS",label:t("instance.form.integration.whatsapp")},{value:"EVOLUTION",label:t("instance.form.integration.evolution")}],a=sn({resolver:on(qQ),defaultValues:{name:"",integration:"WHATSAPP-BAILEYS",token:M1().replace("-","").toUpperCase(),number:"",businessId:""}}),i=a.watch("integration"),c=async d=>{var p,f,h;try{const g={instanceName:d.name,integration:d.integration,token:d.token===""?null:d.token,number:d.number===""?null:d.number,businessId:d.businessId===""?null:d.businessId};await n(g),X.success(t("toast.instance.created")),s(!1),l(),e()}catch(g){console.error("Error:",g),X.error(`Error : ${(h=(f=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:f.response)==null?void 0:h.message}`)}},l=()=>{a.reset({name:"",integration:"WHATSAPP-BAILEYS",token:M1().replace("-","").toLocaleUpperCase(),number:"",businessId:""})};return u.jsxs(Tt,{open:r,onOpenChange:s,children:[u.jsx(Mt,{asChild:!0,children:u.jsxs(K,{variant:"default",size:"sm",children:[t("instance.button.create")," ",u.jsx(Mi,{size:"18"})]})}),u.jsxs(xt,{className:"sm:max-w-[650px]",onCloseAutoFocus:l,children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("instance.modal.title")})}),u.jsx(Tr,{...a,children:u.jsxs("form",{onSubmit:a.handleSubmit(c),className:"grid gap-4 py-4",children:[u.jsx(Z,{required:!0,name:"name",label:t("instance.form.name"),children:u.jsx(Q,{})}),u.jsx(Qt,{name:"integration",label:t("instance.form.integration.label"),options:o}),u.jsx(Z,{required:!0,name:"token",label:t("instance.form.token"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"number",label:t("instance.form.number"),children:u.jsx(Q,{type:"tel"})}),i==="WHATSAPP-BUSINESS"&&u.jsx(Z,{required:!0,name:"businessId",label:t("instance.form.businessId"),children:u.jsx(Q,{})}),u.jsx(rn,{children:u.jsx(K,{type:"submit",children:t("instance.button.save")})})]})})]})]})}function GQ(){const{t:e}=ze(),[t,n]=v.useState(null),{deleteInstance:r,logout:s}=_g(),{data:o,refetch:a}=_V(),[i,c]=v.useState([]),[l,d]=v.useState("all"),[p,f]=v.useState(""),h=async()=>{await a()},g=async b=>{var y,w,S;n(null),c([...i,b]);try{try{await s(b)}catch(E){console.error("Error logout:",E)}await r(b),await new Promise(E=>setTimeout(E,1e3)),h()}catch(E){console.error("Error instance delete:",E),X.error(`Error : ${(S=(w=(y=E==null?void 0:E.response)==null?void 0:y.data)==null?void 0:w.response)==null?void 0:S.message}`)}finally{c(i.filter(E=>E!==b))}},m=v.useMemo(()=>{let b=o?[...o]:[];return l!=="all"&&(b=b.filter(y=>y.connectionStatus===l)),p!==""&&(b=b.filter(y=>y.name.toLowerCase().includes(p.toLowerCase()))),b},[o,p,l]),x=[{value:"all",label:e("status.all")},{value:"close",label:e("status.closed")},{value:"connecting",label:e("status.connecting")},{value:"open",label:e("status.open")}];return u.jsxs("div",{className:"my-4 px-4",children:[u.jsxs("div",{className:"flex w-full items-center justify-between",children:[u.jsx("h2",{className:"text-lg",children:e("dashboard.title")}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(K,{variant:"outline",size:"icon",children:u.jsx(fj,{onClick:h,size:"20"})}),u.jsx(WQ,{resetTable:h})]})]}),u.jsxs("div",{className:"my-4 flex items-center justify-between gap-3 px-4",children:[u.jsx("div",{className:"flex-1",children:u.jsx(Q,{placeholder:e("dashboard.search"),value:p,onChange:b=>f(b.target.value)})}),u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(K,{variant:"secondary",children:[e("dashboard.status")," ",u.jsx(N3,{size:"15"})]})}),u.jsx(ps,{children:x.map(b=>u.jsx(GR,{checked:l===b.value,onCheckedChange:y=>{y&&d(b.value)},children:b.label},b.value))})]})]}),u.jsx("main",{className:"grid gap-6 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:m.length>0&&Array.isArray(o)&&o.map(b=>{var y,w;return u.jsxs(Ja,{children:[u.jsx(Qa,{children:u.jsxs(nd,{to:`/manager/instance/${b.id}/dashboard`,className:"flex w-full flex-row items-center justify-between gap-4",children:[u.jsx("h3",{className:"text-wrap font-semibold",children:b.name}),u.jsx(K,{variant:"ghost",size:"icon",children:u.jsx(Pi,{className:"card-icon",size:"20"})})]})}),u.jsxs(Za,{className:"flex-1 space-y-6",children:[u.jsx(GO,{token:b.token}),u.jsxs("div",{className:"flex w-full flex-wrap",children:[u.jsx("div",{className:"flex flex-1 gap-2",children:b.profileName&&u.jsxs(u.Fragment,{children:[u.jsx(Sg,{children:u.jsx(Cg,{src:b.profilePicUrl,alt:""})}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("strong",{children:b.profileName}),u.jsx("p",{className:"text-sm text-muted-foreground",children:b.ownerJid&&b.ownerJid.split("@")[0]})]})]})}),u.jsxs("div",{className:"flex items-center justify-end gap-4 text-sm",children:[u.jsxs("div",{className:"flex flex-col items-center justify-center gap-1",children:[u.jsx(dj,{className:"text-muted-foreground",size:"20"}),u.jsx("span",{children:new Intl.NumberFormat("pt-BR").format(((y=b==null?void 0:b._count)==null?void 0:y.Contact)||0)})]}),u.jsxs("div",{className:"flex flex-col items-center justify-center gap-1",children:[u.jsx(ug,{className:"text-muted-foreground",size:"20"}),u.jsx("span",{children:new Intl.NumberFormat("pt-BR").format(((w=b==null?void 0:b._count)==null?void 0:w.Message)||0)})]})]})]})]}),u.jsxs(kg,{className:"justify-between",children:[u.jsx(WO,{status:b.connectionStatus}),u.jsx(K,{variant:"destructive",size:"sm",onClick:()=>n(b.name),disabled:i.includes(b.name),children:i.includes(b.name)?u.jsx("span",{children:e("button.deleting")}):u.jsx("span",{children:e("button.delete")})})]})]},b.id)})}),!!t&&u.jsx(Tt,{onOpenChange:()=>n(null),open:!0,children:u.jsxs(xt,{children:[u.jsx(TO,{}),u.jsx(wt,{children:e("modal.delete.title")}),u.jsx("p",{children:e("modal.delete.message",{instanceName:t})}),u.jsx(rn,{children:u.jsxs("div",{className:"flex items-center gap-4",children:[u.jsx(K,{onClick:()=>n(null),size:"sm",variant:"outline",children:e("button.cancel")}),u.jsx(K,{onClick:()=>g(t),variant:"destructive",children:e("button.delete")})]})})]})})]})}const{createElement:au,createContext:JQ,createRef:toe,forwardRef:uM,useCallback:ir,useContext:cM,useEffect:pi,useImperativeHandle:dM,useLayoutEffect:QQ,useMemo:ZQ,useRef:Yn,useState:Pc}=Mh,zC=Mh.useId,YQ=QQ,Hg=JQ(null);Hg.displayName="PanelGroupContext";const hi=YQ,XQ=typeof zC=="function"?zC:()=>null;let eZ=0;function Pw(e=null){const t=XQ(),n=Yn(e||t||null);return n.current===null&&(n.current=""+eZ++),e??n.current}function fM({children:e,className:t="",collapsedSize:n,collapsible:r,defaultSize:s,forwardedRef:o,id:a,maxSize:i,minSize:c,onCollapse:l,onExpand:d,onResize:p,order:f,style:h,tagName:g="div",...m}){const x=cM(Hg);if(x===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:b,expandPanel:y,getPanelSize:w,getPanelStyle:S,groupId:E,isPanelCollapsed:C,reevaluatePanelConstraints:k,registerPanel:T,resizePanel:O,unregisterPanel:M}=x,U=Pw(a),I=Yn({callbacks:{onCollapse:l,onExpand:d,onResize:p},constraints:{collapsedSize:n,collapsible:r,defaultSize:s,maxSize:i,minSize:c},id:U,idIsFromProps:a!==void 0,order:f});Yn({didLogMissingDefaultSizeWarning:!1}),hi(()=>{const{callbacks:V,constraints:G}=I.current,ee={...G};I.current.id=U,I.current.idIsFromProps=a!==void 0,I.current.order=f,V.onCollapse=l,V.onExpand=d,V.onResize=p,G.collapsedSize=n,G.collapsible=r,G.defaultSize=s,G.maxSize=i,G.minSize=c,(ee.collapsedSize!==G.collapsedSize||ee.collapsible!==G.collapsible||ee.maxSize!==G.maxSize||ee.minSize!==G.minSize)&&k(I.current,ee)}),hi(()=>{const V=I.current;return T(V),()=>{M(V)}},[f,U,T,M]),dM(o,()=>({collapse:()=>{b(I.current)},expand:V=>{y(I.current,V)},getId(){return U},getSize(){return w(I.current)},isCollapsed(){return C(I.current)},isExpanded(){return!C(I.current)},resize:V=>{O(I.current,V)}}),[b,y,w,C,U,O]);const J=S(I.current,s);return au(g,{...m,children:e,className:t,id:a,style:{...J,...h},"data-panel":"","data-panel-collapsible":r||void 0,"data-panel-group-id":E,"data-panel-id":U,"data-panel-size":parseFloat(""+J.flexGrow).toFixed(1)})}const pM=uM((e,t)=>au(fM,{...e,forwardedRef:t}));fM.displayName="Panel";pM.displayName="forwardRef(Panel)";let bb=null,Xa=null;function tZ(e,t){if(t){const n=(t&yM)!==0,r=(t&bM)!==0,s=(t&xM)!==0,o=(t&wM)!==0;if(n)return s?"se-resize":o?"ne-resize":"e-resize";if(r)return s?"sw-resize":o?"nw-resize":"w-resize";if(s)return"s-resize";if(o)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function nZ(){Xa!==null&&(document.head.removeChild(Xa),bb=null,Xa=null)}function hv(e,t){const n=tZ(e,t);bb!==n&&(bb=n,Xa===null&&(Xa=document.createElement("style"),document.head.appendChild(Xa)),Xa.innerHTML=`*{cursor: ${n}!important;}`)}function hM(e){return e.type==="keydown"}function gM(e){return e.type.startsWith("pointer")}function mM(e){return e.type.startsWith("mouse")}function Kg(e){if(gM(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(mM(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function rZ(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function sZ(e,t,n){return e.xt.x&&e.yt.y}function oZ(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:HC(e),b:HC(t)};let r;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),r=e;tt(r,"Stacking order can only be calculated for elements with a common ancestor");const s={a:VC(UC(n.a)),b:VC(UC(n.b))};if(s.a===s.b){const o=r.childNodes,a={a:n.a.at(-1),b:n.b.at(-1)};let i=o.length;for(;i--;){const c=o[i];if(c===a.a)return 1;if(c===a.b)return-1}}return Math.sign(s.a-s.b)}const aZ=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function iZ(e){var t;const n=getComputedStyle((t=vM(e))!==null&&t!==void 0?t:e).display;return n==="flex"||n==="inline-flex"}function lZ(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||iZ(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||aZ.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function UC(e){let t=e.length;for(;t--;){const n=e[t];if(tt(n,"Missing node"),lZ(n))return n}return null}function VC(e){return e&&Number(getComputedStyle(e).zIndex)||0}function HC(e){const t=[];for(;e;)t.push(e),e=vM(e);return t}function vM(e){const{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}const yM=1,bM=2,xM=4,wM=8,uZ=rZ()==="coarse";let is=[],_d=!1,Ho=new Map,qg=new Map;const jd=new Set;function cZ(e,t,n,r,s){var o;const{ownerDocument:a}=t,i={direction:n,element:t,hitAreaMargins:r,setResizeHandlerState:s},c=(o=Ho.get(a))!==null&&o!==void 0?o:0;return Ho.set(a,c+1),jd.add(i),kh(),function(){var d;qg.delete(e),jd.delete(i);const p=(d=Ho.get(a))!==null&&d!==void 0?d:1;if(Ho.set(a,p-1),kh(),p===1&&Ho.delete(a),is.includes(i)){const f=is.indexOf(i);f>=0&&is.splice(f,1),Iw()}}}function KC(e){const{target:t}=e,{x:n,y:r}=Kg(e);_d=!0,Mw({target:t,x:n,y:r}),kh(),is.length>0&&(_h("down",e),e.preventDefault(),e.stopPropagation())}function nc(e){const{x:t,y:n}=Kg(e);if(e.buttons===0&&(_d=!1,_h("up",e)),!_d){const{target:r}=e;Mw({target:r,x:t,y:n})}_h("move",e),Iw(),is.length>0&&e.preventDefault()}function Zi(e){const{target:t}=e,{x:n,y:r}=Kg(e);qg.clear(),_d=!1,is.length>0&&e.preventDefault(),_h("up",e),Mw({target:t,x:n,y:r}),Iw(),kh()}function Mw({target:e,x:t,y:n}){is.splice(0);let r=null;e instanceof HTMLElement&&(r=e),jd.forEach(s=>{const{element:o,hitAreaMargins:a}=s,i=o.getBoundingClientRect(),{bottom:c,left:l,right:d,top:p}=i,f=uZ?a.coarse:a.fine;if(t>=l-f&&t<=d+f&&n>=p-f&&n<=c+f){if(r!==null&&o!==r&&!o.contains(r)&&!r.contains(o)&&oZ(r,o)>0){let g=r,m=!1;for(;g&&!g.contains(o);){if(sZ(g.getBoundingClientRect(),i)){m=!0;break}g=g.parentElement}if(m)return}is.push(s)}})}function gv(e,t){qg.set(e,t)}function Iw(){let e=!1,t=!1;is.forEach(r=>{const{direction:s}=r;s==="horizontal"?e=!0:t=!0});let n=0;qg.forEach(r=>{n|=r}),e&&t?hv("intersection",n):e?hv("horizontal",n):t?hv("vertical",n):nZ()}function kh(){Ho.forEach((e,t)=>{const{body:n}=t;n.removeEventListener("contextmenu",Zi),n.removeEventListener("pointerdown",KC),n.removeEventListener("pointerleave",nc),n.removeEventListener("pointermove",nc)}),window.removeEventListener("pointerup",Zi),window.removeEventListener("pointercancel",Zi),jd.size>0&&(_d?(is.length>0&&Ho.forEach((e,t)=>{const{body:n}=t;e>0&&(n.addEventListener("contextmenu",Zi),n.addEventListener("pointerleave",nc),n.addEventListener("pointermove",nc))}),window.addEventListener("pointerup",Zi),window.addEventListener("pointercancel",Zi)):Ho.forEach((e,t)=>{const{body:n}=t;e>0&&(n.addEventListener("pointerdown",KC,{capture:!0}),n.addEventListener("pointermove",nc))}))}function _h(e,t){jd.forEach(n=>{const{setResizeHandlerState:r}=n,s=is.includes(n);r(e,s,t)})}function tt(e,t){if(!e)throw console.error(t),Error(t)}const Dw=10;function Ri(e,t,n=Dw){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function no(e,t,n=Dw){return Ri(e,t,n)===0}function dr(e,t,n){return Ri(e,t,n)===0}function dZ(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r0&&(e=e<0?0-b:b)}}}{const p=e<0?i:c,f=n[p];tt(f,`No panel constraints found for index ${p}`);const{collapsedSize:h=0,collapsible:g,minSize:m=0}=f;if(g){const x=t[p];if(tt(x!=null,`Previous layout not found for panel index ${p}`),dr(x,m)){const b=x-h;Ri(b,Math.abs(e))>0&&(e=e<0?0-b:b)}}}}{const p=e<0?1:-1;let f=e<0?c:i,h=0;for(;;){const m=t[f];tt(m!=null,`Previous layout not found for panel index ${f}`);const b=yl({panelConstraints:n,panelIndex:f,size:100})-m;if(h+=b,f+=p,f<0||f>=n.length)break}const g=Math.min(Math.abs(e),Math.abs(h));e=e<0?0-g:g}{let f=e<0?i:c;for(;f>=0&&f=0))break;e<0?f--:f++}}if(dZ(s,a))return s;{const p=e<0?c:i,f=t[p];tt(f!=null,`Previous layout not found for panel index ${p}`);const h=f+l,g=yl({panelConstraints:n,panelIndex:p,size:h});if(a[p]=g,!dr(g,h)){let m=h-g,b=e<0?c:i;for(;b>=0&&b0?b--:b++}}}const d=a.reduce((p,f)=>f+p,0);return dr(d,100)?a:s}function fZ({layout:e,panelsArray:t,pivotIndices:n}){let r=0,s=100,o=0,a=0;const i=n[0];tt(i!=null,"No pivot index found"),t.forEach((p,f)=>{const{constraints:h}=p,{maxSize:g=100,minSize:m=0}=h;f===i?(r=m,s=g):(o+=m,a+=g)});const c=Math.min(s,100-o),l=Math.max(r,100-a),d=e[i];return{valueMax:c,valueMin:l,valueNow:d}}function Rd(e,t=document){return Array.from(t.querySelectorAll(`[data-panel-resize-handle-id][data-panel-group-id="${e}"]`))}function SM(e,t,n=document){const s=Rd(e,n).findIndex(o=>o.getAttribute("data-panel-resize-handle-id")===t);return s??null}function CM(e,t,n){const r=SM(e,t,n);return r!=null?[r,r+1]:[-1,-1]}function EM(e,t=document){var n;if(t instanceof HTMLElement&&(t==null||(n=t.dataset)===null||n===void 0?void 0:n.panelGroupId)==e)return t;const r=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return r||null}function Wg(e,t=document){const n=t.querySelector(`[data-panel-resize-handle-id="${e}"]`);return n||null}function pZ(e,t,n,r=document){var s,o,a,i;const c=Wg(t,r),l=Rd(e,r),d=c?l.indexOf(c):-1,p=(s=(o=n[d])===null||o===void 0?void 0:o.id)!==null&&s!==void 0?s:null,f=(a=(i=n[d+1])===null||i===void 0?void 0:i.id)!==null&&a!==void 0?a:null;return[p,f]}function hZ({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:r,panelDataArray:s,panelGroupElement:o,setLayout:a}){Yn({didWarnAboutMissingResizeHandle:!1}),hi(()=>{if(!o)return;const i=Rd(n,o);for(let c=0;c{i.forEach((c,l)=>{c.removeAttribute("aria-controls"),c.removeAttribute("aria-valuemax"),c.removeAttribute("aria-valuemin"),c.removeAttribute("aria-valuenow")})}},[n,r,s,o]),pi(()=>{if(!o)return;const i=t.current;tt(i,"Eager values not found");const{panelDataArray:c}=i,l=EM(n,o);tt(l!=null,`No group found for id "${n}"`);const d=Rd(n,o);tt(d,`No resize handles found for group id "${n}"`);const p=d.map(f=>{const h=f.getAttribute("data-panel-resize-handle-id");tt(h,"Resize handle element has no handle id attribute");const[g,m]=pZ(n,h,c,o);if(g==null||m==null)return()=>{};const x=b=>{if(!b.defaultPrevented)switch(b.key){case"Enter":{b.preventDefault();const y=c.findIndex(w=>w.id===g);if(y>=0){const w=c[y];tt(w,`No panel data found for index ${y}`);const S=r[y],{collapsedSize:E=0,collapsible:C,minSize:k=0}=w.constraints;if(S!=null&&C){const T=gc({delta:dr(S,E)?k-E:E-S,initialLayout:r,panelConstraints:c.map(O=>O.constraints),pivotIndices:CM(n,h,o),prevLayout:r,trigger:"keyboard"});r!==T&&a(T)}}break}}};return f.addEventListener("keydown",x),()=>{f.removeEventListener("keydown",x)}});return()=>{p.forEach(f=>f())}},[o,e,t,n,r,s,a])}function qC(e,t){if(e.length!==t.length)return!1;for(let n=0;no.constraints);let r=0,s=100;for(let o=0;o{const o=e[s];tt(o,`Panel data not found for index ${s}`);const{callbacks:a,constraints:i,id:c}=o,{collapsedSize:l=0,collapsible:d}=i,p=n[c];if(p==null||r!==p){n[c]=r;const{onCollapse:f,onExpand:h,onResize:g}=a;g&&g(r,p),d&&(f||h)&&(h&&(p==null||no(p,l))&&!no(r,l)&&h(),f&&(p==null||!no(p,l))&&no(r,l)&&f())}})}function Vf(e,t){if(e.length!==t.length)return!1;for(let n=0;n{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...s)},t)}}function WC(e){try{if(typeof localStorage<"u")e.getItem=t=>localStorage.getItem(t),e.setItem=(t,n)=>{localStorage.setItem(t,n)};else throw new Error("localStorage not supported in this environment")}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}function kM(e){return`react-resizable-panels:${e}`}function _M(e){return e.map(t=>{const{constraints:n,id:r,idIsFromProps:s,order:o}=t;return s?r:o?`${o}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((t,n)=>t.localeCompare(n)).join(",")}function jM(e,t){try{const n=kM(e),r=t.getItem(n);if(r){const s=JSON.parse(r);if(typeof s=="object"&&s!=null)return s}}catch{}return null}function xZ(e,t,n){var r,s;const o=(r=jM(e,n))!==null&&r!==void 0?r:{},a=_M(t);return(s=o[a])!==null&&s!==void 0?s:null}function wZ(e,t,n,r,s){var o;const a=kM(e),i=_M(t),c=(o=jM(e,s))!==null&&o!==void 0?o:{};c[i]={expandToSizes:Object.fromEntries(n.entries()),layout:r};try{s.setItem(a,JSON.stringify(c))}catch(l){console.error(l)}}function GC({layout:e,panelConstraints:t}){const n=[...e],r=n.reduce((o,a)=>o+a,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(o=>`${o}%`).join(", ")}`);if(!dr(r,100))for(let o=0;o(WC(mc),mc.getItem(e)),setItem:(e,t)=>{WC(mc),mc.setItem(e,t)}},JC={};function RM({autoSaveId:e=null,children:t,className:n="",direction:r,forwardedRef:s,id:o=null,onLayout:a=null,keyboardResizeBy:i=null,storage:c=mc,style:l,tagName:d="div",...p}){const f=Pw(o),h=Yn(null),[g,m]=Pc(null),[x,b]=Pc([]),y=Yn({}),w=Yn(new Map),S=Yn(0),E=Yn({autoSaveId:e,direction:r,dragState:g,id:f,keyboardResizeBy:i,onLayout:a,storage:c}),C=Yn({layout:x,panelDataArray:[],panelDataArrayChanged:!1});Yn({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),dM(s,()=>({getId:()=>E.current.id,getLayout:()=>{const{layout:z}=C.current;return z},setLayout:z=>{const{onLayout:se}=E.current,{layout:ne,panelDataArray:ie}=C.current,oe=GC({layout:z,panelConstraints:ie.map(W=>W.constraints)});qC(ne,oe)||(b(oe),C.current.layout=oe,se&&se(oe),Yi(ie,oe,y.current))}}),[]),hi(()=>{E.current.autoSaveId=e,E.current.direction=r,E.current.dragState=g,E.current.id=f,E.current.onLayout=a,E.current.storage=c}),hZ({committedValuesRef:E,eagerValuesRef:C,groupId:f,layout:x,panelDataArray:C.current.panelDataArray,setLayout:b,panelGroupElement:h.current}),pi(()=>{const{panelDataArray:z}=C.current;if(e){if(x.length===0||x.length!==z.length)return;let se=JC[e];se==null&&(se=bZ(wZ,SZ),JC[e]=se);const ne=[...z],ie=new Map(w.current);se(e,ne,ie,x,c)}},[e,x,c]),pi(()=>{});const k=ir(z=>{const{onLayout:se}=E.current,{layout:ne,panelDataArray:ie}=C.current;if(z.constraints.collapsible){const oe=ie.map(Le=>Le.constraints),{collapsedSize:W=0,panelSize:Ce,pivotIndices:Re}=Fa(ie,z,ne);if(tt(Ce!=null,`Panel size not found for panel "${z.id}"`),!no(Ce,W)){w.current.set(z.id,Ce);const Oe=nl(ie,z)===ie.length-1?Ce-W:W-Ce,me=gc({delta:Oe,initialLayout:ne,panelConstraints:oe,pivotIndices:Re,prevLayout:ne,trigger:"imperative-api"});Vf(ne,me)||(b(me),C.current.layout=me,se&&se(me),Yi(ie,me,y.current))}}},[]),T=ir((z,se)=>{const{onLayout:ne}=E.current,{layout:ie,panelDataArray:oe}=C.current;if(z.constraints.collapsible){const W=oe.map(rt=>rt.constraints),{collapsedSize:Ce=0,panelSize:Re=0,minSize:Le=0,pivotIndices:Oe}=Fa(oe,z,ie),me=se??Le;if(no(Re,Ce)){const rt=w.current.get(z.id),It=rt!=null&&rt>=me?rt:me,Wt=nl(oe,z)===oe.length-1?Re-It:It-Re,an=gc({delta:Wt,initialLayout:ie,panelConstraints:W,pivotIndices:Oe,prevLayout:ie,trigger:"imperative-api"});Vf(ie,an)||(b(an),C.current.layout=an,ne&&ne(an),Yi(oe,an,y.current))}}},[]),O=ir(z=>{const{layout:se,panelDataArray:ne}=C.current,{panelSize:ie}=Fa(ne,z,se);return tt(ie!=null,`Panel size not found for panel "${z.id}"`),ie},[]),M=ir((z,se)=>{const{panelDataArray:ne}=C.current,ie=nl(ne,z);return yZ({defaultSize:se,dragState:g,layout:x,panelData:ne,panelIndex:ie})},[g,x]),U=ir(z=>{const{layout:se,panelDataArray:ne}=C.current,{collapsedSize:ie=0,collapsible:oe,panelSize:W}=Fa(ne,z,se);return tt(W!=null,`Panel size not found for panel "${z.id}"`),oe===!0&&no(W,ie)},[]),I=ir(z=>{const{layout:se,panelDataArray:ne}=C.current,{collapsedSize:ie=0,collapsible:oe,panelSize:W}=Fa(ne,z,se);return tt(W!=null,`Panel size not found for panel "${z.id}"`),!oe||Ri(W,ie)>0},[]),J=ir(z=>{const{panelDataArray:se}=C.current;se.push(z),se.sort((ne,ie)=>{const oe=ne.order,W=ie.order;return oe==null&&W==null?0:oe==null?-1:W==null?1:oe-W}),C.current.panelDataArrayChanged=!0},[]);hi(()=>{if(C.current.panelDataArrayChanged){C.current.panelDataArrayChanged=!1;const{autoSaveId:z,onLayout:se,storage:ne}=E.current,{layout:ie,panelDataArray:oe}=C.current;let W=null;if(z){const Re=xZ(z,oe,ne);Re&&(w.current=new Map(Object.entries(Re.expandToSizes)),W=Re.layout)}W==null&&(W=vZ({panelDataArray:oe}));const Ce=GC({layout:W,panelConstraints:oe.map(Re=>Re.constraints)});qC(ie,Ce)||(b(Ce),C.current.layout=Ce,se&&se(Ce),Yi(oe,Ce,y.current))}}),hi(()=>{const z=C.current;return()=>{z.layout=[]}},[]);const V=ir(z=>function(ne){ne.preventDefault();const ie=h.current;if(!ie)return()=>null;const{direction:oe,dragState:W,id:Ce,keyboardResizeBy:Re,onLayout:Le}=E.current,{layout:Oe,panelDataArray:me}=C.current,{initialLayout:rt}=W??{},It=CM(Ce,z,ie);let Zt=mZ(ne,z,oe,W,Re,ie);const Wt=oe==="horizontal";document.dir==="rtl"&&Wt&&(Zt=-Zt);const an=me.map(B=>B.constraints),j=gc({delta:Zt,initialLayout:rt??Oe,panelConstraints:an,pivotIndices:It,prevLayout:Oe,trigger:hM(ne)?"keyboard":"mouse-or-touch"}),D=!Vf(Oe,j);(gM(ne)||mM(ne))&&S.current!=Zt&&(S.current=Zt,D?gv(z,0):Wt?gv(z,Zt<0?yM:bM):gv(z,Zt<0?xM:wM)),D&&(b(j),C.current.layout=j,Le&&Le(j),Yi(me,j,y.current))},[]),G=ir((z,se)=>{const{onLayout:ne}=E.current,{layout:ie,panelDataArray:oe}=C.current,W=oe.map(rt=>rt.constraints),{panelSize:Ce,pivotIndices:Re}=Fa(oe,z,ie);tt(Ce!=null,`Panel size not found for panel "${z.id}"`);const Oe=nl(oe,z)===oe.length-1?Ce-se:se-Ce,me=gc({delta:Oe,initialLayout:ie,panelConstraints:W,pivotIndices:Re,prevLayout:ie,trigger:"imperative-api"});Vf(ie,me)||(b(me),C.current.layout=me,ne&&ne(me),Yi(oe,me,y.current))},[]),ee=ir((z,se)=>{const{layout:ne,panelDataArray:ie}=C.current,{collapsedSize:oe=0,collapsible:W}=se,{collapsedSize:Ce=0,collapsible:Re,maxSize:Le=100,minSize:Oe=0}=z.constraints,{panelSize:me}=Fa(ie,z,ne);me!=null&&(W&&Re&&no(me,oe)?no(oe,Ce)||G(z,Ce):meLe&&G(z,Le))},[G]),q=ir((z,se)=>{const{direction:ne}=E.current,{layout:ie}=C.current;if(!h.current)return;const oe=Wg(z,h.current);tt(oe,`Drag handle element not found for id "${z}"`);const W=TM(ne,se);m({dragHandleId:z,dragHandleRect:oe.getBoundingClientRect(),initialCursorPosition:W,initialLayout:ie})},[]),F=ir(()=>{m(null)},[]),A=ir(z=>{const{panelDataArray:se}=C.current,ne=nl(se,z);ne>=0&&(se.splice(ne,1),delete y.current[z.id],C.current.panelDataArrayChanged=!0)},[]),Y=ZQ(()=>({collapsePanel:k,direction:r,dragState:g,expandPanel:T,getPanelSize:O,getPanelStyle:M,groupId:f,isPanelCollapsed:U,isPanelExpanded:I,reevaluatePanelConstraints:ee,registerPanel:J,registerResizeHandle:V,resizePanel:G,startDragging:q,stopDragging:F,unregisterPanel:A,panelGroupElement:h.current}),[k,g,r,T,O,M,f,U,I,ee,J,V,G,q,F,A]),de={display:"flex",flexDirection:r==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return au(Hg.Provider,{value:Y},au(d,{...p,children:t,className:n,id:o,ref:h,style:{...de,...l},"data-panel-group":"","data-panel-group-direction":r,"data-panel-group-id":f}))}const OM=uM((e,t)=>au(RM,{...e,forwardedRef:t}));RM.displayName="PanelGroup";OM.displayName="forwardRef(PanelGroup)";function nl(e,t){return e.findIndex(n=>n===t||n.id===t.id)}function Fa(e,t,n){const r=nl(e,t),o=r===e.length-1?[r-1,r]:[r,r+1],a=n[r];return{...t.constraints,panelSize:a,pivotIndices:o}}function CZ({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:r}){pi(()=>{if(e||n==null||r==null)return;const s=Wg(t,r);if(s==null)return;const o=a=>{if(!a.defaultPrevented)switch(a.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{a.preventDefault(),n(a);break}case"F6":{a.preventDefault();const i=s.getAttribute("data-panel-group-id");tt(i,`No group element found for id "${i}"`);const c=Rd(i,r),l=SM(i,t,r);tt(l!==null,`No resize element found for id "${t}"`);const d=a.shiftKey?l>0?l-1:c.length-1:l+1{s.removeEventListener("keydown",o)}},[r,e,t,n])}function NM({children:e=null,className:t="",disabled:n=!1,hitAreaMargins:r,id:s,onBlur:o,onDragging:a,onFocus:i,style:c={},tabIndex:l=0,tagName:d="div",...p}){var f,h;const g=Yn(null),m=Yn({onDragging:a});pi(()=>{m.current.onDragging=a});const x=cM(Hg);if(x===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:b,groupId:y,registerResizeHandle:w,startDragging:S,stopDragging:E,panelGroupElement:C}=x,k=Pw(s),[T,O]=Pc("inactive"),[M,U]=Pc(!1),[I,J]=Pc(null),V=Yn({state:T});hi(()=>{V.current.state=T}),pi(()=>{if(n)J(null);else{const F=w(k);J(()=>F)}},[n,k,w]);const G=(f=r==null?void 0:r.coarse)!==null&&f!==void 0?f:15,ee=(h=r==null?void 0:r.fine)!==null&&h!==void 0?h:5;return pi(()=>{if(n||I==null)return;const F=g.current;return tt(F,"Element ref not attached"),cZ(k,F,b,{coarse:G,fine:ee},(Y,de,z)=>{if(de)switch(Y){case"down":{O("drag"),S(k,z);const{onDragging:se}=m.current;se&&se(!0);break}case"move":{const{state:se}=V.current;se!=="drag"&&O("hover"),I(z);break}case"up":{O("hover"),E();const{onDragging:se}=m.current;se&&se(!1);break}}else O("inactive")})},[G,b,n,ee,w,k,I,S,E]),CZ({disabled:n,handleId:k,resizeHandler:I,panelGroupElement:C}),au(d,{...p,children:e,className:t,id:s,onBlur:()=>{U(!1),o==null||o()},onFocus:()=>{U(!0),i==null||i()},ref:g,role:"separator",style:{...{touchAction:"none",userSelect:"none"},...c},tabIndex:l,"data-panel-group-direction":b,"data-panel-group-id":y,"data-resize-handle":"","data-resize-handle-active":T==="drag"?"pointer":M?"keyboard":void 0,"data-resize-handle-state":T,"data-panel-resize-handle-enabled":!n,"data-panel-resize-handle-id":k})}NM.displayName="PanelResizeHandle";const Ou=({className:e,...t})=>u.jsx(OM,{className:ge("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t}),Ur=pM,Nu=({withHandle:e,className:t,...n})=>u.jsx(NM,{className:ge("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 after:bg-border focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...n,children:e&&u.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:u.jsx($3,{className:"h-2.5 w-2.5"})})});var Aw="Tabs",[EZ,noe]=Vr(Aw,[vg]),PM=vg(),[TZ,Fw]=EZ(Aw),MM=v.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:s,defaultValue:o,orientation:a="horizontal",dir:i,activationMode:c="automatic",...l}=e,d=Gd(i),[p,f]=pa({prop:r,onChange:s,defaultProp:o});return u.jsx(TZ,{scope:n,baseId:os(),value:p,onValueChange:f,orientation:a,dir:d,activationMode:c,children:u.jsx(Me.div,{dir:d,"data-orientation":a,...l,ref:t})})});MM.displayName=Aw;var IM="TabsList",DM=v.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...s}=e,o=Fw(IM,n),a=PM(n);return u.jsx(Gj,{asChild:!0,...a,orientation:o.orientation,dir:o.dir,loop:r,children:u.jsx(Me.div,{role:"tablist","aria-orientation":o.orientation,...s,ref:t})})});DM.displayName=IM;var AM="TabsTrigger",FM=v.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:s=!1,...o}=e,a=Fw(AM,n),i=PM(n),c=BM(a.baseId,r),l=zM(a.baseId,r),d=r===a.value;return u.jsx(Jj,{asChild:!0,...i,focusable:!s,active:d,children:u.jsx(Me.button,{type:"button",role:"tab","aria-selected":d,"aria-controls":l,"data-state":d?"active":"inactive","data-disabled":s?"":void 0,disabled:s,id:c,...o,ref:t,onMouseDown:Se(e.onMouseDown,p=>{!s&&p.button===0&&p.ctrlKey===!1?a.onValueChange(r):p.preventDefault()}),onKeyDown:Se(e.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&a.onValueChange(r)}),onFocus:Se(e.onFocus,()=>{const p=a.activationMode!=="manual";!d&&!s&&p&&a.onValueChange(r)})})})});FM.displayName=AM;var LM="TabsContent",$M=v.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:s,children:o,...a}=e,i=Fw(LM,n),c=BM(i.baseId,r),l=zM(i.baseId,r),d=r===i.value,p=v.useRef(d);return v.useEffect(()=>{const f=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(f)},[]),u.jsx(or,{present:s||d,children:({present:f})=>u.jsx(Me.div,{"data-state":d?"active":"inactive","data-orientation":i.orientation,role:"tabpanel","aria-labelledby":c,hidden:!f,id:l,tabIndex:0,...a,ref:t,style:{...e.style,animationDuration:p.current?"0s":void 0},children:f&&o})})});$M.displayName=LM;function BM(e,t){return`${e}-trigger-${t}`}function zM(e,t){return`${e}-content-${t}`}var kZ=MM,UM=DM,VM=FM,HM=$M;const _Z=kZ,KM=v.forwardRef(({className:e,...t},n)=>u.jsx(UM,{ref:n,className:ge("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",e),...t}));KM.displayName=UM.displayName;const xb=v.forwardRef(({className:e,...t},n)=>u.jsx(VM,{ref:n,className:ge("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",e),...t}));xb.displayName=VM.displayName;const wb=v.forwardRef(({className:e,...t},n)=>u.jsx(HM,{ref:n,className:ge("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...t}));wb.displayName=HM.displayName;const jZ=e=>["chats","findChats",JSON.stringify(e)],RZ=async({instanceName:e})=>(await he.post(`/chat/findChats/${e}`,{where:{}})).data,OZ=e=>{const{instanceName:t,...n}=e;return lt({...n,queryKey:jZ({instanceName:t}),queryFn:()=>RZ({instanceName:t}),enabled:!!t})};function Pu(e){const t=o=>typeof window<"u"?window.matchMedia(o).matches:!1,[n,r]=v.useState(t(e));function s(){r(t(e))}return v.useEffect(()=>{const o=window.matchMedia(e);return s(),o.addListener?o.addListener(s):o.addEventListener("change",s),()=>{o.removeListener?o.removeListener(s):o.removeEventListener("change",s)}},[e]),n}const Nl=v.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:ge("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));Nl.displayName="Textarea";const NZ=e=>["chats","findChats",JSON.stringify(e)],PZ=async({instanceName:e,remoteJid:t})=>{const n=await he.post(`/chat/findChats/${e}`,{where:{remoteJid:t}});return Array.isArray(n.data)?n.data[0]:n.data},MZ=e=>{const{instanceName:t,remoteJid:n,...r}=e;return lt({...r,queryKey:NZ({instanceName:t,remoteJid:n}),queryFn:()=>PZ({instanceName:t,remoteJid:n}),enabled:!!t&&!!n})},IZ=e=>["chats","findMessages",JSON.stringify(e)],DZ=async({instanceName:e,remoteJid:t})=>{var r,s;const n=await he.post(`/chat/findMessages/${e}`,{where:{key:{remoteJid:t}}});return(s=(r=n.data)==null?void 0:r.messages)!=null&&s.records?n.data.messages.records:n.data},AZ=e=>{const{instanceName:t,remoteJid:n,...r}=e;return lt({...r,queryKey:IZ({instanceName:t,remoteJid:n}),queryFn:()=>DZ({instanceName:t,remoteJid:n}),enabled:!!t&&!!n})};function FZ({textareaRef:e,handleTextareaChange:t,textareaHeight:n,lastMessageRef:r,scrollToBottom:s}){const{instance:o}=nt(),{remoteJid:a}=So(),{data:i}=MZ({remoteJid:a,instanceName:o==null?void 0:o.name}),{data:c,isSuccess:l}=AZ({remoteJid:a,instanceName:o==null?void 0:o.name});v.useEffect(()=>{l&&c&&s()},[l,c,s]);const d=f=>u.jsx("div",{className:"bubble-right",children:u.jsx("div",{className:"flex items-start gap-4 self-end",children:u.jsx("div",{className:"grid gap-1",children:u.jsx("div",{className:"prose text-muted-foreground",children:u.jsx("div",{className:"bubble",children:JSON.stringify(f.message)})})})})}),p=f=>u.jsx("div",{className:"bubble-left",children:u.jsx("div",{className:"flex items-start gap-4",children:u.jsx("div",{className:"grid gap-1",children:u.jsx("div",{className:"prose text-muted-foreground",children:u.jsx("div",{className:"bubble",children:JSON.stringify(f.message)})})})})});return u.jsxs("div",{className:"flex min-h-screen flex-col",children:[u.jsx("div",{className:"sticky top-0 p-2",children:u.jsxs(nw,{children:[u.jsx(rw,{asChild:!0,children:u.jsxs(K,{variant:"ghost",className:"h-10 gap-1 rounded-xl px-3 text-lg data-[state=open]:bg-muted",children:[(i==null?void 0:i.pushName)||(i==null?void 0:i.remoteJid.split("@")[0]),u.jsx(lg,{className:"h-4 w-4 text-muted-foreground"})]})}),u.jsxs(ps,{align:"start",className:"max-w-[300px]",children:[u.jsxs(ft,{className:"items-start gap-2",children:[u.jsx(W3,{className:"mr-2 h-4 w-4 shrink-0 translate-y-1"}),u.jsxs("div",{children:[u.jsx("div",{className:"font-medium",children:"GPT-4"}),u.jsx("div",{className:"text-muted-foreground/80",children:"With DALL-E, browsing and analysis. Limit 40 messages / 3 hours"})]})]}),u.jsx(Oa,{}),u.jsxs(ft,{className:"items-start gap-2",children:[u.jsx(pj,{className:"mr-2 h-4 w-4 shrink-0 translate-y-1"}),u.jsxs("div",{children:[u.jsx("div",{className:"font-medium",children:"GPT-3"}),u.jsx("div",{className:"text-muted-foreground/80",children:"Great for everyday tasks"})]})]})]})]})}),u.jsxs("div",{className:"message-container mx-auto flex max-w-4xl flex-1 flex-col gap-8 overflow-y-auto px-4",children:[c==null?void 0:c.map(f=>f.key.fromMe?d(f):p(f)),u.jsx("div",{ref:r})]}),u.jsx("div",{className:"sticky bottom-0 mx-auto flex w-full max-w-2xl flex-col gap-1.5 bg-background px-4 py-2",children:u.jsxs("div",{className:"input-message relative",children:[u.jsxs(K,{type:"button",size:"icon",className:"absolute bottom-3 left-3 h-8 w-8 rounded-full bg-transparent text-white hover:bg-transparent",children:[u.jsx(q3,{className:"h-4 w-4 text-white"}),u.jsx("span",{className:"sr-only",children:"Anexar"})]}),u.jsx(Nl,{placeholder:"Enviar mensagem...",name:"message",id:"message",rows:1,ref:e,onChange:t,style:{height:n},className:"max-h-[240px] min-h-[48px] resize-none rounded-3xl border border-none p-4 pl-12 pr-16 shadow-sm"}),u.jsxs(K,{type:"submit",size:"icon",className:"absolute bottom-3 right-3 h-8 w-8 rounded-full",children:[u.jsx(j3,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Enviar"})]})]})})]})}function QC(){const e=Pu("(min-width: 768px)"),t=v.useRef(null),[n]=v.useState("auto"),r=v.useRef(null),{instance:s}=nt(),{data:o,isSuccess:a}=OZ({instanceName:s==null?void 0:s.name}),{instanceId:i,remoteJid:c}=So(),l=An(),d=v.useCallback(()=>{t.current&&t.current.scrollIntoView({})},[]),p=()=>{if(r.current){r.current.style.height="auto";const h=r.current.scrollHeight,m=parseInt(getComputedStyle(r.current).lineHeight)*10;r.current.style.height=`${Math.min(h,m)}px`}};v.useEffect(()=>{a&&d()},[a,d]);const f=h=>{l(`/manager/instance/${i}/chat/${h}`)};return u.jsxs(Ou,{direction:e?"horizontal":"vertical",children:[u.jsx(Ur,{defaultSize:20,children:u.jsxs("div",{className:"hidden flex-col gap-2 bg-background text-foreground md:flex",children:[u.jsx("div",{className:"sticky top-0 p-2",children:u.jsxs(K,{variant:"ghost",className:"w-full justify-start gap-2 px-2 text-left",children:[u.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-full",children:u.jsx(ug,{className:"h-4 w-4"})}),u.jsx("div",{className:"grow overflow-hidden text-ellipsis whitespace-nowrap text-sm",children:"Chat"}),u.jsx(Mi,{className:"h-4 w-4"})]})}),u.jsxs(_Z,{defaultValue:"contacts",children:[u.jsxs(KM,{className:"tabs-chat",children:[u.jsx(xb,{value:"contacts",children:"Contatos"}),u.jsx(xb,{value:"groups",children:"Grupos"})]}),u.jsx(wb,{value:"contacts",children:u.jsx("div",{className:"flex-1 overflow-auto",children:u.jsxs("div",{className:"grid gap-1 p-2 text-foreground",children:[u.jsx("div",{className:"px-2 text-xs font-medium text-muted-foreground",children:"Contatos"}),o==null?void 0:o.map(h=>h.remoteJid.includes("@s.whatsapp.net")&&u.jsxs(nd,{to:"#",onClick:()=>f(h.remoteJid),className:`chat-item flex items-center overflow-hidden truncate whitespace-nowrap rounded-md border-b border-gray-600/50 p-2 text-sm transition-colors hover:bg-muted/50 ${c===h.remoteJid?"active":""}`,children:[u.jsx("span",{className:"chat-avatar mr-2",children:u.jsx("img",{src:h.profilePicUrl||"https://via.placeholder.com/150",alt:"Avatar",className:"h-8 w-8 rounded-full"})}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx("span",{className:"chat-title block font-medium",children:h.pushName}),u.jsx("span",{className:"chat-description block text-xs text-gray-500",children:h.remoteJid.split("@")[0]})]})]},h.id))]})})}),u.jsx(wb,{value:"groups",children:u.jsx("div",{className:"flex-1 overflow-auto",children:u.jsx("div",{className:"grid gap-1 p-2 text-foreground",children:o==null?void 0:o.map(h=>h.remoteJid.includes("@g.us")&&u.jsxs(nd,{to:"#",onClick:()=>f(h.remoteJid),className:`chat-item flex items-center overflow-hidden truncate whitespace-nowrap rounded-md border-b border-gray-600/50 p-2 text-sm transition-colors hover:bg-muted/50 ${c===h.remoteJid?"active":""}`,children:[u.jsx("span",{className:"chat-avatar mr-2",children:u.jsx("img",{src:h.profilePicUrl||"https://via.placeholder.com/150",alt:"Avatar",className:"h-8 w-8 rounded-full"})}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx("span",{className:"chat-title block font-medium",children:h.pushName}),u.jsx("span",{className:"chat-description block text-xs text-gray-500",children:h.remoteJid})]})]},h.id))})})})]})]})}),u.jsx(Nu,{withHandle:!0,className:"border border-black"}),u.jsx(Ur,{children:c&&u.jsx(FZ,{textareaRef:r,handleTextareaChange:p,textareaHeight:n,lastMessageRef:t,scrollToBottom:d})})]})}const LZ=e=>["chatwoot","fetchChatwoot",JSON.stringify(e)],$Z=async({instanceName:e,token:t})=>(await he.get(`/chatwoot/find/${e}`,{headers:{apiKey:t}})).data,BZ=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:LZ({instanceName:t,token:n}),queryFn:()=>$Z({instanceName:t,token:n}),enabled:!!t})},zZ=async({instanceName:e,token:t,data:n})=>(await he.post(`/chatwoot/set/${e}`,n,{headers:{apikey:t}})).data;function UZ(){return{createChatwoot:Ye(zZ,{invalidateKeys:[["chatwoot","fetchChatwoot"]]})}}const Hf=_.string().optional().transform(e=>e===""?void 0:e),VZ=_.object({enabled:_.boolean(),accountId:_.string(),token:_.string(),url:_.string(),signMsg:_.boolean().optional(),signDelimiter:Hf,nameInbox:Hf,organization:Hf,logo:Hf,reopenConversation:_.boolean().optional(),conversationPending:_.boolean().optional(),mergeBrazilContacts:_.boolean().optional(),importContacts:_.boolean().optional(),importMessages:_.boolean().optional(),daysLimitImportMessages:_.coerce.number().optional(),autoCreate:_.boolean(),ignoreJids:_.array(_.string()).default([])});function HZ(){const{t:e}=ze(),{instance:t}=nt(),[,n]=v.useState(!1),{createChatwoot:r}=UZ(),{data:s}=BZ({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),o=sn({resolver:on(VZ),defaultValues:{enabled:!0,accountId:"",token:"",url:"",signMsg:!0,signDelimiter:"\\n",nameInbox:"",organization:"",logo:"",reopenConversation:!0,conversationPending:!1,mergeBrazilContacts:!0,importContacts:!1,importMessages:!1,daysLimitImportMessages:7,autoCreate:!0,ignoreJids:[]}});v.useEffect(()=>{if(s){o.setValue("ignoreJids",s.ignoreJids||[]);const i={enabled:s.enabled,accountId:s.accountId,token:s.token,url:s.url,signMsg:s.signMsg||!1,signDelimiter:s.signDelimiter||"\\n",nameInbox:s.nameInbox||"",organization:s.organization||"",logo:s.logo||"",reopenConversation:s.reopenConversation||!1,conversationPending:s.conversationPending||!1,mergeBrazilContacts:s.mergeBrazilContacts||!1,importContacts:s.importContacts||!1,importMessages:s.importMessages||!1,daysLimitImportMessages:s.daysLimitImportMessages||7,autoCreate:s.autoCreate||!1,ignoreJids:s.ignoreJids};o.reset(i)}},[s,o]);const a=async i=>{if(!t)return;n(!0);const c={enabled:i.enabled,accountId:i.accountId,token:i.token,url:i.url,signMsg:i.signMsg||!1,signDelimiter:i.signDelimiter||"\\n",nameInbox:i.nameInbox||"",organization:i.organization||"",logo:i.logo||"",reopenConversation:i.reopenConversation||!1,conversationPending:i.conversationPending||!1,mergeBrazilContacts:i.mergeBrazilContacts||!1,importContacts:i.importContacts||!1,importMessages:i.importMessages||!1,daysLimitImportMessages:i.daysLimitImportMessages||7,autoCreate:i.autoCreate,ignoreJids:i.ignoreJids};await r({instanceName:t.name,token:t.token,data:c},{onSuccess:()=>{X.success(e("chatwoot.toast.success"))},onError:l=>{var d,p,f;console.error(e("chatwoot.toast.error"),l),A4(l)?X.error(`Error: ${(f=(p=(d=l==null?void 0:l.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`):X.error(e("chatwoot.toast.error"))},onSettled:()=>{n(!1)}})};return u.jsx(u.Fragment,{children:u.jsx(Ma,{...o,children:u.jsxs("form",{onSubmit:o.handleSubmit(a),className:"w-full space-y-6",children:[u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("chatwoot.title")}),u.jsx(Ra,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:px-4 [&>*]:py-2",children:[u.jsx(Pe,{name:"enabled",label:e("chatwoot.form.enabled.label"),className:"w-full justify-between",helper:e("chatwoot.form.enabled.description")}),u.jsx(Z,{name:"url",label:e("chatwoot.form.url.label"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"accountId",label:e("chatwoot.form.accountId.label"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"token",label:e("chatwoot.form.token.label"),children:u.jsx(Q,{type:"password"})}),u.jsx(Pe,{name:"signMsg",label:e("chatwoot.form.signMsg.label"),className:"w-full justify-between",helper:e("chatwoot.form.signMsg.description")}),u.jsx(Z,{name:"signDelimiter",label:e("chatwoot.form.signDelimiter.label"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"nameInbox",label:e("chatwoot.form.nameInbox.label"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"organization",label:e("chatwoot.form.organization.label"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"logo",label:e("chatwoot.form.logo.label"),children:u.jsx(Q,{})}),u.jsx(Pe,{name:"conversationPending",label:e("chatwoot.form.conversationPending.label"),className:"w-full justify-between",helper:e("chatwoot.form.conversationPending.description")}),u.jsx(Pe,{name:"reopenConversation",label:e("chatwoot.form.reopenConversation.label"),className:"w-full justify-between",helper:e("chatwoot.form.reopenConversation.description")}),u.jsx(Pe,{name:"importContacts",label:e("chatwoot.form.importContacts.label"),className:"w-full justify-between",helper:e("chatwoot.form.importContacts.description")}),u.jsx(Pe,{name:"importMessages",label:e("chatwoot.form.importMessages.label"),className:"w-full justify-between",helper:e("chatwoot.form.importMessages.description")}),u.jsx(Z,{name:"daysLimitImportMessages",label:e("chatwoot.form.daysLimitImportMessages.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Ru,{name:"ignoreJids",label:e("chatwoot.form.ignoreJids.label"),placeholder:e("chatwoot.form.ignoreJids.placeholder")}),u.jsx(Pe,{name:"autoCreate",label:e("chatwoot.form.autoCreate.label"),className:"w-full justify-between",helper:e("chatwoot.form.autoCreate.description")})]})]}),u.jsx("div",{className:"mx-4 flex justify-end",children:u.jsx(K,{type:"submit",children:e("chatwoot.button.save")})})]})})})}var Gg={},qM={exports:{}},KZ="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",qZ=KZ,WZ=qZ;function WM(){}function GM(){}GM.resetWarningCache=WM;var GZ=function(){function e(r,s,o,a,i,c){if(c!==WZ){var l=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw l.name="Invariant Violation",l}}e.isRequired=e;function t(){return e}var n={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:GM,resetWarningCache:WM};return n.PropTypes=n,n};qM.exports=GZ();var JM=qM.exports,QM={L:1,M:0,Q:3,H:2},ZM={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},JZ=ZM;function YM(e){this.mode=JZ.MODE_8BIT_BYTE,this.data=e}YM.prototype={getLength:function(e){return this.data.length},write:function(e){for(var t=0;t>>7-e%8&1)==1},put:function(e,t){for(var n=0;n>>t-n-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(e){var t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};var YZ=XM,Xr={glog:function(e){if(e<1)throw new Error("glog("+e+")");return Xr.LOG_TABLE[e]},gexp:function(e){for(;e<0;)e+=255;for(;e>=256;)e-=255;return Xr.EXP_TABLE[e]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(var Cn=0;Cn<8;Cn++)Xr.EXP_TABLE[Cn]=1<=0;)t^=wn.G15<=0;)t^=wn.G18<>>=1;return t},getPatternPosition:function(e){return wn.PATTERN_POSITION_TABLE[e-1]},getMask:function(e,t,n){switch(e){case Do.PATTERN000:return(t+n)%2==0;case Do.PATTERN001:return t%2==0;case Do.PATTERN010:return n%3==0;case Do.PATTERN011:return(t+n)%3==0;case Do.PATTERN100:return(Math.floor(t/2)+Math.floor(n/3))%2==0;case Do.PATTERN101:return t*n%2+t*n%3==0;case Do.PATTERN110:return(t*n%2+t*n%3)%2==0;case Do.PATTERN111:return(t*n%3+(t+n)%2)%2==0;default:throw new Error("bad maskPattern:"+e)}},getErrorCorrectPolynomial:function(e){for(var t=new ZC([1],0),n=0;n5&&(n+=3+o-5)}for(var r=0;r=7&&this.setupTypeNumber(e),this.dataCache==null&&(this.dataCache=Ms.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,t)};kr.setupPositionProbePattern=function(e,t){for(var n=-1;n<=7;n++)if(!(e+n<=-1||this.moduleCount<=e+n))for(var r=-1;r<=7;r++)t+r<=-1||this.moduleCount<=t+r||(0<=n&&n<=6&&(r==0||r==6)||0<=r&&r<=6&&(n==0||n==6)||2<=n&&n<=4&&2<=r&&r<=4?this.modules[e+n][t+r]=!0:this.modules[e+n][t+r]=!1)};kr.getBestMaskPattern=function(){for(var e=0,t=0,n=0;n<8;n++){this.makeImpl(!0,n);var r=Da.getLostPoint(this);(n==0||e>r)&&(e=r,t=n)}return t};kr.createMovieClip=function(e,t,n){var r=e.createEmptyMovieClip(t,n),s=1;this.make();for(var o=0;o>n&1)==1;this.modules[Math.floor(n/3)][n%3+this.moduleCount-8-3]=r}for(var n=0;n<18;n++){var r=!e&&(t>>n&1)==1;this.modules[n%3+this.moduleCount-8-3][Math.floor(n/3)]=r}};kr.setupTypeInfo=function(e,t){for(var n=this.errorCorrectLevel<<3|t,r=Da.getBCHTypeInfo(n),s=0;s<15;s++){var o=!e&&(r>>s&1)==1;s<6?this.modules[s][8]=o:s<8?this.modules[s+1][8]=o:this.modules[this.moduleCount-15+s][8]=o}for(var s=0;s<15;s++){var o=!e&&(r>>s&1)==1;s<8?this.modules[8][this.moduleCount-s-1]=o:s<9?this.modules[8][15-s-1+1]=o:this.modules[8][15-s-1]=o}this.modules[this.moduleCount-8][8]=!e};kr.mapData=function(e,t){for(var n=-1,r=this.moduleCount-1,s=7,o=0,a=this.moduleCount-1;a>0;a-=2)for(a==6&&a--;;){for(var i=0;i<2;i++)if(this.modules[r][a-i]==null){var c=!1;o>>s&1)==1);var l=Da.getMask(t,r,a-i);l&&(c=!c),this.modules[r][a-i]=c,s--,s==-1&&(o++,s=7)}if(r+=n,r<0||this.moduleCount<=r){r-=n,n=-n;break}}};Ms.PAD0=236;Ms.PAD1=17;Ms.createData=function(e,t,n){for(var r=nI.getRSBlocks(e,t),s=new rI,o=0;oi*8)throw new Error("code length overflow. ("+s.getLengthInBits()+">"+i*8+")");for(s.getLengthInBits()+4<=i*8&&s.put(0,4);s.getLengthInBits()%8!=0;)s.putBit(!1);for(;!(s.getLengthInBits()>=i*8||(s.put(Ms.PAD0,8),s.getLengthInBits()>=i*8));)s.put(Ms.PAD1,8);return Ms.createBytes(s,r)};Ms.createBytes=function(e,t){for(var n=0,r=0,s=0,o=new Array(t.length),a=new Array(t.length),i=0;i=0?h.get(g):0}}for(var m=0,d=0;d=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}var iY={bgColor:Or.default.oneOfType([Or.default.object,Or.default.string]).isRequired,bgD:Or.default.string.isRequired,fgColor:Or.default.oneOfType([Or.default.object,Or.default.string]).isRequired,fgD:Or.default.string.isRequired,size:Or.default.number.isRequired,title:Or.default.string,viewBoxSize:Or.default.number.isRequired,xmlns:Or.default.string},$w=(0,sI.forwardRef)(function(e,t){var n=e.bgColor,r=e.bgD,s=e.fgD,o=e.fgColor,a=e.size,i=e.title,c=e.viewBoxSize,l=e.xmlns,d=l===void 0?"http://www.w3.org/2000/svg":l,p=aY(e,["bgColor","bgD","fgD","fgColor","size","title","viewBoxSize","xmlns"]);return qf.default.createElement("svg",sY({},p,{height:a,ref:t,viewBox:"0 0 "+c+" "+c,width:a,xmlns:d}),i?qf.default.createElement("title",null,i):null,qf.default.createElement("path",{d:r,fill:n}),qf.default.createElement("path",{d:s,fill:o}))});$w.displayName="QRCodeSvg";$w.propTypes=iY;Lw.default=$w;Object.defineProperty(Gg,"__esModule",{value:!0});Gg.QRCode=void 0;var lY=Object.assign||function(e){for(var t=1;t=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}var yY={bgColor:Gs.default.oneOfType([Gs.default.object,Gs.default.string]),fgColor:Gs.default.oneOfType([Gs.default.object,Gs.default.string]),level:Gs.default.string,size:Gs.default.number,value:Gs.default.string.isRequired},Jg=(0,aI.forwardRef)(function(e,t){var n=e.bgColor,r=n===void 0?"#FFFFFF":n,s=e.fgColor,o=s===void 0?"#000000":s,a=e.level,i=a===void 0?"L":a,c=e.size,l=c===void 0?256:c,d=e.value,p=vY(e,["bgColor","fgColor","level","size","value"]),f=new pY.default(-1,dY.default[i]);f.addData(d),f.make();var h=f.modules;return hY.default.createElement(mY.default,lY({},p,{bgColor:r,bgD:h.map(function(g,m){return g.map(function(x,b){return x?"":"M "+b+" "+m+" l 1 0 0 1 -1 0 Z"}).join(" ")}).join(" "),fgColor:o,fgD:h.map(function(g,m){return g.map(function(x,b){return x?"M "+b+" "+m+" l 1 0 0 1 -1 0 Z":""}).join(" ")}).join(" "),ref:t,size:l,viewBoxSize:h.length}))});Gg.QRCode=Jg;Jg.displayName="QRCode";Jg.propTypes=yY;var bY=Gg.default=Jg;const xY=ig("relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7 space-y-1 [&_strong]:text-foreground",{variants:{variant:{default:"border-zinc-500/20 bg-zinc-50/50 dark:border-zinc-500/30 dark:bg-zinc-500/10 text-zinc-900 dark:text-zinc-300 [&>svg]:text-zinc-400 dark:[&>svg]:text-zinc-300",destructive:"border-red-500/20 bg-red-50/50 dark:border-red-500/30 dark:bg-red-500/10 text-red-900 dark:text-red-200 [&>svg]:text-red-600 dark:[&>svg]:text-red-400/80",warning:"border-amber-500/20 bg-amber-50/50 dark:border-amber-500/30 dark:bg-amber-500/10 text-amber-900 dark:text-amber-200 [&>svg]:text-amber-500",info:"border-sky-500/20 bg-sky-50/50 dark:border-sky-500/30 dark:bg-sky-500/10 text-sky-900 dark:text-sky-200 [&>svg]:text-sky-500",success:"border-emerald-500/20 bg-emerald-50/50 dark:border-emerald-500/30 dark:bg-emerald-500/10 text-emerald-900 dark:text-emerald-200 [&>svg]:text-emerald-600 dark:[&>svg]:text-emerald-400/80"}},defaultVariants:{variant:"default"}}),iI=v.forwardRef(({className:e,variant:t,...n},r)=>u.jsx("div",{ref:r,role:"alert",className:ge(xY({variant:t}),e),...n}));iI.displayName="Alert";const lI=v.forwardRef(({className:e,...t},n)=>u.jsx("h5",{ref:n,className:ge("font-medium leading-none tracking-tight",e),...t}));lI.displayName="AlertTitle";const wY=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ge("text-sm [&_p]:leading-relaxed",e),...t}));wY.displayName="AlertDescription";const wr=({size:e=45,className:t,...n})=>u.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,...n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:ge("animate-spin",t),children:u.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})});function SY(){const{t:e,i18n:t}=ze(),n=new Intl.NumberFormat(t.language),[r,s]=v.useState(null),[o,a]=v.useState(""),i=Fs(rs.TOKEN),{theme:c}=R_(),{connect:l,logout:d,restart:p}=_g(),{instance:f,reloadInstance:h}=nt(),g=async()=>{await h()},m=async E=>{try{await p(E),await h()}catch(C){console.error("Error:",C)}},x=async E=>{try{await d(E),await h()}catch(C){console.error("Error:",C)}},b=async(E,C)=>{try{if(s(null),!i){console.error("Token not found.");return}if(C){const k=await l({instanceName:E,token:i,number:f==null?void 0:f.number});a(k.pairingCode)}else{const k=await l({instanceName:E,token:i});s(k.code)}}catch(k){console.error("Error:",k)}},y=async()=>{s(null),a(""),await h()},w=v.useMemo(()=>{var E,C,k;return f?{contacts:((E=f._count)==null?void 0:E.Contact)||0,chats:((C=f._count)==null?void 0:C.Chat)||0,messages:((k=f._count)==null?void 0:k.Message)||0}:{contacts:0,chats:0,messages:0}},[f]),S=v.useMemo(()=>c==="dark"?"#fff":c==="light"?"#000":"#189d68",[c]);return f?u.jsxs("main",{className:"flex flex-col gap-8",children:[u.jsx("section",{children:u.jsxs(Ja,{children:[u.jsx(Qa,{children:u.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[u.jsx("h2",{className:"break-all text-lg font-semibold",children:f.name}),u.jsx(WO,{status:f.connectionStatus})]})}),u.jsxs(Za,{className:"flex flex-col items-start space-y-6",children:[u.jsx("div",{className:"flex w-full flex-1",children:u.jsx(GO,{token:f.token})}),f.profileName&&u.jsxs("div",{className:"flex flex-1 gap-2",children:[u.jsx(Sg,{children:u.jsx(Cg,{src:f.profilePicUrl,alt:""})}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("strong",{children:f.profileName}),u.jsx("p",{className:"break-all text-sm text-muted-foreground",children:f.ownerJid})]})]}),f.connectionStatus!=="open"&&u.jsxs(iI,{variant:"warning",className:"flex flex-wrap items-center justify-between gap-3",children:[u.jsx(lI,{className:"text-lg font-bold tracking-wide",children:e("instance.dashboard.alert")}),u.jsxs(Tt,{children:[u.jsx(Mt,{onClick:()=>b(f.name,!1),asChild:!0,children:u.jsx(K,{variant:"warning",children:e("instance.dashboard.button.qrcode.label")})}),u.jsxs(xt,{onCloseAutoFocus:y,children:[u.jsx(wt,{children:e("instance.dashboard.button.qrcode.title")}),u.jsx("div",{className:"flex items-center justify-center",children:r&&u.jsx(bY,{value:r,size:256,bgColor:"transparent",fgColor:S,className:"rounded-sm"})})]})]}),f.number&&u.jsxs(Tt,{children:[u.jsx(Mt,{className:"connect-code-button",onClick:()=>b(f.name,!0),children:e("instance.dashboard.button.pairingCode.label")}),u.jsx(xt,{onCloseAutoFocus:y,children:u.jsx(wt,{children:u.jsx(Fi,{children:o?u.jsxs("div",{className:"py-3",children:[u.jsx("p",{className:"text-center",children:u.jsx("strong",{children:e("instance.dashboard.button.pairingCode.title")})}),u.jsxs("p",{className:"pairing-code text-center",children:[o.substring(0,4),"-",o.substring(4,8)]})]}):u.jsx(wr,{})})})})]})]})]}),u.jsxs(kg,{className:"flex flex-wrap items-center justify-end gap-3",children:[u.jsx(K,{variant:"outline",className:"refresh-button",size:"icon",onClick:g,children:u.jsx(fj,{size:"20"})}),u.jsx(K,{className:"action-button",variant:"secondary",onClick:()=>m(f.name),children:e("instance.dashboard.button.restart").toUpperCase()}),u.jsx(K,{variant:"destructive",onClick:()=>x(f.name),disabled:f.connectionStatus==="close",children:e("instance.dashboard.button.disconnect").toUpperCase()})]})]})}),u.jsxs("section",{className:"grid grid-cols-[repeat(auto-fit,_minmax(15rem,_1fr))] gap-6",children:[u.jsxs(Ja,{className:"instance-card",children:[u.jsx(Qa,{children:u.jsxs(jc,{className:"flex items-center gap-2",children:[u.jsx(dj,{size:"20"}),e("instance.dashboard.contacts")]})}),u.jsx(Za,{children:n.format(w.contacts)})]}),u.jsxs(Ja,{className:"instance-card",children:[u.jsx(Qa,{children:u.jsxs(jc,{className:"flex items-center gap-2",children:[u.jsx(J3,{size:"20"}),e("instance.dashboard.chats")]})}),u.jsx(Za,{children:n.format(w.chats)})]}),u.jsxs(Ja,{className:"instance-card",children:[u.jsx(Qa,{children:u.jsxs(jc,{className:"flex items-center gap-2",children:[u.jsx(ug,{size:"20"}),e("instance.dashboard.messages")]})}),u.jsx(Za,{children:n.format(w.messages)})]})]})]}):u.jsx(wr,{})}var CY="Separator",YC="horizontal",EY=["horizontal","vertical"],uI=v.forwardRef((e,t)=>{const{decorative:n,orientation:r=YC,...s}=e,o=TY(r)?r:YC,i=n?{role:"none"}:{"aria-orientation":o==="vertical"?o:void 0,role:"separator"};return u.jsx(Me.div,{"data-orientation":o,...i,...s,ref:t})});uI.displayName=CY;function TY(e){return EY.includes(e)}var cI=uI;const $t=v.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},s)=>u.jsx(cI,{ref:s,decorative:n,orientation:t,className:ge("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));$t.displayName=cI.displayName;const kY=e=>["dify","fetchDify",JSON.stringify(e)],_Y=async({instanceName:e,token:t})=>(await he.get(`/dify/find/${e}`,{headers:{apikey:t}})).data,dI=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:kY({instanceName:t,token:n}),queryFn:()=>_Y({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},jY=async({instanceName:e,token:t,data:n})=>(await he.post(`/dify/create/${e}`,n,{headers:{apikey:t}})).data,RY=async({instanceName:e,difyId:t,data:n})=>(await he.put(`/dify/update/${t}/${e}`,n)).data,OY=async({instanceName:e,difyId:t})=>(await he.delete(`/dify/delete/${t}/${e}`)).data,NY=async({instanceName:e,token:t,data:n})=>(await he.post(`/dify/settings/${e}`,n,{headers:{apikey:t}})).data,PY=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await he.post(`/dify/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function Qg(){const e=Ye(NY,{invalidateKeys:[["dify","fetchDefaultSettings"]]}),t=Ye(PY,{invalidateKeys:[["dify","getDify"],["dify","fetchSessions"]]}),n=Ye(OY,{invalidateKeys:[["dify","getDify"],["dify","fetchDify"],["dify","fetchSessions"]]}),r=Ye(RY,{invalidateKeys:[["dify","getDify"],["dify","fetchDify"],["dify","fetchSessions"]]}),s=Ye(jY,{invalidateKeys:[["dify","fetchDify"]]});return{setDefaultSettingsDify:e,changeStatusDify:t,deleteDify:n,updateDify:r,createDify:s}}const MY=e=>["dify","fetchDefaultSettings",JSON.stringify(e)],IY=async({instanceName:e,token:t})=>(await he.get(`/dify/fetchSettings/${e}`,{headers:{apikey:t}})).data,DY=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:MY({instanceName:t,token:n}),queryFn:()=>IY({instanceName:t,token:n}),enabled:!!t})},AY=_.object({expire:_.string(),keywordFinish:_.string(),delayMessage:_.string(),unknownMessage:_.string(),listeningFromMe:_.boolean(),stopBotFromMe:_.boolean(),keepOpen:_.boolean(),debounceTime:_.string(),ignoreJids:_.array(_.string()).default([]),difyIdFallback:_.union([_.null(),_.string()]).optional()});function FY(){const{t:e}=ze(),{instance:t}=nt(),{setDefaultSettingsDify:n}=Qg(),[r,s]=v.useState(!1),{data:o,refetch:a}=dI({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token,enabled:r}),{data:i,refetch:c}=DY({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),l=sn({resolver:on(AY),defaultValues:{expire:"0",keywordFinish:e("dify.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("dify.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],difyIdFallback:void 0}});v.useEffect(()=>{i&&l.reset({expire:i!=null&&i.expire?i.expire.toString():"0",keywordFinish:i.keywordFinish,delayMessage:i.delayMessage?i.delayMessage.toString():"0",unknownMessage:i.unknownMessage,listeningFromMe:i.listeningFromMe,stopBotFromMe:i.stopBotFromMe,keepOpen:i.keepOpen,debounceTime:i.debounceTime?i.debounceTime.toString():"0",ignoreJids:i.ignoreJids,difyIdFallback:i.difyIdFallback})},[i]);const d=async f=>{var h,g,m;try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),difyIdFallback:f.difyIdFallback||void 0,ignoreJids:f.ignoreJids};await n({instanceName:t.name,token:t.token,data:x}),X.success(e("dify.toast.defaultSettings.success"))}catch(x){console.error("Error:",x),X.error(`Error: ${(m=(g=(h=x==null?void 0:x.response)==null?void 0:h.data)==null?void 0:g.response)==null?void 0:m.message}`)}};function p(){c(),a()}return u.jsxs(Tt,{open:r,onOpenChange:s,children:[u.jsx(Mt,{asChild:!0,children:u.jsxs(K,{variant:"secondary",size:"sm",children:[u.jsx(Pi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:e("dify.defaultSettings")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[u.jsx(wt,{children:u.jsx(Ut,{children:e("dify.defaultSettings")})}),u.jsx(Tr,{...l,children:u.jsxs("form",{className:"w-full space-y-6",onSubmit:l.handleSubmit(d),children:[u.jsx("div",{children:u.jsxs("div",{className:"space-y-4",children:[u.jsx(Qt,{name:"difyIdFallback",label:e("dify.form.difyIdFallback.label"),options:(o==null?void 0:o.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),u.jsx(Z,{name:"expire",label:e("dify.form.expire.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"keywordFinish",label:e("dify.form.keywordFinish.label"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"delayMessage",label:e("dify.form.delayMessage.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"unknownMessage",label:e("dify.form.unknownMessage.label"),children:u.jsx(Q,{})}),u.jsx(Pe,{name:"listeningFromMe",label:e("dify.form.listeningFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"stopBotFromMe",label:e("dify.form.stopBotFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"keepOpen",label:e("dify.form.keepOpen.label"),reverse:!0}),u.jsx(Z,{name:"debounceTime",label:e("dify.form.debounceTime.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Ru,{name:"ignoreJids",label:e("dify.form.ignoreJids.label"),placeholder:e("dify.form.ignoreJids.placeholder")})]})}),u.jsx(rn,{children:u.jsx(K,{type:"submit",children:e("dify.button.save")})})]})})]})]})}/** + * table-core + * + * Copyright (c) TanStack + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function na(e,t){return typeof e=="function"?e(t):e}function Sr(e,t){return n=>{t.setState(r=>({...r,[e]:na(n,r[e])}))}}function Zg(e){return e instanceof Function}function LY(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function fI(e,t){const n=[],r=s=>{s.forEach(o=>{n.push(o);const a=t(o);a!=null&&a.length&&r(a)})};return r(e),n}function De(e,t,n){let r=[],s;return o=>{let a;n.key&&n.debug&&(a=Date.now());const i=e(o);if(!(i.length!==r.length||i.some((d,p)=>r[p]!==d)))return s;r=i;let l;if(n.key&&n.debug&&(l=Date.now()),s=t(...i),n==null||n.onChange==null||n.onChange(s),n.key&&n.debug&&n!=null&&n.debug()){const d=Math.round((Date.now()-a)*100)/100,p=Math.round((Date.now()-l)*100)/100,f=p/16,h=(g,m)=>{for(g=String(g);g.length{var s;return(s=e==null?void 0:e.debugAll)!=null?s:e[t]},key:!1,onChange:r}}function $Y(e,t,n,r){const s=()=>{var a;return(a=o.getValue())!=null?a:e.options.renderFallbackValue},o={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:s,getContext:De(()=>[e,n,t,o],(a,i,c,l)=>({table:a,column:i,row:c,cell:l,getValue:l.getValue,renderValue:l.renderValue}),Ae(e.options,"debugCells"))};return e._features.forEach(a=>{a.createCell==null||a.createCell(o,n,t,e)},{}),o}function BY(e,t,n,r){var s,o;const i={...e._getDefaultColumnDef(),...t},c=i.accessorKey;let l=(s=(o=i.id)!=null?o:c?typeof String.prototype.replaceAll=="function"?c.replaceAll(".","_"):c.replace(/\./g,"_"):void 0)!=null?s:typeof i.header=="string"?i.header:void 0,d;if(i.accessorFn?d=i.accessorFn:c&&(c.includes(".")?d=f=>{let h=f;for(const m of c.split(".")){var g;h=(g=h)==null?void 0:g[m]}return h}:d=f=>f[i.accessorKey]),!l)throw new Error;let p={id:`${String(l)}`,accessorFn:d,parent:r,depth:n,columnDef:i,columns:[],getFlatColumns:De(()=>[!0],()=>{var f;return[p,...(f=p.columns)==null?void 0:f.flatMap(h=>h.getFlatColumns())]},Ae(e.options,"debugColumns")),getLeafColumns:De(()=>[e._getOrderColumnsFn()],f=>{var h;if((h=p.columns)!=null&&h.length){let g=p.columns.flatMap(m=>m.getLeafColumns());return f(g)}return[p]},Ae(e.options,"debugColumns"))};for(const f of e._features)f.createColumn==null||f.createColumn(p,e);return p}const Nn="debugHeaders";function XC(e,t,n){var r;let o={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const a=[],i=c=>{c.subHeaders&&c.subHeaders.length&&c.subHeaders.map(i),a.push(c)};return i(o),a},getContext:()=>({table:e,header:o,column:t})};return e._features.forEach(a=>{a.createHeader==null||a.createHeader(o,e)}),o}const zY={createTable:e=>{e.getHeaderGroups=De(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,s)=>{var o,a;const i=(o=r==null?void 0:r.map(p=>n.find(f=>f.id===p)).filter(Boolean))!=null?o:[],c=(a=s==null?void 0:s.map(p=>n.find(f=>f.id===p)).filter(Boolean))!=null?a:[],l=n.filter(p=>!(r!=null&&r.includes(p.id))&&!(s!=null&&s.includes(p.id)));return Wf(t,[...i,...l,...c],e)},Ae(e.options,Nn)),e.getCenterHeaderGroups=De(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,s)=>(n=n.filter(o=>!(r!=null&&r.includes(o.id))&&!(s!=null&&s.includes(o.id))),Wf(t,n,e,"center")),Ae(e.options,Nn)),e.getLeftHeaderGroups=De(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var s;const o=(s=r==null?void 0:r.map(a=>n.find(i=>i.id===a)).filter(Boolean))!=null?s:[];return Wf(t,o,e,"left")},Ae(e.options,Nn)),e.getRightHeaderGroups=De(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var s;const o=(s=r==null?void 0:r.map(a=>n.find(i=>i.id===a)).filter(Boolean))!=null?s:[];return Wf(t,o,e,"right")},Ae(e.options,Nn)),e.getFooterGroups=De(()=>[e.getHeaderGroups()],t=>[...t].reverse(),Ae(e.options,Nn)),e.getLeftFooterGroups=De(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),Ae(e.options,Nn)),e.getCenterFooterGroups=De(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),Ae(e.options,Nn)),e.getRightFooterGroups=De(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),Ae(e.options,Nn)),e.getFlatHeaders=De(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),Ae(e.options,Nn)),e.getLeftFlatHeaders=De(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),Ae(e.options,Nn)),e.getCenterFlatHeaders=De(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),Ae(e.options,Nn)),e.getRightFlatHeaders=De(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),Ae(e.options,Nn)),e.getCenterLeafHeaders=De(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Ae(e.options,Nn)),e.getLeftLeafHeaders=De(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Ae(e.options,Nn)),e.getRightLeafHeaders=De(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Ae(e.options,Nn)),e.getLeafHeaders=De(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var s,o,a,i,c,l;return[...(s=(o=t[0])==null?void 0:o.headers)!=null?s:[],...(a=(i=n[0])==null?void 0:i.headers)!=null?a:[],...(c=(l=r[0])==null?void 0:l.headers)!=null?c:[]].map(d=>d.getLeafHeaders()).flat()},Ae(e.options,Nn))}};function Wf(e,t,n,r){var s,o;let a=0;const i=function(f,h){h===void 0&&(h=1),a=Math.max(a,h),f.filter(g=>g.getIsVisible()).forEach(g=>{var m;(m=g.columns)!=null&&m.length&&i(g.columns,h+1)},0)};i(e);let c=[];const l=(f,h)=>{const g={depth:h,id:[r,`${h}`].filter(Boolean).join("_"),headers:[]},m=[];f.forEach(x=>{const b=[...m].reverse()[0],y=x.column.depth===g.depth;let w,S=!1;if(y&&x.column.parent?w=x.column.parent:(w=x.column,S=!0),b&&(b==null?void 0:b.column)===w)b.subHeaders.push(x);else{const E=XC(n,w,{id:[r,h,w.id,x==null?void 0:x.id].filter(Boolean).join("_"),isPlaceholder:S,placeholderId:S?`${m.filter(C=>C.column===w).length}`:void 0,depth:h,index:m.length});E.subHeaders.push(x),m.push(E)}g.headers.push(x),x.headerGroup=g}),c.push(g),h>0&&l(m,h-1)},d=t.map((f,h)=>XC(n,f,{depth:a,index:h}));l(d,a-1),c.reverse();const p=f=>f.filter(g=>g.column.getIsVisible()).map(g=>{let m=0,x=0,b=[0];g.subHeaders&&g.subHeaders.length?(b=[],p(g.subHeaders).forEach(w=>{let{colSpan:S,rowSpan:E}=w;m+=S,b.push(E)})):m=1;const y=Math.min(...b);return x=x+y,g.colSpan=m,g.rowSpan=x,{colSpan:m,rowSpan:x}});return p((s=(o=c[0])==null?void 0:o.headers)!=null?s:[]),c}const Yg=(e,t,n,r,s,o,a)=>{let i={id:t,index:r,original:n,depth:s,parentId:a,_valuesCache:{},_uniqueValuesCache:{},getValue:c=>{if(i._valuesCache.hasOwnProperty(c))return i._valuesCache[c];const l=e.getColumn(c);if(l!=null&&l.accessorFn)return i._valuesCache[c]=l.accessorFn(i.original,r),i._valuesCache[c]},getUniqueValues:c=>{if(i._uniqueValuesCache.hasOwnProperty(c))return i._uniqueValuesCache[c];const l=e.getColumn(c);if(l!=null&&l.accessorFn)return l.columnDef.getUniqueValues?(i._uniqueValuesCache[c]=l.columnDef.getUniqueValues(i.original,r),i._uniqueValuesCache[c]):(i._uniqueValuesCache[c]=[i.getValue(c)],i._uniqueValuesCache[c])},renderValue:c=>{var l;return(l=i.getValue(c))!=null?l:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>fI(i.subRows,c=>c.subRows),getParentRow:()=>i.parentId?e.getRow(i.parentId,!0):void 0,getParentRows:()=>{let c=[],l=i;for(;;){const d=l.getParentRow();if(!d)break;c.push(d),l=d}return c.reverse()},getAllCells:De(()=>[e.getAllLeafColumns()],c=>c.map(l=>$Y(e,i,l,l.id)),Ae(e.options,"debugRows")),_getAllCellsByColumnId:De(()=>[i.getAllCells()],c=>c.reduce((l,d)=>(l[d.column.id]=d,l),{}),Ae(e.options,"debugRows"))};for(let c=0;c{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},pI=(e,t,n)=>{var r;const s=n.toLowerCase();return!!(!((r=e.getValue(t))==null||(r=r.toString())==null||(r=r.toLowerCase())==null)&&r.includes(s))};pI.autoRemove=e=>ls(e);const hI=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};hI.autoRemove=e=>ls(e);const gI=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===(n==null?void 0:n.toLowerCase())};gI.autoRemove=e=>ls(e);const mI=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};mI.autoRemove=e=>ls(e)||!(e!=null&&e.length);const vI=(e,t,n)=>!n.some(r=>{var s;return!((s=e.getValue(t))!=null&&s.includes(r))});vI.autoRemove=e=>ls(e)||!(e!=null&&e.length);const yI=(e,t,n)=>n.some(r=>{var s;return(s=e.getValue(t))==null?void 0:s.includes(r)});yI.autoRemove=e=>ls(e)||!(e!=null&&e.length);const bI=(e,t,n)=>e.getValue(t)===n;bI.autoRemove=e=>ls(e);const xI=(e,t,n)=>e.getValue(t)==n;xI.autoRemove=e=>ls(e);const Bw=(e,t,n)=>{let[r,s]=n;const o=e.getValue(t);return o>=r&&o<=s};Bw.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,s=typeof n!="number"?parseFloat(n):n,o=t===null||Number.isNaN(r)?-1/0:r,a=n===null||Number.isNaN(s)?1/0:s;if(o>a){const i=o;o=a,a=i}return[o,a]};Bw.autoRemove=e=>ls(e)||ls(e[0])&&ls(e[1]);const Xs={includesString:pI,includesStringSensitive:hI,equalsString:gI,arrIncludes:mI,arrIncludesAll:vI,arrIncludesSome:yI,equals:bI,weakEquals:xI,inNumberRange:Bw};function ls(e){return e==null||e===""}const VY={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:Sr("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n==null?void 0:n.getValue(e.id);return typeof r=="string"?Xs.includesString:typeof r=="number"?Xs.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?Xs.equals:Array.isArray(r)?Xs.arrIncludes:Xs.weakEquals},e.getFilterFn=()=>{var n,r;return Zg(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:Xs[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,s;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((s=t.options.enableFilters)!=null?s:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(s=>s.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const s=e.getFilterFn(),o=r==null?void 0:r.find(d=>d.id===e.id),a=na(n,o?o.value:void 0);if(eE(s,a,e)){var i;return(i=r==null?void 0:r.filter(d=>d.id!==e.id))!=null?i:[]}const c={id:e.id,value:a};if(o){var l;return(l=r==null?void 0:r.map(d=>d.id===e.id?c:d))!=null?l:[]}return r!=null&&r.length?[...r,c]:[c]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=s=>{var o;return(o=na(t,s))==null?void 0:o.filter(a=>{const i=n.find(c=>c.id===a.id);if(i){const c=i.getFilterFn();if(eE(c,a.value,i))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function eE(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const HY=(e,t,n)=>n.reduce((r,s)=>{const o=s.getValue(e);return r+(typeof o=="number"?o:0)},0),KY=(e,t,n)=>{let r;return n.forEach(s=>{const o=s.getValue(e);o!=null&&(r>o||r===void 0&&o>=o)&&(r=o)}),r},qY=(e,t,n)=>{let r;return n.forEach(s=>{const o=s.getValue(e);o!=null&&(r=o)&&(r=o)}),r},WY=(e,t,n)=>{let r,s;return n.forEach(o=>{const a=o.getValue(e);a!=null&&(r===void 0?a>=a&&(r=s=a):(r>a&&(r=a),s{let n=0,r=0;if(t.forEach(s=>{let o=s.getValue(e);o!=null&&(o=+o)>=o&&(++n,r+=o)}),n)return r/n},JY=(e,t)=>{if(!t.length)return;const n=t.map(o=>o.getValue(e));if(!LY(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),s=n.sort((o,a)=>o-a);return n.length%2!==0?s[r]:(s[r-1]+s[r])/2},QY=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),ZY=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,YY=(e,t)=>t.length,mv={sum:HY,min:KY,max:qY,extent:WY,mean:GY,median:JY,unique:QY,uniqueCount:ZY,count:YY},XY={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:Sr("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n==null?void 0:n.getValue(e.id);if(typeof r=="number")return mv.sum;if(Object.prototype.toString.call(r)==="[object Date]")return mv.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return Zg(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:mv[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var s;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((s=n.subRows)!=null&&s.length)}}};function eX(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(o=>!t.includes(o.id));return n==="remove"?r:[...t.map(o=>e.find(a=>a.id===o)).filter(Boolean),...r]}const tX={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:Sr("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=De(n=>[Mc(t,n)],n=>n.findIndex(r=>r.id===e.id),Ae(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=Mc(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const s=Mc(t,n);return((r=s[s.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=De(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>s=>{let o=[];if(!(t!=null&&t.length))o=s;else{const a=[...t],i=[...s];for(;i.length&&a.length;){const c=a.shift(),l=i.findIndex(d=>d.id===c);l>-1&&o.push(i.splice(l,1)[0])}o=[...o,...i]}return eX(o,n,r)},Ae(e.options,"debugTable"))}},vv=()=>({left:[],right:[]}),nX={getInitialState:e=>({columnPinning:vv(),...e}),getDefaultOptions:e=>({onColumnPinningChange:Sr("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(s=>s.id).filter(Boolean);t.setColumnPinning(s=>{var o,a;if(n==="right"){var i,c;return{left:((i=s==null?void 0:s.left)!=null?i:[]).filter(p=>!(r!=null&&r.includes(p))),right:[...((c=s==null?void 0:s.right)!=null?c:[]).filter(p=>!(r!=null&&r.includes(p))),...r]}}if(n==="left"){var l,d;return{left:[...((l=s==null?void 0:s.left)!=null?l:[]).filter(p=>!(r!=null&&r.includes(p))),...r],right:((d=s==null?void 0:s.right)!=null?d:[]).filter(p=>!(r!=null&&r.includes(p)))}}return{left:((o=s==null?void 0:s.left)!=null?o:[]).filter(p=>!(r!=null&&r.includes(p))),right:((a=s==null?void 0:s.right)!=null?a:[]).filter(p=>!(r!=null&&r.includes(p)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var s,o,a;return((s=r.columnDef.enablePinning)!=null?s:!0)&&((o=(a=t.options.enableColumnPinning)!=null?a:t.options.enablePinning)!=null?o:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(i=>i.id),{left:r,right:s}=t.getState().columnPinning,o=n.some(i=>r==null?void 0:r.includes(i)),a=n.some(i=>s==null?void 0:s.includes(i));return o?"left":a?"right":!1},e.getPinnedIndex=()=>{var n,r;const s=e.getIsPinned();return s?(n=(r=t.getState().columnPinning)==null||(r=r[s])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=De(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,s)=>{const o=[...r??[],...s??[]];return n.filter(a=>!o.includes(a.column.id))},Ae(t.options,"debugRows")),e.getLeftVisibleCells=De(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(o=>n.find(a=>a.column.id===o)).filter(Boolean).map(o=>({...o,position:"left"})),Ae(t.options,"debugRows")),e.getRightVisibleCells=De(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(o=>n.find(a=>a.column.id===o)).filter(Boolean).map(o=>({...o,position:"right"})),Ae(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?vv():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:vv())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var s,o;return!!((s=r.left)!=null&&s.length||(o=r.right)!=null&&o.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=De(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(s=>s.id===r)).filter(Boolean),Ae(e.options,"debugColumns")),e.getRightLeafColumns=De(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(s=>s.id===r)).filter(Boolean),Ae(e.options,"debugColumns")),e.getCenterLeafColumns=De(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const s=[...n??[],...r??[]];return t.filter(o=>!s.includes(o.id))},Ae(e.options,"debugColumns"))}},Gf={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},yv=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),rX={getDefaultColumnDef:()=>Gf,getInitialState:e=>({columnSizing:{},columnSizingInfo:yv(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:Sr("columnSizing",e),onColumnSizingInfoChange:Sr("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,s;const o=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Gf.minSize,(r=o??e.columnDef.size)!=null?r:Gf.size),(s=e.columnDef.maxSize)!=null?s:Gf.maxSize)},e.getStart=De(n=>[n,Mc(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((s,o)=>s+o.getSize(),0),Ae(t.options,"debugColumns")),e.getAfter=De(n=>[n,Mc(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((s,o)=>s+o.getSize(),0),Ae(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...s}=n;return s})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=s=>{if(s.subHeaders.length)s.subHeaders.forEach(r);else{var o;n+=(o=s.column.getSize())!=null?o:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),s=r==null?void 0:r.getCanResize();return o=>{if(!r||!s||(o.persist==null||o.persist(),bv(o)&&o.touches&&o.touches.length>1))return;const a=e.getSize(),i=e?e.getLeafHeaders().map(b=>[b.column.id,b.column.getSize()]):[[r.id,r.getSize()]],c=bv(o)?Math.round(o.touches[0].clientX):o.clientX,l={},d=(b,y)=>{typeof y=="number"&&(t.setColumnSizingInfo(w=>{var S,E;const C=t.options.columnResizeDirection==="rtl"?-1:1,k=(y-((S=w==null?void 0:w.startOffset)!=null?S:0))*C,T=Math.max(k/((E=w==null?void 0:w.startSize)!=null?E:0),-.999999);return w.columnSizingStart.forEach(O=>{let[M,U]=O;l[M]=Math.round(Math.max(U+U*T,0)*100)/100}),{...w,deltaOffset:k,deltaPercentage:T}}),(t.options.columnResizeMode==="onChange"||b==="end")&&t.setColumnSizing(w=>({...w,...l})))},p=b=>d("move",b),f=b=>{d("end",b),t.setColumnSizingInfo(y=>({...y,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},h=n||typeof document<"u"?document:null,g={moveHandler:b=>p(b.clientX),upHandler:b=>{h==null||h.removeEventListener("mousemove",g.moveHandler),h==null||h.removeEventListener("mouseup",g.upHandler),f(b.clientX)}},m={moveHandler:b=>(b.cancelable&&(b.preventDefault(),b.stopPropagation()),p(b.touches[0].clientX),!1),upHandler:b=>{var y;h==null||h.removeEventListener("touchmove",m.moveHandler),h==null||h.removeEventListener("touchend",m.upHandler),b.cancelable&&(b.preventDefault(),b.stopPropagation()),f((y=b.touches[0])==null?void 0:y.clientX)}},x=sX()?{passive:!1}:!1;bv(o)?(h==null||h.addEventListener("touchmove",m.moveHandler,x),h==null||h.addEventListener("touchend",m.upHandler,x)):(h==null||h.addEventListener("mousemove",g.moveHandler,x),h==null||h.addEventListener("mouseup",g.upHandler,x)),t.setColumnSizingInfo(b=>({...b,startOffset:c,startSize:a,deltaOffset:0,deltaPercentage:0,columnSizingStart:i,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?yv():(n=e.initialState.columnSizingInfo)!=null?n:yv())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0}}};let Jf=null;function sX(){if(typeof Jf=="boolean")return Jf;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Jf=e,Jf}function bv(e){return e.type==="touchstart"}const oX={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:Sr("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const s=e.columns;return(n=s.length?s.some(o=>o.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=De(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),Ae(t.options,"debugRows")),e.getVisibleCells=De(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,s)=>[...n,...r,...s],Ae(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>De(()=>[r(),r().filter(s=>s.getIsVisible()).map(s=>s.id).join("_")],s=>s.filter(o=>o.getIsVisible==null?void 0:o.getIsVisible()),Ae(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((s,o)=>({...s,[o.id]:n||!(o.getCanHide!=null&&o.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function Mc(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const aX={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},iX={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:Sr("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,s,o;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((s=t.options.enableFilters)!=null?s:!0)&&((o=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?o:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>Xs.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return Zg(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:Xs[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},lX={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:Sr("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,s;if(!t){e._queue(()=>{t=!0});return}if((r=(s=e.options.autoResetAll)!=null?s:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var s,o;e.setExpanded(r?{}:(s=(o=e.initialState)==null?void 0:o.expanded)!=null?s:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(s=>!s.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(o=>{const a=o.split(".");r=Math.max(r,a.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var s;const o=r===!0?!0:!!(r!=null&&r[e.id]);let a={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(i=>{a[i]=!0}):a=r,n=(s=n)!=null?s:!o,!o&&n)return{...a,[e.id]:!0};if(o&&!n){const{[e.id]:i,...c}=a;return c}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r!=null&&r[e.id])},e.getCanExpand=()=>{var n,r,s;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((s=e.subRows)!=null&&s.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},Sb=0,Cb=10,xv=()=>({pageIndex:Sb,pageSize:Cb}),uX={getInitialState:e=>({...e,pagination:{...xv(),...e==null?void 0:e.pagination}}),getDefaultOptions:e=>({onPaginationChange:Sr("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,s;if(!t){e._queue(()=>{t=!0});return}if((r=(s=e.options.autoResetAll)!=null?s:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const s=o=>na(r,o);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(s)},e.resetPagination=r=>{var s;e.setPagination(r?xv():(s=e.initialState.pagination)!=null?s:xv())},e.setPageIndex=r=>{e.setPagination(s=>{let o=na(r,s.pageIndex);const a=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return o=Math.max(0,Math.min(o,a)),{...s,pageIndex:o}})},e.resetPageIndex=r=>{var s,o;e.setPageIndex(r?Sb:(s=(o=e.initialState)==null||(o=o.pagination)==null?void 0:o.pageIndex)!=null?s:Sb)},e.resetPageSize=r=>{var s,o;e.setPageSize(r?Cb:(s=(o=e.initialState)==null||(o=o.pagination)==null?void 0:o.pageSize)!=null?s:Cb)},e.setPageSize=r=>{e.setPagination(s=>{const o=Math.max(1,na(r,s.pageSize)),a=s.pageSize*s.pageIndex,i=Math.floor(a/o);return{...s,pageIndex:i,pageSize:o}})},e.setPageCount=r=>e.setPagination(s=>{var o;let a=na(r,(o=e.options.pageCount)!=null?o:-1);return typeof a=="number"&&(a=Math.max(-1,a)),{...s,pageCount:a}}),e.getPageOptions=De(()=>[e.getPageCount()],r=>{let s=[];return r&&r>0&&(s=[...new Array(r)].fill(null).map((o,a)=>a)),s},Ae(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,s=e.getPageCount();return s===-1?!0:s===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},wv=()=>({top:[],bottom:[]}),cX={getInitialState:e=>({rowPinning:wv(),...e}),getDefaultOptions:e=>({onRowPinningChange:Sr("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,s)=>{const o=r?e.getLeafRows().map(c=>{let{id:l}=c;return l}):[],a=s?e.getParentRows().map(c=>{let{id:l}=c;return l}):[],i=new Set([...a,e.id,...o]);t.setRowPinning(c=>{var l,d;if(n==="bottom"){var p,f;return{top:((p=c==null?void 0:c.top)!=null?p:[]).filter(m=>!(i!=null&&i.has(m))),bottom:[...((f=c==null?void 0:c.bottom)!=null?f:[]).filter(m=>!(i!=null&&i.has(m))),...Array.from(i)]}}if(n==="top"){var h,g;return{top:[...((h=c==null?void 0:c.top)!=null?h:[]).filter(m=>!(i!=null&&i.has(m))),...Array.from(i)],bottom:((g=c==null?void 0:c.bottom)!=null?g:[]).filter(m=>!(i!=null&&i.has(m)))}}return{top:((l=c==null?void 0:c.top)!=null?l:[]).filter(m=>!(i!=null&&i.has(m))),bottom:((d=c==null?void 0:c.bottom)!=null?d:[]).filter(m=>!(i!=null&&i.has(m)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:s}=t.options;return typeof r=="function"?r(e):(n=r??s)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:s}=t.getState().rowPinning,o=n.some(i=>r==null?void 0:r.includes(i)),a=n.some(i=>s==null?void 0:s.includes(i));return o?"top":a?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const s=e.getIsPinned();if(!s)return-1;const o=(n=s==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(a=>{let{id:i}=a;return i});return(r=o==null?void 0:o.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?wv():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:wv())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var s,o;return!!((s=r.top)!=null&&s.length||(o=r.bottom)!=null&&o.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var s;return((s=e.options.keepPinnedRows)==null||s?(n??[]).map(a=>{const i=e.getRow(a,!0);return i.getIsAllParentsExpanded()?i:null}):(n??[]).map(a=>t.find(i=>i.id===a))).filter(Boolean).map(a=>({...a,position:r}))},e.getTopRows=De(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),Ae(e.options,"debugRows")),e.getBottomRows=De(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),Ae(e.options,"debugRows")),e.getCenterRows=De(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const s=new Set([...n??[],...r??[]]);return t.filter(o=>!s.has(o.id))},Ae(e.options,"debugRows"))}},dX={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:Sr("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},s=e.getPreGroupedRowModel().flatRows;return t?s.forEach(o=>{o.getCanSelect()&&(r[o.id]=!0)}):s.forEach(o=>{delete r[o.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),s={...n};return e.getRowModel().rows.forEach(o=>{Eb(s,o.id,r,!0,e)}),s}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=De(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?Sv(e,n):{rows:[],flatRows:[],rowsById:{}},Ae(e.options,"debugTable")),e.getFilteredSelectedRowModel=De(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?Sv(e,n):{rows:[],flatRows:[],rowsById:{}},Ae(e.options,"debugTable")),e.getGroupedSelectedRowModel=De(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?Sv(e,n):{rows:[],flatRows:[],rowsById:{}},Ae(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(s=>s.getCanSelect()&&!n[s.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(s=>s.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(s=>!n[s.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const s=e.getIsSelected();t.setRowSelection(o=>{var a;if(n=typeof n<"u"?n:!s,e.getCanSelect()&&s===n)return o;const i={...o};return Eb(i,e.id,n,(a=r==null?void 0:r.selectChildren)!=null?a:!0,t),i})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return zw(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return Tb(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return Tb(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var s;n&&e.toggleSelected((s=r.target)==null?void 0:s.checked)}}}},Eb=(e,t,n,r,s)=>{var o;const a=s.getRow(t,!0);n?(a.getCanMultiSelect()||Object.keys(e).forEach(i=>delete e[i]),a.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(o=a.subRows)!=null&&o.length&&a.getCanSelectSubRows()&&a.subRows.forEach(i=>Eb(e,i.id,n,r,s))};function Sv(e,t){const n=e.getState().rowSelection,r=[],s={},o=function(a,i){return a.map(c=>{var l;const d=zw(c,n);if(d&&(r.push(c),s[c.id]=c),(l=c.subRows)!=null&&l.length&&(c={...c,subRows:o(c.subRows)}),d)return c}).filter(Boolean)};return{rows:o(t.rows),flatRows:r,rowsById:s}}function zw(e,t){var n;return(n=t[e.id])!=null?n:!1}function Tb(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let s=!0,o=!1;return e.subRows.forEach(a=>{if(!(o&&!s)&&(a.getCanSelect()&&(zw(a,t)?o=!0:s=!1),a.subRows&&a.subRows.length)){const i=Tb(a,t);i==="all"?o=!0:(i==="some"&&(o=!0),s=!1)}}),s?"all":o?"some":!1}const kb=/([0-9]+)/gm,fX=(e,t,n)=>wI(Sa(e.getValue(n)).toLowerCase(),Sa(t.getValue(n)).toLowerCase()),pX=(e,t,n)=>wI(Sa(e.getValue(n)),Sa(t.getValue(n))),hX=(e,t,n)=>Uw(Sa(e.getValue(n)).toLowerCase(),Sa(t.getValue(n)).toLowerCase()),gX=(e,t,n)=>Uw(Sa(e.getValue(n)),Sa(t.getValue(n))),mX=(e,t,n)=>{const r=e.getValue(n),s=t.getValue(n);return r>s?1:rUw(e.getValue(n),t.getValue(n));function Uw(e,t){return e===t?0:e>t?1:-1}function Sa(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function wI(e,t){const n=e.split(kb).filter(Boolean),r=t.split(kb).filter(Boolean);for(;n.length&&r.length;){const s=n.shift(),o=r.shift(),a=parseInt(s,10),i=parseInt(o,10),c=[a,i].sort();if(isNaN(c[0])){if(s>o)return 1;if(o>s)return-1;continue}if(isNaN(c[1]))return isNaN(a)?-1:1;if(a>i)return 1;if(i>a)return-1}return n.length-r.length}const rc={alphanumeric:fX,alphanumericCaseSensitive:pX,text:hX,textCaseSensitive:gX,datetime:mX,basic:vX},yX={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:Sr("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const s of n){const o=s==null?void 0:s.getValue(e.id);if(Object.prototype.toString.call(o)==="[object Date]")return rc.datetime;if(typeof o=="string"&&(r=!0,o.split(kb).length>1))return rc.alphanumeric}return r?rc.text:rc.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof(n==null?void 0:n.getValue(e.id))=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return Zg(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:rc[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const s=e.getNextSortingOrder(),o=typeof n<"u"&&n!==null;t.setSorting(a=>{const i=a==null?void 0:a.find(h=>h.id===e.id),c=a==null?void 0:a.findIndex(h=>h.id===e.id);let l=[],d,p=o?n:s==="desc";if(a!=null&&a.length&&e.getCanMultiSort()&&r?i?d="toggle":d="add":a!=null&&a.length&&c!==a.length-1?d="replace":i?d="toggle":d="replace",d==="toggle"&&(o||s||(d="remove")),d==="add"){var f;l=[...a,{id:e.id,desc:p}],l.splice(0,l.length-((f=t.options.maxMultiSortColCount)!=null?f:Number.MAX_SAFE_INTEGER))}else d==="toggle"?l=a.map(h=>h.id===e.id?{...h,desc:p}:h):d==="remove"?l=a.filter(h=>h.id!==e.id):l=[{id:e.id,desc:p}];return l})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,s;const o=e.getFirstSortDir(),a=e.getIsSorted();return a?a!==o&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(s=t.options.enableMultiRemove)!=null)||s)?!1:a==="desc"?"asc":"desc":o},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(s=>s.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(s=>s.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},bX=[zY,oX,tX,nX,UY,VY,aX,iX,yX,XY,lX,uX,cX,dX,rX];function xX(e){var t,n;const r=[...bX,...(t=e._features)!=null?t:[]];let s={_features:r};const o=s._features.reduce((f,h)=>Object.assign(f,h.getDefaultOptions==null?void 0:h.getDefaultOptions(s)),{}),a=f=>s.options.mergeOptions?s.options.mergeOptions(o,f):{...o,...f};let c={...{},...(n=e.initialState)!=null?n:{}};s._features.forEach(f=>{var h;c=(h=f.getInitialState==null?void 0:f.getInitialState(c))!=null?h:c});const l=[];let d=!1;const p={_features:r,options:{...o,...e},initialState:c,_queue:f=>{l.push(f),d||(d=!0,Promise.resolve().then(()=>{for(;l.length;)l.shift()();d=!1}).catch(h=>setTimeout(()=>{throw h})))},reset:()=>{s.setState(s.initialState)},setOptions:f=>{const h=na(f,s.options);s.options=a(h)},getState:()=>s.options.state,setState:f=>{s.options.onStateChange==null||s.options.onStateChange(f)},_getRowId:(f,h,g)=>{var m;return(m=s.options.getRowId==null?void 0:s.options.getRowId(f,h,g))!=null?m:`${g?[g.id,h].join("."):h}`},getCoreRowModel:()=>(s._getCoreRowModel||(s._getCoreRowModel=s.options.getCoreRowModel(s)),s._getCoreRowModel()),getRowModel:()=>s.getPaginationRowModel(),getRow:(f,h)=>{let g=(h?s.getPrePaginationRowModel():s.getRowModel()).rowsById[f];if(!g&&(g=s.getCoreRowModel().rowsById[f],!g))throw new Error;return g},_getDefaultColumnDef:De(()=>[s.options.defaultColumn],f=>{var h;return f=(h=f)!=null?h:{},{header:g=>{const m=g.header.column.columnDef;return m.accessorKey?m.accessorKey:m.accessorFn?m.id:null},cell:g=>{var m,x;return(m=(x=g.renderValue())==null||x.toString==null?void 0:x.toString())!=null?m:null},...s._features.reduce((g,m)=>Object.assign(g,m.getDefaultColumnDef==null?void 0:m.getDefaultColumnDef()),{}),...f}},Ae(e,"debugColumns")),_getColumnDefs:()=>s.options.columns,getAllColumns:De(()=>[s._getColumnDefs()],f=>{const h=function(g,m,x){return x===void 0&&(x=0),g.map(b=>{const y=BY(s,b,x,m),w=b;return y.columns=w.columns?h(w.columns,y,x+1):[],y})};return h(f)},Ae(e,"debugColumns")),getAllFlatColumns:De(()=>[s.getAllColumns()],f=>f.flatMap(h=>h.getFlatColumns()),Ae(e,"debugColumns")),_getAllFlatColumnsById:De(()=>[s.getAllFlatColumns()],f=>f.reduce((h,g)=>(h[g.id]=g,h),{}),Ae(e,"debugColumns")),getAllLeafColumns:De(()=>[s.getAllColumns(),s._getOrderColumnsFn()],(f,h)=>{let g=f.flatMap(m=>m.getLeafColumns());return h(g)},Ae(e,"debugColumns")),getColumn:f=>s._getAllFlatColumnsById()[f]};Object.assign(s,p);for(let f=0;fDe(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(s,o,a){o===void 0&&(o=0);const i=[];for(let l=0;le._autoResetPageIndex()))}function SX(e,t,n){return n.options.filterFromLeafRows?CX(e,t,n):EX(e,t,n)}function CX(e,t,n){var r;const s=[],o={},a=(r=n.options.maxLeafRowFilterDepth)!=null?r:100,i=function(c,l){l===void 0&&(l=0);const d=[];for(let f=0;fDe(()=>[e.getPreFilteredRowModel(),e.getState().columnFilters,e.getState().globalFilter],(t,n,r)=>{if(!t.rows.length||!(n!=null&&n.length)&&!r){for(let f=0;f{var h;const g=e.getColumn(f.id);if(!g)return;const m=g.getFilterFn();m&&s.push({id:f.id,filterFn:m,resolvedValue:(h=m.resolveFilterValue==null?void 0:m.resolveFilterValue(f.value))!=null?h:f.value})});const a=(n??[]).map(f=>f.id),i=e.getGlobalFilterFn(),c=e.getAllLeafColumns().filter(f=>f.getCanGlobalFilter());r&&i&&c.length&&(a.push("__global__"),c.forEach(f=>{var h;o.push({id:f.id,filterFn:i,resolvedValue:(h=i.resolveFilterValue==null?void 0:i.resolveFilterValue(r))!=null?h:r})}));let l,d;for(let f=0;f{h.columnFiltersMeta[m]=x})}if(o.length){for(let g=0;g{h.columnFiltersMeta[m]=x})){h.columnFilters.__global__=!0;break}}h.columnFilters.__global__!==!0&&(h.columnFilters.__global__=!1)}}const p=f=>{for(let h=0;he._autoResetPageIndex()))}function kX(){return e=>De(()=>[e.getState().grouping,e.getPreGroupedRowModel()],(t,n)=>{if(!n.rows.length||!t.length)return n.rows.forEach(c=>{c.depth=0,c.parentId=void 0}),n;const r=t.filter(c=>e.getColumn(c)),s=[],o={},a=function(c,l,d){if(l===void 0&&(l=0),l>=r.length)return c.map(g=>(g.depth=l,s.push(g),o[g.id]=g,g.subRows&&(g.subRows=a(g.subRows,l+1,g.id)),g));const p=r[l],f=_X(c,p);return Array.from(f.entries()).map((g,m)=>{let[x,b]=g,y=`${p}:${x}`;y=d?`${d}>${y}`:y;const w=a(b,l+1,y);w.forEach(C=>{C.parentId=y});const S=l?fI(b,C=>C.subRows):b,E=Yg(e,y,S[0].original,m,l,void 0,d);return Object.assign(E,{groupingColumnId:p,groupingValue:x,subRows:w,leafRows:S,getValue:C=>{if(r.includes(C)){if(E._valuesCache.hasOwnProperty(C))return E._valuesCache[C];if(b[0]){var k;E._valuesCache[C]=(k=b[0].getValue(C))!=null?k:void 0}return E._valuesCache[C]}if(E._groupingValuesCache.hasOwnProperty(C))return E._groupingValuesCache[C];const T=e.getColumn(C),O=T==null?void 0:T.getAggregationFn();if(O)return E._groupingValuesCache[C]=O(C,S,b),E._groupingValuesCache[C]}}),w.forEach(C=>{s.push(C),o[C.id]=C}),E})},i=a(n.rows,0);return i.forEach(c=>{s.push(c),o[c.id]=c}),{rows:i,flatRows:s,rowsById:o}},Ae(e.options,"debugTable","getGroupedRowModel",()=>{e._queue(()=>{e._autoResetExpanded(),e._autoResetPageIndex()})}))}function _X(e,t){const n=new Map;return e.reduce((r,s)=>{const o=`${s.getGroupingValue(t)}`,a=r.get(o);return a?a.push(s):r.set(o,[s]),r},n)}function jX(){return e=>De(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,s=[],o=r.filter(c=>{var l;return(l=e.getColumn(c.id))==null?void 0:l.getCanSort()}),a={};o.forEach(c=>{const l=e.getColumn(c.id);l&&(a[c.id]={sortUndefined:l.columnDef.sortUndefined,invertSorting:l.columnDef.invertSorting,sortingFn:l.getSortingFn()})});const i=c=>{const l=c.map(d=>({...d}));return l.sort((d,p)=>{for(let h=0;h{var p;s.push(d),(p=d.subRows)!=null&&p.length&&(d.subRows=i(d.subRows))}),l};return{rows:i(n.rows),flatRows:s,rowsById:n.rowsById}},Ae(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}/** + * react-table + * + * Copyright (c) TanStack + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function tE(e,t){return e?RX(e)?v.createElement(e,t):e:null}function RX(e){return OX(e)||typeof e=="function"||NX(e)}function OX(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function NX(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function PX(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=v.useState(()=>({current:xX(t)})),[r,s]=v.useState(()=>n.current.initialState);return n.current.setOptions(o=>({...o,...e,state:{...r,...e.state},onStateChange:a=>{s(a),e.onStateChange==null||e.onStateChange(a)}})),n.current}const SI=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{className:"relative w-full overflow-auto",children:u.jsx("table",{ref:n,className:ge("w-full caption-bottom text-sm",e),...t})}));SI.displayName="Table";const CI=v.forwardRef(({className:e,...t},n)=>u.jsx("thead",{ref:n,className:ge("[&_tr]:border-b",e),...t}));CI.displayName="TableHeader";const EI=v.forwardRef(({className:e,...t},n)=>u.jsx("tbody",{ref:n,className:ge("[&_tr:last-child]:border-0",e),...t}));EI.displayName="TableBody";const MX=v.forwardRef(({className:e,...t},n)=>u.jsx("tfoot",{ref:n,className:ge("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",e),...t}));MX.displayName="TableFooter";const vc=v.forwardRef(({className:e,...t},n)=>u.jsx("tr",{ref:n,className:ge("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",e),...t}));vc.displayName="TableRow";const TI=v.forwardRef(({className:e,...t},n)=>u.jsx("th",{ref:n,className:ge("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",e),...t}));TI.displayName="TableHead";const Ep=v.forwardRef(({className:e,...t},n)=>u.jsx("td",{ref:n,className:ge("p-4 align-middle [&:has([role=checkbox])]:pr-0",e),...t}));Ep.displayName="TableCell";const IX=v.forwardRef(({className:e,...t},n)=>u.jsx("caption",{ref:n,className:ge("mt-4 text-sm text-muted-foreground",e),...t}));IX.displayName="TableCaption";function Mu({columns:e,data:t,isLoading:n,loadingMessage:r,noResultsMessage:s,enableHeaders:o=!0,className:a,highlightedRows:i,...c}){var d;const l=PX({...c,data:t,columns:e,getCoreRowModel:wX(),getFilteredRowModel:TX(),getGroupedRowModel:kX(),getSortedRowModel:jX()});return u.jsx("div",{className:ge("rounded-md border",a),children:u.jsxs(SI,{children:[o&&u.jsx(CI,{children:l.getHeaderGroups().map(p=>u.jsx(vc,{children:p.headers.map(f=>u.jsx(TI,{children:f.isPlaceholder?null:tE(f.column.columnDef.header,f.getContext())},f.id))},p.id))}),u.jsx(EI,{children:n?u.jsx(vc,{children:u.jsx(Ep,{colSpan:e.length,className:"h-24 text-center text-muted-foreground",children:r??"Carregando..."})}):u.jsx(u.Fragment,{children:(d=l.getRowModel().rows)!=null&&d.length?l.getRowModel().rows.map(p=>u.jsx(vc,{"data-state":p.getIsSelected()?"selected":i!=null&&i.includes(p.id)?"highlighted":"",children:p.getVisibleCells().map(f=>u.jsx(Ep,{children:tE(f.column.columnDef.cell,f.getContext())},f.id))},p.id)):u.jsx(vc,{children:u.jsx(Ep,{colSpan:e.length,className:"h-24 text-center",children:s??"Nenhum resultado encontrado!"})})})})]})})}const DX=e=>["dify","fetchSessions",JSON.stringify(e)],AX=async({difyId:e,instanceName:t})=>(await he.get(`/dify/fetchSessions/${e}/${t}`)).data,FX=e=>{const{difyId:t,instanceName:n,...r}=e;return lt({...r,queryKey:DX({difyId:t,instanceName:n}),queryFn:()=>AX({difyId:t,instanceName:n}),enabled:!!n&&!!t&&(e.enabled??!0),staleTime:1e3*10})};function kI({difyId:e}){const{t}=ze(),{instance:n}=nt(),{changeStatusDify:r}=Qg(),[s,o]=v.useState([]),{data:a,refetch:i}=FX({difyId:e,instanceName:n==null?void 0:n.name}),[c,l]=v.useState(!1),[d,p]=v.useState("");function f(){i()}const h=async(m,x)=>{var b,y,w;try{if(!n)return;await r({instanceName:n.name,token:n.token,remoteJid:m,status:x}),X.success(t("dify.toast.success.status")),f()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},g=[{accessorKey:"remoteJid",header:()=>u.jsx("div",{className:"text-center",children:t("dify.sessions.table.remoteJid")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>u.jsx("div",{className:"text-center",children:t("dify.sessions.table.pushName")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>u.jsx("div",{className:"text-center",children:t("dify.sessions.table.sessionId")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>u.jsx("div",{className:"text-center",children:t("dify.sessions.table.status")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(K,{variant:"ghost",className:"h-8 w-8 p-0",children:[u.jsx("span",{className:"sr-only",children:t("dify.sessions.table.actions.title")}),u.jsx(vu,{className:"h-4 w-4"})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(Ai,{children:t("dify.sessions.table.actions.title")}),u.jsx(Oa,{}),x.status!=="opened"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"opened"),children:[u.jsx(qd,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"paused"),children:[u.jsx(Kd,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.pause")]}),x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"closed"),children:[u.jsx(Ud,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.close")]}),u.jsxs(ft,{onClick:()=>h(x.remoteJid,"delete"),children:[u.jsx(Vd,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.delete")]})]})]})}}];return u.jsxs(Tt,{open:c,onOpenChange:l,children:[u.jsx(Mt,{asChild:!0,children:u.jsxs(K,{variant:"secondary",size:"sm",children:[u.jsx(Hd,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("dify.sessions.label")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("dify.sessions.label")})}),u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[u.jsx(Q,{placeholder:t("dify.sessions.search"),value:d,onChange:m=>p(m.target.value)}),u.jsx(K,{variant:"outline",onClick:f,size:"icon",children:u.jsx(Wd,{})})]}),u.jsx(Mu,{columns:g,data:a??[],onSortingChange:o,state:{sorting:s,globalFilter:d},onGlobalFilterChange:p,enableGlobalFilter:!0,noResultsMessage:t("dify.sessions.table.none")})]})]})]})}const LX=_.object({enabled:_.boolean(),description:_.string(),botType:_.string(),apiUrl:_.string(),apiKey:_.string(),triggerType:_.string(),triggerOperator:_.string().optional(),triggerValue:_.string().optional(),expire:_.coerce.number().optional(),keywordFinish:_.string().optional(),delayMessage:_.coerce.number().optional(),unknownMessage:_.string().optional(),listeningFromMe:_.boolean().optional(),stopBotFromMe:_.boolean().optional(),keepOpen:_.boolean().optional(),debounceTime:_.coerce.number().optional()});function _I({initialData:e,onSubmit:t,handleDelete:n,difyId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:i=()=>{}}){const{t:c}=ze(),l=sn({resolver:on(LX),defaultValues:e||{enabled:!0,description:"",botType:"chatBot",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}}),d=l.watch("triggerType");return u.jsx(Tr,{...l,children:u.jsxs("form",{onSubmit:l.handleSubmit(t),className:"w-full space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsx(Pe,{name:"enabled",label:c("dify.form.enabled.label"),reverse:!0}),u.jsx(Z,{name:"description",label:c("dify.form.description.label"),required:!0,children:u.jsx(Q,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("dify.form.difySettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"botType",label:c("dify.form.botType.label"),options:[{label:c("dify.form.botType.chatBot"),value:"chatBot"},{label:c("dify.form.botType.textGenerator"),value:"textGenerator"},{label:c("dify.form.botType.agent"),value:"agent"},{label:c("dify.form.botType.workflow"),value:"workflow"}]}),u.jsx(Z,{name:"apiUrl",label:c("dify.form.apiUrl.label"),required:!0,children:u.jsx(Q,{})}),u.jsx(Z,{name:"apiKey",label:c("dify.form.apiKey.label"),required:!0,children:u.jsx(Q,{type:"password"})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("dify.form.triggerSettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"triggerType",label:c("dify.form.triggerType.label"),options:[{label:c("dify.form.triggerType.keyword"),value:"keyword"},{label:c("dify.form.triggerType.all"),value:"all"},{label:c("dify.form.triggerType.advanced"),value:"advanced"},{label:c("dify.form.triggerType.none"),value:"none"}]}),d==="keyword"&&u.jsxs(u.Fragment,{children:[u.jsx(Qt,{name:"triggerOperator",label:c("dify.form.triggerOperator.label"),options:[{label:c("dify.form.triggerOperator.contains"),value:"contains"},{label:c("dify.form.triggerOperator.equals"),value:"equals"},{label:c("dify.form.triggerOperator.startsWith"),value:"startsWith"},{label:c("dify.form.triggerOperator.endsWith"),value:"endsWith"},{label:c("dify.form.triggerOperator.regex"),value:"regex"}]}),u.jsx(Z,{name:"triggerValue",label:c("dify.form.triggerValue.label"),children:u.jsx(Q,{})})]}),d==="advanced"&&u.jsx(Z,{name:"triggerValue",label:c("dify.form.triggerConditions.label"),children:u.jsx(Q,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("dify.form.generalSettings.label")}),u.jsx($t,{})]}),u.jsx(Z,{name:"expire",label:c("dify.form.expire.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"keywordFinish",label:c("dify.form.keywordFinish.label"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"delayMessage",label:c("dify.form.delayMessage.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"unknownMessage",label:c("dify.form.unknownMessage.label"),children:u.jsx(Q,{})}),u.jsx(Pe,{name:"listeningFromMe",label:c("dify.form.listeningFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"stopBotFromMe",label:c("dify.form.stopBotFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"keepOpen",label:c("dify.form.keepOpen.label"),reverse:!0}),u.jsx(Z,{name:"debounceTime",label:c("dify.form.debounceTime.label"),children:u.jsx(Q,{type:"number"})})]}),s&&u.jsx(rn,{children:u.jsx(K,{disabled:o,type:"submit",children:c(o?"dify.button.saving":"dify.button.save")})}),!s&&u.jsxs("div",{children:[u.jsx(kI,{difyId:r}),u.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[u.jsxs(Tt,{open:a,onOpenChange:i,children:[u.jsx(Mt,{asChild:!0,children:u.jsx(K,{variant:"destructive",size:"sm",children:c("dify.button.delete")})}),u.jsx(xt,{children:u.jsxs(wt,{children:[u.jsx(Ut,{children:c("modal.delete.title")}),u.jsx(Fi,{children:c("modal.delete.messageSingle")}),u.jsxs(rn,{children:[u.jsx(K,{size:"sm",variant:"outline",onClick:()=>i(!1),children:c("button.cancel")}),u.jsx(K,{variant:"destructive",onClick:n,children:c("button.delete")})]})]})})]}),u.jsx(K,{disabled:o,type:"submit",children:c(o?"dify.button.saving":"dify.button.update")})]})]})]})})}function $X({resetTable:e}){const{t}=ze(),{instance:n}=nt(),[r,s]=v.useState(!1),[o,a]=v.useState(!1),{createDify:i}=Qg(),c=async l=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");s(!0);const h={enabled:l.enabled,description:l.description,botType:l.botType,apiUrl:l.apiUrl,apiKey:l.apiKey,triggerType:l.triggerType,triggerOperator:l.triggerOperator||"",triggerValue:l.triggerValue||"",expire:l.expire||0,keywordFinish:l.keywordFinish||"",delayMessage:l.delayMessage||0,unknownMessage:l.unknownMessage||"",listeningFromMe:l.listeningFromMe||!1,stopBotFromMe:l.stopBotFromMe||!1,keepOpen:l.keepOpen||!1,debounceTime:l.debounceTime||0};await i({instanceName:n.name,token:n.token,data:h}),X.success(t("dify.toast.success.create")),a(!1),e()}catch(h){console.error("Error:",h),X.error(`Error: ${(f=(p=(d=h==null?void 0:h.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{s(!1)}};return u.jsxs(Tt,{open:o,onOpenChange:a,children:[u.jsx(Mt,{asChild:!0,children:u.jsxs(K,{size:"sm",children:[u.jsx(Mi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("dify.button.create")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("dify.form.title")})}),u.jsx(_I,{onSubmit:c,isModal:!0,isLoading:r})]})]})}const BX=e=>["dify","getDify",JSON.stringify(e)],zX=async({difyId:e,instanceName:t})=>(await he.get(`/dify/fetch/${e}/${t}`)).data,UX=e=>{const{difyId:t,instanceName:n,...r}=e;return lt({...r,queryKey:BX({difyId:t,instanceName:n}),queryFn:()=>zX({difyId:t,instanceName:n}),enabled:!!n&&!!t&&(e.enabled??!0)})};function VX({difyId:e,resetTable:t}){const{t:n}=ze(),{instance:r}=nt(),s=An(),[o,a]=v.useState(!1),{deleteDify:i,updateDify:c}=Qg(),{data:l,isLoading:d}=UX({difyId:e,instanceName:r==null?void 0:r.name}),p=v.useMemo(()=>({enabled:!!(l!=null&&l.enabled),description:(l==null?void 0:l.description)??"",botType:(l==null?void 0:l.botType)??"",apiUrl:(l==null?void 0:l.apiUrl)??"",apiKey:(l==null?void 0:l.apiKey)??"",triggerType:(l==null?void 0:l.triggerType)??"",triggerOperator:(l==null?void 0:l.triggerOperator)??"",triggerValue:(l==null?void 0:l.triggerValue)??"",expire:(l==null?void 0:l.expire)??0,keywordFinish:(l==null?void 0:l.keywordFinish)??"",delayMessage:(l==null?void 0:l.delayMessage)??0,unknownMessage:(l==null?void 0:l.unknownMessage)??"",listeningFromMe:!!(l!=null&&l.listeningFromMe),stopBotFromMe:!!(l!=null&&l.stopBotFromMe),keepOpen:!!(l!=null&&l.keepOpen),debounceTime:(l==null?void 0:l.debounceTime)??0}),[l==null?void 0:l.apiKey,l==null?void 0:l.apiUrl,l==null?void 0:l.botType,l==null?void 0:l.debounceTime,l==null?void 0:l.delayMessage,l==null?void 0:l.description,l==null?void 0:l.enabled,l==null?void 0:l.expire,l==null?void 0:l.keepOpen,l==null?void 0:l.keywordFinish,l==null?void 0:l.listeningFromMe,l==null?void 0:l.stopBotFromMe,l==null?void 0:l.triggerOperator,l==null?void 0:l.triggerType,l==null?void 0:l.triggerValue,l==null?void 0:l.unknownMessage]),f=async g=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:g.enabled,description:g.description,botType:g.botType,apiUrl:g.apiUrl,apiKey:g.apiKey,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire||0,keywordFinish:g.keywordFinish||"",delayMessage:g.delayMessage||1e3,unknownMessage:g.unknownMessage||"",listeningFromMe:g.listeningFromMe||!1,stopBotFromMe:g.stopBotFromMe||!1,keepOpen:g.keepOpen||!1,debounceTime:g.debounceTime||0};await c({instanceName:r.name,difyId:e,data:y}),X.success(n("dify.toast.success.update")),t(),s(`/manager/instance/${r.id}/dify/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),X.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},h=async()=>{try{r&&r.name&&e?(await i({instanceName:r.name,difyId:e}),X.success(n("dify.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/dify`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir dify:",g)}};return d?u.jsx(wr,{}):u.jsx("div",{className:"m-4",children:u.jsx(_I,{initialData:p,onSubmit:f,difyId:e,handleDelete:h,isModal:!1,isLoading:d,openDeletionDialog:o,setOpenDeletionDialog:a})})}function nE(){const{t:e}=ze(),t=Pu("(min-width: 768px)"),{instance:n}=nt(),{difyId:r}=So(),{data:s,refetch:o,isLoading:a}=dI({instanceName:n==null?void 0:n.name}),i=An(),c=d=>{n&&i(`/manager/instance/${n.id}/dify/${d}`)},l=()=>{o()};return u.jsxs("main",{className:"pt-5",children:[u.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[u.jsx("h3",{className:"text-lg font-medium",children:e("dify.title")}),u.jsxs("div",{className:"flex items-center justify-end gap-2",children:[u.jsx(kI,{}),u.jsx(FY,{}),u.jsx($X,{resetTable:l})]})]}),u.jsx($t,{className:"my-4"}),u.jsxs(Ou,{direction:t?"horizontal":"vertical",children:[u.jsx(Ur,{defaultSize:35,className:"pr-4",children:u.jsx("div",{className:"flex flex-col gap-3",children:a?u.jsx(wr,{}):u.jsx(u.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>u.jsxs(K,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>c(`${d.id}`),variant:r===d.id?"secondary":"outline",children:[u.jsx("h4",{className:"text-base",children:d.description||d.id}),u.jsx("p",{className:"text-sm font-normal text-muted-foreground",children:d.botType})]},d.id)):u.jsx(K,{variant:"link",children:e("dify.table.none")})})})}),r&&u.jsxs(u.Fragment,{children:[u.jsx(Nu,{withHandle:!0,className:"border border-border"}),u.jsx(Ur,{children:u.jsx(VX,{difyId:r,resetTable:l})})]})]})]})}const HX=e=>["evolutionBot","findEvolutionBot",JSON.stringify(e)],KX=async({instanceName:e,token:t})=>(await he.get(`/evolutionBot/find/${e}`,{headers:{apiKey:t}})).data,jI=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:HX({instanceName:t}),queryFn:()=>KX({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},qX=e=>["evolutionBot","fetchDefaultSettings",JSON.stringify(e)],WX=async({instanceName:e,token:t})=>{const n=await he.get(`/evolutionBot/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},GX=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:qX({instanceName:t}),queryFn:()=>WX({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},JX=async({instanceName:e,token:t,data:n})=>(await he.post(`/evolutionBot/create/${e}`,n,{headers:{apikey:t}})).data,QX=async({instanceName:e,token:t,evolutionBotId:n,data:r})=>(await he.put(`/evolutionBot/update/${n}/${e}`,r,{headers:{apikey:t}})).data,ZX=async({instanceName:e,evolutionBotId:t})=>(await he.delete(`/evolutionBot/delete/${t}/${e}`)).data,YX=async({instanceName:e,token:t,data:n})=>(await he.post(`/evolutionBot/settings/${e}`,n,{headers:{apikey:t}})).data,XX=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await he.post(`/evolutionBot/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function Xg(){const e=Ye(YX,{invalidateKeys:[["evolutionBot","fetchDefaultSettings"]]}),t=Ye(XX,{invalidateKeys:[["evolutionBot","getEvolutionBot"],["evolutionBot","fetchSessions"]]}),n=Ye(ZX,{invalidateKeys:[["evolutionBot","getEvolutionBot"],["evolutionBot","findEvolutionBot"],["evolutionBot","fetchSessions"]]}),r=Ye(QX,{invalidateKeys:[["evolutionBot","getEvolutionBot"],["evolutionBot","findEvolutionBot"],["evolutionBot","fetchSessions"]]}),s=Ye(JX,{invalidateKeys:[["evolutionBot","findEvolutionBot"]]});return{setDefaultSettingsEvolutionBot:e,changeStatusEvolutionBot:t,deleteEvolutionBot:n,updateEvolutionBot:r,createEvolutionBot:s}}const eee=_.object({expire:_.string(),keywordFinish:_.string(),delayMessage:_.string(),unknownMessage:_.string(),listeningFromMe:_.boolean(),stopBotFromMe:_.boolean(),keepOpen:_.boolean(),debounceTime:_.string(),ignoreJids:_.array(_.string()).default([]),botIdFallback:_.union([_.null(),_.string()]).optional()});function tee(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{data:s,refetch:o}=GX({instanceName:t==null?void 0:t.name,enabled:n}),{data:a,refetch:i}=jI({instanceName:t==null?void 0:t.name,enabled:n}),{setDefaultSettingsEvolutionBot:c}=Xg(),l=sn({resolver:on(eee),defaultValues:{expire:"0",keywordFinish:e("evolutionBot.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("evolutionBot.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],botIdFallback:void 0}});v.useEffect(()=>{s&&l.reset({expire:s!=null&&s.expire?s.expire.toString():"0",keywordFinish:s.keywordFinish,delayMessage:s.delayMessage?s.delayMessage.toString():"0",unknownMessage:s.unknownMessage,listeningFromMe:s.listeningFromMe,stopBotFromMe:s.stopBotFromMe,keepOpen:s.keepOpen,debounceTime:s.debounceTime?s.debounceTime.toString():"0",ignoreJids:s.ignoreJids,botIdFallback:s.botIdFallback})},[s]);const d=async f=>{var h,g,m;try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),botIdFallback:f.botIdFallback||void 0,ignoreJids:f.ignoreJids};await c({instanceName:t.name,token:t.token,data:x}),X.success(e("evolutionBot.toast.defaultSettings.success"))}catch(x){console.error("Error:",x),X.error(`Error: ${(m=(g=(h=x==null?void 0:x.response)==null?void 0:h.data)==null?void 0:g.response)==null?void 0:m.message}`)}};function p(){o(),i()}return u.jsxs(Tt,{open:n,onOpenChange:r,children:[u.jsx(Mt,{asChild:!0,children:u.jsxs(K,{variant:"secondary",size:"sm",children:[u.jsx(Pi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:e("evolutionBot.defaultSettings")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[u.jsx(wt,{children:u.jsx(Ut,{children:e("evolutionBot.defaultSettings")})}),u.jsx(Tr,{...l,children:u.jsxs("form",{className:"w-full space-y-6",onSubmit:l.handleSubmit(d),children:[u.jsx("div",{children:u.jsxs("div",{className:"space-y-4",children:[u.jsx(Qt,{name:"botIdFallback",label:e("evolutionBot.form.botIdFallback.label"),options:(a==null?void 0:a.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),u.jsx(Z,{name:"expire",label:e("evolutionBot.form.expire.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"keywordFinish",label:e("evolutionBot.form.keywordFinish.label"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"delayMessage",label:e("evolutionBot.form.delayMessage.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"unknownMessage",label:e("evolutionBot.form.unknownMessage.label"),children:u.jsx(Q,{})}),u.jsx(Pe,{name:"listeningFromMe",label:e("evolutionBot.form.listeningFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"stopBotFromMe",label:e("evolutionBot.form.stopBotFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"keepOpen",label:e("evolutionBot.form.keepOpen.label"),reverse:!0}),u.jsx(Z,{name:"debounceTime",label:e("evolutionBot.form.debounceTime.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Ru,{name:"ignoreJids",label:e("evolutionBot.form.ignoreJids.label"),placeholder:e("evolutionBot.form.ignoreJids.placeholder")})]})}),u.jsx(rn,{children:u.jsx(K,{type:"submit",children:e("evolutionBot.button.save")})})]})})]})]})}const nee=e=>["evolutionBot","fetchSessions",JSON.stringify(e)],ree=async({instanceName:e,evolutionBotId:t,token:n})=>(await he.get(`/evolutionBot/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,see=e=>{const{instanceName:t,token:n,evolutionBotId:r,...s}=e;return lt({...s,queryKey:nee({instanceName:t}),queryFn:()=>ree({instanceName:t,token:n,evolutionBotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function RI({evolutionBotId:e}){const{t}=ze(),{instance:n}=nt(),[r,s]=v.useState([]),[o,a]=v.useState(!1),[i,c]=v.useState(""),{data:l,refetch:d}=see({instanceName:n==null?void 0:n.name,evolutionBotId:e,enabled:o}),{changeStatusEvolutionBot:p}=Xg();function f(){d()}const h=async(m,x)=>{var b,y,w;try{if(!n)return;await p({instanceName:n.name,token:n.token,remoteJid:m,status:x}),X.success(t("evolutionBot.toast.success.status")),f()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},g=[{accessorKey:"remoteJid",header:()=>u.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.remoteJid")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>u.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.pushName")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>u.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.sessionId")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>u.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.status")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(K,{variant:"ghost",className:"h-8 w-8 p-0",children:[u.jsx("span",{className:"sr-only",children:t("evolutionBot.sessions.table.actions.title")}),u.jsx(vu,{className:"h-4 w-4"})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(Ai,{children:t("evolutionBot.sessions.table.actions.title")}),u.jsx(Oa,{}),x.status!=="opened"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"opened"),children:[u.jsx(qd,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"paused"),children:[u.jsx(Kd,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.pause")]}),x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"closed"),children:[u.jsx(Ud,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.close")]}),u.jsxs(ft,{onClick:()=>h(x.remoteJid,"delete"),children:[u.jsx(Vd,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.delete")]})]})]})}}];return u.jsxs(Tt,{open:o,onOpenChange:a,children:[u.jsx(Mt,{asChild:!0,children:u.jsxs(K,{variant:"secondary",size:"sm",children:[u.jsx(Hd,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("evolutionBot.sessions.label")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("evolutionBot.sessions.label")})}),u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[u.jsx(Q,{placeholder:t("evolutionBot.sessions.search"),value:i,onChange:m=>c(m.target.value)}),u.jsx(K,{variant:"outline",onClick:f,size:"icon",children:u.jsx(Wd,{})})]}),u.jsx(Mu,{columns:g,data:l??[],onSortingChange:s,state:{sorting:r,globalFilter:i},onGlobalFilterChange:c,enableGlobalFilter:!0,noResultsMessage:t("evolutionBot.sessions.table.none")})]})]})]})}const oee=_.object({enabled:_.boolean(),description:_.string(),apiUrl:_.string(),apiKey:_.string().optional(),triggerType:_.string(),triggerOperator:_.string().optional(),triggerValue:_.string().optional(),expire:_.coerce.number().optional(),keywordFinish:_.string().optional(),delayMessage:_.coerce.number().optional(),unknownMessage:_.string().optional(),listeningFromMe:_.boolean().optional(),stopBotFromMe:_.boolean().optional(),keepOpen:_.boolean().optional(),debounceTime:_.coerce.number().optional()});function OI({initialData:e,onSubmit:t,handleDelete:n,evolutionBotId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:i=()=>{}}){const{t:c}=ze(),l=sn({resolver:on(oee),defaultValues:e||{enabled:!0,description:"",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}}),d=l.watch("triggerType");return u.jsx(Tr,{...l,children:u.jsxs("form",{onSubmit:l.handleSubmit(t),className:"w-full space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsx(Pe,{name:"enabled",label:c("evolutionBot.form.enabled.label"),reverse:!0}),u.jsx(Z,{name:"description",label:c("evolutionBot.form.description.label"),required:!0,children:u.jsx(Q,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("evolutionBot.form.evolutionBotSettings.label")}),u.jsx($t,{})]}),u.jsx(Z,{name:"apiUrl",label:c("evolutionBot.form.apiUrl.label"),required:!0,children:u.jsx(Q,{})}),u.jsx(Z,{name:"apiKey",label:c("evolutionBot.form.apiKey.label"),children:u.jsx(Q,{type:"password"})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("evolutionBot.form.triggerSettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"triggerType",label:c("evolutionBot.form.triggerType.label"),options:[{label:c("evolutionBot.form.triggerType.keyword"),value:"keyword"},{label:c("evolutionBot.form.triggerType.all"),value:"all"},{label:c("evolutionBot.form.triggerType.advanced"),value:"advanced"},{label:c("evolutionBot.form.triggerType.none"),value:"none"}]}),d==="keyword"&&u.jsxs(u.Fragment,{children:[u.jsx(Qt,{name:"triggerOperator",label:c("evolutionBot.form.triggerOperator.label"),options:[{label:c("evolutionBot.form.triggerOperator.contains"),value:"contains"},{label:c("evolutionBot.form.triggerOperator.equals"),value:"equals"},{label:c("evolutionBot.form.triggerOperator.startsWith"),value:"startsWith"},{label:c("evolutionBot.form.triggerOperator.endsWith"),value:"endsWith"},{label:c("evolutionBot.form.triggerOperator.regex"),value:"regex"}]}),u.jsx(Z,{name:"triggerValue",label:c("evolutionBot.form.triggerValue.label"),children:u.jsx(Q,{})})]}),d==="advanced"&&u.jsx(Z,{name:"triggerValue",label:c("evolutionBot.form.triggerConditions.label"),children:u.jsx(Q,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("evolutionBot.form.generalSettings.label")}),u.jsx($t,{})]}),u.jsx(Z,{name:"expire",label:c("evolutionBot.form.expire.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"keywordFinish",label:c("evolutionBot.form.keywordFinish.label"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"delayMessage",label:c("evolutionBot.form.delayMessage.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"unknownMessage",label:c("evolutionBot.form.unknownMessage.label"),children:u.jsx(Q,{})}),u.jsx(Pe,{name:"listeningFromMe",label:c("evolutionBot.form.listeningFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"stopBotFromMe",label:c("evolutionBot.form.stopBotFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"keepOpen",label:c("evolutionBot.form.keepOpen.label"),reverse:!0}),u.jsx(Z,{name:"debounceTime",label:c("evolutionBot.form.debounceTime.label"),children:u.jsx(Q,{type:"number"})})]}),s&&u.jsx(rn,{children:u.jsx(K,{disabled:o,type:"submit",children:c(o?"evolutionBot.button.saving":"evolutionBot.button.save")})}),!s&&u.jsxs("div",{children:[u.jsx(RI,{evolutionBotId:r}),u.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[u.jsxs(Tt,{open:a,onOpenChange:i,children:[u.jsx(Mt,{asChild:!0,children:u.jsx(K,{variant:"destructive",size:"sm",children:c("dify.button.delete")})}),u.jsx(xt,{children:u.jsxs(wt,{children:[u.jsx(Ut,{children:c("modal.delete.title")}),u.jsx(Fi,{children:c("modal.delete.messageSingle")}),u.jsxs(rn,{children:[u.jsx(K,{size:"sm",variant:"outline",onClick:()=>i(!1),children:c("button.cancel")}),u.jsx(K,{variant:"destructive",onClick:n,children:c("button.delete")})]})]})})]}),u.jsx(K,{disabled:o,type:"submit",children:c(o?"evolutionBot.button.saving":"evolutionBot.button.update")})]})]})]})})}function aee({resetTable:e}){const{t}=ze(),{instance:n}=nt(),[r,s]=v.useState(!1),[o,a]=v.useState(!1),{createEvolutionBot:i}=Xg(),c=async l=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");s(!0);const h={enabled:l.enabled,description:l.description,apiUrl:l.apiUrl,apiKey:l.apiKey,triggerType:l.triggerType,triggerOperator:l.triggerOperator||"",triggerValue:l.triggerValue||"",expire:l.expire||0,keywordFinish:l.keywordFinish||"",delayMessage:l.delayMessage||0,unknownMessage:l.unknownMessage||"",listeningFromMe:l.listeningFromMe||!1,stopBotFromMe:l.stopBotFromMe||!1,keepOpen:l.keepOpen||!1,debounceTime:l.debounceTime||0};await i({instanceName:n.name,token:n.token,data:h}),X.success(t("evolutionBot.toast.success.create")),a(!1),e()}catch(h){console.error("Error:",h),X.error(`Error: ${(f=(p=(d=h==null?void 0:h.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{s(!1)}};return u.jsxs(Tt,{open:o,onOpenChange:a,children:[u.jsx(Mt,{asChild:!0,children:u.jsxs(K,{size:"sm",children:[u.jsx(Mi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("evolutionBot.button.create")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("evolutionBot.form.title")})}),u.jsx(OI,{onSubmit:c,isModal:!0,isLoading:r})]})]})}const iee=e=>["evolutionBot","getEvolutionBot",JSON.stringify(e)],lee=async({instanceName:e,token:t,evolutionBotId:n})=>{const r=await he.get(`/evolutionBot/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},uee=e=>{const{instanceName:t,token:n,evolutionBotId:r,...s}=e;return lt({...s,queryKey:iee({instanceName:t}),queryFn:()=>lee({instanceName:t,token:n,evolutionBotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function cee({evolutionBotId:e,resetTable:t}){const{t:n}=ze(),{instance:r}=nt(),s=An(),[o,a]=v.useState(!1),{deleteEvolutionBot:i,updateEvolutionBot:c}=Xg(),{data:l,isLoading:d}=uee({instanceName:r==null?void 0:r.name,evolutionBotId:e}),p=v.useMemo(()=>({enabled:(l==null?void 0:l.enabled)??!0,description:(l==null?void 0:l.description)??"",apiUrl:(l==null?void 0:l.apiUrl)??"",apiKey:(l==null?void 0:l.apiKey)??"",triggerType:(l==null?void 0:l.triggerType)??"",triggerOperator:(l==null?void 0:l.triggerOperator)??"",triggerValue:l==null?void 0:l.triggerValue,expire:(l==null?void 0:l.expire)??0,keywordFinish:l==null?void 0:l.keywordFinish,delayMessage:(l==null?void 0:l.delayMessage)??0,unknownMessage:l==null?void 0:l.unknownMessage,listeningFromMe:l==null?void 0:l.listeningFromMe,stopBotFromMe:!!(l!=null&&l.stopBotFromMe),keepOpen:!!(l!=null&&l.keepOpen),debounceTime:(l==null?void 0:l.debounceTime)??0}),[l==null?void 0:l.apiKey,l==null?void 0:l.apiUrl,l==null?void 0:l.debounceTime,l==null?void 0:l.delayMessage,l==null?void 0:l.description,l==null?void 0:l.enabled,l==null?void 0:l.expire,l==null?void 0:l.keepOpen,l==null?void 0:l.keywordFinish,l==null?void 0:l.listeningFromMe,l==null?void 0:l.stopBotFromMe,l==null?void 0:l.triggerOperator,l==null?void 0:l.triggerType,l==null?void 0:l.triggerValue,l==null?void 0:l.unknownMessage]),f=async g=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:g.enabled,description:g.description,apiUrl:g.apiUrl,apiKey:g.apiKey,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire||0,keywordFinish:g.keywordFinish||"",delayMessage:g.delayMessage||1e3,unknownMessage:g.unknownMessage||"",listeningFromMe:g.listeningFromMe||!1,stopBotFromMe:g.stopBotFromMe||!1,keepOpen:g.keepOpen||!1,debounceTime:g.debounceTime||0};await c({instanceName:r.name,evolutionBotId:e,data:y}),X.success(n("evolutionBot.toast.success.update")),t(),s(`/manager/instance/${r.id}/evolutionBot/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),X.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},h=async()=>{try{r&&r.name&&e?(await i({instanceName:r.name,evolutionBotId:e}),X.success(n("evolutionBot.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/evolutionBot`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir evolutionBot:",g)}};return d?u.jsx(wr,{}):u.jsx("div",{className:"m-4",children:u.jsx(OI,{initialData:p,onSubmit:f,evolutionBotId:e,handleDelete:h,isModal:!1,openDeletionDialog:o,setOpenDeletionDialog:a})})}function rE(){const{t:e}=ze(),t=Pu("(min-width: 768px)"),{instance:n}=nt(),{evolutionBotId:r}=So(),{data:s,isLoading:o,refetch:a}=jI({instanceName:n==null?void 0:n.name}),i=An(),c=d=>{n&&i(`/manager/instance/${n.id}/evolutionBot/${d}`)},l=()=>{a()};return u.jsxs("main",{className:"pt-5",children:[u.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[u.jsx("h3",{className:"text-lg font-medium",children:e("evolutionBot.title")}),u.jsxs("div",{className:"flex items-center justify-end gap-2",children:[u.jsx(RI,{}),u.jsx(tee,{}),u.jsx(aee,{resetTable:l})]})]}),u.jsx($t,{className:"my-4"}),u.jsxs(Ou,{direction:t?"horizontal":"vertical",children:[u.jsx(Ur,{defaultSize:35,className:"pr-4",children:u.jsx("div",{className:"flex flex-col gap-3",children:o?u.jsx(wr,{}):u.jsx(u.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>u.jsx(K,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>c(`${d.id}`),variant:r===d.id?"secondary":"outline",children:u.jsx("h4",{className:"text-base",children:d.description||d.id})},d.id)):u.jsx(K,{variant:"link",children:e("evolutionBot.table.none")})})})}),r&&u.jsxs(u.Fragment,{children:[u.jsx(Nu,{withHandle:!0,className:"border border-border"}),u.jsx(Ur,{children:u.jsx(cee,{evolutionBotId:r,resetTable:l})})]})]})]})}const dee=e=>["flowise","findFlowise",JSON.stringify(e)],fee=async({instanceName:e,token:t})=>(await he.get(`/flowise/find/${e}`,{headers:{apiKey:t}})).data,NI=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:dee({instanceName:t}),queryFn:()=>fee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},pee=e=>["flowise","fetchDefaultSettings",JSON.stringify(e)],hee=async({instanceName:e,token:t})=>{const n=await he.get(`/flowise/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},gee=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:pee({instanceName:t}),queryFn:()=>hee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},mee=async({instanceName:e,token:t,data:n})=>(await he.post(`/flowise/create/${e}`,n,{headers:{apikey:t}})).data,vee=async({instanceName:e,flowiseId:t,data:n})=>(await he.put(`/flowise/update/${t}/${e}`,n)).data,yee=async({instanceName:e,flowiseId:t})=>(await he.delete(`/flowise/delete/${t}/${e}`)).data,bee=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await he.post(`/flowise/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data,xee=async({instanceName:e,token:t,data:n})=>(await he.post(`/flowise/settings/${e}`,n,{headers:{apikey:t}})).data;function em(){const e=Ye(xee,{invalidateKeys:[["flowise","fetchDefaultSettings"]]}),t=Ye(bee,{invalidateKeys:[["flowise","getFlowise"],["flowise","fetchSessions"]]}),n=Ye(yee,{invalidateKeys:[["flowise","getFlowise"],["flowise","findFlowise"],["flowise","fetchSessions"]]}),r=Ye(vee,{invalidateKeys:[["flowise","getFlowise"],["flowise","findFlowise"],["flowise","fetchSessions"]]}),s=Ye(mee,{invalidateKeys:[["flowise","findFlowise"]]});return{setDefaultSettingsFlowise:e,changeStatusFlowise:t,deleteFlowise:n,updateFlowise:r,createFlowise:s}}const wee=_.object({expire:_.string(),keywordFinish:_.string(),delayMessage:_.string(),unknownMessage:_.string(),listeningFromMe:_.boolean(),stopBotFromMe:_.boolean(),keepOpen:_.boolean(),debounceTime:_.string(),ignoreJids:_.array(_.string()).default([]),flowiseIdFallback:_.union([_.null(),_.string()]).optional()});function See(){const{t:e}=ze(),{instance:t}=nt(),{setDefaultSettingsFlowise:n}=em(),[r,s]=v.useState(!1),{data:o,refetch:a}=gee({instanceName:t==null?void 0:t.name,enabled:r}),{data:i,refetch:c}=NI({instanceName:t==null?void 0:t.name,enabled:r}),l=sn({resolver:on(wee),defaultValues:{expire:"0",keywordFinish:e("flowise.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("flowise.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],flowiseIdFallback:void 0}});v.useEffect(()=>{o&&l.reset({expire:o!=null&&o.expire?o.expire.toString():"0",keywordFinish:o.keywordFinish,delayMessage:o.delayMessage?o.delayMessage.toString():"0",unknownMessage:o.unknownMessage,listeningFromMe:o.listeningFromMe,stopBotFromMe:o.stopBotFromMe,keepOpen:o.keepOpen,debounceTime:o.debounceTime?o.debounceTime.toString():"0",ignoreJids:o.ignoreJids,flowiseIdFallback:o.flowiseIdFallback})},[o]);const d=async f=>{var h,g,m;try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),flowiseIdFallback:f.flowiseIdFallback||void 0,ignoreJids:f.ignoreJids};await n({instanceName:t.name,token:t.token,data:x}),X.success(e("flowise.toast.defaultSettings.success"))}catch(x){console.error("Error:",x),X.error(`Error: ${(m=(g=(h=x==null?void 0:x.response)==null?void 0:h.data)==null?void 0:g.response)==null?void 0:m.message}`)}};function p(){a(),c()}return u.jsxs(Tt,{open:r,onOpenChange:s,children:[u.jsx(Mt,{asChild:!0,children:u.jsxs(K,{variant:"secondary",size:"sm",children:[u.jsx(Pi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:e("flowise.defaultSettings")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[u.jsx(wt,{children:u.jsx(Ut,{children:e("flowise.defaultSettings")})}),u.jsx(Tr,{...l,children:u.jsxs("form",{className:"w-full space-y-6",onSubmit:l.handleSubmit(d),children:[u.jsx("div",{children:u.jsxs("div",{className:"space-y-4",children:[u.jsx(Qt,{name:"flowiseIdFallback",label:e("flowise.form.flowiseIdFallback.label"),options:(i==null?void 0:i.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),u.jsx(Z,{name:"expire",label:e("flowise.form.expire.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"keywordFinish",label:e("flowise.form.keywordFinish.label"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"delayMessage",label:e("flowise.form.delayMessage.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"unknownMessage",label:e("flowise.form.unknownMessage.label"),children:u.jsx(Q,{})}),u.jsx(Pe,{name:"listeningFromMe",label:e("flowise.form.listeningFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"stopBotFromMe",label:e("flowise.form.stopBotFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"keepOpen",label:e("flowise.form.keepOpen.label"),reverse:!0}),u.jsx(Z,{name:"debounceTime",label:e("flowise.form.debounceTime.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Ru,{name:"ignoreJids",label:e("flowise.form.ignoreJids.label"),placeholder:e("flowise.form.ignoreJids.placeholder")})]})}),u.jsx(rn,{children:u.jsx(K,{type:"submit",children:e("flowise.button.save")})})]})})]})]})}const Cee=e=>["flowise","fetchSessions",JSON.stringify(e)],Eee=async({instanceName:e,flowiseId:t,token:n})=>(await he.get(`/flowise/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,Tee=e=>{const{instanceName:t,token:n,flowiseId:r,...s}=e;return lt({...s,queryKey:Cee({instanceName:t}),queryFn:()=>Eee({instanceName:t,token:n,flowiseId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function PI({flowiseId:e}){const{t}=ze(),{instance:n}=nt(),{changeStatusFlowise:r}=em(),[s,o]=v.useState([]),[a,i]=v.useState(!1),[c,l]=v.useState(""),{data:d,refetch:p}=Tee({instanceName:n==null?void 0:n.name,flowiseId:e,enabled:a});function f(){p()}const h=async(m,x)=>{var b,y,w;try{if(!n)return;await r({instanceName:n.name,token:n.token,remoteJid:m,status:x}),X.success(t("flowise.toast.success.status")),f()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},g=[{accessorKey:"remoteJid",header:()=>u.jsx("div",{className:"text-center",children:t("flowise.sessions.table.remoteJid")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>u.jsx("div",{className:"text-center",children:t("flowise.sessions.table.pushName")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>u.jsx("div",{className:"text-center",children:t("flowise.sessions.table.sessionId")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>u.jsx("div",{className:"text-center",children:t("flowise.sessions.table.status")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(K,{variant:"ghost",className:"h-8 w-8 p-0",children:[u.jsx("span",{className:"sr-only",children:t("flowise.sessions.table.actions.title")}),u.jsx(vu,{className:"h-4 w-4"})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(Ai,{children:t("flowise.sessions.table.actions.title")}),u.jsx(Oa,{}),x.status!=="opened"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"opened"),children:[u.jsx(qd,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"paused"),children:[u.jsx(Kd,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.pause")]}),x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"closed"),children:[u.jsx(Ud,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.close")]}),u.jsxs(ft,{onClick:()=>h(x.remoteJid,"delete"),children:[u.jsx(Vd,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.delete")]})]})]})}}];return u.jsxs(Tt,{open:a,onOpenChange:i,children:[u.jsx(Mt,{asChild:!0,children:u.jsxs(K,{variant:"secondary",size:"sm",children:[u.jsx(Hd,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("flowise.sessions.label")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("flowise.sessions.label")})}),u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[u.jsx(Q,{placeholder:t("flowise.sessions.search"),value:c,onChange:m=>l(m.target.value)}),u.jsx(K,{variant:"outline",onClick:f,size:"icon",children:u.jsx(Wd,{})})]}),u.jsx(Mu,{columns:g,data:d??[],onSortingChange:o,state:{sorting:s,globalFilter:c},onGlobalFilterChange:l,enableGlobalFilter:!0,noResultsMessage:t("flowise.sessions.table.none")})]})]})]})}const kee=_.object({enabled:_.boolean(),description:_.string(),apiUrl:_.string(),apiKey:_.string().optional(),triggerType:_.string(),triggerOperator:_.string().optional(),triggerValue:_.string().optional(),expire:_.coerce.number().optional(),keywordFinish:_.string().optional(),delayMessage:_.coerce.number().optional(),unknownMessage:_.string().optional(),listeningFromMe:_.boolean().optional(),stopBotFromMe:_.boolean().optional(),keepOpen:_.boolean().optional(),debounceTime:_.coerce.number().optional()});function MI({initialData:e,onSubmit:t,handleDelete:n,flowiseId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:i=()=>{}}){const{t:c}=ze(),l=sn({resolver:on(kee),defaultValues:e||{enabled:!0,description:"",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}}),d=l.watch("triggerType");return u.jsx(Tr,{...l,children:u.jsxs("form",{onSubmit:l.handleSubmit(t),className:"w-full space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsx(Pe,{name:"enabled",label:c("flowise.form.enabled.label"),reverse:!0}),u.jsx(Z,{name:"description",label:c("flowise.form.description.label"),required:!0,children:u.jsx(Q,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("flowise.form.flowiseSettings.label")}),u.jsx($t,{})]}),u.jsx(Z,{name:"apiUrl",label:c("flowise.form.apiUrl.label"),required:!0,children:u.jsx(Q,{})}),u.jsx(Z,{name:"apiKey",label:c("flowise.form.apiKey.label"),children:u.jsx(Q,{type:"password"})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("flowise.form.triggerSettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"triggerType",label:c("flowise.form.triggerType.label"),options:[{label:c("flowise.form.triggerType.keyword"),value:"keyword"},{label:c("flowise.form.triggerType.all"),value:"all"},{label:c("flowise.form.triggerType.advanced"),value:"advanced"},{label:c("flowise.form.triggerType.none"),value:"none"}]}),d==="keyword"&&u.jsxs(u.Fragment,{children:[u.jsx(Qt,{name:"triggerOperator",label:c("flowise.form.triggerOperator.label"),options:[{label:c("flowise.form.triggerOperator.contains"),value:"contains"},{label:c("flowise.form.triggerOperator.equals"),value:"equals"},{label:c("flowise.form.triggerOperator.startsWith"),value:"startsWith"},{label:c("flowise.form.triggerOperator.endsWith"),value:"endsWith"},{label:c("flowise.form.triggerOperator.regex"),value:"regex"}]}),u.jsx(Z,{name:"triggerValue",label:c("flowise.form.triggerValue.label"),children:u.jsx(Q,{})})]}),d==="advanced"&&u.jsx(Z,{name:"triggerValue",label:c("flowise.form.triggerConditions.label"),children:u.jsx(Q,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("flowise.form.generalSettings.label")}),u.jsx($t,{})]}),u.jsx(Z,{name:"expire",label:c("flowise.form.expire.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"keywordFinish",label:c("flowise.form.keywordFinish.label"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"delayMessage",label:c("flowise.form.delayMessage.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"unknownMessage",label:c("flowise.form.unknownMessage.label"),children:u.jsx(Q,{})}),u.jsx(Pe,{name:"listeningFromMe",label:c("flowise.form.listeningFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"stopBotFromMe",label:c("flowise.form.stopBotFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"keepOpen",label:c("flowise.form.keepOpen.label"),reverse:!0}),u.jsx(Z,{name:"debounceTime",label:c("flowise.form.debounceTime.label"),children:u.jsx(Q,{type:"number"})})]}),s&&u.jsx(rn,{children:u.jsx(K,{disabled:o,type:"submit",children:c(o?"flowise.button.saving":"flowise.button.save")})}),!s&&u.jsxs("div",{children:[u.jsx(PI,{flowiseId:r}),u.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[u.jsxs(Tt,{open:a,onOpenChange:i,children:[u.jsx(Mt,{asChild:!0,children:u.jsx(K,{variant:"destructive",size:"sm",children:c("dify.button.delete")})}),u.jsx(xt,{children:u.jsxs(wt,{children:[u.jsx(Ut,{children:c("modal.delete.title")}),u.jsx(Fi,{children:c("modal.delete.messageSingle")}),u.jsxs(rn,{children:[u.jsx(K,{size:"sm",variant:"outline",onClick:()=>i(!1),children:c("button.cancel")}),u.jsx(K,{variant:"destructive",onClick:n,children:c("button.delete")})]})]})})]}),u.jsx(K,{disabled:o,type:"submit",children:c(o?"flowise.button.saving":"flowise.button.update")})]})]})]})})}function _ee({resetTable:e}){const{t}=ze(),{instance:n}=nt(),{createFlowise:r}=em(),[s,o]=v.useState(!1),[a,i]=v.useState(!1),c=async l=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");o(!0);const h={enabled:l.enabled,description:l.description,apiUrl:l.apiUrl,apiKey:l.apiKey,triggerType:l.triggerType,triggerOperator:l.triggerOperator||"",triggerValue:l.triggerValue||"",expire:l.expire||0,keywordFinish:l.keywordFinish||"",delayMessage:l.delayMessage||0,unknownMessage:l.unknownMessage||"",listeningFromMe:l.listeningFromMe||!1,stopBotFromMe:l.stopBotFromMe||!1,keepOpen:l.keepOpen||!1,debounceTime:l.debounceTime||0};await r({instanceName:n.name,token:n.token,data:h}),X.success(t("flowise.toast.success.create")),i(!1),e()}catch(h){console.error("Error:",h),X.error(`Error: ${(f=(p=(d=h==null?void 0:h.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{o(!1)}};return u.jsxs(Tt,{open:a,onOpenChange:i,children:[u.jsx(Mt,{asChild:!0,children:u.jsxs(K,{size:"sm",children:[u.jsx(Mi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("flowise.button.create")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("flowise.form.title")})}),u.jsx(MI,{onSubmit:c,isModal:!0,isLoading:s})]})]})}const jee=e=>["flowise","getFlowise",JSON.stringify(e)],Ree=async({instanceName:e,token:t,flowiseId:n})=>{const r=await he.get(`/flowise/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},Oee=e=>{const{instanceName:t,token:n,flowiseId:r,...s}=e;return lt({...s,queryKey:jee({instanceName:t}),queryFn:()=>Ree({instanceName:t,token:n,flowiseId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function Nee({flowiseId:e,resetTable:t}){const{t:n}=ze(),{instance:r}=nt(),s=An(),[o,a]=v.useState(!1),{deleteFlowise:i,updateFlowise:c}=em(),{data:l,isLoading:d}=Oee({instanceName:r==null?void 0:r.name,flowiseId:e}),p=v.useMemo(()=>({enabled:(l==null?void 0:l.enabled)??!0,description:(l==null?void 0:l.description)??"",apiUrl:(l==null?void 0:l.apiUrl)??"",apiKey:(l==null?void 0:l.apiKey)??"",triggerType:(l==null?void 0:l.triggerType)??"",triggerOperator:(l==null?void 0:l.triggerOperator)??"",triggerValue:l==null?void 0:l.triggerValue,expire:(l==null?void 0:l.expire)??0,keywordFinish:l==null?void 0:l.keywordFinish,delayMessage:(l==null?void 0:l.delayMessage)??0,unknownMessage:l==null?void 0:l.unknownMessage,listeningFromMe:l==null?void 0:l.listeningFromMe,stopBotFromMe:l==null?void 0:l.stopBotFromMe,keepOpen:l==null?void 0:l.keepOpen,debounceTime:(l==null?void 0:l.debounceTime)??0}),[l==null?void 0:l.apiKey,l==null?void 0:l.apiUrl,l==null?void 0:l.debounceTime,l==null?void 0:l.delayMessage,l==null?void 0:l.description,l==null?void 0:l.enabled,l==null?void 0:l.expire,l==null?void 0:l.keepOpen,l==null?void 0:l.keywordFinish,l==null?void 0:l.listeningFromMe,l==null?void 0:l.stopBotFromMe,l==null?void 0:l.triggerOperator,l==null?void 0:l.triggerType,l==null?void 0:l.triggerValue,l==null?void 0:l.unknownMessage]),f=async g=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:g.enabled,description:g.description,apiUrl:g.apiUrl,apiKey:g.apiKey,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire||0,keywordFinish:g.keywordFinish||"",delayMessage:g.delayMessage||1e3,unknownMessage:g.unknownMessage||"",listeningFromMe:g.listeningFromMe||!1,stopBotFromMe:g.stopBotFromMe||!1,keepOpen:g.keepOpen||!1,debounceTime:g.debounceTime||0};await c({instanceName:r.name,flowiseId:e,data:y}),X.success(n("flowise.toast.success.update")),t(),s(`/manager/instance/${r.id}/flowise/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),X.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},h=async()=>{try{r&&r.name&&e?(await i({instanceName:r.name,flowiseId:e}),X.success(n("flowise.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/flowise`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir dify:",g)}};return d?u.jsx(wr,{}):u.jsx("div",{className:"m-4",children:u.jsx(MI,{initialData:p,onSubmit:f,flowiseId:e,handleDelete:h,isModal:!1,isLoading:d,openDeletionDialog:o,setOpenDeletionDialog:a})})}function sE(){const{t:e}=ze(),t=Pu("(min-width: 768px)"),{instance:n}=nt(),{flowiseId:r}=So(),{data:s,isLoading:o,refetch:a}=NI({instanceName:n==null?void 0:n.name}),i=An(),c=d=>{n&&i(`/manager/instance/${n.id}/flowise/${d}`)},l=()=>{a()};return u.jsxs("main",{className:"pt-5",children:[u.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[u.jsx("h3",{className:"text-lg font-medium",children:e("flowise.title")}),u.jsxs("div",{className:"flex items-center justify-end gap-2",children:[u.jsx(PI,{}),u.jsx(See,{}),u.jsx(_ee,{resetTable:l})]})]}),u.jsx($t,{className:"my-4"}),u.jsxs(Ou,{direction:t?"horizontal":"vertical",children:[u.jsx(Ur,{defaultSize:35,className:"pr-4",children:u.jsx("div",{className:"flex flex-col gap-3",children:o?u.jsx(wr,{}):u.jsx(u.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>u.jsx(K,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>c(`${d.id}`),variant:r===d.id?"secondary":"outline",children:u.jsx("h4",{className:"text-base",children:d.description||d.id})},d.id)):u.jsx(K,{variant:"link",children:e("flowise.table.none")})})})}),r&&u.jsxs(u.Fragment,{children:[u.jsx(Nu,{withHandle:!0,className:"border border-border"}),u.jsx(Ur,{children:u.jsx(Nee,{flowiseId:r,resetTable:l})})]})]})]})}const Pee=e=>["openai","findOpenai",JSON.stringify(e)],Mee=async({instanceName:e,token:t})=>(await he.get(`/openai/find/${e}`,{headers:{apiKey:t}})).data,II=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:Pee({instanceName:t}),queryFn:()=>Mee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Iee=e=>["openai","findOpenaiCreds",JSON.stringify(e)],Dee=async({instanceName:e,token:t})=>(await he.get(`/openai/creds/${e}`,{headers:{apiKey:t}})).data,Vw=e=>{const{instanceName:t,token:n,...r}=e;return lt({staleTime:1e3*60*60*6,...r,queryKey:Iee({instanceName:t}),queryFn:()=>Dee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Aee=async({instanceName:e,token:t,data:n})=>(await he.post(`/openai/creds/${e}`,n,{headers:{apikey:t}})).data,Fee=async({openaiCredsId:e,instanceName:t})=>(await he.delete(`/openai/creds/${e}/${t}`)).data,Lee=async({instanceName:e,token:t,data:n})=>(await he.post(`/openai/create/${e}`,n,{headers:{apikey:t}})).data,$ee=async({instanceName:e,token:t,openaiId:n,data:r})=>(await he.put(`/openai/update/${n}/${e}`,r,{headers:{apikey:t}})).data,Bee=async({instanceName:e,token:t,openaiId:n})=>(await he.delete(`/openai/delete/${n}/${e}`,{headers:{apikey:t}})).data,zee=async({instanceName:e,token:t,data:n})=>(await he.post(`/openai/settings/${e}`,n,{headers:{apikey:t}})).data,Uee=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await he.post(`/openai/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function rf(){const e=Ye(zee,{invalidateKeys:[["openai","fetchDefaultSettings"]]}),t=Ye(Uee,{invalidateKeys:[["openai","getOpenai"],["openai","fetchSessions"]]}),n=Ye(Bee,{invalidateKeys:[["openai","getOpenai"],["openai","findOpenai"],["openai","fetchSessions"]]}),r=Ye($ee,{invalidateKeys:[["openai","getOpenai"],["openai","findOpenai"],["openai","fetchSessions"]]}),s=Ye(Lee,{invalidateKeys:[["openai","findOpenai"]]}),o=Ye(Aee,{invalidateKeys:[["openai","findOpenaiCreds"]]}),a=Ye(Fee,{invalidateKeys:[["openai","findOpenaiCreds"]]});return{setDefaultSettingsOpenai:e,changeStatusOpenai:t,deleteOpenai:n,updateOpenai:r,createOpenai:s,createOpenaiCreds:o,deleteOpenaiCreds:a}}const Vee=_.object({name:_.string(),apiKey:_.string()});function Hee(){const{t:e}=ze(),{instance:t}=nt(),{createOpenaiCreds:n,deleteOpenaiCreds:r}=rf(),[s,o]=v.useState(!1),[a,i]=v.useState([]),{data:c,refetch:l}=Vw({instanceName:t==null?void 0:t.name,enabled:s}),d=sn({resolver:on(Vee),defaultValues:{name:"",apiKey:""}}),p=async m=>{var x,b,y;try{if(!t||!t.name)throw new Error("instance not found.");const w={name:m.name,apiKey:m.apiKey};await n({instanceName:t.name,token:t.token,data:w}),X.success(e("openai.toast.success.credentialsCreate")),f()}catch(w){console.error("Error:",w),X.error(`Error: ${(y=(b=(x=w==null?void 0:w.response)==null?void 0:x.data)==null?void 0:b.response)==null?void 0:y.message}`)}};function f(){d.reset(),l()}const h=async m=>{var x,b,y;if(!(t!=null&&t.name)){X.error("Instance not found.");return}try{await r({openaiCredsId:m,instanceName:t==null?void 0:t.name}),X.success(e("openai.toast.success.credentialsDelete")),l()}catch(w){console.error("Error:",w),X.error(`Error: ${(y=(b=(x=w==null?void 0:w.response)==null?void 0:x.data)==null?void 0:b.response)==null?void 0:y.message}`)}},g=[{accessorKey:"name",header:({column:m})=>u.jsxs(K,{variant:"ghost",onClick:()=>m.toggleSorting(m.getIsSorted()==="asc"),children:[e("openai.credentials.table.name"),u.jsx(_3,{className:"ml-2 h-4 w-4"})]}),cell:({row:m})=>u.jsx("div",{children:m.getValue("name")})},{accessorKey:"apiKey",header:()=>u.jsx("div",{className:"text-right",children:e("openai.credentials.table.apiKey")}),cell:({row:m})=>u.jsxs("div",{children:[`${m.getValue("apiKey")}`.slice(0,20),"..."]})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(K,{variant:"ghost",className:"h-8 w-8 p-0",children:[u.jsx("span",{className:"sr-only",children:e("openai.credentials.table.actions.title")}),u.jsx(vu,{className:"h-4 w-4"})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(Ai,{children:e("openai.credentials.table.actions.title")}),u.jsx(Oa,{}),u.jsx(ft,{onClick:()=>h(x.id),children:e("openai.credentials.table.actions.delete")})]})]})}}];return u.jsxs(Tt,{open:s,onOpenChange:o,children:[u.jsx(Mt,{asChild:!0,children:u.jsxs(K,{variant:"secondary",size:"sm",children:[u.jsx(H3,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden md:inline",children:e("openai.credentials.title")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:e("openai.credentials.title")})}),u.jsx(Tr,{...d,children:u.jsxs("form",{onSubmit:d.handleSubmit(p),className:"w-full space-y-6",children:[u.jsx("div",{children:u.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[u.jsx(Z,{name:"name",label:e("openai.credentials.table.name"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"apiKey",label:e("openai.credentials.table.apiKey"),children:u.jsx(Q,{type:"password"})})]})}),u.jsx(rn,{children:u.jsx(K,{type:"submit",children:e("openai.button.save")})})]})}),u.jsx($t,{}),u.jsx("div",{children:u.jsx(Mu,{columns:g,data:c??[],onSortingChange:i,state:{sorting:a},noResultsMessage:e("openai.credentials.table.none")})})]})]})}const Kee=e=>["openai","fetchDefaultSettings",JSON.stringify(e)],qee=async({instanceName:e,token:t})=>{const n=await he.get(`/openai/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},Wee=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:Kee({instanceName:t}),queryFn:()=>qee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Gee=_.object({openaiCredsId:_.string(),expire:_.coerce.number(),keywordFinish:_.string(),delayMessage:_.coerce.number().default(0),unknownMessage:_.string(),listeningFromMe:_.boolean(),stopBotFromMe:_.boolean(),keepOpen:_.boolean(),debounceTime:_.coerce.number(),speechToText:_.boolean(),ignoreJids:_.array(_.string()).default([]),openaiIdFallback:_.union([_.null(),_.string()]).optional()});function Jee(){const{t:e}=ze(),{instance:t}=nt(),{setDefaultSettingsOpenai:n}=rf(),[r,s]=v.useState(!1),{data:o,refetch:a}=Wee({instanceName:t==null?void 0:t.name,enabled:r}),{data:i,refetch:c}=II({instanceName:t==null?void 0:t.name,enabled:r}),{data:l}=Vw({instanceName:t==null?void 0:t.name,enabled:r}),d=sn({resolver:on(Gee),defaultValues:{openaiCredsId:"",expire:0,keywordFinish:e("openai.form.examples.keywordFinish"),delayMessage:1e3,unknownMessage:e("openai.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,speechToText:!1,ignoreJids:[],openaiIdFallback:void 0}});v.useEffect(()=>{o&&d.reset({openaiCredsId:o.openaiCredsId,expire:(o==null?void 0:o.expire)??0,keywordFinish:o.keywordFinish,delayMessage:o.delayMessage??0,unknownMessage:o.unknownMessage,listeningFromMe:o.listeningFromMe,stopBotFromMe:o.stopBotFromMe,keepOpen:o.keepOpen,debounceTime:o.debounceTime??0,speechToText:o.speechToText,ignoreJids:o.ignoreJids,openaiIdFallback:o.openaiIdFallback})},[o]);const p=async h=>{var g,m,x;try{if(!t||!t.name)throw new Error("instance not found.");const b={openaiCredsId:h.openaiCredsId,expire:h.expire,keywordFinish:h.keywordFinish,delayMessage:h.delayMessage,unknownMessage:h.unknownMessage,listeningFromMe:h.listeningFromMe,stopBotFromMe:h.stopBotFromMe,keepOpen:h.keepOpen,debounceTime:h.debounceTime,speechToText:h.speechToText,openaiIdFallback:h.openaiIdFallback||void 0,ignoreJids:h.ignoreJids};await n({instanceName:t.name,token:t.token,data:b}),X.success(e("openai.toast.defaultSettings.success"))}catch(b){console.error("Error:",b),X.error(`Error: ${(x=(m=(g=b==null?void 0:b.response)==null?void 0:g.data)==null?void 0:m.response)==null?void 0:x.message}`)}};function f(){a(),c()}return u.jsxs(Tt,{open:r,onOpenChange:s,children:[u.jsx(Mt,{asChild:!0,children:u.jsxs(K,{variant:"secondary",size:"sm",children:[u.jsx(Pi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden md:inline",children:e("openai.defaultSettings")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:e("openai.defaultSettings")})}),u.jsx(Tr,{...d,children:u.jsxs("form",{className:"w-full space-y-6",onSubmit:d.handleSubmit(p),children:[u.jsx("div",{children:u.jsxs("div",{className:"space-y-4",children:[u.jsx(Qt,{name:"openaiCredsId",label:e("openai.form.openaiCredsId.label"),options:(l==null?void 0:l.filter(h=>!!h.id).map(h=>({label:h.name?h.name:h.apiKey.substring(0,15)+"...",value:h.id})))||[]}),u.jsx(Qt,{name:"openaiIdFallback",label:e("openai.form.openaiIdFallback.label"),options:(i==null?void 0:i.filter(h=>!!h.id).map(h=>({label:h.description,value:h.id})))??[]}),u.jsx(Z,{name:"expire",label:e("openai.form.expire.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"keywordFinish",label:e("openai.form.keywordFinish.label"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"delayMessage",label:e("openai.form.delayMessage.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"unknownMessage",label:e("openai.form.unknownMessage.label"),children:u.jsx(Q,{})}),u.jsx(Pe,{name:"listeningFromMe",label:e("openai.form.listeningFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"stopBotFromMe",label:e("openai.form.stopBotFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"keepOpen",label:e("openai.form.keepOpen.label"),reverse:!0}),u.jsx(Pe,{name:"speechToText",label:e("openai.form.speechToText.label"),reverse:!0}),u.jsx(Z,{name:"debounceTime",label:e("openai.form.debounceTime.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Ru,{name:"ignoreJids",label:e("openai.form.ignoreJids.label"),placeholder:e("openai.form.ignoreJids.placeholder")})]})}),u.jsx(rn,{children:u.jsx(K,{type:"submit",children:e("openai.button.save")})})]})})]})]})}const Qee=e=>["openai","getModels",JSON.stringify(e)],Zee=async({instanceName:e,token:t})=>(await he.get(`/openai/getModels/${e}`,{headers:{apiKey:t}})).data,Yee=e=>{const{instanceName:t,token:n,...r}=e;return lt({staleTime:1e3*60*60*6,...r,queryKey:Qee({instanceName:t}),queryFn:()=>Zee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Xee=e=>["openai","fetchSessions",JSON.stringify(e)],ete=async({instanceName:e,openaiId:t,token:n})=>(await he.get(`/openai/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,tte=e=>{const{instanceName:t,token:n,openaiId:r,...s}=e;return lt({...s,queryKey:Xee({instanceName:t}),queryFn:()=>ete({instanceName:t,token:n,openaiId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function DI({openaiId:e}){const{t}=ze(),{instance:n}=nt(),{changeStatusOpenai:r}=rf(),[s,o]=v.useState([]),[a,i]=v.useState(!1),{data:c,refetch:l}=tte({instanceName:n==null?void 0:n.name,openaiId:e,enabled:a}),[d,p]=v.useState("");function f(){l()}const h=async(m,x)=>{var b,y,w;try{if(!n)return;await r({instanceName:n.name,token:n.token,remoteJid:m,status:x}),X.success(t("openai.toast.success.status")),f()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},g=[{accessorKey:"remoteJid",header:()=>u.jsx("div",{className:"text-center",children:t("openai.sessions.table.remoteJid")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>u.jsx("div",{className:"text-center",children:t("openai.sessions.table.pushName")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>u.jsx("div",{className:"text-center",children:t("openai.sessions.table.sessionId")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>u.jsx("div",{className:"text-center",children:t("openai.sessions.table.status")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(K,{variant:"ghost",size:"icon",children:[u.jsx("span",{className:"sr-only",children:t("openai.sessions.table.actions.title")}),u.jsx(vu,{className:"h-4 w-4"})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(Ai,{children:t("openai.sessions.table.actions.title")}),u.jsx(Oa,{}),x.status!=="opened"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"opened"),children:[u.jsx(qd,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"paused"),children:[u.jsx(Kd,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.pause")]}),x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"closed"),children:[u.jsx(Ud,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.close")]}),u.jsxs(ft,{onClick:()=>h(x.remoteJid,"delete"),children:[u.jsx(Vd,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.delete")]})]})]})}}];return u.jsxs(Tt,{open:a,onOpenChange:i,children:[u.jsx(Mt,{asChild:!0,children:u.jsxs(K,{variant:"secondary",size:"sm",children:[u.jsx(Hd,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden md:inline",children:t("openai.sessions.label")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("openai.sessions.label")})}),u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[u.jsx(Q,{placeholder:t("openai.sessions.search"),value:d,onChange:m=>p(m.target.value)}),u.jsx(K,{variant:"outline",onClick:f,size:"icon",children:u.jsx(Wd,{size:16})})]}),u.jsx(Mu,{columns:g,data:c??[],onSortingChange:o,state:{sorting:s,globalFilter:d},onGlobalFilterChange:p,enableGlobalFilter:!0,noResultsMessage:t("openai.sessions.table.none")})]})]})]})}const nte=_.object({enabled:_.boolean(),description:_.string(),openaiCredsId:_.string(),botType:_.string(),assistantId:_.string().optional(),functionUrl:_.string().optional(),model:_.string().optional(),systemMessages:_.string().optional(),assistantMessages:_.string().optional(),userMessages:_.string().optional(),maxTokens:_.coerce.number().optional(),triggerType:_.string(),triggerOperator:_.string().optional(),triggerValue:_.string().optional(),expire:_.coerce.number().optional(),keywordFinish:_.string().optional(),delayMessage:_.coerce.number().optional(),unknownMessage:_.string().optional(),listeningFromMe:_.boolean().optional(),stopBotFromMe:_.boolean().optional(),keepOpen:_.boolean().optional(),debounceTime:_.coerce.number().optional()});function AI({initialData:e,onSubmit:t,handleDelete:n,openaiId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:i=()=>{},open:c}){const{t:l}=ze(),{instance:d}=nt(),{data:p}=Vw({instanceName:d==null?void 0:d.name,enabled:c}),{data:f}=Yee({instanceName:d==null?void 0:d.name,enabled:c}),h=sn({resolver:on(nte),defaultValues:e||{enabled:!0,description:"",openaiCredsId:"",botType:"assistant",assistantId:"",functionUrl:"",model:"",systemMessages:"",assistantMessages:"",userMessages:"",maxTokens:0,triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}}),g=h.watch("botType"),m=h.watch("triggerType");return u.jsx(Tr,{...h,children:u.jsxs("form",{onSubmit:h.handleSubmit(t),className:"w-full space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsx(Pe,{name:"enabled",label:l("openai.form.enabled.label"),reverse:!0}),u.jsx(Z,{name:"description",label:l("openai.form.description.label"),required:!0,children:u.jsx(Q,{})}),u.jsx(Qt,{name:"openaiCredsId",label:l("openai.form.openaiCredsId.label"),required:!0,options:(p==null?void 0:p.filter(x=>!!x.id).map(x=>({label:x.name?x.name:x.apiKey.substring(0,15)+"...",value:x.id})))??[]}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:l("openai.form.openaiSettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"botType",label:l("openai.form.botType.label"),required:!0,options:[{label:l("openai.form.botType.assistant"),value:"assistant"},{label:l("openai.form.botType.chatCompletion"),value:"chatCompletion"}]}),g==="assistant"&&u.jsxs(u.Fragment,{children:[u.jsx(Z,{name:"assistantId",label:l("openai.form.assistantId.label"),required:!0,children:u.jsx(Q,{})}),u.jsx(Z,{name:"functionUrl",label:l("openai.form.functionUrl.label"),required:!0,children:u.jsx(Q,{})})]}),g==="chatCompletion"&&u.jsxs(u.Fragment,{children:[u.jsx(Qt,{name:"model",label:l("openai.form.model.label"),required:!0,options:(f==null?void 0:f.map(x=>({label:x.id,value:x.id})))??[]}),u.jsx(Z,{name:"systemMessages",label:l("openai.form.systemMessages.label"),children:u.jsx(Nl,{})}),u.jsx(Z,{name:"assistantMessages",label:l("openai.form.assistantMessages.label"),children:u.jsx(Nl,{})}),u.jsx(Z,{name:"userMessages",label:l("openai.form.userMessages.label"),children:u.jsx(Nl,{})}),u.jsx(Z,{name:"maxTokens",label:l("openai.form.maxTokens.label"),children:u.jsx(Q,{type:"number"})})]}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:l("openai.form.triggerSettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"triggerType",label:l("openai.form.triggerType.label"),required:!0,options:[{label:l("openai.form.triggerType.keyword"),value:"keyword"},{label:l("openai.form.triggerType.all"),value:"all"},{label:l("openai.form.triggerType.advanced"),value:"advanced"},{label:l("openai.form.triggerType.none"),value:"none"}]}),m==="keyword"&&u.jsxs(u.Fragment,{children:[u.jsx(Qt,{name:"triggerOperator",label:l("openai.form.triggerOperator.label"),required:!0,options:[{label:l("openai.form.triggerOperator.contains"),value:"contains"},{label:l("openai.form.triggerOperator.equals"),value:"equals"},{label:l("openai.form.triggerOperator.startsWith"),value:"startsWith"},{label:l("openai.form.triggerOperator.endsWith"),value:"endsWith"},{label:l("openai.form.triggerOperator.regex"),value:"regex"}]}),u.jsx(Z,{name:"triggerValue",label:l("openai.form.triggerValue.label"),required:!0,children:u.jsx(Q,{})})]}),m==="advanced"&&u.jsx(Z,{name:"triggerValue",label:l("openai.form.triggerConditions.label"),required:!0,children:u.jsx(Q,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:l("openai.form.generalSettings.label")}),u.jsx($t,{})]}),u.jsx(Z,{name:"expire",label:l("openai.form.expire.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"keywordFinish",label:l("openai.form.keywordFinish.label"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"delayMessage",label:l("openai.form.delayMessage.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"unknownMessage",label:l("openai.form.unknownMessage.label"),children:u.jsx(Q,{})}),u.jsx(Pe,{name:"listeningFromMe",label:l("openai.form.listeningFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"stopBotFromMe",label:l("openai.form.stopBotFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"keepOpen",label:l("openai.form.keepOpen.label"),reverse:!0}),u.jsx(Z,{name:"debounceTime",label:l("openai.form.debounceTime.label"),children:u.jsx(Q,{type:"number"})})]}),s&&u.jsx(rn,{children:u.jsx(K,{disabled:o,type:"submit",children:l(o?"openai.button.saving":"openai.button.save")})}),!s&&u.jsxs("div",{children:[u.jsx(DI,{openaiId:r}),u.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[u.jsxs(Tt,{open:a,onOpenChange:i,children:[u.jsx(Mt,{asChild:!0,children:u.jsx(K,{variant:"destructive",size:"sm",children:l("dify.button.delete")})}),u.jsx(xt,{children:u.jsxs(wt,{children:[u.jsx(Ut,{children:l("modal.delete.title")}),u.jsx(Fi,{children:l("modal.delete.messageSingle")}),u.jsxs(rn,{children:[u.jsx(K,{size:"sm",variant:"outline",onClick:()=>i(!1),children:l("button.cancel")}),u.jsx(K,{variant:"destructive",onClick:n,children:l("button.delete")})]})]})})]}),u.jsx(K,{disabled:o,type:"submit",children:l(o?"openai.button.saving":"openai.button.update")})]})]})]})})}function rte({resetTable:e}){const{t}=ze(),{instance:n}=nt(),{createOpenai:r}=rf(),[s,o]=v.useState(!1),[a,i]=v.useState(!1),c=async l=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");o(!0);const h={enabled:l.enabled,description:l.description,openaiCredsId:l.openaiCredsId,botType:l.botType,assistantId:l.assistantId||"",functionUrl:l.functionUrl||"",model:l.model||"",systemMessages:[l.systemMessages||""],assistantMessages:[l.assistantMessages||""],userMessages:[l.userMessages||""],maxTokens:l.maxTokens||0,triggerType:l.triggerType,triggerOperator:l.triggerOperator||"",triggerValue:l.triggerValue||"",expire:l.expire||0,keywordFinish:l.keywordFinish||"",delayMessage:l.delayMessage||0,unknownMessage:l.unknownMessage||"",listeningFromMe:l.listeningFromMe||!1,stopBotFromMe:l.stopBotFromMe||!1,keepOpen:l.keepOpen||!1,debounceTime:l.debounceTime||0};await r({instanceName:n.name,token:n.token,data:h}),X.success(t("openai.toast.success.create")),i(!1),e()}catch(h){console.error("Error:",h),X.error(`Error: ${(f=(p=(d=h==null?void 0:h.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{o(!1)}};return u.jsxs(Tt,{open:a,onOpenChange:i,children:[u.jsx(Mt,{asChild:!0,children:u.jsxs(K,{size:"sm",children:[u.jsx(Mi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("openai.button.create")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("openai.form.title")})}),u.jsx(AI,{onSubmit:c,isModal:!0,isLoading:s,open:a})]})]})}const ste=e=>["openai","getOpenai",JSON.stringify(e)],ote=async({instanceName:e,token:t,openaiId:n})=>{const r=await he.get(`/openai/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},ate=e=>{const{instanceName:t,token:n,openaiId:r,...s}=e;return lt({...s,queryKey:ste({instanceName:t}),queryFn:()=>ote({instanceName:t,token:n,openaiId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function ite({openaiId:e,resetTable:t}){const{t:n}=ze(),{instance:r}=nt(),s=An(),[o,a]=v.useState(!1),{deleteOpenai:i,updateOpenai:c}=rf(),{data:l,isLoading:d}=ate({instanceName:r==null?void 0:r.name,openaiId:e}),p=v.useMemo(()=>({enabled:(l==null?void 0:l.enabled)??!0,description:(l==null?void 0:l.description)??"",openaiCredsId:(l==null?void 0:l.openaiCredsId)??"",botType:(l==null?void 0:l.botType)??"",assistantId:(l==null?void 0:l.assistantId)||"",functionUrl:(l==null?void 0:l.functionUrl)||"",model:(l==null?void 0:l.model)||"",systemMessages:Array.isArray(l==null?void 0:l.systemMessages)?l==null?void 0:l.systemMessages.join(", "):(l==null?void 0:l.systemMessages)||"",assistantMessages:Array.isArray(l==null?void 0:l.assistantMessages)?l==null?void 0:l.assistantMessages.join(", "):(l==null?void 0:l.assistantMessages)||"",userMessages:Array.isArray(l==null?void 0:l.userMessages)?l==null?void 0:l.userMessages.join(", "):(l==null?void 0:l.userMessages)||"",maxTokens:(l==null?void 0:l.maxTokens)||0,triggerType:(l==null?void 0:l.triggerType)||"",triggerOperator:(l==null?void 0:l.triggerOperator)||"",triggerValue:l==null?void 0:l.triggerValue,expire:(l==null?void 0:l.expire)||0,keywordFinish:l==null?void 0:l.keywordFinish,delayMessage:(l==null?void 0:l.delayMessage)||0,unknownMessage:l==null?void 0:l.unknownMessage,listeningFromMe:l==null?void 0:l.listeningFromMe,stopBotFromMe:l==null?void 0:l.stopBotFromMe,keepOpen:l==null?void 0:l.keepOpen,debounceTime:(l==null?void 0:l.debounceTime)||0}),[l==null?void 0:l.assistantId,l==null?void 0:l.assistantMessages,l==null?void 0:l.botType,l==null?void 0:l.debounceTime,l==null?void 0:l.delayMessage,l==null?void 0:l.description,l==null?void 0:l.enabled,l==null?void 0:l.expire,l==null?void 0:l.functionUrl,l==null?void 0:l.keepOpen,l==null?void 0:l.keywordFinish,l==null?void 0:l.listeningFromMe,l==null?void 0:l.maxTokens,l==null?void 0:l.model,l==null?void 0:l.openaiCredsId,l==null?void 0:l.stopBotFromMe,l==null?void 0:l.systemMessages,l==null?void 0:l.triggerOperator,l==null?void 0:l.triggerType,l==null?void 0:l.triggerValue,l==null?void 0:l.unknownMessage,l==null?void 0:l.userMessages]),f=async g=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:g.enabled,description:g.description,openaiCredsId:g.openaiCredsId,botType:g.botType,assistantId:g.assistantId||"",functionUrl:g.functionUrl||"",model:g.model||"",systemMessages:[g.systemMessages||""],assistantMessages:[g.assistantMessages||""],userMessages:[g.userMessages||""],maxTokens:g.maxTokens||0,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire||0,keywordFinish:g.keywordFinish||"",delayMessage:g.delayMessage||1e3,unknownMessage:g.unknownMessage||"",listeningFromMe:g.listeningFromMe||!1,stopBotFromMe:g.stopBotFromMe||!1,keepOpen:g.keepOpen||!1,debounceTime:g.debounceTime||0};await c({instanceName:r.name,openaiId:e,data:y}),X.success(n("openai.toast.success.update")),t(),s(`/manager/instance/${r.id}/openai/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),X.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},h=async()=>{try{r&&r.name&&e?(await i({instanceName:r.name,openaiId:e}),X.success(n("openai.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/openai`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir dify:",g)}};return d?u.jsx(wr,{}):u.jsx("div",{className:"m-4",children:u.jsx(AI,{initialData:p,onSubmit:f,openaiId:e,handleDelete:h,isModal:!1,isLoading:d,openDeletionDialog:o,setOpenDeletionDialog:a})})}function oE(){const{t:e}=ze(),t=Pu("(min-width: 768px)"),{instance:n}=nt(),{botId:r}=So(),{data:s,isLoading:o,refetch:a}=II({instanceName:n==null?void 0:n.name}),i=An(),c=d=>{n&&i(`/manager/instance/${n.id}/openai/${d}`)},l=()=>{a()};return u.jsxs("main",{className:"pt-5",children:[u.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[u.jsx("h3",{className:"text-lg font-medium",children:e("openai.title")}),u.jsxs("div",{className:"flex items-center justify-end gap-2",children:[u.jsx(DI,{}),u.jsx(Jee,{}),u.jsx(Hee,{}),u.jsx(rte,{resetTable:l})]})]}),u.jsx($t,{className:"my-4"}),u.jsxs(Ou,{direction:t?"horizontal":"vertical",children:[u.jsx(Ur,{defaultSize:35,className:"pr-4",children:u.jsx("div",{className:"flex flex-col gap-3",children:o?u.jsx(wr,{}):u.jsx(u.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>u.jsxs(K,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>c(`${d.id}`),variant:r===d.id?"secondary":"outline",children:[u.jsx("h4",{className:"text-base",children:d.description||d.id}),u.jsx("p",{className:"text-sm font-normal text-muted-foreground",children:d.botType})]},d.id)):u.jsx(K,{variant:"link",children:e("openai.table.none")})})})}),r&&u.jsxs(u.Fragment,{children:[u.jsx(Nu,{withHandle:!0,className:"border border-border"}),u.jsx(Ur,{children:u.jsx(ite,{openaiId:r,resetTable:l})})]})]})]})}const lte=e=>["proxy","fetchProxy",JSON.stringify(e)],ute=async({instanceName:e,token:t})=>(await he.get(`/proxy/find/${e}`,{headers:{apiKey:t}})).data,cte=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:lte({instanceName:t,token:n}),queryFn:()=>ute({instanceName:t,token:n}),enabled:!!t})},dte=async({instanceName:e,token:t,data:n})=>(await he.post(`/proxy/set/${e}`,n,{headers:{apikey:t}})).data;function fte(){return{createProxy:Ye(dte,{invalidateKeys:[["proxy","fetchProxy"]]})}}const pte=_.object({enabled:_.boolean(),host:_.string(),port:_.string(),protocol:_.string(),username:_.string(),password:_.string()});function hte(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{createProxy:s}=fte(),{data:o}=cte({instanceName:t==null?void 0:t.name}),a=sn({resolver:on(pte),defaultValues:{enabled:!1,host:"",port:"",protocol:"http",username:"",password:""}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,host:o.host,port:o.port,protocol:o.protocol,username:o.username,password:o.password})},[o]);const i=async c=>{var l,d,p;if(t){r(!0);try{const f={enabled:c.enabled,host:c.host,port:c.port,protocol:c.protocol,username:c.username,password:c.password};await s({instanceName:t.name,token:t.token,data:f}),X.success(e("proxy.toast.success"))}catch(f){console.error(e("proxy.toast.error"),f),X.error(`Error : ${(p=(d=(l=f==null?void 0:f.response)==null?void 0:l.data)==null?void 0:d.response)==null?void 0:p.message}`)}finally{r(!1)}}};return u.jsx(u.Fragment,{children:u.jsx(Ma,{...a,children:u.jsx("form",{onSubmit:a.handleSubmit(i),className:"w-full space-y-6",children:u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("proxy.title")}),u.jsx(Ra,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[u.jsx(Pe,{name:"enabled",label:e("proxy.form.enabled.label"),className:"w-full justify-between",helper:e("proxy.form.enabled.description")}),u.jsxs("div",{className:"grid gap-4 sm:grid-cols-[10rem_1fr_10rem] md:gap-8",children:[u.jsx(Z,{name:"protocol",label:e("proxy.form.protocol.label"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"host",label:e("proxy.form.host.label"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"port",label:e("proxy.form.port.label"),children:u.jsx(Q,{type:"number"})})]}),u.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 md:gap-8",children:[u.jsx(Z,{name:"username",label:e("proxy.form.username.label"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"password",label:e("proxy.form.password.label"),children:u.jsx(Q,{type:"password"})})]}),u.jsx("div",{className:"flex justify-end px-4 pt-6",children:u.jsx(K,{type:"submit",disabled:n,children:e(n?"proxy.button.saving":"proxy.button.save")})})]})]})})})})}const gte=e=>["rabbitmq","fetchRabbitmq",JSON.stringify(e)],mte=async({instanceName:e,token:t})=>(await he.get(`/rabbitmq/find/${e}`,{headers:{apiKey:t}})).data,vte=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:gte({instanceName:t,token:n}),queryFn:()=>mte({instanceName:t,token:n}),enabled:!!t})},yte=async({instanceName:e,token:t,data:n})=>(await he.post(`/rabbitmq/set/${e}`,{rabbitmq:n},{headers:{apikey:t}})).data;function bte(){return{createRabbitmq:Ye(yte,{invalidateKeys:[["rabbitmq","fetchRabbitmq"]]})}}const xte=_.object({enabled:_.boolean(),events:_.array(_.string())});function wte(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{createRabbitmq:s}=bte(),{data:o}=vte({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),a=sn({resolver:on(xte),defaultValues:{enabled:!1,events:[]}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,events:o.events})},[o]);const i=async p=>{var f,h,g;if(t){r(!0);try{const m={enabled:p.enabled,events:p.events};await s({instanceName:t.name,token:t.token,data:m}),X.success(e("rabbitmq.toast.success"))}catch(m){console.error(e("rabbitmq.toast.error"),m),X.error(`Error: ${(g=(h=(f=m==null?void 0:m.response)==null?void 0:f.data)==null?void 0:h.response)==null?void 0:g.message}`)}finally{r(!1)}}},c=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],l=()=>{a.setValue("events",c)},d=()=>{a.setValue("events",[])};return u.jsx(u.Fragment,{children:u.jsx(Ma,{...a,children:u.jsx("form",{onSubmit:a.handleSubmit(i),className:"w-full space-y-6",children:u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("rabbitmq.title")}),u.jsx(Ra,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[u.jsx(Pe,{name:"enabled",label:e("rabbitmq.form.enabled.label"),className:"w-full justify-between",helper:e("rabbitmq.form.enabled.description")}),u.jsxs("div",{className:"mb-4 flex justify-between",children:[u.jsx(K,{variant:"outline",type:"button",onClick:l,children:e("button.markAll")}),u.jsx(K,{variant:"outline",type:"button",onClick:d,children:e("button.unMarkAll")})]}),u.jsx(Ia,{control:a.control,name:"events",render:({field:p})=>u.jsxs(_o,{className:"flex flex-col",children:[u.jsx(xr,{className:"my-2 text-lg",children:e("rabbitmq.form.events.label")}),u.jsx(Vs,{children:u.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:c.sort((f,h)=>f.localeCompare(h)).map(f=>u.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[u.jsx(xr,{className:ge("break-all",p.value.includes(f)?"text-foreground":"text-muted-foreground"),children:f}),u.jsx(ju,{checked:p.value.includes(f),onCheckedChange:h=>{h?p.onChange([...p.value,f]):p.onChange(p.value.filter(g=>g!==f))}})]},f))})})]})})]}),u.jsx("div",{className:"mx-4 flex justify-end pt-6",children:u.jsx(K,{type:"submit",disabled:n,children:e(n?"rabbitmq.button.saving":"rabbitmq.button.save")})})]})})})})}const Ste=e=>["instance","fetchSettings",JSON.stringify(e)],Cte=async({instanceName:e,token:t})=>(await he.get(`/settings/find/${e}`,{headers:{apikey:t}})).data,Ete=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:Ste({instanceName:t,token:n}),queryFn:()=>Cte({instanceName:t,token:n}),enabled:!!t})},Tte=_.object({rejectCall:_.boolean(),msgCall:_.string().optional(),groupsIgnore:_.boolean(),alwaysOnline:_.boolean(),readMessages:_.boolean(),syncFullHistory:_.boolean(),readStatus:_.boolean()});function kte(){const{t:e}=ze(),[t,n]=v.useState(!1),{instance:r}=nt(),{updateSettings:s}=_g(),{data:o,isLoading:a}=Ete({instanceName:r==null?void 0:r.name,token:r==null?void 0:r.token}),i=sn({resolver:on(Tte),defaultValues:{rejectCall:!1,msgCall:"",groupsIgnore:!1,alwaysOnline:!1,readMessages:!1,syncFullHistory:!1,readStatus:!1}});v.useEffect(()=>{o&&i.reset({rejectCall:o.rejectCall,msgCall:o.msgCall||"",groupsIgnore:o.groupsIgnore,alwaysOnline:o.alwaysOnline,readMessages:o.readMessages,syncFullHistory:o.syncFullHistory,readStatus:o.readStatus})},[i,o]);const c=async p=>{try{if(!r||!r.name)throw new Error("instance not found");n(!0);const f={rejectCall:p.rejectCall,msgCall:p.msgCall,groupsIgnore:p.groupsIgnore,alwaysOnline:p.alwaysOnline,readMessages:p.readMessages,syncFullHistory:p.syncFullHistory,readStatus:p.readStatus};await s({instanceName:r.name,token:r.token,data:f}),X.success(e("settings.toast.success"))}catch(f){console.error(e("settings.toast.success"),f),X.error(e("settings.toast.error"))}finally{n(!1)}},l=[{name:"groupsIgnore",label:e("settings.form.groupsIgnore.label"),description:e("settings.form.groupsIgnore.description")},{name:"alwaysOnline",label:e("settings.form.alwaysOnline.label"),description:e("settings.form.alwaysOnline.description")},{name:"readMessages",label:e("settings.form.readMessages.label"),description:e("settings.form.readMessages.description")},{name:"syncFullHistory",label:e("settings.form.syncFullHistory.label"),description:e("settings.form.syncFullHistory.description")},{name:"readStatus",label:e("settings.form.readStatus.label"),description:e("settings.form.readStatus.description")}],d=i.watch("rejectCall");return a?u.jsx(wr,{}):u.jsx(u.Fragment,{children:u.jsx(Ma,{...i,children:u.jsx("form",{onSubmit:i.handleSubmit(c),className:"w-full space-y-6",children:u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("settings.title")}),u.jsx($t,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y",children:[u.jsxs("div",{className:"flex flex-col p-4",children:[u.jsx(Pe,{name:"rejectCall",label:e("settings.form.rejectCall.label"),className:"w-full justify-between",helper:e("settings.form.rejectCall.description")}),d&&u.jsx("div",{className:"mr-16 mt-2",children:u.jsx(Z,{name:"msgCall",children:u.jsx(Nl,{placeholder:e("settings.form.msgCall.description")})})})]}),l.map(p=>u.jsx("div",{className:"flex p-4",children:u.jsx(Pe,{name:p.name,label:p.label,className:"w-full justify-between",helper:p.description})},p.name)),u.jsx("div",{className:"flex justify-end pt-6",children:u.jsx(K,{type:"submit",disabled:t,children:e(t?"settings.button.saving":"settings.button.save")})})]})]})})})})}const _te=e=>["sqs","fetchSqs",JSON.stringify(e)],jte=async({instanceName:e,token:t})=>(await he.get(`/sqs/find/${e}`,{headers:{apiKey:t}})).data,Rte=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:_te({instanceName:t,token:n}),queryFn:()=>jte({instanceName:t,token:n}),enabled:!!t})},Ote=async({instanceName:e,token:t,data:n})=>(await he.post(`/sqs/set/${e}`,{sqs:n},{headers:{apikey:t}})).data;function Nte(){return{createSqs:Ye(Ote,{invalidateKeys:[["sqs","fetchSqs"]]})}}const Pte=_.object({enabled:_.boolean(),events:_.array(_.string())});function Mte(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{createSqs:s}=Nte(),{data:o}=Rte({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),a=sn({resolver:on(Pte),defaultValues:{enabled:!1,events:[]}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,events:o.events})},[o]);const i=async p=>{var f,h,g;if(t){r(!0);try{const m={enabled:p.enabled,events:p.events};await s({instanceName:t.name,token:t.token,data:m}),X.success(e("sqs.toast.success"))}catch(m){console.error(e("sqs.toast.error"),m),X.error(`Error: ${(g=(h=(f=m==null?void 0:m.response)==null?void 0:f.data)==null?void 0:h.response)==null?void 0:g.message}`)}finally{r(!1)}}},c=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],l=()=>{a.setValue("events",c)},d=()=>{a.setValue("events",[])};return u.jsx(u.Fragment,{children:u.jsx(Ma,{...a,children:u.jsx("form",{onSubmit:a.handleSubmit(i),className:"w-full space-y-6",children:u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("sqs.title")}),u.jsx(Ra,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[u.jsx(Pe,{name:"enabled",label:e("sqs.form.enabled.label"),className:"w-full justify-between",helper:e("sqs.form.enabled.description")}),u.jsxs("div",{className:"mb-4 flex justify-between",children:[u.jsx(K,{variant:"outline",type:"button",onClick:l,children:e("button.markAll")}),u.jsx(K,{variant:"outline",type:"button",onClick:d,children:e("button.unMarkAll")})]}),u.jsx(Ia,{control:a.control,name:"events",render:({field:p})=>u.jsxs(_o,{className:"flex flex-col",children:[u.jsx(xr,{className:"my-2 text-lg",children:e("sqs.form.events.label")}),u.jsx(Vs,{children:u.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:c.sort((f,h)=>f.localeCompare(h)).map(f=>u.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[u.jsx(xr,{className:ge("break-all",p.value.includes(f)?"text-foreground":"text-muted-foreground"),children:f}),u.jsx(ju,{checked:p.value.includes(f),onCheckedChange:h=>{h?p.onChange([...p.value,f]):p.onChange(p.value.filter(g=>g!==f))}})]},f))})})]})})]}),u.jsx("div",{className:"mx-4 flex justify-end pt-6",children:u.jsx(K,{type:"submit",disabled:n,children:e(n?"sqs.button.saving":"sqs.button.save")})})]})})})})}const Ite=e=>["typebot","findTypebot",JSON.stringify(e)],Dte=async({instanceName:e,token:t})=>(await he.get(`/typebot/find/${e}`,{headers:{apiKey:t}})).data,FI=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:Ite({instanceName:t}),queryFn:()=>Dte({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Ate=e=>["typebot","fetchDefaultSettings",JSON.stringify(e)],Fte=async({instanceName:e,token:t})=>{const n=await he.get(`/typebot/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},Lte=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:Ate({instanceName:t}),queryFn:()=>Fte({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},$te=async({instanceName:e,token:t,data:n})=>(await he.post(`/typebot/create/${e}`,n,{headers:{apikey:t}})).data,Bte=async({instanceName:e,token:t,typebotId:n,data:r})=>(await he.put(`/typebot/update/${n}/${e}`,r,{headers:{apikey:t}})).data,zte=async({instanceName:e,typebotId:t})=>(await he.delete(`/typebot/delete/${t}/${e}`)).data,Ute=async({instanceName:e,token:t,data:n})=>(await he.post(`/typebot/settings/${e}`,n,{headers:{apikey:t}})).data,Vte=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await he.post(`/typebot/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function tm(){const e=Ye(Ute,{invalidateKeys:[["typebot","fetchDefaultSettings"]]}),t=Ye(Vte,{invalidateKeys:[["typebot","getTypebot"],["typebot","fetchSessions"]]}),n=Ye(zte,{invalidateKeys:[["typebot","getTypebot"],["typebot","findTypebot"],["typebot","fetchSessions"]]}),r=Ye(Bte,{invalidateKeys:[["typebot","getTypebot"],["typebot","findTypebot"],["typebot","fetchSessions"]]}),s=Ye($te,{invalidateKeys:[["typebot","findTypebot"]]});return{setDefaultSettingsTypebot:e,changeStatusTypebot:t,deleteTypebot:n,updateTypebot:r,createTypebot:s}}const Hte=_.object({expire:_.coerce.number(),keywordFinish:_.string(),delayMessage:_.coerce.number(),unknownMessage:_.string(),listeningFromMe:_.boolean(),stopBotFromMe:_.boolean(),keepOpen:_.boolean(),debounceTime:_.coerce.number(),ignoreJids:_.array(_.string()).default([]),typebotIdFallback:_.union([_.null(),_.string()]).optional()});function Kte(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{setDefaultSettingsTypebot:s}=tm(),{data:o,refetch:a}=Lte({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token,enabled:n}),{data:i,refetch:c}=FI({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token,enabled:n}),l=sn({resolver:on(Hte),defaultValues:{expire:0,keywordFinish:e("typebot.form.examples.keywordFinish"),delayMessage:1e3,unknownMessage:e("typebot.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,ignoreJids:[],typebotIdFallback:void 0}});v.useEffect(()=>{o&&l.reset({expire:(o==null?void 0:o.expire)??0,keywordFinish:o.keywordFinish,delayMessage:o.delayMessage??0,unknownMessage:o.unknownMessage,listeningFromMe:o.listeningFromMe,stopBotFromMe:o.stopBotFromMe,keepOpen:o.keepOpen,debounceTime:o.debounceTime??0,ignoreJids:o.ignoreJids,typebotIdFallback:o.typebotIdFallback})},[o]);const d=async f=>{var h,g,m;try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:f.expire,keywordFinish:f.keywordFinish,delayMessage:f.delayMessage,unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:f.debounceTime,typebotIdFallback:f.typebotIdFallback||void 0,ignoreJids:f.ignoreJids};await s({instanceName:t.name,token:t.token,data:x}),X.success(e("typebot.toast.defaultSettings.success"))}catch(x){console.error(e("typebot.toast.defaultSettings.error"),x),X.error(`Error: ${(m=(g=(h=x==null?void 0:x.response)==null?void 0:h.data)==null?void 0:g.response)==null?void 0:m.message}`)}};function p(){a(),c()}return u.jsxs(Tt,{open:n,onOpenChange:r,children:[u.jsx(Mt,{asChild:!0,children:u.jsxs(K,{variant:"secondary",size:"sm",children:[u.jsx(Pi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:e("typebot.button.defaultSettings")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[u.jsx(wt,{children:u.jsx(Ut,{children:e("typebot.modal.defaultSettings.title")})}),u.jsx(Tr,{...l,children:u.jsxs("form",{className:"w-full space-y-6",onSubmit:l.handleSubmit(d),children:[u.jsx("div",{children:u.jsxs("div",{className:"space-y-4",children:[u.jsx(Qt,{name:"typebotIdFallback",label:e("typebot.form.typebotIdFallback.label"),options:(i==null?void 0:i.filter(f=>!!f.id).map(f=>({label:f.typebot,value:f.description})))??[]}),u.jsx(Z,{name:"expire",label:e("typebot.form.expire.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"keywordFinish",label:e("typebot.form.keywordFinish.label"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"delayMessage",label:e("typebot.form.delayMessage.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"unknownMessage",label:e("typebot.form.unknownMessage.label"),children:u.jsx(Q,{})}),u.jsx(Pe,{name:"listeningFromMe",label:e("typebot.form.listeningFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"stopBotFromMe",label:e("typebot.form.stopBotFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"keepOpen",label:e("typebot.form.keepOpen.label"),reverse:!0}),u.jsx(Z,{name:"debounceTime",label:e("typebot.form.debounceTime.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Ru,{name:"ignoreJids",label:e("typebot.form.ignoreJids.label"),placeholder:e("typebot.form.ignoreJids.placeholder")})]})}),u.jsx(rn,{children:u.jsx(K,{type:"submit",children:e("typebot.button.save")})})]})})]})]})}const qte=e=>["typebot","fetchSessions",JSON.stringify(e)],Wte=async({instanceName:e,typebotId:t,token:n})=>(await he.get(`/typebot/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,Gte=e=>{const{instanceName:t,token:n,typebotId:r,...s}=e;return lt({...s,queryKey:qte({instanceName:t}),queryFn:()=>Wte({instanceName:t,token:n,typebotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function LI({typebotId:e}){const{t}=ze(),{instance:n}=nt(),[r,s]=v.useState([]),[o,a]=v.useState(!1),[i,c]=v.useState(""),{changeStatusTypebot:l}=tm(),{data:d,refetch:p}=Gte({instanceName:n==null?void 0:n.name,token:n==null?void 0:n.token,typebotId:e});function f(){p()}const h=async(m,x)=>{var b,y,w;try{if(!n)return;await l({instanceName:n.name,token:n.token,remoteJid:m,status:x}),X.success(t("typebot.toast.success.status")),f()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},g=[{accessorKey:"remoteJid",header:()=>u.jsx("div",{className:"text-center",children:t("typebot.sessions.table.remoteJid")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>u.jsx("div",{className:"text-center",children:t("typebot.sessions.table.pushName")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>u.jsx("div",{className:"text-center",children:t("typebot.sessions.table.sessionId")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>u.jsx("div",{className:"text-center",children:t("typebot.sessions.table.status")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(K,{variant:"ghost",className:"h-8 w-8 p-0",children:[u.jsx("span",{className:"sr-only",children:t("typebot.sessions.table.actions.title")}),u.jsx(vu,{className:"h-4 w-4"})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(Ai,{children:"Actions"}),u.jsx(Oa,{}),x.status!=="opened"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"opened"),children:[u.jsx(qd,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"paused"),children:[u.jsx(Kd,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.pause")]}),x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"closed"),children:[u.jsx(Ud,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.close")]}),u.jsxs(ft,{onClick:()=>h(x.remoteJid,"delete"),children:[u.jsx(Vd,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.delete")]})]})]})}}];return u.jsxs(Tt,{open:o,onOpenChange:a,children:[u.jsx(Mt,{asChild:!0,children:u.jsxs(K,{variant:"secondary",size:"sm",children:[u.jsx(Hd,{size:16,className:"mr-1"})," ",u.jsx("span",{className:"hidden sm:inline",children:t("typebot.sessions.label")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("typebot.sessions.label")})}),u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[u.jsx(Q,{placeholder:t("typebot.sessions.search"),value:i,onChange:m=>c(m.target.value)}),u.jsx(K,{variant:"outline",onClick:f,size:"icon",children:u.jsx(Wd,{size:16})})]}),u.jsx(Mu,{columns:g,data:d??[],onSortingChange:s,state:{sorting:r,globalFilter:i},onGlobalFilterChange:c,enableGlobalFilter:!0,noResultsMessage:t("typebot.sessions.table.none")})]})]})]})}const Jte=_.object({enabled:_.boolean(),description:_.string(),url:_.string(),typebot:_.string().optional(),triggerType:_.string(),triggerOperator:_.string().optional(),triggerValue:_.string().optional(),expire:_.coerce.number().optional(),keywordFinish:_.string().optional(),delayMessage:_.coerce.number().optional(),unknownMessage:_.string().optional(),listeningFromMe:_.boolean().optional(),stopBotFromMe:_.boolean().optional(),keepOpen:_.boolean().optional(),debounceTime:_.coerce.number().optional()});function $I({initialData:e,onSubmit:t,handleDelete:n,typebotId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:i=()=>{}}){const{t:c}=ze(),l=sn({resolver:on(Jte),defaultValues:e||{enabled:!0,description:"",url:"",typebot:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}}),d=l.watch("triggerType");return u.jsx(Tr,{...l,children:u.jsxs("form",{onSubmit:l.handleSubmit(t),className:"w-full space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsx(Pe,{name:"enabled",label:c("typebot.form.enabled.label"),reverse:!0}),u.jsx(Z,{name:"description",label:c("typebot.form.description.label"),required:!0,children:u.jsx(Q,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("typebot.form.typebotSettings.label")}),u.jsx($t,{})]}),u.jsx(Z,{name:"url",label:c("typebot.form.url.label"),required:!0,children:u.jsx(Q,{})}),u.jsx(Z,{name:"typebot",label:c("typebot.form.typebot.label"),children:u.jsx(Q,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("typebot.form.triggerSettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"triggerType",label:c("typebot.form.triggerType.label"),options:[{label:c("typebot.form.triggerType.keyword"),value:"keyword"},{label:c("typebot.form.triggerType.all"),value:"all"},{label:c("typebot.form.triggerType.advanced"),value:"advanced"},{label:c("typebot.form.triggerType.none"),value:"none"}]}),d==="keyword"&&u.jsxs(u.Fragment,{children:[u.jsx(Qt,{name:"triggerOperator",label:c("typebot.form.triggerOperator.label"),options:[{label:c("typebot.form.triggerOperator.contains"),value:"contains"},{label:c("typebot.form.triggerOperator.equals"),value:"equals"},{label:c("typebot.form.triggerOperator.startsWith"),value:"startsWith"},{label:c("typebot.form.triggerOperator.endsWith"),value:"endsWith"},{label:c("typebot.form.triggerOperator.regex"),value:"regex"}]}),u.jsx(Z,{name:"triggerValue",label:c("typebot.form.triggerValue.label"),children:u.jsx(Q,{})})]}),d==="advanced"&&u.jsx(Z,{name:"triggerValue",label:c("typebot.form.triggerConditions.label"),children:u.jsx(Q,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("typebot.form.generalSettings.label")}),u.jsx($t,{})]}),u.jsx(Z,{name:"expire",label:c("typebot.form.expire.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"keywordFinish",label:c("typebot.form.keywordFinish.label"),children:u.jsx(Q,{})}),u.jsx(Z,{name:"delayMessage",label:c("typebot.form.delayMessage.label"),children:u.jsx(Q,{type:"number"})}),u.jsx(Z,{name:"unknownMessage",label:c("typebot.form.unknownMessage.label"),children:u.jsx(Q,{})}),u.jsx(Pe,{name:"listeningFromMe",label:c("typebot.form.listeningFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"stopBotFromMe",label:c("typebot.form.stopBotFromMe.label"),reverse:!0}),u.jsx(Pe,{name:"keepOpen",label:c("typebot.form.keepOpen.label"),reverse:!0}),u.jsx(Z,{name:"debounceTime",label:c("typebot.form.debounceTime.label"),children:u.jsx(Q,{type:"number"})})]}),s&&u.jsx(rn,{children:u.jsx(K,{disabled:o,type:"submit",children:c(o?"typebot.button.saving":"typebot.button.save")})}),!s&&u.jsxs("div",{children:[u.jsx(LI,{typebotId:r}),u.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[u.jsxs(Tt,{open:a,onOpenChange:i,children:[u.jsx(Mt,{asChild:!0,children:u.jsx(K,{variant:"destructive",size:"sm",children:c("dify.button.delete")})}),u.jsx(xt,{children:u.jsxs(wt,{children:[u.jsx(Ut,{children:c("modal.delete.title")}),u.jsx(Fi,{children:c("modal.delete.messageSingle")}),u.jsxs(rn,{children:[u.jsx(K,{size:"sm",variant:"outline",onClick:()=>i(!1),children:c("button.cancel")}),u.jsx(K,{variant:"destructive",onClick:n,children:c("button.delete")})]})]})})]}),u.jsx(K,{disabled:o,type:"submit",children:c(o?"typebot.button.saving":"typebot.button.update")})]})]})]})})}function Qte({resetTable:e}){const{t}=ze(),{instance:n}=nt(),{createTypebot:r}=tm(),[s,o]=v.useState(!1),[a,i]=v.useState(!1),c=async l=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");o(!0);const h={enabled:l.enabled,description:l.description,url:l.url,typebot:l.typebot||"",triggerType:l.triggerType,triggerOperator:l.triggerOperator||"",triggerValue:l.triggerValue||"",expire:l.expire||0,keywordFinish:l.keywordFinish||"",delayMessage:l.delayMessage||0,unknownMessage:l.unknownMessage||"",listeningFromMe:l.listeningFromMe||!1,stopBotFromMe:l.stopBotFromMe||!1,keepOpen:l.keepOpen||!1,debounceTime:l.debounceTime||0};await r({instanceName:n.name,token:n.token,data:h}),X.success(t("typebot.toast.success.create")),i(!1),e()}catch(h){console.error("Error:",h),X.error(`Error: ${(f=(p=(d=h==null?void 0:h.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{o(!1)}};return u.jsxs(Tt,{open:a,onOpenChange:i,children:[u.jsx(Mt,{asChild:!0,children:u.jsxs(K,{size:"sm",children:[u.jsx(Mi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("typebot.button.create")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("typebot.form.title")})}),u.jsx($I,{onSubmit:c,isModal:!0,isLoading:s})]})]})}const Zte=e=>["typebot","getTypebot",JSON.stringify(e)],Yte=async({instanceName:e,token:t,typebotId:n})=>{const r=await he.get(`/typebot/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},Xte=e=>{const{instanceName:t,token:n,typebotId:r,...s}=e;return lt({...s,queryKey:Zte({instanceName:t}),queryFn:()=>Yte({instanceName:t,token:n,typebotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function ene({typebotId:e,resetTable:t}){const{t:n}=ze(),{instance:r}=nt(),s=An(),[o,a]=v.useState(!1),{deleteTypebot:i,updateTypebot:c}=tm(),{data:l,isLoading:d}=Xte({instanceName:r==null?void 0:r.name,typebotId:e}),p=v.useMemo(()=>({enabled:!!(l!=null&&l.enabled),description:(l==null?void 0:l.description)??"",url:(l==null?void 0:l.url)??"",typebot:(l==null?void 0:l.typebot)??"",triggerType:(l==null?void 0:l.triggerType)??"",triggerOperator:(l==null?void 0:l.triggerOperator)??"",triggerValue:l==null?void 0:l.triggerValue,expire:(l==null?void 0:l.expire)??0,keywordFinish:l==null?void 0:l.keywordFinish,delayMessage:(l==null?void 0:l.delayMessage)??0,unknownMessage:l==null?void 0:l.unknownMessage,listeningFromMe:!!(l!=null&&l.listeningFromMe),stopBotFromMe:!!(l!=null&&l.stopBotFromMe),keepOpen:!!(l!=null&&l.keepOpen),debounceTime:(l==null?void 0:l.debounceTime)??0}),[l==null?void 0:l.debounceTime,l==null?void 0:l.delayMessage,l==null?void 0:l.description,l==null?void 0:l.enabled,l==null?void 0:l.expire,l==null?void 0:l.keepOpen,l==null?void 0:l.keywordFinish,l==null?void 0:l.listeningFromMe,l==null?void 0:l.stopBotFromMe,l==null?void 0:l.triggerOperator,l==null?void 0:l.triggerType,l==null?void 0:l.triggerValue,l==null?void 0:l.typebot,l==null?void 0:l.unknownMessage,l==null?void 0:l.url]),f=async g=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:g.enabled,description:g.description,url:g.url,typebot:g.typebot||"",triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire||0,keywordFinish:g.keywordFinish||"",delayMessage:g.delayMessage||1e3,unknownMessage:g.unknownMessage||"",listeningFromMe:g.listeningFromMe||!1,stopBotFromMe:g.stopBotFromMe||!1,keepOpen:g.keepOpen||!1,debounceTime:g.debounceTime||0};await c({instanceName:r.name,typebotId:e,data:y}),X.success(n("typebot.toast.success.update")),t(),s(`/manager/instance/${r.id}/typebot/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),X.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},h=async()=>{try{r&&r.name&&e?(await i({instanceName:r.name,typebotId:e}),X.success(n("typebot.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/typebot`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir dify:",g)}};return d?u.jsx(wr,{}):u.jsx("div",{className:"m-4",children:u.jsx($I,{initialData:p,onSubmit:f,typebotId:e,handleDelete:h,isModal:!1,isLoading:d,openDeletionDialog:o,setOpenDeletionDialog:a})})}function aE(){const{t:e}=ze(),t=Pu("(min-width: 768px)"),{instance:n}=nt(),{typebotId:r}=So(),{data:s,isLoading:o,refetch:a}=FI({instanceName:n==null?void 0:n.name,token:n==null?void 0:n.token}),i=An(),c=d=>{n&&i(`/manager/instance/${n.id}/typebot/${d}`)},l=()=>{a()};return u.jsxs("main",{className:"pt-5",children:[u.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[u.jsx("h3",{className:"text-lg font-medium",children:e("typebot.title")}),u.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[u.jsx(LI,{}),u.jsx(Kte,{}),u.jsx(Qte,{resetTable:l})]})]}),u.jsx($t,{className:"my-4"}),u.jsxs(Ou,{direction:t?"horizontal":"vertical",children:[u.jsx(Ur,{defaultSize:35,className:"pr-4",children:u.jsx("div",{className:"flex flex-col gap-3",children:o?u.jsx(wr,{}):u.jsx(u.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>u.jsx(K,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>c(`${d.id}`),variant:r===d.id?"secondary":"outline",children:d.description?u.jsxs(u.Fragment,{children:[u.jsx("h4",{className:"text-base",children:d.description}),u.jsxs("p",{className:"text-wrap text-sm font-normal text-muted-foreground",children:[d.url," - ",d.typebot]})]}):u.jsxs(u.Fragment,{children:[u.jsx("h4",{className:"text-base",children:d.url}),u.jsx("p",{className:"text-wrap text-sm font-normal text-muted-foreground",children:d.typebot})]})},d.id)):u.jsx(K,{variant:"link",children:e("typebot.table.none")})})})}),r&&u.jsxs(u.Fragment,{children:[u.jsx(Nu,{withHandle:!0,className:"border border-black"}),u.jsx(Ur,{children:u.jsx(ene,{typebotId:r,resetTable:l})})]})]})]})}const tne=e=>["webhook","fetchWebhook",JSON.stringify(e)],nne=async({instanceName:e,token:t})=>(await he.get(`/webhook/find/${e}`,{headers:{apiKey:t}})).data,rne=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:tne({instanceName:t,token:n}),queryFn:()=>nne({instanceName:t,token:n}),enabled:!!t})},sne=async({instanceName:e,token:t,data:n})=>(await he.post(`/webhook/set/${e}`,{webhook:n},{headers:{apikey:t}})).data;function one(){return{createWebhook:Ye(sne,{invalidateKeys:[["webhook","fetchWebhook"]]})}}const ane=_.object({enabled:_.boolean(),url:_.string().url("Invalid URL format"),events:_.array(_.string()),base64:_.boolean(),byEvents:_.boolean()});function ine(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{createWebhook:s}=one(),{data:o}=rne({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),a=sn({resolver:on(ane),defaultValues:{enabled:!1,url:"",events:[],base64:!1,byEvents:!1}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,url:o.url,events:o.events,base64:o.webhookBase64,byEvents:o.webhookByEvents})},[o]);const i=async p=>{var f,h,g;if(t){r(!0);try{const m={enabled:p.enabled,url:p.url,events:p.events,base64:p.base64,byEvents:p.byEvents};await s({instanceName:t.name,token:t.token,data:m}),X.success(e("webhook.toast.success"))}catch(m){console.error(e("webhook.toast.error"),m),X.error(`Error: ${(g=(h=(f=m==null?void 0:m.response)==null?void 0:f.data)==null?void 0:h.response)==null?void 0:g.message}`)}finally{r(!1)}}},c=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],l=()=>{a.setValue("events",c)},d=()=>{a.setValue("events",[])};return u.jsx(u.Fragment,{children:u.jsx(Ma,{...a,children:u.jsx("form",{onSubmit:a.handleSubmit(i),className:"w-full space-y-6",children:u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("webhook.title")}),u.jsx(Ra,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[u.jsx(Pe,{name:"enabled",label:e("webhook.form.enabled.label"),className:"w-full justify-between",helper:e("webhook.form.enabled.description")}),u.jsx(Z,{name:"url",label:"URL",children:u.jsx(Q,{})}),u.jsx(Pe,{name:"byEvents",label:e("webhook.form.byEvents.label"),className:"w-full justify-between",helper:e("webhook.form.byEvents.description")}),u.jsx(Pe,{name:"base64",label:e("webhook.form.base64.label"),className:"w-full justify-between",helper:e("webhook.form.base64.description")}),u.jsxs("div",{className:"mb-4 flex justify-between",children:[u.jsx(K,{variant:"outline",type:"button",onClick:l,children:e("button.markAll")}),u.jsx(K,{variant:"outline",type:"button",onClick:d,children:e("button.unMarkAll")})]}),u.jsx(Ia,{control:a.control,name:"events",render:({field:p})=>u.jsxs(_o,{className:"flex flex-col",children:[u.jsx(xr,{className:"my-2 text-lg",children:e("webhook.form.events.label")}),u.jsx(Vs,{children:u.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:c.sort((f,h)=>f.localeCompare(h)).map(f=>u.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[u.jsx(xr,{className:ge("break-all",p.value.includes(f)?"text-foreground":"text-muted-foreground"),children:f}),u.jsx(ju,{checked:p.value.includes(f),onCheckedChange:h=>{h?p.onChange([...p.value,f]):p.onChange(p.value.filter(g=>g!==f))}})]},f))})})]})})]}),u.jsx("div",{className:"mx-4 flex justify-end pt-6",children:u.jsx(K,{type:"submit",disabled:n,children:e(n?"webhook.button.saving":"webhook.button.save")})})]})})})})}const lne=e=>["websocket","fetchWebsocket",JSON.stringify(e)],une=async({instanceName:e,token:t})=>(await he.get(`/websocket/find/${e}`,{headers:{apiKey:t}})).data,cne=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:lne({instanceName:t,token:n}),queryFn:()=>une({instanceName:t,token:n}),enabled:!!t})},dne=async({instanceName:e,token:t,data:n})=>(await he.post(`/websocket/set/${e}`,{websocket:n},{headers:{apikey:t}})).data;function fne(){return{createWebsocket:Ye(dne,{invalidateKeys:[["websocket","fetchWebsocket"]]})}}const pne=_.object({enabled:_.boolean(),events:_.array(_.string())});function hne(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{createWebsocket:s}=fne(),{data:o}=cne({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),a=sn({resolver:on(pne),defaultValues:{enabled:!1,events:[]}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,events:o.events})},[o]);const i=async p=>{var f,h,g;if(t){r(!0);try{const m={enabled:p.enabled,events:p.events};await s({instanceName:t.name,token:t.token,data:m}),X.success(e("websocket.toast.success"))}catch(m){console.error(e("websocket.toast.error"),m),X.error(`Error: ${(g=(h=(f=m==null?void 0:m.response)==null?void 0:f.data)==null?void 0:h.response)==null?void 0:g.message}`)}finally{r(!1)}}},c=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],l=()=>{a.setValue("events",c)},d=()=>{a.setValue("events",[])};return u.jsx(u.Fragment,{children:u.jsx(Ma,{...a,children:u.jsx("form",{onSubmit:a.handleSubmit(i),className:"w-full space-y-6",children:u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("websocket.title")}),u.jsx(Ra,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[u.jsx(Pe,{name:"enabled",label:e("websocket.form.enabled.label"),className:"w-full justify-between",helper:e("websocket.form.enabled.description")}),u.jsxs("div",{className:"mb-4 flex justify-between",children:[u.jsx(K,{variant:"outline",type:"button",onClick:l,children:e("button.markAll")}),u.jsx(K,{variant:"outline",type:"button",onClick:d,children:e("button.unMarkAll")})]}),u.jsx(Ia,{control:a.control,name:"events",render:({field:p})=>u.jsxs(_o,{className:"flex flex-col",children:[u.jsx(xr,{className:"my-2 text-lg",children:e("websocket.form.events.label")}),u.jsx(Vs,{children:u.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:c.sort((f,h)=>f.localeCompare(h)).map(f=>u.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[u.jsx(xr,{className:ge("break-all",p.value.includes(f)?"text-foreground":"text-muted-foreground"),children:f}),u.jsx(ju,{checked:p.value.includes(f),onCheckedChange:h=>{h?p.onChange([...p.value,f]):p.onChange(p.value.filter(g=>g!==f))}})]},f))})})]})})]}),u.jsx("div",{className:"mx-4 flex justify-end pt-6",children:u.jsx(K,{type:"submit",disabled:n,children:e(n?"websocket.button.saving":"websocket.button.save")})})]})})})})}const gne=async({url:e,token:t})=>{try{const{data:n}=await zt.post(`${e}/verify-creds`,{},{headers:{apikey:t}});return O_({facebookAppId:n.facebookAppId,facebookConfigId:n.facebookConfigId,facebookUserToken:n.facebookUserToken}),n}catch{return null}},mne=_.object({serverUrl:_.string({required_error:"serverUrl is required"}).url("URL inválida"),apiKey:_.string({required_error:"ApiKey is required"})});function vne(){const{t:e}=ze(),t=An(),n=sn({resolver:on(mne),defaultValues:{serverUrl:window.location.protocol+"//"+window.location.host,apiKey:""}}),r=async s=>{const o=await nj({url:s.serverUrl});if(!o||!o.version){N_(),n.setError("serverUrl",{type:"manual",message:e("login.message.invalidServer")});return}if(!await gne({token:s.apiKey,url:s.serverUrl})){n.setError("apiKey",{type:"manual",message:e("login.message.invalidCredentials")});return}O_({version:o.version,clientName:o.clientName,url:s.serverUrl,token:s.apiKey}),t("/manager/")};return u.jsxs("div",{className:"flex min-h-screen flex-col",children:[u.jsx("div",{className:"flex items-center justify-center pt-2",children:u.jsx("img",{className:"h-10",src:"/assets/images/evolution-logo.png",alt:"logo"})}),u.jsx("div",{className:"flex flex-1 items-center justify-center p-8",children:u.jsxs(Ja,{className:"b-none w-[350px] shadow-none",children:[u.jsxs(Qa,{children:[u.jsx(jc,{className:"text-center",children:e("login.title")}),u.jsx(JO,{className:"text-center",children:e("login.description")})]}),u.jsx(Ma,{...n,children:u.jsxs("form",{onSubmit:n.handleSubmit(r),children:[u.jsx(Za,{children:u.jsxs("div",{className:"grid w-full items-center gap-4",children:[u.jsx(Z,{required:!0,name:"serverUrl",label:e("login.form.serverUrl"),children:u.jsx(Q,{})}),u.jsx(Z,{required:!0,name:"apiKey",label:e("login.form.apiKey"),children:u.jsx(Q,{type:"password"})})]})}),u.jsx(kg,{className:"flex justify-center",children:u.jsx(K,{className:"w-full",type:"submit",children:e("login.button.login")})})]})})]})}),u.jsx(Ax,{})]})}const yne=PL([{path:"/manager/login",element:u.jsx(l$,{children:u.jsx(vne,{})})},{path:"/manager/",element:u.jsx(Gt,{children:u.jsx(SV,{children:u.jsx(GQ,{})})})},{path:"/manager/instance/:instanceId/dashboard",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(SY,{})})})},{path:"/manager/instance/:instanceId/chat",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(QC,{})})})},{path:"/manager/instance/:instanceId/chat/:remoteJid",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(QC,{})})})},{path:"/manager/instance/:instanceId/settings",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(kte,{})})})},{path:"/manager/instance/:instanceId/openai",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(oE,{})})})},{path:"/manager/instance/:instanceId/openai/:botId",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(oE,{})})})},{path:"/manager/instance/:instanceId/webhook",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(ine,{})})})},{path:"/manager/instance/:instanceId/websocket",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(hne,{})})})},{path:"/manager/instance/:instanceId/rabbitmq",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(wte,{})})})},{path:"/manager/instance/:instanceId/sqs",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(Mte,{})})})},{path:"/manager/instance/:instanceId/chatwoot",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(HZ,{})})})},{path:"/manager/instance/:instanceId/typebot",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(aE,{})})})},{path:"/manager/instance/:instanceId/typebot/:typebotId",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(aE,{})})})},{path:"/manager/instance/:instanceId/dify",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(nE,{})})})},{path:"/manager/instance/:instanceId/dify/:difyId",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(nE,{})})})},{path:"/manager/instance/:instanceId/evolutionBot",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(rE,{})})})},{path:"/manager/instance/:instanceId/evolutionBot/:evolutionBotId",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(rE,{})})})},{path:"/manager/instance/:instanceId/flowise",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(sE,{})})})},{path:"/manager/instance/:instanceId/flowise/:flowiseId",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(sE,{})})})},{path:"/manager/instance/:instanceId/proxy",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(hte,{})})})}]),bne={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){console&&console[e]&&console[e].apply(console,t)}};class jh{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.init(t,n)}init(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.prefix=n.prefix||"i18next:",this.logger=t||bne,this.options=n,this.debug=n.debug}log(){for(var t=arguments.length,n=new Array(t),r=0;r{this.observers[r]||(this.observers[r]=new Map);const s=this.observers[r].get(n)||0;this.observers[r].set(n,s+1)}),this}off(t,n){if(this.observers[t]){if(!n){delete this.observers[t];return}this.observers[t].delete(n)}}emit(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s{let[i,c]=a;for(let l=0;l{let[i,c]=a;for(let l=0;l{let e,t;const n=new Promise((r,s)=>{e=r,t=s});return n.resolve=e,n.reject=t,n},iE=e=>e==null?"":""+e,xne=(e,t,n)=>{e.forEach(r=>{t[r]&&(n[r]=t[r])})},wne=/###/g,lE=e=>e&&e.indexOf("###")>-1?e.replace(wne,"."):e,uE=e=>!e||typeof e=="string",Ic=(e,t,n)=>{const r=typeof t!="string"?t:t.split(".");let s=0;for(;s{const{obj:r,k:s}=Ic(e,t,Object);if(r!==void 0||t.length===1){r[s]=n;return}let o=t[t.length-1],a=t.slice(0,t.length-1),i=Ic(e,a,Object);for(;i.obj===void 0&&a.length;)o=`${a[a.length-1]}.${o}`,a=a.slice(0,a.length-1),i=Ic(e,a,Object),i&&i.obj&&typeof i.obj[`${i.k}.${o}`]<"u"&&(i.obj=void 0);i.obj[`${i.k}.${o}`]=n},Sne=(e,t,n,r)=>{const{obj:s,k:o}=Ic(e,t,Object);s[o]=s[o]||[],s[o].push(n)},Rh=(e,t)=>{const{obj:n,k:r}=Ic(e,t);if(n)return n[r]},Cne=(e,t,n)=>{const r=Rh(e,n);return r!==void 0?r:Rh(t,n)},BI=(e,t,n)=>{for(const r in t)r!=="__proto__"&&r!=="constructor"&&(r in e?typeof e[r]=="string"||e[r]instanceof String||typeof t[r]=="string"||t[r]instanceof String?n&&(e[r]=t[r]):BI(e[r],t[r],n):e[r]=t[r]);return e},Xi=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var Ene={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const Tne=e=>typeof e=="string"?e.replace(/[&<>"'\/]/g,t=>Ene[t]):e;class kne{constructor(t){this.capacity=t,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(t){const n=this.regExpMap.get(t);if(n!==void 0)return n;const r=new RegExp(t);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(t,r),this.regExpQueue.push(t),r}}const _ne=[" ",",","?","!",";"],jne=new kne(20),Rne=(e,t,n)=>{t=t||"",n=n||"";const r=_ne.filter(a=>t.indexOf(a)<0&&n.indexOf(a)<0);if(r.length===0)return!0;const s=jne.getRegExp(`(${r.map(a=>a==="?"?"\\?":a).join("|")})`);let o=!s.test(e);if(!o){const a=e.indexOf(n);a>0&&!s.test(e.substring(0,a))&&(o=!0)}return o},_b=function(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:".";if(!e)return;if(e[t])return e[t];const r=t.split(n);let s=e;for(let o=0;o-1&&ce&&e.indexOf("_")>0?e.replace("_","-"):e;class dE extends nm{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{ns:["translation"],defaultNS:"translation"};super(),this.data=t||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}removeNamespaces(t){const n=this.options.ns.indexOf(t);n>-1&&this.options.ns.splice(n,1)}getResource(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};const o=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,a=s.ignoreJSONStructure!==void 0?s.ignoreJSONStructure:this.options.ignoreJSONStructure;let i;t.indexOf(".")>-1?i=t.split("."):(i=[t,n],r&&(Array.isArray(r)?i.push(...r):typeof r=="string"&&o?i.push(...r.split(o)):i.push(r)));const c=Rh(this.data,i);return!c&&!n&&!r&&t.indexOf(".")>-1&&(t=i[0],n=i[1],r=i.slice(2).join(".")),c||!a||typeof r!="string"?c:_b(this.data&&this.data[t]&&this.data[t][n],r,o)}addResource(t,n,r,s){let o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{silent:!1};const a=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator;let i=[t,n];r&&(i=i.concat(a?r.split(a):r)),t.indexOf(".")>-1&&(i=t.split("."),s=n,n=i[1]),this.addNamespaces(n),cE(this.data,i,s),o.silent||this.emit("added",t,n,r,s)}addResources(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{silent:!1};for(const o in r)(typeof r[o]=="string"||Array.isArray(r[o]))&&this.addResource(t,n,o,r[o],{silent:!0});s.silent||this.emit("added",t,n,r)}addResourceBundle(t,n,r,s,o){let a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{silent:!1,skipCopy:!1},i=[t,n];t.indexOf(".")>-1&&(i=t.split("."),s=r,r=n,n=i[1]),this.addNamespaces(n);let c=Rh(this.data,i)||{};a.skipCopy||(r=JSON.parse(JSON.stringify(r))),s?BI(c,r,o):c={...c,...r},cE(this.data,i,c),a.silent||this.emit("added",t,n,r)}removeResourceBundle(t,n){this.hasResourceBundle(t,n)&&delete this.data[t][n],this.removeNamespaces(n),this.emit("removed",t,n)}hasResourceBundle(t,n){return this.getResource(t,n)!==void 0}getResourceBundle(t,n){return n||(n=this.options.defaultNS),this.options.compatibilityAPI==="v1"?{...this.getResource(t,n)}:this.getResource(t,n)}getDataByLanguage(t){return this.data[t]}hasLanguageSomeTranslations(t){const n=this.getDataByLanguage(t);return!!(n&&Object.keys(n)||[]).find(s=>n[s]&&Object.keys(n[s]).length>0)}toJSON(){return this.data}}var zI={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,n,r,s){return e.forEach(o=>{this.processors[o]&&(t=this.processors[o].process(t,n,r,s))}),t}};const fE={};class Nh extends nm{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),xne(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],t,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Is.create("translator")}changeLanguage(t){t&&(this.language=t)}exists(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}};if(t==null)return!1;const r=this.resolve(t,n);return r&&r.res!==void 0}extractFromKey(t,n){let r=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const s=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let o=n.ns||this.options.defaultNS||[];const a=r&&t.indexOf(r)>-1,i=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!Rne(t,r,s);if(a&&!i){const c=t.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:t,namespaces:o};const l=t.split(r);(r!==s||r===s&&this.options.ns.indexOf(l[0])>-1)&&(o=l.shift()),t=l.join(s)}return typeof o=="string"&&(o=[o]),{key:t,namespaces:o}}translate(t,n,r){if(typeof n!="object"&&this.options.overloadTranslationOptionHandler&&(n=this.options.overloadTranslationOptionHandler(arguments)),typeof n=="object"&&(n={...n}),n||(n={}),t==null)return"";Array.isArray(t)||(t=[String(t)]);const s=n.returnDetails!==void 0?n.returnDetails:this.options.returnDetails,o=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator,{key:a,namespaces:i}=this.extractFromKey(t[t.length-1],n),c=i[i.length-1],l=n.lng||this.language,d=n.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(l&&l.toLowerCase()==="cimode"){if(d){const S=n.nsSeparator||this.options.nsSeparator;return s?{res:`${c}${S}${a}`,usedKey:a,exactUsedKey:a,usedLng:l,usedNS:c,usedParams:this.getUsedParamsDetails(n)}:`${c}${S}${a}`}return s?{res:a,usedKey:a,exactUsedKey:a,usedLng:l,usedNS:c,usedParams:this.getUsedParamsDetails(n)}:a}const p=this.resolve(t,n);let f=p&&p.res;const h=p&&p.usedKey||a,g=p&&p.exactUsedKey||a,m=Object.prototype.toString.apply(f),x=["[object Number]","[object Function]","[object RegExp]"],b=n.joinArrays!==void 0?n.joinArrays:this.options.joinArrays,y=!this.i18nFormat||this.i18nFormat.handleAsObject;if(y&&f&&(typeof f!="string"&&typeof f!="boolean"&&typeof f!="number")&&x.indexOf(m)<0&&!(typeof b=="string"&&Array.isArray(f))){if(!n.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const S=this.options.returnedObjectHandler?this.options.returnedObjectHandler(h,f,{...n,ns:i}):`key '${a} (${this.language})' returned an object instead of string.`;return s?(p.res=S,p.usedParams=this.getUsedParamsDetails(n),p):S}if(o){const S=Array.isArray(f),E=S?[]:{},C=S?g:h;for(const k in f)if(Object.prototype.hasOwnProperty.call(f,k)){const T=`${C}${o}${k}`;E[k]=this.translate(T,{...n,joinArrays:!1,ns:i}),E[k]===T&&(E[k]=f[k])}f=E}}else if(y&&typeof b=="string"&&Array.isArray(f))f=f.join(b),f&&(f=this.extendTranslation(f,t,n,r));else{let S=!1,E=!1;const C=n.count!==void 0&&typeof n.count!="string",k=Nh.hasDefaultValue(n),T=C?this.pluralResolver.getSuffix(l,n.count,n):"",O=n.ordinal&&C?this.pluralResolver.getSuffix(l,n.count,{ordinal:!1}):"",M=C&&!n.ordinal&&n.count===0&&this.pluralResolver.shouldUseIntlApi(),U=M&&n[`defaultValue${this.options.pluralSeparator}zero`]||n[`defaultValue${T}`]||n[`defaultValue${O}`]||n.defaultValue;!this.isValidLookup(f)&&k&&(S=!0,f=U),this.isValidLookup(f)||(E=!0,f=a);const J=(n.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&E?void 0:f,V=k&&U!==f&&this.options.updateMissing;if(E||S||V){if(this.logger.log(V?"updateKey":"missingKey",l,c,a,V?U:f),o){const F=this.resolve(a,{...n,keySeparator:!1});F&&F.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let G=[];const ee=this.languageUtils.getFallbackCodes(this.options.fallbackLng,n.lng||this.language);if(this.options.saveMissingTo==="fallback"&&ee&&ee[0])for(let F=0;F{const de=k&&Y!==f?Y:J;this.options.missingKeyHandler?this.options.missingKeyHandler(F,c,A,de,V,n):this.backendConnector&&this.backendConnector.saveMissing&&this.backendConnector.saveMissing(F,c,A,de,V,n),this.emit("missingKey",F,c,A,f)};this.options.saveMissing&&(this.options.saveMissingPlurals&&C?G.forEach(F=>{const A=this.pluralResolver.getSuffixes(F,n);M&&n[`defaultValue${this.options.pluralSeparator}zero`]&&A.indexOf(`${this.options.pluralSeparator}zero`)<0&&A.push(`${this.options.pluralSeparator}zero`),A.forEach(Y=>{q([F],a+Y,n[`defaultValue${Y}`]||U)})}):q(G,a,U))}f=this.extendTranslation(f,t,n,p,r),E&&f===a&&this.options.appendNamespaceToMissingKey&&(f=`${c}:${a}`),(E||S)&&this.options.parseMissingKeyHandler&&(this.options.compatibilityAPI!=="v1"?f=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${c}:${a}`:a,S?f:void 0):f=this.options.parseMissingKeyHandler(f))}return s?(p.res=f,p.usedParams=this.getUsedParamsDetails(n),p):f}extendTranslation(t,n,r,s,o){var a=this;if(this.i18nFormat&&this.i18nFormat.parse)t=this.i18nFormat.parse(t,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||s.usedLng,s.usedNS,s.usedKey,{resolved:s});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const l=typeof t=="string"&&(r&&r.interpolation&&r.interpolation.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let d;if(l){const f=t.match(this.interpolator.nestingRegexp);d=f&&f.length}let p=r.replace&&typeof r.replace!="string"?r.replace:r;if(this.options.interpolation.defaultVariables&&(p={...this.options.interpolation.defaultVariables,...p}),t=this.interpolator.interpolate(t,p,r.lng||this.language||s.usedLng,r),l){const f=t.match(this.interpolator.nestingRegexp),h=f&&f.length;d1&&arguments[1]!==void 0?arguments[1]:{},r,s,o,a,i;return typeof t=="string"&&(t=[t]),t.forEach(c=>{if(this.isValidLookup(r))return;const l=this.extractFromKey(c,n),d=l.key;s=d;let p=l.namespaces;this.options.fallbackNS&&(p=p.concat(this.options.fallbackNS));const f=n.count!==void 0&&typeof n.count!="string",h=f&&!n.ordinal&&n.count===0&&this.pluralResolver.shouldUseIntlApi(),g=n.context!==void 0&&(typeof n.context=="string"||typeof n.context=="number")&&n.context!=="",m=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);p.forEach(x=>{this.isValidLookup(r)||(i=x,!fE[`${m[0]}-${x}`]&&this.utils&&this.utils.hasLoadedNamespace&&!this.utils.hasLoadedNamespace(i)&&(fE[`${m[0]}-${x}`]=!0,this.logger.warn(`key "${s}" for languages "${m.join(", ")}" won't get resolved as namespace "${i}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),m.forEach(b=>{if(this.isValidLookup(r))return;a=b;const y=[d];if(this.i18nFormat&&this.i18nFormat.addLookupKeys)this.i18nFormat.addLookupKeys(y,d,b,x,n);else{let S;f&&(S=this.pluralResolver.getSuffix(b,n.count,n));const E=`${this.options.pluralSeparator}zero`,C=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(f&&(y.push(d+S),n.ordinal&&S.indexOf(C)===0&&y.push(d+S.replace(C,this.options.pluralSeparator)),h&&y.push(d+E)),g){const k=`${d}${this.options.contextSeparator}${n.context}`;y.push(k),f&&(y.push(k+S),n.ordinal&&S.indexOf(C)===0&&y.push(k+S.replace(C,this.options.pluralSeparator)),h&&y.push(k+E))}}let w;for(;w=y.pop();)this.isValidLookup(r)||(o=w,r=this.getResource(b,x,w,n))}))})}),{res:r,usedKey:s,exactUsedKey:o,usedLng:a,usedNS:i}}isValidLookup(t){return t!==void 0&&!(!this.options.returnNull&&t===null)&&!(!this.options.returnEmptyString&&t==="")}getResource(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(t,n,r,s):this.resourceStore.getResource(t,n,r,s)}getUsedParamsDetails(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=t.replace&&typeof t.replace!="string";let s=r?t.replace:t;if(r&&typeof t.count<"u"&&(s.count=t.count),this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),!r){s={...s};for(const o of n)delete s[o]}return s}static hasDefaultValue(t){const n="defaultValue";for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&n===r.substring(0,n.length)&&t[r]!==void 0)return!0;return!1}}const Cv=e=>e.charAt(0).toUpperCase()+e.slice(1);class pE{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Is.create("languageUtils")}getScriptPartFromCode(t){if(t=Oh(t),!t||t.indexOf("-")<0)return null;const n=t.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(t){if(t=Oh(t),!t||t.indexOf("-")<0)return t;const n=t.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(t){if(typeof t=="string"&&t.indexOf("-")>-1){const n=["hans","hant","latn","cyrl","cans","mong","arab"];let r=t.split("-");return this.options.lowerCaseLng?r=r.map(s=>s.toLowerCase()):r.length===2?(r[0]=r[0].toLowerCase(),r[1]=r[1].toUpperCase(),n.indexOf(r[1].toLowerCase())>-1&&(r[1]=Cv(r[1].toLowerCase()))):r.length===3&&(r[0]=r[0].toLowerCase(),r[1].length===2&&(r[1]=r[1].toUpperCase()),r[0]!=="sgn"&&r[2].length===2&&(r[2]=r[2].toUpperCase()),n.indexOf(r[1].toLowerCase())>-1&&(r[1]=Cv(r[1].toLowerCase())),n.indexOf(r[2].toLowerCase())>-1&&(r[2]=Cv(r[2].toLowerCase()))),r.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}isSupportedCode(t){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}getBestMatchFromCodes(t){if(!t)return null;let n;return t.forEach(r=>{if(n)return;const s=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(s))&&(n=s)}),!n&&this.options.supportedLngs&&t.forEach(r=>{if(n)return;const s=this.getLanguagePartFromCode(r);if(this.isSupportedCode(s))return n=s;n=this.options.supportedLngs.find(o=>{if(o===s)return o;if(!(o.indexOf("-")<0&&s.indexOf("-")<0)&&(o.indexOf("-")>0&&s.indexOf("-")<0&&o.substring(0,o.indexOf("-"))===s||o.indexOf(s)===0&&s.length>1))return o})}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(t,n){if(!t)return[];if(typeof t=="function"&&(t=t(n)),typeof t=="string"&&(t=[t]),Array.isArray(t))return t;if(!n)return t.default||[];let r=t[n];return r||(r=t[this.getScriptPartFromCode(n)]),r||(r=t[this.formatLanguageCode(n)]),r||(r=t[this.getLanguagePartFromCode(n)]),r||(r=t.default),r||[]}toResolveHierarchy(t,n){const r=this.getFallbackCodes(n||this.options.fallbackLng||[],t),s=[],o=a=>{a&&(this.isSupportedCode(a)?s.push(a):this.logger.warn(`rejecting language code not found in supportedLngs: ${a}`))};return typeof t=="string"&&(t.indexOf("-")>-1||t.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&o(this.formatLanguageCode(t)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&o(this.getScriptPartFromCode(t)),this.options.load!=="currentOnly"&&o(this.getLanguagePartFromCode(t))):typeof t=="string"&&o(this.formatLanguageCode(t)),r.forEach(a=>{s.indexOf(a)<0&&o(this.formatLanguageCode(a))}),s}}let One=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],Nne={1:e=>+(e>1),2:e=>+(e!=1),3:e=>0,4:e=>e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2,5:e=>e==0?0:e==1?1:e==2?2:e%100>=3&&e%100<=10?3:e%100>=11?4:5,6:e=>e==1?0:e>=2&&e<=4?1:2,7:e=>e==1?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2,8:e=>e==1?0:e==2?1:e!=8&&e!=11?2:3,9:e=>+(e>=2),10:e=>e==1?0:e==2?1:e<7?2:e<11?3:4,11:e=>e==1||e==11?0:e==2||e==12?1:e>2&&e<20?2:3,12:e=>+(e%10!=1||e%100==11),13:e=>+(e!==0),14:e=>e==1?0:e==2?1:e==3?2:3,15:e=>e%10==1&&e%100!=11?0:e%10>=2&&(e%100<10||e%100>=20)?1:2,16:e=>e%10==1&&e%100!=11?0:e!==0?1:2,17:e=>e==1||e%10==1&&e%100!=11?0:1,18:e=>e==0?0:e==1?1:2,19:e=>e==1?0:e==0||e%100>1&&e%100<11?1:e%100>10&&e%100<20?2:3,20:e=>e==1?0:e==0||e%100>0&&e%100<20?1:2,21:e=>e%100==1?1:e%100==2?2:e%100==3||e%100==4?3:0,22:e=>e==1?0:e==2?1:(e<0||e>10)&&e%10==0?2:3};const Pne=["v1","v2","v3"],Mne=["v4"],hE={zero:0,one:1,two:2,few:3,many:4,other:5},Ine=()=>{const e={};return One.forEach(t=>{t.lngs.forEach(n=>{e[n]={numbers:t.nr,plurals:Nne[t.fc]}})}),e};class Dne{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.languageUtils=t,this.options=n,this.logger=Is.create("pluralResolver"),(!this.options.compatibilityJSON||Mne.includes(this.options.compatibilityJSON))&&(typeof Intl>"u"||!Intl.PluralRules)&&(this.options.compatibilityJSON="v3",this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.")),this.rules=Ine(),this.pluralRulesCache={}}addRule(t,n){this.rules[t]=n}clearCache(){this.pluralRulesCache={}}getRule(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.shouldUseIntlApi())try{const r=Oh(t==="dev"?"en":t),s=n.ordinal?"ordinal":"cardinal",o=JSON.stringify({cleanedCode:r,type:s});if(o in this.pluralRulesCache)return this.pluralRulesCache[o];const a=new Intl.PluralRules(r,{type:s});return this.pluralRulesCache[o]=a,a}catch{return}return this.rules[t]||this.rules[this.languageUtils.getLanguagePartFromCode(t)]}needsPlural(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=this.getRule(t,n);return this.shouldUseIntlApi()?r&&r.resolvedOptions().pluralCategories.length>1:r&&r.numbers.length>1}getPluralFormsOfKey(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this.getSuffixes(t,r).map(s=>`${n}${s}`)}getSuffixes(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=this.getRule(t,n);return r?this.shouldUseIntlApi()?r.resolvedOptions().pluralCategories.sort((s,o)=>hE[s]-hE[o]).map(s=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${s}`):r.numbers.map(s=>this.getSuffix(t,s,n)):[]}getSuffix(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const s=this.getRule(t,r);return s?this.shouldUseIntlApi()?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${s.select(n)}`:this.getSuffixRetroCompatible(s,n):(this.logger.warn(`no plural rule found for: ${t}`),"")}getSuffixRetroCompatible(t,n){const r=t.noAbs?t.plurals(n):t.plurals(Math.abs(n));let s=t.numbers[r];this.options.simplifyPluralSuffix&&t.numbers.length===2&&t.numbers[0]===1&&(s===2?s="plural":s===1&&(s=""));const o=()=>this.options.prepend&&s.toString()?this.options.prepend+s.toString():s.toString();return this.options.compatibilityJSON==="v1"?s===1?"":typeof s=="number"?`_plural_${s.toString()}`:o():this.options.compatibilityJSON==="v2"||this.options.simplifyPluralSuffix&&t.numbers.length===2&&t.numbers[0]===1?o():this.options.prepend&&r.toString()?this.options.prepend+r.toString():r.toString()}shouldUseIntlApi(){return!Pne.includes(this.options.compatibilityJSON)}}const gE=function(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:".",s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,o=Cne(e,t,n);return!o&&s&&typeof n=="string"&&(o=_b(e,n,r),o===void 0&&(o=_b(t,n,r))),o},Ev=e=>e.replace(/\$/g,"$$$$");class Ane{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.logger=Is.create("interpolator"),this.options=t,this.format=t.interpolation&&t.interpolation.format||(n=>n),this.init(t)}init(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};t.interpolation||(t.interpolation={escapeValue:!0});const{escape:n,escapeValue:r,useRawValueToEscape:s,prefix:o,prefixEscaped:a,suffix:i,suffixEscaped:c,formatSeparator:l,unescapeSuffix:d,unescapePrefix:p,nestingPrefix:f,nestingPrefixEscaped:h,nestingSuffix:g,nestingSuffixEscaped:m,nestingOptionsSeparator:x,maxReplaces:b,alwaysFormat:y}=t.interpolation;this.escape=n!==void 0?n:Tne,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=s!==void 0?s:!1,this.prefix=o?Xi(o):a||"{{",this.suffix=i?Xi(i):c||"}}",this.formatSeparator=l||",",this.unescapePrefix=d?"":p||"-",this.unescapeSuffix=this.unescapePrefix?"":d||"",this.nestingPrefix=f?Xi(f):h||Xi("$t("),this.nestingSuffix=g?Xi(g):m||Xi(")"),this.nestingOptionsSeparator=x||",",this.maxReplaces=b||1e3,this.alwaysFormat=y!==void 0?y:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const t=(n,r)=>n&&n.source===r?(n.lastIndex=0,n):new RegExp(r,"g");this.regexp=t(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=t(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=t(this.nestingRegexp,`${this.nestingPrefix}(.+?)${this.nestingSuffix}`)}interpolate(t,n,r,s){let o,a,i;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},l=h=>{if(h.indexOf(this.formatSeparator)<0){const b=gE(n,c,h,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(b,void 0,r,{...s,...n,interpolationkey:h}):b}const g=h.split(this.formatSeparator),m=g.shift().trim(),x=g.join(this.formatSeparator).trim();return this.format(gE(n,c,m,this.options.keySeparator,this.options.ignoreJSONStructure),x,r,{...s,...n,interpolationkey:m})};this.resetRegExp();const d=s&&s.missingInterpolationHandler||this.options.missingInterpolationHandler,p=s&&s.interpolation&&s.interpolation.skipOnVariables!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:h=>Ev(h)},{regex:this.regexp,safeValue:h=>this.escapeValue?Ev(this.escape(h)):Ev(h)}].forEach(h=>{for(i=0;o=h.regex.exec(t);){const g=o[1].trim();if(a=l(g),a===void 0)if(typeof d=="function"){const x=d(t,o,s);a=typeof x=="string"?x:""}else if(s&&Object.prototype.hasOwnProperty.call(s,g))a="";else if(p){a=o[0];continue}else this.logger.warn(`missed to pass in variable ${g} for interpolating ${t}`),a="";else typeof a!="string"&&!this.useRawValueToEscape&&(a=iE(a));const m=h.safeValue(a);if(t=t.replace(o[0],m),p?(h.regex.lastIndex+=a.length,h.regex.lastIndex-=o[0].length):h.regex.lastIndex=0,i++,i>=this.maxReplaces)break}}),t}nest(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s,o,a;const i=(c,l)=>{const d=this.nestingOptionsSeparator;if(c.indexOf(d)<0)return c;const p=c.split(new RegExp(`${d}[ ]*{`));let f=`{${p[1]}`;c=p[0],f=this.interpolate(f,a);const h=f.match(/'/g),g=f.match(/"/g);(h&&h.length%2===0&&!g||g.length%2!==0)&&(f=f.replace(/'/g,'"'));try{a=JSON.parse(f),l&&(a={...l,...a})}catch(m){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,m),`${c}${d}${f}`}return a.defaultValue&&a.defaultValue.indexOf(this.prefix)>-1&&delete a.defaultValue,c};for(;s=this.nestingRegexp.exec(t);){let c=[];a={...r},a=a.replace&&typeof a.replace!="string"?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;let l=!1;if(s[0].indexOf(this.formatSeparator)!==-1&&!/{.*}/.test(s[1])){const d=s[1].split(this.formatSeparator).map(p=>p.trim());s[1]=d.shift(),c=d,l=!0}if(o=n(i.call(this,s[1].trim(),a),a),o&&s[0]===t&&typeof o!="string")return o;typeof o!="string"&&(o=iE(o)),o||(this.logger.warn(`missed to resolve ${s[1]} for nesting ${t}`),o=""),l&&(o=c.reduce((d,p)=>this.format(d,p,r.lng,{...r,interpolationkey:s[1].trim()}),o.trim())),t=t.replace(s[0],o),this.regexp.lastIndex=0}return t}}const Fne=e=>{let t=e.toLowerCase().trim();const n={};if(e.indexOf("(")>-1){const r=e.split("(");t=r[0].toLowerCase().trim();const s=r[1].substring(0,r[1].length-1);t==="currency"&&s.indexOf(":")<0?n.currency||(n.currency=s.trim()):t==="relativetime"&&s.indexOf(":")<0?n.range||(n.range=s.trim()):s.split(";").forEach(a=>{if(a){const[i,...c]=a.split(":"),l=c.join(":").trim().replace(/^'+|'+$/g,""),d=i.trim();n[d]||(n[d]=l),l==="false"&&(n[d]=!1),l==="true"&&(n[d]=!0),isNaN(l)||(n[d]=parseInt(l,10))}})}return{formatName:t,formatOptions:n}},el=e=>{const t={};return(n,r,s)=>{let o=s;s&&s.interpolationkey&&s.formatParams&&s.formatParams[s.interpolationkey]&&s[s.interpolationkey]&&(o={...o,[s.interpolationkey]:void 0});const a=r+JSON.stringify(o);let i=t[a];return i||(i=e(Oh(r),s),t[a]=i),i(n)}};class Lne{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.logger=Is.create("formatter"),this.options=t,this.formats={number:el((n,r)=>{const s=new Intl.NumberFormat(n,{...r});return o=>s.format(o)}),currency:el((n,r)=>{const s=new Intl.NumberFormat(n,{...r,style:"currency"});return o=>s.format(o)}),datetime:el((n,r)=>{const s=new Intl.DateTimeFormat(n,{...r});return o=>s.format(o)}),relativetime:el((n,r)=>{const s=new Intl.RelativeTimeFormat(n,{...r});return o=>s.format(o,r.range||"day")}),list:el((n,r)=>{const s=new Intl.ListFormat(n,{...r});return o=>s.format(o)})},this.init(t)}init(t){const r=(arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}}).interpolation;this.formatSeparator=r.formatSeparator?r.formatSeparator:r.formatSeparator||","}add(t,n){this.formats[t.toLowerCase().trim()]=n}addCached(t,n){this.formats[t.toLowerCase().trim()]=el(n)}format(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};const o=n.split(this.formatSeparator);if(o.length>1&&o[0].indexOf("(")>1&&o[0].indexOf(")")<0&&o.find(i=>i.indexOf(")")>-1)){const i=o.findIndex(c=>c.indexOf(")")>-1);o[0]=[o[0],...o.splice(1,i)].join(this.formatSeparator)}return o.reduce((i,c)=>{const{formatName:l,formatOptions:d}=Fne(c);if(this.formats[l]){let p=i;try{const f=s&&s.formatParams&&s.formatParams[s.interpolationkey]||{},h=f.locale||f.lng||s.locale||s.lng||r;p=this.formats[l](i,h,{...d,...s,...f})}catch(f){this.logger.warn(f)}return p}else this.logger.warn(`there was no format function for ${l}`);return i},t)}}const $ne=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)};class Bne extends nm{constructor(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};super(),this.backend=t,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=s,this.logger=Is.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=s.maxParallelReads||10,this.readingCalls=0,this.maxRetries=s.maxRetries>=0?s.maxRetries:5,this.retryTimeout=s.retryTimeout>=1?s.retryTimeout:350,this.state={},this.queue=[],this.backend&&this.backend.init&&this.backend.init(r,s.backend,s)}queueLoad(t,n,r,s){const o={},a={},i={},c={};return t.forEach(l=>{let d=!0;n.forEach(p=>{const f=`${l}|${p}`;!r.reload&&this.store.hasResourceBundle(l,p)?this.state[f]=2:this.state[f]<0||(this.state[f]===1?a[f]===void 0&&(a[f]=!0):(this.state[f]=1,d=!1,a[f]===void 0&&(a[f]=!0),o[f]===void 0&&(o[f]=!0),c[p]===void 0&&(c[p]=!0)))}),d||(i[l]=!0)}),(Object.keys(o).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:s}),{toLoad:Object.keys(o),pending:Object.keys(a),toLoadLanguages:Object.keys(i),toLoadNamespaces:Object.keys(c)}}loaded(t,n,r){const s=t.split("|"),o=s[0],a=s[1];n&&this.emit("failedLoading",o,a,n),!n&&r&&this.store.addResourceBundle(o,a,r,void 0,void 0,{skipCopy:!0}),this.state[t]=n?-1:2,n&&r&&(this.state[t]=0);const i={};this.queue.forEach(c=>{Sne(c.loaded,[o],a),$ne(c,t),n&&c.errors.push(n),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(l=>{i[l]||(i[l]={});const d=c.loaded[l];d.length&&d.forEach(p=>{i[l][p]===void 0&&(i[l][p]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",i),this.queue=this.queue.filter(c=>!c.done)}read(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:this.retryTimeout,a=arguments.length>5?arguments[5]:void 0;if(!t.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:t,ns:n,fcName:r,tried:s,wait:o,callback:a});return}this.readingCalls++;const i=(l,d)=>{if(this.readingCalls--,this.waitingReads.length>0){const p=this.waitingReads.shift();this.read(p.lng,p.ns,p.fcName,p.tried,p.wait,p.callback)}if(l&&d&&s{this.read.call(this,t,n,r,s+1,o*2,a)},o);return}a(l,d)},c=this.backend[r].bind(this.backend);if(c.length===2){try{const l=c(t,n);l&&typeof l.then=="function"?l.then(d=>i(null,d)).catch(i):i(null,l)}catch(l){i(l)}return}return c(t,n,i)}prepareLoading(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),s&&s();typeof t=="string"&&(t=this.languageUtils.toResolveHierarchy(t)),typeof n=="string"&&(n=[n]);const o=this.queueLoad(t,n,r,s);if(!o.toLoad.length)return o.pending.length||s(),null;o.toLoad.forEach(a=>{this.loadOne(a)})}load(t,n,r){this.prepareLoading(t,n,{},r)}reload(t,n,r){this.prepareLoading(t,n,{reload:!0},r)}loadOne(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const r=t.split("|"),s=r[0],o=r[1];this.read(s,o,"read",void 0,void 0,(a,i)=>{a&&this.logger.warn(`${n}loading namespace ${o} for language ${s} failed`,a),!a&&i&&this.logger.log(`${n}loaded namespace ${o} for language ${s}`,i),this.loaded(t,a,i)})}saveMissing(t,n,r,s,o){let a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{},i=arguments.length>6&&arguments[6]!==void 0?arguments[6]:()=>{};if(this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${r}" as the namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(r==null||r==="")){if(this.backend&&this.backend.create){const c={...a,isUpdate:o},l=this.backend.create.bind(this.backend);if(l.length<6)try{let d;l.length===5?d=l(t,n,r,s,c):d=l(t,n,r,s),d&&typeof d.then=="function"?d.then(p=>i(null,p)).catch(i):i(null,d)}catch(d){i(d)}else l(t,n,r,s,i,c)}!t||!t[0]||this.store.addResource(t[0],n,r,s)}}}const mE=()=>({debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if(typeof e[1]=="object"&&(t=e[1]),typeof e[1]=="string"&&(t.defaultValue=e[1]),typeof e[2]=="string"&&(t.tDescription=e[2]),typeof e[2]=="object"||typeof e[3]=="object"){const n=e[3]||e[2];Object.keys(n).forEach(r=>{t[r]=n[r]})}return t},interpolation:{escapeValue:!0,format:e=>e,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0}}),vE=e=>(typeof e.ns=="string"&&(e.ns=[e.ns]),typeof e.fallbackLng=="string"&&(e.fallbackLng=[e.fallbackLng]),typeof e.fallbackNS=="string"&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs&&e.supportedLngs.indexOf("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),e),Qf=()=>{},zne=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(n=>{typeof e[n]=="function"&&(e[n]=e[n].bind(e))})};class Od extends nm{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;if(super(),this.options=vE(t),this.services={},this.logger=Is,this.modules={external:[]},zne(this),n&&!this.isInitialized&&!t.isClone){if(!this.options.initImmediate)return this.init(t,n),this;setTimeout(()=>{this.init(t,n)},0)}}init(){var t=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;this.isInitializing=!0,typeof n=="function"&&(r=n,n={}),!n.defaultNS&&n.defaultNS!==!1&&n.ns&&(typeof n.ns=="string"?n.defaultNS=n.ns:n.ns.indexOf("translation")<0&&(n.defaultNS=n.ns[0]));const s=mE();this.options={...s,...this.options,...vE(n)},this.options.compatibilityAPI!=="v1"&&(this.options.interpolation={...s.interpolation,...this.options.interpolation}),n.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=n.keySeparator),n.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=n.nsSeparator);const o=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?Is.init(o(this.modules.logger),this.options):Is.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:typeof Intl<"u"&&(d=Lne);const p=new pE(this.options);this.store=new dE(this.options.resources,this.options);const f=this.services;f.logger=Is,f.resourceStore=this.store,f.languageUtils=p,f.pluralResolver=new Dne(p,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),d&&(!this.options.interpolation.format||this.options.interpolation.format===s.interpolation.format)&&(f.formatter=o(d),f.formatter.init(f,this.options),this.options.interpolation.format=f.formatter.format.bind(f.formatter)),f.interpolator=new Ane(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new Bne(o(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",function(h){for(var g=arguments.length,m=new Array(g>1?g-1:0),x=1;x1?g-1:0),x=1;x{h.init&&h.init(this)})}if(this.format=this.options.interpolation.format,r||(r=Qf),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const d=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);d.length>0&&d[0]!=="dev"&&(this.options.lng=d[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(d=>{this[d]=function(){return t.store[d](...arguments)}}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(d=>{this[d]=function(){return t.store[d](...arguments),t}});const c=sc(),l=()=>{const d=(p,f)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),c.resolve(f),r(p,f)};if(this.languages&&this.options.compatibilityAPI!=="v1"&&!this.isInitialized)return d(null,this.t.bind(this));this.changeLanguage(this.options.lng,d)};return this.options.resources||!this.options.initImmediate?l():setTimeout(l,0),c}loadResources(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Qf;const s=typeof t=="string"?t:this.language;if(typeof t=="function"&&(r=t),!this.options.resources||this.options.partialBundledLanguages){if(s&&s.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return r();const o=[],a=i=>{if(!i||i==="cimode")return;this.services.languageUtils.toResolveHierarchy(i).forEach(l=>{l!=="cimode"&&o.indexOf(l)<0&&o.push(l)})};s?a(s):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(c=>a(c)),this.options.preload&&this.options.preload.forEach(i=>a(i)),this.services.backendConnector.load(o,this.options.ns,i=>{!i&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),r(i)})}else r(null)}reloadResources(t,n,r){const s=sc();return typeof t=="function"&&(r=t,t=void 0),typeof n=="function"&&(r=n,n=void 0),t||(t=this.languages),n||(n=this.options.ns),r||(r=Qf),this.services.backendConnector.reload(t,n,o=>{s.resolve(),r(o)}),s}use(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return t.type==="backend"&&(this.modules.backend=t),(t.type==="logger"||t.log&&t.warn&&t.error)&&(this.modules.logger=t),t.type==="languageDetector"&&(this.modules.languageDetector=t),t.type==="i18nFormat"&&(this.modules.i18nFormat=t),t.type==="postProcessor"&&zI.addPostProcessor(t),t.type==="formatter"&&(this.modules.formatter=t),t.type==="3rdParty"&&this.modules.external.push(t),this}setResolvedLanguage(t){if(!(!t||!this.languages)&&!(["cimode","dev"].indexOf(t)>-1))for(let n=0;n-1)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}}changeLanguage(t,n){var r=this;this.isLanguageChangingTo=t;const s=sc();this.emit("languageChanging",t);const o=c=>{this.language=c,this.languages=this.services.languageUtils.toResolveHierarchy(c),this.resolvedLanguage=void 0,this.setResolvedLanguage(c)},a=(c,l)=>{l?(o(l),this.translator.changeLanguage(l),this.isLanguageChangingTo=void 0,this.emit("languageChanged",l),this.logger.log("languageChanged",l)):this.isLanguageChangingTo=void 0,s.resolve(function(){return r.t(...arguments)}),n&&n(c,function(){return r.t(...arguments)})},i=c=>{!t&&!c&&this.services.languageDetector&&(c=[]);const l=typeof c=="string"?c:this.services.languageUtils.getBestMatchFromCodes(c);l&&(this.language||o(l),this.translator.language||this.translator.changeLanguage(l),this.services.languageDetector&&this.services.languageDetector.cacheUserLanguage&&this.services.languageDetector.cacheUserLanguage(l)),this.loadResources(l,d=>{a(d,l)})};return!t&&this.services.languageDetector&&!this.services.languageDetector.async?i(this.services.languageDetector.detect()):!t&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(i):this.services.languageDetector.detect(i):i(t),s}getFixedT(t,n,r){var s=this;const o=function(a,i){let c;if(typeof i!="object"){for(var l=arguments.length,d=new Array(l>2?l-2:0),p=2;p`${c.keyPrefix}${f}${g}`):h=c.keyPrefix?`${c.keyPrefix}${f}${a}`:a,s.t(h,c)};return typeof t=="string"?o.lng=t:o.lngs=t,o.ns=n,o.keyPrefix=r,o}t(){return this.translator&&this.translator.translate(...arguments)}exists(){return this.translator&&this.translator.exists(...arguments)}setDefaultNamespace(t){this.options.defaultNS=t}hasLoadedNamespace(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const r=n.lng||this.resolvedLanguage||this.languages[0],s=this.options?this.options.fallbackLng:!1,o=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const a=(i,c)=>{const l=this.services.backendConnector.state[`${i}|${c}`];return l===-1||l===0||l===2};if(n.precheck){const i=n.precheck(this,a);if(i!==void 0)return i}return!!(this.hasResourceBundle(r,t)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(r,t)&&(!s||a(o,t)))}loadNamespaces(t,n){const r=sc();return this.options.ns?(typeof t=="string"&&(t=[t]),t.forEach(s=>{this.options.ns.indexOf(s)<0&&this.options.ns.push(s)}),this.loadResources(s=>{r.resolve(),n&&n(s)}),r):(n&&n(),Promise.resolve())}loadLanguages(t,n){const r=sc();typeof t=="string"&&(t=[t]);const s=this.options.preload||[],o=t.filter(a=>s.indexOf(a)<0&&this.services.languageUtils.isSupportedCode(a));return o.length?(this.options.preload=s.concat(o),this.loadResources(a=>{r.resolve(),n&&n(a)}),r):(n&&n(),Promise.resolve())}dir(t){if(t||(t=this.resolvedLanguage||(this.languages&&this.languages.length>0?this.languages[0]:this.language)),!t)return"rtl";const n=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],r=this.services&&this.services.languageUtils||new pE(mE());return n.indexOf(r.getLanguagePartFromCode(t))>-1||t.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;return new Od(t,n)}cloneInstance(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Qf;const r=t.forkResourceStore;r&&delete t.forkResourceStore;const s={...this.options,...t,isClone:!0},o=new Od(s);return(t.debug!==void 0||t.prefix!==void 0)&&(o.logger=o.logger.clone(t)),["store","services","language"].forEach(i=>{o[i]=this[i]}),o.services={...this.services},o.services.utils={hasLoadedNamespace:o.hasLoadedNamespace.bind(o)},r&&(o.store=new dE(this.store.data,s),o.services.resourceStore=o.store),o.translator=new Nh(o.services,s),o.translator.on("*",function(i){for(var c=arguments.length,l=new Array(c>1?c-1:0),d=1;d()=>(t||e((t={exports:{}}).exports,t),t.exports);var VK=dR((_o,Eo)=>{function yS(e,t){for(var n=0;nr[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const s of o)if(s.type==="childList")for(const i of s.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(o){if(o.ep)return;o.ep=!0;const s=n(o);fetch(o.href,s)}})();function Km(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var xS={exports:{}},Tf={},wS={exports:{}},et={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Zc=Symbol.for("react.element"),fR=Symbol.for("react.portal"),pR=Symbol.for("react.fragment"),hR=Symbol.for("react.strict_mode"),gR=Symbol.for("react.profiler"),mR=Symbol.for("react.provider"),vR=Symbol.for("react.context"),yR=Symbol.for("react.forward_ref"),xR=Symbol.for("react.suspense"),wR=Symbol.for("react.memo"),bR=Symbol.for("react.lazy"),cx=Symbol.iterator;function SR(e){return e===null||typeof e!="object"?null:(e=cx&&e[cx]||e["@@iterator"],typeof e=="function"?e:null)}var bS={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},SS=Object.assign,CS={};function Fi(e,t,n){this.props=e,this.context=t,this.refs=CS,this.updater=n||bS}Fi.prototype.isReactComponent={};Fi.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};Fi.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function jS(){}jS.prototype=Fi.prototype;function qm(e,t,n){this.props=e,this.context=t,this.refs=CS,this.updater=n||bS}var Zm=qm.prototype=new jS;Zm.constructor=qm;SS(Zm,Fi.prototype);Zm.isPureReactComponent=!0;var ux=Array.isArray,_S=Object.prototype.hasOwnProperty,Jm={current:null},ES={key:!0,ref:!0,__self:!0,__source:!0};function TS(e,t,n){var r,o={},s=null,i=null;if(t!=null)for(r in t.ref!==void 0&&(i=t.ref),t.key!==void 0&&(s=""+t.key),t)_S.call(t,r)&&!ES.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,B=z[fe];if(0>>1;feo(ie,te))oeo(W,ie)?(z[fe]=W,z[oe]=te,fe=oe):(z[fe]=ie,z[Q]=te,fe=Q);else if(oeo(W,te))z[fe]=W,z[oe]=te,fe=oe;else break e}}return L}function o(z,L){var te=z.sortIndex-L.sortIndex;return te!==0?te:z.id-L.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;e.unstable_now=function(){return s.now()}}else{var i=Date,l=i.now();e.unstable_now=function(){return i.now()-l}}var c=[],u=[],f=1,p=null,d=3,h=!1,m=!1,g=!1,w=typeof setTimeout=="function"?setTimeout:null,x=typeof clearTimeout=="function"?clearTimeout:null,v=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function b(z){for(var L=n(u);L!==null;){if(L.callback===null)r(u);else if(L.startTime<=z)r(u),L.sortIndex=L.expirationTime,t(c,L);else break;L=n(u)}}function C(z){if(g=!1,b(z),!m)if(n(c)!==null)m=!0,re(j);else{var L=n(u);L!==null&&K(C,L.startTime-z)}}function j(z,L){m=!1,g&&(g=!1,x(E),E=-1),h=!0;var te=d;try{for(b(L),p=n(c);p!==null&&(!(p.expirationTime>L)||z&&!Z());){var fe=p.callback;if(typeof fe=="function"){p.callback=null,d=p.priorityLevel;var B=fe(p.expirationTime<=L);L=e.unstable_now(),typeof B=="function"?p.callback=B:p===n(c)&&r(c),b(L)}else r(c);p=n(c)}if(p!==null)var ne=!0;else{var Q=n(u);Q!==null&&K(C,Q.startTime-L),ne=!1}return ne}finally{p=null,d=te,h=!1}}var S=!1,N=null,E=-1,A=5,F=-1;function Z(){return!(e.unstable_now()-Fz||125fe?(z.sortIndex=te,t(u,z),n(c)===null&&z===n(u)&&(g?(x(E),E=-1):g=!0,K(C,te-fe))):(z.sortIndex=B,t(c,z),m||h||(m=!0,re(j))),z},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function(z){var L=d;return function(){var te=d;d=L;try{return z.apply(this,arguments)}finally{d=te}}}})(IS);PS.exports=IS;var DR=PS.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var OR=y,rr=DR;function X(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),lg=Object.prototype.hasOwnProperty,MR=/^[: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]*$/,fx={},px={};function AR(e){return lg.call(px,e)?!0:lg.call(fx,e)?!1:MR.test(e)?px[e]=!0:(fx[e]=!0,!1)}function FR(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function LR(e,t,n,r){if(t===null||typeof t>"u"||FR(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Dn(e,t,n,r,o,s,i){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=s,this.removeEmptyString=i}var cn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){cn[e]=new Dn(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];cn[t]=new Dn(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){cn[e]=new Dn(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){cn[e]=new Dn(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){cn[e]=new Dn(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){cn[e]=new Dn(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){cn[e]=new Dn(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){cn[e]=new Dn(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){cn[e]=new Dn(e,5,!1,e.toLowerCase(),null,!1,!1)});var Xm=/[\-:]([a-z])/g;function Qm(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Xm,Qm);cn[t]=new Dn(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Xm,Qm);cn[t]=new Dn(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Xm,Qm);cn[t]=new Dn(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){cn[e]=new Dn(e,1,!1,e.toLowerCase(),null,!1,!1)});cn.xlinkHref=new Dn("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){cn[e]=new Dn(e,1,!1,e.toLowerCase(),null,!0,!0)});function ev(e,t,n,r){var o=cn.hasOwnProperty(t)?cn[t]:null;(o!==null?o.type!==0:r||!(2l||o[i]!==s[l]){var c=` -`+o[i].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}while(1<=i&&0<=l);break}}}finally{Kp=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?Tl(e):""}function $R(e){switch(e.tag){case 5:return Tl(e.type);case 16:return Tl("Lazy");case 13:return Tl("Suspense");case 19:return Tl("SuspenseList");case 0:case 2:case 15:return e=qp(e.type,!1),e;case 11:return e=qp(e.type.render,!1),e;case 1:return e=qp(e.type,!0),e;default:return""}}function fg(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case qa:return"Fragment";case Ka:return"Portal";case cg:return"Profiler";case tv:return"StrictMode";case ug:return"Suspense";case dg:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case MS:return(e.displayName||"Context")+".Consumer";case OS:return(e._context.displayName||"Context")+".Provider";case nv:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case rv:return t=e.displayName||null,t!==null?t:fg(e.type)||"Memo";case os:t=e._payload,e=e._init;try{return fg(e(t))}catch{}}return null}function zR(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return fg(t);case 8:return t===tv?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Ss(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function FS(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function VR(e){var t=FS(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var o=n.get,s=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(i){r=""+i,s.call(this,i)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(i){r=""+i},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function ju(e){e._valueTracker||(e._valueTracker=VR(e))}function LS(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=FS(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Td(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function pg(e,t){var n=t.checked;return Ot({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function gx(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Ss(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function $S(e,t){t=t.checked,t!=null&&ev(e,"checked",t,!1)}function hg(e,t){$S(e,t);var n=Ss(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?gg(e,t.type,n):t.hasOwnProperty("defaultValue")&&gg(e,t.type,Ss(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function mx(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function gg(e,t,n){(t!=="number"||Td(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Nl=Array.isArray;function ui(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=_u.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function rc(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Ll={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},UR=["Webkit","ms","Moz","O"];Object.keys(Ll).forEach(function(e){UR.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Ll[t]=Ll[e]})});function BS(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Ll.hasOwnProperty(e)&&Ll[e]?(""+t).trim():t+"px"}function HS(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=BS(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var BR=Ot({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function yg(e,t){if(t){if(BR[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(X(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(X(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(X(61))}if(t.style!=null&&typeof t.style!="object")throw Error(X(62))}}function xg(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var wg=null;function ov(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var bg=null,di=null,fi=null;function xx(e){if(e=Xc(e)){if(typeof bg!="function")throw Error(X(280));var t=e.stateNode;t&&(t=Df(t),bg(e.stateNode,e.type,t))}}function GS(e){di?fi?fi.push(e):fi=[e]:di=e}function WS(){if(di){var e=di,t=fi;if(fi=di=null,xx(e),t)for(e=0;e>>=0,e===0?32:31-(eP(e)/tP|0)|0}var Eu=64,Tu=4194304;function kl(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Pd(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,s=e.pingedLanes,i=n&268435455;if(i!==0){var l=i&~o;l!==0?r=kl(l):(s&=i,s!==0&&(r=kl(s)))}else i=n&~o,i!==0?r=kl(i):s!==0&&(r=kl(s));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,s=t&-t,o>=s||o===16&&(s&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Jc(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-kr(t),e[t]=n}function sP(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=zl),Nx=" ",kx=!1;function fC(e,t){switch(e){case"keyup":return DP.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function pC(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Za=!1;function MP(e,t){switch(e){case"compositionend":return pC(t);case"keypress":return t.which!==32?null:(kx=!0,Nx);case"textInput":return e=t.data,e===Nx&&kx?null:e;default:return null}}function AP(e,t){if(Za)return e==="compositionend"||!fv&&fC(e,t)?(e=uC(),sd=cv=us=null,Za=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Dx(n)}}function vC(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?vC(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function yC(){for(var e=window,t=Td();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Td(e.document)}return t}function pv(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function GP(e){var t=yC(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&vC(n.ownerDocument.documentElement,n)){if(r!==null&&pv(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var o=n.textContent.length,s=Math.min(r.start,o);r=r.end===void 0?s:Math.min(r.end,o),!e.extend&&s>r&&(o=r,r=s,s=o),o=Ox(n,s);var i=Ox(n,r);o&&i&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==i.node||e.focusOffset!==i.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),s>r?(e.addRange(t),e.extend(i.node,i.offset)):(t.setEnd(i.node,i.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Ja=null,Tg=null,Ul=null,Ng=!1;function Mx(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Ng||Ja==null||Ja!==Td(r)||(r=Ja,"selectionStart"in r&&pv(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Ul&&cc(Ul,r)||(Ul=r,r=Od(Tg,"onSelect"),0Qa||(e.current=Og[Qa],Og[Qa]=null,Qa--)}function gt(e,t){Qa++,Og[Qa]=e.current,e.current=t}var Cs={},wn=As(Cs),zn=As(!1),da=Cs;function Ci(e,t){var n=e.type.contextTypes;if(!n)return Cs;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},s;for(s in n)o[s]=t[s];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function Vn(e){return e=e.childContextTypes,e!=null}function Ad(){jt(zn),jt(wn)}function Ux(e,t,n){if(wn.current!==Cs)throw Error(X(168));gt(wn,t),gt(zn,n)}function TC(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(X(108,zR(e)||"Unknown",o));return Ot({},n,r)}function Fd(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Cs,da=wn.current,gt(wn,e),gt(zn,zn.current),!0}function Bx(e,t,n){var r=e.stateNode;if(!r)throw Error(X(169));n?(e=TC(e,t,da),r.__reactInternalMemoizedMergedChildContext=e,jt(zn),jt(wn),gt(wn,e)):jt(zn),gt(zn,n)}var xo=null,Of=!1,lh=!1;function NC(e){xo===null?xo=[e]:xo.push(e)}function rI(e){Of=!0,NC(e)}function Fs(){if(!lh&&xo!==null){lh=!0;var e=0,t=ct;try{var n=xo;for(ct=1;e>=i,o-=i,So=1<<32-kr(t)+o|n<E?(A=N,N=null):A=N.sibling;var F=d(x,N,b[E],C);if(F===null){N===null&&(N=A);break}e&&N&&F.alternate===null&&t(x,N),v=s(F,v,E),S===null?j=F:S.sibling=F,S=F,N=A}if(E===b.length)return n(x,N),Et&&Gs(x,E),j;if(N===null){for(;EE?(A=N,N=null):A=N.sibling;var Z=d(x,N,F.value,C);if(Z===null){N===null&&(N=A);break}e&&N&&Z.alternate===null&&t(x,N),v=s(Z,v,E),S===null?j=Z:S.sibling=Z,S=Z,N=A}if(F.done)return n(x,N),Et&&Gs(x,E),j;if(N===null){for(;!F.done;E++,F=b.next())F=p(x,F.value,C),F!==null&&(v=s(F,v,E),S===null?j=F:S.sibling=F,S=F);return Et&&Gs(x,E),j}for(N=r(x,N);!F.done;E++,F=b.next())F=h(N,x,E,F.value,C),F!==null&&(e&&F.alternate!==null&&N.delete(F.key===null?E:F.key),v=s(F,v,E),S===null?j=F:S.sibling=F,S=F);return e&&N.forEach(function(I){return t(x,I)}),Et&&Gs(x,E),j}function w(x,v,b,C){if(typeof b=="object"&&b!==null&&b.type===qa&&b.key===null&&(b=b.props.children),typeof b=="object"&&b!==null){switch(b.$$typeof){case Cu:e:{for(var j=b.key,S=v;S!==null;){if(S.key===j){if(j=b.type,j===qa){if(S.tag===7){n(x,S.sibling),v=o(S,b.props.children),v.return=x,x=v;break e}}else if(S.elementType===j||typeof j=="object"&&j!==null&&j.$$typeof===os&&Wx(j)===S.type){n(x,S.sibling),v=o(S,b.props),v.ref=dl(x,S,b),v.return=x,x=v;break e}n(x,S);break}else t(x,S);S=S.sibling}b.type===qa?(v=sa(b.props.children,x.mode,C,b.key),v.return=x,x=v):(C=pd(b.type,b.key,b.props,null,x.mode,C),C.ref=dl(x,v,b),C.return=x,x=C)}return i(x);case Ka:e:{for(S=b.key;v!==null;){if(v.key===S)if(v.tag===4&&v.stateNode.containerInfo===b.containerInfo&&v.stateNode.implementation===b.implementation){n(x,v.sibling),v=o(v,b.children||[]),v.return=x,x=v;break e}else{n(x,v);break}else t(x,v);v=v.sibling}v=mh(b,x.mode,C),v.return=x,x=v}return i(x);case os:return S=b._init,w(x,v,S(b._payload),C)}if(Nl(b))return m(x,v,b,C);if(al(b))return g(x,v,b,C);Ou(x,b)}return typeof b=="string"&&b!==""||typeof b=="number"?(b=""+b,v!==null&&v.tag===6?(n(x,v.sibling),v=o(v,b),v.return=x,x=v):(n(x,v),v=gh(b,x.mode,C),v.return=x,x=v),i(x)):n(x,v)}return w}var _i=IC(!0),DC=IC(!1),zd=As(null),Vd=null,ni=null,vv=null;function yv(){vv=ni=Vd=null}function xv(e){var t=zd.current;jt(zd),e._currentValue=t}function Fg(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function hi(e,t){Vd=e,vv=ni=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&($n=!0),e.firstContext=null)}function yr(e){var t=e._currentValue;if(vv!==e)if(e={context:e,memoizedValue:t,next:null},ni===null){if(Vd===null)throw Error(X(308));ni=e,Vd.dependencies={lanes:0,firstContext:e}}else ni=ni.next=e;return t}var Ys=null;function wv(e){Ys===null?Ys=[e]:Ys.push(e)}function OC(e,t,n,r){var o=t.interleaved;return o===null?(n.next=n,wv(t)):(n.next=o.next,o.next=n),t.interleaved=n,Io(e,r)}function Io(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var ss=!1;function bv(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function MC(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function To(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function ys(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,nt&2){var o=r.pending;return o===null?t.next=t:(t.next=o.next,o.next=t),r.pending=t,Io(e,n)}return o=r.interleaved,o===null?(t.next=t,wv(r)):(t.next=o.next,o.next=t),r.interleaved=t,Io(e,n)}function id(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,av(e,n)}}function Kx(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var o=null,s=null;if(n=n.firstBaseUpdate,n!==null){do{var i={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};s===null?o=s=i:s=s.next=i,n=n.next}while(n!==null);s===null?o=s=t:s=s.next=t}else o=s=t;n={baseState:r.baseState,firstBaseUpdate:o,lastBaseUpdate:s,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Ud(e,t,n,r){var o=e.updateQueue;ss=!1;var s=o.firstBaseUpdate,i=o.lastBaseUpdate,l=o.shared.pending;if(l!==null){o.shared.pending=null;var c=l,u=c.next;c.next=null,i===null?s=u:i.next=u,i=c;var f=e.alternate;f!==null&&(f=f.updateQueue,l=f.lastBaseUpdate,l!==i&&(l===null?f.firstBaseUpdate=u:l.next=u,f.lastBaseUpdate=c))}if(s!==null){var p=o.baseState;i=0,f=u=c=null,l=s;do{var d=l.lane,h=l.eventTime;if((r&d)===d){f!==null&&(f=f.next={eventTime:h,lane:0,tag:l.tag,payload:l.payload,callback:l.callback,next:null});e:{var m=e,g=l;switch(d=t,h=n,g.tag){case 1:if(m=g.payload,typeof m=="function"){p=m.call(h,p,d);break e}p=m;break e;case 3:m.flags=m.flags&-65537|128;case 0:if(m=g.payload,d=typeof m=="function"?m.call(h,p,d):m,d==null)break e;p=Ot({},p,d);break e;case 2:ss=!0}}l.callback!==null&&l.lane!==0&&(e.flags|=64,d=o.effects,d===null?o.effects=[l]:d.push(l))}else h={eventTime:h,lane:d,tag:l.tag,payload:l.payload,callback:l.callback,next:null},f===null?(u=f=h,c=p):f=f.next=h,i|=d;if(l=l.next,l===null){if(l=o.shared.pending,l===null)break;d=l,l=d.next,d.next=null,o.lastBaseUpdate=d,o.shared.pending=null}}while(!0);if(f===null&&(c=p),o.baseState=c,o.firstBaseUpdate=u,o.lastBaseUpdate=f,t=o.shared.interleaved,t!==null){o=t;do i|=o.lane,o=o.next;while(o!==t)}else s===null&&(o.shared.lanes=0);ha|=i,e.lanes=i,e.memoizedState=p}}function qx(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=uh.transition;uh.transition={};try{e(!1),t()}finally{ct=n,uh.transition=r}}function XC(){return xr().memoizedState}function iI(e,t,n){var r=ws(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},QC(e))ej(t,n);else if(n=OC(e,t,n,r),n!==null){var o=Rn();Rr(n,e,r,o),tj(n,t,r)}}function lI(e,t,n){var r=ws(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(QC(e))ej(t,o);else{var s=e.alternate;if(e.lanes===0&&(s===null||s.lanes===0)&&(s=t.lastRenderedReducer,s!==null))try{var i=t.lastRenderedState,l=s(i,n);if(o.hasEagerState=!0,o.eagerState=l,Ar(l,i)){var c=t.interleaved;c===null?(o.next=o,wv(t)):(o.next=c.next,c.next=o),t.interleaved=o;return}}catch{}finally{}n=OC(e,t,o,r),n!==null&&(o=Rn(),Rr(n,e,r,o),tj(n,t,r))}}function QC(e){var t=e.alternate;return e===It||t!==null&&t===It}function ej(e,t){Bl=Hd=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function tj(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,av(e,n)}}var Gd={readContext:yr,useCallback:pn,useContext:pn,useEffect:pn,useImperativeHandle:pn,useInsertionEffect:pn,useLayoutEffect:pn,useMemo:pn,useReducer:pn,useRef:pn,useState:pn,useDebugValue:pn,useDeferredValue:pn,useTransition:pn,useMutableSource:pn,useSyncExternalStore:pn,useId:pn,unstable_isNewReconciler:!1},cI={readContext:yr,useCallback:function(e,t){return qr().memoizedState=[e,t===void 0?null:t],e},useContext:yr,useEffect:Jx,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,cd(4194308,4,KC.bind(null,t,e),n)},useLayoutEffect:function(e,t){return cd(4194308,4,e,t)},useInsertionEffect:function(e,t){return cd(4,2,e,t)},useMemo:function(e,t){var n=qr();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=qr();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=iI.bind(null,It,e),[r.memoizedState,e]},useRef:function(e){var t=qr();return e={current:e},t.memoizedState=e},useState:Zx,useDebugValue:kv,useDeferredValue:function(e){return qr().memoizedState=e},useTransition:function(){var e=Zx(!1),t=e[0];return e=aI.bind(null,e[1]),qr().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=It,o=qr();if(Et){if(n===void 0)throw Error(X(407));n=n()}else{if(n=t(),en===null)throw Error(X(349));pa&30||$C(r,t,n)}o.memoizedState=n;var s={value:n,getSnapshot:t};return o.queue=s,Jx(VC.bind(null,r,s,e),[e]),r.flags|=2048,vc(9,zC.bind(null,r,s,n,t),void 0,null),n},useId:function(){var e=qr(),t=en.identifierPrefix;if(Et){var n=Co,r=So;n=(r&~(1<<32-kr(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=gc++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=i.createElement(n,{is:r.is}):(e=i.createElement(n),n==="select"&&(i=e,r.multiple?i.multiple=!0:r.size&&(i.size=r.size))):e=i.createElementNS(e,n),e[Zr]=t,e[fc]=r,dj(e,t,!1,!1),t.stateNode=e;e:{switch(i=xg(n,r),n){case"dialog":wt("cancel",e),wt("close",e),o=r;break;case"iframe":case"object":case"embed":wt("load",e),o=r;break;case"video":case"audio":for(o=0;oNi&&(t.flags|=128,r=!0,fl(s,!1),t.lanes=4194304)}else{if(!r)if(e=Bd(i),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),fl(s,!0),s.tail===null&&s.tailMode==="hidden"&&!i.alternate&&!Et)return hn(t),null}else 2*Vt()-s.renderingStartTime>Ni&&n!==1073741824&&(t.flags|=128,r=!0,fl(s,!1),t.lanes=4194304);s.isBackwards?(i.sibling=t.child,t.child=i):(n=s.last,n!==null?n.sibling=i:t.child=i,s.last=i)}return s.tail!==null?(t=s.tail,s.rendering=t,s.tail=t.sibling,s.renderingStartTime=Vt(),t.sibling=null,n=Pt.current,gt(Pt,r?n&1|2:n&1),t):(hn(t),null);case 22:case 23:return Mv(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Kn&1073741824&&(hn(t),t.subtreeFlags&6&&(t.flags|=8192)):hn(t),null;case 24:return null;case 25:return null}throw Error(X(156,t.tag))}function vI(e,t){switch(gv(t),t.tag){case 1:return Vn(t.type)&&Ad(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ei(),jt(zn),jt(wn),jv(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Cv(t),null;case 13:if(jt(Pt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(X(340));ji()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return jt(Pt),null;case 4:return Ei(),null;case 10:return xv(t.type._context),null;case 22:case 23:return Mv(),null;case 24:return null;default:return null}}var Au=!1,yn=!1,yI=typeof WeakSet=="function"?WeakSet:Set,xe=null;function ri(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){At(e,t,r)}else n.current=null}function Wg(e,t,n){try{n()}catch(r){At(e,t,r)}}var iw=!1;function xI(e,t){if(kg=Id,e=yC(),pv(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var o=r.anchorOffset,s=r.focusNode;r=r.focusOffset;try{n.nodeType,s.nodeType}catch{n=null;break e}var i=0,l=-1,c=-1,u=0,f=0,p=e,d=null;t:for(;;){for(var h;p!==n||o!==0&&p.nodeType!==3||(l=i+o),p!==s||r!==0&&p.nodeType!==3||(c=i+r),p.nodeType===3&&(i+=p.nodeValue.length),(h=p.firstChild)!==null;)d=p,p=h;for(;;){if(p===e)break t;if(d===n&&++u===o&&(l=i),d===s&&++f===r&&(c=i),(h=p.nextSibling)!==null)break;p=d,d=p.parentNode}p=h}n=l===-1||c===-1?null:{start:l,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(Rg={focusedElem:e,selectionRange:n},Id=!1,xe=t;xe!==null;)if(t=xe,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,xe=e;else for(;xe!==null;){t=xe;try{var m=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(m!==null){var g=m.memoizedProps,w=m.memoizedState,x=t.stateNode,v=x.getSnapshotBeforeUpdate(t.elementType===t.type?g:Cr(t.type,g),w);x.__reactInternalSnapshotBeforeUpdate=v}break;case 3:var b=t.stateNode.containerInfo;b.nodeType===1?b.textContent="":b.nodeType===9&&b.documentElement&&b.removeChild(b.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(X(163))}}catch(C){At(t,t.return,C)}if(e=t.sibling,e!==null){e.return=t.return,xe=e;break}xe=t.return}return m=iw,iw=!1,m}function Hl(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var s=o.destroy;o.destroy=void 0,s!==void 0&&Wg(t,n,s)}o=o.next}while(o!==r)}}function Ff(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Kg(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function hj(e){var t=e.alternate;t!==null&&(e.alternate=null,hj(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Zr],delete t[fc],delete t[Dg],delete t[tI],delete t[nI])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function gj(e){return e.tag===5||e.tag===3||e.tag===4}function lw(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||gj(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function qg(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Md));else if(r!==4&&(e=e.child,e!==null))for(qg(e,t,n),e=e.sibling;e!==null;)qg(e,t,n),e=e.sibling}function Zg(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Zg(e,t,n),e=e.sibling;e!==null;)Zg(e,t,n),e=e.sibling}var an=null,jr=!1;function Xo(e,t,n){for(n=n.child;n!==null;)mj(e,t,n),n=n.sibling}function mj(e,t,n){if(eo&&typeof eo.onCommitFiberUnmount=="function")try{eo.onCommitFiberUnmount(kf,n)}catch{}switch(n.tag){case 5:yn||ri(n,t);case 6:var r=an,o=jr;an=null,Xo(e,t,n),an=r,jr=o,an!==null&&(jr?(e=an,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):an.removeChild(n.stateNode));break;case 18:an!==null&&(jr?(e=an,n=n.stateNode,e.nodeType===8?ih(e.parentNode,n):e.nodeType===1&&ih(e,n),ic(e)):ih(an,n.stateNode));break;case 4:r=an,o=jr,an=n.stateNode.containerInfo,jr=!0,Xo(e,t,n),an=r,jr=o;break;case 0:case 11:case 14:case 15:if(!yn&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){o=r=r.next;do{var s=o,i=s.destroy;s=s.tag,i!==void 0&&(s&2||s&4)&&Wg(n,t,i),o=o.next}while(o!==r)}Xo(e,t,n);break;case 1:if(!yn&&(ri(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){At(n,t,l)}Xo(e,t,n);break;case 21:Xo(e,t,n);break;case 22:n.mode&1?(yn=(r=yn)||n.memoizedState!==null,Xo(e,t,n),yn=r):Xo(e,t,n);break;default:Xo(e,t,n)}}function cw(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new yI),t.forEach(function(r){var o=NI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function Sr(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=i),r&=~s}if(r=o,r=Vt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*bI(r/1960))-r,10e?16:e,ds===null)var r=!1;else{if(e=ds,ds=null,qd=0,nt&6)throw Error(X(331));var o=nt;for(nt|=4,xe=e.current;xe!==null;){var s=xe,i=s.child;if(xe.flags&16){var l=s.deletions;if(l!==null){for(var c=0;cVt()-Dv?oa(e,0):Iv|=n),Un(e,t)}function jj(e,t){t===0&&(e.mode&1?(t=Tu,Tu<<=1,!(Tu&130023424)&&(Tu=4194304)):t=1);var n=Rn();e=Io(e,t),e!==null&&(Jc(e,t,n),Un(e,n))}function TI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),jj(e,n)}function NI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(X(314))}r!==null&&r.delete(t),jj(e,n)}var _j;_j=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||zn.current)$n=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return $n=!1,gI(e,t,n);$n=!!(e.flags&131072)}else $n=!1,Et&&t.flags&1048576&&kC(t,$d,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;ud(e,t),e=t.pendingProps;var o=Ci(t,wn.current);hi(t,n),o=Ev(null,t,r,e,o,n);var s=Tv();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Vn(r)?(s=!0,Fd(t)):s=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,bv(t),o.updater=Af,t.stateNode=o,o._reactInternals=t,$g(t,r,e,n),t=Ug(null,t,r,!0,s,n)):(t.tag=0,Et&&s&&hv(t),Tn(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(ud(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=RI(r),e=Cr(r,e),o){case 0:t=Vg(null,t,r,e,n);break e;case 1:t=ow(null,t,r,e,n);break e;case 11:t=nw(null,t,r,e,n);break e;case 14:t=rw(null,t,r,Cr(r.type,e),n);break e}throw Error(X(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:Cr(r,o),Vg(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:Cr(r,o),ow(e,t,r,o,n);case 3:e:{if(lj(t),e===null)throw Error(X(387));r=t.pendingProps,s=t.memoizedState,o=s.element,MC(e,t),Ud(t,r,null,n);var i=t.memoizedState;if(r=i.element,s.isDehydrated)if(s={element:r,isDehydrated:!1,cache:i.cache,pendingSuspenseBoundaries:i.pendingSuspenseBoundaries,transitions:i.transitions},t.updateQueue.baseState=s,t.memoizedState=s,t.flags&256){o=Ti(Error(X(423)),t),t=sw(e,t,r,n,o);break e}else if(r!==o){o=Ti(Error(X(424)),t),t=sw(e,t,r,n,o);break e}else for(Yn=vs(t.stateNode.containerInfo.firstChild),Qn=t,Et=!0,Er=null,n=DC(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(ji(),r===o){t=Do(e,t,n);break e}Tn(e,t,r,n)}t=t.child}return t;case 5:return AC(t),e===null&&Ag(t),r=t.type,o=t.pendingProps,s=e!==null?e.memoizedProps:null,i=o.children,Pg(r,o)?i=null:s!==null&&Pg(r,s)&&(t.flags|=32),ij(e,t),Tn(e,t,i,n),t.child;case 6:return e===null&&Ag(t),null;case 13:return cj(e,t,n);case 4:return Sv(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=_i(t,null,r,n):Tn(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:Cr(r,o),nw(e,t,r,o,n);case 7:return Tn(e,t,t.pendingProps,n),t.child;case 8:return Tn(e,t,t.pendingProps.children,n),t.child;case 12:return Tn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,s=t.memoizedProps,i=o.value,gt(zd,r._currentValue),r._currentValue=i,s!==null)if(Ar(s.value,i)){if(s.children===o.children&&!zn.current){t=Do(e,t,n);break e}}else for(s=t.child,s!==null&&(s.return=t);s!==null;){var l=s.dependencies;if(l!==null){i=s.child;for(var c=l.firstContext;c!==null;){if(c.context===r){if(s.tag===1){c=To(-1,n&-n),c.tag=2;var u=s.updateQueue;if(u!==null){u=u.shared;var f=u.pending;f===null?c.next=c:(c.next=f.next,f.next=c),u.pending=c}}s.lanes|=n,c=s.alternate,c!==null&&(c.lanes|=n),Fg(s.return,n,t),l.lanes|=n;break}c=c.next}}else if(s.tag===10)i=s.type===t.type?null:s.child;else if(s.tag===18){if(i=s.return,i===null)throw Error(X(341));i.lanes|=n,l=i.alternate,l!==null&&(l.lanes|=n),Fg(i,n,t),i=s.sibling}else i=s.child;if(i!==null)i.return=s;else for(i=s;i!==null;){if(i===t){i=null;break}if(s=i.sibling,s!==null){s.return=i.return,i=s;break}i=i.return}s=i}Tn(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,hi(t,n),o=yr(o),r=r(o),t.flags|=1,Tn(e,t,r,n),t.child;case 14:return r=t.type,o=Cr(r,t.pendingProps),o=Cr(r.type,o),rw(e,t,r,o,n);case 15:return sj(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:Cr(r,o),ud(e,t),t.tag=1,Vn(r)?(e=!0,Fd(t)):e=!1,hi(t,n),nj(t,r,o),$g(t,r,o,n),Ug(null,t,r,!0,e,n);case 19:return uj(e,t,n);case 22:return aj(e,t,n)}throw Error(X(156,t.tag))};function Ej(e,t){return QS(e,t)}function kI(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function hr(e,t,n,r){return new kI(e,t,n,r)}function Fv(e){return e=e.prototype,!(!e||!e.isReactComponent)}function RI(e){if(typeof e=="function")return Fv(e)?1:0;if(e!=null){if(e=e.$$typeof,e===nv)return 11;if(e===rv)return 14}return 2}function bs(e,t){var n=e.alternate;return n===null?(n=hr(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function pd(e,t,n,r,o,s){var i=2;if(r=e,typeof e=="function")Fv(e)&&(i=1);else if(typeof e=="string")i=5;else e:switch(e){case qa:return sa(n.children,o,s,t);case tv:i=8,o|=8;break;case cg:return e=hr(12,n,t,o|2),e.elementType=cg,e.lanes=s,e;case ug:return e=hr(13,n,t,o),e.elementType=ug,e.lanes=s,e;case dg:return e=hr(19,n,t,o),e.elementType=dg,e.lanes=s,e;case AS:return $f(n,o,s,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case OS:i=10;break e;case MS:i=9;break e;case nv:i=11;break e;case rv:i=14;break e;case os:i=16,r=null;break e}throw Error(X(130,e==null?e:typeof e,""))}return t=hr(i,n,t,o),t.elementType=e,t.type=r,t.lanes=s,t}function sa(e,t,n,r){return e=hr(7,e,r,t),e.lanes=n,e}function $f(e,t,n,r){return e=hr(22,e,r,t),e.elementType=AS,e.lanes=n,e.stateNode={isHidden:!1},e}function gh(e,t,n){return e=hr(6,e,null,t),e.lanes=n,e}function mh(e,t,n){return t=hr(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function PI(e,t,n,r,o){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Jp(0),this.expirationTimes=Jp(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Jp(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Lv(e,t,n,r,o,s,i,l,c){return e=new PI(e,t,n,l,c),t===1?(t=1,s===!0&&(t|=8)):t=0,s=hr(3,null,null,t),e.current=s,s.stateNode=e,s.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},bv(s),e}function II(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Rj)}catch(e){console.error(e)}}Rj(),RS.exports=sr;var Ls=RS.exports;const Pj=Km(Ls),FI=yS({__proto__:null,default:Pj},[Ls]);var vw=Ls;ig.createRoot=vw.createRoot,ig.hydrateRoot=vw.hydrateRoot;/** - * @remix-run/router v1.18.0 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function Rt(){return Rt=Object.assign?Object.assign.bind():function(e){for(var t=1;t"u")throw new Error(t)}function ki(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function $I(){return Math.random().toString(36).substr(2,8)}function xw(e,t){return{usr:e.state,key:e.key,idx:t}}function xc(e,t,n,r){return n===void 0&&(n=null),Rt({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?$s(t):t,{state:n,key:t&&t.key||r||$I()})}function ma(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function $s(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function zI(e,t,n,r){r===void 0&&(r={});let{window:o=document.defaultView,v5Compat:s=!1}=r,i=o.history,l=Ht.Pop,c=null,u=f();u==null&&(u=0,i.replaceState(Rt({},i.state,{idx:u}),""));function f(){return(i.state||{idx:null}).idx}function p(){l=Ht.Pop;let w=f(),x=w==null?null:w-u;u=w,c&&c({action:l,location:g.location,delta:x})}function d(w,x){l=Ht.Push;let v=xc(g.location,w,x);u=f()+1;let b=xw(v,u),C=g.createHref(v);try{i.pushState(b,"",C)}catch(j){if(j instanceof DOMException&&j.name==="DataCloneError")throw j;o.location.assign(C)}s&&c&&c({action:l,location:g.location,delta:1})}function h(w,x){l=Ht.Replace;let v=xc(g.location,w,x);u=f();let b=xw(v,u),C=g.createHref(v);i.replaceState(b,"",C),s&&c&&c({action:l,location:g.location,delta:0})}function m(w){let x=o.location.origin!=="null"?o.location.origin:o.location.href,v=typeof w=="string"?w:ma(w);return v=v.replace(/ $/,"%20"),Ze(x,"No window.location.(origin|href) available to create URL for href: "+v),new URL(v,x)}let g={get action(){return l},get location(){return e(o,i)},listen(w){if(c)throw new Error("A history only accepts one active listener");return o.addEventListener(yw,p),c=w,()=>{o.removeEventListener(yw,p),c=null}},createHref(w){return t(o,w)},createURL:m,encodeLocation(w){let x=m(w);return{pathname:x.pathname,search:x.search,hash:x.hash}},push:d,replace:h,go(w){return i.go(w)}};return g}var ht;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(ht||(ht={}));const VI=new Set(["lazy","caseSensitive","path","id","index","children"]);function UI(e){return e.index===!0}function wc(e,t,n,r){return n===void 0&&(n=[]),r===void 0&&(r={}),e.map((o,s)=>{let i=[...n,String(s)],l=typeof o.id=="string"?o.id:i.join("-");if(Ze(o.index!==!0||!o.children,"Cannot specify children on an index route"),Ze(!r[l],'Found a route id collision on id "'+l+`". Route id's must be globally unique within Data Router usages`),UI(o)){let c=Rt({},o,t(o),{id:l});return r[l]=c,c}else{let c=Rt({},o,t(o),{id:l,children:void 0});return r[l]=c,o.children&&(c.children=wc(o.children,t,i,r)),c}})}function qs(e,t,n){return n===void 0&&(n="/"),hd(e,t,n,!1)}function hd(e,t,n,r){let o=typeof t=="string"?$s(t):t,s=zi(o.pathname||"/",n);if(s==null)return null;let i=Ij(e);HI(i);let l=null;for(let c=0;l==null&&c{let c={relativePath:l===void 0?s.path||"":l,caseSensitive:s.caseSensitive===!0,childrenIndex:i,route:s};c.relativePath.startsWith("/")&&(Ze(c.relativePath.startsWith(r),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(r.length));let u=No([r,c.relativePath]),f=n.concat(c);s.children&&s.children.length>0&&(Ze(s.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+u+'".')),Ij(s.children,t,f,u)),!(s.path==null&&!s.index)&&t.push({path:u,score:YI(u,s.index),routesMeta:f})};return e.forEach((s,i)=>{var l;if(s.path===""||!((l=s.path)!=null&&l.includes("?")))o(s,i);else for(let c of Dj(s.path))o(s,i,c)}),t}function Dj(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,o=n.endsWith("?"),s=n.replace(/\?$/,"");if(r.length===0)return o?[s,""]:[s];let i=Dj(r.join("/")),l=[];return l.push(...i.map(c=>c===""?s:[s,c].join("/"))),o&&l.push(...i),l.map(c=>e.startsWith("/")&&c===""?"/":c)}function HI(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:XI(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const GI=/^:[\w-]+$/,WI=3,KI=2,qI=1,ZI=10,JI=-2,ww=e=>e==="*";function YI(e,t){let n=e.split("/"),r=n.length;return n.some(ww)&&(r+=JI),t&&(r+=KI),n.filter(o=>!ww(o)).reduce((o,s)=>o+(GI.test(s)?WI:s===""?qI:ZI),r)}function XI(e,t){return e.length===t.length&&e.slice(0,-1).every((r,o)=>r===t[o])?e[e.length-1]-t[t.length-1]:0}function QI(e,t,n){n===void 0&&(n=!1);let{routesMeta:r}=e,o={},s="/",i=[];for(let l=0;l{let{paramName:d,isOptional:h}=f;if(d==="*"){let g=l[p]||"";i=s.slice(0,s.length-g.length).replace(/(.)\/+$/,"$1")}const m=l[p];return h&&!m?u[d]=void 0:u[d]=(m||"").replace(/%2F/g,"/"),u},{}),pathname:s,pathnameBase:i,pattern:e}}function eD(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),ki(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],o="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(i,l,c)=>(r.push({paramName:l,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),o+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?o+="\\/*$":e!==""&&e!=="/"&&(o+="(?:(?=\\/|$))"),[new RegExp(o,t?void 0:"i"),r]}function tD(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return ki(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function zi(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function nD(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:o=""}=typeof e=="string"?$s(e):e;return{pathname:n?n.startsWith("/")?n:rD(n,t):t,search:sD(r),hash:aD(o)}}function rD(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(o=>{o===".."?n.length>1&&n.pop():o!=="."&&n.push(o)}),n.length>1?n.join("/"):"/"}function vh(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function Oj(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Hf(e,t){let n=Oj(e);return t?n.map((r,o)=>o===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function Gf(e,t,n,r){r===void 0&&(r=!1);let o;typeof e=="string"?o=$s(e):(o=Rt({},e),Ze(!o.pathname||!o.pathname.includes("?"),vh("?","pathname","search",o)),Ze(!o.pathname||!o.pathname.includes("#"),vh("#","pathname","hash",o)),Ze(!o.search||!o.search.includes("#"),vh("#","search","hash",o)));let s=e===""||o.pathname==="",i=s?"/":o.pathname,l;if(i==null)l=n;else{let p=t.length-1;if(!r&&i.startsWith("..")){let d=i.split("/");for(;d[0]==="..";)d.shift(),p-=1;o.pathname=d.join("/")}l=p>=0?t[p]:"/"}let c=nD(o,l),u=i&&i!=="/"&&i.endsWith("/"),f=(s||i===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(u||f)&&(c.pathname+="/"),c}const No=e=>e.join("/").replace(/\/\/+/g,"/"),oD=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),sD=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,aD=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;class Uv{constructor(t,n,r,o){o===void 0&&(o=!1),this.status=t,this.statusText=n||"",this.internal=o,r instanceof Error?(this.data=r.toString(),this.error=r):this.data=r}}function Wf(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const Mj=["post","put","patch","delete"],iD=new Set(Mj),lD=["get",...Mj],cD=new Set(lD),uD=new Set([301,302,303,307,308]),dD=new Set([307,308]),yh={state:"idle",location:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},fD={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},hl={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},Bv=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,pD=e=>({hasErrorBoundary:!!e.hasErrorBoundary}),Aj="remix-router-transitions";function hD(e){const t=e.window?e.window:typeof window<"u"?window:void 0,n=typeof t<"u"&&typeof t.document<"u"&&typeof t.document.createElement<"u",r=!n;Ze(e.routes.length>0,"You must provide a non-empty routes array to createRouter");let o;if(e.mapRouteProperties)o=e.mapRouteProperties;else if(e.detectErrorBoundary){let k=e.detectErrorBoundary;o=P=>({hasErrorBoundary:k(P)})}else o=pD;let s={},i=wc(e.routes,o,void 0,s),l,c=e.basename||"/",u=e.unstable_dataStrategy||xD,f=e.unstable_patchRoutesOnMiss,p=Rt({v7_fetcherPersist:!1,v7_normalizeFormMethod:!1,v7_partialHydration:!1,v7_prependBasename:!1,v7_relativeSplatPath:!1,v7_skipActionErrorRevalidation:!1},e.future),d=null,h=new Set,m=null,g=null,w=null,x=e.hydrationData!=null,v=qs(i,e.history.location,c),b=null;if(v==null&&!f){let k=En(404,{pathname:e.history.location.pathname}),{matches:P,route:$}=Pw(i);v=P,b={[$.id]:k}}v&&f&&!e.hydrationData&&Hp(v,i,e.history.location.pathname).active&&(v=null);let C;if(!v)C=!1,v=[];else if(v.some(k=>k.route.lazy))C=!1;else if(!v.some(k=>k.route.loader))C=!0;else if(p.v7_partialHydration){let k=e.hydrationData?e.hydrationData.loaderData:null,P=e.hydrationData?e.hydrationData.errors:null,$=G=>G.route.loader?typeof G.route.loader=="function"&&G.route.loader.hydrate===!0?!1:k&&k[G.route.id]!==void 0||P&&P[G.route.id]!==void 0:!0;if(P){let G=v.findIndex(ve=>P[ve.route.id]!==void 0);C=v.slice(0,G+1).every($)}else C=v.every($)}else C=e.hydrationData!=null;let j,S={historyAction:e.history.action,location:e.history.location,matches:v,initialized:C,navigation:yh,restoreScrollPosition:e.hydrationData!=null?!1:null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||b,fetchers:new Map,blockers:new Map},N=Ht.Pop,E=!1,A,F=!1,Z=new Map,I=null,q=!1,H=!1,J=[],re=[],K=new Map,z=0,L=-1,te=new Map,fe=new Set,B=new Map,ne=new Map,Q=new Set,ie=new Map,oe=new Map,W=new Map,we=!1;function Pe(){if(d=e.history.listen(k=>{let{action:P,location:$,delta:G}=k;if(we){we=!1;return}ki(oe.size===0||G!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let ve=Jo({currentLocation:S.location,nextLocation:$,historyAction:P});if(ve&&G!=null){we=!0,e.history.go(G*-1),Br(ve,{state:"blocked",location:$,proceed(){Br(ve,{state:"proceeding",proceed:void 0,reset:void 0,location:$}),e.history.go(G)},reset(){let _e=new Map(S.blockers);_e.set(ve,hl),he({blockers:_e})}});return}return $t(P,$)}),n){ID(t,Z);let k=()=>DD(t,Z);t.addEventListener("pagehide",k),I=()=>t.removeEventListener("pagehide",k)}return S.initialized||$t(Ht.Pop,S.location,{initialHydration:!0}),j}function Fe(){d&&d(),I&&I(),h.clear(),A&&A.abort(),S.fetchers.forEach((k,P)=>Ur(P)),S.blockers.forEach((k,P)=>fn(P))}function Ie(k){return h.add(k),()=>h.delete(k)}function he(k,P){P===void 0&&(P={}),S=Rt({},S,k);let $=[],G=[];p.v7_fetcherPersist&&S.fetchers.forEach((ve,_e)=>{ve.state==="idle"&&(Q.has(_e)?G.push(_e):$.push(_e))}),[...h].forEach(ve=>ve(S,{deletedFetchers:G,unstable_viewTransitionOpts:P.viewTransitionOpts,unstable_flushSync:P.flushSync===!0})),p.v7_fetcherPersist&&($.forEach(ve=>S.fetchers.delete(ve)),G.forEach(ve=>Ur(ve)))}function Xe(k,P,$){var G,ve;let{flushSync:_e}=$===void 0?{}:$,Le=S.actionData!=null&&S.navigation.formMethod!=null&&_r(S.navigation.formMethod)&&S.navigation.state==="loading"&&((G=k.state)==null?void 0:G._isRedirect)!==!0,de;P.actionData?Object.keys(P.actionData).length>0?de=P.actionData:de=null:Le?de=S.actionData:de=null;let Ge=P.loaderData?kw(S.loaderData,P.loaderData,P.matches||[],P.errors):S.loaderData,Ne=S.blockers;Ne.size>0&&(Ne=new Map(Ne),Ne.forEach((it,ft)=>Ne.set(ft,hl)));let De=E===!0||S.navigation.formMethod!=null&&_r(S.navigation.formMethod)&&((ve=k.state)==null?void 0:ve._isRedirect)!==!0;l&&(i=l,l=void 0),q||N===Ht.Pop||(N===Ht.Push?e.history.push(k,k.state):N===Ht.Replace&&e.history.replace(k,k.state));let dt;if(N===Ht.Pop){let it=Z.get(S.location.pathname);it&&it.has(k.pathname)?dt={currentLocation:S.location,nextLocation:k}:Z.has(k.pathname)&&(dt={currentLocation:k,nextLocation:S.location})}else if(F){let it=Z.get(S.location.pathname);it?it.add(k.pathname):(it=new Set([k.pathname]),Z.set(S.location.pathname,it)),dt={currentLocation:S.location,nextLocation:k}}he(Rt({},P,{actionData:de,loaderData:Ge,historyAction:N,location:k,initialized:!0,navigation:yh,revalidation:"idle",restoreScrollPosition:ix(k,P.matches||S.matches),preventScrollReset:De,blockers:Ne}),{viewTransitionOpts:dt,flushSync:_e===!0}),N=Ht.Pop,E=!1,F=!1,q=!1,H=!1,J=[],re=[]}async function Nt(k,P){if(typeof k=="number"){e.history.go(k);return}let $=em(S.location,S.matches,c,p.v7_prependBasename,k,p.v7_relativeSplatPath,P==null?void 0:P.fromRouteId,P==null?void 0:P.relative),{path:G,submission:ve,error:_e}=Sw(p.v7_normalizeFormMethod,!1,$,P),Le=S.location,de=xc(S.location,G,P&&P.state);de=Rt({},de,e.history.encodeLocation(de));let Ge=P&&P.replace!=null?P.replace:void 0,Ne=Ht.Push;Ge===!0?Ne=Ht.Replace:Ge===!1||ve!=null&&_r(ve.formMethod)&&ve.formAction===S.location.pathname+S.location.search&&(Ne=Ht.Replace);let De=P&&"preventScrollReset"in P?P.preventScrollReset===!0:void 0,dt=(P&&P.unstable_flushSync)===!0,it=Jo({currentLocation:Le,nextLocation:de,historyAction:Ne});if(it){Br(it,{state:"blocked",location:de,proceed(){Br(it,{state:"proceeding",proceed:void 0,reset:void 0,location:de}),Nt(k,P)},reset(){let ft=new Map(S.blockers);ft.set(it,hl),he({blockers:ft})}});return}return await $t(Ne,de,{submission:ve,pendingError:_e,preventScrollReset:De,replace:P&&P.replace,enableViewTransition:P&&P.unstable_viewTransition,flushSync:dt})}function Ut(){if(Yt(),he({revalidation:"loading"}),S.navigation.state!=="submitting"){if(S.navigation.state==="idle"){$t(S.historyAction,S.location,{startUninterruptedRevalidation:!0});return}$t(N||S.historyAction,S.navigation.location,{overrideNavigation:S.navigation})}}async function $t(k,P,$){A&&A.abort(),A=null,N=k,q=($&&$.startUninterruptedRevalidation)===!0,iR(S.location,S.matches),E=($&&$.preventScrollReset)===!0,F=($&&$.enableViewTransition)===!0;let G=l||i,ve=$&&$.overrideNavigation,_e=qs(G,P,c),Le=($&&$.flushSync)===!0,de=Hp(_e,G,P.pathname);if(de.active&&de.matches&&(_e=de.matches),!_e){let{error:st,notFoundMatches:on,route:Bt}=rl(P.pathname);Xe(P,{matches:on,loaderData:{},errors:{[Bt.id]:st}},{flushSync:Le});return}if(S.initialized&&!H&&_D(S.location,P)&&!($&&$.submission&&_r($.submission.formMethod))){Xe(P,{matches:_e},{flushSync:Le});return}A=new AbortController;let Ge=Aa(e.history,P,A.signal,$&&$.submission),Ne;if($&&$.pendingError)Ne=[si(_e).route.id,{type:ht.error,error:$.pendingError}];else if($&&$.submission&&_r($.submission.formMethod)){let st=await Wt(Ge,P,$.submission,_e,de.active,{replace:$.replace,flushSync:Le});if(st.shortCircuited)return;if(st.pendingActionResult){let[on,Bt]=st.pendingActionResult;if(Zn(Bt)&&Wf(Bt.error)&&Bt.error.status===404){A=null,Xe(P,{matches:st.matches,loaderData:{},errors:{[on]:Bt.error}});return}}_e=st.matches||_e,Ne=st.pendingActionResult,ve=xh(P,$.submission),Le=!1,de.active=!1,Ge=Aa(e.history,Ge.url,Ge.signal)}let{shortCircuited:De,matches:dt,loaderData:it,errors:ft}=await _(Ge,P,_e,de.active,ve,$&&$.submission,$&&$.fetcherSubmission,$&&$.replace,$&&$.initialHydration===!0,Le,Ne);De||(A=null,Xe(P,Rt({matches:dt||_e},Rw(Ne),{loaderData:it,errors:ft})))}async function Wt(k,P,$,G,ve,_e){_e===void 0&&(_e={}),Yt();let Le=RD(P,$);if(he({navigation:Le},{flushSync:_e.flushSync===!0}),ve){let Ne=await yu(G,P.pathname,k.signal);if(Ne.type==="aborted")return{shortCircuited:!0};if(Ne.type==="error"){let{boundaryId:De,error:dt}=Pa(P.pathname,Ne);return{matches:Ne.partialMatches,pendingActionResult:[De,{type:ht.error,error:dt}]}}else if(Ne.matches)G=Ne.matches;else{let{notFoundMatches:De,error:dt,route:it}=rl(P.pathname);return{matches:De,pendingActionResult:[it.id,{type:ht.error,error:dt}]}}}let de,Ge=Pl(G,P);if(!Ge.route.action&&!Ge.route.lazy)de={type:ht.error,error:En(405,{method:k.method,pathname:P.pathname,routeId:Ge.route.id})};else if(de=(await Je("action",k,[Ge],G))[0],k.signal.aborted)return{shortCircuited:!0};if(ea(de)){let Ne;return _e&&_e.replace!=null?Ne=_e.replace:Ne=Ew(de.response.headers.get("Location"),new URL(k.url),c)===S.location.pathname+S.location.search,await be(k,de,{submission:$,replace:Ne}),{shortCircuited:!0}}if(Qs(de))throw En(400,{type:"defer-action"});if(Zn(de)){let Ne=si(G,Ge.route.id);return(_e&&_e.replace)!==!0&&(N=Ht.Push),{matches:G,pendingActionResult:[Ne.route.id,de]}}return{matches:G,pendingActionResult:[Ge.route.id,de]}}async function _(k,P,$,G,ve,_e,Le,de,Ge,Ne,De){let dt=ve||xh(P,_e),it=_e||Le||Ow(dt),ft=!q&&(!p.v7_partialHydration||!Ge);if(G){if(ft){let Mt=M(De);he(Rt({navigation:dt},Mt!==void 0?{actionData:Mt}:{}),{flushSync:Ne})}let Ke=await yu($,P.pathname,k.signal);if(Ke.type==="aborted")return{shortCircuited:!0};if(Ke.type==="error"){let{boundaryId:Mt,error:Hn}=Pa(P.pathname,Ke);return{matches:Ke.partialMatches,loaderData:{},errors:{[Mt]:Hn}}}else if(Ke.matches)$=Ke.matches;else{let{error:Mt,notFoundMatches:Hn,route:_t}=rl(P.pathname);return{matches:Hn,loaderData:{},errors:{[_t.id]:Mt}}}}let st=l||i,[on,Bt]=Cw(e.history,S,$,it,P,p.v7_partialHydration&&Ge===!0,p.v7_skipActionErrorRevalidation,H,J,re,Q,B,fe,st,c,De);if(Hr(Ke=>!($&&$.some(Mt=>Mt.route.id===Ke))||on&&on.some(Mt=>Mt.route.id===Ke)),L=++z,on.length===0&&Bt.length===0){let Ke=ze();return Xe(P,Rt({matches:$,loaderData:{},errors:De&&Zn(De[1])?{[De[0]]:De[1].error}:null},Rw(De),Ke?{fetchers:new Map(S.fetchers)}:{}),{flushSync:Ne}),{shortCircuited:!0}}if(ft){let Ke={};if(!G){Ke.navigation=dt;let Mt=M(De);Mt!==void 0&&(Ke.actionData=Mt)}Bt.length>0&&(Ke.fetchers=U(Bt)),he(Ke,{flushSync:Ne})}Bt.forEach(Ke=>{K.has(Ke.key)&&_n(Ke.key),Ke.controller&&K.set(Ke.key,Ke.controller)});let sl=()=>Bt.forEach(Ke=>_n(Ke.key));A&&A.signal.addEventListener("abort",sl);let{loaderResults:Yo,fetcherResults:Ia}=await yt(S.matches,$,on,Bt,k);if(k.signal.aborted)return{shortCircuited:!0};A&&A.signal.removeEventListener("abort",sl),Bt.forEach(Ke=>K.delete(Ke.key));let Da=Iw([...Yo,...Ia]);if(Da){if(Da.idx>=on.length){let Ke=Bt[Da.idx-on.length].key;fe.add(Ke)}return await be(k,Da.result,{replace:de}),{shortCircuited:!0}}let{loaderData:Oa,errors:Gr}=Nw(S,$,on,Yo,De,Bt,Ia,ie);ie.forEach((Ke,Mt)=>{Ke.subscribe(Hn=>{(Hn||Ke.done)&&ie.delete(Mt)})}),p.v7_partialHydration&&Ge&&S.errors&&Object.entries(S.errors).filter(Ke=>{let[Mt]=Ke;return!on.some(Hn=>Hn.route.id===Mt)}).forEach(Ke=>{let[Mt,Hn]=Ke;Gr=Object.assign(Gr||{},{[Mt]:Hn})});let xu=ze(),wu=pt(L),bu=xu||wu||Bt.length>0;return Rt({matches:$,loaderData:Oa,errors:Gr},bu?{fetchers:new Map(S.fetchers)}:{})}function M(k){if(k&&!Zn(k[1]))return{[k[0]]:k[1].data};if(S.actionData)return Object.keys(S.actionData).length===0?null:S.actionData}function U(k){return k.forEach(P=>{let $=S.fetchers.get(P.key),G=gl(void 0,$?$.data:void 0);S.fetchers.set(P.key,G)}),new Map(S.fetchers)}function pe(k,P,$,G){if(r)throw new Error("router.fetch() was called during the server render, but it shouldn't be. You are likely calling a useFetcher() method in the body of your component. Try moving it to a useEffect or a callback.");K.has(k)&&_n(k);let ve=(G&&G.unstable_flushSync)===!0,_e=l||i,Le=em(S.location,S.matches,c,p.v7_prependBasename,$,p.v7_relativeSplatPath,P,G==null?void 0:G.relative),de=qs(_e,Le,c),Ge=Hp(de,_e,Le);if(Ge.active&&Ge.matches&&(de=Ge.matches),!de){Xt(k,P,En(404,{pathname:Le}),{flushSync:ve});return}let{path:Ne,submission:De,error:dt}=Sw(p.v7_normalizeFormMethod,!0,Le,G);if(dt){Xt(k,P,dt,{flushSync:ve});return}let it=Pl(de,Ne);if(E=(G&&G.preventScrollReset)===!0,De&&_r(De.formMethod)){le(k,P,Ne,it,de,Ge.active,ve,De);return}B.set(k,{routeId:P,path:Ne}),se(k,P,Ne,it,de,Ge.active,ve,De)}async function le(k,P,$,G,ve,_e,Le,de){Yt(),B.delete(k);function Ge(_t){if(!_t.route.action&&!_t.route.lazy){let fo=En(405,{method:de.formMethod,pathname:$,routeId:P});return Xt(k,P,fo,{flushSync:Le}),!0}return!1}if(!_e&&Ge(G))return;let Ne=S.fetchers.get(k);rn(k,PD(de,Ne),{flushSync:Le});let De=new AbortController,dt=Aa(e.history,$,De.signal,de);if(_e){let _t=await yu(ve,$,dt.signal);if(_t.type==="aborted")return;if(_t.type==="error"){let{error:fo}=Pa($,_t);Xt(k,P,fo,{flushSync:Le});return}else if(_t.matches){if(ve=_t.matches,G=Pl(ve,$),Ge(G))return}else{Xt(k,P,En(404,{pathname:$}),{flushSync:Le});return}}K.set(k,De);let it=z,st=(await Je("action",dt,[G],ve))[0];if(dt.signal.aborted){K.get(k)===De&&K.delete(k);return}if(p.v7_fetcherPersist&&Q.has(k)){if(ea(st)||Zn(st)){rn(k,ns(void 0));return}}else{if(ea(st))if(K.delete(k),L>it){rn(k,ns(void 0));return}else return fe.add(k),rn(k,gl(de)),be(dt,st,{fetcherSubmission:de});if(Zn(st)){Xt(k,P,st.error);return}}if(Qs(st))throw En(400,{type:"defer-action"});let on=S.navigation.location||S.location,Bt=Aa(e.history,on,De.signal),sl=l||i,Yo=S.navigation.state!=="idle"?qs(sl,S.navigation.location,c):S.matches;Ze(Yo,"Didn't find any matches after fetcher action");let Ia=++z;te.set(k,Ia);let Da=gl(de,st.data);S.fetchers.set(k,Da);let[Oa,Gr]=Cw(e.history,S,Yo,de,on,!1,p.v7_skipActionErrorRevalidation,H,J,re,Q,B,fe,sl,c,[G.route.id,st]);Gr.filter(_t=>_t.key!==k).forEach(_t=>{let fo=_t.key,lx=S.fetchers.get(fo),uR=gl(void 0,lx?lx.data:void 0);S.fetchers.set(fo,uR),K.has(fo)&&_n(fo),_t.controller&&K.set(fo,_t.controller)}),he({fetchers:new Map(S.fetchers)});let xu=()=>Gr.forEach(_t=>_n(_t.key));De.signal.addEventListener("abort",xu);let{loaderResults:wu,fetcherResults:bu}=await yt(S.matches,Yo,Oa,Gr,Bt);if(De.signal.aborted)return;De.signal.removeEventListener("abort",xu),te.delete(k),K.delete(k),Gr.forEach(_t=>K.delete(_t.key));let Ke=Iw([...wu,...bu]);if(Ke){if(Ke.idx>=Oa.length){let _t=Gr[Ke.idx-Oa.length].key;fe.add(_t)}return be(Bt,Ke.result)}let{loaderData:Mt,errors:Hn}=Nw(S,S.matches,Oa,wu,void 0,Gr,bu,ie);if(S.fetchers.has(k)){let _t=ns(st.data);S.fetchers.set(k,_t)}pt(Ia),S.navigation.state==="loading"&&Ia>L?(Ze(N,"Expected pending action"),A&&A.abort(),Xe(S.navigation.location,{matches:Yo,loaderData:Mt,errors:Hn,fetchers:new Map(S.fetchers)})):(he({errors:Hn,loaderData:kw(S.loaderData,Mt,Yo,Hn),fetchers:new Map(S.fetchers)}),H=!1)}async function se(k,P,$,G,ve,_e,Le,de){let Ge=S.fetchers.get(k);rn(k,gl(de,Ge?Ge.data:void 0),{flushSync:Le});let Ne=new AbortController,De=Aa(e.history,$,Ne.signal);if(_e){let st=await yu(ve,$,De.signal);if(st.type==="aborted")return;if(st.type==="error"){let{error:on}=Pa($,st);Xt(k,P,on,{flushSync:Le});return}else if(st.matches)ve=st.matches,G=Pl(ve,$);else{Xt(k,P,En(404,{pathname:$}),{flushSync:Le});return}}K.set(k,Ne);let dt=z,ft=(await Je("loader",De,[G],ve))[0];if(Qs(ft)&&(ft=await Vj(ft,De.signal,!0)||ft),K.get(k)===Ne&&K.delete(k),!De.signal.aborted){if(Q.has(k)){rn(k,ns(void 0));return}if(ea(ft))if(L>dt){rn(k,ns(void 0));return}else{fe.add(k),await be(De,ft);return}if(Zn(ft)){Xt(k,P,ft.error);return}Ze(!Qs(ft),"Unhandled fetcher deferred data"),rn(k,ns(ft.data))}}async function be(k,P,$){let{submission:G,fetcherSubmission:ve,replace:_e}=$===void 0?{}:$;P.response.headers.has("X-Remix-Revalidate")&&(H=!0);let Le=P.response.headers.get("Location");Ze(Le,"Expected a Location header on the redirect Response"),Le=Ew(Le,new URL(k.url),c);let de=xc(S.location,Le,{_isRedirect:!0});if(n){let ft=!1;if(P.response.headers.has("X-Remix-Reload-Document"))ft=!0;else if(Bv.test(Le)){const st=e.history.createURL(Le);ft=st.origin!==t.location.origin||zi(st.pathname,c)==null}if(ft){_e?t.location.replace(Le):t.location.assign(Le);return}}A=null;let Ge=_e===!0?Ht.Replace:Ht.Push,{formMethod:Ne,formAction:De,formEncType:dt}=S.navigation;!G&&!ve&&Ne&&De&&dt&&(G=Ow(S.navigation));let it=G||ve;if(dD.has(P.response.status)&&it&&_r(it.formMethod))await $t(Ge,de,{submission:Rt({},it,{formAction:Le}),preventScrollReset:E});else{let ft=xh(de,G);await $t(Ge,de,{overrideNavigation:ft,fetcherSubmission:ve,preventScrollReset:E})}}async function Je(k,P,$,G){try{let ve=await wD(u,k,P,$,G,s,o);return await Promise.all(ve.map((_e,Le)=>{if(TD(_e)){let de=_e.result;return{type:ht.redirect,response:CD(de,P,$[Le].route.id,G,c,p.v7_relativeSplatPath)}}return SD(_e)}))}catch(ve){return $.map(()=>({type:ht.error,error:ve}))}}async function yt(k,P,$,G,ve){let[_e,...Le]=await Promise.all([$.length?Je("loader",ve,$,P):[],...G.map(de=>{if(de.matches&&de.match&&de.controller){let Ge=Aa(e.history,de.path,de.controller.signal);return Je("loader",Ge,[de.match],de.matches).then(Ne=>Ne[0])}else return Promise.resolve({type:ht.error,error:En(404,{pathname:de.path})})})]);return await Promise.all([Dw(k,$,_e,_e.map(()=>ve.signal),!1,S.loaderData),Dw(k,G.map(de=>de.match),Le,G.map(de=>de.controller?de.controller.signal:null),!0)]),{loaderResults:_e,fetcherResults:Le}}function Yt(){H=!0,J.push(...Hr()),B.forEach((k,P)=>{K.has(P)&&(re.push(P),_n(P))})}function rn(k,P,$){$===void 0&&($={}),S.fetchers.set(k,P),he({fetchers:new Map(S.fetchers)},{flushSync:($&&$.flushSync)===!0})}function Xt(k,P,$,G){G===void 0&&(G={});let ve=si(S.matches,P);Ur(k),he({errors:{[ve.route.id]:$},fetchers:new Map(S.fetchers)},{flushSync:(G&&G.flushSync)===!0})}function Zo(k){return p.v7_fetcherPersist&&(ne.set(k,(ne.get(k)||0)+1),Q.has(k)&&Q.delete(k)),S.fetchers.get(k)||fD}function Ur(k){let P=S.fetchers.get(k);K.has(k)&&!(P&&P.state==="loading"&&te.has(k))&&_n(k),B.delete(k),te.delete(k),fe.delete(k),Q.delete(k),S.fetchers.delete(k)}function Bs(k){if(p.v7_fetcherPersist){let P=(ne.get(k)||0)-1;P<=0?(ne.delete(k),Q.add(k)):ne.set(k,P)}else Ur(k);he({fetchers:new Map(S.fetchers)})}function _n(k){let P=K.get(k);Ze(P,"Expected fetch controller: "+k),P.abort(),K.delete(k)}function ce(k){for(let P of k){let $=Zo(P),G=ns($.data);S.fetchers.set(P,G)}}function ze(){let k=[],P=!1;for(let $ of fe){let G=S.fetchers.get($);Ze(G,"Expected fetcher: "+$),G.state==="loading"&&(fe.delete($),k.push($),P=!0)}return ce(k),P}function pt(k){let P=[];for(let[$,G]of te)if(G0}function ot(k,P){let $=S.blockers.get(k)||hl;return oe.get(k)!==P&&oe.set(k,P),$}function fn(k){S.blockers.delete(k),oe.delete(k)}function Br(k,P){let $=S.blockers.get(k)||hl;Ze($.state==="unblocked"&&P.state==="blocked"||$.state==="blocked"&&P.state==="blocked"||$.state==="blocked"&&P.state==="proceeding"||$.state==="blocked"&&P.state==="unblocked"||$.state==="proceeding"&&P.state==="unblocked","Invalid blocker state transition: "+$.state+" -> "+P.state);let G=new Map(S.blockers);G.set(k,P),he({blockers:G})}function Jo(k){let{currentLocation:P,nextLocation:$,historyAction:G}=k;if(oe.size===0)return;oe.size>1&&ki(!1,"A router only supports one blocker at a time");let ve=Array.from(oe.entries()),[_e,Le]=ve[ve.length-1],de=S.blockers.get(_e);if(!(de&&de.state==="proceeding")&&Le({currentLocation:P,nextLocation:$,historyAction:G}))return _e}function rl(k){let P=En(404,{pathname:k}),$=l||i,{matches:G,route:ve}=Pw($);return Hr(),{notFoundMatches:G,route:ve,error:P}}function Pa(k,P){return{boundaryId:si(P.partialMatches).route.id,error:En(400,{type:"route-discovery",pathname:k,message:P.error!=null&&"message"in P.error?P.error:String(P.error)})}}function Hr(k){let P=[];return ie.forEach(($,G)=>{(!k||k(G))&&($.cancel(),P.push(G),ie.delete(G))}),P}function ol(k,P,$){if(m=k,w=P,g=$||null,!x&&S.navigation===yh){x=!0;let G=ix(S.location,S.matches);G!=null&&he({restoreScrollPosition:G})}return()=>{m=null,w=null,g=null}}function ax(k,P){return g&&g(k,P.map(G=>BI(G,S.loaderData)))||k.key}function iR(k,P){if(m&&w){let $=ax(k,P);m[$]=w()}}function ix(k,P){if(m){let $=ax(k,P),G=m[$];if(typeof G=="number")return G}return null}function Hp(k,P,$){if(f)if(k){let G=k[k.length-1].route;if(G.path&&(G.path==="*"||G.path.endsWith("/*")))return{active:!0,matches:hd(P,$,c,!0)}}else return{active:!0,matches:hd(P,$,c,!0)||[]};return{active:!1,matches:null}}async function yu(k,P,$){let G=k,ve=G.length>0?G[G.length-1].route:null;for(;;){let _e=l==null,Le=l||i;try{await yD(f,P,G,Le,s,o,W,$)}catch(De){return{type:"error",error:De,partialMatches:G}}finally{_e&&(i=[...i])}if($.aborted)return{type:"aborted"};let de=qs(Le,P,c),Ge=!1;if(de){let De=de[de.length-1].route;if(De.index)return{type:"success",matches:de};if(De.path&&De.path.length>0)if(De.path==="*")Ge=!0;else return{type:"success",matches:de}}let Ne=hd(Le,P,c,!0);if(!Ne||G.map(De=>De.route.id).join("-")===Ne.map(De=>De.route.id).join("-"))return{type:"success",matches:Ge?de:null};if(G=Ne,ve=G[G.length-1].route,ve.path==="*")return{type:"success",matches:G}}}function lR(k){s={},l=wc(k,o,void 0,s)}function cR(k,P){let $=l==null;Lj(k,P,l||i,s,o),$&&(i=[...i],he({}))}return j={get basename(){return c},get future(){return p},get state(){return S},get routes(){return i},get window(){return t},initialize:Pe,subscribe:Ie,enableScrollRestoration:ol,navigate:Nt,fetch:pe,revalidate:Ut,createHref:k=>e.history.createHref(k),encodeLocation:k=>e.history.encodeLocation(k),getFetcher:Zo,deleteFetcher:Bs,dispose:Fe,getBlocker:ot,deleteBlocker:fn,patchRoutes:cR,_internalFetchControllers:K,_internalActiveDeferreds:ie,_internalSetRoutes:lR},j}function gD(e){return e!=null&&("formData"in e&&e.formData!=null||"body"in e&&e.body!==void 0)}function em(e,t,n,r,o,s,i,l){let c,u;if(i){c=[];for(let p of t)if(c.push(p),p.route.id===i){u=p;break}}else c=t,u=t[t.length-1];let f=Gf(o||".",Hf(c,s),zi(e.pathname,n)||e.pathname,l==="path");return o==null&&(f.search=e.search,f.hash=e.hash),(o==null||o===""||o===".")&&u&&u.route.index&&!Hv(f.search)&&(f.search=f.search?f.search.replace(/^\?/,"?index&"):"?index"),r&&n!=="/"&&(f.pathname=f.pathname==="/"?n:No([n,f.pathname])),ma(f)}function Sw(e,t,n,r){if(!r||!gD(r))return{path:n};if(r.formMethod&&!kD(r.formMethod))return{path:n,error:En(405,{method:r.formMethod})};let o=()=>({path:n,error:En(400,{type:"invalid-body"})}),s=r.formMethod||"get",i=e?s.toUpperCase():s.toLowerCase(),l=$j(n);if(r.body!==void 0){if(r.formEncType==="text/plain"){if(!_r(i))return o();let d=typeof r.body=="string"?r.body:r.body instanceof FormData||r.body instanceof URLSearchParams?Array.from(r.body.entries()).reduce((h,m)=>{let[g,w]=m;return""+h+g+"="+w+` -`},""):String(r.body);return{path:n,submission:{formMethod:i,formAction:l,formEncType:r.formEncType,formData:void 0,json:void 0,text:d}}}else if(r.formEncType==="application/json"){if(!_r(i))return o();try{let d=typeof r.body=="string"?JSON.parse(r.body):r.body;return{path:n,submission:{formMethod:i,formAction:l,formEncType:r.formEncType,formData:void 0,json:d,text:void 0}}}catch{return o()}}}Ze(typeof FormData=="function","FormData is not available in this environment");let c,u;if(r.formData)c=tm(r.formData),u=r.formData;else if(r.body instanceof FormData)c=tm(r.body),u=r.body;else if(r.body instanceof URLSearchParams)c=r.body,u=Tw(c);else if(r.body==null)c=new URLSearchParams,u=new FormData;else try{c=new URLSearchParams(r.body),u=Tw(c)}catch{return o()}let f={formMethod:i,formAction:l,formEncType:r&&r.formEncType||"application/x-www-form-urlencoded",formData:u,json:void 0,text:void 0};if(_r(f.formMethod))return{path:n,submission:f};let p=$s(n);return t&&p.search&&Hv(p.search)&&c.append("index",""),p.search="?"+c,{path:ma(p),submission:f}}function mD(e,t){let n=e;if(t){let r=e.findIndex(o=>o.route.id===t);r>=0&&(n=e.slice(0,r))}return n}function Cw(e,t,n,r,o,s,i,l,c,u,f,p,d,h,m,g){let w=g?Zn(g[1])?g[1].error:g[1].data:void 0,x=e.createURL(t.location),v=e.createURL(o),b=g&&Zn(g[1])?g[0]:void 0,C=b?mD(n,b):n,j=g?g[1].statusCode:void 0,S=i&&j&&j>=400,N=C.filter((A,F)=>{let{route:Z}=A;if(Z.lazy)return!0;if(Z.loader==null)return!1;if(s)return typeof Z.loader!="function"||Z.loader.hydrate?!0:t.loaderData[Z.id]===void 0&&(!t.errors||t.errors[Z.id]===void 0);if(vD(t.loaderData,t.matches[F],A)||c.some(H=>H===A.route.id))return!0;let I=t.matches[F],q=A;return jw(A,Rt({currentUrl:x,currentParams:I.params,nextUrl:v,nextParams:q.params},r,{actionResult:w,actionStatus:j,defaultShouldRevalidate:S?!1:l||x.pathname+x.search===v.pathname+v.search||x.search!==v.search||Fj(I,q)}))}),E=[];return p.forEach((A,F)=>{if(s||!n.some(J=>J.route.id===A.routeId)||f.has(F))return;let Z=qs(h,A.path,m);if(!Z){E.push({key:F,routeId:A.routeId,path:A.path,matches:null,match:null,controller:null});return}let I=t.fetchers.get(F),q=Pl(Z,A.path),H=!1;d.has(F)?H=!1:u.includes(F)?H=!0:I&&I.state!=="idle"&&I.data===void 0?H=l:H=jw(q,Rt({currentUrl:x,currentParams:t.matches[t.matches.length-1].params,nextUrl:v,nextParams:n[n.length-1].params},r,{actionResult:w,actionStatus:j,defaultShouldRevalidate:S?!1:l})),H&&E.push({key:F,routeId:A.routeId,path:A.path,matches:Z,match:q,controller:new AbortController})}),[N,E]}function vD(e,t,n){let r=!t||n.route.id!==t.route.id,o=e[n.route.id]===void 0;return r||o}function Fj(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith("*")&&e.params["*"]!==t.params["*"]}function jw(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n=="boolean")return n}return t.defaultShouldRevalidate}async function yD(e,t,n,r,o,s,i,l){let c=[t,...n.map(u=>u.route.id)].join("-");try{let u=i.get(c);u||(u=e({path:t,matches:n,patch:(f,p)=>{l.aborted||Lj(f,p,r,o,s)}}),i.set(c,u)),u&&ED(u)&&await u}finally{i.delete(c)}}function Lj(e,t,n,r,o){if(e){var s;let i=r[e];Ze(i,"No route found to patch children into: routeId = "+e);let l=wc(t,o,[e,"patch",String(((s=i.children)==null?void 0:s.length)||"0")],r);i.children?i.children.push(...l):i.children=l}else{let i=wc(t,o,["patch",String(n.length||"0")],r);n.push(...i)}}async function _w(e,t,n){if(!e.lazy)return;let r=await e.lazy();if(!e.lazy)return;let o=n[e.id];Ze(o,"No route found in manifest");let s={};for(let i in r){let c=o[i]!==void 0&&i!=="hasErrorBoundary";ki(!c,'Route "'+o.id+'" has a static property "'+i+'" defined but its lazy function is also returning a value for this property. '+('The lazy route property "'+i+'" will be ignored.')),!c&&!VI.has(i)&&(s[i]=r[i])}Object.assign(o,s),Object.assign(o,Rt({},t(o),{lazy:void 0}))}function xD(e){return Promise.all(e.matches.map(t=>t.resolve()))}async function wD(e,t,n,r,o,s,i,l){let c=r.reduce((p,d)=>p.add(d.route.id),new Set),u=new Set,f=await e({matches:o.map(p=>{let d=c.has(p.route.id);return Rt({},p,{shouldLoad:d,resolve:m=>(u.add(p.route.id),d?bD(t,n,p,s,i,m,l):Promise.resolve({type:ht.data,result:void 0}))})}),request:n,params:o[0].params,context:l});return o.forEach(p=>Ze(u.has(p.route.id),'`match.resolve()` was not called for route id "'+p.route.id+'". You must call `match.resolve()` on every match passed to `dataStrategy` to ensure all routes are properly loaded.')),f.filter((p,d)=>c.has(o[d].route.id))}async function bD(e,t,n,r,o,s,i){let l,c,u=f=>{let p,d=new Promise((g,w)=>p=w);c=()=>p(),t.signal.addEventListener("abort",c);let h=g=>typeof f!="function"?Promise.reject(new Error("You cannot call the handler for a route which defines a boolean "+('"'+e+'" [routeId: '+n.route.id+"]"))):f({request:t,params:n.params,context:i},...g!==void 0?[g]:[]),m;return s?m=s(g=>h(g)):m=(async()=>{try{return{type:"data",result:await h()}}catch(g){return{type:"error",result:g}}})(),Promise.race([m,d])};try{let f=n.route[e];if(n.route.lazy)if(f){let p,[d]=await Promise.all([u(f).catch(h=>{p=h}),_w(n.route,o,r)]);if(p!==void 0)throw p;l=d}else if(await _w(n.route,o,r),f=n.route[e],f)l=await u(f);else if(e==="action"){let p=new URL(t.url),d=p.pathname+p.search;throw En(405,{method:t.method,pathname:d,routeId:n.route.id})}else return{type:ht.data,result:void 0};else if(f)l=await u(f);else{let p=new URL(t.url),d=p.pathname+p.search;throw En(404,{pathname:d})}Ze(l.result!==void 0,"You defined "+(e==="action"?"an action":"a loader")+" for route "+('"'+n.route.id+"\" but didn't return anything from your `"+e+"` ")+"function. Please return a value or `null`.")}catch(f){return{type:ht.error,result:f}}finally{c&&t.signal.removeEventListener("abort",c)}return l}async function SD(e){let{result:t,type:n,status:r}=e;if(zj(t)){let i;try{let l=t.headers.get("Content-Type");l&&/\bapplication\/json\b/.test(l)?t.body==null?i=null:i=await t.json():i=await t.text()}catch(l){return{type:ht.error,error:l}}return n===ht.error?{type:ht.error,error:new Uv(t.status,t.statusText,i),statusCode:t.status,headers:t.headers}:{type:ht.data,data:i,statusCode:t.status,headers:t.headers}}if(n===ht.error)return{type:ht.error,error:t,statusCode:Wf(t)?t.status:r};if(ND(t)){var o,s;return{type:ht.deferred,deferredData:t,statusCode:(o=t.init)==null?void 0:o.status,headers:((s=t.init)==null?void 0:s.headers)&&new Headers(t.init.headers)}}return{type:ht.data,data:t,statusCode:r}}function CD(e,t,n,r,o,s){let i=e.headers.get("Location");if(Ze(i,"Redirects returned/thrown from loaders/actions must have a Location header"),!Bv.test(i)){let l=r.slice(0,r.findIndex(c=>c.route.id===n)+1);i=em(new URL(t.url),l,o,!0,i,s),e.headers.set("Location",i)}return e}function Ew(e,t,n){if(Bv.test(e)){let r=e,o=r.startsWith("//")?new URL(t.protocol+r):new URL(r),s=zi(o.pathname,n)!=null;if(o.origin===t.origin&&s)return o.pathname+o.search+o.hash}return e}function Aa(e,t,n,r){let o=e.createURL($j(t)).toString(),s={signal:n};if(r&&_r(r.formMethod)){let{formMethod:i,formEncType:l}=r;s.method=i.toUpperCase(),l==="application/json"?(s.headers=new Headers({"Content-Type":l}),s.body=JSON.stringify(r.json)):l==="text/plain"?s.body=r.text:l==="application/x-www-form-urlencoded"&&r.formData?s.body=tm(r.formData):s.body=r.formData}return new Request(o,s)}function tm(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r=="string"?r:r.name);return t}function Tw(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function jD(e,t,n,r,o,s){let i={},l=null,c,u=!1,f={},p=r&&Zn(r[1])?r[1].error:void 0;return n.forEach((d,h)=>{let m=t[h].route.id;if(Ze(!ea(d),"Cannot handle redirect results in processLoaderData"),Zn(d)){let g=d.error;p!==void 0&&(g=p,p=void 0),l=l||{};{let w=si(e,m);l[w.route.id]==null&&(l[w.route.id]=g)}i[m]=void 0,u||(u=!0,c=Wf(d.error)?d.error.status:500),d.headers&&(f[m]=d.headers)}else Qs(d)?(o.set(m,d.deferredData),i[m]=d.deferredData.data,d.statusCode!=null&&d.statusCode!==200&&!u&&(c=d.statusCode),d.headers&&(f[m]=d.headers)):(i[m]=d.data,d.statusCode&&d.statusCode!==200&&!u&&(c=d.statusCode),d.headers&&(f[m]=d.headers))}),p!==void 0&&r&&(l={[r[0]]:p},i[r[0]]=void 0),{loaderData:i,errors:l,statusCode:c||200,loaderHeaders:f}}function Nw(e,t,n,r,o,s,i,l){let{loaderData:c,errors:u}=jD(t,n,r,o,l);for(let f=0;fr.route.id===t)+1):[...e]).reverse().find(r=>r.route.hasErrorBoundary===!0)||e[0]}function Pw(e){let t=e.length===1?e[0]:e.find(n=>n.index||!n.path||n.path==="/")||{id:"__shim-error-route__"};return{matches:[{params:{},pathname:"",pathnameBase:"",route:t}],route:t}}function En(e,t){let{pathname:n,routeId:r,method:o,type:s,message:i}=t===void 0?{}:t,l="Unknown Server Error",c="Unknown @remix-run/router error";return e===400?(l="Bad Request",s==="route-discovery"?c='Unable to match URL "'+n+'" - the `unstable_patchRoutesOnMiss()` '+(`function threw the following error: -`+i):o&&n&&r?c="You made a "+o+' request to "'+n+'" but '+('did not provide a `loader` for route "'+r+'", ')+"so there is no way to handle the request.":s==="defer-action"?c="defer() is not supported in actions":s==="invalid-body"&&(c="Unable to encode submission body")):e===403?(l="Forbidden",c='Route "'+r+'" does not match URL "'+n+'"'):e===404?(l="Not Found",c='No route matches URL "'+n+'"'):e===405&&(l="Method Not Allowed",o&&n&&r?c="You made a "+o.toUpperCase()+' request to "'+n+'" but '+('did not provide an `action` for route "'+r+'", ')+"so there is no way to handle the request.":o&&(c='Invalid request method "'+o.toUpperCase()+'"')),new Uv(e||500,l,new Error(c),!0)}function Iw(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(ea(n))return{result:n,idx:t}}}function $j(e){let t=typeof e=="string"?$s(e):e;return ma(Rt({},t,{hash:""}))}function _D(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===""?t.hash!=="":e.hash===t.hash?!0:t.hash!==""}function ED(e){return typeof e=="object"&&e!=null&&"then"in e}function TD(e){return zj(e.result)&&uD.has(e.result.status)}function Qs(e){return e.type===ht.deferred}function Zn(e){return e.type===ht.error}function ea(e){return(e&&e.type)===ht.redirect}function ND(e){let t=e;return t&&typeof t=="object"&&typeof t.data=="object"&&typeof t.subscribe=="function"&&typeof t.cancel=="function"&&typeof t.resolveData=="function"}function zj(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.headers=="object"&&typeof e.body<"u"}function kD(e){return cD.has(e.toLowerCase())}function _r(e){return iD.has(e.toLowerCase())}async function Dw(e,t,n,r,o,s){for(let i=0;ip.route.id===c.route.id),f=u!=null&&!Fj(u,c)&&(s&&s[c.route.id])!==void 0;if(Qs(l)&&(o||f)){let p=r[i];Ze(p,"Expected an AbortSignal for revalidating fetcher deferred result"),await Vj(l,p,o).then(d=>{d&&(n[i]=d||n[i])})}}}async function Vj(e,t,n){if(n===void 0&&(n=!1),!await e.deferredData.resolveData(t)){if(n)try{return{type:ht.data,data:e.deferredData.unwrappedData}}catch(o){return{type:ht.error,error:o}}return{type:ht.data,data:e.deferredData.data}}}function Hv(e){return new URLSearchParams(e).getAll("index").some(t=>t==="")}function Pl(e,t){let n=typeof t=="string"?$s(t).search:t.search;if(e[e.length-1].route.index&&Hv(n||""))return e[e.length-1];let r=Oj(e);return r[r.length-1]}function Ow(e){let{formMethod:t,formAction:n,formEncType:r,text:o,formData:s,json:i}=e;if(!(!t||!n||!r)){if(o!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:o};if(s!=null)return{formMethod:t,formAction:n,formEncType:r,formData:s,json:void 0,text:void 0};if(i!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:i,text:void 0}}}function xh(e,t){return t?{state:"loading",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}:{state:"loading",location:e,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function RD(e,t){return{state:"submitting",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}function gl(e,t){return e?{state:"loading",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:"loading",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function PD(e,t){return{state:"submitting",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function ns(e){return{state:"idle",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function ID(e,t){try{let n=e.sessionStorage.getItem(Aj);if(n){let r=JSON.parse(n);for(let[o,s]of Object.entries(r||{}))s&&Array.isArray(s)&&t.set(o,new Set(s||[]))}}catch{}}function DD(e,t){if(t.size>0){let n={};for(let[r,o]of t)n[r]=[...o];try{e.sessionStorage.setItem(Aj,JSON.stringify(n))}catch(r){ki(!1,"Failed to save applied view transitions in sessionStorage ("+r+").")}}}/** - * React Router v6.25.1 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function Yd(){return Yd=Object.assign?Object.assign.bind():function(e){for(var t=1;t{l.current=!0}),y.useCallback(function(u,f){if(f===void 0&&(f={}),!l.current)return;if(typeof u=="number"){r.go(u);return}let p=Gf(u,JSON.parse(i),s,f.relative==="path");e==null&&t!=="/"&&(p.pathname=p.pathname==="/"?t:No([t,p.pathname])),(f.replace?r.replace:r.push)(p,f.state,f)},[t,r,i,s,e])}function Ta(){let{matches:e}=y.useContext(Vo),t=e[e.length-1];return t?t.params:{}}function Gj(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=y.useContext(zs),{matches:o}=y.useContext(Vo),{pathname:s}=eu(),i=JSON.stringify(Hf(o,r.v7_relativeSplatPath));return y.useMemo(()=>Gf(e,JSON.parse(i),s,n==="path"),[e,i,s,n])}function AD(e,t,n,r){Vi()||Ze(!1);let{navigator:o}=y.useContext(zs),{matches:s}=y.useContext(Vo),i=s[s.length-1],l=i?i.params:{};i&&i.pathname;let c=i?i.pathnameBase:"/";i&&i.route;let u=eu(),f;f=u;let p=f.pathname||"/",d=p;if(c!=="/"){let g=c.replace(/^\//,"").split("/");d="/"+p.replace(/^\//,"").split("/").slice(g.length).join("/")}let h=qs(e,{pathname:d});return VD(h&&h.map(g=>Object.assign({},g,{params:Object.assign({},l,g.params),pathname:No([c,o.encodeLocation?o.encodeLocation(g.pathname).pathname:g.pathname]),pathnameBase:g.pathnameBase==="/"?c:No([c,o.encodeLocation?o.encodeLocation(g.pathnameBase).pathname:g.pathnameBase])})),s,n,r)}function FD(){let e=GD(),t=Wf(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,o={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return y.createElement(y.Fragment,null,y.createElement("h2",null,"Unexpected Application Error!"),y.createElement("h3",{style:{fontStyle:"italic"}},t),n?y.createElement("pre",{style:o},n):null,null)}const LD=y.createElement(FD,null);class $D extends y.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?y.createElement(Vo.Provider,{value:this.props.routeContext},y.createElement(Bj.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function zD(e){let{routeContext:t,match:n,children:r}=e,o=y.useContext(Kf);return o&&o.static&&o.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(o.staticContext._deepestRenderedBoundaryId=n.route.id),y.createElement(Vo.Provider,{value:t},r)}function VD(e,t,n,r){var o;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var s;if((s=n)!=null&&s.errors)e=n.matches;else return null}let i=e,l=(o=n)==null?void 0:o.errors;if(l!=null){let f=i.findIndex(p=>p.route.id&&(l==null?void 0:l[p.route.id])!==void 0);f>=0||Ze(!1),i=i.slice(0,Math.min(i.length,f+1))}let c=!1,u=-1;if(n&&r&&r.v7_partialHydration)for(let f=0;f=0?i=i.slice(0,u+1):i=[i[0]];break}}}return i.reduceRight((f,p,d)=>{let h,m=!1,g=null,w=null;n&&(h=l&&p.route.id?l[p.route.id]:void 0,g=p.route.errorElement||LD,c&&(u<0&&d===0?(KD("route-fallback"),m=!0,w=null):u===d&&(m=!0,w=p.route.hydrateFallbackElement||null)));let x=t.concat(i.slice(0,d+1)),v=()=>{let b;return h?b=g:m?b=w:p.route.Component?b=y.createElement(p.route.Component,null):p.route.element?b=p.route.element:b=f,y.createElement(zD,{match:p,routeContext:{outlet:f,matches:x,isDataRoute:n!=null},children:b})};return n&&(p.route.ErrorBoundary||p.route.errorElement||d===0)?y.createElement($D,{location:n.location,revalidation:n.revalidation,component:g,error:h,children:v(),routeContext:{outlet:null,matches:x,isDataRoute:!0}}):v()},null)}var Wj=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(Wj||{}),Xd=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(Xd||{});function UD(e){let t=y.useContext(Kf);return t||Ze(!1),t}function BD(e){let t=y.useContext(Uj);return t||Ze(!1),t}function HD(e){let t=y.useContext(Vo);return t||Ze(!1),t}function Kj(e){let t=HD(),n=t.matches[t.matches.length-1];return n.route.id||Ze(!1),n.route.id}function GD(){var e;let t=y.useContext(Bj),n=BD(Xd.UseRouteError),r=Kj(Xd.UseRouteError);return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function WD(){let{router:e}=UD(Wj.UseNavigateStable),t=Kj(Xd.UseNavigateStable),n=y.useRef(!1);return Hj(()=>{n.current=!0}),y.useCallback(function(o,s){s===void 0&&(s={}),n.current&&(typeof o=="number"?e.navigate(o):e.navigate(o,Yd({fromRouteId:t},s)))},[e,t])}const Mw={};function KD(e,t,n){Mw[e]||(Mw[e]=!0)}function qj(e){let{to:t,replace:n,state:r,relative:o}=e;Vi()||Ze(!1);let{future:s,static:i}=y.useContext(zs),{matches:l}=y.useContext(Vo),{pathname:c}=eu(),u=ir(),f=Gf(t,Hf(l,s.v7_relativeSplatPath),c,o==="path"),p=JSON.stringify(f);return y.useEffect(()=>u(JSON.parse(p),{replace:n,state:r,relative:o}),[u,p,o,n,r]),null}function qD(e){let{basename:t="/",children:n=null,location:r,navigationType:o=Ht.Pop,navigator:s,static:i=!1,future:l}=e;Vi()&&Ze(!1);let c=t.replace(/^\/*/,"/"),u=y.useMemo(()=>({basename:c,navigator:s,static:i,future:Yd({v7_relativeSplatPath:!1},l)}),[c,l,s,i]);typeof r=="string"&&(r=$s(r));let{pathname:f="/",search:p="",hash:d="",state:h=null,key:m="default"}=r,g=y.useMemo(()=>{let w=zi(f,c);return w==null?null:{location:{pathname:w,search:p,hash:d,state:h,key:m},navigationType:o}},[c,f,p,d,h,m,o]);return g==null?null:y.createElement(zs.Provider,{value:u},y.createElement(Gv.Provider,{children:n,value:g}))}new Promise(()=>{});function ZD(e){let t={hasErrorBoundary:e.ErrorBoundary!=null||e.errorElement!=null};return e.Component&&Object.assign(t,{element:y.createElement(e.Component),Component:void 0}),e.HydrateFallback&&Object.assign(t,{hydrateFallbackElement:y.createElement(e.HydrateFallback),HydrateFallback:void 0}),e.ErrorBoundary&&Object.assign(t,{errorElement:y.createElement(e.ErrorBoundary),ErrorBoundary:void 0}),t}/** - * React Router DOM v6.25.1 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function bc(){return bc=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0)&&(n[o]=e[o]);return n}function YD(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function XD(e,t){return e.button===0&&(!t||t==="_self")&&!YD(e)}const QD=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","unstable_viewTransition"],eO="6";try{window.__reactRouterVersion=eO}catch{}function tO(e,t){return hD({basename:void 0,future:bc({},void 0,{v7_prependBasename:!0}),history:LI({window:void 0}),hydrationData:nO(),routes:e,mapRouteProperties:ZD,unstable_dataStrategy:void 0,unstable_patchRoutesOnMiss:void 0,window:void 0}).initialize()}function nO(){var e;let t=(e=window)==null?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=bc({},t,{errors:rO(t.errors)})),t}function rO(e){if(!e)return null;let t=Object.entries(e),n={};for(let[r,o]of t)if(o&&o.__type==="RouteErrorResponse")n[r]=new Uv(o.status,o.statusText,o.data,o.internal===!0);else if(o&&o.__type==="Error"){if(o.__subType){let s=window[o.__subType];if(typeof s=="function")try{let i=new s(o.message);i.stack="",n[r]=i}catch{}}if(n[r]==null){let s=new Error(o.message);s.stack="",n[r]=s}}else n[r]=o;return n}const oO=y.createContext({isTransitioning:!1}),sO=y.createContext(new Map),aO="startTransition",Aw=Nf[aO],iO="flushSync",Fw=FI[iO];function lO(e){Aw?Aw(e):e()}function ml(e){Fw?Fw(e):e()}class cO{constructor(){this.status="pending",this.promise=new Promise((t,n)=>{this.resolve=r=>{this.status==="pending"&&(this.status="resolved",t(r))},this.reject=r=>{this.status==="pending"&&(this.status="rejected",n(r))}})}}function uO(e){let{fallbackElement:t,router:n,future:r}=e,[o,s]=y.useState(n.state),[i,l]=y.useState(),[c,u]=y.useState({isTransitioning:!1}),[f,p]=y.useState(),[d,h]=y.useState(),[m,g]=y.useState(),w=y.useRef(new Map),{v7_startTransition:x}=r||{},v=y.useCallback(E=>{x?lO(E):E()},[x]),b=y.useCallback((E,A)=>{let{deletedFetchers:F,unstable_flushSync:Z,unstable_viewTransitionOpts:I}=A;F.forEach(H=>w.current.delete(H)),E.fetchers.forEach((H,J)=>{H.data!==void 0&&w.current.set(J,H.data)});let q=n.window==null||n.window.document==null||typeof n.window.document.startViewTransition!="function";if(!I||q){Z?ml(()=>s(E)):v(()=>s(E));return}if(Z){ml(()=>{d&&(f&&f.resolve(),d.skipTransition()),u({isTransitioning:!0,flushSync:!0,currentLocation:I.currentLocation,nextLocation:I.nextLocation})});let H=n.window.document.startViewTransition(()=>{ml(()=>s(E))});H.finished.finally(()=>{ml(()=>{p(void 0),h(void 0),l(void 0),u({isTransitioning:!1})})}),ml(()=>h(H));return}d?(f&&f.resolve(),d.skipTransition(),g({state:E,currentLocation:I.currentLocation,nextLocation:I.nextLocation})):(l(E),u({isTransitioning:!0,flushSync:!1,currentLocation:I.currentLocation,nextLocation:I.nextLocation}))},[n.window,d,f,w,v]);y.useLayoutEffect(()=>n.subscribe(b),[n,b]),y.useEffect(()=>{c.isTransitioning&&!c.flushSync&&p(new cO)},[c]),y.useEffect(()=>{if(f&&i&&n.window){let E=i,A=f.promise,F=n.window.document.startViewTransition(async()=>{v(()=>s(E)),await A});F.finished.finally(()=>{p(void 0),h(void 0),l(void 0),u({isTransitioning:!1})}),h(F)}},[v,i,f,n.window]),y.useEffect(()=>{f&&i&&o.location.key===i.location.key&&f.resolve()},[f,d,o.location,i]),y.useEffect(()=>{!c.isTransitioning&&m&&(l(m.state),u({isTransitioning:!0,flushSync:!1,currentLocation:m.currentLocation,nextLocation:m.nextLocation}),g(void 0))},[c.isTransitioning,m]),y.useEffect(()=>{},[]);let C=y.useMemo(()=>({createHref:n.createHref,encodeLocation:n.encodeLocation,go:E=>n.navigate(E),push:(E,A,F)=>n.navigate(E,{state:A,preventScrollReset:F==null?void 0:F.preventScrollReset}),replace:(E,A,F)=>n.navigate(E,{replace:!0,state:A,preventScrollReset:F==null?void 0:F.preventScrollReset})}),[n]),j=n.basename||"/",S=y.useMemo(()=>({router:n,navigator:C,static:!1,basename:j}),[n,C,j]),N=y.useMemo(()=>({v7_relativeSplatPath:n.future.v7_relativeSplatPath}),[n.future.v7_relativeSplatPath]);return y.createElement(y.Fragment,null,y.createElement(Kf.Provider,{value:S},y.createElement(Uj.Provider,{value:o},y.createElement(sO.Provider,{value:w.current},y.createElement(oO.Provider,{value:c},y.createElement(qD,{basename:j,location:o.location,navigationType:o.historyAction,navigator:C,future:N},o.initialized||n.future.v7_partialHydration?y.createElement(dO,{routes:n.routes,future:n.future,state:o}):t))))),null)}const dO=y.memo(fO);function fO(e){let{routes:t,future:n,state:r}=e;return AD(t,void 0,r,n)}const pO=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",hO=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Lw=y.forwardRef(function(t,n){let{onClick:r,relative:o,reloadDocument:s,replace:i,state:l,target:c,to:u,preventScrollReset:f,unstable_viewTransition:p}=t,d=JD(t,QD),{basename:h}=y.useContext(zs),m,g=!1;if(typeof u=="string"&&hO.test(u)&&(m=u,pO))try{let b=new URL(window.location.href),C=u.startsWith("//")?new URL(b.protocol+u):new URL(u),j=zi(C.pathname,h);C.origin===b.origin&&j!=null?u=j+C.search+C.hash:g=!0}catch{}let w=OD(u,{relative:o}),x=gO(u,{replace:i,state:l,target:c,preventScrollReset:f,relative:o,unstable_viewTransition:p});function v(b){r&&r(b),b.defaultPrevented||x(b)}return y.createElement("a",bc({},d,{href:m||w,onClick:g||s?r:v,ref:n,target:c}))});var $w;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})($w||($w={}));var zw;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(zw||(zw={}));function gO(e,t){let{target:n,replace:r,state:o,preventScrollReset:s,relative:i,unstable_viewTransition:l}=t===void 0?{}:t,c=ir(),u=eu(),f=Gj(e,{relative:i});return y.useCallback(p=>{if(XD(p,n)){p.preventDefault();let d=r!==void 0?r:ma(u)===ma(f);c(e,{replace:d,state:o,preventScrollReset:s,relative:i,unstable_viewTransition:l})}},[u,c,f,r,o,n,e,s,i,l])}const sn=({children:e})=>{const t=localStorage.getItem("apiUrl"),n=localStorage.getItem("token"),r=localStorage.getItem("version");return!t||!n||!r?a.jsx(qj,{to:"/manager/login"}):e},mO=({children:e})=>{const t=localStorage.getItem("apiUrl"),n=localStorage.getItem("token"),r=localStorage.getItem("version");return t&&n&&r?a.jsx(qj,{to:"/"}):e};function Zj(e,t){return function(){return e.apply(t,arguments)}}const{toString:vO}=Object.prototype,{getPrototypeOf:Wv}=Object,qf=(e=>t=>{const n=vO.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),$r=e=>(e=e.toLowerCase(),t=>qf(t)===e),Zf=e=>t=>typeof t===e,{isArray:Ui}=Array,Sc=Zf("undefined");function yO(e){return e!==null&&!Sc(e)&&e.constructor!==null&&!Sc(e.constructor)&&mr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Jj=$r("ArrayBuffer");function xO(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Jj(e.buffer),t}const wO=Zf("string"),mr=Zf("function"),Yj=Zf("number"),Jf=e=>e!==null&&typeof e=="object",bO=e=>e===!0||e===!1,gd=e=>{if(qf(e)!=="object")return!1;const t=Wv(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},SO=$r("Date"),CO=$r("File"),jO=$r("Blob"),_O=$r("FileList"),EO=e=>Jf(e)&&mr(e.pipe),TO=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||mr(e.append)&&((t=qf(e))==="formdata"||t==="object"&&mr(e.toString)&&e.toString()==="[object FormData]"))},NO=$r("URLSearchParams"),[kO,RO,PO,IO]=["ReadableStream","Request","Response","Headers"].map($r),DO=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function tu(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),Ui(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const Qj=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,e_=e=>!Sc(e)&&e!==Qj;function nm(){const{caseless:e}=e_(this)&&this||{},t={},n=(r,o)=>{const s=e&&Xj(t,o)||o;gd(t[s])&&gd(r)?t[s]=nm(t[s],r):gd(r)?t[s]=nm({},r):Ui(r)?t[s]=r.slice():t[s]=r};for(let r=0,o=arguments.length;r(tu(t,(o,s)=>{n&&mr(o)?e[s]=Zj(o,n):e[s]=o},{allOwnKeys:r}),e),MO=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),AO=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},FO=(e,t,n,r)=>{let o,s,i;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),s=o.length;s-- >0;)i=o[s],(!r||r(i,e,t))&&!l[i]&&(t[i]=e[i],l[i]=!0);e=n!==!1&&Wv(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},LO=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},$O=e=>{if(!e)return null;if(Ui(e))return e;let t=e.length;if(!Yj(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},zO=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Wv(Uint8Array)),VO=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const s=o.value;t.call(e,s[0],s[1])}},UO=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},BO=$r("HTMLFormElement"),HO=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),Vw=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),GO=$r("RegExp"),t_=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};tu(n,(o,s)=>{let i;(i=t(o,s,e))!==!1&&(r[s]=i||o)}),Object.defineProperties(e,r)},WO=e=>{t_(e,(t,n)=>{if(mr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(mr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},KO=(e,t)=>{const n={},r=o=>{o.forEach(s=>{n[s]=!0})};return Ui(e)?r(e):r(String(e).split(t)),n},qO=()=>{},ZO=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,wh="abcdefghijklmnopqrstuvwxyz",Uw="0123456789",n_={DIGIT:Uw,ALPHA:wh,ALPHA_DIGIT:wh+wh.toUpperCase()+Uw},JO=(e=16,t=n_.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function YO(e){return!!(e&&mr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const XO=e=>{const t=new Array(10),n=(r,o)=>{if(Jf(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const s=Ui(r)?[]:{};return tu(r,(i,l)=>{const c=n(i,o+1);!Sc(c)&&(s[l]=c)}),t[o]=void 0,s}}return r};return n(e,0)},QO=$r("AsyncFunction"),eM=e=>e&&(Jf(e)||mr(e))&&mr(e.then)&&mr(e.catch),V={isArray:Ui,isArrayBuffer:Jj,isBuffer:yO,isFormData:TO,isArrayBufferView:xO,isString:wO,isNumber:Yj,isBoolean:bO,isObject:Jf,isPlainObject:gd,isReadableStream:kO,isRequest:RO,isResponse:PO,isHeaders:IO,isUndefined:Sc,isDate:SO,isFile:CO,isBlob:jO,isRegExp:GO,isFunction:mr,isStream:EO,isURLSearchParams:NO,isTypedArray:zO,isFileList:_O,forEach:tu,merge:nm,extend:OO,trim:DO,stripBOM:MO,inherits:AO,toFlatObject:FO,kindOf:qf,kindOfTest:$r,endsWith:LO,toArray:$O,forEachEntry:VO,matchAll:UO,isHTMLForm:BO,hasOwnProperty:Vw,hasOwnProp:Vw,reduceDescriptors:t_,freezeMethods:WO,toObjectSet:KO,toCamelCase:HO,noop:qO,toFiniteNumber:ZO,findKey:Xj,global:Qj,isContextDefined:e_,ALPHABET:n_,generateString:JO,isSpecCompliantForm:YO,toJSONObject:XO,isAsyncFn:QO,isThenable:eM};function Be(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}V.inherits(Be,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:V.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const r_=Be.prototype,o_={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{o_[e]={value:e}});Object.defineProperties(Be,o_);Object.defineProperty(r_,"isAxiosError",{value:!0});Be.from=(e,t,n,r,o,s)=>{const i=Object.create(r_);return V.toFlatObject(e,i,function(c){return c!==Error.prototype},l=>l!=="isAxiosError"),Be.call(i,e.message,t,n,r,o),i.cause=e,i.name=e.name,s&&Object.assign(i,s),i};const tM=null;function rm(e){return V.isPlainObject(e)||V.isArray(e)}function s_(e){return V.endsWith(e,"[]")?e.slice(0,-2):e}function Bw(e,t,n){return e?e.concat(t).map(function(o,s){return o=s_(o),!n&&s?"["+o+"]":o}).join(n?".":""):t}function nM(e){return V.isArray(e)&&!e.some(rm)}const rM=V.toFlatObject(V,{},null,function(t){return/^is[A-Z]/.test(t)});function Yf(e,t,n){if(!V.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=V.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(g,w){return!V.isUndefined(w[g])});const r=n.metaTokens,o=n.visitor||f,s=n.dots,i=n.indexes,c=(n.Blob||typeof Blob<"u"&&Blob)&&V.isSpecCompliantForm(t);if(!V.isFunction(o))throw new TypeError("visitor must be a function");function u(m){if(m===null)return"";if(V.isDate(m))return m.toISOString();if(!c&&V.isBlob(m))throw new Be("Blob is not supported. Use a Buffer instead.");return V.isArrayBuffer(m)||V.isTypedArray(m)?c&&typeof Blob=="function"?new Blob([m]):Buffer.from(m):m}function f(m,g,w){let x=m;if(m&&!w&&typeof m=="object"){if(V.endsWith(g,"{}"))g=r?g:g.slice(0,-2),m=JSON.stringify(m);else if(V.isArray(m)&&nM(m)||(V.isFileList(m)||V.endsWith(g,"[]"))&&(x=V.toArray(m)))return g=s_(g),x.forEach(function(b,C){!(V.isUndefined(b)||b===null)&&t.append(i===!0?Bw([g],C,s):i===null?g:g+"[]",u(b))}),!1}return rm(m)?!0:(t.append(Bw(w,g,s),u(m)),!1)}const p=[],d=Object.assign(rM,{defaultVisitor:f,convertValue:u,isVisitable:rm});function h(m,g){if(!V.isUndefined(m)){if(p.indexOf(m)!==-1)throw Error("Circular reference detected in "+g.join("."));p.push(m),V.forEach(m,function(x,v){(!(V.isUndefined(x)||x===null)&&o.call(t,x,V.isString(v)?v.trim():v,g,d))===!0&&h(x,g?g.concat(v):[v])}),p.pop()}}if(!V.isObject(e))throw new TypeError("data must be an object");return h(e),t}function Hw(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function Kv(e,t){this._pairs=[],e&&Yf(e,this,t)}const a_=Kv.prototype;a_.append=function(t,n){this._pairs.push([t,n])};a_.toString=function(t){const n=t?function(r){return t.call(this,r,Hw)}:Hw;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function oM(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function i_(e,t,n){if(!t)return e;const r=n&&n.encode||oM,o=n&&n.serialize;let s;if(o?s=o(t,n):s=V.isURLSearchParams(t)?t.toString():new Kv(t,n).toString(r),s){const i=e.indexOf("#");i!==-1&&(e=e.slice(0,i)),e+=(e.indexOf("?")===-1?"?":"&")+s}return e}class Gw{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){V.forEach(this.handlers,function(r){r!==null&&t(r)})}}const l_={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},sM=typeof URLSearchParams<"u"?URLSearchParams:Kv,aM=typeof FormData<"u"?FormData:null,iM=typeof Blob<"u"?Blob:null,lM={isBrowser:!0,classes:{URLSearchParams:sM,FormData:aM,Blob:iM},protocols:["http","https","file","blob","url","data"]},qv=typeof window<"u"&&typeof document<"u",cM=(e=>qv&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),uM=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",dM=qv&&window.location.href||"http://localhost",fM=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:qv,hasStandardBrowserEnv:cM,hasStandardBrowserWebWorkerEnv:uM,origin:dM},Symbol.toStringTag,{value:"Module"})),Pr={...fM,...lM};function pM(e,t){return Yf(e,new Pr.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,s){return Pr.isNode&&V.isBuffer(n)?(this.append(r,n.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)}},t))}function hM(e){return V.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function gM(e){const t={},n=Object.keys(e);let r;const o=n.length;let s;for(r=0;r=n.length;return i=!i&&V.isArray(o)?o.length:i,c?(V.hasOwnProp(o,i)?o[i]=[o[i],r]:o[i]=r,!l):((!o[i]||!V.isObject(o[i]))&&(o[i]=[]),t(n,r,o[i],s)&&V.isArray(o[i])&&(o[i]=gM(o[i])),!l)}if(V.isFormData(e)&&V.isFunction(e.entries)){const n={};return V.forEachEntry(e,(r,o)=>{t(hM(r),o,n,0)}),n}return null}function mM(e,t,n){if(V.isString(e))try{return(t||JSON.parse)(e),V.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const nu={transitional:l_,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,s=V.isObject(t);if(s&&V.isHTMLForm(t)&&(t=new FormData(t)),V.isFormData(t))return o?JSON.stringify(c_(t)):t;if(V.isArrayBuffer(t)||V.isBuffer(t)||V.isStream(t)||V.isFile(t)||V.isBlob(t)||V.isReadableStream(t))return t;if(V.isArrayBufferView(t))return t.buffer;if(V.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return pM(t,this.formSerializer).toString();if((l=V.isFileList(t))||r.indexOf("multipart/form-data")>-1){const c=this.env&&this.env.FormData;return Yf(l?{"files[]":t}:t,c&&new c,this.formSerializer)}}return s||o?(n.setContentType("application/json",!1),mM(t)):t}],transformResponse:[function(t){const n=this.transitional||nu.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(V.isResponse(t)||V.isReadableStream(t))return t;if(t&&V.isString(t)&&(r&&!this.responseType||o)){const i=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(i)throw l.name==="SyntaxError"?Be.from(l,Be.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Pr.classes.FormData,Blob:Pr.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};V.forEach(["delete","get","head","post","put","patch"],e=>{nu.headers[e]={}});const vM=V.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"]),yM=e=>{const t={};let n,r,o;return e&&e.split(` -`).forEach(function(i){o=i.indexOf(":"),n=i.substring(0,o).trim().toLowerCase(),r=i.substring(o+1).trim(),!(!n||t[n]&&vM[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},Ww=Symbol("internals");function vl(e){return e&&String(e).trim().toLowerCase()}function md(e){return e===!1||e==null?e:V.isArray(e)?e.map(md):String(e)}function xM(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const wM=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function bh(e,t,n,r,o){if(V.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!V.isString(t)){if(V.isString(r))return t.indexOf(r)!==-1;if(V.isRegExp(r))return r.test(t)}}function bM(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function SM(e,t){const n=V.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,s,i){return this[r].call(this,t,o,s,i)},configurable:!0})})}class Bn{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function s(l,c,u){const f=vl(c);if(!f)throw new Error("header name must be a non-empty string");const p=V.findKey(o,f);(!p||o[p]===void 0||u===!0||u===void 0&&o[p]!==!1)&&(o[p||c]=md(l))}const i=(l,c)=>V.forEach(l,(u,f)=>s(u,f,c));if(V.isPlainObject(t)||t instanceof this.constructor)i(t,n);else if(V.isString(t)&&(t=t.trim())&&!wM(t))i(yM(t),n);else if(V.isHeaders(t))for(const[l,c]of t.entries())s(c,l,r);else t!=null&&s(n,t,r);return this}get(t,n){if(t=vl(t),t){const r=V.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return xM(o);if(V.isFunction(n))return n.call(this,o,r);if(V.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=vl(t),t){const r=V.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||bh(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function s(i){if(i=vl(i),i){const l=V.findKey(r,i);l&&(!n||bh(r,r[l],l,n))&&(delete r[l],o=!0)}}return V.isArray(t)?t.forEach(s):s(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const s=n[r];(!t||bh(this,this[s],s,t,!0))&&(delete this[s],o=!0)}return o}normalize(t){const n=this,r={};return V.forEach(this,(o,s)=>{const i=V.findKey(r,s);if(i){n[i]=md(o),delete n[s];return}const l=t?bM(s):String(s).trim();l!==s&&delete n[s],n[l]=md(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return V.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&V.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` -`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[Ww]=this[Ww]={accessors:{}}).accessors,o=this.prototype;function s(i){const l=vl(i);r[l]||(SM(o,i),r[l]=!0)}return V.isArray(t)?t.forEach(s):s(t),this}}Bn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);V.reduceDescriptors(Bn.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});V.freezeMethods(Bn);function Sh(e,t){const n=this||nu,r=t||n,o=Bn.from(r.headers);let s=r.data;return V.forEach(e,function(l){s=l.call(n,s,o.normalize(),t?t.status:void 0)}),o.normalize(),s}function u_(e){return!!(e&&e.__CANCEL__)}function Bi(e,t,n){Be.call(this,e??"canceled",Be.ERR_CANCELED,t,n),this.name="CanceledError"}V.inherits(Bi,Be,{__CANCEL__:!0});function d_(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new Be("Request failed with status code "+n.status,[Be.ERR_BAD_REQUEST,Be.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function CM(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function jM(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,s=0,i;return t=t!==void 0?t:1e3,function(c){const u=Date.now(),f=r[s];i||(i=u),n[o]=c,r[o]=u;let p=s,d=0;for(;p!==o;)d+=n[p++],p=p%e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),u-ir)return o&&(clearTimeout(o),o=null),n=l,e.apply(null,arguments);o||(o=setTimeout(()=>(o=null,n=Date.now(),e.apply(null,arguments)),r-(l-n)))}}const Qd=(e,t,n=3)=>{let r=0;const o=jM(50,250);return _M(s=>{const i=s.loaded,l=s.lengthComputable?s.total:void 0,c=i-r,u=o(c),f=i<=l;r=i;const p={loaded:i,total:l,progress:l?i/l:void 0,bytes:c,rate:u||void 0,estimated:u&&l&&f?(l-i)/u:void 0,event:s,lengthComputable:l!=null};p[t?"download":"upload"]=!0,e(p)},n)},EM=Pr.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(s){let i=s;return t&&(n.setAttribute("href",i),i=n.href),n.setAttribute("href",i),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(i){const l=V.isString(i)?o(i):i;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}(),TM=Pr.hasStandardBrowserEnv?{write(e,t,n,r,o,s){const i=[e+"="+encodeURIComponent(t)];V.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),V.isString(r)&&i.push("path="+r),V.isString(o)&&i.push("domain="+o),s===!0&&i.push("secure"),document.cookie=i.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function NM(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function kM(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function f_(e,t){return e&&!NM(t)?kM(e,t):t}const Kw=e=>e instanceof Bn?{...e}:e;function va(e,t){t=t||{};const n={};function r(u,f,p){return V.isPlainObject(u)&&V.isPlainObject(f)?V.merge.call({caseless:p},u,f):V.isPlainObject(f)?V.merge({},f):V.isArray(f)?f.slice():f}function o(u,f,p){if(V.isUndefined(f)){if(!V.isUndefined(u))return r(void 0,u,p)}else return r(u,f,p)}function s(u,f){if(!V.isUndefined(f))return r(void 0,f)}function i(u,f){if(V.isUndefined(f)){if(!V.isUndefined(u))return r(void 0,u)}else return r(void 0,f)}function l(u,f,p){if(p in t)return r(u,f);if(p in e)return r(void 0,u)}const c={url:s,method:s,data:s,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:l,headers:(u,f)=>o(Kw(u),Kw(f),!0)};return V.forEach(Object.keys(Object.assign({},e,t)),function(f){const p=c[f]||o,d=p(e[f],t[f],f);V.isUndefined(d)&&p!==l||(n[f]=d)}),n}const p_=e=>{const t=va({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:l}=t;t.headers=i=Bn.from(i),t.url=i_(f_(t.baseURL,t.url),e.params,e.paramsSerializer),l&&i.set("Authorization","Basic "+btoa((l.username||"")+":"+(l.password?unescape(encodeURIComponent(l.password)):"")));let c;if(V.isFormData(n)){if(Pr.hasStandardBrowserEnv||Pr.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if((c=i.getContentType())!==!1){const[u,...f]=c?c.split(";").map(p=>p.trim()).filter(Boolean):[];i.setContentType([u||"multipart/form-data",...f].join("; "))}}if(Pr.hasStandardBrowserEnv&&(r&&V.isFunction(r)&&(r=r(t)),r||r!==!1&&EM(t.url))){const u=o&&s&&TM.read(s);u&&i.set(o,u)}return t},RM=typeof XMLHttpRequest<"u",PM=RM&&function(e){return new Promise(function(n,r){const o=p_(e);let s=o.data;const i=Bn.from(o.headers).normalize();let{responseType:l}=o,c;function u(){o.cancelToken&&o.cancelToken.unsubscribe(c),o.signal&&o.signal.removeEventListener("abort",c)}let f=new XMLHttpRequest;f.open(o.method.toUpperCase(),o.url,!0),f.timeout=o.timeout;function p(){if(!f)return;const h=Bn.from("getAllResponseHeaders"in f&&f.getAllResponseHeaders()),g={data:!l||l==="text"||l==="json"?f.responseText:f.response,status:f.status,statusText:f.statusText,headers:h,config:e,request:f};d_(function(x){n(x),u()},function(x){r(x),u()},g),f=null}"onloadend"in f?f.onloadend=p:f.onreadystatechange=function(){!f||f.readyState!==4||f.status===0&&!(f.responseURL&&f.responseURL.indexOf("file:")===0)||setTimeout(p)},f.onabort=function(){f&&(r(new Be("Request aborted",Be.ECONNABORTED,o,f)),f=null)},f.onerror=function(){r(new Be("Network Error",Be.ERR_NETWORK,o,f)),f=null},f.ontimeout=function(){let m=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const g=o.transitional||l_;o.timeoutErrorMessage&&(m=o.timeoutErrorMessage),r(new Be(m,g.clarifyTimeoutError?Be.ETIMEDOUT:Be.ECONNABORTED,o,f)),f=null},s===void 0&&i.setContentType(null),"setRequestHeader"in f&&V.forEach(i.toJSON(),function(m,g){f.setRequestHeader(g,m)}),V.isUndefined(o.withCredentials)||(f.withCredentials=!!o.withCredentials),l&&l!=="json"&&(f.responseType=o.responseType),typeof o.onDownloadProgress=="function"&&f.addEventListener("progress",Qd(o.onDownloadProgress,!0)),typeof o.onUploadProgress=="function"&&f.upload&&f.upload.addEventListener("progress",Qd(o.onUploadProgress)),(o.cancelToken||o.signal)&&(c=h=>{f&&(r(!h||h.type?new Bi(null,e,f):h),f.abort(),f=null)},o.cancelToken&&o.cancelToken.subscribe(c),o.signal&&(o.signal.aborted?c():o.signal.addEventListener("abort",c)));const d=CM(o.url);if(d&&Pr.protocols.indexOf(d)===-1){r(new Be("Unsupported protocol "+d+":",Be.ERR_BAD_REQUEST,e));return}f.send(s||null)})},IM=(e,t)=>{let n=new AbortController,r;const o=function(c){if(!r){r=!0,i();const u=c instanceof Error?c:this.reason;n.abort(u instanceof Be?u:new Bi(u instanceof Error?u.message:u))}};let s=t&&setTimeout(()=>{o(new Be(`timeout ${t} of ms exceeded`,Be.ETIMEDOUT))},t);const i=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach(c=>{c&&(c.removeEventListener?c.removeEventListener("abort",o):c.unsubscribe(o))}),e=null)};e.forEach(c=>c&&c.addEventListener&&c.addEventListener("abort",o));const{signal:l}=n;return l.unsubscribe=i,[l,()=>{s&&clearTimeout(s),s=null}]},DM=function*(e,t){let n=e.byteLength;if(!t||n{const s=OM(e,t,o);let i=0;return new ReadableStream({type:"bytes",async pull(l){const{done:c,value:u}=await s.next();if(c){l.close(),r();return}let f=u.byteLength;n&&n(i+=f),l.enqueue(new Uint8Array(u))},cancel(l){return r(l),s.return()}},{highWaterMark:2})},Zw=(e,t)=>{const n=e!=null;return r=>setTimeout(()=>t({lengthComputable:n,total:e,loaded:r}))},Xf=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",h_=Xf&&typeof ReadableStream=="function",om=Xf&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),MM=h_&&(()=>{let e=!1;const t=new Request(Pr.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})(),Jw=64*1024,sm=h_&&!!(()=>{try{return V.isReadableStream(new Response("").body)}catch{}})(),ef={stream:sm&&(e=>e.body)};Xf&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!ef[t]&&(ef[t]=V.isFunction(e[t])?n=>n[t]():(n,r)=>{throw new Be(`Response type '${t}' is not supported`,Be.ERR_NOT_SUPPORT,r)})})})(new Response);const AM=async e=>{if(e==null)return 0;if(V.isBlob(e))return e.size;if(V.isSpecCompliantForm(e))return(await new Request(e).arrayBuffer()).byteLength;if(V.isArrayBufferView(e))return e.byteLength;if(V.isURLSearchParams(e)&&(e=e+""),V.isString(e))return(await om(e)).byteLength},FM=async(e,t)=>{const n=V.toFiniteNumber(e.getContentLength());return n??AM(t)},LM=Xf&&(async e=>{let{url:t,method:n,data:r,signal:o,cancelToken:s,timeout:i,onDownloadProgress:l,onUploadProgress:c,responseType:u,headers:f,withCredentials:p="same-origin",fetchOptions:d}=p_(e);u=u?(u+"").toLowerCase():"text";let[h,m]=o||s||i?IM([o,s],i):[],g,w;const x=()=>{!g&&setTimeout(()=>{h&&h.unsubscribe()}),g=!0};let v;try{if(c&&MM&&n!=="get"&&n!=="head"&&(v=await FM(f,r))!==0){let S=new Request(t,{method:"POST",body:r,duplex:"half"}),N;V.isFormData(r)&&(N=S.headers.get("content-type"))&&f.setContentType(N),S.body&&(r=qw(S.body,Jw,Zw(v,Qd(c)),null,om))}V.isString(p)||(p=p?"cors":"omit"),w=new Request(t,{...d,signal:h,method:n.toUpperCase(),headers:f.normalize().toJSON(),body:r,duplex:"half",withCredentials:p});let b=await fetch(w);const C=sm&&(u==="stream"||u==="response");if(sm&&(l||C)){const S={};["status","statusText","headers"].forEach(E=>{S[E]=b[E]});const N=V.toFiniteNumber(b.headers.get("content-length"));b=new Response(qw(b.body,Jw,l&&Zw(N,Qd(l,!0)),C&&x,om),S)}u=u||"text";let j=await ef[V.findKey(ef,u)||"text"](b,e);return!C&&x(),m&&m(),await new Promise((S,N)=>{d_(S,N,{data:j,headers:Bn.from(b.headers),status:b.status,statusText:b.statusText,config:e,request:w})})}catch(b){throw x(),b&&b.name==="TypeError"&&/fetch/i.test(b.message)?Object.assign(new Be("Network Error",Be.ERR_NETWORK,e,w),{cause:b.cause||b}):Be.from(b,b&&b.code,e,w)}}),am={http:tM,xhr:PM,fetch:LM};V.forEach(am,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Yw=e=>`- ${e}`,$M=e=>V.isFunction(e)||e===null||e===!1,g_={getAdapter:e=>{e=V.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let s=0;s`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build"));let i=t?s.length>1?`since : -`+s.map(Yw).join(` -`):" "+Yw(s[0]):"as no adapter specified";throw new Be("There is no suitable adapter to dispatch the request "+i,"ERR_NOT_SUPPORT")}return r},adapters:am};function Ch(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Bi(null,e)}function Xw(e){return Ch(e),e.headers=Bn.from(e.headers),e.data=Sh.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),g_.getAdapter(e.adapter||nu.adapter)(e).then(function(r){return Ch(e),r.data=Sh.call(e,e.transformResponse,r),r.headers=Bn.from(r.headers),r},function(r){return u_(r)||(Ch(e),r&&r.response&&(r.response.data=Sh.call(e,e.transformResponse,r.response),r.response.headers=Bn.from(r.response.headers))),Promise.reject(r)})}const m_="1.7.2",Zv={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Zv[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Qw={};Zv.transitional=function(t,n,r){function o(s,i){return"[Axios v"+m_+"] Transitional option '"+s+"'"+i+(r?". "+r:"")}return(s,i,l)=>{if(t===!1)throw new Be(o(i," has been removed"+(n?" in "+n:"")),Be.ERR_DEPRECATED);return n&&!Qw[i]&&(Qw[i]=!0,console.warn(o(i," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(s,i,l):!0}};function zM(e,t,n){if(typeof e!="object")throw new Be("options must be an object",Be.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const s=r[o],i=t[s];if(i){const l=e[s],c=l===void 0||i(l,s,e);if(c!==!0)throw new Be("option "+s+" must be "+c,Be.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Be("Unknown option "+s,Be.ERR_BAD_OPTION)}}const im={assertOptions:zM,validators:Zv},Qo=im.validators;class aa{constructor(t){this.defaults=t,this.interceptors={request:new Gw,response:new Gw}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let o;Error.captureStackTrace?Error.captureStackTrace(o={}):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=` -`+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=va(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&im.assertOptions(r,{silentJSONParsing:Qo.transitional(Qo.boolean),forcedJSONParsing:Qo.transitional(Qo.boolean),clarifyTimeoutError:Qo.transitional(Qo.boolean)},!1),o!=null&&(V.isFunction(o)?n.paramsSerializer={serialize:o}:im.assertOptions(o,{encode:Qo.function,serialize:Qo.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&V.merge(s.common,s[n.method]);s&&V.forEach(["delete","get","head","post","put","patch","common"],m=>{delete s[m]}),n.headers=Bn.concat(i,s);const l=[];let c=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(c=c&&g.synchronous,l.unshift(g.fulfilled,g.rejected))});const u=[];this.interceptors.response.forEach(function(g){u.push(g.fulfilled,g.rejected)});let f,p=0,d;if(!c){const m=[Xw.bind(this),void 0];for(m.unshift.apply(m,l),m.push.apply(m,u),d=m.length,f=Promise.resolve(n);p{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(l=>{r.subscribe(l),s=l}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,l){r.reason||(r.reason=new Bi(s,i,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new Jv(function(o){t=o}),cancel:t}}}function VM(e){return function(n){return e.apply(null,n)}}function UM(e){return V.isObject(e)&&e.isAxiosError===!0}const lm={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(lm).forEach(([e,t])=>{lm[t]=e});function v_(e){const t=new aa(e),n=Zj(aa.prototype.request,t);return V.extend(n,aa.prototype,t,{allOwnKeys:!0}),V.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return v_(va(e,o))},n}const Lt=v_(nu);Lt.Axios=aa;Lt.CanceledError=Bi;Lt.CancelToken=Jv;Lt.isCancel=u_;Lt.VERSION=m_;Lt.toFormData=Yf;Lt.AxiosError=Be;Lt.Cancel=Lt.CanceledError;Lt.all=function(t){return Promise.all(t)};Lt.spread=VM;Lt.isAxiosError=UM;Lt.mergeConfig=va;Lt.AxiosHeaders=Bn;Lt.formToJSON=e=>c_(V.isHTMLForm(e)?new FormData(e):e);Lt.getAdapter=g_.getAdapter;Lt.HttpStatusCode=lm;Lt.default=Lt;const BM=async(e,t)=>{try{const n=e.endsWith("/")?e.slice(0,-1):e;return localStorage.setItem("apiUrl",n),localStorage.setItem("token",t),!0}catch{return!1}},HM=async e=>(await Lt.get(`${e}/`)).data,y_=()=>{localStorage.removeItem("apiUrl"),localStorage.removeItem("token"),localStorage.removeItem("version")},GM=async(e,t)=>{try{return(await Lt.post(`${e}/verify-creds`,{},{headers:{apikey:t}})).data}catch{return null}};class zr{constructor(){this.apiInstance=Lt.create({timeout:1e4}),this.apiInstance.interceptors.request.use(async t=>{const n=localStorage.getItem("token");return n&&(t.headers.apikey=`${n}`),t},t=>Promise.reject(t))}getInstance(){const t=localStorage.getItem("apiUrl");return t&&(this.apiInstance.defaults.baseURL=t.toString()),this.apiInstance}}const Uo=new zr,WM=async e=>(await Uo.getInstance().post("/instance/create",e)).data,KM=async()=>(await Uo.getInstance().get("/instance/fetchInstances")).data,x_=async e=>(await Uo.getInstance().get(`/instance/fetchInstances?instanceId=${e}`)).data,qM=async e=>(await Uo.getInstance().post(`/instance/restart/${e}`)).data,w_=async e=>(await Uo.getInstance().delete(`/instance/logout/${e}`)).data,ZM=async e=>(await Uo.getInstance().delete(`/instance/delete/${e}`)).data,e0=async(e,t,n)=>{let r=`/instance/connect/${e}`;return n&&(r+=`?number=${n}`),(await Uo.getInstance().get(r,{headers:{apikey:t}})).data},JM=async(e,t)=>(await Uo.getInstance().get(`/settings/find/${e}`,{headers:{apikey:t}})).data,YM=async(e,t,n)=>(await Uo.getInstance().post(`/settings/set/${e}`,n,{headers:{apikey:t}})).data;/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const XM=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),b_=(...e)=>e.filter((t,n,r)=>!!t&&r.indexOf(t)===n).join(" ");/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */var QM={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const eA=y.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:s,iconNode:i,...l},c)=>y.createElement("svg",{ref:c,...QM,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:b_("lucide",o),...l},[...i.map(([u,f])=>y.createElement(u,f)),...Array.isArray(s)?s:[s]]));/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const rt=(e,t)=>{const n=y.forwardRef(({className:r,...o},s)=>y.createElement(eA,{ref:s,iconNode:t,className:b_(`lucide-${XM(e)}`,r),...o}));return n.displayName=`${e}`,n};/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const tA=rt("ArrowUpDown",[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const nA=rt("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ai=rt("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Qf=rt("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const rA=rt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const oA=rt("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const sA=rt("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const aA=rt("CircleHelp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Yv=rt("CircleStop",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{width:"6",height:"6",x:"9",y:"9",key:"1wrtvo"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const iA=rt("CircleUser",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662",key:"154egf"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const lA=rt("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ru=rt("Cog",[["path",{d:"M12 20a8 8 0 1 0 0-16 8 8 0 0 0 0 16Z",key:"sobvz5"}],["path",{d:"M12 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z",key:"11i496"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 22v-2",key:"1osdcq"}],["path",{d:"m17 20.66-1-1.73",key:"eq3orb"}],["path",{d:"M11 10.27 7 3.34",key:"16pf9h"}],["path",{d:"m20.66 17-1.73-1",key:"sg0v6f"}],["path",{d:"m3.34 7 1.73 1",key:"1ulond"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"m20.66 7-1.73 1",key:"1ow05n"}],["path",{d:"m3.34 17 1.73-1",key:"nuk764"}],["path",{d:"m17 3.34-1 1.73",key:"2wel8s"}],["path",{d:"m11 13.73-4 6.93",key:"794ttg"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const S_=rt("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Xv=rt("Delete",[["path",{d:"M10 5a2 2 0 0 0-1.344.519l-6.328 5.74a1 1 0 0 0 0 1.481l6.328 5.741A2 2 0 0 0 10 19h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2z",key:"1yo7s0"}],["path",{d:"m12 9 6 6",key:"anjzzh"}],["path",{d:"m18 9-6 6",key:"1fp51s"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const cA=rt("DoorOpen",[["path",{d:"M13 4h3a2 2 0 0 1 2 2v14",key:"hrm0s9"}],["path",{d:"M2 20h3",key:"1gaodv"}],["path",{d:"M13 20h9",key:"s90cdi"}],["path",{d:"M10 12v.01",key:"vx6srw"}],["path",{d:"M13 4.562v16.157a1 1 0 0 1-1.242.97L5 20V5.562a2 2 0 0 1 1.515-1.94l4-1A2 2 0 0 1 13 4.561Z",key:"199qr4"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ep=rt("Ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const C_=rt("EyeOff",[["path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24",key:"1jxqfv"}],["path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68",key:"9wicm4"}],["path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61",key:"1jreej"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const j_=rt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const uA=rt("FileQuestion",[["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const dA=rt("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const fA=rt("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const pA=rt("LifeBuoy",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.93 4.93 4.24 4.24",key:"1ymg45"}],["path",{d:"m14.83 9.17 4.24-4.24",key:"1cb5xl"}],["path",{d:"m14.83 14.83 4.24 4.24",key:"q42g0n"}],["path",{d:"m9.17 14.83-4.24 4.24",key:"bqpfvv"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Qv=rt("ListCollapse",[["path",{d:"m3 10 2.5-2.5L3 5",key:"i6eama"}],["path",{d:"m3 19 2.5-2.5L3 14",key:"w2gmor"}],["path",{d:"M10 6h11",key:"c7qv1k"}],["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 18h11",key:"11hvi2"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const hA=rt("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ey=rt("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const gA=rt("Paperclip",[["path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48",key:"1u3ebp"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ty=rt("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ny=rt("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ou=rt("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const __=rt("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const mA=rt("Sparkle",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const vA=rt("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const yA=rt("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]);function E_({instanceId:e}){const t=ir(),n=()=>{y_(),t("/manager/login")},r=()=>{t("/manager/")},[o,s]=y.useState(null);return y.useEffect(()=>{e&&(async l=>{try{const c=await x_(l);s(c[0]||null)}catch(c){console.error("Erro ao buscar dados:",c)}})(e)},[e]),a.jsxs("header",{children:[a.jsxs("a",{href:"#",onClick:r,className:"header-logo",children:[a.jsx("img",{src:"/assets/images/evolution-logo.png",alt:"Logo"}),a.jsx("span",{className:"header-title",children:"Evolution Manager"})]}),a.jsxs("div",{className:"header-buttons",children:[e&&a.jsx("button",{className:"profile-button",children:a.jsx("img",{src:(o==null?void 0:o.profilePicUrl)||"/assets/images/evolution-logo.png",alt:"Perfil",className:"profile-picture"})}),a.jsx("button",{onClick:n,className:"exit-button",children:a.jsx(cA,{size:"18"})})]})]})}const xA=[{id:"dashboard",title:"Visão Geral",icon:fA,path:"dashboard"},{navLabel:!0,title:"Configurações",icon:ru,children:[{id:"settings",title:"Comportamento",path:"settings"},{id:"openai",title:"OpenAI",path:"openai"},{id:"dify",title:"Dify",path:"dify"},{id:"webhook",title:"Webhook",path:"webhook"},{id:"websocket",title:"Websocket",path:"websocket"},{id:"rabbitmq",title:"RabbitMQ",path:"rabbitmq"},{id:"sqs",title:"Amazon SQS",path:"sqs"},{id:"chatwoot",title:"Chatwoot",path:"chatwoot"},{id:"typebot",title:"Typebot",path:"typebot"},{id:"proxy",title:"Proxy",path:"proxy"}]},{id:"documentation",title:"Documentação",icon:uA,link:"https://doc.evolution-api.com"},{id:"postman",title:"Postman",icon:aA,link:"https://evolution-api.com/postman"},{id:"discord",title:"Discord",icon:ey,link:"https://evolution-api.com/discord"},{id:"support-premium",title:"Support Premium",icon:pA,link:"https://evolution-api.com/suporte-pro"}],T_=y.createContext(null),Tt=()=>{const e=y.useContext(T_);if(!e)throw new Error("useInstance must be used within an InstanceProvider");return e},wA=({children:e})=>{const{instanceId:t}=Ta(),[n,r]=y.useState(null);return y.useEffect(()=>{t&&(async s=>{try{const i=await x_(s);r(i[0]||null)}catch(i){console.error("Erro ao buscar dados:",i)}})(t)},[t]),a.jsx(T_.Provider,{value:{instance:n},children:e})};function je(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function bA(e,t){const n=y.createContext(t);function r(s){const{children:i,...l}=s,c=y.useMemo(()=>l,Object.values(l));return a.jsx(n.Provider,{value:c,children:i})}function o(s){const i=y.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function lo(e,t=[]){let n=[];function r(s,i){const l=y.createContext(i),c=n.length;n=[...n,i];function u(p){const{scope:d,children:h,...m}=p,g=(d==null?void 0:d[e][c])||l,w=y.useMemo(()=>m,Object.values(m));return a.jsx(g.Provider,{value:w,children:h})}function f(p,d){const h=(d==null?void 0:d[e][c])||l,m=y.useContext(h);if(m)return m;if(i!==void 0)return i;throw new Error(`\`${p}\` must be used within \`${s}\``)}return u.displayName=s+"Provider",[u,f]}const o=()=>{const s=n.map(i=>y.createContext(i));return function(l){const c=(l==null?void 0:l[e])||s;return y.useMemo(()=>({[`__scope${e}`]:{...l,[e]:c}}),[l,c])}};return o.scopeName=e,[r,SA(o,...t)]}function SA(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((l,{useScope:c,scopeName:u})=>{const p=c(s)[`__scope${u}`];return{...l,...p}},{});return y.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}function wr(e){const t=y.useRef(e);return y.useEffect(()=>{t.current=e}),y.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function js({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=CA({defaultProp:t,onChange:n}),s=e!==void 0,i=s?e:r,l=wr(n),c=y.useCallback(u=>{if(s){const p=typeof u=="function"?u(e):u;p!==e&&l(p)}else o(u)},[s,e,o,l]);return[i,c]}function CA({defaultProp:e,onChange:t}){const n=y.useState(e),[r]=n,o=y.useRef(r),s=wr(t);return y.useEffect(()=>{o.current!==r&&(s(r),o.current=r)},[r,o,s]),n}var bn=globalThis!=null&&globalThis.document?y.useLayoutEffect:()=>{};function jA(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function tp(...e){return t=>e.forEach(n=>jA(n,t))}function ut(...e){return y.useCallback(tp(...e),e)}var Oo=y.forwardRef((e,t)=>{const{children:n,...r}=e,o=y.Children.toArray(n),s=o.find(EA);if(s){const i=s.props.children,l=o.map(c=>c===s?y.Children.count(i)>1?y.Children.only(null):y.isValidElement(i)?i.props.children:null:c);return a.jsx(cm,{...r,ref:t,children:y.isValidElement(i)?y.cloneElement(i,void 0,l):null})}return a.jsx(cm,{...r,ref:t,children:n})});Oo.displayName="Slot";var cm=y.forwardRef((e,t)=>{const{children:n,...r}=e;if(y.isValidElement(n)){const o=NA(n);return y.cloneElement(n,{...TA(r,n.props),ref:t?tp(t,o):o})}return y.Children.count(n)>1?y.Children.only(null):null});cm.displayName="SlotClone";var _A=({children:e})=>a.jsx(a.Fragment,{children:e});function EA(e){return y.isValidElement(e)&&e.type===_A}function TA(e,t){const n={...t};for(const r in t){const o=e[r],s=t[r];/^on[A-Z]/.test(r)?o&&s?n[r]=(...l)=>{s(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...s}:r==="className"&&(n[r]=[o,s].filter(Boolean).join(" "))}return{...e,...n}}function NA(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var kA=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Ve=kA.reduce((e,t)=>{const n=y.forwardRef((r,o)=>{const{asChild:s,...i}=r,l=s?Oo:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),a.jsx(l,{...i,ref:o})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function N_(e,t){e&&Ls.flushSync(()=>e.dispatchEvent(t))}function RA(e,t){return y.useReducer((n,r)=>t[n][r]??n,e)}var co=e=>{const{present:t,children:n}=e,r=PA(t),o=typeof n=="function"?n({present:r.isPresent}):y.Children.only(n),s=ut(r.ref,IA(o));return typeof n=="function"||r.isPresent?y.cloneElement(o,{ref:s}):null};co.displayName="Presence";function PA(e){const[t,n]=y.useState(),r=y.useRef({}),o=y.useRef(e),s=y.useRef("none"),i=e?"mounted":"unmounted",[l,c]=RA(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return y.useEffect(()=>{const u=$u(r.current);s.current=l==="mounted"?u:"none"},[l]),bn(()=>{const u=r.current,f=o.current;if(f!==e){const d=s.current,h=$u(u);e?c("MOUNT"):h==="none"||(u==null?void 0:u.display)==="none"?c("UNMOUNT"):c(f&&d!==h?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,c]),bn(()=>{if(t){const u=p=>{const h=$u(r.current).includes(p.animationName);p.target===t&&h&&Ls.flushSync(()=>c("ANIMATION_END"))},f=p=>{p.target===t&&(s.current=$u(r.current))};return t.addEventListener("animationstart",f),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{t.removeEventListener("animationstart",f),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:y.useCallback(u=>{u&&(r.current=getComputedStyle(u)),n(u)},[])}}function $u(e){return(e==null?void 0:e.animationName)||"none"}function IA(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var DA=Nf.useId||(()=>{}),OA=0;function Ir(e){const[t,n]=y.useState(DA());return bn(()=>{n(r=>r??String(OA++))},[e]),t?`radix-${t}`:""}var ry="Collapsible",[MA,BK]=lo(ry),[AA,oy]=MA(ry),k_=y.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:o,disabled:s,onOpenChange:i,...l}=e,[c=!1,u]=js({prop:r,defaultProp:o,onChange:i});return a.jsx(AA,{scope:n,disabled:s,contentId:Ir(),open:c,onOpenToggle:y.useCallback(()=>u(f=>!f),[u]),children:a.jsx(Ve.div,{"data-state":ay(c),"data-disabled":s?"":void 0,...l,ref:t})})});k_.displayName=ry;var R_="CollapsibleTrigger",P_=y.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,o=oy(R_,n);return a.jsx(Ve.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":ay(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...r,ref:t,onClick:je(e.onClick,o.onOpenToggle)})});P_.displayName=R_;var sy="CollapsibleContent",I_=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=oy(sy,e.__scopeCollapsible);return a.jsx(co,{present:n||o.open,children:({present:s})=>a.jsx(FA,{...r,ref:t,present:s})})});I_.displayName=sy;var FA=y.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:o,...s}=e,i=oy(sy,n),[l,c]=y.useState(r),u=y.useRef(null),f=ut(t,u),p=y.useRef(0),d=p.current,h=y.useRef(0),m=h.current,g=i.open||l,w=y.useRef(g),x=y.useRef();return y.useEffect(()=>{const v=requestAnimationFrame(()=>w.current=!1);return()=>cancelAnimationFrame(v)},[]),bn(()=>{const v=u.current;if(v){x.current=x.current||{transitionDuration:v.style.transitionDuration,animationName:v.style.animationName},v.style.transitionDuration="0s",v.style.animationName="none";const b=v.getBoundingClientRect();p.current=b.height,h.current=b.width,w.current||(v.style.transitionDuration=x.current.transitionDuration,v.style.animationName=x.current.animationName),c(r)}},[i.open,r]),a.jsx(Ve.div,{"data-state":ay(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!g,...s,ref:f,style:{"--radix-collapsible-content-height":d?`${d}px`:void 0,"--radix-collapsible-content-width":m?`${m}px`:void 0,...e.style},children:g&&o})});function ay(e){return e?"open":"closed"}var LA=k_;const $A=LA,zA=P_,VA=I_;function UA(){const e=ir(),{instance:t}=Tt(),n=r=>{!r||!t||(r.path&&e(`/manager/instance/${t.id}/${r.path}`),r.link&&window.open(r.link,"_blank"))};return a.jsx("menu",{className:"sidebar",children:a.jsx("ul",{className:"sidebar-nav",children:xA.map(r=>{const o=window.location.pathname;let s=!1;return r.path&&o.includes(r.path)?s=!0:s=!1,a.jsx("li",{className:"nav-item",children:r.children?a.jsxs($A,{children:[a.jsxs(zA,{children:[r.icon?a.jsxs(a.Fragment,{children:[a.jsx(r.icon,{className:"nav-icon",size:"15"}),a.jsx("span",{className:"nav-title",children:r.title})]}):a.jsx("span",{className:"nav-label",children:r.title}),r.children&&a.jsx("span",{className:"nav-arrow",children:a.jsx(Qf,{size:"15"})})]}),a.jsx(VA,{children:a.jsx("ul",{className:"sidebar-nav",children:r.children.map(i=>{const l=window.location.pathname;let c=!1;return i.path&&l.includes(i.path)?c=!0:c=!1,a.jsx("li",{className:"nav-item",children:a.jsx("button",{onClick:()=>n(i),className:c?"active":"",children:i.icon?a.jsxs(a.Fragment,{children:[a.jsx(i.icon,{className:"nav-icon",size:"15"}),a.jsx("span",{className:"nav-title",children:i.title})]}):a.jsx("span",{className:"nav-label",children:i.title})})},i.id)})})})]}):a.jsx("button",{onClick:()=>n(r),className:s?"active":"",children:r.icon?a.jsxs(a.Fragment,{children:[a.jsx(r.icon,{className:"nav-icon",size:"15"}),a.jsx("span",{className:"nav-title",children:r.title})]}):a.jsx("span",{className:"nav-label",children:r.title})})},r.id)})})})}const{createElement:Ri,createContext:BA,createRef:HK,forwardRef:D_,useCallback:Gn,useContext:O_,useEffect:ia,useImperativeHandle:M_,useLayoutEffect:HA,useMemo:GA,useRef:Fn,useState:Kl}=Nf,t0=Nf.useId,WA=HA,np=BA(null);np.displayName="PanelGroupContext";const la=WA,KA=typeof t0=="function"?t0:()=>null;let qA=0;function iy(e=null){const t=KA(),n=Fn(e||t||null);return n.current===null&&(n.current=""+qA++),e??n.current}function A_({children:e,className:t="",collapsedSize:n,collapsible:r,defaultSize:o,forwardedRef:s,id:i,maxSize:l,minSize:c,onCollapse:u,onExpand:f,onResize:p,order:d,style:h,tagName:m="div",...g}){const w=O_(np);if(w===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:x,expandPanel:v,getPanelSize:b,getPanelStyle:C,groupId:j,isPanelCollapsed:S,reevaluatePanelConstraints:N,registerPanel:E,resizePanel:A,unregisterPanel:F}=w,Z=iy(i),I=Fn({callbacks:{onCollapse:u,onExpand:f,onResize:p},constraints:{collapsedSize:n,collapsible:r,defaultSize:o,maxSize:l,minSize:c},id:Z,idIsFromProps:i!==void 0,order:d});Fn({didLogMissingDefaultSizeWarning:!1}),la(()=>{const{callbacks:H,constraints:J}=I.current,re={...J};I.current.id=Z,I.current.idIsFromProps=i!==void 0,I.current.order=d,H.onCollapse=u,H.onExpand=f,H.onResize=p,J.collapsedSize=n,J.collapsible=r,J.defaultSize=o,J.maxSize=l,J.minSize=c,(re.collapsedSize!==J.collapsedSize||re.collapsible!==J.collapsible||re.maxSize!==J.maxSize||re.minSize!==J.minSize)&&N(I.current,re)}),la(()=>{const H=I.current;return E(H),()=>{F(H)}},[d,Z,E,F]),M_(s,()=>({collapse:()=>{x(I.current)},expand:H=>{v(I.current,H)},getId(){return Z},getSize(){return b(I.current)},isCollapsed(){return S(I.current)},isExpanded(){return!S(I.current)},resize:H=>{A(I.current,H)}}),[x,v,b,S,Z,A]);const q=C(I.current,o);return Ri(m,{...g,children:e,className:t,id:i,style:{...q,...h},"data-panel":"","data-panel-collapsible":r||void 0,"data-panel-group-id":j,"data-panel-id":Z,"data-panel-size":parseFloat(""+q.flexGrow).toFixed(1)})}const F_=D_((e,t)=>Ri(A_,{...e,forwardedRef:t}));A_.displayName="Panel";F_.displayName="forwardRef(Panel)";let um=null,ta=null;function ZA(e,t){if(t){const n=(t&U_)!==0,r=(t&B_)!==0,o=(t&H_)!==0,s=(t&G_)!==0;if(n)return o?"se-resize":s?"ne-resize":"e-resize";if(r)return o?"sw-resize":s?"nw-resize":"w-resize";if(o)return"s-resize";if(s)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function JA(){ta!==null&&(document.head.removeChild(ta),um=null,ta=null)}function jh(e,t){const n=ZA(e,t);um!==n&&(um=n,ta===null&&(ta=document.createElement("style"),document.head.appendChild(ta)),ta.innerHTML=`*{cursor: ${n}!important;}`)}function L_(e){return e.type==="keydown"}function $_(e){return e.type.startsWith("pointer")}function z_(e){return e.type.startsWith("mouse")}function rp(e){if($_(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(z_(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function YA(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function XA(e,t,n){return e.xt.x&&e.yt.y}function QA(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:o0(e),b:o0(t)};let r;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),r=e;Ye(r,"Stacking order can only be calculated for elements with a common ancestor");const o={a:r0(n0(n.a)),b:r0(n0(n.b))};if(o.a===o.b){const s=r.childNodes,i={a:n.a.at(-1),b:n.b.at(-1)};let l=s.length;for(;l--;){const c=s[l];if(c===i.a)return 1;if(c===i.b)return-1}}return Math.sign(o.a-o.b)}const eF=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function tF(e){var t;const n=getComputedStyle((t=V_(e))!==null&&t!==void 0?t:e).display;return n==="flex"||n==="inline-flex"}function nF(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||tF(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||eF.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function n0(e){let t=e.length;for(;t--;){const n=e[t];if(Ye(n,"Missing node"),nF(n))return n}return null}function r0(e){return e&&Number(getComputedStyle(e).zIndex)||0}function o0(e){const t=[];for(;e;)t.push(e),e=V_(e);return t}function V_(e){const{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}const U_=1,B_=2,H_=4,G_=8,rF=YA()==="coarse";let Dr=[],Cc=!1,ls=new Map,op=new Map;const jc=new Set;function oF(e,t,n,r,o){var s;const{ownerDocument:i}=t,l={direction:n,element:t,hitAreaMargins:r,setResizeHandlerState:o},c=(s=ls.get(i))!==null&&s!==void 0?s:0;return ls.set(i,c+1),jc.add(l),tf(),function(){var f;op.delete(e),jc.delete(l);const p=(f=ls.get(i))!==null&&f!==void 0?f:1;if(ls.set(i,p-1),tf(),p===1&&ls.delete(i),Dr.includes(l)){const d=Dr.indexOf(l);d>=0&&Dr.splice(d,1),cy()}}}function s0(e){const{target:t}=e,{x:n,y:r}=rp(e);Cc=!0,ly({target:t,x:n,y:r}),tf(),Dr.length>0&&(nf("down",e),e.preventDefault(),e.stopPropagation())}function yl(e){const{x:t,y:n}=rp(e);if(e.buttons===0&&(Cc=!1,nf("up",e)),!Cc){const{target:r}=e;ly({target:r,x:t,y:n})}nf("move",e),cy(),Dr.length>0&&e.preventDefault()}function Fa(e){const{target:t}=e,{x:n,y:r}=rp(e);op.clear(),Cc=!1,Dr.length>0&&e.preventDefault(),nf("up",e),ly({target:t,x:n,y:r}),cy(),tf()}function ly({target:e,x:t,y:n}){Dr.splice(0);let r=null;e instanceof HTMLElement&&(r=e),jc.forEach(o=>{const{element:s,hitAreaMargins:i}=o,l=s.getBoundingClientRect(),{bottom:c,left:u,right:f,top:p}=l,d=rF?i.coarse:i.fine;if(t>=u-d&&t<=f+d&&n>=p-d&&n<=c+d){if(r!==null&&s!==r&&!s.contains(r)&&!r.contains(s)&&QA(r,s)>0){let m=r,g=!1;for(;m&&!m.contains(s);){if(XA(m.getBoundingClientRect(),l)){g=!0;break}m=m.parentElement}if(g)return}Dr.push(o)}})}function _h(e,t){op.set(e,t)}function cy(){let e=!1,t=!1;Dr.forEach(r=>{const{direction:o}=r;o==="horizontal"?e=!0:t=!0});let n=0;op.forEach(r=>{n|=r}),e&&t?jh("intersection",n):e?jh("horizontal",n):t?jh("vertical",n):JA()}function tf(){ls.forEach((e,t)=>{const{body:n}=t;n.removeEventListener("contextmenu",Fa),n.removeEventListener("pointerdown",s0),n.removeEventListener("pointerleave",yl),n.removeEventListener("pointermove",yl)}),window.removeEventListener("pointerup",Fa),window.removeEventListener("pointercancel",Fa),jc.size>0&&(Cc?(Dr.length>0&&ls.forEach((e,t)=>{const{body:n}=t;e>0&&(n.addEventListener("contextmenu",Fa),n.addEventListener("pointerleave",yl),n.addEventListener("pointermove",yl))}),window.addEventListener("pointerup",Fa),window.addEventListener("pointercancel",Fa)):ls.forEach((e,t)=>{const{body:n}=t;e>0&&(n.addEventListener("pointerdown",s0,{capture:!0}),n.addEventListener("pointermove",yl))}))}function nf(e,t){jc.forEach(n=>{const{setResizeHandlerState:r}=n,o=Dr.includes(n);r(e,o,t)})}function Ye(e,t){if(!e)throw console.error(t),Error(t)}const uy=10;function ya(e,t,n=uy){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function wo(e,t,n=uy){return ya(e,t,n)===0}function qn(e,t,n){return ya(e,t,n)===0}function sF(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r0&&(e=e<0?0-x:x)}}}{const p=e<0?l:c,d=n[p];Ye(d,`No panel constraints found for index ${p}`);const{collapsedSize:h=0,collapsible:m,minSize:g=0}=d;if(m){const w=t[p];if(Ye(w!=null,`Previous layout not found for panel index ${p}`),qn(w,g)){const x=w-h;ya(x,Math.abs(e))>0&&(e=e<0?0-x:x)}}}}{const p=e<0?1:-1;let d=e<0?c:l,h=0;for(;;){const g=t[d];Ye(g!=null,`Previous layout not found for panel index ${d}`);const x=ii({panelConstraints:n,panelIndex:d,size:100})-g;if(h+=x,d+=p,d<0||d>=n.length)break}const m=Math.min(Math.abs(e),Math.abs(h));e=e<0?0-m:m}{let d=e<0?l:c;for(;d>=0&&d=0))break;e<0?d--:d++}}if(sF(o,i))return o;{const p=e<0?c:l,d=t[p];Ye(d!=null,`Previous layout not found for panel index ${p}`);const h=d+u,m=ii({panelConstraints:n,panelIndex:p,size:h});if(i[p]=m,!qn(m,h)){let g=h-m,x=e<0?c:l;for(;x>=0&&x0?x--:x++}}}const f=i.reduce((p,d)=>d+p,0);return qn(f,100)?i:o}function aF({layout:e,panelsArray:t,pivotIndices:n}){let r=0,o=100,s=0,i=0;const l=n[0];Ye(l!=null,"No pivot index found"),t.forEach((p,d)=>{const{constraints:h}=p,{maxSize:m=100,minSize:g=0}=h;d===l?(r=g,o=m):(s+=g,i+=m)});const c=Math.min(o,100-s),u=Math.max(r,100-i),f=e[l];return{valueMax:c,valueMin:u,valueNow:f}}function _c(e,t=document){return Array.from(t.querySelectorAll(`[data-panel-resize-handle-id][data-panel-group-id="${e}"]`))}function W_(e,t,n=document){const o=_c(e,n).findIndex(s=>s.getAttribute("data-panel-resize-handle-id")===t);return o??null}function K_(e,t,n){const r=W_(e,t,n);return r!=null?[r,r+1]:[-1,-1]}function q_(e,t=document){var n;if(t instanceof HTMLElement&&(t==null||(n=t.dataset)===null||n===void 0?void 0:n.panelGroupId)==e)return t;const r=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return r||null}function sp(e,t=document){const n=t.querySelector(`[data-panel-resize-handle-id="${e}"]`);return n||null}function iF(e,t,n,r=document){var o,s,i,l;const c=sp(t,r),u=_c(e,r),f=c?u.indexOf(c):-1,p=(o=(s=n[f])===null||s===void 0?void 0:s.id)!==null&&o!==void 0?o:null,d=(i=(l=n[f+1])===null||l===void 0?void 0:l.id)!==null&&i!==void 0?i:null;return[p,d]}function lF({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:r,panelDataArray:o,panelGroupElement:s,setLayout:i}){Fn({didWarnAboutMissingResizeHandle:!1}),la(()=>{if(!s)return;const l=_c(n,s);for(let c=0;c{l.forEach((c,u)=>{c.removeAttribute("aria-controls"),c.removeAttribute("aria-valuemax"),c.removeAttribute("aria-valuemin"),c.removeAttribute("aria-valuenow")})}},[n,r,o,s]),ia(()=>{if(!s)return;const l=t.current;Ye(l,"Eager values not found");const{panelDataArray:c}=l,u=q_(n,s);Ye(u!=null,`No group found for id "${n}"`);const f=_c(n,s);Ye(f,`No resize handles found for group id "${n}"`);const p=f.map(d=>{const h=d.getAttribute("data-panel-resize-handle-id");Ye(h,"Resize handle element has no handle id attribute");const[m,g]=iF(n,h,c,s);if(m==null||g==null)return()=>{};const w=x=>{if(!x.defaultPrevented)switch(x.key){case"Enter":{x.preventDefault();const v=c.findIndex(b=>b.id===m);if(v>=0){const b=c[v];Ye(b,`No panel data found for index ${v}`);const C=r[v],{collapsedSize:j=0,collapsible:S,minSize:N=0}=b.constraints;if(C!=null&&S){const E=Il({delta:qn(C,j)?N-j:j-C,initialLayout:r,panelConstraints:c.map(A=>A.constraints),pivotIndices:K_(n,h,s),prevLayout:r,trigger:"keyboard"});r!==E&&i(E)}}break}}};return d.addEventListener("keydown",w),()=>{d.removeEventListener("keydown",w)}});return()=>{p.forEach(d=>d())}},[s,e,t,n,r,o,i])}function a0(e,t){if(e.length!==t.length)return!1;for(let n=0;ns.constraints);let r=0,o=100;for(let s=0;s{const s=e[o];Ye(s,`Panel data not found for index ${o}`);const{callbacks:i,constraints:l,id:c}=s,{collapsedSize:u=0,collapsible:f}=l,p=n[c];if(p==null||r!==p){n[c]=r;const{onCollapse:d,onExpand:h,onResize:m}=i;m&&m(r,p),f&&(d||h)&&(h&&(p==null||wo(p,u))&&!wo(r,u)&&h(),d&&(p==null||!wo(p,u))&&wo(r,u)&&d())}})}function zu(e,t){if(e.length!==t.length)return!1;for(let n=0;n{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...o)},t)}}function i0(e){try{if(typeof localStorage<"u")e.getItem=t=>localStorage.getItem(t),e.setItem=(t,n)=>{localStorage.setItem(t,n)};else throw new Error("localStorage not supported in this environment")}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}function J_(e){return`react-resizable-panels:${e}`}function Y_(e){return e.map(t=>{const{constraints:n,id:r,idIsFromProps:o,order:s}=t;return o?r:s?`${s}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((t,n)=>t.localeCompare(n)).join(",")}function X_(e,t){try{const n=J_(e),r=t.getItem(n);if(r){const o=JSON.parse(r);if(typeof o=="object"&&o!=null)return o}}catch{}return null}function hF(e,t,n){var r,o;const s=(r=X_(e,n))!==null&&r!==void 0?r:{},i=Y_(t);return(o=s[i])!==null&&o!==void 0?o:null}function gF(e,t,n,r,o){var s;const i=J_(e),l=Y_(t),c=(s=X_(e,o))!==null&&s!==void 0?s:{};c[l]={expandToSizes:Object.fromEntries(n.entries()),layout:r};try{o.setItem(i,JSON.stringify(c))}catch(u){console.error(u)}}function l0({layout:e,panelConstraints:t}){const n=[...e],r=n.reduce((s,i)=>s+i,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(s=>`${s}%`).join(", ")}`);if(!qn(r,100))for(let s=0;s(i0(Dl),Dl.getItem(e)),setItem:(e,t)=>{i0(Dl),Dl.setItem(e,t)}},c0={};function Q_({autoSaveId:e=null,children:t,className:n="",direction:r,forwardedRef:o,id:s=null,onLayout:i=null,keyboardResizeBy:l=null,storage:c=Dl,style:u,tagName:f="div",...p}){const d=iy(s),h=Fn(null),[m,g]=Kl(null),[w,x]=Kl([]),v=Fn({}),b=Fn(new Map),C=Fn(0),j=Fn({autoSaveId:e,direction:r,dragState:m,id:d,keyboardResizeBy:l,onLayout:i,storage:c}),S=Fn({layout:w,panelDataArray:[],panelDataArrayChanged:!1});Fn({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),M_(o,()=>({getId:()=>j.current.id,getLayout:()=>{const{layout:B}=S.current;return B},setLayout:B=>{const{onLayout:ne}=j.current,{layout:Q,panelDataArray:ie}=S.current,oe=l0({layout:B,panelConstraints:ie.map(W=>W.constraints)});a0(Q,oe)||(x(oe),S.current.layout=oe,ne&&ne(oe),La(ie,oe,v.current))}}),[]),la(()=>{j.current.autoSaveId=e,j.current.direction=r,j.current.dragState=m,j.current.id=d,j.current.onLayout=i,j.current.storage=c}),lF({committedValuesRef:j,eagerValuesRef:S,groupId:d,layout:w,panelDataArray:S.current.panelDataArray,setLayout:x,panelGroupElement:h.current}),ia(()=>{const{panelDataArray:B}=S.current;if(e){if(w.length===0||w.length!==B.length)return;let ne=c0[e];ne==null&&(ne=pF(gF,mF),c0[e]=ne);const Q=[...B],ie=new Map(b.current);ne(e,Q,ie,w,c)}},[e,w,c]),ia(()=>{});const N=Gn(B=>{const{onLayout:ne}=j.current,{layout:Q,panelDataArray:ie}=S.current;if(B.constraints.collapsible){const oe=ie.map(Fe=>Fe.constraints),{collapsedSize:W=0,panelSize:we,pivotIndices:Pe}=Hs(ie,B,Q);if(Ye(we!=null,`Panel size not found for panel "${B.id}"`),!wo(we,W)){b.current.set(B.id,we);const Ie=Ga(ie,B)===ie.length-1?we-W:W-we,he=Il({delta:Ie,initialLayout:Q,panelConstraints:oe,pivotIndices:Pe,prevLayout:Q,trigger:"imperative-api"});zu(Q,he)||(x(he),S.current.layout=he,ne&&ne(he),La(ie,he,v.current))}}},[]),E=Gn((B,ne)=>{const{onLayout:Q}=j.current,{layout:ie,panelDataArray:oe}=S.current;if(B.constraints.collapsible){const W=oe.map(Xe=>Xe.constraints),{collapsedSize:we=0,panelSize:Pe=0,minSize:Fe=0,pivotIndices:Ie}=Hs(oe,B,ie),he=ne??Fe;if(wo(Pe,we)){const Xe=b.current.get(B.id),Nt=Xe!=null&&Xe>=he?Xe:he,$t=Ga(oe,B)===oe.length-1?Pe-Nt:Nt-Pe,Wt=Il({delta:$t,initialLayout:ie,panelConstraints:W,pivotIndices:Ie,prevLayout:ie,trigger:"imperative-api"});zu(ie,Wt)||(x(Wt),S.current.layout=Wt,Q&&Q(Wt),La(oe,Wt,v.current))}}},[]),A=Gn(B=>{const{layout:ne,panelDataArray:Q}=S.current,{panelSize:ie}=Hs(Q,B,ne);return Ye(ie!=null,`Panel size not found for panel "${B.id}"`),ie},[]),F=Gn((B,ne)=>{const{panelDataArray:Q}=S.current,ie=Ga(Q,B);return fF({defaultSize:ne,dragState:m,layout:w,panelData:Q,panelIndex:ie})},[m,w]),Z=Gn(B=>{const{layout:ne,panelDataArray:Q}=S.current,{collapsedSize:ie=0,collapsible:oe,panelSize:W}=Hs(Q,B,ne);return Ye(W!=null,`Panel size not found for panel "${B.id}"`),oe===!0&&wo(W,ie)},[]),I=Gn(B=>{const{layout:ne,panelDataArray:Q}=S.current,{collapsedSize:ie=0,collapsible:oe,panelSize:W}=Hs(Q,B,ne);return Ye(W!=null,`Panel size not found for panel "${B.id}"`),!oe||ya(W,ie)>0},[]),q=Gn(B=>{const{panelDataArray:ne}=S.current;ne.push(B),ne.sort((Q,ie)=>{const oe=Q.order,W=ie.order;return oe==null&&W==null?0:oe==null?-1:W==null?1:oe-W}),S.current.panelDataArrayChanged=!0},[]);la(()=>{if(S.current.panelDataArrayChanged){S.current.panelDataArrayChanged=!1;const{autoSaveId:B,onLayout:ne,storage:Q}=j.current,{layout:ie,panelDataArray:oe}=S.current;let W=null;if(B){const Pe=hF(B,oe,Q);Pe&&(b.current=new Map(Object.entries(Pe.expandToSizes)),W=Pe.layout)}W==null&&(W=dF({panelDataArray:oe}));const we=l0({layout:W,panelConstraints:oe.map(Pe=>Pe.constraints)});a0(ie,we)||(x(we),S.current.layout=we,ne&&ne(we),La(oe,we,v.current))}}),la(()=>{const B=S.current;return()=>{B.layout=[]}},[]);const H=Gn(B=>function(Q){Q.preventDefault();const ie=h.current;if(!ie)return()=>null;const{direction:oe,dragState:W,id:we,keyboardResizeBy:Pe,onLayout:Fe}=j.current,{layout:Ie,panelDataArray:he}=S.current,{initialLayout:Xe}=W??{},Nt=K_(we,B,ie);let Ut=uF(Q,B,oe,W,Pe,ie);const $t=oe==="horizontal";document.dir==="rtl"&&$t&&(Ut=-Ut);const Wt=he.map(U=>U.constraints),_=Il({delta:Ut,initialLayout:Xe??Ie,panelConstraints:Wt,pivotIndices:Nt,prevLayout:Ie,trigger:L_(Q)?"keyboard":"mouse-or-touch"}),M=!zu(Ie,_);($_(Q)||z_(Q))&&C.current!=Ut&&(C.current=Ut,M?_h(B,0):$t?_h(B,Ut<0?U_:B_):_h(B,Ut<0?H_:G_)),M&&(x(_),S.current.layout=_,Fe&&Fe(_),La(he,_,v.current))},[]),J=Gn((B,ne)=>{const{onLayout:Q}=j.current,{layout:ie,panelDataArray:oe}=S.current,W=oe.map(Xe=>Xe.constraints),{panelSize:we,pivotIndices:Pe}=Hs(oe,B,ie);Ye(we!=null,`Panel size not found for panel "${B.id}"`);const Ie=Ga(oe,B)===oe.length-1?we-ne:ne-we,he=Il({delta:Ie,initialLayout:ie,panelConstraints:W,pivotIndices:Pe,prevLayout:ie,trigger:"imperative-api"});zu(ie,he)||(x(he),S.current.layout=he,Q&&Q(he),La(oe,he,v.current))},[]),re=Gn((B,ne)=>{const{layout:Q,panelDataArray:ie}=S.current,{collapsedSize:oe=0,collapsible:W}=ne,{collapsedSize:we=0,collapsible:Pe,maxSize:Fe=100,minSize:Ie=0}=B.constraints,{panelSize:he}=Hs(ie,B,Q);he!=null&&(W&&Pe&&wo(he,oe)?wo(oe,we)||J(B,we):heFe&&J(B,Fe))},[J]),K=Gn((B,ne)=>{const{direction:Q}=j.current,{layout:ie}=S.current;if(!h.current)return;const oe=sp(B,h.current);Ye(oe,`Drag handle element not found for id "${B}"`);const W=Z_(Q,ne);g({dragHandleId:B,dragHandleRect:oe.getBoundingClientRect(),initialCursorPosition:W,initialLayout:ie})},[]),z=Gn(()=>{g(null)},[]),L=Gn(B=>{const{panelDataArray:ne}=S.current,Q=Ga(ne,B);Q>=0&&(ne.splice(Q,1),delete v.current[B.id],S.current.panelDataArrayChanged=!0)},[]),te=GA(()=>({collapsePanel:N,direction:r,dragState:m,expandPanel:E,getPanelSize:A,getPanelStyle:F,groupId:d,isPanelCollapsed:Z,isPanelExpanded:I,reevaluatePanelConstraints:re,registerPanel:q,registerResizeHandle:H,resizePanel:J,startDragging:K,stopDragging:z,unregisterPanel:L,panelGroupElement:h.current}),[N,m,r,E,A,F,d,Z,I,re,q,H,J,K,z,L]),fe={display:"flex",flexDirection:r==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return Ri(np.Provider,{value:te},Ri(f,{...p,children:t,className:n,id:s,ref:h,style:{...fe,...u},"data-panel-group":"","data-panel-group-direction":r,"data-panel-group-id":d}))}const e1=D_((e,t)=>Ri(Q_,{...e,forwardedRef:t}));Q_.displayName="PanelGroup";e1.displayName="forwardRef(PanelGroup)";function Ga(e,t){return e.findIndex(n=>n===t||n.id===t.id)}function Hs(e,t,n){const r=Ga(e,t),s=r===e.length-1?[r-1,r]:[r,r+1],i=n[r];return{...t.constraints,panelSize:i,pivotIndices:s}}function vF({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:r}){ia(()=>{if(e||n==null||r==null)return;const o=sp(t,r);if(o==null)return;const s=i=>{if(!i.defaultPrevented)switch(i.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{i.preventDefault(),n(i);break}case"F6":{i.preventDefault();const l=o.getAttribute("data-panel-group-id");Ye(l,`No group element found for id "${l}"`);const c=_c(l,r),u=W_(l,t,r);Ye(u!==null,`No resize element found for id "${t}"`);const f=i.shiftKey?u>0?u-1:c.length-1:u+1{o.removeEventListener("keydown",s)}},[r,e,t,n])}function t1({children:e=null,className:t="",disabled:n=!1,hitAreaMargins:r,id:o,onBlur:s,onDragging:i,onFocus:l,style:c={},tabIndex:u=0,tagName:f="div",...p}){var d,h;const m=Fn(null),g=Fn({onDragging:i});ia(()=>{g.current.onDragging=i});const w=O_(np);if(w===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:x,groupId:v,registerResizeHandle:b,startDragging:C,stopDragging:j,panelGroupElement:S}=w,N=iy(o),[E,A]=Kl("inactive"),[F,Z]=Kl(!1),[I,q]=Kl(null),H=Fn({state:E});la(()=>{H.current.state=E}),ia(()=>{if(n)q(null);else{const z=b(N);q(()=>z)}},[n,N,b]);const J=(d=r==null?void 0:r.coarse)!==null&&d!==void 0?d:15,re=(h=r==null?void 0:r.fine)!==null&&h!==void 0?h:5;return ia(()=>{if(n||I==null)return;const z=m.current;return Ye(z,"Element ref not attached"),oF(N,z,x,{coarse:J,fine:re},(te,fe,B)=>{if(fe)switch(te){case"down":{A("drag"),C(N,B);const{onDragging:ne}=g.current;ne&&ne(!0);break}case"move":{const{state:ne}=H.current;ne!=="drag"&&A("hover"),I(B);break}case"up":{A("hover"),j();const{onDragging:ne}=g.current;ne&&ne(!1);break}}else A("inactive")})},[J,x,n,re,b,N,I,C,j]),vF({disabled:n,handleId:N,resizeHandler:I,panelGroupElement:S}),Ri(f,{...p,children:e,className:t,id:o,onBlur:()=>{Z(!1),s==null||s()},onFocus:()=>{Z(!0),l==null||l()},ref:m,role:"separator",style:{...{touchAction:"none",userSelect:"none"},...c},tabIndex:u,"data-panel-group-direction":x,"data-panel-group-id":v,"data-resize-handle":"","data-resize-handle-active":E==="drag"?"pointer":F?"keyboard":void 0,"data-resize-handle-state":E,"data-panel-resize-handle-enabled":!n,"data-panel-resize-handle-id":N})}t1.displayName="PanelResizeHandle";function n1(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;tl(s)))==null?void 0:i.classGroupId}const u0=/^\[(.+)\]$/;function xF(e){if(u0.test(e)){const t=u0.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function wF(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return SF(Object.entries(e.classGroups),n).forEach(([s,i])=>{dm(i,r,s,t)}),r}function dm(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const s=o===""?t:d0(t,o);s.classGroupId=n;return}if(typeof o=="function"){if(bF(o)){dm(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([s,i])=>{dm(i,d0(t,s),n,r)})})}function d0(e,t){let n=e;return t.split(dy).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function bF(e){return e.isThemeGetter}function SF(e,t){return t?e.map(([n,r])=>{const o=r.map(s=>typeof s=="string"?t+s:typeof s=="object"?Object.fromEntries(Object.entries(s).map(([i,l])=>[t+i,l])):s);return[n,o]}):e}function CF(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(s,i){n.set(s,i),t++,t>e&&(t=0,r=n,n=new Map)}return{get(s){let i=n.get(s);if(i!==void 0)return i;if((i=r.get(s))!==void 0)return o(s,i),i},set(s,i){n.has(s)?n.set(s,i):o(s,i)}}}const o1="!";function jF(e){const{separator:t,experimentalParseClassName:n}=e,r=t.length===1,o=t[0],s=t.length;function i(l){const c=[];let u=0,f=0,p;for(let w=0;wf?p-f:void 0;return{modifiers:c,hasImportantModifier:h,baseClassName:m,maybePostfixModifierPosition:g}}return n?function(c){return n({className:c,parseClassName:i})}:i}function _F(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function EF(e){return{cache:CF(e.cacheSize),parseClassName:jF(e),...yF(e)}}const TF=/\s+/;function NF(e,t){const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,s=new Set;return e.trim().split(TF).map(i=>{const{modifiers:l,hasImportantModifier:c,baseClassName:u,maybePostfixModifierPosition:f}=n(i);let p=!!f,d=r(p?u.substring(0,f):u);if(!d){if(!p)return{isTailwindClass:!1,originalClassName:i};if(d=r(u),!d)return{isTailwindClass:!1,originalClassName:i};p=!1}const h=_F(l).join(":");return{isTailwindClass:!0,modifierId:c?h+o1:h,classGroupId:d,originalClassName:i,hasPostfixModifier:p}}).reverse().filter(i=>{if(!i.isTailwindClass)return!0;const{modifierId:l,classGroupId:c,hasPostfixModifier:u}=i,f=l+c;return s.has(f)?!1:(s.add(f),o(c,u).forEach(p=>s.add(l+p)),!0)}).reverse().map(i=>i.originalClassName).join(" ")}function kF(){let e=0,t,n,r="";for(;ep(f),e());return n=EF(u),r=n.cache.get,o=n.cache.set,s=l,l(c)}function l(c){const u=r(c);if(u)return u;const f=NF(c,n);return o(c,f),f}return function(){return s(kF.apply(null,arguments))}}function xt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const a1=/^\[(?:([a-z-]+):)?(.+)\]$/i,PF=/^\d+\/\d+$/,IF=new Set(["px","full","screen"]),DF=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,OF=/\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$/,MF=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,AF=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,FF=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function po(e){return na(e)||IF.has(e)||PF.test(e)}function es(e){return Hi(e,"length",GF)}function na(e){return!!e&&!Number.isNaN(Number(e))}function Vu(e){return Hi(e,"number",na)}function xl(e){return!!e&&Number.isInteger(Number(e))}function LF(e){return e.endsWith("%")&&na(e.slice(0,-1))}function We(e){return a1.test(e)}function ts(e){return DF.test(e)}const $F=new Set(["length","size","percentage"]);function zF(e){return Hi(e,$F,i1)}function VF(e){return Hi(e,"position",i1)}const UF=new Set(["image","url"]);function BF(e){return Hi(e,UF,KF)}function HF(e){return Hi(e,"",WF)}function wl(){return!0}function Hi(e,t,n){const r=a1.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function GF(e){return OF.test(e)&&!MF.test(e)}function i1(){return!1}function WF(e){return AF.test(e)}function KF(e){return FF.test(e)}function qF(){const e=xt("colors"),t=xt("spacing"),n=xt("blur"),r=xt("brightness"),o=xt("borderColor"),s=xt("borderRadius"),i=xt("borderSpacing"),l=xt("borderWidth"),c=xt("contrast"),u=xt("grayscale"),f=xt("hueRotate"),p=xt("invert"),d=xt("gap"),h=xt("gradientColorStops"),m=xt("gradientColorStopPositions"),g=xt("inset"),w=xt("margin"),x=xt("opacity"),v=xt("padding"),b=xt("saturate"),C=xt("scale"),j=xt("sepia"),S=xt("skew"),N=xt("space"),E=xt("translate"),A=()=>["auto","contain","none"],F=()=>["auto","hidden","clip","visible","scroll"],Z=()=>["auto",We,t],I=()=>[We,t],q=()=>["",po,es],H=()=>["auto",na,We],J=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],re=()=>["solid","dashed","dotted","double","none"],K=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],z=()=>["start","end","center","between","around","evenly","stretch"],L=()=>["","0",We],te=()=>["auto","avoid","all","avoid-page","page","left","right","column"],fe=()=>[na,Vu],B=()=>[na,We];return{cacheSize:500,separator:":",theme:{colors:[wl],spacing:[po,es],blur:["none","",ts,We],brightness:fe(),borderColor:[e],borderRadius:["none","","full",ts,We],borderSpacing:I(),borderWidth:q(),contrast:fe(),grayscale:L(),hueRotate:B(),invert:L(),gap:I(),gradientColorStops:[e],gradientColorStopPositions:[LF,es],inset:Z(),margin:Z(),opacity:fe(),padding:I(),saturate:fe(),scale:fe(),sepia:L(),skew:B(),space:I(),translate:I()},classGroups:{aspect:[{aspect:["auto","square","video",We]}],container:["container"],columns:[{columns:[ts]}],"break-after":[{"break-after":te()}],"break-before":[{"break-before":te()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...J(),We]}],overflow:[{overflow:F()}],"overflow-x":[{"overflow-x":F()}],"overflow-y":[{"overflow-y":F()}],overscroll:[{overscroll:A()}],"overscroll-x":[{"overscroll-x":A()}],"overscroll-y":[{"overscroll-y":A()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[g]}],"inset-x":[{"inset-x":[g]}],"inset-y":[{"inset-y":[g]}],start:[{start:[g]}],end:[{end:[g]}],top:[{top:[g]}],right:[{right:[g]}],bottom:[{bottom:[g]}],left:[{left:[g]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",xl,We]}],basis:[{basis:Z()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",We]}],grow:[{grow:L()}],shrink:[{shrink:L()}],order:[{order:["first","last","none",xl,We]}],"grid-cols":[{"grid-cols":[wl]}],"col-start-end":[{col:["auto",{span:["full",xl,We]},We]}],"col-start":[{"col-start":H()}],"col-end":[{"col-end":H()}],"grid-rows":[{"grid-rows":[wl]}],"row-start-end":[{row:["auto",{span:[xl,We]},We]}],"row-start":[{"row-start":H()}],"row-end":[{"row-end":H()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",We]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",We]}],gap:[{gap:[d]}],"gap-x":[{"gap-x":[d]}],"gap-y":[{"gap-y":[d]}],"justify-content":[{justify:["normal",...z()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...z(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...z(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[v]}],px:[{px:[v]}],py:[{py:[v]}],ps:[{ps:[v]}],pe:[{pe:[v]}],pt:[{pt:[v]}],pr:[{pr:[v]}],pb:[{pb:[v]}],pl:[{pl:[v]}],m:[{m:[w]}],mx:[{mx:[w]}],my:[{my:[w]}],ms:[{ms:[w]}],me:[{me:[w]}],mt:[{mt:[w]}],mr:[{mr:[w]}],mb:[{mb:[w]}],ml:[{ml:[w]}],"space-x":[{"space-x":[N]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[N]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",We,t]}],"min-w":[{"min-w":[We,t,"min","max","fit"]}],"max-w":[{"max-w":[We,t,"none","full","min","max","fit","prose",{screen:[ts]},ts]}],h:[{h:[We,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[We,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[We,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[We,t,"auto","min","max","fit"]}],"font-size":[{text:["base",ts,es]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Vu]}],"font-family":[{font:[wl]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",We]}],"line-clamp":[{"line-clamp":["none",na,Vu]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",po,We]}],"list-image":[{"list-image":["none",We]}],"list-style-type":[{list:["none","disc","decimal",We]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[x]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[x]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...re(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",po,es]}],"underline-offset":[{"underline-offset":["auto",po,We]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:I()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",We]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",We]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[x]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...J(),VF]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",zF]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},BF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[m]}],"gradient-via-pos":[{via:[m]}],"gradient-to-pos":[{to:[m]}],"gradient-from":[{from:[h]}],"gradient-via":[{via:[h]}],"gradient-to":[{to:[h]}],rounded:[{rounded:[s]}],"rounded-s":[{"rounded-s":[s]}],"rounded-e":[{"rounded-e":[s]}],"rounded-t":[{"rounded-t":[s]}],"rounded-r":[{"rounded-r":[s]}],"rounded-b":[{"rounded-b":[s]}],"rounded-l":[{"rounded-l":[s]}],"rounded-ss":[{"rounded-ss":[s]}],"rounded-se":[{"rounded-se":[s]}],"rounded-ee":[{"rounded-ee":[s]}],"rounded-es":[{"rounded-es":[s]}],"rounded-tl":[{"rounded-tl":[s]}],"rounded-tr":[{"rounded-tr":[s]}],"rounded-br":[{"rounded-br":[s]}],"rounded-bl":[{"rounded-bl":[s]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[x]}],"border-style":[{border:[...re(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[x]}],"divide-style":[{divide:re()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[o]}],"border-color-t":[{"border-t":[o]}],"border-color-r":[{"border-r":[o]}],"border-color-b":[{"border-b":[o]}],"border-color-l":[{"border-l":[o]}],"divide-color":[{divide:[o]}],"outline-style":[{outline:["",...re()]}],"outline-offset":[{"outline-offset":[po,We]}],"outline-w":[{outline:[po,es]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:q()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[x]}],"ring-offset-w":[{"ring-offset":[po,es]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",ts,HF]}],"shadow-color":[{shadow:[wl]}],opacity:[{opacity:[x]}],"mix-blend":[{"mix-blend":[...K(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":K()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",ts,We]}],grayscale:[{grayscale:[u]}],"hue-rotate":[{"hue-rotate":[f]}],invert:[{invert:[p]}],saturate:[{saturate:[b]}],sepia:[{sepia:[j]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[u]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[f]}],"backdrop-invert":[{"backdrop-invert":[p]}],"backdrop-opacity":[{"backdrop-opacity":[x]}],"backdrop-saturate":[{"backdrop-saturate":[b]}],"backdrop-sepia":[{"backdrop-sepia":[j]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[i]}],"border-spacing-x":[{"border-spacing-x":[i]}],"border-spacing-y":[{"border-spacing-y":[i]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",We]}],duration:[{duration:B()}],ease:[{ease:["linear","in","out","in-out",We]}],delay:[{delay:B()}],animate:[{animate:["none","spin","ping","pulse","bounce",We]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[C]}],"scale-x":[{"scale-x":[C]}],"scale-y":[{"scale-y":[C]}],rotate:[{rotate:[xl,We]}],"translate-x":[{"translate-x":[E]}],"translate-y":[{"translate-y":[E]}],"skew-x":[{"skew-x":[S]}],"skew-y":[{"skew-y":[S]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",We]}],accent:[{accent:["auto",e]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",We]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":I()}],"scroll-mx":[{"scroll-mx":I()}],"scroll-my":[{"scroll-my":I()}],"scroll-ms":[{"scroll-ms":I()}],"scroll-me":[{"scroll-me":I()}],"scroll-mt":[{"scroll-mt":I()}],"scroll-mr":[{"scroll-mr":I()}],"scroll-mb":[{"scroll-mb":I()}],"scroll-ml":[{"scroll-ml":I()}],"scroll-p":[{"scroll-p":I()}],"scroll-px":[{"scroll-px":I()}],"scroll-py":[{"scroll-py":I()}],"scroll-ps":[{"scroll-ps":I()}],"scroll-pe":[{"scroll-pe":I()}],"scroll-pt":[{"scroll-pt":I()}],"scroll-pr":[{"scroll-pr":I()}],"scroll-pb":[{"scroll-pb":I()}],"scroll-pl":[{"scroll-pl":I()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",We]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[po,es,Vu]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}}const ZF=RF(qF);function Re(...e){return ZF(jo(e))}const su=({className:e,...t})=>a.jsx(e1,{className:Re("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t}),ro=F_,au=({withHandle:e,className:t,...n})=>a.jsx(t1,{className:Re("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...n,children:e&&a.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:a.jsx(dA,{className:"h-2.5 w-2.5"})})});function gn({children:e}){const{instanceId:t}=Ta();return a.jsxs(wA,{children:[a.jsx(E_,{instanceId:t}),a.jsx("div",{className:"layout-general",children:a.jsx("div",{className:"instance-layout",children:a.jsxs(su,{direction:"horizontal",children:[a.jsx(ro,{defaultSize:15,children:a.jsx(UA,{})}),a.jsx(au,{withHandle:!0,className:"border border-black"}),a.jsx(ro,{children:e})]})})})]})}function l1(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;ttypeof e=="boolean"?"".concat(e):e===0?"0":e,p0=JF,c1=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return p0(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:s}=t,i=Object.keys(o).map(u=>{const f=n==null?void 0:n[u],p=s==null?void 0:s[u];if(f===null)return null;const d=f0(f)||f0(p);return o[u][d]}),l=n&&Object.entries(n).reduce((u,f)=>{let[p,d]=f;return d===void 0||(u[p]=d),u},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((u,f)=>{let{class:p,className:d,...h}=f;return Object.entries(h).every(m=>{let[g,w]=m;return Array.isArray(w)?w.includes({...s,...l}[g]):{...s,...l}[g]===w})?[...u,p,d]:u},[]);return p0(e,i,c,n==null?void 0:n.class,n==null?void 0:n.className)},YF=c1("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),Te=y.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?Oo:"button";return a.jsx(i,{className:Re(YF({variant:t,size:n,className:e})),ref:s,...o})});Te.displayName="Button";function u1(){return a.jsxs("footer",{className:"footer",children:[a.jsxs("div",{className:"footer-info",children:["Client Name: ",a.jsx("strong",{children:localStorage.getItem("clientName")})," Version:"," ",a.jsx("strong",{children:localStorage.getItem("version")})]}),a.jsxs("div",{className:"footer-buttons",children:[a.jsx(Te,{variant:"link",children:a.jsx("a",{href:"https://evolution-api.com/discord",target:"_blank",rel:"noopener noreferrer",children:"Discord"})}),a.jsx(Te,{variant:"link",children:a.jsx("a",{href:"https://evolution-api.com/postman",target:"_blank",rel:"noopener noreferrer",children:"Postman"})}),a.jsx(Te,{variant:"link",children:a.jsx("a",{href:"https://github.com/EvolutionAPI/evolution-api",target:"_blank",rel:"noopener noreferrer",children:"GitHub"})}),a.jsx(Te,{variant:"link",children:a.jsx("a",{href:"https://doc.evolution-api.com",target:"_blank",rel:"noopener noreferrer",children:"Docs"})})]})]})}function XF({children:e}){return a.jsxs("div",{className:"layout",children:[a.jsx(E_,{}),a.jsxs("div",{className:"layout-general",children:[a.jsx("main",{className:"content",children:e}),a.jsx(u1,{})]})]})}const mi=y.forwardRef(({className:e,...t},n)=>a.jsx("div",{ref:n,className:Re("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));mi.displayName="Card";const ql=y.forwardRef(({className:e,...t},n)=>a.jsx("div",{ref:n,className:Re("flex flex-col space-y-1.5 p-6",e),...t}));ql.displayName="CardHeader";const Zl=y.forwardRef(({className:e,...t},n)=>a.jsx("h3",{ref:n,className:Re("text-2xl font-semibold leading-none tracking-tight",e),...t}));Zl.displayName="CardTitle";const d1=y.forwardRef(({className:e,...t},n)=>a.jsx("p",{ref:n,className:Re("text-sm text-muted-foreground",e),...t}));d1.displayName="CardDescription";const Jl=y.forwardRef(({className:e,...t},n)=>a.jsx("div",{ref:n,className:Re("p-6 pt-0",e),...t}));Jl.displayName="CardContent";const f1=y.forwardRef(({className:e,...t},n)=>a.jsx("div",{ref:n,className:Re("flex items-center p-6 pt-0",e),...t}));f1.displayName="CardFooter";function QF(e,t=globalThis==null?void 0:globalThis.document){const n=wr(e);y.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var e2="DismissableLayer",fm="dismissableLayer.update",t2="dismissableLayer.pointerDownOutside",n2="dismissableLayer.focusOutside",h0,p1=y.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),ap=y.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:l,...c}=e,u=y.useContext(p1),[f,p]=y.useState(null),d=(f==null?void 0:f.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,h]=y.useState({}),m=ut(t,N=>p(N)),g=Array.from(u.layers),[w]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),x=g.indexOf(w),v=f?g.indexOf(f):-1,b=u.layersWithOutsidePointerEventsDisabled.size>0,C=v>=x,j=s2(N=>{const E=N.target,A=[...u.branches].some(F=>F.contains(E));!C||A||(o==null||o(N),i==null||i(N),N.defaultPrevented||l==null||l())},d),S=a2(N=>{const E=N.target;[...u.branches].some(F=>F.contains(E))||(s==null||s(N),i==null||i(N),N.defaultPrevented||l==null||l())},d);return QF(N=>{v===u.layers.size-1&&(r==null||r(N),!N.defaultPrevented&&l&&(N.preventDefault(),l()))},d),y.useEffect(()=>{if(f)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(h0=d.body.style.pointerEvents,d.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(f)),u.layers.add(f),g0(),()=>{n&&u.layersWithOutsidePointerEventsDisabled.size===1&&(d.body.style.pointerEvents=h0)}},[f,d,n,u]),y.useEffect(()=>()=>{f&&(u.layers.delete(f),u.layersWithOutsidePointerEventsDisabled.delete(f),g0())},[f,u]),y.useEffect(()=>{const N=()=>h({});return document.addEventListener(fm,N),()=>document.removeEventListener(fm,N)},[]),a.jsx(Ve.div,{...c,ref:m,style:{pointerEvents:b?C?"auto":"none":void 0,...e.style},onFocusCapture:je(e.onFocusCapture,S.onFocusCapture),onBlurCapture:je(e.onBlurCapture,S.onBlurCapture),onPointerDownCapture:je(e.onPointerDownCapture,j.onPointerDownCapture)})});ap.displayName=e2;var r2="DismissableLayerBranch",o2=y.forwardRef((e,t)=>{const n=y.useContext(p1),r=y.useRef(null),o=ut(t,r);return y.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),a.jsx(Ve.div,{...e,ref:o})});o2.displayName=r2;function s2(e,t=globalThis==null?void 0:globalThis.document){const n=wr(e),r=y.useRef(!1),o=y.useRef(()=>{});return y.useEffect(()=>{const s=l=>{if(l.target&&!r.current){let c=function(){h1(t2,n,u,{discrete:!0})};const u={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=c,t.addEventListener("click",o.current,{once:!0})):c()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function a2(e,t=globalThis==null?void 0:globalThis.document){const n=wr(e),r=y.useRef(!1);return y.useEffect(()=>{const o=s=>{s.target&&!r.current&&h1(n2,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function g0(){const e=new CustomEvent(fm);document.dispatchEvent(e)}function h1(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?N_(o,s):o.dispatchEvent(s)}var Eh="focusScope.autoFocusOnMount",Th="focusScope.autoFocusOnUnmount",m0={bubbles:!1,cancelable:!0},i2="FocusScope",ip=y.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[l,c]=y.useState(null),u=wr(o),f=wr(s),p=y.useRef(null),d=ut(t,g=>c(g)),h=y.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;y.useEffect(()=>{if(r){let g=function(b){if(h.paused||!l)return;const C=b.target;l.contains(C)?p.current=C:rs(p.current,{select:!0})},w=function(b){if(h.paused||!l)return;const C=b.relatedTarget;C!==null&&(l.contains(C)||rs(p.current,{select:!0}))},x=function(b){if(document.activeElement===document.body)for(const j of b)j.removedNodes.length>0&&rs(l)};document.addEventListener("focusin",g),document.addEventListener("focusout",w);const v=new MutationObserver(x);return l&&v.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",w),v.disconnect()}}},[r,l,h.paused]),y.useEffect(()=>{if(l){y0.add(h);const g=document.activeElement;if(!l.contains(g)){const x=new CustomEvent(Eh,m0);l.addEventListener(Eh,u),l.dispatchEvent(x),x.defaultPrevented||(l2(p2(g1(l)),{select:!0}),document.activeElement===g&&rs(l))}return()=>{l.removeEventListener(Eh,u),setTimeout(()=>{const x=new CustomEvent(Th,m0);l.addEventListener(Th,f),l.dispatchEvent(x),x.defaultPrevented||rs(g??document.body,{select:!0}),l.removeEventListener(Th,f),y0.remove(h)},0)}}},[l,u,f,h]);const m=y.useCallback(g=>{if(!n&&!r||h.paused)return;const w=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,x=document.activeElement;if(w&&x){const v=g.currentTarget,[b,C]=c2(v);b&&C?!g.shiftKey&&x===C?(g.preventDefault(),n&&rs(b,{select:!0})):g.shiftKey&&x===b&&(g.preventDefault(),n&&rs(C,{select:!0})):x===v&&g.preventDefault()}},[n,r,h.paused]);return a.jsx(Ve.div,{tabIndex:-1,...i,ref:d,onKeyDown:m})});ip.displayName=i2;function l2(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(rs(r,{select:t}),document.activeElement!==n)return}function c2(e){const t=g1(e),n=v0(t,e),r=v0(t.reverse(),e);return[n,r]}function g1(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function v0(e,t){for(const n of e)if(!u2(n,{upTo:t}))return n}function u2(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function d2(e){return e instanceof HTMLInputElement&&"select"in e}function rs(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&d2(e)&&t&&e.select()}}var y0=f2();function f2(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=x0(e,t),e.unshift(t)},remove(t){var n;e=x0(e,t),(n=e[0])==null||n.resume()}}}function x0(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function p2(e){return e.filter(t=>t.tagName!=="A")}var h2="Portal",lp=y.forwardRef((e,t)=>{var l;const{container:n,...r}=e,[o,s]=y.useState(!1);bn(()=>s(!0),[]);const i=n||o&&((l=globalThis==null?void 0:globalThis.document)==null?void 0:l.body);return i?Pj.createPortal(a.jsx(Ve.div,{...r,ref:t}),i):null});lp.displayName=h2;var Nh=0;function fy(){y.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??w0()),document.body.insertAdjacentElement("beforeend",e[1]??w0()),Nh++,()=>{Nh===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Nh--}},[])}function w0(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Jr=function(){return Jr=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return P2;var t=I2(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},O2=x1(),vi="data-scroll-locked",M2=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,l=e.gap;return n===void 0&&(n="margin"),` - .`.concat(m2,` { - overflow: hidden `).concat(r,`; - padding-right: `).concat(l,"px ").concat(r,`; - } - body[`).concat(vi,`] { - overflow: hidden `).concat(r,`; - overscroll-behavior: contain; - `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&` - padding-left: `.concat(o,`px; - padding-top: `).concat(s,`px; - padding-right: `).concat(i,`px; - margin-left:0; - margin-top:0; - margin-right: `).concat(l,"px ").concat(r,`; - `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` - } - - .`).concat(vd,` { - right: `).concat(l,"px ").concat(r,`; - } - - .`).concat(yd,` { - margin-right: `).concat(l,"px ").concat(r,`; - } - - .`).concat(vd," .").concat(vd,` { - right: 0 `).concat(r,`; - } - - .`).concat(yd," .").concat(yd,` { - margin-right: 0 `).concat(r,`; - } - - body[`).concat(vi,`] { - `).concat(v2,": ").concat(l,`px; - } -`)},S0=function(){var e=parseInt(document.body.getAttribute(vi)||"0",10);return isFinite(e)?e:0},A2=function(){y.useEffect(function(){return document.body.setAttribute(vi,(S0()+1).toString()),function(){var e=S0()-1;e<=0?document.body.removeAttribute(vi):document.body.setAttribute(vi,e.toString())}},[])},F2=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r;A2();var s=y.useMemo(function(){return D2(o)},[o]);return y.createElement(O2,{styles:M2(s,!t,o,n?"":"!important")})},pm=!1;if(typeof window<"u")try{var Uu=Object.defineProperty({},"passive",{get:function(){return pm=!0,!0}});window.addEventListener("test",Uu,Uu),window.removeEventListener("test",Uu,Uu)}catch{pm=!1}var $a=pm?{passive:!1}:!1,L2=function(e){return e.tagName==="TEXTAREA"},w1=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!L2(e)&&n[t]==="visible")},$2=function(e){return w1(e,"overflowY")},z2=function(e){return w1(e,"overflowX")},C0=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=b1(e,r);if(o){var s=S1(e,r),i=s[1],l=s[2];if(i>l)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},V2=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},U2=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},b1=function(e,t){return e==="v"?$2(t):z2(t)},S1=function(e,t){return e==="v"?V2(t):U2(t)},B2=function(e,t){return e==="h"&&t==="rtl"?-1:1},H2=function(e,t,n,r,o){var s=B2(e,window.getComputedStyle(t).direction),i=s*r,l=n.target,c=t.contains(l),u=!1,f=i>0,p=0,d=0;do{var h=S1(e,l),m=h[0],g=h[1],w=h[2],x=g-w-s*m;(m||x)&&b1(e,l)&&(p+=x,d+=m),l instanceof ShadowRoot?l=l.host:l=l.parentNode}while(!c&&l!==document.body||c&&(t.contains(l)||t===l));return(f&&(Math.abs(p)<1||!o)||!f&&(Math.abs(d)<1||!o))&&(u=!0),u},Bu=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},j0=function(e){return[e.deltaX,e.deltaY]},_0=function(e){return e&&"current"in e?e.current:e},G2=function(e,t){return e[0]===t[0]&&e[1]===t[1]},W2=function(e){return` - .block-interactivity-`.concat(e,` {pointer-events: none;} - .allow-interactivity-`).concat(e,` {pointer-events: all;} -`)},K2=0,za=[];function q2(e){var t=y.useRef([]),n=y.useRef([0,0]),r=y.useRef(),o=y.useState(K2++)[0],s=y.useState(x1)[0],i=y.useRef(e);y.useEffect(function(){i.current=e},[e]),y.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var g=g2([e.lockRef.current],(e.shards||[]).map(_0),!0).filter(Boolean);return g.forEach(function(w){return w.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),g.forEach(function(w){return w.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=y.useCallback(function(g,w){if("touches"in g&&g.touches.length===2)return!i.current.allowPinchZoom;var x=Bu(g),v=n.current,b="deltaX"in g?g.deltaX:v[0]-x[0],C="deltaY"in g?g.deltaY:v[1]-x[1],j,S=g.target,N=Math.abs(b)>Math.abs(C)?"h":"v";if("touches"in g&&N==="h"&&S.type==="range")return!1;var E=C0(N,S);if(!E)return!0;if(E?j=N:(j=N==="v"?"h":"v",E=C0(N,S)),!E)return!1;if(!r.current&&"changedTouches"in g&&(b||C)&&(r.current=j),!j)return!0;var A=r.current||j;return H2(A,w,g,A==="h"?b:C,!0)},[]),c=y.useCallback(function(g){var w=g;if(!(!za.length||za[za.length-1]!==s)){var x="deltaY"in w?j0(w):Bu(w),v=t.current.filter(function(j){return j.name===w.type&&(j.target===w.target||w.target===j.shadowParent)&&G2(j.delta,x)})[0];if(v&&v.should){w.cancelable&&w.preventDefault();return}if(!v){var b=(i.current.shards||[]).map(_0).filter(Boolean).filter(function(j){return j.contains(w.target)}),C=b.length>0?l(w,b[0]):!i.current.noIsolation;C&&w.cancelable&&w.preventDefault()}}},[]),u=y.useCallback(function(g,w,x,v){var b={name:g,delta:w,target:x,should:v,shadowParent:Z2(x)};t.current.push(b),setTimeout(function(){t.current=t.current.filter(function(C){return C!==b})},1)},[]),f=y.useCallback(function(g){n.current=Bu(g),r.current=void 0},[]),p=y.useCallback(function(g){u(g.type,j0(g),g.target,l(g,e.lockRef.current))},[]),d=y.useCallback(function(g){u(g.type,Bu(g),g.target,l(g,e.lockRef.current))},[]);y.useEffect(function(){return za.push(s),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:d}),document.addEventListener("wheel",c,$a),document.addEventListener("touchmove",c,$a),document.addEventListener("touchstart",f,$a),function(){za=za.filter(function(g){return g!==s}),document.removeEventListener("wheel",c,$a),document.removeEventListener("touchmove",c,$a),document.removeEventListener("touchstart",f,$a)}},[]);var h=e.removeScrollBar,m=e.inert;return y.createElement(y.Fragment,null,m?y.createElement(s,{styles:W2(o)}):null,h?y.createElement(F2,{gapMode:e.gapMode}):null)}function Z2(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const J2=j2(y1,q2);var up=y.forwardRef(function(e,t){return y.createElement(cp,Jr({},e,{ref:t,sideCar:J2}))});up.classNames=cp.classNames;var Y2=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Va=new WeakMap,Hu=new WeakMap,Gu={},Ih=0,C1=function(e){return e&&(e.host||C1(e.parentNode))},X2=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=C1(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},Q2=function(e,t,n,r){var o=X2(t,Array.isArray(e)?e:[e]);Gu[n]||(Gu[n]=new WeakMap);var s=Gu[n],i=[],l=new Set,c=new Set(o),u=function(p){!p||l.has(p)||(l.add(p),u(p.parentNode))};o.forEach(u);var f=function(p){!p||c.has(p)||Array.prototype.forEach.call(p.children,function(d){if(l.has(d))f(d);else try{var h=d.getAttribute(r),m=h!==null&&h!=="false",g=(Va.get(d)||0)+1,w=(s.get(d)||0)+1;Va.set(d,g),s.set(d,w),i.push(d),g===1&&m&&Hu.set(d,!0),w===1&&d.setAttribute(n,"true"),m||d.setAttribute(r,"true")}catch(x){console.error("aria-hidden: cannot operate on ",d,x)}})};return f(t),l.clear(),Ih++,function(){i.forEach(function(p){var d=Va.get(p)-1,h=s.get(p)-1;Va.set(p,d),s.set(p,h),d||(Hu.has(p)||p.removeAttribute(r),Hu.delete(p)),h||p.removeAttribute(n)}),Ih--,Ih||(Va=new WeakMap,Va=new WeakMap,Hu=new WeakMap,Gu={})}},py=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=Y2(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),Q2(r,o,n,"aria-hidden")):function(){return null}},hy="Dialog",[j1,GK]=lo(hy),[eL,Vr]=j1(hy),_1=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:s,modal:i=!0}=e,l=y.useRef(null),c=y.useRef(null),[u=!1,f]=js({prop:r,defaultProp:o,onChange:s});return a.jsx(eL,{scope:t,triggerRef:l,contentRef:c,contentId:Ir(),titleId:Ir(),descriptionId:Ir(),open:u,onOpenChange:f,onOpenToggle:y.useCallback(()=>f(p=>!p),[f]),modal:i,children:n})};_1.displayName=hy;var E1="DialogTrigger",T1=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Vr(E1,n),s=ut(t,o.triggerRef);return a.jsx(Ve.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":vy(o.open),...r,ref:s,onClick:je(e.onClick,o.onOpenToggle)})});T1.displayName=E1;var gy="DialogPortal",[tL,N1]=j1(gy,{forceMount:void 0}),k1=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,s=Vr(gy,t);return a.jsx(tL,{scope:t,forceMount:n,children:y.Children.map(r,i=>a.jsx(co,{present:n||s.open,children:a.jsx(lp,{asChild:!0,container:o,children:i})}))})};k1.displayName=gy;var rf="DialogOverlay",R1=y.forwardRef((e,t)=>{const n=N1(rf,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=Vr(rf,e.__scopeDialog);return s.modal?a.jsx(co,{present:r||s.open,children:a.jsx(nL,{...o,ref:t})}):null});R1.displayName=rf;var nL=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Vr(rf,n);return a.jsx(up,{as:Oo,allowPinchZoom:!0,shards:[o.contentRef],children:a.jsx(Ve.div,{"data-state":vy(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),xa="DialogContent",P1=y.forwardRef((e,t)=>{const n=N1(xa,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=Vr(xa,e.__scopeDialog);return a.jsx(co,{present:r||s.open,children:s.modal?a.jsx(rL,{...o,ref:t}):a.jsx(oL,{...o,ref:t})})});P1.displayName=xa;var rL=y.forwardRef((e,t)=>{const n=Vr(xa,e.__scopeDialog),r=y.useRef(null),o=ut(t,n.contentRef,r);return y.useEffect(()=>{const s=r.current;if(s)return py(s)},[]),a.jsx(I1,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:je(e.onCloseAutoFocus,s=>{var i;s.preventDefault(),(i=n.triggerRef.current)==null||i.focus()}),onPointerDownOutside:je(e.onPointerDownOutside,s=>{const i=s.detail.originalEvent,l=i.button===0&&i.ctrlKey===!0;(i.button===2||l)&&s.preventDefault()}),onFocusOutside:je(e.onFocusOutside,s=>s.preventDefault())})}),oL=y.forwardRef((e,t)=>{const n=Vr(xa,e.__scopeDialog),r=y.useRef(!1),o=y.useRef(!1);return a.jsx(I1,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var i,l;(i=e.onCloseAutoFocus)==null||i.call(e,s),s.defaultPrevented||(r.current||(l=n.triggerRef.current)==null||l.focus(),s.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:s=>{var c,u;(c=e.onInteractOutside)==null||c.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const i=s.target;((u=n.triggerRef.current)==null?void 0:u.contains(i))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})}),I1=y.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:s,...i}=e,l=Vr(xa,n),c=y.useRef(null),u=ut(t,c);return fy(),a.jsxs(a.Fragment,{children:[a.jsx(ip,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:s,children:a.jsx(ap,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":vy(l.open),...i,ref:u,onDismiss:()=>l.onOpenChange(!1)})}),a.jsxs(a.Fragment,{children:[a.jsx(sL,{titleId:l.titleId}),a.jsx(iL,{contentRef:c,descriptionId:l.descriptionId})]})]})}),my="DialogTitle",D1=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Vr(my,n);return a.jsx(Ve.h2,{id:o.titleId,...r,ref:t})});D1.displayName=my;var O1="DialogDescription",M1=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Vr(O1,n);return a.jsx(Ve.p,{id:o.descriptionId,...r,ref:t})});M1.displayName=O1;var A1="DialogClose",F1=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Vr(A1,n);return a.jsx(Ve.button,{type:"button",...r,ref:t,onClick:je(e.onClick,()=>o.onOpenChange(!1))})});F1.displayName=A1;function vy(e){return e?"open":"closed"}var L1="DialogTitleWarning",[WK,$1]=bA(L1,{contentName:xa,titleName:my,docsSlug:"dialog"}),sL=({titleId:e})=>{const t=$1(L1),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users. - -If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component. - -For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return y.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},aL="DialogDescriptionWarning",iL=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${$1(aL).contentName}}.`;return y.useEffect(()=>{var s;const o=(s=e.current)==null?void 0:s.getAttribute("aria-describedby");t&&o&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},lL=_1,cL=T1,uL=k1,z1=R1,V1=P1,U1=D1,B1=M1,dL=F1;const Sn=lL,Cn=cL,fL=uL,H1=y.forwardRef(({className:e,...t},n)=>a.jsx(z1,{ref:n,className:Re("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));H1.displayName=z1.displayName;const un=y.forwardRef(({className:e,children:t,...n},r)=>a.jsxs(fL,{children:[a.jsx(H1,{}),a.jsxs(V1,{ref:r,className:Re("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...n,children:[t,a.jsxs(dL,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[a.jsx(vA,{className:"h-4 w-4"}),a.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));un.displayName=V1.displayName;const dn=({className:e,...t})=>a.jsx("div",{className:Re("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});dn.displayName="DialogHeader";const br=({className:e,...t})=>a.jsx("div",{className:Re("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});br.displayName="DialogFooter";const On=y.forwardRef(({className:e,...t},n)=>a.jsx(U1,{ref:n,className:Re("text-lg font-semibold leading-none tracking-tight",e),...t}));On.displayName=U1.displayName;const Pi=y.forwardRef(({className:e,...t},n)=>a.jsx(B1,{ref:n,className:Re("text-sm text-muted-foreground",e),...t}));Pi.displayName=B1.displayName;var iu=e=>e.type==="checkbox",li=e=>e instanceof Date,Nn=e=>e==null;const G1=e=>typeof e=="object";var Jt=e=>!Nn(e)&&!Array.isArray(e)&&G1(e)&&!li(e),W1=e=>Jt(e)&&e.target?iu(e.target)?e.target.checked:e.target.value:e,pL=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,K1=(e,t)=>e.has(pL(t)),hL=e=>{const t=e.constructor&&e.constructor.prototype;return Jt(t)&&t.hasOwnProperty("isPrototypeOf")},yy=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function An(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(yy&&(e instanceof Blob||e instanceof FileList))&&(n||Jt(e)))if(t=n?[]:{},!n&&!hL(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=An(e[r]));else return e;return t}var dp=e=>Array.isArray(e)?e.filter(Boolean):[],Ft=e=>e===void 0,ue=(e,t,n)=>{if(!t||!Jt(e))return n;const r=dp(t.split(/[,[\].]+?/)).reduce((o,s)=>Nn(o)?o:o[s],e);return Ft(r)||r===e?Ft(e[t])?n:e[t]:r},Yr=e=>typeof e=="boolean",xy=e=>/^\w*$/.test(e),q1=e=>dp(e.replace(/["|']|\]/g,"").split(/\.|\[/)),at=(e,t,n)=>{let r=-1;const o=xy(t)?[t]:q1(t),s=o.length,i=s-1;for(;++rSe.useContext(Z1),Bo=e=>{const{children:t,...n}=e;return Se.createElement(Z1.Provider,{value:n},t)};var J1=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const s in e)Object.defineProperty(o,s,{get:()=>{const i=s;return t._proxyFormState[i]!==Tr.all&&(t._proxyFormState[i]=!r||Tr.all),n&&(n[i]=!0),e[i]}});return o},Wn=e=>Jt(e)&&!Object.keys(e).length,Y1=(e,t,n,r)=>{n(e);const{name:o,...s}=e;return Wn(s)||Object.keys(s).length>=Object.keys(t).length||Object.keys(s).find(i=>t[i]===(!r||Tr.all))},Yl=e=>Array.isArray(e)?e:[e],X1=(e,t,n)=>!e||!t||e===t||Yl(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function wy(e){const t=Se.useRef(e);t.current=e,Se.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function gL(e){const t=fp(),{control:n=t.control,disabled:r,name:o,exact:s}=e||{},[i,l]=Se.useState(n._formState),c=Se.useRef(!0),u=Se.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1}),f=Se.useRef(o);return f.current=o,wy({disabled:r,next:p=>c.current&&X1(f.current,p.name,s)&&Y1(p,u.current,n._updateFormState)&&l({...n._formState,...p}),subject:n._subjects.state}),Se.useEffect(()=>(c.current=!0,u.current.isValid&&n._updateValid(!0),()=>{c.current=!1}),[n]),J1(i,n,u.current,!1)}var Xr=e=>typeof e=="string",Q1=(e,t,n,r,o)=>Xr(e)?(r&&t.watch.add(e),ue(n,e,o)):Array.isArray(e)?e.map(s=>(r&&t.watch.add(s),ue(n,s))):(r&&(t.watchAll=!0),n);function mL(e){const t=fp(),{control:n=t.control,name:r,defaultValue:o,disabled:s,exact:i}=e||{},l=Se.useRef(r);l.current=r,wy({disabled:s,subject:n._subjects.values,next:f=>{X1(l.current,f.name,i)&&u(An(Q1(l.current,n._names,f.values||n._formValues,!1,o)))}});const[c,u]=Se.useState(n._getWatch(r,o));return Se.useEffect(()=>n._removeUnmounted()),c}function vL(e){const t=fp(),{name:n,disabled:r,control:o=t.control,shouldUnregister:s}=e,i=K1(o._names.array,n),l=mL({control:o,name:n,defaultValue:ue(o._formValues,n,ue(o._defaultValues,n,e.defaultValue)),exact:!0}),c=gL({control:o,name:n}),u=Se.useRef(o.register(n,{...e.rules,value:l,...Yr(e.disabled)?{disabled:e.disabled}:{}}));return Se.useEffect(()=>{const f=o._options.shouldUnregister||s,p=(d,h)=>{const m=ue(o._fields,d);m&&m._f&&(m._f.mount=h)};if(p(n,!0),f){const d=An(ue(o._options.defaultValues,n));at(o._defaultValues,n,d),Ft(ue(o._formValues,n))&&at(o._formValues,n,d)}return()=>{(i?f&&!o._state.action:f)?o.unregister(n):p(n,!1)}},[n,o,i,s]),Se.useEffect(()=>{ue(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ue(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...Yr(r)||c.disabled?{disabled:c.disabled||r}:{},onChange:Se.useCallback(f=>u.current.onChange({target:{value:W1(f),name:n},type:of.CHANGE}),[n]),onBlur:Se.useCallback(()=>u.current.onBlur({target:{value:ue(o._formValues,n),name:n},type:of.BLUR}),[n,o]),ref:f=>{const p=ue(o._fields,n);p&&f&&(p._f.ref={focus:()=>f.focus(),select:()=>f.select(),setCustomValidity:d=>f.setCustomValidity(d),reportValidity:()=>f.reportValidity()})}},formState:c,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ue(c.errors,n)},isDirty:{enumerable:!0,get:()=>!!ue(c.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ue(c.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!ue(c.validatingFields,n)},error:{enumerable:!0,get:()=>ue(c.errors,n)}})}}const yL=e=>e.render(vL(e));var eE=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},E0=e=>({isOnSubmit:!e||e===Tr.onSubmit,isOnBlur:e===Tr.onBlur,isOnChange:e===Tr.onChange,isOnAll:e===Tr.all,isOnTouch:e===Tr.onTouched}),T0=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const Xl=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const s=ue(e,o);if(s){const{_f:i,...l}=s;if(i){if(i.refs&&i.refs[0]&&t(i.refs[0],o)&&!r)break;if(i.ref&&t(i.ref,i.name)&&!r)break;Xl(l,t)}else Jt(l)&&Xl(l,t)}}};var xL=(e,t,n)=>{const r=Yl(ue(e,n));return at(r,"root",t[n]),at(e,n,r),e},by=e=>e.type==="file",fs=e=>typeof e=="function",sf=e=>{if(!yy)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},xd=e=>Xr(e),Sy=e=>e.type==="radio",af=e=>e instanceof RegExp;const N0={value:!1,isValid:!1},k0={value:!0,isValid:!0};var tE=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ft(e[0].attributes.value)?Ft(e[0].value)||e[0].value===""?k0:{value:e[0].value,isValid:!0}:k0:N0}return N0};const R0={isValid:!1,value:null};var nE=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,R0):R0;function P0(e,t,n="validate"){if(xd(e)||Array.isArray(e)&&e.every(xd)||Yr(e)&&!e)return{type:n,message:xd(e)?e:"",ref:t}}var Ua=e=>Jt(e)&&!af(e)?e:{value:e,message:""},I0=async(e,t,n,r,o)=>{const{ref:s,refs:i,required:l,maxLength:c,minLength:u,min:f,max:p,pattern:d,validate:h,name:m,valueAsNumber:g,mount:w,disabled:x}=e._f,v=ue(t,m);if(!w||x)return{};const b=i?i[0]:s,C=I=>{r&&b.reportValidity&&(b.setCustomValidity(Yr(I)?"":I||""),b.reportValidity())},j={},S=Sy(s),N=iu(s),E=S||N,A=(g||by(s))&&Ft(s.value)&&Ft(v)||sf(s)&&s.value===""||v===""||Array.isArray(v)&&!v.length,F=eE.bind(null,m,n,j),Z=(I,q,H,J=ho.maxLength,re=ho.minLength)=>{const K=I?q:H;j[m]={type:I?J:re,message:K,ref:s,...F(I?J:re,K)}};if(o?!Array.isArray(v)||!v.length:l&&(!E&&(A||Nn(v))||Yr(v)&&!v||N&&!tE(i).isValid||S&&!nE(i).isValid)){const{value:I,message:q}=xd(l)?{value:!!l,message:l}:Ua(l);if(I&&(j[m]={type:ho.required,message:q,ref:b,...F(ho.required,q)},!n))return C(q),j}if(!A&&(!Nn(f)||!Nn(p))){let I,q;const H=Ua(p),J=Ua(f);if(!Nn(v)&&!isNaN(v)){const re=s.valueAsNumber||v&&+v;Nn(H.value)||(I=re>H.value),Nn(J.value)||(q=renew Date(new Date().toDateString()+" "+te),z=s.type=="time",L=s.type=="week";Xr(H.value)&&v&&(I=z?K(v)>K(H.value):L?v>H.value:re>new Date(H.value)),Xr(J.value)&&v&&(q=z?K(v)+I.value,J=!Nn(q.value)&&v.length<+q.value;if((H||J)&&(Z(H,I.message,q.message),!n))return C(j[m].message),j}if(d&&!A&&Xr(v)){const{value:I,message:q}=Ua(d);if(af(I)&&!v.match(I)&&(j[m]={type:ho.pattern,message:q,ref:s,...F(ho.pattern,q)},!n))return C(q),j}if(h){if(fs(h)){const I=await h(v,t),q=P0(I,b);if(q&&(j[m]={...q,...F(ho.validate,q.message)},!n))return C(q.message),j}else if(Jt(h)){let I={};for(const q in h){if(!Wn(I)&&!n)break;const H=P0(await h[q](v,t),b,q);H&&(I={...H,...F(q,H.message)},C(H.message),n&&(j[m]=I))}if(!Wn(I)&&(j[m]={ref:b,...I},!n))return j}}return C(!0),j};function wL(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{let e=[];return{get observers(){return e},next:o=>{for(const s of e)s.next&&s.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(s=>s!==o)}}),unsubscribe:()=>{e=[]}}},lf=e=>Nn(e)||!G1(e);function ra(e,t){if(lf(e)||lf(t))return e===t;if(li(e)&&li(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const s=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const i=t[o];if(li(s)&&li(i)||Jt(s)&&Jt(i)||Array.isArray(s)&&Array.isArray(i)?!ra(s,i):s!==i)return!1}}return!0}var rE=e=>e.type==="select-multiple",SL=e=>Sy(e)||iu(e),Oh=e=>sf(e)&&e.isConnected,oE=e=>{for(const t in e)if(fs(e[t]))return!0;return!1};function cf(e,t={}){const n=Array.isArray(e);if(Jt(e)||n)for(const r in e)Array.isArray(e[r])||Jt(e[r])&&!oE(e[r])?(t[r]=Array.isArray(e[r])?[]:{},cf(e[r],t[r])):Nn(e[r])||(t[r]=!0);return t}function sE(e,t,n){const r=Array.isArray(e);if(Jt(e)||r)for(const o in e)Array.isArray(e[o])||Jt(e[o])&&!oE(e[o])?Ft(t)||lf(n[o])?n[o]=Array.isArray(e[o])?cf(e[o],[]):{...cf(e[o])}:sE(e[o],Nn(t)?{}:t[o],n[o]):n[o]=!ra(e[o],t[o]);return n}var Wu=(e,t)=>sE(e,t,cf(t)),aE=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ft(e)?e:t?e===""?NaN:e&&+e:n&&Xr(e)?new Date(e):r?r(e):e;function Mh(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return by(t)?t.files:Sy(t)?nE(e.refs).value:rE(t)?[...t.selectedOptions].map(({value:n})=>n):iu(t)?tE(e.refs).value:aE(Ft(t.value)?e.ref.value:t.value,e)}var CL=(e,t,n,r)=>{const o={};for(const s of e){const i=ue(t,s);i&&at(o,s,i._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},bl=e=>Ft(e)?e:af(e)?e.source:Jt(e)?af(e.value)?e.value.source:e.value:e,jL=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function D0(e,t,n){const r=ue(e,n);if(r||xy(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const s=o.join("."),i=ue(t,s),l=ue(e,s);if(i&&!Array.isArray(i)&&n!==s)return{name:n};if(l&&l.type)return{name:s,error:l};o.pop()}return{name:n}}var _L=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,EL=(e,t)=>!dp(ue(e,t)).length&&Kt(e,t);const TL={mode:Tr.onSubmit,reValidateMode:Tr.onChange,shouldFocusError:!0};function NL(e={}){let t={...TL,...e},n={submitCount:0,isDirty:!1,isLoading:fs(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},r={},o=Jt(t.defaultValues)||Jt(t.values)?An(t.defaultValues||t.values)||{}:{},s=t.shouldUnregister?{}:An(o),i={action:!1,mount:!1,watch:!1},l={mount:new Set,unMount:new Set,array:new Set,watch:new Set},c,u=0;const f={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},p={values:Dh(),array:Dh(),state:Dh()},d=E0(t.mode),h=E0(t.reValidateMode),m=t.criteriaMode===Tr.all,g=_=>M=>{clearTimeout(u),u=setTimeout(_,M)},w=async _=>{if(f.isValid||_){const M=t.resolver?Wn((await E()).errors):await F(r,!0);M!==n.isValid&&p.state.next({isValid:M})}},x=(_,M)=>{(f.isValidating||f.validatingFields)&&((_||Array.from(l.mount)).forEach(U=>{U&&(M?at(n.validatingFields,U,M):Kt(n.validatingFields,U))}),p.state.next({validatingFields:n.validatingFields,isValidating:!Wn(n.validatingFields)}))},v=(_,M=[],U,pe,le=!0,se=!0)=>{if(pe&&U){if(i.action=!0,se&&Array.isArray(ue(r,_))){const be=U(ue(r,_),pe.argA,pe.argB);le&&at(r,_,be)}if(se&&Array.isArray(ue(n.errors,_))){const be=U(ue(n.errors,_),pe.argA,pe.argB);le&&at(n.errors,_,be),EL(n.errors,_)}if(f.touchedFields&&se&&Array.isArray(ue(n.touchedFields,_))){const be=U(ue(n.touchedFields,_),pe.argA,pe.argB);le&&at(n.touchedFields,_,be)}f.dirtyFields&&(n.dirtyFields=Wu(o,s)),p.state.next({name:_,isDirty:I(_,M),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else at(s,_,M)},b=(_,M)=>{at(n.errors,_,M),p.state.next({errors:n.errors})},C=_=>{n.errors=_,p.state.next({errors:n.errors,isValid:!1})},j=(_,M,U,pe)=>{const le=ue(r,_);if(le){const se=ue(s,_,Ft(U)?ue(o,_):U);Ft(se)||pe&&pe.defaultChecked||M?at(s,_,M?se:Mh(le._f)):J(_,se),i.mount&&w()}},S=(_,M,U,pe,le)=>{let se=!1,be=!1;const Je={name:_},yt=!!(ue(r,_)&&ue(r,_)._f&&ue(r,_)._f.disabled);if(!U||pe){f.isDirty&&(be=n.isDirty,n.isDirty=Je.isDirty=I(),se=be!==Je.isDirty);const Yt=yt||ra(ue(o,_),M);be=!!(!yt&&ue(n.dirtyFields,_)),Yt||yt?Kt(n.dirtyFields,_):at(n.dirtyFields,_,!0),Je.dirtyFields=n.dirtyFields,se=se||f.dirtyFields&&be!==!Yt}if(U){const Yt=ue(n.touchedFields,_);Yt||(at(n.touchedFields,_,U),Je.touchedFields=n.touchedFields,se=se||f.touchedFields&&Yt!==U)}return se&&le&&p.state.next(Je),se?Je:{}},N=(_,M,U,pe)=>{const le=ue(n.errors,_),se=f.isValid&&Yr(M)&&n.isValid!==M;if(e.delayError&&U?(c=g(()=>b(_,U)),c(e.delayError)):(clearTimeout(u),c=null,U?at(n.errors,_,U):Kt(n.errors,_)),(U?!ra(le,U):le)||!Wn(pe)||se){const be={...pe,...se&&Yr(M)?{isValid:M}:{},errors:n.errors,name:_};n={...n,...be},p.state.next(be)}},E=async _=>{x(_,!0);const M=await t.resolver(s,t.context,CL(_||l.mount,r,t.criteriaMode,t.shouldUseNativeValidation));return x(_),M},A=async _=>{const{errors:M}=await E(_);if(_)for(const U of _){const pe=ue(M,U);pe?at(n.errors,U,pe):Kt(n.errors,U)}else n.errors=M;return M},F=async(_,M,U={valid:!0})=>{for(const pe in _){const le=_[pe];if(le){const{_f:se,...be}=le;if(se){const Je=l.array.has(se.name);x([pe],!0);const yt=await I0(le,s,m,t.shouldUseNativeValidation&&!M,Je);if(x([pe]),yt[se.name]&&(U.valid=!1,M))break;!M&&(ue(yt,se.name)?Je?xL(n.errors,yt,se.name):at(n.errors,se.name,yt[se.name]):Kt(n.errors,se.name))}be&&await F(be,M,U)}}return U.valid},Z=()=>{for(const _ of l.unMount){const M=ue(r,_);M&&(M._f.refs?M._f.refs.every(U=>!Oh(U)):!Oh(M._f.ref))&&oe(_)}l.unMount=new Set},I=(_,M)=>(_&&M&&at(s,_,M),!ra(fe(),o)),q=(_,M,U)=>Q1(_,l,{...i.mount?s:Ft(M)?o:Xr(_)?{[_]:M}:M},U,M),H=_=>dp(ue(i.mount?s:o,_,e.shouldUnregister?ue(o,_,[]):[])),J=(_,M,U={})=>{const pe=ue(r,_);let le=M;if(pe){const se=pe._f;se&&(!se.disabled&&at(s,_,aE(M,se)),le=sf(se.ref)&&Nn(M)?"":M,rE(se.ref)?[...se.ref.options].forEach(be=>be.selected=le.includes(be.value)):se.refs?iu(se.ref)?se.refs.length>1?se.refs.forEach(be=>(!be.defaultChecked||!be.disabled)&&(be.checked=Array.isArray(le)?!!le.find(Je=>Je===be.value):le===be.value)):se.refs[0]&&(se.refs[0].checked=!!le):se.refs.forEach(be=>be.checked=be.value===le):by(se.ref)?se.ref.value="":(se.ref.value=le,se.ref.type||p.values.next({name:_,values:{...s}})))}(U.shouldDirty||U.shouldTouch)&&S(_,le,U.shouldTouch,U.shouldDirty,!0),U.shouldValidate&&te(_)},re=(_,M,U)=>{for(const pe in M){const le=M[pe],se=`${_}.${pe}`,be=ue(r,se);(l.array.has(_)||!lf(le)||be&&!be._f)&&!li(le)?re(se,le,U):J(se,le,U)}},K=(_,M,U={})=>{const pe=ue(r,_),le=l.array.has(_),se=An(M);at(s,_,se),le?(p.array.next({name:_,values:{...s}}),(f.isDirty||f.dirtyFields)&&U.shouldDirty&&p.state.next({name:_,dirtyFields:Wu(o,s),isDirty:I(_,se)})):pe&&!pe._f&&!Nn(se)?re(_,se,U):J(_,se,U),T0(_,l)&&p.state.next({...n}),p.values.next({name:i.mount?_:void 0,values:{...s}})},z=async _=>{i.mount=!0;const M=_.target;let U=M.name,pe=!0;const le=ue(r,U),se=()=>M.type?Mh(le._f):W1(_),be=Je=>{pe=Number.isNaN(Je)||Je===ue(s,U,Je)};if(le){let Je,yt;const Yt=se(),rn=_.type===of.BLUR||_.type===of.FOCUS_OUT,Xt=!jL(le._f)&&!t.resolver&&!ue(n.errors,U)&&!le._f.deps||_L(rn,ue(n.touchedFields,U),n.isSubmitted,h,d),Zo=T0(U,l,rn);at(s,U,Yt),rn?(le._f.onBlur&&le._f.onBlur(_),c&&c(0)):le._f.onChange&&le._f.onChange(_);const Ur=S(U,Yt,rn,!1),Bs=!Wn(Ur)||Zo;if(!rn&&p.values.next({name:U,type:_.type,values:{...s}}),Xt)return f.isValid&&w(),Bs&&p.state.next({name:U,...Zo?{}:Ur});if(!rn&&Zo&&p.state.next({...n}),t.resolver){const{errors:_n}=await E([U]);if(be(Yt),pe){const ce=D0(n.errors,r,U),ze=D0(_n,r,ce.name||U);Je=ze.error,U=ze.name,yt=Wn(_n)}}else x([U],!0),Je=(await I0(le,s,m,t.shouldUseNativeValidation))[U],x([U]),be(Yt),pe&&(Je?yt=!1:f.isValid&&(yt=await F(r,!0)));pe&&(le._f.deps&&te(le._f.deps),N(U,yt,Je,Ur))}},L=(_,M)=>{if(ue(n.errors,M)&&_.focus)return _.focus(),1},te=async(_,M={})=>{let U,pe;const le=Yl(_);if(t.resolver){const se=await A(Ft(_)?_:le);U=Wn(se),pe=_?!le.some(be=>ue(se,be)):U}else _?(pe=(await Promise.all(le.map(async se=>{const be=ue(r,se);return await F(be&&be._f?{[se]:be}:be)}))).every(Boolean),!(!pe&&!n.isValid)&&w()):pe=U=await F(r);return p.state.next({...!Xr(_)||f.isValid&&U!==n.isValid?{}:{name:_},...t.resolver||!_?{isValid:U}:{},errors:n.errors}),M.shouldFocus&&!pe&&Xl(r,L,_?le:l.mount),pe},fe=_=>{const M={...i.mount?s:o};return Ft(_)?M:Xr(_)?ue(M,_):_.map(U=>ue(M,U))},B=(_,M)=>({invalid:!!ue((M||n).errors,_),isDirty:!!ue((M||n).dirtyFields,_),error:ue((M||n).errors,_),isValidating:!!ue(n.validatingFields,_),isTouched:!!ue((M||n).touchedFields,_)}),ne=_=>{_&&Yl(_).forEach(M=>Kt(n.errors,M)),p.state.next({errors:_?n.errors:{}})},Q=(_,M,U)=>{const pe=(ue(r,_,{_f:{}})._f||{}).ref,le=ue(n.errors,_)||{},{ref:se,message:be,type:Je,...yt}=le;at(n.errors,_,{...yt,...M,ref:pe}),p.state.next({name:_,errors:n.errors,isValid:!1}),U&&U.shouldFocus&&pe&&pe.focus&&pe.focus()},ie=(_,M)=>fs(_)?p.values.subscribe({next:U=>_(q(void 0,M),U)}):q(_,M,!0),oe=(_,M={})=>{for(const U of _?Yl(_):l.mount)l.mount.delete(U),l.array.delete(U),M.keepValue||(Kt(r,U),Kt(s,U)),!M.keepError&&Kt(n.errors,U),!M.keepDirty&&Kt(n.dirtyFields,U),!M.keepTouched&&Kt(n.touchedFields,U),!M.keepIsValidating&&Kt(n.validatingFields,U),!t.shouldUnregister&&!M.keepDefaultValue&&Kt(o,U);p.values.next({values:{...s}}),p.state.next({...n,...M.keepDirty?{isDirty:I()}:{}}),!M.keepIsValid&&w()},W=({disabled:_,name:M,field:U,fields:pe,value:le})=>{if(Yr(_)&&i.mount||_){const se=_?void 0:Ft(le)?Mh(U?U._f:ue(pe,M)._f):le;at(s,M,se),S(M,se,!1,!1,!0)}},we=(_,M={})=>{let U=ue(r,_);const pe=Yr(M.disabled);return at(r,_,{...U||{},_f:{...U&&U._f?U._f:{ref:{name:_}},name:_,mount:!0,...M}}),l.mount.add(_),U?W({field:U,disabled:M.disabled,name:_,value:M.value}):j(_,!0,M.value),{...pe?{disabled:M.disabled}:{},...t.progressive?{required:!!M.required,min:bl(M.min),max:bl(M.max),minLength:bl(M.minLength),maxLength:bl(M.maxLength),pattern:bl(M.pattern)}:{},name:_,onChange:z,onBlur:z,ref:le=>{if(le){we(_,M),U=ue(r,_);const se=Ft(le.value)&&le.querySelectorAll&&le.querySelectorAll("input,select,textarea")[0]||le,be=SL(se),Je=U._f.refs||[];if(be?Je.find(yt=>yt===se):se===U._f.ref)return;at(r,_,{_f:{...U._f,...be?{refs:[...Je.filter(Oh),se,...Array.isArray(ue(o,_))?[{}]:[]],ref:{type:se.type,name:_}}:{ref:se}}}),j(_,!1,void 0,se)}else U=ue(r,_,{}),U._f&&(U._f.mount=!1),(t.shouldUnregister||M.shouldUnregister)&&!(K1(l.array,_)&&i.action)&&l.unMount.add(_)}}},Pe=()=>t.shouldFocusError&&Xl(r,L,l.mount),Fe=_=>{Yr(_)&&(p.state.next({disabled:_}),Xl(r,(M,U)=>{const pe=ue(r,U);pe&&(M.disabled=pe._f.disabled||_,Array.isArray(pe._f.refs)&&pe._f.refs.forEach(le=>{le.disabled=pe._f.disabled||_}))},0,!1))},Ie=(_,M)=>async U=>{let pe;U&&(U.preventDefault&&U.preventDefault(),U.persist&&U.persist());let le=An(s);if(p.state.next({isSubmitting:!0}),t.resolver){const{errors:se,values:be}=await E();n.errors=se,le=be}else await F(r);if(Kt(n.errors,"root"),Wn(n.errors)){p.state.next({errors:{}});try{await _(le,U)}catch(se){pe=se}}else M&&await M({...n.errors},U),Pe(),setTimeout(Pe);if(p.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Wn(n.errors)&&!pe,submitCount:n.submitCount+1,errors:n.errors}),pe)throw pe},he=(_,M={})=>{ue(r,_)&&(Ft(M.defaultValue)?K(_,An(ue(o,_))):(K(_,M.defaultValue),at(o,_,An(M.defaultValue))),M.keepTouched||Kt(n.touchedFields,_),M.keepDirty||(Kt(n.dirtyFields,_),n.isDirty=M.defaultValue?I(_,An(ue(o,_))):I()),M.keepError||(Kt(n.errors,_),f.isValid&&w()),p.state.next({...n}))},Xe=(_,M={})=>{const U=_?An(_):o,pe=An(U),le=Wn(_),se=le?o:pe;if(M.keepDefaultValues||(o=U),!M.keepValues){if(M.keepDirtyValues)for(const be of l.mount)ue(n.dirtyFields,be)?at(se,be,ue(s,be)):K(be,ue(se,be));else{if(yy&&Ft(_))for(const be of l.mount){const Je=ue(r,be);if(Je&&Je._f){const yt=Array.isArray(Je._f.refs)?Je._f.refs[0]:Je._f.ref;if(sf(yt)){const Yt=yt.closest("form");if(Yt){Yt.reset();break}}}}r={}}s=e.shouldUnregister?M.keepDefaultValues?An(o):{}:An(se),p.array.next({values:{...se}}),p.values.next({values:{...se}})}l={mount:M.keepDirtyValues?l.mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},i.mount=!f.isValid||!!M.keepIsValid||!!M.keepDirtyValues,i.watch=!!e.shouldUnregister,p.state.next({submitCount:M.keepSubmitCount?n.submitCount:0,isDirty:le?!1:M.keepDirty?n.isDirty:!!(M.keepDefaultValues&&!ra(_,o)),isSubmitted:M.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:le?{}:M.keepDirtyValues?M.keepDefaultValues&&s?Wu(o,s):n.dirtyFields:M.keepDefaultValues&&_?Wu(o,_):M.keepDirty?n.dirtyFields:{},touchedFields:M.keepTouched?n.touchedFields:{},errors:M.keepErrors?n.errors:{},isSubmitSuccessful:M.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},Nt=(_,M)=>Xe(fs(_)?_(s):_,M);return{control:{register:we,unregister:oe,getFieldState:B,handleSubmit:Ie,setError:Q,_executeSchema:E,_getWatch:q,_getDirty:I,_updateValid:w,_removeUnmounted:Z,_updateFieldArray:v,_updateDisabledField:W,_getFieldArray:H,_reset:Xe,_resetDefaultValues:()=>fs(t.defaultValues)&&t.defaultValues().then(_=>{Nt(_,t.resetOptions),p.state.next({isLoading:!1})}),_updateFormState:_=>{n={...n,..._}},_disableForm:Fe,_subjects:p,_proxyFormState:f,_setErrors:C,get _fields(){return r},get _formValues(){return s},get _state(){return i},set _state(_){i=_},get _defaultValues(){return o},get _names(){return l},set _names(_){l=_},get _formState(){return n},set _formState(_){n=_},get _options(){return t},set _options(_){t={...t,..._}}},trigger:te,register:we,handleSubmit:Ie,watch:ie,setValue:K,getValues:fe,reset:Nt,resetField:he,clearErrors:ne,unregister:oe,setError:Q,setFocus:(_,M={})=>{const U=ue(r,_),pe=U&&U._f;if(pe){const le=pe.refs?pe.refs[0]:pe.ref;le.focus&&(le.focus(),M.shouldSelect&&le.select())}},getFieldState:B}}function tn(e={}){const t=Se.useRef(),n=Se.useRef(),[r,o]=Se.useState({isDirty:!1,isValidating:!1,isLoading:fs(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1,defaultValues:fs(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...NL(e),formState:r});const s=t.current.control;return s._options=e,wy({subject:s._subjects.state,next:i=>{Y1(i,s._proxyFormState,s._updateFormState,!0)&&o({...s._formState})}}),Se.useEffect(()=>s._disableForm(e.disabled),[s,e.disabled]),Se.useEffect(()=>{if(s._proxyFormState.isDirty){const i=s._getDirty();i!==r.isDirty&&s._subjects.state.next({isDirty:i})}},[s,r.isDirty]),Se.useEffect(()=>{e.values&&!ra(e.values,n.current)?(s._reset(e.values,s._options.resetOptions),n.current=e.values,o(i=>({...i}))):s._resetDefaultValues()},[e.values,s]),Se.useEffect(()=>{e.errors&&s._setErrors(e.errors)},[e.errors,s]),Se.useEffect(()=>{s._state.mount||(s._updateValid(),s._state.mount=!0),s._state.watch&&(s._state.watch=!1,s._subjects.state.next({...s._formState})),s._removeUnmounted()}),Se.useEffect(()=>{e.shouldUnregister&&s._subjects.values.next({values:s._getWatch()})},[e.shouldUnregister,s]),t.current.formState=J1(r,s),t.current}var kL="Label",iE=y.forwardRef((e,t)=>a.jsx(Ve.label,{...e,ref:t,onMouseDown:n=>{var o;n.target.closest("button, input, select, textarea")||((o=e.onMouseDown)==null||o.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));iE.displayName=kL;var lE=iE;const RL=c1("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),bo=y.forwardRef(({className:e,...t},n)=>a.jsx(lE,{ref:n,className:Re(RL(),e),...t}));bo.displayName=lE.displayName;const uo=Bo,cE=y.createContext({}),R=({...e})=>a.jsx(cE.Provider,{value:{name:e.name},children:a.jsx(yL,{...e})}),pp=()=>{const e=y.useContext(cE),t=y.useContext(uE),{getFieldState:n,formState:r}=fp(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:s}=t;return{id:s,name:e.name,formItemId:`${s}-form-item`,formDescriptionId:`${s}-form-item-description`,formMessageId:`${s}-form-item-message`,...o}},uE=y.createContext({}),D=y.forwardRef(({className:e,...t},n)=>{const r=y.useId();return a.jsx(uE.Provider,{value:{id:r},children:a.jsx("div",{ref:n,className:Re("space-y-2",e),...t})})});D.displayName="FormItem";const O=y.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=pp();return a.jsx(bo,{ref:n,className:Re(r&&"text-destructive",e),htmlFor:o,...t})});O.displayName="FormLabel";const ae=y.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:s}=pp();return a.jsx(Oo,{ref:t,id:r,"aria-describedby":n?`${o} ${s}`:`${o}`,"aria-invalid":!!n,...e})});ae.displayName="FormControl";const zt=y.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=pp();return a.jsx("p",{ref:n,id:r,className:Re("text-sm text-muted-foreground",e),...t})});zt.displayName="FormDescription";const PL=y.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:s}=pp(),i=o?String(o==null?void 0:o.message):t;return i?a.jsx("p",{ref:r,id:s,className:Re("text-sm font-medium text-destructive",e),...n,children:i}):null});PL.displayName="FormMessage";const Y=y.forwardRef(({className:e,type:t,...n},r)=>a.jsx("input",{type:t,className:Re("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,...n}));Y.displayName="Input";function O0(e,[t,n]){return Math.min(n,Math.max(t,e))}function Cy(e){const t=e+"CollectionProvider",[n,r]=lo(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=h=>{const{scope:m,children:g}=h,w=Se.useRef(null),x=Se.useRef(new Map).current;return a.jsx(o,{scope:m,itemMap:x,collectionRef:w,children:g})};i.displayName=t;const l=e+"CollectionSlot",c=Se.forwardRef((h,m)=>{const{scope:g,children:w}=h,x=s(l,g),v=ut(m,x.collectionRef);return a.jsx(Oo,{ref:v,children:w})});c.displayName=l;const u=e+"CollectionItemSlot",f="data-radix-collection-item",p=Se.forwardRef((h,m)=>{const{scope:g,children:w,...x}=h,v=Se.useRef(null),b=ut(m,v),C=s(u,g);return Se.useEffect(()=>(C.itemMap.set(v,{ref:v,...x}),()=>void C.itemMap.delete(v))),a.jsx(Oo,{[f]:"",ref:b,children:w})});p.displayName=u;function d(h){const m=s(e+"CollectionConsumer",h);return Se.useCallback(()=>{const w=m.collectionRef.current;if(!w)return[];const x=Array.from(w.querySelectorAll(`[${f}]`));return Array.from(m.itemMap.values()).sort((C,j)=>x.indexOf(C.ref.current)-x.indexOf(j.ref.current))},[m.collectionRef,m.itemMap])}return[{Provider:i,Slot:c,ItemSlot:p},d,r]}var IL=y.createContext(void 0);function hp(e){const t=y.useContext(IL);return e||t||"ltr"}const DL=["top","right","bottom","left"],Qr=Math.min,Jn=Math.max,uf=Math.round,Ku=Math.floor,_s=e=>({x:e,y:e}),OL={left:"right",right:"left",bottom:"top",top:"bottom"},ML={start:"end",end:"start"};function hm(e,t,n){return Jn(e,Qr(t,n))}function Mo(e,t){return typeof e=="function"?e(t):e}function Ao(e){return e.split("-")[0]}function Gi(e){return e.split("-")[1]}function jy(e){return e==="x"?"y":"x"}function _y(e){return e==="y"?"height":"width"}function Es(e){return["top","bottom"].includes(Ao(e))?"y":"x"}function Ey(e){return jy(Es(e))}function AL(e,t,n){n===void 0&&(n=!1);const r=Gi(e),o=Ey(e),s=_y(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=df(i)),[i,df(i)]}function FL(e){const t=df(e);return[gm(e),t,gm(t)]}function gm(e){return e.replace(/start|end/g,t=>ML[t])}function LL(e,t,n){const r=["left","right"],o=["right","left"],s=["top","bottom"],i=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?s:i;default:return[]}}function $L(e,t,n,r){const o=Gi(e);let s=LL(Ao(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(gm)))),s}function df(e){return e.replace(/left|right|bottom|top/g,t=>OL[t])}function zL(e){return{top:0,right:0,bottom:0,left:0,...e}}function dE(e){return typeof e!="number"?zL(e):{top:e,right:e,bottom:e,left:e}}function ff(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function M0(e,t,n){let{reference:r,floating:o}=e;const s=Es(t),i=Ey(t),l=_y(i),c=Ao(t),u=s==="y",f=r.x+r.width/2-o.width/2,p=r.y+r.height/2-o.height/2,d=r[l]/2-o[l]/2;let h;switch(c){case"top":h={x:f,y:r.y-o.height};break;case"bottom":h={x:f,y:r.y+r.height};break;case"right":h={x:r.x+r.width,y:p};break;case"left":h={x:r.x-o.width,y:p};break;default:h={x:r.x,y:r.y}}switch(Gi(t)){case"start":h[i]-=d*(n&&u?-1:1);break;case"end":h[i]+=d*(n&&u?-1:1);break}return h}const VL=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,l=s.filter(Boolean),c=await(i.isRTL==null?void 0:i.isRTL(t));let u=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:f,y:p}=M0(u,r,c),d=r,h={},m=0;for(let g=0;g({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:i,elements:l,middlewareData:c}=t,{element:u,padding:f=0}=Mo(e,t)||{};if(u==null)return{};const p=dE(f),d={x:n,y:r},h=Ey(o),m=_y(h),g=await i.getDimensions(u),w=h==="y",x=w?"top":"left",v=w?"bottom":"right",b=w?"clientHeight":"clientWidth",C=s.reference[m]+s.reference[h]-d[h]-s.floating[m],j=d[h]-s.reference[h],S=await(i.getOffsetParent==null?void 0:i.getOffsetParent(u));let N=S?S[b]:0;(!N||!await(i.isElement==null?void 0:i.isElement(S)))&&(N=l.floating[b]||s.floating[m]);const E=C/2-j/2,A=N/2-g[m]/2-1,F=Qr(p[x],A),Z=Qr(p[v],A),I=F,q=N-g[m]-Z,H=N/2-g[m]/2+E,J=hm(I,H,q),re=!c.arrow&&Gi(o)!=null&&H!==J&&s.reference[m]/2-(HH<=0)){var Z,I;const H=(((Z=s.flip)==null?void 0:Z.index)||0)+1,J=N[H];if(J)return{data:{index:H,overflows:F},reset:{placement:J}};let re=(I=F.filter(K=>K.overflows[0]<=0).sort((K,z)=>K.overflows[1]-z.overflows[1])[0])==null?void 0:I.placement;if(!re)switch(h){case"bestFit":{var q;const K=(q=F.filter(z=>{if(S){const L=Es(z.placement);return L===v||L==="y"}return!0}).map(z=>[z.placement,z.overflows.filter(L=>L>0).reduce((L,te)=>L+te,0)]).sort((z,L)=>z[1]-L[1])[0])==null?void 0:q[0];K&&(re=K);break}case"initialPlacement":re=l;break}if(o!==re)return{reset:{placement:re}}}return{}}}};function A0(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function F0(e){return DL.some(t=>e[t]>=0)}const HL=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Mo(e,t);switch(r){case"referenceHidden":{const s=await Ec(t,{...o,elementContext:"reference"}),i=A0(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:F0(i)}}}case"escaped":{const s=await Ec(t,{...o,altBoundary:!0}),i=A0(s,n.floating);return{data:{escapedOffsets:i,escaped:F0(i)}}}default:return{}}}}};async function GL(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=Ao(n),l=Gi(n),c=Es(n)==="y",u=["left","top"].includes(i)?-1:1,f=s&&c?-1:1,p=Mo(t,e);let{mainAxis:d,crossAxis:h,alignmentAxis:m}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...p};return l&&typeof m=="number"&&(h=l==="end"?m*-1:m),c?{x:h*f,y:d*u}:{x:d*u,y:h*f}}const WL=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:s,placement:i,middlewareData:l}=t,c=await GL(t,e);return i===((n=l.offset)==null?void 0:n.placement)&&(r=l.arrow)!=null&&r.alignmentOffset?{}:{x:o+c.x,y:s+c.y,data:{...c,placement:i}}}}},KL=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:s=!0,crossAxis:i=!1,limiter:l={fn:w=>{let{x,y:v}=w;return{x,y:v}}},...c}=Mo(e,t),u={x:n,y:r},f=await Ec(t,c),p=Es(Ao(o)),d=jy(p);let h=u[d],m=u[p];if(s){const w=d==="y"?"top":"left",x=d==="y"?"bottom":"right",v=h+f[w],b=h-f[x];h=hm(v,h,b)}if(i){const w=p==="y"?"top":"left",x=p==="y"?"bottom":"right",v=m+f[w],b=m-f[x];m=hm(v,m,b)}const g=l.fn({...t,[d]:h,[p]:m});return{...g,data:{x:g.x-n,y:g.y-r}}}}},qL=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:i}=t,{offset:l=0,mainAxis:c=!0,crossAxis:u=!0}=Mo(e,t),f={x:n,y:r},p=Es(o),d=jy(p);let h=f[d],m=f[p];const g=Mo(l,t),w=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(c){const b=d==="y"?"height":"width",C=s.reference[d]-s.floating[b]+w.mainAxis,j=s.reference[d]+s.reference[b]-w.mainAxis;hj&&(h=j)}if(u){var x,v;const b=d==="y"?"width":"height",C=["top","left"].includes(Ao(o)),j=s.reference[p]-s.floating[b]+(C&&((x=i.offset)==null?void 0:x[p])||0)+(C?0:w.crossAxis),S=s.reference[p]+s.reference[b]+(C?0:((v=i.offset)==null?void 0:v[p])||0)-(C?w.crossAxis:0);mS&&(m=S)}return{[d]:h,[p]:m}}}},ZL=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:s}=t,{apply:i=()=>{},...l}=Mo(e,t),c=await Ec(t,l),u=Ao(n),f=Gi(n),p=Es(n)==="y",{width:d,height:h}=r.floating;let m,g;u==="top"||u==="bottom"?(m=u,g=f===(await(o.isRTL==null?void 0:o.isRTL(s.floating))?"start":"end")?"left":"right"):(g=u,m=f==="end"?"top":"bottom");const w=h-c.top-c.bottom,x=d-c.left-c.right,v=Qr(h-c[m],w),b=Qr(d-c[g],x),C=!t.middlewareData.shift;let j=v,S=b;if(p?S=f||C?Qr(b,x):x:j=f||C?Qr(v,w):w,C&&!f){const E=Jn(c.left,0),A=Jn(c.right,0),F=Jn(c.top,0),Z=Jn(c.bottom,0);p?S=d-2*(E!==0||A!==0?E+A:Jn(c.left,c.right)):j=h-2*(F!==0||Z!==0?F+Z:Jn(c.top,c.bottom))}await i({...t,availableWidth:S,availableHeight:j});const N=await o.getDimensions(s.floating);return d!==N.width||h!==N.height?{reset:{rects:!0}}:{}}}};function Wi(e){return fE(e)?(e.nodeName||"").toLowerCase():"#document"}function er(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Ho(e){var t;return(t=(fE(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function fE(e){return e instanceof Node||e instanceof er(e).Node}function oo(e){return e instanceof Element||e instanceof er(e).Element}function so(e){return e instanceof HTMLElement||e instanceof er(e).HTMLElement}function L0(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof er(e).ShadowRoot}function lu(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Fr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function JL(e){return["table","td","th"].includes(Wi(e))}function gp(e){return[":popover-open",":modal"].some(t=>{try{return e.matches(t)}catch{return!1}})}function Ty(e){const t=Ny(),n=Fr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function YL(e){let t=Ts(e);for(;so(t)&&!Ii(t);){if(gp(t))return null;if(Ty(t))return t;t=Ts(t)}return null}function Ny(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Ii(e){return["html","body","#document"].includes(Wi(e))}function Fr(e){return er(e).getComputedStyle(e)}function mp(e){return oo(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Ts(e){if(Wi(e)==="html")return e;const t=e.assignedSlot||e.parentNode||L0(e)&&e.host||Ho(e);return L0(t)?t.host:t}function pE(e){const t=Ts(e);return Ii(t)?e.ownerDocument?e.ownerDocument.body:e.body:so(t)&&lu(t)?t:pE(t)}function Tc(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=pE(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=er(o);return s?t.concat(i,i.visualViewport||[],lu(o)?o:[],i.frameElement&&n?Tc(i.frameElement):[]):t.concat(o,Tc(o,[],n))}function hE(e){const t=Fr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=so(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,l=uf(n)!==s||uf(r)!==i;return l&&(n=s,r=i),{width:n,height:r,$:l}}function ky(e){return oo(e)?e:e.contextElement}function yi(e){const t=ky(e);if(!so(t))return _s(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=hE(t);let i=(s?uf(n.width):n.width)/r,l=(s?uf(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!l||!Number.isFinite(l))&&(l=1),{x:i,y:l}}const XL=_s(0);function gE(e){const t=er(e);return!Ny()||!t.visualViewport?XL:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function QL(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==er(e)?!1:t}function wa(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=ky(e);let i=_s(1);t&&(r?oo(r)&&(i=yi(r)):i=yi(e));const l=QL(s,n,r)?gE(s):_s(0);let c=(o.left+l.x)/i.x,u=(o.top+l.y)/i.y,f=o.width/i.x,p=o.height/i.y;if(s){const d=er(s),h=r&&oo(r)?er(r):r;let m=d,g=m.frameElement;for(;g&&r&&h!==m;){const w=yi(g),x=g.getBoundingClientRect(),v=Fr(g),b=x.left+(g.clientLeft+parseFloat(v.paddingLeft))*w.x,C=x.top+(g.clientTop+parseFloat(v.paddingTop))*w.y;c*=w.x,u*=w.y,f*=w.x,p*=w.y,c+=b,u+=C,m=er(g),g=m.frameElement}}return ff({width:f,height:p,x:c,y:u})}function e$(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=Ho(r),l=t?gp(t.floating):!1;if(r===i||l&&s)return n;let c={scrollLeft:0,scrollTop:0},u=_s(1);const f=_s(0),p=so(r);if((p||!p&&!s)&&((Wi(r)!=="body"||lu(i))&&(c=mp(r)),so(r))){const d=wa(r);u=yi(r),f.x=d.x+r.clientLeft,f.y=d.y+r.clientTop}return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-c.scrollLeft*u.x+f.x,y:n.y*u.y-c.scrollTop*u.y+f.y}}function t$(e){return Array.from(e.getClientRects())}function mE(e){return wa(Ho(e)).left+mp(e).scrollLeft}function n$(e){const t=Ho(e),n=mp(e),r=e.ownerDocument.body,o=Jn(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Jn(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+mE(e);const l=-n.scrollTop;return Fr(r).direction==="rtl"&&(i+=Jn(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:l}}function r$(e,t){const n=er(e),r=Ho(e),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,l=0,c=0;if(o){s=o.width,i=o.height;const u=Ny();(!u||u&&t==="fixed")&&(l=o.offsetLeft,c=o.offsetTop)}return{width:s,height:i,x:l,y:c}}function o$(e,t){const n=wa(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=so(e)?yi(e):_s(1),i=e.clientWidth*s.x,l=e.clientHeight*s.y,c=o*s.x,u=r*s.y;return{width:i,height:l,x:c,y:u}}function $0(e,t,n){let r;if(t==="viewport")r=r$(e,n);else if(t==="document")r=n$(Ho(e));else if(oo(t))r=o$(t,n);else{const o=gE(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return ff(r)}function vE(e,t){const n=Ts(e);return n===t||!oo(n)||Ii(n)?!1:Fr(n).position==="fixed"||vE(n,t)}function s$(e,t){const n=t.get(e);if(n)return n;let r=Tc(e,[],!1).filter(l=>oo(l)&&Wi(l)!=="body"),o=null;const s=Fr(e).position==="fixed";let i=s?Ts(e):e;for(;oo(i)&&!Ii(i);){const l=Fr(i),c=Ty(i);!c&&l.position==="fixed"&&(o=null),(s?!c&&!o:!c&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||lu(i)&&!c&&vE(e,i))?r=r.filter(f=>f!==i):o=l,i=Ts(i)}return t.set(e,r),r}function a$(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?gp(t)?[]:s$(t,this._c):[].concat(n),r],l=i[0],c=i.reduce((u,f)=>{const p=$0(t,f,o);return u.top=Jn(p.top,u.top),u.right=Qr(p.right,u.right),u.bottom=Qr(p.bottom,u.bottom),u.left=Jn(p.left,u.left),u},$0(t,l,o));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function i$(e){const{width:t,height:n}=hE(e);return{width:t,height:n}}function l$(e,t,n){const r=so(t),o=Ho(t),s=n==="fixed",i=wa(e,!0,s,t);let l={scrollLeft:0,scrollTop:0};const c=_s(0);if(r||!r&&!s)if((Wi(t)!=="body"||lu(o))&&(l=mp(t)),r){const p=wa(t,!0,s,t);c.x=p.x+t.clientLeft,c.y=p.y+t.clientTop}else o&&(c.x=mE(o));const u=i.left+l.scrollLeft-c.x,f=i.top+l.scrollTop-c.y;return{x:u,y:f,width:i.width,height:i.height}}function Ah(e){return Fr(e).position==="static"}function z0(e,t){return!so(e)||Fr(e).position==="fixed"?null:t?t(e):e.offsetParent}function yE(e,t){const n=er(e);if(gp(e))return n;if(!so(e)){let o=Ts(e);for(;o&&!Ii(o);){if(oo(o)&&!Ah(o))return o;o=Ts(o)}return n}let r=z0(e,t);for(;r&&JL(r)&&Ah(r);)r=z0(r,t);return r&&Ii(r)&&Ah(r)&&!Ty(r)?n:r||YL(e)||n}const c$=async function(e){const t=this.getOffsetParent||yE,n=this.getDimensions,r=await n(e.floating);return{reference:l$(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function u$(e){return Fr(e).direction==="rtl"}const d$={convertOffsetParentRelativeRectToViewportRelativeRect:e$,getDocumentElement:Ho,getClippingRect:a$,getOffsetParent:yE,getElementRects:c$,getClientRects:t$,getDimensions:i$,getScale:yi,isElement:oo,isRTL:u$};function f$(e,t){let n=null,r;const o=Ho(e);function s(){var l;clearTimeout(r),(l=n)==null||l.disconnect(),n=null}function i(l,c){l===void 0&&(l=!1),c===void 0&&(c=1),s();const{left:u,top:f,width:p,height:d}=e.getBoundingClientRect();if(l||t(),!p||!d)return;const h=Ku(f),m=Ku(o.clientWidth-(u+p)),g=Ku(o.clientHeight-(f+d)),w=Ku(u),v={rootMargin:-h+"px "+-m+"px "+-g+"px "+-w+"px",threshold:Jn(0,Qr(1,c))||1};let b=!0;function C(j){const S=j[0].intersectionRatio;if(S!==c){if(!b)return i();S?i(!1,S):r=setTimeout(()=>{i(!1,1e-7)},1e3)}b=!1}try{n=new IntersectionObserver(C,{...v,root:o.ownerDocument})}catch{n=new IntersectionObserver(C,v)}n.observe(e)}return i(!0),s}function p$(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:c=!1}=r,u=ky(e),f=o||s?[...u?Tc(u):[],...Tc(t)]:[];f.forEach(x=>{o&&x.addEventListener("scroll",n,{passive:!0}),s&&x.addEventListener("resize",n)});const p=u&&l?f$(u,n):null;let d=-1,h=null;i&&(h=new ResizeObserver(x=>{let[v]=x;v&&v.target===u&&h&&(h.unobserve(t),cancelAnimationFrame(d),d=requestAnimationFrame(()=>{var b;(b=h)==null||b.observe(t)})),n()}),u&&!c&&h.observe(u),h.observe(t));let m,g=c?wa(e):null;c&&w();function w(){const x=wa(e);g&&(x.x!==g.x||x.y!==g.y||x.width!==g.width||x.height!==g.height)&&n(),g=x,m=requestAnimationFrame(w)}return n(),()=>{var x;f.forEach(v=>{o&&v.removeEventListener("scroll",n),s&&v.removeEventListener("resize",n)}),p==null||p(),(x=h)==null||x.disconnect(),h=null,c&&cancelAnimationFrame(m)}}const h$=WL,g$=KL,m$=BL,v$=ZL,y$=HL,V0=UL,x$=qL,w$=(e,t,n)=>{const r=new Map,o={platform:d$,...n},s={...o.platform,_c:r};return VL(e,t,{...o,platform:s})};var wd=typeof document<"u"?y.useLayoutEffect:y.useEffect;function pf(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!pf(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const s=o[r];if(!(s==="_owner"&&e.$$typeof)&&!pf(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function xE(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function U0(e,t){const n=xE(e);return Math.round(t*n)/n}function B0(e){const t=y.useRef(e);return wd(()=>{t.current=e}),t}function b$(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:i}={},transform:l=!0,whileElementsMounted:c,open:u}=e,[f,p]=y.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[d,h]=y.useState(r);pf(d,r)||h(r);const[m,g]=y.useState(null),[w,x]=y.useState(null),v=y.useCallback(K=>{K!==S.current&&(S.current=K,g(K))},[]),b=y.useCallback(K=>{K!==N.current&&(N.current=K,x(K))},[]),C=s||m,j=i||w,S=y.useRef(null),N=y.useRef(null),E=y.useRef(f),A=c!=null,F=B0(c),Z=B0(o),I=y.useCallback(()=>{if(!S.current||!N.current)return;const K={placement:t,strategy:n,middleware:d};Z.current&&(K.platform=Z.current),w$(S.current,N.current,K).then(z=>{const L={...z,isPositioned:!0};q.current&&!pf(E.current,L)&&(E.current=L,Ls.flushSync(()=>{p(L)}))})},[d,t,n,Z]);wd(()=>{u===!1&&E.current.isPositioned&&(E.current.isPositioned=!1,p(K=>({...K,isPositioned:!1})))},[u]);const q=y.useRef(!1);wd(()=>(q.current=!0,()=>{q.current=!1}),[]),wd(()=>{if(C&&(S.current=C),j&&(N.current=j),C&&j){if(F.current)return F.current(C,j,I);I()}},[C,j,I,F,A]);const H=y.useMemo(()=>({reference:S,floating:N,setReference:v,setFloating:b}),[v,b]),J=y.useMemo(()=>({reference:C,floating:j}),[C,j]),re=y.useMemo(()=>{const K={position:n,left:0,top:0};if(!J.floating)return K;const z=U0(J.floating,f.x),L=U0(J.floating,f.y);return l?{...K,transform:"translate("+z+"px, "+L+"px)",...xE(J.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:z,top:L}},[n,l,J.floating,f.x,f.y]);return y.useMemo(()=>({...f,update:I,refs:H,elements:J,floatingStyles:re}),[f,I,H,J,re])}const S$=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?V0({element:r.current,padding:o}).fn(n):{}:r?V0({element:r,padding:o}).fn(n):{}}}},C$=(e,t)=>({...h$(e),options:[e,t]}),j$=(e,t)=>({...g$(e),options:[e,t]}),_$=(e,t)=>({...x$(e),options:[e,t]}),E$=(e,t)=>({...m$(e),options:[e,t]}),T$=(e,t)=>({...v$(e),options:[e,t]}),N$=(e,t)=>({...y$(e),options:[e,t]}),k$=(e,t)=>({...S$(e),options:[e,t]});var R$="Arrow",wE=y.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return a.jsx(Ve.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:a.jsx("polygon",{points:"0,0 30,0 15,10"})})});wE.displayName=R$;var P$=wE;function bE(e){const[t,n]=y.useState(void 0);return bn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,l;if("borderBoxSize"in s){const c=s.borderBoxSize,u=Array.isArray(c)?c[0]:c;i=u.inlineSize,l=u.blockSize}else i=e.offsetWidth,l=e.offsetHeight;n({width:i,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var Ry="Popper",[SE,vp]=lo(Ry),[I$,CE]=SE(Ry),jE=e=>{const{__scopePopper:t,children:n}=e,[r,o]=y.useState(null);return a.jsx(I$,{scope:t,anchor:r,onAnchorChange:o,children:n})};jE.displayName=Ry;var _E="PopperAnchor",EE=y.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=CE(_E,n),i=y.useRef(null),l=ut(t,i);return y.useEffect(()=>{s.onAnchorChange((r==null?void 0:r.current)||i.current)}),r?null:a.jsx(Ve.div,{...o,ref:l})});EE.displayName=_E;var Py="PopperContent",[D$,O$]=SE(Py),TE=y.forwardRef((e,t)=>{var W,we,Pe,Fe,Ie,he;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:l=0,avoidCollisions:c=!0,collisionBoundary:u=[],collisionPadding:f=0,sticky:p="partial",hideWhenDetached:d=!1,updatePositionStrategy:h="optimized",onPlaced:m,...g}=e,w=CE(Py,n),[x,v]=y.useState(null),b=ut(t,Xe=>v(Xe)),[C,j]=y.useState(null),S=bE(C),N=(S==null?void 0:S.width)??0,E=(S==null?void 0:S.height)??0,A=r+(s!=="center"?"-"+s:""),F=typeof f=="number"?f:{top:0,right:0,bottom:0,left:0,...f},Z=Array.isArray(u)?u:[u],I=Z.length>0,q={padding:F,boundary:Z.filter(A$),altBoundary:I},{refs:H,floatingStyles:J,placement:re,isPositioned:K,middlewareData:z}=b$({strategy:"fixed",placement:A,whileElementsMounted:(...Xe)=>p$(...Xe,{animationFrame:h==="always"}),elements:{reference:w.anchor},middleware:[C$({mainAxis:o+E,alignmentAxis:i}),c&&j$({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?_$():void 0,...q}),c&&E$({...q}),T$({...q,apply:({elements:Xe,rects:Nt,availableWidth:Ut,availableHeight:$t})=>{const{width:Wt,height:_}=Nt.reference,M=Xe.floating.style;M.setProperty("--radix-popper-available-width",`${Ut}px`),M.setProperty("--radix-popper-available-height",`${$t}px`),M.setProperty("--radix-popper-anchor-width",`${Wt}px`),M.setProperty("--radix-popper-anchor-height",`${_}px`)}}),C&&k$({element:C,padding:l}),F$({arrowWidth:N,arrowHeight:E}),d&&N$({strategy:"referenceHidden",...q})]}),[L,te]=RE(re),fe=wr(m);bn(()=>{K&&(fe==null||fe())},[K,fe]);const B=(W=z.arrow)==null?void 0:W.x,ne=(we=z.arrow)==null?void 0:we.y,Q=((Pe=z.arrow)==null?void 0:Pe.centerOffset)!==0,[ie,oe]=y.useState();return bn(()=>{x&&oe(window.getComputedStyle(x).zIndex)},[x]),a.jsx("div",{ref:H.setFloating,"data-radix-popper-content-wrapper":"",style:{...J,transform:K?J.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ie,"--radix-popper-transform-origin":[(Fe=z.transformOrigin)==null?void 0:Fe.x,(Ie=z.transformOrigin)==null?void 0:Ie.y].join(" "),...((he=z.hide)==null?void 0:he.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:a.jsx(D$,{scope:n,placedSide:L,onArrowChange:j,arrowX:B,arrowY:ne,shouldHideArrow:Q,children:a.jsx(Ve.div,{"data-side":L,"data-align":te,...g,ref:b,style:{...g.style,animation:K?void 0:"none"}})})})});TE.displayName=Py;var NE="PopperArrow",M$={top:"bottom",right:"left",bottom:"top",left:"right"},kE=y.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=O$(NE,r),i=M$[s.placedSide];return a.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:a.jsx(P$,{...o,ref:n,style:{...o.style,display:"block"}})})});kE.displayName=NE;function A$(e){return e!==null}var F$=e=>({name:"transformOrigin",options:e,fn(t){var w,x,v;const{placement:n,rects:r,middlewareData:o}=t,i=((w=o.arrow)==null?void 0:w.centerOffset)!==0,l=i?0:e.arrowWidth,c=i?0:e.arrowHeight,[u,f]=RE(n),p={start:"0%",center:"50%",end:"100%"}[f],d=(((x=o.arrow)==null?void 0:x.x)??0)+l/2,h=(((v=o.arrow)==null?void 0:v.y)??0)+c/2;let m="",g="";return u==="bottom"?(m=i?p:`${d}px`,g=`${-c}px`):u==="top"?(m=i?p:`${d}px`,g=`${r.floating.height+c}px`):u==="right"?(m=`${-c}px`,g=i?p:`${h}px`):u==="left"&&(m=`${r.floating.width+c}px`,g=i?p:`${h}px`),{data:{x:m,y:g}}}});function RE(e){const[t,n="center"]=e.split("-");return[t,n]}var PE=jE,IE=EE,DE=TE,OE=kE;function ME(e){const t=y.useRef({value:e,previous:e});return y.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var L$="VisuallyHidden",AE=y.forwardRef((e,t)=>a.jsx(Ve.span,{...e,ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}));AE.displayName=L$;var $$=[" ","Enter","ArrowUp","ArrowDown"],z$=[" ","Enter"],cu="Select",[yp,xp,V$]=Cy(cu),[Ki,KK]=lo(cu,[V$,vp]),wp=vp(),[U$,Vs]=Ki(cu),[B$,H$]=Ki(cu),FE=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:s,value:i,defaultValue:l,onValueChange:c,dir:u,name:f,autoComplete:p,disabled:d,required:h}=e,m=wp(t),[g,w]=y.useState(null),[x,v]=y.useState(null),[b,C]=y.useState(!1),j=hp(u),[S=!1,N]=js({prop:r,defaultProp:o,onChange:s}),[E,A]=js({prop:i,defaultProp:l,onChange:c}),F=y.useRef(null),Z=g?!!g.closest("form"):!0,[I,q]=y.useState(new Set),H=Array.from(I).map(J=>J.props.value).join(";");return a.jsx(PE,{...m,children:a.jsxs(U$,{required:h,scope:t,trigger:g,onTriggerChange:w,valueNode:x,onValueNodeChange:v,valueNodeHasChildren:b,onValueNodeHasChildrenChange:C,contentId:Ir(),value:E,onValueChange:A,open:S,onOpenChange:N,dir:j,triggerPointerDownPosRef:F,disabled:d,children:[a.jsx(yp.Provider,{scope:t,children:a.jsx(B$,{scope:e.__scopeSelect,onNativeOptionAdd:y.useCallback(J=>{q(re=>new Set(re).add(J))},[]),onNativeOptionRemove:y.useCallback(J=>{q(re=>{const K=new Set(re);return K.delete(J),K})},[]),children:n})}),Z?a.jsxs(lT,{"aria-hidden":!0,required:h,tabIndex:-1,name:f,autoComplete:p,value:E,onChange:J=>A(J.target.value),disabled:d,children:[E===void 0?a.jsx("option",{value:""}):null,Array.from(I)]},H):null]})})};FE.displayName=cu;var LE="SelectTrigger",$E=y.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,s=wp(n),i=Vs(LE,n),l=i.disabled||r,c=ut(t,i.onTriggerChange),u=xp(n),[f,p,d]=cT(m=>{const g=u().filter(v=>!v.disabled),w=g.find(v=>v.value===i.value),x=uT(g,m,w);x!==void 0&&i.onValueChange(x.value)}),h=()=>{l||(i.onOpenChange(!0),d())};return a.jsx(IE,{asChild:!0,...s,children:a.jsx(Ve.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":iT(i.value)?"":void 0,...o,ref:c,onClick:je(o.onClick,m=>{m.currentTarget.focus()}),onPointerDown:je(o.onPointerDown,m=>{const g=m.target;g.hasPointerCapture(m.pointerId)&&g.releasePointerCapture(m.pointerId),m.button===0&&m.ctrlKey===!1&&(h(),i.triggerPointerDownPosRef.current={x:Math.round(m.pageX),y:Math.round(m.pageY)},m.preventDefault())}),onKeyDown:je(o.onKeyDown,m=>{const g=f.current!=="";!(m.ctrlKey||m.altKey||m.metaKey)&&m.key.length===1&&p(m.key),!(g&&m.key===" ")&&$$.includes(m.key)&&(h(),m.preventDefault())})})})});$E.displayName=LE;var zE="SelectValue",VE=y.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:s,placeholder:i="",...l}=e,c=Vs(zE,n),{onValueNodeHasChildrenChange:u}=c,f=s!==void 0,p=ut(t,c.onValueNodeChange);return bn(()=>{u(f)},[u,f]),a.jsx(Ve.span,{...l,ref:p,style:{pointerEvents:"none"},children:iT(c.value)?a.jsx(a.Fragment,{children:i}):s})});VE.displayName=zE;var G$="SelectIcon",UE=y.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return a.jsx(Ve.span,{"aria-hidden":!0,...o,ref:t,children:r||"▼"})});UE.displayName=G$;var W$="SelectPortal",BE=e=>a.jsx(lp,{asChild:!0,...e});BE.displayName=W$;var ba="SelectContent",HE=y.forwardRef((e,t)=>{const n=Vs(ba,e.__scopeSelect),[r,o]=y.useState();if(bn(()=>{o(new DocumentFragment)},[]),!n.open){const s=r;return s?Ls.createPortal(a.jsx(GE,{scope:e.__scopeSelect,children:a.jsx(yp.Slot,{scope:e.__scopeSelect,children:a.jsx("div",{children:e.children})})}),s):null}return a.jsx(WE,{...e,ref:t})});HE.displayName=ba;var vo=10,[GE,Us]=Ki(ba),K$="SelectContentImpl",WE=y.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:s,onPointerDownOutside:i,side:l,sideOffset:c,align:u,alignOffset:f,arrowPadding:p,collisionBoundary:d,collisionPadding:h,sticky:m,hideWhenDetached:g,avoidCollisions:w,...x}=e,v=Vs(ba,n),[b,C]=y.useState(null),[j,S]=y.useState(null),N=ut(t,W=>C(W)),[E,A]=y.useState(null),[F,Z]=y.useState(null),I=xp(n),[q,H]=y.useState(!1),J=y.useRef(!1);y.useEffect(()=>{if(b)return py(b)},[b]),fy();const re=y.useCallback(W=>{const[we,...Pe]=I().map(he=>he.ref.current),[Fe]=Pe.slice(-1),Ie=document.activeElement;for(const he of W)if(he===Ie||(he==null||he.scrollIntoView({block:"nearest"}),he===we&&j&&(j.scrollTop=0),he===Fe&&j&&(j.scrollTop=j.scrollHeight),he==null||he.focus(),document.activeElement!==Ie))return},[I,j]),K=y.useCallback(()=>re([E,b]),[re,E,b]);y.useEffect(()=>{q&&K()},[q,K]);const{onOpenChange:z,triggerPointerDownPosRef:L}=v;y.useEffect(()=>{if(b){let W={x:0,y:0};const we=Fe=>{var Ie,he;W={x:Math.abs(Math.round(Fe.pageX)-(((Ie=L.current)==null?void 0:Ie.x)??0)),y:Math.abs(Math.round(Fe.pageY)-(((he=L.current)==null?void 0:he.y)??0))}},Pe=Fe=>{W.x<=10&&W.y<=10?Fe.preventDefault():b.contains(Fe.target)||z(!1),document.removeEventListener("pointermove",we),L.current=null};return L.current!==null&&(document.addEventListener("pointermove",we),document.addEventListener("pointerup",Pe,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",we),document.removeEventListener("pointerup",Pe,{capture:!0})}}},[b,z,L]),y.useEffect(()=>{const W=()=>z(!1);return window.addEventListener("blur",W),window.addEventListener("resize",W),()=>{window.removeEventListener("blur",W),window.removeEventListener("resize",W)}},[z]);const[te,fe]=cT(W=>{const we=I().filter(Ie=>!Ie.disabled),Pe=we.find(Ie=>Ie.ref.current===document.activeElement),Fe=uT(we,W,Pe);Fe&&setTimeout(()=>Fe.ref.current.focus())}),B=y.useCallback((W,we,Pe)=>{const Fe=!J.current&&!Pe;(v.value!==void 0&&v.value===we||Fe)&&(A(W),Fe&&(J.current=!0))},[v.value]),ne=y.useCallback(()=>b==null?void 0:b.focus(),[b]),Q=y.useCallback((W,we,Pe)=>{const Fe=!J.current&&!Pe;(v.value!==void 0&&v.value===we||Fe)&&Z(W)},[v.value]),ie=r==="popper"?mm:KE,oe=ie===mm?{side:l,sideOffset:c,align:u,alignOffset:f,arrowPadding:p,collisionBoundary:d,collisionPadding:h,sticky:m,hideWhenDetached:g,avoidCollisions:w}:{};return a.jsx(GE,{scope:n,content:b,viewport:j,onViewportChange:S,itemRefCallback:B,selectedItem:E,onItemLeave:ne,itemTextRefCallback:Q,focusSelectedItem:K,selectedItemText:F,position:r,isPositioned:q,searchRef:te,children:a.jsx(up,{as:Oo,allowPinchZoom:!0,children:a.jsx(ip,{asChild:!0,trapped:v.open,onMountAutoFocus:W=>{W.preventDefault()},onUnmountAutoFocus:je(o,W=>{var we;(we=v.trigger)==null||we.focus({preventScroll:!0}),W.preventDefault()}),children:a.jsx(ap,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:W=>W.preventDefault(),onDismiss:()=>v.onOpenChange(!1),children:a.jsx(ie,{role:"listbox",id:v.contentId,"data-state":v.open?"open":"closed",dir:v.dir,onContextMenu:W=>W.preventDefault(),...x,...oe,onPlaced:()=>H(!0),ref:N,style:{display:"flex",flexDirection:"column",outline:"none",...x.style},onKeyDown:je(x.onKeyDown,W=>{const we=W.ctrlKey||W.altKey||W.metaKey;if(W.key==="Tab"&&W.preventDefault(),!we&&W.key.length===1&&fe(W.key),["ArrowUp","ArrowDown","Home","End"].includes(W.key)){let Fe=I().filter(Ie=>!Ie.disabled).map(Ie=>Ie.ref.current);if(["ArrowUp","End"].includes(W.key)&&(Fe=Fe.slice().reverse()),["ArrowUp","ArrowDown"].includes(W.key)){const Ie=W.target,he=Fe.indexOf(Ie);Fe=Fe.slice(he+1)}setTimeout(()=>re(Fe)),W.preventDefault()}})})})})})})});WE.displayName=K$;var q$="SelectItemAlignedPosition",KE=y.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,s=Vs(ba,n),i=Us(ba,n),[l,c]=y.useState(null),[u,f]=y.useState(null),p=ut(t,N=>f(N)),d=xp(n),h=y.useRef(!1),m=y.useRef(!0),{viewport:g,selectedItem:w,selectedItemText:x,focusSelectedItem:v}=i,b=y.useCallback(()=>{if(s.trigger&&s.valueNode&&l&&u&&g&&w&&x){const N=s.trigger.getBoundingClientRect(),E=u.getBoundingClientRect(),A=s.valueNode.getBoundingClientRect(),F=x.getBoundingClientRect();if(s.dir!=="rtl"){const Ie=F.left-E.left,he=A.left-Ie,Xe=N.left-he,Nt=N.width+Xe,Ut=Math.max(Nt,E.width),$t=window.innerWidth-vo,Wt=O0(he,[vo,$t-Ut]);l.style.minWidth=Nt+"px",l.style.left=Wt+"px"}else{const Ie=E.right-F.right,he=window.innerWidth-A.right-Ie,Xe=window.innerWidth-N.right-he,Nt=N.width+Xe,Ut=Math.max(Nt,E.width),$t=window.innerWidth-vo,Wt=O0(he,[vo,$t-Ut]);l.style.minWidth=Nt+"px",l.style.right=Wt+"px"}const Z=d(),I=window.innerHeight-vo*2,q=g.scrollHeight,H=window.getComputedStyle(u),J=parseInt(H.borderTopWidth,10),re=parseInt(H.paddingTop,10),K=parseInt(H.borderBottomWidth,10),z=parseInt(H.paddingBottom,10),L=J+re+q+z+K,te=Math.min(w.offsetHeight*5,L),fe=window.getComputedStyle(g),B=parseInt(fe.paddingTop,10),ne=parseInt(fe.paddingBottom,10),Q=N.top+N.height/2-vo,ie=I-Q,oe=w.offsetHeight/2,W=w.offsetTop+oe,we=J+re+W,Pe=L-we;if(we<=Q){const Ie=w===Z[Z.length-1].ref.current;l.style.bottom="0px";const he=u.clientHeight-g.offsetTop-g.offsetHeight,Xe=Math.max(ie,oe+(Ie?ne:0)+he+K),Nt=we+Xe;l.style.height=Nt+"px"}else{const Ie=w===Z[0].ref.current;l.style.top="0px";const Xe=Math.max(Q,J+g.offsetTop+(Ie?B:0)+oe)+Pe;l.style.height=Xe+"px",g.scrollTop=we-Q+g.offsetTop}l.style.margin=`${vo}px 0`,l.style.minHeight=te+"px",l.style.maxHeight=I+"px",r==null||r(),requestAnimationFrame(()=>h.current=!0)}},[d,s.trigger,s.valueNode,l,u,g,w,x,s.dir,r]);bn(()=>b(),[b]);const[C,j]=y.useState();bn(()=>{u&&j(window.getComputedStyle(u).zIndex)},[u]);const S=y.useCallback(N=>{N&&m.current===!0&&(b(),v==null||v(),m.current=!1)},[b,v]);return a.jsx(J$,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:h,onScrollButtonChange:S,children:a.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:C},children:a.jsx(Ve.div,{...o,ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});KE.displayName=q$;var Z$="SelectPopperPosition",mm=y.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=vo,...s}=e,i=wp(n);return a.jsx(DE,{...i,...s,ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});mm.displayName=Z$;var[J$,Iy]=Ki(ba,{}),vm="SelectViewport",qE=y.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...o}=e,s=Us(vm,n),i=Iy(vm,n),l=ut(t,s.onViewportChange),c=y.useRef(0);return a.jsxs(a.Fragment,{children:[a.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),a.jsx(yp.Slot,{scope:n,children:a.jsx(Ve.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:l,style:{position:"relative",flex:1,overflow:"auto",...o.style},onScroll:je(o.onScroll,u=>{const f=u.currentTarget,{contentWrapper:p,shouldExpandOnScrollRef:d}=i;if(d!=null&&d.current&&p){const h=Math.abs(c.current-f.scrollTop);if(h>0){const m=window.innerHeight-vo*2,g=parseFloat(p.style.minHeight),w=parseFloat(p.style.height),x=Math.max(g,w);if(x0?C:0,p.style.justifyContent="flex-end")}}}c.current=f.scrollTop})})})]})});qE.displayName=vm;var ZE="SelectGroup",[Y$,X$]=Ki(ZE),Q$=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ir();return a.jsx(Y$,{scope:n,id:o,children:a.jsx(Ve.div,{role:"group","aria-labelledby":o,...r,ref:t})})});Q$.displayName=ZE;var JE="SelectLabel",YE=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=X$(JE,n);return a.jsx(Ve.div,{id:o.id,...r,ref:t})});YE.displayName=JE;var hf="SelectItem",[e4,XE]=Ki(hf),QE=y.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:s,...i}=e,l=Vs(hf,n),c=Us(hf,n),u=l.value===r,[f,p]=y.useState(s??""),[d,h]=y.useState(!1),m=ut(t,x=>{var v;return(v=c.itemRefCallback)==null?void 0:v.call(c,x,r,o)}),g=Ir(),w=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return a.jsx(e4,{scope:n,value:r,disabled:o,textId:g,isSelected:u,onItemTextChange:y.useCallback(x=>{p(v=>v||((x==null?void 0:x.textContent)??"").trim())},[]),children:a.jsx(yp.ItemSlot,{scope:n,value:r,disabled:o,textValue:f,children:a.jsx(Ve.div,{role:"option","aria-labelledby":g,"data-highlighted":d?"":void 0,"aria-selected":u&&d,"data-state":u?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...i,ref:m,onFocus:je(i.onFocus,()=>h(!0)),onBlur:je(i.onBlur,()=>h(!1)),onPointerUp:je(i.onPointerUp,w),onPointerMove:je(i.onPointerMove,x=>{var v;o?(v=c.onItemLeave)==null||v.call(c):x.currentTarget.focus({preventScroll:!0})}),onPointerLeave:je(i.onPointerLeave,x=>{var v;x.currentTarget===document.activeElement&&((v=c.onItemLeave)==null||v.call(c))}),onKeyDown:je(i.onKeyDown,x=>{var b;((b=c.searchRef)==null?void 0:b.current)!==""&&x.key===" "||(z$.includes(x.key)&&w(),x.key===" "&&x.preventDefault())})})})})});QE.displayName=hf;var Ol="SelectItemText",eT=y.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...s}=e,i=Vs(Ol,n),l=Us(Ol,n),c=XE(Ol,n),u=H$(Ol,n),[f,p]=y.useState(null),d=ut(t,x=>p(x),c.onItemTextChange,x=>{var v;return(v=l.itemTextRefCallback)==null?void 0:v.call(l,x,c.value,c.disabled)}),h=f==null?void 0:f.textContent,m=y.useMemo(()=>a.jsx("option",{value:c.value,disabled:c.disabled,children:h},c.value),[c.disabled,c.value,h]),{onNativeOptionAdd:g,onNativeOptionRemove:w}=u;return bn(()=>(g(m),()=>w(m)),[g,w,m]),a.jsxs(a.Fragment,{children:[a.jsx(Ve.span,{id:c.textId,...s,ref:d}),c.isSelected&&i.valueNode&&!i.valueNodeHasChildren?Ls.createPortal(s.children,i.valueNode):null]})});eT.displayName=Ol;var tT="SelectItemIndicator",nT=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return XE(tT,n).isSelected?a.jsx(Ve.span,{"aria-hidden":!0,...r,ref:t}):null});nT.displayName=tT;var ym="SelectScrollUpButton",rT=y.forwardRef((e,t)=>{const n=Us(ym,e.__scopeSelect),r=Iy(ym,e.__scopeSelect),[o,s]=y.useState(!1),i=ut(t,r.onScrollButtonChange);return bn(()=>{if(n.viewport&&n.isPositioned){let l=function(){const u=c.scrollTop>0;s(u)};const c=n.viewport;return l(),c.addEventListener("scroll",l),()=>c.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),o?a.jsx(sT,{...e,ref:i,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=n;l&&c&&(l.scrollTop=l.scrollTop-c.offsetHeight)}}):null});rT.displayName=ym;var xm="SelectScrollDownButton",oT=y.forwardRef((e,t)=>{const n=Us(xm,e.__scopeSelect),r=Iy(xm,e.__scopeSelect),[o,s]=y.useState(!1),i=ut(t,r.onScrollButtonChange);return bn(()=>{if(n.viewport&&n.isPositioned){let l=function(){const u=c.scrollHeight-c.clientHeight,f=Math.ceil(c.scrollTop)c.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),o?a.jsx(sT,{...e,ref:i,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=n;l&&c&&(l.scrollTop=l.scrollTop+c.offsetHeight)}}):null});oT.displayName=xm;var sT=y.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,s=Us("SelectScrollButton",n),i=y.useRef(null),l=xp(n),c=y.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return y.useEffect(()=>()=>c(),[c]),bn(()=>{var f;const u=l().find(p=>p.ref.current===document.activeElement);(f=u==null?void 0:u.ref.current)==null||f.scrollIntoView({block:"nearest"})},[l]),a.jsx(Ve.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:je(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:je(o.onPointerMove,()=>{var u;(u=s.onItemLeave)==null||u.call(s),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:je(o.onPointerLeave,()=>{c()})})}),t4="SelectSeparator",aT=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return a.jsx(Ve.div,{"aria-hidden":!0,...r,ref:t})});aT.displayName=t4;var wm="SelectArrow",n4=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=wp(n),s=Vs(wm,n),i=Us(wm,n);return s.open&&i.position==="popper"?a.jsx(OE,{...o,...r,ref:t}):null});n4.displayName=wm;function iT(e){return e===""||e===void 0}var lT=y.forwardRef((e,t)=>{const{value:n,...r}=e,o=y.useRef(null),s=ut(t,o),i=ME(n);return y.useEffect(()=>{const l=o.current,c=window.HTMLSelectElement.prototype,f=Object.getOwnPropertyDescriptor(c,"value").set;if(i!==n&&f){const p=new Event("change",{bubbles:!0});f.call(l,n),l.dispatchEvent(p)}},[i,n]),a.jsx(AE,{asChild:!0,children:a.jsx("select",{...r,ref:s,defaultValue:n})})});lT.displayName="BubbleSelect";function cT(e){const t=wr(e),n=y.useRef(""),r=y.useRef(0),o=y.useCallback(i=>{const l=n.current+i;t(l),function c(u){n.current=u,window.clearTimeout(r.current),u!==""&&(r.current=window.setTimeout(()=>c(""),1e3))}(l)},[t]),s=y.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return y.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,s]}function uT(e,t,n){const o=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=r4(e,Math.max(s,0));o.length===1&&(i=i.filter(u=>u!==n));const c=i.find(u=>u.textValue.toLowerCase().startsWith(o.toLowerCase()));return c!==n?c:void 0}function r4(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var o4=FE,dT=$E,s4=VE,a4=UE,i4=BE,fT=HE,l4=qE,pT=YE,hT=QE,c4=eT,u4=nT,gT=rT,mT=oT,vT=aT;const St=o4,Ct=s4,mt=y.forwardRef(({className:e,children:t,...n},r)=>a.jsxs(dT,{ref:r,className:Re("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,a.jsx(a4,{asChild:!0,children:a.jsx(Qf,{className:"h-4 w-4 opacity-50"})})]}));mt.displayName=dT.displayName;const yT=y.forwardRef(({className:e,...t},n)=>a.jsx(gT,{ref:n,className:Re("flex cursor-default items-center justify-center py-1",e),...t,children:a.jsx(oA,{className:"h-4 w-4"})}));yT.displayName=gT.displayName;const xT=y.forwardRef(({className:e,...t},n)=>a.jsx(mT,{ref:n,className:Re("flex cursor-default items-center justify-center py-1",e),...t,children:a.jsx(Qf,{className:"h-4 w-4"})}));xT.displayName=mT.displayName;const vt=y.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>a.jsx(i4,{children:a.jsxs(fT,{ref:o,className:Re("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[a.jsx(yT,{}),a.jsx(l4,{className:Re("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),a.jsx(xT,{})]})}));vt.displayName=fT.displayName;const d4=y.forwardRef(({className:e,...t},n)=>a.jsx(pT,{ref:n,className:Re("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));d4.displayName=pT.displayName;const me=y.forwardRef(({className:e,children:t,...n},r)=>a.jsxs(hT,{ref:r,className:Re("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[a.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a.jsx(u4,{children:a.jsx(ai,{className:"h-4 w-4"})})}),a.jsx(c4,{children:t})]}));me.displayName=hT.displayName;const f4=y.forwardRef(({className:e,...t},n)=>a.jsx(vT,{ref:n,className:Re("-mx-1 my-1 h-px bg-muted",e),...t}));f4.displayName=vT.displayName;const Nc=e=>typeof e=="number"&&!isNaN(e),ca=e=>typeof e=="string",Xn=e=>typeof e=="function",bd=e=>ca(e)||Xn(e)?e:null,bm=e=>y.isValidElement(e)||ca(e)||Xn(e)||Nc(e);function p4(e,t,n){n===void 0&&(n=300);const{scrollHeight:r,style:o}=e;requestAnimationFrame(()=>{o.minHeight="initial",o.height=r+"px",o.transition=`all ${n}ms`,requestAnimationFrame(()=>{o.height="0",o.padding="0",o.margin="0",setTimeout(t,n)})})}function bp(e){let{enter:t,exit:n,appendPosition:r=!1,collapse:o=!0,collapseDuration:s=300}=e;return function(i){let{children:l,position:c,preventExitTransition:u,done:f,nodeRef:p,isIn:d,playToast:h}=i;const m=r?`${t}--${c}`:t,g=r?`${n}--${c}`:n,w=y.useRef(0);return y.useLayoutEffect(()=>{const x=p.current,v=m.split(" "),b=C=>{C.target===p.current&&(h(),x.removeEventListener("animationend",b),x.removeEventListener("animationcancel",b),w.current===0&&C.type!=="animationcancel"&&x.classList.remove(...v))};x.classList.add(...v),x.addEventListener("animationend",b),x.addEventListener("animationcancel",b)},[]),y.useEffect(()=>{const x=p.current,v=()=>{x.removeEventListener("animationend",v),o?p4(x,f,s):f()};d||(u?v():(w.current=1,x.className+=` ${g}`,x.addEventListener("animationend",v)))},[d]),Se.createElement(Se.Fragment,null,l)}}function H0(e,t){return e!=null?{content:e.content,containerId:e.props.containerId,id:e.props.toastId,theme:e.props.theme,type:e.props.type,data:e.props.data||{},isLoading:e.props.isLoading,icon:e.props.icon,status:t}:{}}const kn=new Map;let kc=[];const Sm=new Set,h4=e=>Sm.forEach(t=>t(e)),wT=()=>kn.size>0;function bT(e,t){var n;if(t)return!((n=kn.get(t))==null||!n.isToastActive(e));let r=!1;return kn.forEach(o=>{o.isToastActive(e)&&(r=!0)}),r}function ST(e,t){bm(e)&&(wT()||kc.push({content:e,options:t}),kn.forEach(n=>{n.buildToast(e,t)}))}function G0(e,t){kn.forEach(n=>{t!=null&&t!=null&&t.containerId?(t==null?void 0:t.containerId)===n.id&&n.toggle(e,t==null?void 0:t.id):n.toggle(e,t==null?void 0:t.id)})}function g4(e){const{subscribe:t,getSnapshot:n,setProps:r}=y.useRef(function(s){const i=s.containerId||1;return{subscribe(l){const c=function(f,p,d){let h=1,m=0,g=[],w=[],x=[],v=p;const b=new Map,C=new Set,j=()=>{x=Array.from(b.values()),C.forEach(E=>E())},S=E=>{w=E==null?[]:w.filter(A=>A!==E),j()},N=E=>{const{toastId:A,onOpen:F,updateId:Z,children:I}=E.props,q=Z==null;E.staleId&&b.delete(E.staleId),b.set(A,E),w=[...w,E.props.toastId].filter(H=>H!==E.staleId),j(),d(H0(E,q?"added":"updated")),q&&Xn(F)&&F(y.isValidElement(I)&&I.props)};return{id:f,props:v,observe:E=>(C.add(E),()=>C.delete(E)),toggle:(E,A)=>{b.forEach(F=>{A!=null&&A!==F.props.toastId||Xn(F.toggle)&&F.toggle(E)})},removeToast:S,toasts:b,clearQueue:()=>{m-=g.length,g=[]},buildToast:(E,A)=>{if((B=>{let{containerId:ne,toastId:Q,updateId:ie}=B;const oe=ne?ne!==f:f!==1,W=b.has(Q)&&ie==null;return oe||W})(A))return;const{toastId:F,updateId:Z,data:I,staleId:q,delay:H}=A,J=()=>{S(F)},re=Z==null;re&&m++;const K={...v,style:v.toastStyle,key:h++,...Object.fromEntries(Object.entries(A).filter(B=>{let[ne,Q]=B;return Q!=null})),toastId:F,updateId:Z,data:I,closeToast:J,isIn:!1,className:bd(A.className||v.toastClassName),bodyClassName:bd(A.bodyClassName||v.bodyClassName),progressClassName:bd(A.progressClassName||v.progressClassName),autoClose:!A.isLoading&&(z=A.autoClose,L=v.autoClose,z===!1||Nc(z)&&z>0?z:L),deleteToast(){const B=b.get(F),{onClose:ne,children:Q}=B.props;Xn(ne)&&ne(y.isValidElement(Q)&&Q.props),d(H0(B,"removed")),b.delete(F),m--,m<0&&(m=0),g.length>0?N(g.shift()):j()}};var z,L;K.closeButton=v.closeButton,A.closeButton===!1||bm(A.closeButton)?K.closeButton=A.closeButton:A.closeButton===!0&&(K.closeButton=!bm(v.closeButton)||v.closeButton);let te=E;y.isValidElement(E)&&!ca(E.type)?te=y.cloneElement(E,{closeToast:J,toastProps:K,data:I}):Xn(E)&&(te=E({closeToast:J,toastProps:K,data:I}));const fe={content:te,props:K,staleId:q};v.limit&&v.limit>0&&m>v.limit&&re?g.push(fe):Nc(H)?setTimeout(()=>{N(fe)},H):N(fe)},setProps(E){v=E},setToggle:(E,A)=>{b.get(E).toggle=A},isToastActive:E=>w.some(A=>A===E),getSnapshot:()=>v.newestOnTop?x.reverse():x}}(i,s,h4);kn.set(i,c);const u=c.observe(l);return kc.forEach(f=>ST(f.content,f.options)),kc=[],()=>{u(),kn.delete(i)}},setProps(l){var c;(c=kn.get(i))==null||c.setProps(l)},getSnapshot(){var l;return(l=kn.get(i))==null?void 0:l.getSnapshot()}}}(e)).current;r(e);const o=y.useSyncExternalStore(t,n,n);return{getToastToRender:function(s){if(!o)return[];const i=new Map;return o.forEach(l=>{const{position:c}=l.props;i.has(c)||i.set(c,[]),i.get(c).push(l)}),Array.from(i,l=>s(l[0],l[1]))},isToastActive:bT,count:o==null?void 0:o.length}}function m4(e){const[t,n]=y.useState(!1),[r,o]=y.useState(!1),s=y.useRef(null),i=y.useRef({start:0,delta:0,removalDistance:0,canCloseOnClick:!0,canDrag:!1,didMove:!1}).current,{autoClose:l,pauseOnHover:c,closeToast:u,onClick:f,closeOnClick:p}=e;var d,h;function m(){n(!0)}function g(){n(!1)}function w(b){const C=s.current;i.canDrag&&C&&(i.didMove=!0,t&&g(),i.delta=e.draggableDirection==="x"?b.clientX-i.start:b.clientY-i.start,i.start!==b.clientX&&(i.canCloseOnClick=!1),C.style.transform=`translate3d(${e.draggableDirection==="x"?`${i.delta}px, var(--y)`:`0, calc(${i.delta}px + var(--y))`},0)`,C.style.opacity=""+(1-Math.abs(i.delta/i.removalDistance)))}function x(){document.removeEventListener("pointermove",w),document.removeEventListener("pointerup",x);const b=s.current;if(i.canDrag&&i.didMove&&b){if(i.canDrag=!1,Math.abs(i.delta)>i.removalDistance)return o(!0),e.closeToast(),void e.collapseAll();b.style.transition="transform 0.2s, opacity 0.2s",b.style.removeProperty("transform"),b.style.removeProperty("opacity")}}(h=kn.get((d={id:e.toastId,containerId:e.containerId,fn:n}).containerId||1))==null||h.setToggle(d.id,d.fn),y.useEffect(()=>{if(e.pauseOnFocusLoss)return document.hasFocus()||g(),window.addEventListener("focus",m),window.addEventListener("blur",g),()=>{window.removeEventListener("focus",m),window.removeEventListener("blur",g)}},[e.pauseOnFocusLoss]);const v={onPointerDown:function(b){if(e.draggable===!0||e.draggable===b.pointerType){i.didMove=!1,document.addEventListener("pointermove",w),document.addEventListener("pointerup",x);const C=s.current;i.canCloseOnClick=!0,i.canDrag=!0,C.style.transition="none",e.draggableDirection==="x"?(i.start=b.clientX,i.removalDistance=C.offsetWidth*(e.draggablePercent/100)):(i.start=b.clientY,i.removalDistance=C.offsetHeight*(e.draggablePercent===80?1.5*e.draggablePercent:e.draggablePercent)/100)}},onPointerUp:function(b){const{top:C,bottom:j,left:S,right:N}=s.current.getBoundingClientRect();b.nativeEvent.type!=="touchend"&&e.pauseOnHover&&b.clientX>=S&&b.clientX<=N&&b.clientY>=C&&b.clientY<=j?g():m()}};return l&&c&&(v.onMouseEnter=g,e.stacked||(v.onMouseLeave=m)),p&&(v.onClick=b=>{f&&f(b),i.canCloseOnClick&&u()}),{playToast:m,pauseToast:g,isRunning:t,preventExitTransition:r,toastRef:s,eventHandlers:v}}function v4(e){let{delay:t,isRunning:n,closeToast:r,type:o="default",hide:s,className:i,style:l,controlledProgress:c,progress:u,rtl:f,isIn:p,theme:d}=e;const h=s||c&&u===0,m={...l,animationDuration:`${t}ms`,animationPlayState:n?"running":"paused"};c&&(m.transform=`scaleX(${u})`);const g=jo("Toastify__progress-bar",c?"Toastify__progress-bar--controlled":"Toastify__progress-bar--animated",`Toastify__progress-bar-theme--${d}`,`Toastify__progress-bar--${o}`,{"Toastify__progress-bar--rtl":f}),w=Xn(i)?i({rtl:f,type:o,defaultClassName:g}):jo(g,i),x={[c&&u>=1?"onTransitionEnd":"onAnimationEnd"]:c&&u<1?null:()=>{p&&r()}};return Se.createElement("div",{className:"Toastify__progress-bar--wrp","data-hidden":h},Se.createElement("div",{className:`Toastify__progress-bar--bg Toastify__progress-bar-theme--${d} Toastify__progress-bar--${o}`}),Se.createElement("div",{role:"progressbar","aria-hidden":h?"true":"false","aria-label":"notification timer",className:w,style:m,...x}))}let y4=1;const CT=()=>""+y4++;function x4(e){return e&&(ca(e.toastId)||Nc(e.toastId))?e.toastId:CT()}function Ql(e,t){return ST(e,t),t.toastId}function gf(e,t){return{...t,type:t&&t.type||e,toastId:x4(t)}}function qu(e){return(t,n)=>Ql(t,gf(e,n))}function lt(e,t){return Ql(e,gf("default",t))}lt.loading=(e,t)=>Ql(e,gf("default",{isLoading:!0,autoClose:!1,closeOnClick:!1,closeButton:!1,draggable:!1,...t})),lt.promise=function(e,t,n){let r,{pending:o,error:s,success:i}=t;o&&(r=ca(o)?lt.loading(o,n):lt.loading(o.render,{...n,...o}));const l={isLoading:null,autoClose:null,closeOnClick:null,closeButton:null,draggable:null},c=(f,p,d)=>{if(p==null)return void lt.dismiss(r);const h={type:f,...l,...n,data:d},m=ca(p)?{render:p}:p;return r?lt.update(r,{...h,...m}):lt(m.render,{...h,...m}),d},u=Xn(e)?e():e;return u.then(f=>c("success",i,f)).catch(f=>c("error",s,f)),u},lt.success=qu("success"),lt.info=qu("info"),lt.error=qu("error"),lt.warning=qu("warning"),lt.warn=lt.warning,lt.dark=(e,t)=>Ql(e,gf("default",{theme:"dark",...t})),lt.dismiss=function(e){(function(t){var n;if(wT()){if(t==null||ca(n=t)||Nc(n))kn.forEach(r=>{r.removeToast(t)});else if(t&&("containerId"in t||"id"in t)){const r=kn.get(t.containerId);r?r.removeToast(t.id):kn.forEach(o=>{o.removeToast(t.id)})}}else kc=kc.filter(r=>t!=null&&r.options.toastId!==t)})(e)},lt.clearWaitingQueue=function(e){e===void 0&&(e={}),kn.forEach(t=>{!t.props.limit||e.containerId&&t.id!==e.containerId||t.clearQueue()})},lt.isActive=bT,lt.update=function(e,t){t===void 0&&(t={});const n=((r,o)=>{var s;let{containerId:i}=o;return(s=kn.get(i||1))==null?void 0:s.toasts.get(r)})(e,t);if(n){const{props:r,content:o}=n,s={delay:100,...r,...t,toastId:t.toastId||e,updateId:CT()};s.toastId!==e&&(s.staleId=e);const i=s.render||o;delete s.render,Ql(i,s)}},lt.done=e=>{lt.update(e,{progress:1})},lt.onChange=function(e){return Sm.add(e),()=>{Sm.delete(e)}},lt.play=e=>G0(!0,e),lt.pause=e=>G0(!1,e);const w4=typeof window<"u"?y.useLayoutEffect:y.useEffect,Zu=e=>{let{theme:t,type:n,isLoading:r,...o}=e;return Se.createElement("svg",{viewBox:"0 0 24 24",width:"100%",height:"100%",fill:t==="colored"?"currentColor":`var(--toastify-icon-color-${n})`,...o})},Fh={info:function(e){return Se.createElement(Zu,{...e},Se.createElement("path",{d:"M12 0a12 12 0 1012 12A12.013 12.013 0 0012 0zm.25 5a1.5 1.5 0 11-1.5 1.5 1.5 1.5 0 011.5-1.5zm2.25 13.5h-4a1 1 0 010-2h.75a.25.25 0 00.25-.25v-4.5a.25.25 0 00-.25-.25h-.75a1 1 0 010-2h1a2 2 0 012 2v4.75a.25.25 0 00.25.25h.75a1 1 0 110 2z"}))},warning:function(e){return Se.createElement(Zu,{...e},Se.createElement("path",{d:"M23.32 17.191L15.438 2.184C14.728.833 13.416 0 11.996 0c-1.42 0-2.733.833-3.443 2.184L.533 17.448a4.744 4.744 0 000 4.368C1.243 23.167 2.555 24 3.975 24h16.05C22.22 24 24 22.044 24 19.632c0-.904-.251-1.746-.68-2.44zm-9.622 1.46c0 1.033-.724 1.823-1.698 1.823s-1.698-.79-1.698-1.822v-.043c0-1.028.724-1.822 1.698-1.822s1.698.79 1.698 1.822v.043zm.039-12.285l-.84 8.06c-.057.581-.408.943-.897.943-.49 0-.84-.367-.896-.942l-.84-8.065c-.057-.624.25-1.095.779-1.095h1.91c.528.005.84.476.784 1.1z"}))},success:function(e){return Se.createElement(Zu,{...e},Se.createElement("path",{d:"M12 0a12 12 0 1012 12A12.014 12.014 0 0012 0zm6.927 8.2l-6.845 9.289a1.011 1.011 0 01-1.43.188l-4.888-3.908a1 1 0 111.25-1.562l4.076 3.261 6.227-8.451a1 1 0 111.61 1.183z"}))},error:function(e){return Se.createElement(Zu,{...e},Se.createElement("path",{d:"M11.983 0a12.206 12.206 0 00-8.51 3.653A11.8 11.8 0 000 12.207 11.779 11.779 0 0011.8 24h.214A12.111 12.111 0 0024 11.791 11.766 11.766 0 0011.983 0zM10.5 16.542a1.476 1.476 0 011.449-1.53h.027a1.527 1.527 0 011.523 1.47 1.475 1.475 0 01-1.449 1.53h-.027a1.529 1.529 0 01-1.523-1.47zM11 12.5v-6a1 1 0 012 0v6a1 1 0 11-2 0z"}))},spinner:function(){return Se.createElement("div",{className:"Toastify__spinner"})}},b4=e=>{const{isRunning:t,preventExitTransition:n,toastRef:r,eventHandlers:o,playToast:s}=m4(e),{closeButton:i,children:l,autoClose:c,onClick:u,type:f,hideProgressBar:p,closeToast:d,transition:h,position:m,className:g,style:w,bodyClassName:x,bodyStyle:v,progressClassName:b,progressStyle:C,updateId:j,role:S,progress:N,rtl:E,toastId:A,deleteToast:F,isIn:Z,isLoading:I,closeOnClick:q,theme:H}=e,J=jo("Toastify__toast",`Toastify__toast-theme--${H}`,`Toastify__toast--${f}`,{"Toastify__toast--rtl":E},{"Toastify__toast--close-on-click":q}),re=Xn(g)?g({rtl:E,position:m,type:f,defaultClassName:J}):jo(J,g),K=function(fe){let{theme:B,type:ne,isLoading:Q,icon:ie}=fe,oe=null;const W={theme:B,type:ne};return ie===!1||(Xn(ie)?oe=ie({...W,isLoading:Q}):y.isValidElement(ie)?oe=y.cloneElement(ie,W):Q?oe=Fh.spinner():(we=>we in Fh)(ne)&&(oe=Fh[ne](W))),oe}(e),z=!!N||!c,L={closeToast:d,type:f,theme:H};let te=null;return i===!1||(te=Xn(i)?i(L):y.isValidElement(i)?y.cloneElement(i,L):function(fe){let{closeToast:B,theme:ne,ariaLabel:Q="close"}=fe;return Se.createElement("button",{className:`Toastify__close-button Toastify__close-button--${ne}`,type:"button",onClick:ie=>{ie.stopPropagation(),B(ie)},"aria-label":Q},Se.createElement("svg",{"aria-hidden":"true",viewBox:"0 0 14 16"},Se.createElement("path",{fillRule:"evenodd",d:"M7.71 8.23l3.75 3.75-1.48 1.48-3.75-3.75-3.75 3.75L1 11.98l3.75-3.75L1 4.48 2.48 3l3.75 3.75L9.98 3l1.48 1.48-3.75 3.75z"})))}(L)),Se.createElement(h,{isIn:Z,done:F,position:m,preventExitTransition:n,nodeRef:r,playToast:s},Se.createElement("div",{id:A,onClick:u,"data-in":Z,className:re,...o,style:w,ref:r},Se.createElement("div",{...Z&&{role:S},className:Xn(x)?x({type:f}):jo("Toastify__toast-body",x),style:v},K!=null&&Se.createElement("div",{className:jo("Toastify__toast-icon",{"Toastify--animate-icon Toastify__zoom-enter":!I})},K),Se.createElement("div",null,l)),te,Se.createElement(v4,{...j&&!z?{key:`pb-${j}`}:{},rtl:E,theme:H,delay:c,isRunning:t,isIn:Z,closeToast:d,hide:p,type:f,style:C,className:b,controlledProgress:z,progress:N||0})))},Sp=function(e,t){return t===void 0&&(t=!1),{enter:`Toastify--animate Toastify__${e}-enter`,exit:`Toastify--animate Toastify__${e}-exit`,appendPosition:t}},S4=bp(Sp("bounce",!0));bp(Sp("slide",!0));bp(Sp("zoom"));bp(Sp("flip"));const C4={position:"top-right",transition:S4,autoClose:5e3,closeButton:!0,pauseOnHover:!0,pauseOnFocusLoss:!0,draggable:"touch",draggablePercent:80,draggableDirection:"x",role:"alert",theme:"light"};function j4(e){let t={...C4,...e};const n=e.stacked,[r,o]=y.useState(!0),s=y.useRef(null),{getToastToRender:i,isToastActive:l,count:c}=g4(t),{className:u,style:f,rtl:p,containerId:d}=t;function h(g){const w=jo("Toastify__toast-container",`Toastify__toast-container--${g}`,{"Toastify__toast-container--rtl":p});return Xn(u)?u({position:g,rtl:p,defaultClassName:w}):jo(w,bd(u))}function m(){n&&(o(!0),lt.play())}return w4(()=>{if(n){var g;const w=s.current.querySelectorAll('[data-in="true"]'),x=12,v=(g=t.position)==null?void 0:g.includes("top");let b=0,C=0;Array.from(w).reverse().forEach((j,S)=>{const N=j;N.classList.add("Toastify__toast--stacked"),S>0&&(N.dataset.collapsed=`${r}`),N.dataset.pos||(N.dataset.pos=v?"top":"bot");const E=b*(r?.2:1)+(r?0:x*S);N.style.setProperty("--y",`${v?E:-1*E}px`),N.style.setProperty("--g",`${x}`),N.style.setProperty("--s",""+(1-(r?C:0))),b+=N.offsetHeight,C+=.025})}},[r,c,n]),Se.createElement("div",{ref:s,className:"Toastify",id:d,onMouseEnter:()=>{n&&(o(!1),lt.pause())},onMouseLeave:m},i((g,w)=>{const x=w.length?{...f}:{...f,pointerEvents:"none"};return Se.createElement("div",{className:h(g),style:x,key:`container-${g}`},w.map(v=>{let{content:b,props:C}=v;return Se.createElement(b4,{...C,stacked:n,collapseAll:m,isIn:l(C.toastId,C.containerId),style:C.style,key:`toast-${C.key}`},b)}))}))}class _4{constructor(){this.defaultOptions={position:"top-right",autoClose:5e3,hideProgressBar:!1,closeOnClick:!0,pauseOnHover:!0,draggable:!0,progress:void 0,theme:"colored"}}success(t,n){lt.success(t,{...this.defaultOptions,...n})}error(t,n){lt.error(t,{...this.defaultOptions,...n})}info(t,n){lt.info(t,{...this.defaultOptions,...n})}warning(t,n){lt.warning(t,{...this.defaultOptions,...n})}}const ke=new _4,W0=(e,t,n)=>{if(e&&"reportValidity"in e){const r=ue(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},jT=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?W0(r.ref,n,e):r.refs&&r.refs.forEach(o=>W0(o,n,e))}},E4=(e,t)=>{t.shouldUseNativeValidation&&jT(e,t);const n={};for(const r in e){const o=ue(t.fields,r),s=Object.assign(e[r]||{},{ref:o&&o.ref});if(T4(t.names||Object.keys(e),r)){const i=Object.assign({},ue(n,r));at(i,"root",s),at(n,r,i)}else at(n,r,s)}return n},T4=(e,t)=>e.some(n=>n.startsWith(t+"."));var N4=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,s=r.message,i=r.path.join(".");if(!n[i])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[i]={message:l.message,type:l.code}}else n[i]={message:s,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(f){return f.errors.forEach(function(p){return e.push(p)})}),t){var c=n[i].types,u=c&&c[r.code];n[i]=eE(i,t,n,o,u?[].concat(u,r.message):r.message)}e.shift()}return n},nn=function(e,t,n){return n===void 0&&(n={}),function(r,o,s){try{return Promise.resolve(function(i,l){try{var c=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(u){return s.shouldUseNativeValidation&&jT({},s),{errors:{},values:n.raw?r:u}})}catch(u){return l(u)}return c&&c.then?c.then(void 0,l):c}(0,function(i){if(function(l){return Array.isArray(l==null?void 0:l.errors)}(i))return{values:{},errors:E4(N4(i.errors,!s.shouldUseNativeValidation&&s.criteriaMode==="all"),s)};throw i}))}catch(i){return Promise.reject(i)}}},tt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const s={};for(const i of o)s[i]=i;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),i={};for(const l of s)i[l]=o[l];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},e.find=(o,s)=>{for(const i of o)if(s(i))return i},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(tt||(tt={}));var Cm;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Cm||(Cm={}));const ye=tt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),cs=e=>{switch(typeof e){case"undefined":return ye.undefined;case"string":return ye.string;case"number":return isNaN(e)?ye.nan:ye.number;case"boolean":return ye.boolean;case"function":return ye.function;case"bigint":return ye.bigint;case"symbol":return ye.symbol;case"object":return Array.isArray(e)?ye.array:e===null?ye.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?ye.promise:typeof Map<"u"&&e instanceof Map?ye.map:typeof Set<"u"&&e instanceof Set?ye.set:typeof Date<"u"&&e instanceof Date?ye.date:ye.object;default:return ye.unknown}},ee=tt.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"]),k4=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class tr extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(const i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let l=r,c=0;for(;cn.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}tr.create=e=>new tr(e);const Di=(e,t)=>{let n;switch(e.code){case ee.invalid_type:e.received===ye.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case ee.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,tt.jsonStringifyReplacer)}`;break;case ee.unrecognized_keys:n=`Unrecognized key(s) in object: ${tt.joinValues(e.keys,", ")}`;break;case ee.invalid_union:n="Invalid input";break;case ee.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${tt.joinValues(e.options)}`;break;case ee.invalid_enum_value:n=`Invalid enum value. Expected ${tt.joinValues(e.options)}, received '${e.received}'`;break;case ee.invalid_arguments:n="Invalid function arguments";break;case ee.invalid_return_type:n="Invalid function return type";break;case ee.invalid_date:n="Invalid date";break;case ee.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:tt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case ee.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case ee.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case ee.custom:n="Invalid input";break;case ee.invalid_intersection_types:n="Intersection results could not be merged";break;case ee.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case ee.not_finite:n="Number must be finite";break;default:n=t.defaultError,tt.assertNever(e)}return{message:n}};let _T=Di;function R4(e){_T=e}function mf(){return _T}const vf=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let l="";const c=r.filter(u=>!!u).slice().reverse();for(const u of c)l=u(i,{data:t,defaultError:l}).message;return{...o,path:s,message:l}},P4=[];function ge(e,t){const n=mf(),r=vf({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Di?void 0:Di].filter(o=>!!o)});e.common.issues.push(r)}class jn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return $e;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n){const s=await o.key,i=await o.value;r.push({key:s,value:i})}return jn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return $e;s.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:t.value,value:r}}}const $e=Object.freeze({status:"aborted"}),ci=e=>({status:"dirty",value:e}),Pn=e=>({status:"valid",value:e}),jm=e=>e.status==="aborted",_m=e=>e.status==="dirty",Rc=e=>e.status==="valid",Pc=e=>typeof Promise<"u"&&e instanceof Promise;function yf(e,t,n,r){if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function ET(e,t,n,r,o){if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var Ee;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Ee||(Ee={}));var Ml,Al;class ao{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const K0=(e,t)=>{if(Rc(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new tr(e.common.issues);return this._error=n,this._error}}};function He(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,l)=>{var c,u;const{message:f}=e;return i.code==="invalid_enum_value"?{message:f??l.defaultError}:typeof l.data>"u"?{message:(c=f??r)!==null&&c!==void 0?c:l.defaultError}:i.code!=="invalid_type"?{message:l.defaultError}:{message:(u=f??n)!==null&&u!==void 0?u:l.defaultError}},description:o}}class qe{constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return cs(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:cs(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new jn,ctx:{common:t.parent.common,data:t.data,parsedType:cs(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(Pc(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const o={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:cs(t)},s=this._parseSync({data:t,path:o.path,parent:o});return K0(o,s)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:cs(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(Pc(o)?o:Promise.resolve(o));return K0(r,s)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{const i=t(o),l=()=>s.addIssue({code:ee.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(l(),!1)):i?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Lr({schema:this,typeName:Ae.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return no.create(this,this._def)}nullable(){return Ps.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Or.create(this,this._def)}promise(){return Mi.create(this,this._def)}or(t){return Mc.create([this,t],this._def)}and(t){return Ac.create(this,t,this._def)}transform(t){return new Lr({...He(this._def),schema:this,typeName:Ae.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Vc({...He(this._def),innerType:this,defaultValue:n,typeName:Ae.ZodDefault})}brand(){return new Dy({typeName:Ae.ZodBranded,type:this,...He(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Uc({...He(this._def),innerType:this,catchValue:n,typeName:Ae.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return uu.create(this,t)}readonly(){return Bc.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const I4=/^c[^\s-]{8,}$/i,D4=/^[0-9a-z]+$/,O4=/^[0-9A-HJKMNP-TV-Z]{26}$/,M4=/^[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,A4=/^[a-z0-9_-]{21}$/i,F4=/^[-+]?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)?)??$/,L4=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,$4="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Lh;const z4=/^(?:(?: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])$/,V4=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,U4=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,TT="((\\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])))",B4=new RegExp(`^${TT}$`);function NT(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`),t}function H4(e){return new RegExp(`^${NT(e)}$`)}function kT(e){let t=`${TT}T${NT(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function G4(e,t){return!!((t==="v4"||!t)&&z4.test(e)||(t==="v6"||!t)&&V4.test(e))}class Nr extends qe{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ye.string){const s=this._getOrReturnCtx(t);return ge(s,{code:ee.invalid_type,expected:ye.string,received:s.parsedType}),$e}const r=new jn;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.lengths.value&&(o=this._getOrReturnCtx(t,o),ge(o,{code:ee.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const i=t.data.length>s.value,l=t.data.lengtht.test(o),{validation:n,code:ee.invalid_string,...Ee.errToObj(r)})}_addCheck(t){return new Nr({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ee.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ee.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ee.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ee.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Ee.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ee.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ee.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ee.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Ee.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ee.errToObj(t)})}datetime(t){var n,r;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,local:(r=t==null?void 0:t.local)!==null&&r!==void 0?r:!1,...Ee.errToObj(t==null?void 0:t.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,...Ee.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...Ee.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Ee.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...Ee.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Ee.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Ee.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Ee.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Ee.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Ee.errToObj(n)})}nonempty(t){return this.min(1,Ee.errToObj(t))}trim(){return new Nr({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Nr({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Nr({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new Nr({checks:[],typeName:Ae.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...He(e)})};function W4(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=parseInt(e.toFixed(o).replace(".","")),i=parseInt(t.toFixed(o).replace(".",""));return s%i/Math.pow(10,o)}class Ns extends qe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==ye.number){const s=this._getOrReturnCtx(t);return ge(s,{code:ee.invalid_type,expected:ye.number,received:s.parsedType}),$e}let r;const o=new jn;for(const s of this._def.checks)s.kind==="int"?tt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),ge(r,{code:ee.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.datas.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),ge(r,{code:ee.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?W4(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),ge(r,{code:ee.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),ge(r,{code:ee.not_finite,message:s.message}),o.dirty()):tt.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ee.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ee.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ee.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ee.toString(n))}setLimit(t,n,r,o){return new Ns({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ee.toString(o)}]})}_addCheck(t){return new Ns({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ee.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ee.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ee.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ee.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ee.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ee.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Ee.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ee.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ee.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&tt.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.valuenew Ns({checks:[],typeName:Ae.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...He(e)});class ks extends qe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==ye.bigint){const s=this._getOrReturnCtx(t);return ge(s,{code:ee.invalid_type,expected:ye.bigint,received:s.parsedType}),$e}let r;const o=new jn;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.datas.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),ge(r,{code:ee.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),ge(r,{code:ee.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):tt.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ee.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ee.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ee.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ee.toString(n))}setLimit(t,n,r,o){return new ks({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ee.toString(o)}]})}_addCheck(t){return new ks({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ee.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ee.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ee.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ee.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ee.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new ks({checks:[],typeName:Ae.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...He(e)})};class Ic extends qe{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ye.boolean){const r=this._getOrReturnCtx(t);return ge(r,{code:ee.invalid_type,expected:ye.boolean,received:r.parsedType}),$e}return Pn(t.data)}}Ic.create=e=>new Ic({typeName:Ae.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...He(e)});class Sa extends qe{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ye.date){const s=this._getOrReturnCtx(t);return ge(s,{code:ee.invalid_type,expected:ye.date,received:s.parsedType}),$e}if(isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return ge(s,{code:ee.invalid_date}),$e}const r=new jn;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()s.value&&(o=this._getOrReturnCtx(t,o),ge(o,{code:ee.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):tt.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Sa({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Ee.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Ee.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew Sa({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:Ae.ZodDate,...He(e)});class xf extends qe{_parse(t){if(this._getType(t)!==ye.symbol){const r=this._getOrReturnCtx(t);return ge(r,{code:ee.invalid_type,expected:ye.symbol,received:r.parsedType}),$e}return Pn(t.data)}}xf.create=e=>new xf({typeName:Ae.ZodSymbol,...He(e)});class Dc extends qe{_parse(t){if(this._getType(t)!==ye.undefined){const r=this._getOrReturnCtx(t);return ge(r,{code:ee.invalid_type,expected:ye.undefined,received:r.parsedType}),$e}return Pn(t.data)}}Dc.create=e=>new Dc({typeName:Ae.ZodUndefined,...He(e)});class Oc extends qe{_parse(t){if(this._getType(t)!==ye.null){const r=this._getOrReturnCtx(t);return ge(r,{code:ee.invalid_type,expected:ye.null,received:r.parsedType}),$e}return Pn(t.data)}}Oc.create=e=>new Oc({typeName:Ae.ZodNull,...He(e)});class Oi extends qe{constructor(){super(...arguments),this._any=!0}_parse(t){return Pn(t.data)}}Oi.create=e=>new Oi({typeName:Ae.ZodAny,...He(e)});class ua extends qe{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Pn(t.data)}}ua.create=e=>new ua({typeName:Ae.ZodUnknown,...He(e)});class Fo extends qe{_parse(t){const n=this._getOrReturnCtx(t);return ge(n,{code:ee.invalid_type,expected:ye.never,received:n.parsedType}),$e}}Fo.create=e=>new Fo({typeName:Ae.ZodNever,...He(e)});class wf extends qe{_parse(t){if(this._getType(t)!==ye.undefined){const r=this._getOrReturnCtx(t);return ge(r,{code:ee.invalid_type,expected:ye.void,received:r.parsedType}),$e}return Pn(t.data)}}wf.create=e=>new wf({typeName:Ae.ZodVoid,...He(e)});class Or extends qe{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==ye.array)return ge(n,{code:ee.invalid_type,expected:ye.array,received:n.parsedType}),$e;if(o.exactLength!==null){const i=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(ge(n,{code:ee.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,l)=>o.type._parseAsync(new ao(n,i,n.path,l)))).then(i=>jn.mergeArray(r,i));const s=[...n.data].map((i,l)=>o.type._parseSync(new ao(n,i,n.path,l)));return jn.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new Or({...this._def,minLength:{value:t,message:Ee.toString(n)}})}max(t,n){return new Or({...this._def,maxLength:{value:t,message:Ee.toString(n)}})}length(t,n){return new Or({...this._def,exactLength:{value:t,message:Ee.toString(n)}})}nonempty(t){return this.min(1,t)}}Or.create=(e,t)=>new Or({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ae.ZodArray,...He(t)});function Wa(e){if(e instanceof kt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=no.create(Wa(r))}return new kt({...e._def,shape:()=>t})}else return e instanceof Or?new Or({...e._def,type:Wa(e.element)}):e instanceof no?no.create(Wa(e.unwrap())):e instanceof Ps?Ps.create(Wa(e.unwrap())):e instanceof io?io.create(e.items.map(t=>Wa(t))):e}class kt extends qe{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=tt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==ye.object){const u=this._getOrReturnCtx(t);return ge(u,{code:ee.invalid_type,expected:ye.object,received:u.parsedType}),$e}const{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),l=[];if(!(this._def.catchall instanceof Fo&&this._def.unknownKeys==="strip"))for(const u in o.data)i.includes(u)||l.push(u);const c=[];for(const u of i){const f=s[u],p=o.data[u];c.push({key:{status:"valid",value:u},value:f._parse(new ao(o,p,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof Fo){const u=this._def.unknownKeys;if(u==="passthrough")for(const f of l)c.push({key:{status:"valid",value:f},value:{status:"valid",value:o.data[f]}});else if(u==="strict")l.length>0&&(ge(o,{code:ee.unrecognized_keys,keys:l}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const f of l){const p=o.data[f];c.push({key:{status:"valid",value:f},value:u._parse(new ao(o,p,o.path,f)),alwaysSet:f in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const u=[];for(const f of c){const p=await f.key,d=await f.value;u.push({key:p,value:d,alwaysSet:f.alwaysSet})}return u}).then(u=>jn.mergeObjectSync(r,u)):jn.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return Ee.errToObj,new kt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,s,i,l;const c=(i=(s=(o=this._def).errorMap)===null||s===void 0?void 0:s.call(o,n,r).message)!==null&&i!==void 0?i:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=Ee.errToObj(t).message)!==null&&l!==void 0?l:c}:{message:c}}}:{}})}strip(){return new kt({...this._def,unknownKeys:"strip"})}passthrough(){return new kt({...this._def,unknownKeys:"passthrough"})}extend(t){return new kt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new kt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Ae.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new kt({...this._def,catchall:t})}pick(t){const n={};return tt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new kt({...this._def,shape:()=>n})}omit(t){const n={};return tt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new kt({...this._def,shape:()=>n})}deepPartial(){return Wa(this)}partial(t){const n={};return tt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new kt({...this._def,shape:()=>n})}required(t){const n={};return tt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof no;)s=s._def.innerType;n[r]=s}}),new kt({...this._def,shape:()=>n})}keyof(){return RT(tt.objectKeys(this.shape))}}kt.create=(e,t)=>new kt({shape:()=>e,unknownKeys:"strip",catchall:Fo.create(),typeName:Ae.ZodObject,...He(t)});kt.strictCreate=(e,t)=>new kt({shape:()=>e,unknownKeys:"strict",catchall:Fo.create(),typeName:Ae.ZodObject,...He(t)});kt.lazycreate=(e,t)=>new kt({shape:e,unknownKeys:"strip",catchall:Fo.create(),typeName:Ae.ZodObject,...He(t)});class Mc extends qe{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(const l of s)if(l.result.status==="valid")return l.result;for(const l of s)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const i=s.map(l=>new tr(l.ctx.common.issues));return ge(n,{code:ee.invalid_union,unionErrors:i}),$e}if(n.common.async)return Promise.all(r.map(async s=>{const i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s;const i=[];for(const c of r){const u={...n,common:{...n.common,issues:[]},parent:null},f=c._parseSync({data:n.data,path:n.path,parent:u});if(f.status==="valid")return f;f.status==="dirty"&&!s&&(s={result:f,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const l=i.map(c=>new tr(c));return ge(n,{code:ee.invalid_union,unionErrors:l}),$e}}get options(){return this._def.options}}Mc.create=(e,t)=>new Mc({options:e,typeName:Ae.ZodUnion,...He(t)});const go=e=>e instanceof Lc?go(e.schema):e instanceof Lr?go(e.innerType()):e instanceof $c?[e.value]:e instanceof Rs?e.options:e instanceof zc?tt.objectValues(e.enum):e instanceof Vc?go(e._def.innerType):e instanceof Dc?[void 0]:e instanceof Oc?[null]:e instanceof no?[void 0,...go(e.unwrap())]:e instanceof Ps?[null,...go(e.unwrap())]:e instanceof Dy||e instanceof Bc?go(e.unwrap()):e instanceof Uc?go(e._def.innerType):[];class Cp extends qe{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==ye.object)return ge(n,{code:ee.invalid_type,expected:ye.object,received:n.parsedType}),$e;const r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(ge(n,{code:ee.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),$e)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const s of n){const i=go(s.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of i){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,s)}}return new Cp({typeName:Ae.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...He(r)})}}function Em(e,t){const n=cs(e),r=cs(t);if(e===t)return{valid:!0,data:e};if(n===ye.object&&r===ye.object){const o=tt.objectKeys(t),s=tt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),i={...e,...t};for(const l of s){const c=Em(e[l],t[l]);if(!c.valid)return{valid:!1};i[l]=c.data}return{valid:!0,data:i}}else if(n===ye.array&&r===ye.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s{if(jm(s)||jm(i))return $e;const l=Em(s.value,i.value);return l.valid?((_m(s)||_m(i))&&n.dirty(),{status:n.value,value:l.data}):(ge(r,{code:ee.invalid_intersection_types}),$e)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Ac.create=(e,t,n)=>new Ac({left:e,right:t,typeName:Ae.ZodIntersection,...He(n)});class io extends qe{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==ye.array)return ge(r,{code:ee.invalid_type,expected:ye.array,received:r.parsedType}),$e;if(r.data.lengththis._def.items.length&&(ge(r,{code:ee.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((i,l)=>{const c=this._def.items[l]||this._def.rest;return c?c._parse(new ao(r,i,r.path,l)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>jn.mergeArray(n,i)):jn.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new io({...this._def,rest:t})}}io.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new io({items:e,typeName:Ae.ZodTuple,rest:null,...He(t)})};class Fc extends qe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==ye.object)return ge(r,{code:ee.invalid_type,expected:ye.object,received:r.parsedType}),$e;const o=[],s=this._def.keyType,i=this._def.valueType;for(const l in r.data)o.push({key:s._parse(new ao(r,l,r.path,l)),value:i._parse(new ao(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?jn.mergeObjectAsync(n,o):jn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof qe?new Fc({keyType:t,valueType:n,typeName:Ae.ZodRecord,...He(r)}):new Fc({keyType:Nr.create(),valueType:t,typeName:Ae.ZodRecord,...He(n)})}}class bf extends qe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==ye.map)return ge(r,{code:ee.invalid_type,expected:ye.map,received:r.parsedType}),$e;const o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([l,c],u)=>({key:o._parse(new ao(r,l,r.path,[u,"key"])),value:s._parse(new ao(r,c,r.path,[u,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const c of i){const u=await c.key,f=await c.value;if(u.status==="aborted"||f.status==="aborted")return $e;(u.status==="dirty"||f.status==="dirty")&&n.dirty(),l.set(u.value,f.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const c of i){const u=c.key,f=c.value;if(u.status==="aborted"||f.status==="aborted")return $e;(u.status==="dirty"||f.status==="dirty")&&n.dirty(),l.set(u.value,f.value)}return{status:n.value,value:l}}}}bf.create=(e,t,n)=>new bf({valueType:t,keyType:e,typeName:Ae.ZodMap,...He(n)});class Ca extends qe{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==ye.set)return ge(r,{code:ee.invalid_type,expected:ye.set,received:r.parsedType}),$e;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(ge(r,{code:ee.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const s=this._def.valueType;function i(c){const u=new Set;for(const f of c){if(f.status==="aborted")return $e;f.status==="dirty"&&n.dirty(),u.add(f.value)}return{status:n.value,value:u}}const l=[...r.data.values()].map((c,u)=>s._parse(new ao(r,c,r.path,u)));return r.common.async?Promise.all(l).then(c=>i(c)):i(l)}min(t,n){return new Ca({...this._def,minSize:{value:t,message:Ee.toString(n)}})}max(t,n){return new Ca({...this._def,maxSize:{value:t,message:Ee.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}Ca.create=(e,t)=>new Ca({valueType:e,minSize:null,maxSize:null,typeName:Ae.ZodSet,...He(t)});class xi extends qe{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==ye.function)return ge(n,{code:ee.invalid_type,expected:ye.function,received:n.parsedType}),$e;function r(l,c){return vf({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,mf(),Di].filter(u=>!!u),issueData:{code:ee.invalid_arguments,argumentsError:c}})}function o(l,c){return vf({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,mf(),Di].filter(u=>!!u),issueData:{code:ee.invalid_return_type,returnTypeError:c}})}const s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Mi){const l=this;return Pn(async function(...c){const u=new tr([]),f=await l._def.args.parseAsync(c,s).catch(h=>{throw u.addIssue(r(c,h)),u}),p=await Reflect.apply(i,this,f);return await l._def.returns._def.type.parseAsync(p,s).catch(h=>{throw u.addIssue(o(p,h)),u})})}else{const l=this;return Pn(function(...c){const u=l._def.args.safeParse(c,s);if(!u.success)throw new tr([r(c,u.error)]);const f=Reflect.apply(i,this,u.data),p=l._def.returns.safeParse(f,s);if(!p.success)throw new tr([o(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new xi({...this._def,args:io.create(t).rest(ua.create())})}returns(t){return new xi({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new xi({args:t||io.create([]).rest(ua.create()),returns:n||ua.create(),typeName:Ae.ZodFunction,...He(r)})}}class Lc extends qe{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Lc.create=(e,t)=>new Lc({getter:e,typeName:Ae.ZodLazy,...He(t)});class $c extends qe{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return ge(n,{received:n.data,code:ee.invalid_literal,expected:this._def.value}),$e}return{status:"valid",value:t.data}}get value(){return this._def.value}}$c.create=(e,t)=>new $c({value:e,typeName:Ae.ZodLiteral,...He(t)});function RT(e,t){return new Rs({values:e,typeName:Ae.ZodEnum,...He(t)})}class Rs extends qe{constructor(){super(...arguments),Ml.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return ge(n,{expected:tt.joinValues(r),received:n.parsedType,code:ee.invalid_type}),$e}if(yf(this,Ml)||ET(this,Ml,new Set(this._def.values)),!yf(this,Ml).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return ge(n,{received:n.data,code:ee.invalid_enum_value,options:r}),$e}return Pn(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Rs.create(t,{...this._def,...n})}exclude(t,n=this._def){return Rs.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}Ml=new WeakMap;Rs.create=RT;class zc extends qe{constructor(){super(...arguments),Al.set(this,void 0)}_parse(t){const n=tt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==ye.string&&r.parsedType!==ye.number){const o=tt.objectValues(n);return ge(r,{expected:tt.joinValues(o),received:r.parsedType,code:ee.invalid_type}),$e}if(yf(this,Al)||ET(this,Al,new Set(tt.getValidEnumValues(this._def.values))),!yf(this,Al).has(t.data)){const o=tt.objectValues(n);return ge(r,{received:r.data,code:ee.invalid_enum_value,options:o}),$e}return Pn(t.data)}get enum(){return this._def.values}}Al=new WeakMap;zc.create=(e,t)=>new zc({values:e,typeName:Ae.ZodNativeEnum,...He(t)});class Mi extends qe{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==ye.promise&&n.common.async===!1)return ge(n,{code:ee.invalid_type,expected:ye.promise,received:n.parsedType}),$e;const r=n.parsedType===ye.promise?n.data:Promise.resolve(n.data);return Pn(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Mi.create=(e,t)=>new Mi({type:e,typeName:Ae.ZodPromise,...He(t)});class Lr extends qe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ae.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:i=>{ge(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async l=>{if(n.value==="aborted")return $e;const c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?$e:c.status==="dirty"||n.value==="dirty"?ci(c.value):c});{if(n.value==="aborted")return $e;const l=this._def.schema._parseSync({data:i,path:r.path,parent:r});return l.status==="aborted"?$e:l.status==="dirty"||n.value==="dirty"?ci(l.value):l}}if(o.type==="refinement"){const i=l=>{const c=o.refinement(l,s);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?$e:(l.status==="dirty"&&n.dirty(),i(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?$e:(l.status==="dirty"&&n.dirty(),i(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Rc(i))return i;const l=o.transform(i.value,s);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>Rc(i)?Promise.resolve(o.transform(i.value,s)).then(l=>({status:n.value,value:l})):i);tt.assertNever(o)}}Lr.create=(e,t,n)=>new Lr({schema:e,typeName:Ae.ZodEffects,effect:t,...He(n)});Lr.createWithPreprocess=(e,t,n)=>new Lr({schema:t,effect:{type:"preprocess",transform:e},typeName:Ae.ZodEffects,...He(n)});class no extends qe{_parse(t){return this._getType(t)===ye.undefined?Pn(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}no.create=(e,t)=>new no({innerType:e,typeName:Ae.ZodOptional,...He(t)});class Ps extends qe{_parse(t){return this._getType(t)===ye.null?Pn(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Ps.create=(e,t)=>new Ps({innerType:e,typeName:Ae.ZodNullable,...He(t)});class Vc extends qe{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===ye.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Vc.create=(e,t)=>new Vc({innerType:e,typeName:Ae.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...He(t)});class Uc extends qe{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Pc(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new tr(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new tr(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Uc.create=(e,t)=>new Uc({innerType:e,typeName:Ae.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...He(t)});class Sf extends qe{_parse(t){if(this._getType(t)!==ye.nan){const r=this._getOrReturnCtx(t);return ge(r,{code:ee.invalid_type,expected:ye.nan,received:r.parsedType}),$e}return{status:"valid",value:t.data}}}Sf.create=e=>new Sf({typeName:Ae.ZodNaN,...He(e)});const K4=Symbol("zod_brand");class Dy extends qe{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class uu extends qe{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?$e:s.status==="dirty"?(n.dirty(),ci(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?$e:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new uu({in:t,out:n,typeName:Ae.ZodPipeline})}}class Bc extends qe{_parse(t){const n=this._def.innerType._parse(t),r=o=>(Rc(o)&&(o.value=Object.freeze(o.value)),o);return Pc(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}Bc.create=(e,t)=>new Bc({innerType:e,typeName:Ae.ZodReadonly,...He(t)});function PT(e,t={},n){return e?Oi.create().superRefine((r,o)=>{var s,i;if(!e(r)){const l=typeof t=="function"?t(r):typeof t=="string"?{message:t}:t,c=(i=(s=l.fatal)!==null&&s!==void 0?s:n)!==null&&i!==void 0?i:!0,u=typeof l=="string"?{message:l}:l;o.addIssue({code:"custom",...u,fatal:c})}}):Oi.create()}const q4={object:kt.lazycreate};var Ae;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(Ae||(Ae={}));const Z4=(e,t={message:`Input not instance of ${e.name}`})=>PT(n=>n instanceof e,t),IT=Nr.create,DT=Ns.create,J4=Sf.create,Y4=ks.create,OT=Ic.create,X4=Sa.create,Q4=xf.create,ez=Dc.create,tz=Oc.create,nz=Oi.create,rz=ua.create,oz=Fo.create,sz=wf.create,az=Or.create,iz=kt.create,lz=kt.strictCreate,cz=Mc.create,uz=Cp.create,dz=Ac.create,fz=io.create,pz=Fc.create,hz=bf.create,gz=Ca.create,mz=xi.create,vz=Lc.create,yz=$c.create,xz=Rs.create,wz=zc.create,bz=Mi.create,q0=Lr.create,Sz=no.create,Cz=Ps.create,jz=Lr.createWithPreprocess,_z=uu.create,Ez=()=>IT().optional(),Tz=()=>DT().optional(),Nz=()=>OT().optional(),kz={string:e=>Nr.create({...e,coerce:!0}),number:e=>Ns.create({...e,coerce:!0}),boolean:e=>Ic.create({...e,coerce:!0}),bigint:e=>ks.create({...e,coerce:!0}),date:e=>Sa.create({...e,coerce:!0})},Rz=$e;var T=Object.freeze({__proto__:null,defaultErrorMap:Di,setErrorMap:R4,getErrorMap:mf,makeIssue:vf,EMPTY_PATH:P4,addIssueToContext:ge,ParseStatus:jn,INVALID:$e,DIRTY:ci,OK:Pn,isAborted:jm,isDirty:_m,isValid:Rc,isAsync:Pc,get util(){return tt},get objectUtil(){return Cm},ZodParsedType:ye,getParsedType:cs,ZodType:qe,datetimeRegex:kT,ZodString:Nr,ZodNumber:Ns,ZodBigInt:ks,ZodBoolean:Ic,ZodDate:Sa,ZodSymbol:xf,ZodUndefined:Dc,ZodNull:Oc,ZodAny:Oi,ZodUnknown:ua,ZodNever:Fo,ZodVoid:wf,ZodArray:Or,ZodObject:kt,ZodUnion:Mc,ZodDiscriminatedUnion:Cp,ZodIntersection:Ac,ZodTuple:io,ZodRecord:Fc,ZodMap:bf,ZodSet:Ca,ZodFunction:xi,ZodLazy:Lc,ZodLiteral:$c,ZodEnum:Rs,ZodNativeEnum:zc,ZodPromise:Mi,ZodEffects:Lr,ZodTransformer:Lr,ZodOptional:no,ZodNullable:Ps,ZodDefault:Vc,ZodCatch:Uc,ZodNaN:Sf,BRAND:K4,ZodBranded:Dy,ZodPipeline:uu,ZodReadonly:Bc,custom:PT,Schema:qe,ZodSchema:qe,late:q4,get ZodFirstPartyTypeKind(){return Ae},coerce:kz,any:nz,array:az,bigint:Y4,boolean:OT,date:X4,discriminatedUnion:uz,effect:q0,enum:xz,function:mz,instanceof:Z4,intersection:dz,lazy:vz,literal:yz,map:hz,nan:J4,nativeEnum:wz,never:oz,null:tz,nullable:Cz,number:DT,object:iz,oboolean:Nz,onumber:Tz,optional:Sz,ostring:Ez,pipeline:_z,preprocess:jz,promise:bz,record:pz,set:gz,strictObject:lz,string:IT,symbol:Q4,transformer:q0,tuple:fz,undefined:ez,union:cz,unknown:rz,void:sz,NEVER:Rz,ZodIssueCode:ee,quotelessJson:k4,ZodError:tr});const Pz=T.object({name:T.string(),integration:T.string(),token:T.string(),number:T.string(),businessId:T.string()});function Iz({resetTable:e}){const[t,n]=y.useState(!1),r=tn({resolver:nn(Pz),defaultValues:{name:"",integration:"WHATSAPP-BAILEYS",token:crypto.randomUUID().replace("-","").toLocaleUpperCase(),number:"",businessId:""}}),o=async i=>{var l,c,u;try{const f={instanceName:i.name,integration:i.integration,token:i.token===""?void 0:i.token,number:i.number===""?void 0:i.number,businessId:i.businessId===""?void 0:i.businessId};await WM(f),ke.success("Instância criada com sucesso"),n(!1),s(),e()}catch(f){console.error("Erro ao criar instância:",f),ke.error(`Erro ao criar : ${(u=(c=(l=f==null?void 0:f.response)==null?void 0:l.data)==null?void 0:c.response)==null?void 0:u.message}`)}},s=()=>{r.reset({name:"",integration:"WHATSAPP-BAILEYS",token:crypto.randomUUID().replace("-","").toLocaleUpperCase(),number:"",businessId:""})};return a.jsxs(Sn,{open:t,onOpenChange:n,children:[a.jsx(Cn,{asChild:!0,children:a.jsxs(Te,{variant:"default",children:[a.jsx(ou,{})," Instância"]})}),a.jsxs(un,{className:"sm:max-w-[650px]",onCloseAutoFocus:s,children:[a.jsx(dn,{children:a.jsx(On,{children:"Nova Instância"})}),a.jsx(Bo,{...r,children:a.jsxs("form",{onSubmit:r.handleSubmit(o),className:"grid gap-4 py-4",children:[a.jsxs("div",{className:"grid grid-cols-4 items-center gap-4",children:[a.jsx(bo,{htmlFor:"name",className:"text-right",children:"Nome"}),a.jsx(Y,{id:"name",...r.register("name"),className:"col-span-3 border border-gray-600"})]}),a.jsxs("div",{className:"grid grid-cols-4 items-center gap-4",children:[a.jsx(bo,{htmlFor:"integration",className:"text-right",children:"Integração"}),a.jsx(R,{control:r.control,name:"integration",render:({field:i})=>a.jsx(D,{className:"col-span-3 w-full border border-gray-600",children:a.jsxs(St,{onValueChange:i.onChange,defaultValue:i.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione uma credencial"})})}),a.jsxs(vt,{className:"border border-gray-600",children:[a.jsx(me,{value:"WHATSAPP-BAILEYS",children:"Baileys"}),a.jsx(me,{value:"WHATSAPP-BUSINESS",children:"Whatsapp Cloud API"})]})]})})})]}),a.jsxs("div",{className:"grid grid-cols-4 items-center gap-4",children:[a.jsx(bo,{htmlFor:"token",className:"text-right",children:"Token"}),a.jsx(Y,{id:"token",...r.register("token"),className:"col-span-3 border border-gray-600"})]}),a.jsxs("div",{className:"grid grid-cols-4 items-center gap-4",children:[a.jsx(bo,{htmlFor:"number",className:"text-right",children:"Número"}),a.jsx(Y,{id:"number",...r.register("number"),className:"col-span-3 border border-gray-600"})]}),r.watch("integration")==="WHATSAPP-BUSINESS"&&a.jsxs("div",{className:"grid grid-cols-4 items-center gap-4",children:[a.jsx(bo,{htmlFor:"businessId",className:"text-right",children:"Business ID"}),a.jsx(Y,{id:"businessId",...r.register("businessId"),className:"col-span-3 border border-gray-600"})]}),a.jsx(br,{children:a.jsx(Te,{type:"submit",children:"Salvar"})})]})})]})]})}const MT=e=>{navigator.clipboard.writeText(e),ke.success("Copiado para a área de transferência")},$h=async e=>{try{const t=await KM();e(t)}catch(t){console.error("Erro ao buscar dados:",t)}};function Dz(){const[e,t]=y.useState(!1),[n,r]=y.useState([]),[o,s]=y.useState([]),[i,l]=y.useState([]),[c,u]=y.useState("all"),f=ir(),p=()=>{t(!e)},d=v=>()=>{f(`/manager/instance/${v}/dashboard`)};y.useEffect(()=>{(async()=>{await $h(b=>{r(b)})})()},[]);const h=v=>{switch(v){case"open":return a.jsxs("div",{className:"btn connected",children:["Conectada ",a.jsx("span",{className:"status-connected connected"})]});case"connecting":return a.jsxs("div",{className:"btn connected",children:["Conectando ",a.jsx("span",{className:"status-connecting connected"})]});case"closed":return a.jsxs("div",{className:"btn connected",children:["Desconectado ",a.jsx("span",{className:"status-disconnected connected"})]});default:return a.jsxs("div",{className:"btn connected",children:["Desconectado ",a.jsx("span",{className:"status-disconnected connected"})]})}},m=async()=>{await $h(v=>{r(v)})},g=async v=>{var b,C,j;s([...o,v]);try{try{await w_(v)}catch(S){console.error("Erro ao fazer logout:",S)}await ZM(v),await new Promise(S=>setTimeout(S,1e3)),m()}catch(S){console.error("Erro ao deletar instância:",S),ke.error(`Erro ao deletar : ${(j=(C=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:C.response)==null?void 0:j.message}`)}finally{s(o.filter(S=>S!==v))}},w=async v=>{if(v===""){await m();return}const b=n.filter(C=>C.name.toLowerCase().includes(v.toLowerCase()));r(b)},x=async v=>{if(u(v),v==="all"){await m();return}await $h(b=>{const C=b.filter(j=>j.connectionStatus===v);r(C)})};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"toolbar",children:[a.jsx("div",{className:"toolbar-title",children:a.jsx("h2",{children:"Instâncias"})}),a.jsxs("div",{className:"toolbar-buttons",children:[a.jsx(Te,{variant:"outline",className:"refresh-button",children:a.jsx(__,{onClick:m,size:"20"})}),a.jsx(Iz,{resetTable:m})]})]}),a.jsxs("div",{className:"search",children:[a.jsx("div",{className:"search-bar",children:a.jsx("input",{type:"text",placeholder:"Pesquisar",onChange:v=>w(v.target.value)})}),a.jsxs("div",{className:"status-dropdown",children:[a.jsxs("button",{className:"dropdown-button",onClick:p,children:["Status ",a.jsx(sA,{size:"15"})]}),e&&a.jsxs("div",{className:"dropdown-menu",children:[a.jsxs("button",{className:`dropdown-item ${c==="all"?"active":""}`,onClick:()=>x("all"),children:["Todos",c==="all"&&a.jsx("span",{children:a.jsx(ai,{size:"15",className:"ml-2"})})]}),a.jsxs("button",{onClick:()=>x("close"),className:`dropdown-item ${c==="close"?"active":""}`,children:["Desconectado",c==="close"&&a.jsx("span",{children:a.jsx(ai,{size:"15",className:"ml-2"})})]}),a.jsxs("button",{onClick:()=>x("connecting"),className:`dropdown-item ${c==="connecting"?"active":""}`,children:["Conectando",c==="connecting"&&a.jsx("span",{children:a.jsx(ai,{size:"15",className:"ml-2"})})]}),a.jsxs("button",{onClick:()=>x("open"),className:`dropdown-item ${c==="open"?"active":""}`,children:["Conectado",c==="open"&&a.jsx("span",{children:a.jsx(ai,{size:"15",className:"ml-2"})})]})]})]})]}),a.jsx("main",{className:"instance-cards",children:n&&n.length>0&&Array.isArray(n)&&n.map(v=>{var b,C;return a.jsxs(mi,{className:"instance-card",children:[a.jsxs("div",{className:"card-header",children:[a.jsxs("div",{className:"card-id",children:[a.jsx("span",{children:i.includes(v.token)?v.token.substring(0,36)+"...":v.token.substring(0,36).split("").map(()=>"*").join("")}),a.jsx(S_,{className:"card-icon",size:"15",onClick:()=>{MT(v.token)}}),i.includes(v.token)?a.jsx(C_,{className:"card-icon",size:"15",onClick:()=>{l(i.filter(j=>j!==v.token))}}):a.jsx(j_,{className:"card-icon",size:"15",onClick:()=>{l([...i,v.token])}})]}),a.jsx("div",{className:"card-menu",onClick:d(v.id),children:a.jsx(ru,{className:"card-icon",size:"20"})})]}),a.jsxs("div",{className:"card-body",children:[a.jsxs("div",{className:"card-details",children:[a.jsx("p",{className:"instance-name",children:v.name}),a.jsx("p",{className:"instance-description",children:v.profileName})]}),a.jsx("div",{className:"card-contact",children:a.jsx("p",{children:v.ownerJid&&v.ownerJid.split("@")[0]})})]}),a.jsxs("div",{className:"card-footer",children:[a.jsxs("div",{className:"card-stats",children:[a.jsxs("div",{className:"stat",children:[a.jsx(iA,{className:"stat-icon",size:"20"}),a.jsx("span",{children:((b=v==null?void 0:v._count)==null?void 0:b.Contact)||0})]}),a.jsxs("div",{className:"stat",children:[a.jsx(ey,{className:"stat-icon",size:"20"}),a.jsx("span",{children:((C=v==null?void 0:v._count)==null?void 0:C.Message)||0})]})]}),a.jsxs("div",{className:"card-actions",children:[h(v.connectionStatus),a.jsx("button",{className:`btn disconnect ${o.includes(v.name)?"disabled":""}`,onClick:()=>g(v.name),disabled:o.includes(v.name),children:o.includes(v.name)?a.jsx("span",{children:"Deletando..."}):a.jsx("span",{children:"Deletar"})})]})]})]},v.id)})})]})}var zh="rovingFocusGroup.onEntryFocus",Oz={bubbles:!1,cancelable:!0},jp="RovingFocusGroup",[Tm,AT,Mz]=Cy(jp),[Az,_p]=lo(jp,[Mz]),[Fz,Lz]=Az(jp),FT=y.forwardRef((e,t)=>a.jsx(Tm.Provider,{scope:e.__scopeRovingFocusGroup,children:a.jsx(Tm.Slot,{scope:e.__scopeRovingFocusGroup,children:a.jsx($z,{...e,ref:t})})}));FT.displayName=jp;var $z=y.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:c,onEntryFocus:u,preventScrollOnEntryFocus:f=!1,...p}=e,d=y.useRef(null),h=ut(t,d),m=hp(s),[g=null,w]=js({prop:i,defaultProp:l,onChange:c}),[x,v]=y.useState(!1),b=wr(u),C=AT(n),j=y.useRef(!1),[S,N]=y.useState(0);return y.useEffect(()=>{const E=d.current;if(E)return E.addEventListener(zh,b),()=>E.removeEventListener(zh,b)},[b]),a.jsx(Fz,{scope:n,orientation:r,dir:m,loop:o,currentTabStopId:g,onItemFocus:y.useCallback(E=>w(E),[w]),onItemShiftTab:y.useCallback(()=>v(!0),[]),onFocusableItemAdd:y.useCallback(()=>N(E=>E+1),[]),onFocusableItemRemove:y.useCallback(()=>N(E=>E-1),[]),children:a.jsx(Ve.div,{tabIndex:x||S===0?-1:0,"data-orientation":r,...p,ref:h,style:{outline:"none",...e.style},onMouseDown:je(e.onMouseDown,()=>{j.current=!0}),onFocus:je(e.onFocus,E=>{const A=!j.current;if(E.target===E.currentTarget&&A&&!x){const F=new CustomEvent(zh,Oz);if(E.currentTarget.dispatchEvent(F),!F.defaultPrevented){const Z=C().filter(re=>re.focusable),I=Z.find(re=>re.active),q=Z.find(re=>re.id===g),J=[I,q,...Z].filter(Boolean).map(re=>re.ref.current);zT(J,f)}}j.current=!1}),onBlur:je(e.onBlur,()=>v(!1))})})}),LT="RovingFocusGroupItem",$T=y.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,...i}=e,l=Ir(),c=s||l,u=Lz(LT,n),f=u.currentTabStopId===c,p=AT(n),{onFocusableItemAdd:d,onFocusableItemRemove:h}=u;return y.useEffect(()=>{if(r)return d(),()=>h()},[r,d,h]),a.jsx(Tm.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:a.jsx(Ve.span,{tabIndex:f?0:-1,"data-orientation":u.orientation,...i,ref:t,onMouseDown:je(e.onMouseDown,m=>{r?u.onItemFocus(c):m.preventDefault()}),onFocus:je(e.onFocus,()=>u.onItemFocus(c)),onKeyDown:je(e.onKeyDown,m=>{if(m.key==="Tab"&&m.shiftKey){u.onItemShiftTab();return}if(m.target!==m.currentTarget)return;const g=Uz(m,u.orientation,u.dir);if(g!==void 0){if(m.metaKey||m.ctrlKey||m.altKey||m.shiftKey)return;m.preventDefault();let x=p().filter(v=>v.focusable).map(v=>v.ref.current);if(g==="last")x.reverse();else if(g==="prev"||g==="next"){g==="prev"&&x.reverse();const v=x.indexOf(m.currentTarget);x=u.loop?Bz(x,v+1):x.slice(v+1)}setTimeout(()=>zT(x))}})})})});$T.displayName=LT;var zz={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Vz(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Uz(e,t,n){const r=Vz(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return zz[r]}function zT(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Bz(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var VT=FT,UT=$T,Nm=["Enter"," "],Hz=["ArrowDown","PageUp","Home"],BT=["ArrowUp","PageDown","End"],Gz=[...Hz,...BT],Wz={ltr:[...Nm,"ArrowRight"],rtl:[...Nm,"ArrowLeft"]},Kz={ltr:["ArrowLeft"],rtl:["ArrowRight"]},du="Menu",[Hc,qz,Zz]=Cy(du),[Na,HT]=lo(du,[Zz,vp,_p]),Ep=vp(),GT=_p(),[Jz,ka]=Na(du),[Yz,fu]=Na(du),WT=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:s,modal:i=!0}=e,l=Ep(t),[c,u]=y.useState(null),f=y.useRef(!1),p=wr(s),d=hp(o);return y.useEffect(()=>{const h=()=>{f.current=!0,document.addEventListener("pointerdown",m,{capture:!0,once:!0}),document.addEventListener("pointermove",m,{capture:!0,once:!0})},m=()=>f.current=!1;return document.addEventListener("keydown",h,{capture:!0}),()=>{document.removeEventListener("keydown",h,{capture:!0}),document.removeEventListener("pointerdown",m,{capture:!0}),document.removeEventListener("pointermove",m,{capture:!0})}},[]),a.jsx(PE,{...l,children:a.jsx(Jz,{scope:t,open:n,onOpenChange:p,content:c,onContentChange:u,children:a.jsx(Yz,{scope:t,onClose:y.useCallback(()=>p(!1),[p]),isUsingKeyboardRef:f,dir:d,modal:i,children:r})})})};WT.displayName=du;var Xz="MenuAnchor",Oy=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=Ep(n);return a.jsx(IE,{...o,...r,ref:t})});Oy.displayName=Xz;var My="MenuPortal",[Qz,KT]=Na(My,{forceMount:void 0}),qT=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,s=ka(My,t);return a.jsx(Qz,{scope:t,forceMount:n,children:a.jsx(co,{present:n||s.open,children:a.jsx(lp,{asChild:!0,container:o,children:r})})})};qT.displayName=My;var vr="MenuContent",[eV,Ay]=Na(vr),ZT=y.forwardRef((e,t)=>{const n=KT(vr,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=ka(vr,e.__scopeMenu),i=fu(vr,e.__scopeMenu);return a.jsx(Hc.Provider,{scope:e.__scopeMenu,children:a.jsx(co,{present:r||s.open,children:a.jsx(Hc.Slot,{scope:e.__scopeMenu,children:i.modal?a.jsx(tV,{...o,ref:t}):a.jsx(nV,{...o,ref:t})})})})}),tV=y.forwardRef((e,t)=>{const n=ka(vr,e.__scopeMenu),r=y.useRef(null),o=ut(t,r);return y.useEffect(()=>{const s=r.current;if(s)return py(s)},[]),a.jsx(Fy,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:je(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),nV=y.forwardRef((e,t)=>{const n=ka(vr,e.__scopeMenu);return a.jsx(Fy,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),Fy=y.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:s,onCloseAutoFocus:i,disableOutsidePointerEvents:l,onEntryFocus:c,onEscapeKeyDown:u,onPointerDownOutside:f,onFocusOutside:p,onInteractOutside:d,onDismiss:h,disableOutsideScroll:m,...g}=e,w=ka(vr,n),x=fu(vr,n),v=Ep(n),b=GT(n),C=qz(n),[j,S]=y.useState(null),N=y.useRef(null),E=ut(t,N,w.onContentChange),A=y.useRef(0),F=y.useRef(""),Z=y.useRef(0),I=y.useRef(null),q=y.useRef("right"),H=y.useRef(0),J=m?up:y.Fragment,re=m?{as:Oo,allowPinchZoom:!0}:void 0,K=L=>{var W,we;const te=F.current+L,fe=C().filter(Pe=>!Pe.disabled),B=document.activeElement,ne=(W=fe.find(Pe=>Pe.ref.current===B))==null?void 0:W.textValue,Q=fe.map(Pe=>Pe.textValue),ie=hV(Q,te,ne),oe=(we=fe.find(Pe=>Pe.textValue===ie))==null?void 0:we.ref.current;(function Pe(Fe){F.current=Fe,window.clearTimeout(A.current),Fe!==""&&(A.current=window.setTimeout(()=>Pe(""),1e3))})(te),oe&&setTimeout(()=>oe.focus())};y.useEffect(()=>()=>window.clearTimeout(A.current),[]),fy();const z=y.useCallback(L=>{var fe,B;return q.current===((fe=I.current)==null?void 0:fe.side)&&mV(L,(B=I.current)==null?void 0:B.area)},[]);return a.jsx(eV,{scope:n,searchRef:F,onItemEnter:y.useCallback(L=>{z(L)&&L.preventDefault()},[z]),onItemLeave:y.useCallback(L=>{var te;z(L)||((te=N.current)==null||te.focus(),S(null))},[z]),onTriggerLeave:y.useCallback(L=>{z(L)&&L.preventDefault()},[z]),pointerGraceTimerRef:Z,onPointerGraceIntentChange:y.useCallback(L=>{I.current=L},[]),children:a.jsx(J,{...re,children:a.jsx(ip,{asChild:!0,trapped:o,onMountAutoFocus:je(s,L=>{var te;L.preventDefault(),(te=N.current)==null||te.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:a.jsx(ap,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:u,onPointerDownOutside:f,onFocusOutside:p,onInteractOutside:d,onDismiss:h,children:a.jsx(VT,{asChild:!0,...b,dir:x.dir,orientation:"vertical",loop:r,currentTabStopId:j,onCurrentTabStopIdChange:S,onEntryFocus:je(c,L=>{x.isUsingKeyboardRef.current||L.preventDefault()}),preventScrollOnEntryFocus:!0,children:a.jsx(DE,{role:"menu","aria-orientation":"vertical","data-state":dN(w.open),"data-radix-menu-content":"",dir:x.dir,...v,...g,ref:E,style:{outline:"none",...g.style},onKeyDown:je(g.onKeyDown,L=>{const fe=L.target.closest("[data-radix-menu-content]")===L.currentTarget,B=L.ctrlKey||L.altKey||L.metaKey,ne=L.key.length===1;fe&&(L.key==="Tab"&&L.preventDefault(),!B&&ne&&K(L.key));const Q=N.current;if(L.target!==Q||!Gz.includes(L.key))return;L.preventDefault();const oe=C().filter(W=>!W.disabled).map(W=>W.ref.current);BT.includes(L.key)&&oe.reverse(),fV(oe)}),onBlur:je(e.onBlur,L=>{L.currentTarget.contains(L.target)||(window.clearTimeout(A.current),F.current="")}),onPointerMove:je(e.onPointerMove,Gc(L=>{const te=L.target,fe=H.current!==L.clientX;if(L.currentTarget.contains(te)&&fe){const B=L.clientX>H.current?"right":"left";q.current=B,H.current=L.clientX}}))})})})})})})});ZT.displayName=vr;var rV="MenuGroup",Ly=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return a.jsx(Ve.div,{role:"group",...r,ref:t})});Ly.displayName=rV;var oV="MenuLabel",JT=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return a.jsx(Ve.div,{...r,ref:t})});JT.displayName=oV;var Cf="MenuItem",Z0="menu.itemSelect",Tp=y.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,s=y.useRef(null),i=fu(Cf,e.__scopeMenu),l=Ay(Cf,e.__scopeMenu),c=ut(t,s),u=y.useRef(!1),f=()=>{const p=s.current;if(!n&&p){const d=new CustomEvent(Z0,{bubbles:!0,cancelable:!0});p.addEventListener(Z0,h=>r==null?void 0:r(h),{once:!0}),N_(p,d),d.defaultPrevented?u.current=!1:i.onClose()}};return a.jsx(YT,{...o,ref:c,disabled:n,onClick:je(e.onClick,f),onPointerDown:p=>{var d;(d=e.onPointerDown)==null||d.call(e,p),u.current=!0},onPointerUp:je(e.onPointerUp,p=>{var d;u.current||(d=p.currentTarget)==null||d.click()}),onKeyDown:je(e.onKeyDown,p=>{const d=l.searchRef.current!=="";n||d&&p.key===" "||Nm.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});Tp.displayName=Cf;var YT=y.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...s}=e,i=Ay(Cf,n),l=GT(n),c=y.useRef(null),u=ut(t,c),[f,p]=y.useState(!1),[d,h]=y.useState("");return y.useEffect(()=>{const m=c.current;m&&h((m.textContent??"").trim())},[s.children]),a.jsx(Hc.ItemSlot,{scope:n,disabled:r,textValue:o??d,children:a.jsx(UT,{asChild:!0,...l,focusable:!r,children:a.jsx(Ve.div,{role:"menuitem","data-highlighted":f?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:u,onPointerMove:je(e.onPointerMove,Gc(m=>{r?i.onItemLeave(m):(i.onItemEnter(m),m.defaultPrevented||m.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:je(e.onPointerLeave,Gc(m=>i.onItemLeave(m))),onFocus:je(e.onFocus,()=>p(!0)),onBlur:je(e.onBlur,()=>p(!1))})})})}),sV="MenuCheckboxItem",XT=y.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return a.jsx(rN,{scope:e.__scopeMenu,checked:n,children:a.jsx(Tp,{role:"menuitemcheckbox","aria-checked":jf(n)?"mixed":n,...o,ref:t,"data-state":zy(n),onSelect:je(o.onSelect,()=>r==null?void 0:r(jf(n)?!0:!n),{checkForDefaultPrevented:!1})})})});XT.displayName=sV;var QT="MenuRadioGroup",[aV,iV]=Na(QT,{value:void 0,onValueChange:()=>{}}),eN=y.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,s=wr(r);return a.jsx(aV,{scope:e.__scopeMenu,value:n,onValueChange:s,children:a.jsx(Ly,{...o,ref:t})})});eN.displayName=QT;var tN="MenuRadioItem",nN=y.forwardRef((e,t)=>{const{value:n,...r}=e,o=iV(tN,e.__scopeMenu),s=n===o.value;return a.jsx(rN,{scope:e.__scopeMenu,checked:s,children:a.jsx(Tp,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":zy(s),onSelect:je(r.onSelect,()=>{var i;return(i=o.onValueChange)==null?void 0:i.call(o,n)},{checkForDefaultPrevented:!1})})})});nN.displayName=tN;var $y="MenuItemIndicator",[rN,lV]=Na($y,{checked:!1}),oN=y.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,s=lV($y,n);return a.jsx(co,{present:r||jf(s.checked)||s.checked===!0,children:a.jsx(Ve.span,{...o,ref:t,"data-state":zy(s.checked)})})});oN.displayName=$y;var cV="MenuSeparator",sN=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return a.jsx(Ve.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});sN.displayName=cV;var uV="MenuArrow",aN=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=Ep(n);return a.jsx(OE,{...o,...r,ref:t})});aN.displayName=uV;var dV="MenuSub",[qK,iN]=Na(dV),Fl="MenuSubTrigger",lN=y.forwardRef((e,t)=>{const n=ka(Fl,e.__scopeMenu),r=fu(Fl,e.__scopeMenu),o=iN(Fl,e.__scopeMenu),s=Ay(Fl,e.__scopeMenu),i=y.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:c}=s,u={__scopeMenu:e.__scopeMenu},f=y.useCallback(()=>{i.current&&window.clearTimeout(i.current),i.current=null},[]);return y.useEffect(()=>f,[f]),y.useEffect(()=>{const p=l.current;return()=>{window.clearTimeout(p),c(null)}},[l,c]),a.jsx(Oy,{asChild:!0,...u,children:a.jsx(YT,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":dN(n.open),...e,ref:tp(t,o.onTriggerChange),onClick:p=>{var d;(d=e.onClick)==null||d.call(e,p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:je(e.onPointerMove,Gc(p=>{s.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!i.current&&(s.onPointerGraceIntentChange(null),i.current=window.setTimeout(()=>{n.onOpenChange(!0),f()},100))})),onPointerLeave:je(e.onPointerLeave,Gc(p=>{var h,m;f();const d=(h=n.content)==null?void 0:h.getBoundingClientRect();if(d){const g=(m=n.content)==null?void 0:m.dataset.side,w=g==="right",x=w?-5:5,v=d[w?"left":"right"],b=d[w?"right":"left"];s.onPointerGraceIntentChange({area:[{x:p.clientX+x,y:p.clientY},{x:v,y:d.top},{x:b,y:d.top},{x:b,y:d.bottom},{x:v,y:d.bottom}],side:g}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(p),p.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:je(e.onKeyDown,p=>{var h;const d=s.searchRef.current!=="";e.disabled||d&&p.key===" "||Wz[r.dir].includes(p.key)&&(n.onOpenChange(!0),(h=n.content)==null||h.focus(),p.preventDefault())})})})});lN.displayName=Fl;var cN="MenuSubContent",uN=y.forwardRef((e,t)=>{const n=KT(vr,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=ka(vr,e.__scopeMenu),i=fu(vr,e.__scopeMenu),l=iN(cN,e.__scopeMenu),c=y.useRef(null),u=ut(t,c);return a.jsx(Hc.Provider,{scope:e.__scopeMenu,children:a.jsx(co,{present:r||s.open,children:a.jsx(Hc.Slot,{scope:e.__scopeMenu,children:a.jsx(Fy,{id:l.contentId,"aria-labelledby":l.triggerId,...o,ref:u,align:"start",side:i.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:f=>{var p;i.isUsingKeyboardRef.current&&((p=c.current)==null||p.focus()),f.preventDefault()},onCloseAutoFocus:f=>f.preventDefault(),onFocusOutside:je(e.onFocusOutside,f=>{f.target!==l.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:je(e.onEscapeKeyDown,f=>{i.onClose(),f.preventDefault()}),onKeyDown:je(e.onKeyDown,f=>{var h;const p=f.currentTarget.contains(f.target),d=Kz[i.dir].includes(f.key);p&&d&&(s.onOpenChange(!1),(h=l.trigger)==null||h.focus(),f.preventDefault())})})})})})});uN.displayName=cN;function dN(e){return e?"open":"closed"}function jf(e){return e==="indeterminate"}function zy(e){return jf(e)?"indeterminate":e?"checked":"unchecked"}function fV(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function pV(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function hV(e,t,n){const o=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=pV(e,Math.max(s,0));o.length===1&&(i=i.filter(u=>u!==n));const c=i.find(u=>u.toLowerCase().startsWith(o.toLowerCase()));return c!==n?c:void 0}function gV(e,t){const{x:n,y:r}=e;let o=!1;for(let s=0,i=t.length-1;sr!=f>r&&n<(u-l)*(r-c)/(f-c)+l&&(o=!o)}return o}function mV(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return gV(n,t)}function Gc(e){return t=>t.pointerType==="mouse"?e(t):void 0}var vV=WT,yV=Oy,xV=qT,wV=ZT,bV=Ly,SV=JT,CV=Tp,jV=XT,_V=eN,EV=nN,TV=oN,NV=sN,kV=aN,RV=lN,PV=uN,Vy="DropdownMenu",[IV,ZK]=lo(Vy,[HT]),Mn=HT(),[DV,fN]=IV(Vy),Uy=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:s,onOpenChange:i,modal:l=!0}=e,c=Mn(t),u=y.useRef(null),[f=!1,p]=js({prop:o,defaultProp:s,onChange:i});return a.jsx(DV,{scope:t,triggerId:Ir(),triggerRef:u,contentId:Ir(),open:f,onOpenChange:p,onOpenToggle:y.useCallback(()=>p(d=>!d),[p]),modal:l,children:a.jsx(vV,{...c,open:f,onOpenChange:p,dir:r,modal:l,children:n})})};Uy.displayName=Vy;var pN="DropdownMenuTrigger",By=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,s=fN(pN,n),i=Mn(n);return a.jsx(yV,{asChild:!0,...i,children:a.jsx(Ve.button,{type:"button",id:s.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":s.open?s.contentId:void 0,"data-state":s.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...o,ref:tp(t,s.triggerRef),onPointerDown:je(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(s.onOpenToggle(),s.open||l.preventDefault())}),onKeyDown:je(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&s.onOpenToggle(),l.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});By.displayName=pN;var OV="DropdownMenuPortal",hN=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Mn(t);return a.jsx(xV,{...r,...n})};hN.displayName=OV;var gN="DropdownMenuContent",mN=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=fN(gN,n),s=Mn(n),i=y.useRef(!1);return a.jsx(wV,{id:o.contentId,"aria-labelledby":o.triggerId,...s,...r,ref:t,onCloseAutoFocus:je(e.onCloseAutoFocus,l=>{var c;i.current||(c=o.triggerRef.current)==null||c.focus(),i.current=!1,l.preventDefault()}),onInteractOutside:je(e.onInteractOutside,l=>{const c=l.detail.originalEvent,u=c.button===0&&c.ctrlKey===!0,f=c.button===2||u;(!o.modal||f)&&(i.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});mN.displayName=gN;var MV="DropdownMenuGroup",AV=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Mn(n);return a.jsx(bV,{...o,...r,ref:t})});AV.displayName=MV;var FV="DropdownMenuLabel",vN=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Mn(n);return a.jsx(SV,{...o,...r,ref:t})});vN.displayName=FV;var LV="DropdownMenuItem",yN=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Mn(n);return a.jsx(CV,{...o,...r,ref:t})});yN.displayName=LV;var $V="DropdownMenuCheckboxItem",xN=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Mn(n);return a.jsx(jV,{...o,...r,ref:t})});xN.displayName=$V;var zV="DropdownMenuRadioGroup",VV=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Mn(n);return a.jsx(_V,{...o,...r,ref:t})});VV.displayName=zV;var UV="DropdownMenuRadioItem",wN=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Mn(n);return a.jsx(EV,{...o,...r,ref:t})});wN.displayName=UV;var BV="DropdownMenuItemIndicator",bN=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Mn(n);return a.jsx(TV,{...o,...r,ref:t})});bN.displayName=BV;var HV="DropdownMenuSeparator",SN=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Mn(n);return a.jsx(NV,{...o,...r,ref:t})});SN.displayName=HV;var GV="DropdownMenuArrow",WV=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Mn(n);return a.jsx(kV,{...o,...r,ref:t})});WV.displayName=GV;var KV="DropdownMenuSubTrigger",CN=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Mn(n);return a.jsx(RV,{...o,...r,ref:t})});CN.displayName=KV;var qV="DropdownMenuSubContent",jN=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Mn(n);return a.jsx(PV,{...o,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});jN.displayName=qV;var ZV=Uy,JV=By,YV=hN,_N=mN,EN=vN,TN=yN,NN=xN,kN=wN,RN=bN,Go=SN,PN=CN,IN=jN;const Np=ZV,kp=JV,XV=y.forwardRef(({className:e,inset:t,children:n,...r},o)=>a.jsxs(PN,{ref:o,className:Re("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",e),...r,children:[n,a.jsx(rA,{className:"ml-auto h-4 w-4"})]}));XV.displayName=PN.displayName;const QV=y.forwardRef(({className:e,...t},n)=>a.jsx(IN,{ref:n,className:Re("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));QV.displayName=IN.displayName;const qi=y.forwardRef(({className:e,sideOffset:t=4,...n},r)=>a.jsx(YV,{children:a.jsx(_N,{ref:r,sideOffset:t,className:Re("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})}));qi.displayName=_N.displayName;const xn=y.forwardRef(({className:e,inset:t,...n},r)=>a.jsx(TN,{ref:r,className:Re("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));xn.displayName=TN.displayName;const e3=y.forwardRef(({className:e,children:t,checked:n,...r},o)=>a.jsxs(NN,{ref:o,className:Re("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[a.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a.jsx(RN,{children:a.jsx(ai,{className:"h-4 w-4"})})}),t]}));e3.displayName=NN.displayName;const t3=y.forwardRef(({className:e,children:t,...n},r)=>a.jsxs(kN,{ref:r,className:Re("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[a.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a.jsx(RN,{children:a.jsx(lA,{className:"h-2 w-2 fill-current"})})}),t]}));t3.displayName=kN.displayName;const pu=y.forwardRef(({className:e,inset:t,...n},r)=>a.jsx(EN,{ref:r,className:Re("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));pu.displayName=EN.displayName;const Zi=y.forwardRef(({className:e,...t},n)=>a.jsx(Go,{ref:n,className:Re("-mx-1 my-1 h-px bg-muted",e),...t}));Zi.displayName=Go.displayName;const ko=y.forwardRef(({className:e,...t},n)=>a.jsx("textarea",{className:Re("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));ko.displayName="Textarea";const Hy=new zr,n3=async e=>(await Hy.getInstance().post(`/chat/findChats/${e}`,{where:{}})).data,r3=async(e,t)=>(await Hy.getInstance().post(`/chat/findChats/${e}`,{where:{remoteJid:t}},{headers:{"Content-Type":"application/json"}})).data,o3=async(e,t)=>(await Hy.getInstance().post(`/chat/findMessages/${e}`,{where:{key:{remoteJid:t}}})).data;function s3({textareaRef:e,handleTextareaChange:t,textareaHeight:n,lastMessageRef:r,scrollToBottom:o}){const{instance:s}=Tt(),[i,l]=y.useState(null),[c,u]=y.useState([]),{remoteJid:f}=Ta();y.useEffect(()=>{const h=async(g,w)=>{try{const x=await r3(g,w);l(x[0])}catch(x){console.error("Erro ao buscar dados:",x)}},m=async(g,w)=>{try{const x=await o3(g,w);u(x.messages.records),o()}catch(x){console.error("Erro ao buscar dados:",x)}};s&&f&&(h(s.name,f),m(s.name,f))},[f,s,o]);const p=h=>a.jsx("div",{className:"bubble-right",children:a.jsx("div",{className:"flex items-start gap-4 self-end",children:a.jsx("div",{className:"grid gap-1",children:a.jsx("div",{className:"prose text-muted-foreground",children:a.jsx("div",{className:"bubble",children:JSON.stringify(h.message)})})})})}),d=h=>a.jsx("div",{className:"bubble-left",children:a.jsx("div",{className:"flex items-start gap-4",children:a.jsx("div",{className:"grid gap-1",children:a.jsx("div",{className:"prose text-muted-foreground",children:a.jsx("div",{className:"bubble",children:JSON.stringify(h.message)})})})})});return a.jsxs("div",{className:"min-h-screen flex flex-col",children:[a.jsx("div",{className:"sticky top-0 p-2",children:a.jsxs(Uy,{children:[a.jsx(By,{asChild:!0,children:a.jsxs(Te,{variant:"ghost",className:"gap-1 rounded-xl px-3 h-10 data-[state=open]:bg-muted text-lg",children:[(i==null?void 0:i.pushName)||(i==null?void 0:i.remoteJid.split("@")[0]),a.jsx(Qf,{className:"w-4 h-4 text-muted-foreground"})]})}),a.jsxs(qi,{align:"start",className:"max-w-[300px]",children:[a.jsxs(xn,{className:"items-start gap-2",children:[a.jsx(mA,{className:"w-4 h-4 mr-2 translate-y-1 shrink-0"}),a.jsxs("div",{children:[a.jsx("div",{className:"font-medium",children:"GPT-4"}),a.jsx("div",{className:"text-muted-foreground/80",children:"With DALL-E, browsing and analysis. Limit 40 messages / 3 hours"})]})]}),a.jsx(Zi,{}),a.jsxs(xn,{className:"items-start gap-2",children:[a.jsx(yA,{className:"w-4 h-4 mr-2 translate-y-1 shrink-0"}),a.jsxs("div",{children:[a.jsx("div",{className:"font-medium",children:"GPT-3"}),a.jsx("div",{className:"text-muted-foreground/80",children:"Great for everyday tasks"})]})]})]})]})}),a.jsxs("div",{className:"flex flex-col flex-1 max-w-4xl gap-8 px-4 mx-auto message-container overflow-y-auto",children:[c.map(h=>h.key.fromMe?p(h):d(h)),a.jsx("div",{ref:r})]}),a.jsx("div",{className:"max-w-2xl w-full sticky bottom-0 mx-auto py-2 flex flex-col gap-1.5 px-4 bg-background",children:a.jsxs("div",{className:"relative input-message",children:[a.jsxs(Te,{type:"button",size:"icon",className:"absolute w-8 h-8 bottom-3 left-3 rounded-full bg-transparent text-white hover:bg-transparent",children:[a.jsx(gA,{className:"w-4 h-4 text-white"}),a.jsx("span",{className:"sr-only",children:"Anexar"})]}),a.jsx(ko,{placeholder:"Enviar mensagem...",name:"message",id:"message",rows:1,ref:e,onChange:t,style:{height:n},className:"min-h-[48px] max-h-[240px] rounded-3xl resize-none p-4 pl-12 pr-16 border border-none shadow-sm"}),a.jsxs(Te,{type:"submit",size:"icon",className:"absolute w-8 h-8 bottom-3 right-3 rounded-full",children:[a.jsx(nA,{className:"w-4 h-4"}),a.jsx("span",{className:"sr-only",children:"Enviar"})]})]})})]})}var Gy="Tabs",[a3,JK]=lo(Gy,[_p]),DN=_p(),[i3,Wy]=a3(Gy),ON=y.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:s,orientation:i="horizontal",dir:l,activationMode:c="automatic",...u}=e,f=hp(l),[p,d]=js({prop:r,onChange:o,defaultProp:s});return a.jsx(i3,{scope:n,baseId:Ir(),value:p,onValueChange:d,orientation:i,dir:f,activationMode:c,children:a.jsx(Ve.div,{dir:f,"data-orientation":i,...u,ref:t})})});ON.displayName=Gy;var MN="TabsList",AN=y.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,s=Wy(MN,n),i=DN(n);return a.jsx(VT,{asChild:!0,...i,orientation:s.orientation,dir:s.dir,loop:r,children:a.jsx(Ve.div,{role:"tablist","aria-orientation":s.orientation,...o,ref:t})})});AN.displayName=MN;var FN="TabsTrigger",LN=y.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...s}=e,i=Wy(FN,n),l=DN(n),c=VN(i.baseId,r),u=UN(i.baseId,r),f=r===i.value;return a.jsx(UT,{asChild:!0,...l,focusable:!o,active:f,children:a.jsx(Ve.button,{type:"button",role:"tab","aria-selected":f,"aria-controls":u,"data-state":f?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:c,...s,ref:t,onMouseDown:je(e.onMouseDown,p=>{!o&&p.button===0&&p.ctrlKey===!1?i.onValueChange(r):p.preventDefault()}),onKeyDown:je(e.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&i.onValueChange(r)}),onFocus:je(e.onFocus,()=>{const p=i.activationMode!=="manual";!f&&!o&&p&&i.onValueChange(r)})})})});LN.displayName=FN;var $N="TabsContent",zN=y.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:s,...i}=e,l=Wy($N,n),c=VN(l.baseId,r),u=UN(l.baseId,r),f=r===l.value,p=y.useRef(f);return y.useEffect(()=>{const d=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(d)},[]),a.jsx(co,{present:o||f,children:({present:d})=>a.jsx(Ve.div,{"data-state":f?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":c,hidden:!d,id:u,tabIndex:0,...i,ref:t,style:{...e.style,animationDuration:p.current?"0s":void 0},children:d&&s})})});zN.displayName=$N;function VN(e,t){return`${e}-trigger-${t}`}function UN(e,t){return`${e}-content-${t}`}var l3=ON,BN=AN,HN=LN,GN=zN;const c3=l3,WN=y.forwardRef(({className:e,...t},n)=>a.jsx(BN,{ref:n,className:Re("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",e),...t}));WN.displayName=BN.displayName;const km=y.forwardRef(({className:e,...t},n)=>a.jsx(HN,{ref:n,className:Re("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",e),...t}));km.displayName=HN.displayName;const Rm=y.forwardRef(({className:e,...t},n)=>a.jsx(GN,{ref:n,className:Re("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...t}));Rm.displayName=GN.displayName;function J0(){const e=y.useRef(null),[t]=y.useState("auto"),n=y.useRef(null),[r,o]=y.useState([]),{instance:s}=Tt(),{instanceId:i,remoteJid:l}=Ta(),c=ir(),u=()=>{e.current&&e.current.scrollIntoView({})},f=()=>{if(n.current){n.current.style.height="auto";const d=n.current.scrollHeight,m=parseInt(getComputedStyle(n.current).lineHeight)*10;n.current.style.height=`${Math.min(d,m)}px`}};y.useEffect(()=>{s&&(async h=>{try{const m=await n3(h);o(m)}catch(m){console.error("Erro ao buscar dados:",m)}})(s.name),u()},[s]);const p=d=>{c(`/manager/instance/${i}/chat/${d}`)};return a.jsxs(su,{direction:"horizontal",children:[a.jsx(ro,{defaultSize:20,children:a.jsxs("div",{className:"flex-col hidden gap-2 text-foreground bg-background md:flex",children:[a.jsx("div",{className:"sticky top-0 p-2",children:a.jsxs(Te,{variant:"ghost",className:"justify-start w-full gap-2 px-2 text-left",children:[a.jsx("div",{className:"flex items-center justify-center rounded-full w-7 h-7",children:a.jsx(ey,{className:"w-4 h-4"})}),a.jsx("div",{className:"overflow-hidden text-sm grow text-ellipsis whitespace-nowrap",children:"Chat"}),a.jsx(ou,{className:"w-4 h-4"})]})}),a.jsxs(c3,{defaultValue:"contacts",children:[a.jsxs(WN,{className:"tabs-chat",children:[a.jsx(km,{value:"contacts",children:"Contatos"}),a.jsx(km,{value:"groups",children:"Grupos"})]}),a.jsx(Rm,{value:"contacts",children:a.jsx("div",{className:"flex-1 overflow-auto",children:a.jsxs("div",{className:"grid gap-1 p-2 text-foreground",children:[a.jsx("div",{className:"px-2 text-xs font-medium text-muted-foreground",children:"Contatos"}),r.map(d=>d.remoteJid.includes("@s.whatsapp.net")&&a.jsxs(Lw,{to:"#",onClick:()=>p(d.remoteJid),className:`flex items-center block p-2 overflow-hidden text-sm truncate transition-colors rounded-md whitespace-nowrap hover:bg-muted/50 chat-item border-b border-gray-600/50 ${l===d.remoteJid?"active":""}`,children:[a.jsx("span",{className:"chat-avatar mr-2",children:a.jsx("img",{src:d.profilePicUrl||"https://via.placeholder.com/150",alt:"Avatar",className:"w-8 h-8 rounded-full"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("span",{className:"chat-title block font-medium",children:d.pushName}),a.jsx("span",{className:"chat-description block text-xs text-gray-500",children:d.remoteJid.split("@")[0]})]})]}))]})})}),a.jsx(Rm,{value:"groups",children:a.jsx("div",{className:"flex-1 overflow-auto",children:a.jsx("div",{className:"grid gap-1 p-2 text-foreground",children:r.map(d=>d.remoteJid.includes("@g.us")&&a.jsxs(Lw,{to:"#",onClick:()=>p(d.remoteJid),className:`flex items-center block p-2 overflow-hidden text-sm truncate transition-colors rounded-md whitespace-nowrap hover:bg-muted/50 chat-item border-b border-gray-600/50 ${l===d.remoteJid?"active":""}`,children:[a.jsx("span",{className:"chat-avatar mr-2",children:a.jsx("img",{src:d.profilePicUrl||"https://via.placeholder.com/150",alt:"Avatar",className:"w-8 h-8 rounded-full"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("span",{className:"chat-title block font-medium",children:d.pushName}),a.jsx("span",{className:"chat-description block text-xs text-gray-500",children:d.remoteJid})]})]}))})})})]})]})}),a.jsx(au,{withHandle:!0,className:"border border-black"}),a.jsx(ro,{children:l&&a.jsx(s3,{textareaRef:n,handleTextareaChange:f,textareaHeight:t,lastMessageRef:e,scrollToBottom:u})})]})}var Ky="Switch",[u3,YK]=lo(Ky),[d3,f3]=u3(Ky),KN=y.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:s,required:i,disabled:l,value:c="on",onCheckedChange:u,...f}=e,[p,d]=y.useState(null),h=ut(t,v=>d(v)),m=y.useRef(!1),g=p?!!p.closest("form"):!0,[w=!1,x]=js({prop:o,defaultProp:s,onChange:u});return a.jsxs(d3,{scope:n,checked:w,disabled:l,children:[a.jsx(Ve.button,{type:"button",role:"switch","aria-checked":w,"aria-required":i,"data-state":JN(w),"data-disabled":l?"":void 0,disabled:l,value:c,...f,ref:h,onClick:je(e.onClick,v=>{x(b=>!b),g&&(m.current=v.isPropagationStopped(),m.current||v.stopPropagation())})}),g&&a.jsx(p3,{control:p,bubbles:!m.current,name:r,value:c,checked:w,required:i,disabled:l,style:{transform:"translateX(-100%)"}})]})});KN.displayName=Ky;var qN="SwitchThumb",ZN=y.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=f3(qN,n);return a.jsx(Ve.span,{"data-state":JN(o.checked),"data-disabled":o.disabled?"":void 0,...r,ref:t})});ZN.displayName=qN;var p3=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,s=y.useRef(null),i=ME(n),l=bE(t);return y.useEffect(()=>{const c=s.current,u=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(u,"checked").set;if(i!==n&&p){const d=new Event("click",{bubbles:r});p.call(c,n),c.dispatchEvent(d)}},[i,n,r]),a.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...o,tabIndex:-1,ref:s,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})};function JN(e){return e?"checked":"unchecked"}var YN=KN,h3=ZN;const Ce=y.forwardRef(({className:e,...t},n)=>a.jsx(YN,{className:Re("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-slate-400",e),...t,ref:n,children:a.jsx(h3,{className:Re("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));Ce.displayName=YN.displayName;const XN=new zr,g3=async(e,t)=>(await XN.getInstance().get(`/chatwoot/find/${e}`,{headers:{apikey:t}})).data,m3=async(e,t,n)=>(await XN.getInstance().post(`/chatwoot/set/${e}`,n,{headers:{apikey:t}})).data,v3=T.object({enabled:T.boolean(),accountId:T.string(),token:T.string(),url:T.string(),signMsg:T.boolean(),signDelimiter:T.string(),nameInbox:T.string(),organization:T.string(),logo:T.string(),reopenConversation:T.boolean(),conversationPending:T.boolean(),mergeBrazilContacts:T.boolean(),importContacts:T.boolean(),importMessages:T.boolean(),daysLimitImportMessages:T.string(),autoCreate:T.boolean()});function y3(){const{instance:e}=Tt(),[,t]=y.useState(!1),n=tn({resolver:nn(v3),defaultValues:{enabled:!0,accountId:"",token:"",url:"",signMsg:!0,signDelimiter:"\\n",nameInbox:"",organization:"",logo:"",reopenConversation:!0,conversationPending:!1,mergeBrazilContacts:!0,importContacts:!1,importMessages:!1,daysLimitImportMessages:"7",autoCreate:!0}});y.useEffect(()=>{(async()=>{if(e){t(!0);try{const s=await g3(e.name,e.token);n.reset(s)}catch(s){console.error("Erro ao buscar dados do chatwoot:",s)}finally{t(!1)}}})()},[e,n]);const r=async()=>{var s,i,l;if(!e)return;const o=n.getValues();t(!0);try{const c={enabled:o.enabled,accountId:o.accountId,token:o.token,url:o.url,signMsg:o.signMsg,signDelimiter:o.signDelimiter,nameInbox:o.nameInbox,organization:o.organization,logo:o.logo,reopenConversation:o.reopenConversation,conversationPending:o.conversationPending,mergeBrazilContacts:o.mergeBrazilContacts,importContacts:o.importContacts,importMessages:o.importMessages,daysLimitImportMessages:parseInt(o.daysLimitImportMessages,10),autoCreate:o.autoCreate};await m3(e.name,e.token,c),ke.success("Chatwoot criado com sucesso")}catch(c){console.error("Erro ao criar chatwoot:",c),ke.error(`Erro ao criar : ${(l=(i=(s=c==null?void 0:c.response)==null?void 0:s.data)==null?void 0:i.response)==null?void 0:l.message}`)}finally{t(!1)}};return a.jsx("main",{className:"main-content",children:a.jsx("div",{className:"form-container",children:a.jsx(uo,{...n,children:a.jsxs("form",{className:"w-full space-y-6",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"mb-1 text-lg font-medium",children:"Chatwoot"}),a.jsx(Go,{className:"my-4 border-t border-gray-600"}),a.jsxs("div",{className:"space-y-4",children:[a.jsx(R,{control:n.control,name:"enabled",render:({field:o})=>a.jsxs(D,{className:"flex flex-row items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Ativo"}),a.jsx(zt,{children:"Ativa ou desativa o chatwoot"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:o.value,onCheckedChange:o.onChange})})]})}),a.jsx(R,{control:n.control,name:"url",render:({field:o})=>a.jsx(Y,{...o,className:"border border-gray-600 w-full",placeholder:"URL do chatwoot"})}),a.jsx(R,{control:n.control,name:"accountId",render:({field:o})=>a.jsx(Y,{...o,className:"border border-gray-600 w-full",placeholder:"ID da Conta"})}),a.jsx(R,{control:n.control,name:"token",render:({field:o})=>a.jsx(Y,{...o,className:"border border-gray-600 w-full",placeholder:"Token da Conta",type:"password"})}),a.jsx(R,{control:n.control,name:"signMsg",render:({field:o})=>a.jsxs(D,{className:"flex flex-row items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Assinar Mensagem"}),a.jsx(zt,{children:"Assina mensagem com o nome do usuário do chatwoot"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:o.value,onCheckedChange:o.onChange})})]})}),a.jsx(R,{control:n.control,name:"signDelimiter",render:({field:o})=>a.jsx(Y,{...o,className:"border border-gray-600 w-full",placeholder:"Delimitador de Assinatura"})}),a.jsx(R,{control:n.control,name:"nameInbox",render:({field:o})=>a.jsx(Y,{...o,className:"border border-gray-600 w-full",placeholder:"Nome da Caixa de Entrada"})}),a.jsx(R,{control:n.control,name:"organization",render:({field:o})=>a.jsx(Y,{...o,className:"border border-gray-600 w-full",placeholder:"Nome da organização"})}),a.jsx(R,{control:n.control,name:"logo",render:({field:o})=>a.jsx(Y,{...o,className:"border border-gray-600 w-full",placeholder:"URL do logo"})}),a.jsx(R,{control:n.control,name:"conversationPending",render:({field:o})=>a.jsxs(D,{className:"flex flex-row items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Conversas Pendentes"}),a.jsx(zt,{children:"Conversas iniciam como pendentes"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:o.value,onCheckedChange:o.onChange})})]})}),a.jsx(R,{control:n.control,name:"reopenConversation",render:({field:o})=>a.jsxs(D,{className:"flex flex-row items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Reabrir Conversa"}),a.jsx(zt,{children:"Reabre conversa ao receber mensagem"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:o.value,onCheckedChange:o.onChange})})]})}),a.jsx(R,{control:n.control,name:"importContacts",render:({field:o})=>a.jsxs(D,{className:"flex flex-row items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Importar Contatos"}),a.jsx(zt,{children:"Importa contatos da agenda do whatsapp ao conectar o qrcode"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:o.value,onCheckedChange:o.onChange})})]})}),a.jsx(R,{control:n.control,name:"importMessages",render:({field:o})=>a.jsxs(D,{className:"flex flex-row items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Importar Mensagens"}),a.jsx(zt,{children:"Importa conversas e mensagens do whatsapp ao conectar o qrcode"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:o.value,onCheckedChange:o.onChange})})]})}),a.jsx(R,{control:n.control,name:"daysLimitImportMessages",render:({field:o})=>a.jsx(Y,{...o,className:"border border-gray-600 w-full",placeholder:"Limite de Dias para Importar Mensagens",type:"number"})}),a.jsx(R,{control:n.control,name:"autoCreate",render:({field:o})=>a.jsxs(D,{className:"flex flex-row items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Criar Automaticamente"}),a.jsx(zt,{children:"Cria automaticamente integração com chatwoot ao Salvar"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:o.value,onCheckedChange:o.onChange})})]})})]})]}),a.jsx(Te,{type:"button",onClick:r,children:"Salvar"})]})})})})}const Lo=({size:e=45,className:t,...n})=>a.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:a.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,...n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:Re("animate-spin",t),children:a.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})}),Y0=e=>{switch(e){case"open":return"status-connected";case"close":return"status-disconnected";case"connecting":return"status-connecting";default:return"status-disconnected"}},x3=e=>{switch(e){case"open":return"Conectado";case"close":return"Desconectado";case"connecting":return"Conectando";default:return"Desconectado"}};function w3(){var h,m,g;const[e,t]=y.useState(""),[n,r]=y.useState(""),o=localStorage.getItem("token"),[s,i]=y.useState([]),{instance:l}=Tt(),c=()=>{window.location.reload()},u=async w=>{try{await qM(w),window.location.reload()}catch(x){console.error("Erro ao reiniciar:",x)}},f=async w=>{try{await w_(w),window.location.reload()}catch(x){console.error("Erro ao desconectar:",x)}},p=async(w,x)=>{try{if(t(""),!o){console.error("Token não encontrado.");return}if(x){const v=await e0(w,o,l==null?void 0:l.number);r(v.pairingCode)}else{const v=await e0(w,o);t(v.base64)}}catch(v){console.error("Erro ao conectar:",v)}},d=()=>{t(""),r(""),window.location.reload()};return l?a.jsxs(a.Fragment,{children:[a.jsx("main",{className:"dashboard-instance",children:a.jsxs("div",{className:"dashboard-card",children:[a.jsxs("div",{className:"dashboard-info",children:[a.jsxs("div",{className:`dashboard-status ${Y0(l.connectionStatus)}`,children:[a.jsx("i",{className:`status-icon ${Y0(l.connectionStatus)}`}),a.jsx("span",{className:"status-text",children:x3(l.connectionStatus)})]}),a.jsx("div",{className:"dashboard-name",children:l.name}),a.jsx("div",{className:"dashboard-description",children:l.ownerJid}),a.jsxs("div",{className:"card-id",children:[a.jsx("span",{children:s.includes(l.token)?l.token.substring(0,32)+"...":l.token.substring(0,32).split("").map(()=>"*").join("")}),a.jsx(S_,{className:"card-icon",size:"15",onClick:()=>{MT(l.token)}}),s.includes(l.token)?a.jsx(C_,{className:"card-icon",size:"15",onClick:()=>{i(s.filter(w=>w!==l.token))}}):a.jsx(j_,{className:"card-icon",size:"15",onClick:()=>{i([...s,l.token])}})]}),l.connectionStatus!=="open"&&a.jsxs("div",{className:"connection-warning",children:[a.jsx("span",{children:"Telefone não conectado"}),a.jsxs(Sn,{children:[a.jsx(Cn,{className:"connect-button",onClick:()=>p(l.name,!1),children:"Gerar QRCODE"}),a.jsx(un,{onCloseAutoFocus:d,children:a.jsx(dn,{children:a.jsx(Pi,{children:e?a.jsx("img",{src:e,alt:"QR Code",width:"500"}):a.jsx("img",{src:"/assets/images/evolution-logo.png",alt:"Carregando...",width:"500"})})})})]}),l.number&&a.jsxs(Sn,{children:[a.jsx(Cn,{className:"connect-code-button",onClick:()=>p(l.name,!0),children:"Solicitar Código"}),a.jsx(un,{onCloseAutoFocus:d,children:a.jsx(dn,{children:a.jsx(Pi,{children:n?a.jsxs("div",{className:"py-3",children:[a.jsx("p",{className:"text-center",children:a.jsx("strong",{children:"Código de emparelhamento:"})}),a.jsxs("p",{className:"text-center pairing-code",children:[n.substring(0,4),"-",n.substring(4,8)]})]}):a.jsx(Lo,{})})})})]})]})]}),a.jsxs("div",{className:"dashboard-actions",children:[a.jsx(Te,{variant:"outline",className:"refresh-button",children:a.jsx(__,{onClick:c,size:"20"})}),a.jsx(Te,{className:"action-button",onClick:()=>u(l.name),children:"REINICIAR"}),a.jsx(Te,{className:`action-button ${l.connectionStatus==="close"?"disabled":""}`,onClick:()=>f(l.name),disabled:l.connectionStatus==="close",children:"DESCONECTAR"})]})]},l.id)}),a.jsxs("main",{className:"instance-cards",children:[a.jsxs(mi,{className:"instance-card",children:[a.jsx(ql,{children:a.jsx(Zl,{children:"Contatos"})}),a.jsx(Jl,{children:((h=l==null?void 0:l._count)==null?void 0:h.Contact)||0})]}),a.jsxs(mi,{className:"instance-card",children:[a.jsx(ql,{children:a.jsx(Zl,{children:"Chats"})}),a.jsx(Jl,{children:((m=l==null?void 0:l._count)==null?void 0:m.Chat)||0})]}),a.jsxs(mi,{className:"instance-card",children:[a.jsx(ql,{children:a.jsx(Zl,{children:"Mensagens"})}),a.jsx(Jl,{children:((g=l==null?void 0:l._count)==null?void 0:g.Message)||0})]})]})]}):a.jsx(Lo,{})}var b3="Separator",X0="horizontal",S3=["horizontal","vertical"],QN=y.forwardRef((e,t)=>{const{decorative:n,orientation:r=X0,...o}=e,s=C3(r)?r:X0,l=n?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return a.jsx(Ve.div,{"data-orientation":s,...l,...o,ref:t})});QN.displayName=b3;function C3(e){return S3.includes(e)}var ek=QN;const Dt=y.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>a.jsx(ek,{ref:o,decorative:n,orientation:t,className:Re("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Dt.displayName=ek.displayName;const lr=new zr,tk=async(e,t)=>(await lr.getInstance().get(`/openai/creds/${e}`,{headers:{apikey:t}})).data,j3=async(e,t,n)=>(await lr.getInstance().post(`/openai/creds/${e}`,n,{headers:{apikey:t}})).data,_3=async(e,t)=>(await lr.getInstance().delete(`/openai/creds/${e}/${t}`)).data,nk=async(e,t)=>(await lr.getInstance().get(`/openai/find/${e}`,{headers:{apikey:t}})).data,E3=async(e,t,n)=>(await lr.getInstance().get(`/openai/fetch/${n}/${e}`,{headers:{apikey:t}})).data,T3=async(e,t,n)=>(await lr.getInstance().post(`/openai/create/${e}`,n,{headers:{apikey:t}})).data,N3=async(e,t,n,r)=>(await lr.getInstance().put(`/openai/update/${n}/${e}`,r,{headers:{apikey:t}})).data,k3=async(e,t,n)=>(await lr.getInstance().delete(`/openai/delete/${n}/${e}`,{headers:{apikey:t}})).data,R3=async(e,t)=>(await lr.getInstance().get(`/openai/fetchSettings/${e}`,{headers:{apikey:t}})).data,P3=async(e,t,n)=>(await lr.getInstance().post(`/openai/settings/${e}`,n,{headers:{apikey:t}})).data,I3=async(e,t,n)=>(await lr.getInstance().get(`/openai/fetchSessions/${n}/${e}`,{headers:{apikey:t}})).data,D3=async(e,t,n,r)=>(await lr.getInstance().post(`/openai/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data,rk=async(e,t)=>(await lr.getInstance().get(`/openai/getModels/${e}`,{headers:{apikey:t}})).data;/** - * table-core - * - * Copyright (c) TanStack - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function ps(e,t){return typeof e=="function"?e(t):e}function or(e,t){return n=>{t.setState(r=>({...r,[e]:ps(n,r[e])}))}}function Rp(e){return e instanceof Function}function O3(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function M3(e,t){const n=[],r=o=>{o.forEach(s=>{n.push(s);const i=t(s);i!=null&&i.length&&r(i)})};return r(e),n}function Oe(e,t,n){let r=[],o;return s=>{let i;n.key&&n.debug&&(i=Date.now());const l=e(s);if(!(l.length!==r.length||l.some((f,p)=>r[p]!==f)))return o;r=l;let u;if(n.key&&n.debug&&(u=Date.now()),o=t(...l),n==null||n.onChange==null||n.onChange(o),n.key&&n.debug&&n!=null&&n.debug()){const f=Math.round((Date.now()-i)*100)/100,p=Math.round((Date.now()-u)*100)/100,d=p/16,h=(m,g)=>{for(m=String(m);m.length{var o;return(o=e==null?void 0:e.debugAll)!=null?o:e[t]},key:!1,onChange:r}}function A3(e,t,n,r){const o=()=>{var i;return(i=s.getValue())!=null?i:e.options.renderFallbackValue},s={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:o,getContext:Oe(()=>[e,n,t,s],(i,l,c,u)=>({table:i,column:l,row:c,cell:u,getValue:u.getValue,renderValue:u.renderValue}),Me(e.options,"debugCells"))};return e._features.forEach(i=>{i.createCell==null||i.createCell(s,n,t,e)},{}),s}function F3(e,t,n,r){var o,s;const l={...e._getDefaultColumnDef(),...t},c=l.accessorKey;let u=(o=(s=l.id)!=null?s:c?c.replace(".","_"):void 0)!=null?o:typeof l.header=="string"?l.header:void 0,f;if(l.accessorFn?f=l.accessorFn:c&&(c.includes(".")?f=d=>{let h=d;for(const g of c.split(".")){var m;h=(m=h)==null?void 0:m[g]}return h}:f=d=>d[l.accessorKey]),!u)throw new Error;let p={id:`${String(u)}`,accessorFn:f,parent:r,depth:n,columnDef:l,columns:[],getFlatColumns:Oe(()=>[!0],()=>{var d;return[p,...(d=p.columns)==null?void 0:d.flatMap(h=>h.getFlatColumns())]},Me(e.options,"debugColumns")),getLeafColumns:Oe(()=>[e._getOrderColumnsFn()],d=>{var h;if((h=p.columns)!=null&&h.length){let m=p.columns.flatMap(g=>g.getLeafColumns());return d(m)}return[p]},Me(e.options,"debugColumns"))};for(const d of e._features)d.createColumn==null||d.createColumn(p,e);return p}const mn="debugHeaders";function Q0(e,t,n){var r;let s={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const i=[],l=c=>{c.subHeaders&&c.subHeaders.length&&c.subHeaders.map(l),i.push(c)};return l(s),i},getContext:()=>({table:e,header:s,column:t})};return e._features.forEach(i=>{i.createHeader==null||i.createHeader(s,e)}),s}const L3={createTable:e=>{e.getHeaderGroups=Oe(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,o)=>{var s,i;const l=(s=r==null?void 0:r.map(p=>n.find(d=>d.id===p)).filter(Boolean))!=null?s:[],c=(i=o==null?void 0:o.map(p=>n.find(d=>d.id===p)).filter(Boolean))!=null?i:[],u=n.filter(p=>!(r!=null&&r.includes(p.id))&&!(o!=null&&o.includes(p.id)));return Ju(t,[...l,...u,...c],e)},Me(e.options,mn)),e.getCenterHeaderGroups=Oe(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,o)=>(n=n.filter(s=>!(r!=null&&r.includes(s.id))&&!(o!=null&&o.includes(s.id))),Ju(t,n,e,"center")),Me(e.options,mn)),e.getLeftHeaderGroups=Oe(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var o;const s=(o=r==null?void 0:r.map(i=>n.find(l=>l.id===i)).filter(Boolean))!=null?o:[];return Ju(t,s,e,"left")},Me(e.options,mn)),e.getRightHeaderGroups=Oe(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var o;const s=(o=r==null?void 0:r.map(i=>n.find(l=>l.id===i)).filter(Boolean))!=null?o:[];return Ju(t,s,e,"right")},Me(e.options,mn)),e.getFooterGroups=Oe(()=>[e.getHeaderGroups()],t=>[...t].reverse(),Me(e.options,mn)),e.getLeftFooterGroups=Oe(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),Me(e.options,mn)),e.getCenterFooterGroups=Oe(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),Me(e.options,mn)),e.getRightFooterGroups=Oe(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),Me(e.options,mn)),e.getFlatHeaders=Oe(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),Me(e.options,mn)),e.getLeftFlatHeaders=Oe(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),Me(e.options,mn)),e.getCenterFlatHeaders=Oe(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),Me(e.options,mn)),e.getRightFlatHeaders=Oe(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),Me(e.options,mn)),e.getCenterLeafHeaders=Oe(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Me(e.options,mn)),e.getLeftLeafHeaders=Oe(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Me(e.options,mn)),e.getRightLeafHeaders=Oe(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Me(e.options,mn)),e.getLeafHeaders=Oe(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var o,s,i,l,c,u;return[...(o=(s=t[0])==null?void 0:s.headers)!=null?o:[],...(i=(l=n[0])==null?void 0:l.headers)!=null?i:[],...(c=(u=r[0])==null?void 0:u.headers)!=null?c:[]].map(f=>f.getLeafHeaders()).flat()},Me(e.options,mn))}};function Ju(e,t,n,r){var o,s;let i=0;const l=function(d,h){h===void 0&&(h=1),i=Math.max(i,h),d.filter(m=>m.getIsVisible()).forEach(m=>{var g;(g=m.columns)!=null&&g.length&&l(m.columns,h+1)},0)};l(e);let c=[];const u=(d,h)=>{const m={depth:h,id:[r,`${h}`].filter(Boolean).join("_"),headers:[]},g=[];d.forEach(w=>{const x=[...g].reverse()[0],v=w.column.depth===m.depth;let b,C=!1;if(v&&w.column.parent?b=w.column.parent:(b=w.column,C=!0),x&&(x==null?void 0:x.column)===b)x.subHeaders.push(w);else{const j=Q0(n,b,{id:[r,h,b.id,w==null?void 0:w.id].filter(Boolean).join("_"),isPlaceholder:C,placeholderId:C?`${g.filter(S=>S.column===b).length}`:void 0,depth:h,index:g.length});j.subHeaders.push(w),g.push(j)}m.headers.push(w),w.headerGroup=m}),c.push(m),h>0&&u(g,h-1)},f=t.map((d,h)=>Q0(n,d,{depth:i,index:h}));u(f,i-1),c.reverse();const p=d=>d.filter(m=>m.column.getIsVisible()).map(m=>{let g=0,w=0,x=[0];m.subHeaders&&m.subHeaders.length?(x=[],p(m.subHeaders).forEach(b=>{let{colSpan:C,rowSpan:j}=b;g+=C,x.push(j)})):g=1;const v=Math.min(...x);return w=w+v,m.colSpan=g,m.rowSpan=w,{colSpan:g,rowSpan:w}});return p((o=(s=c[0])==null?void 0:s.headers)!=null?o:[]),c}const qy=(e,t,n,r,o,s,i)=>{let l={id:t,index:r,original:n,depth:o,parentId:i,_valuesCache:{},_uniqueValuesCache:{},getValue:c=>{if(l._valuesCache.hasOwnProperty(c))return l._valuesCache[c];const u=e.getColumn(c);if(u!=null&&u.accessorFn)return l._valuesCache[c]=u.accessorFn(l.original,r),l._valuesCache[c]},getUniqueValues:c=>{if(l._uniqueValuesCache.hasOwnProperty(c))return l._uniqueValuesCache[c];const u=e.getColumn(c);if(u!=null&&u.accessorFn)return u.columnDef.getUniqueValues?(l._uniqueValuesCache[c]=u.columnDef.getUniqueValues(l.original,r),l._uniqueValuesCache[c]):(l._uniqueValuesCache[c]=[l.getValue(c)],l._uniqueValuesCache[c])},renderValue:c=>{var u;return(u=l.getValue(c))!=null?u:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>M3(l.subRows,c=>c.subRows),getParentRow:()=>l.parentId?e.getRow(l.parentId,!0):void 0,getParentRows:()=>{let c=[],u=l;for(;;){const f=u.getParentRow();if(!f)break;c.push(f),u=f}return c.reverse()},getAllCells:Oe(()=>[e.getAllLeafColumns()],c=>c.map(u=>A3(e,l,u,u.id)),Me(e.options,"debugRows")),_getAllCellsByColumnId:Oe(()=>[l.getAllCells()],c=>c.reduce((u,f)=>(u[f.column.id]=f,u),{}),Me(e.options,"debugRows"))};for(let c=0;c{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},ok=(e,t,n)=>{var r;const o=n.toLowerCase();return!!(!((r=e.getValue(t))==null||(r=r.toString())==null||(r=r.toLowerCase())==null)&&r.includes(o))};ok.autoRemove=e=>Mr(e);const sk=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};sk.autoRemove=e=>Mr(e);const ak=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===(n==null?void 0:n.toLowerCase())};ak.autoRemove=e=>Mr(e);const ik=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};ik.autoRemove=e=>Mr(e)||!(e!=null&&e.length);const lk=(e,t,n)=>!n.some(r=>{var o;return!((o=e.getValue(t))!=null&&o.includes(r))});lk.autoRemove=e=>Mr(e)||!(e!=null&&e.length);const ck=(e,t,n)=>n.some(r=>{var o;return(o=e.getValue(t))==null?void 0:o.includes(r)});ck.autoRemove=e=>Mr(e)||!(e!=null&&e.length);const uk=(e,t,n)=>e.getValue(t)===n;uk.autoRemove=e=>Mr(e);const dk=(e,t,n)=>e.getValue(t)==n;dk.autoRemove=e=>Mr(e);const Zy=(e,t,n)=>{let[r,o]=n;const s=e.getValue(t);return s>=r&&s<=o};Zy.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,o=typeof n!="number"?parseFloat(n):n,s=t===null||Number.isNaN(r)?-1/0:r,i=n===null||Number.isNaN(o)?1/0:o;if(s>i){const l=s;s=i,i=l}return[s,i]};Zy.autoRemove=e=>Mr(e)||Mr(e[0])&&Mr(e[1]);const yo={includesString:ok,includesStringSensitive:sk,equalsString:ak,arrIncludes:ik,arrIncludesAll:lk,arrIncludesSome:ck,equals:uk,weakEquals:dk,inNumberRange:Zy};function Mr(e){return e==null||e===""}const z3={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:or("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n==null?void 0:n.getValue(e.id);return typeof r=="string"?yo.includesString:typeof r=="number"?yo.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?yo.equals:Array.isArray(r)?yo.arrIncludes:yo.weakEquals},e.getFilterFn=()=>{var n,r;return Rp(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:yo[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,o;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((o=t.options.enableFilters)!=null?o:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(o=>o.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const o=e.getFilterFn(),s=r==null?void 0:r.find(f=>f.id===e.id),i=ps(n,s?s.value:void 0);if(eb(o,i,e)){var l;return(l=r==null?void 0:r.filter(f=>f.id!==e.id))!=null?l:[]}const c={id:e.id,value:i};if(s){var u;return(u=r==null?void 0:r.map(f=>f.id===e.id?c:f))!=null?u:[]}return r!=null&&r.length?[...r,c]:[c]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=o=>{var s;return(s=ps(t,o))==null?void 0:s.filter(i=>{const l=n.find(c=>c.id===i.id);if(l){const c=l.getFilterFn();if(eb(c,i.value,l))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function eb(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const V3=(e,t,n)=>n.reduce((r,o)=>{const s=o.getValue(e);return r+(typeof s=="number"?s:0)},0),U3=(e,t,n)=>{let r;return n.forEach(o=>{const s=o.getValue(e);s!=null&&(r>s||r===void 0&&s>=s)&&(r=s)}),r},B3=(e,t,n)=>{let r;return n.forEach(o=>{const s=o.getValue(e);s!=null&&(r=s)&&(r=s)}),r},H3=(e,t,n)=>{let r,o;return n.forEach(s=>{const i=s.getValue(e);i!=null&&(r===void 0?i>=i&&(r=o=i):(r>i&&(r=i),o{let n=0,r=0;if(t.forEach(o=>{let s=o.getValue(e);s!=null&&(s=+s)>=s&&(++n,r+=s)}),n)return r/n},W3=(e,t)=>{if(!t.length)return;const n=t.map(s=>s.getValue(e));if(!O3(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),o=n.sort((s,i)=>s-i);return n.length%2!==0?o[r]:(o[r-1]+o[r])/2},K3=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),q3=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,Z3=(e,t)=>t.length,Vh={sum:V3,min:U3,max:B3,extent:H3,mean:G3,median:W3,unique:K3,uniqueCount:q3,count:Z3},J3={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:or("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n==null?void 0:n.getValue(e.id);if(typeof r=="number")return Vh.sum;if(Object.prototype.toString.call(r)==="[object Date]")return Vh.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return Rp(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:Vh[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var o;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((o=n.subRows)!=null&&o.length)}}};function Y3(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(s=>!t.includes(s.id));return n==="remove"?r:[...t.map(s=>e.find(i=>i.id===s)).filter(Boolean),...r]}const X3={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:or("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=Oe(n=>[ec(t,n)],n=>n.findIndex(r=>r.id===e.id),Me(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=ec(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const o=ec(t,n);return((r=o[o.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=Oe(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>o=>{let s=[];if(!(t!=null&&t.length))s=o;else{const i=[...t],l=[...o];for(;l.length&&i.length;){const c=i.shift(),u=l.findIndex(f=>f.id===c);u>-1&&s.push(l.splice(u,1)[0])}s=[...s,...l]}return Y3(s,n,r)},Me(e.options,"debugTable"))}},Uh=()=>({left:[],right:[]}),Q3={getInitialState:e=>({columnPinning:Uh(),...e}),getDefaultOptions:e=>({onColumnPinningChange:or("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(o=>o.id).filter(Boolean);t.setColumnPinning(o=>{var s,i;if(n==="right"){var l,c;return{left:((l=o==null?void 0:o.left)!=null?l:[]).filter(p=>!(r!=null&&r.includes(p))),right:[...((c=o==null?void 0:o.right)!=null?c:[]).filter(p=>!(r!=null&&r.includes(p))),...r]}}if(n==="left"){var u,f;return{left:[...((u=o==null?void 0:o.left)!=null?u:[]).filter(p=>!(r!=null&&r.includes(p))),...r],right:((f=o==null?void 0:o.right)!=null?f:[]).filter(p=>!(r!=null&&r.includes(p)))}}return{left:((s=o==null?void 0:o.left)!=null?s:[]).filter(p=>!(r!=null&&r.includes(p))),right:((i=o==null?void 0:o.right)!=null?i:[]).filter(p=>!(r!=null&&r.includes(p)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var o,s,i;return((o=r.columnDef.enablePinning)!=null?o:!0)&&((s=(i=t.options.enableColumnPinning)!=null?i:t.options.enablePinning)!=null?s:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(l=>l.id),{left:r,right:o}=t.getState().columnPinning,s=n.some(l=>r==null?void 0:r.includes(l)),i=n.some(l=>o==null?void 0:o.includes(l));return s?"left":i?"right":!1},e.getPinnedIndex=()=>{var n,r;const o=e.getIsPinned();return o?(n=(r=t.getState().columnPinning)==null||(r=r[o])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=Oe(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,o)=>{const s=[...r??[],...o??[]];return n.filter(i=>!s.includes(i.column.id))},Me(t.options,"debugRows")),e.getLeftVisibleCells=Oe(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(s=>n.find(i=>i.column.id===s)).filter(Boolean).map(s=>({...s,position:"left"})),Me(t.options,"debugRows")),e.getRightVisibleCells=Oe(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(s=>n.find(i=>i.column.id===s)).filter(Boolean).map(s=>({...s,position:"right"})),Me(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?Uh():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:Uh())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var o,s;return!!((o=r.left)!=null&&o.length||(s=r.right)!=null&&s.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=Oe(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(o=>o.id===r)).filter(Boolean),Me(e.options,"debugColumns")),e.getRightLeafColumns=Oe(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(o=>o.id===r)).filter(Boolean),Me(e.options,"debugColumns")),e.getCenterLeafColumns=Oe(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const o=[...n??[],...r??[]];return t.filter(s=>!o.includes(s.id))},Me(e.options,"debugColumns"))}},Yu={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},Bh=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),eU={getDefaultColumnDef:()=>Yu,getInitialState:e=>({columnSizing:{},columnSizingInfo:Bh(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:or("columnSizing",e),onColumnSizingInfoChange:or("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,o;const s=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Yu.minSize,(r=s??e.columnDef.size)!=null?r:Yu.size),(o=e.columnDef.maxSize)!=null?o:Yu.maxSize)},e.getStart=Oe(n=>[n,ec(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((o,s)=>o+s.getSize(),0),Me(t.options,"debugColumns")),e.getAfter=Oe(n=>[n,ec(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((o,s)=>o+s.getSize(),0),Me(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...o}=n;return o})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=o=>{if(o.subHeaders.length)o.subHeaders.forEach(r);else{var s;n+=(s=o.column.getSize())!=null?s:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),o=r==null?void 0:r.getCanResize();return s=>{if(!r||!o||(s.persist==null||s.persist(),Hh(s)&&s.touches&&s.touches.length>1))return;const i=e.getSize(),l=e?e.getLeafHeaders().map(x=>[x.column.id,x.column.getSize()]):[[r.id,r.getSize()]],c=Hh(s)?Math.round(s.touches[0].clientX):s.clientX,u={},f=(x,v)=>{typeof v=="number"&&(t.setColumnSizingInfo(b=>{var C,j;const S=t.options.columnResizeDirection==="rtl"?-1:1,N=(v-((C=b==null?void 0:b.startOffset)!=null?C:0))*S,E=Math.max(N/((j=b==null?void 0:b.startSize)!=null?j:0),-.999999);return b.columnSizingStart.forEach(A=>{let[F,Z]=A;u[F]=Math.round(Math.max(Z+Z*E,0)*100)/100}),{...b,deltaOffset:N,deltaPercentage:E}}),(t.options.columnResizeMode==="onChange"||x==="end")&&t.setColumnSizing(b=>({...b,...u})))},p=x=>f("move",x),d=x=>{f("end",x),t.setColumnSizingInfo(v=>({...v,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},h=n||typeof document<"u"?document:null,m={moveHandler:x=>p(x.clientX),upHandler:x=>{h==null||h.removeEventListener("mousemove",m.moveHandler),h==null||h.removeEventListener("mouseup",m.upHandler),d(x.clientX)}},g={moveHandler:x=>(x.cancelable&&(x.preventDefault(),x.stopPropagation()),p(x.touches[0].clientX),!1),upHandler:x=>{var v;h==null||h.removeEventListener("touchmove",g.moveHandler),h==null||h.removeEventListener("touchend",g.upHandler),x.cancelable&&(x.preventDefault(),x.stopPropagation()),d((v=x.touches[0])==null?void 0:v.clientX)}},w=tU()?{passive:!1}:!1;Hh(s)?(h==null||h.addEventListener("touchmove",g.moveHandler,w),h==null||h.addEventListener("touchend",g.upHandler,w)):(h==null||h.addEventListener("mousemove",m.moveHandler,w),h==null||h.addEventListener("mouseup",m.upHandler,w)),t.setColumnSizingInfo(x=>({...x,startOffset:c,startSize:i,deltaOffset:0,deltaPercentage:0,columnSizingStart:l,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?Bh():(n=e.initialState.columnSizingInfo)!=null?n:Bh())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,o)=>r+o.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,o)=>r+o.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,o)=>r+o.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,o)=>r+o.getSize(),0))!=null?t:0}}};let Xu=null;function tU(){if(typeof Xu=="boolean")return Xu;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Xu=e,Xu}function Hh(e){return e.type==="touchstart"}const nU={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:or("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const o=e.columns;return(n=o.length?o.some(s=>s.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=Oe(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),Me(t.options,"debugRows")),e.getVisibleCells=Oe(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,o)=>[...n,...r,...o],Me(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>Oe(()=>[r(),r().filter(o=>o.getIsVisible()).map(o=>o.id).join("_")],o=>o.filter(s=>s.getIsVisible==null?void 0:s.getIsVisible()),Me(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((o,s)=>({...o,[s.id]:n||!(s.getCanHide!=null&&s.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function ec(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const rU={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},oU={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:or("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,o,s;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((o=t.options.enableFilters)!=null?o:!0)&&((s=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?s:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>yo.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return Rp(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:yo[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},sU={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:or("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,o;if(!t){e._queue(()=>{t=!0});return}if((r=(o=e.options.autoResetAll)!=null?o:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var o,s;e.setExpanded(r?{}:(o=(s=e.initialState)==null?void 0:s.expanded)!=null?o:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(o=>!o.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(s=>{const i=s.split(".");r=Math.max(r,i.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var o;const s=r===!0?!0:!!(r!=null&&r[e.id]);let i={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(l=>{i[l]=!0}):i=r,n=(o=n)!=null?o:!s,!s&&n)return{...i,[e.id]:!0};if(s&&!n){const{[e.id]:l,...c}=i;return c}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r!=null&&r[e.id])},e.getCanExpand=()=>{var n,r,o;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((o=e.subRows)!=null&&o.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},Pm=0,Im=10,Gh=()=>({pageIndex:Pm,pageSize:Im}),aU={getInitialState:e=>({...e,pagination:{...Gh(),...e==null?void 0:e.pagination}}),getDefaultOptions:e=>({onPaginationChange:or("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,o;if(!t){e._queue(()=>{t=!0});return}if((r=(o=e.options.autoResetAll)!=null?o:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const o=s=>ps(r,s);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(o)},e.resetPagination=r=>{var o;e.setPagination(r?Gh():(o=e.initialState.pagination)!=null?o:Gh())},e.setPageIndex=r=>{e.setPagination(o=>{let s=ps(r,o.pageIndex);const i=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return s=Math.max(0,Math.min(s,i)),{...o,pageIndex:s}})},e.resetPageIndex=r=>{var o,s;e.setPageIndex(r?Pm:(o=(s=e.initialState)==null||(s=s.pagination)==null?void 0:s.pageIndex)!=null?o:Pm)},e.resetPageSize=r=>{var o,s;e.setPageSize(r?Im:(o=(s=e.initialState)==null||(s=s.pagination)==null?void 0:s.pageSize)!=null?o:Im)},e.setPageSize=r=>{e.setPagination(o=>{const s=Math.max(1,ps(r,o.pageSize)),i=o.pageSize*o.pageIndex,l=Math.floor(i/s);return{...o,pageIndex:l,pageSize:s}})},e.setPageCount=r=>e.setPagination(o=>{var s;let i=ps(r,(s=e.options.pageCount)!=null?s:-1);return typeof i=="number"&&(i=Math.max(-1,i)),{...o,pageCount:i}}),e.getPageOptions=Oe(()=>[e.getPageCount()],r=>{let o=[];return r&&r>0&&(o=[...new Array(r)].fill(null).map((s,i)=>i)),o},Me(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,o=e.getPageCount();return o===-1?!0:o===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},Wh=()=>({top:[],bottom:[]}),iU={getInitialState:e=>({rowPinning:Wh(),...e}),getDefaultOptions:e=>({onRowPinningChange:or("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,o)=>{const s=r?e.getLeafRows().map(c=>{let{id:u}=c;return u}):[],i=o?e.getParentRows().map(c=>{let{id:u}=c;return u}):[],l=new Set([...i,e.id,...s]);t.setRowPinning(c=>{var u,f;if(n==="bottom"){var p,d;return{top:((p=c==null?void 0:c.top)!=null?p:[]).filter(g=>!(l!=null&&l.has(g))),bottom:[...((d=c==null?void 0:c.bottom)!=null?d:[]).filter(g=>!(l!=null&&l.has(g))),...Array.from(l)]}}if(n==="top"){var h,m;return{top:[...((h=c==null?void 0:c.top)!=null?h:[]).filter(g=>!(l!=null&&l.has(g))),...Array.from(l)],bottom:((m=c==null?void 0:c.bottom)!=null?m:[]).filter(g=>!(l!=null&&l.has(g)))}}return{top:((u=c==null?void 0:c.top)!=null?u:[]).filter(g=>!(l!=null&&l.has(g))),bottom:((f=c==null?void 0:c.bottom)!=null?f:[]).filter(g=>!(l!=null&&l.has(g)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:o}=t.options;return typeof r=="function"?r(e):(n=r??o)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:o}=t.getState().rowPinning,s=n.some(l=>r==null?void 0:r.includes(l)),i=n.some(l=>o==null?void 0:o.includes(l));return s?"top":i?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const o=e.getIsPinned();if(!o)return-1;const s=(n=o==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(i=>{let{id:l}=i;return l});return(r=s==null?void 0:s.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?Wh():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:Wh())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var o,s;return!!((o=r.top)!=null&&o.length||(s=r.bottom)!=null&&s.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var o;return((o=e.options.keepPinnedRows)==null||o?(n??[]).map(i=>{const l=e.getRow(i,!0);return l.getIsAllParentsExpanded()?l:null}):(n??[]).map(i=>t.find(l=>l.id===i))).filter(Boolean).map(i=>({...i,position:r}))},e.getTopRows=Oe(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),Me(e.options,"debugRows")),e.getBottomRows=Oe(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),Me(e.options,"debugRows")),e.getCenterRows=Oe(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const o=new Set([...n??[],...r??[]]);return t.filter(s=>!o.has(s.id))},Me(e.options,"debugRows"))}},lU={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:or("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},o=e.getPreGroupedRowModel().flatRows;return t?o.forEach(s=>{s.getCanSelect()&&(r[s.id]=!0)}):o.forEach(s=>{delete r[s.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),o={...n};return e.getRowModel().rows.forEach(s=>{Dm(o,s.id,r,!0,e)}),o}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=Oe(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?Kh(e,n):{rows:[],flatRows:[],rowsById:{}},Me(e.options,"debugTable")),e.getFilteredSelectedRowModel=Oe(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?Kh(e,n):{rows:[],flatRows:[],rowsById:{}},Me(e.options,"debugTable")),e.getGroupedSelectedRowModel=Oe(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?Kh(e,n):{rows:[],flatRows:[],rowsById:{}},Me(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(o=>o.getCanSelect()&&!n[o.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(o=>o.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(o=>!n[o.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const o=e.getIsSelected();t.setRowSelection(s=>{var i;if(n=typeof n<"u"?n:!o,e.getCanSelect()&&o===n)return s;const l={...s};return Dm(l,e.id,n,(i=r==null?void 0:r.selectChildren)!=null?i:!0,t),l})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return Jy(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return Om(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return Om(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var o;n&&e.toggleSelected((o=r.target)==null?void 0:o.checked)}}}},Dm=(e,t,n,r,o)=>{var s;const i=o.getRow(t,!0);n?(i.getCanMultiSelect()||Object.keys(e).forEach(l=>delete e[l]),i.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(s=i.subRows)!=null&&s.length&&i.getCanSelectSubRows()&&i.subRows.forEach(l=>Dm(e,l.id,n,r,o))};function Kh(e,t){const n=e.getState().rowSelection,r=[],o={},s=function(i,l){return i.map(c=>{var u;const f=Jy(c,n);if(f&&(r.push(c),o[c.id]=c),(u=c.subRows)!=null&&u.length&&(c={...c,subRows:s(c.subRows)}),f)return c}).filter(Boolean)};return{rows:s(t.rows),flatRows:r,rowsById:o}}function Jy(e,t){var n;return(n=t[e.id])!=null?n:!1}function Om(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let o=!0,s=!1;return e.subRows.forEach(i=>{if(!(s&&!o)&&(i.getCanSelect()&&(Jy(i,t)?s=!0:o=!1),i.subRows&&i.subRows.length)){const l=Om(i,t);l==="all"?s=!0:(l==="some"&&(s=!0),o=!1)}}),o?"all":s?"some":!1}const Mm=/([0-9]+)/gm,cU=(e,t,n)=>fk(Is(e.getValue(n)).toLowerCase(),Is(t.getValue(n)).toLowerCase()),uU=(e,t,n)=>fk(Is(e.getValue(n)),Is(t.getValue(n))),dU=(e,t,n)=>Yy(Is(e.getValue(n)).toLowerCase(),Is(t.getValue(n)).toLowerCase()),fU=(e,t,n)=>Yy(Is(e.getValue(n)),Is(t.getValue(n))),pU=(e,t,n)=>{const r=e.getValue(n),o=t.getValue(n);return r>o?1:rYy(e.getValue(n),t.getValue(n));function Yy(e,t){return e===t?0:e>t?1:-1}function Is(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function fk(e,t){const n=e.split(Mm).filter(Boolean),r=t.split(Mm).filter(Boolean);for(;n.length&&r.length;){const o=n.shift(),s=r.shift(),i=parseInt(o,10),l=parseInt(s,10),c=[i,l].sort();if(isNaN(c[0])){if(o>s)return 1;if(s>o)return-1;continue}if(isNaN(c[1]))return isNaN(i)?-1:1;if(i>l)return 1;if(l>i)return-1}return n.length-r.length}const Sl={alphanumeric:cU,alphanumericCaseSensitive:uU,text:dU,textCaseSensitive:fU,datetime:pU,basic:hU},gU={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:or("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const o of n){const s=o==null?void 0:o.getValue(e.id);if(Object.prototype.toString.call(s)==="[object Date]")return Sl.datetime;if(typeof s=="string"&&(r=!0,s.split(Mm).length>1))return Sl.alphanumeric}return r?Sl.text:Sl.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof(n==null?void 0:n.getValue(e.id))=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return Rp(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:Sl[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const o=e.getNextSortingOrder(),s=typeof n<"u"&&n!==null;t.setSorting(i=>{const l=i==null?void 0:i.find(h=>h.id===e.id),c=i==null?void 0:i.findIndex(h=>h.id===e.id);let u=[],f,p=s?n:o==="desc";if(i!=null&&i.length&&e.getCanMultiSort()&&r?l?f="toggle":f="add":i!=null&&i.length&&c!==i.length-1?f="replace":l?f="toggle":f="replace",f==="toggle"&&(s||o||(f="remove")),f==="add"){var d;u=[...i,{id:e.id,desc:p}],u.splice(0,u.length-((d=t.options.maxMultiSortColCount)!=null?d:Number.MAX_SAFE_INTEGER))}else f==="toggle"?u=i.map(h=>h.id===e.id?{...h,desc:p}:h):f==="remove"?u=i.filter(h=>h.id!==e.id):u=[{id:e.id,desc:p}];return u})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,o;const s=e.getFirstSortDir(),i=e.getIsSorted();return i?i!==s&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(o=t.options.enableMultiRemove)!=null)||o)?!1:i==="desc"?"asc":"desc":s},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(o=>o.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(o=>o.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},mU=[L3,nU,X3,Q3,$3,z3,rU,oU,gU,J3,sU,aU,iU,lU,eU];function vU(e){var t,n;const r=[...mU,...(t=e._features)!=null?t:[]];let o={_features:r};const s=o._features.reduce((d,h)=>Object.assign(d,h.getDefaultOptions==null?void 0:h.getDefaultOptions(o)),{}),i=d=>o.options.mergeOptions?o.options.mergeOptions(s,d):{...s,...d};let c={...{},...(n=e.initialState)!=null?n:{}};o._features.forEach(d=>{var h;c=(h=d.getInitialState==null?void 0:d.getInitialState(c))!=null?h:c});const u=[];let f=!1;const p={_features:r,options:{...s,...e},initialState:c,_queue:d=>{u.push(d),f||(f=!0,Promise.resolve().then(()=>{for(;u.length;)u.shift()();f=!1}).catch(h=>setTimeout(()=>{throw h})))},reset:()=>{o.setState(o.initialState)},setOptions:d=>{const h=ps(d,o.options);o.options=i(h)},getState:()=>o.options.state,setState:d=>{o.options.onStateChange==null||o.options.onStateChange(d)},_getRowId:(d,h,m)=>{var g;return(g=o.options.getRowId==null?void 0:o.options.getRowId(d,h,m))!=null?g:`${m?[m.id,h].join("."):h}`},getCoreRowModel:()=>(o._getCoreRowModel||(o._getCoreRowModel=o.options.getCoreRowModel(o)),o._getCoreRowModel()),getRowModel:()=>o.getPaginationRowModel(),getRow:(d,h)=>{let m=(h?o.getPrePaginationRowModel():o.getRowModel()).rowsById[d];if(!m&&(m=o.getCoreRowModel().rowsById[d],!m))throw new Error;return m},_getDefaultColumnDef:Oe(()=>[o.options.defaultColumn],d=>{var h;return d=(h=d)!=null?h:{},{header:m=>{const g=m.header.column.columnDef;return g.accessorKey?g.accessorKey:g.accessorFn?g.id:null},cell:m=>{var g,w;return(g=(w=m.renderValue())==null||w.toString==null?void 0:w.toString())!=null?g:null},...o._features.reduce((m,g)=>Object.assign(m,g.getDefaultColumnDef==null?void 0:g.getDefaultColumnDef()),{}),...d}},Me(e,"debugColumns")),_getColumnDefs:()=>o.options.columns,getAllColumns:Oe(()=>[o._getColumnDefs()],d=>{const h=function(m,g,w){return w===void 0&&(w=0),m.map(x=>{const v=F3(o,x,w,g),b=x;return v.columns=b.columns?h(b.columns,v,w+1):[],v})};return h(d)},Me(e,"debugColumns")),getAllFlatColumns:Oe(()=>[o.getAllColumns()],d=>d.flatMap(h=>h.getFlatColumns()),Me(e,"debugColumns")),_getAllFlatColumnsById:Oe(()=>[o.getAllFlatColumns()],d=>d.reduce((h,m)=>(h[m.id]=m,h),{}),Me(e,"debugColumns")),getAllLeafColumns:Oe(()=>[o.getAllColumns(),o._getOrderColumnsFn()],(d,h)=>{let m=d.flatMap(g=>g.getLeafColumns());return h(m)},Me(e,"debugColumns")),getColumn:d=>o._getAllFlatColumnsById()[d]};Object.assign(o,p);for(let d=0;dOe(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(o,s,i){s===void 0&&(s=0);const l=[];for(let u=0;ue._autoResetPageIndex()))}function yU(e){const t=[],n=r=>{var o;t.push(r),(o=r.subRows)!=null&&o.length&&r.getIsExpanded()&&r.subRows.forEach(n)};return e.rows.forEach(n),{rows:t,flatRows:e.flatRows,rowsById:e.rowsById}}function xU(e,t,n){return n.options.filterFromLeafRows?wU(e,t,n):bU(e,t,n)}function wU(e,t,n){var r;const o=[],s={},i=(r=n.options.maxLeafRowFilterDepth)!=null?r:100,l=function(c,u){u===void 0&&(u=0);const f=[];for(let d=0;dOe(()=>[e.getPreFilteredRowModel(),e.getState().columnFilters,e.getState().globalFilter],(t,n,r)=>{if(!t.rows.length||!(n!=null&&n.length)&&!r){for(let d=0;d{var h;const m=e.getColumn(d.id);if(!m)return;const g=m.getFilterFn();g&&o.push({id:d.id,filterFn:g,resolvedValue:(h=g.resolveFilterValue==null?void 0:g.resolveFilterValue(d.value))!=null?h:d.value})});const i=(n??[]).map(d=>d.id),l=e.getGlobalFilterFn(),c=e.getAllLeafColumns().filter(d=>d.getCanGlobalFilter());r&&l&&c.length&&(i.push("__global__"),c.forEach(d=>{var h;s.push({id:d.id,filterFn:l,resolvedValue:(h=l.resolveFilterValue==null?void 0:l.resolveFilterValue(r))!=null?h:r})}));let u,f;for(let d=0;d{h.columnFiltersMeta[g]=w})}if(s.length){for(let m=0;m{h.columnFiltersMeta[g]=w})){h.columnFilters.__global__=!0;break}}h.columnFilters.__global__!==!0&&(h.columnFilters.__global__=!1)}}const p=d=>{for(let h=0;he._autoResetPageIndex()))}function Dp(e){return t=>Oe(()=>[t.getState().pagination,t.getPrePaginationRowModel(),t.options.paginateExpandedRows?void 0:t.getState().expanded],(n,r)=>{if(!r.rows.length)return r;const{pageSize:o,pageIndex:s}=n;let{rows:i,flatRows:l,rowsById:c}=r;const u=o*s,f=u+o;i=i.slice(u,f);let p;t.options.paginateExpandedRows?p={rows:i,flatRows:l,rowsById:c}:p=yU({rows:i,flatRows:l,rowsById:c}),p.flatRows=[];const d=h=>{p.flatRows.push(h),h.subRows.length&&h.subRows.forEach(d)};return p.rows.forEach(d),p},Me(t.options,"debugTable"))}function Op(){return e=>Oe(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,o=[],s=r.filter(c=>{var u;return(u=e.getColumn(c.id))==null?void 0:u.getCanSort()}),i={};s.forEach(c=>{const u=e.getColumn(c.id);u&&(i[c.id]={sortUndefined:u.columnDef.sortUndefined,invertSorting:u.columnDef.invertSorting,sortingFn:u.getSortingFn()})});const l=c=>{const u=c.map(f=>({...f}));return u.sort((f,p)=>{for(let h=0;h{var p;o.push(f),(p=f.subRows)!=null&&p.length&&(f.subRows=l(f.subRows))}),u};return{rows:l(n.rows),flatRows:o,rowsById:n.rowsById}},Me(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}/** - * react-table - * - * Copyright (c) TanStack - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function Ds(e,t){return e?SU(e)?y.createElement(e,t):e:null}function SU(e){return CU(e)||typeof e=="function"||jU(e)}function CU(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function jU(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function Mp(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=y.useState(()=>({current:vU(t)})),[r,o]=y.useState(()=>n.current.initialState);return n.current.setOptions(s=>({...s,...e,state:{...r,...e.state},onStateChange:i=>{o(i),e.onStateChange==null||e.onStateChange(i)}})),n.current}const hu=y.forwardRef(({className:e,...t},n)=>a.jsx("div",{className:"relative w-full overflow-auto",children:a.jsx("table",{ref:n,className:Re("w-full caption-bottom text-sm",e),...t})}));hu.displayName="Table";const gu=y.forwardRef(({className:e,...t},n)=>a.jsx("thead",{ref:n,className:Re("[&_tr]:border-b",e),...t}));gu.displayName="TableHeader";const mu=y.forwardRef(({className:e,...t},n)=>a.jsx("tbody",{ref:n,className:Re("[&_tr:last-child]:border-0",e),...t}));mu.displayName="TableBody";const _U=y.forwardRef(({className:e,...t},n)=>a.jsx("tfoot",{ref:n,className:Re("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",e),...t}));_U.displayName="TableFooter";const nr=y.forwardRef(({className:e,...t},n)=>a.jsx("tr",{ref:n,className:Re("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",e),...t}));nr.displayName="TableRow";const vu=y.forwardRef(({className:e,...t},n)=>a.jsx("th",{ref:n,className:Re("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",e),...t}));vu.displayName="TableHead";const $o=y.forwardRef(({className:e,...t},n)=>a.jsx("td",{ref:n,className:Re("p-4 align-middle [&:has([role=checkbox])]:pr-0",e),...t}));$o.displayName="TableCell";const EU=y.forwardRef(({className:e,...t},n)=>a.jsx("caption",{ref:n,className:Re("mt-4 text-sm text-muted-foreground",e),...t}));EU.displayName="TableCaption";const tb=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const o=await I3(e.name,r,t);n(o)}else console.error("Token ou nome da instância não encontrados.")}catch(r){console.error("Erro ao carregar sessões:",r)}};function TU({openaiBotId:e}){var f,p;const{instance:t}=Tt(),[n,r]=y.useState([]),[o,s]=y.useState([]);y.useEffect(()=>{tb(t,e,s)},[t,e]);function i(){tb(t,e,s)}const l=async(d,h)=>{var m,g,w;try{if(!t)return;await D3(t.name,t.token,d,h),ke.success("Status alterado com sucesso."),i()}catch(x){console.error("Erro ao atualizar:",x),ke.error(`Erro ao atualizar : ${(w=(g=(m=x==null?void 0:x.response)==null?void 0:m.data)==null?void 0:g.response)==null?void 0:w.message}`)}},c=[{accessorKey:"remoteJid",header:()=>a.jsx("div",{className:"text-center",children:"Remote Jid"}),cell:({row:d})=>a.jsx("div",{children:d.getValue("remoteJid")})},{accessorKey:"sessionId",header:()=>a.jsx("div",{className:"text-center",children:"Session ID"}),cell:({row:d})=>a.jsx("div",{children:d.getValue("sessionId")})},{accessorKey:"status",header:()=>a.jsx("div",{className:"text-center",children:"Status"}),cell:({row:d})=>a.jsx("div",{children:d.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:d})=>{const h=d.original;return a.jsxs(Np,{children:[a.jsx(kp,{asChild:!0,children:a.jsxs(Te,{variant:"ghost",className:"h-8 w-8 p-0",children:[a.jsx("span",{className:"sr-only",children:"Open menu"}),a.jsx(ep,{className:"h-4 w-4"})]})}),a.jsxs(qi,{align:"end",children:[a.jsx(pu,{children:"Actions"}),a.jsx(Zi,{}),h.status!=="opened"&&a.jsxs(xn,{onClick:()=>l(h.remoteJid,"opened"),children:[a.jsx(ny,{className:"w-4 h-4 mr-2"}),"Abrir"]}),h.status!=="paused"&&h.status!=="closed"&&a.jsxs(xn,{onClick:()=>l(h.remoteJid,"paused"),children:[a.jsx(ty,{className:"w-4 h-4 mr-2"}),"Pausar"]}),h.status!=="closed"&&a.jsxs(xn,{onClick:()=>l(h.remoteJid,"closed"),children:[a.jsx(Yv,{className:"w-4 h-4 mr-2"}),"Fechar"]}),a.jsxs(xn,{onClick:()=>l(h.remoteJid,"delete"),children:[a.jsx(Xv,{className:"w-4 h-4 mr-2"}),"Excluir"]})]})]})}}],u=Mp({data:o,columns:c,onSortingChange:r,getCoreRowModel:Pp(),getPaginationRowModel:Dp(),getSortedRowModel:Op(),getFilteredRowModel:Ip(),state:{sorting:n}});return a.jsxs(Sn,{children:[a.jsx(Cn,{asChild:!0,children:a.jsxs(Te,{variant:"default",className:"mr-5 text-white",children:[a.jsx(Qv,{})," Sessões"]})}),a.jsxs(un,{className:"sm:max-w-[950px] overflow-y-auto",onCloseAutoFocus:i,children:[a.jsx(dn,{children:a.jsx(On,{children:"Sessões"})}),a.jsxs("div",{children:[a.jsx(Y,{placeholder:"Search by remoteJid...",value:((f=u.getColumn("remoteJid"))==null?void 0:f.getFilterValue())??"",onChange:d=>{var h;return(h=u.getColumn("remoteJid"))==null?void 0:h.setFilterValue(d.target.value)},className:"max-w-sm border border-gray-300 rounded-md"}),a.jsxs(hu,{children:[a.jsx(gu,{children:u.getHeaderGroups().map(d=>a.jsx(nr,{children:d.headers.map(h=>a.jsx(vu,{children:h.isPlaceholder?null:Ds(h.column.columnDef.header,h.getContext())},h.id))},d.id))}),a.jsx(mu,{children:(p=u.getRowModel().rows)!=null&&p.length?u.getRowModel().rows.map(d=>a.jsx(nr,{"data-state":d.getIsSelected()&&"selected",children:d.getVisibleCells().map(h=>a.jsx($o,{children:Ds(h.column.columnDef.cell,h.getContext())},h.id))},d.id)):a.jsx(nr,{children:a.jsx($o,{colSpan:c.length,className:"h-24 text-center",children:"No results."})})})]})]})]})]})}const NU=T.object({enabled:T.boolean(),description:T.string(),openaiCredsId:T.string(),botType:T.string(),assistantId:T.string(),model:T.string(),systemMessages:T.string(),assistantMessages:T.string(),userMessages:T.string(),maxTokens:T.string(),triggerType:T.string(),triggerOperator:T.string().optional(),triggerValue:T.string().optional(),expire:T.string(),keywordFinish:T.string(),delayMessage:T.string(),unknownMessage:T.string(),listeningFromMe:T.boolean(),stopBotFromMe:T.boolean(),keepOpen:T.boolean(),debounceTime:T.string(),ignoreJids:T.array(T.string())});function kU({openaiBotId:e,instance:t,creds:n,resetTable:r}){const[,o]=y.useState(""),[s,i]=y.useState(!0),[l,c]=y.useState(!1),[u,f]=y.useState([]),p=ir(),d=tn({resolver:nn(NU),defaultValues:{enabled:!0,description:"",openaiCredsId:"",botType:"assistant",assistantId:"",model:"gpt-3.5-turbo",systemMessages:"",assistantMessages:"",userMessages:"",maxTokens:"300",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:"0",keywordFinish:"",delayMessage:"0",unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0"}});y.useEffect(()=>{const g=async()=>{try{const x=localStorage.getItem("token");if(x&&t&&t.name&&e){o(x);const v=await E3(t.name,x,e);d.reset({enabled:v.enabled,description:v.description,openaiCredsId:v.openaiCredsId,botType:v.botType,assistantId:v.assistantId,model:v.model,systemMessages:v.systemMessages.toString(),assistantMessages:v.assistantMessages.toString(),userMessages:v.userMessages.toString(),maxTokens:v.maxTokens.toString(),triggerType:v.triggerType,triggerOperator:v.triggerOperator,triggerValue:v.triggerValue,expire:v.expire.toString(),keywordFinish:v.keywordFinish,delayMessage:v.delayMessage.toString(),unknownMessage:v.unknownMessage,listeningFromMe:v.listeningFromMe,stopBotFromMe:v.stopBotFromMe,keepOpen:v.keepOpen,debounceTime:v.debounceTime.toString()})}else console.error("Token ou nome da instância não encontrados.");i(!1)}catch(x){console.error("Erro ao carregar configurações:",x),i(!1)}},w=async()=>{try{if(!t)return;const x=await rk(t.name,t.token);f(x)}catch(x){console.error("Erro ao buscar modelos:",x)}};g(),w()},[d,t,e]);const h=async()=>{var g,w,x;try{const v=d.getValues(),b=localStorage.getItem("token");if(b&&t&&t.name&&e){const C={enabled:v.enabled,description:v.description,openaiCredsId:v.openaiCredsId,botType:v.botType,assistantId:v.assistantId,model:v.model,systemMessages:[v.systemMessages],assistantMessages:[v.assistantMessages],userMessages:[v.userMessages],maxTokens:parseInt(v.maxTokens,10),triggerType:v.triggerType,triggerOperator:v.triggerOperator||"",triggerValue:v.triggerValue||"",expire:parseInt(v.expire,10),keywordFinish:v.keywordFinish,delayMessage:parseInt(v.delayMessage,10),unknownMessage:v.unknownMessage,listeningFromMe:v.listeningFromMe,stopBotFromMe:v.stopBotFromMe,keepOpen:v.keepOpen,debounceTime:parseInt(v.debounceTime,10)};await N3(t.name,b,e,C),ke.success("Bot atualizado com sucesso.")}else console.error("Token ou nome da instância não encontrados.")}catch(v){console.error("Erro ao atualizar bot:",v),ke.error(`Erro ao atualizar : ${(x=(w=(g=v==null?void 0:v.response)==null?void 0:g.data)==null?void 0:w.response)==null?void 0:x.message}`)}},m=async()=>{try{const g=localStorage.getItem("token");g&&t&&t.name&&e?(await k3(t.name,g,e),ke.success("Bot excluído com sucesso."),c(!1),r(),p(`/manager/instance/${t.id}/openai`)):console.error("Token ou nome da instância não encontrados.")}catch(g){console.error("Erro ao excluir bot:",g)}};return a.jsxs("div",{className:"form",children:[s&&a.jsx(Lo,{}),!s&&a.jsx(uo,{...d,children:a.jsxs("form",{onSubmit:d.handleSubmit(h),className:"w-full space-y-6",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Openai"}),a.jsxs("div",{className:"space-y-4",children:[a.jsx(R,{control:d.control,name:"enabled",render:({field:g})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:g.value,onCheckedChange:g.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Ativo"})})]})}),a.jsx(R,{control:d.control,name:"description",render:({field:g})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Descrição"}),a.jsx(Y,{...g,className:"border border-gray-600 w-full",placeholder:"Descrição"})]})}),a.jsx(R,{control:d.control,name:"openaiCredsId",render:({field:g})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Credencial"}),a.jsxs(St,{onValueChange:g.onChange,defaultValue:g.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione uma credencial"})})}),a.jsx(vt,{className:"border border-gray-600",children:n&&n.length>0&&Array.isArray(n)&&n.map(w=>a.jsx(me,{value:`${w.id}`,children:w.name?w.name:w.apiKey.substring(0,15)+"..."},w.id))})]})]})}),a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Openai Settings"}),a.jsx(Dt,{className:"border border-gray-700"}),a.jsx(R,{control:d.control,name:"botType",render:({field:g})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Tipo de Bot"}),a.jsxs(St,{onValueChange:g.onChange,defaultValue:g.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione uma tipo de bot"})})}),a.jsxs(vt,{className:"border border-gray-600",children:[a.jsx(me,{value:"assistant",children:"Assistente"}),a.jsx(me,{value:"chatCompletion",children:"Chat Completion"})]})]})]})}),d.watch("botType")==="assistant"&&a.jsx(R,{control:d.control,name:"assistantId",render:({field:g})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"ID do Assistente"}),a.jsx(Y,{...g,className:"border border-gray-600 w-full",placeholder:"ID do Assistente"})]})}),d.watch("botType")==="chatCompletion"&&a.jsxs(a.Fragment,{children:[a.jsx(R,{control:d.control,name:"model",render:({field:g})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Modelo de Linguagem"}),a.jsxs(St,{onValueChange:g.onChange,defaultValue:g.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione um modelo"})})}),a.jsx(vt,{className:"border border-gray-600",children:u&&u.length>0&&Array.isArray(u)&&u.map(w=>a.jsx(me,{value:w.id,children:w.id},w.id))})]})]})}),a.jsx(R,{control:d.control,name:"systemMessages",render:({field:g})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Mensagem do Sistem"}),a.jsx(ko,{...g,className:"border border-gray-600 w-full",placeholder:"Mensagem do Sistem"})]})}),a.jsx(R,{control:d.control,name:"assistantMessages",render:({field:g})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Mensagem do Asistente"}),a.jsx(ko,{...g,className:"border border-gray-600 w-full",placeholder:"Mensagem do Asistente"})]})}),a.jsx(R,{control:d.control,name:"userMessages",render:({field:g})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Mensagem do Usuário"}),a.jsx(ko,{...g,className:"border border-gray-600 w-full",placeholder:"Mensagem do Usuário"})]})}),a.jsx(R,{control:d.control,name:"maxTokens",render:({field:g})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Máximo de tokens"}),a.jsx(Y,{...g,className:"border border-gray-600 w-full",placeholder:"Máximo de tokens",type:"number"})]})})]}),a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Trigger Settings"}),a.jsx(Dt,{className:"border border-gray-700"}),a.jsx(R,{control:d.control,name:"triggerType",render:({field:g})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Tipo de gatilho"}),a.jsxs(St,{onValueChange:g.onChange,defaultValue:g.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione um tipo"})})}),a.jsxs(vt,{className:"border border-gray-600",children:[a.jsx(me,{value:"keyword",children:"Palavra Chave"}),a.jsx(me,{value:"all",children:"Todos"}),a.jsx(me,{value:"none",children:"Nenhum"})]})]})]})}),d.watch("triggerType")==="keyword"&&a.jsxs(a.Fragment,{children:[a.jsx(R,{control:d.control,name:"triggerOperator",render:({field:g})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Operador do gatilho"}),a.jsxs(St,{onValueChange:g.onChange,defaultValue:g.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione um operador"})})}),a.jsxs(vt,{className:"border border-gray-600",children:[a.jsx(me,{value:"contains",children:"Contém"}),a.jsx(me,{value:"equals",children:"Igual à"}),a.jsx(me,{value:"startsWith",children:"Começa com"}),a.jsx(me,{value:"endsWith",children:"Termina com"}),a.jsx(me,{value:"regex",children:"Regex"})]})]})]})}),a.jsx(R,{control:d.control,name:"triggerValue",render:({field:g})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Gatilho"}),a.jsx(Y,{...g,className:"border border-gray-600 w-full",placeholder:"Gatilho"})]})})]}),a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Options Settings"}),a.jsx(Dt,{className:"border border-gray-700"}),a.jsx(R,{control:d.control,name:"expire",render:({field:g})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Expira em (minitos)"}),a.jsx(Y,{...g,className:"border border-gray-600 w-full",placeholder:"Expira em (minitos)",type:"number"})]})}),a.jsx(R,{control:d.control,name:"keywordFinish",render:({field:g})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Palavra Chave de Finalização"}),a.jsx(Y,{...g,className:"border border-gray-600 w-full",placeholder:"Palavra Chave de Finalização"})]})}),a.jsx(R,{control:d.control,name:"delayMessage",render:({field:g})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Delay padrão da mensagem"}),a.jsx(Y,{...g,className:"border border-gray-600 w-full",placeholder:"Delay padrão da mensagem",type:"number"})]})}),a.jsx(R,{control:d.control,name:"unknownMessage",render:({field:g})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Mensagem para tipo de mensagem desconhecida"}),a.jsx(Y,{...g,className:"border border-gray-600 w-full",placeholder:"Mensagem para tipo de mensagem desconhecida"})]})}),a.jsx(R,{control:d.control,name:"listeningFromMe",render:({field:g})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:g.value,onCheckedChange:g.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Escuta mensagens enviadas por mim"})})]})}),a.jsx(R,{control:d.control,name:"stopBotFromMe",render:({field:g})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:g.value,onCheckedChange:g.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Pausa o bot quando eu enviar uma mensagem"})})]})}),a.jsx(R,{control:d.control,name:"keepOpen",render:({field:g})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:g.value,onCheckedChange:g.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Mantem a sessão do bot aberta"})})]})}),a.jsx(R,{control:d.control,name:"debounceTime",render:({field:g})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Tempo de espera"}),a.jsx(Y,{...g,className:"border border-gray-600 w-full",placeholder:"Tempo de espera",type:"number"})]})})]})]}),a.jsx("div",{children:a.jsx(TU,{openaiBotId:e})}),a.jsx(Te,{className:"bg-blue-400 hover:bg-blue-600 text-white",onClick:h,children:"Atualizar"}),a.jsxs(Sn,{open:l,onOpenChange:c,children:[a.jsx(Cn,{asChild:!0,children:a.jsx(Te,{variant:"secondary",className:"ml-2 bg-red-400 hover:bg-red-600",children:"Excluir"})}),a.jsx(un,{children:a.jsxs(dn,{children:[a.jsx(On,{children:"Tem certeza que deseja excluir?"}),a.jsx(Pi,{children:"Esta ação não pode ser desfeita."}),a.jsxs(br,{children:[a.jsx(Te,{variant:"default",className:"bg-red-400 hover:bg-red-600 text-white",onClick:m,children:"Exluir"}),a.jsx(Te,{variant:"outline",onClick:()=>c(!1),children:"Cancelar"})]})]})})]})]})})]})}const RU=T.object({enabled:T.boolean(),description:T.string(),openaiCredsId:T.string(),botType:T.string(),assistantId:T.string(),model:T.string(),systemMessages:T.string(),assistantMessages:T.string(),userMessages:T.string(),maxTokens:T.string(),triggerType:T.string(),triggerOperator:T.string().optional(),triggerValue:T.string().optional(),expire:T.string(),keywordFinish:T.string(),delayMessage:T.string(),unknownMessage:T.string(),listeningFromMe:T.boolean(),stopBotFromMe:T.boolean(),keepOpen:T.boolean(),debounceTime:T.string()});function PU({creds:e,resetTable:t}){const{instance:n}=Tt(),[r,o]=y.useState(!1),[s,i]=y.useState(!1),[l,c]=y.useState([]),u=tn({resolver:nn(RU),defaultValues:{enabled:!0,description:"",openaiCredsId:"",botType:"assistant",assistantId:"",model:"gpt-3.5-turbo",systemMessages:"",assistantMessages:"",userMessages:"",maxTokens:"300",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:"0",keywordFinish:"",delayMessage:"0",unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0"}});y.useEffect(()=>{(async()=>{try{if(!n)return;const h=await rk(n.name,n.token);c(h)}catch(h){console.error("Erro ao buscar modelos:",h)}})()},[n]);const f=async d=>{var h,m,g;try{if(!n||!n.name)throw new Error("Nome da instância não encontrado.");o(!0);const w={enabled:d.enabled,description:d.description,openaiCredsId:d.openaiCredsId,botType:d.botType,assistantId:d.assistantId,model:d.model,systemMessages:[d.systemMessages],assistantMessages:[d.assistantMessages],userMessages:[d.userMessages],maxTokens:parseInt(d.maxTokens,10),triggerType:d.triggerType,triggerOperator:d.triggerOperator||"",triggerValue:d.triggerValue||"",expire:parseInt(d.expire,10),keywordFinish:d.keywordFinish,delayMessage:parseInt(d.delayMessage,10),unknownMessage:d.unknownMessage,listeningFromMe:d.listeningFromMe,stopBotFromMe:d.stopBotFromMe,keepOpen:d.keepOpen,debounceTime:parseInt(d.debounceTime,10)};await T3(n.name,n.token,w),ke.success("Bot criado com sucesso!"),i(!1),p(),t()}catch(w){console.error("Erro ao criar bot:",w),ke.error(`Erro ao criar : ${(g=(m=(h=w==null?void 0:w.response)==null?void 0:h.data)==null?void 0:m.response)==null?void 0:g.message}`)}finally{o(!1)}};function p(){u.reset()}return a.jsxs(Sn,{open:s,onOpenChange:i,children:[a.jsx(Cn,{asChild:!0,children:a.jsxs(Te,{variant:"default",className:"mr-5",children:[a.jsx(ou,{})," Openai Bot"]})}),a.jsxs(un,{className:"sm:max-w-[740px] sm:max-h-[600px] overflow-y-auto",onCloseAutoFocus:p,children:[a.jsx(dn,{children:a.jsx(On,{children:"Novo Openai Bot"})}),a.jsx(Bo,{...u,children:a.jsxs("form",{onSubmit:u.handleSubmit(f),className:"w-full space-y-6",children:[a.jsx("div",{children:a.jsxs("div",{className:"space-y-4",children:[a.jsx(R,{control:u.control,name:"enabled",render:({field:d})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:d.value,onCheckedChange:d.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Ativo"})})]})}),a.jsx(R,{control:u.control,name:"description",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Descrição"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Descrição"})]})}),a.jsx(R,{control:u.control,name:"openaiCredsId",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Credencial"}),a.jsxs(St,{onValueChange:d.onChange,defaultValue:d.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione uma credencial"})})}),a.jsx(vt,{className:"border border-gray-600",children:e&&e.length>0&&Array.isArray(e)&&e.map(h=>a.jsx(me,{value:`${h.id}`,children:h.name?h.name:h.apiKey.substring(0,15)+"..."},h.id))})]})]})}),a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Openai Settings"}),a.jsx(Dt,{className:"border border-gray-700"}),a.jsx(R,{control:u.control,name:"botType",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Tipo de Bot"}),a.jsxs(St,{onValueChange:d.onChange,defaultValue:d.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione uma tipo de bot"})})}),a.jsxs(vt,{className:"border border-gray-600",children:[a.jsx(me,{value:"assistant",children:"Assistente"}),a.jsx(me,{value:"chatCompletion",children:"Chat Completion"})]})]})]})}),u.watch("botType")==="assistant"&&a.jsx(R,{control:u.control,name:"assistantId",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"ID do Assistente"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"ID do Assistente"})]})}),u.watch("botType")==="chatCompletion"&&a.jsxs(a.Fragment,{children:[a.jsx(R,{control:u.control,name:"model",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Modelo de Linguagem"}),a.jsxs(St,{onValueChange:d.onChange,defaultValue:d.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione um modelo"})})}),a.jsx(vt,{className:"border border-gray-600",children:l&&l.length>0&&Array.isArray(l)&&l.map(h=>a.jsx(me,{value:h.id,children:h.id},h.id))})]})]})}),a.jsx(R,{control:u.control,name:"systemMessages",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Mensagem do Sistem"}),a.jsx(ko,{...d,className:"border border-gray-600 w-full",placeholder:"Mensagem do Sistem"})]})}),a.jsx(R,{control:u.control,name:"assistantMessages",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Mensagem do Asistente"}),a.jsx(ko,{...d,className:"border border-gray-600 w-full",placeholder:"Mensagem do Asistente"})]})}),a.jsx(R,{control:u.control,name:"userMessages",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Mensagem do Usuário"}),a.jsx(ko,{...d,className:"border border-gray-600 w-full",placeholder:"Mensagem do Usuário"})]})}),a.jsx(R,{control:u.control,name:"maxTokens",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Máximo de tokens"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Máximo de tokens",type:"number"})]})})]}),a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Trigger Settings"}),a.jsx(Dt,{className:"border border-gray-700"}),a.jsx(R,{control:u.control,name:"triggerType",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Tipo de gatilho"}),a.jsxs(St,{onValueChange:d.onChange,defaultValue:d.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione um tipo"})})}),a.jsxs(vt,{className:"border border-gray-600",children:[a.jsx(me,{value:"keyword",children:"Palavra Chave"}),a.jsx(me,{value:"all",children:"Todos"}),a.jsx(me,{value:"none",children:"Nenhum"})]})]})]})}),u.watch("triggerType")==="keyword"&&a.jsxs(a.Fragment,{children:[a.jsx(R,{control:u.control,name:"triggerOperator",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Operador do gatilho"}),a.jsxs(St,{onValueChange:d.onChange,defaultValue:d.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione um operador"})})}),a.jsxs(vt,{className:"border border-gray-600",children:[a.jsx(me,{value:"contains",children:"Contém"}),a.jsx(me,{value:"equals",children:"Igual à"}),a.jsx(me,{value:"startsWith",children:"Começa com"}),a.jsx(me,{value:"endsWith",children:"Termina com"}),a.jsx(me,{value:"regex",children:"Regex"})]})]})]})}),a.jsx(R,{control:u.control,name:"triggerValue",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Gatilho"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Gatilho"})]})})]}),a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Options Settings"}),a.jsx(Dt,{className:"border border-gray-700"}),a.jsx(R,{control:u.control,name:"expire",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Expira em (minitos)"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Expira em (minitos)",type:"number"})]})}),a.jsx(R,{control:u.control,name:"keywordFinish",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Palavra Chave de Finalização"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Palavra Chave de Finalização"})]})}),a.jsx(R,{control:u.control,name:"delayMessage",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Delay padrão da mensagem"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Delay padrão da mensagem",type:"number"})]})}),a.jsx(R,{control:u.control,name:"unknownMessage",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Mensagem para tipo de mensagem desconhecida"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Mensagem para tipo de mensagem desconhecida"})]})}),a.jsx(R,{control:u.control,name:"listeningFromMe",render:({field:d})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:d.value,onCheckedChange:d.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Escuta mensagens enviadas por mim"})})]})}),a.jsx(R,{control:u.control,name:"stopBotFromMe",render:({field:d})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:d.value,onCheckedChange:d.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Pausa o bot quando eu enviar uma mensagem"})})]})}),a.jsx(R,{control:u.control,name:"keepOpen",render:({field:d})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:d.value,onCheckedChange:d.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Mantem a sessão do bot aberta"})})]})}),a.jsx(R,{control:u.control,name:"debounceTime",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Tempo de espera"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Tempo de espera",type:"number"})]})})]})}),a.jsx(br,{children:a.jsx(Te,{disabled:r,variant:"default",type:"submit",children:"Salvar"})})]})})]})]})}const IU=T.object({name:T.string(),apiKey:T.string()}),qh=async(e,t)=>{try{const n=localStorage.getItem("token");if(n&&e&&e.name){const r=await tk(e.name,n);t(r)}else console.error("Token ou nome da instância não encontrados.")}catch(n){console.error("Erro ao carregar configurações:",n)}};function DU(){var h;const{instance:e}=Tt(),[t,n]=y.useState(!1),[r,o]=y.useState([]),[s,i]=y.useState([]),l=tn({resolver:nn(IU),defaultValues:{name:"",apiKey:""}});y.useEffect(()=>{qh(e,i)},[e]);const c=async m=>{var g,w,x;try{if(!e||!e.name)throw new Error("Nome da instância não encontrado.");const v={name:m.name,apiKey:m.apiKey};await j3(e.name,e.token,v),ke.success("Credencial criada com sucesso!"),u()}catch(v){console.error("Erro ao criar bot:",v),ke.error(`Erro ao criar : ${(x=(w=(g=v==null?void 0:v.response)==null?void 0:g.data)==null?void 0:w.response)==null?void 0:x.message}`)}};function u(){l.reset(),qh(e,i)}const f=async m=>{var g,w,x;try{await _3(m,e==null?void 0:e.name),ke.success("Credencial excluída com sucesso!"),qh(e,i)}catch(v){console.error("Erro ao excluir credencial:",v),ke.error(`Erro ao excluir credencial: ${(x=(w=(g=v==null?void 0:v.response)==null?void 0:g.data)==null?void 0:w.response)==null?void 0:x.message}`)}},p=[{accessorKey:"name",header:({column:m})=>a.jsxs(Te,{variant:"ghost",onClick:()=>m.toggleSorting(m.getIsSorted()==="asc"),children:["Nome",a.jsx(tA,{className:"ml-2 h-4 w-4"})]}),cell:({row:m})=>a.jsx("div",{children:m.getValue("name")})},{accessorKey:"apiKey",header:()=>a.jsx("div",{className:"text-right",children:"Api Key"}),cell:({row:m})=>a.jsxs("div",{children:[`${m.getValue("apiKey")}`.slice(0,20),"..."]})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const g=m.original;return a.jsxs(Np,{children:[a.jsx(kp,{asChild:!0,children:a.jsxs(Te,{variant:"ghost",className:"h-8 w-8 p-0",children:[a.jsx("span",{className:"sr-only",children:"Open menu"}),a.jsx(ep,{className:"h-4 w-4"})]})}),a.jsxs(qi,{align:"end",children:[a.jsx(pu,{children:"Actions"}),a.jsx(Zi,{}),a.jsx(xn,{onClick:()=>f(g.id),children:"Excluir"})]})]})}}],d=Mp({data:s,columns:p,onSortingChange:o,getCoreRowModel:Pp(),getPaginationRowModel:Dp(),getSortedRowModel:Op(),getFilteredRowModel:Ip(),state:{sorting:r}});return a.jsxs(Sn,{open:t,onOpenChange:n,children:[a.jsx(Cn,{asChild:!0,children:a.jsxs(Te,{variant:"default",className:"mr-5",children:[a.jsx(hA,{})," Credenciais"]})}),a.jsxs(un,{className:"sm:max-w-[740px] sm:max-h-[600px] overflow-y-auto",onCloseAutoFocus:u,children:[a.jsx(dn,{children:a.jsx(On,{children:"Credenciais"})}),a.jsx(Bo,{...l,children:a.jsxs("form",{onSubmit:l.handleSubmit(c),className:"w-full space-y-6",children:[a.jsx("div",{children:a.jsxs("div",{className:"space-y-4",children:[a.jsx(R,{control:l.control,name:"name",render:({field:m})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Nome"}),a.jsx(Y,{...m,className:"border border-gray-600 w-full",placeholder:"Nome"})]})}),a.jsx(R,{control:l.control,name:"apiKey",render:({field:m})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Api Key"}),a.jsx(Y,{...m,className:"border border-gray-600 w-full",placeholder:"Api Key",type:"password"})]})})]})}),a.jsx(br,{children:a.jsx(Te,{variant:"default",type:"submit",children:"Salvar"})})]})}),a.jsx(Dt,{className:"border border-gray-700"}),a.jsx("div",{children:a.jsxs(hu,{children:[a.jsx(gu,{children:d.getHeaderGroups().map(m=>a.jsx(nr,{children:m.headers.map(g=>a.jsx(vu,{children:g.isPlaceholder?null:Ds(g.column.columnDef.header,g.getContext())},g.id))},m.id))}),a.jsx(mu,{children:(h=d.getRowModel().rows)!=null&&h.length?d.getRowModel().rows.map(m=>a.jsx(nr,{"data-state":m.getIsSelected()&&"selected",children:m.getVisibleCells().map(g=>a.jsx($o,{children:Ds(g.column.columnDef.cell,g.getContext())},g.id))},m.id)):a.jsx(nr,{children:a.jsx($o,{colSpan:p.length,className:"h-24 text-center",children:"No results."})})})]})})]})]})}var pk=y.createContext({dragDropManager:void 0}),pr;(function(e){e.SOURCE="SOURCE",e.TARGET="TARGET"})(pr||(pr={}));function Ue(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),o=2;o-1})}var LU={type:Xy,payload:{clientOffset:null,sourceClientOffset:null}};function $U(e){return function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{publishSource:!0},o=r.publishSource,s=o===void 0?!0:o,i=r.clientOffset,l=r.getSourceClientOffset,c=e.getMonitor(),u=e.getRegistry();e.dispatch(nb(i)),zU(n,c,u);var f=BU(n,c);if(f===null){e.dispatch(LU);return}var p=null;if(i){if(!l)throw new Error("getSourceClientOffset must be defined");VU(l),p=l(f)}e.dispatch(nb(i,p));var d=u.getSource(f),h=d.beginDrag(c,f);if(h!=null){UU(h),u.pinSource(f);var m=u.getSourceType(f);return{type:Ap,payload:{itemType:m,item:h,sourceId:f,clientOffset:i||null,sourceClientOffset:p||null,isSourcePublic:!!s}}}}}function zU(e,t,n){Ue(!t.isDragging(),"Cannot call beginDrag while dragging."),e.forEach(function(r){Ue(n.getSource(r),"Expected sourceIds to be registered.")})}function VU(e){Ue(typeof e=="function","When clientOffset is provided, getSourceClientOffset must be a function.")}function UU(e){Ue(hk(e),"Item must be an object.")}function BU(e,t){for(var n=null,r=e.length-1;r>=0;r--)if(t.canDragSource(e[r])){n=e[r];break}return n}function HU(e){return function(){var n=e.getMonitor();if(n.isDragging())return{type:Qy}}}function Am(e,t){return t===null?e===null:Array.isArray(e)?e.some(function(n){return n===t}):e===t}function GU(e){return function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=r.clientOffset;WU(n);var s=n.slice(0),i=e.getMonitor(),l=e.getRegistry();KU(s,i,l);var c=i.getItemType();return qU(s,l,c),ZU(s,i,l),{type:Fp,payload:{targetIds:s,clientOffset:o||null}}}}function WU(e){Ue(Array.isArray(e),"Expected targetIds to be an array.")}function KU(e,t,n){Ue(t.isDragging(),"Cannot call hover while not dragging."),Ue(!t.didDrop(),"Cannot call hover after drop.");for(var r=0;r=0;r--){var o=e[r],s=t.getTargetType(o);Am(s,n)||e.splice(r,1)}}function ZU(e,t,n){e.forEach(function(r){var o=n.getTarget(r);o.hover(t,r)})}function rb(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),n.push.apply(n,r)}return n}function ob(e){for(var t=1;t0&&arguments[0]!==void 0?arguments[0]:{},r=e.getMonitor(),o=e.getRegistry();XU(r);var s=t5(r);s.forEach(function(i,l){var c=QU(i,l,o,r),u={type:Lp,payload:{dropResult:ob(ob({},n),c)}};e.dispatch(u)})}}function XU(e){Ue(e.isDragging(),"Cannot call drop while not dragging."),Ue(!e.didDrop(),"Cannot call drop twice during one drag operation.")}function QU(e,t,n,r){var o=n.getTarget(e),s=o?o.drop(r,e):void 0;return e5(s),typeof s>"u"&&(s=t===0?{}:r.getDropResult()),s}function e5(e){Ue(typeof e>"u"||hk(e),"Drop result must either be an object or undefined.")}function t5(e){var t=e.getTargetIds().filter(e.canDropOnTarget,e);return t.reverse(),t}function n5(e){return function(){var n=e.getMonitor(),r=e.getRegistry();r5(n);var o=n.getSourceId();if(o!=null){var s=r.getSource(o,!0);s.endDrag(n,o),r.unpinSource()}return{type:$p}}}function r5(e){Ue(e.isDragging(),"Cannot call endDrag while not dragging.")}function o5(e){return{beginDrag:$U(e),publishDragSource:HU(e),hover:GU(e),drop:YU(e),endDrag:n5(e)}}function s5(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a5(e,t){for(var n=0;n0;r.backend&&(o&&!r.isSetUp?(r.backend.setup(),r.isSetUp=!0):!o&&r.isSetUp&&(r.backend.teardown(),r.isSetUp=!1))}),this.store=t,this.monitor=n,t.subscribe(this.handleRefCountChange)}return i5(e,[{key:"receiveBackend",value:function(n){this.backend=n}},{key:"getMonitor",value:function(){return this.monitor}},{key:"getBackend",value:function(){return this.backend}},{key:"getRegistry",value:function(){return this.monitor.registry}},{key:"getActions",value:function(){var n=this,r=this.store.dispatch;function o(i){return function(){for(var l=arguments.length,c=new Array(l),u=0;u"u"&&(n=t,t=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(cr(1));return n(gk)(e,t)}if(typeof e!="function")throw new Error(cr(2));var o=e,s=t,i=[],l=i,c=!1;function u(){l===i&&(l=i.slice())}function f(){if(c)throw new Error(cr(3));return s}function p(g){if(typeof g!="function")throw new Error(cr(4));if(c)throw new Error(cr(5));var w=!0;return u(),l.push(g),function(){if(w){if(c)throw new Error(cr(6));w=!1,u();var v=l.indexOf(g);l.splice(v,1),i=null}}}function d(g){if(!c5(g))throw new Error(cr(7));if(typeof g.type>"u")throw new Error(cr(8));if(c)throw new Error(cr(9));try{c=!0,s=o(s,g)}finally{c=!1}for(var w=i=l,x=0;x2&&arguments[2]!==void 0?arguments[2]:u5;if(e.length!==t.length)return!1;for(var r=0;r0&&arguments[0]!==void 0?arguments[0]:cb,t=arguments.length>1?arguments[1]:void 0,n=t.payload;switch(t.type){case Xy:case Ap:return{initialSourceClientOffset:n.sourceClientOffset,initialClientOffset:n.clientOffset,clientOffset:n.clientOffset};case Fp:return d5(e.clientOffset,n.clientOffset)?e:lb(lb({},e),{},{clientOffset:n.clientOffset});case $p:case Lp:return cb;default:return e}}var ex="dnd-core/ADD_SOURCE",tx="dnd-core/ADD_TARGET",nx="dnd-core/REMOVE_SOURCE",zp="dnd-core/REMOVE_TARGET";function g5(e){return{type:ex,payload:{sourceId:e}}}function m5(e){return{type:tx,payload:{targetId:e}}}function v5(e){return{type:nx,payload:{sourceId:e}}}function y5(e){return{type:zp,payload:{targetId:e}}}function ub(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),n.push.apply(n,r)}return n}function ur(e){for(var t=1;t0&&arguments[0]!==void 0?arguments[0]:w5,t=arguments.length>1?arguments[1]:void 0,n=t.payload;switch(t.type){case Ap:return ur(ur({},e),{},{itemType:n.itemType,item:n.item,sourceId:n.sourceId,isSourcePublic:n.isSourcePublic,dropResult:null,didDrop:!1});case Qy:return ur(ur({},e),{},{isSourcePublic:!0});case Fp:return ur(ur({},e),{},{targetIds:n.targetIds});case zp:return e.targetIds.indexOf(n.targetId)===-1?e:ur(ur({},e),{},{targetIds:MU(e.targetIds,n.targetId)});case Lp:return ur(ur({},e),{},{dropResult:n.dropResult,didDrop:!0,targetIds:[]});case $p:return ur(ur({},e),{},{itemType:null,item:null,sourceId:null,dropResult:null,didDrop:!1,isSourcePublic:null,targetIds:[]});default:return e}}function S5(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,t=arguments.length>1?arguments[1]:void 0;switch(t.type){case ex:case tx:return e+1;case nx:case zp:return e-1;default:return e}}var _f=[],rx=[];_f.__IS_NONE__=!0;rx.__IS_ALL__=!0;function C5(e,t){if(e===_f)return!1;if(e===rx||typeof t>"u")return!0;var n=FU(t,e);return n.length>0}function j5(){var e=arguments.length>1?arguments[1]:void 0;switch(e.type){case Fp:break;case ex:case tx:case zp:case nx:return _f;case Ap:case Qy:case $p:case Lp:default:return rx}var t=e.payload,n=t.targetIds,r=n===void 0?[]:n,o=t.prevTargetIds,s=o===void 0?[]:o,i=AU(r,s),l=i.length>0||!f5(r,s);if(!l)return _f;var c=s[s.length-1],u=r[r.length-1];return c!==u&&(c&&i.push(c),u&&i.push(u)),i}function _5(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return e+1}function db(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),n.push.apply(n,r)}return n}function fb(e){for(var t=1;t0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;return{dirtyHandlerIds:j5(e.dirtyHandlerIds,{type:t.type,payload:fb(fb({},t.payload),{},{prevTargetIds:OU(e,"dragOperation.targetIds",[])})}),dragOffset:h5(e.dragOffset,t),refCount:S5(e.refCount,t),dragOperation:b5(e.dragOperation,t),stateId:_5(e.stateId)}}function N5(e,t){return{x:e.x+t.x,y:e.y+t.y}}function mk(e,t){return{x:e.x-t.x,y:e.y-t.y}}function k5(e){var t=e.clientOffset,n=e.initialClientOffset,r=e.initialSourceClientOffset;return!t||!n||!r?null:mk(N5(t,r),n)}function R5(e){var t=e.clientOffset,n=e.initialClientOffset;return!t||!n?null:mk(t,n)}function P5(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function I5(e,t){for(var n=0;n1&&arguments[1]!==void 0?arguments[1]:{handlerIds:void 0},s=o.handlerIds;Ue(typeof n=="function","listener must be a function."),Ue(typeof s>"u"||Array.isArray(s),"handlerIds, when specified, must be an array of strings.");var i=this.store.getState().stateId,l=function(){var u=r.store.getState(),f=u.stateId;try{var p=f===i||f===i+1&&!C5(u.dirtyHandlerIds,s);p||n()}finally{i=f}};return this.store.subscribe(l)}},{key:"subscribeToOffsetChange",value:function(n){var r=this;Ue(typeof n=="function","listener must be a function.");var o=this.store.getState().dragOffset,s=function(){var l=r.store.getState().dragOffset;l!==o&&(o=l,n())};return this.store.subscribe(s)}},{key:"canDragSource",value:function(n){if(!n)return!1;var r=this.registry.getSource(n);return Ue(r,"Expected to find a valid source. sourceId=".concat(n)),this.isDragging()?!1:r.canDrag(this,n)}},{key:"canDropOnTarget",value:function(n){if(!n)return!1;var r=this.registry.getTarget(n);if(Ue(r,"Expected to find a valid target. targetId=".concat(n)),!this.isDragging()||this.didDrop())return!1;var o=this.registry.getTargetType(n),s=this.getItemType();return Am(o,s)&&r.canDrop(this,n)}},{key:"isDragging",value:function(){return!!this.getItemType()}},{key:"isDraggingSource",value:function(n){if(!n)return!1;var r=this.registry.getSource(n,!0);if(Ue(r,"Expected to find a valid source. sourceId=".concat(n)),!this.isDragging()||!this.isSourcePublic())return!1;var o=this.registry.getSourceType(n),s=this.getItemType();return o!==s?!1:r.isDragging(this,n)}},{key:"isOverTarget",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shallow:!1};if(!n)return!1;var o=r.shallow;if(!this.isDragging())return!1;var s=this.registry.getTargetType(n),i=this.getItemType();if(i&&!Am(s,i))return!1;var l=this.getTargetIds();if(!l.length)return!1;var c=l.indexOf(n);return o?c===l.length-1:c>-1}},{key:"getItemType",value:function(){return this.store.getState().dragOperation.itemType}},{key:"getItem",value:function(){return this.store.getState().dragOperation.item}},{key:"getSourceId",value:function(){return this.store.getState().dragOperation.sourceId}},{key:"getTargetIds",value:function(){return this.store.getState().dragOperation.targetIds}},{key:"getDropResult",value:function(){return this.store.getState().dragOperation.dropResult}},{key:"didDrop",value:function(){return this.store.getState().dragOperation.didDrop}},{key:"isSourcePublic",value:function(){return!!this.store.getState().dragOperation.isSourcePublic}},{key:"getInitialClientOffset",value:function(){return this.store.getState().dragOffset.initialClientOffset}},{key:"getInitialSourceClientOffset",value:function(){return this.store.getState().dragOffset.initialSourceClientOffset}},{key:"getClientOffset",value:function(){return this.store.getState().dragOffset.clientOffset}},{key:"getSourceClientOffset",value:function(){return k5(this.store.getState().dragOffset)}},{key:"getDifferenceFromInitialOffset",value:function(){return R5(this.store.getState().dragOffset)}}]),e}(),M5=0;function A5(){return M5++}function Cd(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Cd=function(n){return typeof n}:Cd=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Cd(e)}function F5(e){Ue(typeof e.canDrag=="function","Expected canDrag to be a function."),Ue(typeof e.beginDrag=="function","Expected beginDrag to be a function."),Ue(typeof e.endDrag=="function","Expected endDrag to be a function.")}function L5(e){Ue(typeof e.canDrop=="function","Expected canDrop to be a function."),Ue(typeof e.hover=="function","Expected hover to be a function."),Ue(typeof e.drop=="function","Expected beginDrag to be a function.")}function Fm(e,t){if(t&&Array.isArray(e)){e.forEach(function(n){return Fm(n,!1)});return}Ue(typeof e=="string"||Cd(e)==="symbol",t?"Type can only be a string, a symbol, or an array of either.":"Type can only be a string or a symbol.")}const hb=typeof global<"u"?global:self,vk=hb.MutationObserver||hb.WebKitMutationObserver;function yk(e){return function(){const n=setTimeout(o,0),r=setInterval(o,50);function o(){clearTimeout(n),clearInterval(r),e()}}}function $5(e){let t=1;const n=new vk(e),r=document.createTextNode("");return n.observe(r,{characterData:!0}),function(){t=-t,r.data=t}}const z5=typeof vk=="function"?$5:yk;class V5{enqueueTask(t){const{queue:n,requestFlush:r}=this;n.length||(r(),this.flushing=!0),n[n.length]=t}constructor(){this.queue=[],this.pendingErrors=[],this.flushing=!1,this.index=0,this.capacity=1024,this.flush=()=>{const{queue:t}=this;for(;this.indexthis.capacity){for(let r=0,o=t.length-this.index;r{this.pendingErrors.push(t),this.requestErrorThrow()},this.requestFlush=z5(this.flush),this.requestErrorThrow=yk(()=>{if(this.pendingErrors.length)throw this.pendingErrors.shift()})}}class U5{call(){try{this.task&&this.task()}catch(t){this.onError(t)}finally{this.task=null,this.release(this)}}constructor(t,n){this.onError=t,this.release=n,this.task=null}}class B5{create(t){const n=this.freeTasks,r=n.length?n.pop():new U5(this.onError,o=>n[n.length]=o);return r.task=t,r}constructor(t){this.onError=t,this.freeTasks=[]}}const xk=new V5,H5=new B5(xk.registerPendingError);function G5(e){xk.enqueueTask(H5.create(e))}function W5(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function K5(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n1&&arguments[1]!==void 0?arguments[1]:!1;Ue(this.isSourceId(n),"Expected a valid source ID.");var o=r&&n===this.pinnedSourceId,s=o?this.pinnedSource:this.dragSources.get(n);return s}},{key:"getTarget",value:function(n){return Ue(this.isTargetId(n),"Expected a valid target ID."),this.dropTargets.get(n)}},{key:"getSourceType",value:function(n){return Ue(this.isSourceId(n),"Expected a valid source ID."),this.types.get(n)}},{key:"getTargetType",value:function(n){return Ue(this.isTargetId(n),"Expected a valid target ID."),this.types.get(n)}},{key:"isSourceId",value:function(n){var r=mb(n);return r===pr.SOURCE}},{key:"isTargetId",value:function(n){var r=mb(n);return r===pr.TARGET}},{key:"removeSource",value:function(n){var r=this;Ue(this.getSource(n),"Expected an existing source."),this.store.dispatch(v5(n)),G5(function(){r.dragSources.delete(n),r.types.delete(n)})}},{key:"removeTarget",value:function(n){Ue(this.getTarget(n),"Expected an existing target."),this.store.dispatch(y5(n)),this.dropTargets.delete(n),this.types.delete(n)}},{key:"pinSource",value:function(n){var r=this.getSource(n);Ue(r,"Expected an existing source."),this.pinnedSourceId=n,this.pinnedSource=r}},{key:"unpinSource",value:function(){Ue(this.pinnedSource,"No source is pinned at the time."),this.pinnedSourceId=null,this.pinnedSource=null}},{key:"addHandler",value:function(n,r,o){var s=e6(n);return this.types.set(s,r),n===pr.SOURCE?this.dragSources.set(s,o):n===pr.TARGET&&this.dropTargets.set(s,o),s}}]),e}();function n6(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,o=r6(r),s=new O5(o,new t6(o)),i=new l5(o,s),l=e(i,t,n);return i.receiveBackend(l),i}function r6(e){var t=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION__;return gk(T5,e&&t&&t({name:"dnd-core",instanceId:"dnd-core"}))}var o6=["children"];function s6(e,t){return c6(e)||l6(e,t)||i6(e,t)||a6()}function a6(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. -In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function i6(e,t){if(e){if(typeof e=="string")return yb(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return yb(e,t)}}function yb(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function d6(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,s;for(s=0;s=0)&&(n[o]=e[o]);return n}var xb=0,jd=Symbol.for("__REACT_DND_CONTEXT_INSTANCE__"),f6=y.memo(function(t){var n=t.children,r=u6(t,o6),o=p6(r),s=s6(o,2),i=s[0],l=s[1];return y.useEffect(function(){if(l){var c=wk();return++xb,function(){--xb===0&&(c[jd]=null)}}},[]),a.jsx(pk.Provider,Object.assign({value:i},{children:n}),void 0)});function p6(e){if("manager"in e){var t={dragDropManager:e.manager};return[t,!1]}var n=h6(e.backend,e.context,e.options,e.debugMode),r=!e.context;return[n,r]}function h6(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:wk(),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3?arguments[3]:void 0,o=t;return o[jd]||(o[jd]={dragDropManager:n6(e,t,n,r)}),o[jd]}function wk(){return typeof global<"u"?global:window}function g6(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function m6(e,t){for(var n=0;n, or turn it into a ")+"drag source or a drop target itself.")}}function j6(e){return function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;if(!y.isValidElement(t)){var r=t;return e(r,n),r}var o=t;C6(o);var s=n?function(i){return e(i,n)}:e;return _6(o,s)}}function bk(e){var t={};return Object.keys(e).forEach(function(n){var r=e[n];if(n.endsWith("Ref"))t[n]=e[n];else{var o=j6(r);t[n]=function(){return o}}}),t}function Sb(e,t){typeof e=="function"?e(t):e.current=t}function _6(e,t){var n=e.ref;return Ue(typeof n!="string","Cannot connect React DnD to an element with an existing string ref. Please convert it to use a callback ref instead, or wrap it into a or
. Read more: https://reactjs.org/docs/refs-and-the-dom.html#callback-refs"),n?y.cloneElement(e,{ref:function(o){Sb(n,o),Sb(t,o)}}):y.cloneElement(e,{ref:t})}function _d(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?_d=function(n){return typeof n}:_d=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},_d(e)}function Lm(e){return e!==null&&_d(e)==="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function $m(e,t,n,r){var o=void 0;if(o!==void 0)return!!o;if(e===t)return!0;if(typeof e!="object"||!e||typeof t!="object"||!t)return!1;var s=Object.keys(e),i=Object.keys(t);if(s.length!==i.length)return!1;for(var l=Object.prototype.hasOwnProperty.bind(t),c=0;ce.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n0}},{key:"leave",value:function(n){var r=this.entered.length;return this.entered=OB(this.entered.filter(this.isNodeInDocument),n),r>0&&this.entered.length===0}},{key:"reset",value:function(){this.entered=[]}}]),e}(),zB=jk(function(){return/firefox/i.test(navigator.userAgent)}),_k=jk(function(){return!!window.safari});function VB(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function UB(e,t){for(var n=0;nn)f=p-1;else return o[p]}c=Math.max(0,f);var h=n-r[c],m=h*h;return o[c]+s[c]*h+i[c]*m+l[c]*h*m}}]),e}(),HB=1;function Ek(e){var t=e.nodeType===HB?e:e.parentElement;if(!t)return null;var n=t.getBoundingClientRect(),r=n.top,o=n.left;return{x:o,y:r}}function Qu(e){return{x:e.clientX,y:e.clientY}}function GB(e){var t;return e.nodeName==="IMG"&&(zB()||!((t=document.documentElement)!==null&&t!==void 0&&t.contains(e)))}function WB(e,t,n,r){var o=e?t.width:n,s=e?t.height:r;return _k()&&e&&(s/=window.devicePixelRatio,o/=window.devicePixelRatio),{dragPreviewWidth:o,dragPreviewHeight:s}}function KB(e,t,n,r,o){var s=GB(t),i=s?e:t,l=Ek(i),c={x:n.x-l.x,y:n.y-l.y},u=e.offsetWidth,f=e.offsetHeight,p=r.anchorX,d=r.anchorY,h=WB(s,t,u,f),m=h.dragPreviewWidth,g=h.dragPreviewHeight,w=function(){var N=new kb([0,.5,1],[c.y,c.y/f*g,c.y+g-f]),E=N.interpolate(d);return _k()&&s&&(E+=(window.devicePixelRatio-1)*g),E},x=function(){var N=new kb([0,.5,1],[c.x,c.x/u*m,c.x+m-u]);return N.interpolate(p)},v=o.offsetX,b=o.offsetY,C=v===0||v,j=b===0||b;return{x:C?v:x(),y:j?b:w()}}var Tk="__NATIVE_FILE__",Nk="__NATIVE_URL__",kk="__NATIVE_TEXT__",Rk="__NATIVE_HTML__";const Rb=Object.freeze(Object.defineProperty({__proto__:null,FILE:Tk,HTML:Rk,TEXT:kk,URL:Nk},Symbol.toStringTag,{value:"Module"}));function eg(e,t,n){var r=t.reduce(function(o,s){return o||e.getData(s)},"");return r??n}var Ha;function ed(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var Vm=(Ha={},ed(Ha,Tk,{exposeProperties:{files:function(t){return Array.prototype.slice.call(t.files)},items:function(t){return t.items},dataTransfer:function(t){return t}},matchesTypes:["Files"]}),ed(Ha,Rk,{exposeProperties:{html:function(t,n){return eg(t,n,"")},dataTransfer:function(t){return t}},matchesTypes:["Html","text/html"]}),ed(Ha,Nk,{exposeProperties:{urls:function(t,n){return eg(t,n,"").split(` -`)},dataTransfer:function(t){return t}},matchesTypes:["Url","text/uri-list"]}),ed(Ha,kk,{exposeProperties:{text:function(t,n){return eg(t,n,"")},dataTransfer:function(t){return t}},matchesTypes:["Text","text/plain"]}),Ha);function qB(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function ZB(e,t){for(var n=0;n-1})})[0]||null}function QB(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function eH(e,t){for(var n=0;n0&&o.actions.hover(i,{clientOffset:Qu(s)});var l=i.some(function(c){return o.monitor.canDropOnTarget(c)});l&&(s.preventDefault(),s.dataTransfer&&(s.dataTransfer.dropEffect=o.getCurrentDropEffect()))}}),Qe(this,"handleTopDragOverCapture",function(){o.dragOverTargetIds=[]}),Qe(this,"handleTopDragOver",function(s){var i=o.dragOverTargetIds;if(o.dragOverTargetIds=[],!o.monitor.isDragging()){s.preventDefault(),s.dataTransfer&&(s.dataTransfer.dropEffect="none");return}o.altKeyPressed=s.altKey,o.lastClientOffset=Qu(s),o.hoverRafId===null&&typeof requestAnimationFrame<"u"&&(o.hoverRafId=requestAnimationFrame(function(){o.monitor.isDragging()&&o.actions.hover(i||[],{clientOffset:o.lastClientOffset}),o.hoverRafId=null}));var l=(i||[]).some(function(c){return o.monitor.canDropOnTarget(c)});l?(s.preventDefault(),s.dataTransfer&&(s.dataTransfer.dropEffect=o.getCurrentDropEffect())):o.isDraggingNativeItem()?s.preventDefault():(s.preventDefault(),s.dataTransfer&&(s.dataTransfer.dropEffect="none"))}),Qe(this,"handleTopDragLeaveCapture",function(s){o.isDraggingNativeItem()&&s.preventDefault();var i=o.enterLeaveCounter.leave(s.target);i&&o.isDraggingNativeItem()&&setTimeout(function(){return o.endDragNativeItem()},0)}),Qe(this,"handleTopDropCapture",function(s){if(o.dropTargetIds=[],o.isDraggingNativeItem()){var i;s.preventDefault(),(i=o.currentNativeSource)===null||i===void 0||i.loadDataTransfer(s.dataTransfer)}else tg(s.dataTransfer)&&s.preventDefault();o.enterLeaveCounter.reset()}),Qe(this,"handleTopDrop",function(s){var i=o.dropTargetIds;o.dropTargetIds=[],o.actions.hover(i,{clientOffset:Qu(s)}),o.actions.drop({dropEffect:o.getCurrentDropEffect()}),o.isDraggingNativeItem()?o.endDragNativeItem():o.monitor.isDragging()&&o.actions.endDrag()}),Qe(this,"handleSelectStart",function(s){var i=s.target;typeof i.dragDrop=="function"&&(i.tagName==="INPUT"||i.tagName==="SELECT"||i.tagName==="TEXTAREA"||i.isContentEditable||(s.preventDefault(),i.dragDrop()))}),this.options=new nH(n,r),this.actions=t.getActions(),this.monitor=t.getMonitor(),this.registry=t.getRegistry(),this.enterLeaveCounter=new $B(this.isNodeInDocument)}return sH(e,[{key:"profile",value:function(){var n,r;return{sourcePreviewNodes:this.sourcePreviewNodes.size,sourcePreviewNodeOptions:this.sourcePreviewNodeOptions.size,sourceNodeOptions:this.sourceNodeOptions.size,sourceNodes:this.sourceNodes.size,dragStartSourceIds:((n=this.dragStartSourceIds)===null||n===void 0?void 0:n.length)||0,dropTargetIds:this.dropTargetIds.length,dragEnterTargetIds:this.dragEnterTargetIds.length,dragOverTargetIds:((r=this.dragOverTargetIds)===null||r===void 0?void 0:r.length)||0}}},{key:"window",get:function(){return this.options.window}},{key:"document",get:function(){return this.options.document}},{key:"rootElement",get:function(){return this.options.rootElement}},{key:"setup",value:function(){var n=this.rootElement;if(n!==void 0){if(n.__isReactDndBackendSetUp)throw new Error("Cannot have two HTML5 backends at the same time.");n.__isReactDndBackendSetUp=!0,this.addEventListeners(n)}}},{key:"teardown",value:function(){var n=this.rootElement;if(n!==void 0&&(n.__isReactDndBackendSetUp=!1,this.removeEventListeners(this.rootElement),this.clearCurrentDragSourceNode(),this.asyncEndDragFrameId)){var r;(r=this.window)===null||r===void 0||r.cancelAnimationFrame(this.asyncEndDragFrameId)}}},{key:"connectDragPreview",value:function(n,r,o){var s=this;return this.sourcePreviewNodeOptions.set(n,o),this.sourcePreviewNodes.set(n,r),function(){s.sourcePreviewNodes.delete(n),s.sourcePreviewNodeOptions.delete(n)}}},{key:"connectDragSource",value:function(n,r,o){var s=this;this.sourceNodes.set(n,r),this.sourceNodeOptions.set(n,o);var i=function(u){return s.handleDragStart(u,n)},l=function(u){return s.handleSelectStart(u)};return r.setAttribute("draggable","true"),r.addEventListener("dragstart",i),r.addEventListener("selectstart",l),function(){s.sourceNodes.delete(n),s.sourceNodeOptions.delete(n),r.removeEventListener("dragstart",i),r.removeEventListener("selectstart",l),r.setAttribute("draggable","false")}}},{key:"connectDropTarget",value:function(n,r){var o=this,s=function(u){return o.handleDragEnter(u,n)},i=function(u){return o.handleDragOver(u,n)},l=function(u){return o.handleDrop(u,n)};return r.addEventListener("dragenter",s),r.addEventListener("dragover",i),r.addEventListener("drop",l),function(){r.removeEventListener("dragenter",s),r.removeEventListener("dragover",i),r.removeEventListener("drop",l)}}},{key:"addEventListeners",value:function(n){n.addEventListener&&(n.addEventListener("dragstart",this.handleTopDragStart),n.addEventListener("dragstart",this.handleTopDragStartCapture,!0),n.addEventListener("dragend",this.handleTopDragEndCapture,!0),n.addEventListener("dragenter",this.handleTopDragEnter),n.addEventListener("dragenter",this.handleTopDragEnterCapture,!0),n.addEventListener("dragleave",this.handleTopDragLeaveCapture,!0),n.addEventListener("dragover",this.handleTopDragOver),n.addEventListener("dragover",this.handleTopDragOverCapture,!0),n.addEventListener("drop",this.handleTopDrop),n.addEventListener("drop",this.handleTopDropCapture,!0))}},{key:"removeEventListeners",value:function(n){n.removeEventListener&&(n.removeEventListener("dragstart",this.handleTopDragStart),n.removeEventListener("dragstart",this.handleTopDragStartCapture,!0),n.removeEventListener("dragend",this.handleTopDragEndCapture,!0),n.removeEventListener("dragenter",this.handleTopDragEnter),n.removeEventListener("dragenter",this.handleTopDragEnterCapture,!0),n.removeEventListener("dragleave",this.handleTopDragLeaveCapture,!0),n.removeEventListener("dragover",this.handleTopDragOver),n.removeEventListener("dragover",this.handleTopDragOverCapture,!0),n.removeEventListener("drop",this.handleTopDrop),n.removeEventListener("drop",this.handleTopDropCapture,!0))}},{key:"getCurrentSourceNodeOptions",value:function(){var n=this.monitor.getSourceId(),r=this.sourceNodeOptions.get(n);return Db({dropEffect:this.altKeyPressed?"copy":"move"},r||{})}},{key:"getCurrentDropEffect",value:function(){return this.isDraggingNativeItem()?"copy":this.getCurrentSourceNodeOptions().dropEffect}},{key:"getCurrentSourcePreviewNodeOptions",value:function(){var n=this.monitor.getSourceId(),r=this.sourcePreviewNodeOptions.get(n);return Db({anchorX:.5,anchorY:.5,captureDraggingState:!1},r||{})}},{key:"isDraggingNativeItem",value:function(){var n=this.monitor.getItemType();return Object.keys(Rb).some(function(r){return Rb[r]===n})}},{key:"beginDragNativeItem",value:function(n,r){this.clearCurrentDragSourceNode(),this.currentNativeSource=XB(n,r),this.currentNativeHandle=this.registry.addSource(n,this.currentNativeSource),this.actions.beginDrag([this.currentNativeHandle])}},{key:"setCurrentDragSourceNode",value:function(n){var r=this;this.clearCurrentDragSourceNode(),this.currentDragSourceNode=n;var o=1e3;this.mouseMoveTimeoutTimer=setTimeout(function(){var s;return(s=r.rootElement)===null||s===void 0?void 0:s.addEventListener("mousemove",r.endDragIfSourceWasRemovedFromDOM,!0)},o)}},{key:"clearCurrentDragSourceNode",value:function(){if(this.currentDragSourceNode){if(this.currentDragSourceNode=null,this.rootElement){var n;(n=this.window)===null||n===void 0||n.clearTimeout(this.mouseMoveTimeoutTimer||void 0),this.rootElement.removeEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0)}return this.mouseMoveTimeoutTimer=null,!0}return!1}},{key:"handleDragStart",value:function(n,r){n.defaultPrevented||(this.dragStartSourceIds||(this.dragStartSourceIds=[]),this.dragStartSourceIds.unshift(r))}},{key:"handleDragEnter",value:function(n,r){this.dragEnterTargetIds.unshift(r)}},{key:"handleDragOver",value:function(n,r){this.dragOverTargetIds===null&&(this.dragOverTargetIds=[]),this.dragOverTargetIds.unshift(r)}},{key:"handleDrop",value:function(n,r){this.dropTargetIds.unshift(r)}}]),e}(),iH=function(t,n,r){return new aH(t,n,r)},lH=Object.create,Pk=Object.defineProperty,cH=Object.getOwnPropertyDescriptor,Ik=Object.getOwnPropertyNames,uH=Object.getPrototypeOf,dH=Object.prototype.hasOwnProperty,fH=(e,t)=>function(){return t||(0,e[Ik(e)[0]])((t={exports:{}}).exports,t),t.exports},pH=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ik(t))!dH.call(e,o)&&o!==n&&Pk(e,o,{get:()=>t[o],enumerable:!(r=cH(t,o))||r.enumerable});return e},Dk=(e,t,n)=>(n=e!=null?lH(uH(e)):{},pH(Pk(n,"default",{value:e,enumerable:!0}),e)),Ok=fH({"node_modules/classnames/index.js"(e,t){(function(){var n={}.hasOwnProperty;function r(){for(var o=[],s=0;s-1}var S8=b8,C8=9007199254740991,j8=/^(?:0|[1-9]\d*)$/;function _8(e,t){var n=typeof e;return t=t??C8,!!t&&(n=="number"||n!="symbol"&&j8.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=N8}var Vk=k8;function R8(e){return e!=null&&Vk(e.length)&&!$k(e)}var P8=R8,I8=Object.prototype;function D8(e){var t=e&&e.constructor,n=typeof t=="function"&&t.prototype||I8;return e===n}var O8=D8;function M8(e,t){for(var n=-1,r=Array(e);++n-1}var f9=d9;function p9(e,t){var n=this.__data__,r=Vp(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}var h9=p9;function el(e){var t=-1,n=e==null?0:e.length;for(this.clear();++tl))return!1;var u=s.get(e),f=s.get(t);if(u&&f)return u==t&&f==e;var p=-1,d=!0,h=n&bG?new qk:void 0;for(s.set(e,t),s.set(t,e);++p":">",'"':""","'":"'"},eW=D9(QG),tW=eW,Xk=/[&<>"']/g,nW=RegExp(Xk.source);function rW(e){return e=Kk(e),e&&nW.test(e)?e.replace(Xk,tW):e}var oW=rW,Qk=/[\\^$.*+?()[\]{}|]/g,sW=RegExp(Qk.source);function aW(e){return e=Kk(e),e&&sW.test(e)?e.replace(Qk,"\\$&"):e}var iW=aW;function lW(e,t){return JG(e,t)}var cW=lW,uW=1/0,dW=bi&&1/ox(new bi([,-0]))[1]==uW?function(e){return new bi(e)}:f8,fW=dW,pW=200;function hW(e,t,n){var r=-1,o=S8,s=e.length,i=!0,l=[],c=l;if(n)i=!1,o=XG;else if(s>=pW){var u=t?null:fW(e);if(u)return ox(u);i=!1,o=Zk,c=new qk}else c=t?[]:l;e:for(;++ra.jsx("button",{className:e.classNames.clearAll,onClick:e.onClick,children:"Clear all"}),xW=yW,wW=(e,t)=>{const n=t.offsetHeight,r=e.offsetHeight,o=e.offsetTop-t.scrollTop;o+r>=n?t.scrollTop+=o-n+r:o<0&&(t.scrollTop+=o)},Wm=(e,t,n,r)=>typeof r=="function"?r(e):e.length>=t&&n,bW=e=>{const t=y.createRef(),{labelField:n,minQueryLength:r,isFocused:o,classNames:s,selectedIndex:i,query:l}=e;y.useEffect(()=>{if(!t.current)return;const p=t.current.querySelector(`.${s.activeSuggestion}`);p&&wW(p,t.current)},[i]);const c=(p,d)=>{const h=d.trim().replace(/[-\\^$*+?.()|[\]{}]/g,"\\$&"),{[n]:m}=p;return{__html:m.replace(RegExp(h,"gi"),g=>`${oW(g)}`)}},u=(p,d)=>typeof e.renderSuggestion=="function"?e.renderSuggestion(p,d):a.jsx("span",{dangerouslySetInnerHTML:c(p,d)}),f=e.suggestions.map((p,d)=>a.jsx("li",{onMouseDown:e.handleClick.bind(null,d),onTouchStart:e.handleClick.bind(null,d),onMouseOver:e.handleHover.bind(null,d),className:d===e.selectedIndex?e.classNames.activeSuggestion:"",children:u(p,e.query)},d));return f.length===0||!Wm(l,r||2,o,e.shouldRenderSuggestions)?null:a.jsx("div",{ref:t,className:s.suggestions,"data-testid":"suggestions",children:a.jsxs("ul",{children:[" ",f," "]})})},SW=(e,t)=>{const{query:n,minQueryLength:r=2,isFocused:o,suggestions:s}=t;return!!(e.isFocused===o&&cW(e.suggestions,s)&&Wm(n,r,o,t.shouldRenderSuggestions)===Wm(e.query,e.minQueryLength??2,e.isFocused,e.shouldRenderSuggestions)&&e.selectedIndex===t.selectedIndex)},CW=y.memo(bW,SW),jW=CW,_W=Dk(Ok()),EW=Dk(Ok());function TW(e){const t=e.map(r=>{const o=r-48*Math.floor(r/48);return String.fromCharCode(96<=r?o:r)}).join(""),n=iW(t);return new RegExp(`[${n}]+`)}function NW(e){switch(e){case Zs.ENTER:return[10,13];case Zs.TAB:return 9;case Zs.COMMA:return 188;case Zs.SPACE:return 32;case Zs.SEMICOLON:return 186;default:return 0}}function sS(e){const{moveTag:t,readOnly:n,allowDragDrop:r}=e;return t!==void 0&&!n&&r}function kW(e){const{readOnly:t,allowDragDrop:n}=e;return!t&&n}var RW=e=>{const{readOnly:t,removeComponent:n,onRemove:r,className:o,tag:s,index:i}=e,l=u=>{if(wi.ENTER.includes(u.keyCode)||u.keyCode===wi.SPACE){u.preventDefault(),u.stopPropagation();return}u.keyCode===wi.BACKSPACE&&r(u)};if(t)return a.jsx("span",{});const c=`Tag at index ${i} with value ${s.id} focussed. Press backspace to remove`;if(n){const u=n;return a.jsx(u,{"data-testid":"remove",onRemove:r,onKeyDown:l,className:o,"aria-label":c,tag:s,index:i})}return a.jsx("button",{"data-testid":"remove",onClick:r,onKeyDown:l,className:o,type:"button","aria-label":c,children:a.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",height:"12",width:"12",fill:"#fff",children:a.jsx("path",{d:"M376.6 84.5c11.3-13.6 9.5-33.8-4.1-45.1s-33.8-9.5-45.1 4.1L192 206 56.6 43.5C45.3 29.9 25.1 28.1 11.5 39.4S-3.9 70.9 7.4 84.5L150.3 256 7.4 427.5c-11.3 13.6-9.5 33.8 4.1 45.1s33.8 9.5 45.1-4.1L192 306 327.4 468.5c11.3 13.6 31.5 15.4 45.1 4.1s15.4-31.5 4.1-45.1L233.7 256 376.6 84.5z"})})})},PW=RW,aS={TAG:"tag"},IW=e=>{const t=y.useRef(null),{readOnly:n=!1,tag:r,classNames:o,index:s,moveTag:i,allowDragDrop:l=!0,labelField:c="text",tags:u}=e,[{isDragging:f},p]=vB(()=>({type:aS.TAG,collect:w=>({isDragging:!!w.isDragging()}),item:e,canDrag:()=>sS({moveTag:i,readOnly:n,allowDragDrop:l})}),[u]),[,d]=DB(()=>({accept:aS.TAG,drop:w=>{var b;const x=w.index,v=s;x!==v&&((b=e==null?void 0:e.moveTag)==null||b.call(e,x,v))},canDrop:w=>kW(w)}),[u]);p(d(t));const h=e.tag[c],{className:m=""}=r,g=f?0:1;return a.jsxs("span",{ref:t,className:(0,EW.default)("tag-wrapper",o.tag,m),style:{opacity:g,cursor:sS({moveTag:i,readOnly:n,allowDragDrop:l})?"move":"auto"},"data-testid":"tag",onClick:e.onTagClicked,onTouchStart:e.onTagClicked,children:[h,a.jsx(PW,{tag:e.tag,className:o.remove,removeComponent:e.removeComponent,onRemove:e.onDelete,readOnly:n,index:s})]})},DW=e=>{const{autofocus:t,autoFocus:n,readOnly:r,labelField:o,allowDeleteFromEmptyInput:s,allowAdditionFromPaste:i,allowDragDrop:l,minQueryLength:c,shouldRenderSuggestions:u,removeComponent:f,autocomplete:p,inline:d,maxTags:h,allowUnique:m,editable:g,placeholder:w,delimiters:x,separators:v,tags:b,inputFieldPosition:C,inputProps:j,classNames:S,maxLength:N,inputValue:E,clearAll:A}=e,[F,Z]=y.useState(e.suggestions),[I,q]=y.useState(""),[H,J]=y.useState(!1),[re,K]=y.useState(-1),[z,L]=y.useState(!1),[te,fe]=y.useState(""),[B,ne]=y.useState(-1),[Q,ie]=y.useState(""),oe=y.createRef(),W=y.useRef(null),we=y.useRef(null);y.useEffect(()=>{x.length&&console.warn("[Deprecation] The delimiters prop is deprecated and will be removed in v7.x.x, please use separators instead. If you have any concerns regarding this, please share your thoughts in https://github.com/react-tags/react-tags/issues/960")},[]),y.useEffect(()=>{typeof d<"u"&&console.warn("[Deprecation] The inline attribute is deprecated and will be removed in v7.x.x, please use inputFieldPosition instead.")},[d]),y.useEffect(()=>{typeof t<"u"&&console.warn("[Deprecated] autofocus prop will be removed in 7.x so please migrate to autoFocus prop."),(t||n&&t!==!1)&&!r&&Ie()},[n,n,r]),y.useEffect(()=>{$t()},[I,e.suggestions]);const Pe=ce=>{let ze=e.suggestions.slice();if(m){const fn=b.map(Br=>Br.id.trim().toLowerCase());ze=ze.filter(Br=>!fn.includes(Br.id.toLowerCase()))}if(e.handleFilterSuggestions)return e.handleFilterSuggestions(ce,ze);const pt=ze.filter(fn=>Fe(ce,fn)===0),ot=ze.filter(fn=>Fe(ce,fn)>0);return pt.concat(ot)},Fe=(ce,ze)=>ze[o].toLowerCase().indexOf(ce.toLowerCase()),Ie=()=>{q(""),W.current&&(W.current.value="",W.current.focus())},he=(ce,ze)=>{var ot;ze.preventDefault(),ze.stopPropagation();const pt=b.slice();pt.length!==0&&(ie(""),(ot=e==null?void 0:e.handleDelete)==null||ot.call(e,ce,ze),Xe(ce,pt))},Xe=(ce,ze)=>{var fn;if(!(oe!=null&&oe.current))return;const pt=oe.current.querySelectorAll(".ReactTags__remove");let ot="";ce===0&&ze.length>1?(ot=`Tag at index ${ce} with value ${ze[ce].id} deleted. Tag at index 0 with value ${ze[1].id} focussed. Press backspace to remove`,pt[0].focus()):ce>0?(ot=`Tag at index ${ce} with value ${ze[ce].id} deleted. Tag at index ${ce-1} with value ${ze[ce-1].id} focussed. Press backspace to remove`,pt[ce-1].focus()):(ot=`Tag at index ${ce} with value ${ze[ce].id} deleted. Input focussed. Press enter to add a new tag`,(fn=W.current)==null||fn.focus()),fe(ot)},Nt=(ce,ze,pt)=>{var ot,fn;r||(g&&(ne(ce),q(ze[o]),(ot=we.current)==null||ot.focus()),(fn=e.handleTagClick)==null||fn.call(e,ce,pt))},Ut=ce=>{e.handleInputChange&&e.handleInputChange(ce.target.value,ce);const ze=ce.target.value.trim();q(ze)},$t=()=>{const ce=Pe(I);Z(ce),K(re>=ce.length?ce.length-1:re)},Wt=ce=>{const ze=ce.target.value;e.handleInputFocus&&e.handleInputFocus(ze,ce),J(!0)},_=ce=>{const ze=ce.target.value;e.handleInputBlur&&(e.handleInputBlur(ze,ce),W.current&&(W.current.value="")),J(!1),ne(-1)},M=ce=>{if(ce.key==="Escape"&&(ce.preventDefault(),ce.stopPropagation(),K(-1),L(!1),Z([]),ne(-1)),(v.indexOf(ce.key)!==-1||x.indexOf(ce.keyCode)!==-1)&&!ce.shiftKey){(ce.keyCode!==wi.TAB||I!=="")&&ce.preventDefault();const ze=z&&re!==-1?F[re]:{id:I.trim(),[o]:I.trim(),className:""};Object.keys(ze)&&le(ze)}ce.key==="Backspace"&&I===""&&(s||C===_l.INLINE)&&he(b.length-1,ce),ce.keyCode===wi.UP_ARROW&&(ce.preventDefault(),K(re<=0?F.length-1:re-1),L(!0)),ce.keyCode===wi.DOWN_ARROW&&(ce.preventDefault(),L(!0),F.length===0?K(-1):K((re+1)%F.length))},U=()=>h&&b.length>=h,pe=ce=>{if(!i)return;if(U()){ie(Mb.TAG_LIMIT),Ie();return}ie(""),ce.preventDefault();const ze=ce.clipboardData||window.clipboardData,pt=ze.getData("text"),{maxLength:ot=pt.length}=e,fn=Math.min(ot,pt.length),Br=ze.getData("text").substr(0,fn);let Jo=x;v.length&&(Jo=[],v.forEach(Hr=>{const ol=NW(Hr);Array.isArray(ol)?Jo=[...Jo,...ol]:Jo.push(ol)}));const rl=TW(Jo),Pa=Br.split(rl).map(Hr=>Hr.trim());vW(Pa).forEach(Hr=>le({id:Hr.trim(),[o]:Hr.trim(),className:""}))},le=ce=>{var pt;if(!ce.id||!ce[o])return;if(B===-1){if(U()){ie(Mb.TAG_LIMIT),Ie();return}ie("")}const ze=b.map(ot=>ot.id.toLowerCase());if(!(m&&ze.indexOf(ce.id.trim().toLowerCase())>=0)){if(p){const ot=Pe(ce[o]);console.warn("[Deprecation] The autocomplete prop will be removed in 7.x to simplify the integration and make it more intutive. If you have any concerns regarding this, please share your thoughts in https://github.com/react-tags/react-tags/issues/949"),(p===1&&ot.length===1||p===!0&&ot.length)&&(ce=ot[0])}B!==-1&&e.onTagUpdate?e.onTagUpdate(B,ce):(pt=e==null?void 0:e.handleAddition)==null||pt.call(e,ce),q(""),L(!1),K(-1),ne(-1),Ie()}},se=ce=>{le(F[ce])},be=()=>{e.onClearAll&&e.onClearAll(),ie(""),Ie()},Je=ce=>{K(ce),L(!0)},yt=(ce,ze)=>{var ot;const pt=b[ce];(ot=e==null?void 0:e.handleDrag)==null||ot.call(e,pt,ce,ze)},rn=(()=>{const ce={...Ob,...e.classNames};return b.map((ze,pt)=>a.jsx(y.Fragment,{children:B===pt?a.jsx("div",{className:ce.editTagInput,children:a.jsx("input",{ref:ot=>{we.current=ot},onFocus:Wt,value:I,onChange:Ut,onKeyDown:M,onBlur:_,className:ce.editTagInputField,onPaste:pe,"data-testid":"tag-edit"})}):a.jsx(IW,{index:pt,tag:ze,tags:b,labelField:o,onDelete:ot=>he(pt,ot),moveTag:l?yt:void 0,removeComponent:f,onTagClicked:ot=>Nt(pt,ze,ot),readOnly:r,classNames:ce,allowDragDrop:l})},pt))})(),Xt={...Ob,...S},{name:Zo,id:Ur}=e,Bs=d===!1?_l.BOTTOM:C,_n=r?null:a.jsxs("div",{className:Xt.tagInput,children:[a.jsx("input",{...j,ref:ce=>{W.current=ce},className:Xt.tagInputField,type:"text",placeholder:w,"aria-label":w,onFocus:Wt,onBlur:_,onChange:Ut,onKeyDown:M,onPaste:pe,name:Zo,id:Ur,maxLength:N,value:E,"data-automation":"input","data-testid":"input"}),a.jsx(jW,{query:I.trim(),suggestions:F,labelField:o,selectedIndex:re,handleClick:se,handleHover:Je,minQueryLength:c,shouldRenderSuggestions:u,isFocused:H,classNames:Xt,renderSuggestion:e.renderSuggestion}),A&&b.length>0&&a.jsx(xW,{classNames:Xt,onClick:be}),Q&&a.jsxs("div",{"data-testid":"error",className:"ReactTags__error",children:[a.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",height:"24",width:"24",fill:"#e03131",children:a.jsx("path",{d:"M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224a32 32 0 1 0 -64 0 32 32 0 1 0 64 0z"})}),Q]})]});return a.jsxs("div",{className:(0,_W.default)(Xt.tags,"react-tags-wrapper"),ref:oe,children:[a.jsx("p",{role:"alert",className:"sr-only",style:{position:"absolute",overflow:"hidden",clip:"rect(0 0 0 0)",margin:"-1px",padding:0,width:"1px",height:"1px",border:0},children:te}),Bs===_l.TOP&&_n,a.jsxs("div",{className:Xt.selected,children:[rn,Bs===_l.INLINE&&_n]}),Bs===_l.BOTTOM&&_n]})},OW=DW,MW=e=>{var Q;const{placeholder:t=hH,labelField:n=gH,suggestions:r=[],delimiters:o=[],separators:s=(Q=e.delimiters)!=null&&Q.length?[]:[Zs.ENTER,Zs.TAB],autofocus:i,autoFocus:l=!0,inline:c,inputFieldPosition:u="inline",allowDeleteFromEmptyInput:f=!1,allowAdditionFromPaste:p=!0,autocomplete:d=!1,readOnly:h=!1,allowUnique:m=!0,allowDragDrop:g=!0,tags:w=[],inputProps:x={},editable:v=!1,clearAll:b=!1,handleDelete:C,handleAddition:j,onTagUpdate:S,handleDrag:N,handleFilterSuggestions:E,handleTagClick:A,handleInputChange:F,handleInputFocus:Z,handleInputBlur:I,minQueryLength:q,shouldRenderSuggestions:H,removeComponent:J,onClearAll:re,classNames:K,name:z,id:L,maxLength:te,inputValue:fe,maxTags:B,renderSuggestion:ne}=e;return a.jsx(OW,{placeholder:t,labelField:n,suggestions:r,delimiters:o,separators:s,autofocus:i,autoFocus:l,inline:c,inputFieldPosition:u,allowDeleteFromEmptyInput:f,allowAdditionFromPaste:p,autocomplete:d,readOnly:h,allowUnique:m,allowDragDrop:g,tags:w,inputProps:x,editable:v,clearAll:b,handleDelete:C,handleAddition:j,onTagUpdate:S,handleDrag:N,handleFilterSuggestions:E,handleTagClick:A,handleInputChange:F,handleInputFocus:Z,handleInputBlur:I,minQueryLength:q,shouldRenderSuggestions:H,removeComponent:J,onClearAll:re,classNames:K,name:z,id:L,maxLength:te,inputValue:fe,maxTags:B,renderSuggestion:ne})},sx=({...e})=>a.jsx(f6,{backend:iH,children:a.jsx(MW,{...e})});/*! Bundled license information: - -classnames/index.js: - (*! - Copyright (c) 2018 Jed Watson. - Licensed under the MIT License (MIT), see - http://jedwatson.github.io/classnames - *) - -lodash-es/lodash.js: - (** - * @license - * Lodash (Custom Build) - * Build: `lodash modularize exports="es" -o ./` - * Copyright OpenJS Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - *) -*/const AW=T.object({openaiCredsId:T.string(),expire:T.string(),keywordFinish:T.string(),delayMessage:T.string(),unknownMessage:T.string(),listeningFromMe:T.boolean(),stopBotFromMe:T.boolean(),keepOpen:T.boolean(),debounceTime:T.string(),speechToText:T.boolean(),ignoreJids:T.array(T.string()),openaiIdFallback:T.string().optional()}),iS=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const o=await R3(e.name,r);t(o);const s=await nk(e.name,r);n(s)}else console.error("Token ou nome da instância não encontrados.")}catch(r){console.error("Erro ao carregar configurações:",r)}};function FW({creds:e}){const{instance:t}=Tt(),[n,r]=y.useState([]),[o,s]=y.useState(),[i,l]=y.useState([]),c=h=>{r(n.filter((m,g)=>g!==h))},u=h=>{r([...n,h])},f=tn({resolver:nn(AW),defaultValues:{openaiCredsId:"",expire:"0",keywordFinish:"#SAIR",delayMessage:"1000",unknownMessage:"Mensagem não reconhecida",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",speechToText:!1,ignoreJids:[],openaiIdFallback:void 0}});y.useEffect(()=>{iS(t,s,l)},[t]),y.useEffect(()=>{var h;o&&(f.reset({openaiCredsId:o.openaiCredsId,expire:o!=null&&o.expire?o.expire.toString():"0",keywordFinish:o.keywordFinish,delayMessage:o.delayMessage?o.delayMessage.toString():"0",unknownMessage:o.unknownMessage,listeningFromMe:o.listeningFromMe,stopBotFromMe:o.stopBotFromMe,keepOpen:o.keepOpen,debounceTime:o.debounceTime?o.debounceTime.toString():"0",speechToText:o.speechToText,ignoreJids:o.ignoreJids,openaiIdFallback:o.openaiIdFallback}),r(((h=o.ignoreJids)==null?void 0:h.map(m=>({id:m,text:m,className:""})))||[]))},[o]);const p=async()=>{var h,m,g;try{const w=f.getValues();if(!t||!t.name)throw new Error("Nome da instância não encontrado.");const x={openaiCredsId:w.openaiCredsId,expire:parseInt(w.expire),keywordFinish:w.keywordFinish,delayMessage:parseInt(w.delayMessage),unknownMessage:w.unknownMessage,listeningFromMe:w.listeningFromMe,stopBotFromMe:w.stopBotFromMe,keepOpen:w.keepOpen,debounceTime:parseInt(w.debounceTime),speechToText:w.speechToText,openaiIdFallback:w.openaiIdFallback||void 0,ignoreJids:n.map(v=>v.text)};await P3(t.name,t.token,x),ke.success("Configuração salva com sucesso!")}catch(w){console.error("Erro ao criar bot:",w),ke.error(`Erro ao criar : ${(g=(m=(h=w==null?void 0:w.response)==null?void 0:h.data)==null?void 0:m.response)==null?void 0:g.message}`)}};function d(){iS(t,s,l)}return a.jsxs(Sn,{children:[a.jsx(Cn,{asChild:!0,children:a.jsxs(Te,{variant:"default",className:"mr-5",children:[a.jsx(ru,{})," Configurações Padrão"]})}),a.jsxs(un,{className:"sm:max-w-[740px] sm:max-h-[600px] overflow-y-auto",onCloseAutoFocus:d,children:[a.jsx(dn,{children:a.jsx(On,{children:"Configurações Padrão"})}),a.jsx(Bo,{...f,children:a.jsxs("form",{className:"w-full space-y-6",children:[a.jsx("div",{children:a.jsxs("div",{className:"space-y-4",children:[a.jsx(R,{control:f.control,name:"openaiCredsId",render:({field:h})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Credencial"}),a.jsxs(St,{onValueChange:h.onChange,defaultValue:h.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione uma credencial"})})}),a.jsx(vt,{className:"border border-gray-600",children:e&&e.length>0&&Array.isArray(e)&&e.map(m=>a.jsx(me,{value:`${m.id}`,children:m.name?m.name:m.apiKey.substring(0,15)+"..."},m.id))})]})]})}),a.jsx(R,{control:f.control,name:"openaiIdFallback",render:({field:h})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Bot Fallback"}),a.jsxs(St,{onValueChange:h.onChange,defaultValue:h.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione um bot"})})}),a.jsx(vt,{className:"border border-gray-600",children:i&&i.length>0&&Array.isArray(i)&&i.map(m=>a.jsx(me,{value:`${m.id}`,children:m.id},m.id))})]})]})}),a.jsx(R,{control:f.control,name:"expire",render:({field:h})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Expira em (minitos)"}),a.jsx(Y,{...h,className:"border border-gray-600 w-full",placeholder:"Expira em (minitos)",type:"number"})]})}),a.jsx(R,{control:f.control,name:"keywordFinish",render:({field:h})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Palavra Chave de Finalização"}),a.jsx(Y,{...h,className:"border border-gray-600 w-full",placeholder:"Palavra Chave de Finalização"})]})}),a.jsx(R,{control:f.control,name:"delayMessage",render:({field:h})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Delay padrão da mensagem"}),a.jsx(Y,{...h,className:"border border-gray-600 w-full",placeholder:"Delay padrão da mensagem",type:"number"})]})}),a.jsx(R,{control:f.control,name:"unknownMessage",render:({field:h})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Mensagem para tipo de mensagem desconhecida"}),a.jsx(Y,{...h,className:"border border-gray-600 w-full",placeholder:"Mensagem para tipo de mensagem desconhecida"})]})}),a.jsx(R,{control:f.control,name:"listeningFromMe",render:({field:h})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:h.value,onCheckedChange:h.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Escuta mensagens enviadas por mim"})})]})}),a.jsx(R,{control:f.control,name:"stopBotFromMe",render:({field:h})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:h.value,onCheckedChange:h.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Pausa o bot quando eu enviar uma mensagem"})})]})}),a.jsx(R,{control:f.control,name:"keepOpen",render:({field:h})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:h.value,onCheckedChange:h.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Mantem a sessão do bot aberta"})})]})}),a.jsx(R,{control:f.control,name:"speechToText",render:({field:h})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:h.value,onCheckedChange:h.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Converter áudio em texto"})})]})}),a.jsx(R,{control:f.control,name:"debounceTime",render:({field:h})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Tempo de espera"}),a.jsx(Y,{...h,className:"border border-gray-600 w-full",placeholder:"Tempo de espera",type:"number"})]})}),a.jsx(R,{control:f.control,name:"ignoreJids",render:({field:h})=>a.jsxs("div",{className:"pb-4",children:[a.jsx("label",{className:"block text-sm font-medium",children:"Ignorar JIDs"}),a.jsx(sx,{tags:n,handleDelete:c,handleAddition:u,inputFieldPosition:"bottom",placeholder:"Adicionar JIDs ex: 1234567890@s.whatsapp.net",autoFocus:!1,classNames:{tags:"tagsClass",tagInput:"tagInputClass",tagInputField:"tagInputFieldClass",selected:"selectedClass",tag:"tagClass",remove:"removeClass",suggestions:"suggestionsClass",activeSuggestion:"activeSuggestionClass",editTagInput:"editTagInputClass",editTagInputField:"editTagInputFieldClass",clearAll:"clearAllClass"}}),a.jsx("input",{type:"hidden",...h,value:n.map(m=>m.text).join(",")})]})})]})}),a.jsx(br,{children:a.jsx(Te,{variant:"default",type:"button",onClick:p,children:"Salvar"})})]})})]})]})}const lS=async(e,t,n,r)=>{try{const o=localStorage.getItem("token");if(o&&e&&e.name){const s=await nk(e.name,o);t(s);const i=await tk(e.name,o);n(i)}else console.error("Token ou nome da instância não encontrados.");r(!1)}catch(o){console.error("Erro ao carregar configurações:",o),r(!1)}};function cS(){const{instance:e}=Tt(),{openaiBotId:t}=Ta(),[n,r]=y.useState(!0),[o,s]=y.useState([]),[i,l]=y.useState([]),c=ir();y.useEffect(()=>{lS(e,s,l,r)},[e]);const u=p=>{e&&c(`/manager/instance/${e.id}/openai/${p}`)},f=()=>{lS(e,s,l,r)};return a.jsxs("main",{className:"main-table pt-5",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h3",{className:"ml-5 mb-1 text-lg font-medium",children:"Openai Bots"}),a.jsxs("div",{children:[a.jsx(FW,{creds:i}),a.jsx(DU,{}),a.jsx(PU,{resetTable:f,creds:i})]})]}),a.jsx(Dt,{className:"mt-4 border border-black"}),a.jsxs(su,{direction:"horizontal",children:[a.jsx(ro,{defaultSize:35,className:"p-5",children:a.jsx("div",{className:"table",children:n?a.jsx(Lo,{}):a.jsx(a.Fragment,{children:o&&o.length>0&&Array.isArray(o)?o.map(p=>a.jsxs("div",{className:`table-item ${p.id===t?"selected":""}`,onClick:()=>u(`${p.id}`),children:[a.jsx("h3",{className:"table-item-title",children:p.description||p.id}),a.jsx("p",{className:"table-item-description",children:p.botType})]})):a.jsx("p",{children:"Nenhum bot encontrado."})})})}),a.jsx(au,{withHandle:!0,className:"border border-black"}),a.jsx(ro,{className:"",children:t&&a.jsx(kU,{creds:i,openaiBotId:t,instance:e,resetTable:f})})]})]})}const eR=new zr,LW=async(e,t)=>(await eR.getInstance().get(`/proxy/find/${e}`,{headers:{apikey:t}})).data,$W=async(e,t,n)=>(await eR.getInstance().post(`/proxy/set/${e}`,n,{headers:{apikey:t}})).data,zW=T.object({enabled:T.boolean(),host:T.string(),port:T.string(),protocol:T.string(),username:T.string(),password:T.string()});function VW(){const{instance:e}=Tt(),[t,n]=y.useState(!1),r=tn({resolver:nn(zW),defaultValues:{enabled:!1,host:"",port:"",protocol:"http",username:"",password:""}});y.useEffect(()=>{(async()=>{if(e){n(!0);try{const i=await LW(e.name,e.token);r.reset(i)}catch(i){console.error("Erro ao buscar dados do proxy:",i)}finally{n(!1)}}})()},[e,r]);const o=async()=>{var i,l,c;if(!e)return;const s=r.getValues();n(!0);try{const u={enabled:s.enabled,host:s.host,port:s.port,protocol:s.protocol,username:s.username,password:s.password};await $W(e.name,e.token,u),ke.success("Proxy criado com sucesso")}catch(u){console.error("Erro ao criar proxy:",u),ke.error(`Erro ao criar : ${(c=(l=(i=u==null?void 0:u.response)==null?void 0:i.data)==null?void 0:l.response)==null?void 0:c.message}`)}finally{n(!1)}};return a.jsx("main",{className:"main-content",children:a.jsx(uo,{...r,children:a.jsxs("form",{className:"w-full space-y-6",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"mb-1 text-lg font-medium",children:"Proxy"}),a.jsx(Go,{className:"my-4 border-t border-gray-600"}),a.jsxs("div",{className:"space-y-4",children:[a.jsx(R,{control:r.control,name:"enabled",render:({field:s})=>a.jsxs(D,{className:"flex flex-row items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Ativo"}),a.jsx(zt,{children:"Ativa ou desativa o proxy"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:s.value,onCheckedChange:s.onChange})})]})}),a.jsx(R,{control:r.control,name:"host",render:({field:s})=>a.jsx(Y,{...s,className:"border border-gray-600 w-full",placeholder:"Host"})}),a.jsx(R,{control:r.control,name:"port",render:({field:s})=>a.jsx(Y,{...s,className:"border border-gray-600 w-full",placeholder:"Porta",type:"number"})}),a.jsx(R,{control:r.control,name:"protocol",render:({field:s})=>a.jsx(Y,{...s,className:"border border-gray-600 w-full",placeholder:"Protocolo"})}),a.jsx(R,{control:r.control,name:"username",render:({field:s})=>a.jsx(Y,{...s,className:"border border-gray-600 w-full",placeholder:"Usuário"})}),a.jsx(R,{control:r.control,name:"password",render:({field:s})=>a.jsx(Y,{...s,className:"border border-gray-600 w-full",placeholder:"Senha",type:"password"})})]})]}),a.jsx(Te,{disabled:t,onClick:o,children:t?"Salvando...":"Salvar"})]})})})}const tR=new zr,UW=async(e,t)=>(await tR.getInstance().get(`/rabbitmq/find/${e}`,{headers:{apikey:t}})).data,BW=async(e,t,n)=>(await tR.getInstance().post(`/rabbitmq/set/${e}`,n,{headers:{apikey:t}})).data,HW=T.object({enabled:T.boolean(),events:T.array(T.string())});function GW(){const{instance:e}=Tt(),[t,n]=y.useState(!1),r=tn({resolver:nn(HW),defaultValues:{enabled:!1,events:[]}});y.useEffect(()=>{(async()=>{if(e){n(!0);try{const l=await UW(e.name,e.token);r.reset(l)}catch(l){console.error("Erro ao buscar dados do rabbitmq:",l)}finally{n(!1)}}})()},[e,r]);const o=async()=>{var l,c,u;if(!e)return;const i=r.getValues();n(!0);try{const f={enabled:i.enabled,events:i.events};await BW(e.name,e.token,f),ke.success("Rabbitmq criado com sucesso")}catch(f){console.error("Erro ao criar rabbitmq:",f),ke.error(`Erro ao criar : ${(u=(c=(l=f==null?void 0:f.response)==null?void 0:l.data)==null?void 0:c.response)==null?void 0:u.message}`)}finally{n(!1)}},s=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"];return a.jsx("main",{className:"main-content",children:a.jsx(uo,{...r,children:a.jsxs("form",{className:"w-full space-y-6",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"mb-1 text-lg font-medium",children:"Rabbitmq"}),a.jsx(Go,{className:"my-4 border-t border-gray-600"}),a.jsxs("div",{className:"space-y-4",children:[a.jsx(R,{control:r.control,name:"enabled",render:({field:i})=>a.jsxs(D,{className:"flex flex-row items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Ativo"}),a.jsx(zt,{children:"Ativa ou desativa o rabbitmq"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:i.value,onCheckedChange:i.onChange})})]})}),a.jsx(R,{control:r.control,name:"events",render:({field:i})=>a.jsxs(D,{className:"flex flex-col",children:[a.jsx(O,{children:"Eventos"}),a.jsx(ae,{children:a.jsx(a.Fragment,{children:s.map(l=>a.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsx("span",{children:l}),a.jsx(Ce,{checked:i.value.includes(l),onCheckedChange:c=>{c?i.onChange([...i.value,l]):i.onChange(i.value.filter(u=>u!==l))}})]},l))})})]})})]})]}),a.jsx(Te,{disabled:t,onClick:o,children:t?"Salvando...":"Salvar"})]})})})}const WW=T.object({rejectCall:T.boolean(),msgCall:T.string().optional(),groupsIgnore:T.boolean(),alwaysOnline:T.boolean(),readMessages:T.boolean(),syncFullHistory:T.boolean(),readStatus:T.boolean()});function KW(){const[e,t]=y.useState(!0),[n,r]=y.useState(!1),[o,s]=y.useState(""),{instance:i}=Tt(),l=tn({resolver:nn(WW),defaultValues:{rejectCall:!1,msgCall:"",groupsIgnore:!1,alwaysOnline:!1,readMessages:!1,syncFullHistory:!1,readStatus:!1}});y.useEffect(()=>{(async()=>{try{if(i&&i.name&&i.token){s(i.token);const f=await JM(i.name,i.token);l.reset({rejectCall:f.rejectCall,msgCall:f.msgCall||"",groupsIgnore:f.groupsIgnore,alwaysOnline:f.alwaysOnline,readMessages:f.readMessages,syncFullHistory:f.syncFullHistory,readStatus:f.readStatus})}else console.error("Token ou nome da instância não encontrados.");t(!1)}catch(f){console.error("Erro ao carregar configurações:",f),t(!1)}})()},[l,i]);const c=async u=>{try{if(!i||!i.name)throw new Error("Nome da instância não encontrado.");r(!0);const f={rejectCall:u.rejectCall,msgCall:u.msgCall,groupsIgnore:u.groupsIgnore,alwaysOnline:u.alwaysOnline,readMessages:u.readMessages,syncFullHistory:u.syncFullHistory,readStatus:u.readStatus};await YM(i.name,o,f),ke.success("Configurações atualizadas com sucesso!")}catch(f){console.error("Erro ao atualizar configurações:",f),ke.error("Erro ao atualizar configurações.")}finally{r(!1)}};return e?a.jsx(Lo,{}):a.jsx("main",{className:"main-content",children:a.jsx(uo,{...l,children:a.jsxs("form",{onSubmit:l.handleSubmit(c),className:"w-full space-y-6",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"mb-1 text-lg font-medium",children:"Comportamento"}),a.jsx(Go,{className:"my-4 border-t border-gray-600"}),a.jsxs("div",{className:"space-y-4",children:[a.jsx(R,{control:l.control,name:"rejectCall",render:({field:u})=>a.jsxs(D,{className:"flex flex-col items-start rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"flex flex-row items-center justify-between w-full",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Rejeitar Chamadas"}),a.jsx(zt,{children:"Rejeitas chamadas de voz e vídeo no Whatsapp"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:u.value,onCheckedChange:u.onChange})})]}),u.value&&a.jsx("div",{className:"w-full mt-4",children:a.jsx(R,{control:l.control,name:"msgCall",render:({field:f})=>a.jsx(ae,{children:a.jsx(ko,{...f,placeholder:"Mensagem ao rejeitar chamada",className:"border border-gray-600 w-full"})})})})]})}),a.jsx(R,{control:l.control,name:"groupsIgnore",render:({field:u})=>a.jsxs(D,{className:"flex flex-row items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Ignorar Grupos"}),a.jsx(zt,{children:"Ignora eventos de grupos no Whatsapp"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:u.value,onCheckedChange:u.onChange})})]})}),a.jsx(R,{control:l.control,name:"alwaysOnline",render:({field:u})=>a.jsxs(D,{className:"flex flex-row items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Sempre Online"}),a.jsx(zt,{children:"Mantém o Whatsapp sempre online"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:u.value,onCheckedChange:u.onChange})})]})}),a.jsx(R,{control:l.control,name:"readMessages",render:({field:u})=>a.jsxs(D,{className:"flex flex-row items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Visualizar Mensagens"}),a.jsx(zt,{children:"Visualiza mensagens automaticamente"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:u.value,onCheckedChange:u.onChange})})]})}),a.jsx(R,{control:l.control,name:"syncFullHistory",render:({field:u})=>a.jsxs(D,{className:"flex flex-row items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Sincronizar Histórico Completo"}),a.jsx(zt,{children:"Sincroniza o histórico completo de mensagens ao ler o qrcode"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:u.value,onCheckedChange:u.onChange})})]})}),a.jsx(R,{control:l.control,name:"readStatus",render:({field:u})=>a.jsxs(D,{className:"flex flex-row items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Visualizar Status"}),a.jsx(zt,{children:"Recebe eventos dos broadcasts e visualiza todos os status"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:u.value,onCheckedChange:u.onChange})})]})})]})]}),a.jsx(Te,{type:"submit",disabled:n,children:n?"Salvando...":"Salvar"})]})})})}const nR=new zr,qW=async(e,t)=>(await nR.getInstance().get(`/sqs/find/${e}`,{headers:{apikey:t}})).data,ZW=async(e,t,n)=>(await nR.getInstance().post(`/sqs/set/${e}`,n,{headers:{apikey:t}})).data,JW=T.object({enabled:T.boolean(),events:T.array(T.string())});function YW(){const{instance:e}=Tt(),[t,n]=y.useState(!1),r=tn({resolver:nn(JW),defaultValues:{enabled:!1,events:[]}});y.useEffect(()=>{(async()=>{if(e){n(!0);try{const l=await qW(e.name,e.token);r.reset(l)}catch(l){console.error("Erro ao buscar dados do sqs:",l)}finally{n(!1)}}})()},[e,r]);const o=async()=>{var l,c,u;if(!e)return;const i=r.getValues();n(!0);try{const f={enabled:i.enabled,events:i.events};await ZW(e.name,e.token,f),ke.success("Sqs criado com sucesso")}catch(f){console.error("Erro ao criar sqs:",f),ke.error(`Erro ao criar : ${(u=(c=(l=f==null?void 0:f.response)==null?void 0:l.data)==null?void 0:c.response)==null?void 0:u.message}`)}finally{n(!1)}},s=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"];return a.jsx("main",{className:"main-content",children:a.jsx(uo,{...r,children:a.jsxs("form",{className:"w-full space-y-6",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"mb-1 text-lg font-medium",children:"Sqs"}),a.jsx(Go,{className:"my-4 border-t border-gray-600"}),a.jsxs("div",{className:"space-y-4",children:[a.jsx(R,{control:r.control,name:"enabled",render:({field:i})=>a.jsxs(D,{className:"flex flex-row items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Ativo"}),a.jsx(zt,{children:"Ativa ou desativa o sqs"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:i.value,onCheckedChange:i.onChange})})]})}),a.jsx(R,{control:r.control,name:"events",render:({field:i})=>a.jsxs(D,{className:"flex flex-col",children:[a.jsx(O,{children:"Eventos"}),a.jsx(ae,{children:a.jsx(a.Fragment,{children:s.map(l=>a.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsx("span",{children:l}),a.jsx(Ce,{checked:i.value.includes(l),onCheckedChange:c=>{c?i.onChange([...i.value,l]):i.onChange(i.value.filter(u=>u!==l))}})]},l))})})]})})]})]}),a.jsx(Te,{disabled:t,onClick:o,children:t?"Salvando...":"Salvar"})]})})})}const Ko=new zr,rR=async(e,t)=>(await Ko.getInstance().get(`/typebot/find/${e}`,{headers:{apikey:t}})).data,XW=async(e,t,n)=>(await Ko.getInstance().get(`/typebot/fetch/${n}/${e}`,{headers:{apikey:t}})).data,QW=async(e,t,n)=>(await Ko.getInstance().post(`/typebot/create/${e}`,n,{headers:{apikey:t}})).data,eK=async(e,t,n,r)=>(await Ko.getInstance().put(`/typebot/update/${n}/${e}`,r,{headers:{apikey:t}})).data,tK=async(e,t,n)=>(await Ko.getInstance().delete(`/typebot/delete/${n}/${e}`,{headers:{apikey:t}})).data,nK=async(e,t)=>(await Ko.getInstance().get(`/typebot/fetchSettings/${e}`,{headers:{apikey:t}})).data,rK=async(e,t,n)=>(await Ko.getInstance().post(`/typebot/settings/${e}`,n,{headers:{apikey:t}})).data,oK=async(e,t,n)=>(await Ko.getInstance().get(`/typebot/fetchSessions/${n}/${e}`,{headers:{apikey:t}})).data,sK=async(e,t,n,r)=>(await Ko.getInstance().post(`/typebot/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data,aK=T.object({enabled:T.boolean(),description:T.string(),url:T.string().url(),typebot:T.string(),triggerType:T.string(),triggerOperator:T.string().optional(),triggerValue:T.string().optional(),expire:T.string(),keywordFinish:T.string(),delayMessage:T.string(),unknownMessage:T.string(),listeningFromMe:T.boolean(),stopBotFromMe:T.boolean(),keepOpen:T.boolean(),debounceTime:T.string(),ignoreJids:T.array(T.string())});function iK({resetTable:e}){const{instance:t}=Tt(),[n,r]=y.useState(!1),[o,s]=y.useState(!1),i=tn({resolver:nn(aK),defaultValues:{enabled:!0,description:"",url:"",typebot:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:"0",keywordFinish:"",delayMessage:"0",unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[]}}),l=async u=>{var f,p,d;try{if(!t||!t.name)throw new Error("Nome da instância não encontrado.");r(!0);const h={enabled:u.enabled,description:u.description,url:u.url,typebot:u.typebot,triggerType:u.triggerType,triggerOperator:u.triggerOperator||"",triggerValue:u.triggerValue||"",expire:parseInt(u.expire,10),keywordFinish:u.keywordFinish,delayMessage:parseInt(u.delayMessage,10),unknownMessage:u.unknownMessage,listeningFromMe:u.listeningFromMe,stopBotFromMe:u.stopBotFromMe,keepOpen:u.keepOpen,debounceTime:parseInt(u.debounceTime,10)};await QW(t.name,t.token,h),ke.success("Typebot criado com sucesso!"),s(!1),c(),e()}catch(h){console.error("Erro ao criar typebot:",h),ke.error(`Erro ao criar : ${(d=(p=(f=h==null?void 0:h.response)==null?void 0:f.data)==null?void 0:p.response)==null?void 0:d.message}`)}finally{r(!1)}};function c(){i.reset()}return a.jsxs(Sn,{open:o,onOpenChange:s,children:[a.jsx(Cn,{asChild:!0,children:a.jsxs(Te,{variant:"default",className:"mr-5",children:[a.jsx(ou,{})," Typebot"]})}),a.jsxs(un,{className:"sm:max-w-[740px] sm:max-h-[600px] overflow-y-auto",onCloseAutoFocus:c,children:[a.jsx(dn,{children:a.jsx(On,{children:"Novo Typebot"})}),a.jsx(Bo,{...i,children:a.jsxs("form",{onSubmit:i.handleSubmit(l),className:"w-full space-y-6",children:[a.jsx("div",{children:a.jsxs("div",{className:"space-y-4",children:[a.jsx(R,{control:i.control,name:"enabled",render:({field:u})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:u.value,onCheckedChange:u.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Ativo"})})]})}),a.jsx(R,{control:i.control,name:"description",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Descrição"}),a.jsx(Y,{...u,className:"border border-gray-600 w-full",placeholder:"Descrição"})]})}),a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Typebot Settings"}),a.jsx(Dt,{className:"border border-gray-700"}),a.jsx(R,{control:i.control,name:"url",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"URL da API do Typebot"}),a.jsx(Y,{...u,className:"border border-gray-600 w-full",placeholder:"URL da API do Typebot"})]})}),a.jsx(R,{control:i.control,name:"typebot",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Nome do Typebot"}),a.jsx(Y,{...u,className:"border border-gray-600 w-full",placeholder:"Nome do Typebot"})]})}),a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Trigger Settings"}),a.jsx(Dt,{className:"border border-gray-700"}),a.jsx(R,{control:i.control,name:"triggerType",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Tipo de gatilho"}),a.jsxs(St,{onValueChange:u.onChange,defaultValue:u.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione um tipo"})})}),a.jsxs(vt,{className:"border border-gray-600",children:[a.jsx(me,{value:"keyword",children:"Palavra Chave"}),a.jsx(me,{value:"all",children:"Todos"}),a.jsx(me,{value:"none",children:"Nenhum"})]})]})]})}),i.watch("triggerType")==="keyword"&&a.jsxs(a.Fragment,{children:[a.jsx(R,{control:i.control,name:"triggerOperator",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Operador do gatilho"}),a.jsxs(St,{onValueChange:u.onChange,defaultValue:u.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione um operador"})})}),a.jsxs(vt,{className:"border border-gray-600",children:[a.jsx(me,{value:"contains",children:"Contém"}),a.jsx(me,{value:"equals",children:"Igual à"}),a.jsx(me,{value:"startsWith",children:"Começa com"}),a.jsx(me,{value:"endsWith",children:"Termina com"}),a.jsx(me,{value:"regex",children:"Regex"})]})]})]})}),a.jsx(R,{control:i.control,name:"triggerValue",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Gatilho"}),a.jsx(Y,{...u,className:"border border-gray-600 w-full",placeholder:"Gatilho"})]})})]}),a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Options Settings"}),a.jsx(Dt,{className:"border border-gray-700"}),a.jsx(R,{control:i.control,name:"expire",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Expira em (minitos)"}),a.jsx(Y,{...u,className:"border border-gray-600 w-full",placeholder:"Expira em (minitos)",type:"number"})]})}),a.jsx(R,{control:i.control,name:"keywordFinish",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Palavra Chave de Finalização"}),a.jsx(Y,{...u,className:"border border-gray-600 w-full",placeholder:"Palavra Chave de Finalização"})]})}),a.jsx(R,{control:i.control,name:"delayMessage",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Delay padrão da mensagem"}),a.jsx(Y,{...u,className:"border border-gray-600 w-full",placeholder:"Delay padrão da mensagem",type:"number"})]})}),a.jsx(R,{control:i.control,name:"unknownMessage",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Mensagem para tipo de mensagem desconhecida"}),a.jsx(Y,{...u,className:"border border-gray-600 w-full",placeholder:"Mensagem para tipo de mensagem desconhecida"})]})}),a.jsx(R,{control:i.control,name:"listeningFromMe",render:({field:u})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:u.value,onCheckedChange:u.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Escuta mensagens enviadas por mim"})})]})}),a.jsx(R,{control:i.control,name:"stopBotFromMe",render:({field:u})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:u.value,onCheckedChange:u.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Pausa o bot quando eu enviar uma mensagem"})})]})}),a.jsx(R,{control:i.control,name:"keepOpen",render:({field:u})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:u.value,onCheckedChange:u.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Mantem a sessão do bot aberta"})})]})}),a.jsx(R,{control:i.control,name:"debounceTime",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Tempo de espera"}),a.jsx(Y,{...u,className:"border border-gray-600 w-full",placeholder:"Tempo de espera",type:"number"})]})})]})}),a.jsx(br,{children:a.jsx(Te,{disabled:n,variant:"default",type:"submit",children:"Salvar"})})]})})]})]})}const uS=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const o=await oK(e.name,r,t);n(o)}else console.error("Token ou nome da instância não encontrados.")}catch(r){console.error("Erro ao carregar sessões:",r)}};function lK({typebotId:e}){var f,p;const{instance:t}=Tt(),[n,r]=y.useState([]),[o,s]=y.useState([]);y.useEffect(()=>{uS(t,e,s)},[t,e]);function i(){uS(t,e,s)}const l=async(d,h)=>{var m,g,w;try{if(!t)return;await sK(t.name,t.token,d,h),ke.success("Status alterado com sucesso."),i()}catch(x){console.error("Erro ao atualizar:",x),ke.error(`Erro ao atualizar : ${(w=(g=(m=x==null?void 0:x.response)==null?void 0:m.data)==null?void 0:g.response)==null?void 0:w.message}`)}},c=[{accessorKey:"remoteJid",header:()=>a.jsx("div",{className:"text-center",children:"Remote Jid"}),cell:({row:d})=>a.jsx("div",{children:d.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>a.jsx("div",{className:"text-center",children:"Push Name"}),cell:({row:d})=>a.jsx("div",{children:d.getValue("pushName")})},{accessorKey:"sessionId",header:()=>a.jsx("div",{className:"text-center",children:"Session ID"}),cell:({row:d})=>a.jsx("div",{children:d.getValue("sessionId")})},{accessorKey:"status",header:()=>a.jsx("div",{className:"text-center",children:"Status"}),cell:({row:d})=>a.jsx("div",{children:d.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:d})=>{const h=d.original;return a.jsxs(Np,{children:[a.jsx(kp,{asChild:!0,children:a.jsxs(Te,{variant:"ghost",className:"h-8 w-8 p-0",children:[a.jsx("span",{className:"sr-only",children:"Open menu"}),a.jsx(ep,{className:"h-4 w-4"})]})}),a.jsxs(qi,{align:"end",children:[a.jsx(pu,{children:"Actions"}),a.jsx(Zi,{}),h.status!=="opened"&&a.jsxs(xn,{onClick:()=>l(h.remoteJid,"opened"),children:[a.jsx(ny,{className:"w-4 h-4 mr-2"}),"Abrir"]}),h.status!=="paused"&&h.status!=="closed"&&a.jsxs(xn,{onClick:()=>l(h.remoteJid,"paused"),children:[a.jsx(ty,{className:"w-4 h-4 mr-2"}),"Pausar"]}),h.status!=="closed"&&a.jsxs(xn,{onClick:()=>l(h.remoteJid,"closed"),children:[a.jsx(Yv,{className:"w-4 h-4 mr-2"}),"Fechar"]}),a.jsxs(xn,{onClick:()=>l(h.remoteJid,"delete"),children:[a.jsx(Xv,{className:"w-4 h-4 mr-2"}),"Excluir"]})]})]})}}],u=Mp({data:o,columns:c,onSortingChange:r,getCoreRowModel:Pp(),getPaginationRowModel:Dp(),getSortedRowModel:Op(),getFilteredRowModel:Ip(),state:{sorting:n}});return a.jsxs(Sn,{children:[a.jsx(Cn,{asChild:!0,children:a.jsxs(Te,{variant:"default",className:"mr-5 text-white",children:[a.jsx(Qv,{})," Sessões"]})}),a.jsxs(un,{className:"sm:max-w-[950px] overflow-y-auto",onCloseAutoFocus:i,children:[a.jsx(dn,{children:a.jsx(On,{children:"Sessões"})}),a.jsxs("div",{children:[a.jsx(Y,{placeholder:"Search by remoteJid...",value:((f=u.getColumn("remoteJid"))==null?void 0:f.getFilterValue())??"",onChange:d=>{var h;return(h=u.getColumn("remoteJid"))==null?void 0:h.setFilterValue(d.target.value)},className:"max-w-sm border border-gray-300 rounded-md"}),a.jsxs(hu,{children:[a.jsx(gu,{children:u.getHeaderGroups().map(d=>a.jsx(nr,{children:d.headers.map(h=>a.jsx(vu,{children:h.isPlaceholder?null:Ds(h.column.columnDef.header,h.getContext())},h.id))},d.id))}),a.jsx(mu,{children:(p=u.getRowModel().rows)!=null&&p.length?u.getRowModel().rows.map(d=>a.jsx(nr,{"data-state":d.getIsSelected()&&"selected",children:d.getVisibleCells().map(h=>a.jsx($o,{children:Ds(h.column.columnDef.cell,h.getContext())},h.id))},d.id)):a.jsx(nr,{children:a.jsx($o,{colSpan:c.length,className:"h-24 text-center",children:"No results."})})})]})]})]})]})}const cK=T.object({enabled:T.boolean(),description:T.string(),url:T.string().url(),typebot:T.string(),triggerType:T.string(),triggerOperator:T.string().optional(),triggerValue:T.string().optional(),expire:T.string(),keywordFinish:T.string(),delayMessage:T.string(),unknownMessage:T.string(),listeningFromMe:T.boolean(),stopBotFromMe:T.boolean(),keepOpen:T.boolean(),debounceTime:T.string(),ignoreJids:T.array(T.string())});function uK({typebotId:e,instance:t,resetTable:n}){const[,r]=y.useState(""),[o,s]=y.useState(!0),[i,l]=y.useState(!1),c=ir(),u=tn({resolver:nn(cK),defaultValues:{enabled:!0,description:"",url:"",typebot:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:"0",keywordFinish:"",delayMessage:"0",unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[]}});y.useEffect(()=>{(async()=>{try{const h=localStorage.getItem("token");if(h&&t&&t.name&&e){r(h);const m=await XW(t.name,h,e);u.reset({enabled:m.enabled,description:m.description,url:m.url,typebot:m.typebot,triggerType:m.triggerType,triggerOperator:m.triggerOperator,triggerValue:m.triggerValue,expire:m.expire.toString(),keywordFinish:m.keywordFinish,delayMessage:m.delayMessage.toString(),unknownMessage:m.unknownMessage,listeningFromMe:m.listeningFromMe,stopBotFromMe:m.stopBotFromMe,keepOpen:m.keepOpen,debounceTime:m.debounceTime.toString()})}else console.error("Token ou nome da instância não encontrados.");s(!1)}catch(h){console.error("Erro ao carregar configurações:",h),s(!1)}})()},[u,t,e]);const f=async()=>{var d,h,m;try{const g=u.getValues(),w=localStorage.getItem("token");if(w&&t&&t.name&&e){const x={enabled:g.enabled,description:g.description,url:g.url,typebot:g.typebot,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:parseInt(g.expire,10),keywordFinish:g.keywordFinish,delayMessage:parseInt(g.delayMessage,10),unknownMessage:g.unknownMessage,listeningFromMe:g.listeningFromMe,stopBotFromMe:g.stopBotFromMe,keepOpen:g.keepOpen,debounceTime:parseInt(g.debounceTime,10)};await eK(t.name,w,e,x),ke.success("Typebot atualizado com sucesso.")}else console.error("Token ou nome da instância não encontrados.")}catch(g){console.error("Erro ao atualizar typebot:",g),ke.error(`Erro ao atualizar : ${(m=(h=(d=g==null?void 0:g.response)==null?void 0:d.data)==null?void 0:h.response)==null?void 0:m.message}`)}},p=async()=>{try{const d=localStorage.getItem("token");d&&t&&t.name&&e?(await tK(t.name,d,e),ke.success("Typebot excluído com sucesso."),l(!1),n(),c(`/manager/instance/${t.id}/typebot`)):console.error("Token ou nome da instância não encontrados.")}catch(d){console.error("Erro ao excluir typebot:",d)}};return a.jsxs("div",{className:"form",children:[o&&a.jsx(Lo,{}),!o&&a.jsx(uo,{...u,children:a.jsxs("form",{onSubmit:u.handleSubmit(f),className:"w-full space-y-6",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Typebot"}),a.jsxs("div",{className:"space-y-4",children:[a.jsx(R,{control:u.control,name:"enabled",render:({field:d})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:d.value,onCheckedChange:d.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Ativo"})})]})}),a.jsx(R,{control:u.control,name:"description",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Descrição"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Descrição"})]})}),a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Typebot Settings"}),a.jsx(Dt,{className:"border border-gray-700"}),a.jsx(R,{control:u.control,name:"url",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"URL da API do Typebot"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"URL da API do Typebot"})]})}),a.jsx(R,{control:u.control,name:"typebot",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Nome do Typebot"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Nome do Typebot"})]})}),a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Trigger Settings"}),a.jsx(Dt,{className:"border border-gray-700"}),a.jsx(R,{control:u.control,name:"triggerType",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Tipo de gatilho"}),a.jsxs(St,{onValueChange:d.onChange,defaultValue:d.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione um tipo"})})}),a.jsxs(vt,{className:"border border-gray-600",children:[a.jsx(me,{value:"keyword",children:"Palavra Chave"}),a.jsx(me,{value:"all",children:"Todos"}),a.jsx(me,{value:"none",children:"Nenhum"})]})]})]})}),u.watch("triggerType")==="keyword"&&a.jsxs(a.Fragment,{children:[a.jsx(R,{control:u.control,name:"triggerOperator",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Operador do gatilho"}),a.jsxs(St,{onValueChange:d.onChange,defaultValue:d.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione um operador"})})}),a.jsxs(vt,{className:"border border-gray-600",children:[a.jsx(me,{value:"contains",children:"Contém"}),a.jsx(me,{value:"equals",children:"Igual à"}),a.jsx(me,{value:"startsWith",children:"Começa com"}),a.jsx(me,{value:"endsWith",children:"Termina com"}),a.jsx(me,{value:"regex",children:"Regex"})]})]})]})}),a.jsx(R,{control:u.control,name:"triggerValue",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Gatilho"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Gatilho"})]})})]}),a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Options Settings"}),a.jsx(Dt,{className:"border border-gray-700"}),a.jsx(R,{control:u.control,name:"expire",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Expira em (minitos)"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Expira em (minitos)",type:"number"})]})}),a.jsx(R,{control:u.control,name:"keywordFinish",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Palavra Chave de Finalização"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Palavra Chave de Finalização"})]})}),a.jsx(R,{control:u.control,name:"delayMessage",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Delay padrão da mensagem"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Delay padrão da mensagem",type:"number"})]})}),a.jsx(R,{control:u.control,name:"unknownMessage",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Mensagem para tipo de mensagem desconhecida"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Mensagem para tipo de mensagem desconhecida"})]})}),a.jsx(R,{control:u.control,name:"listeningFromMe",render:({field:d})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:d.value,onCheckedChange:d.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Escuta mensagens enviadas por mim"})})]})}),a.jsx(R,{control:u.control,name:"stopBotFromMe",render:({field:d})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:d.value,onCheckedChange:d.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Pausa o bot quando eu enviar uma mensagem"})})]})}),a.jsx(R,{control:u.control,name:"keepOpen",render:({field:d})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:d.value,onCheckedChange:d.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Mantem a sessão do bot aberta"})})]})}),a.jsx(R,{control:u.control,name:"debounceTime",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Tempo de espera"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Tempo de espera",type:"number"})]})})]})]}),a.jsx("div",{children:a.jsx(lK,{typebotId:e})}),a.jsx(Te,{className:"bg-blue-400 hover:bg-blue-600 text-white",onClick:f,children:"Atualizar"}),a.jsxs(Sn,{open:i,onOpenChange:l,children:[a.jsx(Cn,{asChild:!0,children:a.jsx(Te,{variant:"secondary",className:"ml-2 bg-red-400 hover:bg-red-600",children:"Excluir"})}),a.jsx(un,{children:a.jsxs(dn,{children:[a.jsx(On,{children:"Tem certeza que deseja excluir?"}),a.jsx(Pi,{children:"Esta ação não pode ser desfeita."}),a.jsxs(br,{children:[a.jsx(Te,{variant:"default",className:"bg-red-400 hover:bg-red-600 text-white",onClick:p,children:"Exluir"}),a.jsx(Te,{variant:"outline",onClick:()=>l(!1),children:"Cancelar"})]})]})})]})]})})]})}const dK=T.object({expire:T.string(),keywordFinish:T.string(),delayMessage:T.string(),unknownMessage:T.string(),listeningFromMe:T.boolean(),stopBotFromMe:T.boolean(),keepOpen:T.boolean(),debounceTime:T.string(),ignoreJids:T.array(T.string()),typebotIdFallback:T.string().optional()}),dS=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const o=await nK(e.name,r);t(o);const s=await rR(e.name,r);n(s)}else console.error("Token ou nome da instância não encontrados.")}catch(r){console.error("Erro ao carregar configurações:",r)}};function fK(){const{instance:e}=Tt(),[t,n]=y.useState([]),[r,o]=y.useState(),[s,i]=y.useState([]),l=d=>{n(t.filter((h,m)=>m!==d))},c=d=>{n([...t,d])},u=tn({resolver:nn(dK),defaultValues:{expire:"0",keywordFinish:"#SAIR",delayMessage:"1000",unknownMessage:"Mensagem não reconhecida",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],typebotIdFallback:void 0}});y.useEffect(()=>{dS(e,o,i)},[e]),y.useEffect(()=>{var d;r&&(u.reset({expire:r!=null&&r.expire?r.expire.toString():"0",keywordFinish:r.keywordFinish,delayMessage:r.delayMessage?r.delayMessage.toString():"0",unknownMessage:r.unknownMessage,listeningFromMe:r.listeningFromMe,stopBotFromMe:r.stopBotFromMe,keepOpen:r.keepOpen,debounceTime:r.debounceTime?r.debounceTime.toString():"0",ignoreJids:r.ignoreJids,typebotIdFallback:r.typebotIdFallback}),n(((d=r.ignoreJids)==null?void 0:d.map(h=>({id:h,text:h,className:""})))||[]))},[r]);const f=async()=>{var d,h,m;try{const g=u.getValues();if(!e||!e.name)throw new Error("Nome da instância não encontrado.");const w={expire:parseInt(g.expire),keywordFinish:g.keywordFinish,delayMessage:parseInt(g.delayMessage),unknownMessage:g.unknownMessage,listeningFromMe:g.listeningFromMe,stopBotFromMe:g.stopBotFromMe,keepOpen:g.keepOpen,debounceTime:parseInt(g.debounceTime),typebotIdFallback:g.typebotIdFallback||void 0,ignoreJids:t.map(x=>x.text)};await rK(e.name,e.token,w),ke.success("Configuração salva com sucesso!")}catch(g){console.error("Erro ao criar bot:",g),ke.error(`Erro ao criar : ${(m=(h=(d=g==null?void 0:g.response)==null?void 0:d.data)==null?void 0:h.response)==null?void 0:m.message}`)}};function p(){dS(e,o,i)}return a.jsxs(Sn,{children:[a.jsx(Cn,{asChild:!0,children:a.jsxs(Te,{variant:"default",className:"mr-5",children:[a.jsx(ru,{})," Configurações Padrão"]})}),a.jsxs(un,{className:"sm:max-w-[740px] sm:max-h-[600px] overflow-y-auto",onCloseAutoFocus:p,children:[a.jsx(dn,{children:a.jsx(On,{children:"Configurações Padrão"})}),a.jsx(Bo,{...u,children:a.jsxs("form",{className:"w-full space-y-6",children:[a.jsx("div",{children:a.jsxs("div",{className:"space-y-4",children:[a.jsx(R,{control:u.control,name:"typebotIdFallback",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Typebot Fallback"}),a.jsxs(St,{onValueChange:d.onChange,defaultValue:d.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione um typebot"})})}),a.jsx(vt,{className:"border border-gray-600",children:s&&s.length>0&&Array.isArray(s)&&s.map(h=>a.jsx(me,{value:`${h.id}`,children:h.typebot},h.id))})]})]})}),a.jsx(R,{control:u.control,name:"expire",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Expira em (minitos)"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Expira em (minitos)",type:"number"})]})}),a.jsx(R,{control:u.control,name:"keywordFinish",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Palavra Chave de Finalização"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Palavra Chave de Finalização"})]})}),a.jsx(R,{control:u.control,name:"delayMessage",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Delay padrão da mensagem"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Delay padrão da mensagem",type:"number"})]})}),a.jsx(R,{control:u.control,name:"unknownMessage",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Mensagem para tipo de mensagem desconhecida"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Mensagem para tipo de mensagem desconhecida"})]})}),a.jsx(R,{control:u.control,name:"listeningFromMe",render:({field:d})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:d.value,onCheckedChange:d.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Escuta mensagens enviadas por mim"})})]})}),a.jsx(R,{control:u.control,name:"stopBotFromMe",render:({field:d})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:d.value,onCheckedChange:d.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Pausa o bot quando eu enviar uma mensagem"})})]})}),a.jsx(R,{control:u.control,name:"keepOpen",render:({field:d})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:d.value,onCheckedChange:d.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Mantem a sessão do bot aberta"})})]})}),a.jsx(R,{control:u.control,name:"debounceTime",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Tempo de espera"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Tempo de espera",type:"number"})]})}),a.jsx(R,{control:u.control,name:"ignoreJids",render:({field:d})=>a.jsxs("div",{className:"pb-4",children:[a.jsx("label",{className:"block text-sm font-medium",children:"Ignorar JIDs"}),a.jsx(sx,{tags:t,handleDelete:l,handleAddition:c,inputFieldPosition:"bottom",placeholder:"Adicionar JIDs ex: 1234567890@s.whatsapp.net",autoFocus:!1,classNames:{tags:"tagsClass",tagInput:"tagInputClass",tagInputField:"tagInputFieldClass",selected:"selectedClass",tag:"tagClass",remove:"removeClass",suggestions:"suggestionsClass",activeSuggestion:"activeSuggestionClass",editTagInput:"editTagInputClass",editTagInputField:"editTagInputFieldClass",clearAll:"clearAllClass"}}),a.jsx("input",{type:"hidden",...d,value:t.map(h=>h.text).join(",")})]})})]})}),a.jsx(br,{children:a.jsx(Te,{variant:"default",type:"button",onClick:f,children:"Salvar"})})]})})]})]})}const fS=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const o=await rR(e.name,r);t(o)}else console.error("Token ou nome da instância não encontrados.");n(!1)}catch(r){console.error("Erro ao carregar configurações:",r),n(!1)}};function pS(){const{instance:e}=Tt(),{typebotId:t}=Ta(),[n,r]=y.useState(!0),[o,s]=y.useState([]),i=ir();y.useEffect(()=>{fS(e,s,r)},[e]);const l=u=>{e&&i(`/manager/instance/${e.id}/typebot/${u}`)},c=()=>{fS(e,s,r)};return a.jsxs("main",{className:"main-table pt-5",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h3",{className:"ml-5 mb-1 text-lg font-medium",children:"Typebots"}),a.jsxs("div",{children:[a.jsx(fK,{}),a.jsx(iK,{resetTable:c})]})]}),a.jsx(Dt,{className:"mt-4 border border-black"}),a.jsxs(su,{direction:"horizontal",children:[a.jsx(ro,{defaultSize:35,className:"p-5",children:a.jsx("div",{className:"table",children:n?a.jsx(Lo,{}):a.jsx(a.Fragment,{children:o&&o.length>0&&Array.isArray(o)?o.map(u=>a.jsx("div",{className:`table-item ${u.id===t?"selected":""}`,onClick:()=>l(`${u.id}`),children:u.description?a.jsxs(a.Fragment,{children:[a.jsx("h3",{className:"table-item-title",children:u.description}),a.jsxs("p",{className:"table-item-description",children:[u.url," - ",u.typebot]})]}):a.jsxs(a.Fragment,{children:[a.jsx("h3",{className:"table-item-title",children:u.url}),a.jsx("p",{className:"table-item-description",children:u.typebot})]})})):a.jsx("p",{children:"Nenhum typebot encontrado."})})})}),a.jsx(au,{withHandle:!0,className:"border border-black"}),a.jsx(ro,{className:"",children:t&&a.jsx(uK,{typebotId:t,instance:e,resetTable:c})})]})]})}const qo=new zr,oR=async(e,t)=>(await qo.getInstance().get(`/dify/find/${e}`,{headers:{apikey:t}})).data,pK=async(e,t,n)=>(await qo.getInstance().get(`/dify/fetch/${n}/${e}`,{headers:{apikey:t}})).data,hK=async(e,t,n)=>(await qo.getInstance().post(`/dify/create/${e}`,n,{headers:{apikey:t}})).data,gK=async(e,t,n,r)=>(await qo.getInstance().put(`/dify/update/${n}/${e}`,r,{headers:{apikey:t}})).data,mK=async(e,t,n)=>(await qo.getInstance().delete(`/dify/delete/${n}/${e}`,{headers:{apikey:t}})).data,vK=async(e,t)=>(await qo.getInstance().get(`/dify/fetchSettings/${e}`,{headers:{apikey:t}})).data,yK=async(e,t,n)=>(await qo.getInstance().post(`/dify/settings/${e}`,n,{headers:{apikey:t}})).data,xK=async(e,t,n)=>(await qo.getInstance().get(`/dify/fetchSessions/${n}/${e}`,{headers:{apikey:t}})).data,wK=async(e,t,n,r)=>(await qo.getInstance().post(`/dify/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data,hS=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const o=await xK(e.name,r,t);n(o)}else console.error("Token ou nome da instância não encontrados.")}catch(r){console.error("Erro ao carregar sessões:",r)}};function bK({difyId:e}){var f,p;const{instance:t}=Tt(),[n,r]=y.useState([]),[o,s]=y.useState([]);y.useEffect(()=>{hS(t,e,s)},[t,e]);function i(){hS(t,e,s)}const l=async(d,h)=>{var m,g,w;try{if(!t)return;await wK(t.name,t.token,d,h),ke.success("Status alterado com sucesso."),i()}catch(x){console.error("Erro ao atualizar:",x),ke.error(`Erro ao atualizar : ${(w=(g=(m=x==null?void 0:x.response)==null?void 0:m.data)==null?void 0:g.response)==null?void 0:w.message}`)}},c=[{accessorKey:"remoteJid",header:()=>a.jsx("div",{className:"text-center",children:"Remote Jid"}),cell:({row:d})=>a.jsx("div",{children:d.getValue("remoteJid")})},{accessorKey:"sessionId",header:()=>a.jsx("div",{className:"text-center",children:"Session ID"}),cell:({row:d})=>a.jsx("div",{children:d.getValue("sessionId")})},{accessorKey:"status",header:()=>a.jsx("div",{className:"text-center",children:"Status"}),cell:({row:d})=>a.jsx("div",{children:d.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:d})=>{const h=d.original;return a.jsxs(Np,{children:[a.jsx(kp,{asChild:!0,children:a.jsxs(Te,{variant:"ghost",className:"h-8 w-8 p-0",children:[a.jsx("span",{className:"sr-only",children:"Open menu"}),a.jsx(ep,{className:"h-4 w-4"})]})}),a.jsxs(qi,{align:"end",children:[a.jsx(pu,{children:"Actions"}),a.jsx(Zi,{}),h.status!=="opened"&&a.jsxs(xn,{onClick:()=>l(h.remoteJid,"opened"),children:[a.jsx(ny,{className:"w-4 h-4 mr-2"}),"Abrir"]}),h.status!=="paused"&&h.status!=="closed"&&a.jsxs(xn,{onClick:()=>l(h.remoteJid,"paused"),children:[a.jsx(ty,{className:"w-4 h-4 mr-2"}),"Pausar"]}),h.status!=="closed"&&a.jsxs(xn,{onClick:()=>l(h.remoteJid,"closed"),children:[a.jsx(Yv,{className:"w-4 h-4 mr-2"}),"Fechar"]}),a.jsxs(xn,{onClick:()=>l(h.remoteJid,"delete"),children:[a.jsx(Xv,{className:"w-4 h-4 mr-2"}),"Excluir"]})]})]})}}],u=Mp({data:o,columns:c,onSortingChange:r,getCoreRowModel:Pp(),getPaginationRowModel:Dp(),getSortedRowModel:Op(),getFilteredRowModel:Ip(),state:{sorting:n}});return a.jsxs(Sn,{children:[a.jsx(Cn,{asChild:!0,children:a.jsxs(Te,{variant:"default",className:"mr-5 text-white",children:[a.jsx(Qv,{})," Sessões"]})}),a.jsxs(un,{className:"sm:max-w-[950px] overflow-y-auto",onCloseAutoFocus:i,children:[a.jsx(dn,{children:a.jsx(On,{children:"Sessões"})}),a.jsxs("div",{children:[a.jsx(Y,{placeholder:"Search by remoteJid...",value:((f=u.getColumn("remoteJid"))==null?void 0:f.getFilterValue())??"",onChange:d=>{var h;return(h=u.getColumn("remoteJid"))==null?void 0:h.setFilterValue(d.target.value)},className:"max-w-sm border border-gray-300 rounded-md"}),a.jsxs(hu,{children:[a.jsx(gu,{children:u.getHeaderGroups().map(d=>a.jsx(nr,{children:d.headers.map(h=>a.jsx(vu,{children:h.isPlaceholder?null:Ds(h.column.columnDef.header,h.getContext())},h.id))},d.id))}),a.jsx(mu,{children:(p=u.getRowModel().rows)!=null&&p.length?u.getRowModel().rows.map(d=>a.jsx(nr,{"data-state":d.getIsSelected()&&"selected",children:d.getVisibleCells().map(h=>a.jsx($o,{children:Ds(h.column.columnDef.cell,h.getContext())},h.id))},d.id)):a.jsx(nr,{children:a.jsx($o,{colSpan:c.length,className:"h-24 text-center",children:"No results."})})})]})]})]})]})}const SK=T.object({enabled:T.boolean(),description:T.string(),botType:T.string(),apiUrl:T.string(),apiKey:T.string(),triggerType:T.string(),triggerOperator:T.string().optional(),triggerValue:T.string().optional(),expire:T.string(),keywordFinish:T.string(),delayMessage:T.string(),unknownMessage:T.string(),listeningFromMe:T.boolean(),stopBotFromMe:T.boolean(),keepOpen:T.boolean(),debounceTime:T.string()});function CK({difyId:e,instance:t,resetTable:n}){const[,r]=y.useState(""),[o,s]=y.useState(!0),[i,l]=y.useState(!1),c=ir(),u=tn({resolver:nn(SK),defaultValues:{enabled:!0,description:"",botType:"chatBot",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:"0",keywordFinish:"",delayMessage:"0",unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0"}});y.useEffect(()=>{(async()=>{try{const h=localStorage.getItem("token");if(h&&t&&t.name&&e){r(h);const m=await pK(t.name,h,e);u.reset({enabled:m.enabled,description:m.description,botType:m.botType,apiUrl:m.apiUrl,apiKey:m.apiKey,triggerType:m.triggerType,triggerOperator:m.triggerOperator,triggerValue:m.triggerValue,expire:m.expire.toString(),keywordFinish:m.keywordFinish,delayMessage:m.delayMessage.toString(),unknownMessage:m.unknownMessage,listeningFromMe:m.listeningFromMe,stopBotFromMe:m.stopBotFromMe,keepOpen:m.keepOpen,debounceTime:m.debounceTime.toString()})}else console.error("Token ou nome da instância não encontrados.");s(!1)}catch(h){console.error("Erro ao carregar configurações:",h),s(!1)}})()},[u,t,e]);const f=async()=>{var d,h,m;try{const g=u.getValues(),w=localStorage.getItem("token");if(w&&t&&t.name&&e){const x={enabled:g.enabled,description:g.description,botType:g.botType,apiUrl:g.apiUrl,apiKey:g.apiKey,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:parseInt(g.expire,10),keywordFinish:g.keywordFinish,delayMessage:parseInt(g.delayMessage,10),unknownMessage:g.unknownMessage,listeningFromMe:g.listeningFromMe,stopBotFromMe:g.stopBotFromMe,keepOpen:g.keepOpen,debounceTime:parseInt(g.debounceTime,10)};await gK(t.name,w,e,x),ke.success("Dify atualizado com sucesso.")}else console.error("Token ou nome da instância não encontrados.")}catch(g){console.error("Erro ao atualizar bot:",g),ke.error(`Erro ao atualizar : ${(m=(h=(d=g==null?void 0:g.response)==null?void 0:d.data)==null?void 0:h.response)==null?void 0:m.message}`)}},p=async()=>{try{const d=localStorage.getItem("token");d&&t&&t.name&&e?(await mK(t.name,d,e),ke.success("Dify excluído com sucesso."),l(!1),n(),c(`/manager/instance/${t.id}/dify`)):console.error("Token ou nome da instância não encontrados.")}catch(d){console.error("Erro ao excluir dify:",d)}};return a.jsxs("div",{className:"form",children:[o&&a.jsx(Lo,{}),!o&&a.jsx(uo,{...u,children:a.jsxs("form",{onSubmit:u.handleSubmit(f),className:"w-full space-y-6",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Dify"}),a.jsxs("div",{className:"space-y-4",children:[a.jsx(R,{control:u.control,name:"enabled",render:({field:d})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:d.value,onCheckedChange:d.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Ativo"})})]})}),a.jsx(R,{control:u.control,name:"description",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Descrição"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Descrição"})]})}),a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Dify Settings"}),a.jsx(Dt,{className:"border border-gray-700"}),a.jsx(R,{control:u.control,name:"botType",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Tipo de Bot"}),a.jsxs(St,{onValueChange:d.onChange,defaultValue:d.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione uma tipo de bot"})})}),a.jsxs(vt,{className:"border border-gray-600",children:[a.jsx(me,{value:"chatBot",children:"Chat Bot"}),a.jsx(me,{value:"textGenerator",children:"Gerador de texto"}),a.jsx(me,{value:"agent",children:"Agente"}),a.jsx(me,{value:"workflow",children:"Workflow"})]})]})]})}),a.jsx(R,{control:u.control,name:"apiUrl",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"URL da API"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"URL da API"})]})}),a.jsx(R,{control:u.control,name:"apiKey",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Chave da API"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Chave da API",type:"password"})]})}),a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Trigger Settings"}),a.jsx(Dt,{className:"border border-gray-700"}),a.jsx(R,{control:u.control,name:"triggerType",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Tipo de gatilho"}),a.jsxs(St,{onValueChange:d.onChange,defaultValue:d.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione um tipo"})})}),a.jsxs(vt,{className:"border border-gray-600",children:[a.jsx(me,{value:"keyword",children:"Palavra Chave"}),a.jsx(me,{value:"all",children:"Todos"}),a.jsx(me,{value:"none",children:"Nenhum"})]})]})]})}),u.watch("triggerType")==="keyword"&&a.jsxs(a.Fragment,{children:[a.jsx(R,{control:u.control,name:"triggerOperator",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Operador do gatilho"}),a.jsxs(St,{onValueChange:d.onChange,defaultValue:d.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione um operador"})})}),a.jsxs(vt,{className:"border border-gray-600",children:[a.jsx(me,{value:"contains",children:"Contém"}),a.jsx(me,{value:"equals",children:"Igual à"}),a.jsx(me,{value:"startsWith",children:"Começa com"}),a.jsx(me,{value:"endsWith",children:"Termina com"}),a.jsx(me,{value:"regex",children:"Regex"})]})]})]})}),a.jsx(R,{control:u.control,name:"triggerValue",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Gatilho"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Gatilho"})]})})]}),a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Options Settings"}),a.jsx(Dt,{className:"border border-gray-700"}),a.jsx(R,{control:u.control,name:"expire",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Expira em (minitos)"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Expira em (minitos)",type:"number"})]})}),a.jsx(R,{control:u.control,name:"keywordFinish",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Palavra Chave de Finalização"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Palavra Chave de Finalização"})]})}),a.jsx(R,{control:u.control,name:"delayMessage",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Delay padrão da mensagem"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Delay padrão da mensagem",type:"number"})]})}),a.jsx(R,{control:u.control,name:"unknownMessage",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Mensagem para tipo de mensagem desconhecida"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Mensagem para tipo de mensagem desconhecida"})]})}),a.jsx(R,{control:u.control,name:"listeningFromMe",render:({field:d})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:d.value,onCheckedChange:d.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Escuta mensagens enviadas por mim"})})]})}),a.jsx(R,{control:u.control,name:"stopBotFromMe",render:({field:d})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:d.value,onCheckedChange:d.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Pausa o bot quando eu enviar uma mensagem"})})]})}),a.jsx(R,{control:u.control,name:"keepOpen",render:({field:d})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:d.value,onCheckedChange:d.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Mantem a sessão do bot aberta"})})]})}),a.jsx(R,{control:u.control,name:"debounceTime",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Tempo de espera"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Tempo de espera",type:"number"})]})})]})]}),a.jsx("div",{children:a.jsx(bK,{difyId:e})}),a.jsx(Te,{className:"bg-blue-400 hover:bg-blue-600 text-white",onClick:f,children:"Atualizar"}),a.jsxs(Sn,{open:i,onOpenChange:l,children:[a.jsx(Cn,{asChild:!0,children:a.jsx(Te,{variant:"secondary",className:"ml-2 bg-red-400 hover:bg-red-600",children:"Excluir"})}),a.jsx(un,{children:a.jsxs(dn,{children:[a.jsx(On,{children:"Tem certeza que deseja excluir?"}),a.jsx(Pi,{children:"Esta ação não pode ser desfeita."}),a.jsxs(br,{children:[a.jsx(Te,{variant:"default",className:"bg-red-400 hover:bg-red-600 text-white",onClick:p,children:"Exluir"}),a.jsx(Te,{variant:"outline",onClick:()=>l(!1),children:"Cancelar"})]})]})})]})]})})]})}const jK=T.object({enabled:T.boolean(),description:T.string(),botType:T.string(),apiUrl:T.string(),apiKey:T.string(),triggerType:T.string(),triggerOperator:T.string().optional(),triggerValue:T.string().optional(),expire:T.string(),keywordFinish:T.string(),delayMessage:T.string(),unknownMessage:T.string(),listeningFromMe:T.boolean(),stopBotFromMe:T.boolean(),keepOpen:T.boolean(),debounceTime:T.string()});function _K({resetTable:e}){const{instance:t}=Tt(),[n,r]=y.useState(!1),[o,s]=y.useState(!1),i=tn({resolver:nn(jK),defaultValues:{enabled:!0,description:"",botType:"chatBot",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:"0",keywordFinish:"",delayMessage:"0",unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0"}}),l=async u=>{var f,p,d;try{if(!t||!t.name)throw new Error("Nome da instância não encontrado.");r(!0);const h={enabled:u.enabled,description:u.description,botType:u.botType,apiUrl:u.apiUrl,apiKey:u.apiKey,triggerType:u.triggerType,triggerOperator:u.triggerOperator||"",triggerValue:u.triggerValue||"",expire:parseInt(u.expire,10),keywordFinish:u.keywordFinish,delayMessage:parseInt(u.delayMessage,10),unknownMessage:u.unknownMessage,listeningFromMe:u.listeningFromMe,stopBotFromMe:u.stopBotFromMe,keepOpen:u.keepOpen,debounceTime:parseInt(u.debounceTime,10)};await hK(t.name,t.token,h),ke.success("Dify criado com sucesso!"),s(!1),c(),e()}catch(h){console.error("Erro ao criar bot:",h),ke.error(`Erro ao criar : ${(d=(p=(f=h==null?void 0:h.response)==null?void 0:f.data)==null?void 0:p.response)==null?void 0:d.message}`)}finally{r(!1)}};function c(){i.reset()}return a.jsxs(Sn,{open:o,onOpenChange:s,children:[a.jsx(Cn,{asChild:!0,children:a.jsxs(Te,{variant:"default",className:"mr-5",children:[a.jsx(ou,{})," Dify"]})}),a.jsxs(un,{className:"sm:max-w-[740px] sm:max-h-[600px] overflow-y-auto",onCloseAutoFocus:c,children:[a.jsx(dn,{children:a.jsx(On,{children:"Novo Dify"})}),a.jsx(Bo,{...i,children:a.jsxs("form",{onSubmit:i.handleSubmit(l),className:"w-full space-y-6",children:[a.jsx("div",{children:a.jsxs("div",{className:"space-y-4",children:[a.jsx(R,{control:i.control,name:"enabled",render:({field:u})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:u.value,onCheckedChange:u.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Ativo"})})]})}),a.jsx(R,{control:i.control,name:"description",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Descrição"}),a.jsx(Y,{...u,className:"border border-gray-600 w-full",placeholder:"Descrição"})]})}),a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Dify Settings"}),a.jsx(Dt,{className:"border border-gray-700"}),a.jsx(R,{control:i.control,name:"botType",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Tipo de Bot"}),a.jsxs(St,{onValueChange:u.onChange,defaultValue:u.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione uma tipo de bot"})})}),a.jsxs(vt,{className:"border border-gray-600",children:[a.jsx(me,{value:"chatBot",children:"Chat Bot"}),a.jsx(me,{value:"textGenerator",children:"Gerador de texto"}),a.jsx(me,{value:"agent",children:"Agente"}),a.jsx(me,{value:"workflow",children:"Workflow"})]})]})]})}),a.jsx(R,{control:i.control,name:"apiUrl",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"URL da API"}),a.jsx(Y,{...u,className:"border border-gray-600 w-full",placeholder:"URL da API"})]})}),a.jsx(R,{control:i.control,name:"apiKey",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Chave da API"}),a.jsx(Y,{...u,className:"border border-gray-600 w-full",placeholder:"Chave da API",type:"password"})]})}),a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Trigger Settings"}),a.jsx(Dt,{className:"border border-gray-700"}),a.jsx(R,{control:i.control,name:"triggerType",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Tipo de gatilho"}),a.jsxs(St,{onValueChange:u.onChange,defaultValue:u.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione um tipo"})})}),a.jsxs(vt,{className:"border border-gray-600",children:[a.jsx(me,{value:"keyword",children:"Palavra Chave"}),a.jsx(me,{value:"all",children:"Todos"}),a.jsx(me,{value:"none",children:"Nenhum"})]})]})]})}),i.watch("triggerType")==="keyword"&&a.jsxs(a.Fragment,{children:[a.jsx(R,{control:i.control,name:"triggerOperator",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Operador do gatilho"}),a.jsxs(St,{onValueChange:u.onChange,defaultValue:u.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione um operador"})})}),a.jsxs(vt,{className:"border border-gray-600",children:[a.jsx(me,{value:"contains",children:"Contém"}),a.jsx(me,{value:"equals",children:"Igual à"}),a.jsx(me,{value:"startsWith",children:"Começa com"}),a.jsx(me,{value:"endsWith",children:"Termina com"}),a.jsx(me,{value:"regex",children:"Regex"})]})]})]})}),a.jsx(R,{control:i.control,name:"triggerValue",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Gatilho"}),a.jsx(Y,{...u,className:"border border-gray-600 w-full",placeholder:"Gatilho"})]})})]}),a.jsx("h3",{className:"mb-4 text-lg font-medium",children:"Options Settings"}),a.jsx(Dt,{className:"border border-gray-700"}),a.jsx(R,{control:i.control,name:"expire",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Expira em (minitos)"}),a.jsx(Y,{...u,className:"border border-gray-600 w-full",placeholder:"Expira em (minitos)",type:"number"})]})}),a.jsx(R,{control:i.control,name:"keywordFinish",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Palavra Chave de Finalização"}),a.jsx(Y,{...u,className:"border border-gray-600 w-full",placeholder:"Palavra Chave de Finalização"})]})}),a.jsx(R,{control:i.control,name:"delayMessage",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Delay padrão da mensagem"}),a.jsx(Y,{...u,className:"border border-gray-600 w-full",placeholder:"Delay padrão da mensagem",type:"number"})]})}),a.jsx(R,{control:i.control,name:"unknownMessage",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Mensagem para tipo de mensagem desconhecida"}),a.jsx(Y,{...u,className:"border border-gray-600 w-full",placeholder:"Mensagem para tipo de mensagem desconhecida"})]})}),a.jsx(R,{control:i.control,name:"listeningFromMe",render:({field:u})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:u.value,onCheckedChange:u.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Escuta mensagens enviadas por mim"})})]})}),a.jsx(R,{control:i.control,name:"stopBotFromMe",render:({field:u})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:u.value,onCheckedChange:u.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Pausa o bot quando eu enviar uma mensagem"})})]})}),a.jsx(R,{control:i.control,name:"keepOpen",render:({field:u})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:u.value,onCheckedChange:u.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Mantem a sessão do bot aberta"})})]})}),a.jsx(R,{control:i.control,name:"debounceTime",render:({field:u})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Tempo de espera"}),a.jsx(Y,{...u,className:"border border-gray-600 w-full",placeholder:"Tempo de espera",type:"number"})]})})]})}),a.jsx(br,{children:a.jsx(Te,{disabled:n,variant:"default",type:"submit",children:"Salvar"})})]})})]})]})}const EK=T.object({expire:T.string(),keywordFinish:T.string(),delayMessage:T.string(),unknownMessage:T.string(),listeningFromMe:T.boolean(),stopBotFromMe:T.boolean(),keepOpen:T.boolean(),debounceTime:T.string(),ignoreJids:T.array(T.string()),difyIdFallback:T.string().optional()}),gS=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const o=await vK(e.name,r);t(o);const s=await oR(e.name,r);n(s)}else console.error("Token ou nome da instância não encontrados.")}catch(r){console.error("Erro ao carregar configurações:",r)}};function TK(){const{instance:e}=Tt(),[t,n]=y.useState([]),[r,o]=y.useState(),[s,i]=y.useState([]),l=d=>{n(t.filter((h,m)=>m!==d))},c=d=>{n([...t,d])},u=tn({resolver:nn(EK),defaultValues:{expire:"0",keywordFinish:"#SAIR",delayMessage:"1000",unknownMessage:"Mensagem não reconhecida",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],difyIdFallback:void 0}});y.useEffect(()=>{gS(e,o,i)},[e]),y.useEffect(()=>{var d;r&&(u.reset({expire:r!=null&&r.expire?r.expire.toString():"0",keywordFinish:r.keywordFinish,delayMessage:r.delayMessage?r.delayMessage.toString():"0",unknownMessage:r.unknownMessage,listeningFromMe:r.listeningFromMe,stopBotFromMe:r.stopBotFromMe,keepOpen:r.keepOpen,debounceTime:r.debounceTime?r.debounceTime.toString():"0",ignoreJids:r.ignoreJids,difyIdFallback:r.difyIdFallback}),n(((d=r.ignoreJids)==null?void 0:d.map(h=>({id:h,text:h,className:""})))||[]))},[r]);const f=async()=>{var d,h,m;try{const g=u.getValues();if(!e||!e.name)throw new Error("Nome da instância não encontrado.");const w={expire:parseInt(g.expire),keywordFinish:g.keywordFinish,delayMessage:parseInt(g.delayMessage),unknownMessage:g.unknownMessage,listeningFromMe:g.listeningFromMe,stopBotFromMe:g.stopBotFromMe,keepOpen:g.keepOpen,debounceTime:parseInt(g.debounceTime),difyIdFallback:g.difyIdFallback||void 0,ignoreJids:t.map(x=>x.text)};await yK(e.name,e.token,w),ke.success("Configuração salva com sucesso!")}catch(g){console.error("Erro ao criar bot:",g),ke.error(`Erro ao criar : ${(m=(h=(d=g==null?void 0:g.response)==null?void 0:d.data)==null?void 0:h.response)==null?void 0:m.message}`)}};function p(){gS(e,o,i)}return a.jsxs(Sn,{children:[a.jsx(Cn,{asChild:!0,children:a.jsxs(Te,{variant:"default",className:"mr-5",children:[a.jsx(ru,{})," Configurações Padrão"]})}),a.jsxs(un,{className:"sm:max-w-[740px] sm:max-h-[600px] overflow-y-auto",onCloseAutoFocus:p,children:[a.jsx(dn,{children:a.jsx(On,{children:"Configurações Padrão"})}),a.jsx(Bo,{...u,children:a.jsxs("form",{className:"w-full space-y-6",children:[a.jsx("div",{children:a.jsxs("div",{className:"space-y-4",children:[a.jsx(R,{control:u.control,name:"difyIdFallback",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Bot Fallback"}),a.jsxs(St,{onValueChange:d.onChange,defaultValue:d.value,children:[a.jsx(ae,{className:"border border-gray-600",children:a.jsx(mt,{children:a.jsx(Ct,{placeholder:"Selecione um bot"})})}),a.jsx(vt,{className:"border border-gray-600",children:s&&s.length>0&&Array.isArray(s)&&s.map(h=>a.jsx(me,{value:`${h.id}`,children:h.id},h.id))})]})]})}),a.jsx(R,{control:u.control,name:"expire",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Expira em (minitos)"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Expira em (minitos)",type:"number"})]})}),a.jsx(R,{control:u.control,name:"keywordFinish",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Palavra Chave de Finalização"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Palavra Chave de Finalização"})]})}),a.jsx(R,{control:u.control,name:"delayMessage",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Delay padrão da mensagem"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Delay padrão da mensagem",type:"number"})]})}),a.jsx(R,{control:u.control,name:"unknownMessage",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Mensagem para tipo de mensagem desconhecida"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Mensagem para tipo de mensagem desconhecida"})]})}),a.jsx(R,{control:u.control,name:"listeningFromMe",render:({field:d})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:d.value,onCheckedChange:d.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Escuta mensagens enviadas por mim"})})]})}),a.jsx(R,{control:u.control,name:"stopBotFromMe",render:({field:d})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:d.value,onCheckedChange:d.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Pausa o bot quando eu enviar uma mensagem"})})]})}),a.jsx(R,{control:u.control,name:"keepOpen",render:({field:d})=>a.jsxs(D,{className:"flex flex-row items-center justify-start py-4",children:[a.jsx(ae,{children:a.jsx(Ce,{checked:d.value,onCheckedChange:d.onChange})}),a.jsx("div",{className:"ml-4 space-y-0.5",children:a.jsx(O,{className:"text-sm",children:"Mantem a sessão do bot aberta"})})]})}),a.jsx(R,{control:u.control,name:"debounceTime",render:({field:d})=>a.jsxs(D,{className:"pb-4",children:[a.jsx(O,{children:"Tempo de espera"}),a.jsx(Y,{...d,className:"border border-gray-600 w-full",placeholder:"Tempo de espera",type:"number"})]})}),a.jsx(R,{control:u.control,name:"ignoreJids",render:({field:d})=>a.jsxs("div",{className:"pb-4",children:[a.jsx("label",{className:"block text-sm font-medium",children:"Ignorar JIDs"}),a.jsx(sx,{tags:t,handleDelete:l,handleAddition:c,inputFieldPosition:"bottom",placeholder:"Adicionar JIDs ex: 1234567890@s.whatsapp.net",autoFocus:!1,classNames:{tags:"tagsClass",tagInput:"tagInputClass",tagInputField:"tagInputFieldClass",selected:"selectedClass",tag:"tagClass",remove:"removeClass",suggestions:"suggestionsClass",activeSuggestion:"activeSuggestionClass",editTagInput:"editTagInputClass",editTagInputField:"editTagInputFieldClass",clearAll:"clearAllClass"}}),a.jsx("input",{type:"hidden",...d,value:t.map(h=>h.text).join(",")})]})})]})}),a.jsx(br,{children:a.jsx(Te,{variant:"default",type:"button",onClick:f,children:"Salvar"})})]})})]})]})}const mS=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const o=await oR(e.name,r);t(o)}else console.error("Token ou nome da instância não encontrados.");n(!1)}catch(r){console.error("Erro ao carregar configurações:",r),n(!1)}};function vS(){const{instance:e}=Tt(),{difyId:t}=Ta(),[n,r]=y.useState(!0),[o,s]=y.useState([]),i=ir();y.useEffect(()=>{mS(e,s,r)},[e]);const l=u=>{e&&i(`/manager/instance/${e.id}/dify/${u}`)},c=()=>{mS(e,s,r)};return a.jsxs("main",{className:"main-table pt-5",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h3",{className:"ml-5 mb-1 text-lg font-medium",children:"Dify Bots"}),a.jsxs("div",{children:[a.jsx(TK,{}),a.jsx(_K,{resetTable:c})]})]}),a.jsx(Dt,{className:"mt-4 border border-black"}),a.jsxs(su,{direction:"horizontal",children:[a.jsx(ro,{defaultSize:35,className:"p-5",children:a.jsx("div",{className:"table",children:n?a.jsx(Lo,{}):a.jsx(a.Fragment,{children:o&&o.length>0&&Array.isArray(o)?o.map(u=>a.jsxs("div",{className:`table-item ${u.id===t?"selected":""}`,onClick:()=>l(`${u.id}`),children:[a.jsx("h3",{className:"table-item-title",children:u.description||u.id}),a.jsx("p",{className:"table-item-description",children:u.botType})]})):a.jsx("p",{children:"Nenhum bot encontrado."})})})}),a.jsx(au,{withHandle:!0,className:"border border-black"}),a.jsx(ro,{className:"",children:t&&a.jsx(CK,{difyId:t,instance:e,resetTable:c})})]})]})}const sR=new zr,NK=async(e,t)=>(await sR.getInstance().get(`/webhook/find/${e}`,{headers:{apikey:t}})).data,kK=async(e,t,n)=>(await sR.getInstance().post(`/webhook/set/${e}`,n,{headers:{apikey:t}})).data,RK=T.object({enabled:T.boolean(),url:T.string().url("Invalid URL format"),events:T.array(T.string()),webhookBase64:T.boolean(),webhookByEvents:T.boolean()});function PK(){const{instance:e}=Tt(),[t,n]=y.useState(!1),r=tn({resolver:nn(RK),defaultValues:{enabled:!1,url:"",events:[],webhookBase64:!1,webhookByEvents:!1}});y.useEffect(()=>{(async()=>{if(e){n(!0);try{const l=await NK(e.name,e.token);r.reset(l)}catch(l){console.error("Erro ao buscar dados do webhook:",l)}finally{n(!1)}}})()},[e,r]);const o=async()=>{var l,c,u;if(!e)return;const i=r.getValues();n(!0);try{const f={enabled:i.enabled,url:i.url,events:i.events,webhookBase64:i.webhookBase64,webhookByEvents:i.webhookByEvents};await kK(e.name,e.token,f),ke.success("Webhook criado com sucesso")}catch(f){console.error("Erro ao criar webhook:",f),ke.error(`Erro ao criar : ${(u=(c=(l=f==null?void 0:f.response)==null?void 0:l.data)==null?void 0:c.response)==null?void 0:u.message}`)}finally{n(!1)}},s=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"];return a.jsx("main",{className:"main-content",children:a.jsx(uo,{...r,children:a.jsxs("form",{className:"w-full space-y-6",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"mb-1 text-lg font-medium",children:"Webhook"}),a.jsx(Go,{className:"my-4 border-t border-gray-600"}),a.jsxs("div",{className:"space-y-4",children:[a.jsx(R,{control:r.control,name:"enabled",render:({field:i})=>a.jsxs(D,{className:"flex flex-row items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Ativo"}),a.jsx(zt,{children:"Ativa ou desativa o webhook"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:i.value,onCheckedChange:i.onChange})})]})}),a.jsx(R,{control:r.control,name:"url",render:({field:i})=>a.jsx(Y,{...i,className:"border border-gray-600 w-full",placeholder:"URL"})}),a.jsx(R,{control:r.control,name:"webhookByEvents",render:({field:i})=>a.jsxs(D,{className:"flex flex-row items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Webhook por Eventos"}),a.jsx(zt,{children:"Cria uma rota para cada evento adicionando o nome do evento no final da URL"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:i.value,onCheckedChange:i.onChange})})]})}),a.jsx(R,{control:r.control,name:"webhookBase64",render:({field:i})=>a.jsxs(D,{className:"flex flex-row items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Base64 no Webhook"}),a.jsx(zt,{children:"Envie os dados do base64 das mídias no webhook"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:i.value,onCheckedChange:i.onChange})})]})}),a.jsx(R,{control:r.control,name:"events",render:({field:i})=>a.jsxs(D,{className:"flex flex-col",children:[a.jsx(O,{children:"Eventos"}),a.jsx(ae,{children:a.jsx(a.Fragment,{children:s.map(l=>a.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsx("span",{children:l}),a.jsx(Ce,{checked:i.value.includes(l),onCheckedChange:c=>{c?i.onChange([...i.value,l]):i.onChange(i.value.filter(u=>u!==l))}})]},l))})})]})})]})]}),a.jsx(Te,{disabled:t,onClick:o,children:t?"Salvando...":"Salvar"})]})})})}const aR=new zr,IK=async(e,t)=>(await aR.getInstance().get(`/websocket/find/${e}`,{headers:{apikey:t}})).data,DK=async(e,t,n)=>(await aR.getInstance().post(`/websocket/set/${e}`,n,{headers:{apikey:t}})).data,OK=T.object({enabled:T.boolean(),events:T.array(T.string())});function MK(){const{instance:e}=Tt(),[t,n]=y.useState(!1),r=tn({resolver:nn(OK),defaultValues:{enabled:!1,events:[]}});y.useEffect(()=>{(async()=>{if(e){n(!0);try{const l=await IK(e.name,e.token);r.reset(l)}catch(l){console.error("Erro ao buscar dados do websocket:",l)}finally{n(!1)}}})()},[e,r]);const o=async()=>{var l,c,u;if(!e)return;const i=r.getValues();n(!0);try{const f={enabled:i.enabled,events:i.events};await DK(e.name,e.token,f),ke.success("Websocket criado com sucesso")}catch(f){console.error("Erro ao criar websocket:",f),ke.error(`Erro ao criar : ${(u=(c=(l=f==null?void 0:f.response)==null?void 0:l.data)==null?void 0:c.response)==null?void 0:u.message}`)}finally{n(!1)}},s=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"];return a.jsx("main",{className:"main-content",children:a.jsx(uo,{...r,children:a.jsxs("form",{className:"w-full space-y-6",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"mb-1 text-lg font-medium",children:"Websocket"}),a.jsx(Go,{className:"my-4 border-t border-gray-600"}),a.jsxs("div",{className:"space-y-4",children:[a.jsx(R,{control:r.control,name:"enabled",render:({field:i})=>a.jsxs(D,{className:"flex flex-row items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsxs("div",{className:"space-y-0.5",children:[a.jsx(O,{className:"text-sm",children:"Ativo"}),a.jsx(zt,{children:"Ativa ou desativa o websocket"})]}),a.jsx(ae,{children:a.jsx(Ce,{checked:i.value,onCheckedChange:i.onChange})})]})}),a.jsx(R,{control:r.control,name:"events",render:({field:i})=>a.jsxs(D,{className:"flex flex-col",children:[a.jsx(O,{children:"Eventos"}),a.jsx(ae,{children:a.jsx(a.Fragment,{children:s.map(l=>a.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-gray-600 p-4",children:[a.jsx("span",{children:l}),a.jsx(Ce,{checked:i.value.includes(l),onCheckedChange:c=>{c?i.onChange([...i.value,l]):i.onChange(i.value.filter(u=>u!==l))}})]},l))})})]})})]})]}),a.jsx(Te,{disabled:t,onClick:o,children:t?"Salvando...":"Salvar"})]})})})}function AK(){const e=ir(),[t,n]=y.useState(window.location.protocol+"//"+window.location.host),[r,o]=y.useState(""),s=async()=>{if(!t||!r){ke.error("Credenciais inválidas");return}const i=await HM(t);if(!i||!i.version){y_(),ke.error("Servidor inválido");return}if(!await GM(t,r)){ke.error("Credenciais inválidas");return}if(!await BM(t,r)){ke.error("Credenciais inválidas");return}localStorage.setItem("version",i.version),localStorage.setItem("clientName",i.clientName),e("/manager/")};return a.jsxs("div",{children:[a.jsx("div",{className:"pt-2",children:a.jsx("img",{className:"logo",src:"/assets/images/evolution-logo.png",alt:"logo"})}),a.jsx("div",{className:"root",children:a.jsxs(mi,{className:"w-[350px] no-border",children:[a.jsxs(ql,{children:[a.jsx(Zl,{className:"text-center",children:"Evolution Manager"}),a.jsx(d1,{className:"text-center",children:"Login to your evolution api server"})]}),a.jsx(Jl,{children:a.jsxs("div",{className:"grid w-full items-center gap-4",children:[a.jsxs("div",{className:"flex flex-col space-y-1.5",children:[a.jsx(bo,{className:"text-center",htmlFor:"serverUrl",children:"Server URL"}),a.jsx(Y,{className:"border border-gray-300",id:"serverUrl",placeholder:"Server URL",value:t,onChange:i=>n(i.target.value)})]}),a.jsxs("div",{className:"flex flex-col space-y-1.5",children:[a.jsx(bo,{className:"text-center",htmlFor:"apiKey",children:"Global ApiKey"}),a.jsx(Y,{id:"apiKey",className:"border border-gray-300",placeholder:"Global ApiKey",type:"password",value:r,onChange:i=>o(i.target.value)})]})]})}),a.jsx(f1,{className:"flex justify-center",children:a.jsx(Te,{className:"w-full",onClick:s,children:"Login"})})]})}),a.jsx(u1,{})]})}const FK=tO([{path:"/manager/login",element:a.jsx(mO,{children:a.jsx(AK,{})})},{path:"/manager/",element:a.jsx(sn,{children:a.jsx(XF,{children:a.jsx(Dz,{})})})},{path:"/manager/instance/:instanceId/dashboard",element:a.jsx(sn,{children:a.jsx(gn,{children:a.jsx(w3,{})})})},{path:"/manager/instance/:instanceId/chat",element:a.jsx(sn,{children:a.jsx(gn,{children:a.jsx(J0,{})})})},{path:"/manager/instance/:instanceId/chat/:remoteJid",element:a.jsx(sn,{children:a.jsx(gn,{children:a.jsx(J0,{})})})},{path:"/manager/instance/:instanceId/settings",element:a.jsx(sn,{children:a.jsx(gn,{children:a.jsx(KW,{})})})},{path:"/manager/instance/:instanceId/openai",element:a.jsx(sn,{children:a.jsx(gn,{children:a.jsx(cS,{})})})},{path:"/manager/instance/:instanceId/openai/:openaiBotId",element:a.jsx(sn,{children:a.jsx(gn,{children:a.jsx(cS,{})})})},{path:"/manager/instance/:instanceId/webhook",element:a.jsx(sn,{children:a.jsx(gn,{children:a.jsx(PK,{})})})},{path:"/manager/instance/:instanceId/websocket",element:a.jsx(sn,{children:a.jsx(gn,{children:a.jsx(MK,{})})})},{path:"/manager/instance/:instanceId/rabbitmq",element:a.jsx(sn,{children:a.jsx(gn,{children:a.jsx(GW,{})})})},{path:"/manager/instance/:instanceId/sqs",element:a.jsx(sn,{children:a.jsx(gn,{children:a.jsx(YW,{})})})},{path:"/manager/instance/:instanceId/chatwoot",element:a.jsx(sn,{children:a.jsx(gn,{children:a.jsx(y3,{})})})},{path:"/manager/instance/:instanceId/typebot",element:a.jsx(sn,{children:a.jsx(gn,{children:a.jsx(pS,{})})})},{path:"/manager/instance/:instanceId/typebot/:typebotId",element:a.jsx(sn,{children:a.jsx(gn,{children:a.jsx(pS,{})})})},{path:"/manager/instance/:instanceId/dify",element:a.jsx(sn,{children:a.jsx(gn,{children:a.jsx(vS,{})})})},{path:"/manager/instance/:instanceId/dify/:difyId",element:a.jsx(sn,{children:a.jsx(gn,{children:a.jsx(vS,{})})})},{path:"/manager/instance/:instanceId/proxy",element:a.jsx(sn,{children:a.jsx(gn,{children:a.jsx(VW,{})})})}]),LK={theme:"system",setTheme:()=>null},$K=y.createContext(LK);function zK({children:e,defaultTheme:t="system",storageKey:n="vite-ui-theme",...r}){const[o,s]=y.useState(()=>localStorage.getItem(n)||t);y.useEffect(()=>{const l=window.document.documentElement;if(l.classList.remove("light","dark"),o==="system"){const c=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";l.classList.add(c);return}l.classList.add(o)},[o]);const i={theme:o,setTheme:l=>{localStorage.setItem(n,l),s(l)}};return a.jsx($K.Provider,{...r,value:i,children:e})}ig.createRoot(document.getElementById("root")).render(a.jsxs(Se.StrictMode,{children:[a.jsx(zK,{defaultTheme:"dark",storageKey:"vite-ui-theme",children:a.jsx(uO,{router:FK})}),a.jsx(j4,{})]}))});export default VK(); diff --git a/manager/dist/index.html b/manager/dist/index.html index 40aa22d9..52a5ffc4 100644 --- a/manager/dist/index.html +++ b/manager/dist/index.html @@ -5,8 +5,8 @@ Evolution Manager - - + +
diff --git a/package.json b/package.json index ccb542fb..96c408a2 100644 --- a/package.json +++ b/package.json @@ -1,19 +1,20 @@ { "name": "evolution-api", - "version": "2.0.6-rc", + "version": "2.1.1", "description": "Rest api for communication with WhatsApp", - "main": "./dist/src/main.js", + "main": "./dist/main.js", + "type": "commonjs", "scripts": { - "build": "tsc", - "start": "ts-node --files --transpile-only ./src/main.ts", - "start:prod": "node dist/src/main", - "dev:server": "clear && tsnd --files --transpile-only --respawn --ignore-watch node_modules ./src/main.ts", - "test": "clear && tsnd --files --transpile-only --respawn --ignore-watch node_modules ./test/all.test.ts", + "build": "tsc --noEmit && tsup", + "start": "tsnd -r tsconfig-paths/register --files --transpile-only ./src/main.ts", + "start:prod": "node dist/main", + "dev:server": "clear && tsnd -r tsconfig-paths/register --files --transpile-only --respawn --ignore-watch node_modules ./src/main.ts", + "test": "clear && tsnd -r tsconfig-paths/register --files --transpile-only --respawn --ignore-watch node_modules ./test/all.test.ts", "lint": "eslint --fix --ext .ts src", - "db:migrate:postgres": "npx prisma migrate dev --name init --schema ./prisma/postgresql-schema.prisma", - "db:migrate:mysql": "npx prisma migrate dev --name init --schema ./prisma/mysql-schema.prisma", - "db:studio:postgres": "npx prisma studio --schema ./prisma/postgresql-schema.prisma", - "db:studio:mysql": "npx prisma studio --schema ./prisma/mysql-schema.prisma" + "db:generate": "node runWithProvider.js \"npx prisma generate --schema ./prisma/DATABASE_PROVIDER-schema.prisma\"", + "db:deploy": "node runWithProvider.js \"rm -rf ./prisma/migrations && cp -r ./prisma/DATABASE_PROVIDER-migrations ./prisma/migrations && npx prisma migrate deploy --schema ./prisma/DATABASE_PROVIDER-schema.prisma\"", + "db:studio": "node runWithProvider.js \"npx prisma studio --schema ./prisma/DATABASE_PROVIDER-schema.prisma\"", + "db:migrate:dev": "node runWithProvider.js \"rm -rf ./prisma/migrations && cp -r ./prisma/DATABASE_PROVIDER-migrations ./prisma/migrations && npx prisma migrate dev --schema ./prisma/DATABASE_PROVIDER-schema.prisma && cp -r ./prisma/migrations/* ./prisma/DATABASE_PROVIDER-migrations\"" }, "repository": { "type": "git", @@ -37,9 +38,9 @@ ], "author": { "name": "Davidson Gomes", - "email": "contato@agenciadgcode.com" + "email": "contato@atendai.com" }, - "license": "GPL-3.0", + "license": "Apache-2.0", "bugs": { "url": "https://github.com/EvolutionAPI/evolution-api/issues" }, @@ -51,10 +52,10 @@ "@figuro/chatwoot-sdk": "^1.1.16", "@hapi/boom": "^10.0.1", "@prisma/client": "^5.15.0", - "@sentry/node": "^7.59.2", + "@sentry/node": "^8.28.0", "amqplib": "^0.10.3", "axios": "^1.6.5", - "baileys": "6.7.5", + "baileys": "6.7.7", "class-validator": "^0.14.1", "compression": "^1.7.4", "cors": "^2.8.5", @@ -62,7 +63,6 @@ "dayjs": "^1.11.7", "dotenv": "^16.4.5", "eventemitter2": "^6.4.9", - "evolution-manager-v2": "^0.0.2", "exiftool-vendored": "^22.0.0", "express": "^4.18.2", "express-async-errors": "^3.1.1", @@ -74,11 +74,13 @@ "jimp": "^0.16.13", "join": "^3.0.0", "js-yaml": "^4.1.0", + "json-schema": "^0.4.0", "jsonschema": "^1.4.1", "link-preview-js": "^3.0.4", + "long": "^5.2.3", + "mime": "^3.0.0", "minio": "^8.0.1", "node-cache": "^5.1.2", - "node-mime-types": "^1.1.0", "node-windows": "^1.0.0-beta.8", "openai": "^4.52.7", "parse-bmfont-xml": "^1.1.4", @@ -91,6 +93,7 @@ "sharp": "^0.32.2", "socket.io": "^4.7.1", "socks-proxy-agent": "^8.0.1", + "tsup": "^8.2.4", "uuid": "^9.0.0", "xml2js": "^0.6.2", "yamljs": "^0.3.0" @@ -100,7 +103,8 @@ "@types/cors": "^2.8.13", "@types/express": "^4.17.17", "@types/js-yaml": "^4.0.5", - "@types/mime-types": "^2.1.1", + "@types/json-schema": "^7.0.15", + "@types/mime": "3.0.0", "@types/node": "^18.15.11", "@types/node-windows": "^0.1.2", "@types/qrcode": "^1.5.0", @@ -115,6 +119,7 @@ "eslint-plugin-simple-import-sort": "^10.0.0", "prettier": "^2.8.8", "ts-node-dev": "^2.0.0", - "typescript": "^4.9.5" + "tsconfig-paths": "^4.2.0", + "typescript": "^5.5.4" } } diff --git a/prisma/mysql-migrations/20240809105427_init/migration.sql b/prisma/mysql-migrations/20240809105427_init/migration.sql new file mode 100644 index 00000000..096aebb0 --- /dev/null +++ b/prisma/mysql-migrations/20240809105427_init/migration.sql @@ -0,0 +1,588 @@ +-- CreateTable +CREATE TABLE `Instance` ( + `id` VARCHAR(191) NOT NULL, + `name` VARCHAR(255) NOT NULL, + `connectionStatus` ENUM('open', 'close', 'connecting') NOT NULL DEFAULT 'open', + `ownerJid` VARCHAR(100) NULL, + `profileName` VARCHAR(100) NULL, + `profilePicUrl` VARCHAR(500) NULL, + `integration` VARCHAR(100) NULL, + `number` VARCHAR(100) NULL, + `businessId` VARCHAR(100) NULL, + `token` VARCHAR(255) NULL, + `clientName` VARCHAR(100) NULL, + `disconnectionReasonCode` INTEGER NULL, + `disconnectionObject` JSON NULL, + `disconnectionAt` TIMESTAMP NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NULL, + + UNIQUE INDEX `Instance_name_key`(`name`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Session` ( + `id` VARCHAR(191) NOT NULL, + `sessionId` VARCHAR(191) NOT NULL, + `creds` TEXT NULL, + `createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + + UNIQUE INDEX `Session_sessionId_key`(`sessionId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Chat` ( + `id` VARCHAR(191) NOT NULL, + `remoteJid` VARCHAR(100) NOT NULL, + `labels` JSON NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NULL, + `instanceId` VARCHAR(191) NOT NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Contact` ( + `id` VARCHAR(191) NOT NULL, + `remoteJid` VARCHAR(100) NOT NULL, + `pushName` VARCHAR(100) NULL, + `profilePicUrl` VARCHAR(500) NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NULL, + `instanceId` VARCHAR(191) NOT NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Message` ( + `id` VARCHAR(191) NOT NULL, + `key` JSON NOT NULL, + `pushName` VARCHAR(100) NULL, + `participant` VARCHAR(100) NULL, + `messageType` VARCHAR(100) NOT NULL, + `message` JSON NOT NULL, + `contextInfo` JSON NULL, + `source` ENUM('ios', 'android', 'web', 'unknown', 'desktop') NOT NULL, + `messageTimestamp` INTEGER NOT NULL, + `chatwootMessageId` INTEGER NULL, + `chatwootInboxId` INTEGER NULL, + `chatwootConversationId` INTEGER NULL, + `chatwootContactInboxSourceId` VARCHAR(100) NULL, + `chatwootIsRead` BOOLEAN NULL DEFAULT false, + `instanceId` VARCHAR(191) NOT NULL, + `typebotSessionId` VARCHAR(191) NULL, + `openaiSessionId` VARCHAR(191) NULL, + `webhookUrl` VARCHAR(500) NULL, + `difySessionId` VARCHAR(191) NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `MessageUpdate` ( + `id` VARCHAR(191) NOT NULL, + `keyId` VARCHAR(100) NOT NULL, + `remoteJid` VARCHAR(100) NOT NULL, + `fromMe` BOOLEAN NOT NULL, + `participant` VARCHAR(100) NULL, + `pollUpdates` JSON NULL, + `status` VARCHAR(30) NOT NULL, + `messageId` VARCHAR(191) NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Webhook` ( + `id` VARCHAR(191) NOT NULL, + `url` VARCHAR(500) NOT NULL, + `enabled` BOOLEAN NULL DEFAULT true, + `events` JSON NULL, + `webhookByEvents` BOOLEAN NULL DEFAULT false, + `webhookBase64` BOOLEAN NULL DEFAULT false, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `Webhook_instanceId_key`(`instanceId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Chatwoot` ( + `id` VARCHAR(191) NOT NULL, + `enabled` BOOLEAN NULL DEFAULT true, + `accountId` VARCHAR(100) NULL, + `token` VARCHAR(100) NULL, + `url` VARCHAR(500) NULL, + `nameInbox` VARCHAR(100) NULL, + `signMsg` BOOLEAN NULL DEFAULT false, + `signDelimiter` VARCHAR(100) NULL, + `number` VARCHAR(100) NULL, + `reopenConversation` BOOLEAN NULL DEFAULT false, + `conversationPending` BOOLEAN NULL DEFAULT false, + `mergeBrazilContacts` BOOLEAN NULL DEFAULT false, + `importContacts` BOOLEAN NULL DEFAULT false, + `importMessages` BOOLEAN NULL DEFAULT false, + `daysLimitImportMessages` INTEGER NULL, + `organization` VARCHAR(100) NULL, + `logo` VARCHAR(500) NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `Chatwoot_instanceId_key`(`instanceId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Label` ( + `id` VARCHAR(191) NOT NULL, + `labelId` VARCHAR(100) NULL, + `name` VARCHAR(100) NOT NULL, + `color` VARCHAR(100) NOT NULL, + `predefinedId` VARCHAR(100) NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `Label_labelId_key`(`labelId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Proxy` ( + `id` VARCHAR(191) NOT NULL, + `enabled` BOOLEAN NOT NULL DEFAULT false, + `host` VARCHAR(100) NOT NULL, + `port` VARCHAR(100) NOT NULL, + `protocol` VARCHAR(100) NOT NULL, + `username` VARCHAR(100) NOT NULL, + `password` VARCHAR(100) NOT NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `Proxy_instanceId_key`(`instanceId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Setting` ( + `id` VARCHAR(191) NOT NULL, + `rejectCall` BOOLEAN NOT NULL DEFAULT false, + `msgCall` VARCHAR(100) NULL, + `groupsIgnore` BOOLEAN NOT NULL DEFAULT false, + `alwaysOnline` BOOLEAN NOT NULL DEFAULT false, + `readMessages` BOOLEAN NOT NULL DEFAULT false, + `readStatus` BOOLEAN NOT NULL DEFAULT false, + `syncFullHistory` BOOLEAN NOT NULL DEFAULT false, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `Setting_instanceId_key`(`instanceId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Rabbitmq` ( + `id` VARCHAR(191) NOT NULL, + `enabled` BOOLEAN NOT NULL DEFAULT false, + `events` JSON NOT NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `Rabbitmq_instanceId_key`(`instanceId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Sqs` ( + `id` VARCHAR(191) NOT NULL, + `enabled` BOOLEAN NOT NULL DEFAULT false, + `events` JSON NOT NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `Sqs_instanceId_key`(`instanceId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Websocket` ( + `id` VARCHAR(191) NOT NULL, + `enabled` BOOLEAN NOT NULL DEFAULT false, + `events` JSON NOT NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `Websocket_instanceId_key`(`instanceId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Typebot` ( + `id` VARCHAR(191) NOT NULL, + `enabled` BOOLEAN NOT NULL DEFAULT true, + `description` VARCHAR(255) NULL, + `url` VARCHAR(500) NOT NULL, + `typebot` VARCHAR(100) NOT NULL, + `expire` INTEGER NULL DEFAULT 0, + `keywordFinish` VARCHAR(100) NULL, + `delayMessage` INTEGER NULL, + `unknownMessage` VARCHAR(100) NULL, + `listeningFromMe` BOOLEAN NULL DEFAULT false, + `stopBotFromMe` BOOLEAN NULL DEFAULT false, + `keepOpen` BOOLEAN NULL DEFAULT false, + `debounceTime` INTEGER NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NULL, + `ignoreJids` JSON NULL, + `triggerType` ENUM('all', 'keyword', 'none') NULL, + `triggerOperator` ENUM('contains', 'equals', 'startsWith', 'endsWith', 'regex') NULL, + `triggerValue` VARCHAR(191) NULL, + `instanceId` VARCHAR(191) NOT NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `TypebotSession` ( + `id` VARCHAR(191) NOT NULL, + `remoteJid` VARCHAR(100) NOT NULL, + `pushName` VARCHAR(100) NULL, + `sessionId` VARCHAR(100) NOT NULL, + `status` ENUM('opened', 'closed', 'paused') NOT NULL, + `prefilledVariables` JSON NULL, + `awaitUser` BOOLEAN NOT NULL DEFAULT false, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `typebotId` VARCHAR(191) NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `TypebotSetting` ( + `id` VARCHAR(191) NOT NULL, + `expire` INTEGER NULL DEFAULT 0, + `keywordFinish` VARCHAR(100) NULL, + `delayMessage` INTEGER NULL, + `unknownMessage` VARCHAR(100) NULL, + `listeningFromMe` BOOLEAN NULL DEFAULT false, + `stopBotFromMe` BOOLEAN NULL DEFAULT false, + `keepOpen` BOOLEAN NULL DEFAULT false, + `debounceTime` INTEGER NULL, + `typebotIdFallback` VARCHAR(100) NULL, + `ignoreJids` JSON NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `TypebotSetting_instanceId_key`(`instanceId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Media` ( + `id` VARCHAR(191) NOT NULL, + `fileName` VARCHAR(500) NOT NULL, + `type` VARCHAR(100) NOT NULL, + `mimetype` VARCHAR(100) NOT NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `messageId` VARCHAR(191) NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `Media_fileName_key`(`fileName`), + UNIQUE INDEX `Media_messageId_key`(`messageId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `OpenaiCreds` ( + `id` VARCHAR(191) NOT NULL, + `name` VARCHAR(255) NULL, + `apiKey` VARCHAR(255) NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `OpenaiCreds_name_key`(`name`), + UNIQUE INDEX `OpenaiCreds_apiKey_key`(`apiKey`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `OpenaiBot` ( + `id` VARCHAR(191) NOT NULL, + `enabled` BOOLEAN NOT NULL DEFAULT true, + `description` VARCHAR(255) NULL, + `botType` ENUM('assistant', 'chatCompletion') NOT NULL, + `assistantId` VARCHAR(255) NULL, + `functionUrl` VARCHAR(500) NULL, + `model` VARCHAR(100) NULL, + `systemMessages` JSON NULL, + `assistantMessages` JSON NULL, + `userMessages` JSON NULL, + `maxTokens` INTEGER NULL, + `expire` INTEGER NULL DEFAULT 0, + `keywordFinish` VARCHAR(100) NULL, + `delayMessage` INTEGER NULL, + `unknownMessage` VARCHAR(100) NULL, + `listeningFromMe` BOOLEAN NULL DEFAULT false, + `stopBotFromMe` BOOLEAN NULL DEFAULT false, + `keepOpen` BOOLEAN NULL DEFAULT false, + `debounceTime` INTEGER NULL, + `ignoreJids` JSON NULL, + `triggerType` ENUM('all', 'keyword', 'none') NULL, + `triggerOperator` ENUM('contains', 'equals', 'startsWith', 'endsWith', 'regex') NULL, + `triggerValue` VARCHAR(191) NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `openaiCredsId` VARCHAR(191) NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `OpenaiSession` ( + `id` VARCHAR(191) NOT NULL, + `sessionId` VARCHAR(255) NOT NULL, + `remoteJid` VARCHAR(100) NOT NULL, + `status` ENUM('opened', 'closed', 'paused') NOT NULL, + `awaitUser` BOOLEAN NOT NULL DEFAULT false, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `openaiBotId` VARCHAR(191) NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `OpenaiSetting` ( + `id` VARCHAR(191) NOT NULL, + `expire` INTEGER NULL DEFAULT 0, + `keywordFinish` VARCHAR(100) NULL, + `delayMessage` INTEGER NULL, + `unknownMessage` VARCHAR(100) NULL, + `listeningFromMe` BOOLEAN NULL DEFAULT false, + `stopBotFromMe` BOOLEAN NULL DEFAULT false, + `keepOpen` BOOLEAN NULL DEFAULT false, + `debounceTime` INTEGER NULL, + `ignoreJids` JSON NULL, + `speechToText` BOOLEAN NULL DEFAULT false, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `openaiCredsId` VARCHAR(191) NOT NULL, + `openaiIdFallback` VARCHAR(100) NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `OpenaiSetting_openaiCredsId_key`(`openaiCredsId`), + UNIQUE INDEX `OpenaiSetting_instanceId_key`(`instanceId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Template` ( + `id` VARCHAR(191) NOT NULL, + `templateId` VARCHAR(255) NOT NULL, + `name` VARCHAR(255) NOT NULL, + `template` JSON NOT NULL, + `webhookUrl` VARCHAR(500) NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `Template_templateId_key`(`templateId`), + UNIQUE INDEX `Template_name_key`(`name`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Dify` ( + `id` VARCHAR(191) NOT NULL, + `enabled` BOOLEAN NOT NULL DEFAULT true, + `description` VARCHAR(255) NULL, + `botType` ENUM('chatBot', 'textGenerator', 'agent', 'workflow') NOT NULL, + `apiUrl` VARCHAR(255) NULL, + `apiKey` VARCHAR(255) NULL, + `expire` INTEGER NULL DEFAULT 0, + `keywordFinish` VARCHAR(100) NULL, + `delayMessage` INTEGER NULL, + `unknownMessage` VARCHAR(100) NULL, + `listeningFromMe` BOOLEAN NULL DEFAULT false, + `stopBotFromMe` BOOLEAN NULL DEFAULT false, + `keepOpen` BOOLEAN NULL DEFAULT false, + `debounceTime` INTEGER NULL, + `ignoreJids` JSON NULL, + `triggerType` ENUM('all', 'keyword', 'none') NULL, + `triggerOperator` ENUM('contains', 'equals', 'startsWith', 'endsWith', 'regex') NULL, + `triggerValue` VARCHAR(191) NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `DifySession` ( + `id` VARCHAR(191) NOT NULL, + `sessionId` VARCHAR(255) NOT NULL, + `remoteJid` VARCHAR(100) NOT NULL, + `status` ENUM('opened', 'closed', 'paused') NOT NULL, + `awaitUser` BOOLEAN NOT NULL DEFAULT false, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `difyId` VARCHAR(191) NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `DifySetting` ( + `id` VARCHAR(191) NOT NULL, + `expire` INTEGER NULL DEFAULT 0, + `keywordFinish` VARCHAR(100) NULL, + `delayMessage` INTEGER NULL, + `unknownMessage` VARCHAR(100) NULL, + `listeningFromMe` BOOLEAN NULL DEFAULT false, + `stopBotFromMe` BOOLEAN NULL DEFAULT false, + `keepOpen` BOOLEAN NULL DEFAULT false, + `debounceTime` INTEGER NULL, + `ignoreJids` JSON NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `difyIdFallback` VARCHAR(100) NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `DifySetting_instanceId_key`(`instanceId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- AddForeignKey +ALTER TABLE `Session` ADD CONSTRAINT `Session_sessionId_fkey` FOREIGN KEY (`sessionId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Chat` ADD CONSTRAINT `Chat_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Contact` ADD CONSTRAINT `Contact_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Message` ADD CONSTRAINT `Message_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Message` ADD CONSTRAINT `Message_typebotSessionId_fkey` FOREIGN KEY (`typebotSessionId`) REFERENCES `TypebotSession`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Message` ADD CONSTRAINT `Message_openaiSessionId_fkey` FOREIGN KEY (`openaiSessionId`) REFERENCES `OpenaiSession`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Message` ADD CONSTRAINT `Message_difySessionId_fkey` FOREIGN KEY (`difySessionId`) REFERENCES `DifySession`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `MessageUpdate` ADD CONSTRAINT `MessageUpdate_messageId_fkey` FOREIGN KEY (`messageId`) REFERENCES `Message`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `MessageUpdate` ADD CONSTRAINT `MessageUpdate_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Webhook` ADD CONSTRAINT `Webhook_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Chatwoot` ADD CONSTRAINT `Chatwoot_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Label` ADD CONSTRAINT `Label_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Proxy` ADD CONSTRAINT `Proxy_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Setting` ADD CONSTRAINT `Setting_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Rabbitmq` ADD CONSTRAINT `Rabbitmq_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Sqs` ADD CONSTRAINT `Sqs_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Websocket` ADD CONSTRAINT `Websocket_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Typebot` ADD CONSTRAINT `Typebot_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `TypebotSession` ADD CONSTRAINT `TypebotSession_typebotId_fkey` FOREIGN KEY (`typebotId`) REFERENCES `Typebot`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `TypebotSession` ADD CONSTRAINT `TypebotSession_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `TypebotSetting` ADD CONSTRAINT `TypebotSetting_typebotIdFallback_fkey` FOREIGN KEY (`typebotIdFallback`) REFERENCES `Typebot`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `TypebotSetting` ADD CONSTRAINT `TypebotSetting_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Media` ADD CONSTRAINT `Media_messageId_fkey` FOREIGN KEY (`messageId`) REFERENCES `Message`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Media` ADD CONSTRAINT `Media_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `OpenaiCreds` ADD CONSTRAINT `OpenaiCreds_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `OpenaiBot` ADD CONSTRAINT `OpenaiBot_openaiCredsId_fkey` FOREIGN KEY (`openaiCredsId`) REFERENCES `OpenaiCreds`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `OpenaiBot` ADD CONSTRAINT `OpenaiBot_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `OpenaiSession` ADD CONSTRAINT `OpenaiSession_openaiBotId_fkey` FOREIGN KEY (`openaiBotId`) REFERENCES `OpenaiBot`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `OpenaiSession` ADD CONSTRAINT `OpenaiSession_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `OpenaiSetting` ADD CONSTRAINT `OpenaiSetting_openaiCredsId_fkey` FOREIGN KEY (`openaiCredsId`) REFERENCES `OpenaiCreds`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `OpenaiSetting` ADD CONSTRAINT `OpenaiSetting_openaiIdFallback_fkey` FOREIGN KEY (`openaiIdFallback`) REFERENCES `OpenaiBot`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `OpenaiSetting` ADD CONSTRAINT `OpenaiSetting_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Template` ADD CONSTRAINT `Template_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Dify` ADD CONSTRAINT `Dify_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `DifySession` ADD CONSTRAINT `DifySession_difyId_fkey` FOREIGN KEY (`difyId`) REFERENCES `Dify`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `DifySession` ADD CONSTRAINT `DifySession_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `DifySetting` ADD CONSTRAINT `DifySetting_difyIdFallback_fkey` FOREIGN KEY (`difyIdFallback`) REFERENCES `Dify`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `DifySetting` ADD CONSTRAINT `DifySetting_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/mysql-migrations/20240813153900_add_unique_index_for_remoted_jid_and_instance_in_contacts/migration.sql b/prisma/mysql-migrations/20240813153900_add_unique_index_for_remoted_jid_and_instance_in_contacts/migration.sql new file mode 100644 index 00000000..5765ce97 --- /dev/null +++ b/prisma/mysql-migrations/20240813153900_add_unique_index_for_remoted_jid_and_instance_in_contacts/migration.sql @@ -0,0 +1,173 @@ +/* +Warnings: +- You are about to alter the column `createdAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `DifySession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `DifySession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `disconnectionAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `Media` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `OpenaiSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `OpenaiSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `Session` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `TypebotSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `TypebotSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `createdAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- You are about to alter the column `updatedAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. +- A unique constraint covering the columns `[remoteJid,instanceId]` on the table `Contact` will be added. If there are existing duplicate values, this will fail. +*/ +-- AlterTable +ALTER TABLE `Chat` +ADD COLUMN `name` VARCHAR(100) NULL, +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Chatwoot` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Contact` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Dify` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `DifySession` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `DifySetting` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Instance` +MODIFY `disconnectionAt` TIMESTAMP NULL, +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Label` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Media` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `OpenaiBot` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiCreds` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiSession` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiSetting` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Proxy` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Rabbitmq` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Session` +MODIFY `createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `Setting` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Sqs` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Template` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Typebot` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `TypebotSession` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `TypebotSetting` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Webhook` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Websocket` +MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, +MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- CreateIndex +CREATE UNIQUE INDEX `Contact_remoteJid_instanceId_key` ON `Contact` (`remoteJid`, `instanceId`); \ No newline at end of file diff --git a/prisma/mysql-migrations/20240814173138_add_ignore_jids_chatwoot/migration.sql b/prisma/mysql-migrations/20240814173138_add_ignore_jids_chatwoot/migration.sql new file mode 100644 index 00000000..99a38e4c --- /dev/null +++ b/prisma/mysql-migrations/20240814173138_add_ignore_jids_chatwoot/migration.sql @@ -0,0 +1,150 @@ +/* + Warnings: + + - You are about to alter the column `createdAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `DifySession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `DifySession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `disconnectionAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Media` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Session` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `TypebotSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `TypebotSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + +*/ +-- DropIndex +DROP INDEX `Label_labelId_key` ON `Label`; + +-- AlterTable +ALTER TABLE `Chat` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Chatwoot` ADD COLUMN `ignoreJids` JSON NULL, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Contact` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Dify` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `DifySession` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `DifySetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Instance` MODIFY `disconnectionAt` TIMESTAMP NULL, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Label` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Media` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `OpenaiBot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiCreds` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiSession` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Proxy` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Rabbitmq` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Session` MODIFY `createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `Setting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Sqs` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Template` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Typebot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `TypebotSession` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `TypebotSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Webhook` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Websocket` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; diff --git a/prisma/mysql-migrations/20240814214314_integrations_unification/migration.sql b/prisma/mysql-migrations/20240814214314_integrations_unification/migration.sql new file mode 100644 index 00000000..30b455ce --- /dev/null +++ b/prisma/mysql-migrations/20240814214314_integrations_unification/migration.sql @@ -0,0 +1,208 @@ +/* + Warnings: + + - You are about to alter the column `createdAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `disconnectionAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Media` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to drop the column `difySessionId` on the `Message` table. All the data in the column will be lost. + - You are about to drop the column `openaiSessionId` on the `Message` table. All the data in the column will be lost. + - You are about to alter the column `createdAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Session` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to drop the `DifySession` table. If the table is not empty, all the data it contains will be lost. + - You are about to drop the `OpenaiSession` table. If the table is not empty, all the data it contains will be lost. + - You are about to drop the `TypebotSession` table. If the table is not empty, all the data it contains will be lost. + +*/ +-- DropForeignKey +ALTER TABLE `DifySession` DROP FOREIGN KEY `DifySession_difyId_fkey`; + +-- DropForeignKey +ALTER TABLE `DifySession` DROP FOREIGN KEY `DifySession_instanceId_fkey`; + +-- DropForeignKey +ALTER TABLE `Message` DROP FOREIGN KEY `Message_difySessionId_fkey`; + +-- DropForeignKey +ALTER TABLE `Message` DROP FOREIGN KEY `Message_openaiSessionId_fkey`; + +-- DropForeignKey +ALTER TABLE `Message` DROP FOREIGN KEY `Message_typebotSessionId_fkey`; + +-- DropForeignKey +ALTER TABLE `OpenaiSession` DROP FOREIGN KEY `OpenaiSession_instanceId_fkey`; + +-- DropForeignKey +ALTER TABLE `OpenaiSession` DROP FOREIGN KEY `OpenaiSession_openaiBotId_fkey`; + +-- DropForeignKey +ALTER TABLE `TypebotSession` DROP FOREIGN KEY `TypebotSession_instanceId_fkey`; + +-- DropForeignKey +ALTER TABLE `TypebotSession` DROP FOREIGN KEY `TypebotSession_typebotId_fkey`; + +-- AlterTable +ALTER TABLE `Chat` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Chatwoot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Contact` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Dify` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `DifySetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Instance` MODIFY `disconnectionAt` TIMESTAMP NULL, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Label` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Media` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `Message` DROP COLUMN `difySessionId`, + DROP COLUMN `openaiSessionId`, + ADD COLUMN `sessionId` VARCHAR(191) NULL; + +-- AlterTable +ALTER TABLE `OpenaiBot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiCreds` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Proxy` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Rabbitmq` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Session` MODIFY `createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `Setting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Sqs` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Template` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Typebot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `TypebotSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Webhook` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Websocket` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- DropTable +DROP TABLE `DifySession`; + +-- DropTable +DROP TABLE `OpenaiSession`; + +-- DropTable +DROP TABLE `TypebotSession`; + +-- CreateTable +CREATE TABLE `IntegrationSession` ( + `id` VARCHAR(191) NOT NULL, + `sessionId` VARCHAR(255) NOT NULL, + `remoteJid` VARCHAR(100) NOT NULL, + `pushName` VARCHAR(191) NULL, + `status` ENUM('opened', 'closed', 'paused') NOT NULL, + `awaitUser` BOOLEAN NOT NULL DEFAULT false, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + `parameters` JSON NULL, + `openaiBotId` VARCHAR(191) NULL, + `difyId` VARCHAR(191) NULL, + `typebotId` VARCHAR(191) NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- AddForeignKey +ALTER TABLE `Message` ADD CONSTRAINT `Message_sessionId_fkey` FOREIGN KEY (`sessionId`) REFERENCES `IntegrationSession`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `IntegrationSession` ADD CONSTRAINT `IntegrationSession_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `IntegrationSession` ADD CONSTRAINT `IntegrationSession_openaiBotId_fkey` FOREIGN KEY (`openaiBotId`) REFERENCES `OpenaiBot`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `IntegrationSession` ADD CONSTRAINT `IntegrationSession_difyId_fkey` FOREIGN KEY (`difyId`) REFERENCES `Dify`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `IntegrationSession` ADD CONSTRAINT `IntegrationSession_typebotId_fkey` FOREIGN KEY (`typebotId`) REFERENCES `Typebot`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/mysql-migrations/20240821203259_add_postgres_migrations/migration.sql b/prisma/mysql-migrations/20240821203259_add_postgres_migrations/migration.sql new file mode 100644 index 00000000..9c248d9c --- /dev/null +++ b/prisma/mysql-migrations/20240821203259_add_postgres_migrations/migration.sql @@ -0,0 +1,269 @@ +/* + Warnings: + + - You are about to alter the column `createdAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `disconnectionAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to drop the column `difyId` on the `IntegrationSession` table. All the data in the column will be lost. + - You are about to drop the column `openaiBotId` on the `IntegrationSession` table. All the data in the column will be lost. + - You are about to drop the column `typebotId` on the `IntegrationSession` table. All the data in the column will be lost. + - You are about to alter the column `createdAt` on the `IntegrationSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `IntegrationSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Media` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Session` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + +*/ +-- DropForeignKey +ALTER TABLE `IntegrationSession` DROP FOREIGN KEY `IntegrationSession_difyId_fkey`; + +-- DropForeignKey +ALTER TABLE `IntegrationSession` DROP FOREIGN KEY `IntegrationSession_openaiBotId_fkey`; + +-- DropForeignKey +ALTER TABLE `IntegrationSession` DROP FOREIGN KEY `IntegrationSession_typebotId_fkey`; + +-- DropIndex +DROP INDEX `Message_typebotSessionId_fkey` ON `Message`; + +-- AlterTable +ALTER TABLE `Chat` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Chatwoot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Contact` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Dify` MODIFY `triggerType` ENUM('all', 'keyword', 'none', 'advanced') NULL, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `DifySetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Instance` MODIFY `disconnectionAt` TIMESTAMP NULL, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `IntegrationSession` DROP COLUMN `difyId`, + DROP COLUMN `openaiBotId`, + DROP COLUMN `typebotId`, + ADD COLUMN `botId` VARCHAR(191) NULL, + ADD COLUMN `context` JSON NULL, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Label` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Media` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `OpenaiBot` MODIFY `triggerType` ENUM('all', 'keyword', 'none', 'advanced') NULL, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiCreds` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Proxy` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Rabbitmq` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Session` MODIFY `createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `Setting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Sqs` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Template` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Typebot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL, + MODIFY `triggerType` ENUM('all', 'keyword', 'none', 'advanced') NULL; + +-- AlterTable +ALTER TABLE `TypebotSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Webhook` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Websocket` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- CreateTable +CREATE TABLE `GenericBot` ( + `id` VARCHAR(191) NOT NULL, + `enabled` BOOLEAN NOT NULL DEFAULT true, + `description` VARCHAR(255) NULL, + `apiUrl` VARCHAR(255) NULL, + `apiKey` VARCHAR(255) NULL, + `expire` INTEGER NULL DEFAULT 0, + `keywordFinish` VARCHAR(100) NULL, + `delayMessage` INTEGER NULL, + `unknownMessage` VARCHAR(100) NULL, + `listeningFromMe` BOOLEAN NULL DEFAULT false, + `stopBotFromMe` BOOLEAN NULL DEFAULT false, + `keepOpen` BOOLEAN NULL DEFAULT false, + `debounceTime` INTEGER NULL, + `ignoreJids` JSON NULL, + `triggerType` ENUM('all', 'keyword', 'none', 'advanced') NULL, + `triggerOperator` ENUM('contains', 'equals', 'startsWith', 'endsWith', 'regex') NULL, + `triggerValue` VARCHAR(191) NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `GenericSetting` ( + `id` VARCHAR(191) NOT NULL, + `expire` INTEGER NULL DEFAULT 0, + `keywordFinish` VARCHAR(100) NULL, + `delayMessage` INTEGER NULL, + `unknownMessage` VARCHAR(100) NULL, + `listeningFromMe` BOOLEAN NULL DEFAULT false, + `stopBotFromMe` BOOLEAN NULL DEFAULT false, + `keepOpen` BOOLEAN NULL DEFAULT false, + `debounceTime` INTEGER NULL, + `ignoreJids` JSON NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `botIdFallback` VARCHAR(100) NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `GenericSetting_instanceId_key`(`instanceId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `Flowise` ( + `id` VARCHAR(191) NOT NULL, + `enabled` BOOLEAN NOT NULL DEFAULT true, + `description` VARCHAR(255) NULL, + `apiUrl` VARCHAR(255) NULL, + `apiKey` VARCHAR(255) NULL, + `expire` INTEGER NULL DEFAULT 0, + `keywordFinish` VARCHAR(100) NULL, + `delayMessage` INTEGER NULL, + `unknownMessage` VARCHAR(100) NULL, + `listeningFromMe` BOOLEAN NULL DEFAULT false, + `stopBotFromMe` BOOLEAN NULL DEFAULT false, + `keepOpen` BOOLEAN NULL DEFAULT false, + `debounceTime` INTEGER NULL, + `ignoreJids` JSON NULL, + `triggerType` ENUM('all', 'keyword', 'none', 'advanced') NULL, + `triggerOperator` ENUM('contains', 'equals', 'startsWith', 'endsWith', 'regex') NULL, + `triggerValue` VARCHAR(191) NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `FlowiseSetting` ( + `id` VARCHAR(191) NOT NULL, + `expire` INTEGER NULL DEFAULT 0, + `keywordFinish` VARCHAR(100) NULL, + `delayMessage` INTEGER NULL, + `unknownMessage` VARCHAR(100) NULL, + `listeningFromMe` BOOLEAN NULL DEFAULT false, + `stopBotFromMe` BOOLEAN NULL DEFAULT false, + `keepOpen` BOOLEAN NULL DEFAULT false, + `debounceTime` INTEGER NULL, + `ignoreJids` JSON NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `flowiseIdFallback` VARCHAR(100) NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `FlowiseSetting_instanceId_key`(`instanceId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- AddForeignKey +ALTER TABLE `GenericBot` ADD CONSTRAINT `GenericBot_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `GenericSetting` ADD CONSTRAINT `GenericSetting_botIdFallback_fkey` FOREIGN KEY (`botIdFallback`) REFERENCES `GenericBot`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `GenericSetting` ADD CONSTRAINT `GenericSetting_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `Flowise` ADD CONSTRAINT `Flowise_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `FlowiseSetting` ADD CONSTRAINT `FlowiseSetting_flowiseIdFallback_fkey` FOREIGN KEY (`flowiseIdFallback`) REFERENCES `Flowise`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `FlowiseSetting` ADD CONSTRAINT `FlowiseSetting_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/mysql-migrations/20240824162012_add_type_on_integration_sessions/migration.sql b/prisma/mysql-migrations/20240824162012_add_type_on_integration_sessions/migration.sql new file mode 100644 index 00000000..5c08030c --- /dev/null +++ b/prisma/mysql-migrations/20240824162012_add_type_on_integration_sessions/migration.sql @@ -0,0 +1,159 @@ +/* + Warnings: + + - You are about to alter the column `createdAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Flowise` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Flowise` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `FlowiseSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `FlowiseSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `GenericBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `GenericBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `GenericSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `GenericSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `disconnectionAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `IntegrationSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `IntegrationSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Media` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Session` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + +*/ +-- AlterTable +ALTER TABLE `Chat` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Chatwoot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Contact` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Dify` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `DifySetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Flowise` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `FlowiseSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `GenericBot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `GenericSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Instance` MODIFY `disconnectionAt` TIMESTAMP NULL, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `IntegrationSession` ADD COLUMN `type` VARCHAR(100) NULL, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Label` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Media` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `OpenaiBot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiCreds` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Proxy` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Rabbitmq` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Session` MODIFY `createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `Setting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Sqs` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Template` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Typebot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `TypebotSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Webhook` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Websocket` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; diff --git a/prisma/mysql-migrations/20240825131301_change_to_evolution_bot/migration.sql b/prisma/mysql-migrations/20240825131301_change_to_evolution_bot/migration.sql new file mode 100644 index 00000000..9a2d937c --- /dev/null +++ b/prisma/mysql-migrations/20240825131301_change_to_evolution_bot/migration.sql @@ -0,0 +1,219 @@ +/* + Warnings: + + - You are about to alter the column `createdAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Flowise` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Flowise` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `FlowiseSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `FlowiseSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `disconnectionAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `IntegrationSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `IntegrationSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Media` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Session` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to drop the `GenericBot` table. If the table is not empty, all the data it contains will be lost. + - You are about to drop the `GenericSetting` table. If the table is not empty, all the data it contains will be lost. + +*/ +-- DropForeignKey +ALTER TABLE `GenericBot` DROP FOREIGN KEY `GenericBot_instanceId_fkey`; + +-- DropForeignKey +ALTER TABLE `GenericSetting` DROP FOREIGN KEY `GenericSetting_botIdFallback_fkey`; + +-- DropForeignKey +ALTER TABLE `GenericSetting` DROP FOREIGN KEY `GenericSetting_instanceId_fkey`; + +-- AlterTable +ALTER TABLE `Chat` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Chatwoot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Contact` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Dify` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `DifySetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Flowise` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `FlowiseSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Instance` MODIFY `disconnectionAt` TIMESTAMP NULL, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `IntegrationSession` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Label` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Media` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `OpenaiBot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiCreds` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Proxy` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Rabbitmq` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Session` MODIFY `createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `Setting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Sqs` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Template` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Typebot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `TypebotSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Webhook` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Websocket` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- DropTable +DROP TABLE `GenericBot`; + +-- DropTable +DROP TABLE `GenericSetting`; + +-- CreateTable +CREATE TABLE `EvolutionBot` ( + `id` VARCHAR(191) NOT NULL, + `enabled` BOOLEAN NOT NULL DEFAULT true, + `description` VARCHAR(255) NULL, + `apiUrl` VARCHAR(255) NULL, + `apiKey` VARCHAR(255) NULL, + `expire` INTEGER NULL DEFAULT 0, + `keywordFinish` VARCHAR(100) NULL, + `delayMessage` INTEGER NULL, + `unknownMessage` VARCHAR(100) NULL, + `listeningFromMe` BOOLEAN NULL DEFAULT false, + `stopBotFromMe` BOOLEAN NULL DEFAULT false, + `keepOpen` BOOLEAN NULL DEFAULT false, + `debounceTime` INTEGER NULL, + `ignoreJids` JSON NULL, + `triggerType` ENUM('all', 'keyword', 'none', 'advanced') NULL, + `triggerOperator` ENUM('contains', 'equals', 'startsWith', 'endsWith', 'regex') NULL, + `triggerValue` VARCHAR(191) NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `EvolutionBotSetting` ( + `id` VARCHAR(191) NOT NULL, + `expire` INTEGER NULL DEFAULT 0, + `keywordFinish` VARCHAR(100) NULL, + `delayMessage` INTEGER NULL, + `unknownMessage` VARCHAR(100) NULL, + `listeningFromMe` BOOLEAN NULL DEFAULT false, + `stopBotFromMe` BOOLEAN NULL DEFAULT false, + `keepOpen` BOOLEAN NULL DEFAULT false, + `debounceTime` INTEGER NULL, + `ignoreJids` JSON NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `botIdFallback` VARCHAR(100) NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `EvolutionBotSetting_instanceId_key`(`instanceId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- AddForeignKey +ALTER TABLE `EvolutionBot` ADD CONSTRAINT `EvolutionBot_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `EvolutionBotSetting` ADD CONSTRAINT `EvolutionBotSetting_botIdFallback_fkey` FOREIGN KEY (`botIdFallback`) REFERENCES `EvolutionBot`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `EvolutionBotSetting` ADD CONSTRAINT `EvolutionBotSetting_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/mysql-migrations/migration_lock.toml b/prisma/mysql-migrations/migration_lock.toml new file mode 100644 index 00000000..e5a788a7 --- /dev/null +++ b/prisma/mysql-migrations/migration_lock.toml @@ -0,0 +1,3 @@ +# Please do not edit this file manually +# It should be added in your version-control system (i.e. Git) +provider = "mysql" \ No newline at end of file diff --git a/prisma/mysql-schema.prisma b/prisma/mysql-schema.prisma index 533907fa..88400f0f 100644 --- a/prisma/mysql-schema.prisma +++ b/prisma/mysql-schema.prisma @@ -27,8 +27,8 @@ enum DeviceMessage { desktop } -enum TypebotSessionStatus { - open +enum SessionStatus { + opened closed paused } @@ -37,6 +37,7 @@ enum TriggerType { all keyword none + advanced } enum TriggerOperator { @@ -44,53 +45,82 @@ enum TriggerOperator { equals startsWith endsWith + regex +} + +enum OpenaiBotType { + assistant + chatCompletion +} + +enum DifyBotType { + chatBot + textGenerator + agent + workflow } model Instance { - id String @id @default(cuid()) - name String @unique @db.VarChar(255) - connectionStatus InstanceConnectionStatus @default(open) - ownerJid String? @db.VarChar(100) - profileName String? @db.VarChar(100) - profilePicUrl String? @db.VarChar(500) - integration String? @db.VarChar(100) - number String? @db.VarChar(100) - token String? @unique @db.VarChar(255) - clientName String? @db.VarChar(100) - createdAt DateTime? @default(now()) @db.Timestamp - updatedAt DateTime? @updatedAt @db.Timestamp - Chat Chat[] - Contact Contact[] - Message Message[] - Webhook Webhook? - Chatwoot Chatwoot? - Label Label[] - Proxy Proxy? - Setting Setting? - Rabbitmq Rabbitmq? - Sqs Sqs? - Websocket Websocket? - Typebot Typebot[] - Session Session? - MessageUpdate MessageUpdate[] - TypebotSession TypebotSession[] - TypebotSetting TypebotSetting? + id String @id @default(cuid()) + name String @unique @db.VarChar(255) + connectionStatus InstanceConnectionStatus @default(open) + ownerJid String? @db.VarChar(100) + profileName String? @db.VarChar(100) + profilePicUrl String? @db.VarChar(500) + integration String? @db.VarChar(100) + number String? @db.VarChar(100) + businessId String? @db.VarChar(100) + token String? @db.VarChar(255) + clientName String? @db.VarChar(100) + disconnectionReasonCode Int? @db.Int + disconnectionObject Json? @db.Json + disconnectionAt DateTime? @db.Timestamp + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime? @updatedAt @db.Timestamp + Chat Chat[] + Contact Contact[] + Message Message[] + Webhook Webhook? + Chatwoot Chatwoot? + Label Label[] + Proxy Proxy? + Setting Setting? + Rabbitmq Rabbitmq? + Sqs Sqs? + Websocket Websocket? + Typebot Typebot[] + Session Session? + MessageUpdate MessageUpdate[] + TypebotSetting TypebotSetting? + Media Media[] + OpenaiCreds OpenaiCreds[] + OpenaiBot OpenaiBot[] + OpenaiSetting OpenaiSetting? + Template Template[] + Dify Dify[] + DifySetting DifySetting? + integrationSessions IntegrationSession[] + EvolutionBot EvolutionBot[] + EvolutionBotSetting EvolutionBotSetting? + Flowise Flowise[] + FlowiseSetting FlowiseSetting? } model Session { id String @id @default(cuid()) sessionId String @unique creds String? @db.Text - createdAt DateTime @default(now()) + createdAt DateTime @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp Instance Instance @relation(fields: [sessionId], references: [id], onDelete: Cascade) } model Chat { id String @id @default(cuid()) remoteJid String @db.VarChar(100) + name String? @db.VarChar(100) labels Json? @db.Json - createdAt DateTime? @default(now()) @db.Date - updatedAt DateTime? @updatedAt @db.Date + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime? @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String } @@ -100,10 +130,12 @@ model Contact { remoteJid String @db.VarChar(100) pushName String? @db.VarChar(100) profilePicUrl String? @db.VarChar(500) - createdAt DateTime? @default(now()) @db.Date - updatedAt DateTime? @updatedAt @db.Date + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime? @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String + + @@unique([remoteJid, instanceId]) } model Message { @@ -115,17 +147,21 @@ model Message { message Json @db.Json contextInfo Json? @db.Json source DeviceMessage - messageTimestamp String @db.VarChar(100) + messageTimestamp Int @db.Int chatwootMessageId Int? @db.Int chatwootInboxId Int? @db.Int chatwootConversationId Int? @db.Int chatwootContactInboxSourceId String? @db.VarChar(100) - chatwootIsRead Boolean? + chatwootIsRead Boolean? @default(false) Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String typebotSessionId String? MessageUpdate MessageUpdate[] - TypebotSession TypebotSession? @relation(fields: [typebotSessionId], references: [id]) + Media Media? + webhookUrl String? @db.VarChar(500) + + sessionId String? + session IntegrationSession? @relation(fields: [sessionId], references: [id]) } model MessageUpdate { @@ -134,7 +170,6 @@ model MessageUpdate { remoteJid String @db.VarChar(100) fromMe Boolean participant String? @db.VarChar(100) - dateTime DateTime @db.Date pollUpdates Json? @db.Json status String @db.VarChar(30) Message Message @relation(fields: [messageId], references: [id], onDelete: Cascade) @@ -146,12 +181,13 @@ model MessageUpdate { model Webhook { id String @id @default(cuid()) url String @db.VarChar(500) - enabled Boolean? @default(false) + headers Json? @db.Json + enabled Boolean? @default(true) events Json? @db.Json webhookByEvents Boolean? @default(false) webhookBase64 Boolean? @default(false) - createdAt DateTime? @default(now()) @db.Date - updatedAt DateTime @updatedAt @db.Date + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String @unique } @@ -173,21 +209,22 @@ model Chatwoot { importMessages Boolean? @default(false) daysLimitImportMessages Int? @db.Int organization String? @db.VarChar(100) - logoUrl String? @db.VarChar(500) - createdAt DateTime? @default(now()) @db.Date - updatedAt DateTime @updatedAt @db.Date + logo String? @db.VarChar(500) + ignoreJids Json? + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String @unique } model Label { id String @id @default(cuid()) - labelId String? @unique @db.VarChar(100) + labelId String? @db.VarChar(100) name String @db.VarChar(100) color String @db.VarChar(100) predefinedId String? @db.VarChar(100) - createdAt DateTime? @default(now()) @db.Date - updatedAt DateTime @updatedAt @db.Date + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String } @@ -200,8 +237,8 @@ model Proxy { protocol String @db.VarChar(100) username String @db.VarChar(100) password String @db.VarChar(100) - createdAt DateTime? @default(now()) @db.Date - updatedAt DateTime @updatedAt @db.Date + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String @unique } @@ -215,8 +252,8 @@ model Setting { readMessages Boolean @default(false) readStatus Boolean @default(false) syncFullHistory Boolean @default(false) - createdAt DateTime? @default(now()) @db.Date - updatedAt DateTime @updatedAt @db.Date + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String @unique } @@ -225,8 +262,8 @@ model Rabbitmq { id String @id @default(cuid()) enabled Boolean @default(false) events Json @db.Json - createdAt DateTime? @default(now()) @db.Date - updatedAt DateTime @updatedAt @db.Date + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String @unique } @@ -235,8 +272,8 @@ model Sqs { id String @id @default(cuid()) enabled Boolean @default(false) events Json @db.Json - createdAt DateTime? @default(now()) @db.Date - updatedAt DateTime @updatedAt @db.Date + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String @unique } @@ -245,8 +282,8 @@ model Websocket { id String @id @default(cuid()) enabled Boolean @default(false) events Json @db.Json - createdAt DateTime? @default(now()) @db.Date - updatedAt DateTime @updatedAt @db.Date + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String @unique } @@ -254,6 +291,7 @@ model Websocket { model Typebot { id String @id @default(cuid()) enabled Boolean @default(true) + description String? @db.VarChar(255) url String @db.VarChar(500) typebot String @db.VarChar(100) expire Int? @default(0) @db.Int @@ -264,34 +302,173 @@ model Typebot { stopBotFromMe Boolean? @default(false) keepOpen Boolean? @default(false) debounceTime Int? @db.Int - createdAt DateTime? @default(now()) @db.Date - updatedAt DateTime? @updatedAt @db.Date + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime? @updatedAt @db.Timestamp + ignoreJids Json? triggerType TriggerType? triggerOperator TriggerOperator? triggerValue String? Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String - sessions TypebotSession[] -} - -model TypebotSession { - id String @id @default(cuid()) - remoteJid String @db.VarChar(100) - pushName String? @db.VarChar(100) - sessionId String @db.VarChar(100) - status String @db.VarChar(100) - prefilledVariables Json? @db.Json - debounceTime Int? @db.Int - createdAt DateTime? @default(now()) @db.Date - updatedAt DateTime @updatedAt @db.Date - Typebot Typebot @relation(fields: [typebotId], references: [id], onDelete: Cascade) - typebotId String - Message Message[] - Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) - instanceId String + TypebotSetting TypebotSetting[] } model TypebotSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Int + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Int + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) + stopBotFromMe Boolean? @default(false) + keepOpen Boolean? @default(false) + debounceTime Int? @db.Int + typebotIdFallback String? @db.VarChar(100) + ignoreJids Json? + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback Typebot? @relation(fields: [typebotIdFallback], references: [id]) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model IntegrationSession { + id String @id @default(cuid()) + sessionId String @db.VarChar(255) + remoteJid String @db.VarChar(100) + pushName String? + status SessionStatus + awaitUser Boolean @default(false) + context Json? + type String? @db.VarChar(100) + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Message Message[] + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + parameters Json? + + botId String? +} + +model Media { + id String @id @default(cuid()) + fileName String @unique @db.VarChar(500) + type String @db.VarChar(100) + mimetype String @db.VarChar(100) + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + Message Message @relation(fields: [messageId], references: [id], onDelete: Cascade) + messageId String @unique + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String +} + +model OpenaiCreds { + id String @id @default(cuid()) + name String? @unique @db.VarChar(255) + apiKey String? @unique @db.VarChar(255) + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + OpenaiAssistant OpenaiBot[] + OpenaiSetting OpenaiSetting? +} + +model OpenaiBot { + id String @id @default(cuid()) + enabled Boolean @default(true) + description String? @db.VarChar(255) + botType OpenaiBotType + assistantId String? @db.VarChar(255) + functionUrl String? @db.VarChar(500) + model String? @db.VarChar(100) + systemMessages Json? @db.Json + assistantMessages Json? @db.Json + userMessages Json? @db.Json + maxTokens Int? @db.Int + expire Int? @default(0) @db.Int + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Int + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) + stopBotFromMe Boolean? @default(false) + keepOpen Boolean? @default(false) + debounceTime Int? @db.Int + ignoreJids Json? + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + OpenaiCreds OpenaiCreds @relation(fields: [openaiCredsId], references: [id], onDelete: Cascade) + openaiCredsId String + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + OpenaiSetting OpenaiSetting[] +} + +model OpenaiSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Int + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Int + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) + stopBotFromMe Boolean? @default(false) + keepOpen Boolean? @default(false) + debounceTime Int? @db.Int + ignoreJids Json? + speechToText Boolean? @default(false) + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + OpenaiCreds OpenaiCreds? @relation(fields: [openaiCredsId], references: [id]) + openaiCredsId String @unique + Fallback OpenaiBot? @relation(fields: [openaiIdFallback], references: [id]) + openaiIdFallback String? @db.VarChar(100) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model Template { + id String @id @default(cuid()) + templateId String @unique @db.VarChar(255) + name String @unique @db.VarChar(255) + template Json @db.Json + webhookUrl String? @db.VarChar(500) + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String +} + +model Dify { + id String @id @default(cuid()) + enabled Boolean @default(true) + description String? @db.VarChar(255) + botType DifyBotType + apiUrl String? @db.VarChar(255) + apiKey String? @db.VarChar(255) + expire Int? @default(0) @db.Int + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Int + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) + stopBotFromMe Boolean? @default(false) + keepOpen Boolean? @default(false) + debounceTime Int? @db.Int + ignoreJids Json? + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + DifySetting DifySetting[] +} + +model DifySetting { id String @id @default(cuid()) expire Int? @default(0) @db.Int keywordFinish String? @db.VarChar(100) @@ -300,8 +477,100 @@ model TypebotSetting { listeningFromMe Boolean? @default(false) stopBotFromMe Boolean? @default(false) keepOpen Boolean? @default(false) - createdAt DateTime? @default(now()) @db.Date - updatedAt DateTime @updatedAt @db.Date + debounceTime Int? @db.Int + ignoreJids Json? + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback Dify? @relation(fields: [difyIdFallback], references: [id]) + difyIdFallback String? @db.VarChar(100) Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String @unique } + +model EvolutionBot { + id String @id @default(cuid()) + enabled Boolean @default(true) + description String? @db.VarChar(255) + apiUrl String? @db.VarChar(255) + apiKey String? @db.VarChar(255) + expire Int? @default(0) @db.Int + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Int + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) + stopBotFromMe Boolean? @default(false) + keepOpen Boolean? @default(false) + debounceTime Int? @db.Int + ignoreJids Json? + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + EvolutionBotSetting EvolutionBotSetting[] +} + +model EvolutionBotSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Int + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Int + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) + stopBotFromMe Boolean? @default(false) + keepOpen Boolean? @default(false) + debounceTime Int? @db.Int + ignoreJids Json? + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback EvolutionBot? @relation(fields: [botIdFallback], references: [id]) + botIdFallback String? @db.VarChar(100) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model Flowise { + id String @id @default(cuid()) + enabled Boolean @default(true) + description String? @db.VarChar(255) + apiUrl String? @db.VarChar(255) + apiKey String? @db.VarChar(255) + expire Int? @default(0) @db.Int + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Int + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) + stopBotFromMe Boolean? @default(false) + keepOpen Boolean? @default(false) + debounceTime Int? @db.Int + ignoreJids Json? + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + FlowiseSetting FlowiseSetting[] +} + +model FlowiseSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Int + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Int + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) + stopBotFromMe Boolean? @default(false) + keepOpen Boolean? @default(false) + debounceTime Int? @db.Int + ignoreJids Json? + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback Flowise? @relation(fields: [flowiseIdFallback], references: [id]) + flowiseIdFallback String? @db.VarChar(100) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} diff --git a/prisma/migrations/20240609181238_init/migration.sql b/prisma/postgresql-migrations/20240609181238_init/migration.sql similarity index 100% rename from prisma/migrations/20240609181238_init/migration.sql rename to prisma/postgresql-migrations/20240609181238_init/migration.sql diff --git a/prisma/migrations/20240610144159_create_column_profile_name_instance/migration.sql b/prisma/postgresql-migrations/20240610144159_create_column_profile_name_instance/migration.sql similarity index 100% rename from prisma/migrations/20240610144159_create_column_profile_name_instance/migration.sql rename to prisma/postgresql-migrations/20240610144159_create_column_profile_name_instance/migration.sql diff --git a/prisma/migrations/20240611125754_create_columns_whitelabel_chatwoot/migration.sql b/prisma/postgresql-migrations/20240611125754_create_columns_whitelabel_chatwoot/migration.sql similarity index 100% rename from prisma/migrations/20240611125754_create_columns_whitelabel_chatwoot/migration.sql rename to prisma/postgresql-migrations/20240611125754_create_columns_whitelabel_chatwoot/migration.sql diff --git a/prisma/migrations/20240611202817_create_columns_debounce_time_typebot/migration.sql b/prisma/postgresql-migrations/20240611202817_create_columns_debounce_time_typebot/migration.sql similarity index 100% rename from prisma/migrations/20240611202817_create_columns_debounce_time_typebot/migration.sql rename to prisma/postgresql-migrations/20240611202817_create_columns_debounce_time_typebot/migration.sql diff --git a/prisma/migrations/20240712144948_add_business_id_column_to_instances/migration.sql b/prisma/postgresql-migrations/20240712144948_add_business_id_column_to_instances/migration.sql similarity index 100% rename from prisma/migrations/20240712144948_add_business_id_column_to_instances/migration.sql rename to prisma/postgresql-migrations/20240712144948_add_business_id_column_to_instances/migration.sql diff --git a/prisma/migrations/20240712150256_create_templates_table/migration.sql b/prisma/postgresql-migrations/20240712150256_create_templates_table/migration.sql similarity index 100% rename from prisma/migrations/20240712150256_create_templates_table/migration.sql rename to prisma/postgresql-migrations/20240712150256_create_templates_table/migration.sql diff --git a/prisma/migrations/20240712155950_adjusts_in_templates_table/migration.sql b/prisma/postgresql-migrations/20240712155950_adjusts_in_templates_table/migration.sql similarity index 100% rename from prisma/migrations/20240712155950_adjusts_in_templates_table/migration.sql rename to prisma/postgresql-migrations/20240712155950_adjusts_in_templates_table/migration.sql diff --git a/prisma/migrations/20240712162206_remove_templates_table/migration.sql b/prisma/postgresql-migrations/20240712162206_remove_templates_table/migration.sql similarity index 100% rename from prisma/migrations/20240712162206_remove_templates_table/migration.sql rename to prisma/postgresql-migrations/20240712162206_remove_templates_table/migration.sql diff --git a/prisma/migrations/20240712223655_column_fallback_typebot/migration.sql b/prisma/postgresql-migrations/20240712223655_column_fallback_typebot/migration.sql similarity index 100% rename from prisma/migrations/20240712223655_column_fallback_typebot/migration.sql rename to prisma/postgresql-migrations/20240712223655_column_fallback_typebot/migration.sql diff --git a/prisma/migrations/20240712230631_column_ignore_jids_typebot/migration.sql b/prisma/postgresql-migrations/20240712230631_column_ignore_jids_typebot/migration.sql similarity index 100% rename from prisma/migrations/20240712230631_column_ignore_jids_typebot/migration.sql rename to prisma/postgresql-migrations/20240712230631_column_ignore_jids_typebot/migration.sql diff --git a/prisma/migrations/20240713184337_add_media_table/migration.sql b/prisma/postgresql-migrations/20240713184337_add_media_table/migration.sql similarity index 100% rename from prisma/migrations/20240713184337_add_media_table/migration.sql rename to prisma/postgresql-migrations/20240713184337_add_media_table/migration.sql diff --git a/prisma/migrations/20240718121437_add_openai_tables/migration.sql b/prisma/postgresql-migrations/20240718121437_add_openai_tables/migration.sql similarity index 100% rename from prisma/migrations/20240718121437_add_openai_tables/migration.sql rename to prisma/postgresql-migrations/20240718121437_add_openai_tables/migration.sql diff --git a/prisma/migrations/20240718123923_adjusts_openai_tables/migration.sql b/prisma/postgresql-migrations/20240718123923_adjusts_openai_tables/migration.sql similarity index 100% rename from prisma/migrations/20240718123923_adjusts_openai_tables/migration.sql rename to prisma/postgresql-migrations/20240718123923_adjusts_openai_tables/migration.sql diff --git a/prisma/migrations/20240722173259_add_name_column_to_openai_creds/migration.sql b/prisma/postgresql-migrations/20240722173259_add_name_column_to_openai_creds/migration.sql similarity index 100% rename from prisma/migrations/20240722173259_add_name_column_to_openai_creds/migration.sql rename to prisma/postgresql-migrations/20240722173259_add_name_column_to_openai_creds/migration.sql diff --git a/prisma/migrations/20240722173518_add_name_column_to_openai_creds/migration.sql b/prisma/postgresql-migrations/20240722173518_add_name_column_to_openai_creds/migration.sql similarity index 100% rename from prisma/migrations/20240722173518_add_name_column_to_openai_creds/migration.sql rename to prisma/postgresql-migrations/20240722173518_add_name_column_to_openai_creds/migration.sql diff --git a/prisma/migrations/20240723152648_adjusts_in_column_openai_creds/migration.sql b/prisma/postgresql-migrations/20240723152648_adjusts_in_column_openai_creds/migration.sql similarity index 100% rename from prisma/migrations/20240723152648_adjusts_in_column_openai_creds/migration.sql rename to prisma/postgresql-migrations/20240723152648_adjusts_in_column_openai_creds/migration.sql diff --git a/prisma/migrations/20240723200254_add_webhookurl_on_message/migration.sql b/prisma/postgresql-migrations/20240723200254_add_webhookurl_on_message/migration.sql similarity index 100% rename from prisma/migrations/20240723200254_add_webhookurl_on_message/migration.sql rename to prisma/postgresql-migrations/20240723200254_add_webhookurl_on_message/migration.sql diff --git a/prisma/migrations/20240725184147_create_template_table/migration.sql b/prisma/postgresql-migrations/20240725184147_create_template_table/migration.sql similarity index 100% rename from prisma/migrations/20240725184147_create_template_table/migration.sql rename to prisma/postgresql-migrations/20240725184147_create_template_table/migration.sql diff --git a/prisma/migrations/20240725202651_add_webhook_url_template_table/migration.sql b/prisma/postgresql-migrations/20240725202651_add_webhook_url_template_table/migration.sql similarity index 100% rename from prisma/migrations/20240725202651_add_webhook_url_template_table/migration.sql rename to prisma/postgresql-migrations/20240725202651_add_webhook_url_template_table/migration.sql diff --git a/prisma/migrations/20240725221646_modify_token_instance_table/migration.sql b/prisma/postgresql-migrations/20240725221646_modify_token_instance_table/migration.sql similarity index 100% rename from prisma/migrations/20240725221646_modify_token_instance_table/migration.sql rename to prisma/postgresql-migrations/20240725221646_modify_token_instance_table/migration.sql diff --git a/prisma/migrations/20240729115127_modify_trigger_type_openai_typebot_table/migration.sql b/prisma/postgresql-migrations/20240729115127_modify_trigger_type_openai_typebot_table/migration.sql similarity index 100% rename from prisma/migrations/20240729115127_modify_trigger_type_openai_typebot_table/migration.sql rename to prisma/postgresql-migrations/20240729115127_modify_trigger_type_openai_typebot_table/migration.sql diff --git a/prisma/migrations/20240729180347_modify_typebot_session_status_openai_typebot_table/migration.sql b/prisma/postgresql-migrations/20240729180347_modify_typebot_session_status_openai_typebot_table/migration.sql similarity index 100% rename from prisma/migrations/20240729180347_modify_typebot_session_status_openai_typebot_table/migration.sql rename to prisma/postgresql-migrations/20240729180347_modify_typebot_session_status_openai_typebot_table/migration.sql diff --git a/prisma/migrations/20240730152156_create_dify_tables/migration.sql b/prisma/postgresql-migrations/20240730152156_create_dify_tables/migration.sql similarity index 100% rename from prisma/migrations/20240730152156_create_dify_tables/migration.sql rename to prisma/postgresql-migrations/20240730152156_create_dify_tables/migration.sql diff --git a/prisma/migrations/20240801193907_add_column_speech_to_text_openai_setting_table/migration.sql b/prisma/postgresql-migrations/20240801193907_add_column_speech_to_text_openai_setting_table/migration.sql similarity index 100% rename from prisma/migrations/20240801193907_add_column_speech_to_text_openai_setting_table/migration.sql rename to prisma/postgresql-migrations/20240801193907_add_column_speech_to_text_openai_setting_table/migration.sql diff --git a/prisma/migrations/20240803163908_add_column_description_on_integrations_table/migration.sql b/prisma/postgresql-migrations/20240803163908_add_column_description_on_integrations_table/migration.sql similarity index 100% rename from prisma/migrations/20240803163908_add_column_description_on_integrations_table/migration.sql rename to prisma/postgresql-migrations/20240803163908_add_column_description_on_integrations_table/migration.sql diff --git a/prisma/postgresql-migrations/20240808210239_add_column_function_url_openaibot_table/migration.sql b/prisma/postgresql-migrations/20240808210239_add_column_function_url_openaibot_table/migration.sql new file mode 100644 index 00000000..16ca6b5d --- /dev/null +++ b/prisma/postgresql-migrations/20240808210239_add_column_function_url_openaibot_table/migration.sql @@ -0,0 +1,7 @@ +-- AlterTable +ALTER TABLE "Instance" ADD COLUMN "disconnectionAt" TIMESTAMP, +ADD COLUMN "disconnectionObject" JSONB, +ADD COLUMN "disconnectionReasonCode" INTEGER; + +-- AlterTable +ALTER TABLE "OpenaiBot" ADD COLUMN "functionUrl" VARCHAR(500); diff --git a/prisma/postgresql-migrations/20240811021156_add_chat_name_column/migration.sql b/prisma/postgresql-migrations/20240811021156_add_chat_name_column/migration.sql new file mode 100644 index 00000000..79d7fc1f --- /dev/null +++ b/prisma/postgresql-migrations/20240811021156_add_chat_name_column/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "Chat" ADD COLUMN "name" VARCHAR(100); diff --git a/prisma/postgresql-migrations/20240811183328_add_unique_index_for_remoted_jid_and_instance_in_contacts/migration.sql b/prisma/postgresql-migrations/20240811183328_add_unique_index_for_remoted_jid_and_instance_in_contacts/migration.sql new file mode 100644 index 00000000..1adcb7f4 --- /dev/null +++ b/prisma/postgresql-migrations/20240811183328_add_unique_index_for_remoted_jid_and_instance_in_contacts/migration.sql @@ -0,0 +1,17 @@ +/* + Warnings: + + - A unique constraint covering the columns `[remoteJid,instanceId]` on the table `Contact` will be added. If there are existing duplicate values, this will fail. + +*/ +-- Remove the duplicates +DELETE FROM "Contact" +WHERE ctid NOT IN ( + SELECT min(ctid) + FROM "Contact" + GROUP BY "remoteJid", "instanceId" +); + + +-- CreateIndex +CREATE UNIQUE INDEX "Contact_remoteJid_instanceId_key" ON "Contact"("remoteJid", "instanceId"); diff --git a/prisma/postgresql-migrations/20240813003116_make_label_unique_for_instance/migration.sql b/prisma/postgresql-migrations/20240813003116_make_label_unique_for_instance/migration.sql new file mode 100644 index 00000000..9110ed8a --- /dev/null +++ b/prisma/postgresql-migrations/20240813003116_make_label_unique_for_instance/migration.sql @@ -0,0 +1,11 @@ +/* + Warnings: + + - A unique constraint covering the columns `[labelId,instanceId]` on the table `Label` will be added. If there are existing duplicate values, this will fail. + +*/ +-- DropIndex +DROP INDEX "Label_labelId_key"; + +-- CreateIndex +CREATE UNIQUE INDEX "Label_labelId_instanceId_key" ON "Label"("labelId", "instanceId"); diff --git a/prisma/postgresql-migrations/20240814173033_add_ignore_jids_chatwoot/migration.sql b/prisma/postgresql-migrations/20240814173033_add_ignore_jids_chatwoot/migration.sql new file mode 100644 index 00000000..61470ed6 --- /dev/null +++ b/prisma/postgresql-migrations/20240814173033_add_ignore_jids_chatwoot/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "Chatwoot" ADD COLUMN "ignoreJids" JSONB; diff --git a/prisma/postgresql-migrations/20240814202359_integrations_unification/migration.sql b/prisma/postgresql-migrations/20240814202359_integrations_unification/migration.sql new file mode 100644 index 00000000..1192cf54 --- /dev/null +++ b/prisma/postgresql-migrations/20240814202359_integrations_unification/migration.sql @@ -0,0 +1,92 @@ +/* + Warnings: + + - You are about to drop the column `difySessionId` on the `Message` table. All the data in the column will be lost. + - You are about to drop the column `openaiSessionId` on the `Message` table. All the data in the column will be lost. + - You are about to drop the column `typebotSessionId` on the `Message` table. All the data in the column will be lost. + - You are about to drop the `DifySession` table. If the table is not empty, all the data it contains will be lost. + - You are about to drop the `OpenaiSession` table. If the table is not empty, all the data it contains will be lost. + - You are about to drop the `TypebotSession` table. If the table is not empty, all the data it contains will be lost. + +*/ +-- CreateEnum +CREATE TYPE "SessionStatus" AS ENUM ('opened', 'closed', 'paused'); + +-- DropForeignKey +ALTER TABLE "DifySession" DROP CONSTRAINT "DifySession_difyId_fkey"; + +-- DropForeignKey +ALTER TABLE "DifySession" DROP CONSTRAINT "DifySession_instanceId_fkey"; + +-- DropForeignKey +ALTER TABLE "Message" DROP CONSTRAINT "Message_difySessionId_fkey"; + +-- DropForeignKey +ALTER TABLE "Message" DROP CONSTRAINT "Message_openaiSessionId_fkey"; + +-- DropForeignKey +ALTER TABLE "Message" DROP CONSTRAINT "Message_typebotSessionId_fkey"; + +-- DropForeignKey +ALTER TABLE "OpenaiSession" DROP CONSTRAINT "OpenaiSession_instanceId_fkey"; + +-- DropForeignKey +ALTER TABLE "OpenaiSession" DROP CONSTRAINT "OpenaiSession_openaiBotId_fkey"; + +-- DropForeignKey +ALTER TABLE "TypebotSession" DROP CONSTRAINT "TypebotSession_instanceId_fkey"; + +-- DropForeignKey +ALTER TABLE "TypebotSession" DROP CONSTRAINT "TypebotSession_typebotId_fkey"; + +-- AlterTable +ALTER TABLE "Message" DROP COLUMN "difySessionId", +DROP COLUMN "openaiSessionId", +DROP COLUMN "typebotSessionId", +ADD COLUMN "sessionId" TEXT; + +-- DropTable +DROP TABLE "DifySession"; + +-- DropTable +DROP TABLE "OpenaiSession"; + +-- DropTable +DROP TABLE "TypebotSession"; + +-- DropEnum +DROP TYPE "TypebotSessionStatus"; + +-- CreateTable +CREATE TABLE "IntegrationSession" ( + "id" TEXT NOT NULL, + "sessionId" VARCHAR(255) NOT NULL, + "remoteJid" VARCHAR(100) NOT NULL, + "pushName" TEXT, + "status" "SessionStatus" NOT NULL, + "awaitUser" BOOLEAN NOT NULL DEFAULT false, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP NOT NULL, + "instanceId" TEXT NOT NULL, + "parameters" JSONB, + "openaiBotId" TEXT, + "difyId" TEXT, + "typebotId" TEXT, + + CONSTRAINT "IntegrationSession_pkey" PRIMARY KEY ("id") +); + +-- AddForeignKey +ALTER TABLE "Message" ADD CONSTRAINT "Message_sessionId_fkey" FOREIGN KEY ("sessionId") REFERENCES "IntegrationSession"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "IntegrationSession" ADD CONSTRAINT "IntegrationSession_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "IntegrationSession" ADD CONSTRAINT "IntegrationSession_openaiBotId_fkey" FOREIGN KEY ("openaiBotId") REFERENCES "OpenaiBot"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "IntegrationSession" ADD CONSTRAINT "IntegrationSession_difyId_fkey" FOREIGN KEY ("difyId") REFERENCES "Dify"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "IntegrationSession" ADD CONSTRAINT "IntegrationSession_typebotId_fkey" FOREIGN KEY ("typebotId") REFERENCES "Typebot"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/postgresql-migrations/20240817110155_add_trigger_type_advanced/migration.sql b/prisma/postgresql-migrations/20240817110155_add_trigger_type_advanced/migration.sql new file mode 100644 index 00000000..9d88fe37 --- /dev/null +++ b/prisma/postgresql-migrations/20240817110155_add_trigger_type_advanced/migration.sql @@ -0,0 +1,2 @@ +-- AlterEnum +ALTER TYPE "TriggerType" ADD VALUE 'advanced'; diff --git a/prisma/postgresql-migrations/20240819154941_add_context_to_integration_session/migration.sql b/prisma/postgresql-migrations/20240819154941_add_context_to_integration_session/migration.sql new file mode 100644 index 00000000..68adcd8c --- /dev/null +++ b/prisma/postgresql-migrations/20240819154941_add_context_to_integration_session/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "IntegrationSession" ADD COLUMN "context" JSONB; diff --git a/prisma/postgresql-migrations/20240821120816_bot_id_integration_session/migration.sql b/prisma/postgresql-migrations/20240821120816_bot_id_integration_session/migration.sql new file mode 100644 index 00000000..bfe174b6 --- /dev/null +++ b/prisma/postgresql-migrations/20240821120816_bot_id_integration_session/migration.sql @@ -0,0 +1,22 @@ +/* + Warnings: + + - You are about to drop the column `difyId` on the `IntegrationSession` table. All the data in the column will be lost. + - You are about to drop the column `openaiBotId` on the `IntegrationSession` table. All the data in the column will be lost. + - You are about to drop the column `typebotId` on the `IntegrationSession` table. All the data in the column will be lost. + +*/ +-- DropForeignKey +ALTER TABLE "IntegrationSession" DROP CONSTRAINT "IntegrationSession_difyId_fkey"; + +-- DropForeignKey +ALTER TABLE "IntegrationSession" DROP CONSTRAINT "IntegrationSession_openaiBotId_fkey"; + +-- DropForeignKey +ALTER TABLE "IntegrationSession" DROP CONSTRAINT "IntegrationSession_typebotId_fkey"; + +-- AlterTable +ALTER TABLE "IntegrationSession" DROP COLUMN "difyId", +DROP COLUMN "openaiBotId", +DROP COLUMN "typebotId", +ADD COLUMN "botId" TEXT; diff --git a/prisma/postgresql-migrations/20240821171327_add_generic_bot_table/migration.sql b/prisma/postgresql-migrations/20240821171327_add_generic_bot_table/migration.sql new file mode 100644 index 00000000..6ea99e2b --- /dev/null +++ b/prisma/postgresql-migrations/20240821171327_add_generic_bot_table/migration.sql @@ -0,0 +1,57 @@ +-- CreateTable +CREATE TABLE "GenericBot" ( + "id" TEXT NOT NULL, + "enabled" BOOLEAN NOT NULL DEFAULT true, + "description" VARCHAR(255), + "apiUrl" VARCHAR(255), + "apiKey" VARCHAR(255), + "expire" INTEGER DEFAULT 0, + "keywordFinish" VARCHAR(100), + "delayMessage" INTEGER, + "unknownMessage" VARCHAR(100), + "listeningFromMe" BOOLEAN DEFAULT false, + "stopBotFromMe" BOOLEAN DEFAULT false, + "keepOpen" BOOLEAN DEFAULT false, + "debounceTime" INTEGER, + "ignoreJids" JSONB, + "triggerType" "TriggerType", + "triggerOperator" "TriggerOperator", + "triggerValue" TEXT, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP NOT NULL, + "instanceId" TEXT NOT NULL, + + CONSTRAINT "GenericBot_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "GenericSetting" ( + "id" TEXT NOT NULL, + "expire" INTEGER DEFAULT 0, + "keywordFinish" VARCHAR(100), + "delayMessage" INTEGER, + "unknownMessage" VARCHAR(100), + "listeningFromMe" BOOLEAN DEFAULT false, + "stopBotFromMe" BOOLEAN DEFAULT false, + "keepOpen" BOOLEAN DEFAULT false, + "debounceTime" INTEGER, + "ignoreJids" JSONB, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP NOT NULL, + "botIdFallback" VARCHAR(100), + "instanceId" TEXT NOT NULL, + + CONSTRAINT "GenericSetting_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "GenericSetting_instanceId_key" ON "GenericSetting"("instanceId"); + +-- AddForeignKey +ALTER TABLE "GenericBot" ADD CONSTRAINT "GenericBot_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "GenericSetting" ADD CONSTRAINT "GenericSetting_botIdFallback_fkey" FOREIGN KEY ("botIdFallback") REFERENCES "GenericBot"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "GenericSetting" ADD CONSTRAINT "GenericSetting_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/postgresql-migrations/20240821194524_add_flowise_table/migration.sql b/prisma/postgresql-migrations/20240821194524_add_flowise_table/migration.sql new file mode 100644 index 00000000..e61141ae --- /dev/null +++ b/prisma/postgresql-migrations/20240821194524_add_flowise_table/migration.sql @@ -0,0 +1,57 @@ +-- CreateTable +CREATE TABLE "Flowise" ( + "id" TEXT NOT NULL, + "enabled" BOOLEAN NOT NULL DEFAULT true, + "description" VARCHAR(255), + "apiUrl" VARCHAR(255), + "apiKey" VARCHAR(255), + "expire" INTEGER DEFAULT 0, + "keywordFinish" VARCHAR(100), + "delayMessage" INTEGER, + "unknownMessage" VARCHAR(100), + "listeningFromMe" BOOLEAN DEFAULT false, + "stopBotFromMe" BOOLEAN DEFAULT false, + "keepOpen" BOOLEAN DEFAULT false, + "debounceTime" INTEGER, + "ignoreJids" JSONB, + "triggerType" "TriggerType", + "triggerOperator" "TriggerOperator", + "triggerValue" TEXT, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP NOT NULL, + "instanceId" TEXT NOT NULL, + + CONSTRAINT "Flowise_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "FlowiseSetting" ( + "id" TEXT NOT NULL, + "expire" INTEGER DEFAULT 0, + "keywordFinish" VARCHAR(100), + "delayMessage" INTEGER, + "unknownMessage" VARCHAR(100), + "listeningFromMe" BOOLEAN DEFAULT false, + "stopBotFromMe" BOOLEAN DEFAULT false, + "keepOpen" BOOLEAN DEFAULT false, + "debounceTime" INTEGER, + "ignoreJids" JSONB, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP NOT NULL, + "flowiseIdFallback" VARCHAR(100), + "instanceId" TEXT NOT NULL, + + CONSTRAINT "FlowiseSetting_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "FlowiseSetting_instanceId_key" ON "FlowiseSetting"("instanceId"); + +-- AddForeignKey +ALTER TABLE "Flowise" ADD CONSTRAINT "Flowise_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "FlowiseSetting" ADD CONSTRAINT "FlowiseSetting_flowiseIdFallback_fkey" FOREIGN KEY ("flowiseIdFallback") REFERENCES "Flowise"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "FlowiseSetting" ADD CONSTRAINT "FlowiseSetting_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/postgresql-migrations/20240824161333_add_type_on_integration_sessions/migration.sql b/prisma/postgresql-migrations/20240824161333_add_type_on_integration_sessions/migration.sql new file mode 100644 index 00000000..954c2560 --- /dev/null +++ b/prisma/postgresql-migrations/20240824161333_add_type_on_integration_sessions/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "IntegrationSession" ADD COLUMN "type" VARCHAR(100); diff --git a/prisma/postgresql-migrations/20240825130616_change_to_evolution_bot/migration.sql b/prisma/postgresql-migrations/20240825130616_change_to_evolution_bot/migration.sql new file mode 100644 index 00000000..11880ee3 --- /dev/null +++ b/prisma/postgresql-migrations/20240825130616_change_to_evolution_bot/migration.sql @@ -0,0 +1,79 @@ +/* + Warnings: + + - You are about to drop the `GenericBot` table. If the table is not empty, all the data it contains will be lost. + - You are about to drop the `GenericSetting` table. If the table is not empty, all the data it contains will be lost. + +*/ +-- DropForeignKey +ALTER TABLE "GenericBot" DROP CONSTRAINT "GenericBot_instanceId_fkey"; + +-- DropForeignKey +ALTER TABLE "GenericSetting" DROP CONSTRAINT "GenericSetting_botIdFallback_fkey"; + +-- DropForeignKey +ALTER TABLE "GenericSetting" DROP CONSTRAINT "GenericSetting_instanceId_fkey"; + +-- DropTable +DROP TABLE "GenericBot"; + +-- DropTable +DROP TABLE "GenericSetting"; + +-- CreateTable +CREATE TABLE "EvolutionBot" ( + "id" TEXT NOT NULL, + "enabled" BOOLEAN NOT NULL DEFAULT true, + "description" VARCHAR(255), + "apiUrl" VARCHAR(255), + "apiKey" VARCHAR(255), + "expire" INTEGER DEFAULT 0, + "keywordFinish" VARCHAR(100), + "delayMessage" INTEGER, + "unknownMessage" VARCHAR(100), + "listeningFromMe" BOOLEAN DEFAULT false, + "stopBotFromMe" BOOLEAN DEFAULT false, + "keepOpen" BOOLEAN DEFAULT false, + "debounceTime" INTEGER, + "ignoreJids" JSONB, + "triggerType" "TriggerType", + "triggerOperator" "TriggerOperator", + "triggerValue" TEXT, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP NOT NULL, + "instanceId" TEXT NOT NULL, + + CONSTRAINT "EvolutionBot_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "EvolutionBotSetting" ( + "id" TEXT NOT NULL, + "expire" INTEGER DEFAULT 0, + "keywordFinish" VARCHAR(100), + "delayMessage" INTEGER, + "unknownMessage" VARCHAR(100), + "listeningFromMe" BOOLEAN DEFAULT false, + "stopBotFromMe" BOOLEAN DEFAULT false, + "keepOpen" BOOLEAN DEFAULT false, + "debounceTime" INTEGER, + "ignoreJids" JSONB, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP NOT NULL, + "botIdFallback" VARCHAR(100), + "instanceId" TEXT NOT NULL, + + CONSTRAINT "EvolutionBotSetting_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "EvolutionBotSetting_instanceId_key" ON "EvolutionBotSetting"("instanceId"); + +-- AddForeignKey +ALTER TABLE "EvolutionBot" ADD CONSTRAINT "EvolutionBot_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "EvolutionBotSetting" ADD CONSTRAINT "EvolutionBotSetting_botIdFallback_fkey" FOREIGN KEY ("botIdFallback") REFERENCES "EvolutionBot"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "EvolutionBotSetting" ADD CONSTRAINT "EvolutionBotSetting_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/postgresql-migrations/20240828140837_add_is_on_whatsapp_table/migration.sql b/prisma/postgresql-migrations/20240828140837_add_is_on_whatsapp_table/migration.sql new file mode 100644 index 00000000..bb577211 --- /dev/null +++ b/prisma/postgresql-migrations/20240828140837_add_is_on_whatsapp_table/migration.sql @@ -0,0 +1,14 @@ +-- CreateTable +CREATE TABLE "is_on_whatsapp" ( + "id" TEXT NOT NULL, + "remote_jid" VARCHAR(100) NOT NULL, + "name" TEXT, + "jid_options" TEXT NOT NULL, + "created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP NOT NULL, + + CONSTRAINT "is_on_whatsapp_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "is_on_whatsapp_remote_jid_key" ON "is_on_whatsapp"("remote_jid"); diff --git a/prisma/postgresql-migrations/20240828141556_remove_name_column_from_on_whatsapp_table/migration.sql b/prisma/postgresql-migrations/20240828141556_remove_name_column_from_on_whatsapp_table/migration.sql new file mode 100644 index 00000000..de907df7 --- /dev/null +++ b/prisma/postgresql-migrations/20240828141556_remove_name_column_from_on_whatsapp_table/migration.sql @@ -0,0 +1,8 @@ +/* + Warnings: + + - You are about to drop the column `name` on the `is_on_whatsapp` table. All the data in the column will be lost. + +*/ +-- AlterTable +ALTER TABLE "is_on_whatsapp" DROP COLUMN "name"; diff --git a/prisma/postgresql-migrations/20240830193533_changed_table_case/migration.sql b/prisma/postgresql-migrations/20240830193533_changed_table_case/migration.sql new file mode 100644 index 00000000..209dd18c --- /dev/null +++ b/prisma/postgresql-migrations/20240830193533_changed_table_case/migration.sql @@ -0,0 +1,22 @@ +/* + Warnings: + + - You are about to drop the `is_on_whatsapp` table. If the table is not empty, all the data it contains will be lost. + +*/ +-- DropTable +DROP TABLE "is_on_whatsapp"; + +-- CreateTable +CREATE TABLE "IsOnWhatsapp" ( + "id" TEXT NOT NULL, + "remoteJid" VARCHAR(100) NOT NULL, + "jidOptions" TEXT NOT NULL, + "createdAt" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP NOT NULL, + + CONSTRAINT "IsOnWhatsapp_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "IsOnWhatsapp_remoteJid_key" ON "IsOnWhatsapp"("remoteJid"); diff --git a/prisma/postgresql-migrations/20240906202019_add_headers_on_webhook_config/migration.sql b/prisma/postgresql-migrations/20240906202019_add_headers_on_webhook_config/migration.sql new file mode 100644 index 00000000..1dc3ccbc --- /dev/null +++ b/prisma/postgresql-migrations/20240906202019_add_headers_on_webhook_config/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "Webhook" ADD COLUMN "headers" JSONB; diff --git a/prisma/migrations/migration_lock.toml b/prisma/postgresql-migrations/migration_lock.toml similarity index 100% rename from prisma/migrations/migration_lock.toml rename to prisma/postgresql-migrations/migration_lock.toml diff --git a/prisma/postgresql-schema.prisma b/prisma/postgresql-schema.prisma index 49bddc76..738140ba 100644 --- a/prisma/postgresql-schema.prisma +++ b/prisma/postgresql-schema.prisma @@ -27,7 +27,7 @@ enum DeviceMessage { desktop } -enum TypebotSessionStatus { +enum SessionStatus { opened closed paused @@ -37,6 +37,7 @@ enum TriggerType { all keyword none + advanced } enum TriggerOperator { @@ -60,44 +61,49 @@ enum DifyBotType { } model Instance { - id String @id @default(cuid()) - name String @unique @db.VarChar(255) - connectionStatus InstanceConnectionStatus @default(open) - ownerJid String? @db.VarChar(100) - profileName String? @db.VarChar(100) - profilePicUrl String? @db.VarChar(500) - integration String? @db.VarChar(100) - number String? @db.VarChar(100) - businessId String? @db.VarChar(100) - token String? @db.VarChar(255) - clientName String? @db.VarChar(100) - createdAt DateTime? @default(now()) @db.Timestamp - updatedAt DateTime? @updatedAt @db.Timestamp - Chat Chat[] - Contact Contact[] - Message Message[] - Webhook Webhook? - Chatwoot Chatwoot? - Label Label[] - Proxy Proxy? - Setting Setting? - Rabbitmq Rabbitmq? - Sqs Sqs? - Websocket Websocket? - Typebot Typebot[] - Session Session? - MessageUpdate MessageUpdate[] - TypebotSession TypebotSession[] - TypebotSetting TypebotSetting? - Media Media[] - OpenaiCreds OpenaiCreds[] - OpenaiBot OpenaiBot[] - OpenaiSession OpenaiSession[] - OpenaiSetting OpenaiSetting? - Template Template[] - Dify Dify[] - DifySession DifySession[] - DifySetting DifySetting? + id String @id @default(cuid()) + name String @unique @db.VarChar(255) + connectionStatus InstanceConnectionStatus @default(open) + ownerJid String? @db.VarChar(100) + profileName String? @db.VarChar(100) + profilePicUrl String? @db.VarChar(500) + integration String? @db.VarChar(100) + number String? @db.VarChar(100) + businessId String? @db.VarChar(100) + token String? @db.VarChar(255) + clientName String? @db.VarChar(100) + disconnectionReasonCode Int? @db.Integer + disconnectionObject Json? @db.JsonB + disconnectionAt DateTime? @db.Timestamp + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime? @updatedAt @db.Timestamp + Chat Chat[] + Contact Contact[] + Message Message[] + Webhook Webhook? + Chatwoot Chatwoot? + Label Label[] + Proxy Proxy? + Setting Setting? + Rabbitmq Rabbitmq? + Sqs Sqs? + Websocket Websocket? + Typebot Typebot[] + Session Session? + MessageUpdate MessageUpdate[] + TypebotSetting TypebotSetting? + Media Media[] + OpenaiCreds OpenaiCreds[] + OpenaiBot OpenaiBot[] + OpenaiSetting OpenaiSetting? + Template Template[] + Dify Dify[] + DifySetting DifySetting? + integrationSessions IntegrationSession[] + EvolutionBot EvolutionBot[] + EvolutionBotSetting EvolutionBotSetting? + Flowise Flowise[] + FlowiseSetting FlowiseSetting? } model Session { @@ -111,6 +117,7 @@ model Session { model Chat { id String @id @default(cuid()) remoteJid String @db.VarChar(100) + name String? @db.VarChar(100) labels Json? @db.JsonB createdAt DateTime? @default(now()) @db.Timestamp updatedAt DateTime? @updatedAt @db.Timestamp @@ -127,6 +134,8 @@ model Contact { updatedAt DateTime? @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String + + @@unique([remoteJid, instanceId]) } model Message { @@ -146,15 +155,12 @@ model Message { chatwootIsRead Boolean? @db.Boolean Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String - typebotSessionId String? MessageUpdate MessageUpdate[] - TypebotSession TypebotSession? @relation(fields: [typebotSessionId], references: [id]) Media Media? - OpenaiSession OpenaiSession? @relation(fields: [openaiSessionId], references: [id]) - openaiSessionId String? webhookUrl String? @db.VarChar(500) - DifySession DifySession? @relation(fields: [difySessionId], references: [id]) - difySessionId String? + + sessionId String? + session IntegrationSession? @relation(fields: [sessionId], references: [id]) } model MessageUpdate { @@ -174,6 +180,7 @@ model MessageUpdate { model Webhook { id String @id @default(cuid()) url String @db.VarChar(500) + headers Json? @db.JsonB enabled Boolean? @default(true) @db.Boolean events Json? @db.JsonB webhookByEvents Boolean? @default(false) @db.Boolean @@ -202,6 +209,7 @@ model Chatwoot { daysLimitImportMessages Int? @db.Integer organization String? @db.VarChar(100) logo String? @db.VarChar(500) + ignoreJids Json? createdAt DateTime? @default(now()) @db.Timestamp updatedAt DateTime @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) @@ -210,7 +218,7 @@ model Chatwoot { model Label { id String @id @default(cuid()) - labelId String? @unique @db.VarChar(100) + labelId String? @db.VarChar(100) name String @db.VarChar(100) color String @db.VarChar(100) predefinedId String? @db.VarChar(100) @@ -218,6 +226,8 @@ model Label { updatedAt DateTime @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String + + @@unique([labelId, instanceId]) } model Proxy { @@ -301,27 +311,9 @@ model Typebot { triggerValue String? Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String - sessions TypebotSession[] TypebotSetting TypebotSetting[] } -model TypebotSession { - id String @id @default(cuid()) - remoteJid String @db.VarChar(100) - pushName String? @db.VarChar(100) - sessionId String @db.VarChar(100) - status TypebotSessionStatus - prefilledVariables Json? @db.JsonB - awaitUser Boolean @default(false) @db.Boolean - createdAt DateTime? @default(now()) @db.Timestamp - updatedAt DateTime @updatedAt @db.Timestamp - Typebot Typebot @relation(fields: [typebotId], references: [id], onDelete: Cascade) - typebotId String - Message Message[] - Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) - instanceId String -} - model TypebotSetting { id String @id @default(cuid()) expire Int? @default(0) @db.Integer @@ -371,6 +363,7 @@ model OpenaiBot { description String? @db.VarChar(255) botType OpenaiBotType assistantId String? @db.VarChar(255) + functionUrl String? @db.VarChar(500) model String? @db.VarChar(100) systemMessages Json? @db.JsonB assistantMessages Json? @db.JsonB @@ -394,23 +387,26 @@ model OpenaiBot { openaiCredsId String Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String - OpenaiSession OpenaiSession[] OpenaiSetting OpenaiSetting[] } -model OpenaiSession { - id String @id @default(cuid()) - sessionId String @db.VarChar(255) - remoteJid String @db.VarChar(100) - status TypebotSessionStatus - awaitUser Boolean @default(false) @db.Boolean - createdAt DateTime? @default(now()) @db.Timestamp - updatedAt DateTime @updatedAt @db.Timestamp - OpenaiBot OpenaiBot @relation(fields: [openaiBotId], references: [id], onDelete: Cascade) - openaiBotId String - Message Message[] - Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) - instanceId String +model IntegrationSession { + id String @id @default(cuid()) + sessionId String @db.VarChar(255) + remoteJid String @db.VarChar(100) + pushName String? + status SessionStatus + awaitUser Boolean @default(false) @db.Boolean + context Json? + type String? @db.VarChar(100) + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Message Message[] + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + parameters Json? @db.JsonB + + botId String? } model OpenaiSetting { @@ -470,25 +466,9 @@ model Dify { updatedAt DateTime @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String - DifySession DifySession[] DifySetting DifySetting[] } -model DifySession { - id String @id @default(cuid()) - sessionId String @db.VarChar(255) - remoteJid String @db.VarChar(100) - status TypebotSessionStatus - awaitUser Boolean @default(false) @db.Boolean - createdAt DateTime? @default(now()) @db.Timestamp - updatedAt DateTime @updatedAt @db.Timestamp - Dify Dify @relation(fields: [difyId], references: [id], onDelete: Cascade) - difyId String - Message Message[] - Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) - instanceId String -} - model DifySetting { id String @id @default(cuid()) expire Int? @default(0) @db.Integer @@ -507,3 +487,99 @@ model DifySetting { Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String @unique } + +model EvolutionBot { + id String @id @default(cuid()) + enabled Boolean @default(true) @db.Boolean + description String? @db.VarChar(255) + apiUrl String? @db.VarChar(255) + apiKey String? @db.VarChar(255) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + EvolutionBotSetting EvolutionBotSetting[] +} + +model EvolutionBotSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback EvolutionBot? @relation(fields: [botIdFallback], references: [id]) + botIdFallback String? @db.VarChar(100) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model Flowise { + id String @id @default(cuid()) + enabled Boolean @default(true) @db.Boolean + description String? @db.VarChar(255) + apiUrl String? @db.VarChar(255) + apiKey String? @db.VarChar(255) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + FlowiseSetting FlowiseSetting[] +} + +model FlowiseSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback Flowise? @relation(fields: [flowiseIdFallback], references: [id]) + flowiseIdFallback String? @db.VarChar(100) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model IsOnWhatsapp { + id String @id @default(cuid()) + remoteJid String @unique @db.VarChar(100) + jidOptions String + createdAt DateTime @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp +} diff --git a/runWithProvider.js b/runWithProvider.js new file mode 100644 index 00000000..8fe1af0d --- /dev/null +++ b/runWithProvider.js @@ -0,0 +1,22 @@ +const dotenv = require('dotenv'); +const { execSync } = require('child_process'); +dotenv.config(); + +const { DATABASE_PROVIDER } = process.env; + +if (!DATABASE_PROVIDER) { + console.error('DATABASE_PROVIDER is not set in the .env file'); + process.exit(1); +} + +const command = process.argv + .slice(2) + .join(' ') + .replace(/\DATABASE_PROVIDER/g, DATABASE_PROVIDER); + +try { + execSync(command, { stdio: 'inherit' }); +} catch (error) { + console.error(`Error executing command: ${command}`); + process.exit(1); +} diff --git a/src/api/abstract/abstract.repository.ts b/src/api/abstract/abstract.repository.ts index a5b7a841..16bf81f9 100644 --- a/src/api/abstract/abstract.repository.ts +++ b/src/api/abstract/abstract.repository.ts @@ -1,9 +1,8 @@ +import { ConfigService, Database } from '@config/env.config'; +import { ROOT_DIR } from '@config/path.config'; import { existsSync, mkdirSync, writeFileSync } from 'fs'; import { join } from 'path'; -import { ConfigService, Database } from '../../config/env.config'; -import { ROOT_DIR } from '../../config/path.config'; - export type IInsert = { insertCount: number }; export interface IRepository { diff --git a/src/api/abstract/abstract.router.ts b/src/api/abstract/abstract.router.ts index 18770ffa..e8449a8c 100644 --- a/src/api/abstract/abstract.router.ts +++ b/src/api/abstract/abstract.router.ts @@ -1,14 +1,13 @@ import 'express-async-errors'; +import { GetParticipant, GroupInvite } from '@api/dto/group.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { Logger } from '@config/logger.config'; +import { BadRequestException } from '@exceptions'; import { Request } from 'express'; import { JSONSchema7 } from 'json-schema'; import { validate } from 'jsonschema'; -import { Logger } from '../../config/logger.config'; -import { BadRequestException } from '../../exceptions'; -import { GetParticipant, GroupInvite } from '../dto/group.dto'; -import { InstanceDto } from '../dto/instance.dto'; - type DataValidate = { request: Request; schema: JSONSchema7; diff --git a/src/api/controllers/chat.controller.ts b/src/api/controllers/chat.controller.ts index 044a9833..207d8ba5 100644 --- a/src/api/controllers/chat.controller.ts +++ b/src/api/controllers/chat.controller.ts @@ -1,5 +1,3 @@ -import { Contact, Message, MessageUpdate } from '@prisma/client'; - import { ArchiveChatDto, BlockUserDto, @@ -15,10 +13,11 @@ import { SendPresenceDto, UpdateMessageDto, WhatsAppNumberDto, -} from '../dto/chat.dto'; -import { InstanceDto } from '../dto/instance.dto'; -import { Query } from '../repository/repository.service'; -import { WAMonitoringService } from '../services/monitor.service'; +} from '@api/dto/chat.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { Query } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Contact, Message, MessageUpdate } from '@prisma/client'; export class ChatController { constructor(private readonly waMonitor: WAMonitoringService) {} diff --git a/src/api/controllers/group.controller.ts b/src/api/controllers/group.controller.ts index 0e3bdf4c..ebe7c036 100644 --- a/src/api/controllers/group.controller.ts +++ b/src/api/controllers/group.controller.ts @@ -11,9 +11,9 @@ import { GroupToggleEphemeralDto, GroupUpdateParticipantDto, GroupUpdateSettingDto, -} from '../dto/group.dto'; -import { InstanceDto } from '../dto/instance.dto'; -import { WAMonitoringService } from '../services/monitor.service'; +} from '@api/dto/group.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { WAMonitoringService } from '@api/services/monitor.service'; export class GroupController { constructor(private readonly waMonitor: WAMonitoringService) {} diff --git a/src/api/controllers/instance.controller.ts b/src/api/controllers/instance.controller.ts index 302b598d..b04edddd 100644 --- a/src/api/controllers/instance.controller.ts +++ b/src/api/controllers/instance.controller.ts @@ -1,27 +1,20 @@ -import { JsonValue } from '@prisma/client/runtime/library'; +import { InstanceDto, SetPresenceDto } from '@api/dto/instance.dto'; +import { ChatwootService } from '@api/integrations/chatbot/chatwoot/services/chatwoot.service'; +import { ProviderFiles } from '@api/provider/sessions'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { channelController, eventManager } from '@api/server.module'; +import { CacheService } from '@api/services/cache.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { SettingsService } from '@api/services/settings.service'; +import { Events, Integration, wa } from '@api/types/wa.types'; +import { Auth, Chatwoot, ConfigService, HttpServer, WaBusiness } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { BadRequestException, InternalServerErrorException, UnauthorizedException } from '@exceptions'; import { delay } from 'baileys'; import { isArray, isURL } from 'class-validator'; import EventEmitter2 from 'eventemitter2'; import { v4 } from 'uuid'; -import { Auth, Chatwoot, ConfigService, HttpServer, WaBusiness } from '../../config/env.config'; -import { Logger } from '../../config/logger.config'; -import { BadRequestException, InternalServerErrorException, UnauthorizedException } from '../../exceptions'; -import { InstanceDto, SetPresenceDto } from '../dto/instance.dto'; -import { ChatwootService } from '../integrations/chatwoot/services/chatwoot.service'; -import { RabbitmqService } from '../integrations/rabbitmq/services/rabbitmq.service'; -import { SqsService } from '../integrations/sqs/services/sqs.service'; -import { WebsocketService } from '../integrations/websocket/services/websocket.service'; -import { ProviderFiles } from '../provider/sessions'; -import { PrismaRepository } from '../repository/repository.service'; -import { AuthService } from '../services/auth.service'; -import { CacheService } from '../services/cache.service'; -import { BaileysStartupService } from '../services/channels/whatsapp.baileys.service'; -import { BusinessStartupService } from '../services/channels/whatsapp.business.service'; -import { WAMonitoringService } from '../services/monitor.service'; -import { SettingsService } from '../services/settings.service'; -import { WebhookService } from '../services/webhook.service'; -import { Events, Integration, wa } from '../types/wa.types'; import { ProxyController } from './proxy.controller'; export class InstanceController { @@ -30,13 +23,8 @@ export class InstanceController { private readonly configService: ConfigService, private readonly prismaRepository: PrismaRepository, private readonly eventEmitter: EventEmitter2, - private readonly authService: AuthService, - private readonly webhookService: WebhookService, private readonly chatwootService: ChatwootService, private readonly settingsService: SettingsService, - private readonly websocketService: WebsocketService, - private readonly rabbitmqService: RabbitmqService, - private readonly sqsService: SqsService, private readonly proxyService: ProxyController, private readonly cache: CacheService, private readonly chatwootCache: CacheService, @@ -44,321 +32,70 @@ export class InstanceController { private readonly providerFiles: ProviderFiles, ) {} - private readonly logger = new Logger(InstanceController.name); + private readonly logger = new Logger('InstanceController'); - public async createInstance({ - instanceName, - qrcode, - number, - integration, - token, - rejectCall, - msgCall, - groupsIgnore, - alwaysOnline, - readMessages, - readStatus, - syncFullHistory, - proxyHost, - proxyPort, - proxyProtocol, - proxyUsername, - proxyPassword, - webhookUrl, - webhookByEvents, - webhookBase64, - webhookEvents, - websocketEnabled, - websocketEvents, - rabbitmqEnabled, - rabbitmqEvents, - sqsEnabled, - sqsEvents, - chatwootAccountId, - chatwootToken, - chatwootUrl, - chatwootSignMsg, - chatwootReopenConversation, - chatwootConversationPending, - chatwootImportContacts, - chatwootNameInbox, - chatwootMergeBrazilContacts, - chatwootImportMessages, - chatwootDaysLimitImportMessages, - chatwootOrganization, - chatwootLogo, - businessId, - }: InstanceDto) { + public async createInstance(instanceData: InstanceDto) { try { - // if (token) await this.authService.checkDuplicateToken(token); + const instance = channelController.init(instanceData, { + configService: this.configService, + eventEmitter: this.eventEmitter, + prismaRepository: this.prismaRepository, + cache: this.cache, + chatwootCache: this.chatwootCache, + baileysCache: this.baileysCache, + providerFiles: this.providerFiles, + }); - if (!token && integration === Integration.WHATSAPP_BUSINESS) { - throw new BadRequestException('token is required'); - } - - let instance: BaileysStartupService | BusinessStartupService; - if (integration === Integration.WHATSAPP_BUSINESS) { - instance = new BusinessStartupService( - this.configService, - this.eventEmitter, - this.prismaRepository, - this.cache, - this.chatwootCache, - this.baileysCache, - this.providerFiles, - ); - } else { - instance = new BaileysStartupService( - this.configService, - this.eventEmitter, - this.prismaRepository, - this.cache, - this.chatwootCache, - this.baileysCache, - this.providerFiles, - ); + if (!instance) { + throw new BadRequestException('Invalid integration'); } const instanceId = v4(); + instanceData.instanceId = instanceId; + let hash: string; - if (!token) hash = v4().toUpperCase(); - else hash = token; + if (!instanceData.token) hash = v4().toUpperCase(); + else hash = instanceData.token; - await this.waMonitor.saveInstance({ instanceId, integration, instanceName, hash, number, businessId }); - - instance.setInstance({ - instanceName, + await this.waMonitor.saveInstance({ instanceId, - integration, - token: hash, - number, - businessId, + integration: instanceData.integration, + instanceName: instanceData.instanceName, + hash, + number: instanceData.number, + businessId: instanceData.businessId, + status: instanceData.status, }); - instance.sendDataWebhook(Events.INSTANCE_CREATE, { - instanceName, - instanceId: instanceId, + instance.setInstance({ + instanceName: instanceData.instanceName, + instanceId, + integration: instanceData.integration, + token: hash, + number: instanceData.number, + businessId: instanceData.businessId, }); this.waMonitor.waInstances[instance.instanceName] = instance; this.waMonitor.delInstanceTime(instance.instanceName); - let getWebhookEvents: string[]; + // set events + await eventManager.setInstance(instance.instanceName, instanceData); - if (webhookUrl) { - if (!isURL(webhookUrl, { require_tld: false })) { - throw new BadRequestException('Invalid "url" property in webhook'); - } + instance.sendDataWebhook(Events.INSTANCE_CREATE, { + instanceName: instanceData.instanceName, + instanceId: instanceId, + }); - try { - let newEvents: string[] = []; - if (webhookEvents.length === 0) { - newEvents = [ - 'APPLICATION_STARTUP', - 'QRCODE_UPDATED', - 'MESSAGES_SET', - 'MESSAGES_UPSERT', - 'MESSAGES_EDITED', - 'MESSAGES_UPDATE', - 'MESSAGES_DELETE', - 'SEND_MESSAGE', - 'CONTACTS_SET', - 'CONTACTS_UPSERT', - 'CONTACTS_UPDATE', - 'PRESENCE_UPDATE', - 'CHATS_SET', - 'CHATS_UPSERT', - 'CHATS_UPDATE', - 'CHATS_DELETE', - 'GROUPS_UPSERT', - 'GROUP_UPDATE', - 'GROUP_PARTICIPANTS_UPDATE', - 'CONNECTION_UPDATE', - 'LABELS_EDIT', - 'LABELS_ASSOCIATION', - 'CALL', - 'TYPEBOT_START', - 'TYPEBOT_CHANGE_STATUS', - ]; - } else { - newEvents = webhookEvents; - } - this.webhookService.create(instance, { - enabled: true, - url: webhookUrl, - events: newEvents, - webhookByEvents, - webhookBase64, - }); - - const webhookEventsJson: JsonValue = (await this.webhookService.find(instance)).events; - - getWebhookEvents = Array.isArray(webhookEventsJson) ? webhookEventsJson.map((event) => String(event)) : []; - } catch (error) { - this.logger.log(error); - } - } - - let getWebsocketEvents: string[]; - - if (websocketEnabled) { - try { - let newEvents: string[] = []; - if (websocketEvents.length === 0) { - newEvents = [ - 'APPLICATION_STARTUP', - 'QRCODE_UPDATED', - 'MESSAGES_SET', - 'MESSAGES_UPSERT', - 'MESSAGES_EDITED', - 'MESSAGES_UPDATE', - 'MESSAGES_DELETE', - 'SEND_MESSAGE', - 'CONTACTS_SET', - 'CONTACTS_UPSERT', - 'CONTACTS_UPDATE', - 'PRESENCE_UPDATE', - 'CHATS_SET', - 'CHATS_UPSERT', - 'CHATS_UPDATE', - 'CHATS_DELETE', - 'GROUPS_UPSERT', - 'GROUP_UPDATE', - 'GROUP_PARTICIPANTS_UPDATE', - 'CONNECTION_UPDATE', - 'LABELS_EDIT', - 'LABELS_ASSOCIATION', - 'CALL', - 'TYPEBOT_START', - 'TYPEBOT_CHANGE_STATUS', - ]; - } else { - newEvents = websocketEvents; - } - this.websocketService.create(instance, { - enabled: true, - events: newEvents, - }); - - const websocketEventsJson: JsonValue = (await this.websocketService.find(instance)).events; - - getWebsocketEvents = Array.isArray(websocketEventsJson) - ? websocketEventsJson.map((event) => String(event)) - : []; - } catch (error) { - this.logger.log(error); - } - } - - let getRabbitmqEvents: string[]; - - if (rabbitmqEnabled) { - try { - let newEvents: string[] = []; - if (rabbitmqEvents.length === 0) { - newEvents = [ - 'APPLICATION_STARTUP', - 'QRCODE_UPDATED', - 'MESSAGES_SET', - 'MESSAGES_UPSERT', - 'MESSAGES_EDITED', - 'MESSAGES_UPDATE', - 'MESSAGES_DELETE', - 'SEND_MESSAGE', - 'CONTACTS_SET', - 'CONTACTS_UPSERT', - 'CONTACTS_UPDATE', - 'PRESENCE_UPDATE', - 'CHATS_SET', - 'CHATS_UPSERT', - 'CHATS_UPDATE', - 'CHATS_DELETE', - 'GROUPS_UPSERT', - 'GROUP_UPDATE', - 'GROUP_PARTICIPANTS_UPDATE', - 'CONNECTION_UPDATE', - 'LABELS_EDIT', - 'LABELS_ASSOCIATION', - 'CALL', - 'TYPEBOT_START', - 'TYPEBOT_CHANGE_STATUS', - ]; - } else { - newEvents = rabbitmqEvents; - } - this.rabbitmqService.create(instance, { - enabled: true, - events: newEvents, - }); - - const rabbitmqEventsJson: JsonValue = (await this.rabbitmqService.find(instance)).events; - - getRabbitmqEvents = Array.isArray(rabbitmqEventsJson) ? rabbitmqEventsJson.map((event) => String(event)) : []; - } catch (error) { - this.logger.log(error); - } - } - - let getSqsEvents: string[]; - - if (sqsEnabled) { - try { - let newEvents: string[] = []; - if (sqsEvents.length === 0) { - newEvents = [ - 'APPLICATION_STARTUP', - 'QRCODE_UPDATED', - 'MESSAGES_SET', - 'MESSAGES_UPSERT', - 'MESSAGES_EDITED', - 'MESSAGES_UPDATE', - 'MESSAGES_DELETE', - 'SEND_MESSAGE', - 'CONTACTS_SET', - 'CONTACTS_UPSERT', - 'CONTACTS_UPDATE', - 'PRESENCE_UPDATE', - 'CHATS_SET', - 'CHATS_UPSERT', - 'CHATS_UPDATE', - 'CHATS_DELETE', - 'GROUPS_UPSERT', - 'GROUP_UPDATE', - 'GROUP_PARTICIPANTS_UPDATE', - 'CONNECTION_UPDATE', - 'LABELS_EDIT', - 'LABELS_ASSOCIATION', - 'CALL', - 'TYPEBOT_START', - 'TYPEBOT_CHANGE_STATUS', - ]; - } else { - newEvents = sqsEvents; - } - this.sqsService.create(instance, { - enabled: true, - events: newEvents, - }); - - const sqsEventsJson: JsonValue = (await this.sqsService.find(instance)).events; - - getSqsEvents = Array.isArray(sqsEventsJson) ? sqsEventsJson.map((event) => String(event)) : []; - - // sqsEvents = (await this.sqsService.find(instance)).events; - } catch (error) { - this.logger.log(error); - } - } - - if (proxyHost && proxyPort && proxyProtocol) { + if (instanceData.proxyHost && instanceData.proxyPort && instanceData.proxyProtocol) { const testProxy = await this.proxyService.testProxy({ - host: proxyHost, - port: proxyPort, - protocol: proxyProtocol, - username: proxyUsername, - password: proxyPassword, + host: instanceData.proxyHost, + port: instanceData.proxyPort, + protocol: instanceData.proxyProtocol, + username: instanceData.proxyUsername, + password: instanceData.proxyPassword, }); if (!testProxy) { throw new BadRequestException('Invalid proxy'); @@ -366,22 +103,22 @@ export class InstanceController { await this.proxyService.createProxy(instance, { enabled: true, - host: proxyHost, - port: proxyPort, - protocol: proxyProtocol, - username: proxyUsername, - password: proxyPassword, + host: instanceData.proxyHost, + port: instanceData.proxyPort, + protocol: instanceData.proxyProtocol, + username: instanceData.proxyUsername, + password: instanceData.proxyPassword, }); } const settings: wa.LocalSettings = { - rejectCall: rejectCall === true, - msgCall: msgCall || '', - groupsIgnore: groupsIgnore === true, - alwaysOnline: alwaysOnline === true, - readMessages: readMessages === true, - readStatus: readStatus === true, - syncFullHistory: syncFullHistory === true, + rejectCall: instanceData.rejectCall === true, + msgCall: instanceData.msgCall || '', + groupsIgnore: instanceData.groupsIgnore === true, + alwaysOnline: instanceData.alwaysOnline === true, + readMessages: instanceData.readMessages === true, + readStatus: instanceData.readStatus === true, + syncFullHistory: instanceData.syncFullHistory === true, }; await this.settingsService.create(instance, settings); @@ -389,8 +126,8 @@ export class InstanceController { let webhookWaBusiness = null, accessTokenWaBusiness = ''; - if (integration === Integration.WHATSAPP_BUSINESS) { - if (!number) { + if (instanceData.integration === Integration.WHATSAPP_BUSINESS) { + if (!instanceData.number) { throw new BadRequestException('number is required'); } const urlServer = this.configService.get('SERVER').URL; @@ -398,11 +135,11 @@ export class InstanceController { accessTokenWaBusiness = this.configService.get('WA_BUSINESS').TOKEN_WEBHOOK; } - if (!chatwootAccountId || !chatwootToken || !chatwootUrl) { + if (!instanceData.chatwootAccountId || !instanceData.chatwootToken || !instanceData.chatwootUrl) { let getQrcode: wa.QrCode; - if (qrcode && integration === Integration.WHATSAPP_BAILEYS) { - await instance.connectToWhatsapp(number); + if (instanceData.qrcode && instanceData.integration === Integration.WHATSAPP_BAILEYS) { + await instance.connectToWhatsapp(instanceData.number); await delay(5000); getQrcode = instance.qrCode; } @@ -411,29 +148,26 @@ export class InstanceController { instance: { instanceName: instance.instanceName, instanceId: instanceId, - integration: integration, + integration: instanceData.integration, webhookWaBusiness, accessTokenWaBusiness, - status: 'created', + status: instance.connectionStatus.state, }, hash, webhook: { - webhookUrl, - webhookByEvents, - webhookBase64, - events: getWebhookEvents, + webhookUrl: instanceData?.webhook?.url, + webhookHeaders: instanceData?.webhook?.headers, + webhookByEvents: instanceData?.webhook?.byEvents, + webhookBase64: instanceData?.webhook?.base64, }, websocket: { - enabled: websocketEnabled, - events: getWebsocketEvents, + enabled: instanceData?.websocket?.enabled, }, rabbitmq: { - enabled: rabbitmqEnabled, - events: getRabbitmqEvents, + enabled: instanceData?.rabbitmq?.enabled, }, sqs: { - enabled: sqsEnabled, - events: getSqsEvents, + enabled: instanceData?.sqs?.enabled, }, settings, qrcode: getQrcode, @@ -445,31 +179,31 @@ export class InstanceController { if (!this.configService.get('CHATWOOT').ENABLED) throw new BadRequestException('Chatwoot is not enabled'); - if (!chatwootAccountId) { + if (!instanceData.chatwootAccountId) { throw new BadRequestException('accountId is required'); } - if (!chatwootToken) { + if (!instanceData.chatwootToken) { throw new BadRequestException('token is required'); } - if (!chatwootUrl) { + if (!instanceData.chatwootUrl) { throw new BadRequestException('url is required'); } - if (!isURL(chatwootUrl, { require_tld: false })) { + if (!isURL(instanceData.chatwootUrl, { require_tld: false })) { throw new BadRequestException('Invalid "url" property in chatwoot'); } - if (chatwootSignMsg !== true && chatwootSignMsg !== false) { + if (instanceData.chatwootSignMsg !== true && instanceData.chatwootSignMsg !== false) { throw new BadRequestException('signMsg is required'); } - if (chatwootReopenConversation !== true && chatwootReopenConversation !== false) { + if (instanceData.chatwootReopenConversation !== true && instanceData.chatwootReopenConversation !== false) { throw new BadRequestException('reopenConversation is required'); } - if (chatwootConversationPending !== true && chatwootConversationPending !== false) { + if (instanceData.chatwootConversationPending !== true && instanceData.chatwootConversationPending !== false) { throw new BadRequestException('conversationPending is required'); } @@ -478,21 +212,21 @@ export class InstanceController { try { this.chatwootService.create(instance, { enabled: true, - accountId: chatwootAccountId, - token: chatwootToken, - url: chatwootUrl, - signMsg: chatwootSignMsg || false, - nameInbox: chatwootNameInbox ?? instance.instanceName.split('-cwId-')[0], - number, - reopenConversation: chatwootReopenConversation || false, - conversationPending: chatwootConversationPending || false, - importContacts: chatwootImportContacts ?? true, - mergeBrazilContacts: chatwootMergeBrazilContacts ?? false, - importMessages: chatwootImportMessages ?? true, - daysLimitImportMessages: chatwootDaysLimitImportMessages ?? 60, - organization: chatwootOrganization, - logo: chatwootLogo, - autoCreate: true, + accountId: instanceData.chatwootAccountId, + token: instanceData.chatwootToken, + url: instanceData.chatwootUrl, + signMsg: instanceData.chatwootSignMsg || false, + nameInbox: instanceData.chatwootNameInbox ?? instance.instanceName.split('-cwId-')[0], + number: instanceData.number, + reopenConversation: instanceData.chatwootReopenConversation || false, + conversationPending: instanceData.chatwootConversationPending || false, + importContacts: instanceData.chatwootImportContacts ?? true, + mergeBrazilContacts: instanceData.chatwootMergeBrazilContacts ?? false, + importMessages: instanceData.chatwootImportMessages ?? true, + daysLimitImportMessages: instanceData.chatwootDaysLimitImportMessages ?? 60, + organization: instanceData.chatwootOrganization, + logo: instanceData.chatwootLogo, + autoCreate: instanceData.chatwootAutoCreate !== false, }); } catch (error) { this.logger.log(error); @@ -502,49 +236,47 @@ export class InstanceController { instance: { instanceName: instance.instanceName, instanceId: instanceId, - integration: integration, + integration: instanceData.integration, webhookWaBusiness, accessTokenWaBusiness, - status: 'created', + status: instance.connectionStatus.state, }, hash, webhook: { - webhookUrl, - webhookByEvents, - webhookBase64, - events: getWebhookEvents, + webhookUrl: instanceData?.webhook?.url, + webhookHeaders: instanceData?.webhook?.headers, + webhookByEvents: instanceData?.webhook?.byEvents, + webhookBase64: instanceData?.webhook?.base64, }, websocket: { - enabled: websocketEnabled, - events: getWebsocketEvents, + enabled: instanceData?.websocket?.enabled, }, rabbitmq: { - enabled: rabbitmqEnabled, - events: getRabbitmqEvents, + enabled: instanceData?.rabbitmq?.enabled, }, sqs: { - enabled: sqsEnabled, - events: getSqsEvents, + enabled: instanceData?.sqs?.enabled, }, settings, chatwoot: { enabled: true, - accountId: chatwootAccountId, - token: chatwootToken, - url: chatwootUrl, - signMsg: chatwootSignMsg || false, - reopenConversation: chatwootReopenConversation || false, - conversationPending: chatwootConversationPending || false, - mergeBrazilContacts: chatwootMergeBrazilContacts ?? false, - importContacts: chatwootImportContacts ?? true, - importMessages: chatwootImportMessages ?? true, - daysLimitImportMessages: chatwootDaysLimitImportMessages || 60, - number, - nameInbox: chatwootNameInbox ?? instance.instanceName, + accountId: instanceData.chatwootAccountId, + token: instanceData.chatwootToken, + url: instanceData.chatwootUrl, + signMsg: instanceData.chatwootSignMsg || false, + reopenConversation: instanceData.chatwootReopenConversation || false, + conversationPending: instanceData.chatwootConversationPending || false, + mergeBrazilContacts: instanceData.chatwootMergeBrazilContacts ?? false, + importContacts: instanceData.chatwootImportContacts ?? true, + importMessages: instanceData.chatwootImportMessages ?? true, + daysLimitImportMessages: instanceData.chatwootDaysLimitImportMessages || 60, + number: instanceData.number, + nameInbox: instanceData.chatwootNameInbox ?? instance.instanceName, webhookUrl: `${urlServer}/chatwoot/webhook/${encodeURIComponent(instance.instanceName)}`, }, }; } catch (error) { + this.waMonitor.deleteInstance(instanceData.instanceName); this.logger.error(isArray(error.message) ? error.message[0] : error.message); throw new BadRequestException(isArray(error.message) ? error.message[0] : error.message); } @@ -570,7 +302,7 @@ export class InstanceController { if (state == 'close') { await instance.connectToWhatsapp(number); - await delay(5000); + await delay(2000); return instance.qrCode; } @@ -606,6 +338,7 @@ export class InstanceController { instance.client?.end(new Error('restart')); return await this.connectToWhatsapp({ instanceName }); } else if (state == 'connecting') { + instance.client?.ws?.close(); instance.client?.end(new Error('restart')); return await this.connectToWhatsapp({ instanceName }); } @@ -682,7 +415,6 @@ export class InstanceController { } try { const waInstances = this.waMonitor.waInstances[instanceName]; - waInstances?.removeRabbitmqQueues(); if (this.configService.get('CHATWOOT').ENABLED) waInstances?.clearCacheChatwoot(); if (instance.state === 'connecting') { diff --git a/src/api/controllers/label.controller.ts b/src/api/controllers/label.controller.ts index 669af147..2df112f7 100644 --- a/src/api/controllers/label.controller.ts +++ b/src/api/controllers/label.controller.ts @@ -1,6 +1,6 @@ -import { InstanceDto } from '../dto/instance.dto'; -import { HandleLabelDto } from '../dto/label.dto'; -import { WAMonitoringService } from '../services/monitor.service'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { HandleLabelDto } from '@api/dto/label.dto'; +import { WAMonitoringService } from '@api/services/monitor.service'; export class LabelController { constructor(private readonly waMonitor: WAMonitoringService) {} diff --git a/src/api/controllers/proxy.controller.ts b/src/api/controllers/proxy.controller.ts index 9dbc4510..3fcde3bb 100644 --- a/src/api/controllers/proxy.controller.ts +++ b/src/api/controllers/proxy.controller.ts @@ -1,13 +1,12 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { ProxyDto } from '@api/dto/proxy.dto'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { ProxyService } from '@api/services/proxy.service'; +import { Logger } from '@config/logger.config'; +import { BadRequestException, NotFoundException } from '@exceptions'; +import { makeProxyAgent } from '@utils/makeProxyAgent'; import axios from 'axios'; -import { Logger } from '../../config/logger.config'; -import { BadRequestException, NotFoundException } from '../../exceptions'; -import { makeProxyAgent } from '../../utils/makeProxyAgent'; -import { InstanceDto } from '../dto/instance.dto'; -import { ProxyDto } from '../dto/proxy.dto'; -import { WAMonitoringService } from '../services/monitor.service'; -import { ProxyService } from '../services/proxy.service'; - const logger = new Logger('ProxyController'); export class ProxyController { @@ -18,7 +17,7 @@ export class ProxyController { throw new NotFoundException(`The "${instance.instanceName}" instance does not exist`); } - if (!data.enabled) { + if (!data?.enabled) { data.host = ''; data.port = ''; data.protocol = ''; diff --git a/src/api/controllers/sendMessage.controller.ts b/src/api/controllers/sendMessage.controller.ts index 8c005094..6a286cb8 100644 --- a/src/api/controllers/sendMessage.controller.ts +++ b/src/api/controllers/sendMessage.controller.ts @@ -1,7 +1,4 @@ -import { isBase64, isURL } from 'class-validator'; - -import { BadRequestException } from '../../exceptions'; -import { InstanceDto } from '../dto/instance.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; import { SendAudioDto, SendButtonDto, @@ -15,8 +12,10 @@ import { SendStickerDto, SendTemplateDto, SendTextDto, -} from '../dto/sendMessage.dto'; -import { WAMonitoringService } from '../services/monitor.service'; +} from '@api/dto/sendMessage.dto'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { BadRequestException } from '@exceptions'; +import { isBase64, isURL } from 'class-validator'; export class SendMessageController { constructor(private readonly waMonitor: WAMonitoringService) {} diff --git a/src/api/controllers/settings.controller.ts b/src/api/controllers/settings.controller.ts index 5e0e6aae..8a600a24 100644 --- a/src/api/controllers/settings.controller.ts +++ b/src/api/controllers/settings.controller.ts @@ -1,6 +1,6 @@ -import { InstanceDto } from '../dto/instance.dto'; -import { SettingsDto } from '../dto/settings.dto'; -import { SettingsService } from '../services/settings.service'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { SettingsDto } from '@api/dto/settings.dto'; +import { SettingsService } from '@api/services/settings.service'; export class SettingsController { constructor(private readonly settingsService: SettingsService) {} diff --git a/src/api/controllers/template.controller.ts b/src/api/controllers/template.controller.ts index b55100c7..d9b62045 100644 --- a/src/api/controllers/template.controller.ts +++ b/src/api/controllers/template.controller.ts @@ -1,6 +1,6 @@ -import { InstanceDto } from '../dto/instance.dto'; -import { TemplateDto } from '../dto/template.dto'; -import { TemplateService } from '../services/template.service'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { TemplateDto } from '@api/dto/template.dto'; +import { TemplateService } from '@api/services/template.service'; export class TemplateController { constructor(private readonly templateService: TemplateService) {} diff --git a/src/api/controllers/webhook.controller.ts b/src/api/controllers/webhook.controller.ts deleted file mode 100644 index 0e79b2c9..00000000 --- a/src/api/controllers/webhook.controller.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { isURL } from 'class-validator'; - -import { BadRequestException } from '../../exceptions'; -import { InstanceDto } from '../dto/instance.dto'; -import { WebhookDto } from '../dto/webhook.dto'; -import { WAMonitoringService } from '../services/monitor.service'; -import { WebhookService } from '../services/webhook.service'; - -export class WebhookController { - constructor(private readonly webhookService: WebhookService, private readonly waMonitor: WAMonitoringService) {} - - public async createWebhook(instance: InstanceDto, data: WebhookDto) { - if (!isURL(data.url, { require_tld: false })) { - throw new BadRequestException('Invalid "url" property'); - } - - data.enabled = data.enabled ?? true; - - if (!data.enabled) { - data.url = ''; - data.events = []; - } else if (data.events.length === 0) { - data.events = [ - 'APPLICATION_STARTUP', - 'QRCODE_UPDATED', - 'MESSAGES_SET', - 'MESSAGES_UPSERT', - 'MESSAGES_EDITED', - 'MESSAGES_UPDATE', - 'MESSAGES_DELETE', - 'SEND_MESSAGE', - 'CONTACTS_SET', - 'CONTACTS_UPSERT', - 'CONTACTS_UPDATE', - 'PRESENCE_UPDATE', - 'CHATS_SET', - 'CHATS_UPSERT', - 'CHATS_UPDATE', - 'CHATS_DELETE', - 'GROUPS_UPSERT', - 'GROUP_UPDATE', - 'GROUP_PARTICIPANTS_UPDATE', - 'CONNECTION_UPDATE', - 'LABELS_EDIT', - 'LABELS_ASSOCIATION', - 'CALL', - 'TYPEBOT_START', - 'TYPEBOT_CHANGE_STATUS', - ]; - } - - return this.webhookService.create(instance, data); - } - - public async findWebhook(instance: InstanceDto) { - return this.webhookService.find(instance); - } - - public async receiveWebhook(data: any) { - this.webhookService.receiveWebhook(data); - - return { - message: 'Webhook received', - }; - } -} diff --git a/src/api/dto/chat.dto.ts b/src/api/dto/chat.dto.ts index fc2ff5d3..00da7fdd 100644 --- a/src/api/dto/chat.dto.ts +++ b/src/api/dto/chat.dto.ts @@ -1,4 +1,11 @@ -import { proto, WAPresence, WAPrivacyOnlineValue, WAPrivacyValue, WAReadReceiptsValue } from 'baileys'; +import { + proto, + WAPresence, + WAPrivacyGroupAddValue, + WAPrivacyOnlineValue, + WAPrivacyValue, + WAReadReceiptsValue, +} from 'baileys'; export class OnWhatsAppDto { constructor( @@ -84,7 +91,7 @@ export class PrivacySettingDto { status: WAPrivacyValue; online: WAPrivacyOnlineValue; last: WAPrivacyValue; - groupadd: WAPrivacyValue; + groupadd: WAPrivacyGroupAddValue; } export class DeleteMessage { diff --git a/src/api/dto/chatbot.dto.ts b/src/api/dto/chatbot.dto.ts new file mode 100644 index 00000000..e1515483 --- /dev/null +++ b/src/api/dto/chatbot.dto.ts @@ -0,0 +1,12 @@ +export class Session { + remoteJid?: string; + sessionId?: string; + status?: string; + createdAt?: number; + updateAt?: number; +} + +export class IgnoreJidDto { + remoteJid?: string; + action?: string; +} diff --git a/src/api/dto/instance.dto.ts b/src/api/dto/instance.dto.ts index 86a3f67e..3bb48b5e 100644 --- a/src/api/dto/instance.dto.ts +++ b/src/api/dto/instance.dto.ts @@ -1,16 +1,16 @@ +import { IntegrationDto } from '@api/integrations/integration.dto'; import { WAPresence } from 'baileys'; -export class InstanceDto { +export class InstanceDto extends IntegrationDto { instanceName: string; instanceId?: string; qrcode?: boolean; + businessId?: string; number?: string; integration?: string; token?: string; - webhookUrl?: string; - webhookByEvents?: boolean; - webhookBase64?: boolean; - webhookEvents?: string[]; + status?: string; + // settings rejectCall?: boolean; msgCall?: string; groupsIgnore?: boolean; @@ -18,31 +18,12 @@ export class InstanceDto { readMessages?: boolean; readStatus?: boolean; syncFullHistory?: boolean; - chatwootAccountId?: string; - chatwootToken?: string; - chatwootUrl?: string; - chatwootSignMsg?: boolean; - chatwootReopenConversation?: boolean; - chatwootConversationPending?: boolean; - chatwootMergeBrazilContacts?: boolean; - chatwootImportContacts?: boolean; - chatwootImportMessages?: boolean; - chatwootDaysLimitImportMessages?: number; - chatwootNameInbox?: string; - chatwootOrganization?: string; - chatwootLogo?: string; - websocketEnabled?: boolean; - websocketEvents?: string[]; - rabbitmqEnabled?: boolean; - rabbitmqEvents?: string[]; - sqsEnabled?: boolean; - sqsEvents?: string[]; + // proxy proxyHost?: string; proxyPort?: string; proxyProtocol?: string; proxyUsername?: string; proxyPassword?: string; - businessId?: string; } export class SetPresenceDto { diff --git a/src/api/dto/webhook.dto.ts b/src/api/dto/webhook.dto.ts deleted file mode 100644 index e0e6b722..00000000 --- a/src/api/dto/webhook.dto.ts +++ /dev/null @@ -1,7 +0,0 @@ -export class WebhookDto { - enabled?: boolean; - url?: string; - events?: string[]; - webhookByEvents?: boolean; - webhookBase64?: boolean; -} diff --git a/src/api/guards/auth.guard.ts b/src/api/guards/auth.guard.ts index a2d665d2..9ad20b61 100644 --- a/src/api/guards/auth.guard.ts +++ b/src/api/guards/auth.guard.ts @@ -1,11 +1,10 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { prismaRepository } from '@api/server.module'; +import { Auth, configService, Database } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { ForbiddenException, UnauthorizedException } from '@exceptions'; import { NextFunction, Request, Response } from 'express'; -import { Auth, configService, Database } from '../../config/env.config'; -import { Logger } from '../../config/logger.config'; -import { ForbiddenException, UnauthorizedException } from '../../exceptions'; -import { InstanceDto } from '../dto/instance.dto'; -import { prismaRepository } from '../server.module'; - const logger = new Logger('GUARD'); async function apikey(req: Request, _: Response, next: NextFunction) { @@ -35,7 +34,7 @@ async function apikey(req: Request, _: Response, next: NextFunction) { return next(); } } else { - if (req.originalUrl.includes('/instance/fetchInstances') && db.ENABLED) { + if (req.originalUrl.includes('/instance/fetchInstances') && db.SAVE_DATA.INSTANCE) { const instanceByKey = await prismaRepository.instance.findFirst({ where: { token: key }, }); diff --git a/src/api/guards/instance.guard.ts b/src/api/guards/instance.guard.ts index df0e8bc6..874fa07f 100644 --- a/src/api/guards/instance.guard.ts +++ b/src/api/guards/instance.guard.ts @@ -1,19 +1,12 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { cache, waMonitor } from '@api/server.module'; +import { CacheConf, configService } from '@config/env.config'; +import { BadRequestException, ForbiddenException, InternalServerErrorException, NotFoundException } from '@exceptions'; +import { prismaServer } from '@libs/prisma.connect'; import { NextFunction, Request, Response } from 'express'; -import { CacheConf, configService, Database } from '../../config/env.config'; -import { - BadRequestException, - ForbiddenException, - InternalServerErrorException, - NotFoundException, -} from '../../exceptions'; -import { prismaServer } from '../../libs/prisma.connect'; -import { InstanceDto } from '../dto/instance.dto'; -import { cache, waMonitor } from '../server.module'; - async function getInstance(instanceName: string) { try { - const db = configService.get('DATABASE'); const cacheConf = configService.get('CACHE'); const exists = !!waMonitor.waInstances[instanceName]; @@ -24,13 +17,9 @@ async function getInstance(instanceName: string) { return exists || keyExists; } - if (db.ENABLED) { - const prisma = prismaServer; + const prisma = prismaServer; - return exists || (await prisma.instance.findMany({ where: { name: instanceName } })).length > 0; - } - - return false; + return exists || (await prisma.instance.findMany({ where: { name: instanceName } })).length > 0; } catch (error) { throw new InternalServerErrorException(error?.toString()); } @@ -61,8 +50,6 @@ export async function instanceLoggedGuard(req: Request, _: Response, next: NextF } if (waMonitor.waInstances[instance.instanceName]) { - waMonitor.waInstances[instance.instanceName]?.removeRabbitmqQueues(); - waMonitor.waInstances[instance.instanceName]?.removeSqsQueues(); delete waMonitor.waInstances[instance.instanceName]; } } diff --git a/src/api/guards/telemetry.guard.ts b/src/api/guards/telemetry.guard.ts index c8599e39..f82c01ed 100644 --- a/src/api/guards/telemetry.guard.ts +++ b/src/api/guards/telemetry.guard.ts @@ -1,7 +1,6 @@ +import { sendTelemetry } from '@utils/sendTelemetry'; import { NextFunction, Request, Response } from 'express'; -import { sendTelemetry } from '../../utils/sendTelemetry'; - class Telemetry { public collectTelemetry(req: Request, res: Response, next: NextFunction): void { sendTelemetry(req.path); diff --git a/src/api/integrations/channel/channel.controller.ts b/src/api/integrations/channel/channel.controller.ts new file mode 100644 index 00000000..3304d987 --- /dev/null +++ b/src/api/integrations/channel/channel.controller.ts @@ -0,0 +1,97 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { ProviderFiles } from '@api/provider/sessions'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { CacheService } from '@api/services/cache.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Integration } from '@api/types/wa.types'; +import { ConfigService } from '@config/env.config'; +import { BadRequestException } from '@exceptions'; +import EventEmitter2 from 'eventemitter2'; + +import { EvolutionStartupService } from './evolution/evolution.channel.service'; +import { BusinessStartupService } from './meta/whatsapp.business.service'; +import { BaileysStartupService } from './whatsapp/whatsapp.baileys.service'; + +type ChannelDataType = { + configService: ConfigService; + eventEmitter: EventEmitter2; + prismaRepository: PrismaRepository; + cache: CacheService; + chatwootCache: CacheService; + baileysCache: CacheService; + providerFiles: ProviderFiles; +}; + +export interface ChannelControllerInterface { + receiveWebhook(data: any): Promise; +} + +export class ChannelController { + public prismaRepository: PrismaRepository; + public waMonitor: WAMonitoringService; + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + this.prisma = prismaRepository; + this.monitor = waMonitor; + } + + public set prisma(prisma: PrismaRepository) { + this.prismaRepository = prisma; + } + + public get prisma() { + return this.prismaRepository; + } + + public set monitor(waMonitor: WAMonitoringService) { + this.waMonitor = waMonitor; + } + + public get monitor() { + return this.waMonitor; + } + + public init(instanceData: InstanceDto, data: ChannelDataType) { + if (!instanceData.token && instanceData.integration === Integration.WHATSAPP_BUSINESS) { + throw new BadRequestException('token is required'); + } + + if (instanceData.integration === Integration.WHATSAPP_BUSINESS) { + return new BusinessStartupService( + data.configService, + data.eventEmitter, + data.prismaRepository, + data.cache, + data.chatwootCache, + data.baileysCache, + data.providerFiles, + ); + } + + if (instanceData.integration === Integration.EVOLUTION) { + return new EvolutionStartupService( + data.configService, + data.eventEmitter, + data.prismaRepository, + data.cache, + data.chatwootCache, + data.baileysCache, + data.providerFiles, + ); + } + + if (instanceData.integration === Integration.WHATSAPP_BAILEYS) { + return new BaileysStartupService( + data.configService, + data.eventEmitter, + data.prismaRepository, + data.cache, + data.chatwootCache, + data.baileysCache, + data.providerFiles, + ); + } + + return null; + } +} diff --git a/src/api/integrations/channel/channel.router.ts b/src/api/integrations/channel/channel.router.ts new file mode 100644 index 00000000..c5bce859 --- /dev/null +++ b/src/api/integrations/channel/channel.router.ts @@ -0,0 +1,15 @@ +import { Router } from 'express'; + +import { EvolutionRouter } from './evolution/evolution.router'; +import { MetaRouter } from './meta/meta.router'; + +export class ChannelRouter { + public readonly router: Router; + + constructor(configService: any) { + this.router = Router(); + + this.router.use('/', new EvolutionRouter(configService).router); + this.router.use('/', new MetaRouter(configService).router); + } +} diff --git a/src/api/integrations/channel/evolution/evolution.channel.service.ts b/src/api/integrations/channel/evolution/evolution.channel.service.ts new file mode 100644 index 00000000..4c278668 --- /dev/null +++ b/src/api/integrations/channel/evolution/evolution.channel.service.ts @@ -0,0 +1,640 @@ +import { MediaMessage, Options, SendAudioDto, SendMediaDto, SendTextDto } from '@api/dto/sendMessage.dto'; +import { ProviderFiles } from '@api/provider/sessions'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { chatbotController } from '@api/server.module'; +import { CacheService } from '@api/services/cache.service'; +import { ChannelStartupService } from '@api/services/channel.service'; +import { Events, wa } from '@api/types/wa.types'; +import { Chatwoot, ConfigService, Openai } from '@config/env.config'; +import { BadRequestException, InternalServerErrorException } from '@exceptions'; +import { isURL } from 'class-validator'; +import EventEmitter2 from 'eventemitter2'; +import mime from 'mime'; +import { v4 } from 'uuid'; + +export class EvolutionStartupService extends ChannelStartupService { + constructor( + public readonly configService: ConfigService, + public readonly eventEmitter: EventEmitter2, + public readonly prismaRepository: PrismaRepository, + public readonly cache: CacheService, + public readonly chatwootCache: CacheService, + public readonly baileysCache: CacheService, + private readonly providerFiles: ProviderFiles, + ) { + super(configService, eventEmitter, prismaRepository, chatwootCache); + + this.client = null; + } + + public client: any; + + public stateConnection: wa.StateConnection = { state: 'open' }; + + public phoneNumber: string; + public mobile: boolean; + + public get connectionStatus() { + return this.stateConnection; + } + + public async closeClient() { + this.stateConnection = { state: 'close' }; + } + + public get qrCode(): wa.QrCode { + return { + pairingCode: this.instance.qrcode?.pairingCode, + code: this.instance.qrcode?.code, + base64: this.instance.qrcode?.base64, + count: this.instance.qrcode?.count, + }; + } + + public async logoutInstance() { + await this.closeClient(); + } + + public async profilePicture(number: string) { + const jid = this.createJid(number); + + return { + wuid: jid, + profilePictureUrl: null, + }; + } + + public async getProfileName() { + return null; + } + + public async profilePictureUrl() { + return null; + } + + public async getProfileStatus() { + return null; + } + + public async connectToWhatsapp(data?: any): Promise { + if (!data) return; + + try { + this.loadChatwoot(); + + this.eventHandler(data); + } catch (error) { + this.logger.error(error); + throw new InternalServerErrorException(error?.toString()); + } + } + + protected async eventHandler(received: any) { + try { + let messageRaw: any; + + if (received.message) { + const key = { + id: received.key.id || v4(), + remoteJid: received.key.remoteJid, + fromMe: received.key.fromMe, + }; + messageRaw = { + key, + pushName: received.pushName, + message: received.message, + messageType: received.messageType, + messageTimestamp: Math.round(new Date().getTime() / 1000), + source: 'unknown', + instanceId: this.instanceId, + }; + + if (this.configService.get('OPENAI').ENABLED) { + const openAiDefaultSettings = await this.prismaRepository.openaiSetting.findFirst({ + where: { + instanceId: this.instanceId, + }, + include: { + OpenaiCreds: true, + }, + }); + + if ( + openAiDefaultSettings && + openAiDefaultSettings.openaiCredsId && + openAiDefaultSettings.speechToText && + received?.message?.audioMessage + ) { + messageRaw.message.speechToText = await this.openaiService.speechToText( + openAiDefaultSettings.OpenaiCreds, + received, + this.client.updateMediaMessage, + ); + } + } + + this.logger.log(messageRaw); + + this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw); + + await chatbotController.emit({ + instance: { instanceName: this.instance.name, instanceId: this.instanceId }, + remoteJid: messageRaw.key.remoteJid, + msg: messageRaw, + pushName: messageRaw.pushName, + }); + + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { + const chatwootSentMessage = await this.chatwootService.eventWhatsapp( + Events.MESSAGES_UPSERT, + { instanceName: this.instance.name, instanceId: this.instanceId }, + messageRaw, + ); + + if (chatwootSentMessage?.id) { + messageRaw.chatwootMessageId = chatwootSentMessage.id; + messageRaw.chatwootInboxId = chatwootSentMessage.id; + messageRaw.chatwootConversationId = chatwootSentMessage.id; + } + } + + await this.prismaRepository.message.create({ + data: messageRaw, + }); + + await this.updateContact({ + remoteJid: messageRaw.key.remoteJid, + pushName: messageRaw.pushName, + profilePicUrl: received.profilePicUrl, + }); + } + } catch (error) { + this.logger.error(error); + } + } + + private async updateContact(data: { remoteJid: string; pushName?: string; profilePicUrl?: string }) { + const contact = await this.prismaRepository.contact.findFirst({ + where: { instanceId: this.instanceId, remoteJid: data.remoteJid }, + }); + + if (contact) { + const contactRaw: any = { + remoteJid: data.remoteJid, + pushName: data?.pushName, + instanceId: this.instanceId, + profilePicUrl: data?.profilePicUrl, + }; + + this.sendDataWebhook(Events.CONTACTS_UPDATE, contactRaw); + + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { + await this.chatwootService.eventWhatsapp( + Events.CONTACTS_UPDATE, + { instanceName: this.instance.name, instanceId: this.instanceId }, + contactRaw, + ); + } + + await this.prismaRepository.contact.updateMany({ + where: { remoteJid: contact.remoteJid, instanceId: this.instanceId }, + data: contactRaw, + }); + return; + } + + const contactRaw: any = { + remoteJid: data.remoteJid, + pushName: data?.pushName, + instanceId: this.instanceId, + profilePicUrl: data?.profilePicUrl, + }; + + this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw); + + await this.prismaRepository.contact.create({ + data: contactRaw, + }); + + const chat = await this.prismaRepository.chat.findFirst({ + where: { instanceId: this.instanceId, remoteJid: data.remoteJid }, + }); + + if (chat) { + const chatRaw: any = { + remoteJid: data.remoteJid, + instanceId: this.instanceId, + }; + + this.sendDataWebhook(Events.CHATS_UPDATE, chatRaw); + + await this.prismaRepository.chat.updateMany({ + where: { remoteJid: chat.remoteJid }, + data: chatRaw, + }); + } + + const chatRaw: any = { + remoteJid: data.remoteJid, + instanceId: this.instanceId, + }; + + this.sendDataWebhook(Events.CHATS_UPSERT, chatRaw); + + await this.prismaRepository.chat.create({ + data: chatRaw, + }); + } + + protected async sendMessageWithTyping(number: string, message: any, options?: Options, isIntegration = false) { + try { + let quoted: any; + let webhookUrl: any; + + if (options?.quoted) { + const m = options?.quoted; + + const msg = m?.key; + + if (!msg) { + throw 'Message not found'; + } + + quoted = msg; + } + + if (options.delay) { + await new Promise((resolve) => setTimeout(resolve, options.delay)); + } + + if (options?.webhookUrl) { + webhookUrl = options.webhookUrl; + } + + const messageId = v4(); + + let messageRaw: any; + + if (message?.mediaType === 'image') { + messageRaw = { + key: { fromMe: true, id: messageId, remoteJid: number }, + message: { + mediaUrl: message.media, + quoted, + }, + messageType: 'imageMessage', + messageTimestamp: Math.round(new Date().getTime() / 1000), + webhookUrl, + source: 'unknown', + instanceId: this.instanceId, + }; + } else if (message?.mediaType === 'video') { + messageRaw = { + key: { fromMe: true, id: messageId, remoteJid: number }, + message: { + mediaUrl: message.media, + quoted, + }, + messageType: 'videoMessage', + messageTimestamp: Math.round(new Date().getTime() / 1000), + webhookUrl, + source: 'unknown', + instanceId: this.instanceId, + }; + } else if (message?.mediaType === 'audio') { + messageRaw = { + key: { fromMe: true, id: messageId, remoteJid: number }, + message: { + mediaUrl: message.media, + quoted, + }, + messageType: 'audioMessage', + messageTimestamp: Math.round(new Date().getTime() / 1000), + webhookUrl, + source: 'unknown', + instanceId: this.instanceId, + }; + } else if (message?.mediaType === 'document') { + messageRaw = { + key: { fromMe: true, id: messageId, remoteJid: number }, + message: { + mediaUrl: message.media, + quoted, + }, + messageType: 'documentMessage', + messageTimestamp: Math.round(new Date().getTime() / 1000), + webhookUrl, + source: 'unknown', + instanceId: this.instanceId, + }; + } else { + messageRaw = { + key: { fromMe: true, id: messageId, remoteJid: number }, + message: { + ...message, + quoted, + }, + messageType: 'conversation', + messageTimestamp: Math.round(new Date().getTime() / 1000), + webhookUrl, + source: 'unknown', + instanceId: this.instanceId, + }; + } + + this.logger.log(messageRaw); + + this.sendDataWebhook(Events.SEND_MESSAGE, messageRaw); + + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled && !isIntegration) { + this.chatwootService.eventWhatsapp( + Events.SEND_MESSAGE, + { instanceName: this.instance.name, instanceId: this.instanceId }, + messageRaw, + ); + } + + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled && isIntegration) + await chatbotController.emit({ + instance: { instanceName: this.instance.name, instanceId: this.instanceId }, + remoteJid: messageRaw.key.remoteJid, + msg: messageRaw, + pushName: messageRaw.pushName, + }); + + await this.prismaRepository.message.create({ + data: messageRaw, + }); + + return messageRaw; + } catch (error) { + this.logger.error(error); + throw new BadRequestException(error.toString()); + } + } + + public async textMessage(data: SendTextDto, isIntegration = false) { + const res = await this.sendMessageWithTyping( + data.number, + { + conversation: data.text, + }, + { + delay: data?.delay, + presence: 'composing', + quoted: data?.quoted, + linkPreview: data?.linkPreview, + mentionsEveryOne: data?.mentionsEveryOne, + mentioned: data?.mentioned, + }, + isIntegration, + ); + return res; + } + + protected async prepareMediaMessage(mediaMessage: MediaMessage) { + try { + if (mediaMessage.mediatype === 'document' && !mediaMessage.fileName) { + const regex = new RegExp(/.*\/(.+?)\./); + const arrayMatch = regex.exec(mediaMessage.media); + mediaMessage.fileName = arrayMatch[1]; + } + + if (mediaMessage.mediatype === 'image' && !mediaMessage.fileName) { + mediaMessage.fileName = 'image.png'; + } + + if (mediaMessage.mediatype === 'video' && !mediaMessage.fileName) { + mediaMessage.fileName = 'video.mp4'; + } + + let mimetype: string; + + const prepareMedia: any = { + caption: mediaMessage?.caption, + fileName: mediaMessage.fileName, + mediaType: mediaMessage.mediatype, + media: mediaMessage.media, + gifPlayback: false, + }; + + if (isURL(mediaMessage.media)) { + mimetype = mime.getType(mediaMessage.media); + } else { + mimetype = mime.getType(mediaMessage.fileName); + } + + prepareMedia.mimetype = mimetype; + + return prepareMedia; + } catch (error) { + this.logger.error(error); + throw new InternalServerErrorException(error?.toString() || error); + } + } + + public async mediaMessage(data: SendMediaDto, isIntegration = false) { + const message = await this.prepareMediaMessage(data); + + console.log('message', message); + return await this.sendMessageWithTyping( + data.number, + { ...message }, + { + delay: data?.delay, + presence: 'composing', + quoted: data?.quoted, + linkPreview: data?.linkPreview, + mentionsEveryOne: data?.mentionsEveryOne, + mentioned: data?.mentioned, + }, + isIntegration, + ); + } + + public async processAudio(audio: string, number: string) { + number = number.replace(/\D/g, ''); + const hash = `${number}-${new Date().getTime()}`; + + let mimetype: string; + + const prepareMedia: any = { + fileName: `${hash}.mp4`, + mediaType: 'audio', + media: audio, + }; + + if (isURL(audio)) { + mimetype = mime.getType(audio); + } else { + mimetype = mime.getType(prepareMedia.fileName); + } + + prepareMedia.mimetype = mimetype; + + return prepareMedia; + } + + public async audioWhatsapp(data: SendAudioDto, isIntegration = false) { + const message = await this.processAudio(data.audio, data.number); + + return await this.sendMessageWithTyping( + data.number, + { ...message }, + { + delay: data?.delay, + presence: 'composing', + quoted: data?.quoted, + linkPreview: data?.linkPreview, + mentionsEveryOne: data?.mentionsEveryOne, + mentioned: data?.mentioned, + }, + isIntegration, + ); + } + + public async buttonMessage() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async locationMessage() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async listMessage() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async templateMessage() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async contactMessage() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async reactionMessage() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async getBase64FromMediaMessage() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async deleteMessage() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async mediaSticker() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async pollMessage() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async statusMessage() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async reloadConnection() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async whatsappNumber() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async markMessageAsRead() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async archiveChat() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async markChatUnread() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async fetchProfile() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async sendPresence() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async setPresence() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async fetchPrivacySettings() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async updatePrivacySettings() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async fetchBusinessProfile() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async updateProfileName() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async updateProfileStatus() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async updateProfilePicture() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async removeProfilePicture() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async blockUser() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async updateMessage() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async createGroup() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async updateGroupPicture() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async updateGroupSubject() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async updateGroupDescription() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async findGroup() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async fetchAllGroups() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async inviteCode() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async inviteInfo() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async sendInvite() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async acceptInviteCode() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async revokeInviteCode() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async findParticipants() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async updateGParticipant() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async updateGSetting() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async toggleEphemeral() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async leaveGroup() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async fetchLabels() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async handleLabel() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async receiveMobileCode() { + throw new BadRequestException('Method not available on Evolution Channel'); + } + public async fakeCall() { + throw new BadRequestException('Method not available on Evolution Channel'); + } +} diff --git a/src/api/integrations/channel/evolution/evolution.controller.ts b/src/api/integrations/channel/evolution/evolution.controller.ts new file mode 100644 index 00000000..c9f36585 --- /dev/null +++ b/src/api/integrations/channel/evolution/evolution.controller.ts @@ -0,0 +1,39 @@ +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Logger } from '@config/logger.config'; + +import { ChannelController, ChannelControllerInterface } from '../channel.controller'; + +export class EvolutionController extends ChannelController implements ChannelControllerInterface { + private readonly logger = new Logger('EvolutionController'); + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + super(prismaRepository, waMonitor); + } + + integrationEnabled: boolean; + + public async receiveWebhook(data: any) { + const numberId = data.numberId; + + if (!numberId) { + this.logger.error('WebhookService -> receiveWebhookEvolution -> numberId not found'); + return; + } + + const instance = await this.prismaRepository.instance.findFirst({ + where: { number: numberId }, + }); + + if (!instance) { + this.logger.error('WebhookService -> receiveWebhook -> instance not found'); + return; + } + + await this.waMonitor.waInstances[instance.name].connectToWhatsapp(data); + + return { + status: 'success', + }; + } +} diff --git a/src/api/integrations/channel/evolution/evolution.router.ts b/src/api/integrations/channel/evolution/evolution.router.ts new file mode 100644 index 00000000..1ab0ec00 --- /dev/null +++ b/src/api/integrations/channel/evolution/evolution.router.ts @@ -0,0 +1,18 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { evolutionController } from '@api/server.module'; +import { ConfigService } from '@config/env.config'; +import { Router } from 'express'; + +export class EvolutionRouter extends RouterBroker { + constructor(readonly configService: ConfigService) { + super(); + this.router.post(this.routerPath('webhook/evolution', false), async (req, res) => { + const { body } = req; + const response = await evolutionController.receiveWebhook(body); + + return res.status(200).json(response); + }); + } + + public readonly router: Router = Router(); +} diff --git a/src/api/integrations/channel/meta/meta.controller.ts b/src/api/integrations/channel/meta/meta.controller.ts new file mode 100644 index 00000000..558a22e9 --- /dev/null +++ b/src/api/integrations/channel/meta/meta.controller.ts @@ -0,0 +1,72 @@ +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Logger } from '@config/logger.config'; +import axios from 'axios'; + +import { ChannelController, ChannelControllerInterface } from '../channel.controller'; + +export class MetaController extends ChannelController implements ChannelControllerInterface { + private readonly logger = new Logger('MetaController'); + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + super(prismaRepository, waMonitor); + } + + integrationEnabled: boolean; + + public async receiveWebhook(data: any) { + if (data.object === 'whatsapp_business_account') { + if (data.entry[0]?.changes[0]?.field === 'message_template_status_update') { + const template = await this.prismaRepository.template.findFirst({ + where: { templateId: `${data.entry[0].changes[0].value.message_template_id}` }, + }); + + if (!template) { + console.log('template not found'); + return; + } + + const { webhookUrl } = template; + + await axios.post(webhookUrl, data.entry[0].changes[0].value, { + headers: { + 'Content-Type': 'application/json', + }, + }); + return; + } + + data.entry?.forEach(async (entry: any) => { + const numberId = entry.changes[0].value.metadata.phone_number_id; + + if (!numberId) { + this.logger.error('WebhookService -> receiveWebhookMeta -> numberId not found'); + return { + status: 'success', + }; + } + + const instance = await this.prismaRepository.instance.findFirst({ + where: { number: numberId }, + }); + + if (!instance) { + this.logger.error('WebhookService -> receiveWebhookMeta -> instance not found'); + return { + status: 'success', + }; + } + + await this.waMonitor.waInstances[instance.name].connectToWhatsapp(data); + + return { + status: 'success', + }; + }); + } + + return { + status: 'success', + }; + } +} diff --git a/src/api/integrations/channel/meta/meta.router.ts b/src/api/integrations/channel/meta/meta.router.ts new file mode 100644 index 00000000..b0fc43ce --- /dev/null +++ b/src/api/integrations/channel/meta/meta.router.ts @@ -0,0 +1,24 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { metaController } from '@api/server.module'; +import { ConfigService, WaBusiness } from '@config/env.config'; +import { Router } from 'express'; + +export class MetaRouter extends RouterBroker { + constructor(readonly configService: ConfigService) { + super(); + this.router + .get(this.routerPath('webhook/meta', false), async (req, res) => { + if (req.query['hub.verify_token'] === configService.get('WA_BUSINESS').TOKEN_WEBHOOK) + res.send(req.query['hub.challenge']); + else res.send('Error, wrong validation token'); + }) + .post(this.routerPath('webhook/meta', false), async (req, res) => { + const { body } = req; + const response = await metaController.receiveWebhook(body); + + return res.status(200).json(response); + }); + } + + public readonly router: Router = Router(); +} diff --git a/src/api/services/channels/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts similarity index 90% rename from src/api/services/channels/whatsapp.business.service.ts rename to src/api/integrations/channel/meta/whatsapp.business.service.ts index 87c9e138..a45e2cde 100644 --- a/src/api/services/channels/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -1,13 +1,4 @@ -import axios from 'axios'; -import { arrayUnique, isURL } from 'class-validator'; -import EventEmitter2 from 'eventemitter2'; -import FormData from 'form-data'; -import { createReadStream } from 'fs'; -import { getMIMEType } from 'node-mime-types'; - -import { Chatwoot, ConfigService, Database, Dify, Openai, Typebot, WaBusiness } from '../../../config/env.config'; -import { BadRequestException, InternalServerErrorException } from '../../../exceptions'; -import { NumberBusiness } from '../../dto/chat.dto'; +import { NumberBusiness } from '@api/dto/chat.dto'; import { ContactMessage, MediaMessage, @@ -21,12 +12,23 @@ import { SendReactionDto, SendTemplateDto, SendTextDto, -} from '../../dto/sendMessage.dto'; -import { ProviderFiles } from '../../provider/sessions'; -import { PrismaRepository } from '../../repository/repository.service'; -import { Events, wa } from '../../types/wa.types'; -import { CacheService } from './../cache.service'; -import { ChannelStartupService } from './../channel.service'; +} from '@api/dto/sendMessage.dto'; +import * as s3Service from '@api/integrations/storage/s3/libs/minio.server'; +import { ProviderFiles } from '@api/provider/sessions'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { chatbotController } from '@api/server.module'; +import { CacheService } from '@api/services/cache.service'; +import { ChannelStartupService } from '@api/services/channel.service'; +import { Events, wa } from '@api/types/wa.types'; +import { Chatwoot, ConfigService, Database, Openai, S3, WaBusiness } from '@config/env.config'; +import { BadRequestException, InternalServerErrorException } from '@exceptions'; +import axios from 'axios'; +import { arrayUnique, isURL } from 'class-validator'; +import EventEmitter2 from 'eventemitter2'; +import FormData from 'form-data'; +import { createReadStream } from 'fs'; +import mime from 'mime'; +import { join } from 'path'; export class BusinessStartupService extends ChannelStartupService { constructor( @@ -83,17 +85,10 @@ export class BusinessStartupService extends ChannelStartupService { public async profilePicture(number: string) { const jid = this.createJid(number); - try { - return { - wuid: jid, - profilePictureUrl: await this.client.profilePictureUrl(jid, 'image'), - }; - } catch (error) { - return { - wuid: jid, - profilePictureUrl: null, - }; - } + return { + wuid: jid, + profilePictureUrl: null, + }; } public async getProfileName() { @@ -128,11 +123,7 @@ export class BusinessStartupService extends ChannelStartupService { const content = data.entry[0].changes[0].value; try { - this.loadWebhook(); this.loadChatwoot(); - this.loadWebsocket(); - this.loadRabbitmq(); - this.loadSqs(); this.eventHandler(content); @@ -298,7 +289,6 @@ export class BusinessStartupService extends ChannelStartupService { protected async messageHandle(received: any, database: Database, settings: any) { try { - console.log(received); let messageRaw: any; let pushName: any; @@ -316,20 +306,78 @@ export class BusinessStartupService extends ChannelStartupService { received?.messages[0].audio || received?.messages[0].video ) { - const buffer = await this.downloadMediaMessage(received?.messages[0]); messageRaw = { key, pushName, - message: { - ...this.messageMediaJson(received), - base64: buffer ? buffer.toString('base64') : undefined, - }, + message: this.messageMediaJson(received), contextInfo: this.messageMediaJson(received)?.contextInfo, messageType: this.renderMessageType(received.messages[0].type), messageTimestamp: parseInt(received.messages[0].timestamp) as number, source: 'unknown', instanceId: this.instanceId, }; + + if (this.configService.get('S3').ENABLE) { + try { + const message: any = received; + + const id = message.messages[0][message.messages[0].type].id; + let urlServer = this.configService.get('WA_BUSINESS').URL; + const version = this.configService.get('WA_BUSINESS').VERSION; + urlServer = `${urlServer}/${version}/${id}`; + const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${this.token}` }; + const result = await axios.get(urlServer, { headers }); + + const buffer = await axios.get(result.data.url, { headers, responseType: 'arraybuffer' }); + + const mediaType = message.messages[0].document + ? 'document' + : message.messages[0].image + ? 'image' + : message.messages[0].audio + ? 'audio' + : 'video'; + + const mimetype = result.headers['content-type']; + + const contentDisposition = result.headers['content-disposition']; + let fileName = `${message.messages[0].id}.${mimetype.split('/')[1]}`; + if (contentDisposition) { + const match = contentDisposition.match(/filename="(.+?)"/); + if (match) { + fileName = match[1]; + } + } + + const size = result.headers['content-length'] || buffer.data.byteLength; + + const fullName = join(`${this.instance.id}`, received.key.remoteJid, mediaType, fileName); + + await s3Service.uploadFile(fullName, buffer.data, size, { + 'Content-Type': mimetype, + }); + + await this.prismaRepository.media.create({ + data: { + messageId: received.messages[0].id, + instanceId: this.instanceId, + type: mediaType, + fileName: fullName, + mimetype, + }, + }); + + const mediaUrl = await s3Service.getObjectUrl(fullName); + + messageRaw.message.mediaUrl = mediaUrl; + } catch (error) { + this.logger.error(['Error on upload file to minio', error?.message, error?.stack]); + } + } else { + const buffer = await this.downloadMediaMessage(received?.messages[0]); + + messageRaw.message.base64 = buffer.toString('base64'); + } } else if (received?.messages[0].interactive) { messageRaw = { key, @@ -338,7 +386,7 @@ export class BusinessStartupService extends ChannelStartupService { ...this.messageInteractiveJson(received), }, contextInfo: this.messageInteractiveJson(received)?.contextInfo, - messageType: 'conversation', + messageType: 'interactiveMessage', messageTimestamp: parseInt(received.messages[0].timestamp) as number, source: 'unknown', instanceId: this.instanceId, @@ -351,7 +399,7 @@ export class BusinessStartupService extends ChannelStartupService { ...this.messageButtonJson(received), }, contextInfo: this.messageButtonJson(received)?.contextInfo, - messageType: 'conversation', + messageType: 'buttonMessage', messageTimestamp: parseInt(received.messages[0].timestamp) as number, source: 'unknown', instanceId: this.instanceId, @@ -377,7 +425,7 @@ export class BusinessStartupService extends ChannelStartupService { ...this.messageContactsJson(received), }, contextInfo: this.messageContactsJson(received)?.contextInfo, - messageType: 'conversation', + messageType: 'contactMessage', messageTimestamp: parseInt(received.messages[0].timestamp) as number, source: 'unknown', instanceId: this.instanceId, @@ -395,11 +443,7 @@ export class BusinessStartupService extends ChannelStartupService { }; } - if (this.localSettings.readMessages && received.key.id !== 'status@broadcast') { - // await this.client.readMessages([received.key]); - } - - if (this.localSettings.readStatus && received.key.id === 'status@broadcast') { + if (this.localSettings.readMessages) { // await this.client.readMessages([received.key]); } @@ -431,7 +475,14 @@ export class BusinessStartupService extends ChannelStartupService { this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot.enabled) { + await chatbotController.emit({ + instance: { instanceName: this.instance.name, instanceId: this.instanceId }, + remoteJid: messageRaw.key.remoteJid, + msg: messageRaw, + pushName: messageRaw.pushName, + }); + + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { const chatwootSentMessage = await this.chatwootService.eventWhatsapp( Events.MESSAGES_UPSERT, { instanceName: this.instance.name, instanceId: this.instanceId }, @@ -445,33 +496,6 @@ export class BusinessStartupService extends ChannelStartupService { } } - if (this.configService.get('TYPEBOT').ENABLED) { - if (messageRaw.messageType !== 'reactionMessage') - await this.typebotService.sendTypebot( - { instanceName: this.instance.name, instanceId: this.instanceId }, - messageRaw.key.remoteJid, - messageRaw, - ); - } - - if (this.configService.get('OPENAI').ENABLED) { - if (messageRaw.messageType !== 'reactionMessage') - await this.openaiService.sendOpenai( - { instanceName: this.instance.name, instanceId: this.instanceId }, - messageRaw.key.remoteJid, - messageRaw, - ); - } - - if (this.configService.get('DIFY').ENABLED) { - if (messageRaw.messageType !== 'reactionMessage') - await this.difyService.sendDify( - { instanceName: this.instance.name, instanceId: this.instanceId }, - messageRaw.key.remoteJid, - messageRaw, - ); - } - await this.prismaRepository.message.create({ data: messageRaw, }); @@ -501,7 +525,7 @@ export class BusinessStartupService extends ChannelStartupService { this.sendDataWebhook(Events.CONTACTS_UPDATE, contactRaw); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot.enabled) { + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { await this.chatwootService.eventWhatsapp( Events.CONTACTS_UPDATE, { instanceName: this.instance.name, instanceId: this.instanceId }, @@ -564,7 +588,7 @@ export class BusinessStartupService extends ChannelStartupService { data: message, }); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot.enabled) { + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { this.chatwootService.eventWhatsapp( Events.MESSAGES_DELETE, { instanceName: this.instance.name, instanceId: this.instanceId }, @@ -884,7 +908,7 @@ export class BusinessStartupService extends ChannelStartupService { this.sendDataWebhook(Events.SEND_MESSAGE, messageRaw); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot.enabled && !isIntegration) { + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled && !isIntegration) { this.chatwootService.eventWhatsapp( Events.SEND_MESSAGE, { instanceName: this.instance.name, instanceId: this.instanceId }, @@ -892,13 +916,20 @@ export class BusinessStartupService extends ChannelStartupService { ); } + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled && isIntegration) + await chatbotController.emit({ + instance: { instanceName: this.instance.name, instanceId: this.instanceId }, + remoteJid: messageRaw.key.remoteJid, + msg: messageRaw, + pushName: messageRaw.pushName, + }); + await this.prismaRepository.message.create({ data: messageRaw, }); return messageRaw; } catch (error) { - console.log(error.response.data); this.logger.error(error); throw new BadRequestException(error.toString()); } @@ -976,11 +1007,11 @@ export class BusinessStartupService extends ChannelStartupService { }; if (isURL(mediaMessage.media)) { - mimetype = getMIMEType(mediaMessage.media); + mimetype = mime.getType(mediaMessage.media); prepareMedia.id = mediaMessage.media; prepareMedia.type = 'link'; } else { - mimetype = getMIMEType(mediaMessage.fileName); + mimetype = mime.getType(mediaMessage.fileName); const id = await this.getIdMedia(prepareMedia); prepareMedia.id = id; prepareMedia.type = 'id'; @@ -1026,11 +1057,11 @@ export class BusinessStartupService extends ChannelStartupService { }; if (isURL(audio)) { - mimetype = getMIMEType(audio); + mimetype = mime.getType(audio); prepareMedia.id = audio; prepareMedia.type = 'link'; } else { - mimetype = getMIMEType(prepareMedia.fileName); + mimetype = mime.getType(prepareMedia.fileName); const id = await this.getIdMedia(prepareMedia); prepareMedia.id = id; prepareMedia.type = 'id'; @@ -1263,7 +1294,7 @@ export class BusinessStartupService extends ChannelStartupService { public async getBase64FromMediaMessage(data: any) { try { const msg = data.message; - const messageType = msg.messageType + 'Message'; + const messageType = msg.messageType.includes('Message') ? msg.messageType : msg.messageType + 'Message'; const mediaMessage = msg.message[messageType]; return { diff --git a/src/api/services/channels/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts similarity index 83% rename from src/api/services/channels/whatsapp.baileys.service.ts rename to src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 6cf5d435..f875aaec 100644 --- a/src/api/services/channels/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -1,6 +1,80 @@ +import { + ArchiveChatDto, + BlockUserDto, + DeleteMessage, + getBase64FromMediaMessageDto, + LastMessage, + MarkChatUnreadDto, + NumberBusiness, + OnWhatsAppDto, + PrivacySettingDto, + ReadMessageDto, + SendPresenceDto, + UpdateMessageDto, + WhatsAppNumberDto, +} from '@api/dto/chat.dto'; +import { + AcceptGroupInvite, + CreateGroupDto, + GetParticipant, + GroupDescriptionDto, + GroupInvite, + GroupJid, + GroupPictureDto, + GroupSendInvite, + GroupSubjectDto, + GroupToggleEphemeralDto, + GroupUpdateParticipantDto, + GroupUpdateSettingDto, +} from '@api/dto/group.dto'; +import { InstanceDto, SetPresenceDto } from '@api/dto/instance.dto'; +import { HandleLabelDto, LabelDto } from '@api/dto/label.dto'; +import { + ContactMessage, + MediaMessage, + Options, + SendAudioDto, + SendContactDto, + SendLocationDto, + SendMediaDto, + SendPollDto, + SendReactionDto, + SendStatusDto, + SendStickerDto, + SendTextDto, + StatusMessage, +} from '@api/dto/sendMessage.dto'; +import { chatwootImport } from '@api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper'; +import * as s3Service from '@api/integrations/storage/s3/libs/minio.server'; +import { ProviderFiles } from '@api/provider/sessions'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { chatbotController, waMonitor } from '@api/server.module'; +import { CacheService } from '@api/services/cache.service'; +import { ChannelStartupService } from '@api/services/channel.service'; +import { Events, MessageSubtype, TypeMediaMessage, wa } from '@api/types/wa.types'; +import { CacheEngine } from '@cache/cacheengine'; +import { + CacheConf, + Chatwoot, + ConfigService, + configService, + ConfigSessionPhone, + Database, + Log, + Openai, + ProviderSession, + QrCode, + S3, +} from '@config/env.config'; +import { BadRequestException, InternalServerErrorException, NotFoundException } from '@exceptions'; import ffmpegPath from '@ffmpeg-installer/ffmpeg'; import { Boom } from '@hapi/boom'; import { Instance } from '@prisma/client'; +import { makeProxyAgent } from '@utils/makeProxyAgent'; +import { getOnWhatsappCache, saveOnWhatsappCache } from '@utils/onWhatsappCache'; +import useMultiFileAuthStatePrisma from '@utils/use-multi-file-auth-state-prisma'; +import { AuthStateProvider } from '@utils/use-multi-file-auth-state-provider-files'; +import { useMultiFileAuthStateRedisDb } from '@utils/use-multi-file-auth-state-redis-db'; import axios from 'axios'; import makeWASocket, { AnyMessageContent, @@ -19,9 +93,9 @@ import makeWASocket, { getContentType, getDevice, GroupMetadata, - GroupParticipant, isJidBroadcast, isJidGroup, + isJidNewsletter, isJidUser, makeCacheableSignalKeyStore, MessageUpsertType, @@ -42,14 +116,11 @@ import { LabelAssociation } from 'baileys/lib/Types/LabelAssociation'; import { isBase64, isURL } from 'class-validator'; import { randomBytes } from 'crypto'; import EventEmitter2 from 'eventemitter2'; -// import { exec } from 'child_process'; import ffmpeg from 'fluent-ffmpeg'; -// import ffmpeg from 'fluent-ffmpeg'; -import { existsSync, readFileSync } from 'fs'; +import { readFileSync } from 'fs'; import Long from 'long'; import mime from 'mime'; import NodeCache from 'node-cache'; -import { getMIMEType } from 'node-mime-types'; import { release } from 'os'; import { join } from 'path'; import P from 'pino'; @@ -59,84 +130,6 @@ import sharp from 'sharp'; import { PassThrough } from 'stream'; import { v4 } from 'uuid'; -import { CacheEngine } from '../../../cache/cacheengine'; -import { - CacheConf, - Chatwoot, - ConfigService, - configService, - ConfigSessionPhone, - Database, - Dify, - Log, - Openai, - ProviderSession, - QrCode, - S3, - Typebot, -} from '../../../config/env.config'; -import { INSTANCE_DIR } from '../../../config/path.config'; -import { BadRequestException, InternalServerErrorException, NotFoundException } from '../../../exceptions'; -import { makeProxyAgent } from '../../../utils/makeProxyAgent'; -import useMultiFileAuthStatePrisma from '../../../utils/use-multi-file-auth-state-prisma'; -import { AuthStateProvider } from '../../../utils/use-multi-file-auth-state-provider-files'; -import { useMultiFileAuthStateRedisDb } from '../../../utils/use-multi-file-auth-state-redis-db'; -import { - ArchiveChatDto, - BlockUserDto, - DeleteMessage, - getBase64FromMediaMessageDto, - LastMessage, - MarkChatUnreadDto, - NumberBusiness, - OnWhatsAppDto, - PrivacySettingDto, - ReadMessageDto, - SendPresenceDto, - UpdateMessageDto, - WhatsAppNumberDto, -} from '../../dto/chat.dto'; -import { - AcceptGroupInvite, - CreateGroupDto, - GetParticipant, - GroupDescriptionDto, - GroupInvite, - GroupJid, - GroupPictureDto, - GroupSendInvite, - GroupSubjectDto, - GroupToggleEphemeralDto, - GroupUpdateParticipantDto, - GroupUpdateSettingDto, -} from '../../dto/group.dto'; -import { InstanceDto, SetPresenceDto } from '../../dto/instance.dto'; -import { HandleLabelDto, LabelDto } from '../../dto/label.dto'; -import { - ContactMessage, - MediaMessage, - Options, - SendAudioDto, - SendContactDto, - SendListDto, - SendLocationDto, - SendMediaDto, - SendPollDto, - SendReactionDto, - SendStatusDto, - SendStickerDto, - SendTextDto, - StatusMessage, -} from '../../dto/sendMessage.dto'; -import { chatwootImport } from '../../integrations/chatwoot/utils/chatwoot-import-helper'; -import * as s3Service from '../../integrations/s3/libs/minio.server'; -import { ProviderFiles } from '../../provider/sessions'; -import { PrismaRepository } from '../../repository/repository.service'; -import { waMonitor } from '../../server.module'; -import { Events, MessageSubtype, TypeMediaMessage, wa } from '../../types/wa.types'; -import { CacheService } from './../cache.service'; -import { ChannelStartupService } from './../channel.service'; - const groupMetadataCache = new CacheService(new CacheEngine(configService, 'groups').getEngine()); export class BaileysStartupService extends ChannelStartupService { @@ -151,7 +144,6 @@ export class BaileysStartupService extends ChannelStartupService { ) { super(configService, eventEmitter, prismaRepository, chatwootCache); this.instance.qrcode = { count: 0 }; - this.recoveringMessages(); this.authStateProvider = new AuthStateProvider(this.providerFiles); } @@ -166,58 +158,6 @@ export class BaileysStartupService extends ChannelStartupService { public phoneNumber: string; - private async recoveringMessages() { - const cacheConf = this.configService.get('CACHE'); - - if ((cacheConf?.REDIS?.ENABLED && cacheConf?.REDIS?.URI !== '') || cacheConf?.LOCAL?.ENABLED) { - this.logger.info('Recovering messages lost from cache'); - setInterval(async () => { - this.baileysCache.keys().then((keys) => { - keys.forEach(async (key) => { - const data = await this.baileysCache.get(key.split(':')[2]); - - let message: any; - let retry: number; - - if (!data?.message) { - message = data; - retry = 0; - } else { - message = data.message; - retry = data.retry; - } - - if (message.messageStubParameters && message.messageStubParameters[0] === 'Message absent from node') { - retry = retry + 1; - this.logger.info(`Message absent from node, retrying to send, key: ${key.split(':')[2]} retry: ${retry}`); - if (message.messageStubParameters[1]) { - await this.client.sendMessageAck(JSON.parse(message.messageStubParameters[1], BufferJSON.reviver)); - } - - this.baileysCache.set(key.split(':')[2], { message, retry }); - - if (retry >= 100) { - this.logger.warn(`Message absent from node, retry limit reached, key: ${key.split(':')[2]}`); - this.baileysCache.delete(key.split(':')[2]); - return; - } - } - }); - }); - // 15 minutes - }, 15 * 60 * 1000); - } - } - - private async forceUpdateGroupMetadataCache() { - this.logger.verbose('Force update group metadata cache'); - const groups = await this.fetchAllGroups({ getParticipants: 'false' }); - - for (const group of groups) { - await this.updateGroupMetadataCache(group.id); - } - } - public get connectionStatus() { return this.stateConnection; } @@ -227,31 +167,27 @@ export class BaileysStartupService extends ChannelStartupService { this.client?.ws?.close(); - await this.prismaRepository.session.delete({ - where: { - sessionId: this.instanceId, - }, + const sessionExists = await this.prismaRepository.session.findFirst({ + where: { sessionId: this.instanceId }, }); + if (sessionExists) { + await this.prismaRepository.session.delete({ + where: { + sessionId: this.instanceId, + }, + }); + } } public async getProfileName() { let profileName = this.client.user?.name ?? this.client.user?.verifiedName; if (!profileName) { - if (this.configService.get('DATABASE').ENABLED) { - const data = await this.prismaRepository.session.findUnique({ - where: { sessionId: this.instanceId }, - }); + const data = await this.prismaRepository.session.findUnique({ + where: { sessionId: this.instanceId }, + }); - if (data) { - const creds = JSON.parse(JSON.stringify(data.creds), BufferJSON.reviver); - profileName = creds.me?.name || creds.me?.verifiedName; - } - } else if (existsSync(join(INSTANCE_DIR, this.instanceName, 'creds.json'))) { - const creds = JSON.parse( - readFileSync(join(INSTANCE_DIR, this.instanceName, 'creds.json'), { - encoding: 'utf-8', - }), - ); + if (data) { + const creds = JSON.parse(JSON.stringify(data.creds), BufferJSON.reviver); profileName = creds.me?.name || creds.me?.verifiedName; } } @@ -286,7 +222,7 @@ export class BaileysStartupService extends ChannelStartupService { statusCode: DisconnectReason.badSession, }); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot.enabled) { + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { this.chatwootService.eventWhatsapp( Events.QRCODE_UPDATED, { instanceName: this.instance.name, instanceId: this.instanceId }, @@ -344,7 +280,7 @@ export class BaileysStartupService extends ChannelStartupService { }, }); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot.enabled) { + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { this.chatwootService.eventWhatsapp( Events.QRCODE_UPDATED, { instanceName: this.instance.name, instanceId: this.instanceId }, @@ -388,25 +324,31 @@ export class BaileysStartupService extends ChannelStartupService { } if (connection === 'close') { - const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut; + const statusCode = (lastDisconnect?.error as Boom)?.output?.statusCode; + const codesToNotReconnect = [DisconnectReason.loggedOut, DisconnectReason.forbidden, 402, 406]; + const shouldReconnect = !codesToNotReconnect.includes(statusCode); if (shouldReconnect) { await this.connectToWhatsapp(this.phoneNumber); } else { this.sendDataWebhook(Events.STATUS_INSTANCE, { instance: this.instance.name, status: 'closed', + disconnectionAt: new Date(), + disconnectionReasonCode: statusCode, + disconnectionObject: JSON.stringify(lastDisconnect), }); - if (this.configService.get('DATABASE').ENABLED) { - await this.prismaRepository.instance.update({ - where: { id: this.instanceId }, - data: { - connectionStatus: 'close', - }, - }); - } + await this.prismaRepository.instance.update({ + where: { id: this.instanceId }, + data: { + connectionStatus: 'close', + disconnectionAt: new Date(), + disconnectionReasonCode: statusCode, + disconnectionObject: JSON.stringify(lastDisconnect), + }, + }); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot.enabled) { + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { this.chatwootService.eventWhatsapp( Events.STATUS_INSTANCE, { instanceName: this.instance.name, instanceId: this.instanceId }, @@ -423,17 +365,6 @@ export class BaileysStartupService extends ChannelStartupService { } } - // if (connection === 'connecting') { - // if (this.configService.get('DATABASE').ENABLED) { - // await this.prismaRepository.instance.update({ - // where: { id: this.instanceId }, - // data: { - // connectionStatus: 'connecting', - // }, - // }); - // } - // } - if (connection === 'open') { this.instance.wuid = this.client.user.id.replace(/:\d+/, ''); this.instance.profilePictureUrl = (await this.profilePicture(this.instance.wuid)).profilePictureUrl; @@ -452,19 +383,17 @@ export class BaileysStartupService extends ChannelStartupService { `, ); - if (this.configService.get('DATABASE').ENABLED) { - await this.prismaRepository.instance.update({ - where: { id: this.instanceId }, - data: { - ownerJid: this.instance.wuid, - profileName: (await this.getProfileName()) as string, - profilePicUrl: this.instance.profilePictureUrl, - connectionStatus: 'open', - }, - }); - } + await this.prismaRepository.instance.update({ + where: { id: this.instanceId }, + data: { + ownerJid: this.instance.wuid, + profileName: (await this.getProfileName()) as string, + profilePicUrl: this.instance.profilePictureUrl, + connectionStatus: 'open', + }, + }); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot.enabled) { + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { this.chatwootService.eventWhatsapp( Events.CONNECTION_UPDATE, { instanceName: this.instance.name, instanceId: this.instanceId }, @@ -510,6 +439,7 @@ export class BaileysStartupService extends ChannelStartupService { return webMessageInfo[0].message; } catch (error) { + this.logger.error('line 508'); return { conversation: '' }; } } @@ -529,7 +459,7 @@ export class BaileysStartupService extends ChannelStartupService { return await useMultiFileAuthStateRedisDb(this.instance.id, this.cache); } - if (db.SAVE_DATA.INSTANCE && db.ENABLED) { + if (db.SAVE_DATA.INSTANCE) { return await useMultiFileAuthStatePrisma(this.instance.id, this.cache); } } @@ -570,7 +500,7 @@ export class BaileysStartupService extends ChannelStartupService { let options; - if (this.localProxy.enabled) { + if (this.localProxy?.enabled) { this.logger.info('Proxy enabled: ' + this.localProxy?.host); if (this.localProxy?.host?.includes('proxyscrape')) { @@ -609,56 +539,40 @@ export class BaileysStartupService extends ChannelStartupService { const socketConfig: UserFacingSocketConfig = { ...options, + version, + logger: P({ level: this.logBaileys }), + printQRInTerminal: false, auth: { creds: this.instance.authState.state.creds, keys: makeCacheableSignalKeyStore(this.instance.authState.state.keys, P({ level: 'error' }) as any), }, - logger: P({ level: this.logBaileys }), - printQRInTerminal: false, + msgRetryCounterCache: this.msgRetryCounterCache, + generateHighQualityLinkPreview: true, + getMessage: async (key) => (await this.getMessage(key)) as Promise, ...browserOptions, - version, markOnlineOnConnect: this.localSettings.alwaysOnline, retryRequestDelayMs: 350, maxMsgRetryCount: 4, fireInitQueries: true, - connectTimeoutMs: 20_000, + connectTimeoutMs: 30_000, keepAliveIntervalMs: 30_000, qrTimeout: 45_000, emitOwnEvents: false, shouldIgnoreJid: (jid) => { const isGroupJid = this.localSettings.groupsIgnore && isJidGroup(jid); const isBroadcast = !this.localSettings.readStatus && isJidBroadcast(jid); - const isNewsletter = jid.includes('newsletter'); + const isNewsletter = isJidNewsletter(jid); + // const isNewsletter = jid && jid.includes('newsletter'); return isGroupJid || isBroadcast || isNewsletter; }, - msgRetryCounterCache: this.msgRetryCounterCache, - getMessage: async (key) => (await this.getMessage(key)) as Promise, - generateHighQualityLinkPreview: true, syncFullHistory: this.localSettings.syncFullHistory, shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => { return this.historySyncNotification(msg); }, + cachedGroupMetadata: this.getGroupMetadataCache, userDevicesCache: this.userDevicesCache, transactionOpts: { maxCommitRetries: 10, delayBetweenTriesMs: 3000 }, - patchMessageBeforeSending(message) { - if ( - message.deviceSentMessage?.message?.listMessage?.listType === proto.Message.ListMessage.ListType.PRODUCT_LIST - ) { - message = JSON.parse(JSON.stringify(message)); - - message.deviceSentMessage.message.listMessage.listType = proto.Message.ListMessage.ListType.SINGLE_SELECT; - } - - if (message.listMessage?.listType == proto.Message.ListMessage.ListType.PRODUCT_LIST) { - message = JSON.parse(JSON.stringify(message)); - - message.listMessage.listType = proto.Message.ListMessage.ListType.SINGLE_SELECT; - } - - return message; - }, - forceGroupsPrekeys: false, }; this.endSession = false; @@ -674,16 +588,13 @@ export class BaileysStartupService extends ChannelStartupService { public async connectToWhatsapp(number?: string): Promise { try { - this.loadWebhook(); this.loadChatwoot(); this.loadSettings(); - this.loadWebsocket(); - this.loadRabbitmq(); - this.loadSqs(); this.loadProxy(); return await this.createClient(number); } catch (error) { + this.logger.error('line 667'); this.logger.error(error); throw new InternalServerErrorException(error?.toString()); } @@ -693,6 +604,7 @@ export class BaileysStartupService extends ChannelStartupService { try { return await this.createClient(this.phoneNumber); } catch (error) { + this.logger.error('line 677'); this.logger.error(error); throw new InternalServerErrorException(error?.toString()); } @@ -708,8 +620,8 @@ export class BaileysStartupService extends ChannelStartupService { const existingChatIdSet = new Set(existingChatIds.map((chat) => chat.remoteJid)); const chatsToInsert = chats - .filter((chat) => !existingChatIdSet.has(chat.id)) - .map((chat) => ({ remoteJid: chat.id, instanceId: this.instanceId })); + .filter((chat) => !existingChatIdSet?.has(chat.id)) + .map((chat) => ({ remoteJid: chat.id, instanceId: this.instanceId, name: chat.name })); this.sendDataWebhook(Events.CHATS_UPSERT, chatsToInsert); @@ -717,6 +629,7 @@ export class BaileysStartupService extends ChannelStartupService { if (this.configService.get('DATABASE').SAVE_DATA.CHATS) await this.prismaRepository.chat.createMany({ data: chatsToInsert, + skipDuplicates: true, }); } }, @@ -741,10 +654,9 @@ export class BaileysStartupService extends ChannelStartupService { where: { instanceId: this.instanceId, remoteJid: chat.id, + name: chat.name, }, - data: { - remoteJid: chat.id, - }, + data: { remoteJid: chat.id }, }); } }, @@ -771,19 +683,24 @@ export class BaileysStartupService extends ChannelStartupService { instanceId: this.instanceId, })); - if (contactsRaw.length > 0) this.sendDataWebhook(Events.CONTACTS_UPSERT, contactsRaw); - if (contactsRaw.length > 0) { + this.sendDataWebhook(Events.CONTACTS_UPSERT, contactsRaw); + if (this.configService.get('DATABASE').SAVE_DATA.CONTACTS) await this.prismaRepository.contact.createMany({ data: contactsRaw, skipDuplicates: true, }); + + const usersContacts = contactsRaw.filter((c) => c.remoteJid.includes('@s.whatsapp')); + if (usersContacts) { + await saveOnWhatsappCache(usersContacts.map((c) => ({ remoteJid: c.remoteJid }))); + } } if ( this.configService.get('CHATWOOT').ENABLED && - this.localChatwoot.enabled && + this.localChatwoot?.enabled && this.localChatwoot.importContacts && contactsRaw.length ) { @@ -806,27 +723,58 @@ export class BaileysStartupService extends ChannelStartupService { })), ); - if (updatedContacts.length > 0) this.sendDataWebhook(Events.CONTACTS_UPDATE, updatedContacts); - if (updatedContacts.length > 0) { + const usersContacts = updatedContacts.filter((c) => c.remoteJid.includes('@s.whatsapp')); + if (usersContacts) { + await saveOnWhatsappCache(usersContacts.map((c) => ({ remoteJid: c.remoteJid }))); + } + + this.sendDataWebhook(Events.CONTACTS_UPDATE, updatedContacts); await Promise.all( - updatedContacts.map((contact) => - this.prismaRepository.contact.updateMany({ + updatedContacts.map(async (contact) => { + const update = this.prismaRepository.contact.updateMany({ where: { remoteJid: contact.remoteJid, instanceId: this.instanceId }, data: { profilePicUrl: contact.profilePicUrl, }, - }), - ), + }); + + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { + const instance = { instanceName: this.instance.name, instanceId: this.instance.id }; + + const findParticipant = await this.chatwootService.findContact( + instance, + contact.remoteJid.split('@')[0], + ); + + if (!findParticipant) { + return; + } + + this.chatwootService.updateContact(instance, findParticipant.id, { + name: contact.pushName, + avatar_url: contact.profilePicUrl, + }); + } + + return update; + }), ); } } catch (error) { + console.error(error); + this.logger.error('line 817'); this.logger.error(`Error: ${error.message}`); } }, 'contacts.update': async (contacts: Partial[]) => { - const contactsRaw: any = []; + const contactsRaw: { + remoteJid: string; + pushName?: string; + profilePicUrl?: string; + instanceId: string; + }[] = []; for await (const contact of contacts) { contactsRaw.push({ remoteJid: contact.id, @@ -838,10 +786,19 @@ export class BaileysStartupService extends ChannelStartupService { this.sendDataWebhook(Events.CONTACTS_UPDATE, contactsRaw); - this.prismaRepository.contact.updateMany({ - where: { instanceId: this.instanceId }, - data: contactsRaw, - }); + const updateTransactions = contactsRaw.map((contact) => + this.prismaRepository.contact.upsert({ + where: { remoteJid_instanceId: { remoteJid: contact.remoteJid, instanceId: contact.instanceId } }, + create: contact, + update: contact, + }), + ); + await this.prismaRepository.$transaction(updateTransactions); + + const usersContacts = contactsRaw.filter((c) => c.remoteJid.includes('@s.whatsapp')); + if (usersContacts) { + await saveOnWhatsappCache(usersContacts.map((c) => ({ remoteJid: c.remoteJid }))); + } }, }; @@ -850,19 +807,31 @@ export class BaileysStartupService extends ChannelStartupService { messages, chats, contacts, + isLatest, + progress, + syncType, }: { chats: Chat[]; contacts: Contact[]; messages: proto.IWebMessageInfo[]; - isLatest: boolean; + isLatest?: boolean; + progress?: number; + syncType?: proto.HistorySync.HistorySyncType; }) => { try { + if (syncType === proto.HistorySync.HistorySyncType.ON_DEMAND) { + console.log('received on-demand history sync, messages=', messages); + } + console.log( + `recv ${chats.length} chats, ${contacts.length} contacts, ${messages.length} msgs (is latest: ${isLatest}, progress: ${progress}%), type: ${syncType}`, + ); + const instance: InstanceDto = { instanceName: this.instance.name }; let timestampLimitToImport = null; if (this.configService.get('CHATWOOT').ENABLED) { - const daysLimitToImport = this.localChatwoot.enabled ? this.localChatwoot.daysLimitImportMessages : 1000; + const daysLimitToImport = this.localChatwoot?.enabled ? this.localChatwoot.daysLimitImportMessages : 1000; const date = new Date(); timestampLimitToImport = new Date(date.setDate(date.getDate() - daysLimitToImport)).getTime() / 1000; @@ -876,7 +845,7 @@ export class BaileysStartupService extends ChannelStartupService { } } - const chatsRaw: any[] = []; + const chatsRaw: { remoteJid: string; instanceId: string; name?: string }[] = []; const chatsRepository = new Set( ( await this.prismaRepository.chat.findMany({ @@ -886,25 +855,24 @@ export class BaileysStartupService extends ChannelStartupService { ); for (const chat of chats) { - if (chatsRepository.has(chat.id)) { + if (chatsRepository?.has(chat.id)) { continue; } chatsRaw.push({ remoteJid: chat.id, instanceId: this.instanceId, + name: chat.name, }); } this.sendDataWebhook(Events.CHATS_SET, chatsRaw); if (this.configService.get('DATABASE').SAVE_DATA.HISTORIC) { - const chatsSaved = await this.prismaRepository.chat.createMany({ + await this.prismaRepository.chat.createMany({ data: chatsRaw, skipDuplicates: true, }); - - console.log('chatsSaved', chatsSaved); } const messagesRaw: any[] = []; @@ -944,36 +912,25 @@ export class BaileysStartupService extends ChannelStartupService { } } - if (messagesRepository.has(m.key.id)) { + if (messagesRepository?.has(m.key.id)) { continue; } - messagesRaw.push({ - key: m.key, - pushName: m.pushName || m.key.remoteJid.split('@')[0], - participant: m.participant, - message: { ...m.message }, - messageType: getContentType(m.message), - messageTimestamp: m.messageTimestamp as number, - instanceId: this.instanceId, - source: getDevice(m.key.id), - }); + messagesRaw.push(this.prepareMessage(m)); } this.sendDataWebhook(Events.MESSAGES_SET, [...messagesRaw]); if (this.configService.get('DATABASE').SAVE_DATA.HISTORIC) { - const messagesSaved = await this.prismaRepository.message.createMany({ + await this.prismaRepository.message.createMany({ data: messagesRaw, skipDuplicates: true, }); - - console.log('messagesSaved', messagesSaved); } if ( this.configService.get('CHATWOOT').ENABLED && - this.localChatwoot.enabled && + this.localChatwoot?.enabled && this.localChatwoot.importMessages && messagesRaw.length > 0 ) { @@ -985,7 +942,7 @@ export class BaileysStartupService extends ChannelStartupService { await this.contactHandle['contacts.upsert']( contacts - .filter((c) => !!c.notify ?? !!c.name) + .filter((c) => !!c.notify || !!c.name) .map((c) => ({ id: c.id, name: c.name ?? c.notify, @@ -996,6 +953,7 @@ export class BaileysStartupService extends ChannelStartupService { messages = undefined; chats = undefined; } catch (error) { + this.logger.error('line 1011'); this.logger.error(error); } }, @@ -1004,19 +962,36 @@ export class BaileysStartupService extends ChannelStartupService { { messages, type, + requestId, }: { messages: proto.IWebMessageInfo[]; type: MessageUpsertType; + requestId?: string; }, settings: any, ) => { try { for (const received of messages) { + if (received.message?.conversation || received.message?.extendedTextMessage?.text) { + const text = received.message?.conversation || received.message?.extendedTextMessage?.text; + if (text == 'requestPlaceholder' && !requestId) { + const messageId = await this.client.requestPlaceholderResend(received.key); + console.log('requested placeholder resync, id=', messageId); + } else if (requestId) { + console.log('Message received from phone, id=', requestId, received); + } + + if (text == 'onDemandHistSync') { + const messageId = await this.client.fetchMessageHistory(50, received.key, received.messageTimestamp!); + console.log('requested on-demand sync, id=', messageId); + } + } + if (received.message?.protocolMessage?.editedMessage || received.message?.editedMessage?.message) { const editedMessage = received.message?.protocolMessage || received.message?.editedMessage?.message?.protocolMessage; if (editedMessage) { - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot.enabled) + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) this.chatwootService.eventWhatsapp( 'messages.edit', { instanceName: this.instance.name, instanceId: this.instance.id }, @@ -1061,18 +1036,7 @@ export class BaileysStartupService extends ChannelStartupService { return; } - const contentMsg = received?.message[getContentType(received.message)] as any; - - const messageRaw: any = { - key: received.key, - pushName: received.pushName, - message: { ...received.message }, - contextInfo: contentMsg?.contextInfo, - messageType: getContentType(received.message), - messageTimestamp: received.messageTimestamp as number, - instanceId: this.instanceId, - source: getDevice(received.key.id), - }; + const messageRaw = this.prepareMessage(received); const isMedia = received?.message?.imageMessage || @@ -1092,7 +1056,7 @@ export class BaileysStartupService extends ChannelStartupService { if ( this.configService.get('CHATWOOT').ENABLED && - this.localChatwoot.enabled && + this.localChatwoot?.enabled && !received.key.id.includes('@broadcast') ) { const chatwootSentMessage = await this.chatwootService.eventWhatsapp( @@ -1108,66 +1072,6 @@ export class BaileysStartupService extends ChannelStartupService { } } - if (this.configService.get('DATABASE').SAVE_DATA.NEW_MESSAGE) { - const msg = await this.prismaRepository.message.create({ - data: messageRaw, - }); - - if (isMedia) { - if (this.configService.get('S3').ENABLE) { - try { - const message: any = received; - const media = await this.getBase64FromMediaMessage( - { - message, - }, - true, - ); - - const { buffer, mediaType, fileName, size } = media; - - const mimetype = mime.lookup(fileName).toString(); - - const fullName = join(`${this.instance.id}`, received.key.remoteJid, mediaType, fileName); - - await s3Service.uploadFile(fullName, buffer, size.fileLength, { - 'Content-Type': mimetype, - }); - - await this.prismaRepository.media.create({ - data: { - messageId: msg.id, - instanceId: this.instanceId, - type: mediaType, - fileName: fullName, - mimetype, - }, - }); - - const mediaUrl = await s3Service.getObjectUrl(fullName); - - messageRaw.message.mediaUrl = mediaUrl; - } catch (error) { - this.logger.error(['Error on upload file to minio', error?.message, error?.stack]); - } - } - } - } - - if (isMedia && !this.configService.get('S3').ENABLE && this.localWebhook.webhookBase64 === true) { - const buffer = await downloadMediaMessage( - { key: received.key, message: received?.message }, - 'buffer', - {}, - { - logger: P({ level: 'error' }) as any, - reuploadRequest: this.client.updateMediaMessage, - }, - ); - - messageRaw.message.base64 = buffer ? buffer.toString('base64') : undefined; - } - if (this.configService.get('OPENAI').ENABLED) { const openAiDefaultSettings = await this.prismaRepository.openaiSetting.findFirst({ where: { @@ -1192,60 +1096,100 @@ export class BaileysStartupService extends ChannelStartupService { } } + if (this.configService.get('DATABASE').SAVE_DATA.NEW_MESSAGE) { + const msg = await this.prismaRepository.message.create({ + data: messageRaw, + }); + + if (isMedia) { + if (this.configService.get('S3').ENABLE) { + try { + const message: any = received; + const media = await this.getBase64FromMediaMessage( + { + message, + }, + true, + ); + + const { buffer, mediaType, fileName, size } = media; + + const mimetype = mime.getType(fileName).toString(); + + const fullName = join(`${this.instance.id}`, received.key.remoteJid, mediaType, fileName); + + await s3Service.uploadFile(fullName, buffer, size.fileLength?.low, { + 'Content-Type': mimetype, + }); + + await this.prismaRepository.media.create({ + data: { + messageId: msg.id, + instanceId: this.instanceId, + type: mediaType, + fileName: fullName, + mimetype, + }, + }); + + const mediaUrl = await s3Service.getObjectUrl(fullName); + + messageRaw.message.mediaUrl = mediaUrl; + + await this.prismaRepository.message.update({ + where: { id: msg.id }, + data: messageRaw, + }); + } catch (error) { + this.logger.error('line 1181'); + this.logger.error(['Error on upload file to minio', error?.message, error?.stack]); + } + } + } + } + + if (isMedia && !this.configService.get('S3').ENABLE) { + const buffer = await downloadMediaMessage( + { key: received.key, message: received?.message }, + 'buffer', + {}, + { + logger: P({ level: 'error' }) as any, + reuploadRequest: this.client.updateMediaMessage, + }, + ); + + messageRaw.message.base64 = buffer ? buffer.toString('base64') : undefined; + } + this.logger.log(messageRaw); this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw); - if (this.configService.get('TYPEBOT').ENABLED) { - if (type === 'notify') { - if (messageRaw.messageType !== 'reactionMessage') - await this.typebotService.sendTypebot( - { instanceName: this.instance.name, instanceId: this.instanceId }, - messageRaw.key.remoteJid, - messageRaw, - ); - } - } - - if (this.configService.get('OPENAI').ENABLED) { - if (type === 'notify') { - if (messageRaw.messageType !== 'reactionMessage') - await this.openaiService.sendOpenai( - { instanceName: this.instance.name, instanceId: this.instanceId }, - messageRaw.key.remoteJid, - messageRaw, - ); - } - } - - if (this.configService.get('DIFY').ENABLED) { - if (type === 'notify') { - if (messageRaw.messageType !== 'reactionMessage') - await this.difyService.sendDify( - { instanceName: this.instance.name, instanceId: this.instanceId }, - messageRaw.key.remoteJid, - messageRaw, - ); - } - } + await chatbotController.emit({ + instance: { instanceName: this.instance.name, instanceId: this.instanceId }, + remoteJid: messageRaw.key.remoteJid, + msg: messageRaw, + pushName: messageRaw.pushName, + }); const contact = await this.prismaRepository.contact.findFirst({ where: { remoteJid: received.key.remoteJid, instanceId: this.instanceId }, }); - const contactRaw: any = { + const contactRaw: { remoteJid: string; pushName: string; profilePicUrl?: string; instanceId: string } = { remoteJid: received.key.remoteJid, pushName: received.pushName, profilePicUrl: (await this.profilePicture(received.key.remoteJid)).profilePictureUrl, instanceId: this.instanceId, }; - if (contactRaw.id === 'status@broadcast') { + if (contactRaw.remoteJid === 'status@broadcast') { return; } if (contact) { - const contactRaw: any = { + const contactRaw: { remoteJid: string; pushName: string; profilePicUrl?: string; instanceId: string } = { remoteJid: received.key.remoteJid, pushName: contact.pushName, profilePicUrl: (await this.profilePicture(received.key.remoteJid)).profilePictureUrl, @@ -1254,7 +1198,7 @@ export class BaileysStartupService extends ChannelStartupService { this.sendDataWebhook(Events.CONTACTS_UPDATE, contactRaw); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot.enabled) { + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { await this.chatwootService.eventWhatsapp( Events.CONTACTS_UPDATE, { instanceName: this.instance.name, instanceId: this.instanceId }, @@ -1274,8 +1218,27 @@ export class BaileysStartupService extends ChannelStartupService { data: contactRaw, }); } + + this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw); + + if (this.configService.get('DATABASE').SAVE_DATA.CONTACTS) + await this.prismaRepository.contact.upsert({ + where: { + remoteJid_instanceId: { + remoteJid: contactRaw.remoteJid, + instanceId: contactRaw.instanceId, + }, + }, + update: contactRaw, + create: contactRaw, + }); + + if (contactRaw.remoteJid.includes('@s.whatsapp')) { + await saveOnWhatsappCache([{ remoteJid: contactRaw.remoteJid }]); + } } } catch (error) { + this.logger.error('line 1318'); this.logger.error(error); } }, @@ -1295,7 +1258,7 @@ export class BaileysStartupService extends ChannelStartupService { } if (status[update.status] === 'READ' && key.fromMe) { - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot.enabled) { + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { this.chatwootService.eventWhatsapp( 'messages.read', { instanceName: this.instance.name, instanceId: this.instanceId }, @@ -1351,7 +1314,7 @@ export class BaileysStartupService extends ChannelStartupService { data: message, }); - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot.enabled) { + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { this.chatwootService.eventWhatsapp( Events.MESSAGES_DELETE, { instanceName: this.instance.name, instanceId: this.instanceId }, @@ -1419,7 +1382,7 @@ export class BaileysStartupService extends ChannelStartupService { const savedLabel = labelsRepository.find((l) => l.labelId === label.id); if (label.deleted && savedLabel) { await this.prismaRepository.label.delete({ - where: { instanceId: this.instanceId, labelId: label.id }, + where: { labelId_instanceId: { instanceId: this.instanceId, labelId: label.id } }, }); this.sendDataWebhook(Events.LABELS_EDIT, { ...label, instance: this.instance.name }); return; @@ -1427,16 +1390,25 @@ export class BaileysStartupService extends ChannelStartupService { const labelName = label.name.replace(/[^\x20-\x7E]/g, ''); if (!savedLabel || savedLabel.color !== `${label.color}` || savedLabel.name !== labelName) { - if (this.configService.get('DATABASE').SAVE_DATA.LABELS) - await this.prismaRepository.label.create({ - data: { - color: `${label.color}`, - name: labelName, - labelId: label.id, - predefinedId: label.predefinedId, - instanceId: this.instanceId, + if (this.configService.get('DATABASE').SAVE_DATA.LABELS) { + const labelData = { + color: `${label.color}`, + name: labelName, + labelId: label.id, + predefinedId: label.predefinedId, + instanceId: this.instanceId, + }; + await this.prismaRepository.label.upsert({ + where: { + labelId_instanceId: { + instanceId: labelData.instanceId, + labelId: labelData.labelId, + }, }, + update: labelData, + create: labelData, }); + } this.sendDataWebhook(Events.LABELS_EDIT, { ...label, instance: this.instance.name }); } }, @@ -1445,7 +1417,7 @@ export class BaileysStartupService extends ChannelStartupService { data: { association: LabelAssociation; type: 'remove' | 'add' }, database: Database, ) => { - if (database.ENABLED && database.SAVE_DATA.CHATS) { + if (database.SAVE_DATA.CHATS) { const chats = await this.prismaRepository.chat.findMany({ where: { instanceId: this.instanceId }, }); @@ -1468,7 +1440,6 @@ export class BaileysStartupService extends ChannelStartupService { } } - // Envia dados para o webhook this.sendDataWebhook(Events.LABELS_ASSOCIATION, { instance: this.instance.name, type: data.type, @@ -1599,7 +1570,7 @@ export class BaileysStartupService extends ChannelStartupService { if ( this.configService.get('CHATWOOT').ENABLED && - this.localChatwoot.enabled && + this.localChatwoot?.enabled && this.localChatwoot.importMessages && this.isSyncNotificationFromUsedSyncType(msg) ) { @@ -1628,9 +1599,11 @@ export class BaileysStartupService extends ChannelStartupService { const jid = this.createJid(number); try { + const profilePictureUrl = await this.client.profilePictureUrl(jid, 'image'); + return { wuid: jid, - profilePictureUrl: await this.client.profilePictureUrl(jid, 'image'), + profilePictureUrl, }; } catch (error) { return { @@ -1719,18 +1692,18 @@ export class BaileysStartupService extends ChannelStartupService { quoted: any, messageId?: string, ephemeralExpiration?: number, - participants?: GroupParticipant[], + // participants?: GroupParticipant[], ) { const option: any = { quoted, }; if (isJidGroup(sender)) { - if (participants) - option.cachedGroupMetadata = async () => { - return { participants: participants as GroupParticipant[] }; - }; - else option.cachedGroupMetadata = this.getGroupMetadataCache; + option.useCachedGroupMetadata = true; + // if (participants) + // option.cachedGroupMetadata = async () => { + // return { participants: participants as GroupParticipant[] }; + // }; } if (ephemeralExpiration) option.ephemeralExpiration = ephemeralExpiration; @@ -1852,7 +1825,7 @@ export class BaileysStartupService extends ChannelStartupService { const isWA = (await this.whatsappNumber({ numbers: [number] }))?.shift(); if (!isWA.exists && !isJidGroup(isWA.jid) && !isWA.jid.includes('@broadcast')) { - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot.enabled) { + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { const body = { key: { remoteJid: isWA.jid }, }; @@ -1957,34 +1930,27 @@ export class BaileysStartupService extends ChannelStartupService { quoted, null, group?.ephemeralDuration, - group.participants, + // group?.participants, ); } else { messageSent = await this.sendMessage(sender, message, mentions, linkPreview, quoted); } - const contentMsg = messageSent.message[getContentType(messageSent.message)] as any; - if (Long.isLong(messageSent?.messageTimestamp)) { messageSent.messageTimestamp = messageSent.messageTimestamp?.toNumber(); } - const messageRaw: any = { - key: messageSent.key, - pushName: messageSent.pushName, - message: { ...messageSent.message }, - contextInfo: contentMsg?.contextInfo, - messageType: getContentType(messageSent.message), - messageTimestamp: messageSent.messageTimestamp as number, - instanceId: this.instanceId, - source: getDevice(messageSent.key.id), - }; + const messageRaw = this.prepareMessage(messageSent); - this.logger.log(messageRaw); + const isMedia = + messageSent?.message?.imageMessage || + messageSent?.message?.videoMessage || + messageSent?.message?.stickerMessage || + messageSent?.message?.documentMessage || + messageSent?.message?.documentWithCaptionMessage || + messageSent?.message?.audioMessage; - this.sendDataWebhook(Events.SEND_MESSAGE, messageRaw); - - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot.enabled && !isIntegration) { + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled && !isIntegration) { this.chatwootService.eventWhatsapp( Events.SEND_MESSAGE, { instanceName: this.instance.name, instanceId: this.instanceId }, @@ -1992,13 +1958,111 @@ export class BaileysStartupService extends ChannelStartupService { ); } - if (this.configService.get('DATABASE').SAVE_DATA.NEW_MESSAGE) - await this.prismaRepository.message.create({ + if (this.configService.get('OPENAI').ENABLED) { + const openAiDefaultSettings = await this.prismaRepository.openaiSetting.findFirst({ + where: { + instanceId: this.instanceId, + }, + include: { + OpenaiCreds: true, + }, + }); + + if ( + openAiDefaultSettings && + openAiDefaultSettings.openaiCredsId && + openAiDefaultSettings.speechToText && + messageRaw?.message?.audioMessage + ) { + messageRaw.message.speechToText = await this.openaiService.speechToText( + openAiDefaultSettings.OpenaiCreds, + messageRaw, + this.client.updateMediaMessage, + ); + } + } + + if (this.configService.get('DATABASE').SAVE_DATA.NEW_MESSAGE) { + const msg = await this.prismaRepository.message.create({ data: messageRaw, }); - return messageSent; + if (isMedia && this.configService.get('S3').ENABLE) { + try { + const message: any = messageRaw; + const media = await this.getBase64FromMediaMessage( + { + message, + }, + true, + ); + + const { buffer, mediaType, fileName, size } = media; + + const mimetype = mime.getType(fileName).toString(); + + const fullName = join(`${this.instance.id}`, messageRaw.key.remoteJid, mediaType, fileName); + + await s3Service.uploadFile(fullName, buffer, size.fileLength?.low, { + 'Content-Type': mimetype, + }); + + await this.prismaRepository.media.create({ + data: { + messageId: msg.id, + instanceId: this.instanceId, + type: mediaType, + fileName: fullName, + mimetype, + }, + }); + + const mediaUrl = await s3Service.getObjectUrl(fullName); + + messageRaw.message.mediaUrl = mediaUrl; + + await this.prismaRepository.message.update({ + where: { id: msg.id }, + data: messageRaw, + }); + } catch (error) { + this.logger.error('line 1181'); + this.logger.error(['Error on upload file to minio', error?.message, error?.stack]); + } + } + } + + if (isMedia && !this.configService.get('S3').ENABLE) { + const buffer = await downloadMediaMessage( + { key: messageRaw.key, message: messageRaw?.message }, + 'buffer', + {}, + { + logger: P({ level: 'error' }) as any, + reuploadRequest: this.client.updateMediaMessage, + }, + ); + + messageRaw.message.base64 = buffer ? buffer.toString('base64') : undefined; + } + + this.logger.log(messageRaw); + + this.sendDataWebhook(Events.SEND_MESSAGE, messageRaw); + + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled && isIntegration) { + await chatbotController.emit({ + instance: { instanceName: this.instance.name, instanceId: this.instanceId }, + remoteJid: messageRaw.key.remoteJid, + msg: messageRaw, + pushName: messageRaw.pushName, + isIntegration, + }); + } + + return messageRaw; } catch (error) { + this.logger.error('line 2097'); this.logger.error(error); throw new BadRequestException(error.toString()); } @@ -2051,6 +2115,7 @@ export class BaileysStartupService extends ChannelStartupService { return { presence: data.presence }; } catch (error) { + this.logger.error('line 2134'); this.logger.error(error); throw new BadRequestException(error.toString()); } @@ -2063,6 +2128,7 @@ export class BaileysStartupService extends ChannelStartupService { return { presence: data.presence }; } catch (error) { + this.logger.error('line 2147'); this.logger.error(error); throw new BadRequestException(error.toString()); } @@ -2250,14 +2316,14 @@ export class BaileysStartupService extends ChannelStartupService { if (mediaMessage.mimetype) { mimetype = mediaMessage.mimetype; } else { - mimetype = getMIMEType(mediaMessage.fileName); + mimetype = mime.getType(mediaMessage.fileName); if (!mimetype && isURL(mediaMessage.media)) { let config: any = { responseType: 'arraybuffer', }; - if (this.localProxy.enabled) { + if (this.localProxy?.enabled) { config = { ...config, httpsAgent: makeProxyAgent({ @@ -2293,6 +2359,7 @@ export class BaileysStartupService extends ChannelStartupService { { userJid: this.instance.wuid }, ); } catch (error) { + this.logger.error('line 2378'); this.logger.error(error); throw new InternalServerErrorException(error?.toString() || error); } @@ -2313,7 +2380,7 @@ export class BaileysStartupService extends ChannelStartupService { responseType: 'arraybuffer', }; - if (this.localProxy.enabled) { + if (this.localProxy?.enabled) { config = { ...config, httpsAgent: makeProxyAgent({ @@ -2334,6 +2401,7 @@ export class BaileysStartupService extends ChannelStartupService { return webpBuffer; } catch (error) { + this.logger.error('line 2420'); console.error('Erro ao converter a imagem para WebP:', error); throw error; } @@ -2541,27 +2609,8 @@ export class BaileysStartupService extends ChannelStartupService { ); } - public async listMessage(data: SendListDto) { - return await this.sendMessageWithTyping( - data.number, - { - listMessage: { - title: data.title, - description: data?.description, - buttonText: data?.buttonText, - footerText: data?.footerText, - sections: data.sections, - listType: 2, - }, - }, - { - delay: data?.delay, - presence: 'composing', - quoted: data?.quoted, - mentionsEveryOne: data?.mentionsEveryOne, - mentioned: data?.mentioned, - }, - ); + public async listMessage() { + throw new BadRequestException('Method not available on WhatsApp Baileys'); } public async contactMessage(data: SendContactDto) { @@ -2674,11 +2723,27 @@ export class BaileysStartupService extends ChannelStartupService { }); const numbersToVerify = jids.users.map(({ jid }) => jid.replace('+', '')); - const verify = await this.client.onWhatsApp(...numbersToVerify); + + const cachedNumbers = await getOnWhatsappCache(numbersToVerify); + const filteredNumbers = numbersToVerify.filter( + (jid) => !cachedNumbers.some((cached) => cached.jidOptions.includes(jid)), + ); + + const verify = await this.client.onWhatsApp(...filteredNumbers); const users: OnWhatsAppDto[] = await Promise.all( jids.users.map(async (user) => { let numberVerified: (typeof verify)[0] | null = null; + const cached = cachedNumbers.find((cached) => cached.jidOptions.includes(user.jid.replace('+', ''))); + if (cached) { + return { + exists: true, + jid: cached.remoteJid, + name: contacts.find((c) => c.remoteJid === cached.remoteJid)?.pushName, + number: user.number, + }; + } + // Brazilian numbers if (user.number.startsWith('55')) { const numberWithDigit = @@ -2721,6 +2786,7 @@ export class BaileysStartupService extends ChannelStartupService { } const numberJid = numberVerified?.jid || user.jid; + return { exists: !!numberVerified?.exists, jid: numberJid, @@ -2730,6 +2796,8 @@ export class BaileysStartupService extends ChannelStartupService { }), ); + await saveOnWhatsappCache(users.filter((user) => user.exists).map((user) => ({ remoteJid: user.jid }))); + onWhatsapp.push(...users); return onWhatsapp; @@ -2750,6 +2818,7 @@ export class BaileysStartupService extends ChannelStartupService { await this.client.readMessages(keys); return { message: 'Read messages', read: 'success' }; } catch (error) { + this.logger.error('line 2818'); throw new InternalServerErrorException('Read messages fail', error.toString()); } } @@ -2815,6 +2884,7 @@ export class BaileysStartupService extends ChannelStartupService { archived: true, }; } catch (error) { + this.logger.error('line 2884'); throw new InternalServerErrorException({ archived: false, message: ['An error occurred while archiving the chat. Open a calling.', error.toString()], @@ -2852,6 +2922,7 @@ export class BaileysStartupService extends ChannelStartupService { markedChatUnread: true, }; } catch (error) { + this.logger.error('line 2922'); throw new InternalServerErrorException({ markedChatUnread: false, message: ['An error occurred while marked unread the chat. Open a calling.', error.toString()], @@ -2863,6 +2934,7 @@ export class BaileysStartupService extends ChannelStartupService { try { return await this.client.sendMessage(del.remoteJid, { delete: del }); } catch (error) { + this.logger.error('line 2934'); throw new InternalServerErrorException('Error while deleting message for everyone', error?.toString()); } } @@ -2914,7 +2986,7 @@ export class BaileysStartupService extends ChannelStartupService { ); const typeMessage = getContentType(msg.message); - const ext = mime.extension(mediaMessage?.['mimetype']); + const ext = mime.getExtension(mediaMessage?.['mimetype']); const fileName = mediaMessage?.['fileName'] || `${msg.key.id}.${ext}` || `${v4()}.${ext}`; @@ -2954,6 +3026,7 @@ export class BaileysStartupService extends ChannelStartupService { buffer: getBuffer ? buffer : null, }; } catch (error) { + this.logger.error('line 3026'); this.logger.error(error); throw new BadRequestException(error.toString()); } @@ -2995,6 +3068,7 @@ export class BaileysStartupService extends ChannelStartupService { }, }; } catch (error) { + this.logger.error('line 3068'); throw new InternalServerErrorException('Error updating privacy settings', error.toString()); } } @@ -3020,6 +3094,7 @@ export class BaileysStartupService extends ChannelStartupService { ...profile, }; } catch (error) { + this.logger.error('line 3094'); throw new InternalServerErrorException('Error updating profile name', error.toString()); } } @@ -3030,6 +3105,7 @@ export class BaileysStartupService extends ChannelStartupService { return { update: 'success' }; } catch (error) { + this.logger.error('line 3105'); throw new InternalServerErrorException('Error updating profile name', error.toString()); } } @@ -3040,6 +3116,7 @@ export class BaileysStartupService extends ChannelStartupService { return { update: 'success' }; } catch (error) { + this.logger.error('line 3116'); throw new InternalServerErrorException('Error updating profile status', error.toString()); } } @@ -3055,7 +3132,7 @@ export class BaileysStartupService extends ChannelStartupService { responseType: 'arraybuffer', }; - if (this.localProxy.enabled) { + if (this.localProxy?.enabled) { config = { ...config, httpsAgent: makeProxyAgent({ @@ -3081,6 +3158,7 @@ export class BaileysStartupService extends ChannelStartupService { return { update: 'success' }; } catch (error) { + this.logger.error('line 3158'); throw new InternalServerErrorException('Error updating profile picture', error.toString()); } } @@ -3093,6 +3171,7 @@ export class BaileysStartupService extends ChannelStartupService { return { update: 'success' }; } catch (error) { + this.logger.error('line 3171'); throw new InternalServerErrorException('Error removing profile picture', error.toString()); } } @@ -3113,6 +3192,7 @@ export class BaileysStartupService extends ChannelStartupService { return { block: 'success' }; } catch (error) { + this.logger.error('line 3192'); throw new InternalServerErrorException('Error blocking user', error.toString()); } } @@ -3143,6 +3223,7 @@ export class BaileysStartupService extends ChannelStartupService { return null; } catch (error) { + this.logger.error('line 3223'); this.logger.error(error); throw new BadRequestException(error.toString()); } @@ -3164,6 +3245,7 @@ export class BaileysStartupService extends ChannelStartupService { edit: data.key, }); } catch (error) { + this.logger.error('line 3245'); this.logger.error(error); throw new BadRequestException(error.toString()); } @@ -3206,6 +3288,7 @@ export class BaileysStartupService extends ChannelStartupService { return { numberJid: contact.jid, labelId: data.labelId, remove: true }; } } catch (error) { + this.logger.error('line 3288'); throw new BadRequestException(`Unable to ${data.action} label to chat`, error.toString()); } } @@ -3215,14 +3298,19 @@ export class BaileysStartupService extends ChannelStartupService { try { const meta = await this.client.groupMetadata(groupJid); - this.logger.verbose(`Updating cache for group: ${groupJid}`); - await groupMetadataCache.set(groupJid, { - timestamp: Date.now(), - data: meta, - }); + const cacheConf = this.configService.get('CACHE'); + + if ((cacheConf?.REDIS?.ENABLED && cacheConf?.REDIS?.URI !== '') || cacheConf?.LOCAL?.ENABLED) { + this.logger.verbose(`Updating cache for group: ${groupJid}`); + await groupMetadataCache.set(groupJid, { + timestamp: Date.now(), + data: meta, + }); + } return meta; } catch (error) { + this.logger.error('line 3310'); this.logger.error(error); return null; } @@ -3231,19 +3319,25 @@ export class BaileysStartupService extends ChannelStartupService { private async getGroupMetadataCache(groupJid: string) { if (!isJidGroup(groupJid)) return null; - if (await groupMetadataCache.has(groupJid)) { - console.log(`Cache request for group: ${groupJid}`); - const meta = await groupMetadataCache.get(groupJid); + const cacheConf = configService.get('CACHE'); - if (Date.now() - meta.timestamp > 3600000) { - await this.updateGroupMetadataCache(groupJid); + if ((cacheConf?.REDIS?.ENABLED && cacheConf?.REDIS?.URI !== '') || cacheConf?.LOCAL?.ENABLED) { + if (await groupMetadataCache?.has(groupJid)) { + console.log(`Cache request for group: ${groupJid}`); + const meta = await groupMetadataCache.get(groupJid); + + if (Date.now() - meta.timestamp > 3600000) { + await this.updateGroupMetadataCache(groupJid); + } + + return meta.data; } - return meta.data; + console.log(`Cache request for group: ${groupJid} - not found`); + return await this.updateGroupMetadataCache(groupJid); } - console.log(`Cache request for group: ${groupJid} - not found`); - return await this.updateGroupMetadataCache(groupJid); + return await this.findGroup({ groupJid }, 'inner'); } public async createGroup(create: CreateGroupDto) { @@ -3269,6 +3363,7 @@ export class BaileysStartupService extends ChannelStartupService { return group; } catch (error) { + this.logger.error('line 3363'); this.logger.error(error); throw new InternalServerErrorException('Error creating group', error.toString()); } @@ -3285,7 +3380,7 @@ export class BaileysStartupService extends ChannelStartupService { responseType: 'arraybuffer', }; - if (this.localProxy.enabled) { + if (this.localProxy?.enabled) { config = { ...config, httpsAgent: makeProxyAgent({ @@ -3308,6 +3403,7 @@ export class BaileysStartupService extends ChannelStartupService { return { update: 'success' }; } catch (error) { + this.logger.error('line 3403'); throw new InternalServerErrorException('Error update group picture', error.toString()); } } @@ -3318,6 +3414,7 @@ export class BaileysStartupService extends ChannelStartupService { return { update: 'success' }; } catch (error) { + this.logger.error('line 3414'); throw new InternalServerErrorException('Error updating group subject', error.toString()); } } @@ -3328,6 +3425,7 @@ export class BaileysStartupService extends ChannelStartupService { return { update: 'success' }; } catch (error) { + this.logger.error('line 3425'); throw new InternalServerErrorException('Error updating group description', error.toString()); } } @@ -3336,6 +3434,11 @@ export class BaileysStartupService extends ChannelStartupService { try { const group = await this.client.groupMetadata(id.groupJid); + if (!group) { + this.logger.error('Group not found'); + return null; + } + const picture = await this.profilePicture(group.id); return { @@ -3357,43 +3460,41 @@ export class BaileysStartupService extends ChannelStartupService { if (reply === 'inner') { return; } + this.logger.error('line 3460'); throw new NotFoundException('Error fetching group', error.toString()); } } public async fetchAllGroups(getParticipants: GetParticipant) { - try { - const fetch = Object.values(await this?.client?.groupFetchAllParticipating()); - let groups = []; - for (const group of fetch) { - const picture = await this.profilePicture(group.id); + const fetch = Object.values(await this?.client?.groupFetchAllParticipating()); - const result = { - id: group.id, - subject: group.subject, - subjectOwner: group.subjectOwner, - subjectTime: group.subjectTime, - pictureUrl: picture.profilePictureUrl, - size: group.participants.length, - creation: group.creation, - owner: group.owner, - desc: group.desc, - descId: group.descId, - restrict: group.restrict, - announce: group.announce, - }; + let groups = []; + for (const group of fetch) { + const picture = await this.profilePicture(group.id); - if (getParticipants.getParticipants == 'true') { - result['participants'] = group.participants; - } + const result = { + id: group.id, + subject: group.subject, + subjectOwner: group.subjectOwner, + subjectTime: group.subjectTime, + pictureUrl: picture?.profilePictureUrl, + size: group.participants.length, + creation: group.creation, + owner: group.owner, + desc: group.desc, + descId: group.descId, + restrict: group.restrict, + announce: group.announce, + }; - groups = [...groups, result]; + if (getParticipants.getParticipants == 'true') { + result['participants'] = group.participants; } - return groups; - } catch (error) { - throw new NotFoundException('Error fetching group', error.toString()); + groups = [...groups, result]; } + + return groups; } public async inviteCode(id: GroupJid) { @@ -3401,6 +3502,7 @@ export class BaileysStartupService extends ChannelStartupService { const code = await this.client.groupInviteCode(id.groupJid); return { inviteUrl: `https://chat.whatsapp.com/${code}`, inviteCode: code }; } catch (error) { + this.logger.error('line 3502'); throw new NotFoundException('No invite code', error.toString()); } } @@ -3409,6 +3511,7 @@ export class BaileysStartupService extends ChannelStartupService { try { return await this.client.groupGetInviteInfo(id.inviteCode); } catch (error) { + this.logger.error('line 3511'); throw new NotFoundException('No invite info', id.inviteCode); } } @@ -3434,6 +3537,7 @@ export class BaileysStartupService extends ChannelStartupService { return { send: true, inviteUrl }; } catch (error) { + this.logger.error('line 3537'); throw new NotFoundException('No send invite'); } } @@ -3443,6 +3547,7 @@ export class BaileysStartupService extends ChannelStartupService { const groupJid = await this.client.groupAcceptInvite(id.inviteCode); return { accepted: true, groupJid: groupJid }; } catch (error) { + this.logger.error('line 3547'); throw new NotFoundException('Accept invite error', error.toString()); } } @@ -3452,6 +3557,7 @@ export class BaileysStartupService extends ChannelStartupService { const inviteCode = await this.client.groupRevokeInvite(id.groupJid); return { revoked: true, inviteCode }; } catch (error) { + this.logger.error('line 3557'); throw new NotFoundException('Revoke error', error.toString()); } } @@ -3475,8 +3581,16 @@ export class BaileysStartupService extends ChannelStartupService { imgUrl: participant.imgUrl ?? contact?.profilePicUrl, }; }); + + const usersContacts = parsedParticipants.filter((c) => c.id.includes('@s.whatsapp')); + if (usersContacts) { + await saveOnWhatsappCache(usersContacts.map((c) => ({ remoteJid: c.id }))); + } + return { participants: parsedParticipants }; } catch (error) { + console.error(error); + this.logger.error('line 3583'); throw new NotFoundException('No participants', error.toString()); } } @@ -3491,6 +3605,7 @@ export class BaileysStartupService extends ChannelStartupService { ); return { updateParticipants: updateParticipants }; } catch (error) { + this.logger.error('line 3598'); throw new BadRequestException('Error updating participants', error.toString()); } } @@ -3500,6 +3615,7 @@ export class BaileysStartupService extends ChannelStartupService { const updateSetting = await this.client.groupSettingUpdate(update.groupJid, update.action); return { updateSetting: updateSetting }; } catch (error) { + this.logger.error('line 3608'); throw new BadRequestException('Error updating setting', error.toString()); } } @@ -3509,6 +3625,7 @@ export class BaileysStartupService extends ChannelStartupService { await this.client.groupToggleEphemeral(update.groupJid, update.expiration); return { success: true }; } catch (error) { + this.logger.error('line 3618'); throw new BadRequestException('Error updating setting', error.toString()); } } @@ -3518,10 +3635,34 @@ export class BaileysStartupService extends ChannelStartupService { await this.client.groupLeave(id.groupJid); return { groupJid: id.groupJid, leave: true }; } catch (error) { + this.logger.error('line 3628'); throw new BadRequestException('Unable to leave the group', error.toString()); } } public async templateMessage() { throw new Error('Method not available in the Baileys service'); } + + private prepareMessage(message: proto.IWebMessageInfo): any { + const contentMsg = message?.message[getContentType(message.message)] as any; + + const messageRaw = { + key: message.key, + pushName: message.pushName, + message: { ...message.message }, + contextInfo: contentMsg?.contextInfo, + messageType: getContentType(message.message) || 'unknown', + messageTimestamp: message.messageTimestamp as number, + instanceId: this.instanceId, + source: getDevice(message.key.id), + }; + + if (messageRaw.message.extendedTextMessage) { + messageRaw.messageType = 'conversation'; + messageRaw.message.conversation = messageRaw.message.extendedTextMessage.text; + delete messageRaw.message.extendedTextMessage; + } + + return messageRaw; + } } diff --git a/src/api/integrations/chatbot/chatbot.controller.ts b/src/api/integrations/chatbot/chatbot.controller.ts new file mode 100644 index 00000000..2db9a654 --- /dev/null +++ b/src/api/integrations/chatbot/chatbot.controller.ts @@ -0,0 +1,210 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { + difyController, + evolutionBotController, + flowiseController, + openaiController, + typebotController, +} from '@api/server.module'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Logger } from '@config/logger.config'; +import { IntegrationSession } from '@prisma/client'; +import { findBotByTrigger } from '@utils/findBotByTrigger'; + +export type EmitData = { + instance: InstanceDto; + remoteJid: string; + msg: any; + pushName?: string; +}; + +export interface ChatbotControllerInterface { + integrationEnabled: boolean; + botRepository: any; + settingsRepository: any; + sessionRepository: any; + userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } }; + + createBot(instance: InstanceDto, data: any): Promise; + findBot(instance: InstanceDto): Promise; + fetchBot(instance: InstanceDto, botId: string): Promise; + updateBot(instance: InstanceDto, botId: string, data: any): Promise; + deleteBot(instance: InstanceDto, botId: string): Promise; + + settings(instance: InstanceDto, data: any): Promise; + fetchSettings(instance: InstanceDto): Promise; + + changeStatus(instance: InstanceDto, botId: string, status: string): Promise; + fetchSessions(instance: InstanceDto, botId: string, remoteJid?: string): Promise; + ignoreJid(instance: InstanceDto, data: any): Promise; + + emit(data: EmitData): Promise; +} + +export class ChatbotController { + public prismaRepository: PrismaRepository; + public waMonitor: WAMonitoringService; + + public readonly logger = new Logger('ChatbotController'); + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + this.prisma = prismaRepository; + this.monitor = waMonitor; + } + + public set prisma(prisma: PrismaRepository) { + this.prismaRepository = prisma; + } + + public get prisma() { + return this.prismaRepository; + } + + public set monitor(waMonitor: WAMonitoringService) { + this.waMonitor = waMonitor; + } + + public get monitor() { + return this.waMonitor; + } + + public async emit({ + instance, + remoteJid, + msg, + pushName, + isIntegration = false, + }: { + instance: InstanceDto; + remoteJid: string; + msg: any; + pushName?: string; + isIntegration?: boolean; + }): Promise { + const emitData = { + instance, + remoteJid, + msg, + pushName, + isIntegration, + }; + await evolutionBotController.emit(emitData); + + await typebotController.emit(emitData); + + await openaiController.emit(emitData); + + await difyController.emit(emitData); + + await flowiseController.emit(emitData); + } + + public processDebounce( + userMessageDebounce: any, + content: string, + remoteJid: string, + debounceTime: number, + callback: any, + ) { + if (userMessageDebounce[remoteJid]) { + userMessageDebounce[remoteJid].message += `\n${content}`; + this.logger.log('message debounced: ' + userMessageDebounce[remoteJid].message); + clearTimeout(userMessageDebounce[remoteJid].timeoutId); + } else { + userMessageDebounce[remoteJid] = { + message: content, + timeoutId: null, + }; + } + + userMessageDebounce[remoteJid].timeoutId = setTimeout(() => { + const myQuestion = userMessageDebounce[remoteJid].message; + this.logger.log('Debounce complete. Processing message: ' + myQuestion); + + delete userMessageDebounce[remoteJid]; + callback(myQuestion); + }, debounceTime * 1000); + } + + public checkIgnoreJids(ignoreJids: any, remoteJid: string) { + if (ignoreJids && ignoreJids.length > 0) { + let ignoreGroups = false; + let ignoreContacts = false; + + if (ignoreJids.includes('@g.us')) { + ignoreGroups = true; + } + + if (ignoreJids.includes('@s.whatsapp.net')) { + ignoreContacts = true; + } + + if (ignoreGroups && remoteJid.endsWith('@g.us')) { + this.logger.warn('Ignoring message from group: ' + remoteJid); + return true; + } + + if (ignoreContacts && remoteJid.endsWith('@s.whatsapp.net')) { + this.logger.warn('Ignoring message from contact: ' + remoteJid); + return true; + } + + if (ignoreJids.includes(remoteJid)) { + this.logger.warn('Ignoring message from jid: ' + remoteJid); + return true; + } + + return false; + } + + return false; + } + + public async getSession(remoteJid: string, instance: InstanceDto) { + let session = await this.prismaRepository.integrationSession.findFirst({ + where: { + remoteJid: remoteJid, + instanceId: instance.instanceId, + }, + orderBy: { createdAt: 'desc' }, + }); + + if (session) { + if (session.status !== 'closed' && !session.botId) { + this.logger.warn('Session is already opened in another integration'); + return; + } else if (!session.botId) { + session = null; + } + } + + return session; + } + + public async findBotTrigger( + botRepository: any, + settingsRepository: any, + content: string, + instance: InstanceDto, + session?: IntegrationSession, + ) { + let findBot: null; + + if (!session) { + findBot = await findBotByTrigger(botRepository, settingsRepository, content, instance.instanceId); + + if (!findBot) { + return; + } + } else { + findBot = await botRepository.findFirst({ + where: { + id: session.botId, + }, + }); + } + + return findBot; + } +} diff --git a/src/api/integrations/chatbot/chatbot.router.ts b/src/api/integrations/chatbot/chatbot.router.ts new file mode 100644 index 00000000..19fc74b7 --- /dev/null +++ b/src/api/integrations/chatbot/chatbot.router.ts @@ -0,0 +1,23 @@ +import { ChatwootRouter } from '@api/integrations/chatbot/chatwoot/routes/chatwoot.router'; +import { DifyRouter } from '@api/integrations/chatbot/dify/routes/dify.router'; +import { OpenaiRouter } from '@api/integrations/chatbot/openai/routes/openai.router'; +import { TypebotRouter } from '@api/integrations/chatbot/typebot/routes/typebot.router'; +import { Router } from 'express'; + +import { EvolutionBotRouter } from './evolutionBot/routes/evolutionBot.router'; +import { FlowiseRouter } from './flowise/routes/flowise.router'; + +export class ChatbotRouter { + public readonly router: Router; + + constructor(...guards: any[]) { + this.router = Router(); + + this.router.use('/evolutionBot', new EvolutionBotRouter(...guards).router); + this.router.use('/chatwoot', new ChatwootRouter(...guards).router); + this.router.use('/typebot', new TypebotRouter(...guards).router); + this.router.use('/openai', new OpenaiRouter(...guards).router); + this.router.use('/dify', new DifyRouter(...guards).router); + this.router.use('/flowise', new FlowiseRouter(...guards).router); + } +} diff --git a/src/api/integrations/chatbot/chatbot.schema.ts b/src/api/integrations/chatbot/chatbot.schema.ts new file mode 100644 index 00000000..efc2388f --- /dev/null +++ b/src/api/integrations/chatbot/chatbot.schema.ts @@ -0,0 +1,6 @@ +export * from '@api/integrations/chatbot/chatwoot/validate/chatwoot.schema'; +export * from '@api/integrations/chatbot/dify/validate/dify.schema'; +export * from '@api/integrations/chatbot/evolutionBot/validate/evolutionBot.schema'; +export * from '@api/integrations/chatbot/flowise/validate/flowise.schema'; +export * from '@api/integrations/chatbot/openai/validate/openai.schema'; +export * from '@api/integrations/chatbot/typebot/validate/typebot.schema'; diff --git a/src/api/integrations/chatwoot/controllers/chatwoot.controller.ts b/src/api/integrations/chatbot/chatwoot/controllers/chatwoot.controller.ts similarity index 80% rename from src/api/integrations/chatwoot/controllers/chatwoot.controller.ts rename to src/api/integrations/chatbot/chatwoot/controllers/chatwoot.controller.ts index bf9ac397..bfebad12 100644 --- a/src/api/integrations/chatwoot/controllers/chatwoot.controller.ts +++ b/src/api/integrations/chatbot/chatwoot/controllers/chatwoot.controller.ts @@ -1,15 +1,14 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { ChatwootDto } from '@api/integrations/chatbot/chatwoot/dto/chatwoot.dto'; +import { ChatwootService } from '@api/integrations/chatbot/chatwoot/services/chatwoot.service'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { waMonitor } from '@api/server.module'; +import { CacheService } from '@api/services/cache.service'; +import { CacheEngine } from '@cache/cacheengine'; +import { Chatwoot, ConfigService, HttpServer } from '@config/env.config'; +import { BadRequestException } from '@exceptions'; import { isURL } from 'class-validator'; -import { CacheEngine } from '../../../../cache/cacheengine'; -import { Chatwoot, ConfigService, HttpServer } from '../../../../config/env.config'; -import { BadRequestException } from '../../../../exceptions'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { PrismaRepository } from '../../../repository/repository.service'; -import { waMonitor } from '../../../server.module'; -import { CacheService } from '../../../services/cache.service'; -import { ChatwootDto } from '../dto/chatwoot.dto'; -import { ChatwootService } from '../services/chatwoot.service'; - export class ChatwootController { constructor( private readonly chatwootService: ChatwootService, @@ -20,7 +19,7 @@ export class ChatwootController { public async createChatwoot(instance: InstanceDto, data: ChatwootDto) { if (!this.configService.get('CHATWOOT').ENABLED) throw new BadRequestException('Chatwoot is disabled'); - if (data.enabled) { + if (data?.enabled) { if (!isURL(data.url, { require_tld: false })) { throw new BadRequestException('url is not valid'); } diff --git a/src/api/integrations/chatbot/chatwoot/dto/chatwoot.dto.ts b/src/api/integrations/chatbot/chatwoot/dto/chatwoot.dto.ts new file mode 100644 index 00000000..4abf468f --- /dev/null +++ b/src/api/integrations/chatbot/chatwoot/dto/chatwoot.dto.ts @@ -0,0 +1,41 @@ +import { Constructor } from '@api/integrations/integration.dto'; + +export class ChatwootDto { + enabled?: boolean; + accountId?: string; + token?: string; + url?: string; + nameInbox?: string; + signMsg?: boolean; + signDelimiter?: string; + number?: string; + reopenConversation?: boolean; + conversationPending?: boolean; + mergeBrazilContacts?: boolean; + importContacts?: boolean; + importMessages?: boolean; + daysLimitImportMessages?: number; + autoCreate?: boolean; + organization?: string; + logo?: string; + ignoreJids?: string[]; +} + +export function ChatwootInstanceMixin(Base: TBase) { + return class extends Base { + chatwootAccountId?: string; + chatwootToken?: string; + chatwootUrl?: string; + chatwootSignMsg?: boolean; + chatwootReopenConversation?: boolean; + chatwootConversationPending?: boolean; + chatwootMergeBrazilContacts?: boolean; + chatwootImportContacts?: boolean; + chatwootImportMessages?: boolean; + chatwootDaysLimitImportMessages?: number; + chatwootNameInbox?: string; + chatwootOrganization?: string; + chatwootLogo?: string; + chatwootAutoCreate?: boolean; + }; +} diff --git a/src/api/integrations/chatwoot/libs/postgres.client.ts b/src/api/integrations/chatbot/chatwoot/libs/postgres.client.ts similarity index 83% rename from src/api/integrations/chatwoot/libs/postgres.client.ts rename to src/api/integrations/chatbot/chatwoot/libs/postgres.client.ts index 20e6515f..3e3e9685 100644 --- a/src/api/integrations/chatwoot/libs/postgres.client.ts +++ b/src/api/integrations/chatbot/chatwoot/libs/postgres.client.ts @@ -1,12 +1,11 @@ +import { Chatwoot, configService } from '@config/env.config'; +import { Logger } from '@config/logger.config'; import postgresql from 'pg'; -import { Chatwoot, configService } from '../../../../config/env.config'; -import { Logger } from '../../../../config/logger.config'; - const { Pool } = postgresql; class Postgres { - private logger = new Logger(Postgres.name); + private logger = new Logger('Postgres'); private pool; private connected = false; diff --git a/src/api/integrations/chatwoot/routes/chatwoot.router.ts b/src/api/integrations/chatbot/chatwoot/routes/chatwoot.router.ts similarity index 75% rename from src/api/integrations/chatwoot/routes/chatwoot.router.ts rename to src/api/integrations/chatbot/chatwoot/routes/chatwoot.router.ts index 20dc3183..51b23ab5 100644 --- a/src/api/integrations/chatwoot/routes/chatwoot.router.ts +++ b/src/api/integrations/chatbot/chatwoot/routes/chatwoot.router.ts @@ -1,12 +1,11 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { ChatwootDto } from '@api/integrations/chatbot/chatwoot/dto/chatwoot.dto'; +import { HttpStatus } from '@api/routes/index.router'; +import { chatwootController } from '@api/server.module'; +import { chatwootSchema, instanceSchema } from '@validate/validate.schema'; import { RequestHandler, Router } from 'express'; -import { chatwootSchema, instanceSchema } from '../../../../validate/validate.schema'; -import { RouterBroker } from '../../../abstract/abstract.router'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { HttpStatus } from '../../../routes/index.router'; -import { chatwootController } from '../../../server.module'; -import { ChatwootDto } from '../dto/chatwoot.dto'; - export class ChatwootRouter extends RouterBroker { constructor(...guards: RequestHandler[]) { super(); @@ -43,5 +42,5 @@ export class ChatwootRouter extends RouterBroker { }); } - public readonly router = Router(); + public readonly router: Router = Router(); } diff --git a/src/api/integrations/chatwoot/services/chatwoot.service.ts b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts similarity index 94% rename from src/api/integrations/chatwoot/services/chatwoot.service.ts rename to src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts index 865a0bf0..b5bc9a45 100644 --- a/src/api/integrations/chatwoot/services/chatwoot.service.ts +++ b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts @@ -1,3 +1,14 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { Options, Quoted, SendAudioDto, SendMediaDto, SendTextDto } from '@api/dto/sendMessage.dto'; +import { ChatwootDto } from '@api/integrations/chatbot/chatwoot/dto/chatwoot.dto'; +import { postgresClient } from '@api/integrations/chatbot/chatwoot/libs/postgres.client'; +import { chatwootImport } from '@api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { CacheService } from '@api/services/cache.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Events } from '@api/types/wa.types'; +import { Chatwoot, ConfigService, HttpServer } from '@config/env.config'; +import { Logger } from '@config/logger.config'; import ChatwootClient, { ChatwootAPIConfig, contact, @@ -9,29 +20,17 @@ import ChatwootClient, { } from '@figuro/chatwoot-sdk'; import { request as chatwootRequest } from '@figuro/chatwoot-sdk/dist/core/request'; import { Chatwoot as ChatwootModel, Contact as ContactModel, Message as MessageModel } from '@prisma/client'; +import i18next from '@utils/i18n'; +import { sendTelemetry } from '@utils/sendTelemetry'; import axios from 'axios'; import { proto } from 'baileys'; import FormData from 'form-data'; import Jimp from 'jimp'; import Long from 'long'; -import mimeTypes from 'mime-types'; +import mime from 'mime'; import path from 'path'; import { Readable } from 'stream'; -import { Chatwoot, ConfigService, HttpServer } from '../../../../config/env.config'; -import { Logger } from '../../../../config/logger.config'; -import i18next from '../../../../utils/i18n'; -import { sendTelemetry } from '../../../../utils/sendTelemetry'; -import { ICache } from '../../../abstract/abstract.cache'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { Options, Quoted, SendAudioDto, SendMediaDto, SendTextDto } from '../../../dto/sendMessage.dto'; -import { PrismaRepository } from '../../../repository/repository.service'; -import { WAMonitoringService } from '../../../services/monitor.service'; -import { Events } from '../../../types/wa.types'; -import { ChatwootDto } from '../dto/chatwoot.dto'; -import { postgresClient } from '../libs/postgres.client'; -import { chatwootImport } from '../utils/chatwoot-import-helper'; - interface ChatwootMessage { messageId?: number; inboxId?: number; @@ -41,7 +40,7 @@ interface ChatwootMessage { } export class ChatwootService { - private readonly logger = new Logger(ChatwootService.name); + private readonly logger = new Logger('ChatwootService'); private provider: any; @@ -49,7 +48,7 @@ export class ChatwootService { private readonly waMonitor: WAMonitoringService, private readonly configService: ConfigService, private readonly prismaRepository: PrismaRepository, - private readonly cache: ICache, + private readonly cache: CacheService, ) {} private pgClient = postgresClient.getChatwootConnection(); @@ -216,7 +215,13 @@ export class ChatwootService { inboxId = inbox.id; } - this.logger.log(`Inox created - inboxId: ${inboxId}`); + this.logger.log(`Inbox created - inboxId: ${inboxId}`); + + if (!this.configService.get('CHATWOOT').BOT_CONTACT) { + this.logger.log('Chatwoot bot contact is disabled'); + + return true; + } this.logger.log('Creating chatwoot bot contact'); const contact = @@ -301,10 +306,13 @@ export class ChatwootService { data = { inbox_id: inboxId, name: name || phoneNumber, - phone_number: `+${phoneNumber}`, identifier: jid, avatar_url: avatar_url, }; + + if ((jid && jid.includes('@')) || !jid) { + data['phone_number'] = `+${phoneNumber}`; + } } else { data = { inbox_id: inboxId, @@ -355,12 +363,16 @@ export class ChatwootService { return contact; } catch (error) { - this.logger.error(error); + return null; } } public async addLabelToContact(nameInbox: string, contactId: number) { try { + const uri = this.configService.get('CHATWOOT').IMPORT.DATABASE.CONNECTION.URI; + + if (!uri) return false; + const sqlTags = `SELECT id FROM tags WHERE name = '${nameInbox}' LIMIT 1`; const tagData = (await this.pgClient.query(sqlTags))?.rows[0]; @@ -645,7 +657,7 @@ export class ChatwootService { } } } else { - const jid = isGroup ? null : body.key.remoteJid; + const jid = body.key.remoteJid; contact = await this.createContact( instance, chatId, @@ -858,6 +870,12 @@ export class ChatwootService { return null; } + if (!this.configService.get('CHATWOOT').BOT_CONTACT) { + this.logger.log('Chatwoot bot contact is disabled'); + + return true; + } + const contact = await this.findContact(instance, '123456'); if (!contact) { @@ -972,6 +990,12 @@ export class ChatwootService { return null; } + if (!this.configService.get('CHATWOOT').BOT_CONTACT) { + this.logger.log('Chatwoot bot contact is disabled'); + + return true; + } + const contact = await this.findContact(instance, '123456'); if (!contact) { @@ -1028,7 +1052,7 @@ export class ChatwootService { public async sendAttachment(waInstance: any, number: string, media: any, caption?: string, options?: Options) { try { const parsedMedia = path.parse(decodeURIComponent(media)); - let mimeType = mimeTypes.lookup(parsedMedia?.ext) || ''; + let mimeType = mime.getType(parsedMedia?.ext) || ''; let fileName = parsedMedia?.name + parsedMedia?.ext; if (!mimeType) { @@ -1150,7 +1174,7 @@ export class ChatwootService { } const chatId = - body.conversation.meta.sender?.phone_number?.replace('+', '') || body.conversation.meta.sender?.identifier; + body.conversation.meta.sender?.identifier || body.conversation.meta.sender?.phone_number.replace('+', ''); // Chatwoot to Whatsapp const messageReceived = body.content ? body.content @@ -1191,7 +1215,9 @@ export class ChatwootService { return { message: 'bot' }; } - if (chatId === '123456' && body.message_type === 'outgoing') { + const cwBotContact = this.configService.get('CHATWOOT').BOT_CONTACT; + + if (cwBotContact && chatId === '123456' && body.message_type === 'outgoing') { const command = messageReceived.replace('/', ''); if (command.includes('init') || command.includes('iniciar')) { @@ -1487,7 +1513,7 @@ export class ChatwootService { let inReplyToExternalId = null; if (msg) { - inReplyToExternalId = msg.message?.extendedTextMessage?.contextInfo?.stanzaId; + inReplyToExternalId = msg.message?.extendedTextMessage?.contextInfo?.stanzaId ?? msg.contextInfo?.stanzaId; if (inReplyToExternalId) { const message = await this.getMessageByKeyId(instance, inReplyToExternalId); if (message?.chatwootMessageId) { @@ -1537,6 +1563,7 @@ export class ChatwootService { 'audioMessage', 'videoMessage', 'stickerMessage', + 'viewOnceMessageV2' ]; const messageKeys = Object.keys(message); @@ -1590,6 +1617,8 @@ export class ChatwootService { liveLocationMessage: msg.liveLocationMessage, listMessage: msg.listMessage, listResponseMessage: msg.listResponseMessage, + viewOnceMessageV2: msg?.message?.viewOnceMessageV2?.message?.imageMessage?.url || msg?.message?.viewOnceMessageV2?.message?.videoMessage?.url || msg?.message?.viewOnceMessageV2?.message?.audioMessage?.url, + }; return types; @@ -1598,7 +1627,12 @@ export class ChatwootService { private getMessageContent(types: any) { const typeKey = Object.keys(types).find((key) => types[key] !== undefined); - const result = typeKey ? types[typeKey] : undefined; + let result = typeKey ? types[typeKey] : undefined; + + // Remove externalAdReplyBody| in Chatwoot (Already Have) + if (result && typeof result === 'string' && result.includes('externalAdReplyBody|')) { + result = result.split('externalAdReplyBody|').filter(Boolean).join(''); + } if (typeKey === 'locationMessage' || typeKey === 'liveLocationMessage') { const latitude = result.degreesLatitude; @@ -1770,6 +1804,36 @@ export class ChatwootService { return null; } + if (this.provider?.ignoreJids && this.provider?.ignoreJids.length > 0) { + const ignoreJids: any = this.provider?.ignoreJids; + + let ignoreGroups = false; + let ignoreContacts = false; + + if (ignoreJids.includes('@g.us')) { + ignoreGroups = true; + } + + if (ignoreJids.includes('@s.whatsapp.net')) { + ignoreContacts = true; + } + + if (ignoreGroups && body?.key?.remoteJid.endsWith('@g.us')) { + this.logger.warn('Ignoring message from group: ' + body?.key?.remoteJid); + return; + } + + if (ignoreContacts && body?.key?.remoteJid.endsWith('@s.whatsapp.net')) { + this.logger.warn('Ignoring message from contact: ' + body?.key?.remoteJid); + return; + } + + if (ignoreJids.includes(body?.key?.remoteJid)) { + this.logger.warn('Ignoring message from jid: ' + body?.key?.remoteJid); + return; + } + } + if (event === 'contact.is_not_in_wpp') { const getConversation = await this.createConversation(instance, body); @@ -1796,14 +1860,12 @@ export class ChatwootService { return; } - // fix when receiving/sending messages from whatsapp desktop with ephemeral messages enabled if (body.message?.ephemeralMessage?.message) { body.message = { ...body.message?.ephemeralMessage?.message, }; } - // Whatsapp to Chatwoot const originalMessage = await this.getConversationMessage(body.message); const bodyMessage = originalMessage ? originalMessage @@ -1859,7 +1921,8 @@ export class ChatwootService { let nameFile: string; const messageBody = body?.message[body?.messageType]; - const originalFilename = messageBody?.fileName || messageBody?.message?.documentMessage?.fileName; + const originalFilename = + messageBody?.fileName || messageBody?.filename || messageBody?.message?.documentMessage?.fileName; if (originalFilename) { const parsedFile = path.parse(originalFilename); if (parsedFile.name && parsedFile.ext) { @@ -1868,9 +1931,7 @@ export class ChatwootService { } if (!nameFile) { - nameFile = `${Math.random().toString(36).substring(7)}.${ - mimeTypes.extension(downloadBase64.mimetype) || '' - }`; + nameFile = `${Math.random().toString(36).substring(7)}.${mime.getExtension(downloadBase64.mimetype) || ''}`; } const fileData = Buffer.from(downloadBase64.base64, 'base64'); @@ -1958,8 +2019,8 @@ export class ChatwootService { if (adsMessage) { const imgBuffer = await axios.get(adsMessage.thumbnailUrl, { responseType: 'arraybuffer' }); - const extension = mimeTypes.extension(imgBuffer.headers['content-type']); - const mimeType = extension && mimeTypes.lookup(extension); + const extension = mime.getExtension(imgBuffer.headers['content-type']); + const mimeType = extension && mime.getType(extension); if (!mimeType) { this.logger.warn('mimetype of Ads message not found'); @@ -1967,7 +2028,7 @@ export class ChatwootService { } const random = Math.random().toString(36).substring(7); - const nameFile = `${random}.${mimeTypes.extension(mimeType)}`; + const nameFile = `${random}.${mime.getExtension(mimeType)}`; const fileData = Buffer.from(imgBuffer.data, 'binary'); const img = await Jimp.read(fileData); diff --git a/src/api/integrations/chatwoot/utils/chatwoot-import-helper.ts b/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts similarity index 96% rename from src/api/integrations/chatwoot/utils/chatwoot-import-helper.ts rename to src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts index cf4b3f89..f331e494 100644 --- a/src/api/integrations/chatwoot/utils/chatwoot-import-helper.ts +++ b/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts @@ -1,14 +1,13 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { ChatwootDto } from '@api/integrations/chatbot/chatwoot/dto/chatwoot.dto'; +import { postgresClient } from '@api/integrations/chatbot/chatwoot/libs/postgres.client'; +import { ChatwootService } from '@api/integrations/chatbot/chatwoot/services/chatwoot.service'; +import { Chatwoot, configService } from '@config/env.config'; +import { Logger } from '@config/logger.config'; import { inbox } from '@figuro/chatwoot-sdk'; import { Chatwoot as ChatwootModel, Contact, Message } from '@prisma/client'; import { proto } from 'baileys'; -import { InstanceDto } from '../../../../api/dto/instance.dto'; -import { Chatwoot, configService } from '../../../../config/env.config'; -import { Logger } from '../../../../config/logger.config'; -import { ChatwootDto } from '../dto/chatwoot.dto'; -import { postgresClient } from '../libs/postgres.client'; -import { ChatwootService } from '../services/chatwoot.service'; - type ChatwootUser = { user_type: string; user_id: number; @@ -28,7 +27,7 @@ type firstLastTimestamp = { type IWebMessageInfo = Omit & Partial>; class ChatwootImport { - private logger = new Logger(ChatwootImport.name); + private logger = new Logger('ChatwootImport'); private repositoryMessagesCache = new Map>(); private historyMessages = new Map(); private historyContacts = new Map(); @@ -290,7 +289,12 @@ class ChatwootImport { this.deleteHistoryMessages(instance); this.deleteRepositoryMessagesCache(instance); - this.importHistoryContacts(instance, provider); + const providerData: ChatwootDto = { + ...provider, + ignoreJids: Array.isArray(provider.ignoreJids) ? provider.ignoreJids.map((event) => String(event)) : [], + }; + + this.importHistoryContacts(instance, providerData); return totalMessagesImported; } catch (error) { diff --git a/src/api/integrations/chatwoot/validate/chatwoot.schema.ts b/src/api/integrations/chatbot/chatwoot/validate/chatwoot.schema.ts similarity index 96% rename from src/api/integrations/chatwoot/validate/chatwoot.schema.ts rename to src/api/integrations/chatbot/chatwoot/validate/chatwoot.schema.ts index 6e021c39..ce9cf701 100644 --- a/src/api/integrations/chatwoot/validate/chatwoot.schema.ts +++ b/src/api/integrations/chatbot/chatwoot/validate/chatwoot.schema.ts @@ -38,6 +38,7 @@ export const chatwootSchema: JSONSchema7 = { mergeBrazilContacts: { type: 'boolean', enum: [true, false] }, importMessages: { type: 'boolean', enum: [true, false] }, daysLimitImportMessages: { type: 'number' }, + ignoreJids: { type: 'array', items: { type: 'string' } }, }, required: ['enabled', 'accountId', 'token', 'url', 'signMsg', 'reopenConversation', 'conversationPending'], ...isNotEmpty('enabled', 'accountId', 'token', 'url', 'signMsg', 'reopenConversation', 'conversationPending'), diff --git a/src/api/integrations/chatbot/dify/controllers/dify.controller.ts b/src/api/integrations/chatbot/dify/controllers/dify.controller.ts new file mode 100644 index 00000000..f98ff470 --- /dev/null +++ b/src/api/integrations/chatbot/dify/controllers/dify.controller.ts @@ -0,0 +1,838 @@ +import { IgnoreJidDto } from '@api/dto/chatbot.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { DifyDto } from '@api/integrations/chatbot/dify/dto/dify.dto'; +import { DifyService } from '@api/integrations/chatbot/dify/services/dify.service'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { configService, Dify } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { BadRequestException } from '@exceptions'; +import { Dify as DifyModel } from '@prisma/client'; +import { getConversationMessage } from '@utils/getConversationMessage'; + +import { ChatbotController, ChatbotControllerInterface, EmitData } from '../../chatbot.controller'; + +export class DifyController extends ChatbotController implements ChatbotControllerInterface { + constructor( + private readonly difyService: DifyService, + prismaRepository: PrismaRepository, + waMonitor: WAMonitoringService, + ) { + super(prismaRepository, waMonitor); + + this.botRepository = this.prismaRepository.dify; + this.settingsRepository = this.prismaRepository.difySetting; + this.sessionRepository = this.prismaRepository.integrationSession; + } + + public readonly logger = new Logger('DifyController'); + + integrationEnabled = configService.get('DIFY').ENABLED; + botRepository: any; + settingsRepository: any; + sessionRepository: any; + userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; + + // Bots + public async createBot(instance: InstanceDto, data: DifyDto) { + if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + if ( + !data.expire || + !data.keywordFinish || + !data.delayMessage || + !data.unknownMessage || + !data.listeningFromMe || + !data.stopBotFromMe || + !data.keepOpen || + !data.debounceTime || + !data.ignoreJids + ) { + const defaultSettingCheck = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (!data.expire) data.expire = defaultSettingCheck?.expire || 0; + if (!data.keywordFinish) data.keywordFinish = defaultSettingCheck?.keywordFinish || ''; + if (!data.delayMessage) data.delayMessage = defaultSettingCheck?.delayMessage || 1000; + if (!data.unknownMessage) data.unknownMessage = defaultSettingCheck?.unknownMessage || ''; + if (!data.listeningFromMe) data.listeningFromMe = defaultSettingCheck?.listeningFromMe || false; + if (!data.stopBotFromMe) data.stopBotFromMe = defaultSettingCheck?.stopBotFromMe || false; + if (!data.keepOpen) data.keepOpen = defaultSettingCheck?.keepOpen || false; + if (!data.debounceTime) data.debounceTime = defaultSettingCheck?.debounceTime || 0; + if (!data.ignoreJids) data.ignoreJids = defaultSettingCheck?.ignoreJids || []; + + if (!defaultSettingCheck) { + await this.settings(instance, { + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + ignoreJids: data.ignoreJids, + }); + } + } + + const checkTriggerAll = await this.botRepository.findFirst({ + where: { + enabled: true, + triggerType: 'all', + instanceId: instanceId, + }, + }); + + if (checkTriggerAll && data.triggerType === 'all') { + throw new Error('You already have a dify with an "All" trigger, you cannot have more bots while it is active'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + instanceId: instanceId, + botType: data.botType, + apiUrl: data.apiUrl, + apiKey: data.apiKey, + }, + }); + + if (checkDuplicate) { + throw new Error('Dify already exists'); + } + + if (data.triggerType === 'keyword') { + if (!data.triggerOperator || !data.triggerValue) { + throw new Error('Trigger operator and value are required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + if (data.triggerType === 'advanced') { + if (!data.triggerValue) { + throw new Error('Trigger value is required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerValue: data.triggerValue, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + try { + const bot = await this.botRepository.create({ + data: { + enabled: data?.enabled, + description: data.description, + botType: data.botType, + apiUrl: data.apiUrl, + apiKey: data.apiKey, + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + instanceId: instanceId, + triggerType: data.triggerType, + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + ignoreJids: data.ignoreJids, + }, + }); + + return bot; + } catch (error) { + this.logger.error(error); + throw new Error('Error creating dify'); + } + } + + public async findBot(instance: InstanceDto) { + if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bots = await this.botRepository.findMany({ + where: { + instanceId: instanceId, + }, + }); + + if (!bots.length) { + return null; + } + + return bots; + } + + public async fetchBot(instance: InstanceDto, botId: string) { + if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (!bot) { + throw new Error('Dify not found'); + } + + if (bot.instanceId !== instanceId) { + throw new Error('Dify not found'); + } + + return bot; + } + + public async updateBot(instance: InstanceDto, botId: string, data: DifyDto) { + if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (!bot) { + throw new Error('Dify not found'); + } + + if (bot.instanceId !== instanceId) { + throw new Error('Dify not found'); + } + + if (data.triggerType === 'all') { + const checkTriggerAll = await this.botRepository.findFirst({ + where: { + enabled: true, + triggerType: 'all', + id: { + not: botId, + }, + instanceId: instanceId, + }, + }); + + if (checkTriggerAll) { + throw new Error('You already have a dify with an "All" trigger, you cannot have more bots while it is active'); + } + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + id: { + not: botId, + }, + instanceId: instanceId, + botType: data.botType, + apiUrl: data.apiUrl, + apiKey: data.apiKey, + }, + }); + + if (checkDuplicate) { + throw new Error('Dify already exists'); + } + + if (data.triggerType === 'keyword') { + if (!data.triggerOperator || !data.triggerValue) { + throw new Error('Trigger operator and value are required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + id: { not: botId }, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + if (data.triggerType === 'advanced') { + if (!data.triggerValue) { + throw new Error('Trigger value is required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerValue: data.triggerValue, + id: { not: botId }, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + try { + const bot = await this.botRepository.update({ + where: { + id: botId, + }, + data: { + enabled: data?.enabled, + description: data.description, + botType: data.botType, + apiUrl: data.apiUrl, + apiKey: data.apiKey, + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + instanceId: instanceId, + triggerType: data.triggerType, + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + ignoreJids: data.ignoreJids, + }, + }); + + return bot; + } catch (error) { + this.logger.error(error); + throw new Error('Error updating dify'); + } + } + + public async deleteBot(instance: InstanceDto, botId: string) { + if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (!bot) { + throw new Error('Dify not found'); + } + + if (bot.instanceId !== instanceId) { + throw new Error('Dify not found'); + } + try { + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: botId, + }, + }); + + await this.botRepository.delete({ + where: { + id: botId, + }, + }); + + return { bot: { id: botId } }; + } catch (error) { + this.logger.error(error); + throw new Error('Error deleting dify bot'); + } + } + + // Settings + public async settings(instance: InstanceDto, data: any) { + if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (settings) { + const updateSettings = await this.settingsRepository.update({ + where: { + id: settings.id, + }, + data: { + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + difyIdFallback: data.difyIdFallback, + ignoreJids: data.ignoreJids, + }, + }); + + return { + expire: updateSettings.expire, + keywordFinish: updateSettings.keywordFinish, + delayMessage: updateSettings.delayMessage, + unknownMessage: updateSettings.unknownMessage, + listeningFromMe: updateSettings.listeningFromMe, + stopBotFromMe: updateSettings.stopBotFromMe, + keepOpen: updateSettings.keepOpen, + debounceTime: updateSettings.debounceTime, + difyIdFallback: updateSettings.difyIdFallback, + ignoreJids: updateSettings.ignoreJids, + }; + } + + const newSetttings = await this.settingsRepository.create({ + data: { + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + difyIdFallback: data.difyIdFallback, + ignoreJids: data.ignoreJids, + instanceId: instanceId, + }, + }); + + return { + expire: newSetttings.expire, + keywordFinish: newSetttings.keywordFinish, + delayMessage: newSetttings.delayMessage, + unknownMessage: newSetttings.unknownMessage, + listeningFromMe: newSetttings.listeningFromMe, + stopBotFromMe: newSetttings.stopBotFromMe, + keepOpen: newSetttings.keepOpen, + debounceTime: newSetttings.debounceTime, + difyIdFallback: newSetttings.difyIdFallback, + ignoreJids: newSetttings.ignoreJids, + }; + } catch (error) { + this.logger.error(error); + throw new Error('Error setting default settings'); + } + } + + public async fetchSettings(instance: InstanceDto) { + if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + include: { + Fallback: true, + }, + }); + + if (!settings) { + return { + expire: 0, + keywordFinish: '', + delayMessage: 0, + unknownMessage: '', + listeningFromMe: false, + stopBotFromMe: false, + keepOpen: false, + ignoreJids: [], + difyIdFallback: '', + fallback: null, + }; + } + + return { + expire: settings.expire, + keywordFinish: settings.keywordFinish, + delayMessage: settings.delayMessage, + unknownMessage: settings.unknownMessage, + listeningFromMe: settings.listeningFromMe, + stopBotFromMe: settings.stopBotFromMe, + keepOpen: settings.keepOpen, + ignoreJids: settings.ignoreJids, + difyIdFallback: settings.difyIdFallback, + fallback: settings.Fallback, + }; + } catch (error) { + this.logger.error(error); + throw new Error('Error fetching default settings'); + } + } + + // Sessions + public async changeStatus(instance: InstanceDto, data: any) { + if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const defaultSettingCheck = await this.settingsRepository.findFirst({ + where: { + instanceId, + }, + }); + + const remoteJid = data.remoteJid; + const status = data.status; + + if (status === 'delete') { + await this.sessionRepository.deleteMany({ + where: { + remoteJid: remoteJid, + botId: { not: null }, + }, + }); + + return { bot: { remoteJid: remoteJid, status: status } }; + } + + if (status === 'closed') { + if (defaultSettingCheck?.keepOpen) { + await this.sessionRepository.updateMany({ + where: { + remoteJid: remoteJid, + botId: { not: null }, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.sessionRepository.deleteMany({ + where: { + remoteJid: remoteJid, + botId: { not: null }, + }, + }); + } + + return { bot: { ...instance, bot: { remoteJid: remoteJid, status: status } } }; + } else { + const session = await this.sessionRepository.updateMany({ + where: { + instanceId: instanceId, + remoteJid: remoteJid, + botId: { not: null }, + }, + data: { + status: status, + }, + }); + + const botData = { + remoteJid: remoteJid, + status: status, + session, + }; + + return { bot: { ...instance, bot: botData } }; + } + } catch (error) { + this.logger.error(error); + throw new Error('Error changing status'); + } + } + + public async fetchSessions(instance: InstanceDto, botId: string, remoteJid?: string) { + if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (bot && bot.instanceId !== instanceId) { + throw new Error('Dify not found'); + } + + return await this.sessionRepository.findMany({ + where: { + instanceId: instanceId, + remoteJid, + botId: bot ? botId : { not: null }, + type: 'dify', + }, + }); + } catch (error) { + this.logger.error(error); + throw new Error('Error fetching sessions'); + } + } + + public async ignoreJid(instance: InstanceDto, data: IgnoreJidDto) { + if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (!settings) { + throw new Error('Settings not found'); + } + + let ignoreJids: any = settings?.ignoreJids || []; + + if (data.action === 'add') { + if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; + + ignoreJids.push(data.remoteJid); + } else { + ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); + } + + const updateSettings = await this.settingsRepository.update({ + where: { + id: settings.id, + }, + data: { + ignoreJids: ignoreJids, + }, + }); + + return { + ignoreJids: updateSettings.ignoreJids, + }; + } catch (error) { + this.logger.error(error); + throw new Error('Error setting default settings'); + } + } + + // Emit + public async emit({ instance, remoteJid, msg }: EmitData) { + if (!this.integrationEnabled) return; + + try { + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instance.instanceId, + }, + }); + + if (this.checkIgnoreJids(settings?.ignoreJids, remoteJid)) return; + + const session = await this.getSession(remoteJid, instance); + + const content = getConversationMessage(msg); + + const findBot = (await this.findBotTrigger( + this.botRepository, + this.settingsRepository, + content, + instance, + session, + )) as DifyModel; + + if (!findBot) return; + + let expire = findBot?.expire; + let keywordFinish = findBot?.keywordFinish; + let delayMessage = findBot?.delayMessage; + let unknownMessage = findBot?.unknownMessage; + let listeningFromMe = findBot?.listeningFromMe; + let stopBotFromMe = findBot?.stopBotFromMe; + let keepOpen = findBot?.keepOpen; + let debounceTime = findBot?.debounceTime; + let ignoreJids = findBot?.ignoreJids; + + if (!expire) expire = settings.expire; + if (!keywordFinish) keywordFinish = settings.keywordFinish; + if (!delayMessage) delayMessage = settings.delayMessage; + if (!unknownMessage) unknownMessage = settings.unknownMessage; + if (!listeningFromMe) listeningFromMe = settings.listeningFromMe; + if (!stopBotFromMe) stopBotFromMe = settings.stopBotFromMe; + if (!keepOpen) keepOpen = settings.keepOpen; + if (!debounceTime) debounceTime = settings.debounceTime; + if (!ignoreJids) ignoreJids = settings.ignoreJids; + + const key = msg.key as { + id: string; + remoteJid: string; + fromMe: boolean; + participant: string; + }; + + if (stopBotFromMe && key.fromMe && session) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'paused', + }, + }); + return; + } + + if (!listeningFromMe && key.fromMe) { + return; + } + + if (session && !session.awaitUser) { + return; + } + + if (debounceTime && debounceTime > 0) { + this.processDebounce(this.userMessageDebounce, content, remoteJid, debounceTime, async (debouncedContent) => { + await this.difyService.processDify( + this.waMonitor.waInstances[instance.instanceName], + remoteJid, + findBot, + session, + { + ...settings, + expire, + keywordFinish, + delayMessage, + unknownMessage, + listeningFromMe, + stopBotFromMe, + keepOpen, + debounceTime, + ignoreJids, + }, + debouncedContent, + msg?.pushName, + ); + }); + } else { + await this.difyService.processDify( + this.waMonitor.waInstances[instance.instanceName], + remoteJid, + findBot, + session, + { + ...settings, + expire, + keywordFinish, + delayMessage, + unknownMessage, + listeningFromMe, + stopBotFromMe, + keepOpen, + debounceTime, + ignoreJids, + }, + content, + msg?.pushName, + ); + } + + return; + } catch (error) { + this.logger.error(error); + return; + } + } +} diff --git a/src/api/integrations/dify/dto/dify.dto.ts b/src/api/integrations/chatbot/dify/dto/dify.dto.ts similarity index 79% rename from src/api/integrations/dify/dto/dify.dto.ts rename to src/api/integrations/chatbot/dify/dto/dify.dto.ts index 7967f491..734e7dd5 100644 --- a/src/api/integrations/dify/dto/dify.dto.ts +++ b/src/api/integrations/chatbot/dify/dto/dify.dto.ts @@ -1,13 +1,5 @@ import { $Enums, TriggerOperator, TriggerType } from '@prisma/client'; -export class Session { - remoteJid?: string; - sessionId?: string; - status?: string; - createdAt?: number; - updateAt?: number; -} - export class DifyDto { enabled?: boolean; description?: string; @@ -40,8 +32,3 @@ export class DifySettingDto { difyIdFallback?: string; ignoreJids?: any; } - -export class DifyIgnoreJidDto { - remoteJid?: string; - action?: string; -} diff --git a/src/api/integrations/dify/routes/dify.router.ts b/src/api/integrations/chatbot/dify/routes/dify.router.ts similarity index 79% rename from src/api/integrations/dify/routes/dify.router.ts rename to src/api/integrations/chatbot/dify/routes/dify.router.ts index f3f61d12..1d80b903 100644 --- a/src/api/integrations/dify/routes/dify.router.ts +++ b/src/api/integrations/chatbot/dify/routes/dify.router.ts @@ -1,17 +1,17 @@ -import { RequestHandler, Router } from 'express'; - +import { RouterBroker } from '@api/abstract/abstract.router'; +import { IgnoreJidDto } from '@api/dto/chatbot.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { DifyDto, DifySettingDto } from '@api/integrations/chatbot/dify/dto/dify.dto'; +import { HttpStatus } from '@api/routes/index.router'; +import { difyController } from '@api/server.module'; import { difyIgnoreJidSchema, difySchema, difySettingSchema, difyStatusSchema, instanceSchema, -} from '../../../../validate/validate.schema'; -import { RouterBroker } from '../../../abstract/abstract.router'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { HttpStatus } from '../../../routes/index.router'; -import { difyController } from '../../../server.module'; -import { DifyDto, DifyIgnoreJidDto, DifySettingDto } from '../dto/dify.dto'; +} from '@validate/validate.schema'; +import { RequestHandler, Router } from 'express'; export class DifyRouter extends RouterBroker { constructor(...guards: RequestHandler[]) { @@ -22,7 +22,7 @@ export class DifyRouter extends RouterBroker { request: req, schema: difySchema, ClassRef: DifyDto, - execute: (instance, data) => difyController.createDify(instance, data), + execute: (instance, data) => difyController.createBot(instance, data), }); res.status(HttpStatus.CREATED).json(response); @@ -32,7 +32,7 @@ export class DifyRouter extends RouterBroker { request: req, schema: instanceSchema, ClassRef: InstanceDto, - execute: (instance) => difyController.findDify(instance), + execute: (instance) => difyController.findBot(instance), }); res.status(HttpStatus.OK).json(response); @@ -42,7 +42,7 @@ export class DifyRouter extends RouterBroker { request: req, schema: instanceSchema, ClassRef: InstanceDto, - execute: (instance) => difyController.fetchDify(instance, req.params.difyId), + execute: (instance) => difyController.fetchBot(instance, req.params.difyId), }); res.status(HttpStatus.OK).json(response); @@ -52,7 +52,7 @@ export class DifyRouter extends RouterBroker { request: req, schema: difySchema, ClassRef: DifyDto, - execute: (instance, data) => difyController.updateDify(instance, req.params.difyId, data), + execute: (instance, data) => difyController.updateBot(instance, req.params.difyId, data), }); res.status(HttpStatus.OK).json(response); @@ -62,7 +62,7 @@ export class DifyRouter extends RouterBroker { request: req, schema: instanceSchema, ClassRef: InstanceDto, - execute: (instance) => difyController.deleteDify(instance, req.params.difyId), + execute: (instance) => difyController.deleteBot(instance, req.params.difyId), }); res.status(HttpStatus.OK).json(response); @@ -108,10 +108,10 @@ export class DifyRouter extends RouterBroker { res.status(HttpStatus.OK).json(response); }) .post(this.routerPath('ignoreJid'), ...guards, async (req, res) => { - const response = await this.dataValidate({ + const response = await this.dataValidate({ request: req, schema: difyIgnoreJidSchema, - ClassRef: DifyIgnoreJidDto, + ClassRef: IgnoreJidDto, execute: (instance, data) => difyController.ignoreJid(instance, data), }); @@ -119,5 +119,5 @@ export class DifyRouter extends RouterBroker { }); } - public readonly router = Router(); + public readonly router: Router = Router(); } diff --git a/src/api/integrations/chatbot/dify/services/dify.service.ts b/src/api/integrations/chatbot/dify/services/dify.service.ts new file mode 100644 index 00000000..4c3f3f2e --- /dev/null +++ b/src/api/integrations/chatbot/dify/services/dify.service.ts @@ -0,0 +1,570 @@ +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { InstanceDto } from '@api/dto/instance.dto'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Integration } from '@api/types/wa.types'; +import { Auth, ConfigService, HttpServer } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { Dify, DifySetting, IntegrationSession } from '@prisma/client'; +import { sendTelemetry } from '@utils/sendTelemetry'; +import axios from 'axios'; +import { Readable } from 'stream'; + +export class DifyService { + constructor( + private readonly waMonitor: WAMonitoringService, + private readonly configService: ConfigService, + private readonly prismaRepository: PrismaRepository, + ) {} + + private readonly logger = new Logger('DifyService'); + + public async createNewSession(instance: InstanceDto, data: any) { + try { + const session = await this.prismaRepository.integrationSession.create({ + data: { + remoteJid: data.remoteJid, + pushName: data.pushName, + sessionId: data.remoteJid, + status: 'opened', + awaitUser: false, + botId: data.botId, + instanceId: instance.instanceId, + type: 'dify', + }, + }); + + return { session }; + } catch (error) { + this.logger.error(error); + return; + } + } + + private isImageMessage(content: string) { + return content.includes('imageMessage'); + } + + private isJSON(str: string): boolean { + try { + JSON.parse(str); + return true; + } catch (e) { + return false; + } + } + + private async sendMessageToBot( + instance: any, + session: IntegrationSession, + settings: DifySetting, + dify: Dify, + remoteJid: string, + pushName: string, + content: string, + ) { + try { + let endpoint: string = dify.apiUrl; + + if (dify.botType === 'chatBot') { + endpoint += '/chat-messages'; + const payload: any = { + inputs: { + remoteJid: remoteJid, + pushName: pushName, + instanceName: instance.instanceName, + serverUrl: this.configService.get('SERVER').URL, + apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, + }, + query: content, + response_mode: 'blocking', + conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, + user: remoteJid, + }; + + if (this.isImageMessage(content)) { + const contentSplit = content.split('|'); + + payload.files = [ + { + type: 'image', + transfer_method: 'remote_url', + url: contentSplit[1].split('?')[0], + }, + ]; + payload.query = contentSplit[2] || content; + } + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.presenceSubscribe(remoteJid); + await instance.client.sendPresenceUpdate('composing', remoteJid); + } + + const response = await axios.post(endpoint, payload, { + headers: { + Authorization: `Bearer ${dify.apiKey}`, + }, + }); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) + await instance.client.sendPresenceUpdate('paused', remoteJid); + + const message = response?.data?.answer; + const conversationId = response?.data?.conversation_id; + + await this.sendMessageWhatsApp(instance, remoteJid, message, settings); + + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: true, + sessionId: session.sessionId === remoteJid ? conversationId : session.sessionId, + }, + }); + } + + if (dify.botType === 'textGenerator') { + endpoint += '/completion-messages'; + const payload: any = { + inputs: { + query: content, + pushName: pushName, + remoteJid: remoteJid, + instanceName: instance.instanceName, + serverUrl: this.configService.get('SERVER').URL, + apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, + }, + response_mode: 'blocking', + conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, + user: remoteJid, + }; + + if (this.isImageMessage(content)) { + const contentSplit = content.split('|'); + + payload.files = [ + { + type: 'image', + transfer_method: 'remote_url', + url: contentSplit[1].split('?')[0], + }, + ]; + payload.inputs.query = contentSplit[2] || content; + } + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.presenceSubscribe(remoteJid); + await instance.client.sendPresenceUpdate('composing', remoteJid); + } + + const response = await axios.post(endpoint, payload, { + headers: { + Authorization: `Bearer ${dify.apiKey}`, + }, + }); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) + await instance.client.sendPresenceUpdate('paused', remoteJid); + + const message = response?.data?.answer; + const conversationId = response?.data?.conversation_id; + + await this.sendMessageWhatsApp(instance, remoteJid, message, settings); + + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: true, + sessionId: session.sessionId === remoteJid ? conversationId : session.sessionId, + }, + }); + } + + if (dify.botType === 'agent') { + endpoint += '/chat-messages'; + const payload: any = { + inputs: { + remoteJid: remoteJid, + pushName: pushName, + instanceName: instance.instanceName, + serverUrl: this.configService.get('SERVER').URL, + apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, + }, + query: content, + response_mode: 'streaming', + conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, + user: remoteJid, + }; + + if (this.isImageMessage(content)) { + const contentSplit = content.split('|'); + + payload.files = [ + { + type: 'image', + transfer_method: 'remote_url', + url: contentSplit[1].split('?')[0], + }, + ]; + payload.query = contentSplit[2] || content; + } + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.presenceSubscribe(remoteJid); + await instance.client.sendPresenceUpdate('composing', remoteJid); + } + + const response = await axios.post(endpoint, payload, { + headers: { + Authorization: `Bearer ${dify.apiKey}`, + }, + responseType: 'stream', + }); + + let conversationId; + let answer = ''; + + const stream = response.data; + const reader = new Readable().wrap(stream); + + reader.on('data', (chunk) => { + const data = chunk.toString().replace(/data:\s*/g, ''); + + if (data.trim() === '' || !data.startsWith('{')) { + return; + } + + try { + const events = data.split('\n').filter((line) => line.trim() !== ''); + + for (const eventString of events) { + if (eventString.trim().startsWith('{')) { + const event = JSON.parse(eventString); + + if (event?.event === 'agent_message') { + console.log('event:', event); + conversationId = conversationId ?? event?.conversation_id; + answer += event?.answer; + } + } + } + } catch (error) { + console.error('Error parsing stream data:', error); + } + }); + + reader.on('end', async () => { + if (instance.integration === Integration.WHATSAPP_BAILEYS) + await instance.client.sendPresenceUpdate('paused', remoteJid); + + const message = answer; + + await this.sendMessageWhatsApp(instance, remoteJid, message, settings); + + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: true, + sessionId: conversationId, + }, + }); + }); + + reader.on('error', (error) => { + console.error('Error reading stream:', error); + }); + + return; + } + + if (dify.botType === 'workflow') { + endpoint += '/workflows/run'; + const payload: any = { + inputs: { + query: content, + remoteJid: remoteJid, + pushName: pushName, + instanceName: instance.instanceName, + serverUrl: this.configService.get('SERVER').URL, + apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, + }, + response_mode: 'blocking', + user: remoteJid, + }; + + if (this.isImageMessage(content)) { + const contentSplit = content.split('|'); + + payload.files = [ + { + type: 'image', + transfer_method: 'remote_url', + url: contentSplit[1].split('?')[0], + }, + ]; + payload.inputs.query = contentSplit[2] || content; + } + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.presenceSubscribe(remoteJid); + await instance.client.sendPresenceUpdate('composing', remoteJid); + } + + const response = await axios.post(endpoint, payload, { + headers: { + Authorization: `Bearer ${dify.apiKey}`, + }, + }); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) + await instance.client.sendPresenceUpdate('paused', remoteJid); + + const message = response?.data?.data.outputs.text; + + await this.sendMessageWhatsApp(instance, remoteJid, message, settings); + + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: true, + }, + }); + + return; + } + } catch (error) { + this.logger.error(error.response?.data || error); + return; + } + } + + private async sendMessageWhatsApp(instance: any, remoteJid: string, message: string, settings: DifySetting) { + const linkRegex = /(!?)\[(.*?)\]\((.*?)\)/g; + + let textBuffer = ''; + let lastIndex = 0; + + let match: RegExpExecArray | null; + + const getMediaType = (url: string): string | null => { + const extension = url.split('.').pop()?.toLowerCase(); + const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']; + const audioExtensions = ['mp3', 'wav', 'aac', 'ogg']; + const videoExtensions = ['mp4', 'avi', 'mkv', 'mov']; + const documentExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']; + + if (imageExtensions.includes(extension || '')) return 'image'; + if (audioExtensions.includes(extension || '')) return 'audio'; + if (videoExtensions.includes(extension || '')) return 'video'; + if (documentExtensions.includes(extension || '')) return 'document'; + return null; + }; + + while ((match = linkRegex.exec(message)) !== null) { + const [fullMatch, exclMark, altText, url] = match; + const mediaType = getMediaType(url); + + const beforeText = message.slice(lastIndex, match.index); + if (beforeText) { + textBuffer += beforeText; + } + + if (mediaType) { + if (textBuffer.trim()) { + await instance.textMessage( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + text: textBuffer.trim(), + }, + false, + ); + textBuffer = ''; + } + + if (mediaType === 'audio') { + await instance.audioWhatsapp({ + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + audio: url, + caption: altText, + }); + } else { + await instance.mediaMessage( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + mediatype: mediaType, + media: url, + caption: altText, + }, + false, + ); + } + } else { + textBuffer += `[${altText}](${url})`; + } + + lastIndex = linkRegex.lastIndex; + } + + if (lastIndex < message.length) { + const remainingText = message.slice(lastIndex); + if (remainingText.trim()) { + textBuffer += remainingText; + } + } + + if (textBuffer.trim()) { + await instance.textMessage( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + text: textBuffer.trim(), + }, + false, + ); + } + + sendTelemetry('/message/sendText'); + } + + private async initNewSession( + instance: any, + remoteJid: string, + dify: Dify, + settings: DifySetting, + session: IntegrationSession, + content: string, + pushName?: string, + ) { + const data = await this.createNewSession(instance, { + remoteJid, + pushName, + botId: dify.id, + }); + + if (data.session) { + session = data.session; + } + + await this.sendMessageToBot(instance, session, settings, dify, remoteJid, pushName, content); + + return; + } + + public async processDify( + instance: any, + remoteJid: string, + dify: Dify, + session: IntegrationSession, + settings: DifySetting, + content: string, + pushName?: string, + ) { + if (session && session.status !== 'opened') { + return; + } + + if (session && settings.expire && settings.expire > 0) { + const now = Date.now(); + + const sessionUpdatedAt = new Date(session.updatedAt).getTime(); + + const diff = now - sessionUpdatedAt; + + const diffInMinutes = Math.floor(diff / 1000 / 60); + + if (diffInMinutes > settings.expire) { + if (settings.keepOpen) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: dify.id, + remoteJid: remoteJid, + }, + }); + } + + await this.initNewSession(instance, remoteJid, dify, settings, session, content, pushName); + return; + } + } + + if (!session) { + await this.initNewSession(instance, remoteJid, dify, settings, session, content, pushName); + return; + } + + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: false, + }, + }); + + if (!content) { + if (settings.unknownMessage) { + this.waMonitor.waInstances[instance.instanceName].textMessage( + { + number: remoteJid.split('@')[0], + delay: settings.delayMessage || 1000, + text: settings.unknownMessage, + }, + false, + ); + + sendTelemetry('/message/sendText'); + } + return; + } + + if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) { + if (settings.keepOpen) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: dify.id, + remoteJid: remoteJid, + }, + }); + } + return; + } + + await this.sendMessageToBot(instance, session, settings, dify, remoteJid, pushName, content); + + return; + } +} diff --git a/src/api/integrations/dify/validate/dify.schema.ts b/src/api/integrations/chatbot/dify/validate/dify.schema.ts similarity index 99% rename from src/api/integrations/dify/validate/dify.schema.ts rename to src/api/integrations/chatbot/dify/validate/dify.schema.ts index b3006f34..d244bbe4 100644 --- a/src/api/integrations/dify/validate/dify.schema.ts +++ b/src/api/integrations/chatbot/dify/validate/dify.schema.ts @@ -29,7 +29,7 @@ export const difySchema: JSONSchema7 = { botType: { type: 'string', enum: ['chatBot', 'textGenerator', 'agent', 'workflow'] }, apiUrl: { type: 'string' }, apiKey: { type: 'string' }, - triggerType: { type: 'string', enum: ['all', 'keyword', 'none'] }, + triggerType: { type: 'string', enum: ['all', 'keyword', 'none', 'advanced'] }, triggerOperator: { type: 'string', enum: ['equals', 'contains', 'startsWith', 'endsWith', 'regex'] }, triggerValue: { type: 'string' }, expire: { type: 'integer' }, diff --git a/src/api/integrations/chatbot/evolutionBot/controllers/evolutionBot.controller.ts b/src/api/integrations/chatbot/evolutionBot/controllers/evolutionBot.controller.ts new file mode 100644 index 00000000..a2af0c5b --- /dev/null +++ b/src/api/integrations/chatbot/evolutionBot/controllers/evolutionBot.controller.ts @@ -0,0 +1,810 @@ +import { IgnoreJidDto } from '@api/dto/chatbot.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Logger } from '@config/logger.config'; +import { EvolutionBot } from '@prisma/client'; +import { getConversationMessage } from '@utils/getConversationMessage'; + +import { ChatbotController, ChatbotControllerInterface, EmitData } from '../../chatbot.controller'; +import { EvolutionBotDto } from '../dto/evolutionBot.dto'; +import { EvolutionBotService } from '../services/evolutionBot.service'; + +export class EvolutionBotController extends ChatbotController implements ChatbotControllerInterface { + constructor( + private readonly evolutionBotService: EvolutionBotService, + prismaRepository: PrismaRepository, + waMonitor: WAMonitoringService, + ) { + super(prismaRepository, waMonitor); + + this.botRepository = this.prismaRepository.evolutionBot; + this.settingsRepository = this.prismaRepository.evolutionBotSetting; + this.sessionRepository = this.prismaRepository.integrationSession; + } + + public readonly logger = new Logger('EvolutionBotController'); + + integrationEnabled: boolean; + botRepository: any; + settingsRepository: any; + sessionRepository: any; + userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; + + // Bots + public async createBot(instance: InstanceDto, data: EvolutionBotDto) { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + if ( + !data.expire || + !data.keywordFinish || + !data.delayMessage || + !data.unknownMessage || + !data.listeningFromMe || + !data.stopBotFromMe || + !data.keepOpen || + !data.debounceTime || + !data.ignoreJids + ) { + const defaultSettingCheck = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (!data.expire) data.expire = defaultSettingCheck?.expire || 0; + if (!data.keywordFinish) data.keywordFinish = defaultSettingCheck?.keywordFinish || ''; + if (!data.delayMessage) data.delayMessage = defaultSettingCheck?.delayMessage || 1000; + if (!data.unknownMessage) data.unknownMessage = defaultSettingCheck?.unknownMessage || ''; + if (!data.listeningFromMe) data.listeningFromMe = defaultSettingCheck?.listeningFromMe || false; + if (!data.stopBotFromMe) data.stopBotFromMe = defaultSettingCheck?.stopBotFromMe || false; + if (!data.keepOpen) data.keepOpen = defaultSettingCheck?.keepOpen || false; + if (!data.debounceTime) data.debounceTime = defaultSettingCheck?.debounceTime || 0; + if (!data.ignoreJids) data.ignoreJids = defaultSettingCheck?.ignoreJids || []; + + if (!defaultSettingCheck) { + await this.settings(instance, { + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + ignoreJids: data.ignoreJids, + }); + } + } + + const checkTriggerAll = await this.botRepository.findFirst({ + where: { + enabled: true, + triggerType: 'all', + instanceId: instanceId, + }, + }); + + if (checkTriggerAll && data.triggerType === 'all') { + throw new Error('You already have a dify with an "All" trigger, you cannot have more bots while it is active'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + instanceId: instanceId, + apiUrl: data.apiUrl, + apiKey: data.apiKey, + }, + }); + + if (checkDuplicate) { + throw new Error('Dify already exists'); + } + + if (data.triggerType === 'keyword') { + if (!data.triggerOperator || !data.triggerValue) { + throw new Error('Trigger operator and value are required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + if (data.triggerType === 'advanced') { + if (!data.triggerValue) { + throw new Error('Trigger value is required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerValue: data.triggerValue, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + try { + const bot = await this.botRepository.create({ + data: { + enabled: data?.enabled, + description: data.description, + apiUrl: data.apiUrl, + apiKey: data.apiKey, + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + instanceId: instanceId, + triggerType: data.triggerType, + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + ignoreJids: data.ignoreJids, + }, + }); + + return bot; + } catch (error) { + this.logger.error(error); + throw new Error('Error creating bot'); + } + } + + public async findBot(instance: InstanceDto) { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bots = await this.botRepository.findMany({ + where: { + instanceId: instanceId, + }, + }); + + if (!bots.length) { + return null; + } + + return bots; + } + + public async fetchBot(instance: InstanceDto, botId: string) { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (!bot) { + throw new Error('Bot not found'); + } + + if (bot.instanceId !== instanceId) { + throw new Error('Bot not found'); + } + + return bot; + } + + public async updateBot(instance: InstanceDto, botId: string, data: EvolutionBotDto) { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (!bot) { + throw new Error('Bot not found'); + } + + if (bot.instanceId !== instanceId) { + throw new Error('Bot not found'); + } + + if (data.triggerType === 'all') { + const checkTriggerAll = await this.botRepository.findFirst({ + where: { + enabled: true, + triggerType: 'all', + id: { + not: botId, + }, + instanceId: instanceId, + }, + }); + + if (checkTriggerAll) { + throw new Error('You already have a bot with an "All" trigger, you cannot have more bots while it is active'); + } + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + id: { + not: botId, + }, + instanceId: instanceId, + apiUrl: data.apiUrl, + apiKey: data.apiKey, + }, + }); + + if (checkDuplicate) { + throw new Error('Bot already exists'); + } + + if (data.triggerType === 'keyword') { + if (!data.triggerOperator || !data.triggerValue) { + throw new Error('Trigger operator and value are required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + id: { not: botId }, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + if (data.triggerType === 'advanced') { + if (!data.triggerValue) { + throw new Error('Trigger value is required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerValue: data.triggerValue, + id: { not: botId }, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + try { + const bot = await this.botRepository.update({ + where: { + id: botId, + }, + data: { + enabled: data?.enabled, + description: data.description, + apiUrl: data.apiUrl, + apiKey: data.apiKey, + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + instanceId: instanceId, + triggerType: data.triggerType, + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + ignoreJids: data.ignoreJids, + }, + }); + + return bot; + } catch (error) { + this.logger.error(error); + throw new Error('Error updating bot'); + } + } + + public async deleteBot(instance: InstanceDto, botId: string) { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (!bot) { + throw new Error('Bot not found'); + } + + if (bot.instanceId !== instanceId) { + throw new Error('Bot not found'); + } + try { + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: botId, + }, + }); + + await this.botRepository.delete({ + where: { + id: botId, + }, + }); + + return { bot: { id: botId } }; + } catch (error) { + this.logger.error(error); + throw new Error('Error deleting bot'); + } + } + + // Settings + public async settings(instance: InstanceDto, data: any) { + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (settings) { + const updateSettings = await this.settingsRepository.update({ + where: { + id: settings.id, + }, + data: { + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + botIdFallback: data.botIdFallback, + ignoreJids: data.ignoreJids, + }, + }); + + return { + expire: updateSettings.expire, + keywordFinish: updateSettings.keywordFinish, + delayMessage: updateSettings.delayMessage, + unknownMessage: updateSettings.unknownMessage, + listeningFromMe: updateSettings.listeningFromMe, + stopBotFromMe: updateSettings.stopBotFromMe, + keepOpen: updateSettings.keepOpen, + debounceTime: updateSettings.debounceTime, + botIdFallback: updateSettings.botIdFallback, + ignoreJids: updateSettings.ignoreJids, + }; + } + + const newSetttings = await this.settingsRepository.create({ + data: { + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + botIdFallback: data.botIdFallback, + ignoreJids: data.ignoreJids, + instanceId: instanceId, + }, + }); + + return { + expire: newSetttings.expire, + keywordFinish: newSetttings.keywordFinish, + delayMessage: newSetttings.delayMessage, + unknownMessage: newSetttings.unknownMessage, + listeningFromMe: newSetttings.listeningFromMe, + stopBotFromMe: newSetttings.stopBotFromMe, + keepOpen: newSetttings.keepOpen, + debounceTime: newSetttings.debounceTime, + botIdFallback: newSetttings.botIdFallback, + ignoreJids: newSetttings.ignoreJids, + }; + } catch (error) { + this.logger.error(error); + throw new Error('Error setting default settings'); + } + } + + public async fetchSettings(instance: InstanceDto) { + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + include: { + Fallback: true, + }, + }); + + if (!settings) { + return { + expire: 0, + keywordFinish: '', + delayMessage: 0, + unknownMessage: '', + listeningFromMe: false, + stopBotFromMe: false, + keepOpen: false, + ignoreJids: [], + botIdFallback: '', + fallback: null, + }; + } + + return { + expire: settings.expire, + keywordFinish: settings.keywordFinish, + delayMessage: settings.delayMessage, + unknownMessage: settings.unknownMessage, + listeningFromMe: settings.listeningFromMe, + stopBotFromMe: settings.stopBotFromMe, + keepOpen: settings.keepOpen, + ignoreJids: settings.ignoreJids, + botIdFallback: settings.botIdFallback, + fallback: settings.Fallback, + }; + } catch (error) { + this.logger.error(error); + throw new Error('Error fetching default settings'); + } + } + + // Sessions + public async changeStatus(instance: InstanceDto, data: any) { + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const defaultSettingCheck = await this.settingsRepository.findFirst({ + where: { + instanceId, + }, + }); + + const remoteJid = data.remoteJid; + const status = data.status; + + if (status === 'delete') { + await this.sessionRepository.deleteMany({ + where: { + remoteJid: remoteJid, + botId: { not: null }, + }, + }); + + return { bot: { remoteJid: remoteJid, status: status } }; + } + + if (status === 'closed') { + if (defaultSettingCheck?.keepOpen) { + await this.sessionRepository.updateMany({ + where: { + remoteJid: remoteJid, + botId: { not: null }, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.sessionRepository.deleteMany({ + where: { + remoteJid: remoteJid, + botId: { not: null }, + }, + }); + } + + return { bot: { ...instance, bot: { remoteJid: remoteJid, status: status } } }; + } else { + const session = await this.sessionRepository.updateMany({ + where: { + instanceId: instanceId, + remoteJid: remoteJid, + botId: { not: null }, + }, + data: { + status: status, + }, + }); + + const botData = { + remoteJid: remoteJid, + status: status, + session, + }; + + return { bot: { ...instance, bot: botData } }; + } + } catch (error) { + this.logger.error(error); + throw new Error('Error changing status'); + } + } + + public async fetchSessions(instance: InstanceDto, botId: string, remoteJid?: string) { + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (bot && bot.instanceId !== instanceId) { + throw new Error('Dify not found'); + } + + return await this.sessionRepository.findMany({ + where: { + instanceId: instanceId, + remoteJid, + botId: bot ? botId : { not: null }, + type: 'evolution', + }, + }); + } catch (error) { + this.logger.error(error); + throw new Error('Error fetching sessions'); + } + } + + public async ignoreJid(instance: InstanceDto, data: IgnoreJidDto) { + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (!settings) { + throw new Error('Settings not found'); + } + + let ignoreJids: any = settings?.ignoreJids || []; + + if (data.action === 'add') { + if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; + + ignoreJids.push(data.remoteJid); + } else { + ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); + } + + const updateSettings = await this.settingsRepository.update({ + where: { + id: settings.id, + }, + data: { + ignoreJids: ignoreJids, + }, + }); + + return { + ignoreJids: updateSettings.ignoreJids, + }; + } catch (error) { + this.logger.error(error); + throw new Error('Error setting default settings'); + } + } + + // Emit + public async emit({ instance, remoteJid, msg }: EmitData) { + try { + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instance.instanceId, + }, + }); + + if (this.checkIgnoreJids(settings?.ignoreJids, remoteJid)) return; + + const session = await this.getSession(remoteJid, instance); + + const content = getConversationMessage(msg); + + const findBot = (await this.findBotTrigger( + this.botRepository, + this.settingsRepository, + content, + instance, + session, + )) as EvolutionBot; + + if (!findBot) return; + + let expire = findBot?.expire; + let keywordFinish = findBot?.keywordFinish; + let delayMessage = findBot?.delayMessage; + let unknownMessage = findBot?.unknownMessage; + let listeningFromMe = findBot?.listeningFromMe; + let stopBotFromMe = findBot?.stopBotFromMe; + let keepOpen = findBot?.keepOpen; + let debounceTime = findBot?.debounceTime; + let ignoreJids = findBot?.ignoreJids; + + if (!expire) expire = settings.expire; + if (!keywordFinish) keywordFinish = settings.keywordFinish; + if (!delayMessage) delayMessage = settings.delayMessage; + if (!unknownMessage) unknownMessage = settings.unknownMessage; + if (!listeningFromMe) listeningFromMe = settings.listeningFromMe; + if (!stopBotFromMe) stopBotFromMe = settings.stopBotFromMe; + if (!keepOpen) keepOpen = settings.keepOpen; + if (!debounceTime) debounceTime = settings.debounceTime; + if (!ignoreJids) ignoreJids = settings.ignoreJids; + + const key = msg.key as { + id: string; + remoteJid: string; + fromMe: boolean; + participant: string; + }; + + if (stopBotFromMe && key.fromMe && session) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'paused', + }, + }); + return; + } + + if (!listeningFromMe && key.fromMe) { + return; + } + + if (session && !session.awaitUser) { + return; + } + + if (debounceTime && debounceTime > 0) { + this.processDebounce(this.userMessageDebounce, content, remoteJid, debounceTime, async (debouncedContent) => { + await this.evolutionBotService.processBot( + this.waMonitor.waInstances[instance.instanceName], + remoteJid, + findBot, + session, + { + ...settings, + expire, + keywordFinish, + delayMessage, + unknownMessage, + listeningFromMe, + stopBotFromMe, + keepOpen, + debounceTime, + ignoreJids, + }, + debouncedContent, + msg?.pushName, + ); + }); + } else { + await this.evolutionBotService.processBot( + this.waMonitor.waInstances[instance.instanceName], + remoteJid, + findBot, + session, + { + ...settings, + expire, + keywordFinish, + delayMessage, + unknownMessage, + listeningFromMe, + stopBotFromMe, + keepOpen, + debounceTime, + ignoreJids, + }, + content, + msg?.pushName, + ); + } + + return; + } catch (error) { + this.logger.error(error); + return; + } + } +} diff --git a/src/api/integrations/chatbot/evolutionBot/dto/evolutionBot.dto.ts b/src/api/integrations/chatbot/evolutionBot/dto/evolutionBot.dto.ts new file mode 100644 index 00000000..a4ea5781 --- /dev/null +++ b/src/api/integrations/chatbot/evolutionBot/dto/evolutionBot.dto.ts @@ -0,0 +1,33 @@ +import { TriggerOperator, TriggerType } from '@prisma/client'; + +export class EvolutionBotDto { + enabled?: boolean; + description?: string; + apiUrl?: string; + apiKey?: string; + expire?: number; + keywordFinish?: string; + delayMessage?: number; + unknownMessage?: string; + listeningFromMe?: boolean; + stopBotFromMe?: boolean; + keepOpen?: boolean; + debounceTime?: number; + triggerType?: TriggerType; + triggerOperator?: TriggerOperator; + triggerValue?: string; + ignoreJids?: any; +} + +export class EvolutionBotSettingDto { + expire?: number; + keywordFinish?: string; + delayMessage?: number; + unknownMessage?: string; + listeningFromMe?: boolean; + stopBotFromMe?: boolean; + keepOpen?: boolean; + debounceTime?: number; + botIdFallback?: string; + ignoreJids?: any; +} diff --git a/src/api/integrations/chatbot/evolutionBot/routes/evolutionBot.router.ts b/src/api/integrations/chatbot/evolutionBot/routes/evolutionBot.router.ts new file mode 100644 index 00000000..15c1e743 --- /dev/null +++ b/src/api/integrations/chatbot/evolutionBot/routes/evolutionBot.router.ts @@ -0,0 +1,124 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { IgnoreJidDto } from '@api/dto/chatbot.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { HttpStatus } from '@api/routes/index.router'; +import { evolutionBotController } from '@api/server.module'; +import { instanceSchema } from '@validate/instance.schema'; +import { RequestHandler, Router } from 'express'; + +import { EvolutionBotDto, EvolutionBotSettingDto } from '../dto/evolutionBot.dto'; +import { + evolutionBotIgnoreJidSchema, + evolutionBotSchema, + evolutionBotSettingSchema, + evolutionBotStatusSchema, +} from '../validate/evolutionBot.schema'; + +export class EvolutionBotRouter extends RouterBroker { + constructor(...guards: RequestHandler[]) { + super(); + this.router + .post(this.routerPath('create'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: evolutionBotSchema, + ClassRef: EvolutionBotDto, + execute: (instance, data) => evolutionBotController.createBot(instance, data), + }); + + res.status(HttpStatus.CREATED).json(response); + }) + .get(this.routerPath('find'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => evolutionBotController.findBot(instance), + }); + + res.status(HttpStatus.OK).json(response); + }) + .get(this.routerPath('fetch/:evolutionBotId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => evolutionBotController.fetchBot(instance, req.params.evolutionBotId), + }); + + res.status(HttpStatus.OK).json(response); + }) + .put(this.routerPath('update/:evolutionBotId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: evolutionBotSchema, + ClassRef: EvolutionBotDto, + execute: (instance, data) => evolutionBotController.updateBot(instance, req.params.evolutionBotId, data), + }); + + res.status(HttpStatus.OK).json(response); + }) + .delete(this.routerPath('delete/:evolutionBotId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => evolutionBotController.deleteBot(instance, req.params.evolutionBotId), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('settings'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: evolutionBotSettingSchema, + ClassRef: EvolutionBotSettingDto, + execute: (instance, data) => evolutionBotController.settings(instance, data), + }); + + res.status(HttpStatus.OK).json(response); + }) + .get(this.routerPath('fetchSettings'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => evolutionBotController.fetchSettings(instance), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('changeStatus'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: evolutionBotStatusSchema, + ClassRef: InstanceDto, + execute: (instance, data) => evolutionBotController.changeStatus(instance, data), + }); + + res.status(HttpStatus.OK).json(response); + }) + .get(this.routerPath('fetchSessions/:evolutionBotId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => evolutionBotController.fetchSessions(instance, req.params.evolutionBotId), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('ignoreJid'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: evolutionBotIgnoreJidSchema, + ClassRef: IgnoreJidDto, + execute: (instance, data) => evolutionBotController.ignoreJid(instance, data), + }); + + res.status(HttpStatus.OK).json(response); + }); + } + + public readonly router: Router = Router(); +} diff --git a/src/api/integrations/chatbot/evolutionBot/services/evolutionBot.service.ts b/src/api/integrations/chatbot/evolutionBot/services/evolutionBot.service.ts new file mode 100644 index 00000000..bb6eb817 --- /dev/null +++ b/src/api/integrations/chatbot/evolutionBot/services/evolutionBot.service.ts @@ -0,0 +1,352 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Integration } from '@api/types/wa.types'; +import { Auth, ConfigService, HttpServer } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { EvolutionBot, EvolutionBotSetting, IntegrationSession } from '@prisma/client'; +import { sendTelemetry } from '@utils/sendTelemetry'; +import axios from 'axios'; + +export class EvolutionBotService { + constructor( + private readonly waMonitor: WAMonitoringService, + private readonly configService: ConfigService, + private readonly prismaRepository: PrismaRepository, + ) { } + + private readonly logger = new Logger('EvolutionBotService'); + + public async createNewSession(instance: InstanceDto, data: any) { + try { + const session = await this.prismaRepository.integrationSession.create({ + data: { + remoteJid: data.remoteJid, + pushName: data.pushName, + sessionId: data.remoteJid, + status: 'opened', + awaitUser: false, + botId: data.botId, + instanceId: instance.instanceId, + type: 'evolution', + }, + }); + + return { session }; + } catch (error) { + this.logger.error(error); + return; + } + } + + private isImageMessage(content: string) { + return content.includes('imageMessage'); + } + + private async sendMessageToBot( + instance: any, + session: IntegrationSession, + bot: EvolutionBot, + remoteJid: string, + pushName: string, + content: string, + ) { + const payload: any = { + inputs: { + sessionId: session.id, + remoteJid: remoteJid, + pushName: pushName, + instanceName: instance.instanceName, + serverUrl: this.configService.get('SERVER').URL, + apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, + }, + query: content, + conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, + user: remoteJid, + }; + + if (this.isImageMessage(content)) { + const contentSplit = content.split('|'); + + payload.files = [ + { + type: 'image', + url: contentSplit[1].split('?')[0], + }, + ]; + payload.query = contentSplit[2] || content; + } + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.presenceSubscribe(remoteJid); + await instance.client.sendPresenceUpdate('composing', remoteJid); + } + + let headers: any = { + 'Content-Type': 'application/json', + }; + + if (bot.apiKey) { + headers = { + ...headers, + Authorization: `Bearer ${bot.apiKey}`, + }; + } + + const response = await axios.post(bot.apiUrl, payload, { + headers, + }); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) + await instance.client.sendPresenceUpdate('paused', remoteJid); + + const message = response?.data?.message; + + return message; + } + + private async sendMessageWhatsApp( + instance: any, + remoteJid: string, + session: IntegrationSession, + settings: EvolutionBotSetting, + message: string, + ) { + const linkRegex = /(!?)\[(.*?)\]\((.*?)\)/g; + + let textBuffer = ''; + let lastIndex = 0; + + let match: RegExpExecArray | null; + + const getMediaType = (url: string): string | null => { + const extension = url.split('.').pop()?.toLowerCase(); + const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']; + const audioExtensions = ['mp3', 'wav', 'aac', 'ogg']; + const videoExtensions = ['mp4', 'avi', 'mkv', 'mov']; + const documentExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']; + + if (imageExtensions.includes(extension || '')) return 'image'; + if (audioExtensions.includes(extension || '')) return 'audio'; + if (videoExtensions.includes(extension || '')) return 'video'; + if (documentExtensions.includes(extension || '')) return 'document'; + return null; + }; + + while ((match = linkRegex.exec(message)) !== null) { + const [fullMatch, exclMark, altText, url] = match; + const mediaType = getMediaType(url); + + const beforeText = message.slice(lastIndex, match.index); + if (beforeText) { + textBuffer += beforeText; + } + + if (mediaType) { + if (textBuffer.trim()) { + await instance.textMessage( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + text: textBuffer.trim(), + }, + false + ); + textBuffer = ''; + } + + if (mediaType === 'audio') { + await instance.audioWhatsapp( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + audio: url, + caption: altText, + } + ); + } else { + await instance.mediaMessage( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + mediatype: mediaType, + media: url, + caption: altText, + }, + false + ); + } + } else { + textBuffer += `[${altText}](${url})`; + } + + lastIndex = linkRegex.lastIndex; + } + + if (lastIndex < message.length) { + const remainingText = message.slice(lastIndex); + if (remainingText.trim()) { + textBuffer += remainingText; + } + } + + if (textBuffer.trim()) { + await instance.textMessage( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + text: textBuffer.trim(), + }, + false + ); + } + + sendTelemetry('/message/sendText'); + + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: true, + }, + }); + } + + + private async initNewSession( + instance: any, + remoteJid: string, + bot: EvolutionBot, + settings: EvolutionBotSetting, + session: IntegrationSession, + content: string, + pushName?: string, + ) { + const data = await this.createNewSession(instance, { + remoteJid, + pushName, + botId: bot.id, + }); + + if (data.session) { + session = data.session; + } + + const message = await this.sendMessageToBot(instance, session, bot, remoteJid, pushName, content); + + if (!message) return; + + await this.sendMessageWhatsApp(instance, remoteJid, session, settings, message); + + return; + } + + public async processBot( + instance: any, + remoteJid: string, + bot: EvolutionBot, + session: IntegrationSession, + settings: EvolutionBotSetting, + content: string, + pushName?: string, + ) { + if (session && session.status !== 'opened') { + return; + } + + if (session && settings.expire && settings.expire > 0) { + const now = Date.now(); + + const sessionUpdatedAt = new Date(session.updatedAt).getTime(); + + const diff = now - sessionUpdatedAt; + + const diffInMinutes = Math.floor(diff / 1000 / 60); + + if (diffInMinutes > settings.expire) { + if (settings.keepOpen) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: bot.id, + remoteJid: remoteJid, + }, + }); + } + + await this.initNewSession(instance, remoteJid, bot, settings, session, content, pushName); + return; + } + } + + if (!session) { + await this.initNewSession(instance, remoteJid, bot, settings, session, content, pushName); + return; + } + + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: false, + }, + }); + + if (!content) { + if (settings.unknownMessage) { + this.waMonitor.waInstances[instance.instanceName].textMessage( + { + number: remoteJid.split('@')[0], + delay: settings.delayMessage || 1000, + text: settings.unknownMessage, + }, + false, + ); + + sendTelemetry('/message/sendText'); + } + return; + } + + if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) { + if (settings.keepOpen) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: bot.id, + remoteJid: remoteJid, + }, + }); + } + return; + } + + const message = await this.sendMessageToBot(instance, session, bot, remoteJid, pushName, content); + + if (!message) return; + + await this.sendMessageWhatsApp(instance, remoteJid, session, settings, message); + + return; + } +} diff --git a/src/api/integrations/chatbot/evolutionBot/validate/evolutionBot.schema.ts b/src/api/integrations/chatbot/evolutionBot/validate/evolutionBot.schema.ts new file mode 100644 index 00000000..2c5fc752 --- /dev/null +++ b/src/api/integrations/chatbot/evolutionBot/validate/evolutionBot.schema.ts @@ -0,0 +1,107 @@ +import { JSONSchema7 } from 'json-schema'; +import { v4 } from 'uuid'; + +const isNotEmpty = (...propertyNames: string[]): JSONSchema7 => { + const properties = {}; + propertyNames.forEach( + (property) => + (properties[property] = { + minLength: 1, + description: `The "${property}" cannot be empty`, + }), + ); + return { + if: { + propertyNames: { + enum: [...propertyNames], + }, + }, + then: { properties }, + }; +}; + +export const evolutionBotSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + enabled: { type: 'boolean' }, + description: { type: 'string' }, + apiUrl: { type: 'string' }, + apiKey: { type: 'string' }, + triggerType: { type: 'string', enum: ['all', 'keyword', 'none', 'advanced'] }, + triggerOperator: { type: 'string', enum: ['equals', 'contains', 'startsWith', 'endsWith', 'regex'] }, + triggerValue: { type: 'string' }, + expire: { type: 'integer' }, + keywordFinish: { type: 'string' }, + delayMessage: { type: 'integer' }, + unknownMessage: { type: 'string' }, + listeningFromMe: { type: 'boolean' }, + stopBotFromMe: { type: 'boolean' }, + keepOpen: { type: 'boolean' }, + debounceTime: { type: 'integer' }, + ignoreJids: { type: 'array', items: { type: 'string' } }, + }, + required: ['enabled', 'apiUrl', 'triggerType'], + ...isNotEmpty('enabled', 'apiUrl', 'triggerType'), +}; + +export const evolutionBotStatusSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + remoteJid: { type: 'string' }, + status: { type: 'string', enum: ['opened', 'closed', 'paused', 'delete'] }, + }, + required: ['remoteJid', 'status'], + ...isNotEmpty('remoteJid', 'status'), +}; + +export const evolutionBotSettingSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + expire: { type: 'integer' }, + keywordFinish: { type: 'string' }, + delayMessage: { type: 'integer' }, + unknownMessage: { type: 'string' }, + listeningFromMe: { type: 'boolean' }, + stopBotFromMe: { type: 'boolean' }, + keepOpen: { type: 'boolean' }, + debounceTime: { type: 'integer' }, + ignoreJids: { type: 'array', items: { type: 'string' } }, + botIdFallback: { type: 'string' }, + }, + required: [ + 'expire', + 'keywordFinish', + 'delayMessage', + 'unknownMessage', + 'listeningFromMe', + 'stopBotFromMe', + 'keepOpen', + 'debounceTime', + 'ignoreJids', + ], + ...isNotEmpty( + 'expire', + 'keywordFinish', + 'delayMessage', + 'unknownMessage', + 'listeningFromMe', + 'stopBotFromMe', + 'keepOpen', + 'debounceTime', + 'ignoreJids', + ), +}; + +export const evolutionBotIgnoreJidSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + remoteJid: { type: 'string' }, + action: { type: 'string', enum: ['add', 'remove'] }, + }, + required: ['remoteJid', 'action'], + ...isNotEmpty('remoteJid', 'action'), +}; diff --git a/src/api/integrations/chatbot/flowise/controllers/flowise.controller.ts b/src/api/integrations/chatbot/flowise/controllers/flowise.controller.ts new file mode 100644 index 00000000..3ba2d1cc --- /dev/null +++ b/src/api/integrations/chatbot/flowise/controllers/flowise.controller.ts @@ -0,0 +1,810 @@ +import { IgnoreJidDto } from '@api/dto/chatbot.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Logger } from '@config/logger.config'; +import { Flowise } from '@prisma/client'; +import { getConversationMessage } from '@utils/getConversationMessage'; + +import { ChatbotController, ChatbotControllerInterface, EmitData } from '../../chatbot.controller'; +import { FlowiseDto } from '../dto/flowise.dto'; +import { FlowiseService } from '../services/flowise.service'; + +export class FlowiseController extends ChatbotController implements ChatbotControllerInterface { + constructor( + private readonly flowiseService: FlowiseService, + prismaRepository: PrismaRepository, + waMonitor: WAMonitoringService, + ) { + super(prismaRepository, waMonitor); + + this.botRepository = this.prismaRepository.flowise; + this.settingsRepository = this.prismaRepository.flowiseSetting; + this.sessionRepository = this.prismaRepository.integrationSession; + } + + public readonly logger = new Logger('FlowiseController'); + + integrationEnabled: boolean; + botRepository: any; + settingsRepository: any; + sessionRepository: any; + userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; + + // Bots + public async createBot(instance: InstanceDto, data: FlowiseDto) { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + if ( + !data.expire || + !data.keywordFinish || + !data.delayMessage || + !data.unknownMessage || + !data.listeningFromMe || + !data.stopBotFromMe || + !data.keepOpen || + !data.debounceTime || + !data.ignoreJids + ) { + const defaultSettingCheck = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (!data.expire) data.expire = defaultSettingCheck?.expire || 0; + if (!data.keywordFinish) data.keywordFinish = defaultSettingCheck?.keywordFinish || ''; + if (!data.delayMessage) data.delayMessage = defaultSettingCheck?.delayMessage || 1000; + if (!data.unknownMessage) data.unknownMessage = defaultSettingCheck?.unknownMessage || ''; + if (!data.listeningFromMe) data.listeningFromMe = defaultSettingCheck?.listeningFromMe || false; + if (!data.stopBotFromMe) data.stopBotFromMe = defaultSettingCheck?.stopBotFromMe || false; + if (!data.keepOpen) data.keepOpen = defaultSettingCheck?.keepOpen || false; + if (!data.debounceTime) data.debounceTime = defaultSettingCheck?.debounceTime || 0; + if (!data.ignoreJids) data.ignoreJids = defaultSettingCheck?.ignoreJids || []; + + if (!defaultSettingCheck) { + await this.settings(instance, { + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + ignoreJids: data.ignoreJids, + }); + } + } + + const checkTriggerAll = await this.botRepository.findFirst({ + where: { + enabled: true, + triggerType: 'all', + instanceId: instanceId, + }, + }); + + if (checkTriggerAll && data.triggerType === 'all') { + throw new Error('You already have a Flowise with an "All" trigger, you cannot have more bots while it is active'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + instanceId: instanceId, + apiUrl: data.apiUrl, + apiKey: data.apiKey, + }, + }); + + if (checkDuplicate) { + throw new Error('Flowise already exists'); + } + + if (data.triggerType === 'keyword') { + if (!data.triggerOperator || !data.triggerValue) { + throw new Error('Trigger operator and value are required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + if (data.triggerType === 'advanced') { + if (!data.triggerValue) { + throw new Error('Trigger value is required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerValue: data.triggerValue, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + try { + const bot = await this.botRepository.create({ + data: { + enabled: data?.enabled, + description: data.description, + apiUrl: data.apiUrl, + apiKey: data.apiKey, + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + instanceId: instanceId, + triggerType: data.triggerType, + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + ignoreJids: data.ignoreJids, + }, + }); + + return bot; + } catch (error) { + this.logger.error(error); + throw new Error('Error creating bot'); + } + } + + public async findBot(instance: InstanceDto) { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bots = await this.botRepository.findMany({ + where: { + instanceId: instanceId, + }, + }); + + if (!bots.length) { + return null; + } + + return bots; + } + + public async fetchBot(instance: InstanceDto, botId: string) { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (!bot) { + throw new Error('Bot not found'); + } + + if (bot.instanceId !== instanceId) { + throw new Error('Bot not found'); + } + + return bot; + } + + public async updateBot(instance: InstanceDto, botId: string, data: FlowiseDto) { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (!bot) { + throw new Error('Bot not found'); + } + + if (bot.instanceId !== instanceId) { + throw new Error('Bot not found'); + } + + if (data.triggerType === 'all') { + const checkTriggerAll = await this.botRepository.findFirst({ + where: { + enabled: true, + triggerType: 'all', + id: { + not: botId, + }, + instanceId: instanceId, + }, + }); + + if (checkTriggerAll) { + throw new Error('You already have a bot with an "All" trigger, you cannot have more bots while it is active'); + } + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + id: { + not: botId, + }, + instanceId: instanceId, + apiUrl: data.apiUrl, + apiKey: data.apiKey, + }, + }); + + if (checkDuplicate) { + throw new Error('Bot already exists'); + } + + if (data.triggerType === 'keyword') { + if (!data.triggerOperator || !data.triggerValue) { + throw new Error('Trigger operator and value are required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + id: { not: botId }, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + if (data.triggerType === 'advanced') { + if (!data.triggerValue) { + throw new Error('Trigger value is required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerValue: data.triggerValue, + id: { not: botId }, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + try { + const bot = await this.botRepository.update({ + where: { + id: botId, + }, + data: { + enabled: data?.enabled, + description: data.description, + apiUrl: data.apiUrl, + apiKey: data.apiKey, + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + instanceId: instanceId, + triggerType: data.triggerType, + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + ignoreJids: data.ignoreJids, + }, + }); + + return bot; + } catch (error) { + this.logger.error(error); + throw new Error('Error updating bot'); + } + } + + public async deleteBot(instance: InstanceDto, botId: string) { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (!bot) { + throw new Error('Bot not found'); + } + + if (bot.instanceId !== instanceId) { + throw new Error('Bot not found'); + } + try { + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: botId, + }, + }); + + await this.botRepository.delete({ + where: { + id: botId, + }, + }); + + return { bot: { id: botId } }; + } catch (error) { + this.logger.error(error); + throw new Error('Error deleting bot'); + } + } + + // Settings + public async settings(instance: InstanceDto, data: any) { + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (settings) { + const updateSettings = await this.settingsRepository.update({ + where: { + id: settings.id, + }, + data: { + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + flowiseIdFallback: data.flowiseIdFallback, + ignoreJids: data.ignoreJids, + }, + }); + + return { + expire: updateSettings.expire, + keywordFinish: updateSettings.keywordFinish, + delayMessage: updateSettings.delayMessage, + unknownMessage: updateSettings.unknownMessage, + listeningFromMe: updateSettings.listeningFromMe, + stopBotFromMe: updateSettings.stopBotFromMe, + keepOpen: updateSettings.keepOpen, + debounceTime: updateSettings.debounceTime, + flowiseIdFallback: updateSettings.flowiseIdFallback, + ignoreJids: updateSettings.ignoreJids, + }; + } + + const newSetttings = await this.settingsRepository.create({ + data: { + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + flowiseIdFallback: data.flowiseIdFallback, + ignoreJids: data.ignoreJids, + instanceId: instanceId, + }, + }); + + return { + expire: newSetttings.expire, + keywordFinish: newSetttings.keywordFinish, + delayMessage: newSetttings.delayMessage, + unknownMessage: newSetttings.unknownMessage, + listeningFromMe: newSetttings.listeningFromMe, + stopBotFromMe: newSetttings.stopBotFromMe, + keepOpen: newSetttings.keepOpen, + debounceTime: newSetttings.debounceTime, + flowiseIdFallback: newSetttings.flowiseIdFallback, + ignoreJids: newSetttings.ignoreJids, + }; + } catch (error) { + this.logger.error(error); + throw new Error('Error setting default settings'); + } + } + + public async fetchSettings(instance: InstanceDto) { + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + include: { + Fallback: true, + }, + }); + + if (!settings) { + return { + expire: 0, + keywordFinish: '', + delayMessage: 0, + unknownMessage: '', + listeningFromMe: false, + stopBotFromMe: false, + keepOpen: false, + ignoreJids: [], + flowiseIdFallback: '', + fallback: null, + }; + } + + return { + expire: settings.expire, + keywordFinish: settings.keywordFinish, + delayMessage: settings.delayMessage, + unknownMessage: settings.unknownMessage, + listeningFromMe: settings.listeningFromMe, + stopBotFromMe: settings.stopBotFromMe, + keepOpen: settings.keepOpen, + ignoreJids: settings.ignoreJids, + flowiseIdFallback: settings.flowiseIdFallback, + fallback: settings.Fallback, + }; + } catch (error) { + this.logger.error(error); + throw new Error('Error fetching default settings'); + } + } + + // Sessions + public async changeStatus(instance: InstanceDto, data: any) { + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const defaultSettingCheck = await this.settingsRepository.findFirst({ + where: { + instanceId, + }, + }); + + const remoteJid = data.remoteJid; + const status = data.status; + + if (status === 'delete') { + await this.sessionRepository.deleteMany({ + where: { + remoteJid: remoteJid, + botId: { not: null }, + }, + }); + + return { bot: { remoteJid: remoteJid, status: status } }; + } + + if (status === 'closed') { + if (defaultSettingCheck?.keepOpen) { + await this.sessionRepository.updateMany({ + where: { + remoteJid: remoteJid, + botId: { not: null }, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.sessionRepository.deleteMany({ + where: { + remoteJid: remoteJid, + botId: { not: null }, + }, + }); + } + + return { bot: { ...instance, bot: { remoteJid: remoteJid, status: status } } }; + } else { + const session = await this.sessionRepository.updateMany({ + where: { + instanceId: instanceId, + remoteJid: remoteJid, + botId: { not: null }, + }, + data: { + status: status, + }, + }); + + const botData = { + remoteJid: remoteJid, + status: status, + session, + }; + + return { bot: { ...instance, bot: botData } }; + } + } catch (error) { + this.logger.error(error); + throw new Error('Error changing status'); + } + } + + public async fetchSessions(instance: InstanceDto, botId: string, remoteJid?: string) { + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (bot && bot.instanceId !== instanceId) { + throw new Error('Dify not found'); + } + + return await this.sessionRepository.findMany({ + where: { + instanceId: instanceId, + remoteJid, + botId: bot ? botId : { not: null }, + type: 'flowise', + }, + }); + } catch (error) { + this.logger.error(error); + throw new Error('Error fetching sessions'); + } + } + + public async ignoreJid(instance: InstanceDto, data: IgnoreJidDto) { + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (!settings) { + throw new Error('Settings not found'); + } + + let ignoreJids: any = settings?.ignoreJids || []; + + if (data.action === 'add') { + if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; + + ignoreJids.push(data.remoteJid); + } else { + ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); + } + + const updateSettings = await this.settingsRepository.update({ + where: { + id: settings.id, + }, + data: { + ignoreJids: ignoreJids, + }, + }); + + return { + ignoreJids: updateSettings.ignoreJids, + }; + } catch (error) { + this.logger.error(error); + throw new Error('Error setting default settings'); + } + } + + // Emit + public async emit({ instance, remoteJid, msg }: EmitData) { + try { + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instance.instanceId, + }, + }); + + if (this.checkIgnoreJids(settings?.ignoreJids, remoteJid)) return; + + const session = await this.getSession(remoteJid, instance); + + const content = getConversationMessage(msg); + + const findBot = (await this.findBotTrigger( + this.botRepository, + this.settingsRepository, + content, + instance, + session, + )) as Flowise; + + if (!findBot) return; + + let expire = findBot?.expire; + let keywordFinish = findBot?.keywordFinish; + let delayMessage = findBot?.delayMessage; + let unknownMessage = findBot?.unknownMessage; + let listeningFromMe = findBot?.listeningFromMe; + let stopBotFromMe = findBot?.stopBotFromMe; + let keepOpen = findBot?.keepOpen; + let debounceTime = findBot?.debounceTime; + let ignoreJids = findBot?.ignoreJids; + + if (!expire) expire = settings.expire; + if (!keywordFinish) keywordFinish = settings.keywordFinish; + if (!delayMessage) delayMessage = settings.delayMessage; + if (!unknownMessage) unknownMessage = settings.unknownMessage; + if (!listeningFromMe) listeningFromMe = settings.listeningFromMe; + if (!stopBotFromMe) stopBotFromMe = settings.stopBotFromMe; + if (!keepOpen) keepOpen = settings.keepOpen; + if (!debounceTime) debounceTime = settings.debounceTime; + if (!ignoreJids) ignoreJids = settings.ignoreJids; + + const key = msg.key as { + id: string; + remoteJid: string; + fromMe: boolean; + participant: string; + }; + + if (stopBotFromMe && key.fromMe && session) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'paused', + }, + }); + return; + } + + if (!listeningFromMe && key.fromMe) { + return; + } + + if (session && !session.awaitUser) { + return; + } + + if (debounceTime && debounceTime > 0) { + this.processDebounce(this.userMessageDebounce, content, remoteJid, debounceTime, async (debouncedContent) => { + await this.flowiseService.processBot( + this.waMonitor.waInstances[instance.instanceName], + remoteJid, + findBot, + session, + { + ...settings, + expire, + keywordFinish, + delayMessage, + unknownMessage, + listeningFromMe, + stopBotFromMe, + keepOpen, + debounceTime, + ignoreJids, + }, + debouncedContent, + msg?.pushName, + ); + }); + } else { + await this.flowiseService.processBot( + this.waMonitor.waInstances[instance.instanceName], + remoteJid, + findBot, + session, + { + ...settings, + expire, + keywordFinish, + delayMessage, + unknownMessage, + listeningFromMe, + stopBotFromMe, + keepOpen, + debounceTime, + ignoreJids, + }, + content, + msg?.pushName, + ); + } + + return; + } catch (error) { + this.logger.error(error); + return; + } + } +} diff --git a/src/api/integrations/chatbot/flowise/dto/flowise.dto.ts b/src/api/integrations/chatbot/flowise/dto/flowise.dto.ts new file mode 100644 index 00000000..a840a75c --- /dev/null +++ b/src/api/integrations/chatbot/flowise/dto/flowise.dto.ts @@ -0,0 +1,33 @@ +import { TriggerOperator, TriggerType } from '@prisma/client'; + +export class FlowiseDto { + enabled?: boolean; + description?: string; + apiUrl?: string; + apiKey?: string; + expire?: number; + keywordFinish?: string; + delayMessage?: number; + unknownMessage?: string; + listeningFromMe?: boolean; + stopBotFromMe?: boolean; + keepOpen?: boolean; + debounceTime?: number; + triggerType?: TriggerType; + triggerOperator?: TriggerOperator; + triggerValue?: string; + ignoreJids?: any; +} + +export class FlowiseSettingDto { + expire?: number; + keywordFinish?: string; + delayMessage?: number; + unknownMessage?: string; + listeningFromMe?: boolean; + stopBotFromMe?: boolean; + keepOpen?: boolean; + debounceTime?: number; + flowiseIdFallback?: string; + ignoreJids?: any; +} diff --git a/src/api/integrations/chatbot/flowise/routes/flowise.router.ts b/src/api/integrations/chatbot/flowise/routes/flowise.router.ts new file mode 100644 index 00000000..3527f7ce --- /dev/null +++ b/src/api/integrations/chatbot/flowise/routes/flowise.router.ts @@ -0,0 +1,124 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { IgnoreJidDto } from '@api/dto/chatbot.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { HttpStatus } from '@api/routes/index.router'; +import { flowiseController } from '@api/server.module'; +import { instanceSchema } from '@validate/instance.schema'; +import { RequestHandler, Router } from 'express'; + +import { FlowiseDto, FlowiseSettingDto } from '../dto/flowise.dto'; +import { + flowiseIgnoreJidSchema, + flowiseSchema, + flowiseSettingSchema, + flowiseStatusSchema, +} from '../validate/flowise.schema'; + +export class FlowiseRouter extends RouterBroker { + constructor(...guards: RequestHandler[]) { + super(); + this.router + .post(this.routerPath('create'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: flowiseSchema, + ClassRef: FlowiseDto, + execute: (instance, data) => flowiseController.createBot(instance, data), + }); + + res.status(HttpStatus.CREATED).json(response); + }) + .get(this.routerPath('find'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => flowiseController.findBot(instance), + }); + + res.status(HttpStatus.OK).json(response); + }) + .get(this.routerPath('fetch/:flowiseId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => flowiseController.fetchBot(instance, req.params.flowiseId), + }); + + res.status(HttpStatus.OK).json(response); + }) + .put(this.routerPath('update/:flowiseId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: flowiseSchema, + ClassRef: FlowiseDto, + execute: (instance, data) => flowiseController.updateBot(instance, req.params.flowiseId, data), + }); + + res.status(HttpStatus.OK).json(response); + }) + .delete(this.routerPath('delete/:flowiseId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => flowiseController.deleteBot(instance, req.params.flowiseId), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('settings'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: flowiseSettingSchema, + ClassRef: FlowiseSettingDto, + execute: (instance, data) => flowiseController.settings(instance, data), + }); + + res.status(HttpStatus.OK).json(response); + }) + .get(this.routerPath('fetchSettings'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => flowiseController.fetchSettings(instance), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('changeStatus'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: flowiseStatusSchema, + ClassRef: InstanceDto, + execute: (instance, data) => flowiseController.changeStatus(instance, data), + }); + + res.status(HttpStatus.OK).json(response); + }) + .get(this.routerPath('fetchSessions/:flowiseId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => flowiseController.fetchSessions(instance, req.params.flowiseId), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('ignoreJid'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: flowiseIgnoreJidSchema, + ClassRef: IgnoreJidDto, + execute: (instance, data) => flowiseController.ignoreJid(instance, data), + }); + + res.status(HttpStatus.OK).json(response); + }); + } + + public readonly router: Router = Router(); +} diff --git a/src/api/integrations/chatbot/flowise/services/flowise.service.ts b/src/api/integrations/chatbot/flowise/services/flowise.service.ts new file mode 100644 index 00000000..c0b66dd6 --- /dev/null +++ b/src/api/integrations/chatbot/flowise/services/flowise.service.ts @@ -0,0 +1,347 @@ +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { InstanceDto } from '@api/dto/instance.dto'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Integration } from '@api/types/wa.types'; +import { Auth, ConfigService, HttpServer } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { Flowise, FlowiseSetting, IntegrationSession } from '@prisma/client'; +import { sendTelemetry } from '@utils/sendTelemetry'; +import axios from 'axios'; + +export class FlowiseService { + constructor( + private readonly waMonitor: WAMonitoringService, + private readonly configService: ConfigService, + private readonly prismaRepository: PrismaRepository, + ) {} + + private readonly logger = new Logger('FlowiseService'); + + public async createNewSession(instance: InstanceDto, data: any) { + try { + const session = await this.prismaRepository.integrationSession.create({ + data: { + remoteJid: data.remoteJid, + pushName: data.pushName, + sessionId: data.remoteJid, + status: 'opened', + awaitUser: false, + botId: data.botId, + instanceId: instance.instanceId, + type: 'flowise', + }, + }); + + return { session }; + } catch (error) { + this.logger.error(error); + return; + } + } + + private isImageMessage(content: string) { + return content.includes('imageMessage'); + } + + private async sendMessageToBot(instance: any, bot: Flowise, remoteJid: string, pushName: string, content: string) { + const payload: any = { + question: content, + overrideConfig: { + sessionId: remoteJid, + vars: { + remoteJid: remoteJid, + pushName: pushName, + instanceName: instance.instanceName, + serverUrl: this.configService.get('SERVER').URL, + apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, + }, + }, + }; + + if (this.isImageMessage(content)) { + const contentSplit = content.split('|'); + + payload.uploads = [ + { + data: contentSplit[1].split('?')[0], + type: 'url', + name: 'Flowise.png', + mime: 'image/png', + }, + ]; + payload.question = contentSplit[2] || content; + } + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.presenceSubscribe(remoteJid); + await instance.client.sendPresenceUpdate('composing', remoteJid); + } + + let headers: any = { + 'Content-Type': 'application/json', + }; + + if (bot.apiKey) { + headers = { + ...headers, + Authorization: `Bearer ${bot.apiKey}`, + }; + } + + const endpoint = bot.apiUrl; + + if (!endpoint) return null; + + const response = await axios.post(endpoint, payload, { + headers, + }); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) + await instance.client.sendPresenceUpdate('paused', remoteJid); + + const message = response?.data?.text; + + return message; + } + + private async sendMessageWhatsApp( + instance: any, + remoteJid: string, + session: IntegrationSession, + settings: FlowiseSetting, + message: string, + ) { + const linkRegex = /(!?)\[(.*?)\]\((.*?)\)/g; + + let textBuffer = ''; + let lastIndex = 0; + + let match: RegExpExecArray | null; + + const getMediaType = (url: string): string | null => { + const extension = url.split('.').pop()?.toLowerCase(); + const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']; + const audioExtensions = ['mp3', 'wav', 'aac', 'ogg']; + const videoExtensions = ['mp4', 'avi', 'mkv', 'mov']; + const documentExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']; + + if (imageExtensions.includes(extension || '')) return 'image'; + if (audioExtensions.includes(extension || '')) return 'audio'; + if (videoExtensions.includes(extension || '')) return 'video'; + if (documentExtensions.includes(extension || '')) return 'document'; + return null; + }; + + while ((match = linkRegex.exec(message)) !== null) { + const [fullMatch, exclMark, altText, url] = match; + const mediaType = getMediaType(url); + + const beforeText = message.slice(lastIndex, match.index); + if (beforeText) { + textBuffer += beforeText; + } + + if (mediaType) { + if (textBuffer.trim()) { + await instance.textMessage( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + text: textBuffer.trim(), + }, + false, + ); + textBuffer = ''; + } + + if (mediaType === 'audio') { + await instance.audioWhatsapp({ + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + audio: url, + caption: altText, + }); + } else { + await instance.mediaMessage( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + mediatype: mediaType, + media: url, + caption: altText, + }, + false, + ); + } + } else { + textBuffer += `[${altText}](${url})`; + } + + lastIndex = linkRegex.lastIndex; + } + + if (lastIndex < message.length) { + const remainingText = message.slice(lastIndex); + if (remainingText.trim()) { + textBuffer += remainingText; + } + } + + if (textBuffer.trim()) { + await instance.textMessage( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + text: textBuffer.trim(), + }, + false, + ); + } + + sendTelemetry('/message/sendText'); + + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: true, + }, + }); + + return; + } + + private async initNewSession( + instance: any, + remoteJid: string, + bot: Flowise, + settings: FlowiseSetting, + session: IntegrationSession, + content: string, + pushName?: string, + ) { + const data = await this.createNewSession(instance, { + remoteJid, + pushName, + botId: bot.id, + }); + + if (data.session) { + session = data.session; + } + + const message = await this.sendMessageToBot(instance, bot, remoteJid, pushName, content); + + await this.sendMessageWhatsApp(instance, remoteJid, session, settings, message); + + return; + } + + public async processBot( + instance: any, + remoteJid: string, + bot: Flowise, + session: IntegrationSession, + settings: FlowiseSetting, + content: string, + pushName?: string, + ) { + if (session && session.status !== 'opened') { + return; + } + + if (session && settings.expire && settings.expire > 0) { + const now = Date.now(); + + const sessionUpdatedAt = new Date(session.updatedAt).getTime(); + + const diff = now - sessionUpdatedAt; + + const diffInMinutes = Math.floor(diff / 1000 / 60); + + if (diffInMinutes > settings.expire) { + if (settings.keepOpen) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: bot.id, + remoteJid: remoteJid, + }, + }); + } + + await this.initNewSession(instance, remoteJid, bot, settings, session, content, pushName); + return; + } + } + + if (!session) { + await this.initNewSession(instance, remoteJid, bot, settings, session, content, pushName); + return; + } + + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: false, + }, + }); + + if (!content) { + if (settings.unknownMessage) { + this.waMonitor.waInstances[instance.instanceName].textMessage( + { + number: remoteJid.split('@')[0], + delay: settings.delayMessage || 1000, + text: settings.unknownMessage, + }, + false, + ); + + sendTelemetry('/message/sendText'); + } + return; + } + + if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) { + if (settings.keepOpen) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: bot.id, + remoteJid: remoteJid, + }, + }); + } + return; + } + + const message = await this.sendMessageToBot(instance, bot, remoteJid, pushName, content); + + await this.sendMessageWhatsApp(instance, remoteJid, session, settings, message); + + return; + } +} diff --git a/src/api/integrations/chatbot/flowise/validate/flowise.schema.ts b/src/api/integrations/chatbot/flowise/validate/flowise.schema.ts new file mode 100644 index 00000000..83f9d1ea --- /dev/null +++ b/src/api/integrations/chatbot/flowise/validate/flowise.schema.ts @@ -0,0 +1,107 @@ +import { JSONSchema7 } from 'json-schema'; +import { v4 } from 'uuid'; + +const isNotEmpty = (...propertyNames: string[]): JSONSchema7 => { + const properties = {}; + propertyNames.forEach( + (property) => + (properties[property] = { + minLength: 1, + description: `The "${property}" cannot be empty`, + }), + ); + return { + if: { + propertyNames: { + enum: [...propertyNames], + }, + }, + then: { properties }, + }; +}; + +export const flowiseSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + enabled: { type: 'boolean' }, + description: { type: 'string' }, + apiUrl: { type: 'string' }, + apiKey: { type: 'string' }, + triggerType: { type: 'string', enum: ['all', 'keyword', 'none', 'advanced'] }, + triggerOperator: { type: 'string', enum: ['equals', 'contains', 'startsWith', 'endsWith', 'regex'] }, + triggerValue: { type: 'string' }, + expire: { type: 'integer' }, + keywordFinish: { type: 'string' }, + delayMessage: { type: 'integer' }, + unknownMessage: { type: 'string' }, + listeningFromMe: { type: 'boolean' }, + stopBotFromMe: { type: 'boolean' }, + keepOpen: { type: 'boolean' }, + debounceTime: { type: 'integer' }, + ignoreJids: { type: 'array', items: { type: 'string' } }, + }, + required: ['enabled', 'apiUrl', 'triggerType'], + ...isNotEmpty('enabled', 'apiUrl', 'triggerType'), +}; + +export const flowiseStatusSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + remoteJid: { type: 'string' }, + status: { type: 'string', enum: ['opened', 'closed', 'paused', 'delete'] }, + }, + required: ['remoteJid', 'status'], + ...isNotEmpty('remoteJid', 'status'), +}; + +export const flowiseSettingSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + expire: { type: 'integer' }, + keywordFinish: { type: 'string' }, + delayMessage: { type: 'integer' }, + unknownMessage: { type: 'string' }, + listeningFromMe: { type: 'boolean' }, + stopBotFromMe: { type: 'boolean' }, + keepOpen: { type: 'boolean' }, + debounceTime: { type: 'integer' }, + ignoreJids: { type: 'array', items: { type: 'string' } }, + botIdFallback: { type: 'string' }, + }, + required: [ + 'expire', + 'keywordFinish', + 'delayMessage', + 'unknownMessage', + 'listeningFromMe', + 'stopBotFromMe', + 'keepOpen', + 'debounceTime', + 'ignoreJids', + ], + ...isNotEmpty( + 'expire', + 'keywordFinish', + 'delayMessage', + 'unknownMessage', + 'listeningFromMe', + 'stopBotFromMe', + 'keepOpen', + 'debounceTime', + 'ignoreJids', + ), +}; + +export const flowiseIgnoreJidSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + remoteJid: { type: 'string' }, + action: { type: 'string', enum: ['add', 'remove'] }, + }, + required: ['remoteJid', 'action'], + ...isNotEmpty('remoteJid', 'action'), +}; diff --git a/src/api/integrations/chatbot/openai/controllers/openai.controller.ts b/src/api/integrations/chatbot/openai/controllers/openai.controller.ts new file mode 100644 index 00000000..f0fb6276 --- /dev/null +++ b/src/api/integrations/chatbot/openai/controllers/openai.controller.ts @@ -0,0 +1,1076 @@ +import { IgnoreJidDto } from '@api/dto/chatbot.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { OpenaiCredsDto, OpenaiDto } from '@api/integrations/chatbot/openai/dto/openai.dto'; +import { OpenaiService } from '@api/integrations/chatbot/openai/services/openai.service'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { configService, Openai } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { BadRequestException } from '@exceptions'; +import { OpenaiBot } from '@prisma/client'; +import { getConversationMessage } from '@utils/getConversationMessage'; +import OpenAI from 'openai'; + +import { ChatbotController, ChatbotControllerInterface, EmitData } from '../../chatbot.controller'; + +export class OpenaiController extends ChatbotController implements ChatbotControllerInterface { + constructor( + private readonly openaiService: OpenaiService, + prismaRepository: PrismaRepository, + waMonitor: WAMonitoringService, + ) { + super(prismaRepository, waMonitor); + + this.botRepository = this.prismaRepository.openaiBot; + this.settingsRepository = this.prismaRepository.openaiSetting; + this.sessionRepository = this.prismaRepository.integrationSession; + this.credsRepository = this.prismaRepository.openaiCreds; + } + + public readonly logger = new Logger('OpenaiController'); + + integrationEnabled = configService.get('OPENAI').ENABLED; + botRepository: any; + settingsRepository: any; + sessionRepository: any; + userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; + private client: OpenAI; + private credsRepository: any; + + // Credentials + public async createOpenaiCreds(instance: InstanceDto, data: OpenaiCredsDto) { + if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + if (!data.apiKey) throw new Error('API Key is required'); + if (!data.name) throw new Error('Name is required'); + + try { + const creds = await this.credsRepository.create({ + data: { + name: data.name, + apiKey: data.apiKey, + instanceId: instanceId, + }, + }); + + return creds; + } catch (error) { + this.logger.error(error); + throw new Error('Error creating openai creds'); + } + } + + public async findOpenaiCreds(instance: InstanceDto) { + if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const creds = await this.credsRepository.findMany({ + where: { + instanceId: instanceId, + }, + include: { + OpenaiAssistant: true, + }, + }); + + return creds; + } + + public async deleteCreds(instance: InstanceDto, openaiCredsId: string) { + if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const creds = await this.credsRepository.findFirst({ + where: { + id: openaiCredsId, + }, + }); + + if (!creds) { + throw new Error('Openai Creds not found'); + } + + if (creds.instanceId !== instanceId) { + throw new Error('Openai Creds not found'); + } + + try { + await this.credsRepository.delete({ + where: { + id: openaiCredsId, + }, + }); + + return { openaiCreds: { id: openaiCredsId } }; + } catch (error) { + this.logger.error(error); + throw new Error('Error deleting openai creds'); + } + } + + // Models + public async getModels(instance: InstanceDto) { + if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + if (!instanceId) throw new Error('Instance not found'); + + const defaultSettings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + include: { + OpenaiCreds: true, + }, + }); + + if (!defaultSettings) throw new Error('Settings not found'); + + const { apiKey } = defaultSettings.OpenaiCreds; + + try { + this.client = new OpenAI({ apiKey }); + + const models: any = await this.client.models.list(); + + return models?.body?.data; + } catch (error) { + this.logger.error(error); + throw new Error('Error fetching models'); + } + } + + // Bots + public async createBot(instance: InstanceDto, data: OpenaiDto) { + if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + if ( + !data.openaiCredsId || + !data.expire || + !data.keywordFinish || + !data.delayMessage || + !data.unknownMessage || + !data.listeningFromMe || + !data.stopBotFromMe || + !data.keepOpen || + !data.debounceTime || + !data.ignoreJids + ) { + const defaultSettingCheck = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (!data.openaiCredsId) data.openaiCredsId = defaultSettingCheck?.openaiCredsId || null; + if (!data.expire) data.expire = defaultSettingCheck?.expire || 0; + if (!data.keywordFinish) data.keywordFinish = defaultSettingCheck?.keywordFinish || ''; + if (!data.delayMessage) data.delayMessage = defaultSettingCheck?.delayMessage || 1000; + if (!data.unknownMessage) data.unknownMessage = defaultSettingCheck?.unknownMessage || ''; + if (!data.listeningFromMe) data.listeningFromMe = defaultSettingCheck?.listeningFromMe || false; + if (!data.stopBotFromMe) data.stopBotFromMe = defaultSettingCheck?.stopBotFromMe || false; + if (!data.keepOpen) data.keepOpen = defaultSettingCheck?.keepOpen || false; + if (!data.debounceTime) data.debounceTime = defaultSettingCheck?.debounceTime || 0; + if (!data.ignoreJids) data.ignoreJids = defaultSettingCheck?.ignoreJids || []; + + if (!data.openaiCredsId) { + throw new Error('Openai Creds Id is required'); + } + + if (!defaultSettingCheck) { + await this.settings(instance, { + openaiCredsId: data.openaiCredsId, + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + ignoreJids: data.ignoreJids, + }); + } + } + + const checkTriggerAll = await this.botRepository.findFirst({ + where: { + enabled: true, + triggerType: 'all', + instanceId: instanceId, + }, + }); + + if (checkTriggerAll && data.triggerType === 'all') { + throw new Error('You already have a openai with an "All" trigger, you cannot have more bots while it is active'); + } + + let whereDuplication: any = { + instanceId: instanceId, + }; + + if (data.botType === 'assistant') { + if (!data.assistantId) throw new Error('Assistant ID is required'); + + whereDuplication = { + ...whereDuplication, + assistantId: data.assistantId, + botType: data.botType, + }; + } else if (data.botType === 'chatCompletion') { + if (!data.model) throw new Error('Model is required'); + if (!data.maxTokens) throw new Error('Max tokens is required'); + + whereDuplication = { + ...whereDuplication, + model: data.model, + maxTokens: data.maxTokens, + botType: data.botType, + }; + } else { + throw new Error('Bot type is required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: whereDuplication, + }); + + if (checkDuplicate) { + throw new Error('Openai Bot already exists'); + } + + if (data.triggerType === 'keyword') { + if (!data.triggerOperator || !data.triggerValue) { + throw new Error('Trigger operator and value are required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + if (data.triggerType === 'advanced') { + if (!data.triggerValue) { + throw new Error('Trigger value is required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerValue: data.triggerValue, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + try { + const bot = await this.botRepository.create({ + data: { + enabled: data?.enabled, + description: data.description, + openaiCredsId: data.openaiCredsId, + botType: data.botType, + assistantId: data.assistantId, + functionUrl: data.functionUrl, + model: data.model, + systemMessages: data.systemMessages, + assistantMessages: data.assistantMessages, + userMessages: data.userMessages, + maxTokens: data.maxTokens, + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + instanceId: instanceId, + triggerType: data.triggerType, + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + ignoreJids: data.ignoreJids, + }, + }); + + return bot; + } catch (error) { + this.logger.error(error); + throw new Error('Error creating openai bot'); + } + } + + public async findBot(instance: InstanceDto) { + if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bots = await this.botRepository.findMany({ + where: { + instanceId, + }, + }); + + if (!bots.length) { + return null; + } + + return bots; + } + + public async fetchBot(instance: InstanceDto, botId: string) { + if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (!bot) { + throw new Error('Openai Bot not found'); + } + + if (bot.instanceId !== instanceId) { + throw new Error('Openai Bot not found'); + } + + return bot; + } + + public async updateBot(instance: InstanceDto, botId: string, data: OpenaiDto) { + if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (!bot) { + throw new Error('Openai Bot not found'); + } + + if (bot.instanceId !== instanceId) { + throw new Error('Openai Bot not found'); + } + + if (data.triggerType === 'all') { + const checkTriggerAll = await this.botRepository.findFirst({ + where: { + enabled: true, + triggerType: 'all', + id: { + not: botId, + }, + instanceId: instanceId, + }, + }); + + if (checkTriggerAll) { + throw new Error( + 'You already have a openai bot with an "All" trigger, you cannot have more bots while it is active', + ); + } + } + + let whereDuplication: any = { + id: { + not: botId, + }, + instanceId: instanceId, + }; + + if (data.botType === 'assistant') { + if (!data.assistantId) throw new Error('Assistant ID is required'); + + whereDuplication = { + ...whereDuplication, + assistantId: data.assistantId, + }; + } else if (data.botType === 'chatCompletion') { + if (!data.model) throw new Error('Model is required'); + if (!data.maxTokens) throw new Error('Max tokens is required'); + + whereDuplication = { + ...whereDuplication, + model: data.model, + maxTokens: data.maxTokens, + }; + } else { + throw new Error('Bot type is required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: whereDuplication, + }); + + if (checkDuplicate) { + throw new Error('Openai Bot already exists'); + } + + if (data.triggerType === 'keyword') { + if (!data.triggerOperator || !data.triggerValue) { + throw new Error('Trigger operator and value are required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + id: { not: botId }, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + if (data.triggerType === 'advanced') { + if (!data.triggerValue) { + throw new Error('Trigger value is required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerValue: data.triggerValue, + id: { not: botId }, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + try { + const bot = await this.botRepository.update({ + where: { + id: botId, + }, + data: { + enabled: data?.enabled, + description: data.description, + openaiCredsId: data.openaiCredsId, + botType: data.botType, + assistantId: data.assistantId, + functionUrl: data.functionUrl, + model: data.model, + systemMessages: data.systemMessages, + assistantMessages: data.assistantMessages, + userMessages: data.userMessages, + maxTokens: data.maxTokens, + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + instanceId: instanceId, + triggerType: data.triggerType, + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + ignoreJids: data.ignoreJids, + }, + }); + + return bot; + } catch (error) { + this.logger.error(error); + throw new Error('Error updating openai bot'); + } + } + + public async deleteBot(instance: InstanceDto, botId: string) { + if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (!bot) { + throw new Error('Openai bot not found'); + } + + if (bot.instanceId !== instanceId) { + throw new Error('Openai bot not found'); + } + try { + await this.sessionRepository.deleteMany({ + where: { + botId: botId, + }, + }); + + await this.botRepository.delete({ + where: { + id: botId, + }, + }); + + return { bot: { id: botId } }; + } catch (error) { + this.logger.error(error); + throw new Error('Error deleting openai bot'); + } + } + + // Settings + public async settings(instance: InstanceDto, data: any) { + if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (settings) { + const updateSettings = await this.settingsRepository.update({ + where: { + id: settings.id, + }, + data: { + openaiCredsId: data.openaiCredsId, + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + speechToText: data.speechToText, + openaiIdFallback: data.openaiIdFallback, + ignoreJids: data.ignoreJids, + }, + }); + + return { + openaiCredsId: updateSettings.openaiCredsId, + expire: updateSettings.expire, + keywordFinish: updateSettings.keywordFinish, + delayMessage: updateSettings.delayMessage, + unknownMessage: updateSettings.unknownMessage, + listeningFromMe: updateSettings.listeningFromMe, + stopBotFromMe: updateSettings.stopBotFromMe, + keepOpen: updateSettings.keepOpen, + debounceTime: updateSettings.debounceTime, + speechToText: updateSettings.speechToText, + openaiIdFallback: updateSettings.openaiIdFallback, + ignoreJids: updateSettings.ignoreJids, + }; + } + + const newSetttings = await this.settingsRepository.create({ + data: { + openaiCredsId: data.openaiCredsId, + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + openaiIdFallback: data.openaiIdFallback, + ignoreJids: data.ignoreJids, + speechToText: data.speechToText, + instanceId: instanceId, + }, + }); + + return { + openaiCredsId: newSetttings.openaiCredsId, + expire: newSetttings.expire, + keywordFinish: newSetttings.keywordFinish, + delayMessage: newSetttings.delayMessage, + unknownMessage: newSetttings.unknownMessage, + listeningFromMe: newSetttings.listeningFromMe, + stopBotFromMe: newSetttings.stopBotFromMe, + keepOpen: newSetttings.keepOpen, + debounceTime: newSetttings.debounceTime, + openaiIdFallback: newSetttings.openaiIdFallback, + ignoreJids: newSetttings.ignoreJids, + }; + } catch (error) { + this.logger.error(error); + throw new Error('Error setting default settings'); + } + } + + public async fetchSettings(instance: InstanceDto) { + if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); + + try { + const instanceId = ( + await this.prismaRepository.instance.findFirst({ + select: { id: true }, + where: { + name: instance.instanceName, + }, + }) + )?.id; + + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + include: { + Fallback: true, + }, + }); + + if (!settings) { + return { + openaiCredsId: null, + expire: 0, + keywordFinish: '', + delayMessage: 0, + unknownMessage: '', + listeningFromMe: false, + stopBotFromMe: false, + keepOpen: false, + ignoreJids: [], + openaiIdFallback: null, + speechToText: false, + fallback: null, + }; + } + + return { + openaiCredsId: settings.openaiCredsId, + expire: settings.expire, + keywordFinish: settings.keywordFinish, + delayMessage: settings.delayMessage, + unknownMessage: settings.unknownMessage, + listeningFromMe: settings.listeningFromMe, + stopBotFromMe: settings.stopBotFromMe, + keepOpen: settings.keepOpen, + ignoreJids: settings.ignoreJids, + openaiIdFallback: settings.openaiIdFallback, + speechToText: settings.speechToText, + fallback: settings.Fallback, + }; + } catch (error) { + this.logger.error(error); + throw new Error('Error fetching default settings'); + } + } + + // Sessions + public async changeStatus(instance: InstanceDto, data: any) { + if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const defaultSettingCheck = await this.settingsRepository.findFirst({ + where: { + instanceId, + }, + }); + + const remoteJid = data.remoteJid; + const status = data.status; + + if (status === 'delete') { + await this.sessionRepository.deleteMany({ + where: { + remoteJid: remoteJid, + botId: { not: null }, + }, + }); + + return { openai: { remoteJid: remoteJid, status: status } }; + } + + if (status === 'closed') { + if (defaultSettingCheck?.keepOpen) { + await this.sessionRepository.updateMany({ + where: { + remoteJid: remoteJid, + botId: { not: null }, + status: { not: 'closed' }, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.sessionRepository.deleteMany({ + where: { + remoteJid: remoteJid, + }, + }); + } + + return { openai: { ...instance, openai: { remoteJid: remoteJid, status: status } } }; + } else { + const session = await this.sessionRepository.updateMany({ + where: { + instanceId: instanceId, + remoteJid: remoteJid, + botId: { not: null }, + }, + data: { + status: status, + }, + }); + + const openaiData = { + remoteJid: remoteJid, + status: status, + session, + }; + + return { openai: { ...instance, openai: openaiData } }; + } + } catch (error) { + this.logger.error(error); + throw new Error('Error changing status'); + } + } + + public async fetchSessions(instance: InstanceDto, botId: string, remoteJid?: string) { + if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const openaiBot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (openaiBot && openaiBot.instanceId !== instanceId) { + throw new Error('Openai Bot not found'); + } + + return await this.sessionRepository.findMany({ + where: { + instanceId: instanceId, + remoteJid, + botId: openaiBot ? botId : { not: null }, + type: 'openai', + }, + }); + } catch (error) { + this.logger.error(error); + throw new Error('Error fetching sessions'); + } + } + + public async ignoreJid(instance: InstanceDto, data: IgnoreJidDto) { + if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (!settings) { + throw new Error('Settings not found'); + } + + let ignoreJids: any = settings?.ignoreJids || []; + + if (data.action === 'add') { + if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; + + ignoreJids.push(data.remoteJid); + } else { + ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); + } + + const updateSettings = await this.settingsRepository.update({ + where: { + id: settings.id, + }, + data: { + ignoreJids: ignoreJids, + }, + }); + + return { + ignoreJids: updateSettings.ignoreJids, + }; + } catch (error) { + this.logger.error(error); + throw new Error('Error setting default settings'); + } + } + + // Emit + public async emit({ instance, remoteJid, msg, pushName }: EmitData) { + if (!this.integrationEnabled) return; + + try { + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instance.instanceId, + }, + }); + + if (this.checkIgnoreJids(settings?.ignoreJids, remoteJid)) return; + + let session = await this.getSession(remoteJid, instance); + + const content = getConversationMessage(msg); + + const findBot = (await this.findBotTrigger( + this.botRepository, + this.settingsRepository, + content, + instance, + session, + )) as OpenaiBot; + + if (!findBot) return; + + let expire = findBot?.expire; + let keywordFinish = findBot?.keywordFinish; + let delayMessage = findBot?.delayMessage; + let unknownMessage = findBot?.unknownMessage; + let listeningFromMe = findBot?.listeningFromMe; + let stopBotFromMe = findBot?.stopBotFromMe; + let keepOpen = findBot?.keepOpen; + let debounceTime = findBot?.debounceTime; + let ignoreJids = findBot?.ignoreJids; + + if (!expire) expire = settings.expire; + if (!keywordFinish) keywordFinish = settings.keywordFinish; + if (!delayMessage) delayMessage = settings.delayMessage; + if (!unknownMessage) unknownMessage = settings.unknownMessage; + if (!listeningFromMe) listeningFromMe = settings.listeningFromMe; + if (!stopBotFromMe) stopBotFromMe = settings.stopBotFromMe; + if (!keepOpen) keepOpen = settings.keepOpen; + if (!debounceTime) debounceTime = settings.debounceTime; + if (!ignoreJids) ignoreJids = settings.ignoreJids; + + const key = msg.key as { + id: string; + remoteJid: string; + fromMe: boolean; + participant: string; + }; + + if (stopBotFromMe && key.fromMe && session) { + session = await this.sessionRepository.update({ + where: { + id: session.id, + }, + data: { + status: 'paused', + }, + }); + } + + if (!listeningFromMe && key.fromMe) { + return; + } + + if (session && !session.awaitUser) { + return; + } + + if (debounceTime && debounceTime > 0) { + this.processDebounce(this.userMessageDebounce, content, remoteJid, debounceTime, async (debouncedContent) => { + if (findBot.botType === 'assistant') { + await this.openaiService.processOpenaiAssistant( + this.waMonitor.waInstances[instance.instanceName], + remoteJid, + pushName, + key.fromMe, + findBot, + session, + { + ...settings, + expire, + keywordFinish, + delayMessage, + unknownMessage, + listeningFromMe, + stopBotFromMe, + keepOpen, + debounceTime, + ignoreJids, + }, + debouncedContent, + ); + } + + if (findBot.botType === 'chatCompletion') { + await this.openaiService.processOpenaiChatCompletion( + this.waMonitor.waInstances[instance.instanceName], + remoteJid, + pushName, + findBot, + session, + { + ...settings, + expire, + keywordFinish, + delayMessage, + unknownMessage, + listeningFromMe, + stopBotFromMe, + keepOpen, + debounceTime, + ignoreJids, + }, + debouncedContent, + ); + } + }); + } else { + if (findBot.botType === 'assistant') { + await this.openaiService.processOpenaiAssistant( + this.waMonitor.waInstances[instance.instanceName], + remoteJid, + pushName, + key.fromMe, + findBot, + session, + settings, + content, + ); + } + + if (findBot.botType === 'chatCompletion') { + await this.openaiService.processOpenaiChatCompletion( + this.waMonitor.waInstances[instance.instanceName], + remoteJid, + pushName, + findBot, + session, + settings, + content, + ); + } + } + + return; + } catch (error) { + this.logger.error(error); + return; + } + } +} diff --git a/src/api/integrations/openai/dto/openai.dto.ts b/src/api/integrations/chatbot/openai/dto/openai.dto.ts similarity index 83% rename from src/api/integrations/openai/dto/openai.dto.ts rename to src/api/integrations/chatbot/openai/dto/openai.dto.ts index ff562f5a..e3c996cd 100644 --- a/src/api/integrations/openai/dto/openai.dto.ts +++ b/src/api/integrations/chatbot/openai/dto/openai.dto.ts @@ -1,13 +1,5 @@ import { TriggerOperator, TriggerType } from '@prisma/client'; -export class Session { - remoteJid?: string; - sessionId?: string; - status?: string; - createdAt?: number; - updateAt?: number; -} - export class OpenaiCredsDto { name: string; apiKey: string; @@ -19,6 +11,7 @@ export class OpenaiDto { openaiCredsId: string; botType?: string; assistantId?: string; + functionUrl?: string; model?: string; systemMessages?: string[]; assistantMessages?: string[]; @@ -52,8 +45,3 @@ export class OpenaiSettingDto { ignoreJids?: any; speechToText?: boolean; } - -export class OpenaiIgnoreJidDto { - remoteJid?: string; - action?: string; -} diff --git a/src/api/integrations/openai/routes/openai.router.ts b/src/api/integrations/chatbot/openai/routes/openai.router.ts similarity index 83% rename from src/api/integrations/openai/routes/openai.router.ts rename to src/api/integrations/chatbot/openai/routes/openai.router.ts index d41d8775..ed55a4e7 100644 --- a/src/api/integrations/openai/routes/openai.router.ts +++ b/src/api/integrations/chatbot/openai/routes/openai.router.ts @@ -1,5 +1,9 @@ -import { RequestHandler, Router } from 'express'; - +import { RouterBroker } from '@api/abstract/abstract.router'; +import { IgnoreJidDto } from '@api/dto/chatbot.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { OpenaiCredsDto, OpenaiDto, OpenaiSettingDto } from '@api/integrations/chatbot/openai/dto/openai.dto'; +import { HttpStatus } from '@api/routes/index.router'; +import { openaiController } from '@api/server.module'; import { instanceSchema, openaiCredsSchema, @@ -7,12 +11,8 @@ import { openaiSchema, openaiSettingSchema, openaiStatusSchema, -} from '../../../../validate/validate.schema'; -import { RouterBroker } from '../../../abstract/abstract.router'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { HttpStatus } from '../../../routes/index.router'; -import { openaiController } from '../../../server.module'; -import { OpenaiCredsDto, OpenaiDto, OpenaiIgnoreJidDto, OpenaiSettingDto } from '../dto/openai.dto'; +} from '@validate/validate.schema'; +import { RequestHandler, Router } from 'express'; export class OpenaiRouter extends RouterBroker { constructor(...guards: RequestHandler[]) { @@ -53,7 +53,7 @@ export class OpenaiRouter extends RouterBroker { request: req, schema: openaiSchema, ClassRef: OpenaiDto, - execute: (instance, data) => openaiController.createOpenai(instance, data), + execute: (instance, data) => openaiController.createBot(instance, data), }); res.status(HttpStatus.CREATED).json(response); @@ -63,7 +63,7 @@ export class OpenaiRouter extends RouterBroker { request: req, schema: instanceSchema, ClassRef: InstanceDto, - execute: (instance) => openaiController.findOpenai(instance), + execute: (instance) => openaiController.findBot(instance), }); res.status(HttpStatus.OK).json(response); @@ -73,7 +73,7 @@ export class OpenaiRouter extends RouterBroker { request: req, schema: instanceSchema, ClassRef: InstanceDto, - execute: (instance) => openaiController.fetchOpenai(instance, req.params.openaiBotId), + execute: (instance) => openaiController.fetchBot(instance, req.params.openaiBotId), }); res.status(HttpStatus.OK).json(response); @@ -83,7 +83,7 @@ export class OpenaiRouter extends RouterBroker { request: req, schema: openaiSchema, ClassRef: OpenaiDto, - execute: (instance, data) => openaiController.updateOpenai(instance, req.params.openaiBotId, data), + execute: (instance, data) => openaiController.updateBot(instance, req.params.openaiBotId, data), }); res.status(HttpStatus.OK).json(response); @@ -93,7 +93,7 @@ export class OpenaiRouter extends RouterBroker { request: req, schema: instanceSchema, ClassRef: InstanceDto, - execute: (instance) => openaiController.deleteOpenai(instance, req.params.openaiBotId), + execute: (instance) => openaiController.deleteBot(instance, req.params.openaiBotId), }); res.status(HttpStatus.OK).json(response); @@ -139,10 +139,10 @@ export class OpenaiRouter extends RouterBroker { res.status(HttpStatus.OK).json(response); }) .post(this.routerPath('ignoreJid'), ...guards, async (req, res) => { - const response = await this.dataValidate({ + const response = await this.dataValidate({ request: req, schema: openaiIgnoreJidSchema, - ClassRef: OpenaiIgnoreJidDto, + ClassRef: IgnoreJidDto, execute: (instance, data) => openaiController.ignoreJid(instance, data), }); @@ -160,5 +160,5 @@ export class OpenaiRouter extends RouterBroker { }); } - public readonly router = Router(); + public readonly router: Router = Router(); } diff --git a/src/api/integrations/chatbot/openai/services/openai.service.ts b/src/api/integrations/chatbot/openai/services/openai.service.ts new file mode 100644 index 00000000..53f144c4 --- /dev/null +++ b/src/api/integrations/chatbot/openai/services/openai.service.ts @@ -0,0 +1,777 @@ +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { InstanceDto } from '@api/dto/instance.dto'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Integration } from '@api/types/wa.types'; +import { ConfigService, Language } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { IntegrationSession, OpenaiBot, OpenaiCreds, OpenaiSetting } from '@prisma/client'; +import { sendTelemetry } from '@utils/sendTelemetry'; +import axios from 'axios'; +import { downloadMediaMessage } from 'baileys'; +import FormData from 'form-data'; +import OpenAI from 'openai'; +import P from 'pino'; + +export class OpenaiService { + constructor( + private readonly waMonitor: WAMonitoringService, + private readonly configService: ConfigService, + private readonly prismaRepository: PrismaRepository, + ) {} + + private client: OpenAI; + + private readonly logger = new Logger('OpenaiService'); + + private async sendMessageToBot(instance: any, openaiBot: OpenaiBot, remoteJid: string, content: string) { + const systemMessages: any = openaiBot.systemMessages; + + const messagesSystem: any[] = systemMessages.map((message) => { + return { + role: 'system', + content: message, + }; + }); + + const assistantMessages: any = openaiBot.assistantMessages; + + const messagesAssistant: any[] = assistantMessages.map((message) => { + return { + role: 'assistant', + content: message, + }; + }); + + const userMessages: any = openaiBot.userMessages; + + const messagesUser: any[] = userMessages.map((message) => { + return { + role: 'user', + content: message, + }; + }); + + const messageData: any = { + role: 'user', + content: [{ type: 'text', text: content }], + }; + + if (this.isImageMessage(content)) { + const contentSplit = content.split('|'); + + const url = contentSplit[1].split('?')[0]; + + messageData.content = [ + { type: 'text', text: contentSplit[2] || content }, + { + type: 'image_url', + image_url: { + url: url, + }, + }, + ]; + } + + const messages: any[] = [...messagesSystem, ...messagesAssistant, ...messagesUser, messageData]; + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.presenceSubscribe(remoteJid); + await instance.client.sendPresenceUpdate('composing', remoteJid); + } + + const completions = await this.client.chat.completions.create({ + model: openaiBot.model, + messages: messages, + max_tokens: openaiBot.maxTokens, + }); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) + await instance.client.sendPresenceUpdate('paused', remoteJid); + + const message = completions.choices[0].message.content; + + return message; + } + + private async sendMessageToAssistant( + instance: any, + openaiBot: OpenaiBot, + remoteJid: string, + pushName: string, + fromMe: boolean, + content: string, + threadId: string, + ) { + const messageData: any = { + role: fromMe ? 'assistant' : 'user', + content: [{ type: 'text', text: content }], + }; + + if (this.isImageMessage(content)) { + const contentSplit = content.split('|'); + + const url = contentSplit[1].split('?')[0]; + + messageData.content = [ + { type: 'text', text: contentSplit[2] || content }, + { + type: 'image_url', + image_url: { + url: url, + }, + }, + ]; + } + + await this.client.beta.threads.messages.create(threadId, messageData); + + if (fromMe) { + sendTelemetry('/message/sendText'); + return; + } + + const runAssistant = await this.client.beta.threads.runs.create(threadId, { + assistant_id: openaiBot.assistantId, + }); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.presenceSubscribe(remoteJid); + await instance.client.sendPresenceUpdate('composing', remoteJid); + } + + const response = await this.getAIResponse(threadId, runAssistant.id, openaiBot.functionUrl, remoteJid, pushName); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) + await instance.client.sendPresenceUpdate('paused', remoteJid); + + const message = response?.data[0].content[0].text.value; + + return message; + } + + private async sendMessageWhatsapp( + instance: any, + session: IntegrationSession, + remoteJid: string, + settings: OpenaiSetting, + message: string, + ) { + const linkRegex = /(!?)\[(.*?)\]\((.*?)\)/g; + + let textBuffer = ''; + let lastIndex = 0; + + let match: RegExpExecArray | null; + + const getMediaType = (url: string): string | null => { + const extension = url.split('.').pop()?.toLowerCase(); + const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']; + const audioExtensions = ['mp3', 'wav', 'aac', 'ogg']; + const videoExtensions = ['mp4', 'avi', 'mkv', 'mov']; + const documentExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']; + + if (imageExtensions.includes(extension || '')) return 'image'; + if (audioExtensions.includes(extension || '')) return 'audio'; + if (videoExtensions.includes(extension || '')) return 'video'; + if (documentExtensions.includes(extension || '')) return 'document'; + return null; + }; + + while ((match = linkRegex.exec(message)) !== null) { + const [fullMatch, exclMark, altText, url] = match; + const mediaType = getMediaType(url); + + const beforeText = message.slice(lastIndex, match.index); + if (beforeText) { + textBuffer += beforeText; + } + + if (mediaType) { + if (textBuffer.trim()) { + await instance.textMessage( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + text: textBuffer.trim(), + }, + false, + ); + textBuffer = ''; + } + + if (mediaType === 'audio') { + await instance.audioWhatsapp({ + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + audio: url, + caption: altText, + }); + } else { + await instance.mediaMessage( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + mediatype: mediaType, + media: url, + caption: altText, + }, + false, + ); + } + } else { + textBuffer += `[${altText}](${url})`; + } + + lastIndex = linkRegex.lastIndex; + } + + if (lastIndex < message.length) { + const remainingText = message.slice(lastIndex); + if (remainingText.trim()) { + textBuffer += remainingText; + } + } + + if (textBuffer.trim()) { + await instance.textMessage( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + text: textBuffer.trim(), + }, + false, + ); + } + + sendTelemetry('/message/sendText'); + + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: true, + }, + }); + } + + public async createAssistantNewSession(instance: InstanceDto, data: any) { + if (data.remoteJid === 'status@broadcast') return; + + const creds = await this.prismaRepository.openaiCreds.findFirst({ + where: { + id: data.openaiCredsId, + }, + }); + + if (!creds) throw new Error('Openai Creds not found'); + + try { + this.client = new OpenAI({ + apiKey: creds.apiKey, + }); + + const threadId = (await this.client.beta.threads.create({})).id; + + let session = null; + if (threadId) { + session = await this.prismaRepository.integrationSession.create({ + data: { + remoteJid: data.remoteJid, + pushName: data.pushName, + sessionId: threadId, + status: 'opened', + awaitUser: false, + botId: data.botId, + instanceId: instance.instanceId, + type: 'openai', + }, + }); + } + return { session }; + } catch (error) { + this.logger.error(error); + return; + } + } + + private async initAssistantNewSession( + instance: any, + remoteJid: string, + pushName: string, + fromMe: boolean, + openaiBot: OpenaiBot, + settings: OpenaiSetting, + session: IntegrationSession, + content: string, + ) { + const data = await this.createAssistantNewSession(instance, { + remoteJid, + pushName, + openaiCredsId: openaiBot.openaiCredsId, + botId: openaiBot.id, + }); + + if (data.session) { + session = data.session; + } + + const message = await this.sendMessageToAssistant( + instance, + openaiBot, + remoteJid, + pushName, + fromMe, + content, + session.sessionId, + ); + + await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message); + + return; + } + + private isJSON(str: string): boolean { + try { + JSON.parse(str); + return true; + } catch (e) { + return false; + } + } + + private async getAIResponse( + threadId: string, + runId: string, + functionUrl: string, + remoteJid: string, + pushName: string, + ) { + const getRun = await this.client.beta.threads.runs.retrieve(threadId, runId); + let toolCalls; + switch (getRun.status) { + case 'requires_action': + toolCalls = getRun?.required_action?.submit_tool_outputs?.tool_calls; + + if (toolCalls) { + for (const toolCall of toolCalls) { + const id = toolCall.id; + const functionName = toolCall?.function?.name; + const functionArgument = this.isJSON(toolCall?.function?.arguments) + ? JSON.parse(toolCall?.function?.arguments) + : toolCall?.function?.arguments; + + let output = null; + + try { + const { data } = await axios.post(functionUrl, { + name: functionName, + arguments: { ...functionArgument, remoteJid, pushName }, + }); + + output = JSON.stringify(data) + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/\t/g, '\\t'); + } catch (error) { + output = JSON.stringify(error) + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/\t/g, '\\t'); + } + + await this.client.beta.threads.runs.submitToolOutputs(threadId, runId, { + tool_outputs: [ + { + tool_call_id: id, + output, + }, + ], + }); + } + } + + return this.getAIResponse(threadId, runId, functionUrl, remoteJid, pushName); + case 'queued': + await new Promise((resolve) => setTimeout(resolve, 1000)); + return this.getAIResponse(threadId, runId, functionUrl, remoteJid, pushName); + case 'in_progress': + await new Promise((resolve) => setTimeout(resolve, 1000)); + return this.getAIResponse(threadId, runId, functionUrl, remoteJid, pushName); + case 'completed': + return await this.client.beta.threads.messages.list(threadId, { + run_id: runId, + limit: 1, + }); + } + } + + private isImageMessage(content: string) { + return content.includes('imageMessage'); + } + + public async processOpenaiAssistant( + instance: any, + remoteJid: string, + pushName: string, + fromMe: boolean, + openaiBot: OpenaiBot, + session: IntegrationSession, + settings: OpenaiSetting, + content: string, + ) { + if (session && session.status === 'closed') { + return; + } + + if (session && settings.expire && settings.expire > 0) { + const now = Date.now(); + + const sessionUpdatedAt = new Date(session.updatedAt).getTime(); + + const diff = now - sessionUpdatedAt; + + const diffInMinutes = Math.floor(diff / 1000 / 60); + + if (diffInMinutes > settings.expire) { + if (settings.keepOpen) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: openaiBot.id, + remoteJid: remoteJid, + }, + }); + } + + await this.initAssistantNewSession( + instance, + remoteJid, + pushName, + fromMe, + openaiBot, + settings, + session, + content, + ); + return; + } + } + + if (!session) { + await this.initAssistantNewSession(instance, remoteJid, pushName, fromMe, openaiBot, settings, session, content); + return; + } + + if (session.status !== 'paused') + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: false, + }, + }); + + if (!content) { + if (settings.unknownMessage) { + this.waMonitor.waInstances[instance.instanceName].textMessage( + { + number: remoteJid.split('@')[0], + delay: settings.delayMessage || 1000, + text: settings.unknownMessage, + }, + false, + ); + + sendTelemetry('/message/sendText'); + } + return; + } + + if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) { + if (settings.keepOpen) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: openaiBot.id, + remoteJid: remoteJid, + }, + }); + } + return; + } + + const creds = await this.prismaRepository.openaiCreds.findFirst({ + where: { + id: openaiBot.openaiCredsId, + }, + }); + + if (!creds) throw new Error('Openai Creds not found'); + + this.client = new OpenAI({ + apiKey: creds.apiKey, + }); + + const threadId = session.sessionId; + + const message = await this.sendMessageToAssistant( + instance, + openaiBot, + remoteJid, + pushName, + fromMe, + content, + threadId, + ); + + await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message); + + return; + } + + public async createChatCompletionNewSession(instance: InstanceDto, data: any) { + if (data.remoteJid === 'status@broadcast') return; + + const id = Math.floor(Math.random() * 10000000000).toString(); + + const creds = await this.prismaRepository.openaiCreds.findFirst({ + where: { + id: data.openaiCredsId, + }, + }); + + if (!creds) throw new Error('Openai Creds not found'); + + try { + const session = await this.prismaRepository.integrationSession.create({ + data: { + remoteJid: data.remoteJid, + pushName: data.pushName, + sessionId: id, + status: 'opened', + awaitUser: false, + botId: data.botId, + instanceId: instance.instanceId, + type: 'openai', + }, + }); + + return { session, creds }; + } catch (error) { + this.logger.error(error); + return; + } + } + + private async initChatCompletionNewSession( + instance: any, + remoteJid: string, + pushName: string, + openaiBot: OpenaiBot, + settings: OpenaiSetting, + session: IntegrationSession, + content: string, + ) { + const data = await this.createChatCompletionNewSession(instance, { + remoteJid, + pushName, + openaiCredsId: openaiBot.openaiCredsId, + botId: openaiBot.id, + }); + + session = data.session; + + const creds = data.creds; + + this.client = new OpenAI({ + apiKey: creds.apiKey, + }); + + const message = await this.sendMessageToBot(instance, openaiBot, remoteJid, content); + + await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message); + + return; + } + + public async processOpenaiChatCompletion( + instance: any, + remoteJid: string, + pushName: string, + openaiBot: OpenaiBot, + session: IntegrationSession, + settings: OpenaiSetting, + content: string, + ) { + if (session && session.status !== 'opened') { + return; + } + + if (session && settings.expire && settings.expire > 0) { + const now = Date.now(); + + const sessionUpdatedAt = new Date(session.updatedAt).getTime(); + + const diff = now - sessionUpdatedAt; + + const diffInMinutes = Math.floor(diff / 1000 / 60); + + if (diffInMinutes > settings.expire) { + if (settings.keepOpen) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: openaiBot.id, + remoteJid: remoteJid, + }, + }); + } + + await this.initChatCompletionNewSession(instance, remoteJid, pushName, openaiBot, settings, session, content); + return; + } + } + + if (!session) { + await this.initChatCompletionNewSession(instance, remoteJid, pushName, openaiBot, settings, session, content); + return; + } + + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: false, + }, + }); + + if (!content) { + if (settings.unknownMessage) { + this.waMonitor.waInstances[instance.instanceName].textMessage( + { + number: remoteJid.split('@')[0], + delay: settings.delayMessage || 1000, + text: settings.unknownMessage, + }, + false, + ); + + sendTelemetry('/message/sendText'); + } + return; + } + + if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) { + if (settings.keepOpen) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: openaiBot.id, + remoteJid: remoteJid, + }, + }); + } + return; + } + + const creds = await this.prismaRepository.openaiCreds.findFirst({ + where: { + id: openaiBot.openaiCredsId, + }, + }); + + if (!creds) throw new Error('Openai Creds not found'); + + this.client = new OpenAI({ + apiKey: creds.apiKey, + }); + + const message = await this.sendMessageToBot(instance, openaiBot, remoteJid, content); + + await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message); + + return; + } + + public async speechToText(creds: OpenaiCreds, msg: any, updateMediaMessage: any) { + let audio; + + if (msg?.message?.mediaUrl) { + audio = await axios.get(msg.message.mediaUrl, { responseType: 'arraybuffer' }).then((response) => { + return Buffer.from(response.data, 'binary'); + }); + } else { + audio = await downloadMediaMessage( + { key: msg.key, message: msg?.message }, + 'buffer', + {}, + { + logger: P({ level: 'error' }) as any, + reuploadRequest: updateMediaMessage, + }, + ); + } + + const lang = this.configService.get('LANGUAGE').includes('pt') + ? 'pt' + : this.configService.get('LANGUAGE'); + + const formData = new FormData(); + + formData.append('file', audio, 'audio.ogg'); + formData.append('model', 'whisper-1'); + formData.append('language', lang); + + const response = await axios.post('https://api.openai.com/v1/audio/transcriptions', formData, { + headers: { + 'Content-Type': 'multipart/form-data', + Authorization: `Bearer ${creds.apiKey}`, + }, + }); + + return response?.data?.text; + } +} diff --git a/src/api/integrations/openai/validate/openai.schema.ts b/src/api/integrations/chatbot/openai/validate/openai.schema.ts similarity index 98% rename from src/api/integrations/openai/validate/openai.schema.ts rename to src/api/integrations/chatbot/openai/validate/openai.schema.ts index d7b63315..a4ccfe56 100644 --- a/src/api/integrations/openai/validate/openai.schema.ts +++ b/src/api/integrations/chatbot/openai/validate/openai.schema.ts @@ -29,12 +29,13 @@ export const openaiSchema: JSONSchema7 = { openaiCredsId: { type: 'string' }, botType: { type: 'string', enum: ['assistant', 'chatCompletion'] }, assistantId: { type: 'string' }, + functionUrl: { type: 'string' }, model: { type: 'string' }, systemMessages: { type: 'array', items: { type: 'string' } }, assistantMessages: { type: 'array', items: { type: 'string' } }, userMessages: { type: 'array', items: { type: 'string' } }, maxTokens: { type: 'integer' }, - triggerType: { type: 'string', enum: ['all', 'keyword', 'none'] }, + triggerType: { type: 'string', enum: ['all', 'keyword', 'none', 'advanced'] }, triggerOperator: { type: 'string', enum: ['equals', 'contains', 'startsWith', 'endsWith', 'regex'] }, triggerValue: { type: 'string' }, expire: { type: 'integer' }, diff --git a/src/api/integrations/chatbot/typebot/controllers/typebot.controller.ts b/src/api/integrations/chatbot/typebot/controllers/typebot.controller.ts new file mode 100644 index 00000000..a6867e59 --- /dev/null +++ b/src/api/integrations/chatbot/typebot/controllers/typebot.controller.ts @@ -0,0 +1,1094 @@ +import { IgnoreJidDto } from '@api/dto/chatbot.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { TypebotDto } from '@api/integrations/chatbot/typebot/dto/typebot.dto'; +import { TypebotService } from '@api/integrations/chatbot/typebot/services/typebot.service'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Events } from '@api/types/wa.types'; +import { Auth, configService, HttpServer, Typebot } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { BadRequestException } from '@exceptions'; +import { Typebot as TypebotModel } from '@prisma/client'; +import { getConversationMessage } from '@utils/getConversationMessage'; +import axios from 'axios'; + +import { ChatbotController, ChatbotControllerInterface } from '../../chatbot.controller'; + +export class TypebotController extends ChatbotController implements ChatbotControllerInterface { + constructor( + private readonly typebotService: TypebotService, + prismaRepository: PrismaRepository, + waMonitor: WAMonitoringService, + ) { + super(prismaRepository, waMonitor); + + this.botRepository = this.prismaRepository.typebot; + this.settingsRepository = this.prismaRepository.typebotSetting; + this.sessionRepository = this.prismaRepository.integrationSession; + } + + public readonly logger = new Logger('TypebotController'); + + integrationEnabled = configService.get('TYPEBOT').ENABLED; + botRepository: any; + settingsRepository: any; + sessionRepository: any; + userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; + + // Bots + public async createBot(instance: InstanceDto, data: TypebotDto) { + if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + if ( + !data.expire || + !data.keywordFinish || + !data.delayMessage || + !data.unknownMessage || + !data.listeningFromMe || + !data.stopBotFromMe || + !data.keepOpen || + !data.debounceTime || + !data.ignoreJids + ) { + const defaultSettingCheck = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (!data.expire) data.expire = defaultSettingCheck?.expire || 0; + if (!data.keywordFinish) data.keywordFinish = defaultSettingCheck?.keywordFinish || '#SAIR'; + if (!data.delayMessage) data.delayMessage = defaultSettingCheck?.delayMessage || 1000; + if (!data.unknownMessage) data.unknownMessage = defaultSettingCheck?.unknownMessage || 'Desculpe, não entendi'; + if (!data.listeningFromMe) data.listeningFromMe = defaultSettingCheck?.listeningFromMe || false; + if (!data.stopBotFromMe) data.stopBotFromMe = defaultSettingCheck?.stopBotFromMe || false; + if (!data.keepOpen) data.keepOpen = defaultSettingCheck?.keepOpen || false; + if (!data.debounceTime) data.debounceTime = defaultSettingCheck?.debounceTime || 0; + if (!data.ignoreJids) data.ignoreJids = defaultSettingCheck?.ignoreJids || []; + + if (!defaultSettingCheck) { + await this.settings(instance, { + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + ignoreJids: data.ignoreJids, + }); + } + } + + const checkTriggerAll = await this.botRepository.findFirst({ + where: { + enabled: true, + triggerType: 'all', + instanceId: instanceId, + }, + }); + + if (checkTriggerAll && data.triggerType === 'all') { + throw new Error('You already have a typebot with an "All" trigger, you cannot have more bots while it is active'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + url: data.url, + typebot: data.typebot, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Typebot already exists'); + } + + if (data.triggerType === 'keyword') { + if (!data.triggerOperator || !data.triggerValue) { + throw new Error('Trigger operator and value are required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + if (data.triggerType === 'advanced') { + if (!data.triggerValue) { + throw new Error('Trigger value is required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerValue: data.triggerValue, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + try { + const bot = await this.botRepository.create({ + data: { + enabled: data?.enabled, + description: data.description, + url: data.url, + typebot: data.typebot, + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + instanceId: instanceId, + triggerType: data.triggerType, + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + ignoreJids: data.ignoreJids, + }, + }); + + return bot; + } catch (error) { + this.logger.error(error); + throw new Error('Error creating typebot'); + } + } + + public async findBot(instance: InstanceDto) { + if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bots = await this.botRepository.findMany({ + where: { + instanceId: instanceId, + }, + }); + + if (!bots.length) { + return null; + } + + return bots; + } + + public async fetchBot(instance: InstanceDto, botId: string) { + if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (!bot) { + throw new Error('Typebot not found'); + } + + if (bot.instanceId !== instanceId) { + throw new Error('Typebot not found'); + } + + return bot; + } + + public async updateBot(instance: InstanceDto, botId: string, data: TypebotDto) { + if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const typebot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (!typebot) { + throw new Error('Typebot not found'); + } + + if (typebot.instanceId !== instanceId) { + throw new Error('Typebot not found'); + } + + if (data.triggerType === 'all') { + const checkTriggerAll = await this.botRepository.findFirst({ + where: { + enabled: true, + triggerType: 'all', + id: { + not: botId, + }, + instanceId: instanceId, + }, + }); + + if (checkTriggerAll) { + throw new Error( + 'You already have a typebot with an "All" trigger, you cannot have more bots while it is active', + ); + } + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + url: data.url, + typebot: data.typebot, + id: { + not: botId, + }, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Typebot already exists'); + } + + if (data.triggerType === 'keyword') { + if (!data.triggerOperator || !data.triggerValue) { + throw new Error('Trigger operator and value are required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + id: { + not: botId, + }, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + if (data.triggerType === 'advanced') { + if (!data.triggerValue) { + throw new Error('Trigger value is required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerValue: data.triggerValue, + id: { not: botId }, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + try { + const bot = await this.botRepository.update({ + where: { + id: botId, + }, + data: { + enabled: data?.enabled, + description: data.description, + url: data.url, + typebot: data.typebot, + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + triggerType: data.triggerType, + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + ignoreJids: data.ignoreJids, + }, + }); + + return bot; + } catch (error) { + this.logger.error(error); + throw new Error('Error updating typebot'); + } + } + + public async deleteBot(instance: InstanceDto, botId: string) { + if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const typebot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (!typebot) { + throw new Error('Typebot not found'); + } + + if (typebot.instanceId !== instanceId) { + throw new Error('Typebot not found'); + } + try { + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: botId, + }, + }); + + await this.botRepository.delete({ + where: { + id: botId, + }, + }); + + return { typebot: { id: botId } }; + } catch (error) { + this.logger.error(error); + throw new Error('Error deleting typebot'); + } + } + + // Settings + public async settings(instance: InstanceDto, data: any) { + if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (settings) { + const updateSettings = await this.settingsRepository.update({ + where: { + id: settings.id, + }, + data: { + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + typebotIdFallback: data.typebotIdFallback, + ignoreJids: data.ignoreJids, + }, + }); + + return { + expire: updateSettings.expire, + keywordFinish: updateSettings.keywordFinish, + delayMessage: updateSettings.delayMessage, + unknownMessage: updateSettings.unknownMessage, + listeningFromMe: updateSettings.listeningFromMe, + stopBotFromMe: updateSettings.stopBotFromMe, + keepOpen: updateSettings.keepOpen, + debounceTime: updateSettings.debounceTime, + typebotIdFallback: updateSettings.typebotIdFallback, + ignoreJids: updateSettings.ignoreJids, + }; + } + + const newSetttings = await this.settingsRepository.create({ + data: { + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + typebotIdFallback: data.typebotIdFallback, + ignoreJids: data.ignoreJids, + instanceId: instanceId, + }, + }); + + return { + expire: newSetttings.expire, + keywordFinish: newSetttings.keywordFinish, + delayMessage: newSetttings.delayMessage, + unknownMessage: newSetttings.unknownMessage, + listeningFromMe: newSetttings.listeningFromMe, + stopBotFromMe: newSetttings.stopBotFromMe, + keepOpen: newSetttings.keepOpen, + debounceTime: newSetttings.debounceTime, + typebotIdFallback: newSetttings.typebotIdFallback, + ignoreJids: newSetttings.ignoreJids, + }; + } catch (error) { + this.logger.error(error); + throw new Error('Error setting default settings'); + } + } + + public async fetchSettings(instance: InstanceDto) { + if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + include: { + Fallback: true, + }, + }); + + if (!settings) { + return { + expire: 0, + keywordFinish: '', + delayMessage: 0, + unknownMessage: '', + listeningFromMe: false, + stopBotFromMe: false, + keepOpen: false, + ignoreJids: [], + typebotIdFallback: null, + fallback: null, + }; + } + + return { + expire: settings.expire, + keywordFinish: settings.keywordFinish, + delayMessage: settings.delayMessage, + unknownMessage: settings.unknownMessage, + listeningFromMe: settings.listeningFromMe, + stopBotFromMe: settings.stopBotFromMe, + keepOpen: settings.keepOpen, + ignoreJids: settings.ignoreJids, + typebotIdFallback: settings.typebotIdFallback, + fallback: settings.Fallback, + }; + } catch (error) { + this.logger.error(error); + throw new Error('Error fetching default settings'); + } + } + + // Sessions + public async startBot(instance: InstanceDto, data: any) { + if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); + + if (data.remoteJid === 'status@broadcast') return; + + const instanceData = await this.prismaRepository.instance.findFirst({ + where: { + name: instance.instanceName, + }, + }); + + if (!instanceData) throw new Error('Instance not found'); + + const remoteJid = data.remoteJid; + const url = data.url; + const typebot = data.typebot; + const startSession = data.startSession; + const variables = data.variables; + let expire = data?.typebot?.expire; + let keywordFinish = data?.typebot?.keywordFinish; + let delayMessage = data?.typebot?.delayMessage; + let unknownMessage = data?.typebot?.unknownMessage; + let listeningFromMe = data?.typebot?.listeningFromMe; + let stopBotFromMe = data?.typebot?.stopBotFromMe; + let keepOpen = data?.typebot?.keepOpen; + + const defaultSettingCheck = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceData.id, + }, + }); + + if (this.checkIgnoreJids(defaultSettingCheck?.ignoreJids, remoteJid)) throw new Error('Jid not allowed'); + + if ( + !expire || + !keywordFinish || + !delayMessage || + !unknownMessage || + !listeningFromMe || + !stopBotFromMe || + !keepOpen + ) { + if (!expire) expire = defaultSettingCheck?.expire || 0; + if (!keywordFinish) keywordFinish = defaultSettingCheck?.keywordFinish || '#SAIR'; + if (!delayMessage) delayMessage = defaultSettingCheck?.delayMessage || 1000; + if (!unknownMessage) unknownMessage = defaultSettingCheck?.unknownMessage || 'Desculpe, não entendi'; + if (!listeningFromMe) listeningFromMe = defaultSettingCheck?.listeningFromMe || false; + if (!stopBotFromMe) stopBotFromMe = defaultSettingCheck?.stopBotFromMe || false; + if (!keepOpen) keepOpen = defaultSettingCheck?.keepOpen || false; + + if (!defaultSettingCheck) { + await this.settings(instance, { + expire: expire, + keywordFinish: keywordFinish, + delayMessage: delayMessage, + unknownMessage: unknownMessage, + listeningFromMe: listeningFromMe, + stopBotFromMe: stopBotFromMe, + keepOpen: keepOpen, + }); + } + } + + const prefilledVariables = { + remoteJid: remoteJid, + instanceName: instance.instanceName, + serverUrl: configService.get('SERVER').URL, + apiKey: configService.get('AUTHENTICATION').API_KEY.KEY, + ownerJid: instanceData.number, + }; + + if (variables?.length) { + variables.forEach((variable: { name: string | number; value: string }) => { + prefilledVariables[variable.name] = variable.value; + }); + } + + if (startSession) { + let findBot: any = await this.botRepository.findFirst({ + where: { + url: url, + typebot: typebot, + instanceId: instanceData.id, + }, + }); + + if (!findBot) { + findBot = await this.botRepository.upsert({ + where: { + url_typebot_instanceId: { + url: url, + typebot: typebot, + instanceId: instanceData.id, + }, + }, + update: { + enabled: true, + }, + create: { + enabled: true, + url: url, + typebot: typebot, + expire: expire, + triggerType: 'none', + keywordFinish: keywordFinish, + delayMessage: delayMessage, + unknownMessage: unknownMessage, + listeningFromMe: listeningFromMe, + stopBotFromMe: stopBotFromMe, + keepOpen: keepOpen, + instanceId: instanceData.id, + }, + }); + } + + await this.prismaRepository.integrationSession.deleteMany({ + where: { + remoteJid: remoteJid, + instanceId: instanceData.id, + botId: { not: null }, + }, + }); + + const response = await this.typebotService.createNewSession(instanceData, { + enabled: true, + url: url, + typebot: typebot, + remoteJid: remoteJid, + expire: expire, + keywordFinish: keywordFinish, + delayMessage: delayMessage, + unknownMessage: unknownMessage, + listeningFromMe: listeningFromMe, + stopBotFromMe: stopBotFromMe, + keepOpen: keepOpen, + prefilledVariables: prefilledVariables, + typebotId: findBot.id, + }); + + if (response.sessionId) { + await this.typebotService.sendWAMessage( + instanceData, + response.session, + { + expire: expire, + keywordFinish: keywordFinish, + delayMessage: delayMessage, + unknownMessage: unknownMessage, + listeningFromMe: listeningFromMe, + stopBotFromMe: stopBotFromMe, + keepOpen: keepOpen, + }, + remoteJid, + response.messages, + response.input, + response.clientSideActions, + ); + + this.waMonitor.waInstances[instance.instanceName].sendDataWebhook(Events.TYPEBOT_START, { + remoteJid: remoteJid, + url: url, + typebot: typebot, + prefilledVariables: prefilledVariables, + sessionId: `${response.sessionId}`, + }); + } else { + throw new Error('Session ID not found in response'); + } + } else { + const id = Math.floor(Math.random() * 10000000000).toString(); + + try { + const version = configService.get('TYPEBOT').API_VERSION; + let url: string; + let reqData: {}; + if (version === 'latest') { + url = `${data.url}/api/v1/typebots/${data.typebot}/startChat`; + + reqData = { + prefilledVariables: prefilledVariables, + }; + } else { + url = `${data.url}/api/v1/sendMessage`; + + reqData = { + startParams: { + publicId: data.typebot, + prefilledVariables: prefilledVariables, + }, + }; + } + const request = await axios.post(url, reqData); + + await this.typebotService.sendWAMessage( + instanceData, + null, + { + expire: expire, + keywordFinish: keywordFinish, + delayMessage: delayMessage, + unknownMessage: unknownMessage, + listeningFromMe: listeningFromMe, + stopBotFromMe: stopBotFromMe, + keepOpen: keepOpen, + }, + remoteJid, + request.data.messages, + request.data.input, + request.data.clientSideActions, + ); + + this.waMonitor.waInstances[instance.instanceName].sendDataWebhook(Events.TYPEBOT_START, { + remoteJid: remoteJid, + url: url, + typebot: typebot, + variables: variables, + sessionId: id, + }); + } catch (error) { + this.logger.error(error); + return; + } + } + + return { + typebot: { + ...instance, + typebot: { + url: url, + remoteJid: remoteJid, + typebot: typebot, + prefilledVariables: prefilledVariables, + }, + }, + }; + } + + public async changeStatus(instance: InstanceDto, data: any) { + if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const remoteJid = data.remoteJid; + const status = data.status; + + const defaultSettingCheck = await this.settingsRepository.findFirst({ + where: { + instanceId, + }, + }); + + if (status === 'delete') { + await this.sessionRepository.deleteMany({ + where: { + remoteJid: remoteJid, + instanceId: instanceId, + botId: { not: null }, + }, + }); + + return { typebot: { ...instance, typebot: { remoteJid: remoteJid, status: status } } }; + } + + if (status === 'closed') { + if (defaultSettingCheck?.keepOpen) { + await this.sessionRepository.updateMany({ + where: { + instanceId: instanceId, + remoteJid: remoteJid, + botId: { not: null }, + }, + data: { + status: status, + }, + }); + } else { + await this.sessionRepository.deleteMany({ + where: { + remoteJid: remoteJid, + instanceId: instanceId, + botId: { not: null }, + }, + }); + } + + return { typebot: { ...instance, typebot: { remoteJid: remoteJid, status: status } } }; + } + + const session = await this.sessionRepository.updateMany({ + where: { + instanceId: instanceId, + remoteJid: remoteJid, + botId: { not: null }, + }, + data: { + status: status, + }, + }); + + const typebotData = { + remoteJid: remoteJid, + status: status, + session, + }; + + this.waMonitor.waInstances[instance.instanceName].sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData); + + return { typebot: { ...instance, typebot: typebotData } }; + } catch (error) { + this.logger.error(error); + throw new Error('Error changing status'); + } + } + + public async fetchSessions(instance: InstanceDto, botId: string, remoteJid?: string) { + if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const typebot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (typebot && typebot.instanceId !== instanceId) { + throw new Error('Typebot not found'); + } + + return await this.sessionRepository.findMany({ + where: { + instanceId: instanceId, + remoteJid, + botId: botId ?? { not: null }, + type: 'typebot', + }, + }); + } catch (error) { + this.logger.error(error); + throw new Error('Error fetching sessions'); + } + } + + public async ignoreJid(instance: InstanceDto, data: IgnoreJidDto) { + if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (!settings) { + throw new Error('Settings not found'); + } + + let ignoreJids: any = settings?.ignoreJids || []; + + if (data.action === 'add') { + if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; + + ignoreJids.push(data.remoteJid); + } else { + ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); + } + + const updateSettings = await this.settingsRepository.update({ + where: { + id: settings.id, + }, + data: { + ignoreJids: ignoreJids, + }, + }); + + return { + ignoreJids: updateSettings.ignoreJids, + }; + } catch (error) { + this.logger.error(error); + throw new Error('Error setting default settings'); + } + } + + public async emit({ + instance, + remoteJid, + msg, + }: { + instance: InstanceDto; + remoteJid: string; + msg: any; + pushName?: string; + }) { + if (!this.integrationEnabled) return; + + try { + const instanceData = await this.prismaRepository.instance.findFirst({ + where: { + name: instance.instanceName, + }, + }); + + if (!instanceData) throw new Error('Instance not found'); + + const session = await this.getSession(remoteJid, instance); + + const content = getConversationMessage(msg); + + const findBot = (await this.findBotTrigger( + this.botRepository, + this.settingsRepository, + content, + instance, + session, + )) as TypebotModel; + + if (!findBot) return; + + const settings = await this.prismaRepository.typebotSetting.findFirst({ + where: { + instanceId: instance.instanceId, + }, + }); + + const url = findBot?.url; + const typebot = findBot?.typebot; + let expire = findBot?.expire; + let keywordFinish = findBot?.keywordFinish; + let delayMessage = findBot?.delayMessage; + let unknownMessage = findBot?.unknownMessage; + let listeningFromMe = findBot?.listeningFromMe; + let stopBotFromMe = findBot?.stopBotFromMe; + let keepOpen = findBot?.keepOpen; + let debounceTime = findBot?.debounceTime; + let ignoreJids = findBot?.ignoreJids; + + if (!expire) expire = settings.expire; + if (!keywordFinish) keywordFinish = settings.keywordFinish; + if (!delayMessage) delayMessage = settings.delayMessage; + if (!unknownMessage) unknownMessage = settings.unknownMessage; + if (!listeningFromMe) listeningFromMe = settings.listeningFromMe; + if (!stopBotFromMe) stopBotFromMe = settings.stopBotFromMe; + if (!keepOpen) keepOpen = settings.keepOpen; + if (!debounceTime) debounceTime = settings.debounceTime; + if (!ignoreJids) ignoreJids = settings.ignoreJids; + + if (this.checkIgnoreJids(ignoreJids, remoteJid)) return; + + const key = msg.key as { + id: string; + remoteJid: string; + fromMe: boolean; + participant: string; + }; + + if (stopBotFromMe && key.fromMe && session) { + await this.sessionRepository.update({ + where: { + id: session.id, + }, + data: { + status: 'paused', + }, + }); + return; + } + + if (!listeningFromMe && key.fromMe) { + return; + } + + if (session && !session.awaitUser) { + return; + } + + if (debounceTime && debounceTime > 0) { + this.processDebounce(this.userMessageDebounce, content, remoteJid, debounceTime, async (debouncedContent) => { + await this.typebotService.processTypebot( + instanceData, + remoteJid, + msg, + session, + findBot, + url, + expire, + typebot, + keywordFinish, + delayMessage, + unknownMessage, + listeningFromMe, + stopBotFromMe, + keepOpen, + debouncedContent, + ); + }); + } else { + await this.typebotService.processTypebot( + instanceData, + remoteJid, + msg, + session, + findBot, + url, + expire, + typebot, + keywordFinish, + delayMessage, + unknownMessage, + listeningFromMe, + stopBotFromMe, + keepOpen, + content, + ); + } + + if (session && !session.awaitUser) return; + } catch (error) { + this.logger.error(error); + return; + } + } +} diff --git a/src/api/integrations/typebot/dto/typebot.dto.ts b/src/api/integrations/chatbot/typebot/dto/typebot.dto.ts similarity index 78% rename from src/api/integrations/typebot/dto/typebot.dto.ts rename to src/api/integrations/chatbot/typebot/dto/typebot.dto.ts index eedb8bc5..a7565236 100644 --- a/src/api/integrations/typebot/dto/typebot.dto.ts +++ b/src/api/integrations/chatbot/typebot/dto/typebot.dto.ts @@ -1,14 +1,5 @@ import { TriggerOperator, TriggerType } from '@prisma/client'; -export class Session { - remoteJid?: string; - sessionId?: string; - status?: string; - createdAt?: number; - updateAt?: number; - prefilledVariables?: PrefilledVariables; -} - export class PrefilledVariables { remoteJid?: string; pushName?: string; @@ -47,8 +38,3 @@ export class TypebotSettingDto { typebotIdFallback?: string; ignoreJids?: any; } - -export class TypebotIgnoreJidDto { - remoteJid?: string; - action?: string; -} diff --git a/src/api/integrations/typebot/routes/typebot.router.ts b/src/api/integrations/chatbot/typebot/routes/typebot.router.ts similarity index 78% rename from src/api/integrations/typebot/routes/typebot.router.ts rename to src/api/integrations/chatbot/typebot/routes/typebot.router.ts index 842d76dd..f556f94f 100644 --- a/src/api/integrations/typebot/routes/typebot.router.ts +++ b/src/api/integrations/chatbot/typebot/routes/typebot.router.ts @@ -1,5 +1,9 @@ -import { RequestHandler, Router } from 'express'; - +import { RouterBroker } from '@api/abstract/abstract.router'; +import { IgnoreJidDto } from '@api/dto/chatbot.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { TypebotDto, TypebotSettingDto } from '@api/integrations/chatbot/typebot/dto/typebot.dto'; +import { HttpStatus } from '@api/routes/index.router'; +import { typebotController } from '@api/server.module'; import { instanceSchema, typebotIgnoreJidSchema, @@ -7,12 +11,8 @@ import { typebotSettingSchema, typebotStartSchema, typebotStatusSchema, -} from '../../../../validate/validate.schema'; -import { RouterBroker } from '../../../abstract/abstract.router'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { HttpStatus } from '../../../routes/index.router'; -import { typebotController } from '../../../server.module'; -import { TypebotDto, TypebotIgnoreJidDto, TypebotSettingDto } from '../dto/typebot.dto'; +} from '@validate/validate.schema'; +import { RequestHandler, Router } from 'express'; export class TypebotRouter extends RouterBroker { constructor(...guards: RequestHandler[]) { @@ -23,7 +23,7 @@ export class TypebotRouter extends RouterBroker { request: req, schema: typebotSchema, ClassRef: TypebotDto, - execute: (instance, data) => typebotController.createTypebot(instance, data), + execute: (instance, data) => typebotController.createBot(instance, data), }); res.status(HttpStatus.CREATED).json(response); @@ -33,7 +33,7 @@ export class TypebotRouter extends RouterBroker { request: req, schema: instanceSchema, ClassRef: InstanceDto, - execute: (instance) => typebotController.findTypebot(instance), + execute: (instance) => typebotController.findBot(instance), }); res.status(HttpStatus.OK).json(response); @@ -43,7 +43,7 @@ export class TypebotRouter extends RouterBroker { request: req, schema: instanceSchema, ClassRef: InstanceDto, - execute: (instance) => typebotController.fetchTypebot(instance, req.params.typebotId), + execute: (instance) => typebotController.fetchBot(instance, req.params.typebotId), }); res.status(HttpStatus.OK).json(response); @@ -53,7 +53,7 @@ export class TypebotRouter extends RouterBroker { request: req, schema: typebotSchema, ClassRef: TypebotDto, - execute: (instance, data) => typebotController.updateTypebot(instance, req.params.typebotId, data), + execute: (instance, data) => typebotController.updateBot(instance, req.params.typebotId, data), }); res.status(HttpStatus.OK).json(response); @@ -63,7 +63,7 @@ export class TypebotRouter extends RouterBroker { request: req, schema: instanceSchema, ClassRef: InstanceDto, - execute: (instance) => typebotController.deleteTypebot(instance, req.params.typebotId), + execute: (instance) => typebotController.deleteBot(instance, req.params.typebotId), }); res.status(HttpStatus.OK).json(response); @@ -93,7 +93,7 @@ export class TypebotRouter extends RouterBroker { request: req, schema: typebotStartSchema, ClassRef: InstanceDto, - execute: (instance, data) => typebotController.startTypebot(instance, data), + execute: (instance, data) => typebotController.startBot(instance, data), }); res.status(HttpStatus.OK).json(response); @@ -119,10 +119,10 @@ export class TypebotRouter extends RouterBroker { res.status(HttpStatus.OK).json(response); }) .post(this.routerPath('ignoreJid'), ...guards, async (req, res) => { - const response = await this.dataValidate({ + const response = await this.dataValidate({ request: req, schema: typebotIgnoreJidSchema, - ClassRef: TypebotIgnoreJidDto, + ClassRef: IgnoreJidDto, execute: (instance, data) => typebotController.ignoreJid(instance, data), }); @@ -130,5 +130,5 @@ export class TypebotRouter extends RouterBroker { }); } - public readonly router = Router(); + public readonly router: Router = Router(); } diff --git a/src/api/integrations/chatbot/typebot/services/typebot.service.ts b/src/api/integrations/chatbot/typebot/services/typebot.service.ts new file mode 100644 index 00000000..07feba53 --- /dev/null +++ b/src/api/integrations/chatbot/typebot/services/typebot.service.ts @@ -0,0 +1,715 @@ +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Auth, ConfigService, HttpServer, Typebot } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { Instance, IntegrationSession, Message, Typebot as TypebotModel } from '@prisma/client'; +import { getConversationMessage } from '@utils/getConversationMessage'; +import { sendTelemetry } from '@utils/sendTelemetry'; +import axios from 'axios'; + +export class TypebotService { + constructor( + private readonly waMonitor: WAMonitoringService, + private readonly configService: ConfigService, + private readonly prismaRepository: PrismaRepository, + ) {} + + private readonly logger = new Logger('TypebotService'); + + public async createNewSession(instance: Instance, data: any) { + if (data.remoteJid === 'status@broadcast') return; + const id = Math.floor(Math.random() * 10000000000).toString(); + + try { + const version = this.configService.get('TYPEBOT').API_VERSION; + let url: string; + let reqData: {}; + if (version === 'latest') { + url = `${data.url}/api/v1/typebots/${data.typebot}/startChat`; + + reqData = { + prefilledVariables: { + ...data.prefilledVariables, + remoteJid: data.remoteJid, + pushName: data.pushName || data.prefilledVariables?.pushName || '', + instanceName: instance.name, + serverUrl: this.configService.get('SERVER').URL, + apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, + ownerJid: instance.number, + }, + }; + } else { + url = `${data.url}/api/v1/sendMessage`; + + reqData = { + startParams: { + publicId: data.typebot, + prefilledVariables: { + ...data.prefilledVariables, + remoteJid: data.remoteJid, + pushName: data.pushName || data.prefilledVariables?.pushName || '', + instanceName: instance.name, + serverUrl: this.configService.get('SERVER').URL, + apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, + ownerJid: instance.number, + }, + }, + }; + } + const request = await axios.post(url, reqData); + + let session = null; + if (request?.data?.sessionId) { + session = await this.prismaRepository.integrationSession.create({ + data: { + remoteJid: data.remoteJid, + pushName: data.pushName || '', + sessionId: `${id}-${request.data.sessionId}`, + status: 'opened', + parameters: { + ...data.prefilledVariables, + remoteJid: data.remoteJid, + pushName: data.pushName || '', + instanceName: instance.name, + serverUrl: this.configService.get('SERVER').URL, + apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, + ownerJid: instance.number, + }, + awaitUser: false, + botId: data.botId, + instanceId: instance.id, + type: 'typebot', + }, + }); + } + return { ...request.data, session }; + } catch (error) { + this.logger.error(error); + return; + } + } + + public async sendWAMessage( + instance: Instance, + session: IntegrationSession, + settings: { + expire: number; + keywordFinish: string; + delayMessage: number; + unknownMessage: string; + listeningFromMe: boolean; + stopBotFromMe: boolean; + keepOpen: boolean; + }, + remoteJid: string, + messages: any, + input: any, + clientSideActions: any, + ) { + processMessages( + this.waMonitor.waInstances[instance.name], + session, + settings, + messages, + input, + clientSideActions, + applyFormatting, + this.prismaRepository, + ).catch((err) => { + console.error('Erro ao processar mensagens:', err); + }); + + function findItemAndGetSecondsToWait(array, targetId) { + if (!array) return null; + + for (const item of array) { + if (item.lastBubbleBlockId === targetId) { + return item.wait?.secondsToWaitFor; + } + } + return null; + } + + function applyFormatting(element) { + let text = ''; + + if (element.text) { + text += element.text; + } + + if (element.children && element.type !== 'a') { + for (const child of element.children) { + text += applyFormatting(child); + } + } + + if (element.type === 'p' && element.type !== 'inline-variable') { + text = text.trim() + '\n'; + } + + if (element.type === 'inline-variable') { + text = text.trim(); + } + + if (element.type === 'ol') { + text = + '\n' + + text + .split('\n') + .map((line, index) => (line ? `${index + 1}. ${line}` : '')) + .join('\n'); + } + + if (element.type === 'li') { + text = text + .split('\n') + .map((line) => (line ? ` ${line}` : '')) + .join('\n'); + } + + let formats = ''; + + if (element.bold) { + formats += '*'; + } + + if (element.italic) { + formats += '_'; + } + + if (element.underline) { + formats += '~'; + } + + let formattedText = `${formats}${text}${formats.split('').reverse().join('')}`; + + if (element.url) { + formattedText = element.children[0]?.text ? `[${formattedText}]\n(${element.url})` : `${element.url}`; + } + + return formattedText; + } + + async function processMessages( + instance: any, + session: IntegrationSession, + settings: { + expire: number; + keywordFinish: string; + delayMessage: number; + unknownMessage: string; + listeningFromMe: boolean; + stopBotFromMe: boolean; + keepOpen: boolean; + }, + messages: any, + input: any, + clientSideActions: any, + applyFormatting: any, + prismaRepository: PrismaRepository, + ) { + for (const message of messages) { + if (message.type === 'text') { + let formattedText = ''; + + for (const richText of message.content.richText) { + for (const element of richText.children) { + formattedText += applyFormatting(element); + } + formattedText += '\n'; + } + + formattedText = formattedText.replace(/\*\*/g, '').replace(/__/, '').replace(/~~/, '').replace(/\n$/, ''); + + formattedText = formattedText.replace(/\n$/, ''); + + await instance.textMessage( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + text: formattedText, + }, + false, + ); + + sendTelemetry('/message/sendText'); + } + + if (message.type === 'image') { + await instance.mediaMessage( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + mediatype: 'image', + media: message.content.url, + }, + false, + ); + + sendTelemetry('/message/sendMedia'); + } + + if (message.type === 'video') { + await instance.mediaMessage( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + mediatype: 'video', + media: message.content.url, + }, + false, + ); + + sendTelemetry('/message/sendMedia'); + } + + if (message.type === 'audio') { + await instance.audioWhatsapp( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + encoding: true, + audio: message.content.url, + }, + false, + ); + + sendTelemetry('/message/sendWhatsAppAudio'); + } + + const wait = findItemAndGetSecondsToWait(clientSideActions, message.id); + + if (wait) { + await new Promise((resolve) => setTimeout(resolve, wait * 1000)); + } + } + + if (input) { + if (input.type === 'choice input') { + let formattedText = ''; + + const items = input.items; + + for (const item of items) { + formattedText += `▶️ ${item.content}\n`; + } + + formattedText = formattedText.replace(/\n$/, ''); + + await instance.textMessage( + { + number: remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + text: formattedText, + }, + false, + ); + + sendTelemetry('/message/sendText'); + } + + await prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + awaitUser: true, + }, + }); + } else { + if (!settings?.keepOpen) { + await prismaRepository.integrationSession.deleteMany({ + where: { + id: session.id, + }, + }); + } else { + await prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'closed', + }, + }); + } + } + } + } + + public async processTypebot( + instance: Instance, + remoteJid: string, + msg: Message, + session: IntegrationSession, + findTypebot: TypebotModel, + url: string, + expire: number, + typebot: string, + keywordFinish: string, + delayMessage: number, + unknownMessage: string, + listeningFromMe: boolean, + stopBotFromMe: boolean, + keepOpen: boolean, + content: string, + ) { + if (session && expire && expire > 0) { + const now = Date.now(); + + const sessionUpdatedAt = new Date(session.updatedAt).getTime(); + + const diff = now - sessionUpdatedAt; + + const diffInMinutes = Math.floor(diff / 1000 / 60); + + if (diffInMinutes > expire) { + if (keepOpen) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: findTypebot.id, + remoteJid: remoteJid, + }, + }); + } + + const data = await this.createNewSession(instance, { + enabled: findTypebot?.enabled, + url: url, + typebot: typebot, + expire: expire, + keywordFinish: keywordFinish, + delayMessage: delayMessage, + unknownMessage: unknownMessage, + listeningFromMe: listeningFromMe, + remoteJid: remoteJid, + pushName: msg.pushName, + botId: findTypebot.id, + }); + + if (data.session) { + session = data.session; + } + + await this.sendWAMessage( + instance, + session, + { + expire: expire, + keywordFinish: keywordFinish, + delayMessage: delayMessage, + unknownMessage: unknownMessage, + listeningFromMe: listeningFromMe, + stopBotFromMe: stopBotFromMe, + keepOpen: keepOpen, + }, + remoteJid, + data.messages, + data.input, + data.clientSideActions, + ); + + if (data.messages.length === 0) { + const content = getConversationMessage(msg.message); + + if (!content) { + if (unknownMessage) { + this.waMonitor.waInstances[instance.name].textMessage( + { + number: remoteJid.split('@')[0], + delay: delayMessage || 1000, + text: unknownMessage, + }, + false, + ); + + sendTelemetry('/message/sendText'); + } + return; + } + + if (keywordFinish && content.toLowerCase() === keywordFinish.toLowerCase()) { + if (keepOpen) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: findTypebot.id, + remoteJid: remoteJid, + }, + }); + } + return; + } + + try { + const version = this.configService.get('TYPEBOT').API_VERSION; + let urlTypebot: string; + let reqData: {}; + if (version === 'latest') { + urlTypebot = `${url}/api/v1/sessions/${data.sessionId}/continueChat`; + reqData = { + message: content, + }; + } else { + urlTypebot = `${url}/api/v1/sendMessage`; + reqData = { + message: content, + sessionId: data.sessionId, + }; + } + + const request = await axios.post(urlTypebot, reqData); + + await this.sendWAMessage( + instance, + session, + { + expire: expire, + keywordFinish: keywordFinish, + delayMessage: delayMessage, + unknownMessage: unknownMessage, + listeningFromMe: listeningFromMe, + stopBotFromMe: stopBotFromMe, + keepOpen: keepOpen, + }, + remoteJid, + request.data.messages, + request.data.input, + request.data.clientSideActions, + ); + } catch (error) { + this.logger.error(error); + return; + } + } + + return; + } + } + + if (session && session.status !== 'opened') { + return; + } + + if (!session) { + const data = await this.createNewSession(instance, { + enabled: findTypebot?.enabled, + url: url, + typebot: typebot, + expire: expire, + keywordFinish: keywordFinish, + delayMessage: delayMessage, + unknownMessage: unknownMessage, + listeningFromMe: listeningFromMe, + remoteJid: remoteJid, + pushName: msg.pushName, + botId: findTypebot.id, + }); + + if (data?.session) { + session = data.session; + } + + await this.sendWAMessage( + instance, + session, + { + expire: expire, + keywordFinish: keywordFinish, + delayMessage: delayMessage, + unknownMessage: unknownMessage, + listeningFromMe: listeningFromMe, + stopBotFromMe: stopBotFromMe, + keepOpen: keepOpen, + }, + remoteJid, + data?.messages, + data?.input, + data?.clientSideActions, + ); + + if (data.messages.length === 0) { + if (!content) { + if (unknownMessage) { + this.waMonitor.waInstances[instance.name].textMessage( + { + number: remoteJid.split('@')[0], + delay: delayMessage || 1000, + text: unknownMessage, + }, + false, + ); + + sendTelemetry('/message/sendText'); + } + return; + } + + if (keywordFinish && content.toLowerCase() === keywordFinish.toLowerCase()) { + if (keepOpen) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: findTypebot.id, + remoteJid: remoteJid, + }, + }); + } + + return; + } + + let request: any; + try { + const version = this.configService.get('TYPEBOT').API_VERSION; + let urlTypebot: string; + let reqData: {}; + if (version === 'latest') { + urlTypebot = `${url}/api/v1/sessions/${data.sessionId}/continueChat`; + reqData = { + message: content, + }; + } else { + urlTypebot = `${url}/api/v1/sendMessage`; + reqData = { + message: content, + sessionId: data.sessionId, + }; + } + request = await axios.post(urlTypebot, reqData); + + await this.sendWAMessage( + instance, + session, + { + expire: expire, + keywordFinish: keywordFinish, + delayMessage: delayMessage, + unknownMessage: unknownMessage, + listeningFromMe: listeningFromMe, + stopBotFromMe: stopBotFromMe, + keepOpen: keepOpen, + }, + remoteJid, + request.data.messages, + request.data.input, + request.data.clientSideActions, + ); + } catch (error) { + this.logger.error(error); + return; + } + } + return; + } + + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: false, + }, + }); + + if (!content) { + if (unknownMessage) { + this.waMonitor.waInstances[instance.name].textMessage( + { + number: remoteJid.split('@')[0], + delay: delayMessage || 1000, + text: unknownMessage, + }, + false, + ); + + sendTelemetry('/message/sendText'); + } + return; + } + + if (keywordFinish && content.toLowerCase() === keywordFinish.toLowerCase()) { + if (keepOpen) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: findTypebot.id, + remoteJid: remoteJid, + }, + }); + } + return; + } + + const version = this.configService.get('TYPEBOT').API_VERSION; + let urlTypebot: string; + let reqData: {}; + if (version === 'latest') { + urlTypebot = `${url}/api/v1/sessions/${session.sessionId.split('-')[1]}/continueChat`; + reqData = { + message: content, + }; + } else { + urlTypebot = `${url}/api/v1/sendMessage`; + reqData = { + message: content, + sessionId: session.sessionId.split('-')[1], + }; + } + const request = await axios.post(urlTypebot, reqData); + + await this.sendWAMessage( + instance, + session, + { + expire: expire, + keywordFinish: keywordFinish, + delayMessage: delayMessage, + unknownMessage: unknownMessage, + listeningFromMe: listeningFromMe, + stopBotFromMe: stopBotFromMe, + keepOpen: keepOpen, + }, + remoteJid, + request?.data?.messages, + request?.data?.input, + request?.data?.clientSideActions, + ); + + return; + } +} diff --git a/src/api/integrations/typebot/validate/typebot.schema.ts b/src/api/integrations/chatbot/typebot/validate/typebot.schema.ts similarity index 99% rename from src/api/integrations/typebot/validate/typebot.schema.ts rename to src/api/integrations/chatbot/typebot/validate/typebot.schema.ts index e473d016..02dc74e8 100644 --- a/src/api/integrations/typebot/validate/typebot.schema.ts +++ b/src/api/integrations/chatbot/typebot/validate/typebot.schema.ts @@ -28,7 +28,7 @@ export const typebotSchema: JSONSchema7 = { description: { type: 'string' }, url: { type: 'string' }, typebot: { type: 'string' }, - triggerType: { type: 'string', enum: ['all', 'keyword', 'none'] }, + triggerType: { type: 'string', enum: ['all', 'keyword', 'none', 'advanced'] }, triggerOperator: { type: 'string', enum: ['equals', 'contains', 'startsWith', 'endsWith', 'regex'] }, triggerValue: { type: 'string' }, expire: { type: 'integer' }, diff --git a/src/api/integrations/chatwoot/dto/chatwoot.dto.ts b/src/api/integrations/chatwoot/dto/chatwoot.dto.ts deleted file mode 100644 index 8f3729a4..00000000 --- a/src/api/integrations/chatwoot/dto/chatwoot.dto.ts +++ /dev/null @@ -1,19 +0,0 @@ -export class ChatwootDto { - enabled?: boolean; - accountId?: string; - token?: string; - url?: string; - nameInbox?: string; - signMsg?: boolean; - signDelimiter?: string; - number?: string; - reopenConversation?: boolean; - conversationPending?: boolean; - mergeBrazilContacts?: boolean; - importContacts?: boolean; - importMessages?: boolean; - daysLimitImportMessages?: number; - autoCreate?: boolean; - organization?: string; - logo?: string; -} diff --git a/src/api/integrations/dify/controllers/dify.controller.ts b/src/api/integrations/dify/controllers/dify.controller.ts deleted file mode 100644 index ce4e807b..00000000 --- a/src/api/integrations/dify/controllers/dify.controller.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { configService, Dify } from '../../../../config/env.config'; -import { BadRequestException } from '../../../../exceptions'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { DifyDto, DifyIgnoreJidDto } from '../dto/dify.dto'; -import { DifyService } from '../services/dify.service'; - -export class DifyController { - constructor(private readonly difyService: DifyService) {} - - public async createDify(instance: InstanceDto, data: DifyDto) { - if (!configService.get('DIFY').ENABLED) throw new BadRequestException('Dify is disabled'); - - return this.difyService.create(instance, data); - } - - public async findDify(instance: InstanceDto) { - if (!configService.get('DIFY').ENABLED) throw new BadRequestException('Dify is disabled'); - - return this.difyService.find(instance); - } - - public async fetchDify(instance: InstanceDto, difyId: string) { - if (!configService.get('DIFY').ENABLED) throw new BadRequestException('Dify is disabled'); - - return this.difyService.fetch(instance, difyId); - } - - public async updateDify(instance: InstanceDto, difyId: string, data: DifyDto) { - if (!configService.get('DIFY').ENABLED) throw new BadRequestException('Dify is disabled'); - - return this.difyService.update(instance, difyId, data); - } - - public async deleteDify(instance: InstanceDto, difyId: string) { - if (!configService.get('DIFY').ENABLED) throw new BadRequestException('Dify is disabled'); - - return this.difyService.delete(instance, difyId); - } - - public async settings(instance: InstanceDto, data: any) { - if (!configService.get('DIFY').ENABLED) throw new BadRequestException('Dify is disabled'); - - return this.difyService.setDefaultSettings(instance, data); - } - - public async fetchSettings(instance: InstanceDto) { - if (!configService.get('DIFY').ENABLED) throw new BadRequestException('Dify is disabled'); - - return this.difyService.fetchDefaultSettings(instance); - } - - public async changeStatus(instance: InstanceDto, data: any) { - if (!configService.get('DIFY').ENABLED) throw new BadRequestException('Dify is disabled'); - - return this.difyService.changeStatus(instance, data); - } - - public async fetchSessions(instance: InstanceDto, difyId: string) { - if (!configService.get('DIFY').ENABLED) throw new BadRequestException('Dify is disabled'); - - return this.difyService.fetchSessions(instance, difyId); - } - - public async ignoreJid(instance: InstanceDto, data: DifyIgnoreJidDto) { - if (!configService.get('DIFY').ENABLED) throw new BadRequestException('Dify is disabled'); - - return this.difyService.ignoreJid(instance, data); - } -} diff --git a/src/api/integrations/dify/services/dify.service.ts b/src/api/integrations/dify/services/dify.service.ts deleted file mode 100644 index bfdc4f0b..00000000 --- a/src/api/integrations/dify/services/dify.service.ts +++ /dev/null @@ -1,1628 +0,0 @@ -import { Dify, DifySession, DifySetting, Message } from '@prisma/client'; -import axios from 'axios'; -import { Readable } from 'stream'; - -import { ConfigService, S3 } from '../../../../config/env.config'; -import { Logger } from '../../../../config/logger.config'; -import { sendTelemetry } from '../../../../utils/sendTelemetry'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { PrismaRepository } from '../../../repository/repository.service'; -import { WAMonitoringService } from '../../../services/monitor.service'; -import { DifyDto, DifyIgnoreJidDto, DifySettingDto } from '../dto/dify.dto'; - -export class DifyService { - constructor( - private readonly waMonitor: WAMonitoringService, - private readonly configService: ConfigService, - private readonly prismaRepository: PrismaRepository, - ) {} - - private userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; - - private readonly logger = new Logger(DifyService.name); - - public async create(instance: InstanceDto, data: DifyDto) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - if ( - !data.expire || - !data.keywordFinish || - !data.delayMessage || - !data.unknownMessage || - !data.listeningFromMe || - !data.stopBotFromMe || - !data.keepOpen || - !data.debounceTime || - !data.ignoreJids - ) { - const defaultSettingCheck = await this.prismaRepository.difySetting.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (!data.expire) data.expire = defaultSettingCheck?.expire || 0; - if (!data.keywordFinish) data.keywordFinish = defaultSettingCheck?.keywordFinish || ''; - if (!data.delayMessage) data.delayMessage = defaultSettingCheck?.delayMessage || 1000; - if (!data.unknownMessage) data.unknownMessage = defaultSettingCheck?.unknownMessage || ''; - if (!data.listeningFromMe) data.listeningFromMe = defaultSettingCheck?.listeningFromMe || false; - if (!data.stopBotFromMe) data.stopBotFromMe = defaultSettingCheck?.stopBotFromMe || false; - if (!data.keepOpen) data.keepOpen = defaultSettingCheck?.keepOpen || false; - if (!data.debounceTime) data.debounceTime = defaultSettingCheck?.debounceTime || 0; - if (!data.ignoreJids) data.ignoreJids = defaultSettingCheck?.ignoreJids || []; - - if (!defaultSettingCheck) { - await this.setDefaultSettings(instance, { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - ignoreJids: data.ignoreJids, - }); - } - } - - const checkTriggerAll = await this.prismaRepository.dify.findFirst({ - where: { - enabled: true, - triggerType: 'all', - instanceId: instanceId, - }, - }); - - if (checkTriggerAll && data.triggerType === 'all') { - throw new Error('You already have a dify with an "All" trigger, you cannot have more bots while it is active'); - } - - const checkDuplicate = await this.prismaRepository.dify.findFirst({ - where: { - instanceId: instanceId, - botType: data.botType, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - }, - }); - - if (checkDuplicate) { - throw new Error('Dify already exists'); - } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.prismaRepository.dify.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const dify = await this.prismaRepository.dify.create({ - data: { - enabled: data.enabled, - description: data.description, - botType: data.botType, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - }, - }); - - return dify; - } catch (error) { - this.logger.error(error); - throw new Error('Error creating dify'); - } - } - - public async fetch(instance: InstanceDto, difyId: string) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const dify = await this.prismaRepository.dify.findFirst({ - where: { - id: difyId, - }, - include: { - DifySession: true, - }, - }); - - if (!dify) { - throw new Error('Dify not found'); - } - - if (dify.instanceId !== instanceId) { - throw new Error('Dify not found'); - } - - return dify; - } - - public async update(instance: InstanceDto, difyId: string, data: DifyDto) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const dify = await this.prismaRepository.dify.findFirst({ - where: { - id: difyId, - }, - }); - - if (!dify) { - throw new Error('Dify not found'); - } - - if (dify.instanceId !== instanceId) { - throw new Error('Dify not found'); - } - - if (data.triggerType === 'all') { - const checkTriggerAll = await this.prismaRepository.dify.findFirst({ - where: { - enabled: true, - triggerType: 'all', - id: { - not: difyId, - }, - instanceId: instanceId, - }, - }); - - if (checkTriggerAll) { - throw new Error('You already have a dify with an "All" trigger, you cannot have more bots while it is active'); - } - } - - const checkDuplicate = await this.prismaRepository.dify.findFirst({ - where: { - id: { - not: difyId, - }, - instanceId: instanceId, - botType: data.botType, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - }, - }); - - if (checkDuplicate) { - throw new Error('Dify already exists'); - } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.prismaRepository.dify.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - id: { - not: difyId, - }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const dify = await this.prismaRepository.dify.update({ - where: { - id: difyId, - }, - data: { - enabled: data.enabled, - botType: data.botType, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - }, - }); - - return dify; - } catch (error) { - this.logger.error(error); - throw new Error('Error updating dify'); - } - } - - public async find(instance: InstanceDto): Promise { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const difys = await this.prismaRepository.dify.findMany({ - where: { - instanceId: instanceId, - }, - include: { - DifySession: true, - }, - }); - - if (!difys.length) { - return null; - } - - return difys; - } - - public async delete(instance: InstanceDto, difyId: string) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const dify = await this.prismaRepository.dify.findFirst({ - where: { - id: difyId, - }, - }); - - if (!dify) { - throw new Error('Dify not found'); - } - - if (dify.instanceId !== instanceId) { - throw new Error('Dify not found'); - } - try { - await this.prismaRepository.difySession.deleteMany({ - where: { - difyId: difyId, - }, - }); - - await this.prismaRepository.dify.delete({ - where: { - id: difyId, - }, - }); - - return { dify: { id: difyId } }; - } catch (error) { - this.logger.error(error); - throw new Error('Error deleting openai bot'); - } - } - - public async setDefaultSettings(instance: InstanceDto, data: DifySettingDto) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.prismaRepository.difySetting.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (settings) { - const updateSettings = await this.prismaRepository.difySetting.update({ - where: { - id: settings.id, - }, - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - difyIdFallback: data.difyIdFallback, - ignoreJids: data.ignoreJids, - }, - }); - - return { - expire: updateSettings.expire, - keywordFinish: updateSettings.keywordFinish, - delayMessage: updateSettings.delayMessage, - unknownMessage: updateSettings.unknownMessage, - listeningFromMe: updateSettings.listeningFromMe, - stopBotFromMe: updateSettings.stopBotFromMe, - keepOpen: updateSettings.keepOpen, - debounceTime: updateSettings.debounceTime, - difyIdFallback: updateSettings.difyIdFallback, - ignoreJids: updateSettings.ignoreJids, - }; - } - - const newSetttings = await this.prismaRepository.difySetting.create({ - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - difyIdFallback: data.difyIdFallback, - ignoreJids: data.ignoreJids, - instanceId: instanceId, - }, - }); - - return { - expire: newSetttings.expire, - keywordFinish: newSetttings.keywordFinish, - delayMessage: newSetttings.delayMessage, - unknownMessage: newSetttings.unknownMessage, - listeningFromMe: newSetttings.listeningFromMe, - stopBotFromMe: newSetttings.stopBotFromMe, - keepOpen: newSetttings.keepOpen, - debounceTime: newSetttings.debounceTime, - difyIdFallback: newSetttings.difyIdFallback, - ignoreJids: newSetttings.ignoreJids, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - public async fetchDefaultSettings(instance: InstanceDto) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.prismaRepository.difySetting.findFirst({ - where: { - instanceId: instanceId, - }, - include: { - Fallback: true, - }, - }); - - if (!settings) { - return { - expire: 0, - keywordFinish: '', - delayMessage: 0, - unknownMessage: '', - listeningFromMe: false, - stopBotFromMe: false, - keepOpen: false, - ignoreJids: [], - difyIdFallback: '', - fallback: null, - }; - } - - return { - expire: settings.expire, - keywordFinish: settings.keywordFinish, - delayMessage: settings.delayMessage, - unknownMessage: settings.unknownMessage, - listeningFromMe: settings.listeningFromMe, - stopBotFromMe: settings.stopBotFromMe, - keepOpen: settings.keepOpen, - ignoreJids: settings.ignoreJids, - difyIdFallback: settings.difyIdFallback, - fallback: settings.Fallback, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching default settings'); - } - } - - public async ignoreJid(instance: InstanceDto, data: DifyIgnoreJidDto) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.prismaRepository.difySetting.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (!settings) { - throw new Error('Settings not found'); - } - - let ignoreJids: any = settings?.ignoreJids || []; - - if (data.action === 'add') { - if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; - - ignoreJids.push(data.remoteJid); - } else { - ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); - } - - const updateSettings = await this.prismaRepository.difySetting.update({ - where: { - id: settings.id, - }, - data: { - ignoreJids: ignoreJids, - }, - }); - - return { - ignoreJids: updateSettings.ignoreJids, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - public async fetchSessions(instance: InstanceDto, difyId?: string, remoteJid?: string) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const dify = await this.prismaRepository.dify.findFirst({ - where: { - id: difyId, - }, - }); - - if (!dify) { - throw new Error('Dify not found'); - } - - if (dify.instanceId !== instanceId) { - throw new Error('Dify not found'); - } - - if (dify) { - return await this.prismaRepository.difySession.findMany({ - where: { - difyId: difyId, - }, - }); - } - - if (remoteJid) { - return await this.prismaRepository.difySession.findMany({ - where: { - remoteJid: remoteJid, - difyId: difyId, - }, - }); - } - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching sessions'); - } - } - - public async changeStatus(instance: InstanceDto, data: any) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const defaultSettingCheck = await this.prismaRepository.difySetting.findFirst({ - where: { - instanceId, - }, - }); - - const remoteJid = data.remoteJid; - const status = data.status; - - if (status === 'delete') { - await this.prismaRepository.difySession.deleteMany({ - where: { - remoteJid: remoteJid, - }, - }); - - return { dify: { remoteJid: remoteJid, status: status } }; - } - - if (status === 'closed') { - if (defaultSettingCheck?.keepOpen) { - await this.prismaRepository.difySession.updateMany({ - where: { - remoteJid: remoteJid, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.difySession.deleteMany({ - where: { - remoteJid: remoteJid, - }, - }); - } - - return { dify: { ...instance, dify: { remoteJid: remoteJid, status: status } } }; - } else { - const session = await this.prismaRepository.difySession.updateMany({ - where: { - instanceId: instanceId, - remoteJid: remoteJid, - }, - data: { - status: status, - }, - }); - - const difyData = { - remoteJid: remoteJid, - status: status, - session, - }; - - return { dify: { ...instance, dify: difyData } }; - } - } catch (error) { - this.logger.error(error); - throw new Error('Error changing status'); - } - } - - private getTypeMessage(msg: any) { - let mediaId: string; - - if (this.configService.get('S3').ENABLE) mediaId = msg.message.mediaUrl; - else mediaId = msg.key.id; - - const types = { - conversation: msg?.message?.conversation, - extendedTextMessage: msg?.message?.extendedTextMessage?.text, - contactMessage: msg?.message?.contactMessage?.displayName, - locationMessage: msg?.message?.locationMessage?.degreesLatitude, - viewOnceMessageV2: - msg?.message?.viewOnceMessageV2?.message?.imageMessage?.url || - msg?.message?.viewOnceMessageV2?.message?.videoMessage?.url || - msg?.message?.viewOnceMessageV2?.message?.audioMessage?.url, - listResponseMessage: msg?.message?.listResponseMessage?.singleSelectReply?.selectedRowId, - responseRowId: msg?.message?.listResponseMessage?.singleSelectReply?.selectedRowId, - // Medias - audioMessage: msg?.message?.speechToText - ? msg?.message?.speechToText - : msg?.message?.audioMessage - ? `audioMessage|${mediaId}` - : undefined, - imageMessage: msg?.message?.imageMessage ? `imageMessage|${mediaId}` : undefined, - videoMessage: msg?.message?.videoMessage ? `videoMessage|${mediaId}` : undefined, - documentMessage: msg?.message?.documentMessage ? `documentMessage|${mediaId}` : undefined, - documentWithCaptionMessage: msg?.message?.auddocumentWithCaptionMessageioMessage - ? `documentWithCaptionMessage|${mediaId}` - : undefined, - }; - - const messageType = Object.keys(types).find((key) => types[key] !== undefined) || 'unknown'; - - return { ...types, messageType }; - } - - private getMessageContent(types: any) { - const typeKey = Object.keys(types).find((key) => types[key] !== undefined); - - const result = typeKey ? types[typeKey] : undefined; - - return result; - } - - private getConversationMessage(msg: any) { - const types = this.getTypeMessage(msg); - - const messageContent = this.getMessageContent(types); - - return messageContent; - } - - public async findDifyByTrigger(content: string, instanceId: string) { - // Check for triggerType 'all' - const findTriggerAll = await this.prismaRepository.dify.findFirst({ - where: { - enabled: true, - triggerType: 'all', - instanceId: instanceId, - }, - }); - - if (findTriggerAll) return findTriggerAll; - - // Check for exact match - const findTriggerEquals = await this.prismaRepository.dify.findFirst({ - where: { - enabled: true, - triggerType: 'keyword', - triggerOperator: 'equals', - triggerValue: content, - instanceId: instanceId, - }, - }); - - if (findTriggerEquals) return findTriggerEquals; - - // Check for regex match - const findRegex = await this.prismaRepository.dify.findMany({ - where: { - enabled: true, - triggerType: 'keyword', - triggerOperator: 'regex', - instanceId: instanceId, - }, - }); - - let findTriggerRegex = null; - - for (const regex of findRegex) { - const regexValue = new RegExp(regex.triggerValue); - - if (regexValue.test(content)) { - findTriggerRegex = regex; - break; - } - } - - if (findTriggerRegex) return findTriggerRegex; - - // Check for startsWith match - const findStartsWith = await this.prismaRepository.dify.findMany({ - where: { - enabled: true, - triggerType: 'keyword', - triggerOperator: 'startsWith', - instanceId: instanceId, - }, - }); - - let findTriggerStartsWith = null; - - for (const startsWith of findStartsWith) { - if (content.startsWith(startsWith.triggerValue)) { - findTriggerStartsWith = startsWith; - break; - } - } - - if (findTriggerStartsWith) return findTriggerStartsWith; - - // Check for endsWith match - const findEndsWith = await this.prismaRepository.dify.findMany({ - where: { - enabled: true, - triggerType: 'keyword', - triggerOperator: 'endsWith', - instanceId: instanceId, - }, - }); - - let findTriggerEndsWith = null; - - for (const endsWith of findEndsWith) { - if (content.endsWith(endsWith.triggerValue)) { - findTriggerEndsWith = endsWith; - break; - } - } - - if (findTriggerEndsWith) return findTriggerEndsWith; - - // Check for contains match - const findContains = await this.prismaRepository.dify.findMany({ - where: { - enabled: true, - triggerType: 'keyword', - triggerOperator: 'contains', - instanceId: instanceId, - }, - }); - - let findTriggerContains = null; - - for (const contains of findContains) { - if (content.includes(contains.triggerValue)) { - findTriggerContains = contains; - break; - } - } - - if (findTriggerContains) return findTriggerContains; - - const fallback = await this.prismaRepository.difySetting.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (fallback?.difyIdFallback) { - const findFallback = await this.prismaRepository.dify.findFirst({ - where: { - id: fallback.difyIdFallback, - }, - }); - - if (findFallback) return findFallback; - } - - return null; - } - - private processDebounce(content: string, remoteJid: string, debounceTime: number, callback: any) { - if (this.userMessageDebounce[remoteJid]) { - this.userMessageDebounce[remoteJid].message += ` ${content}`; - this.logger.log('message debounced: ' + this.userMessageDebounce[remoteJid].message); - clearTimeout(this.userMessageDebounce[remoteJid].timeoutId); - } else { - this.userMessageDebounce[remoteJid] = { - message: content, - timeoutId: null, - }; - } - - this.userMessageDebounce[remoteJid].timeoutId = setTimeout(() => { - const myQuestion = this.userMessageDebounce[remoteJid].message; - this.logger.log('Debounce complete. Processing message: ' + myQuestion); - - delete this.userMessageDebounce[remoteJid]; - callback(myQuestion); - }, debounceTime * 1000); - } - - public async sendDify(instance: InstanceDto, remoteJid: string, msg: Message) { - try { - const settings = await this.prismaRepository.difySetting.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (settings?.ignoreJids) { - const ignoreJids: any = settings.ignoreJids; - - let ignoreGroups = false; - let ignoreContacts = false; - - if (ignoreJids.includes('@g.us')) { - ignoreGroups = true; - } - - if (ignoreJids.includes('@s.whatsapp.net')) { - ignoreContacts = true; - } - - if (ignoreGroups && remoteJid.endsWith('@g.us')) { - this.logger.warn('Ignoring message from group: ' + remoteJid); - return; - } - - if (ignoreContacts && remoteJid.endsWith('@s.whatsapp.net')) { - this.logger.warn('Ignoring message from contact: ' + remoteJid); - return; - } - - if (ignoreJids.includes(remoteJid)) { - this.logger.warn('Ignoring message from jid: ' + remoteJid); - return; - } - } - - const session = await this.prismaRepository.difySession.findFirst({ - where: { - remoteJid: remoteJid, - instanceId: instance.instanceId, - }, - }); - - const content = this.getConversationMessage(msg); - - let findDify = null; - - if (!session) { - findDify = await this.findDifyByTrigger(content, instance.instanceId); - - if (!findDify) { - return; - } - } else { - findDify = await this.prismaRepository.dify.findFirst({ - where: { - id: session.difyId, - }, - }); - } - - if (!findDify) return; - - let expire = findDify.expire; - let keywordFinish = findDify.keywordFinish; - let delayMessage = findDify.delayMessage; - let unknownMessage = findDify.unknownMessage; - let listeningFromMe = findDify.listeningFromMe; - let stopBotFromMe = findDify.stopBotFromMe; - let keepOpen = findDify.keepOpen; - let debounceTime = findDify.debounceTime; - - if ( - !expire || - !keywordFinish || - !delayMessage || - !unknownMessage || - !listeningFromMe || - !stopBotFromMe || - !keepOpen || - !debounceTime - ) { - if (!expire) expire = settings.expire; - - if (!keywordFinish) keywordFinish = settings.keywordFinish; - - if (!delayMessage) delayMessage = settings.delayMessage; - - if (!unknownMessage) unknownMessage = settings.unknownMessage; - - if (!listeningFromMe) listeningFromMe = settings.listeningFromMe; - - if (!stopBotFromMe) stopBotFromMe = settings.stopBotFromMe; - - if (!keepOpen) keepOpen = settings.keepOpen; - - if (!debounceTime) debounceTime = settings.debounceTime; - } - - const key = msg.key as { - id: string; - remoteJid: string; - fromMe: boolean; - participant: string; - }; - - if (stopBotFromMe && key.fromMe && session) { - if (keepOpen) { - await this.prismaRepository.difySession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.difySession.deleteMany({ - where: { - difyId: findDify.id, - remoteJid: remoteJid, - }, - }); - } - return; - } - - if (!listeningFromMe && key.fromMe) { - return; - } - - if (debounceTime && debounceTime > 0) { - this.processDebounce(content, remoteJid, debounceTime, async (debouncedContent) => { - await this.processDify( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - findDify, - session, - settings, - debouncedContent, - ); - }); - } else { - await this.processDify( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - findDify, - session, - settings, - content, - ); - } - - return; - } catch (error) { - this.logger.error(error); - return; - } - } - - public async createNewSession(instance: InstanceDto, data: any) { - try { - const session = await this.prismaRepository.difySession.create({ - data: { - remoteJid: data.remoteJid, - sessionId: data.remoteJid, - status: 'opened', - awaitUser: false, - difyId: data.difyId, - instanceId: instance.instanceId, - }, - }); - - return { session }; - } catch (error) { - this.logger.error(error); - return; - } - } - - private async initNewSession( - instance: any, - remoteJid: string, - dify: Dify, - settings: DifySetting, - session: DifySession, - content: string, - ) { - const data = await this.createNewSession(instance, { - remoteJid, - difyId: dify.id, - }); - - if (data.session) { - session = data.session; - } - - let endpoint: string = dify.apiUrl; - - if (dify.botType === 'chatBot') { - endpoint += '/chat-messages'; - const payload = { - inputs: {}, - query: content, - response_mode: 'blocking', - conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, - user: remoteJid, - }; - - await instance.client.presenceSubscribe(remoteJid); - - await instance.client.sendPresenceUpdate('composing', remoteJid); - - const response = await axios.post(endpoint, payload, { - headers: { - Authorization: `Bearer ${dify.apiKey}`, - }, - }); - - await instance.client.sendPresenceUpdate('paused', remoteJid); - - const message = response?.data?.answer; - - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - - await this.prismaRepository.difySession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: true, - sessionId: response?.data?.conversation_id, - }, - }); - - sendTelemetry('/message/sendText'); - - return; - } - - if (dify.botType === 'textGenerator') { - endpoint += '/completion-messages'; - const payload = { - inputs: { - query: content, - }, - response_mode: 'blocking', - conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, - user: remoteJid, - }; - - await instance.client.presenceSubscribe(remoteJid); - - await instance.client.sendPresenceUpdate('composing', remoteJid); - - const response = await axios.post(endpoint, payload, { - headers: { - Authorization: `Bearer ${dify.apiKey}`, - }, - }); - - await instance.client.sendPresenceUpdate('paused', remoteJid); - - const message = response?.data?.answer; - - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - - await this.prismaRepository.difySession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: true, - sessionId: response?.data?.conversation_id, - }, - }); - - sendTelemetry('/message/sendText'); - - return; - } - - if (dify.botType === 'agent') { - endpoint += '/chat-messages'; - const payload = { - inputs: {}, - query: content, - response_mode: 'streaming', - conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, - user: remoteJid, - }; - - await instance.client.presenceSubscribe(remoteJid); - - await instance.client.sendPresenceUpdate('composing', remoteJid); - - const response = await axios.post(endpoint, payload, { - headers: { - Authorization: `Bearer ${dify.apiKey}`, - }, - responseType: 'stream', - }); - - let completeMessage = ''; - - const stream = response.data; - const reader = new Readable().wrap(stream); - - reader.on('data', (chunk) => { - const data = chunk.toString(); - - try { - const event = JSON.parse(data); - if (event.event === 'agent_message') { - completeMessage += event.answer; - - console.log('completeMessage:', completeMessage); - } - } catch (error) { - console.error('Error parsing stream data:', error); - } - }); - - reader.on('end', async () => { - await instance.client.sendPresenceUpdate('paused', remoteJid); - - const message = response?.data?.answer; - - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - - await this.prismaRepository.difySession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: true, - sessionId: response?.data?.conversation_id, - }, - }); - - sendTelemetry('/message/sendText'); - }); - - reader.on('error', (error) => { - console.error('Error reading stream:', error); - }); - - return; - } - - if (dify.botType === 'workflow') { - endpoint += '/workflows/run'; - const payload = { - inputs: { - query: content, - }, - response_mode: 'blocking', - user: remoteJid, - }; - - await instance.client.presenceSubscribe(remoteJid); - - await instance.client.sendPresenceUpdate('composing', remoteJid); - - const response = await axios.post(endpoint, payload, { - headers: { - Authorization: `Bearer ${dify.apiKey}`, - }, - }); - - await instance.client.sendPresenceUpdate('paused', remoteJid); - - const message = response?.data?.data.outputs.text; - - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - - if (settings.keepOpen) { - await this.prismaRepository.difySession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.difySession.delete({ - where: { - id: session.id, - }, - }); - } - - sendTelemetry('/message/sendText'); - - return; - } - - return; - } - - private async processDify( - instance: any, - remoteJid: string, - dify: Dify, - session: DifySession, - settings: DifySetting, - content: string, - ) { - if (session && session.status !== 'opened') { - return; - } - - if (session && settings.expire && settings.expire > 0) { - const now = Date.now(); - - const sessionUpdatedAt = new Date(session.updatedAt).getTime(); - - const diff = now - sessionUpdatedAt; - - const diffInMinutes = Math.floor(diff / 1000 / 60); - - if (diffInMinutes > settings.expire) { - if (settings.keepOpen) { - await this.prismaRepository.difySession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.difySession.deleteMany({ - where: { - difyId: dify.id, - remoteJid: remoteJid, - }, - }); - } - - await this.initNewSession(instance, remoteJid, dify, settings, session, content); - return; - } - } - - if (!session) { - await this.initNewSession(instance, remoteJid, dify, settings, session, content); - return; - } - - await this.prismaRepository.difySession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: false, - }, - }); - - if (!content) { - if (settings.unknownMessage) { - this.waMonitor.waInstances[instance.instanceName].textMessage( - { - number: remoteJid.split('@')[0], - delay: settings.delayMessage || 1000, - text: settings.unknownMessage, - }, - false, - ); - - sendTelemetry('/message/sendText'); - } - return; - } - - if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) { - if (settings.keepOpen) { - await this.prismaRepository.difySession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.difySession.deleteMany({ - where: { - difyId: dify.id, - remoteJid: remoteJid, - }, - }); - } - return; - } - - let endpoint: string = dify.apiUrl; - - if (dify.botType === 'chatBot') { - endpoint += '/chat-messages'; - const payload = { - inputs: {}, - query: content, - response_mode: 'blocking', - conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, - user: remoteJid, - }; - - await instance.client.presenceSubscribe(remoteJid); - - await instance.client.sendPresenceUpdate('composing', remoteJid); - - const response = await axios.post(endpoint, payload, { - headers: { - Authorization: `Bearer ${dify.apiKey}`, - }, - }); - - await instance.client.sendPresenceUpdate('paused', remoteJid); - - const message = response?.data?.answer; - - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - - await this.prismaRepository.difySession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: true, - sessionId: response?.data?.conversation_id, - }, - }); - - sendTelemetry('/message/sendText'); - - return; - } - - if (dify.botType === 'textGenerator') { - endpoint += '/completion-messages'; - const payload = { - inputs: { - query: content, - }, - response_mode: 'blocking', - conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, - user: remoteJid, - }; - - await instance.client.presenceSubscribe(remoteJid); - - await instance.client.sendPresenceUpdate('composing', remoteJid); - - const response = await axios.post(endpoint, payload, { - headers: { - Authorization: `Bearer ${dify.apiKey}`, - }, - }); - - await instance.client.sendPresenceUpdate('paused', remoteJid); - - const message = response?.data?.answer; - - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - - await this.prismaRepository.difySession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: true, - sessionId: response?.data?.conversation_id, - }, - }); - - sendTelemetry('/message/sendText'); - - return; - } - - if (dify.botType === 'agent') { - endpoint += '/chat-messages'; - const payload = { - inputs: {}, - query: content, - response_mode: 'streaming', - conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, - user: remoteJid, - }; - - await instance.client.presenceSubscribe(remoteJid); - - await instance.client.sendPresenceUpdate('composing', remoteJid); - - const response = await axios.post(endpoint, payload, { - headers: { - Authorization: `Bearer ${dify.apiKey}`, - }, - responseType: 'stream', - }); - - let completeMessage = ''; - - const stream = response.data; - const reader = new Readable().wrap(stream); - - reader.on('data', (chunk) => { - const data = chunk.toString(); - const lines = data.split('\n'); - - lines.forEach((line) => { - if (line.startsWith('data: ')) { - const jsonString = line.substring(6); - try { - const event = JSON.parse(jsonString); - if (event.event === 'agent_message') { - completeMessage += event.answer; - } - } catch (error) { - console.error('Error parsing stream data:', error); - } - } - }); - }); - - reader.on('end', async () => { - await instance.client.sendPresenceUpdate('paused', remoteJid); - - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: completeMessage, - }, - false, - ); - - await this.prismaRepository.difySession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: true, - sessionId: response?.data?.conversation_id, - }, - }); - - sendTelemetry('/message/sendText'); - }); - - reader.on('error', (error) => { - console.error('Error reading stream:', error); - }); - - return; - } - - if (dify.botType === 'workflow') { - endpoint += '/workflows/run'; - const payload = { - inputs: { - query: content, - }, - response_mode: 'blocking', - conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, - user: remoteJid, - }; - - await instance.client.presenceSubscribe(remoteJid); - - await instance.client.sendPresenceUpdate('composing', remoteJid); - - const response = await axios.post(endpoint, payload, { - headers: { - Authorization: `Bearer ${dify.apiKey}`, - }, - }); - - await instance.client.sendPresenceUpdate('paused', remoteJid); - - const message = response?.data?.data.outputs.text; - - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - - if (settings.keepOpen) { - await this.prismaRepository.difySession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.difySession.delete({ - where: { - id: session.id, - }, - }); - } - - sendTelemetry('/message/sendText'); - - return; - } - - return; - } -} diff --git a/src/api/integrations/event/event.controller.ts b/src/api/integrations/event/event.controller.ts new file mode 100644 index 00000000..220f60f1 --- /dev/null +++ b/src/api/integrations/event/event.controller.ts @@ -0,0 +1,154 @@ +import { EventDto } from '@api/integrations/event/event.dto'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { wa } from '@api/types/wa.types'; + +export type EmitData = { + instanceName: string; + origin: string; + event: string; + data: Object; + serverUrl: string; + dateTime: string; + sender: string; + apiKey?: string; + local?: boolean; +}; + +export interface EventControllerInterface { + set(instanceName: string, data: any): Promise; + get(instanceName: string): Promise; + emit({ instanceName, origin, event, data, serverUrl, dateTime, sender, apiKey, local }: EmitData): Promise; +} + +export class EventController { + private prismaRepository: PrismaRepository; + private waMonitor: WAMonitoringService; + private integrationStatus: boolean; + private integrationName: string; + + constructor( + prismaRepository: PrismaRepository, + waMonitor: WAMonitoringService, + integrationStatus: boolean, + integrationName: string, + ) { + this.prisma = prismaRepository; + this.monitor = waMonitor; + this.status = integrationStatus; + this.name = integrationName; + } + + public set prisma(prisma: PrismaRepository) { + this.prismaRepository = prisma; + } + + public get prisma() { + return this.prismaRepository; + } + + public set monitor(waMonitor: WAMonitoringService) { + this.waMonitor = waMonitor; + } + + public get monitor() { + return this.waMonitor; + } + + public set name(name: string) { + this.integrationName = name; + } + + public get name() { + return this.integrationName; + } + + public set status(status: boolean) { + this.integrationStatus = status; + } + + public get status() { + return this.integrationStatus; + } + + public async set(instanceName: string, data: EventDto): Promise { + if (!this.status) { + return; + } + + if (!data[this.name]?.enabled) { + data[this.name].events = []; + } else { + if (0 === data[this.name].events.length) { + data[this.name].events = EventController.events; + } + } + + return this.prisma[this.name].upsert({ + where: { + instanceId: this.monitor.waInstances[instanceName].instanceId, + }, + update: { + enabled: data[this.name]?.enabled, + events: data[this.name].events, + }, + create: { + enabled: data[this.name]?.enabled, + events: data[this.name].events, + instanceId: this.monitor.waInstances[instanceName].instanceId, + }, + }); + } + + public async get(instanceName: string): Promise { + if (!this.status) { + return; + } + + if (undefined === this.monitor.waInstances[instanceName]) { + return null; + } + + const data = await this.prisma[this.name].findUnique({ + where: { + instanceId: this.monitor.waInstances[instanceName].instanceId, + }, + }); + + if (!data) { + return null; + } + + return data; + } + + public static readonly events = [ + 'APPLICATION_STARTUP', + 'QRCODE_UPDATED', + 'MESSAGES_SET', + 'MESSAGES_UPSERT', + 'MESSAGES_EDITED', + 'MESSAGES_UPDATE', + 'MESSAGES_DELETE', + 'SEND_MESSAGE', + 'CONTACTS_SET', + 'CONTACTS_UPSERT', + 'CONTACTS_UPDATE', + 'PRESENCE_UPDATE', + 'CHATS_SET', + 'CHATS_UPSERT', + 'CHATS_UPDATE', + 'CHATS_DELETE', + 'GROUPS_UPSERT', + 'GROUP_UPDATE', + 'GROUP_PARTICIPANTS_UPDATE', + 'CONNECTION_UPDATE', + 'LABELS_EDIT', + 'LABELS_ASSOCIATION', + 'CALL', + 'TYPEBOT_START', + 'TYPEBOT_CHANGE_STATUS', + 'REMOVE_INSTANCE', + 'LOGOUT_INSTANCE', + ]; +} diff --git a/src/api/integrations/event/event.dto.ts b/src/api/integrations/event/event.dto.ts new file mode 100644 index 00000000..e9388482 --- /dev/null +++ b/src/api/integrations/event/event.dto.ts @@ -0,0 +1,56 @@ +import { Constructor } from '@api/integrations/integration.dto'; +import { JsonValue } from '@prisma/client/runtime/library'; + +export class EventDto { + webhook?: { + enabled?: boolean; + events?: string[]; + url?: string; + headers?: JsonValue; + byEvents?: boolean; + base64?: boolean; + }; + + websocket?: { + enabled?: boolean; + events?: string[]; + }; + + sqs?: { + enabled?: boolean; + events?: string[]; + }; + + rabbitmq?: { + enabled?: boolean; + events?: string[]; + }; +} + +export function EventInstanceMixin(Base: TBase) { + return class extends Base { + webhook?: { + enabled?: boolean; + events?: string[]; + headers?: JsonValue; + url?: string; + byEvents?: boolean; + base64?: boolean; + }; + + websocket?: { + enabled?: boolean; + events?: string[]; + }; + + sqs?: { + enabled?: boolean; + events?: string[]; + }; + + rabbitmq?: { + enabled?: boolean; + events?: string[]; + }; + }; +} diff --git a/src/api/integrations/event/event.manager.ts b/src/api/integrations/event/event.manager.ts new file mode 100644 index 00000000..75daad69 --- /dev/null +++ b/src/api/integrations/event/event.manager.ts @@ -0,0 +1,135 @@ +import { RabbitmqController } from '@api/integrations/event/rabbitmq/rabbitmq.controller'; +import { SqsController } from '@api/integrations/event/sqs/sqs.controller'; +import { WebhookController } from '@api/integrations/event/webhook/webhook.controller'; +import { WebsocketController } from '@api/integrations/event/websocket/websocket.controller'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Server } from 'http'; + +export class EventManager { + private prismaRepository: PrismaRepository; + private waMonitor: WAMonitoringService; + private websocketController: WebsocketController; + private webhookController: WebhookController; + private rabbitmqController: RabbitmqController; + private sqsController: SqsController; + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + this.prisma = prismaRepository; + this.monitor = waMonitor; + + this.websocket = new WebsocketController(prismaRepository, waMonitor); + this.webhook = new WebhookController(prismaRepository, waMonitor); + this.rabbitmq = new RabbitmqController(prismaRepository, waMonitor); + this.sqs = new SqsController(prismaRepository, waMonitor); + } + + public set prisma(prisma: PrismaRepository) { + this.prismaRepository = prisma; + } + + public get prisma() { + return this.prismaRepository; + } + + public set monitor(waMonitor: WAMonitoringService) { + this.waMonitor = waMonitor; + } + + public get monitor() { + return this.waMonitor; + } + + public set websocket(websocket: WebsocketController) { + this.websocketController = websocket; + } + + public get websocket() { + return this.websocketController; + } + + public set webhook(webhook: WebhookController) { + this.webhookController = webhook; + } + + public get webhook() { + return this.webhookController; + } + + public set rabbitmq(rabbitmq: RabbitmqController) { + this.rabbitmqController = rabbitmq; + } + + public get rabbitmq() { + return this.rabbitmqController; + } + + public set sqs(sqs: SqsController) { + this.sqsController = sqs; + } + + public get sqs() { + return this.sqsController; + } + + public init(httpServer: Server): void { + this.websocket.init(httpServer); + this.rabbitmq.init(); + this.sqs.init(); + } + + public async emit(eventData: { + instanceName: string; + origin: string; + event: string; + data: Object; + serverUrl: string; + dateTime: string; + sender: string; + apiKey?: string; + local?: boolean; + }): Promise { + await this.websocket.emit(eventData); + await this.rabbitmq.emit(eventData); + await this.sqs.emit(eventData); + await this.webhook.emit(eventData); + } + + public async setInstance(instanceName: string, data: any): Promise { + if (data.websocket) + await this.websocket.set(instanceName, { + websocket: { + enabled: true, + events: data.websocket?.events, + }, + }); + + if (data.rabbitmq) + await this.rabbitmq.set(instanceName, { + rabbitmq: { + enabled: true, + events: data.rabbitmq?.events, + }, + }); + + if (data.sqs) + await this.sqs.set(instanceName, { + sqs: { + enabled: true, + events: data.sqs?.events, + }, + }); + + if (data.webhook) + await this.webhook.set(instanceName, { + webhook: { + enabled: true, + events: data.webhook?.events, + url: data.webhook?.url, + headers: data.webhook?.headers, + base64: data.webhook?.base64, + byEvents: data.webhook?.byEvents, + }, + }); + } +} diff --git a/src/api/integrations/event/event.router.ts b/src/api/integrations/event/event.router.ts new file mode 100644 index 00000000..77de221c --- /dev/null +++ b/src/api/integrations/event/event.router.ts @@ -0,0 +1,18 @@ +import { RabbitmqRouter } from '@api/integrations/event/rabbitmq/rabbitmq.router'; +import { SqsRouter } from '@api/integrations/event/sqs/sqs.router'; +import { WebhookRouter } from '@api/integrations/event/webhook/webhook.router'; +import { WebsocketRouter } from '@api/integrations/event/websocket/websocket.router'; +import { Router } from 'express'; + +export class EventRouter { + public readonly router: Router; + + constructor(configService: any, ...guards: any[]) { + this.router = Router(); + + this.router.use('/webhook', new WebhookRouter(configService, ...guards).router); + this.router.use('/websocket', new WebsocketRouter(...guards).router); + this.router.use('/rabbitmq', new RabbitmqRouter(...guards).router); + this.router.use('/sqs', new SqsRouter(...guards).router); + } +} diff --git a/src/api/integrations/event/event.schema.ts b/src/api/integrations/event/event.schema.ts new file mode 100644 index 00000000..9ea9fac2 --- /dev/null +++ b/src/api/integrations/event/event.schema.ts @@ -0,0 +1,39 @@ +import { JSONSchema7 } from 'json-schema'; +import { v4 } from 'uuid'; + +import { EventController } from './event.controller'; + +export * from '@api/integrations/event/webhook/webhook.schema'; + +export const eventSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + websocket: { + $ref: '#/$defs/event', + }, + rabbitmq: { + $ref: '#/$defs/event', + }, + sqs: { + $ref: '#/$defs/event', + }, + }, + $defs: { + event: { + type: 'object', + properties: { + enabled: { type: 'boolean', enum: [true, false] }, + events: { + type: 'array', + minItems: 0, + items: { + type: 'string', + enum: EventController.events, + }, + }, + }, + required: ['enabled'], + }, + }, +}; diff --git a/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts b/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts new file mode 100644 index 00000000..c4e0cc36 --- /dev/null +++ b/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts @@ -0,0 +1,224 @@ +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { configService, Log, Rabbitmq } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import * as amqp from 'amqplib/callback_api'; + +import { EmitData, EventController, EventControllerInterface } from '../event.controller'; + +export class RabbitmqController extends EventController implements EventControllerInterface { + public amqpChannel: amqp.Channel | null = null; + private readonly logger = new Logger('RabbitmqController'); + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + super(prismaRepository, waMonitor, configService.get('RABBITMQ')?.ENABLED, 'rabbitmq'); + } + + public async init(): Promise { + if (!this.status) { + return; + } + + await new Promise((resolve, reject) => { + const uri = configService.get('RABBITMQ').URI; + const rabbitmqExchangeName = configService.get('RABBITMQ').EXCHANGE_NAME; + + amqp.connect(uri, (error, connection) => { + if (error) { + reject(error); + + return; + } + + connection.createChannel((channelError, channel) => { + if (channelError) { + reject(channelError); + + return; + } + + const exchangeName = rabbitmqExchangeName; + + channel.assertExchange(exchangeName, 'topic', { + durable: true, + autoDelete: false, + }); + + this.amqpChannel = channel; + + this.logger.info('AMQP initialized'); + + resolve(); + }); + }); + }).then(() => { + if (configService.get('RABBITMQ')?.GLOBAL_ENABLED) this.initGlobalQueues(); + }); + } + + private set channel(channel: amqp.Channel) { + this.amqpChannel = channel; + } + + public get channel(): amqp.Channel { + return this.amqpChannel; + } + + public async emit({ + instanceName, + origin, + event, + data, + serverUrl, + dateTime, + sender, + apiKey, + }: EmitData): Promise { + if (!this.status) { + return; + } + + const instanceRabbitmq = await this.get(instanceName); + const rabbitmqLocal = instanceRabbitmq?.events; + const rabbitmqGlobal = configService.get('RABBITMQ').GLOBAL_ENABLED; + const rabbitmqEvents = configService.get('RABBITMQ').EVENTS; + const rabbitmqExchangeName = configService.get('RABBITMQ').EXCHANGE_NAME; + const we = event.replace(/[.-]/gm, '_').toUpperCase(); + const logEnabled = configService.get('LOG').LEVEL.includes('WEBHOOKS'); + + const message = { + event, + instance: instanceName, + data, + server_url: serverUrl, + date_time: dateTime, + sender, + apikey: apiKey, + }; + + if (instanceRabbitmq?.enabled && this.amqpChannel) { + if (Array.isArray(rabbitmqLocal) && rabbitmqLocal.includes(we)) { + const exchangeName = instanceName ?? rabbitmqExchangeName; + + let retry = 0; + + while (retry < 3) { + try { + await this.amqpChannel.assertExchange(exchangeName, 'topic', { + durable: true, + autoDelete: false, + }); + + const eventName = event.replace(/_/g, '.').toLowerCase(); + + const queueName = `${instanceName}.${eventName}`; + + await this.amqpChannel.assertQueue(queueName, { + durable: true, + autoDelete: false, + arguments: { + 'x-queue-type': 'quorum', + }, + }); + + await this.amqpChannel.bindQueue(queueName, exchangeName, eventName); + + await this.amqpChannel.publish(exchangeName, event, Buffer.from(JSON.stringify(message))); + + if (logEnabled) { + const logData = { + local: `${origin}.sendData-RabbitMQ`, + ...message, + }; + + this.logger.log(logData); + } + + break; + } catch (error) { + retry++; + } + } + } + } + + if (rabbitmqGlobal && rabbitmqEvents[we] && this.amqpChannel) { + const exchangeName = rabbitmqExchangeName; + + let retry = 0; + + while (retry < 3) { + try { + await this.amqpChannel.assertExchange(exchangeName, 'topic', { + durable: true, + autoDelete: false, + }); + + const queueName = event; + + await this.amqpChannel.assertQueue(queueName, { + durable: true, + autoDelete: false, + arguments: { + 'x-queue-type': 'quorum', + }, + }); + + await this.amqpChannel.bindQueue(queueName, exchangeName, event); + + await this.amqpChannel.publish(exchangeName, event, Buffer.from(JSON.stringify(message))); + + if (logEnabled) { + const logData = { + local: `${origin}.sendData-RabbitMQ-Global`, + ...message, + }; + + this.logger.log(logData); + } + + break; + } catch (error) { + retry++; + } + } + } + } + + private async initGlobalQueues(): Promise { + this.logger.info('Initializing global queues'); + + const rabbitmqExchangeName = configService.get('RABBITMQ').EXCHANGE_NAME; + const events = configService.get('RABBITMQ').EVENTS; + + if (!events) { + this.logger.warn('No events to initialize on AMQP'); + + return; + } + + const eventKeys = Object.keys(events); + + eventKeys.forEach((event) => { + if (events[event] === false) return; + + const queueName = `${event.replace(/_/g, '.').toLowerCase()}`; + const exchangeName = rabbitmqExchangeName; + + this.amqpChannel.assertExchange(exchangeName, 'topic', { + durable: true, + autoDelete: false, + }); + + this.amqpChannel.assertQueue(queueName, { + durable: true, + autoDelete: false, + arguments: { + 'x-queue-type': 'quorum', + }, + }); + + this.amqpChannel.bindQueue(queueName, exchangeName, event); + }); + } +} diff --git a/src/api/integrations/event/rabbitmq/rabbitmq.router.ts b/src/api/integrations/event/rabbitmq/rabbitmq.router.ts new file mode 100644 index 00000000..997e1ca2 --- /dev/null +++ b/src/api/integrations/event/rabbitmq/rabbitmq.router.ts @@ -0,0 +1,36 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { EventDto } from '@api/integrations/event/event.dto'; +import { HttpStatus } from '@api/routes/index.router'; +import { eventManager } from '@api/server.module'; +import { eventSchema, instanceSchema } from '@validate/validate.schema'; +import { RequestHandler, Router } from 'express'; + +export class RabbitmqRouter extends RouterBroker { + constructor(...guards: RequestHandler[]) { + super(); + this.router + .post(this.routerPath('set'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: eventSchema, + ClassRef: EventDto, + execute: (instance, data) => eventManager.rabbitmq.set(instance.instanceName, data), + }); + + res.status(HttpStatus.CREATED).json(response); + }) + .get(this.routerPath('find'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => eventManager.rabbitmq.get(instance.instanceName), + }); + + res.status(HttpStatus.OK).json(response); + }); + } + + public readonly router: Router = Router(); +} diff --git a/src/api/integrations/event/sqs/sqs.controller.ts b/src/api/integrations/event/sqs/sqs.controller.ts new file mode 100644 index 00000000..3c94fe81 --- /dev/null +++ b/src/api/integrations/event/sqs/sqs.controller.ts @@ -0,0 +1,185 @@ +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { SQS } from '@aws-sdk/client-sqs'; +import { configService, Log, Sqs } from '@config/env.config'; +import { Logger } from '@config/logger.config'; + +import { EmitData, EventController, EventControllerInterface } from '../event.controller'; + +export class SqsController extends EventController implements EventControllerInterface { + private sqs: SQS; + private readonly logger = new Logger('SqsController'); + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + super(prismaRepository, waMonitor, configService.get('SQS')?.ENABLED, 'sqs'); + } + + public init(): void { + if (!this.status) { + return; + } + + new Promise((resolve) => { + const awsConfig = configService.get('SQS'); + + this.sqs = new SQS({ + credentials: { + accessKeyId: awsConfig.ACCESS_KEY_ID, + secretAccessKey: awsConfig.SECRET_ACCESS_KEY, + }, + + region: awsConfig.REGION, + }); + + this.logger.info('SQS initialized'); + + resolve(); + }); + } + + private set channel(sqs: SQS) { + this.sqs = sqs; + } + + public get channel(): SQS { + return this.sqs; + } + + public async emit({ + instanceName, + origin, + event, + data, + serverUrl, + dateTime, + sender, + apiKey, + }: EmitData): Promise { + if (!this.status) { + return; + } + + const instanceSqs = await this.get(instanceName); + const sqsLocal = instanceSqs?.events; + const we = event.replace(/[.-]/gm, '_').toUpperCase(); + + if (instanceSqs?.enabled) { + if (this.sqs) { + if (Array.isArray(sqsLocal) && sqsLocal.includes(we)) { + const eventFormatted = `${event.replace('.', '_').toLowerCase()}`; + const queueName = `${instanceName}_${eventFormatted}.fifo`; + const sqsConfig = configService.get('SQS'); + const sqsUrl = `https://sqs.${sqsConfig.REGION}.amazonaws.com/${sqsConfig.ACCOUNT_ID}/${queueName}`; + + const message = { + event, + instance: instanceName, + data, + server_url: serverUrl, + date_time: dateTime, + sender, + apikey: apiKey, + }; + + const params = { + MessageBody: JSON.stringify(message), + MessageGroupId: 'evolution', + MessageDeduplicationId: `${instanceName}_${eventFormatted}_${Date.now()}`, + QueueUrl: sqsUrl, + }; + + this.sqs.sendMessage(params, (err) => { + if (err) { + this.logger.error({ + local: `${origin}.sendData-SQS`, + message: err?.message, + hostName: err?.hostname, + code: err?.code, + stack: err?.stack, + name: err?.name, + url: queueName, + server_url: serverUrl, + }); + } else { + if (configService.get('LOG').LEVEL.includes('WEBHOOKS')) { + const logData = { + local: `${origin}.sendData-SQS`, + ...message, + }; + + this.logger.log(logData); + } + } + }); + } + } + } + } + + public async initQueues(instanceName: string, events: string[]) { + if (!events || !events.length) return; + + const queues = events.map((event) => { + return `${event.replace(/_/g, '_').toLowerCase()}`; + }); + + queues.forEach((event) => { + const queueName = `${instanceName}_${event}.fifo`; + + this.sqs.createQueue( + { + QueueName: queueName, + Attributes: { + FifoQueue: 'true', + }, + }, + (err, data) => { + if (err) { + this.logger.error(`Error creating queue ${queueName}: ${err.message}`); + } else { + this.logger.info(`Queue ${queueName} created: ${data.QueueUrl}`); + } + }, + ); + }); + } + + public async removeQueues(instanceName: string, events: any) { + const eventsArray = Array.isArray(events) ? events.map((event) => String(event)) : []; + if (!events || !eventsArray.length) return; + + const queues = eventsArray.map((event) => { + return `${event.replace(/_/g, '_').toLowerCase()}`; + }); + + queues.forEach((event) => { + const queueName = `${instanceName}_${event}.fifo`; + + this.sqs.getQueueUrl( + { + QueueName: queueName, + }, + (err, data) => { + if (err) { + this.logger.error(`Error getting queue URL for ${queueName}: ${err.message}`); + } else { + const queueUrl = data.QueueUrl; + + this.sqs.deleteQueue( + { + QueueUrl: queueUrl, + }, + (deleteErr) => { + if (deleteErr) { + this.logger.error(`Error deleting queue ${queueName}: ${deleteErr.message}`); + } else { + this.logger.info(`Queue ${queueName} deleted`); + } + }, + ); + } + }, + ); + }); + } +} diff --git a/src/api/integrations/event/sqs/sqs.router.ts b/src/api/integrations/event/sqs/sqs.router.ts new file mode 100644 index 00000000..23f63f85 --- /dev/null +++ b/src/api/integrations/event/sqs/sqs.router.ts @@ -0,0 +1,36 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { EventDto } from '@api/integrations/event/event.dto'; +import { HttpStatus } from '@api/routes/index.router'; +import { eventManager } from '@api/server.module'; +import { eventSchema, instanceSchema } from '@validate/validate.schema'; +import { RequestHandler, Router } from 'express'; + +export class SqsRouter extends RouterBroker { + constructor(...guards: RequestHandler[]) { + super(); + this.router + .post(this.routerPath('set'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: eventSchema, + ClassRef: EventDto, + execute: (instance, data) => eventManager.sqs.set(instance.instanceName, data), + }); + + res.status(HttpStatus.CREATED).json(response); + }) + .get(this.routerPath('find'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => eventManager.sqs.get(instance.instanceName), + }); + + res.status(HttpStatus.OK).json(response); + }); + } + + public readonly router: Router = Router(); +} diff --git a/src/api/integrations/event/webhook/webhook.controller.ts b/src/api/integrations/event/webhook/webhook.controller.ts new file mode 100644 index 00000000..2fcf6c44 --- /dev/null +++ b/src/api/integrations/event/webhook/webhook.controller.ts @@ -0,0 +1,179 @@ +import { EventDto } from '@api/integrations/event/event.dto'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { wa } from '@api/types/wa.types'; +import { configService, Log, Webhook } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { BadRequestException } from '@exceptions'; +import axios from 'axios'; +import { isURL } from 'class-validator'; + +import { EmitData, EventController, EventControllerInterface } from '../event.controller'; + +export class WebhookController extends EventController implements EventControllerInterface { + private readonly logger = new Logger('WebhookController'); + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + super(prismaRepository, waMonitor, true, 'webhook'); + } + + override async set(instanceName: string, data: EventDto): Promise { + if (!isURL(data.webhook.url, { require_tld: false })) { + throw new BadRequestException('Invalid "url" property'); + } + + if (!data.webhook?.enabled) { + data.webhook.events = []; + } else { + if (0 === data.webhook.events.length) { + data.webhook.events = EventController.events; + } + } + + return this.prisma.webhook.upsert({ + where: { + instanceId: this.monitor.waInstances[instanceName].instanceId, + }, + update: { + enabled: data.webhook?.enabled, + events: data.webhook?.events, + url: data.webhook?.url, + headers: data.webhook?.headers, + webhookBase64: data.webhook.base64, + webhookByEvents: data.webhook.byEvents, + }, + create: { + enabled: data.webhook?.enabled, + events: data.webhook?.events, + instanceId: this.monitor.waInstances[instanceName].instanceId, + url: data.webhook?.url, + headers: data.webhook?.headers, + webhookBase64: data.webhook.base64, + webhookByEvents: data.webhook.byEvents, + }, + }); + } + + public async emit({ + instanceName, + origin, + event, + data, + serverUrl, + dateTime, + sender, + apiKey, + local, + }: EmitData): Promise { + const instance = (await this.get(instanceName)) as wa.LocalWebHook; + + if (!instance || !instance?.enabled) { + return; + } + + const webhookConfig = configService.get('WEBHOOK'); + const webhookLocal = instance?.events; + const webhookHeaders = instance?.headers; + const we = event.replace(/[.-]/gm, '_').toUpperCase(); + const transformedWe = we.replace(/_/gm, '-').toLowerCase(); + const enabledLog = configService.get('LOG').LEVEL.includes('WEBHOOKS'); + + const webhookData = { + event, + instance: instanceName, + data, + destination: instance?.url, + date_time: dateTime, + sender, + server_url: serverUrl, + apikey: apiKey, + }; + + if (local) { + if (Array.isArray(webhookLocal) && webhookLocal.includes(we)) { + let baseURL: string; + + if (instance?.webhookByEvents) { + baseURL = `${instance?.url}/${transformedWe}`; + } else { + baseURL = instance?.url; + } + + if (enabledLog) { + const logData = { + local: `${origin}.sendData-Webhook`, + url: baseURL, + ...webhookData, + }; + + this.logger.log(logData); + } + + try { + if (instance?.enabled && isURL(instance.url, { require_tld: false })) { + const httpService = axios.create({ + baseURL, + headers: webhookHeaders as Record | undefined, + }); + + await httpService.post('', webhookData); + } + } catch (error) { + this.logger.error({ + local: `${origin}.sendData-Webhook`, + message: error?.message, + hostName: error?.hostname, + syscall: error?.syscall, + code: error?.code, + error: error?.errno, + stack: error?.stack, + name: error?.name, + url: baseURL, + server_url: serverUrl, + }); + } + } + } + + if (webhookConfig.GLOBAL?.ENABLED) { + if (webhookConfig.EVENTS[we]) { + let globalURL = webhookConfig.GLOBAL.URL; + + if (webhookConfig.GLOBAL.WEBHOOK_BY_EVENTS) { + globalURL = `${globalURL}/${transformedWe}`; + } + + if (enabledLog) { + const logData = { + local: `${origin}.sendData-Webhook-Global`, + url: globalURL, + ...webhookData, + }; + + this.logger.log(logData); + } + + try { + if (isURL(globalURL)) { + const httpService = axios.create({ baseURL: globalURL }); + + await httpService.post('', webhookData); + } + } catch (error) { + this.logger.error({ + local: `${origin}.sendData-Webhook-Global`, + message: error?.message, + hostName: error?.hostname, + syscall: error?.syscall, + code: error?.code, + error: error?.errno, + stack: error?.stack, + name: error?.name, + url: globalURL, + server_url: serverUrl, + }); + } + } + } + } +} diff --git a/src/api/integrations/event/webhook/webhook.router.ts b/src/api/integrations/event/webhook/webhook.router.ts new file mode 100644 index 00000000..5193bec5 --- /dev/null +++ b/src/api/integrations/event/webhook/webhook.router.ts @@ -0,0 +1,37 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { EventDto } from '@api/integrations/event/event.dto'; +import { HttpStatus } from '@api/routes/index.router'; +import { eventManager } from '@api/server.module'; +import { ConfigService } from '@config/env.config'; +import { instanceSchema, webhookSchema } from '@validate/validate.schema'; +import { RequestHandler, Router } from 'express'; + +export class WebhookRouter extends RouterBroker { + constructor(readonly configService: ConfigService, ...guards: RequestHandler[]) { + super(); + this.router + .post(this.routerPath('set'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: webhookSchema, + ClassRef: EventDto, + execute: (instance, data) => eventManager.webhook.set(instance.instanceName, data), + }); + + res.status(HttpStatus.CREATED).json(response); + }) + .get(this.routerPath('find'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => eventManager.webhook.get(instance.instanceName), + }); + + res.status(HttpStatus.OK).json(response); + }); + } + + public readonly router: Router = Router(); +} diff --git a/src/api/integrations/event/webhook/webhook.schema.ts b/src/api/integrations/event/webhook/webhook.schema.ts new file mode 100644 index 00000000..5d0f3724 --- /dev/null +++ b/src/api/integrations/event/webhook/webhook.schema.ts @@ -0,0 +1,51 @@ +import { JSONSchema7 } from 'json-schema'; +import { v4 } from 'uuid'; + +import { EventController } from '../event.controller'; + +const isNotEmpty = (...propertyNames: string[]): JSONSchema7 => { + const properties = {}; + propertyNames.forEach( + (property) => + (properties[property] = { + minLength: 1, + description: `The "${property}" cannot be empty`, + }), + ); + return { + if: { + propertyNames: { + enum: [...propertyNames], + }, + }, + then: { properties }, + }; +}; + +export const webhookSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + webhook: { + type: 'object', + properties: { + enabled: { type: 'boolean' }, + url: { type: 'string' }, + headers: { type: 'object' }, + byEvents: { type: 'boolean' }, + base64: { type: 'boolean' }, + events: { + type: 'array', + minItems: 0, + items: { + type: 'string', + enum: EventController.events, + }, + }, + }, + required: ['enabled', 'url'], + ...isNotEmpty('enabled', 'url'), + }, + }, + required: ['webhook'], +}; diff --git a/src/api/integrations/event/websocket/websocket.controller.ts b/src/api/integrations/event/websocket/websocket.controller.ts new file mode 100644 index 00000000..e7dab1df --- /dev/null +++ b/src/api/integrations/event/websocket/websocket.controller.ts @@ -0,0 +1,119 @@ +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { configService, Cors, Log, Websocket } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { Server } from 'http'; +import { Server as SocketIO } from 'socket.io'; + +import { EmitData, EventController, EventControllerInterface } from '../event.controller'; + +export class WebsocketController extends EventController implements EventControllerInterface { + private io: SocketIO; + private corsConfig: Array; + private readonly logger = new Logger('WebsocketController'); + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + super(prismaRepository, waMonitor, configService.get('WEBSOCKET')?.ENABLED, 'websocket'); + + this.cors = configService.get('CORS').ORIGIN; + } + + public init(httpServer: Server): void { + if (!this.status) { + return; + } + + this.socket = new SocketIO(httpServer, { + cors: { + origin: this.cors, + }, + }); + + this.socket.on('connection', (socket) => { + this.logger.info('User connected'); + + socket.on('disconnect', () => { + this.logger.info('User disconnected'); + }); + }); + + this.logger.info('Socket.io initialized'); + } + + private set cors(cors: Array) { + this.corsConfig = cors; + } + + private get cors(): string | Array { + return this.corsConfig?.includes('*') ? '*' : this.corsConfig; + } + + private set socket(socket: SocketIO) { + this.io = socket; + } + + public get socket(): SocketIO { + return this.io; + } + + public async emit({ + instanceName, + origin, + event, + data, + serverUrl, + dateTime, + sender, + apiKey, + }: EmitData): Promise { + if (!this.status) { + return; + } + + const configEv = event.replace(/[.-]/gm, '_').toUpperCase(); + const logEnabled = configService.get('LOG').LEVEL.includes('WEBSOCKET'); + const message = { + event, + instance: instanceName, + data, + server_url: serverUrl, + date_time: dateTime, + sender, + apikey: apiKey, + }; + + if (configService.get('WEBSOCKET')?.GLOBAL_EVENTS) { + this.socket.emit(event, message); + + if (logEnabled) { + this.logger.log({ + local: `${origin}.sendData-WebsocketGlobal`, + ...message, + }); + } + } + + try { + const instance = await this.get(instanceName); + + if (!instance?.enabled) { + return; + } + + if (Array.isArray(instance?.events) && instance?.events.includes(configEv)) { + this.socket.of(`/${instanceName}`).emit(event, message); + + if (logEnabled) { + this.logger.log({ + local: `${origin}.sendData-Websocket`, + ...message, + }); + } + } + } catch (err) { + if (logEnabled) { + this.logger.log(err); + } + } + } +} diff --git a/src/api/integrations/event/websocket/websocket.router.ts b/src/api/integrations/event/websocket/websocket.router.ts new file mode 100644 index 00000000..4271245f --- /dev/null +++ b/src/api/integrations/event/websocket/websocket.router.ts @@ -0,0 +1,36 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { EventDto } from '@api/integrations/event/event.dto'; +import { HttpStatus } from '@api/routes/index.router'; +import { eventManager } from '@api/server.module'; +import { eventSchema, instanceSchema } from '@validate/validate.schema'; +import { RequestHandler, Router } from 'express'; + +export class WebsocketRouter extends RouterBroker { + constructor(...guards: RequestHandler[]) { + super(); + this.router + .post(this.routerPath('set'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: eventSchema, + ClassRef: EventDto, + execute: (instance, data) => eventManager.websocket.set(instance.instanceName, data), + }); + + res.status(HttpStatus.CREATED).json(response); + }) + .get(this.routerPath('find'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => eventManager.websocket.get(instance.instanceName), + }); + + res.status(HttpStatus.OK).json(response); + }); + } + + public readonly router: Router = Router(); +} diff --git a/src/api/integrations/integration.dto.ts b/src/api/integrations/integration.dto.ts new file mode 100644 index 00000000..743364c5 --- /dev/null +++ b/src/api/integrations/integration.dto.ts @@ -0,0 +1,6 @@ +import { ChatwootInstanceMixin } from '@api/integrations/chatbot/chatwoot/dto/chatwoot.dto'; +import { EventInstanceMixin } from '@api/integrations/event/event.dto'; + +export type Constructor = new (...args: any[]) => T; + +export class IntegrationDto extends EventInstanceMixin(ChatwootInstanceMixin(class {})) {} diff --git a/src/api/integrations/openai/controllers/openai.controller.ts b/src/api/integrations/openai/controllers/openai.controller.ts deleted file mode 100644 index 2ba5e91b..00000000 --- a/src/api/integrations/openai/controllers/openai.controller.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { configService, Openai } from '../../../../config/env.config'; -import { BadRequestException } from '../../../../exceptions'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { OpenaiCredsDto, OpenaiDto, OpenaiIgnoreJidDto } from '../dto/openai.dto'; -import { OpenaiService } from '../services/openai.service'; - -export class OpenaiController { - constructor(private readonly openaiService: OpenaiService) {} - - public async createOpenaiCreds(instance: InstanceDto, data: OpenaiCredsDto) { - if (!configService.get('OPENAI').ENABLED) throw new BadRequestException('Openai is disabled'); - - return this.openaiService.createCreds(instance, data); - } - - public async findOpenaiCreds(instance: InstanceDto) { - if (!configService.get('OPENAI').ENABLED) throw new BadRequestException('Openai is disabled'); - - return this.openaiService.findCreds(instance); - } - - public async deleteCreds(instance: InstanceDto, openaiCredsId: string) { - if (!configService.get('OPENAI').ENABLED) throw new BadRequestException('Openai is disabled'); - - return this.openaiService.deleteCreds(instance, openaiCredsId); - } - - public async createOpenai(instance: InstanceDto, data: OpenaiDto) { - if (!configService.get('OPENAI').ENABLED) throw new BadRequestException('Openai is disabled'); - - return this.openaiService.create(instance, data); - } - - public async findOpenai(instance: InstanceDto) { - if (!configService.get('OPENAI').ENABLED) throw new BadRequestException('Openai is disabled'); - - return this.openaiService.find(instance); - } - - public async fetchOpenai(instance: InstanceDto, openaiBotId: string) { - if (!configService.get('OPENAI').ENABLED) throw new BadRequestException('Openai is disabled'); - - return this.openaiService.fetch(instance, openaiBotId); - } - - public async updateOpenai(instance: InstanceDto, openaiBotId: string, data: OpenaiDto) { - if (!configService.get('OPENAI').ENABLED) throw new BadRequestException('Openai is disabled'); - - return this.openaiService.update(instance, openaiBotId, data); - } - - public async deleteOpenai(instance: InstanceDto, openaiBotId: string) { - if (!configService.get('OPENAI').ENABLED) throw new BadRequestException('Openai is disabled'); - - return this.openaiService.delete(instance, openaiBotId); - } - - public async settings(instance: InstanceDto, data: any) { - if (!configService.get('OPENAI').ENABLED) throw new BadRequestException('Openai is disabled'); - - return this.openaiService.setDefaultSettings(instance, data); - } - - public async fetchSettings(instance: InstanceDto) { - if (!configService.get('OPENAI').ENABLED) throw new BadRequestException('Openai is disabled'); - - return this.openaiService.fetchDefaultSettings(instance); - } - - public async changeStatus(instance: InstanceDto, data: any) { - if (!configService.get('OPENAI').ENABLED) throw new BadRequestException('Openai is disabled'); - - return this.openaiService.changeStatus(instance, data); - } - - public async fetchSessions(instance: InstanceDto, openaiBotId: string) { - if (!configService.get('OPENAI').ENABLED) throw new BadRequestException('Openai is disabled'); - - return this.openaiService.fetchSessions(instance, openaiBotId); - } - - public async getModels(instance: InstanceDto) { - if (!configService.get('OPENAI').ENABLED) throw new BadRequestException('Openai is disabled'); - - return this.openaiService.getModels(instance); - } - - public async ignoreJid(instance: InstanceDto, data: OpenaiIgnoreJidDto) { - if (!configService.get('OPENAI').ENABLED) throw new BadRequestException('Openai is disabled'); - - return this.openaiService.ignoreJid(instance, data); - } -} diff --git a/src/api/integrations/openai/services/openai.service.ts b/src/api/integrations/openai/services/openai.service.ts deleted file mode 100644 index 5fec9926..00000000 --- a/src/api/integrations/openai/services/openai.service.ts +++ /dev/null @@ -1,1872 +0,0 @@ -import { Message, OpenaiBot, OpenaiCreds, OpenaiSession, OpenaiSetting } from '@prisma/client'; -import axios from 'axios'; -import { downloadMediaMessage } from 'baileys'; -import FormData from 'form-data'; -import OpenAI from 'openai'; -import P from 'pino'; - -import { ConfigService, Language, S3 } from '../../../../config/env.config'; -import { Logger } from '../../../../config/logger.config'; -import { sendTelemetry } from '../../../../utils/sendTelemetry'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { PrismaRepository } from '../../../repository/repository.service'; -import { WAMonitoringService } from '../../../services/monitor.service'; -import { OpenaiCredsDto, OpenaiDto, OpenaiIgnoreJidDto, OpenaiSettingDto } from '../dto/openai.dto'; - -export class OpenaiService { - constructor( - private readonly waMonitor: WAMonitoringService, - private readonly configService: ConfigService, - private readonly prismaRepository: PrismaRepository, - ) {} - - private userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; - - private client: OpenAI; - - private readonly logger = new Logger(OpenaiService.name); - - public async createCreds(instance: InstanceDto, data: OpenaiCredsDto) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - if (!data.apiKey) throw new Error('API Key is required'); - if (!data.name) throw new Error('Name is required'); - - try { - const creds = await this.prismaRepository.openaiCreds.create({ - data: { - name: data.name, - apiKey: data.apiKey, - instanceId: instanceId, - }, - }); - - return creds; - } catch (error) { - this.logger.error(error); - throw new Error('Error creating openai creds'); - } - } - - public async findCreds(instance: InstanceDto) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const creds = await this.prismaRepository.openaiCreds.findMany({ - where: { - instanceId: instanceId, - }, - include: { - OpenaiAssistant: true, - }, - }); - - return creds; - } - - public async deleteCreds(instance: InstanceDto, openaiCredsId: string) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const creds = await this.prismaRepository.openaiCreds.findFirst({ - where: { - id: openaiCredsId, - }, - }); - - if (!creds) { - throw new Error('Openai Creds not found'); - } - - if (creds.instanceId !== instanceId) { - throw new Error('Openai Creds not found'); - } - - try { - await this.prismaRepository.openaiCreds.delete({ - where: { - id: openaiCredsId, - }, - }); - - return { openaiCreds: { id: openaiCredsId } }; - } catch (error) { - this.logger.error(error); - throw new Error('Error deleting openai creds'); - } - } - - public async create(instance: InstanceDto, data: OpenaiDto) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - if ( - !data.openaiCredsId || - !data.expire || - !data.keywordFinish || - !data.delayMessage || - !data.unknownMessage || - !data.listeningFromMe || - !data.stopBotFromMe || - !data.keepOpen || - !data.debounceTime || - !data.ignoreJids - ) { - const defaultSettingCheck = await this.prismaRepository.openaiSetting.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (!data.openaiCredsId) data.openaiCredsId = defaultSettingCheck?.openaiCredsId || null; - if (!data.expire) data.expire = defaultSettingCheck?.expire || 0; - if (!data.keywordFinish) data.keywordFinish = defaultSettingCheck?.keywordFinish || ''; - if (!data.delayMessage) data.delayMessage = defaultSettingCheck?.delayMessage || 1000; - if (!data.unknownMessage) data.unknownMessage = defaultSettingCheck?.unknownMessage || ''; - if (!data.listeningFromMe) data.listeningFromMe = defaultSettingCheck?.listeningFromMe || false; - if (!data.stopBotFromMe) data.stopBotFromMe = defaultSettingCheck?.stopBotFromMe || false; - if (!data.keepOpen) data.keepOpen = defaultSettingCheck?.keepOpen || false; - if (!data.debounceTime) data.debounceTime = defaultSettingCheck?.debounceTime || 0; - if (!data.ignoreJids) data.ignoreJids = defaultSettingCheck?.ignoreJids || []; - - if (!data.openaiCredsId) { - throw new Error('Openai Creds Id is required'); - } - - if (!defaultSettingCheck) { - await this.setDefaultSettings(instance, { - openaiCredsId: data.openaiCredsId, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - ignoreJids: data.ignoreJids, - }); - } - } - - const checkTriggerAll = await this.prismaRepository.openaiBot.findFirst({ - where: { - enabled: true, - triggerType: 'all', - instanceId: instanceId, - }, - }); - - if (checkTriggerAll && data.triggerType === 'all') { - throw new Error('You already have a openai with an "All" trigger, you cannot have more bots while it is active'); - } - - let whereDuplication: any = { - instanceId: instanceId, - }; - - if (data.botType === 'assistant') { - if (!data.assistantId) throw new Error('Assistant ID is required'); - - whereDuplication = { - ...whereDuplication, - assistantId: data.assistantId, - botType: data.botType, - }; - } else if (data.botType === 'chatCompletion') { - if (!data.model) throw new Error('Model is required'); - if (!data.maxTokens) throw new Error('Max tokens is required'); - - whereDuplication = { - ...whereDuplication, - model: data.model, - maxTokens: data.maxTokens, - botType: data.botType, - }; - } else { - throw new Error('Bot type is required'); - } - - const checkDuplicate = await this.prismaRepository.openaiBot.findFirst({ - where: whereDuplication, - }); - - if (checkDuplicate) { - throw new Error('Openai Bot already exists'); - } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.prismaRepository.openaiBot.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const openaiBot = await this.prismaRepository.openaiBot.create({ - data: { - enabled: data.enabled, - description: data.description, - openaiCredsId: data.openaiCredsId, - botType: data.botType, - assistantId: data.assistantId, - model: data.model, - systemMessages: data.systemMessages, - assistantMessages: data.assistantMessages, - userMessages: data.userMessages, - maxTokens: data.maxTokens, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - }, - }); - - return openaiBot; - } catch (error) { - this.logger.error(error); - throw new Error('Error creating openai bot'); - } - } - - public async fetch(instance: InstanceDto, openaiBotId: string) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const openaiBot = await this.prismaRepository.openaiBot.findFirst({ - where: { - id: openaiBotId, - }, - include: { - OpenaiSession: true, - }, - }); - - if (!openaiBot) { - throw new Error('Openai Bot not found'); - } - - if (openaiBot.instanceId !== instanceId) { - throw new Error('Openai Bot not found'); - } - - return openaiBot; - } - - public async update(instance: InstanceDto, openaiBotId: string, data: OpenaiDto) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const openaiBot = await this.prismaRepository.openaiBot.findFirst({ - where: { - id: openaiBotId, - }, - }); - - if (!openaiBot) { - throw new Error('Openai Bot not found'); - } - - if (openaiBot.instanceId !== instanceId) { - throw new Error('Openai Bot not found'); - } - - if (data.triggerType === 'all') { - const checkTriggerAll = await this.prismaRepository.openaiBot.findFirst({ - where: { - enabled: true, - triggerType: 'all', - id: { - not: openaiBotId, - }, - instanceId: instanceId, - }, - }); - - if (checkTriggerAll) { - throw new Error( - 'You already have a openai bot with an "All" trigger, you cannot have more bots while it is active', - ); - } - } - - let whereDuplication: any = { - id: { - not: openaiBotId, - }, - instanceId: instanceId, - }; - - if (data.botType === 'assistant') { - if (!data.assistantId) throw new Error('Assistant ID is required'); - - whereDuplication = { - ...whereDuplication, - assistantId: data.assistantId, - }; - } else if (data.botType === 'chatCompletion') { - if (!data.model) throw new Error('Model is required'); - if (!data.maxTokens) throw new Error('Max tokens is required'); - - whereDuplication = { - ...whereDuplication, - model: data.model, - maxTokens: data.maxTokens, - }; - } else { - throw new Error('Bot type is required'); - } - - const checkDuplicate = await this.prismaRepository.openaiBot.findFirst({ - where: whereDuplication, - }); - - if (checkDuplicate) { - throw new Error('Openai Bot already exists'); - } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.prismaRepository.openaiBot.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - id: { - not: openaiBotId, - }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const openaiBot = await this.prismaRepository.openaiBot.update({ - where: { - id: openaiBotId, - }, - data: { - enabled: data.enabled, - openaiCredsId: data.openaiCredsId, - botType: data.botType, - assistantId: data.assistantId, - model: data.model, - systemMessages: data.systemMessages, - assistantMessages: data.assistantMessages, - userMessages: data.userMessages, - maxTokens: data.maxTokens, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - }, - }); - - return openaiBot; - } catch (error) { - this.logger.error(error); - throw new Error('Error updating openai bot'); - } - } - - public async find(instance: InstanceDto): Promise { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const openaiBots = await this.prismaRepository.openaiBot.findMany({ - where: { - instanceId: instanceId, - }, - include: { - OpenaiSession: true, - }, - }); - - if (!openaiBots.length) { - return null; - } - - return openaiBots; - } - - public async delete(instance: InstanceDto, openaiBotId: string) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const openaiBot = await this.prismaRepository.openaiBot.findFirst({ - where: { - id: openaiBotId, - }, - }); - - if (!openaiBot) { - throw new Error('Openai bot not found'); - } - - if (openaiBot.instanceId !== instanceId) { - throw new Error('Openai bot not found'); - } - try { - await this.prismaRepository.openaiSession.deleteMany({ - where: { - openaiBotId: openaiBotId, - }, - }); - - await this.prismaRepository.openaiBot.delete({ - where: { - id: openaiBotId, - }, - }); - - return { openaiBot: { id: openaiBotId } }; - } catch (error) { - this.logger.error(error); - throw new Error('Error deleting openai bot'); - } - } - - public async setDefaultSettings(instance: InstanceDto, data: OpenaiSettingDto) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.prismaRepository.openaiSetting.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (settings) { - const updateSettings = await this.prismaRepository.openaiSetting.update({ - where: { - id: settings.id, - }, - data: { - openaiCredsId: data.openaiCredsId, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - speechToText: data.speechToText, - openaiIdFallback: data.openaiIdFallback, - ignoreJids: data.ignoreJids, - }, - }); - - return { - openaiCredsId: updateSettings.openaiCredsId, - expire: updateSettings.expire, - keywordFinish: updateSettings.keywordFinish, - delayMessage: updateSettings.delayMessage, - unknownMessage: updateSettings.unknownMessage, - listeningFromMe: updateSettings.listeningFromMe, - stopBotFromMe: updateSettings.stopBotFromMe, - keepOpen: updateSettings.keepOpen, - debounceTime: updateSettings.debounceTime, - speechToText: updateSettings.speechToText, - openaiIdFallback: updateSettings.openaiIdFallback, - ignoreJids: updateSettings.ignoreJids, - }; - } - - const newSetttings = await this.prismaRepository.openaiSetting.create({ - data: { - openaiCredsId: data.openaiCredsId, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - openaiIdFallback: data.openaiIdFallback, - ignoreJids: data.ignoreJids, - speechToText: data.speechToText, - instanceId: instanceId, - }, - }); - - return { - openaiCredsId: newSetttings.openaiCredsId, - expire: newSetttings.expire, - keywordFinish: newSetttings.keywordFinish, - delayMessage: newSetttings.delayMessage, - unknownMessage: newSetttings.unknownMessage, - listeningFromMe: newSetttings.listeningFromMe, - stopBotFromMe: newSetttings.stopBotFromMe, - keepOpen: newSetttings.keepOpen, - debounceTime: newSetttings.debounceTime, - openaiIdFallback: newSetttings.openaiIdFallback, - ignoreJids: newSetttings.ignoreJids, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - public async fetchDefaultSettings(instance: InstanceDto) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.prismaRepository.openaiSetting.findFirst({ - where: { - instanceId: instanceId, - }, - include: { - Fallback: true, - }, - }); - - if (!settings) { - return { - openaiCredsId: null, - expire: 0, - keywordFinish: '', - delayMessage: 0, - unknownMessage: '', - listeningFromMe: false, - stopBotFromMe: false, - keepOpen: false, - ignoreJids: [], - openaiIdFallback: null, - speechToText: false, - fallback: null, - }; - } - - return { - openaiCredsId: settings.openaiCredsId, - expire: settings.expire, - keywordFinish: settings.keywordFinish, - delayMessage: settings.delayMessage, - unknownMessage: settings.unknownMessage, - listeningFromMe: settings.listeningFromMe, - stopBotFromMe: settings.stopBotFromMe, - keepOpen: settings.keepOpen, - ignoreJids: settings.ignoreJids, - openaiIdFallback: settings.openaiIdFallback, - speechToText: settings.speechToText, - fallback: settings.Fallback, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching default settings'); - } - } - - public async getModels(instance: InstanceDto) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - if (!instanceId) throw new Error('Instance not found'); - - const defaultSettings = await this.prismaRepository.openaiSetting.findFirst({ - where: { - instanceId: instanceId, - }, - include: { - OpenaiCreds: true, - }, - }); - - if (!defaultSettings) throw new Error('Settings not found'); - - const { apiKey } = defaultSettings.OpenaiCreds; - - try { - this.client = new OpenAI({ apiKey }); - - const models: any = await this.client.models.list(); - - return models?.body?.data; - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching models'); - } - } - - public async ignoreJid(instance: InstanceDto, data: OpenaiIgnoreJidDto) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.prismaRepository.openaiSetting.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (!settings) { - throw new Error('Settings not found'); - } - - let ignoreJids: any = settings?.ignoreJids || []; - - if (data.action === 'add') { - if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; - - ignoreJids.push(data.remoteJid); - } else { - ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); - } - - const updateSettings = await this.prismaRepository.openaiSetting.update({ - where: { - id: settings.id, - }, - data: { - ignoreJids: ignoreJids, - }, - }); - - return { - ignoreJids: updateSettings.ignoreJids, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - public async fetchSessions(instance: InstanceDto, openaiBotId?: string, remoteJid?: string) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const openaiBot = await this.prismaRepository.openaiBot.findFirst({ - where: { - id: openaiBotId, - }, - }); - - if (!openaiBot) { - throw new Error('Openai Bot not found'); - } - - if (openaiBot.instanceId !== instanceId) { - throw new Error('Openai Bot not found'); - } - - if (openaiBot) { - return await this.prismaRepository.openaiSession.findMany({ - where: { - openaiBotId: openaiBotId, - }, - }); - } - - if (remoteJid) { - return await this.prismaRepository.openaiSession.findMany({ - where: { - remoteJid: remoteJid, - openaiBotId: openaiBotId, - }, - }); - } - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching sessions'); - } - } - - public async changeStatus(instance: InstanceDto, data: any) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const defaultSettingCheck = await this.prismaRepository.openaiSetting.findFirst({ - where: { - instanceId, - }, - }); - - const remoteJid = data.remoteJid; - const status = data.status; - - if (status === 'delete') { - await this.prismaRepository.openaiSession.deleteMany({ - where: { - remoteJid: remoteJid, - }, - }); - - return { openai: { remoteJid: remoteJid, status: status } }; - } - - if (status === 'closed') { - if (defaultSettingCheck?.keepOpen) { - await this.prismaRepository.openaiSession.updateMany({ - where: { - remoteJid: remoteJid, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.openaiSession.deleteMany({ - where: { - remoteJid: remoteJid, - }, - }); - } - - return { openai: { ...instance, openai: { remoteJid: remoteJid, status: status } } }; - } else { - const session = await this.prismaRepository.openaiSession.updateMany({ - where: { - instanceId: instanceId, - remoteJid: remoteJid, - }, - data: { - status: status, - }, - }); - - const openaiData = { - remoteJid: remoteJid, - status: status, - session, - }; - - return { openai: { ...instance, openai: openaiData } }; - } - } catch (error) { - this.logger.error(error); - throw new Error('Error changing status'); - } - } - - private getTypeMessage(msg: any) { - let mediaId: string; - - if (this.configService.get('S3').ENABLE) mediaId = msg.message.mediaUrl; - else mediaId = msg.key.id; - - const types = { - conversation: msg?.message?.conversation, - extendedTextMessage: msg?.message?.extendedTextMessage?.text, - contactMessage: msg?.message?.contactMessage?.displayName, - locationMessage: msg?.message?.locationMessage?.degreesLatitude, - viewOnceMessageV2: - msg?.message?.viewOnceMessageV2?.message?.imageMessage?.url || - msg?.message?.viewOnceMessageV2?.message?.videoMessage?.url || - msg?.message?.viewOnceMessageV2?.message?.audioMessage?.url, - listResponseMessage: msg?.message?.listResponseMessage?.singleSelectReply?.selectedRowId, - responseRowId: msg?.message?.listResponseMessage?.singleSelectReply?.selectedRowId, - // Medias - audioMessage: msg?.message?.speechToText - ? msg?.message?.speechToText - : msg?.message?.audioMessage - ? `audioMessage|${mediaId}` - : undefined, - imageMessage: msg?.message?.imageMessage ? `imageMessage|${mediaId}` : undefined, - videoMessage: msg?.message?.videoMessage ? `videoMessage|${mediaId}` : undefined, - documentMessage: msg?.message?.documentMessage ? `documentMessage|${mediaId}` : undefined, - documentWithCaptionMessage: msg?.message?.auddocumentWithCaptionMessageioMessage - ? `documentWithCaptionMessage|${mediaId}` - : undefined, - }; - - const messageType = Object.keys(types).find((key) => types[key] !== undefined) || 'unknown'; - - return { ...types, messageType }; - } - - private getMessageContent(types: any) { - const typeKey = Object.keys(types).find((key) => types[key] !== undefined); - - const result = typeKey ? types[typeKey] : undefined; - - return result; - } - - private getConversationMessage(msg: any) { - const types = this.getTypeMessage(msg); - - const messageContent = this.getMessageContent(types); - - return messageContent; - } - - public async findOpenaiByTrigger(content: string, instanceId: string) { - // Check for triggerType 'all' - const findTriggerAll = await this.prismaRepository.openaiBot.findFirst({ - where: { - enabled: true, - triggerType: 'all', - instanceId: instanceId, - }, - }); - - if (findTriggerAll) return findTriggerAll; - - // Check for exact match - const findTriggerEquals = await this.prismaRepository.openaiBot.findFirst({ - where: { - enabled: true, - triggerType: 'keyword', - triggerOperator: 'equals', - triggerValue: content, - instanceId: instanceId, - }, - }); - - if (findTriggerEquals) return findTriggerEquals; - - // Check for regex match - const findRegex = await this.prismaRepository.openaiBot.findMany({ - where: { - enabled: true, - triggerType: 'keyword', - triggerOperator: 'regex', - instanceId: instanceId, - }, - }); - - let findTriggerRegex = null; - - for (const regex of findRegex) { - const regexValue = new RegExp(regex.triggerValue); - - if (regexValue.test(content)) { - findTriggerRegex = regex; - break; - } - } - - if (findTriggerRegex) return findTriggerRegex; - - // Check for startsWith match - const findStartsWith = await this.prismaRepository.openaiBot.findMany({ - where: { - enabled: true, - triggerType: 'keyword', - triggerOperator: 'startsWith', - instanceId: instanceId, - }, - }); - - let findTriggerStartsWith = null; - - for (const startsWith of findStartsWith) { - if (content.startsWith(startsWith.triggerValue)) { - findTriggerStartsWith = startsWith; - break; - } - } - - if (findTriggerStartsWith) return findTriggerStartsWith; - - // Check for endsWith match - const findEndsWith = await this.prismaRepository.openaiBot.findMany({ - where: { - enabled: true, - triggerType: 'keyword', - triggerOperator: 'endsWith', - instanceId: instanceId, - }, - }); - - let findTriggerEndsWith = null; - - for (const endsWith of findEndsWith) { - if (content.endsWith(endsWith.triggerValue)) { - findTriggerEndsWith = endsWith; - break; - } - } - - if (findTriggerEndsWith) return findTriggerEndsWith; - - // Check for contains match - const findContains = await this.prismaRepository.openaiBot.findMany({ - where: { - enabled: true, - triggerType: 'keyword', - triggerOperator: 'contains', - instanceId: instanceId, - }, - }); - - let findTriggerContains = null; - - for (const contains of findContains) { - if (content.includes(contains.triggerValue)) { - findTriggerContains = contains; - break; - } - } - - if (findTriggerContains) return findTriggerContains; - - const fallback = await this.prismaRepository.openaiSetting.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (fallback?.openaiIdFallback) { - const findFallback = await this.prismaRepository.openaiBot.findFirst({ - where: { - id: fallback.openaiIdFallback, - }, - }); - - if (findFallback) return findFallback; - } - - return null; - } - - private processDebounce(content: string, remoteJid: string, debounceTime: number, callback: any) { - if (this.userMessageDebounce[remoteJid]) { - this.userMessageDebounce[remoteJid].message += ` ${content}`; - this.logger.log('message debounced: ' + this.userMessageDebounce[remoteJid].message); - clearTimeout(this.userMessageDebounce[remoteJid].timeoutId); - } else { - this.userMessageDebounce[remoteJid] = { - message: content, - timeoutId: null, - }; - } - - this.userMessageDebounce[remoteJid].timeoutId = setTimeout(() => { - const myQuestion = this.userMessageDebounce[remoteJid].message; - this.logger.log('Debounce complete. Processing message: ' + myQuestion); - - delete this.userMessageDebounce[remoteJid]; - callback(myQuestion); - }, debounceTime * 1000); - } - - public async sendOpenai(instance: InstanceDto, remoteJid: string, msg: Message) { - try { - const settings = await this.prismaRepository.openaiSetting.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (settings?.ignoreJids) { - const ignoreJids: any = settings.ignoreJids; - - let ignoreGroups = false; - let ignoreContacts = false; - - if (ignoreJids.includes('@g.us')) { - ignoreGroups = true; - } - - if (ignoreJids.includes('@s.whatsapp.net')) { - ignoreContacts = true; - } - - if (ignoreGroups && remoteJid.endsWith('@g.us')) { - this.logger.warn('Ignoring message from group: ' + remoteJid); - return; - } - - if (ignoreContacts && remoteJid.endsWith('@s.whatsapp.net')) { - this.logger.warn('Ignoring message from contact: ' + remoteJid); - return; - } - - if (ignoreJids.includes(remoteJid)) { - this.logger.warn('Ignoring message from jid: ' + remoteJid); - return; - } - } - - const session = await this.prismaRepository.openaiSession.findFirst({ - where: { - remoteJid: remoteJid, - instanceId: instance.instanceId, - }, - }); - - const content = this.getConversationMessage(msg); - - let findOpenai = null; - - if (!session) { - findOpenai = await this.findOpenaiByTrigger(content, instance.instanceId); - - if (!findOpenai) { - return; - } - } else { - findOpenai = await this.prismaRepository.openaiBot.findFirst({ - where: { - id: session.openaiBotId, - }, - }); - } - - if (!findOpenai) return; - - let openaiCredsId = findOpenai.openaiCredsId; - let expire = findOpenai.expire; - let keywordFinish = findOpenai.keywordFinish; - let delayMessage = findOpenai.delayMessage; - let unknownMessage = findOpenai.unknownMessage; - let listeningFromMe = findOpenai.listeningFromMe; - let stopBotFromMe = findOpenai.stopBotFromMe; - let keepOpen = findOpenai.keepOpen; - let debounceTime = findOpenai.debounceTime; - - if ( - !openaiCredsId || - !expire || - !keywordFinish || - !delayMessage || - !unknownMessage || - !listeningFromMe || - !stopBotFromMe || - !keepOpen || - !debounceTime - ) { - if (!openaiCredsId) openaiCredsId = settings.openaiCredsId; - - if (!expire) expire = settings.expire; - - if (!keywordFinish) keywordFinish = settings.keywordFinish; - - if (!delayMessage) delayMessage = settings.delayMessage; - - if (!unknownMessage) unknownMessage = settings.unknownMessage; - - if (!listeningFromMe) listeningFromMe = settings.listeningFromMe; - - if (!stopBotFromMe) stopBotFromMe = settings.stopBotFromMe; - - if (!keepOpen) keepOpen = settings.keepOpen; - - if (!debounceTime) debounceTime = settings.debounceTime; - } - - const key = msg.key as { - id: string; - remoteJid: string; - fromMe: boolean; - participant: string; - }; - - if (stopBotFromMe && key.fromMe && session) { - if (keepOpen) { - await this.prismaRepository.openaiSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.openaiSession.deleteMany({ - where: { - openaiBotId: findOpenai.id, - remoteJid: remoteJid, - }, - }); - } - return; - } - - if (!listeningFromMe && key.fromMe) { - return; - } - - if (debounceTime && debounceTime > 0) { - this.processDebounce(content, remoteJid, debounceTime, async (debouncedContent) => { - if (findOpenai.botType === 'assistant') { - await this.processOpenaiAssistant( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - findOpenai, - session, - settings, - debouncedContent, - ); - } - - if (findOpenai.botType === 'chatCompletion') { - await this.processOpenaiChatCompletion( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - findOpenai, - session, - settings, - debouncedContent, - ); - } - }); - } else { - if (findOpenai.botType === 'assistant') { - await this.processOpenaiAssistant( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - findOpenai, - session, - settings, - content, - ); - } - - if (findOpenai.botType === 'chatCompletion') { - await this.processOpenaiChatCompletion( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - findOpenai, - session, - settings, - content, - ); - } - } - - return; - } catch (error) { - this.logger.error(error); - return; - } - } - - public async createAssistantNewSession(instance: InstanceDto, data: any) { - if (data.remoteJid === 'status@broadcast') return; - - const creds = await this.prismaRepository.openaiCreds.findFirst({ - where: { - id: data.openaiCredsId, - }, - }); - - if (!creds) throw new Error('Openai Creds not found'); - - try { - this.client = new OpenAI({ - apiKey: creds.apiKey, - }); - - const threadId = (await this.client.beta.threads.create({})).id; - - let session = null; - if (threadId) { - session = await this.prismaRepository.openaiSession.create({ - data: { - remoteJid: data.remoteJid, - sessionId: threadId, - status: 'opened', - awaitUser: false, - openaiBotId: data.openaiBotId, - instanceId: instance.instanceId, - }, - }); - } - return { session }; - } catch (error) { - this.logger.error(error); - return; - } - } - - private async initAssistantNewSession( - instance: any, - remoteJid: string, - openaiBot: OpenaiBot, - settings: OpenaiSetting, - session: OpenaiSession, - content: string, - ) { - const data = await this.createAssistantNewSession(instance, { - remoteJid, - openaiCredsId: openaiBot.openaiCredsId, - openaiBotId: openaiBot.id, - }); - - if (data.session) { - session = data.session; - } - - await this.client.beta.threads.messages.create(data.session.sessionId, { - role: 'user', - content, - }); - - const runAssistant = await this.client.beta.threads.runs.create(data.session.sessionId, { - assistant_id: openaiBot.assistantId, - }); - - await instance.client.presenceSubscribe(remoteJid); - - await instance.client.sendPresenceUpdate('composing', remoteJid); - - const response = await this.getAIResponse(data.session.sessionId, runAssistant.id); - - await instance.client.sendPresenceUpdate('paused', remoteJid); - - const message = response?.data[0].content[0].text.value; - - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - - await this.prismaRepository.openaiSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: true, - }, - }); - - sendTelemetry('/message/sendText'); - - return; - } - - private async getAIResponse(threadId: string, runId: string) { - const getRun = await this.client.beta.threads.runs.retrieve(threadId, runId); - - switch (getRun.status) { - case 'queued': - await new Promise((resolve) => setTimeout(resolve, 1000)); - return this.getAIResponse(threadId, runId); - case 'in_progress': - await new Promise((resolve) => setTimeout(resolve, 1000)); - return this.getAIResponse(threadId, runId); - case 'requires_action': - return null; - case 'completed': - return await this.client.beta.threads.messages.list(threadId, { - run_id: runId, - limit: 1, - }); - } - } - - private async processOpenaiAssistant( - instance: any, - remoteJid: string, - openaiBot: OpenaiBot, - session: OpenaiSession, - settings: OpenaiSetting, - content: string, - ) { - if (session && session.status !== 'opened') { - return; - } - - if (session && settings.expire && settings.expire > 0) { - const now = Date.now(); - - const sessionUpdatedAt = new Date(session.updatedAt).getTime(); - - const diff = now - sessionUpdatedAt; - - const diffInMinutes = Math.floor(diff / 1000 / 60); - - if (diffInMinutes > settings.expire) { - if (settings.keepOpen) { - await this.prismaRepository.openaiSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.openaiSession.deleteMany({ - where: { - openaiBotId: openaiBot.id, - remoteJid: remoteJid, - }, - }); - } - - await this.initAssistantNewSession(instance, remoteJid, openaiBot, settings, session, content); - return; - } - } - - if (!session) { - await this.initAssistantNewSession(instance, remoteJid, openaiBot, settings, session, content); - return; - } - - await this.prismaRepository.openaiSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: false, - }, - }); - - if (!content) { - if (settings.unknownMessage) { - this.waMonitor.waInstances[instance.instanceName].textMessage( - { - number: remoteJid.split('@')[0], - delay: settings.delayMessage || 1000, - text: settings.unknownMessage, - }, - false, - ); - - sendTelemetry('/message/sendText'); - } - return; - } - - if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) { - if (settings.keepOpen) { - await this.prismaRepository.openaiSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.openaiSession.deleteMany({ - where: { - openaiBotId: openaiBot.id, - remoteJid: remoteJid, - }, - }); - } - return; - } - - const creds = await this.prismaRepository.openaiCreds.findFirst({ - where: { - id: openaiBot.openaiCredsId, - }, - }); - - if (!creds) throw new Error('Openai Creds not found'); - - this.client = new OpenAI({ - apiKey: creds.apiKey, - }); - - const threadId = session.sessionId; - - await this.client.beta.threads.messages.create(threadId, { - role: 'user', - content, - }); - - const runAssistant = await this.client.beta.threads.runs.create(threadId, { - assistant_id: openaiBot.assistantId, - }); - - await instance.client.presenceSubscribe(remoteJid); - - await instance.client.sendPresenceUpdate('composing', remoteJid); - - const response = await this.getAIResponse(threadId, runAssistant.id); - - await instance.client.sendPresenceUpdate('paused', remoteJid); - - const message = response?.data[0].content[0].text.value; - - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - - await this.prismaRepository.openaiSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: true, - }, - }); - - sendTelemetry('/message/sendText'); - - return; - } - - public async createChatCompletionNewSession(instance: InstanceDto, data: any) { - if (data.remoteJid === 'status@broadcast') return; - - const id = Math.floor(Math.random() * 10000000000).toString(); - - const creds = await this.prismaRepository.openaiCreds.findFirst({ - where: { - id: data.openaiCredsId, - }, - }); - - if (!creds) throw new Error('Openai Creds not found'); - - try { - const session = await this.prismaRepository.openaiSession.create({ - data: { - remoteJid: data.remoteJid, - sessionId: id, - status: 'opened', - awaitUser: false, - openaiBotId: data.openaiBotId, - instanceId: instance.instanceId, - }, - }); - - return { session, creds }; - } catch (error) { - this.logger.error(error); - return; - } - } - - private async initChatCompletionNewSession( - instance: any, - remoteJid: string, - openaiBot: OpenaiBot, - settings: OpenaiSetting, - session: OpenaiSession, - content: string, - ) { - const data = await this.createChatCompletionNewSession(instance, { - remoteJid, - openaiCredsId: openaiBot.openaiCredsId, - openaiBotId: openaiBot.id, - }); - - session = data.session; - const creds = data.creds; - - this.client = new OpenAI({ - apiKey: creds.apiKey, - }); - - const systemMessages: any = openaiBot.systemMessages; - - const messagesSystem: any[] = systemMessages.map((message) => { - return { - role: 'system', - content: message, - }; - }); - - const assistantMessages: any = openaiBot.assistantMessages; - - const messagesAssistant: any[] = assistantMessages.map((message) => { - return { - role: 'assistant', - content: message, - }; - }); - - const userMessages: any = openaiBot.userMessages; - - const messagesUser: any[] = userMessages.map((message) => { - return { - role: 'user', - content: message, - }; - }); - - const messages: any[] = [ - ...messagesSystem, - ...messagesAssistant, - ...messagesUser, - { - role: 'user', - content: content, - }, - ]; - - await instance.client.presenceSubscribe(remoteJid); - - await instance.client.sendPresenceUpdate('composing', remoteJid); - - const completions = await this.client.chat.completions.create({ - model: openaiBot.model, - messages: messages, - max_tokens: openaiBot.maxTokens, - }); - - await instance.client.sendPresenceUpdate('paused', remoteJid); - - const message = completions.choices[0].message.content; - - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - - await this.prismaRepository.openaiSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: true, - }, - }); - - sendTelemetry('/message/sendText'); - - return; - } - - private async processOpenaiChatCompletion( - instance: any, - remoteJid: string, - openaiBot: OpenaiBot, - session: OpenaiSession, - settings: OpenaiSetting, - content: string, - ) { - if (session && session.status !== 'opened') { - return; - } - - if (session && settings.expire && settings.expire > 0) { - const now = Date.now(); - - const sessionUpdatedAt = new Date(session.updatedAt).getTime(); - - const diff = now - sessionUpdatedAt; - - const diffInMinutes = Math.floor(diff / 1000 / 60); - - if (diffInMinutes > settings.expire) { - if (settings.keepOpen) { - await this.prismaRepository.openaiSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.openaiSession.deleteMany({ - where: { - openaiBotId: openaiBot.id, - remoteJid: remoteJid, - }, - }); - } - - await this.initChatCompletionNewSession(instance, remoteJid, openaiBot, settings, session, content); - return; - } - } - - if (!session) { - await this.initChatCompletionNewSession(instance, remoteJid, openaiBot, settings, session, content); - return; - } - - await this.prismaRepository.openaiSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: false, - }, - }); - - if (!content) { - if (settings.unknownMessage) { - this.waMonitor.waInstances[instance.instanceName].textMessage( - { - number: remoteJid.split('@')[0], - delay: settings.delayMessage || 1000, - text: settings.unknownMessage, - }, - false, - ); - - sendTelemetry('/message/sendText'); - } - return; - } - - if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) { - if (settings.keepOpen) { - await this.prismaRepository.openaiSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.openaiSession.deleteMany({ - where: { - openaiBotId: openaiBot.id, - remoteJid: remoteJid, - }, - }); - } - return; - } - - const creds = await this.prismaRepository.openaiCreds.findFirst({ - where: { - id: openaiBot.openaiCredsId, - }, - }); - - if (!creds) throw new Error('Openai Creds not found'); - - this.client = new OpenAI({ - apiKey: creds.apiKey, - }); - - const systemMessages: any = openaiBot.systemMessages; - - const messagesSystem: any[] = systemMessages.map((message) => { - return { - role: 'system', - content: message, - }; - }); - - const assistantMessages: any = openaiBot.assistantMessages; - - const messagesAssistant: any[] = assistantMessages.map((message) => { - return { - role: 'assistant', - content: message, - }; - }); - - const userMessages: any = openaiBot.userMessages; - - const messagesUser: any[] = userMessages.map((message) => { - return { - role: 'user', - content: message, - }; - }); - - const messages: any[] = [ - ...messagesSystem, - ...messagesAssistant, - ...messagesUser, - { - role: 'user', - content: content, - }, - ]; - - await instance.client.presenceSubscribe(remoteJid); - - await instance.client.sendPresenceUpdate('composing', remoteJid); - - const completions = await this.client.chat.completions.create({ - model: openaiBot.model, - messages: messages, - max_tokens: openaiBot.maxTokens, - }); - - await instance.client.sendPresenceUpdate('paused', remoteJid); - - const message = completions.choices[0].message.content; - - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - - await this.prismaRepository.openaiSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: true, - }, - }); - - sendTelemetry('/message/sendText'); - - return; - } - - public async speechToText(creds: OpenaiCreds, msg: any, updateMediaMessage: any) { - let audio; - - if (msg?.message?.mediaUrl) { - audio = await axios.get(msg.message.mediaUrl, { responseType: 'arraybuffer' }).then((response) => { - return Buffer.from(response.data, 'binary'); - }); - } else { - audio = await downloadMediaMessage( - { key: msg.key, message: msg?.message }, - 'buffer', - {}, - { - logger: P({ level: 'error' }) as any, - reuploadRequest: updateMediaMessage, - }, - ); - } - - const lang = this.configService.get('LANGUAGE').includes('pt') - ? 'pt' - : this.configService.get('LANGUAGE'); - - const formData = new FormData(); - - formData.append('file', audio, 'audio.ogg'); - formData.append('model', 'whisper-1'); - formData.append('language', lang); - - const response = await axios.post('https://api.openai.com/v1/audio/transcriptions', formData, { - headers: { - 'Content-Type': 'multipart/form-data', - Authorization: `Bearer ${creds.apiKey}`, - }, - }); - - return response?.data?.text; - } -} diff --git a/src/api/integrations/rabbitmq/controllers/rabbitmq.controller.ts b/src/api/integrations/rabbitmq/controllers/rabbitmq.controller.ts deleted file mode 100644 index 773b02cb..00000000 --- a/src/api/integrations/rabbitmq/controllers/rabbitmq.controller.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { configService, Rabbitmq } from '../../../../config/env.config'; -import { BadRequestException } from '../../../../exceptions'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { RabbitmqDto } from '../dto/rabbitmq.dto'; -import { RabbitmqService } from '../services/rabbitmq.service'; - -export class RabbitmqController { - constructor(private readonly rabbitmqService: RabbitmqService) {} - - public async createRabbitmq(instance: InstanceDto, data: RabbitmqDto) { - if (!configService.get('RABBITMQ').ENABLED) throw new BadRequestException('Rabbitmq is disabled'); - - if (!data.enabled) { - data.events = []; - } - - if (data.events.length === 0) { - data.events = [ - 'APPLICATION_STARTUP', - 'QRCODE_UPDATED', - 'MESSAGES_SET', - 'MESSAGES_UPSERT', - 'MESSAGES_EDITED', - 'MESSAGES_UPDATE', - 'MESSAGES_DELETE', - 'SEND_MESSAGE', - 'CONTACTS_SET', - 'CONTACTS_UPSERT', - 'CONTACTS_UPDATE', - 'PRESENCE_UPDATE', - 'CHATS_SET', - 'CHATS_UPSERT', - 'CHATS_UPDATE', - 'CHATS_DELETE', - 'GROUPS_UPSERT', - 'GROUP_UPDATE', - 'GROUP_PARTICIPANTS_UPDATE', - 'CONNECTION_UPDATE', - 'LABELS_EDIT', - 'LABELS_ASSOCIATION', - 'CALL', - 'TYPEBOT_START', - 'TYPEBOT_CHANGE_STATUS', - ]; - } - - return this.rabbitmqService.create(instance, data); - } - - public async findRabbitmq(instance: InstanceDto) { - return this.rabbitmqService.find(instance); - } -} diff --git a/src/api/integrations/rabbitmq/dto/rabbitmq.dto.ts b/src/api/integrations/rabbitmq/dto/rabbitmq.dto.ts deleted file mode 100644 index 9bfd5b42..00000000 --- a/src/api/integrations/rabbitmq/dto/rabbitmq.dto.ts +++ /dev/null @@ -1,4 +0,0 @@ -export class RabbitmqDto { - enabled: boolean; - events?: string[]; -} diff --git a/src/api/integrations/rabbitmq/libs/amqp.server.ts b/src/api/integrations/rabbitmq/libs/amqp.server.ts deleted file mode 100644 index 34b1ae46..00000000 --- a/src/api/integrations/rabbitmq/libs/amqp.server.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { JsonValue } from '@prisma/client/runtime/library'; -import * as amqp from 'amqplib/callback_api'; - -import { configService, Rabbitmq } from '../../../../config/env.config'; -import { Logger } from '../../../../config/logger.config'; - -const logger = new Logger('AMQP'); - -let amqpChannel: amqp.Channel | null = null; - -export const initAMQP = () => { - return new Promise((resolve, reject) => { - const uri = configService.get('RABBITMQ').URI; - amqp.connect(uri, (error, connection) => { - if (error) { - reject(error); - return; - } - - connection.createChannel((channelError, channel) => { - if (channelError) { - reject(channelError); - return; - } - - const exchangeName = configService.get('RABBITMQ').EXCHANGE_NAME || 'evolution_exchange'; - - channel.assertExchange(exchangeName, 'topic', { - durable: true, - autoDelete: false, - }); - - amqpChannel = channel; - - logger.info('AMQP initialized'); - resolve(); - }); - }); - }); -}; - -export const getAMQP = (): amqp.Channel | null => { - return amqpChannel; -}; - -export const initGlobalQueues = () => { - logger.info('Initializing global queues'); - const events = configService.get('RABBITMQ').EVENTS; - - if (!events) { - logger.warn('No events to initialize on AMQP'); - return; - } - - const eventKeys = Object.keys(events); - - eventKeys.forEach((event) => { - if (events[event] === false) return; - - const queueName = `${event.replace(/_/g, '.').toLowerCase()}`; - const amqp = getAMQP(); - const exchangeName = configService.get('RABBITMQ').EXCHANGE_NAME || 'evolution_exchange'; - - amqp.assertExchange(exchangeName, 'topic', { - durable: true, - autoDelete: false, - }); - - amqp.assertQueue(queueName, { - durable: true, - autoDelete: false, - arguments: { - 'x-queue-type': 'quorum', - }, - }); - - amqp.bindQueue(queueName, exchangeName, event); - }); -}; - -export const initQueues = (instanceName: string, events: string[]) => { - if (!events || !events.length) return; - - const queues = events.map((event) => { - return `${event.replace(/_/g, '.').toLowerCase()}`; - }); - - queues.forEach((event) => { - const amqp = getAMQP(); - const exchangeName = instanceName ?? 'evolution_exchange'; - - amqp.assertExchange(exchangeName, 'topic', { - durable: true, - autoDelete: false, - }); - - const queueName = `${instanceName}.${event}`; - - amqp.assertQueue(queueName, { - durable: true, - autoDelete: false, - arguments: { - 'x-queue-type': 'quorum', - }, - }); - - amqp.bindQueue(queueName, exchangeName, event); - }); -}; - -export const removeQueues = (instanceName: string, events: JsonValue) => { - const eventsArray = Array.isArray(events) ? events.map((event) => String(event)) : []; - - if (!events || !eventsArray.length) return; - - const channel = getAMQP(); - - const queues = eventsArray.map((event) => { - return `${event.replace(/_/g, '.').toLowerCase()}`; - }); - - const exchangeName = instanceName ?? 'evolution_exchange'; - - queues.forEach((event) => { - const amqp = getAMQP(); - - amqp.assertExchange(exchangeName, 'topic', { - durable: true, - autoDelete: false, - }); - - const queueName = `${instanceName}.${event}`; - - amqp.deleteQueue(queueName); - }); - - channel.deleteExchange(exchangeName); -}; diff --git a/src/api/integrations/rabbitmq/routes/rabbitmq.router.ts b/src/api/integrations/rabbitmq/routes/rabbitmq.router.ts deleted file mode 100644 index 52e5f7ba..00000000 --- a/src/api/integrations/rabbitmq/routes/rabbitmq.router.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { RequestHandler, Router } from 'express'; - -import { instanceSchema, rabbitmqSchema } from '../../../../validate/validate.schema'; -import { RouterBroker } from '../../../abstract/abstract.router'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { HttpStatus } from '../../../routes/index.router'; -import { rabbitmqController } from '../../../server.module'; -import { RabbitmqDto } from '../dto/rabbitmq.dto'; - -export class RabbitmqRouter extends RouterBroker { - constructor(...guards: RequestHandler[]) { - super(); - this.router - .post(this.routerPath('set'), ...guards, async (req, res) => { - console.log('RabbitmqRouter -> constructor -> req', req.body); - const response = await this.dataValidate({ - request: req, - schema: rabbitmqSchema, - ClassRef: RabbitmqDto, - execute: (instance, data) => rabbitmqController.createRabbitmq(instance, data), - }); - - res.status(HttpStatus.CREATED).json(response); - }) - .get(this.routerPath('find'), ...guards, async (req, res) => { - const response = await this.dataValidate({ - request: req, - schema: instanceSchema, - ClassRef: InstanceDto, - execute: (instance) => rabbitmqController.findRabbitmq(instance), - }); - - res.status(HttpStatus.OK).json(response); - }); - } - - public readonly router = Router(); -} diff --git a/src/api/integrations/rabbitmq/services/rabbitmq.service.ts b/src/api/integrations/rabbitmq/services/rabbitmq.service.ts deleted file mode 100644 index 53af10db..00000000 --- a/src/api/integrations/rabbitmq/services/rabbitmq.service.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { Rabbitmq } from '@prisma/client'; - -import { Logger } from '../../../../config/logger.config'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { WAMonitoringService } from '../../../services/monitor.service'; -import { RabbitmqDto } from '../dto/rabbitmq.dto'; -import { initQueues } from '../libs/amqp.server'; - -export class RabbitmqService { - constructor(private readonly waMonitor: WAMonitoringService) {} - - private readonly logger = new Logger(RabbitmqService.name); - - public create(instance: InstanceDto, data: RabbitmqDto) { - this.waMonitor.waInstances[instance.instanceName].setRabbitmq(data); - - initQueues(instance.instanceName, data.events); - return { rabbitmq: { ...instance, rabbitmq: data } }; - } - - public async find(instance: InstanceDto): Promise { - try { - const result = await this.waMonitor.waInstances[instance.instanceName].findRabbitmq(); - - if (Object.keys(result).length === 0) { - throw new Error('Rabbitmq not found'); - } - - return result; - } catch (error) { - return null; - } - } -} diff --git a/src/api/integrations/rabbitmq/validate/rabbitmq.schema.ts b/src/api/integrations/rabbitmq/validate/rabbitmq.schema.ts deleted file mode 100644 index 1fedf607..00000000 --- a/src/api/integrations/rabbitmq/validate/rabbitmq.schema.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { JSONSchema7 } from 'json-schema'; -import { v4 } from 'uuid'; - -const isNotEmpty = (...propertyNames: string[]): JSONSchema7 => { - const properties = {}; - propertyNames.forEach( - (property) => - (properties[property] = { - minLength: 1, - description: `The "${property}" cannot be empty`, - }), - ); - return { - if: { - propertyNames: { - enum: [...propertyNames], - }, - }, - then: { properties }, - }; -}; - -export const rabbitmqSchema: JSONSchema7 = { - $id: v4(), - type: 'object', - properties: { - enabled: { type: 'boolean', enum: [true, false] }, - events: { - type: 'array', - minItems: 0, - items: { - type: 'string', - enum: [ - 'APPLICATION_STARTUP', - 'QRCODE_UPDATED', - 'MESSAGES_SET', - 'MESSAGES_UPSERT', - 'MESSAGES_EDITED', - 'MESSAGES_UPDATE', - 'MESSAGES_DELETE', - 'SEND_MESSAGE', - 'CONTACTS_SET', - 'CONTACTS_UPSERT', - 'CONTACTS_UPDATE', - 'PRESENCE_UPDATE', - 'CHATS_SET', - 'CHATS_UPSERT', - 'CHATS_UPDATE', - 'CHATS_DELETE', - 'GROUPS_UPSERT', - 'GROUP_UPDATE', - 'GROUP_PARTICIPANTS_UPDATE', - 'CONNECTION_UPDATE', - 'LABELS_EDIT', - 'LABELS_ASSOCIATION', - 'CALL', - 'TYPEBOT_START', - 'TYPEBOT_CHANGE_STATUS', - ], - }, - }, - }, - required: ['enabled'], - ...isNotEmpty('enabled'), -}; diff --git a/src/api/integrations/sqs/controllers/sqs.controller.ts b/src/api/integrations/sqs/controllers/sqs.controller.ts deleted file mode 100644 index 7990a9bc..00000000 --- a/src/api/integrations/sqs/controllers/sqs.controller.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { configService, Sqs } from '../../../../config/env.config'; -import { BadRequestException } from '../../../../exceptions'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { SqsDto } from '../dto/sqs.dto'; -import { SqsService } from '../services/sqs.service'; - -export class SqsController { - constructor(private readonly sqsService: SqsService) {} - - public async createSqs(instance: InstanceDto, data: SqsDto) { - if (!configService.get('SQS').ENABLED) throw new BadRequestException('Sqs is disabled'); - - if (!data.enabled) { - data.events = []; - } - - if (data.events.length === 0) { - data.events = [ - 'APPLICATION_STARTUP', - 'QRCODE_UPDATED', - 'MESSAGES_SET', - 'MESSAGES_UPSERT', - 'MESSAGES_EDITED', - 'MESSAGES_UPDATE', - 'MESSAGES_DELETE', - 'SEND_MESSAGE', - 'CONTACTS_SET', - 'CONTACTS_UPSERT', - 'CONTACTS_UPDATE', - 'PRESENCE_UPDATE', - 'CHATS_SET', - 'CHATS_UPSERT', - 'CHATS_UPDATE', - 'CHATS_DELETE', - 'GROUPS_UPSERT', - 'GROUP_UPDATE', - 'GROUP_PARTICIPANTS_UPDATE', - 'CONNECTION_UPDATE', - 'LABELS_EDIT', - 'LABELS_ASSOCIATION', - 'CALL', - 'TYPEBOT_START', - 'TYPEBOT_CHANGE_STATUS', - ]; - } - - return this.sqsService.create(instance, data); - } - - public async findSqs(instance: InstanceDto) { - return this.sqsService.find(instance); - } -} diff --git a/src/api/integrations/sqs/dto/sqs.dto.ts b/src/api/integrations/sqs/dto/sqs.dto.ts deleted file mode 100644 index 9b8aeedd..00000000 --- a/src/api/integrations/sqs/dto/sqs.dto.ts +++ /dev/null @@ -1,4 +0,0 @@ -export class SqsDto { - enabled: boolean; - events?: string[]; -} diff --git a/src/api/integrations/sqs/libs/sqs.server.ts b/src/api/integrations/sqs/libs/sqs.server.ts deleted file mode 100644 index 18507577..00000000 --- a/src/api/integrations/sqs/libs/sqs.server.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { SQS } from '@aws-sdk/client-sqs'; -import { JsonValue } from '@prisma/client/runtime/library'; - -import { configService, Sqs } from '../../../../config/env.config'; -import { Logger } from '../../../../config/logger.config'; - -const logger = new Logger('SQS'); - -let sqs: SQS; - -export const initSQS = () => { - // eslint-disable-next-line @typescript-eslint/no-unused-vars - return new Promise((resolve, reject) => { - const awsConfig = configService.get('SQS'); - sqs = new SQS({ - credentials: { - accessKeyId: awsConfig.ACCESS_KEY_ID, - secretAccessKey: awsConfig.SECRET_ACCESS_KEY, - }, - - region: awsConfig.REGION, - }); - - logger.info('SQS initialized'); - resolve(); - }); -}; - -export const getSQS = (): SQS => { - return sqs; -}; - -export const initQueues = (instanceName: string, events: string[]) => { - if (!events || !events.length) return; - - const queues = events.map((event) => { - return `${event.replace(/_/g, '_').toLowerCase()}`; - }); - - const sqs = getSQS(); - - queues.forEach((event) => { - const queueName = `${instanceName}_${event}.fifo`; - - sqs.createQueue( - { - QueueName: queueName, - Attributes: { - FifoQueue: 'true', - }, - }, - (err, data) => { - if (err) { - logger.error(`Error creating queue ${queueName}: ${err.message}`); - } else { - logger.info(`Queue ${queueName} created: ${data.QueueUrl}`); - } - }, - ); - }); -}; - -export const removeQueues = (instanceName: string, events: JsonValue) => { - const eventsArray = Array.isArray(events) ? events.map((event) => String(event)) : []; - if (!events || !eventsArray.length) return; - - const sqs = getSQS(); - - const queues = eventsArray.map((event) => { - return `${event.replace(/_/g, '_').toLowerCase()}`; - }); - - queues.forEach((event) => { - const queueName = `${instanceName}_${event}.fifo`; - - sqs.getQueueUrl( - { - QueueName: queueName, - }, - (err, data) => { - if (err) { - logger.error(`Error getting queue URL for ${queueName}: ${err.message}`); - } else { - const queueUrl = data.QueueUrl; - - sqs.deleteQueue( - { - QueueUrl: queueUrl, - }, - (deleteErr) => { - if (deleteErr) { - logger.error(`Error deleting queue ${queueName}: ${deleteErr.message}`); - } else { - logger.info(`Queue ${queueName} deleted`); - } - }, - ); - } - }, - ); - }); -}; diff --git a/src/api/integrations/sqs/routes/sqs.router.ts b/src/api/integrations/sqs/routes/sqs.router.ts deleted file mode 100644 index 3d740770..00000000 --- a/src/api/integrations/sqs/routes/sqs.router.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { RequestHandler, Router } from 'express'; - -import { instanceSchema, sqsSchema } from '../../../../validate/validate.schema'; -import { RouterBroker } from '../../../abstract/abstract.router'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { HttpStatus } from '../../../routes/index.router'; -import { sqsController } from '../../../server.module'; -import { SqsDto } from '../dto/sqs.dto'; - -export class SqsRouter extends RouterBroker { - constructor(...guards: RequestHandler[]) { - super(); - this.router - .post(this.routerPath('set'), ...guards, async (req, res) => { - const response = await this.dataValidate({ - request: req, - schema: sqsSchema, - ClassRef: SqsDto, - execute: (instance, data) => sqsController.createSqs(instance, data), - }); - - res.status(HttpStatus.CREATED).json(response); - }) - .get(this.routerPath('find'), ...guards, async (req, res) => { - const response = await this.dataValidate({ - request: req, - schema: instanceSchema, - ClassRef: InstanceDto, - execute: (instance) => sqsController.findSqs(instance), - }); - - res.status(HttpStatus.OK).json(response); - }); - } - - public readonly router = Router(); -} diff --git a/src/api/integrations/sqs/services/sqs.service.ts b/src/api/integrations/sqs/services/sqs.service.ts deleted file mode 100644 index 30f15282..00000000 --- a/src/api/integrations/sqs/services/sqs.service.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { Sqs } from '@prisma/client'; - -import { Logger } from '../../../../config/logger.config'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { WAMonitoringService } from '../../../services/monitor.service'; -import { SqsDto } from '../dto/sqs.dto'; -import { initQueues } from '../libs/sqs.server'; - -export class SqsService { - constructor(private readonly waMonitor: WAMonitoringService) {} - - private readonly logger = new Logger(SqsService.name); - - public create(instance: InstanceDto, data: SqsDto) { - this.waMonitor.waInstances[instance.instanceName].setSqs(data); - - initQueues(instance.instanceName, data.events); - return { sqs: { ...instance, sqs: data } }; - } - - public async find(instance: InstanceDto): Promise { - try { - const result = await this.waMonitor.waInstances[instance.instanceName].findSqs(); - - if (Object.keys(result).length === 0) { - throw new Error('Sqs not found'); - } - - return result; - } catch (error) { - return null; - } - } -} diff --git a/src/api/integrations/sqs/validate/sqs.schema.ts b/src/api/integrations/sqs/validate/sqs.schema.ts deleted file mode 100644 index 4bea583c..00000000 --- a/src/api/integrations/sqs/validate/sqs.schema.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { JSONSchema7 } from 'json-schema'; -import { v4 } from 'uuid'; - -const isNotEmpty = (...propertyNames: string[]): JSONSchema7 => { - const properties = {}; - propertyNames.forEach( - (property) => - (properties[property] = { - minLength: 1, - description: `The "${property}" cannot be empty`, - }), - ); - return { - if: { - propertyNames: { - enum: [...propertyNames], - }, - }, - then: { properties }, - }; -}; - -export const sqsSchema: JSONSchema7 = { - $id: v4(), - type: 'object', - properties: { - enabled: { type: 'boolean', enum: [true, false] }, - events: { - type: 'array', - minItems: 0, - items: { - type: 'string', - enum: [ - 'APPLICATION_STARTUP', - 'QRCODE_UPDATED', - 'MESSAGES_SET', - 'MESSAGES_UPSERT', - 'MESSAGES_EDITED', - 'MESSAGES_UPDATE', - 'MESSAGES_DELETE', - 'SEND_MESSAGE', - 'CONTACTS_SET', - 'CONTACTS_UPSERT', - 'CONTACTS_UPDATE', - 'PRESENCE_UPDATE', - 'CHATS_SET', - 'CHATS_UPSERT', - 'CHATS_UPDATE', - 'CHATS_DELETE', - 'GROUPS_UPSERT', - 'GROUP_UPDATE', - 'GROUP_PARTICIPANTS_UPDATE', - 'CONNECTION_UPDATE', - 'LABELS_EDIT', - 'LABELS_ASSOCIATION', - 'CALL', - 'TYPEBOT_START', - 'TYPEBOT_CHANGE_STATUS', - ], - }, - }, - }, - required: ['enabled'], - ...isNotEmpty('enabled'), -}; diff --git a/src/api/integrations/s3/controllers/s3.controller.ts b/src/api/integrations/storage/s3/controllers/s3.controller.ts similarity index 62% rename from src/api/integrations/s3/controllers/s3.controller.ts rename to src/api/integrations/storage/s3/controllers/s3.controller.ts index 132b6f76..a72adc64 100644 --- a/src/api/integrations/s3/controllers/s3.controller.ts +++ b/src/api/integrations/storage/s3/controllers/s3.controller.ts @@ -1,6 +1,6 @@ -import { InstanceDto } from '../../../dto/instance.dto'; -import { MediaDto } from '../dto/media.dto'; -import { S3Service } from '../services/s3.service'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { MediaDto } from '@api/integrations/storage/s3/dto/media.dto'; +import { S3Service } from '@api/integrations/storage/s3/services/s3.service'; export class S3Controller { constructor(private readonly s3Service: S3Service) {} diff --git a/src/api/integrations/s3/dto/media.dto.ts b/src/api/integrations/storage/s3/dto/media.dto.ts similarity index 100% rename from src/api/integrations/s3/dto/media.dto.ts rename to src/api/integrations/storage/s3/dto/media.dto.ts diff --git a/src/api/integrations/s3/libs/minio.server.ts b/src/api/integrations/storage/s3/libs/minio.server.ts similarity index 74% rename from src/api/integrations/s3/libs/minio.server.ts rename to src/api/integrations/storage/s3/libs/minio.server.ts index a2afb305..70869cd8 100644 --- a/src/api/integrations/s3/libs/minio.server.ts +++ b/src/api/integrations/storage/s3/libs/minio.server.ts @@ -1,11 +1,10 @@ +import { ConfigService, S3 } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { BadRequestException } from '@exceptions'; import * as MinIo from 'minio'; import { join } from 'path'; import { Readable, Transform } from 'stream'; -import { ConfigService, S3 } from '../../../../config/env.config'; -import { Logger } from '../../../../config/logger.config'; -import { BadRequestException } from '../../../../exceptions'; - const logger = new Logger('S3 Service'); const BUCKET = new ConfigService().get('S3'); @@ -22,6 +21,7 @@ const minioClient = (() => { useSSL: BUCKET.USE_SSL, accessKey: BUCKET.ACCESS_KEY, secretKey: BUCKET.SECRET_KEY, + region: BUCKET.REGION, }); } })(); @@ -39,6 +39,23 @@ const bucketExists = async () => { } }; +const setBucketPolicy = async () => { + if (minioClient) { + const policy = { + Version: '2012-10-17', + Statement: [ + { + Effect: 'Allow', + Principal: '*', + Action: ['s3:GetObject'], + Resource: [`arn:aws:s3:::${bucketName}/*`], + }, + ], + }; + await minioClient.setBucketPolicy(bucketName, JSON.stringify(policy)); + } +}; + const createBucket = async () => { if (minioClient) { try { @@ -47,10 +64,13 @@ const createBucket = async () => { await minioClient.makeBucket(bucketName); } + await setBucketPolicy(); + logger.info(`S3 Bucket ${bucketName} - ON`); return true; } catch (error) { - console.log('S3 ERROR: ', error); + logger.error('S3 ERROR:'); + logger.error(error); return false; } } @@ -65,7 +85,7 @@ const uploadFile = async (fileName: string, file: Buffer | Transform | Readable, metadata['custom-header-application'] = 'evolution-api'; return await minioClient.putObject(bucketName, objectName, file, size, metadata); } catch (error) { - console.log('ERROR: ', error); + logger.error(error); return error; } } diff --git a/src/api/integrations/s3/routes/s3.router.ts b/src/api/integrations/storage/s3/routes/s3.router.ts similarity index 71% rename from src/api/integrations/s3/routes/s3.router.ts rename to src/api/integrations/storage/s3/routes/s3.router.ts index bdbabc1d..0ef8379e 100644 --- a/src/api/integrations/s3/routes/s3.router.ts +++ b/src/api/integrations/storage/s3/routes/s3.router.ts @@ -1,11 +1,10 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { MediaDto } from '@api/integrations/storage/s3/dto/media.dto'; +import { s3Schema, s3UrlSchema } from '@api/integrations/storage/s3/validate/s3.schema'; +import { HttpStatus } from '@api/routes/index.router'; +import { s3Controller } from '@api/server.module'; import { RequestHandler, Router } from 'express'; -import { RouterBroker } from '../../../abstract/abstract.router'; -import { HttpStatus } from '../../../routes/index.router'; -import { s3Controller } from '../../../server.module'; -import { MediaDto } from '../dto/media.dto'; -import { s3Schema, s3UrlSchema } from '../validate/s3.schema'; - export class S3Router extends RouterBroker { constructor(...guards: RequestHandler[]) { super(); @@ -32,5 +31,5 @@ export class S3Router extends RouterBroker { }); } - public readonly router = Router(); + public readonly router: Router = Router(); } diff --git a/src/api/integrations/s3/services/s3.service.ts b/src/api/integrations/storage/s3/services/s3.service.ts similarity index 69% rename from src/api/integrations/s3/services/s3.service.ts rename to src/api/integrations/storage/s3/services/s3.service.ts index 30ababbb..3a0c913b 100644 --- a/src/api/integrations/s3/services/s3.service.ts +++ b/src/api/integrations/storage/s3/services/s3.service.ts @@ -1,14 +1,14 @@ -import { Logger } from '../../../../config/logger.config'; -import { BadRequestException } from '../../../../exceptions'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { PrismaRepository } from '../../../repository/repository.service'; -import { MediaDto } from '../dto/media.dto'; -import { getObjectUrl } from '../libs/minio.server'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { MediaDto } from '@api/integrations/storage/s3/dto/media.dto'; +import { getObjectUrl } from '@api/integrations/storage/s3/libs/minio.server'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { Logger } from '@config/logger.config'; +import { BadRequestException } from '@exceptions'; export class S3Service { constructor(private readonly prismaRepository: PrismaRepository) {} - private readonly logger = new Logger(S3Service.name); + private readonly logger = new Logger('S3Service'); public async getMedia(instance: InstanceDto, query?: MediaDto) { try { diff --git a/src/api/integrations/s3/validate/s3.schema.ts b/src/api/integrations/storage/s3/validate/s3.schema.ts similarity index 100% rename from src/api/integrations/s3/validate/s3.schema.ts rename to src/api/integrations/storage/s3/validate/s3.schema.ts diff --git a/src/api/integrations/storage/storage.router.ts b/src/api/integrations/storage/storage.router.ts new file mode 100644 index 00000000..7bbcb837 --- /dev/null +++ b/src/api/integrations/storage/storage.router.ts @@ -0,0 +1,12 @@ +import { S3Router } from '@api/integrations/storage/s3/routes/s3.router'; +import { Router } from 'express'; + +export class StorageRouter { + public readonly router: Router; + + constructor(...guards: any[]) { + this.router = Router(); + + this.router.use('/s3', new S3Router(...guards).router); + } +} diff --git a/src/api/integrations/typebot/controllers/typebot.controller.ts b/src/api/integrations/typebot/controllers/typebot.controller.ts deleted file mode 100644 index a73771c1..00000000 --- a/src/api/integrations/typebot/controllers/typebot.controller.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { configService, Typebot } from '../../../../config/env.config'; -import { BadRequestException } from '../../../../exceptions'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { TypebotDto, TypebotIgnoreJidDto } from '../dto/typebot.dto'; -import { TypebotService } from '../services/typebot.service'; - -export class TypebotController { - constructor(private readonly typebotService: TypebotService) {} - - public async createTypebot(instance: InstanceDto, data: TypebotDto) { - if (!configService.get('TYPEBOT').ENABLED) throw new BadRequestException('Typebot is disabled'); - - return this.typebotService.create(instance, data); - } - - public async findTypebot(instance: InstanceDto) { - if (!configService.get('TYPEBOT').ENABLED) throw new BadRequestException('Typebot is disabled'); - - return this.typebotService.find(instance); - } - - public async fetchTypebot(instance: InstanceDto, typebotId: string) { - if (!configService.get('TYPEBOT').ENABLED) throw new BadRequestException('Typebot is disabled'); - - return this.typebotService.fetch(instance, typebotId); - } - - public async updateTypebot(instance: InstanceDto, typebotId: string, data: TypebotDto) { - if (!configService.get('TYPEBOT').ENABLED) throw new BadRequestException('Typebot is disabled'); - - return this.typebotService.update(instance, typebotId, data); - } - - public async deleteTypebot(instance: InstanceDto, typebotId: string) { - if (!configService.get('TYPEBOT').ENABLED) throw new BadRequestException('Typebot is disabled'); - - return this.typebotService.delete(instance, typebotId); - } - - public async startTypebot(instance: InstanceDto, data: any) { - if (!configService.get('TYPEBOT').ENABLED) throw new BadRequestException('Typebot is disabled'); - - return this.typebotService.startTypebot(instance, data); - } - - public async settings(instance: InstanceDto, data: any) { - if (!configService.get('TYPEBOT').ENABLED) throw new BadRequestException('Typebot is disabled'); - - return this.typebotService.setDefaultSettings(instance, data); - } - - public async fetchSettings(instance: InstanceDto) { - if (!configService.get('TYPEBOT').ENABLED) throw new BadRequestException('Typebot is disabled'); - - return this.typebotService.fetchDefaultSettings(instance); - } - - public async changeStatus(instance: InstanceDto, data: any) { - if (!configService.get('TYPEBOT').ENABLED) throw new BadRequestException('Typebot is disabled'); - - return this.typebotService.changeStatus(instance, data); - } - - public async fetchSessions(instance: InstanceDto, typebotId: string) { - if (!configService.get('TYPEBOT').ENABLED) throw new BadRequestException('Typebot is disabled'); - - return this.typebotService.fetchSessions(instance, typebotId); - } - - public async ignoreJid(instance: InstanceDto, data: TypebotIgnoreJidDto) { - if (!configService.get('TYPEBOT').ENABLED) throw new BadRequestException('Typebot is disabled'); - - return this.typebotService.ignoreJid(instance, data); - } -} diff --git a/src/api/integrations/typebot/services/typebot.service.ts b/src/api/integrations/typebot/services/typebot.service.ts deleted file mode 100644 index 8c98a0cd..00000000 --- a/src/api/integrations/typebot/services/typebot.service.ts +++ /dev/null @@ -1,1991 +0,0 @@ -import { Message, Typebot as TypebotModel, TypebotSession } from '@prisma/client'; -import axios from 'axios'; - -import { Auth, ConfigService, HttpServer, S3, Typebot } from '../../../../config/env.config'; -import { Logger } from '../../../../config/logger.config'; -import { sendTelemetry } from '../../../../utils/sendTelemetry'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { PrismaRepository } from '../../../repository/repository.service'; -import { WAMonitoringService } from '../../../services/monitor.service'; -import { Events } from '../../../types/wa.types'; -import { TypebotDto, TypebotIgnoreJidDto } from '../dto/typebot.dto'; - -export class TypebotService { - constructor( - private readonly waMonitor: WAMonitoringService, - private readonly configService: ConfigService, - private readonly prismaRepository: PrismaRepository, - ) {} - - private userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; - - private readonly logger = new Logger(TypebotService.name); - - public async create(instance: InstanceDto, data: TypebotDto) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - if ( - !data.expire || - !data.keywordFinish || - !data.delayMessage || - !data.unknownMessage || - !data.listeningFromMe || - !data.stopBotFromMe || - !data.keepOpen || - !data.debounceTime || - !data.ignoreJids - ) { - const defaultSettingCheck = await this.prismaRepository.typebotSetting.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (!data.expire) data.expire = defaultSettingCheck?.expire || 0; - if (!data.keywordFinish) data.keywordFinish = defaultSettingCheck?.keywordFinish || '#SAIR'; - if (!data.delayMessage) data.delayMessage = defaultSettingCheck?.delayMessage || 1000; - if (!data.unknownMessage) data.unknownMessage = defaultSettingCheck?.unknownMessage || 'Desculpe, não entendi'; - if (!data.listeningFromMe) data.listeningFromMe = defaultSettingCheck?.listeningFromMe || false; - if (!data.stopBotFromMe) data.stopBotFromMe = defaultSettingCheck?.stopBotFromMe || false; - if (!data.keepOpen) data.keepOpen = defaultSettingCheck?.keepOpen || false; - if (!data.debounceTime) data.debounceTime = defaultSettingCheck?.debounceTime || 0; - if (!data.ignoreJids) data.ignoreJids = defaultSettingCheck?.ignoreJids || []; - - if (!defaultSettingCheck) { - await this.setDefaultSettings(instance, { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - ignoreJids: data.ignoreJids, - }); - } - } - - const checkTriggerAll = await this.prismaRepository.typebot.findFirst({ - where: { - enabled: true, - triggerType: 'all', - instanceId: instanceId, - }, - }); - - if (checkTriggerAll && data.triggerType === 'all') { - throw new Error('You already have a typebot with an "All" trigger, you cannot have more bots while it is active'); - } - - const checkDuplicate = await this.prismaRepository.typebot.findFirst({ - where: { - url: data.url, - typebot: data.typebot, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Typebot already exists'); - } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.prismaRepository.typebot.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const typebot = await this.prismaRepository.typebot.create({ - data: { - enabled: data.enabled, - description: data.description, - url: data.url, - typebot: data.typebot, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - }, - }); - - return typebot; - } catch (error) { - this.logger.error(error); - throw new Error('Error creating typebot'); - } - } - - public async fetch(instance: InstanceDto, typebotId: string) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const typebot = await this.prismaRepository.typebot.findFirst({ - where: { - id: typebotId, - }, - include: { - sessions: true, - }, - }); - - if (!typebot) { - throw new Error('Typebot not found'); - } - - if (typebot.instanceId !== instanceId) { - throw new Error('Typebot not found'); - } - - return typebot; - } - - public async update(instance: InstanceDto, typebotId: string, data: any) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const typebot = await this.prismaRepository.typebot.findFirst({ - where: { - id: typebotId, - }, - }); - - if (!typebot) { - throw new Error('Typebot not found'); - } - - if (typebot.instanceId !== instanceId) { - throw new Error('Typebot not found'); - } - - if (data.triggerType === 'all') { - const checkTriggerAll = await this.prismaRepository.typebot.findFirst({ - where: { - enabled: true, - triggerType: 'all', - id: { - not: typebotId, - }, - instanceId: instanceId, - }, - }); - - if (checkTriggerAll) { - throw new Error( - 'You already have a typebot with an "All" trigger, you cannot have more bots while it is active', - ); - } - } - - const checkDuplicate = await this.prismaRepository.typebot.findFirst({ - where: { - url: data.url, - typebot: data.typebot, - id: { - not: typebotId, - }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Typebot already exists'); - } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.prismaRepository.typebot.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - id: { - not: typebotId, - }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const typebot = await this.prismaRepository.typebot.update({ - where: { - id: typebotId, - }, - data: { - enabled: data.enabled, - url: data.url, - typebot: data.typebot, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - }, - }); - - return typebot; - } catch (error) { - this.logger.error(error); - throw new Error('Error updating typebot'); - } - } - - public async find(instance: InstanceDto): Promise { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const typebots = await this.prismaRepository.typebot.findMany({ - where: { - instanceId: instanceId, - }, - include: { - sessions: true, - }, - }); - - if (!typebots.length) { - return null; - } - - return typebots; - } - - public async delete(instance: InstanceDto, typebotId: string) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const typebot = await this.prismaRepository.typebot.findFirst({ - where: { - id: typebotId, - }, - }); - - if (!typebot) { - throw new Error('Typebot not found'); - } - - if (typebot.instanceId !== instanceId) { - throw new Error('Typebot not found'); - } - try { - await this.prismaRepository.typebotSession.deleteMany({ - where: { - typebotId: typebotId, - }, - }); - - await this.prismaRepository.typebot.delete({ - where: { - id: typebotId, - }, - }); - - return { typebot: { id: typebotId } }; - } catch (error) { - this.logger.error(error); - throw new Error('Error deleting typebot'); - } - } - - public async setDefaultSettings(instance: InstanceDto, data: any) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.prismaRepository.typebotSetting.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (settings) { - const updateSettings = await this.prismaRepository.typebotSetting.update({ - where: { - id: settings.id, - }, - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - typebotIdFallback: data.typebotIdFallback, - ignoreJids: data.ignoreJids, - }, - }); - - return { - expire: updateSettings.expire, - keywordFinish: updateSettings.keywordFinish, - delayMessage: updateSettings.delayMessage, - unknownMessage: updateSettings.unknownMessage, - listeningFromMe: updateSettings.listeningFromMe, - stopBotFromMe: updateSettings.stopBotFromMe, - keepOpen: updateSettings.keepOpen, - debounceTime: updateSettings.debounceTime, - typebotIdFallback: updateSettings.typebotIdFallback, - ignoreJids: updateSettings.ignoreJids, - }; - } - - const newSetttings = await this.prismaRepository.typebotSetting.create({ - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - typebotIdFallback: data.typebotIdFallback, - ignoreJids: data.ignoreJids, - instanceId: instanceId, - }, - }); - - return { - expire: newSetttings.expire, - keywordFinish: newSetttings.keywordFinish, - delayMessage: newSetttings.delayMessage, - unknownMessage: newSetttings.unknownMessage, - listeningFromMe: newSetttings.listeningFromMe, - stopBotFromMe: newSetttings.stopBotFromMe, - keepOpen: newSetttings.keepOpen, - debounceTime: newSetttings.debounceTime, - typebotIdFallback: newSetttings.typebotIdFallback, - ignoreJids: newSetttings.ignoreJids, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - public async fetchDefaultSettings(instance: InstanceDto) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.prismaRepository.typebotSetting.findFirst({ - where: { - instanceId: instanceId, - }, - include: { - Fallback: true, - }, - }); - - if (!settings) { - return { - expire: 0, - keywordFinish: '', - delayMessage: 0, - unknownMessage: '', - listeningFromMe: false, - stopBotFromMe: false, - keepOpen: false, - ignoreJids: [], - typebotIdFallback: null, - fallback: null, - }; - } - - return { - expire: settings.expire, - keywordFinish: settings.keywordFinish, - delayMessage: settings.delayMessage, - unknownMessage: settings.unknownMessage, - listeningFromMe: settings.listeningFromMe, - stopBotFromMe: settings.stopBotFromMe, - keepOpen: settings.keepOpen, - ignoreJids: settings.ignoreJids, - typebotIdFallback: settings.typebotIdFallback, - fallback: settings.Fallback, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching default settings'); - } - } - - public async ignoreJid(instance: InstanceDto, data: TypebotIgnoreJidDto) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.prismaRepository.typebotSetting.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (!settings) { - throw new Error('Settings not found'); - } - - let ignoreJids: any = settings?.ignoreJids || []; - - if (data.action === 'add') { - if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; - - ignoreJids.push(data.remoteJid); - } else { - ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); - } - - const updateSettings = await this.prismaRepository.typebotSetting.update({ - where: { - id: settings.id, - }, - data: { - ignoreJids: ignoreJids, - }, - }); - - return { - ignoreJids: updateSettings.ignoreJids, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - public async fetchSessions(instance: InstanceDto, typebotId?: string, remoteJid?: string) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const typebot = await this.prismaRepository.typebot.findFirst({ - where: { - id: typebotId, - }, - }); - - if (!typebot) { - throw new Error('Typebot not found'); - } - - if (typebot.instanceId !== instanceId) { - throw new Error('Typebot not found'); - } - - if (typebotId) { - return await this.prismaRepository.typebotSession.findMany({ - where: { - typebotId: typebotId, - }, - }); - } - - if (remoteJid) { - return await this.prismaRepository.typebotSession.findMany({ - where: { - remoteJid: remoteJid, - instanceId: instanceId, - }, - }); - } - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching sessions'); - } - } - - public async changeStatus(instance: InstanceDto, data: any) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const remoteJid = data.remoteJid; - const status = data.status; - - const defaultSettingCheck = await this.prismaRepository.typebotSetting.findFirst({ - where: { - instanceId, - }, - }); - - if (status === 'delete') { - await this.prismaRepository.typebotSession.deleteMany({ - where: { - remoteJid: remoteJid, - instanceId: instanceId, - }, - }); - - return { typebot: { ...instance, typebot: { remoteJid: remoteJid, status: status } } }; - } - - if (status === 'closed') { - if (defaultSettingCheck?.keepOpen) { - await this.prismaRepository.typebotSession.updateMany({ - where: { - instanceId: instanceId, - remoteJid: remoteJid, - }, - data: { - status: status, - }, - }); - } else { - await this.prismaRepository.typebotSession.deleteMany({ - where: { - remoteJid: remoteJid, - instanceId: instanceId, - }, - }); - } - - return { typebot: { ...instance, typebot: { remoteJid: remoteJid, status: status } } }; - } - - const session = await this.prismaRepository.typebotSession.updateMany({ - where: { - instanceId: instanceId, - remoteJid: remoteJid, - }, - data: { - status: status, - }, - }); - - const typebotData = { - remoteJid: remoteJid, - status: status, - session, - }; - - this.waMonitor.waInstances[instance.instanceName].sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData); - - return { typebot: { ...instance, typebot: typebotData } }; - } catch (error) { - this.logger.error(error); - throw new Error('Error changing status'); - } - } - - public async startTypebot(instance: InstanceDto, data: any) { - if (data.remoteJid === 'status@broadcast') return; - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const remoteJid = data.remoteJid; - const url = data.url; - const typebot = data.typebot; - const startSession = data.startSession; - const variables = data.variables; - let expire = data?.typebot?.expire; - let keywordFinish = data?.typebot?.keywordFinish; - let delayMessage = data?.typebot?.delayMessage; - let unknownMessage = data?.typebot?.unknownMessage; - let listeningFromMe = data?.typebot?.listeningFromMe; - let stopBotFromMe = data?.typebot?.stopBotFromMe; - let keepOpen = data?.typebot?.keepOpen; - - const defaultSettingCheck = await this.prismaRepository.typebotSetting.findFirst({ - where: { - instanceId, - }, - }); - - if (defaultSettingCheck?.ignoreJids) { - const ignoreJids: any = defaultSettingCheck.ignoreJids; - - let ignoreGroups = false; - let ignoreContacts = false; - - if (ignoreJids.includes('@g.us')) { - ignoreGroups = true; - } - - if (ignoreJids.includes('@s.whatsapp.net')) { - ignoreContacts = true; - } - - if (ignoreGroups && remoteJid.includes('@g.us')) { - this.logger.warn('Ignoring message from group: ' + remoteJid); - throw new Error('Group not allowed'); - } - - if (ignoreContacts && remoteJid.includes('@s.whatsapp.net')) { - this.logger.warn('Ignoring message from contact: ' + remoteJid); - throw new Error('Contact not allowed'); - } - - if (ignoreJids.includes(remoteJid)) { - this.logger.warn('Ignoring message from jid: ' + remoteJid); - throw new Error('Jid not allowed'); - } - } - - if ( - !expire || - !keywordFinish || - !delayMessage || - !unknownMessage || - !listeningFromMe || - !stopBotFromMe || - !keepOpen - ) { - if (!expire) expire = defaultSettingCheck?.expire || 0; - if (!keywordFinish) keywordFinish = defaultSettingCheck?.keywordFinish || '#SAIR'; - if (!delayMessage) delayMessage = defaultSettingCheck?.delayMessage || 1000; - if (!unknownMessage) unknownMessage = defaultSettingCheck?.unknownMessage || 'Desculpe, não entendi'; - if (!listeningFromMe) listeningFromMe = defaultSettingCheck?.listeningFromMe || false; - if (!stopBotFromMe) stopBotFromMe = defaultSettingCheck?.stopBotFromMe || false; - if (!keepOpen) keepOpen = defaultSettingCheck?.keepOpen || false; - - if (!defaultSettingCheck) { - await this.setDefaultSettings(instance, { - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - stopBotFromMe: stopBotFromMe, - keepOpen: keepOpen, - }); - } - } - - const prefilledVariables = { - remoteJid: remoteJid, - instanceName: instance.instanceName, - serverUrl: this.configService.get('SERVER').URL, - apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, - }; - - if (variables?.length) { - variables.forEach((variable: { name: string | number; value: string }) => { - prefilledVariables[variable.name] = variable.value; - }); - } - - if (startSession) { - let findTypebot: any = await this.prismaRepository.typebot.findFirst({ - where: { - url: url, - typebot: typebot, - instanceId, - }, - }); - - if (!findTypebot) { - findTypebot = await this.prismaRepository.typebot.create({ - data: { - enabled: true, - url: url, - typebot: typebot, - expire: expire, - triggerType: 'none', - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - stopBotFromMe: stopBotFromMe, - keepOpen: keepOpen, - instanceId, - }, - }); - } - - await this.prismaRepository.typebotSession.deleteMany({ - where: { - remoteJid: remoteJid, - instanceId, - }, - }); - - const response = await this.createNewSession( - { - instanceName: instance.instanceName, - instanceId: instanceId, - }, - { - enabled: true, - url: url, - typebot: typebot, - remoteJid: remoteJid, - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - stopBotFromMe: stopBotFromMe, - keepOpen: keepOpen, - prefilledVariables: prefilledVariables, - typebotId: findTypebot.id, - }, - ); - - if (response.sessionId) { - await this.sendWAMessage( - instance, - response.session, - { - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - stopBotFromMe: stopBotFromMe, - keepOpen: keepOpen, - }, - remoteJid, - response.messages, - response.input, - response.clientSideActions, - ); - - this.waMonitor.waInstances[instance.instanceName].sendDataWebhook(Events.TYPEBOT_START, { - remoteJid: remoteJid, - url: url, - typebot: typebot, - prefilledVariables: prefilledVariables, - sessionId: `${response.sessionId}`, - }); - } else { - throw new Error('Session ID not found in response'); - } - } else { - const id = Math.floor(Math.random() * 10000000000).toString(); - - try { - const version = this.configService.get('TYPEBOT').API_VERSION; - let url: string; - let reqData: {}; - if (version === 'latest') { - url = `${data.url}/api/v1/typebots/${data.typebot}/startChat`; - - reqData = { - prefilledVariables: prefilledVariables, - }; - } else { - url = `${data.url}/api/v1/sendMessage`; - - reqData = { - startParams: { - publicId: data.typebot, - prefilledVariables: prefilledVariables, - }, - }; - } - const request = await axios.post(url, reqData); - - await this.sendWAMessage( - instance, - null, - { - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - stopBotFromMe: stopBotFromMe, - keepOpen: keepOpen, - }, - remoteJid, - request.data.messages, - request.data.input, - request.data.clientSideActions, - ); - - this.waMonitor.waInstances[instance.instanceName].sendDataWebhook(Events.TYPEBOT_START, { - remoteJid: remoteJid, - url: url, - typebot: typebot, - variables: variables, - sessionId: id, - }); - } catch (error) { - this.logger.error(error); - return; - } - } - - return { - typebot: { - ...instance, - typebot: { - url: url, - remoteJid: remoteJid, - typebot: typebot, - prefilledVariables: prefilledVariables, - }, - }, - }; - } - - private getTypeMessage(msg: any) { - let mediaId: string; - - if (this.configService.get('S3').ENABLE) mediaId = msg.message.mediaUrl; - else mediaId = msg.key.id; - - const types = { - conversation: msg?.message?.conversation, - extendedTextMessage: msg?.message?.extendedTextMessage?.text, - contactMessage: msg?.message?.contactMessage?.displayName, - locationMessage: msg?.message?.locationMessage?.degreesLatitude, - viewOnceMessageV2: - msg?.message?.viewOnceMessageV2?.message?.imageMessage?.url || - msg?.message?.viewOnceMessageV2?.message?.videoMessage?.url || - msg?.message?.viewOnceMessageV2?.message?.audioMessage?.url, - listResponseMessage: msg?.message?.listResponseMessage?.singleSelectReply?.selectedRowId, - responseRowId: msg?.message?.listResponseMessage?.singleSelectReply?.selectedRowId, - // Medias - audioMessage: msg?.message?.speechToText - ? msg?.message?.speechToText - : msg?.message?.audioMessage - ? `audioMessage|${mediaId}` - : undefined, - imageMessage: msg?.message?.imageMessage ? `imageMessage|${mediaId}` : undefined, - videoMessage: msg?.message?.videoMessage ? `videoMessage|${mediaId}` : undefined, - documentMessage: msg?.message?.documentMessage ? `documentMessage|${mediaId}` : undefined, - documentWithCaptionMessage: msg?.message?.auddocumentWithCaptionMessageioMessage - ? `documentWithCaptionMessage|${mediaId}` - : undefined, - }; - - const messageType = Object.keys(types).find((key) => types[key] !== undefined) || 'unknown'; - - return { ...types, messageType }; - } - - private getMessageContent(types: any) { - const typeKey = Object.keys(types).find((key) => types[key] !== undefined); - - const result = typeKey ? types[typeKey] : undefined; - - return result; - } - - private getConversationMessage(msg: any) { - const types = this.getTypeMessage(msg); - - const messageContent = this.getMessageContent(types); - - return messageContent; - } - - public async createNewSession(instance: InstanceDto, data: any) { - if (data.remoteJid === 'status@broadcast') return; - const id = Math.floor(Math.random() * 10000000000).toString(); - - try { - const version = this.configService.get('TYPEBOT').API_VERSION; - let url: string; - let reqData: {}; - if (version === 'latest') { - url = `${data.url}/api/v1/typebots/${data.typebot}/startChat`; - - reqData = { - prefilledVariables: { - ...data.prefilledVariables, - remoteJid: data.remoteJid, - pushName: data.pushName || data.prefilledVariables?.pushName || '', - instanceName: instance.instanceName, - serverUrl: this.configService.get('SERVER').URL, - apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, - }, - }; - } else { - url = `${data.url}/api/v1/sendMessage`; - - reqData = { - startParams: { - publicId: data.typebot, - prefilledVariables: { - ...data.prefilledVariables, - remoteJid: data.remoteJid, - pushName: data.pushName || data.prefilledVariables?.pushName || '', - instanceName: instance.instanceName, - serverUrl: this.configService.get('SERVER').URL, - apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, - }, - }, - }; - } - const request = await axios.post(url, reqData); - - let session = null; - if (request?.data?.sessionId) { - session = await this.prismaRepository.typebotSession.create({ - data: { - remoteJid: data.remoteJid, - pushName: data.pushName || '', - sessionId: `${id}-${request.data.sessionId}`, - status: 'opened', - prefilledVariables: { - ...data.prefilledVariables, - remoteJid: data.remoteJid, - pushName: data.pushName || '', - instanceName: instance.instanceName, - serverUrl: this.configService.get('SERVER').URL, - apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, - }, - awaitUser: false, - typebotId: data.typebotId, - instanceId: instance.instanceId, - }, - }); - } - return { ...request.data, session }; - } catch (error) { - this.logger.error(error); - return; - } - } - - public async sendWAMessage( - instance: InstanceDto, - session: TypebotSession, - settings: { - expire: number; - keywordFinish: string; - delayMessage: number; - unknownMessage: string; - listeningFromMe: boolean; - stopBotFromMe: boolean; - keepOpen: boolean; - }, - remoteJid: string, - messages: any, - input: any, - clientSideActions: any, - ) { - processMessages( - this.waMonitor.waInstances[instance.instanceName], - session, - settings, - messages, - input, - clientSideActions, - applyFormatting, - this.prismaRepository, - ).catch((err) => { - console.error('Erro ao processar mensagens:', err); - }); - - function findItemAndGetSecondsToWait(array, targetId) { - if (!array) return null; - - for (const item of array) { - if (item.lastBubbleBlockId === targetId) { - return item.wait?.secondsToWaitFor; - } - } - return null; - } - - function applyFormatting(element) { - let text = ''; - - if (element.text) { - text += element.text; - } - - if (element.children && element.type !== 'a') { - for (const child of element.children) { - text += applyFormatting(child); - } - } - - if (element.type === 'p' && element.type !== 'inline-variable') { - text = text.trim() + '\n'; - } - - if (element.type === 'inline-variable') { - text = text.trim(); - } - - if (element.type === 'ol') { - text = - '\n' + - text - .split('\n') - .map((line, index) => (line ? `${index + 1}. ${line}` : '')) - .join('\n'); - } - - if (element.type === 'li') { - text = text - .split('\n') - .map((line) => (line ? ` ${line}` : '')) - .join('\n'); - } - - let formats = ''; - - if (element.bold) { - formats += '*'; - } - - if (element.italic) { - formats += '_'; - } - - if (element.underline) { - formats += '~'; - } - - let formattedText = `${formats}${text}${formats.split('').reverse().join('')}`; - - if (element.url) { - formattedText = element.children[0]?.text ? `[${formattedText}]\n(${element.url})` : `${element.url}`; - } - - return formattedText; - } - - async function processMessages( - instance: any, - session: TypebotSession, - settings: { - expire: number; - keywordFinish: string; - delayMessage: number; - unknownMessage: string; - listeningFromMe: boolean; - stopBotFromMe: boolean; - keepOpen: boolean; - }, - messages: any, - input: any, - clientSideActions: any, - applyFormatting: any, - prismaRepository: PrismaRepository, - ) { - for (const message of messages) { - if (message.type === 'text') { - let formattedText = ''; - - for (const richText of message.content.richText) { - for (const element of richText.children) { - formattedText += applyFormatting(element); - } - formattedText += '\n'; - } - - formattedText = formattedText.replace(/\*\*/g, '').replace(/__/, '').replace(/~~/, '').replace(/\n$/, ''); - - formattedText = formattedText.replace(/\n$/, ''); - - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: formattedText, - }, - false, - ); - - sendTelemetry('/message/sendText'); - } - - if (message.type === 'image') { - await instance.mediaMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - mediatype: 'image', - media: message.content.url, - }, - false, - ); - - sendTelemetry('/message/sendMedia'); - } - - if (message.type === 'video') { - await instance.mediaMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - mediatype: 'video', - media: message.content.url, - }, - false, - ); - - sendTelemetry('/message/sendMedia'); - } - - if (message.type === 'audio') { - await instance.audioWhatsapp( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - encoding: true, - audio: message.content.url, - }, - false, - ); - - sendTelemetry('/message/sendWhatsAppAudio'); - } - - const wait = findItemAndGetSecondsToWait(clientSideActions, message.id); - - if (wait) { - await new Promise((resolve) => setTimeout(resolve, wait * 1000)); - } - } - - if (input) { - if (input.type === 'choice input') { - let formattedText = ''; - - const items = input.items; - - for (const item of items) { - formattedText += `▶️ ${item.content}\n`; - } - - formattedText = formattedText.replace(/\n$/, ''); - - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: formattedText, - }, - false, - ); - - sendTelemetry('/message/sendText'); - } - - await prismaRepository.typebotSession.update({ - where: { - id: session.id, - }, - data: { - awaitUser: true, - }, - }); - } else { - if (!settings?.keepOpen) { - await prismaRepository.typebotSession.deleteMany({ - where: { - id: session.id, - }, - }); - } else { - await prismaRepository.typebotSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } - } - } - } - - public async findTypebotByTrigger(content: string, instanceId: string) { - // Check for triggerType 'all' - const findTriggerAll = await this.prismaRepository.typebot.findFirst({ - where: { - enabled: true, - triggerType: 'all', - instanceId: instanceId, - }, - }); - - if (findTriggerAll) return findTriggerAll; - - // Check for exact match - const findTriggerEquals = await this.prismaRepository.typebot.findFirst({ - where: { - enabled: true, - triggerType: 'keyword', - triggerOperator: 'equals', - triggerValue: content, - instanceId: instanceId, - }, - }); - - if (findTriggerEquals) return findTriggerEquals; - - // Check for regex match - const findRegex = await this.prismaRepository.typebot.findMany({ - where: { - enabled: true, - triggerType: 'keyword', - triggerOperator: 'regex', - instanceId: instanceId, - }, - }); - - let findTriggerRegex = null; - - for (const regex of findRegex) { - const regexValue = new RegExp(regex.triggerValue); - - if (regexValue.test(content)) { - findTriggerRegex = regex; - break; - } - } - - if (findTriggerRegex) return findTriggerRegex; - - // Check for startsWith match - const findStartsWith = await this.prismaRepository.typebot.findMany({ - where: { - enabled: true, - triggerType: 'keyword', - triggerOperator: 'startsWith', - instanceId: instanceId, - }, - }); - - let findTriggerStartsWith = null; - - for (const startsWith of findStartsWith) { - if (content.startsWith(startsWith.triggerValue)) { - findTriggerStartsWith = startsWith; - break; - } - } - - if (findTriggerStartsWith) return findTriggerStartsWith; - - // Check for endsWith match - const findEndsWith = await this.prismaRepository.typebot.findMany({ - where: { - enabled: true, - triggerType: 'keyword', - triggerOperator: 'endsWith', - instanceId: instanceId, - }, - }); - - let findTriggerEndsWith = null; - - for (const endsWith of findEndsWith) { - if (content.endsWith(endsWith.triggerValue)) { - findTriggerEndsWith = endsWith; - break; - } - } - - if (findTriggerEndsWith) return findTriggerEndsWith; - - // Check for contains match - const findContains = await this.prismaRepository.typebot.findMany({ - where: { - enabled: true, - triggerType: 'keyword', - triggerOperator: 'contains', - instanceId: instanceId, - }, - }); - - let findTriggerContains = null; - - for (const contains of findContains) { - if (content.includes(contains.triggerValue)) { - findTriggerContains = contains; - break; - } - } - - if (findTriggerContains) return findTriggerContains; - - const fallback = await this.prismaRepository.typebotSetting.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (fallback?.typebotIdFallback) { - const findFallback = await this.prismaRepository.typebot.findFirst({ - where: { - id: fallback.typebotIdFallback, - }, - }); - - if (findFallback) return findFallback; - } - - return null; - } - - private processDebounce(content: string, remoteJid: string, debounceTime: number, callback: any) { - if (this.userMessageDebounce[remoteJid]) { - this.userMessageDebounce[remoteJid].message += ` ${content}`; - this.logger.log('message debounced: ' + this.userMessageDebounce[remoteJid].message); - clearTimeout(this.userMessageDebounce[remoteJid].timeoutId); - } else { - this.userMessageDebounce[remoteJid] = { - message: content, - timeoutId: null, - }; - } - - this.userMessageDebounce[remoteJid].timeoutId = setTimeout(() => { - const myQuestion = this.userMessageDebounce[remoteJid].message; - this.logger.log('Debounce complete. Processing message: ' + myQuestion); - - delete this.userMessageDebounce[remoteJid]; - callback(myQuestion); - }, debounceTime * 1000); - } - - public async sendTypebot(instance: InstanceDto, remoteJid: string, msg: Message) { - try { - const settings = await this.prismaRepository.typebotSetting.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (settings?.ignoreJids) { - const ignoreJids: any = settings.ignoreJids; - - let ignoreGroups = false; - let ignoreContacts = false; - - if (ignoreJids.includes('@g.us')) { - ignoreGroups = true; - } - - if (ignoreJids.includes('@s.whatsapp.net')) { - ignoreContacts = true; - } - - if (ignoreGroups && remoteJid.endsWith('@g.us')) { - this.logger.warn('Ignoring message from group: ' + remoteJid); - return; - } - - if (ignoreContacts && remoteJid.endsWith('@s.whatsapp.net')) { - this.logger.warn('Ignoring message from contact: ' + remoteJid); - return; - } - - if (ignoreJids.includes(remoteJid)) { - this.logger.warn('Ignoring message from jid: ' + remoteJid); - return; - } - } - - const session = await this.prismaRepository.typebotSession.findFirst({ - where: { - remoteJid: remoteJid, - instanceId: instance.instanceId, - }, - }); - - const content = this.getConversationMessage(msg); - - let findTypebot = null; - - if (!session) { - findTypebot = await this.findTypebotByTrigger(content, instance.instanceId); - - if (!findTypebot) { - return; - } - } else { - findTypebot = await this.prismaRepository.typebot.findFirst({ - where: { - id: session.typebotId, - }, - }); - } - - const url = findTypebot?.url; - const typebot = findTypebot?.typebot; - let expire = findTypebot?.expire; - let keywordFinish = findTypebot?.keywordFinish; - let delayMessage = findTypebot?.delayMessage; - let unknownMessage = findTypebot?.unknownMessage; - let listeningFromMe = findTypebot?.listeningFromMe; - let stopBotFromMe = findTypebot?.stopBotFromMe; - let keepOpen = findTypebot?.keepOpen; - let debounceTime = findTypebot?.debounceTime; - - if ( - !expire || - !keywordFinish || - !delayMessage || - !unknownMessage || - !listeningFromMe || - !stopBotFromMe || - !keepOpen - ) { - if (!expire) expire = settings.expire; - - if (!keywordFinish) keywordFinish = settings.keywordFinish; - - if (!delayMessage) delayMessage = settings.delayMessage; - - if (!unknownMessage) unknownMessage = settings.unknownMessage; - - if (!listeningFromMe) listeningFromMe = settings.listeningFromMe; - - if (!stopBotFromMe) stopBotFromMe = settings.stopBotFromMe; - - if (!keepOpen) keepOpen = settings.keepOpen; - - if (!debounceTime) debounceTime = settings.debounceTime; - } - - const key = msg.key as { - id: string; - remoteJid: string; - fromMe: boolean; - participant: string; - }; - - if (stopBotFromMe && key.fromMe && session) { - if (keepOpen) { - await this.prismaRepository.typebotSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.typebotSession.deleteMany({ - where: { - typebotId: findTypebot.id, - remoteJid: remoteJid, - }, - }); - } - return; - } - - if (!listeningFromMe && key.fromMe) { - return; - } - - if (debounceTime && debounceTime > 0) { - this.processDebounce(content, remoteJid, debounceTime, async (debouncedContent) => { - await this.processTypebot( - instance, - remoteJid, - msg, - session, - findTypebot, - url, - expire, - typebot, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - debouncedContent, - ); - }); - } else { - await this.processTypebot( - instance, - remoteJid, - msg, - session, - findTypebot, - url, - expire, - typebot, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - content, - ); - } - - if (session && !session.awaitUser) return; - } catch (error) { - this.logger.error(error); - return; - } - } - - private async processTypebot( - instance: InstanceDto, - remoteJid: string, - msg: Message, - session: TypebotSession, - findTypebot: TypebotModel, - url: string, - expire: number, - typebot: string, - keywordFinish: string, - delayMessage: number, - unknownMessage: string, - listeningFromMe: boolean, - stopBotFromMe: boolean, - keepOpen: boolean, - content: string, - ) { - if (session && expire && expire > 0) { - const now = Date.now(); - - const sessionUpdatedAt = new Date(session.updatedAt).getTime(); - - const diff = now - sessionUpdatedAt; - - const diffInMinutes = Math.floor(diff / 1000 / 60); - - if (diffInMinutes > expire) { - if (keepOpen) { - await this.prismaRepository.typebotSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.typebotSession.deleteMany({ - where: { - typebotId: findTypebot.id, - remoteJid: remoteJid, - }, - }); - } - - const data = await this.createNewSession(instance, { - enabled: findTypebot.enabled, - url: url, - typebot: typebot, - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - remoteJid: remoteJid, - pushName: msg.pushName, - typebotId: findTypebot.id, - }); - - if (data.session) { - session = data.session; - } - - await this.sendWAMessage( - instance, - session, - { - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - stopBotFromMe: stopBotFromMe, - keepOpen: keepOpen, - }, - remoteJid, - data.messages, - data.input, - data.clientSideActions, - ); - - if (data.messages.length === 0) { - const content = this.getConversationMessage(msg.message); - - if (!content) { - if (unknownMessage) { - this.waMonitor.waInstances[instance.instanceName].textMessage( - { - number: remoteJid.split('@')[0], - delay: delayMessage || 1000, - text: unknownMessage, - }, - false, - ); - - sendTelemetry('/message/sendText'); - } - return; - } - - if (keywordFinish && content.toLowerCase() === keywordFinish.toLowerCase()) { - if (keepOpen) { - await this.prismaRepository.typebotSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.typebotSession.deleteMany({ - where: { - typebotId: findTypebot.id, - remoteJid: remoteJid, - }, - }); - } - return; - } - - try { - const version = this.configService.get('TYPEBOT').API_VERSION; - let urlTypebot: string; - let reqData: {}; - if (version === 'latest') { - urlTypebot = `${url}/api/v1/sessions/${data.sessionId}/continueChat`; - reqData = { - message: content, - }; - } else { - urlTypebot = `${url}/api/v1/sendMessage`; - reqData = { - message: content, - sessionId: data.sessionId, - }; - } - - const request = await axios.post(urlTypebot, reqData); - - await this.sendWAMessage( - instance, - session, - { - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - stopBotFromMe: stopBotFromMe, - keepOpen: keepOpen, - }, - remoteJid, - request.data.messages, - request.data.input, - request.data.clientSideActions, - ); - } catch (error) { - this.logger.error(error); - return; - } - } - - return; - } - } - - if (session && session.status !== 'opened') { - return; - } - - if (!session) { - const data = await this.createNewSession(instance, { - enabled: findTypebot?.enabled, - url: url, - typebot: typebot, - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - remoteJid: remoteJid, - pushName: msg.pushName, - typebotId: findTypebot.id, - }); - - if (data?.session) { - session = data.session; - } - - await this.sendWAMessage( - instance, - session, - { - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - stopBotFromMe: stopBotFromMe, - keepOpen: keepOpen, - }, - remoteJid, - data?.messages, - data?.input, - data?.clientSideActions, - ); - - if (data.messages.length === 0) { - if (!content) { - if (unknownMessage) { - this.waMonitor.waInstances[instance.instanceName].textMessage( - { - number: remoteJid.split('@')[0], - delay: delayMessage || 1000, - text: unknownMessage, - }, - false, - ); - - sendTelemetry('/message/sendText'); - } - return; - } - - if (keywordFinish && content.toLowerCase() === keywordFinish.toLowerCase()) { - if (keepOpen) { - await this.prismaRepository.typebotSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.typebotSession.deleteMany({ - where: { - typebotId: findTypebot.id, - remoteJid: remoteJid, - }, - }); - } - - return; - } - - let request: any; - try { - const version = this.configService.get('TYPEBOT').API_VERSION; - let urlTypebot: string; - let reqData: {}; - if (version === 'latest') { - urlTypebot = `${url}/api/v1/sessions/${data.sessionId}/continueChat`; - reqData = { - message: content, - }; - } else { - urlTypebot = `${url}/api/v1/sendMessage`; - reqData = { - message: content, - sessionId: data.sessionId, - }; - } - request = await axios.post(urlTypebot, reqData); - - await this.sendWAMessage( - instance, - session, - { - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - stopBotFromMe: stopBotFromMe, - keepOpen: keepOpen, - }, - remoteJid, - request.data.messages, - request.data.input, - request.data.clientSideActions, - ); - } catch (error) { - this.logger.error(error); - return; - } - } - return; - } - - await this.prismaRepository.typebotSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: false, - }, - }); - - if (!content) { - if (unknownMessage) { - this.waMonitor.waInstances[instance.instanceName].textMessage( - { - number: remoteJid.split('@')[0], - delay: delayMessage || 1000, - text: unknownMessage, - }, - false, - ); - - sendTelemetry('/message/sendText'); - } - return; - } - - if (keywordFinish && content.toLowerCase() === keywordFinish.toLowerCase()) { - if (keepOpen) { - await this.prismaRepository.typebotSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.typebotSession.deleteMany({ - where: { - typebotId: findTypebot.id, - remoteJid: remoteJid, - }, - }); - } - return; - } - - const version = this.configService.get('TYPEBOT').API_VERSION; - let urlTypebot: string; - let reqData: {}; - if (version === 'latest') { - urlTypebot = `${url}/api/v1/sessions/${session.sessionId.split('-')[1]}/continueChat`; - reqData = { - message: content, - }; - } else { - urlTypebot = `${url}/api/v1/sendMessage`; - reqData = { - message: content, - sessionId: session.sessionId.split('-')[1], - }; - } - const request = await axios.post(urlTypebot, reqData); - - await this.sendWAMessage( - instance, - session, - { - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - stopBotFromMe: stopBotFromMe, - keepOpen: keepOpen, - }, - remoteJid, - request?.data?.messages, - request?.data?.input, - request?.data?.clientSideActions, - ); - - return; - } -} diff --git a/src/api/integrations/websocket/controllers/websocket.controller.ts b/src/api/integrations/websocket/controllers/websocket.controller.ts deleted file mode 100644 index a487f48a..00000000 --- a/src/api/integrations/websocket/controllers/websocket.controller.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { InstanceDto } from '../../../dto/instance.dto'; -import { WebsocketDto } from '../dto/websocket.dto'; -import { WebsocketService } from '../services/websocket.service'; - -export class WebsocketController { - constructor(private readonly websocketService: WebsocketService) {} - - public async createWebsocket(instance: InstanceDto, data: WebsocketDto) { - if (!data.enabled) { - data.events = []; - } - - if (data.events.length === 0) { - data.events = [ - 'APPLICATION_STARTUP', - 'QRCODE_UPDATED', - 'MESSAGES_SET', - 'MESSAGES_UPSERT', - 'MESSAGES_EDITED', - 'MESSAGES_UPDATE', - 'MESSAGES_DELETE', - 'SEND_MESSAGE', - 'CONTACTS_SET', - 'CONTACTS_UPSERT', - 'CONTACTS_UPDATE', - 'PRESENCE_UPDATE', - 'CHATS_SET', - 'CHATS_UPSERT', - 'CHATS_UPDATE', - 'CHATS_DELETE', - 'GROUPS_UPSERT', - 'GROUP_UPDATE', - 'GROUP_PARTICIPANTS_UPDATE', - 'CONNECTION_UPDATE', - 'LABELS_EDIT', - 'LABELS_ASSOCIATION', - 'CALL', - 'TYPEBOT_START', - 'TYPEBOT_CHANGE_STATUS', - ]; - } - - return this.websocketService.create(instance, data); - } - - public async findWebsocket(instance: InstanceDto) { - return this.websocketService.find(instance); - } -} diff --git a/src/api/integrations/websocket/dto/websocket.dto.ts b/src/api/integrations/websocket/dto/websocket.dto.ts deleted file mode 100644 index 27f6d785..00000000 --- a/src/api/integrations/websocket/dto/websocket.dto.ts +++ /dev/null @@ -1,4 +0,0 @@ -export class WebsocketDto { - enabled: boolean; - events?: string[]; -} diff --git a/src/api/integrations/websocket/libs/socket.server.ts b/src/api/integrations/websocket/libs/socket.server.ts deleted file mode 100644 index 948527ae..00000000 --- a/src/api/integrations/websocket/libs/socket.server.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { Server } from 'http'; -import { Server as SocketIO } from 'socket.io'; - -import { configService, Cors, Websocket } from '../../../../config/env.config'; -import { Logger } from '../../../../config/logger.config'; - -const logger = new Logger('Socket'); - -let io: SocketIO; - -const cors = configService.get('CORS').ORIGIN; - -export const initIO = (httpServer: Server) => { - if (configService.get('WEBSOCKET')?.ENABLED) { - io = new SocketIO(httpServer, { - cors: { - origin: cors, - }, - }); - - io.on('connection', (socket) => { - logger.info('User connected'); - - socket.on('disconnect', () => { - logger.info('User disconnected'); - }); - }); - - logger.info('Socket.io initialized'); - return io; - } - return null; -}; - -export const getIO = (): SocketIO => { - if (!io) { - logger.error('Socket.io not initialized'); - throw new Error('Socket.io not initialized'); - } - - return io; -}; diff --git a/src/api/integrations/websocket/routes/websocket.router.ts b/src/api/integrations/websocket/routes/websocket.router.ts deleted file mode 100644 index b8f86fcb..00000000 --- a/src/api/integrations/websocket/routes/websocket.router.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { RequestHandler, Router } from 'express'; - -import { instanceSchema, websocketSchema } from '../../../../validate/validate.schema'; -import { RouterBroker } from '../../../abstract/abstract.router'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { HttpStatus } from '../../../routes/index.router'; -import { websocketController } from '../../../server.module'; -import { WebsocketDto } from '../dto/websocket.dto'; - -export class WebsocketRouter extends RouterBroker { - constructor(...guards: RequestHandler[]) { - super(); - this.router - .post(this.routerPath('set'), ...guards, async (req, res) => { - const response = await this.dataValidate({ - request: req, - schema: websocketSchema, - ClassRef: WebsocketDto, - execute: (instance, data) => websocketController.createWebsocket(instance, data), - }); - - res.status(HttpStatus.CREATED).json(response); - }) - .get(this.routerPath('find'), ...guards, async (req, res) => { - const response = await this.dataValidate({ - request: req, - schema: instanceSchema, - ClassRef: InstanceDto, - execute: (instance) => websocketController.findWebsocket(instance), - }); - - res.status(HttpStatus.OK).json(response); - }); - } - - public readonly router = Router(); -} diff --git a/src/api/integrations/websocket/services/websocket.service.ts b/src/api/integrations/websocket/services/websocket.service.ts deleted file mode 100644 index 0f0d2457..00000000 --- a/src/api/integrations/websocket/services/websocket.service.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { Websocket } from '@prisma/client'; - -import { Logger } from '../../../../config/logger.config'; -import { InstanceDto } from '../../../dto/instance.dto'; -import { WAMonitoringService } from '../../../services/monitor.service'; -import { WebsocketDto } from '../dto/websocket.dto'; - -export class WebsocketService { - constructor(private readonly waMonitor: WAMonitoringService) {} - - private readonly logger = new Logger(WebsocketService.name); - - public create(instance: InstanceDto, data: WebsocketDto) { - this.waMonitor.waInstances[instance.instanceName].setWebsocket(data); - - return { websocket: { ...instance, websocket: data } }; - } - - public async find(instance: InstanceDto): Promise { - try { - const result = await this.waMonitor.waInstances[instance.instanceName].findWebsocket(); - - if (Object.keys(result).length === 0) { - throw new Error('Websocket not found'); - } - - return result; - } catch (error) { - return null; - } - } -} diff --git a/src/api/integrations/websocket/validate/websocket.schema.ts b/src/api/integrations/websocket/validate/websocket.schema.ts deleted file mode 100644 index 8a7678c1..00000000 --- a/src/api/integrations/websocket/validate/websocket.schema.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { JSONSchema7 } from 'json-schema'; -import { v4 } from 'uuid'; - -const isNotEmpty = (...propertyNames: string[]): JSONSchema7 => { - const properties = {}; - propertyNames.forEach( - (property) => - (properties[property] = { - minLength: 1, - description: `The "${property}" cannot be empty`, - }), - ); - return { - if: { - propertyNames: { - enum: [...propertyNames], - }, - }, - then: { properties }, - }; -}; - -export const websocketSchema: JSONSchema7 = { - $id: v4(), - type: 'object', - properties: { - enabled: { type: 'boolean', enum: [true, false] }, - events: { - type: 'array', - minItems: 0, - items: { - type: 'string', - enum: [ - 'APPLICATION_STARTUP', - 'QRCODE_UPDATED', - 'MESSAGES_SET', - 'MESSAGES_UPSERT', - 'MESSAGES_EDITED', - 'MESSAGES_UPDATE', - 'MESSAGES_DELETE', - 'SEND_MESSAGE', - 'CONTACTS_SET', - 'CONTACTS_UPSERT', - 'CONTACTS_UPDATE', - 'PRESENCE_UPDATE', - 'CHATS_SET', - 'CHATS_UPSERT', - 'CHATS_UPDATE', - 'CHATS_DELETE', - 'GROUPS_UPSERT', - 'GROUP_UPDATE', - 'GROUP_PARTICIPANTS_UPDATE', - 'CONNECTION_UPDATE', - 'LABELS_EDIT', - 'LABELS_ASSOCIATION', - 'CALL', - 'TYPEBOT_START', - 'TYPEBOT_CHANGE_STATUS', - ], - }, - }, - }, - required: ['enabled'], - ...isNotEmpty('enabled'), -}; diff --git a/src/api/provider/sessions.ts b/src/api/provider/sessions.ts index 7afc9c89..05668232 100644 --- a/src/api/provider/sessions.ts +++ b/src/api/provider/sessions.ts @@ -1,9 +1,8 @@ +import { Auth, ConfigService, ProviderSession } from '@config/env.config'; +import { Logger } from '@config/logger.config'; import axios from 'axios'; import { execSync } from 'child_process'; -import { Auth, ConfigService, ProviderSession } from '../../config/env.config'; -import { Logger } from '../../config/logger.config'; - type ResponseSuccess = { status: number; data?: any }; type ResponseProvider = Promise<[ResponseSuccess?, Error?]>; @@ -13,7 +12,7 @@ export class ProviderFiles { this.globalApiToken = this.configService.get('AUTHENTICATION').API_KEY.KEY; } - private readonly logger = new Logger(ProviderFiles.name); + private readonly logger = new Logger('ProviderFiles'); private baseUrl: string; private globalApiToken: string; diff --git a/src/api/repository/repository.service.ts b/src/api/repository/repository.service.ts index 9c9bbf0e..793bb0c8 100644 --- a/src/api/repository/repository.service.ts +++ b/src/api/repository/repository.service.ts @@ -1,8 +1,7 @@ +import { ConfigService } from '@config/env.config'; +import { Logger } from '@config/logger.config'; import { PrismaClient } from '@prisma/client'; -import { ConfigService } from '../../config/env.config'; -import { Logger } from '../../config/logger.config'; - export class Query { where?: T; sort?: 'asc' | 'desc'; @@ -15,7 +14,7 @@ export class PrismaRepository extends PrismaClient { super(); } - private readonly logger = new Logger(PrismaRepository.name); + private readonly logger = new Logger('PrismaRepository'); public async onModuleInit() { await this.$connect(); diff --git a/src/api/routes/chat.router.ts b/src/api/routes/chat.router.ts index 936c63f9..20126c1a 100644 --- a/src/api/routes/chat.router.ts +++ b/src/api/routes/chat.router.ts @@ -1,6 +1,24 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { + ArchiveChatDto, + BlockUserDto, + DeleteMessage, + getBase64FromMediaMessageDto, + MarkChatUnreadDto, + NumberDto, + PrivacySettingDto, + ProfileNameDto, + ProfilePictureDto, + ProfileStatusDto, + ReadMessageDto, + SendPresenceDto, + UpdateMessageDto, + WhatsAppNumberDto, +} from '@api/dto/chat.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { Query } from '@api/repository/repository.service'; +import { chatController } from '@api/server.module'; import { Contact, Message, MessageUpdate } from '@prisma/client'; -import { RequestHandler, Router } from 'express'; - import { archiveChatSchema, blockUserSchema, @@ -18,27 +36,9 @@ import { readMessageSchema, updateMessageSchema, whatsappNumberSchema, -} from '../../validate/validate.schema'; -import { RouterBroker } from '../abstract/abstract.router'; -import { - ArchiveChatDto, - BlockUserDto, - DeleteMessage, - getBase64FromMediaMessageDto, - MarkChatUnreadDto, - NumberDto, - PrivacySettingDto, - ProfileNameDto, - ProfilePictureDto, - ProfileStatusDto, - ReadMessageDto, - SendPresenceDto, - UpdateMessageDto, - WhatsAppNumberDto, -} from '../dto/chat.dto'; -import { InstanceDto } from '../dto/instance.dto'; -import { Query } from '../repository/repository.service'; -import { chatController } from '../server.module'; +} from '@validate/validate.schema'; +import { RequestHandler, Router } from 'express'; + import { HttpStatus } from './index.router'; export class ChatRouter extends RouterBroker { @@ -270,5 +270,5 @@ export class ChatRouter extends RouterBroker { }); } - public readonly router = Router(); + public readonly router: Router = Router(); } diff --git a/src/api/routes/group.router.ts b/src/api/routes/group.router.ts index 973d19c1..7086b117 100644 --- a/src/api/routes/group.router.ts +++ b/src/api/routes/group.router.ts @@ -1,20 +1,4 @@ -import { RequestHandler, Router } from 'express'; - -import { - AcceptGroupInviteSchema, - createGroupSchema, - getParticipantsSchema, - groupInviteSchema, - groupJidSchema, - groupSendInviteSchema, - toggleEphemeralSchema, - updateGroupDescriptionSchema, - updateGroupPictureSchema, - updateGroupSubjectSchema, - updateParticipantsSchema, - updateSettingsSchema, -} from '../../validate/validate.schema'; -import { RouterBroker } from '../abstract/abstract.router'; +import { RouterBroker } from '@api/abstract/abstract.router'; import { AcceptGroupInvite, CreateGroupDto, @@ -28,8 +12,24 @@ import { GroupToggleEphemeralDto, GroupUpdateParticipantDto, GroupUpdateSettingDto, -} from '../dto/group.dto'; -import { groupController } from '../server.module'; +} from '@api/dto/group.dto'; +import { groupController } from '@api/server.module'; +import { + AcceptGroupInviteSchema, + createGroupSchema, + getParticipantsSchema, + groupInviteSchema, + groupJidSchema, + groupSendInviteSchema, + toggleEphemeralSchema, + updateGroupDescriptionSchema, + updateGroupPictureSchema, + updateGroupSubjectSchema, + updateParticipantsSchema, + updateSettingsSchema, +} from '@validate/validate.schema'; +import { RequestHandler, Router } from 'express'; + import { HttpStatus } from './index.router'; export class GroupRouter extends RouterBroker { @@ -198,5 +198,5 @@ export class GroupRouter extends RouterBroker { }); } - public readonly router = Router(); + public readonly router: Router = Router(); } diff --git a/src/api/routes/index.router.ts b/src/api/routes/index.router.ts index 7edc1046..43401725 100644 --- a/src/api/routes/index.router.ts +++ b/src/api/routes/index.router.ts @@ -1,21 +1,16 @@ +import { authGuard } from '@api/guards/auth.guard'; +import { instanceExistsGuard, instanceLoggedGuard } from '@api/guards/instance.guard'; +import Telemetry from '@api/guards/telemetry.guard'; +import { ChannelRouter } from '@api/integrations/channel/channel.router'; +import { ChatbotRouter } from '@api/integrations/chatbot/chatbot.router'; +import { EventRouter } from '@api/integrations/event/event.router'; +import { StorageRouter } from '@api/integrations/storage/storage.router'; +import { configService } from '@config/env.config'; import { Router } from 'express'; import fs from 'fs'; import mime from 'mime'; import path from 'path'; -import { configService, WaBusiness } from '../../config/env.config'; -import { authGuard } from '../guards/auth.guard'; -import { instanceExistsGuard, instanceLoggedGuard } from '../guards/instance.guard'; -import Telemetry from '../guards/telemetry.guard'; -import { ChatwootRouter } from '../integrations/chatwoot/routes/chatwoot.router'; -import { DifyRouter } from '../integrations/dify/routes/dify.router'; -import { OpenaiRouter } from '../integrations/openai/routes/openai.router'; -import { RabbitmqRouter } from '../integrations/rabbitmq/routes/rabbitmq.router'; -import { S3Router } from '../integrations/s3/routes/s3.router'; -import { SqsRouter } from '../integrations/sqs/routes/sqs.router'; -import { TypebotRouter } from '../integrations/typebot/routes/typebot.router'; -import { WebsocketRouter } from '../integrations/websocket/routes/websocket.router'; -import { webhookController } from '../server.module'; import { ChatRouter } from './chat.router'; import { GroupRouter } from './group.router'; import { InstanceRouter } from './instance.router'; @@ -25,7 +20,6 @@ import { MessageRouter } from './sendMessage.router'; import { SettingsRouter } from './settings.router'; import { TemplateRouter } from './template.router'; import { ViewsRouter } from './view.router'; -import { WebhookRouter } from './webhook.router'; enum HttpStatus { OK = 200, @@ -37,7 +31,7 @@ enum HttpStatus { INTERNAL_SERVER_ERROR = 500, } -const router = Router(); +const router: Router = Router(); const serverConfig = configService.get('SERVER'); const guards = [instanceExistsGuard, instanceLoggedGuard, authGuard['apikey']]; @@ -54,7 +48,7 @@ router.get('/assets/*', (req, res) => { const filePath = path.join(basePath, 'assets/', fileName); if (fs.existsSync(filePath)) { - res.set('Content-Type', mime.lookup(filePath) || 'text/css'); + res.set('Content-Type', mime.getType(filePath) || 'text/css'); res.send(fs.readFileSync(filePath)); } else { res.status(404).send('File not found'); @@ -78,35 +72,22 @@ router return res.status(HttpStatus.OK).json({ status: HttpStatus.OK, message: 'Credentials are valid', + facebookAppId: process.env.FACEBOOK_APP_ID, + facebookConfigId: process.env.FACEBOOK_CONFIG_ID, + facebookUserToken: process.env.FACEBOOK_USER_TOKEN, }); }) .use('/instance', new InstanceRouter(configService, ...guards).router) .use('/message', new MessageRouter(...guards).router) .use('/chat', new ChatRouter(...guards).router) .use('/group', new GroupRouter(...guards).router) - .use('/webhook', new WebhookRouter(configService, ...guards).router) .use('/template', new TemplateRouter(configService, ...guards).router) - .use('/chatwoot', new ChatwootRouter(...guards).router) .use('/settings', new SettingsRouter(...guards).router) - .use('/websocket', new WebsocketRouter(...guards).router) - .use('/rabbitmq', new RabbitmqRouter(...guards).router) - .use('/sqs', new SqsRouter(...guards).router) - .use('/typebot', new TypebotRouter(...guards).router) .use('/proxy', new ProxyRouter(...guards).router) .use('/label', new LabelRouter(...guards).router) - .use('/s3', new S3Router(...guards).router) - .use('/openai', new OpenaiRouter(...guards).router) - .use('/dify', new DifyRouter(...guards).router) - .get('/webhook/meta', async (req, res) => { - if (req.query['hub.verify_token'] === configService.get('WA_BUSINESS').TOKEN_WEBHOOK) - res.send(req.query['hub.challenge']); - else res.send('Error, wrong validation token'); - }) - .post('/webhook/meta', async (req, res) => { - const { body } = req; - const response = await webhookController.receiveWebhook(body); - - return res.status(200).json(response); - }); + .use('', new ChannelRouter(configService).router) + .use('', new EventRouter(configService, ...guards).router) + .use('', new ChatbotRouter(...guards).router) + .use('', new StorageRouter(...guards).router); export { HttpStatus, router }; diff --git a/src/api/routes/instance.router.ts b/src/api/routes/instance.router.ts index 21f8ef6b..7b81368d 100644 --- a/src/api/routes/instance.router.ts +++ b/src/api/routes/instance.router.ts @@ -1,10 +1,10 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { InstanceDto, SetPresenceDto } from '@api/dto/instance.dto'; +import { instanceController } from '@api/server.module'; +import { ConfigService } from '@config/env.config'; +import { instanceSchema, presenceOnlySchema } from '@validate/validate.schema'; import { RequestHandler, Router } from 'express'; -import { ConfigService } from '../../config/env.config'; -import { instanceSchema, presenceOnlySchema } from '../../validate/validate.schema'; -import { RouterBroker } from '../abstract/abstract.router'; -import { InstanceDto, SetPresenceDto } from '../dto/instance.dto'; -import { instanceController } from '../server.module'; import { HttpStatus } from './index.router'; export class InstanceRouter extends RouterBroker { @@ -95,5 +95,5 @@ export class InstanceRouter extends RouterBroker { }); } - public readonly router = Router(); + public readonly router: Router = Router(); } diff --git a/src/api/routes/label.router.ts b/src/api/routes/label.router.ts index e9dbdb5f..bfb4a085 100644 --- a/src/api/routes/label.router.ts +++ b/src/api/routes/label.router.ts @@ -1,9 +1,9 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { HandleLabelDto, LabelDto } from '@api/dto/label.dto'; +import { labelController } from '@api/server.module'; +import { handleLabelSchema } from '@validate/validate.schema'; import { RequestHandler, Router } from 'express'; -import { handleLabelSchema } from '../../validate/validate.schema'; -import { RouterBroker } from '../abstract/abstract.router'; -import { HandleLabelDto, LabelDto } from '../dto/label.dto'; -import { labelController } from '../server.module'; import { HttpStatus } from './index.router'; export class LabelRouter extends RouterBroker { @@ -32,5 +32,5 @@ export class LabelRouter extends RouterBroker { }); } - public readonly router = Router(); + public readonly router: Router = Router(); } diff --git a/src/api/routes/proxy.router.ts b/src/api/routes/proxy.router.ts index 5ffde824..e04c587b 100644 --- a/src/api/routes/proxy.router.ts +++ b/src/api/routes/proxy.router.ts @@ -1,10 +1,10 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { ProxyDto } from '@api/dto/proxy.dto'; +import { proxyController } from '@api/server.module'; +import { instanceSchema, proxySchema } from '@validate/validate.schema'; import { RequestHandler, Router } from 'express'; -import { instanceSchema, proxySchema } from '../../validate/validate.schema'; -import { RouterBroker } from '../abstract/abstract.router'; -import { InstanceDto } from '../dto/instance.dto'; -import { ProxyDto } from '../dto/proxy.dto'; -import { proxyController } from '../server.module'; import { HttpStatus } from './index.router'; export class ProxyRouter extends RouterBroker { @@ -33,5 +33,5 @@ export class ProxyRouter extends RouterBroker { }); } - public readonly router = Router(); + public readonly router: Router = Router(); } diff --git a/src/api/routes/sendMessage.router.ts b/src/api/routes/sendMessage.router.ts index b8bee8e5..a61230f6 100644 --- a/src/api/routes/sendMessage.router.ts +++ b/src/api/routes/sendMessage.router.ts @@ -1,20 +1,4 @@ -import { RequestHandler, Router } from 'express'; - -import { - audioMessageSchema, - buttonMessageSchema, - contactMessageSchema, - listMessageSchema, - locationMessageSchema, - mediaMessageSchema, - pollMessageSchema, - reactionMessageSchema, - statusMessageSchema, - stickerMessageSchema, - templateMessageSchema, - textMessageSchema, -} from '../../validate/validate.schema'; -import { RouterBroker } from '../abstract/abstract.router'; +import { RouterBroker } from '@api/abstract/abstract.router'; import { SendAudioDto, SendButtonDto, @@ -28,8 +12,24 @@ import { SendStickerDto, SendTemplateDto, SendTextDto, -} from '../dto/sendMessage.dto'; -import { sendMessageController } from '../server.module'; +} from '@api/dto/sendMessage.dto'; +import { sendMessageController } from '@api/server.module'; +import { + audioMessageSchema, + buttonMessageSchema, + contactMessageSchema, + listMessageSchema, + locationMessageSchema, + mediaMessageSchema, + pollMessageSchema, + reactionMessageSchema, + statusMessageSchema, + stickerMessageSchema, + templateMessageSchema, + textMessageSchema, +} from '@validate/validate.schema'; +import { RequestHandler, Router } from 'express'; + import { HttpStatus } from './index.router'; export class MessageRouter extends RouterBroker { @@ -159,5 +159,5 @@ export class MessageRouter extends RouterBroker { }); } - public readonly router = Router(); + public readonly router: Router = Router(); } diff --git a/src/api/routes/settings.router.ts b/src/api/routes/settings.router.ts index ba505cea..214d5fd7 100644 --- a/src/api/routes/settings.router.ts +++ b/src/api/routes/settings.router.ts @@ -1,10 +1,10 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { SettingsDto } from '@api/dto/settings.dto'; +import { settingsController } from '@api/server.module'; +import { settingsSchema } from '@validate/validate.schema'; import { RequestHandler, Router } from 'express'; -import { settingsSchema } from '../../validate/validate.schema'; -import { RouterBroker } from '../abstract/abstract.router'; -import { InstanceDto } from '../dto/instance.dto'; -import { SettingsDto } from '../dto/settings.dto'; -import { settingsController } from '../server.module'; import { HttpStatus } from './index.router'; export class SettingsRouter extends RouterBroker { @@ -33,5 +33,5 @@ export class SettingsRouter extends RouterBroker { }); } - public readonly router = Router(); + public readonly router: Router = Router(); } diff --git a/src/api/routes/template.router.ts b/src/api/routes/template.router.ts index 8eab843e..67607dc8 100644 --- a/src/api/routes/template.router.ts +++ b/src/api/routes/template.router.ts @@ -1,11 +1,11 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { TemplateDto } from '@api/dto/template.dto'; +import { templateController } from '@api/server.module'; +import { ConfigService } from '@config/env.config'; +import { instanceSchema, templateSchema } from '@validate/validate.schema'; import { RequestHandler, Router } from 'express'; -import { ConfigService } from '../../config/env.config'; -import { instanceSchema, templateSchema } from '../../validate/validate.schema'; -import { RouterBroker } from '../abstract/abstract.router'; -import { InstanceDto } from '../dto/instance.dto'; -import { TemplateDto } from '../dto/template.dto'; -import { templateController } from '../server.module'; import { HttpStatus } from './index.router'; export class TemplateRouter extends RouterBroker { @@ -34,5 +34,5 @@ export class TemplateRouter extends RouterBroker { }); } - public readonly router = Router(); + public readonly router: Router = Router(); } diff --git a/src/api/routes/view.router.ts b/src/api/routes/view.router.ts index 8e8fc849..64b4b5ea 100644 --- a/src/api/routes/view.router.ts +++ b/src/api/routes/view.router.ts @@ -1,8 +1,7 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; import express, { Router } from 'express'; import path from 'path'; -import { RouterBroker } from '../abstract/abstract.router'; - export class ViewsRouter extends RouterBroker { public readonly router: Router; @@ -13,9 +12,6 @@ export class ViewsRouter extends RouterBroker { const basePath = path.join(process.cwd(), 'manager', 'dist'); const indexPath = path.join(basePath, 'index.html'); - console.log('Base path:', basePath); - console.log('Index path:', indexPath); - this.router.use(express.static(basePath)); this.router.get('*', (req, res) => { diff --git a/src/api/routes/webhook.router.ts b/src/api/routes/webhook.router.ts deleted file mode 100644 index a442d43f..00000000 --- a/src/api/routes/webhook.router.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { RequestHandler, Router } from 'express'; - -import { ConfigService } from '../../config/env.config'; -import { instanceSchema, webhookSchema } from '../../validate/validate.schema'; -import { RouterBroker } from '../abstract/abstract.router'; -import { InstanceDto } from '../dto/instance.dto'; -import { WebhookDto } from '../dto/webhook.dto'; -import { webhookController } from '../server.module'; -import { HttpStatus } from './index.router'; - -export class WebhookRouter extends RouterBroker { - constructor(readonly configService: ConfigService, ...guards: RequestHandler[]) { - super(); - this.router - .post(this.routerPath('set'), ...guards, async (req, res) => { - const response = await this.dataValidate({ - request: req, - schema: webhookSchema, - ClassRef: WebhookDto, - execute: (instance, data) => webhookController.createWebhook(instance, data), - }); - - res.status(HttpStatus.CREATED).json(response); - }) - .get(this.routerPath('find'), ...guards, async (req, res) => { - const response = await this.dataValidate({ - request: req, - schema: instanceSchema, - ClassRef: InstanceDto, - execute: (instance) => webhookController.findWebhook(instance), - }); - - res.status(HttpStatus.OK).json(response); - }); - } - - public readonly router = Router(); -} diff --git a/src/api/server.module.ts b/src/api/server.module.ts index 0e9ae391..77afe76e 100644 --- a/src/api/server.module.ts +++ b/src/api/server.module.ts @@ -1,7 +1,8 @@ -import { CacheEngine } from '../cache/cacheengine'; -import { Chatwoot, configService, ProviderSession } from '../config/env.config'; -import { eventEmitter } from '../config/event.config'; -import { Logger } from '../config/logger.config'; +import { CacheEngine } from '@cache/cacheengine'; +import { Chatwoot, configService, ProviderSession } from '@config/env.config'; +import { eventEmitter } from '@config/event.config'; +import { Logger } from '@config/logger.config'; + import { ChatController } from './controllers/chat.controller'; import { GroupController } from './controllers/group.controller'; import { InstanceController } from './controllers/instance.controller'; @@ -10,32 +11,32 @@ import { ProxyController } from './controllers/proxy.controller'; import { SendMessageController } from './controllers/sendMessage.controller'; import { SettingsController } from './controllers/settings.controller'; import { TemplateController } from './controllers/template.controller'; -import { WebhookController } from './controllers/webhook.controller'; -import { ChatwootController } from './integrations/chatwoot/controllers/chatwoot.controller'; -import { ChatwootService } from './integrations/chatwoot/services/chatwoot.service'; -import { DifyController } from './integrations/dify/controllers/dify.controller'; -import { DifyService } from './integrations/dify/services/dify.service'; -import { OpenaiController } from './integrations/openai/controllers/openai.controller'; -import { OpenaiService } from './integrations/openai/services/openai.service'; -import { RabbitmqController } from './integrations/rabbitmq/controllers/rabbitmq.controller'; -import { RabbitmqService } from './integrations/rabbitmq/services/rabbitmq.service'; -import { S3Controller } from './integrations/s3/controllers/s3.controller'; -import { S3Service } from './integrations/s3/services/s3.service'; -import { SqsController } from './integrations/sqs/controllers/sqs.controller'; -import { SqsService } from './integrations/sqs/services/sqs.service'; -import { TypebotController } from './integrations/typebot/controllers/typebot.controller'; -import { TypebotService } from './integrations/typebot/services/typebot.service'; -import { WebsocketController } from './integrations/websocket/controllers/websocket.controller'; -import { WebsocketService } from './integrations/websocket/services/websocket.service'; +import { ChannelController } from './integrations/channel/channel.controller'; +import { EvolutionController } from './integrations/channel/evolution/evolution.controller'; +import { MetaController } from './integrations/channel/meta/meta.controller'; +import { ChatbotController } from './integrations/chatbot/chatbot.controller'; +import { ChatwootController } from './integrations/chatbot/chatwoot/controllers/chatwoot.controller'; +import { ChatwootService } from './integrations/chatbot/chatwoot/services/chatwoot.service'; +import { DifyController } from './integrations/chatbot/dify/controllers/dify.controller'; +import { DifyService } from './integrations/chatbot/dify/services/dify.service'; +import { EvolutionBotController } from './integrations/chatbot/evolutionBot/controllers/evolutionBot.controller'; +import { EvolutionBotService } from './integrations/chatbot/evolutionBot/services/evolutionBot.service'; +import { FlowiseController } from './integrations/chatbot/flowise/controllers/flowise.controller'; +import { FlowiseService } from './integrations/chatbot/flowise/services/flowise.service'; +import { OpenaiController } from './integrations/chatbot/openai/controllers/openai.controller'; +import { OpenaiService } from './integrations/chatbot/openai/services/openai.service'; +import { TypebotController } from './integrations/chatbot/typebot/controllers/typebot.controller'; +import { TypebotService } from './integrations/chatbot/typebot/services/typebot.service'; +import { EventManager } from './integrations/event/event.manager'; +import { S3Controller } from './integrations/storage/s3/controllers/s3.controller'; +import { S3Service } from './integrations/storage/s3/services/s3.service'; import { ProviderFiles } from './provider/sessions'; import { PrismaRepository } from './repository/repository.service'; -import { AuthService } from './services/auth.service'; import { CacheService } from './services/cache.service'; import { WAMonitoringService } from './services/monitor.service'; import { ProxyService } from './services/proxy.service'; import { SettingsService } from './services/settings.service'; import { TemplateService } from './services/template.service'; -import { WebhookService } from './services/webhook.service'; const logger = new Logger('WA MODULE'); @@ -64,38 +65,15 @@ export const waMonitor = new WAMonitoringService( baileysCache, ); -const authService = new AuthService(prismaRepository); - -const typebotService = new TypebotService(waMonitor, configService, prismaRepository); -export const typebotController = new TypebotController(typebotService); - -const openaiService = new OpenaiService(waMonitor, configService, prismaRepository); -export const openaiController = new OpenaiController(openaiService); - -const difyService = new DifyService(waMonitor, configService, prismaRepository); -export const difyController = new DifyController(difyService); - const s3Service = new S3Service(prismaRepository); export const s3Controller = new S3Controller(s3Service); -const webhookService = new WebhookService(waMonitor, prismaRepository); -export const webhookController = new WebhookController(webhookService, waMonitor); - const templateService = new TemplateService(waMonitor, prismaRepository, configService); export const templateController = new TemplateController(templateService); -const websocketService = new WebsocketService(waMonitor); -export const websocketController = new WebsocketController(websocketService); - const proxyService = new ProxyService(waMonitor); export const proxyController = new ProxyController(proxyService, waMonitor); -const rabbitmqService = new RabbitmqService(waMonitor); -export const rabbitmqController = new RabbitmqController(rabbitmqService); - -const sqsService = new SqsService(waMonitor); -export const sqsController = new SqsController(sqsService); - const chatwootService = new ChatwootService(waMonitor, configService, prismaRepository, chatwootCache); export const chatwootController = new ChatwootController(chatwootService, configService, prismaRepository); @@ -107,13 +85,8 @@ export const instanceController = new InstanceController( configService, prismaRepository, eventEmitter, - authService, - webhookService, chatwootService, settingsService, - websocketService, - rabbitmqService, - sqsService, proxyController, cache, chatwootCache, @@ -125,4 +98,28 @@ export const chatController = new ChatController(waMonitor); export const groupController = new GroupController(waMonitor); export const labelController = new LabelController(waMonitor); +export const eventManager = new EventManager(prismaRepository, waMonitor); +export const chatbotController = new ChatbotController(prismaRepository, waMonitor); +export const channelController = new ChannelController(prismaRepository, waMonitor); + +// channels +export const evolutionController = new EvolutionController(prismaRepository, waMonitor); +export const metaController = new MetaController(prismaRepository, waMonitor); + +// chatbots +const typebotService = new TypebotService(waMonitor, configService, prismaRepository); +export const typebotController = new TypebotController(typebotService, prismaRepository, waMonitor); + +const openaiService = new OpenaiService(waMonitor, configService, prismaRepository); +export const openaiController = new OpenaiController(openaiService, prismaRepository, waMonitor); + +const difyService = new DifyService(waMonitor, configService, prismaRepository); +export const difyController = new DifyController(difyService, prismaRepository, waMonitor); + +const evolutionBotService = new EvolutionBotService(waMonitor, configService, prismaRepository); +export const evolutionBotController = new EvolutionBotController(evolutionBotService, prismaRepository, waMonitor); + +const flowiseService = new FlowiseService(waMonitor, configService, prismaRepository); +export const flowiseController = new FlowiseController(flowiseService, prismaRepository, waMonitor); + logger.info('Module - ON'); diff --git a/src/api/services/auth.service.ts b/src/api/services/auth.service.ts index 84779237..3a7825f8 100644 --- a/src/api/services/auth.service.ts +++ b/src/api/services/auth.service.ts @@ -1,5 +1,5 @@ -import { BadRequestException } from '../../exceptions'; -import { PrismaRepository } from '../repository/repository.service'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { BadRequestException } from '@exceptions'; export class AuthService { constructor(private readonly prismaRepository: PrismaRepository) {} diff --git a/src/api/services/cache.service.ts b/src/api/services/cache.service.ts index b528b157..e2f96d4b 100644 --- a/src/api/services/cache.service.ts +++ b/src/api/services/cache.service.ts @@ -1,16 +1,15 @@ +import { ICache } from '@api/abstract/abstract.cache'; +import { Logger } from '@config/logger.config'; import { BufferJSON } from 'baileys'; -import { Logger } from '../../config/logger.config'; -import { ICache } from '../abstract/abstract.cache'; - export class CacheService { - private readonly logger = new Logger(CacheService.name); + private readonly logger = new Logger('CacheService'); constructor(private readonly cache: ICache) { if (cache) { - this.logger.info(`cacheservice created using cache engine: ${cache.constructor?.name}`); + this.logger.verbose(`cacheservice created using cache engine: ${cache.constructor?.name}`); } else { - this.logger.info(`cacheservice disabled`); + this.logger.verbose(`cacheservice disabled`); } } @@ -22,6 +21,9 @@ export class CacheService { } public async hGet(key: string, field: string) { + if (!this.cache) { + return null; + } try { const data = await this.cache.hGet(key, field); @@ -36,14 +38,17 @@ export class CacheService { } } - async set(key: string, value: any) { + async set(key: string, value: any, ttl?: number) { if (!this.cache) { return; } - this.cache.set(key, value); + this.cache.set(key, value, ttl); } public async hSet(key: string, field: string, value: any) { + if (!this.cache) { + return; + } try { const json = JSON.stringify(value, BufferJSON.replacer); @@ -68,6 +73,9 @@ export class CacheService { } async hDelete(key: string, field: string) { + if (!this.cache) { + return false; + } try { await this.cache.hDelete(key, field); return true; diff --git a/src/api/services/channel.service.ts b/src/api/services/channel.service.ts index d00ccd54..7fe445e3 100644 --- a/src/api/services/channel.service.ts +++ b/src/api/services/channel.service.ts @@ -1,43 +1,22 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { ProxyDto } from '@api/dto/proxy.dto'; +import { SettingsDto } from '@api/dto/settings.dto'; +import { ChatwootDto } from '@api/integrations/chatbot/chatwoot/dto/chatwoot.dto'; +import { ChatwootService } from '@api/integrations/chatbot/chatwoot/services/chatwoot.service'; +import { DifyService } from '@api/integrations/chatbot/dify/services/dify.service'; +import { OpenaiService } from '@api/integrations/chatbot/openai/services/openai.service'; +import { TypebotService } from '@api/integrations/chatbot/typebot/services/typebot.service'; +import { PrismaRepository, Query } from '@api/repository/repository.service'; +import { eventManager, waMonitor } from '@api/server.module'; +import { Events, wa } from '@api/types/wa.types'; +import { Auth, Chatwoot, ConfigService, HttpServer } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { NotFoundException } from '@exceptions'; import { Contact, Message } from '@prisma/client'; -import axios from 'axios'; import { WASocket } from 'baileys'; -import { isURL } from 'class-validator'; import EventEmitter2 from 'eventemitter2'; -import { join } from 'path'; import { v4 } from 'uuid'; -import { - Auth, - Chatwoot, - ConfigService, - HttpServer, - Log, - Rabbitmq, - Sqs, - Webhook, - Websocket, -} from '../../config/env.config'; -import { Logger } from '../../config/logger.config'; -import { ROOT_DIR } from '../../config/path.config'; -import { NotFoundException } from '../../exceptions'; -import { InstanceDto } from '../dto/instance.dto'; -import { ProxyDto } from '../dto/proxy.dto'; -import { SettingsDto } from '../dto/settings.dto'; -import { WebhookDto } from '../dto/webhook.dto'; -import { ChatwootDto } from '../integrations/chatwoot/dto/chatwoot.dto'; -import { ChatwootService } from '../integrations/chatwoot/services/chatwoot.service'; -import { DifyService } from '../integrations/dify/services/dify.service'; -import { OpenaiService } from '../integrations/openai/services/openai.service'; -import { RabbitmqDto } from '../integrations/rabbitmq/dto/rabbitmq.dto'; -import { getAMQP, removeQueues } from '../integrations/rabbitmq/libs/amqp.server'; -import { SqsDto } from '../integrations/sqs/dto/sqs.dto'; -import { getSQS, removeQueues as removeQueuesSQS } from '../integrations/sqs/libs/sqs.server'; -import { TypebotService } from '../integrations/typebot/services/typebot.service'; -import { WebsocketDto } from '../integrations/websocket/dto/websocket.dto'; -import { getIO } from '../integrations/websocket/libs/socket.server'; -import { PrismaRepository, Query } from '../repository/repository.service'; -import { waMonitor } from '../server.module'; -import { Events, wa } from '../types/wa.types'; import { CacheService } from './cache.service'; export class ChannelStartupService { @@ -48,18 +27,13 @@ export class ChannelStartupService { public readonly chatwootCache: CacheService, ) {} - public readonly logger = new Logger(ChannelStartupService.name); + public readonly logger = new Logger('ChannelStartupService'); public client: WASocket; public readonly instance: wa.Instance = {}; - public readonly localWebhook: wa.LocalWebHook = {}; public readonly localChatwoot: wa.LocalChatwoot = {}; - public readonly localWebsocket: wa.LocalWebsocket = {}; - public readonly localRabbitmq: wa.LocalRabbitmq = {}; - public readonly localSqs: wa.LocalSqs = {}; public readonly localProxy: wa.LocalProxy = {}; public readonly localSettings: wa.LocalSettings = {}; - public readonly storePath = join(ROOT_DIR, 'store'); public chatwootService = new ChatwootService( waMonitor, @@ -84,12 +58,7 @@ export class ChannelStartupService { this.instance.token = instance.token; this.instance.businessId = instance.businessId; - this.sendDataWebhook(Events.STATUS_INSTANCE, { - instance: this.instance.name, - status: 'created', - }); - - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot.enabled) { + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { this.chatwootService.eventWhatsapp( Events.STATUS_INSTANCE, { instanceName: this.instance.name }, @@ -228,73 +197,6 @@ export class ChannelStartupService { }; } - public async loadWebhook() { - const data = await this.prismaRepository.webhook.findUnique({ - where: { - instanceId: this.instanceId, - }, - }); - - this.localWebhook.url = data?.url; - this.localWebhook.enabled = data?.enabled; - this.localWebhook.events = data?.events; - this.localWebhook.webhookByEvents = data?.webhookByEvents; - this.localWebhook.webhookBase64 = data?.webhookBase64; - } - - public async setWebhook(data: WebhookDto) { - const findWebhook = await this.prismaRepository.webhook.findUnique({ - where: { - instanceId: this.instanceId, - }, - }); - - if (findWebhook) { - await this.prismaRepository.webhook.update({ - where: { - instanceId: this.instanceId, - }, - data: { - url: data.url, - enabled: data.enabled, - events: data.events, - webhookByEvents: data.webhookByEvents, - webhookBase64: data.webhookBase64, - }, - }); - - Object.assign(this.localWebhook, data); - return; - } - await this.prismaRepository.webhook.create({ - data: { - url: data.url, - enabled: data.enabled, - events: data.events, - webhookByEvents: data.webhookByEvents, - webhookBase64: data.webhookBase64, - instanceId: this.instanceId, - }, - }); - - Object.assign(this.localWebhook, data); - return; - } - - public async findWebhook() { - const data = await this.prismaRepository.webhook.findUnique({ - where: { - instanceId: this.instanceId, - }, - }); - - if (!data) { - throw new NotFoundException('Webhook not found'); - } - - return data; - } - public async loadChatwoot() { if (!this.configService.get('CHATWOOT').ENABLED) { return; @@ -339,7 +241,7 @@ export class ChannelStartupService { instanceId: this.instanceId, }, data: { - enabled: data.enabled, + enabled: data?.enabled, accountId: data.accountId, token: data.token, url: data.url, @@ -355,6 +257,7 @@ export class ChannelStartupService { daysLimitImportMessages: data.daysLimitImportMessages, organization: data.organization, logo: data.logo, + ignoreJids: data.ignoreJids, }, }); @@ -366,7 +269,7 @@ export class ChannelStartupService { await this.prismaRepository.chatwoot.create({ data: { - enabled: data.enabled, + enabled: data?.enabled, accountId: data.accountId, token: data.token, url: data.url, @@ -379,6 +282,9 @@ export class ChannelStartupService { importContacts: data.importContacts, importMessages: data.importMessages, daysLimitImportMessages: data.daysLimitImportMessages, + organization: data.organization, + logo: data.logo, + ignoreJids: data.ignoreJids, instanceId: this.instanceId, }, }); @@ -388,7 +294,7 @@ export class ChannelStartupService { this.clearCacheChatwoot(); } - public async findChatwoot() { + public async findChatwoot(): Promise { if (!this.configService.get('CHATWOOT').ENABLED) { return null; } @@ -403,8 +309,10 @@ export class ChannelStartupService { return null; } + const ignoreJidsArray = Array.isArray(data.ignoreJids) ? data.ignoreJids.map((event) => String(event)) : []; + return { - enabled: data.enabled, + enabled: data?.enabled, accountId: data.accountId, token: data.token, url: data.url, @@ -417,201 +325,61 @@ export class ChannelStartupService { importContacts: data.importContacts, importMessages: data.importMessages, daysLimitImportMessages: data.daysLimitImportMessages, + organization: data.organization, + logo: data.logo, + ignoreJids: ignoreJidsArray, }; } public clearCacheChatwoot() { - if (this.localChatwoot.enabled) { + if (this.localChatwoot?.enabled) { this.chatwootService.getCache()?.deleteAll(this.instanceName); } } - public async loadWebsocket() { - const data = await this.prismaRepository.websocket.findUnique({ - where: { - instanceId: this.instanceId, - }, - }); - - this.localWebsocket.enabled = data?.enabled; - this.localWebsocket.events = data?.events; - } - - public async setWebsocket(data: WebsocketDto) { - await this.prismaRepository.websocket.create({ - data: { - enabled: data.enabled, - events: data.events, - instanceId: this.instanceId, - }, - }); - - Object.assign(this.localWebsocket, data); - } - - public async findWebsocket() { - const data = await this.prismaRepository.websocket.findUnique({ - where: { - instanceId: this.instanceId, - }, - }); - - if (!data) { - throw new NotFoundException('Websocket not found'); - } - - return data; - } - - public async loadRabbitmq() { - const data = await this.prismaRepository.rabbitmq.findUnique({ - where: { - instanceId: this.instanceId, - }, - }); - - this.localRabbitmq.enabled = data?.enabled; - this.localRabbitmq.events = data?.events; - } - - public async setRabbitmq(data: RabbitmqDto) { - const findRabbitmq = await this.prismaRepository.rabbitmq.findUnique({ - where: { - instanceId: this.instanceId, - }, - }); - - if (findRabbitmq) { - await this.prismaRepository.rabbitmq.update({ - where: { - instanceId: this.instanceId, - }, - data: { - enabled: data.enabled, - events: data.events, - }, - }); - - Object.assign(this.localRabbitmq, data); - return; - } - - await this.prismaRepository.rabbitmq.create({ - data: { - enabled: data.enabled, - events: data.events, - instanceId: this.instanceId, - }, - }); - - Object.assign(this.localRabbitmq, data); - return; - } - - public async findRabbitmq() { - const data = await this.prismaRepository.rabbitmq.findUnique({ - where: { - instanceId: this.instanceId, - }, - }); - - if (!data) { - throw new NotFoundException('Rabbitmq not found'); - } - - return data; - } - - public async removeRabbitmqQueues() { - if (this.localRabbitmq.enabled) { - removeQueues(this.instanceName, this.localRabbitmq.events); - } - } - - public async loadSqs() { - const data = await this.prismaRepository.sqs.findUnique({ - where: { - instanceId: this.instanceId, - }, - }); - - this.localSqs.enabled = data?.enabled; - this.localSqs.events = data?.events; - } - - public async setSqs(data: SqsDto) { - const findSqs = await this.prismaRepository.sqs.findUnique({ - where: { - instanceId: this.instanceId, - }, - }); - - if (findSqs) { - await this.prismaRepository.sqs.update({ - where: { - instanceId: this.instanceId, - }, - data: { - enabled: data.enabled, - events: data.events, - }, - }); - - Object.assign(this.localSqs, data); - return; - } - - await this.prismaRepository.sqs.create({ - data: { - enabled: data.enabled, - events: data.events, - instanceId: this.instanceId, - }, - }); - - Object.assign(this.localSqs, data); - return; - } - - public async findSqs() { - const data = await this.prismaRepository.sqs.findUnique({ - where: { - instanceId: this.instanceId, - }, - }); - - if (!data) { - throw new NotFoundException('Sqs not found'); - } - - return data; - } - - public async removeSqsQueues() { - if (this.localSqs.enabled) { - removeQueuesSQS(this.instanceName, this.localSqs.events); - } - } - public async loadProxy() { + this.localProxy.enabled = false; + + if (process.env.PROXY_HOST) { + this.localProxy.enabled = true; + this.localProxy.host = process.env.PROXY_HOST; + this.localProxy.port = process.env.PROXY_PORT || '80'; + this.localProxy.protocol = process.env.PROXY_PROTOCOL || 'http'; + this.localProxy.username = process.env.PROXY_USERNAME; + this.localProxy.password = process.env.PROXY_PASSWORD; + } + const data = await this.prismaRepository.proxy.findUnique({ where: { instanceId: this.instanceId, }, }); - this.localProxy.enabled = data?.enabled; - this.localProxy.host = data?.host; - this.localProxy.port = data?.port; - this.localProxy.protocol = data?.protocol; - this.localProxy.username = data?.username; - this.localProxy.password = data?.password; + if (data?.enabled) { + this.localProxy.enabled = true; + this.localProxy.host = data?.host; + this.localProxy.port = data?.port; + this.localProxy.protocol = data?.protocol; + this.localProxy.username = data?.username; + this.localProxy.password = data?.password; + } } public async setProxy(data: ProxyDto) { - await this.prismaRepository.proxy.create({ - data: { - enabled: data.enabled, + await this.prismaRepository.proxy.upsert({ + where: { + instanceId: this.instanceId, + }, + update: { + enabled: data?.enabled, + host: data.host, + port: data.port, + protocol: data.protocol, + username: data.username, + password: data.password, + }, + create: { + enabled: data?.enabled, host: data.host, port: data.port, protocol: data.protocol, @@ -639,17 +407,7 @@ export class ChannelStartupService { } public async sendDataWebhook(event: Events, data: T, local = true) { - const webhookGlobal = this.configService.get('WEBHOOK'); - const webhookLocal = this.localWebhook.events; - const websocketLocal = this.localWebsocket.events; - const rabbitmqLocal = this.localRabbitmq.events; - const sqsLocal = this.localSqs.events; const serverUrl = this.configService.get('SERVER').URL; - const rabbitmqEnabled = this.configService.get('RABBITMQ').ENABLED; - const rabbitmqGlobal = this.configService.get('RABBITMQ').GLOBAL_ENABLED; - const rabbitmqEvents = this.configService.get('RABBITMQ').EVENTS; - const we = event.replace(/[.-]/gm, '_').toUpperCase(); - const transformedWe = we.replace(/_/gm, '-').toLowerCase(); const tzoffset = new Date().getTimezoneOffset() * 60000; //offset in milliseconds const localISOTime = new Date(Date.now() - tzoffset).toISOString(); const now = localISOTime; @@ -658,416 +416,17 @@ export class ChannelStartupService { const instanceApikey = this.token || 'Apikey not found'; - if (rabbitmqEnabled) { - const amqp = getAMQP(); - if (this.localRabbitmq.enabled && amqp) { - if (Array.isArray(rabbitmqLocal) && rabbitmqLocal.includes(we)) { - const exchangeName = this.instanceName ?? 'evolution_exchange'; - - let retry = 0; - - while (retry < 3) { - try { - await amqp.assertExchange(exchangeName, 'topic', { - durable: true, - autoDelete: false, - }); - - const eventName = event.replace(/_/g, '.').toLowerCase(); - - const queueName = `${this.instanceName}.${eventName}`; - - await amqp.assertQueue(queueName, { - durable: true, - autoDelete: false, - arguments: { - 'x-queue-type': 'quorum', - }, - }); - - await amqp.bindQueue(queueName, exchangeName, eventName); - - const message = { - event, - instance: this.instance.name, - data, - server_url: serverUrl, - date_time: now, - sender: this.wuid, - }; - - if (expose && instanceApikey) { - message['apikey'] = instanceApikey; - } - - await amqp.publish(exchangeName, event, Buffer.from(JSON.stringify(message))); - - if (this.configService.get('LOG').LEVEL.includes('WEBHOOKS')) { - const logData = { - local: ChannelStartupService.name + '.sendData-RabbitMQ', - event, - instance: this.instance.name, - data, - server_url: serverUrl, - apikey: (expose && instanceApikey) || null, - date_time: now, - sender: this.wuid, - }; - - if (expose && instanceApikey) { - logData['apikey'] = instanceApikey; - } - - this.logger.log(logData); - } - break; - } catch (error) { - retry++; - } - } - } - } - - if (rabbitmqGlobal && rabbitmqEvents[we] && amqp) { - const exchangeName = 'evolution_exchange'; - - let retry = 0; - - while (retry < 3) { - try { - await amqp.assertExchange(exchangeName, 'topic', { - durable: true, - autoDelete: false, - }); - - const queueName = event; - - await amqp.assertQueue(queueName, { - durable: true, - autoDelete: false, - arguments: { - 'x-queue-type': 'quorum', - }, - }); - - await amqp.bindQueue(queueName, exchangeName, event); - - const message = { - event, - instance: this.instance.name, - data, - server_url: serverUrl, - date_time: now, - sender: this.wuid, - }; - - if (expose && instanceApikey) { - message['apikey'] = instanceApikey; - } - await amqp.publish(exchangeName, event, Buffer.from(JSON.stringify(message))); - - if (this.configService.get('LOG').LEVEL.includes('WEBHOOKS')) { - const logData = { - local: ChannelStartupService.name + '.sendData-RabbitMQ-Global', - event, - instance: this.instance.name, - data, - server_url: serverUrl, - apikey: (expose && instanceApikey) || null, - date_time: now, - sender: this.wuid, - }; - - if (expose && instanceApikey) { - logData['apikey'] = instanceApikey; - } - - this.logger.log(logData); - } - - break; - } catch (error) { - retry++; - } - } - } - } - - if (this.localSqs.enabled) { - const sqs = getSQS(); - - if (sqs) { - if (Array.isArray(sqsLocal) && sqsLocal.includes(we)) { - const eventFormatted = `${event.replace('.', '_').toLowerCase()}`; - - const queueName = `${this.instanceName}_${eventFormatted}.fifo`; - - const sqsConfig = this.configService.get('SQS'); - - const sqsUrl = `https://sqs.${sqsConfig.REGION}.amazonaws.com/${sqsConfig.ACCOUNT_ID}/${queueName}`; - - const message = { - event, - instance: this.instance.name, - data, - server_url: serverUrl, - date_time: now, - sender: this.wuid, - }; - - if (expose && instanceApikey) { - message['apikey'] = instanceApikey; - } - - const params = { - MessageBody: JSON.stringify(message), - MessageGroupId: 'evolution', - MessageDeduplicationId: `${this.instanceName}_${eventFormatted}_${Date.now()}`, - QueueUrl: sqsUrl, - }; - - sqs.sendMessage(params, (err, data) => { - if (err) { - this.logger.error({ - local: ChannelStartupService.name + '.sendData-SQS', - message: err?.message, - hostName: err?.hostname, - code: err?.code, - stack: err?.stack, - name: err?.name, - url: queueName, - server_url: serverUrl, - }); - } else { - if (this.configService.get('LOG').LEVEL.includes('WEBHOOKS')) { - const logData = { - local: ChannelStartupService.name + '.sendData-SQS', - event, - instance: this.instance.name, - data, - server_url: serverUrl, - apikey: (expose && instanceApikey) || null, - date_time: now, - sender: this.wuid, - }; - - if (expose && instanceApikey) { - logData['apikey'] = instanceApikey; - } - - this.logger.log(logData); - } - } - }); - } - } - } - - if (this.configService.get('WEBSOCKET')?.ENABLED) { - const io = getIO(); - - const message = { - event, - instance: this.instance.name, - data, - server_url: serverUrl, - date_time: now, - sender: this.wuid, - }; - - if (expose && instanceApikey) { - message['apikey'] = instanceApikey; - } - - if (this.configService.get('WEBSOCKET')?.GLOBAL_EVENTS) { - io.emit(event, message); - - if (this.configService.get('LOG').LEVEL.includes('WEBHOOKS')) { - const logData = { - local: ChannelStartupService.name + '.sendData-WebsocketGlobal', - event, - instance: this.instance.name, - data, - server_url: serverUrl, - apikey: (expose && instanceApikey) || null, - date_time: now, - sender: this.wuid, - }; - - if (expose && instanceApikey) { - logData['apikey'] = instanceApikey; - } - - this.logger.log(logData); - } - } - - if (this.localWebsocket.enabled && Array.isArray(websocketLocal) && websocketLocal.includes(we)) { - io.of(`/${this.instance.name}`).emit(event, message); - - if (this.configService.get('WEBSOCKET')?.GLOBAL_EVENTS) { - io.emit(event, message); - } - - if (this.configService.get('LOG').LEVEL.includes('WEBHOOKS')) { - const logData = { - local: ChannelStartupService.name + '.sendData-Websocket', - event, - instance: this.instance.name, - data, - server_url: serverUrl, - apikey: (expose && instanceApikey) || null, - date_time: now, - sender: this.wuid, - }; - - if (expose && instanceApikey) { - logData['apikey'] = instanceApikey; - } - - this.logger.log(logData); - } - } - } - - const globalApiKey = this.configService.get('AUTHENTICATION').API_KEY.KEY; - - if (local) { - if (Array.isArray(webhookLocal) && webhookLocal.includes(we)) { - let baseURL: string; - - if (this.localWebhook.webhookByEvents) { - baseURL = `${this.localWebhook.url}/${transformedWe}`; - } else { - baseURL = this.localWebhook.url; - } - - if (this.configService.get('LOG').LEVEL.includes('WEBHOOKS')) { - const logData = { - local: ChannelStartupService.name + '.sendDataWebhook-local', - url: baseURL, - event, - instance: this.instance.name, - data, - destination: this.localWebhook.url, - date_time: now, - sender: this.wuid, - server_url: serverUrl, - apikey: (expose && instanceApikey) || null, - }; - - if (expose && instanceApikey) { - logData['apikey'] = instanceApikey; - } - - this.logger.log(logData); - } - - try { - if (this.localWebhook.enabled && isURL(this.localWebhook.url, { require_tld: false })) { - const httpService = axios.create({ baseURL }); - const postData = { - event, - instance: this.instance.name, - data, - destination: this.localWebhook.url, - date_time: now, - sender: this.wuid, - server_url: serverUrl, - }; - - if (expose && instanceApikey) { - postData['apikey'] = instanceApikey; - } - - await httpService.post('', postData); - } - } catch (error) { - this.logger.error({ - local: ChannelStartupService.name + '.sendDataWebhook-local', - message: error?.message, - hostName: error?.hostname, - syscall: error?.syscall, - code: error?.code, - error: error?.errno, - stack: error?.stack, - name: error?.name, - url: baseURL, - server_url: serverUrl, - }); - } - } - } - - if (webhookGlobal.GLOBAL?.ENABLED) { - if (webhookGlobal.EVENTS[we]) { - const globalWebhook = this.configService.get('WEBHOOK').GLOBAL; - - let globalURL; - - if (webhookGlobal.GLOBAL.WEBHOOK_BY_EVENTS) { - globalURL = `${globalWebhook.URL}/${transformedWe}`; - } else { - globalURL = globalWebhook.URL; - } - - const localUrl = this.localWebhook.url; - - if (this.configService.get('LOG').LEVEL.includes('WEBHOOKS')) { - const logData = { - local: ChannelStartupService.name + '.sendDataWebhook-global', - url: globalURL, - event, - instance: this.instance.name, - data, - destination: localUrl, - date_time: now, - sender: this.wuid, - server_url: serverUrl, - }; - - if (expose && globalApiKey) { - logData['apikey'] = globalApiKey; - } - - this.logger.log(logData); - } - - try { - if (globalWebhook && globalWebhook?.ENABLED && isURL(globalURL)) { - const httpService = axios.create({ baseURL: globalURL }); - const postData = { - event, - instance: this.instance.name, - data, - destination: localUrl, - date_time: now, - sender: this.wuid, - server_url: serverUrl, - }; - - if (expose && globalApiKey) { - postData['apikey'] = globalApiKey; - } - - await httpService.post('', postData); - } - } catch (error) { - this.logger.error({ - local: ChannelStartupService.name + '.sendDataWebhook-global', - message: error?.message, - hostName: error?.hostname, - syscall: error?.syscall, - code: error?.code, - error: error?.errno, - stack: error?.stack, - name: error?.name, - url: globalURL, - server_url: serverUrl, - }); - } - } - } + await eventManager.emit({ + instanceName: this.instance.name, + origin: ChannelStartupService.name, + event, + data, + serverUrl, + dateTime: now, + sender: this.wuid, + apiKey: expose && instanceApikey ? instanceApikey : null, + local, + }); } // Check if the number is MX or AR @@ -1168,12 +527,6 @@ export class ChannelStartupService { participants?: string; }; - const remoteJid = keyFilters?.remoteJid - ? keyFilters?.remoteJid.includes('@') - ? keyFilters?.remoteJid - : this.createJid(keyFilters?.remoteJid) - : null; - const count = await this.prismaRepository.message.count({ where: { instanceId: this.instanceId, @@ -1183,7 +536,7 @@ export class ChannelStartupService { AND: [ keyFilters?.id ? { key: { path: ['id'], equals: keyFilters?.id } } : {}, keyFilters?.fromMe ? { key: { path: ['fromMe'], equals: keyFilters?.fromMe } } : {}, - remoteJid ? { key: { path: ['remoteJid'], equals: remoteJid } } : {}, + keyFilters?.remoteJid ? { key: { path: ['remoteJid'], equals: keyFilters?.remoteJid } } : {}, keyFilters?.participants ? { key: { path: ['participants'], equals: keyFilters?.participants } } : {}, ], }, @@ -1206,7 +559,7 @@ export class ChannelStartupService { AND: [ keyFilters?.id ? { key: { path: ['id'], equals: keyFilters?.id } } : {}, keyFilters?.fromMe ? { key: { path: ['fromMe'], equals: keyFilters?.fromMe } } : {}, - remoteJid ? { key: { path: ['remoteJid'], equals: remoteJid } } : {}, + keyFilters?.remoteJid ? { key: { path: ['remoteJid'], equals: keyFilters?.remoteJid } } : {}, keyFilters?.participants ? { key: { path: ['participants'], equals: keyFilters?.participants } } : {}, ], }, @@ -1264,34 +617,56 @@ export class ChannelStartupService { let result; if (remoteJid) { result = await this.prismaRepository.$queryRaw` - SELECT + SELECT "Chat"."id", "Chat"."remoteJid", + "Chat"."name", "Chat"."labels", "Chat"."createdAt", "Chat"."updatedAt", "Contact"."pushName", "Contact"."profilePicUrl" FROM "Chat" + INNER JOIN "Message" ON "Chat"."remoteJid" = "Message"."key"->>'remoteJid' LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid" WHERE "Chat"."instanceId" = ${this.instanceId} AND "Chat"."remoteJid" = ${remoteJid} - ORDER BY "Chat"."updatedAt" DESC + GROUP BY + "Chat"."id", + "Chat"."remoteJid", + "Chat"."name", + "Chat"."labels", + "Chat"."createdAt", + "Chat"."updatedAt", + "Contact"."pushName", + "Contact"."profilePicUrl" + ORDER BY "Chat"."updatedAt" DESC; `; } else { result = await this.prismaRepository.$queryRaw` - SELECT + SELECT "Chat"."id", "Chat"."remoteJid", + "Chat"."name", "Chat"."labels", "Chat"."createdAt", "Chat"."updatedAt", "Contact"."pushName", "Contact"."profilePicUrl" FROM "Chat" + INNER JOIN "Message" ON "Chat"."remoteJid" = "Message"."key"->>'remoteJid' LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid" WHERE "Chat"."instanceId" = ${this.instanceId} - ORDER BY "Chat"."updatedAt" DESC + GROUP BY + "Chat"."id", + "Chat"."remoteJid", + "Chat"."name", + "Chat"."labels", + "Chat"."createdAt", + "Chat"."updatedAt", + "Contact"."pushName", + "Contact"."profilePicUrl" + ORDER BY "Chat"."updatedAt" DESC; `; } diff --git a/src/api/services/monitor.service.ts b/src/api/services/monitor.service.ts index 5fbf1726..0c3d8d50 100644 --- a/src/api/services/monitor.service.ts +++ b/src/api/services/monitor.service.ts @@ -1,19 +1,18 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { ProviderFiles } from '@api/provider/sessions'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { channelController } from '@api/server.module'; +import { Events, Integration } from '@api/types/wa.types'; +import { CacheConf, Chatwoot, ConfigService, Database, DelInstance, ProviderSession } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { INSTANCE_DIR, STORE_DIR } from '@config/path.config'; +import { NotFoundException } from '@exceptions'; import { execSync } from 'child_process'; import EventEmitter2 from 'eventemitter2'; import { rmSync } from 'fs'; import { join } from 'path'; -import { CacheConf, Chatwoot, ConfigService, Database, DelInstance, ProviderSession } from '../../config/env.config'; -import { Logger } from '../../config/logger.config'; -import { INSTANCE_DIR, STORE_DIR } from '../../config/path.config'; -import { NotFoundException } from '../../exceptions'; -import { InstanceDto } from '../dto/instance.dto'; -import { ProviderFiles } from '../provider/sessions'; -import { PrismaRepository } from '../repository/repository.service'; -import { Integration } from '../types/wa.types'; import { CacheService } from './cache.service'; -import { BaileysStartupService } from './channels/whatsapp.baileys.service'; -import { BusinessStartupService } from './channels/whatsapp.business.service'; export class WAMonitoringService { constructor( @@ -35,8 +34,8 @@ export class WAMonitoringService { private readonly db: Partial = {}; private readonly redis: Partial = {}; - private readonly logger = new Logger(WAMonitoringService.name); - public readonly waInstances: Record = {}; + private readonly logger = new Logger('WAMonitoringService'); + public readonly waInstances: Record = {}; private readonly providerSession = Object.freeze(this.configService.get('PROVIDER')); @@ -51,11 +50,8 @@ export class WAMonitoringService { this.waInstances[instance]?.client?.ws?.close(); this.waInstances[instance]?.client?.end(undefined); } - this.waInstances[instance]?.removeRabbitmqQueues(); - delete this.waInstances[instance]; + this.eventEmitter.emit('remove.instance', instance, 'inner'); } else { - this.waInstances[instance]?.removeRabbitmqQueues(); - delete this.waInstances[instance]; this.eventEmitter.emit('remove.instance', instance, 'inner'); } } @@ -68,7 +64,7 @@ export class WAMonitoringService { throw new NotFoundException(`Instance "${instanceName}" not found`); } - const clientName = await this.configService.get('DATABASE').CONNECTION.CLIENT_NAME; + const clientName = this.configService.get('DATABASE').CONNECTION.CLIENT_NAME; const where = instanceName ? { name: instanceName, clientName } : { clientName }; @@ -120,23 +116,30 @@ export class WAMonitoringService { } public async cleaningUp(instanceName: string) { - if (this.db.ENABLED && this.db.SAVE_DATA.INSTANCE) { - const instance = await this.prismaRepository.instance.update({ + let instanceDbId: string; + if (this.db.SAVE_DATA.INSTANCE) { + const findInstance = await this.prismaRepository.instance.findFirst({ where: { name: instanceName }, - data: { connectionStatus: 'close' }, }); - if (!instance) this.logger.error('Instance not found'); + if (findInstance) { + const instance = await this.prismaRepository.instance.update({ + where: { name: instanceName }, + data: { connectionStatus: 'close' }, + }); - rmSync(join(INSTANCE_DIR, instance.id), { recursive: true, force: true }); + rmSync(join(INSTANCE_DIR, instance.id), { recursive: true, force: true }); - await this.prismaRepository.session.deleteMany({ where: { sessionId: instance.id } }); - return; + instanceDbId = instance.id; + await this.prismaRepository.session.deleteMany({ where: { sessionId: instance.id } }); + } } if (this.redis.REDIS.ENABLED && this.redis.REDIS.SAVE_INSTANCES) { await this.cache.delete(instanceName); - return; + if (instanceDbId) { + await this.cache.delete(instanceDbId); + } } if (this.providerSession?.ENABLED) { @@ -145,12 +148,16 @@ export class WAMonitoringService { } public async cleaningStoreData(instanceName: string) { - execSync(`rm -rf ${join(STORE_DIR, 'chatwoot', instanceName + '*')}`); + if (this.configService.get('CHATWOOT').ENABLED) { + execSync(`rm -rf ${join(STORE_DIR, 'chatwoot', instanceName + '*')}`); + } const instance = await this.prismaRepository.instance.findFirst({ where: { name: instanceName }, }); + if (!instance) return; + rmSync(join(INSTANCE_DIR, instance.id), { recursive: true, force: true }); await this.prismaRepository.session.deleteMany({ where: { sessionId: instance.id } }); @@ -165,7 +172,7 @@ export class WAMonitoringService { await this.prismaRepository.proxy.deleteMany({ where: { instanceId: instance.id } }); await this.prismaRepository.rabbitmq.deleteMany({ where: { instanceId: instance.id } }); await this.prismaRepository.sqs.deleteMany({ where: { instanceId: instance.id } }); - await this.prismaRepository.typebotSession.deleteMany({ where: { instanceId: instance.id } }); + await this.prismaRepository.integrationSession.deleteMany({ where: { instanceId: instance.id } }); await this.prismaRepository.typebot.deleteMany({ where: { instanceId: instance.id } }); await this.prismaRepository.websocket.deleteMany({ where: { instanceId: instance.id } }); await this.prismaRepository.setting.deleteMany({ where: { instanceId: instance.id } }); @@ -178,7 +185,7 @@ export class WAMonitoringService { try { if (this.providerSession?.ENABLED) { await this.loadInstancesFromProvider(); - } else if (this.db.ENABLED && this.db.SAVE_DATA.INSTANCE) { + } else if (this.db.SAVE_DATA.INSTANCE) { await this.loadInstancesFromDatabasePostgres(); } else if (this.redis.REDIS.ENABLED && this.redis.REDIS.SAVE_INSTANCES) { await this.loadInstancesFromRedis(); @@ -190,68 +197,54 @@ export class WAMonitoringService { public async saveInstance(data: any) { try { - if (this.db.ENABLED) { - const clientName = await this.configService.get('DATABASE').CONNECTION.CLIENT_NAME; - await this.prismaRepository.instance.create({ - data: { - id: data.instanceId, - name: data.instanceName, - connectionStatus: data.integration && data.integration === Integration.WHATSAPP_BUSINESS ? 'open' : 'close', - number: data.number, - integration: data.integration || Integration.WHATSAPP_BAILEYS, - token: data.hash, - clientName: clientName, - businessId: data.businessId, - }, - }); - } + const clientName = await this.configService.get('DATABASE').CONNECTION.CLIENT_NAME; + await this.prismaRepository.instance.create({ + data: { + id: data.instanceId, + name: data.instanceName, + connectionStatus: + data.integration && data.integration === Integration.WHATSAPP_BAILEYS ? 'close' : data.status ?? 'open', + number: data.number, + integration: data.integration || Integration.WHATSAPP_BAILEYS, + token: data.hash, + clientName: clientName, + businessId: data.businessId, + }, + }); + } catch (error) { + this.logger.error(error); + } + } + + public deleteInstance(instanceName: string) { + try { + this.eventEmitter.emit('remove.instance', instanceName, 'inner'); } catch (error) { this.logger.error(error); } } private async setInstance(instanceData: InstanceDto) { - let instance: BaileysStartupService | BusinessStartupService; + const instance = channelController.init(instanceData, { + configService: this.configService, + eventEmitter: this.eventEmitter, + prismaRepository: this.prismaRepository, + cache: this.cache, + chatwootCache: this.chatwootCache, + baileysCache: this.baileysCache, + providerFiles: this.providerFiles, + }); - if (instanceData.integration && instanceData.integration === Integration.WHATSAPP_BUSINESS) { - instance = new BusinessStartupService( - this.configService, - this.eventEmitter, - this.prismaRepository, - this.cache, - this.chatwootCache, - this.baileysCache, - this.providerFiles, - ); + if (!instance) return; - instance.setInstance({ - instanceId: instanceData.instanceId, - instanceName: instanceData.instanceName, - integration: instanceData.integration, - token: instanceData.token, - number: instanceData.number, - businessId: instanceData.businessId, - }); - } else { - instance = new BaileysStartupService( - this.configService, - this.eventEmitter, - this.prismaRepository, - this.cache, - this.chatwootCache, - this.baileysCache, - this.providerFiles, - ); - - instance.setInstance({ - instanceId: instanceData.instanceId, - instanceName: instanceData.instanceName, - integration: instanceData.integration, - token: instanceData.token, - number: instanceData.number, - businessId: instanceData.businessId, - }); - } + instance.setInstance({ + instanceId: instanceData.instanceId, + instanceName: instanceData.instanceName, + integration: instanceData.integration, + token: instanceData.token, + number: instanceData.number, + businessId: instanceData.businessId, + }); await instance.connectToWhatsapp(); @@ -339,6 +332,8 @@ export class WAMonitoringService { private removeInstance() { this.eventEmitter.on('remove.instance', async (instanceName: string) => { try { + await this.waInstances[instanceName]?.sendDataWebhook(Events.REMOVE_INSTANCE, null); + this.cleaningUp(instanceName); this.cleaningStoreData(instanceName); } finally { @@ -353,7 +348,12 @@ export class WAMonitoringService { }); this.eventEmitter.on('logout.instance', async (instanceName: string) => { try { - if (this.configService.get('CHATWOOT').ENABLED) this.waInstances[instanceName]?.clearCacheChatwoot(); + await this.waInstances[instanceName]?.sendDataWebhook(Events.LOGOUT_INSTANCE, null); + + if (this.configService.get('CHATWOOT').ENABLED) { + this.waInstances[instanceName]?.clearCacheChatwoot(); + } + this.cleaningUp(instanceName); } finally { this.logger.warn(`Instance "${instanceName}" - LOGOUT`); diff --git a/src/api/services/proxy.service.ts b/src/api/services/proxy.service.ts index e65d6758..69ba87b4 100644 --- a/src/api/services/proxy.service.ts +++ b/src/api/services/proxy.service.ts @@ -1,14 +1,14 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { ProxyDto } from '@api/dto/proxy.dto'; +import { Logger } from '@config/logger.config'; import { Proxy } from '@prisma/client'; -import { Logger } from '../../config/logger.config'; -import { InstanceDto } from '../dto/instance.dto'; -import { ProxyDto } from '../dto/proxy.dto'; import { WAMonitoringService } from './monitor.service'; export class ProxyService { constructor(private readonly waMonitor: WAMonitoringService) {} - private readonly logger = new Logger(ProxyService.name); + private readonly logger = new Logger('ProxyService'); public create(instance: InstanceDto, data: ProxyDto) { this.waMonitor.waInstances[instance.instanceName].setProxy(data); diff --git a/src/api/services/settings.service.ts b/src/api/services/settings.service.ts index 565962bd..5b7ab1b8 100644 --- a/src/api/services/settings.service.ts +++ b/src/api/services/settings.service.ts @@ -1,12 +1,13 @@ -import { Logger } from '../../config/logger.config'; -import { InstanceDto } from '../dto/instance.dto'; -import { SettingsDto } from '../dto/settings.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { SettingsDto } from '@api/dto/settings.dto'; +import { Logger } from '@config/logger.config'; + import { WAMonitoringService } from './monitor.service'; export class SettingsService { constructor(private readonly waMonitor: WAMonitoringService) {} - private readonly logger = new Logger(SettingsService.name); + private readonly logger = new Logger('SettingsService'); public async create(instance: InstanceDto, data: SettingsDto) { await this.waMonitor.waInstances[instance.instanceName].setSettings(data); diff --git a/src/api/services/template.service.ts b/src/api/services/template.service.ts index e959be23..949f71c7 100644 --- a/src/api/services/template.service.ts +++ b/src/api/services/template.service.ts @@ -1,10 +1,10 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { TemplateDto } from '@api/dto/template.dto'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { ConfigService, WaBusiness } from '@config/env.config'; +import { Logger } from '@config/logger.config'; import axios from 'axios'; -import { ConfigService, WaBusiness } from '../../config/env.config'; -import { Logger } from '../../config/logger.config'; -import { InstanceDto } from '../dto/instance.dto'; -import { TemplateDto } from '../dto/template.dto'; -import { PrismaRepository } from '../repository/repository.service'; import { WAMonitoringService } from './monitor.service'; export class TemplateService { @@ -14,7 +14,7 @@ export class TemplateService { private readonly configService: ConfigService, ) {} - private readonly logger = new Logger(TemplateService.name); + private readonly logger = new Logger('TemplateService'); private businessId: string; private token: string; diff --git a/src/api/services/webhook.service.ts b/src/api/services/webhook.service.ts deleted file mode 100644 index 80df1688..00000000 --- a/src/api/services/webhook.service.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { Webhook } from '@prisma/client'; -import axios from 'axios'; - -import { Logger } from '../../config/logger.config'; -import { InstanceDto } from '../dto/instance.dto'; -import { WebhookDto } from '../dto/webhook.dto'; -import { PrismaRepository } from '../repository/repository.service'; -import { WAMonitoringService } from './monitor.service'; - -export class WebhookService { - constructor(private readonly waMonitor: WAMonitoringService, public readonly prismaRepository: PrismaRepository) {} - - private readonly logger = new Logger(WebhookService.name); - - public create(instance: InstanceDto, data: WebhookDto) { - this.waMonitor.waInstances[instance.instanceName].setWebhook(data); - - return { webhook: { ...instance, webhook: data } }; - } - - public async find(instance: InstanceDto): Promise { - try { - const result = await this.waMonitor.waInstances[instance.instanceName].findWebhook(); - - if (Object.keys(result).length === 0) { - throw new Error('Webhook not found'); - } - - return result; - } catch (error) { - return null; - } - } - - public async receiveWebhook(data: any) { - if (data.object === 'whatsapp_business_account') { - if (data.entry[0]?.changes[0]?.field === 'message_template_status_update') { - const template = await this.prismaRepository.template.findFirst({ - where: { templateId: `${data.entry[0].changes[0].value.message_template_id}` }, - }); - - if (!template) { - console.log('template not found'); - return; - } - - const { webhookUrl } = template; - - await axios.post(webhookUrl, data.entry[0].changes[0].value, { - headers: { - 'Content-Type': 'application/json', - }, - }); - return; - } - - data.entry?.forEach(async (entry: any) => { - const numberId = entry.changes[0].value.metadata.phone_number_id; - - if (!numberId) { - this.logger.error('WebhookService -> receiveWebhook -> numberId not found'); - return; - } - - const instance = await this.prismaRepository.instance.findFirst({ - where: { number: numberId }, - }); - - if (!instance) { - this.logger.error('WebhookService -> receiveWebhook -> instance not found'); - return; - } - - await this.waMonitor.waInstances[instance.name].connectToWhatsapp(data); - - return; - }); - } - - return; - } -} diff --git a/src/api/types/wa.types.ts b/src/api/types/wa.types.ts index 93187bb6..8d150221 100644 --- a/src/api/types/wa.types.ts +++ b/src/api/types/wa.types.ts @@ -33,6 +33,8 @@ export enum Events { LABELS_ASSOCIATION = 'labels.association', CREDS_UPDATE = 'creds.update', MESSAGING_HISTORY_SET = 'messaging-history.set', + REMOVE_INSTANCE = 'remove.instance', + LOGOUT_INSTANCE = 'logout.instance', } export declare namespace wa { @@ -58,14 +60,6 @@ export declare namespace wa { businessId?: string; }; - export type LocalWebHook = { - enabled?: boolean; - url?: string; - events?: JsonValue; - webhookByEvents?: boolean; - webhookBase64?: boolean; - }; - export type LocalChatwoot = { enabled?: boolean; accountId?: string; @@ -93,19 +87,16 @@ export declare namespace wa { syncFullHistory?: boolean; }; - export type LocalWebsocket = { + export type LocalEvent = { enabled?: boolean; events?: JsonValue; }; - export type LocalRabbitmq = { - enabled?: boolean; - events?: JsonValue; - }; - - export type LocalSqs = { - enabled?: boolean; - events?: JsonValue; + export type LocalWebHook = LocalEvent & { + url?: string; + headers?: JsonValue; + webhookByEvents?: boolean; + webhookBase64?: boolean; }; type Session = { @@ -144,4 +135,5 @@ export const MessageSubtype = [ export const Integration = { WHATSAPP_BUSINESS: 'WHATSAPP-BUSINESS', WHATSAPP_BAILEYS: 'WHATSAPP-BAILEYS', + EVOLUTION: 'EVOLUTION', }; diff --git a/src/cache/cacheengine.ts b/src/cache/cacheengine.ts index dd3d18f1..d6ee87b9 100644 --- a/src/cache/cacheengine.ts +++ b/src/cache/cacheengine.ts @@ -1,10 +1,11 @@ -import { ICache } from '../api/abstract/abstract.cache'; -import { CacheConf, ConfigService } from '../config/env.config'; -import { Logger } from '../config/logger.config'; +import { ICache } from '@api/abstract/abstract.cache'; +import { CacheConf, ConfigService } from '@config/env.config'; +import { Logger } from '@config/logger.config'; + import { LocalCache } from './localcache'; import { RedisCache } from './rediscache'; -const logger = new Logger('Redis'); +const logger = new Logger('CacheEngine'); export class CacheEngine { private engine: ICache; @@ -13,12 +14,14 @@ export class CacheEngine { const cacheConf = configService.get('CACHE'); if (cacheConf?.REDIS?.ENABLED && cacheConf?.REDIS?.URI !== '') { + logger.verbose(`RedisCache initialized for ${module}`); this.engine = new RedisCache(configService, module); } else if (cacheConf?.LOCAL?.ENABLED) { + logger.verbose(`LocalCache initialized for ${module}`); this.engine = new LocalCache(configService, module); } - logger.info(`RedisCache initialized for ${module}`); + } public getEngine() { diff --git a/src/cache/localcache.ts b/src/cache/localcache.ts index 54a51d90..130d4865 100644 --- a/src/cache/localcache.ts +++ b/src/cache/localcache.ts @@ -1,8 +1,7 @@ +import { ICache } from '@api/abstract/abstract.cache'; +import { CacheConf, CacheConfLocal, ConfigService } from '@config/env.config'; import NodeCache from 'node-cache'; -import { ICache } from '../api/abstract/abstract.cache'; -import { CacheConf, CacheConfLocal, ConfigService } from '../config/env.config'; - export class LocalCache implements ICache { private conf: CacheConfLocal; static localCache = new NodeCache(); diff --git a/src/cache/rediscache.client.ts b/src/cache/rediscache.client.ts index 350f05e2..45a0321f 100644 --- a/src/cache/rediscache.client.ts +++ b/src/cache/rediscache.client.ts @@ -1,10 +1,9 @@ +import { CacheConf, CacheConfRedis, configService } from '@config/env.config'; +import { Logger } from '@config/logger.config'; import { createClient, RedisClientType } from 'redis'; -import { CacheConf, CacheConfRedis, configService } from '../config/env.config'; -import { Logger } from '../config/logger.config'; - class Redis { - private logger = new Logger(Redis.name); + private logger = new Logger('Redis'); private client: RedisClientType = null; private conf: CacheConfRedis; private connected = false; diff --git a/src/cache/rediscache.ts b/src/cache/rediscache.ts index c4e98968..67c21c37 100644 --- a/src/cache/rediscache.ts +++ b/src/cache/rediscache.ts @@ -1,13 +1,13 @@ +import { ICache } from '@api/abstract/abstract.cache'; +import { CacheConf, CacheConfRedis, ConfigService } from '@config/env.config'; +import { Logger } from '@config/logger.config'; import { BufferJSON } from 'baileys'; import { RedisClientType } from 'redis'; -import { ICache } from '../api/abstract/abstract.cache'; -import { CacheConf, CacheConfRedis, ConfigService } from '../config/env.config'; -import { Logger } from '../config/logger.config'; import { redisClient } from './rediscache.client'; export class RedisCache implements ICache { - private readonly logger = new Logger(RedisCache.name); + private readonly logger = new Logger('RedisCache'); private client: RedisClientType; private conf: CacheConfRedis; diff --git a/src/config/env.config.ts b/src/config/env.config.ts index 26ff40a0..76aac9c8 100644 --- a/src/config/env.config.ts +++ b/src/config/env.config.ts @@ -20,7 +20,7 @@ export type Cors = { export type LogBaileys = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace'; -export type LogLevel = 'ERROR' | 'WARN' | 'DEBUG' | 'INFO' | 'LOG' | 'VERBOSE' | 'DARK' | 'WEBHOOKS'; +export type LogLevel = 'ERROR' | 'WARN' | 'DEBUG' | 'INFO' | 'LOG' | 'VERBOSE' | 'DARK' | 'WEBHOOKS' | 'WEBSOCKET'; export type Log = { LEVEL: LogLevel[]; @@ -43,6 +43,8 @@ export type SaveData = { CONTACTS: boolean; CHATS: boolean; LABELS: boolean; + IS_ON_WHATSAPP: boolean; + IS_ON_WHATSAPP_DAYS: number; }; export type DBConnection = { @@ -51,7 +53,6 @@ export type DBConnection = { }; export type Database = { CONNECTION: DBConnection; - ENABLED: boolean; PROVIDER: string; SAVE_DATA: SaveData; }; @@ -182,6 +183,7 @@ export type Chatwoot = { ENABLED: boolean; MESSAGE_DELETE: boolean; MESSAGE_READ: boolean; + BOT_CONTACT: boolean; IMPORT: { DATABASE: { CONNECTION: { @@ -202,6 +204,7 @@ export type S3 = { ENABLE: boolean; PORT?: number; USE_SSL?: boolean; + REGION?: string; }; export type CacheConf = { REDIS: CacheConfRedis; LOCAL: CacheConfLocal }; @@ -285,7 +288,6 @@ export class ConfigService { URI: process.env.DATABASE_CONNECTION_URI || '', CLIENT_NAME: process.env.DATABASE_CONNECTION_CLIENT_NAME || 'evolution', }, - ENABLED: process.env?.DATABASE_ENABLED === 'true', PROVIDER: process.env.DATABASE_PROVIDER || 'postgresql', SAVE_DATA: { INSTANCE: process.env?.DATABASE_SAVE_DATA_INSTANCE === 'true', @@ -295,6 +297,8 @@ export class ConfigService { CHATS: process.env?.DATABASE_SAVE_DATA_CHATS === 'true', HISTORIC: process.env?.DATABASE_SAVE_DATA_HISTORIC === 'true', LABELS: process.env?.DATABASE_SAVE_DATA_LABELS === 'true', + IS_ON_WHATSAPP: process.env?.DATABASE_SAVE_IS_ON_WHATSAPP === 'true', + IS_ON_WHATSAPP_DAYS: Number.parseInt(process.env?.DATABASE_SAVE_IS_ON_WHATSAPP_DAYS ?? '7'), }, }, RABBITMQ: { @@ -359,6 +363,7 @@ export class ConfigService { 'VERBOSE', 'DARK', 'WEBHOOKS', + 'WEBSOCKET', ], COLOR: process.env?.LOG_COLOR === 'true', BAILEYS: (process.env?.LOG_BAILEYS as LogBaileys) || 'error', @@ -426,6 +431,7 @@ export class ConfigService { ENABLED: process.env?.CHATWOOT_ENABLED === 'true', MESSAGE_DELETE: process.env.CHATWOOT_MESSAGE_DELETE === 'true', MESSAGE_READ: process.env.CHATWOOT_MESSAGE_READ === 'true', + BOT_CONTACT: !process.env.CHATWOOT_BOT_CONTACT || process.env.CHATWOOT_BOT_CONTACT === 'true', IMPORT: { DATABASE: { CONNECTION: { @@ -463,6 +469,7 @@ export class ConfigService { ENABLE: process.env?.S3_ENABLED === 'true', PORT: Number.parseInt(process.env?.S3_PORT || '9000'), USE_SSL: process.env?.S3_USE_SSL === 'true', + REGION: process.env?.S3_REGION, }, AUTHENTICATION: { API_KEY: { diff --git a/src/config/logger.config.ts b/src/config/logger.config.ts index c52d3ccc..bc27db5c 100644 --- a/src/config/logger.config.ts +++ b/src/config/logger.config.ts @@ -58,7 +58,11 @@ enum Background { export class Logger { private readonly configService = configService; - constructor(private context = 'Logger') {} + private context: string; + + constructor(context = 'Logger') { + this.context = context; + } private instance = null; diff --git a/src/exceptions/400.exception.ts b/src/exceptions/400.exception.ts index 2ea3a7a4..123696cb 100644 --- a/src/exceptions/400.exception.ts +++ b/src/exceptions/400.exception.ts @@ -1,4 +1,4 @@ -import { HttpStatus } from '../api/routes/index.router'; +import { HttpStatus } from '@api/routes/index.router'; export class BadRequestException { constructor(...objectError: any[]) { diff --git a/src/exceptions/401.exception.ts b/src/exceptions/401.exception.ts index f5383e0e..8ff9076c 100644 --- a/src/exceptions/401.exception.ts +++ b/src/exceptions/401.exception.ts @@ -1,4 +1,4 @@ -import { HttpStatus } from '../api/routes/index.router'; +import { HttpStatus } from '@api/routes/index.router'; export class UnauthorizedException { constructor(...objectError: any[]) { diff --git a/src/exceptions/403.exception.ts b/src/exceptions/403.exception.ts index 53d8f05c..f1f39998 100644 --- a/src/exceptions/403.exception.ts +++ b/src/exceptions/403.exception.ts @@ -1,4 +1,4 @@ -import { HttpStatus } from '../api/routes/index.router'; +import { HttpStatus } from '@api/routes/index.router'; export class ForbiddenException { constructor(...objectError: any[]) { diff --git a/src/exceptions/404.exception.ts b/src/exceptions/404.exception.ts index f2fd5c28..16f912e4 100644 --- a/src/exceptions/404.exception.ts +++ b/src/exceptions/404.exception.ts @@ -1,4 +1,4 @@ -import { HttpStatus } from '../api/routes/index.router'; +import { HttpStatus } from '@api/routes/index.router'; export class NotFoundException { constructor(...objectError: any[]) { diff --git a/src/exceptions/500.exception.ts b/src/exceptions/500.exception.ts index c5111f6d..316223e5 100644 --- a/src/exceptions/500.exception.ts +++ b/src/exceptions/500.exception.ts @@ -1,4 +1,4 @@ -import { HttpStatus } from '../api/routes/index.router'; +import { HttpStatus } from '@api/routes/index.router'; export class InternalServerErrorException { constructor(...objectError: any[]) { diff --git a/src/libs/prisma.connect.ts b/src/libs/prisma.connect.ts index 73b1cd21..fa8d6600 100644 --- a/src/libs/prisma.connect.ts +++ b/src/libs/prisma.connect.ts @@ -1,22 +1,16 @@ +import { Logger } from '@config/logger.config'; import { PrismaClient } from '@prisma/client'; -import { configService, Database } from '../config/env.config'; -import { Logger } from '../config/logger.config'; - const logger = new Logger('Prisma'); -const db = configService.get('DATABASE'); - export const prismaServer = (() => { - if (db.ENABLED) { - logger.verbose('connecting'); - const db = new PrismaClient(); + logger.verbose('connecting'); + const db = new PrismaClient(); - process.on('beforeExit', () => { - logger.verbose('instance destroyed'); - db.$disconnect(); - }); + process.on('beforeExit', () => { + logger.verbose('instance destroyed'); + db.$disconnect(); + }); - return db; - } + return db; })(); diff --git a/src/main.ts b/src/main.ts index 15676249..5204b698 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,24 +1,19 @@ -import 'express-async-errors'; - +import { ProviderFiles } from '@api/provider/sessions'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { HttpStatus, router } from '@api/routes/index.router'; +import { eventManager, waMonitor } from '@api/server.module'; +import { Auth, configService, Cors, HttpServer, ProviderSession, Webhook } from '@config/env.config'; +import { onUnexpectedError } from '@config/error.config'; +import { Logger } from '@config/logger.config'; +import { ROOT_DIR } from '@config/path.config'; +import * as Sentry from '@sentry/node'; +import { ServerUP } from '@utils/server-up'; import axios from 'axios'; import compression from 'compression'; import cors from 'cors'; import express, { json, NextFunction, Request, Response, urlencoded } from 'express'; import { join } from 'path'; -import { initAMQP, initGlobalQueues } from './api/integrations/rabbitmq/libs/amqp.server'; -import { initSQS } from './api/integrations/sqs/libs/sqs.server'; -import { initIO } from './api/integrations/websocket/libs/socket.server'; -import { ProviderFiles } from './api/provider/sessions'; -import { PrismaRepository } from './api/repository/repository.service'; -import { HttpStatus, router } from './api/routes/index.router'; -import { waMonitor } from './api/server.module'; -import { Auth, configService, Cors, HttpServer, ProviderSession, Rabbitmq, Sqs, Webhook } from './config/env.config'; -import { onUnexpectedError } from './config/error.config'; -import { Logger } from './config/logger.config'; -import { ROOT_DIR } from './config/path.config'; -import { ServerUP } from './utils/server-up'; - function initWA() { waMonitor.loadInstance(); } @@ -26,6 +21,19 @@ function initWA() { async function bootstrap() { const logger = new Logger('SERVER'); const app = express(); + const dsn = process.env.SENTRY_DSN; + + if (dsn) { + logger.info('Sentry - ON'); + Sentry.init({ + dsn: dsn, + environment: process.env.NODE_ENV || 'development', + tracesSampleRate: 1.0, + profilesSampleRate: 1.0, + }); + + Sentry.setupExpressErrorHandler(app); + } let providerFiles: ProviderFiles = null; if (configService.get('PROVIDER').ENABLED) { @@ -131,20 +139,12 @@ async function bootstrap() { ServerUP.app = app; const server = ServerUP[httpServer.TYPE]; + eventManager.init(server); + server.listen(httpServer.PORT, () => logger.log(httpServer.TYPE.toUpperCase() + ' - ON: ' + httpServer.PORT)); initWA(); - initIO(server); - - if (configService.get('RABBITMQ')?.ENABLED) { - initAMQP().then(() => { - if (configService.get('RABBITMQ')?.GLOBAL_ENABLED) initGlobalQueues(); - }); - } - - if (configService.get('SQS')?.ENABLED) initSQS(); - onUnexpectedError(); } diff --git a/src/utils/advancedOperatorsSearch.ts b/src/utils/advancedOperatorsSearch.ts new file mode 100644 index 00000000..dc0ec5ce --- /dev/null +++ b/src/utils/advancedOperatorsSearch.ts @@ -0,0 +1,45 @@ +function normalizeString(str: string): string { + return str + .normalize('NFD') + .replace(/[\u0300-\u036f]/g, '') + .toLowerCase(); +} + +export function advancedOperatorsSearch(data: string, query: string): boolean { + const filters = query.split(' ').reduce((acc: Record, filter) => { + const [operator, ...values] = filter.split(':'); + const value = values.join(':'); + + if (!acc[operator]) { + acc[operator] = []; + } + acc[operator].push(value); + return acc; + }, {}); + + const normalizedItem = normalizeString(data); + + return Object.entries(filters).every(([operator, values]) => { + return values.some((val) => { + const subValues = val.split(','); + return subValues.every((subVal) => { + const normalizedSubVal = normalizeString(subVal); + + switch (operator.toLowerCase()) { + case 'contains': + return normalizedItem.includes(normalizedSubVal); + case 'notcontains': + return !normalizedItem.includes(normalizedSubVal); + case 'startswith': + return normalizedItem.startsWith(normalizedSubVal); + case 'endswith': + return normalizedItem.endsWith(normalizedSubVal); + case 'exact': + return normalizedItem === normalizedSubVal; + default: + return false; + } + }); + }); + }); +} diff --git a/src/utils/findBotByTrigger.ts b/src/utils/findBotByTrigger.ts new file mode 100644 index 00000000..dc199254 --- /dev/null +++ b/src/utils/findBotByTrigger.ts @@ -0,0 +1,149 @@ +import { advancedOperatorsSearch } from './advancedOperatorsSearch'; + +export const findBotByTrigger = async ( + botRepository: any, + settingsRepository: any, + content: string, + instanceId: string, +) => { + // Check for triggerType 'all' + const findTriggerAll = await botRepository.findFirst({ + where: { + enabled: true, + triggerType: 'all', + instanceId: instanceId, + }, + }); + + if (findTriggerAll) return findTriggerAll; + + const findTriggerAdvanced = await botRepository.findMany({ + where: { + enabled: true, + triggerType: 'advanced', + instanceId: instanceId, + }, + }); + for (const advanced of findTriggerAdvanced) { + if (advancedOperatorsSearch(content, advanced.triggerValue)) { + return advanced; + } + } + + // Check for exact match + const findTriggerEquals = await botRepository.findFirst({ + where: { + enabled: true, + triggerType: 'keyword', + triggerOperator: 'equals', + triggerValue: content, + instanceId: instanceId, + }, + }); + + if (findTriggerEquals) return findTriggerEquals; + + // Check for regex match + const findRegex = await botRepository.findMany({ + where: { + enabled: true, + triggerType: 'keyword', + triggerOperator: 'regex', + instanceId: instanceId, + }, + }); + + let findTriggerRegex = null; + + for (const regex of findRegex) { + const regexValue = new RegExp(regex.triggerValue); + + if (regexValue.test(content)) { + findTriggerRegex = regex; + break; + } + } + + if (findTriggerRegex) return findTriggerRegex; + + // Check for startsWith match + const findStartsWith = await botRepository.findMany({ + where: { + enabled: true, + triggerType: 'keyword', + triggerOperator: 'startsWith', + instanceId: instanceId, + }, + }); + + let findTriggerStartsWith = null; + + for (const startsWith of findStartsWith) { + if (content.startsWith(startsWith.triggerValue)) { + findTriggerStartsWith = startsWith; + break; + } + } + + if (findTriggerStartsWith) return findTriggerStartsWith; + + // Check for endsWith match + const findEndsWith = await botRepository.findMany({ + where: { + enabled: true, + triggerType: 'keyword', + triggerOperator: 'endsWith', + instanceId: instanceId, + }, + }); + + let findTriggerEndsWith = null; + + for (const endsWith of findEndsWith) { + if (content.endsWith(endsWith.triggerValue)) { + findTriggerEndsWith = endsWith; + break; + } + } + + if (findTriggerEndsWith) return findTriggerEndsWith; + + // Check for contains match + const findContains = await botRepository.findMany({ + where: { + enabled: true, + triggerType: 'keyword', + triggerOperator: 'contains', + instanceId: instanceId, + }, + }); + + let findTriggerContains = null; + + for (const contains of findContains) { + if (content.includes(contains.triggerValue)) { + findTriggerContains = contains; + break; + } + } + + if (findTriggerContains) return findTriggerContains; + + const fallback = await settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (fallback?.openaiIdFallback) { + const findFallback = await botRepository.findFirst({ + where: { + id: fallback.openaiIdFallback, + }, + }); + + if (findFallback) return findFallback; + } + + return null; +}; diff --git a/src/utils/getConversationMessage.ts b/src/utils/getConversationMessage.ts new file mode 100644 index 00000000..cbd33b41 --- /dev/null +++ b/src/utils/getConversationMessage.ts @@ -0,0 +1,72 @@ +import { configService, S3 } from '@config/env.config'; + +const getTypeMessage = (msg: any) => { + let mediaId: string; + + if (configService.get('S3').ENABLE) mediaId = msg.message.mediaUrl; + else mediaId = msg.key.id; + + const types = { + conversation: msg?.message?.conversation, + extendedTextMessage: msg?.message?.extendedTextMessage?.text, + contactMessage: msg?.message?.contactMessage?.displayName, + locationMessage: msg?.message?.locationMessage?.degreesLatitude, + viewOnceMessageV2: + msg?.message?.viewOnceMessageV2?.message?.imageMessage?.url || + msg?.message?.viewOnceMessageV2?.message?.videoMessage?.url || + msg?.message?.viewOnceMessageV2?.message?.audioMessage?.url, + listResponseMessage: msg?.message?.listResponseMessage?.singleSelectReply?.selectedRowId, + responseRowId: msg?.message?.listResponseMessage?.singleSelectReply?.selectedRowId, + // Medias + audioMessage: msg?.message?.speechToText + ? msg?.message?.speechToText + : msg?.message?.audioMessage + ? `audioMessage|${mediaId}` + : undefined, + imageMessage: msg?.message?.imageMessage + ? `imageMessage|${mediaId}${msg?.message?.imageMessage?.caption ? `|${msg?.message?.imageMessage?.caption}` : ''}` + : undefined, + videoMessage: msg?.message?.videoMessage + ? `videoMessage|${mediaId}${msg?.message?.videoMessage?.caption ? `|${msg?.message?.videoMessage?.caption}` : ''}` + : undefined, + documentMessage: msg?.message?.documentMessage + ? `documentMessage|${mediaId}${ + msg?.message?.documentMessage?.caption ? `|${msg?.message?.documentMessage?.caption}` : '' + }` + : undefined, + documentWithCaptionMessage: msg?.message?.documentWithCaptionMessage?.message?.documentMessage + ? `documentWithCaptionMessage|${mediaId}${ + msg?.message?.documentWithCaptionMessage?.message?.documentMessage?.caption + ? `|${msg?.message?.documentWithCaptionMessage?.message?.documentMessage?.caption}` + : '' + }` + : undefined, + externalAdReplyBody: msg?.contextInfo?.externalAdReply?.body + ? `externalAdReplyBody|${msg.contextInfo.externalAdReply.body}` + : undefined, + }; + + const messageType = Object.keys(types).find((key) => types[key] !== undefined) || 'unknown'; + + return { ...types, messageType }; +}; + +const getMessageContent = (types: any) => { + const typeKey = Object.keys(types).find((key) => key !== 'externalAdReplyBody' && types[key] !== undefined); + + let result = typeKey ? types[typeKey] : undefined; + + if (types.externalAdReplyBody) { + result = result ? `${result}\n${types.externalAdReplyBody}` : types.externalAdReplyBody; + } + + return result; +}; + +export const getConversationMessage = (msg: any) => { + const types = getTypeMessage(msg); + + const messageContent = getMessageContent(types); + + return messageContent; +}; diff --git a/src/utils/i18n.ts b/src/utils/i18n.ts index 8e23181d..b26a5ef0 100644 --- a/src/utils/i18n.ts +++ b/src/utils/i18n.ts @@ -1,9 +1,8 @@ +import { ConfigService, Language } from '@config/env.config'; import fs from 'fs'; import i18next from 'i18next'; import path from 'path'; -import { ConfigService, Language } from '../config/env.config'; - const languages = ['en', 'pt-BR', 'es']; const translationsPath = path.join(__dirname, 'translations'); const configService: ConfigService = new ConfigService(); diff --git a/src/utils/onWhatsappCache.ts b/src/utils/onWhatsappCache.ts new file mode 100644 index 00000000..a77ac396 --- /dev/null +++ b/src/utils/onWhatsappCache.ts @@ -0,0 +1,100 @@ +import { prismaRepository } from '@api/server.module'; +import { configService, Database } from '@config/env.config'; +import dayjs from 'dayjs'; + +function getAvailableNumbers(remoteJid: string) { + const numbersAvailable: string[] = []; + + if (remoteJid.startsWith('+')) { + remoteJid = remoteJid.slice(1); + } + + const [number, domain] = remoteJid.split('@'); + + // Brazilian numbers + if (remoteJid.startsWith('55')) { + const numberWithDigit = + number.slice(4, 5) === '9' && number.length === 13 ? number : `${number.slice(0, 4)}9${number.slice(4)}`; + const numberWithoutDigit = number.length === 12 ? number : number.slice(0, 4) + number.slice(5); + + numbersAvailable.push(numberWithDigit); + numbersAvailable.push(numberWithoutDigit); + } + + // Mexican/Argentina numbers + // Ref: https://faq.whatsapp.com/1294841057948784 + else if (number.startsWith('52') || number.startsWith('54')) { + let prefix = ''; + if (number.startsWith('52')) { + prefix = '1'; + } + if (number.startsWith('54')) { + prefix = '9'; + } + + const numberWithDigit = + number.slice(2, 3) === prefix && number.length === 13 + ? number + : `${number.slice(0, 2)}${prefix}${number.slice(2)}`; + const numberWithoutDigit = number.length === 12 ? number : number.slice(0, 2) + number.slice(3); + + numbersAvailable.push(numberWithDigit); + numbersAvailable.push(numberWithoutDigit); + } + + // Other countries + else { + numbersAvailable.push(remoteJid); + } + + return numbersAvailable.map((number) => `${number}@${domain}`); +} + +interface ISaveOnWhatsappCacheParams { + remoteJid: string; +} +export async function saveOnWhatsappCache(data: ISaveOnWhatsappCacheParams[]) { + if (configService.get('DATABASE').SAVE_DATA.IS_ON_WHATSAPP) { + const upsertsQuery = data.map((item) => { + const remoteJid = item.remoteJid.startsWith('+') ? item.remoteJid.slice(1) : item.remoteJid; + const numbersAvailable = getAvailableNumbers(remoteJid); + + return prismaRepository.isOnWhatsapp.upsert({ + create: { remoteJid: remoteJid, jidOptions: numbersAvailable.join(',') }, + update: { jidOptions: numbersAvailable.join(',') }, + where: { remoteJid: remoteJid }, + }); + }); + + await prismaRepository.$transaction(upsertsQuery); + } +} + +export async function getOnWhatsappCache(remoteJids: string[]) { + let results: { + remoteJid: string; + number: string; + jidOptions: string[]; + }[] = []; + + if (configService.get('DATABASE').SAVE_DATA.IS_ON_WHATSAPP) { + const remoteJidsWithoutPlus = remoteJids.map((remoteJid) => getAvailableNumbers(remoteJid)).flat(); + + const onWhatsappCache = await prismaRepository.isOnWhatsapp.findMany({ + where: { + OR: remoteJidsWithoutPlus.map((remoteJid) => ({ jidOptions: { contains: remoteJid } })), + updatedAt: { + gte: dayjs().subtract(configService.get('DATABASE').SAVE_DATA.IS_ON_WHATSAPP_DAYS, 'days').toDate(), + }, + }, + }); + + results = onWhatsappCache.map((item) => ({ + remoteJid: item.remoteJid, + number: item.remoteJid.split('@')[0], + jidOptions: item.jidOptions.split(','), + })); + } + + return results; +} diff --git a/src/utils/sendTelemetry.ts b/src/utils/sendTelemetry.ts index 1d823a06..037ca55d 100644 --- a/src/utils/sendTelemetry.ts +++ b/src/utils/sendTelemetry.ts @@ -10,16 +10,29 @@ export interface TelemetryData { } export const sendTelemetry = async (route: string): Promise => { + const enabled = process.env.TELEMETRY_ENABLED === undefined || process.env.TELEMETRY_ENABLED === 'true'; + + if (!enabled) { + return; + } + + if (route === '/') { + return; + } + const telemetry: TelemetryData = { route, apiVersion: `${packageJson.version}`, timestamp: new Date(), }; + const url = + process.env.TELEMETRY_URL && process.env.TELEMETRY_URL !== '' + ? process.env.TELEMETRY_URL + : 'https://log.evolution-api.com/telemetry'; + axios - .post('https://log.evolution-api.com/telemetry', telemetry) + .post(url, telemetry) .then(() => {}) - .catch((error) => { - console.error('Telemetry error', error); - }); + .catch(() => {}); }; diff --git a/src/utils/server-up.ts b/src/utils/server-up.ts index e06caea7..326b3be4 100644 --- a/src/utils/server-up.ts +++ b/src/utils/server-up.ts @@ -1,10 +1,9 @@ +import { configService, SslConf } from '@config/env.config'; import { Express } from 'express'; import { readFileSync } from 'fs'; import * as http from 'http'; import * as https from 'https'; -import { configService, SslConf } from '../config/env.config'; - export class ServerUP { static #app: Express; diff --git a/src/utils/use-multi-file-auth-state-prisma.ts b/src/utils/use-multi-file-auth-state-prisma.ts index 8790b3a5..b7b6e1b2 100644 --- a/src/utils/use-multi-file-auth-state-prisma.ts +++ b/src/utils/use-multi-file-auth-state-prisma.ts @@ -1,11 +1,10 @@ +import { CacheService } from '@api/services/cache.service'; +import { INSTANCE_DIR } from '@config/path.config'; +import { prismaServer } from '@libs/prisma.connect'; import { AuthenticationState, BufferJSON, initAuthCreds, WAProto as proto } from 'baileys'; import fs from 'fs/promises'; import path from 'path'; -import { CacheService } from '../api/services/cache.service'; -import { INSTANCE_DIR } from '../config/path.config'; -import { prismaServer } from '../libs/prisma.connect'; - const prisma = prismaServer; // const fixFileName = (file: string): string | undefined => { diff --git a/src/utils/use-multi-file-auth-state-provider-files.ts b/src/utils/use-multi-file-auth-state-provider-files.ts index ec4d7e6c..4dfa2fb2 100644 --- a/src/utils/use-multi-file-auth-state-provider-files.ts +++ b/src/utils/use-multi-file-auth-state-provider-files.ts @@ -34,18 +34,17 @@ * └──────────────────────────────────────────────────────────────────────────────┘ */ +import { ProviderFiles } from '@api/provider/sessions'; +import { Logger } from '@config/logger.config'; import { AuthenticationCreds, AuthenticationState, BufferJSON, initAuthCreds, proto, SignalDataTypeMap } from 'baileys'; import { isNotEmpty } from 'class-validator'; -import { ProviderFiles } from '../api/provider/sessions'; -import { Logger } from '../config/logger.config'; - export type AuthState = { state: AuthenticationState; saveCreds: () => Promise }; export class AuthStateProvider { constructor(private readonly providerFiles: ProviderFiles) {} - private readonly logger = new Logger(AuthStateProvider.name); + private readonly logger = new Logger('AuthStateProvider'); public async authStateProvider(instance: string): Promise { const [, error] = await this.providerFiles.create(instance); diff --git a/src/utils/use-multi-file-auth-state-redis-db.ts b/src/utils/use-multi-file-auth-state-redis-db.ts index d077b894..837f8092 100644 --- a/src/utils/use-multi-file-auth-state-redis-db.ts +++ b/src/utils/use-multi-file-auth-state-redis-db.ts @@ -1,8 +1,7 @@ +import { CacheService } from '@api/services/cache.service'; +import { Logger } from '@config/logger.config'; import { AuthenticationCreds, AuthenticationState, initAuthCreds, proto, SignalDataTypeMap } from 'baileys'; -import { CacheService } from '../api/services/cache.service'; -import { Logger } from '../config/logger.config'; - export async function useMultiFileAuthStateRedisDb( instanceName: string, cache: CacheService, @@ -10,7 +9,7 @@ export async function useMultiFileAuthStateRedisDb( state: AuthenticationState; saveCreds: () => Promise; }> { - const logger = new Logger(useMultiFileAuthStateRedisDb.name); + const logger = new Logger('useMultiFileAuthStateRedisDb'); const writeData = async (data: any, key: string): Promise => { try { diff --git a/src/validate/instance.schema.ts b/src/validate/instance.schema.ts index 646883f1..de5be2b9 100644 --- a/src/validate/instance.schema.ts +++ b/src/validate/instance.schema.ts @@ -1,8 +1,7 @@ +import { Integration } from '@api/types/wa.types'; import { JSONSchema7 } from 'json-schema'; import { v4 } from 'uuid'; -import { Integration } from '../api/types/wa.types'; - const isNotEmpty = (...propertyNames: string[]): JSONSchema7 => { const properties = {}; propertyNames.forEach( diff --git a/src/validate/validate.schema.ts b/src/validate/validate.schema.ts index 9321718a..cf3d7828 100644 --- a/src/validate/validate.schema.ts +++ b/src/validate/validate.schema.ts @@ -1,10 +1,4 @@ // Integrations Schema -export * from '../api/integrations/chatwoot/validate/chatwoot.schema'; -export * from '../api/integrations/dify/validate/dify.schema'; -export * from '../api/integrations/openai/validate/openai.schema'; -export * from '../api/integrations/rabbitmq/validate/rabbitmq.schema'; -export * from '../api/integrations/sqs/validate/sqs.schema'; -export * from '../api/integrations/typebot/validate/typebot.schema'; export * from './chat.schema'; export * from './group.schema'; export * from './instance.schema'; @@ -13,5 +7,5 @@ export * from './message.schema'; export * from './proxy.schema'; export * from './settings.schema'; export * from './template.schema'; -export * from './webhook.schema'; -export * from './websocket.schema'; +export * from '@api/integrations/chatbot/chatbot.schema'; +export * from '@api/integrations/event/event.schema'; diff --git a/src/validate/webhook.schema.ts b/src/validate/webhook.schema.ts deleted file mode 100644 index 82a3a5c2..00000000 --- a/src/validate/webhook.schema.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { JSONSchema7 } from 'json-schema'; -import { v4 } from 'uuid'; - -const isNotEmpty = (...propertyNames: string[]): JSONSchema7 => { - const properties = {}; - propertyNames.forEach( - (property) => - (properties[property] = { - minLength: 1, - description: `The "${property}" cannot be empty`, - }), - ); - return { - if: { - propertyNames: { - enum: [...propertyNames], - }, - }, - then: { properties }, - }; -}; - -export const webhookSchema: JSONSchema7 = { - $id: v4(), - type: 'object', - properties: { - enabled: { type: 'boolean' }, - url: { type: 'string' }, - webhookByEvents: { type: 'boolean' }, - webhookBase64: { type: 'boolean' }, - events: { - type: 'array', - minItems: 0, - items: { - type: 'string', - enum: [ - 'APPLICATION_STARTUP', - 'QRCODE_UPDATED', - 'MESSAGES_SET', - 'MESSAGES_UPSERT', - 'MESSAGES_EDITED', - 'MESSAGES_UPDATE', - 'MESSAGES_DELETE', - 'SEND_MESSAGE', - 'CONTACTS_SET', - 'CONTACTS_UPSERT', - 'CONTACTS_UPDATE', - 'PRESENCE_UPDATE', - 'CHATS_SET', - 'CHATS_UPSERT', - 'CHATS_UPDATE', - 'CHATS_DELETE', - 'GROUPS_UPSERT', - 'GROUP_UPDATE', - 'GROUP_PARTICIPANTS_UPDATE', - 'CONNECTION_UPDATE', - 'LABELS_EDIT', - 'LABELS_ASSOCIATION', - 'CALL', - 'TYPEBOT_START', - 'TYPEBOT_CHANGE_STATUS', - ], - }, - }, - }, - required: ['enabled', 'url'], - ...isNotEmpty('enabled', 'url'), -}; diff --git a/src/validate/websocket.schema.ts b/src/validate/websocket.schema.ts deleted file mode 100644 index 8a7678c1..00000000 --- a/src/validate/websocket.schema.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { JSONSchema7 } from 'json-schema'; -import { v4 } from 'uuid'; - -const isNotEmpty = (...propertyNames: string[]): JSONSchema7 => { - const properties = {}; - propertyNames.forEach( - (property) => - (properties[property] = { - minLength: 1, - description: `The "${property}" cannot be empty`, - }), - ); - return { - if: { - propertyNames: { - enum: [...propertyNames], - }, - }, - then: { properties }, - }; -}; - -export const websocketSchema: JSONSchema7 = { - $id: v4(), - type: 'object', - properties: { - enabled: { type: 'boolean', enum: [true, false] }, - events: { - type: 'array', - minItems: 0, - items: { - type: 'string', - enum: [ - 'APPLICATION_STARTUP', - 'QRCODE_UPDATED', - 'MESSAGES_SET', - 'MESSAGES_UPSERT', - 'MESSAGES_EDITED', - 'MESSAGES_UPDATE', - 'MESSAGES_DELETE', - 'SEND_MESSAGE', - 'CONTACTS_SET', - 'CONTACTS_UPSERT', - 'CONTACTS_UPDATE', - 'PRESENCE_UPDATE', - 'CHATS_SET', - 'CHATS_UPSERT', - 'CHATS_UPDATE', - 'CHATS_DELETE', - 'GROUPS_UPSERT', - 'GROUP_UPDATE', - 'GROUP_PARTICIPANTS_UPDATE', - 'CONNECTION_UPDATE', - 'LABELS_EDIT', - 'LABELS_ASSOCIATION', - 'CALL', - 'TYPEBOT_START', - 'TYPEBOT_CHANGE_STATUS', - ], - }, - }, - }, - required: ['enabled'], - ...isNotEmpty('enabled'), -}; diff --git a/tsconfig.json b/tsconfig.json index 156bb77c..be16fc49 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -3,7 +3,7 @@ "experimentalDecorators": true, "emitDecoratorMetadata": true, "declaration": true, - "target": "ES6", + "target": "es2020", "module": "commonjs", "rootDir": "./", "resolveJsonModule": true, @@ -16,7 +16,17 @@ "skipLibCheck": true, "strictNullChecks": false, "incremental": true, - "noImplicitAny": false + "noImplicitAny": false, + "baseUrl": ".", + "paths": { + "@api/*": ["./src/api/*"], + "@cache/*": ["./src/cache/*"], + "@config/*": ["./src/config/*"], + "@exceptions": ["./src/exceptions"], + "@libs/*": ["./src/libs/*"], + "@utils/*": ["./src/utils/*"], + "@validate/*": ["./src/validate/*"] + } }, "exclude": ["node_modules", "./test", "./dist", "./prisma"], "include": [ diff --git a/tsup.config.ts b/tsup.config.ts new file mode 100644 index 00000000..2450b52f --- /dev/null +++ b/tsup.config.ts @@ -0,0 +1,19 @@ +import { cpSync } from 'node:fs'; + +import { defineConfig } from 'tsup'; + +export default defineConfig({ + entry: ['src'], + outDir: 'dist', + splitting: false, + sourcemap: true, + clean: true, + minify: true, + format: ['cjs', 'esm'], + onSuccess: async () => { + cpSync('src/utils/translations', 'dist/translations', { recursive: true }); + }, + loader: { + '.json': 'file', + }, +});