diff --git a/.env.example b/.env.example index 435e624d..23a2f50e 100644 --- a/.env.example +++ b/.env.example @@ -3,15 +3,13 @@ # cp .env.example .env # === Layout === -# Root of the runtime tree that bot/gateway modules are resolved from. -# Use an ABSOLUTE path: commerce/key-daemon code resolves modules from it. -IISHKO_APP_ROOT=/absolute/path/to/this/repo/bot +# Bot module directory; scripts/run.py resolves relative paths from the repo root. +IISHKO_APP_ROOT=./bot # Optional override of the bot source file. Default: $IISHKO_APP_ROOT/grok_bot.py IISHKO_BOT_SOURCE= -# Module search path for a local run (production flattens both dirs together): -# POSIX: export PYTHONPATH=bot:gateway -# Windows: set PYTHONPATH=bot;gateway -PYTHONPATH=bot:gateway +# scripts/run.py sets the cross-platform module path; no manual PYTHONPATH needed. +# Direct starts from the repo root: POSIX PYTHONPATH="$PWD/bot:$PWD/gateway:$PWD/bot/webapp" +# PowerShell: $env:PYTHONPATH="$PWD/bot;$PWD/gateway;$PWD/bot/webapp" # === Bot identity === GROK_BOT_TOKEN=REPLACE_ME_TELEGRAM_BOT_TOKEN @@ -22,9 +20,12 @@ GROK_BOT_ALLOW_LOCAL=1 # 1 only for a local single-instanc IISHKO_BOT_DB=./bot.db # bot SQLite: users, keys, economy GROK_BOT_DB=./bot.db # legacy alias of IISHKO_BOT_DB GATE_BOT_DB=./bot.db # gateway-side alias of the same file -IISHKO_GW_DB=./one-api.db # external New API SQLite (read-only use) +IISHKO_GW_DB=./one-api.db # external New API SQLite; economy/key operations WRITE here IISHKO_SKIN_DB=./skin.db # skin/site accounts +# GATE_TG_DB is the legacy alias; IISHKO_SKIN_DB takes precedence. +TG_SID_SECRET_FILE=./.local/tg-sid-secret # private login/session secret, never commit GATE_NEWAPI_DB=./one-api.db # legacy alias of IISHKO_GW_DB +IISHKO_ECON_STATE=./econ_cap_state.json # shared economy pause/cap state # === Upstream (external New API / one-api, AGPL-3.0, not bundled) === IISHKO_UPSTREAM=http://127.0.0.1:48000 # canonical upstream base URL @@ -68,10 +69,13 @@ IISHKO_SRV_EXCLUDED_IPS= # reading an existing wallet and grants keeps working. # === Other optional features, off by default === -IISHKO_ENTRY_AUTOBAN=0 # IP-collision autoban touches balances/keys +IISHKO_ENTRY_AUTOBAN=0 # legacy API compatibility; no automatic IP enforcement IISHKO_BC_PREMIUM_AUTOFILL=0 # cosmetic broadcast emoji autofill IISHKO_SANDBOX_ENABLED=0 # external command/file execution surface IISHKO_NOTIFICATIONS_ENABLED=0 # outbound Telegram notifications +# Optional delivery kill switches; only meaningful after NOTIFICATIONS_ENABLED=1: +# IISHKO_SUPPORT_DELIVERY_ENABLED=0 # suppress support and entry alerts +# IISHKO_ENTRY_DELIVERY_ENABLED=0 # suppress entry alerts only IISHKO_MEMORY_OFF=1 # 1 = no persistent chat context in RAM # === Media / payments providers (disabled while empty) === diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2fa696e9..d2b07729 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,7 +23,6 @@ jobs: # Purchases are config-gated (empty commerce_offers + empty payment token), # not flag-gated: there is no IISHKO_WALLET_ENABLED / PAID_OFFERS switch. IISHKO_ADMIN_IDS: "" - IISHKO_NOTIFICATIONS_ENABLED: "0" IISHKO_SANDBOX_ENABLED: "0" moderation: diff --git a/.gitignore b/.gitignore index 982148ae..2d0dc36d 100644 --- a/.gitignore +++ b/.gitignore @@ -6,15 +6,18 @@ *.sqlite3 .env .env.* +runtime.env !.env.example config.json bot/config.json +providers.json *.key *.pem *.p12 *.pfx secrets/ sessions/ +.local/ logs/ *.log # geo dataset is downloaded by the operator (see bot/geo/provenance.json) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 60103b38..c62e9444 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -1,7 +1,7 @@ # Архитектура -Документ описывает фактическое состояние кода на момент публикации. Проект в бете, -часть решений — временные; раздел «Известные проблемы» честно перечисляет, что сломано. +Документ описывает публичное дерево исходников, а не состояние рабочего сервера. +Внешний New API, настройки провайдеров и runtime-данные сюда не входят. ## Общая схема @@ -32,16 +32,16 @@ Telegram-клиент | Daemon операций с ключами | `bot/webapp/mk_daemon.py` | — (subprocess) | — | `one-api.db` (RW), `bot.db` | | Скин шлюза | `gateway/grok-web-skin.py` | 48001 | `grok-web-skin.service` | `one-api.db` | | Классификатор ошибок | `gateway/gateway_errors.py` | — (импортируется) | — | — | -| grok2api | `gateway/g2a/` (конфиг) | 8000 | `g2a.service` | свой стейт | -| TS-переписывание | `iishko-ts/src/index.ts` | — | `iishko-ts.service` | `node:sqlite` | +| grok2api | `gateway/g2a/` (пример конфига) | внешний сервис | не поставляется | свой стейт | +| TS-версия (эксперимент) | `iishko-ts/src/index.ts` | — | не поставляется | `node:sqlite` | -Мониторинг, TTS и firewall — вне репозитория. +В `deploy/` остаются только шаблоны сервисов с исходниками в этом репозитории. ## Переменные окружения | Компонент | Переменные | Дефолт | |---|---|---| -| grok-web-skin | `GATE_BOT_CONFIG`, `GATE_BOT_DB`, `GATE_NEWAPI_DB`, `GATE_TG_DB`, `IP_LOCK_ENFORCE`, `TG_SID_SECRET_FILE` | — | +| bot / Mini App / skin | `GROK_BOT_CFG` (алиасы `GROK_BOT_CONFIG`, `GATE_BOT_CONFIG`), `IISHKO_BOT_DB`, `IISHKO_GW_DB`, `IISHKO_SKIN_DB` (алиас `GATE_TG_DB`) | через `scripts/run.py`, см. `.env.example` | ## Хранилища @@ -117,39 +117,17 @@ Telegram-клиент - Источники начислений помимо выплаты: дуэли, квесты, джекпот, переводы между ключами. - Казна (`econ`) считается как `supply − сумма_балансов_пользователей`. -## Известные проблемы +## Ограничения -Список честный и приоритизирован — хорошие первые PR. - -1. **Казна не сходится.** `loyalty_awarder` начисляет `MAX(...)` — то есть создаёт - деньги, а `supply` закэширован как `user_sum_at_init + $500K`. При росте балансов - казна уходит в минус. Выбранное решение: динамический supply - (`SUPPLY = user_sum + $500K` на каждое чтение) — не задеплоено. -2. **429 апстрима показывается как вина пользователя.** Текст «Слишком много - запросов» приходит, когда троттлит канал провайдера. Правильно — нейтральный - 503/`upstream_throttled` с ретраем на другой канал. -3. **Обрезка ответов.** Дефолт `max_tokens=2000` резал длинные ответы - («модели отвечают обрывочно»). На проде поднят до 8000; в коде дефолт стоит проверить. -4. **Ранговый гейтинг противоречит справке.** Доступ к моделям tier-gated, а текст - `/help` всё ещё утверждает, что ранг влияет только на лимиты и недельный кредит. -5. **Mini App требует слэш в конце.** Ссылка должна вести на `/webapp/`; - вариант без слэша у части клиентов отдаёт пустой 200 вместо 301 и показывает - «не удалось загрузить мини-апп». -6. **Render-blocking шрифты.** Подключение Google Fonts в `` у пользователей - из РФ может блокировать отрисовку Mini App при живом сервере. -7. **Симлинк `grok_bot.py`.** Сервис запускает `iishko_bot.py`, а модули импортируют - `grok_bot`. При деплое копирование файла поверх симлинка оставляет сервис на старой версии. -8. **`status=4` при положительном балансе.** Авто-исчерпанные ключи с - `remain_quota>0` — видимый пользователю рассинхрон; требует явной политики. -9. **Баланс Mini App vs бот.** Исторически часть функций резолвила ключ как - `tg`, игнорируя `users.token_name`, из-за чего профиль показывал 0, - а вкладка «Эконом» — реальную сумму. Канонический резолв: `users.token_name` → fallback `tg`. -10. **Медиа-модели и `completion_tokens=0`.** Для генерации изображений/видео ноль - выходных токенов — норма; нельзя трактовать это как ошибку и делать возврат. - -## Что планируется - -- Переписать шлюз маршрутизации с нуля вместо форка `new-api` - (текущая кодовая база не поддаётся ни чтению, ни очистке). -- Перевести бота на TypeScript: `iishko-ts/` (grammy, `node:sqlite`, модули - `chat`, `economy`, `keys`, `start`) — модульная и типизированная замена монолиту. +- `bot/grok_bot.py` — монолитная реализация; `bot/iishko_bot.py` — обычный + совместимый лаунчер, не симлинк. Разделение модулей не завершено. +- Python и TS — не взаимозаменяемые реализации. `iishko-ts/` экспериментален, + общего обещания функционального паритета нет. +- Баланс, ранги и операции с ключами зависят от схемы внешнего New API. Несколько + SQLite-файлов не образуют общую транзакцию автоматически: сверяйте квоты с + журналом операций и делайте резервные копии перед миграциями. +- Каталог/справочные характеристики моделей не подтверждают live-маршрутизацию. + Доступность, лимиты и ответы провайдеров проверяются отдельно. +- Совпадение IP сохраняется для ручной проверки, но не является основанием + автоматического бана или обнуления квот. Уведомления по умолчанию выключены. +- Изменение кода здесь не означает его выкладку на рабочий сервер. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4d96c059..967d118b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -3,7 +3,7 @@ Спасибо, что зашли. Проект в бете, мейнтейнер один, времени мало — поэтому правила простые и направлены на то, чтобы ваш PR можно было проверить быстро. -**Все PR ревьюит владелец проекта.** Мержится только то, что прошло ревью. +Мержится только то, что прошло ревью мейнтейнера проекта. ## С чего начать @@ -13,9 +13,10 @@ Также полезно: -- тесты (их почти нет — это главная техническая дыра проекта); +- тесты в `tests/` (`unittest`/`pytest`) — покрытие неровное, регрессии по + экономике, доступу к моделям и стабильности запросов всегда нужны; - TypeScript-переписывание в `iishko-ts/` — бот переезжает туда; -- разбор и чистка монолита `bot/iishko_bot.py` (~800 КБ) на модули. +- разбор и чистка монолита `bot/grok_bot.py` (~14.8 тыс. строк, 847 КБ) на модули. ## Правила PR @@ -25,9 +26,13 @@ 4. **Пруф.** Для баг-фиксов: тест или вывод до/после. «Работает у меня» — не пруф. 5. **Никаких секретов в диффе.** Ключи, токены, куки, IP боевых серверов, Telegram ID реальных пользователей, дампы БД — всё это отклоняется без обсуждения. -6. **Не коммитьте** `config.json`, `*.db*`, `*_state.json`, +6. **Не коммитьте** `config.json`, `runtime.env`, `*.db*`, `*_state.json`, медиа и логи. Смотрите `.gitignore`. -7. **Не ломайте симлинк** `bot/grok_bot.py → iishko_bot.py` (см. README). +7. **Не переименовывайте и не удаляйте** лончер `bot/iishko_bot.py` и модуль + `bot/grok_bot.py`, и **не копируйте один поверх другого.** Это два разных файла: + `bot/iishko_bot.py` — 13-строчный вход, который через `runpy.run_module` выполняет + `bot/grok_bot.py` с реальной реализацией. Оба нужны: первый — стабильная точка + входа, второй — код. 8. **Новые зависимости — только по нужде.** Сначала стандартная библиотека, потом уже пакеты. Каждая зависимость обосновывается в описании PR. 9. **Форматтер не навязываем.** Стиль существующего кода строгий не везде — @@ -37,7 +42,7 @@ ## Чего скорее всего не примут - «Переписал всё и стало красиво» без описания поведения и пруфов. -- Изменения экономики (начисления, квоты, казна, ранги) без обсуждения с владельцем: +- Изменения экономики (начисления, квоты, казна, ранги) без обсуждения с мейнтейнером: там каждая правка двигает живые деньги пользователей. - Отключение проверок, капчи, лимитов и гейтинга «чтобы удобнее тестировать». - Хардкод ключей и эндпоинтов вместо конфига. @@ -45,17 +50,26 @@ ## Локальный запуск -```bash -python -m venv .venv && source .venv/bin/activate -pip install -r requirements.txt +Нужен Python 3.11+ и внешний шлюз (`new-api`/`one-api`) — его в репозитории нет, +см. [deploy/README.md](deploy/README.md). -cp bot/config.example.json bot/config.json # заполнить REPLACE_ME -python bot/iishko_bot.py # бот -python bot/webapp/server.py # Mini App на :8850 +```bash +python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate +pip install -r requirements.txt -r requirements-dev.txt + +python scripts/run.py bot # Telegram-бот +python scripts/run.py miniapp # Mini App на 127.0.0.1:8850 +python scripts/run.py gateway # скин/прокси шлюза на 127.0.0.1:48001 ``` -Для Mini App нужен шлюз (upstream `new-api`/`one-api`) и доступ к его SQLite — -см. README, раздел «Шлюз». +`scripts/run.py` читает `.env` из корня репозитория (реальные переменные окружения +имеют приоритет), нормализует исторические alias‑имена конфига и выставляет +`sys.path`. Явный файл конфигурации: `--env-file PATH`. Офлайн‑проверка без сети и +без запуска приложения: `python scripts/run.py bot --check`. + +Экспорт руками (`PYTHONPATH`, `GROK_BOT_CFG`, `IISHKO_ADMIN_IDS`) остаётся +совместимым — прямое `python bot/iishko_bot.py` тоже работает, но тогда +переменные окружения вы задаёте сами. TypeScript-часть: @@ -66,17 +80,24 @@ npm install npm run dev # tsx src/index.ts ``` +## Проверки перед PR + +```bash +python -m pytest -q # весь набор из tests/ +python scripts/selfcheck.py --source-only # офлайн, без импортов и сети +``` + +Оба прогона должны быть зелёными; падение, которое вы «не трогали», всё равно ваша +ответственность — иначе ревью не начнётся. + +Деплой и раскладка файлов на сервере — [deploy/README.md](deploy/README.md). + ## Язык Issues и PR можно писать по-русски или по-английски. Комментарии в коде — по-английски. ## Вопросы -Общие вопросы и идеи — в чат проекта. Личные — владельцу репозитория (`reform`) на git.reformboss.com. -Уязвимости — только приватно, см. [SECURITY.md](SECURITY.md). - -## Windows checkout note - -`bot/grok_bot.py` — единственная реализация, обычный файл; `bot/iishko_bot.py` — тонкий -лаунчер для совместимости (см. README). Никаких symlink и копирований не нужно — -**не копируйте** `iishko_bot.py` поверх `grok_bot.py`: это затрёт реализацию. +Общие вопросы и идеи — в чат проекта. Личные — мейнтейнеру проекта в Telegram +(контакт указан в профиле владельца репозитория). +Уязвимости — только приватно, см. [SECURITY.md](SECURITY.md). \ No newline at end of file diff --git a/README.md b/README.md index 9a6d1402..f03a9e09 100644 --- a/README.md +++ b/README.md @@ -11,9 +11,8 @@ | Путь | Статус | Комментарий | |---|---|---| -| `bot/`, `bot/webapp/`, `gateway/`, `site/`, `deploy/` | **legacy runtime, production-compatible** | Код, который реально работал на боевом сервере. Интерфейсы и схема БД совместимы с боевыми, но публичным сервисом этот репозиторий не запускается. | +| `bot/`, `bot/webapp/`, `gateway/`, `deploy/` | **legacy runtime** | Публичный снимок Python-компонентов. Это исходники, а не готовый публичный сервис и не подтверждение текущего состояния production. | | `iishko-ts/` | **experimental** | Ранний TypeScript-перепись бота (grammy). Не feature-parity с Python-версией; параллельно с основным ботом не запускать. | -| `site/assets/*` | снимок | Собранный бандл лендинга как есть, без шага сборки. | Честно о проверках: в этом репозитории **нет Docker-прогона и нет заявлений о «smoke-tested production»**. Локальный сценарий ниже — про то, что приложение стартует и отдаёт loopback-порты; @@ -55,18 +54,29 @@ python scripts/selfcheck.py --source-only # синтаксис/замыкани Запуск компонентов (все слушают loopback, наружу — только через ваш reverse proxy): ```bash -# Код сам .env не читает — загрузите его в окружение (в systemd: EnvironmentFile=) -set -a; . ./.env; set +a # POSIX -# PowerShell: Get-Content .env | ? { $_ -match '^[A-Z_]+=' } | % { $k,$v = $_ -split '=',2; Set-Item "env:$k" $v } -export PYTHONPATH=bot:gateway # PowerShell: $env:PYTHONPATH = "bot;gateway" - -python bot/grok_bot.py # Telegram-бот (long polling) -python bot/webapp/server.py # Mini App backend, 127.0.0.1:8850 -python gateway/grok-web-skin.py # скин шлюза, 127.0.0.1:48001 +# Каждая команда сама читает .env; shell-команды source/set не нужны. +python scripts/run.py bot --check # только офлайн preflight конфига, не запуск +python scripts/run.py bot # Telegram-бот (long polling) +python scripts/run.py miniapp # Mini App backend, 127.0.0.1:8850 +python scripts/run.py gateway # скин шлюза, 127.0.0.1:48001 ``` -`bot/iishko_bot.py` — совместимый лаунчер (systemd-юниты и часть модулей исторически -делают `import grok_bot`). Реальная реализация одна — `bot/grok_bot.py`. +`scripts/run.py` явно читает только `.env` в корне (или `--env-file ПУТЬ`), не +исполняет его как shell и не ищет файлы выше проекта. Реальное окружение процесса +имеет приоритет, в том числе legacy-алиасы; относительные пути считаются от корня. +Лаунчер задаёт module path для Windows/POSIX и согласует `GROK_BOT_CFG` с прежними +`GROK_BOT_CONFIG` / `GATE_BOT_CONFIG`. Прямой запуск скриптов сохранён для старых +unit-файлов, но сам `.env` не загружает; окружение и абсолютные пути к данным в этом +режиме задаёт оператор. Не запускайте два polling-процесса с одним токеном; +для локального запуска используйте отдельного бота. + +Для работы нужны заполненный `bot/config.json` и существующий SQLite вашего New API +(`IISHKO_GW_DB`): конфиг-пример и пустой файл не заменяют upstream. `--check` проверяет +наличие конфигурации, но не подключается к Telegram, не проверяет схему New API и +не доказывает доступность моделей. + +`bot/iishko_bot.py` — совместимый лаунчер для прежних запусков и импортов. +`scripts/run.py bot` запускает реализацию `bot/grok_bot.py` напрямую. `bot.db` создаётся при первом запуске; собственный `one-api.db` предоставляет New API. В репозитории нет ни баз, ни пользовательских данных. @@ -138,11 +148,10 @@ python gateway/grok-web-skin.py # скин шлюза, 127.0.0.1:48001 ## Конфигурация -* `.env.example` — переменные окружения: layout (`IISHKO_APP_ROOT` — абсолютный путь, - опционально `IISHKO_BOT_SOURCE`), идентичность бота, - пути к БД (`IISHKO_BOT_DB`, алиасы `GROK_BOT_DB` / `GATE_BOT_DB` / `GATE_NEWAPI_DB`; - БД Telegram-входа шлюза — `IISHKO_SKIN_DB`, алиас `GATE_TG_DB`; бот, автобан и скин - пишут в неё, поэтому путь должен совпадать у всех сервисов), +* `.env.example` — переменные окружения: layout (`IISHKO_APP_ROOT` — каталог модулей + бота, через лаунчер допустим относительный путь; опционально `IISHKO_BOT_SOURCE`), + пути к БД (`IISHKO_BOT_DB`, алиасы `GROK_BOT_DB` / `GATE_BOT_DB`; шлюз — + `IISHKO_GW_DB` / `GATE_NEWAPI_DB`; общая skin-БД — `IISHKO_SKIN_DB` / `GATE_TG_DB`), апстрим (`IISHKO_UPSTREAM`, алиас `NEWAPI_URL`), шлюз (`IISHKO_GATEWAY_HOST` / `IISHKO_GATEWAY_PORT`, `IISHKO_PROVIDERS_FILE`), админы, commerce-флаги. Все дефолты — loopback. @@ -151,14 +160,21 @@ python gateway/grok-web-skin.py # скин шлюза, 127.0.0.1:48001 * `gateway/providers.example.json` — форма реестра провайдеров для pinning (только плейсхолдеры; нужен New API admin/owner). См. `docs/native-gateway.md`. * `bot/config.example.json` — конфиг бота (`GROK_BOT_CFG`). Секреты — заглушки `REPLACE_ME_*`. + Без env-переопределений значения upstream и DB из JSON сохраняются. Лаунчер не + меняет `TG_SID_SECRET_FILE`, если он не задан: существующий путь секрета сохраняется. + `IISHKO_ECON_STATE` задаёт общий файл пауз/лимитов экономики. * Шлюз и провайдеры настраиваются в вашем инстансе New API, не здесь. +Утилита `bot/abilities_guard.py` без `--apply` только читает маршруты. Запись требует +явных `--apply --db /absolute/one-api.db --source /absolute/grok_bot.py`; утилита +включает только подходящие `abilities`, не меняет токены, квоты или историю банов. + ### Выключено по умолчанию | Возможность | Переменная | По умолчанию | |---|---|---| -| Автобан по совпадению IP в Mini App (без него общий IP — только алерт владельцу; включение: `1`) | `IISHKO_ENTRY_AUTOBAN` | `0` (выкл.) | -| Уведомления владельцам в Telegram (саппорт/алерты); выключение: `0` | `IISHKO_NOTIFICATIONS_ENABLED` | `1` (вкл., только `IISHKO_ADMIN_IDS`) | +| Legacy-совместимость API автобана | `IISHKO_ENTRY_AUTOBAN` | `0`; автоматического IP-применения нет, общий IP не банит и при `1` | +| Уведомления в Telegram (саппорт/алерты) | `IISHKO_NOTIFICATIONS_ENABLED` | `0` (выкл.) | | Внешняя песочница исполнения команд/файлов | `IISHKO_SANDBOX_ENABLED` | `0` (выкл.) | | Персистентный контекст чата | `IISHKO_MEMORY_OFF` | `1` (без памяти) | | Геолокация по IP (DB-IP) | файл `bot/geo/*.mmdb` | нет файла → функция выключена | @@ -167,6 +183,17 @@ python gateway/grok-web-skin.py # скин шлюза, 127.0.0.1:48001 | Чтение кошелька и grants | — (переключателя нет) | работает и при пустых офферах | | Премиум-эмодзи в рассылках | `IISHKO_BC_PREMIUM_AUTOFILL` | `0` (выкл.) | +Сетевые совпадения Mini App сохраняются только как сигнал для проверки администратором: +NAT/Wi-Fi/VPN не доказывают мультиаккаунт. Уведомления саппорта/сетевых алертов требуют +`IISHKO_NOTIFICATIONS_ENABLED=1`; дополнительные `IISHKO_SUPPORT_DELIVERY_ENABLED=0` +и `IISHKO_ENTRY_DELIVERY_ENABLED=0` — kill switches. Явная админская модерация не +включает автоматический IP-бан. + +`IISHKO_SKIN_DB` — общий путь сайта и очистки IP-привязок, с legacy-алиасом `GATE_TG_DB`. +БД New API **не read-only** для приложения: выдача ключей, экономика и модерация +обновляют квоты/статусы. Для локальных проверок используйте отдельные тестовые БД, +не production-пути. + Платежи и «денежные» операции не включаются без вашего явного конфига; ни один сценарий быстрого старта не выполняет боевых мутаций баланса. @@ -185,7 +212,6 @@ bot/ # канонический бот: grok_bot.py + модул vendor_entry_geo/ # MaxMind DB Reader (Apache-2.0), provenance.json geo/ # только лицензия и provenance датасета DB-IP (сам .mmdb не включён) gateway/ # скин шлюза, классификатор ошибок, transparent_api, model_identity, public_site -site/ # лендинг/доки/прайс (собранный бандл) deploy/ # примеры systemd/caddy под ваши пути и домены iishko-ts/ # experimental TypeScript-перепись scripts/selfcheck.py# офлайн self-check: синтаксис, замыкание импортов, конфиг diff --git a/SECURITY.md b/SECURITY.md index 11b619b6..d9cca63a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,9 +2,12 @@ ## Как сообщить об уязвимости -**Не создавайте публичный issue и не пишите в общий чат.** +**Не создавайте публичный issue с деталями и не пишите в общий чат.** -Пишите лично владельцу репозитория `reform` на git.reformboss.com (не в публичные issues) +Приватный канал согласуется так: контакт для связи указан в профиле владельца +репозитория (GitHub/Gitea). Напишите туда лично и приложите отчёт. Если контакта в +профиле нет — откройте issue **без деталей** (только «есть уязвимость, нужен приватный +канал») и дождитесь ответа; подробности в публичный issue не переносите. В сообщении укажите: @@ -13,8 +16,8 @@ 3. Что злоумышленник получает в результате. 4. Затронуты ли реальные пользовательские данные. -Подтверждение получения — в течение ~72 часов. Сроки фикса честные: проект в бете, -мейнтейнер один, критичное чинится вне очереди, остальное — в порядке очереди. +Фиксированных сроков ответа нет: проект в бете, мейнтейнер один. Критичное чинится +вне очереди, остальное — как получится. После выпуска фикса раскрытие деталей согласуется с вами; авторство в релизе — по желанию. diff --git a/bot/abilities_guard.py b/bot/abilities_guard.py index d9774b3b..1e0e76ae 100644 --- a/bot/abilities_guard.py +++ b/bot/abilities_guard.py @@ -1,13 +1,18 @@ #!/usr/bin/env python3 +import argparse +from contextlib import closing +from pathlib import Path import os import re import sqlite3 import sys import time -GW_DB = os.environ.get("IISHKO_GW_DB", "/opt/grok-gateway/new-api/one-api.db") -BOT_SRC = "/opt/grok-bot/iishko_bot.py" # [BOTFIX 2310] живой активный сервис -BOT_SRC_FALLBACK = "/opt/grok-bot/grok_bot.py" # старое имя (legacy) +from runtime_config import gateway_db_path + +GW_DB = gateway_db_path() +BOT_SRC = os.environ.get("IISHKO_BOT_SOURCE") or str(Path(__file__).with_name("grok_bot.py")) +BOT_SRC_FALLBACK = BOT_SRC TIER_GROUPS = ("t1", "t2", "t3", "t4") LIVE_SQL = ("SELECT COUNT(*) FROM abilities a JOIN channels c ON c.id=a.channel_id " @@ -38,8 +43,7 @@ def _parse_tiers(src): def catalog_tiers(path=None): - """Список тиров из исходника бота (без импорта бота). - path=None: сначала живой iishko_bot.py (BOT_SRC), затем legacy grok_bot.py.""" + """Read tier declarations without importing or starting the bot.""" paths = (path,) if path else (BOT_SRC, BOT_SRC_FALLBACK) for p in paths: tiers = _parse_tiers(_read_src(p)) @@ -84,29 +88,39 @@ def repair_abilities(con, tiers): return con.execute(sql, params).rowcount -def main(): - tiers = catalog_tiers() +def main(argv=None): + parser = argparse.ArgumentParser( + description="Check route availability; read-only unless --apply is explicit.") + parser.add_argument("--db", help="absolute path to an existing New API SQLite database") + parser.add_argument("--source", help="absolute path to bot source containing TIER_MODELS") + parser.add_argument("--apply", action="store_true", help="explicitly re-enable matching abilities") + args = parser.parse_args(argv) + if args.apply and (not args.db or not args.source): + parser.error("--apply requires explicit --db and --source") + db, source = Path(args.db or GW_DB), Path(args.source or BOT_SRC) + for label, path in (("database", db), ("source", source)): + if not path.is_absolute() or not path.is_file(): + parser.error(label + " must be an absolute path to an existing file") + tiers = catalog_tiers(str(source)) if not tiers: - print(time.strftime("%F %T"), "no catalog tiers parsed - refusing to touch abilities", - flush=True) + print("No catalog tiers parsed; no database changes made.", flush=True) return 1 models = catalog_models(tiers) - con = sqlite3.connect(GW_DB, timeout=60) + mode = "rw" if args.apply else "ro" try: - con.execute("PRAGMA busy_timeout=60000") - fixed = repair_abilities(con, tiers) - con.commit() - dark = [m for m in models if not con.execute(LIVE_SQL, (m,)).fetchone()[0]] - con.close() - except Exception as e: - print(time.strftime("%F %T"), "ERROR", str(e)[:200], flush=True) - try: - con.rollback() - except Exception: - pass + with closing(sqlite3.connect(db.resolve().as_uri() + "?mode=" + mode, + uri=True, timeout=10)) as con: + fixed = 0 + with con: + if args.apply: + fixed = repair_abilities(con, tiers) + dark = [m for m in models if not con.execute(LIVE_SQL, (m,)).fetchone()[0]] + except sqlite3.Error as exc: + print("Database check failed: " + type(exc).__name__, file=sys.stderr) return 2 - print(time.strftime("%F %T"), "catalog=%d re-enabled=%d dark=%s" - % (len(models), fixed, ",".join(dark) if dark else "none"), flush=True) + print("mode=%s catalog=%d re-enabled=%d dark=%s" + % ("apply" if args.apply else "dry-run", len(models), fixed, + ",".join(dark) if dark else "none"), flush=True) return 0 diff --git a/bot/account_admin.py b/bot/account_admin.py index ac3025f3..ae709bd1 100644 --- a/bot/account_admin.py +++ b/bot/account_admin.py @@ -6,9 +6,10 @@ import sqlite3 import time from account_limits import account_uid, _name_scope +from runtime_config import econ_state_path -PAUSE_PATH = "/opt/grok-bot/econ_cap_state.json" +PAUSE_PATH = econ_state_path() # Account-level locks that are not owned by a ban; unban must never clear them. INDEPENDENT_FLAGS = ("api_blocked", "key_locked", "chat_key_locked") diff --git a/bot/config.example.json b/bot/config.example.json index 2490bd60..bbccbbd8 100644 --- a/bot/config.example.json +++ b/bot/config.example.json @@ -7,8 +7,8 @@ "newapi_url": "http://127.0.0.1:48000", "newapi_user": "REPLACE_ME_NEWAPI_ADMIN_LOGIN", "newapi_pass": "REPLACE_ME_NEWAPI_ADMIN_PASSWORD", - "newapi_db": "/opt/grok-gateway/new-api/data/one-api.db", - "bot_db": "/opt/grok-bot/bot.db", + "newapi_db": "./one-api.db", + "bot_db": "./bot.db", "public_base": "http://127.0.0.1:8850", "user_quota": 500000000, "unlimited": false, diff --git a/bot/econ_cap.py b/bot/econ_cap.py index deca3aff..c158b514 100644 --- a/bot/econ_cap.py +++ b/bot/econ_cap.py @@ -8,10 +8,11 @@ from pathlib import Path from contextlib import closing from account_limits import account_uid +from runtime_config import bot_db_path, econ_state_path, gateway_db_path -BOT_DB = '/opt/grok-bot/bot.db' -NA_DB = '/opt/grok-gateway/new-api/one-api.db' -STATE = '/opt/grok-bot/econ_cap_state.json' +BOT_DB = bot_db_path() +NA_DB = gateway_db_path() +STATE = econ_state_path() # Keep this literal compatible with the Mini App's read-only policy parser. DAILY_USD_CAP = {0: 100, 1: 100, 2: 200, 3: 500, 4: 1000} QUOTA_PER_USD = 500000 diff --git a/bot/entry_admin.py b/bot/entry_admin.py index 369fec5b..0cf8633a 100644 --- a/bot/entry_admin.py +++ b/bot/entry_admin.py @@ -1,10 +1,11 @@ from contextlib import closing -import os import sqlite3 import time import unicodedata -BOT_DB = os.environ.get("IISHKO_BOT_DB", os.environ.get("GROK_BOT_DB", "/opt/grok-bot/bot.db")) +from runtime_config import bot_db_path + +BOT_DB = bot_db_path() WINDOW = 86400 TAG_MAX = 48 TAG_LIMIT = 12 diff --git a/bot/entry_autoban.py b/bot/entry_autoban.py index ffcab4ea..4b81f0f1 100644 --- a/bot/entry_autoban.py +++ b/bot/entry_autoban.py @@ -1,25 +1,23 @@ -"""Opt-in: automatic IP-collision bans run only with IISHKO_ENTRY_AUTOBAN=1. -A shared IP (NAT, mobile CGNAT, family Wi-Fi) is otherwise only an operator alert. -Manual operator bans (ban_cluster) are not gated by this flag.""" import json import logging import os from pathlib import Path import re import sqlite3 +from runtime_config import bot_db_path, env_enabled, gateway_db_path, skin_db_path log = logging.getLogger("entry_autoban") -BOT_DB = os.environ.get("IISHKO_BOT_DB", "/opt/grok-bot/bot.db") -GW_DB = os.environ.get("IISHKO_GW_DB", "/opt/grok-gateway/new-api/one-api.db") -SKIN_DB = os.environ.get("IISHKO_SKIN_DB") or os.environ.get("GATE_TG_DB", "/opt/grok-web-skin-tg.db") +BOT_DB = bot_db_path() +GW_DB = gateway_db_path() +SKIN_DB = skin_db_path() PROTECT = tuple(int(v) for v in os.environ.get("IISHKO_PROTECTED_UIDS", "").replace(";", ",").split(",") if v.strip().isdigit()) def enabled(): - return os.environ.get("IISHKO_ENTRY_AUTOBAN", "0").strip().lower() in ("1", "on", "yes", "true") + return env_enabled("IISHKO_ENTRY_AUTOBAN") def _connect(path): @@ -97,6 +95,11 @@ def _processed(g, con, uid, was_banned): def ban_user(uid, reason="entry_ip_collision", taken=None): + """Legacy enforcement; an omitted reason or a shared IP never authorizes sanctions.""" + # An IP match is evidence for review, not account ownership or fraud. + if reason == "entry_ip_collision": + log.info("[ENTRY-AUTOBAN] shared-IP ban skipped uid=%s", uid) + return False uid = int(uid) if uid in PROTECT: return False @@ -200,7 +203,13 @@ def ban_user(uid, reason="entry_ip_collision", taken=None): def ban_cluster(uids, reason="entry_ip_collision"): + if reason == "entry_ip_collision": + log.info("[ENTRY-AUTOBAN] shared network recorded without sanctions") + return [] uids = [int(u) for u in uids] + if reason != "admin_button" and not enabled(): + log.warning("[ENTRY-AUTOBAN] disabled") + return [] out = [] for uid in dict.fromkeys(uids): try: diff --git a/bot/entry_telemetry.py b/bot/entry_telemetry.py index 23c47dcf..2cb73d67 100644 --- a/bot/entry_telemetry.py +++ b/bot/entry_telemetry.py @@ -7,7 +7,6 @@ import hmac import ipaddress import json import math -import os from pathlib import Path import re import secrets @@ -20,6 +19,7 @@ import logging log = logging.getLogger("entry_telemetry") from support_store import NotificationError +from runtime_config import notifications_enabled WINDOW = 86400 # Known shared reverse-proxy/WARP networks; operators may add their own NAT/relay ranges. @@ -75,9 +75,7 @@ def public_ip(value): def delivery_enabled(): - # The existing support switch is also a hard entry-delivery kill switch for old fixtures. - return all(os.environ.get(name, "1") != "0" for name in ( - "IISHKO_NOTIFICATIONS_ENABLED", "IISHKO_SUPPORT_DELIVERY_ENABLED", "IISHKO_ENTRY_DELIVERY_ENABLED")) + return notifications_enabled("entry") def _label(value, length): @@ -209,7 +207,6 @@ class EntryTelemetry: if type(uid) is not int or not 0 < uid <= 2**63 - 1: raise EntryError(403, "entry_forbidden", "Не удалось подтвердить аккаунт.") now = int(self.clock()) - ban_uids = [] with closing(self.connect()) as con: self._eligible(con, uid) ip = public_ip(ip) @@ -245,15 +242,7 @@ class EntryTelemetry: "VALUES(?,?,?,?,?,?)", (tag, now, payload, geo["country"], geo["city"], geo["source"])) con.executemany("INSERT INTO wa_entry_outbox(alert_id,owner_id) VALUES(?,?)", [(alert.lastrowid, owner) for owner in self.owners]) - ban_uids = [row["uid"] for row in accounts] con.commit() - if ban_uids: - try: - import entry_autoban - if entry_autoban.enabled(): # opt-in; otherwise the alert above is the only effect - entry_autoban.ban_cluster(ban_uids, reason="entry_ip_collision") - except Exception: - log.exception("entry autoban failed") def claim(self): now = self.clock() @@ -303,7 +292,7 @@ def notification_text(claim, tags=()): observed = time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime(claim["created_at"])) text = ("Mini App: совпадение сети за 24 часа\nНаблюдение: %s\n%s\nПримерный регион: %s\nИсточник: %s\n" "Сеть #%s. Совпадение IP не доказывает общего владельца: возможны Wi-Fi, NAT, VPN или relay. " - "Автобан применён автоматически (все аккаунты сети, кроме админов).\nГеоданные: IP Geolocation by DB-IP, CC BY 4.0 — https://db-ip.com" % + "Автобан не применяется; требуется проверка администратором.\nГеоданные: IP Geolocation by DB-IP, CC BY 4.0 — https://db-ip.com" % (observed, users, place, source, claim["ip_hmac"][:12]))[:3000] # Operator tags always survive truncation: they are the fastest way to recognise a network. marks = " · ".join(str(tag) for tag in list(tags or ())[:12] if tag) diff --git a/bot/file_intake.py b/bot/file_intake.py index 73f124ee..2c414321 100644 --- a/bot/file_intake.py +++ b/bot/file_intake.py @@ -4,6 +4,7 @@ from __future__ import annotations import io import re import zipfile +import zlib from dataclasses import dataclass, field from html import unescape @@ -11,9 +12,19 @@ MAX_FILE_BYTES = 8 * 1024 * 1024 TEXT_BUDGET = 24000 _MAX_PDF_PAGES = 60 _MAX_XLSX_ROWS = 400 +_MAX_XLSX_CELLS = 2000 _MAX_ZIP_ENTRIES = 200 -_MAX_PPTX_SLIDES = 300 -_MAX_UNPACKED_BYTES = 64 * 1024 * 1024 + +# A ZIP amplifies its input: an 8 MB .pptx inflates into hundreds of MB. The old +# code read every entry in full, so a per-entry limit bounded nothing in memory. +# Here both the entry and the whole archive are bounded, and reads are chunked. +_OFFICE_ENTRY_MAX_BYTES = 8 * 1024 * 1024 +_OFFICE_TOTAL_MAX_BYTES = 24 * 1024 * 1024 +_OFFICE_SLIDE_MAX_BYTES = 4 * 1024 * 1024 +_OFFICE_MAX_SLIDES = 200 +_OFFICE_MAX_ENTRIES = 400 +_OFFICE_READ_CHUNK = 128 * 1024 +_OFFICE_MAX_WARNINGS = 6 TEXT_EXTS = { ".txt", ".md", ".markdown", ".rst", ".log", ".csv", ".tsv", ".json", ".jsonl", @@ -85,68 +96,190 @@ def _looks_binary(text: str) -> bool: return len(_CTRL_RE.findall(sample)) / len(sample) > 0.02 -def _finish(text: str, kind: str, warnings: list | None = None) -> ExtractResult: +def _finish(text: str, kind: str, warnings: list | None = None, cut: bool = False) -> ExtractResult: + """Build the result. `cut` means the content is knowingly incomplete.""" clean = text.replace("\r\n", "\n").replace("\r", "\n") clean = re.sub(r"\n{3,}", "\n\n", clean).strip() - truncated = len(clean) > TEXT_BUDGET - if truncated: + notes = list(warnings or []) + truncated = bool(cut) or len(clean) > TEXT_BUDGET + if len(clean) > TEXT_BUDGET: clean = clean[:TEXT_BUDGET] - warnings = list(warnings or []) - warnings.append(f"показаны первые {TEXT_BUDGET} символов") + notes.append(f"показаны первые {TEXT_BUDGET} символов") if not clean: - return ExtractResult(ok=False, kind=kind, reason="в файле нет извлекаемого текста") + return ExtractResult( + ok=False, kind=kind, reason="в файле нет извлекаемого текста", + truncated=truncated, warnings=notes, + ) return ExtractResult( ok=True, kind=kind, text=clean, chars=len(clean), - truncated=truncated, warnings=list(warnings or []), + truncated=truncated, warnings=notes, ) -def _read_entry(zf: zipfile.ZipFile, name: str) -> str: - info = zf.getinfo(name) - if info.file_size > 32 * 1024 * 1024: - raise RuntimeError(f"entry {name} распаковывается в {info.file_size // 1048576} МБ — слишком много") - return zf.read(name).decode("utf-8", "replace") +class _OfficeBudget: + """Read Office archive entries under one shared decompression budget. + + Only bytes actually read are charged (never the declared `file_size`), the + budget is shared by the whole archive, and reads go in `chunk` blocks. Every + entry we refuse or clip is recorded in `warnings`, and `cut` tells the caller + that the extracted text is incomplete. + """ + + def __init__( + self, + zf: zipfile.ZipFile, + entry_limit: int = _OFFICE_ENTRY_MAX_BYTES, + total_limit: int = _OFFICE_TOTAL_MAX_BYTES, + chunk: int = _OFFICE_READ_CHUNK, + max_entries: int = _OFFICE_MAX_ENTRIES, + ) -> None: + self.zf = zf + self.entry_limit = entry_limit + self.total_limit = total_limit + self.chunk = chunk + self.max_entries = max_entries + self.consumed = 0 # bytes actually decompressed + self.entries_read = 0 + self.cut = False + self.warnings: list[str] = [] + + def note(self, msg: str, cut: bool = True) -> None: + """Record a warning; `cut=True` marks the extracted text as incomplete.""" + if cut: + self.cut = True + if msg not in self.warnings and len(self.warnings) < _OFFICE_MAX_WARNINGS: + self.warnings.append(msg) + + @property + def remaining(self) -> int: + return max(0, self.total_limit - self.consumed) + + @property + def at_entry_limit(self) -> bool: + return self.entries_read >= self.max_entries + + def exhausted(self) -> bool: + return self.remaining <= 0 + + def has(self, name: str) -> bool: + try: + self.zf.getinfo(name) + except KeyError: + return False + return True + + def read_prefix(self, name: str, limit: int | None = None) -> tuple[str, bool]: + """Read the head of one entry within the budget. Returns (text, clipped). + + No lookahead byte is read: reaching the cap is reported as clipped, which + is conservative (an entry of exactly cap bytes is treated as cut). + """ + if self.at_entry_limit: + self.note(f"файлов в архиве больше {self.max_entries} — остальные не читаются") + return "", True + cap = self.entry_limit if limit is None else min(limit, self.entry_limit) + cap = min(cap, self.remaining) + if cap <= 0: + self.note("предел распаковки Office-архива исчерпан — часть документа не прочитана") + return "", True + self.entries_read += 1 + parts: list[bytes] = [] + got = 0 + with self.zf.open(name) as fh: + while got < cap: + block = fh.read(min(self.chunk, cap - got)) + if not block: + break + parts.append(block) + got += len(block) + self.consumed += got + text = b"".join(parts).decode("utf-8", "replace") + clipped = got >= cap + if clipped: + # Cut in the middle of the XML: drop the trailing partial tag. + text = re.sub(r"<[^>]*$", "", text) + self.note("часть документа не прочитана: превышен предел распаковки") + return text, clipped -def _from_docx(zf: zipfile.ZipFile) -> str: - xml = _read_entry(zf, "word/document.xml") +def _from_docx(reader: _OfficeBudget) -> str: + xml, _ = reader.read_prefix("word/document.xml") xml = xml.replace("", "\n").replace("", "\t").replace("", "\n") return unescape(_TAG_RE.sub("", xml)) -def _from_pptx(zf: zipfile.ZipFile) -> str: +def _from_pptx(reader: _OfficeBudget) -> str: slides = sorted( - (n for n in zf.namelist() if re.fullmatch(r"ppt/slides/slide\d+\.xml", n)), - key=lambda n: _num(n), + (n for n in reader.zf.namelist() if re.fullmatch(r"ppt/slides/slide\d+\.xml", n)), + key=_num, ) - out, chars, unpacked = [], 0, 0 - for n in slides[:_MAX_PPTX_SLIDES]: - unpacked += zf.getinfo(n).file_size - if unpacked > _MAX_UNPACKED_BYTES: - raise RuntimeError(f"слайды распаковываются больше чем в {_MAX_UNPACKED_BYTES // 1048576} МБ") - if chars > TEXT_BUDGET: - break # _finish() truncates anyway; don't decompress the rest - xml = _read_entry(zf, n) - xml = xml.replace("", "\n") - out.append(f"--- {n.rsplit('/', 1)[-1]} ---\n" + unescape(_TAG_RE.sub("", xml))) - chars += len(out[-1]) + total = len(slides) + if total > _OFFICE_MAX_SLIDES: + slides = slides[:_OFFICE_MAX_SLIDES] + reader.note(f"в файле {total} слайдов — прочитаны первые {_OFFICE_MAX_SLIDES}") + out: list[str] = [] + produced = 0 + for n in slides: + if reader.at_entry_limit: + reader.note(f"показаны не все слайды: {len(out)} из {total}") + break + if produced >= TEXT_BUDGET or reader.exhausted(): + reader.note(f"показаны не все слайды: {len(out)} из {total}") + break + xml, _ = reader.read_prefix(n, limit=_OFFICE_SLIDE_MAX_BYTES) + text = unescape(_TAG_RE.sub("", xml.replace("", "\n"))) + if text.strip(): + out.append(f"--- {n.rsplit('/', 1)[-1]} ---\n" + text) + produced += len(text) return "\n".join(out) -def _from_xlsx(zf: zipfile.ZipFile) -> str: +def _from_xlsx(reader: _OfficeBudget) -> str: shared: list[str] = [] - if "xl/sharedStrings.xml" in zf.namelist(): - ss = _read_entry(zf, "xl/sharedStrings.xml") + shared_clipped = False + if reader.has("xl/sharedStrings.xml"): + # Half the budget: otherwise the string table eats the limit and sheets stay empty. + ss, shared_clipped = reader.read_prefix( + "xl/sharedStrings.xml", limit=min(_OFFICE_ENTRY_MAX_BYTES, reader.total_limit // 2), + ) shared = [unescape(_TAG_RE.sub("", m)) for m in re.findall(r"(.*?)", ss, re.S)] - sheets = [n for n in zf.namelist() if re.fullmatch(r"xl/worksheets/sheet\d+\.xml", n)] + if shared_clipped: + reader.note("таблица текстов прочитана частично — часть ячеек показана номером, а не значением") + sheets = [n for n in reader.zf.namelist() if re.fullmatch(r"xl/worksheets/sheet\d+\.xml", n)] sheets.sort(key=lambda n: _num(n.rsplit("/", 1)[-1])) + if len(sheets) > 3: + reader.note(f"листов в книге {len(sheets)} — прочитаны первые 3") out: list[str] = [] + produced = 0 for sheet in sheets[:3]: - xml = _read_entry(zf, sheet) + if reader.at_entry_limit: + reader.note(f"показаны не все листы: {len(out)} из {len(sheets)}") + break + if produced >= TEXT_BUDGET or reader.exhausted(): + reader.note("предел распаковки Office-архива исчерпан — часть листов не прочитана") + break + label = sheet.rsplit('/', 1)[-1] + xml, _ = reader.read_prefix(sheet) rows = [] - for row in re.findall(r"]*>(.*?)", xml, re.S)[:_MAX_XLSX_ROWS]: + all_rows = re.findall(r"]*>(.*?)", xml, re.S) + if len(all_rows) > _MAX_XLSX_ROWS: + reader.note(f"строк в листе больше {_MAX_XLSX_ROWS} — показаны первые") + for row in all_rows[:_MAX_XLSX_ROWS]: + if produced >= TEXT_BUDGET: + reader.note(f"показаны не все строки листа {label}") + break cells = [] - for m in re.finditer(r"]*)(?:/>|>(.*?))", row, re.S): + row_chars = 0 + for count, m in enumerate(re.finditer(r"]*)(?:/>|>(.*?))", row, re.S), start=1): + if count > _MAX_XLSX_CELLS: + reader.note(f"ячеек в строке больше {_MAX_XLSX_CELLS} — показаны первые") + break + left = TEXT_BUDGET - produced - row_chars + if left <= 0: + # A tiny shared string reused by many cells must not inflate + # the output: stop expanding as soon as the budget is spent. + reader.note(f"показаны не все ячейки листа {label}") + break attrs, body = m.group(1) or "", m.group(2) or "" val = "" vm = re.search(r"(.*?)", body, re.S) @@ -158,16 +291,20 @@ def _from_xlsx(zf: zipfile.ZipFile) -> str: im = re.search(r"]*>(.*?)", body, re.S) if im: val = unescape(im.group(1)) - cells.append(val.replace("\t", " ").replace("\n", " ")) + val = val.replace("\t", " ").replace("\n", " ")[:left] + row_chars += len(val) + cells.append(val) if any(c.strip() for c in cells): - rows.append("\t".join(cells)) + line = "\t".join(cells) + rows.append(line) + produced += len(line) if rows: - out.append(f"--- {sheet.rsplit('/', 1)[-1]} ---\n" + "\n".join(rows)) + out.append(f"--- {label} ---\n" + "\n".join(rows)) return "\n".join(out) -def _from_odt(zf: zipfile.ZipFile) -> str: - xml = _read_entry(zf, "content.xml") +def _from_odt(reader: _OfficeBudget) -> str: + xml, _ = reader.read_prefix("content.xml") xml = re.sub(r"", "\n", xml) return unescape(_TAG_RE.sub("", xml)) @@ -175,16 +312,39 @@ def _from_odt(zf: zipfile.ZipFile) -> str: def _from_office(data: bytes, ext: str) -> ExtractResult: try: with zipfile.ZipFile(io.BytesIO(data)) as zf: - names = set(zf.namelist()) + reader = _OfficeBudget(zf) + count = len(zf.infolist()) + if count > _OFFICE_MAX_ENTRIES: + # Informational only: the hard bound is enforced on actual reads. + reader.note( + f"в архиве {count} файлов — читаются не более {_OFFICE_MAX_ENTRIES}", + cut=False, + ) + names = zf.namelist() # central directory listing only, nothing decompressed + text: str | None = None + kind = ext.lstrip(".") if ext == ".docx" and "word/document.xml" in names: - return _finish(_from_docx(zf), "docx") - if ext == ".pptx" and any(n.startswith("ppt/slides/slide") for n in names): - return _finish(_from_pptx(zf), "pptx") - if ext in (".xlsx", ".xlsm") and any(n.startswith("xl/worksheets/") for n in names): - return _finish(_from_xlsx(zf), "xlsx") - if ext == ".odt" and "content.xml" in names: - return _finish(_from_odt(zf), "odt") - except (zipfile.BadZipFile, KeyError, ValueError, IndexError, RuntimeError) as exc: + text, kind = _from_docx(reader), "docx" + elif ext == ".pptx" and any(n.startswith("ppt/slides/slide") for n in names): + text, kind = _from_pptx(reader), "pptx" + elif ext in (".xlsx", ".xlsm") and any(n.startswith("xl/worksheets/") for n in names): + text, kind = _from_xlsx(reader), "xlsx" + elif ext == ".odt" and "content.xml" in names: + text, kind = _from_odt(reader), "odt" + if text is None: + return ExtractResult( + ok=False, + reason=f"{ext} без ожидаемой структуры — возможно, старый формат (.doc/.xls/.ppt)", + ) + res = _finish(text, kind, reader.warnings, cut=reader.cut) + if not res.ok and reader.cut: + return ExtractResult( + ok=False, kind=kind, truncated=True, + reason="текста нет: сработал предел распаковки Office-файла (архив слишком «плотный»)", + warnings=list(reader.warnings), + ) + return res + except (zipfile.BadZipFile, KeyError, ValueError, IndexError, RuntimeError, EOFError, zlib.error) as exc: return ExtractResult(ok=False, reason=f"{ext} повреждён или слишком большой внутри: {type(exc).__name__}") return ExtractResult(ok=False, reason=f"{ext} без ожидаемой структуры — возможно, старый формат (.doc/.xls/.ppt)") diff --git a/bot/grok_bot.py b/bot/grok_bot.py index 5c2b5308..56e693cc 100644 --- a/bot/grok_bot.py +++ b/bot/grok_bot.py @@ -4,6 +4,7 @@ import urllib.parse import contextvars # [EFFORT 2110] from contextlib import asynccontextmanager, closing from pathlib import Path +from runtime_config import bot_config_path, effective_bot_config, skin_db_path import reminders as reminder_store import key_notifications import community_economy @@ -32,13 +33,13 @@ from aiogram.types import Message, CallbackQuery, InlineKeyboardMarkup, InlineKe from aiogram.types import WebAppInfo # [WEBAPP 18.10] from aiogram.enums import ParseMode -CFG_PATH = os.environ.get("GROK_BOT_CFG", "/opt/grok-bot/config.json") +CFG_PATH = bot_config_path() # Секреты НЕ хардкодятся: только env-фоллбэк, реальные значения — в config.json (не в git). DEFAULT_CFG = { "bot_token": os.environ.get("GROK_BOT_TOKEN", ""), "channel_username": "@alstack", "channel_link": "https://t.me/alstack", "channel_title": "@alstack", "support": "@your-handle", - "newapi_url": "http://127.0.0.1:3000", + "newapi_url": "http://127.0.0.1:48000", "newapi_user": "root", "newapi_pass": os.environ.get("NEWAPI_PASS", ""), "newapi_db": "/opt/grok-gateway/new-api/one-api.db", "public_base": "https://api.your-domain.com", @@ -52,10 +53,11 @@ def load_cfg(): if not os.path.exists(CFG_PATH): print(f"[FATAL] config.json missing at {CFG_PATH}"); sys.exit(1) try: - with open(CFG_PATH, encoding="utf-8") as _cfh: + with open(CFG_PATH, encoding="utf-8-sig") as _cfh: cfg.update(json.load(_cfh)) except Exception as e: print(f"[FATAL] config.json broken: {e}"); sys.exit(1) + cfg = effective_bot_config(cfg) for k in ("bot_token", "main_key", "channel_username", "newapi_pass"): if not cfg.get(k): print(f"[FATAL] config.json missing required key: {k}"); sys.exit(1) @@ -70,8 +72,7 @@ def load_cfg(): return cfg CFG = load_cfg() KEY_WAIT_SEC = int(CFG.get("key_wait_hours", 24)) * 3600 -BOT_DB = os.environ.get("IISHKO_BOT_DB") or os.environ.get("GROK_BOT_DB", "/opt/grok-bot/bot.db") -SKIN_DB = os.environ.get("IISHKO_SKIN_DB") or os.environ.get("GATE_TG_DB", "/opt/grok-web-skin-tg.db") +BOT_DB = CFG["bot_db"] def tge(em="🩸", _old=None): return em # plain unicode: текст уходит с parse_mode=HTML, tg-emoji там запрещён logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") @@ -461,7 +462,7 @@ async def abuse_watchdog(bot): _wm = int(time.time()) # первый запуск: историю НЕ трогаем (кольца забанены вручную) _nb = 0 try: - sk = sqlite3.connect(Path(SKIN_DB).resolve().as_uri() + "?mode=ro", uri=True) + sk = sqlite3.connect(Path(skin_db_path()).resolve().as_uri() + "?mode=ro", uri=True) _excl = _iplock_excluded_ips() # [IPLOCK-SRVEXCL 2010] loopback + IISHKO_SRV_EXCLUDED_IPS iprows = sk.execute( "SELECT ip, GROUP_CONCAT(DISTINCT token_name) FROM ip_lock_events " @@ -3060,7 +3061,7 @@ async def cb_pquiz(c: CallbackQuery): await c.answer("Верно!" if ok else "Мимо") -GW_DB = os.environ.get("IISHKO_GW_DB", "/opt/grok-gateway/new-api/one-api.db") +GW_DB = CFG["newapi_db"] QUOTA_PER_USD = 500000 def _cas_wallet(uid, paused_ok=True): @@ -3666,7 +3667,7 @@ def _full_ban(uid, tname, reason): # освобождаем ip-клейм: забаненный токен не должен держать IP на 24ч (ложные локи соседей) if tname: try: - _sk = sqlite3.connect(SKIN_DB, timeout=10) + _sk = sqlite3.connect(Path(skin_db_path()).resolve().as_uri() + "?mode=rw", uri=True, timeout=10) _sk.execute("DELETE FROM ip_claims WHERE token_name=?", (tname,)) _sk.commit() _sk.close() @@ -14655,6 +14656,7 @@ async def cmd_unknown(m: Message): import entry_admin as _entry_admin +_entry_admin.BOT_DB = BOT_DB try: _entry_admin.init_db() except Exception: diff --git a/bot/key_notifications.py b/bot/key_notifications.py index 0289a8a5..ceb31571 100644 --- a/bot/key_notifications.py +++ b/bot/key_notifications.py @@ -11,6 +11,7 @@ import secrets import sqlite3 import time from urllib.parse import urlsplit, urlunsplit +from runtime_config import bot_config_path, effective_bot_config log = logging.getLogger("key-notifications") @@ -481,13 +482,14 @@ class KeyNotificationWorker: def main(): parser = argparse.ArgumentParser(description="Read-only first-key notification aggregates; this CLI never sends.") parser.add_argument("action", choices=("dry-run", "status")) - parser.add_argument("--bot-db", default=os.environ.get("GROK_BOT_DB", "/opt/grok-bot/bot.db")) + parser.add_argument("--bot-db") parser.add_argument("--ledger") - parser.add_argument("--config", default=os.environ.get("GROK_BOT_CFG", "/opt/grok-bot/config.json")) + parser.add_argument("--config", default=bot_config_path()) args = parser.parse_args() - with open(args.config, encoding="utf-8") as config: - wait_seconds = int(json.load(config).get("key_wait_hours", 24)) * 3600 - store = KeyNotificationStore(args.bot_db, args.ledger, wait_seconds=wait_seconds) + with open(args.config, encoding="utf-8-sig") as config: + cfg = effective_bot_config(json.load(config)) + wait_seconds = int(cfg.get("key_wait_hours", 24)) * 3600 + store = KeyNotificationStore(args.bot_db or cfg["bot_db"], args.ledger, wait_seconds=wait_seconds) print(json.dumps(store.dry_run() if args.action == "dry-run" else store.status(), ensure_ascii=False, sort_keys=True)) diff --git a/bot/runtime_config.py b/bot/runtime_config.py new file mode 100644 index 00000000..ebb36e65 --- /dev/null +++ b/bot/runtime_config.py @@ -0,0 +1,61 @@ +"""Small shared configuration helpers; importing this module has no side effects.""" +import os + + +_TRUE = frozenset({"1", "true", "yes", "on"}) + + +def env_enabled(name, default=False): + value = os.environ.get(name) + return default if value is None else value.strip().lower() in _TRUE + + +def notifications_enabled(channel=None): + if not env_enabled("IISHKO_NOTIFICATIONS_ENABLED"): + return False + if channel in ("support", "entry") and not env_enabled("IISHKO_SUPPORT_DELIVERY_ENABLED", True): + return False + return channel != "entry" or env_enabled("IISHKO_ENTRY_DELIVERY_ENABLED", True) + + +def skin_db_path(): + """Canonical name wins; keep the old gateway-only name for existing units.""" + return (os.environ.get("IISHKO_SKIN_DB") or os.environ.get("GATE_TG_DB") + or "/opt/grok-web-skin-tg.db") + + +def bot_config_path(): + return (os.environ.get("GROK_BOT_CFG") or os.environ.get("GROK_BOT_CONFIG") + or os.environ.get("GATE_BOT_CONFIG") or "/opt/grok-bot/config.json") + + +def gateway_db_path(fallback="/opt/grok-gateway/new-api/one-api.db"): + return os.environ.get("IISHKO_GW_DB") or os.environ.get("GATE_NEWAPI_DB") or fallback + + +def bot_db_path(fallback="/opt/grok-bot/bot.db"): + return (os.environ.get("IISHKO_BOT_DB") or os.environ.get("GROK_BOT_DB") + or os.environ.get("GATE_BOT_DB") or fallback) + + +def econ_state_path(fallback="/opt/grok-bot/econ_cap_state.json"): + return os.environ.get("IISHKO_ECON_STATE") or fallback + + +def upstream_url(fallback="http://127.0.0.1:48000"): + return (os.environ.get("IISHKO_UPSTREAM") or os.environ.get("NEWAPI_URL") + or fallback) + + +def effective_bot_config(config): + """Apply one environment contract to bot, Mini App and Telegram login.""" + config = dict(config) + for key, name in (("bot_token", "GROK_BOT_TOKEN"), ("newapi_pass", "NEWAPI_PASS")): + if os.environ.get(name): + config[key] = os.environ[name] + config["bot_db"] = bot_db_path(config.get("bot_db") or "/opt/grok-bot/bot.db") + config["newapi_db"] = gateway_db_path( + config.get("newapi_db") or "/opt/grok-gateway/new-api/one-api.db") + config["newapi_url"] = upstream_url( + config.get("newapi_url") or "http://127.0.0.1:48000") + return config diff --git a/bot/webapp/mk_daemon.py b/bot/webapp/mk_daemon.py index 5def2e7f..5e9200b4 100644 --- a/bot/webapp/mk_daemon.py +++ b/bot/webapp/mk_daemon.py @@ -17,14 +17,16 @@ sys.path[:0] = os.environ.get("IISHKO_RUNTIME_PATHS", os.environ.get("IISHKO_APP import key_issue_guard from account_limits import account_uid, account_token_names import account_balances +from runtime_config import bot_db_path, econ_state_path, gateway_db_path _so = sys.stdout sys.stdout = sys.stderr try: import grok_bot as g finally: sys.stdout = _so -BOT_DB = os.environ.get("IISHKO_BOT_DB") or os.environ.get("GROK_BOT_DB", "/opt/grok-bot/bot.db") -GW_DB = g.CFG['newapi_db'] +BOT_DB = bot_db_path(g.CFG["bot_db"]) +# Same value the imported bot resolved, so both sides share one gateway database. +GW_DB = g.CFG.get('newapi_db') or gateway_db_path() Q = g.QUOTA_PER_UNIT @@ -379,17 +381,21 @@ def cmd_reveal(uid, n): return {'ok': True, 'key': 'sk-' + r['key'], 'name': r['name']} -def _read_pause_state(state_path='/opt/grok-bot/econ_cap_state.json'): +def _state_path(state_path=None): + return state_path or econ_state_path() + + +def _read_pause_state(state_path=None): # [FIX-2410] чтение JSON-состояния вынесено из BEGIN IMMEDIATE-транзакции try: - with open(state_path, encoding='utf-8') as fh: + with open(_state_path(state_path), encoding='utf-8') as fh: state = json.load(fh) return state if isinstance(state, dict) else {} except (OSError, ValueError): return {} -def _daily_pause_info(con, row, user, state=None, state_path='/opt/grok-bot/econ_cap_state.json'): +def _daily_pause_info(con, row, user, state=None, state_path=None): if int(row['status']) != 2 or user.get('key_locked'): return {} try: diff --git a/bot/webapp/server.py b/bot/webapp/server.py index b01a53e2..a3b05302 100644 --- a/bot/webapp/server.py +++ b/bot/webapp/server.py @@ -41,6 +41,7 @@ import entry_admin import miniapp_guard import gateway_commerce import commerce_access +from runtime_config import bot_config_path, effective_bot_config, notifications_enabled import community_board import account_balances from account_limits import account_uid @@ -70,12 +71,13 @@ def _model_metadata_rows(model_ids): return reference or None log = logging.getLogger("iishko-webapp") -with open(os.environ.get("GROK_BOT_CONFIG", "/opt/grok-bot/config.json"), encoding="utf-8") as config_file: - CFG = json.load(config_file) +with open(bot_config_path(), encoding="utf-8-sig") as config_file: + CFG = effective_bot_config(json.load(config_file)) BOT_TOKEN = CFG["bot_token"] -BOT_DB = os.environ.get("IISHKO_BOT_DB") or os.environ.get("GROK_BOT_DB", "/opt/grok-bot/bot.db") +BOT_DB = CFG["bot_db"] +entry_admin.BOT_DB = BOT_DB UPTIME_DB = os.environ.get("GROK_UPTIME_DB", os.path.join(os.path.dirname(BOT_DB), "model_uptime.db")) -NEWAPI_DB = CFG.get("newapi_db", "/opt/grok-gateway/new-api/one-api.db") +NEWAPI_DB = CFG["newapi_db"] QUOTA_PER_USD = 500000 ADMIN_IDS = {int(value) for value in os.environ.get("IISHKO_ADMIN_IDS", "").split(",") if value.strip().isdigit()} ADMIN_IDS.update(value for value in CFG.get("admin_ids", []) if type(value) is int and value > 0) @@ -2261,7 +2263,7 @@ async def api_support_get(req): async def _support_notify(admin_id, text, reply_markup=None): - if os.environ.get("IISHKO_NOTIFICATIONS_ENABLED", "1") == "0": + if not notifications_enabled(): raise NotificationError(retryable=False) payload = {"chat_id": admin_id, "text": text, "disable_web_page_preview": True} if reply_markup: @@ -2324,8 +2326,7 @@ async def _support_lifecycle(app): worker = SupportOutbox(_SUPPORT, lambda: ADMIN_IDS, _support_notify) app["support_worker"] = worker task = None - if (os.environ.get("IISHKO_SUPPORT_DELIVERY_ENABLED", "1") != "0" and - os.environ.get("IISHKO_NOTIFICATIONS_ENABLED", "1") != "0"): + if notifications_enabled("support"): task = asyncio.create_task(worker.run(), name="iishko-support-outbox") app["support_task"] = task try: diff --git a/deploy/README.md b/deploy/README.md index 485c3470..221ba84b 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -1,61 +1,104 @@ # Деплой (примеры) -Это **примеры**, а не готовый боевой деплой. Пути (`/opt/...`), домены (`your-domain.com`) -и порты замените на свои. Все приватные порты по умолчанию — loopback (`127.0.0.1`); -наружу выставляйте только через reverse proxy с TLS. +Примеры, а не готовый боевой деплой: домен (`your-domain.com`), владельца юнитов и +порты замените на свои. Приватные порты — loopback (`127.0.0.1`), наружу только через +reverse proxy с TLS. Репозиторий копируется целиком (git clone / rsync), «плоской» +сборки нет: `bot/`, `gateway/`, `scripts/`, `tests/` остаются на месте. + +## Раскладка на сервере + +| Расположение | Источник | Тип | +|---|---|---| +| `/opt/iishko` | корень репозитория | дерево | +| `/etc/iishko/runtime.env` | `deploy/runtime.env.example` (права `0640 root:root`) | конфиг сервера | +| `/etc/iishko/bot/config.json` | `bot/config.example.json` (права `0600`) | конфиг сервера | +| `/opt/iishko/var/` | каталог для SQLite/логов, создаётся вами | состояние | + +Модерация собирается из корня репозитория: + +```bash +mkdir -p bin +(cd moderation && go build -o ../bin/iishko-moderation .) +``` + +Запуск — только через `scripts/run.py`: + +| Цель | Точка входа | +|---|---| +| `bot` | `bot/grok_bot.py` (`bot/iishko_bot.py` оставлен для прежних запусков) | +| `miniapp` | `bot/webapp/server.py` | +| `gateway` | `gateway/grok-web-skin.py` | + +`scripts/run.py` читает `--env-file`, при этом реальная переменная окружения важнее +файла; нормализует исторические имена конфига (`GROK_BOT_CFG` / `GROK_BOT_CONFIG` / +`GATE_BOT_CONFIG`) и стартует цель. Своих загрузчиков env в юнитах нет. `--check` +проверяет конфигурацию офлайн, без сети и без запуска приложения. + +Канонические имена выбирает `bot/runtime_config.py`: конфиг бота — +`GROK_BOT_CFG` > `GROK_BOT_CONFIG` > `GATE_BOT_CONFIG`, база скина — `IISHKO_SKIN_DB` > +`GATE_TG_DB`. База New API (`IISHKO_GW_DB`) должна существовать до старта: `run.py` и +`--check` её не создают и завершаются ошибкой, если файла нет. Остальные SQLite +открывают сами приложения. ## Состав | Файл | Назначение | |---|---| -| `systemd/grok-bot.service` | Telegram-бот (long polling), `bot/grok_bot.py` | -| `systemd/iishko-webapp.service` | Mini App backend, `bot/webapp/server.py`, `127.0.0.1:8850` | -| `systemd/grok-web-skin.service` | скин шлюза, `gateway/grok-web-skin.py`, `127.0.0.1:48001` | -| `systemd/iishko-moderation.service` | сервис модерации (`moderation/`), `127.0.0.1:48003` | -| `caddy/Caddyfile.example` | маршрутизация `/webapp/*`, `/v1/*`, статика сайта | +| `systemd/grok-bot.service` | Telegram-бот (long polling), цель `bot` | +| `systemd/iishko-webapp.service` | Mini App backend, цель `miniapp`, `127.0.0.1:8850` | +| `systemd/grok-web-skin.service` | скин/прокси шлюза, цель `gateway`, `127.0.0.1:48001` | +| `systemd/iishko-moderation.service` | политика модерации (Go-бинарь, loopback `:48003`) | +| `runtime.env.example` | шаблон `/etc/iishko/runtime.env` (только плейсхолдеры) | +| `caddy/Caddyfile.example` | маршрутизация `/webapp/*` и прокси к скину шлюза | -Единицы сняты с боевого сервера и оставлены как пример структуры: перед использованием -поправьте `WorkingDirectory`, `ExecStart`, пути к БД и файл `EnvironmentFile=`. -Мониторинг, TTS и firewall — вне репозитория, используйте свои. +Core-юниты содержат `WorkingDirectory=/opt/iishko` и +`ExecStart=/opt/iishko/.venv/bin/python /opt/iishko/scripts/run.py <цель> --env-file /etc/iishko/runtime.env` +(кроме `iishko-moderation` — он читает `/etc/iishko/runtime.env` напрямую через +`EnvironmentFile=`). Без env-файла юнит падает сразу. ## Порядок -1. Внешний шлюз (New API / one-api) поднимается **отдельно** — в репозиторий не входит. - Заведите каналы, получите мастер-ключ. -2. Заполните `.env` (см. `.env.example`) и `bot/config.json` (из `bot/config.example.json`). -3. `python scripts/selfcheck.py` — офлайн-проверка перед стартом. -4. Запустите бота, Mini App и скин; наружу — через Caddy. +1. Внешний шлюз (New API / one-api) поднимается отдельно, в репозиторий не входит. +2. Клон в `/opt/iishko`, `.venv` и зависимости (`requirements.txt`), сборка + `iishko-moderation` из `moderation/`. +3. `/opt/iishko/var`, `/etc/iishko/bot/config.json` (из `bot/config.example.json`) и + `/etc/iishko/runtime.env` (из `deploy/runtime.env.example`) — со своими значениями. +4. Офлайн-проверка: `.venv/bin/python scripts/run.py bot --env-file /etc/iishko/runtime.env --check` + (так же для `miniapp`, `gateway`). +5. Юниты из `deploy/systemd/`, `systemctl daemon-reload`, `enable --now`. +6. Наружу — только через Caddy по `deploy/caddy/Caddyfile.example`. ## Переменные окружения -PowerShell: +Канонический источник — `/etc/iishko/runtime.env` (см. `runtime.env.example`, там же +приоритеты). Для локальной разработки достаточно `.env` в корне репозитория: ```powershell -$env:PYTHONPATH = "bot;gateway" -$env:GROK_BOT_CFG = "C:\iishko\bot\config.json" -$env:IISHKO_ADMIN_IDS = "123456789" -python bot\grok_bot.py +python scripts/run.py bot # читает .env из корня репозитория +python scripts/run.py gateway --check ``` -POSIX: - ```bash -export PYTHONPATH=bot:gateway -export GROK_BOT_CFG=$PWD/bot/config.json -export IISHKO_ADMIN_IDS=123456789 -python bot/grok_bot.py +python scripts/run.py miniapp --env-file .env ``` +Ручной экспорт (`PYTHONPATH`, `GROK_BOT_CFG`, `IISHKO_ADMIN_IDS`) совместим, но не +обязателен: `scripts/run.py` делает то же самое. + ## Выключено по умолчанию -Автобан Mini App (`IISHKO_ENTRY_AUTOBAN=0`, включается только `=1`), песочница -(`IISHKO_SANDBOX_ENABLED=0`), гео-база (файла нет), платежи (токены пустые). -Включайте осознанно: автобан трогает балансы и ключи реальных аккаунтов, а общий IP -(NAT, мобильный оператор, семья) сам по себе не доказывает мультиаккаунт. -Уведомления владельцам (`IISHKO_ADMIN_IDS`) включены по умолчанию; выключение — -`IISHKO_NOTIFICATIONS_ENABLED=0`. +Legacy-флаг `IISHKO_ENTRY_AUTOBAN=0` оставлен для совместимости API, автоматического +IP-применения нет. Уведомления (`IISHKO_NOTIFICATIONS_ENABLED=0`), песочница +(`IISHKO_SANDBOX_ENABLED=0`), гео-база (файла нет) и платежи (токены пустые) выключены. +Совпадение IP вызывает только алерт для ручной проверки, даже при `IISHKO_ENTRY_AUTOBAN=1`. +Явный бан администратором — отдельная операция; legacy-санкции могут менять квоты и ключи. -## Чего здесь нет +## Что не входит в репозиторий -Баз данных, ключей, логов и юнитов посторонних сервисов. -Датасет DB-IP (~121 MB) скачивается отдельно: `bot/geo/provenance.json`. +Кода и юнитов для healthcheck/health-timer, алертера (`alert-watch`), media/TTS-адаптера, +firewall-скрипта и шлюза New API здесь нет: это сервисы оператора, их код, расписание и +права вы заводите сами. В `deploy/systemd/` — только четыре юнита, которые репозиторий +реально запускает. Заглушек и фальшивых проверок нет. + +Базы, ключи и логи сюда не входят. Caddyfile не импортирует файлы вне `deploy/caddy/`. +Датасет DB-IP (~121 MB) скачивается отдельно: `bot/geo/provenance.json`. \ No newline at end of file diff --git a/deploy/caddy/Caddyfile.example b/deploy/caddy/Caddyfile.example index d85c5e96..37a87cad 100644 --- a/deploy/caddy/Caddyfile.example +++ b/deploy/caddy/Caddyfile.example @@ -38,16 +38,20 @@ api.your-domain.com { import api_common - handle /v1/media/* { - reverse_proxy 127.0.0.1:8000 { - # media responses are large; stream instead of buffering whole bodies - flush_interval -1 - transport http { - read_timeout 300s - dial_timeout 10s - } - } - } + # Media/TTS (/v1/media/*) is NOT routed here: this repo ships no media adapter. + # The gateway skin proxies every /v1/* path to the upstream. If you run an + # operator-run adapter on loopback, + # add your own route above the catch-all: + # + # handle /v1/media/* { + # reverse_proxy 127.0.0.1: { + # flush_interval -1 + # transport http { + # read_timeout 300s + # dial_timeout 10s + # } + # } + # } # [WEBAPP-WIRE 19.10] Mini App: /webapp -> 127.0.0.1:8850 handle /webapp { redir /webapp/ 301 @@ -88,4 +92,3 @@ your-domain.com { } } } - diff --git a/deploy/runtime.env.example b/deploy/runtime.env.example new file mode 100644 index 00000000..62acb7b2 --- /dev/null +++ b/deploy/runtime.env.example @@ -0,0 +1,60 @@ +# IISHKO runtime environment for systemd units. +# +# Install (never commit the real file): +# sudo install -d -m 0750 /etc/iishko +# sudo install -m 0640 -o root -g root \ +# /opt/iishko/deploy/runtime.env.example /etc/iishko/runtime.env +# sudoedit /etc/iishko/runtime.env # replace every REPLACE_ME +# +# Consumers: +# deploy/systemd/grok-bot.service -> scripts/run.py bot --env-file /etc/iishko/runtime.env +# deploy/systemd/iishko-webapp.service -> scripts/run.py miniapp --env-file /etc/iishko/runtime.env +# deploy/systemd/grok-web-skin.service -> scripts/run.py gateway --env-file /etc/iishko/runtime.env +# deploy/systemd/iishko-moderation.service -> EnvironmentFile=/etc/iishko/runtime.env (Go binary) +# +# Priority: a variable already present in the process environment wins over the +# value in this file. scripts/run.py loads the file, normalises the legacy config +# aliases (GROK_BOT_CFG / GROK_BOT_CONFIG / GATE_BOT_CONFIG) and only then starts +# the target process; it does not override real environment variables. +# +# This file holds configuration only. Secrets live in bot/config.json (0600) and +# in this file — both stay outside the repository. + +# --- bot config (canonical name; aliases are set by scripts/run.py) ----------- +GROK_BOT_CFG=/etc/iishko/bot/config.json + +# --- SQLite files (absolute; create the directory first) --------------------- +IISHKO_BOT_DB=/opt/iishko/var/bot.db +IISHKO_GW_DB=/opt/iishko/var/newapi.db +# Canonical skin DB name; GATE_TG_DB is the legacy alias for the same file. +IISHKO_SKIN_DB=/opt/iishko/var/grok-web-skin-tg.db +IISHKO_ECON_STATE=/opt/iishko/var/econ_cap_state.json + +# --- loopback listeners (never expose these directly) ----------------------- +IISHKO_WEBAPP_HOST=127.0.0.1 +IISHKO_WEBAPP_PORT=8850 +IISHKO_GATEWAY_HOST=127.0.0.1 +IISHKO_GATEWAY_PORT=48001 + +# --- upstream gateway (New API / one-api, external service) ------------------ +IISHKO_UPSTREAM=http://127.0.0.1:48000 + +# --- provider registry (operator-owned file, see gateway/providers.example.json) +IISHKO_PROVIDERS_FILE=/etc/iishko/providers.json + +# --- moderation token (required by iishko-moderation, >=32 chars) ------------ +IISHKO_MODERATION_TOKEN=REPLACE_ME_MODERATION_TOKEN + +# --- admin Telegram IDs, comma separated ------------------------------------ +IISHKO_ADMIN_IDS= + +# --- Telegram website session-signing secret (never commit or overwrite) ---- +# Leave the path absent on first start: gateway creates it atomically with mode 0600. +# Keep it outside the repo and preserve it across upgrades. An existing file must +# have mode 0600 and belong to the gateway service user; its contents are not printed. +TG_SID_SECRET_FILE=/etc/iishko/tg-sid-secret + +# --- optional features, off by default (see deploy/README.md) --------------- +IISHKO_ENTRY_AUTOBAN=0 +IISHKO_NOTIFICATIONS_ENABLED=0 +IISHKO_SANDBOX_ENABLED=0 \ No newline at end of file diff --git a/deploy/systemd/grok-bot.service b/deploy/systemd/grok-bot.service index bceef54e..bf5b9e8d 100644 --- a/deploy/systemd/grok-bot.service +++ b/deploy/systemd/grok-bot.service @@ -1,14 +1,23 @@ [Unit] -Description=Grok Telegram Bot -After=network-online.target new-api.service +Description=IISHKO Telegram bot (long polling) +Documentation=file:/opt/iishko/deploy/README.md +After=network-online.target Wants=network-online.target +# The upstream gateway (New API / one-api) is an external service and has no unit +# in this repo. If it runs on this host, add its unit name to After= below. [Service] -EnvironmentFile=/opt/grok-bot/.env -WorkingDirectory=/opt/grok-bot -ExecStart=/opt/venv/bin/python /opt/grok-bot/iishko_bot.py +Type=simple +User=root +WorkingDirectory=/opt/iishko +# scripts/run.py loads /etc/iishko/runtime.env (real environment wins), adds the +# repo directories to sys.path and starts bot/grok_bot.py. +# The file is required: without it the unit fails fast instead of starting half-configured. +ExecStart=/opt/iishko/.venv/bin/python /opt/iishko/scripts/run.py bot --env-file /etc/iishko/runtime.env Restart=always RestartSec=10 +NoNewPrivileges=true +PrivateTmp=true [Install] -WantedBy=multi-user.target +WantedBy=multi-user.target \ No newline at end of file diff --git a/deploy/systemd/grok-web-skin.service b/deploy/systemd/grok-web-skin.service index bc235067..e17aabe8 100644 --- a/deploy/systemd/grok-web-skin.service +++ b/deploy/systemd/grok-web-skin.service @@ -1,13 +1,22 @@ [Unit] -Description=IISHKO gateway web skin -After=network-online.target new-api.service +Description=IISHKO gateway skin (loopback 127.0.0.1:48001) +Documentation=file:/opt/iishko/deploy/README.md +After=network-online.target +Wants=network-online.target +# Upstream gateway is external, see the note in grok-bot.service. [Service] -EnvironmentFile=/opt/grok-bot/.env +Type=simple +User=root +WorkingDirectory=/opt/iishko +# gateway target runs gateway/grok-web-skin.py; sys.path needs gateway/ and bot/ +# (the skin imports bot modules), which scripts/run.py sets up. +ExecStart=/opt/iishko/.venv/bin/python /opt/iishko/scripts/run.py gateway --env-file /etc/iishko/runtime.env TimeoutStopSec=30 -ExecStart=/opt/venv/bin/python /opt/grok-web-skin.py Restart=always RestartSec=3 +NoNewPrivileges=true +PrivateTmp=true [Install] -WantedBy=multi-user.target +WantedBy=multi-user.target \ No newline at end of file diff --git a/deploy/systemd/iishko-moderation.service b/deploy/systemd/iishko-moderation.service index e9e6ba8c..97267fb5 100644 --- a/deploy/systemd/iishko-moderation.service +++ b/deploy/systemd/iishko-moderation.service @@ -1,13 +1,17 @@ [Unit] Description=IISHKO moderation policy (loopback only, no Telegram poller) -After=network.target +Documentation=file:/opt/iishko/deploy/README.md +After=network-online.target +Wants=network-online.target [Service] Type=simple User=root -WorkingDirectory=/opt/grok-bot -EnvironmentFile=/etc/iishko/moderation.env -ExecStart=/opt/grok-bot/bin/iishko-moderation -addr 127.0.0.1:48003 +WorkingDirectory=/opt/iishko +# Native EnvironmentFile: the Go binary is not started through scripts/run.py. +# IISHKO_MODERATION_TOKEN is required (see deploy/runtime.env.example). +EnvironmentFile=/etc/iishko/runtime.env +ExecStart=/opt/iishko/bin/iishko-moderation -addr 127.0.0.1:48003 Restart=on-failure RestartSec=3 TimeoutStopSec=15 @@ -15,6 +19,8 @@ NoNewPrivileges=true PrivateTmp=true ProtectSystem=strict ProtectHome=true +# Runtime state is written under /opt/iishko/var (DBs, logs). +ReadWritePaths=/opt/iishko/var RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX CapabilityBoundingSet= MemoryMax=128M @@ -22,4 +28,4 @@ TasksMax=32 UMask=0077 [Install] -WantedBy=multi-user.target +WantedBy=multi-user.target \ No newline at end of file diff --git a/deploy/systemd/iishko-webapp.service b/deploy/systemd/iishko-webapp.service index 7e240d0e..5f9f77b8 100644 --- a/deploy/systemd/iishko-webapp.service +++ b/deploy/systemd/iishko-webapp.service @@ -1,13 +1,20 @@ [Unit] -Description=iishko webapp (Mini App backend) -After=network.target +Description=IISHKO Mini App backend (loopback 127.0.0.1:8850) +Documentation=file:/opt/iishko/deploy/README.md +After=network-online.target +Wants=network-online.target [Service] -EnvironmentFile=/opt/grok-bot/.env -ExecStart=/opt/venv/bin/python /opt/grok-bot/webapp/server.py -WorkingDirectory=/opt/grok-bot/webapp +Type=simple +User=root +WorkingDirectory=/opt/iishko +# miniapp target runs bot/webapp/server.py; listen address comes from runtime.env +# (IISHKO_WEBAPP_HOST / IISHKO_WEBAPP_PORT). +ExecStart=/opt/iishko/.venv/bin/python /opt/iishko/scripts/run.py miniapp --env-file /etc/iishko/runtime.env Restart=always RestartSec=3 +NoNewPrivileges=true +PrivateTmp=true [Install] -WantedBy=multi-user.target +WantedBy=multi-user.target \ No newline at end of file diff --git a/docs/native-gateway.md b/docs/native-gateway.md index 23ff2b59..c1b1483e 100644 --- a/docs/native-gateway.md +++ b/docs/native-gateway.md @@ -2,8 +2,8 @@ Status: **shipped runtime is Python**. `gateway/grok-web-skin.py` plus the `gateway_*` modules below are the runtime that this tree ships and tests. A Go -native gateway is **not included and is not the default** — nothing here requires -a Go toolchain, and no Go build is part of CI. +native gateway is **not included and is not the default**. The separate Go service +in `moderation/` is built and checked in CI; it is not the gateway. This page documents operational behaviour, not internals. Authoritative behaviour is the code in `gateway/` and the root `tests/` suite. @@ -18,9 +18,9 @@ is the code in `gateway/` and the root `tests/` suite. | `gateway/gateway_usage.py` | usage accounting shared by HTTP and key paths | | `gateway/gateway_providers.py` | provider registry (pinning, ownership, rpm bounds) | | `gateway/gateway_provider_relay.py` | relay of a request to a pinned provider | -| `gateway/gateway_commerce.py` | money routes (wallet/paid offers), disabled by default | -| `gateway/commerce_access.py` | access rules for money/board routes | -| `gateway/community_board.py` | community board: authenticated `/api/activities` (no kill-switch flag) | +| `bot/gateway_commerce.py` | money routes (wallet/paid offers), disabled by default | +| `bot/commerce_access.py` | access rules for money/board routes | +| `bot/community_board.py` | community board: authenticated `/api/activities` (no kill-switch flag) | | `bot/account_balances.py` | exact read-only balance aggregation shared by HTTP and the key daemon | ## Adaptive RPM @@ -42,7 +42,9 @@ output are unaffected. Pinning is opt-in and registry-driven: ```bash -export IISHKO_PROVIDERS_FILE=gateway/providers.example.json +cp gateway/providers.example.json providers.json +# Edit the private copy for your own instance before enabling pinning. +export IISHKO_PROVIDERS_FILE="$PWD/providers.json" ``` * The registry file is operator-owned configuration; `gateway/providers.example.json` diff --git a/gateway/grok-web-skin.py b/gateway/grok-web-skin.py index 8b4492d8..1a4e0afb 100644 --- a/gateway/grok-web-skin.py +++ b/gateway/grok-web-skin.py @@ -28,6 +28,7 @@ from gateway_features import install as install_gateway_features from gateway_provider_relay import relay_selected from gateway_providers import ProviderError, ProviderRegistry from gateway_policy import denial_response +from runtime_config import bot_config_path, bot_db_path, effective_bot_config, skin_db_path # [MODELMETA 2026-10-28] vendor-reference limits: static JSON, read-only, no network. # Optional import: the gateway must boot even if the reference file/module is absent. try: @@ -99,7 +100,12 @@ async def _models_catalogue_response(req, upstream): PROVIDER_KEY = web.AppKey("iishko_providers", ProviderRegistry) -UPSTREAM = os.environ.get("IISHKO_UPSTREAM", "http://127.0.0.1:48000") +try: + with open(bot_config_path(), encoding="utf-8-sig") as config_file: + _runtime_cfg = effective_bot_config(json.load(config_file)) +except FileNotFoundError: + _runtime_cfg = effective_bot_config({}) +UPSTREAM = _runtime_cfg["newapi_url"].rstrip("/") TIMEOUT = aiohttp.ClientTimeout(total=None, connect=10, sock_connect=10, sock_read=860) # Preserve the existing 64 generation slots; reserve independent capacity for reads. GENERATION_CONNECTIONS = 256 @@ -109,10 +115,8 @@ MAX_BODY = 40 * 1024 * 1024 MAX_SSE_FRAME = 65536 LOG = logging.getLogger("gateway_proxy") -# ---------- [GATE] daily checkin + chat subscription enforcement (owner 2026-10-08) ---------- -# Reads current bot-account policy; unavailable databases temporarily deny access. -GATE_BOT_DB = os.environ.get("GATE_BOT_DB", os.environ.get("IISHKO_BOT_DB", "/opt/grok-bot/bot.db")) -GATE_NEWAPI_DB = os.environ.get("GATE_NEWAPI_DB", os.environ.get("IISHKO_GW_DB", "/opt/grok-gateway/new-api/one-api.db")) +GATE_NEWAPI_DB = _runtime_cfg["newapi_db"] +GATE_BOT_DB = bot_db_path(_runtime_cfg["bot_db"]) GATE_TTL = 60 _gate_cache = {} _gate_err_ts = [0.0] @@ -1075,9 +1079,9 @@ async def brand_asset(req): # injected JS POSTs it to /api/tg_widget_login. # Provision: new-api user "tg" via admin API, password kept in skin-local store (0600). # Login: server-side POST /api/user/login, Set-Cookie forwarded to the browser. -TG_BOT_CONFIG = os.environ.get("GATE_BOT_CONFIG", "/opt/grok-bot/config.json") +TG_BOT_CONFIG = bot_config_path() TG_ADMIN_TOKEN_FILE = "/root/.secrets/newapi_admin_token" -TG_PROVISION_DB = os.environ.get("IISHKO_SKIN_DB") or os.environ.get("GATE_TG_DB", "/opt/grok-web-skin-tg.db") +TG_PROVISION_DB = skin_db_path() TG_AUTH_MAX_AGE = 900 TG_SID_SECRET_FILE = os.environ.get("TG_SID_SECRET_FILE", "/root/.secrets/iishko_tg_sid_secret") _TG_SID_SECRET = None @@ -1464,8 +1468,8 @@ def _key_share_seize(user_id, attacker_name, owner_name, key): def _tg_bot_token(): - with open(TG_BOT_CONFIG, encoding="utf-8") as fh: - return json.load(fh)["bot_token"] + with open(TG_BOT_CONFIG, encoding="utf-8-sig") as fh: + return effective_bot_config(json.load(fh))["bot_token"] def _tg_check_hash(data): diff --git a/iishko-ts/README.md b/iishko-ts/README.md index 48265db7..5eea5014 100644 --- a/iishko-ts/README.md +++ b/iishko-ts/README.md @@ -1,22 +1,26 @@ # iishko-ts -TypeScript rewrite of the [iishko](https://github.com/aaronjaworski710/iishko) Telegram AI bot. - -Why rewrite: -- Python monolith (13K lines, single file) accumulated hotfixes; no tests, sync sqlite inside asyncio -- TypeScript + grammY: typed end-to-end, native async, modular from day one, graceful shutdown +Experimental TypeScript/grammY rewrite of the Python bot in this repository. +The Python runtime already has a test suite; this prototype explores a different +structure and is not a drop-in replacement. ## Status -**Skeleton / staging.** Core loop works (start, balance, key issuance, streaming chat with quota spend). Not yet at feature parity with the Python bot — production keeps running the Python version until parity + tests are green. +**Skeleton / staging, not production-ready.** Implemented handlers cover start, +balance, existing-key lookup, and streaming chat with quota spend. Key creation, +feature parity, and end-to-end integration are not established. The `/key` +prototype can print an existing key into a private chat; do not use it with +production credentials. Never run it alongside another polling process using +the same bot token. No staging systemd unit is supplied. ## Parity roadmap - [x] Config (typed, env + config.json) - [x] SQLite (WAL, busy_timeout) — users/tokens/ledger - [x] Gateway client: OpenAI-compat, SSE streaming, native tools, fallback chain (content-policy 400 → next model) -- [x] /start (referral capture), /balance, /key (KEYWAIT gate) +- [x] /start (referral capture), /balance, existing-key lookup with KEYWAIT gate - [x] Streaming chat with edit-throttle + quota spend +- [ ] Key creation and a private reveal flow (not plaintext chat delivery) - [ ] Rank/tier system (MODEL_ALIASES + tier gating via sync_rank_limits equivalent) - [ ] Games/casino/quiz modules - [ ] Webapp (aiohttp → Hono/Fastify) + pricing showcase diff --git a/iishko-ts/deploy/iishko-ts.service b/iishko-ts/deploy/iishko-ts.service deleted file mode 100644 index 8271983f..00000000 --- a/iishko-ts/deploy/iishko-ts.service +++ /dev/null @@ -1,13 +0,0 @@ -[Unit] -Description=iishko TS bot (staging) -After=network-online.target - -[Service] -WorkingDirectory=/opt/iishko-ts -Environment=IISHKO_TS_CONFIG=/opt/iishko-ts/config.json -ExecStart=/usr/bin/node dist/index.js -Restart=always -RestartSec=5 - -[Install] -WantedBy=multi-user.target diff --git a/requirements.txt b/requirements.txt index 45d79c13..c4aaac79 100644 --- a/requirements.txt +++ b/requirements.txt @@ -13,6 +13,8 @@ yarl>=1.9 psutil>=5.9 # password hashing for account bootstrap paths bcrypt>=4.0 +# Explicit .env loading by scripts/run.py (never executes shell statements) +python-dotenv>=1.0,<2 # --- optional features (install only if you use them) --- # Web search in chat replies. Upstream package was renamed diff --git a/scripts/run.py b/scripts/run.py new file mode 100644 index 00000000..18e10969 --- /dev/null +++ b/scripts/run.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""Explicit local/service launcher. --check validates config, not live integrations.""" +import argparse +import json +import os +from pathlib import Path +import runpy +import sys + +ROOT = Path(__file__).resolve().parents[1] +COMPONENTS = { + "bot": "bot/grok_bot.py", + "miniapp": "bot/webapp/server.py", + "gateway": "gateway/grok-web-skin.py", +} +CONFIG_KEYS = ("GROK_BOT_CFG", "GROK_BOT_CONFIG", "GATE_BOT_CONFIG") +PATH_GROUPS = ( + (("IISHKO_BOT_DB", "GROK_BOT_DB", "GATE_BOT_DB"), "bot_db", "/opt/grok-bot/bot.db"), + (("IISHKO_GW_DB", "GATE_NEWAPI_DB"), "newapi_db", "/opt/grok-gateway/new-api/one-api.db"), + (("IISHKO_SKIN_DB", "GATE_TG_DB"), None, "/opt/grok-web-skin-tg.db"), +) + + +def _pick(keys, process, file_values, default): + # A service/environment alias beats a canonical value in the optional file. + for layer in (process, file_values): + for key in keys: + if layer.get(key): + return layer[key] + return default + + +def _path(root, value): + path = Path(value).expanduser() + return str((root / path).resolve()) + + +def prepare_environment(root=ROOT, env_file=None, process=None): + root = Path(root).resolve() + process = dict(os.environ if process is None else process) + explicit = env_file is not None + path = Path(env_file).expanduser() if explicit else root / ".env" + if not path.is_absolute(): + path = root / path + file_values = {} + if path.exists(): + from dotenv import dotenv_values + # No shell evaluation, parent-file discovery or secret interpolation. + file_values = {key: value for key, value in dotenv_values( + path, encoding="utf-8-sig", interpolate=False).items() if value is not None} + elif explicit: + raise ValueError("explicit environment file does not exist") + env = {**file_values, **process} + config_path = _path(root, _pick(CONFIG_KEYS, process, file_values, "bot/config.json")) + for key in CONFIG_KEYS: + env[key] = config_path + config = {} + try: + with open(config_path, encoding="utf-8-sig") as source: + loaded = json.load(source) + if isinstance(loaded, dict): + config = loaded + except (OSError, ValueError): + pass # check_configuration reports the config error without exposing values. + for keys, config_key, default in PATH_GROUPS: + fallback = config.get(config_key) or default + value = _path(root, _pick(keys, process, file_values, fallback)) + for key in keys: + env[key] = value + env["IISHKO_APP_ROOT"] = _path(root, _pick(("IISHKO_APP_ROOT",), process, file_values, "bot")) + for name in ("TG_SID_SECRET_FILE", "IISHKO_BOT_SOURCE", "IISHKO_PROVIDERS_FILE", "IISHKO_ECON_STATE"): + if env.get(name): + env[name] = _path(root, env[name]) + upstream = _pick(("IISHKO_UPSTREAM", "NEWAPI_URL"), process, file_values, + config.get("newapi_url")) + if upstream: + env["IISHKO_UPSTREAM"] = env["NEWAPI_URL"] = upstream + module_dirs = [env["IISHKO_APP_ROOT"], str(root / "gateway"), str(root / "bot/webapp")] + env["IISHKO_RUNTIME_PATHS"] = os.pathsep.join(module_dirs) + # Do not inherit a POSIX-only PYTHONPATH from the distributed .env template. + env["PYTHONPATH"] = os.pathsep.join(module_dirs) + return env + + +def check_configuration(env): + problems = [] + try: + with open(env["GROK_BOT_CFG"], encoding="utf-8-sig") as source: + config = json.load(source) + except (OSError, ValueError): + return ["bot config is missing, unreadable or invalid JSON (GROK_BOT_CFG)"] + if not isinstance(config, dict): + return ["bot config must be a JSON object"] + for key, name in (("bot_token", "GROK_BOT_TOKEN"), ("newapi_pass", "NEWAPI_PASS")): + if env.get(name): + config[key] = env[name] + for key in ("bot_token", "main_key", "channel_username", "newapi_pass"): + value = config.get(key) + if not isinstance(value, str) or not value.strip() or "REPLACE_ME" in value or "your_" in value: + problems.append("bot config requires a real value for " + key) + if not Path(env["IISHKO_APP_ROOT"]).is_dir(): + problems.append("IISHKO_APP_ROOT must be an existing bot module directory") + if not Path(env["IISHKO_GW_DB"]).is_file(): + problems.append("IISHKO_GW_DB must point to your existing New API SQLite database") + for key in ("IISHKO_BOT_DB", "IISHKO_SKIN_DB"): + path = Path(env[key]) + if (path.exists() and not path.is_file()) or not path.parent.is_dir(): + problems.append(key + " must name a file in an existing data directory") + return problems + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("component", choices=COMPONENTS) + parser.add_argument("--env-file", help="explicit dotenv file; real environment takes priority") + parser.add_argument("--check", action="store_true", help="offline config preflight, not an app smoke test") + args = parser.parse_args(argv) + try: + env = prepare_environment(env_file=args.env_file) + problems = check_configuration(env) + except (OSError, ValueError, ImportError): + problems = ["environment setup failed; check the env file and installed requirements"] + if problems: + for problem in problems: + print("ERROR: " + problem, file=sys.stderr) + return 2 + if args.check: + print("Configuration preflight passed; no app started or integrations checked.") + return 0 + os.environ.update(env) + os.chdir(ROOT) + target = ROOT / COMPONENTS[args.component] + sys.path[:0] = [str(target.parent), *env["IISHKO_RUNTIME_PATHS"].split(os.pathsep)] + sys.argv = [str(target)] + runpy.run_path(str(target), run_name="__main__") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/selfcheck.py b/scripts/selfcheck.py index 87763721..04a24ae5 100644 --- a/scripts/selfcheck.py +++ b/scripts/selfcheck.py @@ -149,13 +149,13 @@ def check_config_templates(problems, notes): notes.append("config template absent (optional): %s" % rel) continue try: - json.load(open(path, encoding="utf-8")) + json.load(open(path, encoding="utf-8-sig")) except ValueError as exc: problems.append("invalid JSON template %s: %s" % (rel, exc)) cfg = os.environ.get("GROK_BOT_CFG") or os.path.join(ROOT, "bot", "config.json") if os.path.isfile(cfg): try: - data = json.load(open(cfg, encoding="utf-8")) + data = json.load(open(cfg, encoding="utf-8-sig")) placeholders = sorted(k for k, v in data.items() if isinstance(v, str) and ("REPLACE_ME" in v or "your_" in v)) if placeholders: diff --git a/site/assets/main-D1LzJ0TE.css b/site/assets/main-D1LzJ0TE.css deleted file mode 100644 index fb492c4a..00000000 --- a/site/assets/main-D1LzJ0TE.css +++ /dev/null @@ -1,2 +0,0 @@ -/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */ -@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-space-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-animation-delay:0s;--tw-animation-direction:normal;--tw-animation-duration:initial;--tw-animation-fill-mode:none;--tw-animation-iteration-count:1;--tw-enter-blur:0;--tw-enter-opacity:1;--tw-enter-rotate:0;--tw-enter-scale:1;--tw-enter-translate-x:0;--tw-enter-translate-y:0;--tw-exit-blur:0;--tw-exit-opacity:1;--tw-exit-rotate:0;--tw-exit-scale:1;--tw-exit-translate-x:0;--tw-exit-translate-y:0}}}@layer theme{:root,:host{--font-sans:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--container-sm:24rem;--container-md:28rem;--container-xl:36rem;--container-2xl:42rem;--container-3xl:48rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height:calc(1.5 / 1);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-4xl:2.25rem;--text-4xl--line-height:calc(2.5 / 2.25);--text-5xl:3rem;--text-5xl--line-height:1;--font-weight-medium:500;--font-weight-semibold:600;--tracking-tight:-.025em;--leading-tight:1.25;--leading-relaxed:1.625;--radius-2xl:1rem;--ease-in-out:cubic-bezier(.4, 0, .2, 1);--animate-spin:spin 1s linear infinite;--animate-pulse:pulse 2s cubic-bezier(.4, 0, .6, 1) infinite;--blur-sm:8px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}*{border-color:var(--border)}html{--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark;scroll-behavior:smooth}body{background-color:var(--background);min-height:100vh;color:var(--foreground);-webkit-font-smoothing:antialiased;text-rendering:optimizelegibility;margin:0;font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,Inter,Helvetica Neue,Arial,Noto Sans,sans-serif}h1,h2,h3,h4{letter-spacing:-.01em;font-weight:600}a{color:inherit;text-decoration:none}::selection{background:var(--primary)}@supports (color:color-mix(in lab, red, red)){::selection{background:color-mix(in oklab, var(--primary) 35%, transparent)}}}@layer components;@layer utilities{.pointer-events-none{pointer-events:none}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.sticky{position:sticky}.inset-0{inset:0}.inset-x-0{inset-inline:0}.inset-y-0{inset-block:0}.top-0{top:0}.top-1\/2{top:50%}.top-4{top:calc(var(--spacing) * 4)}.right-0{right:0}.right-4{right:calc(var(--spacing) * 4)}.bottom-0{bottom:0}.left-0{left:0}.left-3{left:calc(var(--spacing) * 3)}.z-40{z-index:40}.z-50{z-index:50}.container{width:100%}@media (width>=40rem){.container{max-width:40rem}}@media (width>=48rem){.container{max-width:48rem}}@media (width>=64rem){.container{max-width:64rem}}@media (width>=80rem){.container{max-width:80rem}}@media (width>=96rem){.container{max-width:96rem}}.mx-auto{margin-inline:auto}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-6{margin-top:calc(var(--spacing) * 6)}.mt-8{margin-top:calc(var(--spacing) * 8)}.mt-10{margin-top:calc(var(--spacing) * 10)}.mt-12{margin-top:calc(var(--spacing) * 12)}.mt-16{margin-top:calc(var(--spacing) * 16)}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline-flex{display:inline-flex}.table{display:table}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-6{height:calc(var(--spacing) * 6)}.h-8{height:calc(var(--spacing) * 8)}.h-9{height:calc(var(--spacing) * 9)}.h-10{height:calc(var(--spacing) * 10)}.h-11{height:calc(var(--spacing) * 11)}.h-12{height:calc(var(--spacing) * 12)}.h-16{height:calc(var(--spacing) * 16)}.h-full{height:100%}.min-h-\[70vh\]{min-height:70vh}.min-h-screen{min-height:100vh}.w-3\/4{width:75%}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-6{width:calc(var(--spacing) * 6)}.w-8{width:calc(var(--spacing) * 8)}.w-10{width:calc(var(--spacing) * 10)}.w-12{width:calc(var(--spacing) * 12)}.w-72{width:calc(var(--spacing) * 72)}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-3xl{max-width:var(--container-3xl)}.max-w-md{max-width:var(--container-md)}.max-w-sm{max-width:var(--container-sm)}.max-w-xl{max-width:var(--container-xl)}.min-w-0{min-width:0}.flex-1{flex:1}.shrink-0{flex-shrink:0}.-translate-y-1\/2{--tw-translate-y:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.animate-pulse{animation:var(--animate-pulse)}.animate-spin{animation:var(--animate-spin)}.list-decimal{list-style-type:decimal}.flex-col{flex-direction:column}.place-items-center{place-items:center}.items-center{align-items:center}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-2{gap:calc(var(--spacing) * 2)}.gap-2\.5{gap:calc(var(--spacing) * 2.5)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-6{gap:calc(var(--spacing) * 6)}.gap-8{gap:calc(var(--spacing) * 8)}:where(.space-y-1\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1.5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1.5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-full{border-radius:2147483647px}.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:calc(var(--radius) + 4px)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-border,.border-border\/60{border-color:var(--border)}@supports (color:color-mix(in lab, red, red)){.border-border\/60{border-color:color-mix(in oklab, var(--border) 60%, transparent)}}.border-border\/70{border-color:var(--border)}@supports (color:color-mix(in lab, red, red)){.border-border\/70{border-color:color-mix(in oklab, var(--border) 70%, transparent)}}.border-destructive\/40{border-color:var(--destructive)}@supports (color:color-mix(in lab, red, red)){.border-destructive\/40{border-color:color-mix(in oklab, var(--destructive) 40%, transparent)}}.border-input{border-color:var(--input)}.border-transparent{border-color:#0000}.bg-background,.bg-background\/80{background-color:var(--background)}@supports (color:color-mix(in lab, red, red)){.bg-background\/80{background-color:color-mix(in oklab, var(--background) 80%, transparent)}}.bg-black\/60{background-color:#0009}@supports (color:color-mix(in lab, red, red)){.bg-black\/60{background-color:color-mix(in oklab, var(--color-black) 60%, transparent)}}.bg-card,.bg-card\/40{background-color:var(--card)}@supports (color:color-mix(in lab, red, red)){.bg-card\/40{background-color:color-mix(in oklab, var(--card) 40%, transparent)}}.bg-destructive{background-color:var(--destructive)}.bg-muted,.bg-muted\/40{background-color:var(--muted)}@supports (color:color-mix(in lab, red, red)){.bg-muted\/40{background-color:color-mix(in oklab, var(--muted) 40%, transparent)}}.bg-primary,.bg-primary\/15{background-color:var(--primary)}@supports (color:color-mix(in lab, red, red)){.bg-primary\/15{background-color:color-mix(in oklab, var(--primary) 15%, transparent)}}.bg-secondary{background-color:var(--secondary)}.bg-transparent{background-color:#0000}.p-0{padding:0}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-5{padding-inline:calc(var(--spacing) * 5)}.px-6{padding-inline:calc(var(--spacing) * 6)}.px-7{padding-inline:calc(var(--spacing) * 7)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-6{padding-block:calc(var(--spacing) * 6)}.py-10{padding-block:calc(var(--spacing) * 10)}.py-12{padding-block:calc(var(--spacing) * 12)}.py-14{padding-block:calc(var(--spacing) * 14)}.py-16{padding-block:calc(var(--spacing) * 16)}.py-20{padding-block:calc(var(--spacing) * 20)}.pt-0{padding-top:0}.pt-6{padding-top:calc(var(--spacing) * 6)}.pr-3{padding-right:calc(var(--spacing) * 3)}.pb-4{padding-bottom:calc(var(--spacing) * 4)}.pb-20{padding-bottom:calc(var(--spacing) * 20)}.pb-24{padding-bottom:calc(var(--spacing) * 24)}.pl-5{padding-left:calc(var(--spacing) * 5)}.pl-9{padding-left:calc(var(--spacing) * 9)}.text-center{text-align:center}.text-left{text-align:left}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading,var(--text-4xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.leading-none{--tw-leading:1;line-height:1}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.break-all{word-break:break-all}.whitespace-nowrap{white-space:nowrap}.text-card-foreground{color:var(--card-foreground)}.text-destructive{color:var(--destructive)}.text-foreground{color:var(--foreground)}.text-muted-foreground{color:var(--muted-foreground)}.text-primary{color:var(--primary)}.text-primary-foreground{color:var(--primary-foreground)}.text-secondary-foreground{color:var(--secondary-foreground)}.text-white{color:var(--color-white)}.underline-offset-4{text-underline-offset:4px}.opacity-70{opacity:.7}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-offset-background{--tw-ring-offset-color:var(--background)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.backdrop-blur{--tw-backdrop-blur:blur(8px);-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,)}.backdrop-blur-sm{--tw-backdrop-blur:blur(var(--blur-sm));-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-200{--tw-duration:.2s;transition-duration:.2s}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.outline-none{--tw-outline-style:none;outline-style:none}.last\:border-0:last-child{border-style:var(--tw-border-style);border-width:0}@media (hover:hover){.hover\:bg-accent:hover{background-color:var(--accent)}.hover\:bg-destructive\/90:hover{background-color:var(--destructive)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-destructive\/90:hover{background-color:color-mix(in oklab, var(--destructive) 90%, transparent)}}.hover\:bg-primary\/88:hover{background-color:var(--primary)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-primary\/88:hover{background-color:color-mix(in oklab, var(--primary) 88%, transparent)}}.hover\:bg-secondary\/80:hover{background-color:var(--secondary)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-secondary\/80:hover{background-color:color-mix(in oklab, var(--secondary) 80%, transparent)}}.hover\:text-accent-foreground:hover{color:var(--accent-foreground)}.hover\:text-foreground:hover{color:var(--foreground)}.hover\:text-primary:hover{color:var(--primary)}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}}.focus\:ring-2:focus{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus\:ring-ring:focus{--tw-ring-color:var(--ring)}.focus\:ring-offset-2:focus{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.focus-visible\:ring-2:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus-visible\:ring-ring:focus-visible{--tw-ring-color:var(--ring)}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus-visible\:ring-offset-background:focus-visible{--tw-ring-offset-color:var(--background)}.focus-visible\:outline-none:focus-visible{--tw-outline-style:none;outline-style:none}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:opacity-50:disabled{opacity:.5}.data-\[state\=closed\]\:animate-accordion-up[data-state=closed]{animation:.2s ease-out accordion-up}.data-\[state\=closed\]\:animate-out[data-state=closed]{animation:exit var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=closed\]\:duration-300[data-state=closed]{--tw-duration:.3s;transition-duration:.3s}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity:0}.data-\[state\=closed\]\:slide-out-to-bottom[data-state=closed]{--tw-exit-translate-y:100%}.data-\[state\=closed\]\:slide-out-to-left[data-state=closed]{--tw-exit-translate-x:-100%}.data-\[state\=closed\]\:slide-out-to-right[data-state=closed]{--tw-exit-translate-x:100%}.data-\[state\=closed\]\:slide-out-to-top[data-state=closed]{--tw-exit-translate-y:-100%}.data-\[state\=open\]\:animate-accordion-down[data-state=open]{animation:.2s ease-out accordion-down}.data-\[state\=open\]\:animate-in[data-state=open]{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=open\]\:duration-500[data-state=open]{--tw-duration:.5s;transition-duration:.5s}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity:0}.data-\[state\=open\]\:slide-in-from-bottom[data-state=open]{--tw-enter-translate-y:100%}.data-\[state\=open\]\:slide-in-from-left[data-state=open]{--tw-enter-translate-x:-100%}.data-\[state\=open\]\:slide-in-from-right[data-state=open]{--tw-enter-translate-x:100%}.data-\[state\=open\]\:slide-in-from-top[data-state=open]{--tw-enter-translate-y:-100%}@media (width>=40rem){.sm\:ml-auto{margin-left:auto}.sm\:max-w-sm{max-width:var(--container-sm)}.sm\:max-w-xs{max-width:var(--container-xs)}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:p-10{padding:calc(var(--spacing) * 10)}.sm\:py-20{padding-block:calc(var(--spacing) * 20)}.sm\:py-28{padding-block:calc(var(--spacing) * 28)}.sm\:text-5xl{font-size:var(--text-5xl);line-height:var(--tw-leading,var(--text-5xl--line-height))}.sm\:text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}}@media (width>=48rem){.md\:block{display:block}.md\:flex{display:flex}.md\:hidden{display:none}}@media (width>=64rem){.lg\:col-span-2{grid-column:span 2/span 2}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}.\[\&_svg\]\:pointer-events-none svg{pointer-events:none}.\[\&_svg\]\:size-4 svg{width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.\[\&_svg\]\:shrink-0 svg{flex-shrink:0}.\[\&\[data-state\=open\]\>svg\]\:rotate-180[data-state=open]>svg{rotate:180deg}.container-x{width:100%;max-width:80rem;margin-inline:auto;padding-inline:1.25rem}@media (width>=640px){.container-x{padding-inline:2rem}}.prose-docs{color:var(--foreground);line-height:1.7}.prose-docs h3{margin-top:1.75rem;margin-bottom:.5rem;font-size:1.125rem}.prose-docs p{color:var(--foreground);margin:.75rem 0}@supports (color:color-mix(in lab, red, red)){.prose-docs p{color:color-mix(in oklab, var(--foreground) 82%, var(--muted-foreground))}}.prose-docs code{background:var(--muted);border:1px solid var(--border);border-radius:.375rem;padding:.1rem .35rem;font-family:ui-monospace,SFMono-Regular,Cascadia Code,Menlo,Consolas,monospace;font-size:.85em}}@property --tw-animation-delay{syntax:"*";inherits:false;initial-value:0s}@property --tw-animation-direction{syntax:"*";inherits:false;initial-value:normal}@property --tw-animation-duration{syntax:"*";inherits:false}@property --tw-animation-fill-mode{syntax:"*";inherits:false;initial-value:none}@property --tw-animation-iteration-count{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-blur{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-opacity{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-rotate{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-scale{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-blur{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-opacity{syntax:"*";inherits:false;initial-value:1}@property --tw-exit-rotate{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-scale{syntax:"*";inherits:false;initial-value:1}@property --tw-exit-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-translate-y{syntax:"*";inherits:false;initial-value:0}:root{--radius:.625rem;--background:oklch(16% .018 240);--foreground:oklch(97% .01 210);--card:oklch(20.5% .02 240);--card-foreground:oklch(97% .01 210);--popover:oklch(20.5% .022 240);--popover-foreground:oklch(97% .01 210);--primary:oklch(78% .13 214);--primary-foreground:oklch(16% .02 240);--secondary:oklch(26% .022 240);--secondary-foreground:oklch(96% .01 210);--muted:oklch(24.5% .02 240);--muted-foreground:oklch(72% .02 220);--accent:oklch(28% .03 216);--accent-foreground:oklch(97% .01 210);--destructive:oklch(64% .21 25);--border:oklch(31% .022 240);--input:oklch(33% .022 240);--ring:oklch(78% .13 214)}.dark{--background:oklch(16% .018 240);--foreground:oklch(97% .01 210);--card:oklch(20.5% .02 240);--card-foreground:oklch(97% .01 210);--popover:oklch(20.5% .022 240);--popover-foreground:oklch(97% .01 210);--primary:oklch(78% .13 214);--primary-foreground:oklch(16% .02 240);--secondary:oklch(26% .022 240);--secondary-foreground:oklch(96% .01 210);--muted:oklch(24.5% .02 240);--muted-foreground:oklch(72% .02 220);--accent:oklch(28% .03 216);--accent-foreground:oklch(97% .01 210);--destructive:oklch(64% .21 25);--border:oklch(31% .022 240);--input:oklch(33% .022 240);--ring:oklch(78% .13 214)}@keyframes accordion-down{0%{height:0}to{height:var(--radix-accordion-content-height,var(--bits-accordion-content-height,var(--reka-accordion-content-height,var(--kb-accordion-content-height,var(--ngp-accordion-content-height,auto)))))}}@keyframes accordion-up{0%{height:var(--radix-accordion-content-height,var(--bits-accordion-content-height,var(--reka-accordion-content-height,var(--kb-accordion-content-height,var(--ngp-accordion-content-height,auto)))))}to{height:0}}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}@keyframes pulse{50%{opacity:.5}}@keyframes enter{0%{opacity:var(--tw-enter-opacity,1);transform:translate3d(var(--tw-enter-translate-x,0),var(--tw-enter-translate-y,0),0)scale3d(var(--tw-enter-scale,1),var(--tw-enter-scale,1),var(--tw-enter-scale,1))rotate(var(--tw-enter-rotate,0));filter:blur(var(--tw-enter-blur,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));filter:blur(var(--tw-exit-blur,0))}} diff --git a/site/assets/main-q3GI4PiK.js b/site/assets/main-q3GI4PiK.js deleted file mode 100644 index 9eff04f2..00000000 --- a/site/assets/main-q3GI4PiK.js +++ /dev/null @@ -1,52 +0,0 @@ -var yp=Object.create,Oh=Object.defineProperty,bp=Object.getOwnPropertyDescriptor,pp=Object.getOwnPropertyNames,Sp=Object.getPrototypeOf,zh=Object.prototype.hasOwnProperty,_l=(i,c)=>()=>(c||(i((c={exports:{}}).exports,c),i=null),c.exports),xp=(i,c,r,f)=>{if(c&&typeof c=="object"||typeof c=="function")for(var s=pp(c),v=0,h=s.length,p;vc[A]).bind(null,p),enumerable:!(f=bp(c,p))||f.enumerable});return i},Rh=(i,c,r)=>(r=i!=null?yp(Sp(i)):{},xp(c||!i||!i.__esModule||!zh.call(i,"default")?Oh(r,"default",{value:i,enumerable:!0}):r,i)),Ep=_l((i=>{function c(q,ce){var ae=q.length;q.push(ce);e:for(;0>>1,K=q[xe];if(0>>1;xes(Pt,ae))vts(x,Pt)?(q[xe]=x,q[vt]=ae,xe=vt):(q[xe]=Pt,q[pt]=ae,xe=pt);else if(vts(x,ae))q[xe]=x,q[vt]=ae,xe=vt;else break e}}return ce}function s(q,ce){var ae=q.sortIndex-ce.sortIndex;return ae!==0?ae:q.id-ce.id}if(i.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var v=performance;i.unstable_now=function(){return v.now()}}else{var h=Date,p=h.now();i.unstable_now=function(){return h.now()-p}}var A=[],C=[],H=1,E=null,g=3,D=!1,G=!1,M=!1,L=!1,V=typeof setTimeout=="function"?setTimeout:null,X=typeof clearTimeout=="function"?clearTimeout:null,B=typeof setImmediate<"u"?setImmediate:null;function Z(q){for(var ce=r(C);ce!==null;){if(ce.callback===null)f(C);else if(ce.startTime<=q)f(C),ce.sortIndex=ce.expirationTime,c(A,ce);else break;ce=r(C)}}function ue(q){if(M=!1,Z(q),!G)if(r(A)!==null)G=!0,ee||(ee=!0,se());else{var ce=r(C);ce!==null&&De(ue,ce.startTime-q)}}var ee=!1,W=-1,w=5,ne=-1;function He(){return L?!0:!(i.unstable_now()-neq&&He());){var xe=E.callback;if(typeof xe=="function"){E.callback=null,g=E.priorityLevel;var K=xe(E.expirationTime<=q);if(q=i.unstable_now(),typeof K=="function"){E.callback=K,Z(q),ce=!0;break t}E===r(A)&&f(A),Z(q)}else f(A);E=r(A)}if(E!==null)ce=!0;else{var Je=r(C);Je!==null&&De(ue,Je.startTime-q),ce=!1}}break e}finally{E=null,g=ae,D=!1}ce=void 0}}finally{ce?se():ee=!1}}}var se;if(typeof B=="function")se=function(){B(Ce)};else if(typeof MessageChannel<"u"){var ke=new MessageChannel,Fe=ke.port2;ke.port1.onmessage=Ce,se=function(){Fe.postMessage(null)}}else se=function(){V(Ce,0)};function De(q,ce){W=V(function(){q(i.unstable_now())},ce)}i.unstable_IdlePriority=5,i.unstable_ImmediatePriority=1,i.unstable_LowPriority=4,i.unstable_NormalPriority=3,i.unstable_Profiling=null,i.unstable_UserBlockingPriority=2,i.unstable_cancelCallback=function(q){q.callback=null},i.unstable_forceFrameRate=function(q){0>q||125xe?(q.sortIndex=ae,c(C,q),r(A)===null&&q===r(C)&&(M?(X(W),W=-1):M=!0,De(ue,ae-xe))):(q.sortIndex=K,c(A,q),G||D||(G=!0,ee||(ee=!0,se()))),q},i.unstable_shouldYield=He,i.unstable_wrapCallback=function(q){var ce=g;return function(){var ae=g;g=ce;try{return q.apply(this,arguments)}finally{g=ae}}}})),Tp=_l(((i,c)=>{c.exports=Ep()})),_p=_l((i=>{var c=Symbol.for("react.transitional.element"),r=Symbol.for("react.portal"),f=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),v=Symbol.for("react.profiler"),h=Symbol.for("react.consumer"),p=Symbol.for("react.context"),A=Symbol.for("react.forward_ref"),C=Symbol.for("react.suspense"),H=Symbol.for("react.memo"),E=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),D=Symbol.for("react.view_transition"),G=Symbol.iterator;function M(x){return x===null||typeof x!="object"?null:(x=G&&x[G]||x["@@iterator"],typeof x=="function"?x:null)}var L={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},V=Object.assign,X={};function B(x,Y,P){this.props=x,this.context=Y,this.refs=X,this.updater=P||L}B.prototype.isReactComponent={},B.prototype.setState=function(x,Y){if(typeof x!="object"&&typeof x!="function"&&x!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,x,Y,"setState")},B.prototype.forceUpdate=function(x){this.updater.enqueueForceUpdate(this,x,"forceUpdate")};function Z(){}Z.prototype=B.prototype;function ue(x,Y,P){this.props=x,this.context=Y,this.refs=X,this.updater=P||L}var ee=ue.prototype=new Z;ee.constructor=ue,V(ee,B.prototype),ee.isPureReactComponent=!0;var W=Array.isArray;function w(){}var ne={H:null,A:null,T:null,S:null},He=Object.prototype.hasOwnProperty;function Ce(x,Y,P){var te=P.ref;return{$$typeof:c,type:x,key:Y,ref:te!==void 0?te:null,props:P}}function se(x,Y){return Ce(x.type,Y,x.props)}function ke(x){return typeof x=="object"&&x!==null&&x.$$typeof===c}function Fe(x){var Y={"=":"=0",":":"=2"};return"$"+x.replace(/[=:]/g,function(P){return Y[P]})}var De=/\/+/g;function q(x,Y){return typeof x=="object"&&x!==null&&x.key!=null?Fe(""+x.key):Y.toString(36)}function ce(x){switch(x.status){case"fulfilled":return x.value;case"rejected":throw x.reason;default:switch(typeof x.status=="string"?x.then(w,w):(x.status="pending",x.then(function(Y){x.status==="pending"&&(x.status="fulfilled",x.value=Y)},function(Y){x.status==="pending"&&(x.status="rejected",x.reason=Y)})),x.status){case"fulfilled":return x.value;case"rejected":throw x.reason}}throw x}function ae(x,Y,P,te,ie){var Se=typeof x;(Se==="undefined"||Se==="boolean")&&(x=null);var ye=!1;if(x===null)ye=!0;else switch(Se){case"bigint":case"string":case"number":ye=!0;break;case"object":switch(x.$$typeof){case c:case r:ye=!0;break;case E:return ye=x._init,ae(ye(x._payload),Y,P,te,ie)}}if(ye)return ie=ie(x),ye=te===""?"."+q(x,0):te,W(ie)?(P="",ye!=null&&(P=ye.replace(De,"$&/")+"/"),ae(ie,Y,P,"",function(St){return St})):ie!=null&&(ke(ie)&&(ie=se(ie,P+(ie.key==null||x&&x.key===ie.key?"":(""+ie.key).replace(De,"$&/")+"/")+ye)),Y.push(ie)),1;ye=0;var $=te===""?".":te+":";if(W(x))for(var re=0;re{c.exports=_p()})),Np=_l((i=>{var c=hf();function r(E){var g="https://react.dev/errors/"+E;if(1{function r(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(r)}catch(f){console.error(f)}}r(),c.exports=Np()})),Cp=_l((i=>{var c=Tp(),r=hf(),f=Dh();function s(e){var t="https://react.dev/errors/"+e;if(1ta||(e.current=cr[ta],cr[ta]=null,ta--)}function Me(e,t){ta++,cr[ta]=e.current,e.current=t}var ol=rl(null),nu=rl(null),kl=rl(null),fi=rl(null);function di(e,t){switch(Me(kl,t),Me(nu,e),Me(ol,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?o0(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=o0(t),e=s0(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}at(ol),Me(ol,e)}function la(){at(ol),at(nu),at(kl)}function rr(e){var t=e.memoizedState;t!==null&&(Va._currentValue=t.memoizedState,Me(fi,e)),t=ol.current;var l=s0(t,e.type);t!==l&&(Me(nu,e),Me(ol,l))}function mi(e){nu.current===e&&(at(ol),at(nu)),fi.current===e&&(at(fi),Va._currentValue=St)}var or,jf;function Jl(e){if(or===void 0)try{throw Error()}catch(l){var t=l.stack.trim().match(/\n( *(at )?)/);or=t&&t[1]||"",jf=-1)":-1a||y[n]!==N[a]){var R=` -`+y[n].replace(" at new "," at ");return e.displayName&&R.includes("")&&(R=R.replace("",e.displayName)),R}while(1<=n&&0<=a);break}}}finally{sr=!1,Error.prepareStackTrace=l}return(l=e?e.displayName||e.name:"")?Jl(l):""}function Ry(e,t){switch(e.tag){case 26:case 27:case 5:return Jl(e.type);case 16:return Jl("Lazy");case 13:return e.child!==t&&t!==null?Jl("Suspense Fallback"):Jl("Suspense");case 19:return Jl("SuspenseList");case 0:case 15:return fr(e.type,!1);case 11:return fr(e.type.render,!1);case 1:return fr(e.type,!0);case 31:return Jl("Activity");case 30:return Jl("ViewTransition");default:return""}}function Mf(e){try{var t="",l=null;do t+=Ry(e,l),l=e,e=e.return;while(e);return t}catch(n){return` -Error generating stack: `+n.message+` -`+n.stack}}var dr=Object.prototype.hasOwnProperty,mr=c.unstable_scheduleCallback,vr=c.unstable_cancelCallback,Dy=c.unstable_shouldYield,jy=c.unstable_requestPaint,zt=c.unstable_now,My=c.unstable_getCurrentPriorityLevel,wf=c.unstable_ImmediatePriority,Uf=c.unstable_UserBlockingPriority,vi=c.unstable_NormalPriority,wy=c.unstable_LowPriority,Hf=c.unstable_IdlePriority,Uy=c.log,Hy=c.unstable_setDisableYieldValue,au=null,Rt=null;function Il(e){if(typeof Uy=="function"&&Hy(e),Rt&&typeof Rt.setStrictMode=="function")try{Rt.setStrictMode(au,e)}catch{}}var Dt=Math.clz32?Math.clz32:Yy,By=Math.log,Ly=Math.LN2;function Yy(e){return e>>>=0,e===0?32:31-(By(e)/Ly|0)|0}var hi=256,gi=262144,yi=4194304;function On(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&-e;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function bi(e,t,l){var n=e.pendingLanes;if(n===0)return 0;var a=0,u=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var d=n&134217727;return d!==0?(n=d&~u,n!==0?a=On(n):(o&=d,o!==0?a=On(o):l||(l=d&~e,l!==0&&(a=On(l))))):(d=n&~u,d!==0?a=On(d):o!==0?a=On(o):l||(l=n&~e,l!==0&&(a=On(l)))),a===0?0:t!==0&&t!==a&&(t&u)===0&&(u=a&-a,l=t&-t,u>=l||u===32&&(l&4194048)!==0)?t:a}function uu(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Bf(e,t){(t&8)!==0&&(t|=t&32);var l=e.entangledLanes;if(l!==0)for(e=e.entanglements,l&=t;0l;l++)t.push(e);return t}function iu(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function qy(e,t,l,n,a,u){var o=e.pendingLanes;e.pendingLanes=l,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=l,e.entangledLanes&=l,e.errorRecoveryDisabledLanes&=l,e.shellSuspendCounter=0;var d=e.entanglements,y=e.expirationTimes,N=e.hiddenUpdates;for(l=o&~l;0"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Nr=!1;if(Ol)try{var fu={};Object.defineProperty(fu,"passive",{get:function(){Nr=!0}}),window.addEventListener("test",fu,fu),window.removeEventListener("test",fu,fu)}catch{Nr=!1}var $l=null,Cr=null,_i=null;function cd(){if(_i)return _i;var e,t=Cr,l=t.length,n,a="value"in $l?$l.value:$l.textContent,u=a.length;for(e=0;e=vu),md=" ",vd=!1;function hd(e,t){switch(e){case"keyup":return f1.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function gd(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var sa=!1;function m1(e,t){switch(e){case"compositionend":return gd(t);case"keypress":return t.which!==32?null:(vd=!0,md);case"textInput":return e=t.data,e===md&&vd?null:e;default:return null}}function v1(e,t){if(sa)return e==="compositionend"||!Dr&&hd(e,t)?(e=cd(),_i=Cr=$l=null,sa=!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"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function _d(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function Nd(e,t){var l=_d(e);e=0;for(var n;l;){if(l.nodeType===3){if(n=e+l.textContent.length,e<=t&&n>=t)return{node:l,offset:t-e};e=n}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=_d(l)}}function Cd(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Cd(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Ad(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=wr(e.document);t instanceof e.HTMLIFrameElement;){try{var l=typeof t.contentWindow.location.href=="string"}catch{l=!1}if(l)e=t.contentWindow;else break;t=wr(e.document)}return t}function Ur(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")}var E1=Ol&&"documentMode"in document&&11>=document.documentMode,fa=null,Hr=null,bu=null,Br=!1;function Od(e,t,l){var n=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;Br||fa==null||fa!==wr(n)||(n=fa,"selectionStart"in n&&Ur(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),bu&&yu(bu,n)||(bu=n,n=zc(Hr,"onSelect"),0>=o,a-=o,fl=1<<32-Dt(t)+a|l<oe?(Ze=le,le=null):Ze=le.sibling;var Ee=T(_,le,O[oe],j);if(Ee===null){le===null&&(le=Ze);break}e&&le&&Ee.alternate===null&&t(_,le),S=u(Ee,S,oe),pe===null?k=Ee:pe.sibling=Ee,pe=Ee,le=Ze}if(oe===O.length)return l(_,le),me&&jl(_,oe),k;if(le===null){for(;oeoe?(Ze=le,le=null):Ze=le.sibling;var En=T(_,le,Ee.value,j);if(En===null){le===null&&(le=Ze);break}e&&le&&En.alternate===null&&t(_,le),S=u(En,S,oe),pe===null?k=En:pe.sibling=En,pe=En,le=Ze}if(Ee.done)return l(_,le),me&&jl(_,oe),k;if(le===null){for(;!Ee.done;oe++,Ee=O.next())Ee=U(_,Ee.value,j),Ee!==null&&(S=u(Ee,S,oe),pe===null?k=Ee:pe.sibling=Ee,pe=Ee);return me&&jl(_,oe),k}for(le=n(le);!Ee.done;oe++,Ee=O.next())Ee=z(le,_,oe,Ee.value,j),Ee!==null&&(e&&(Ze=Ee.alternate,Ze!==null&&le.delete(Ze.key===null?oe:Ze.key)),S=u(Ee,S,oe),pe===null?k=Ee:pe.sibling=Ee,pe=Ee);return e&&le.forEach(function(gp){return t(_,gp)}),me&&jl(_,oe),k}function de(_,S,O,j){if(typeof O=="object"&&O!==null&&O.type===se&&O.key===null&&O.props.ref===void 0&&(O=O.props.children),typeof O=="object"&&O!==null){switch(O.$$typeof){case He:e:{for(var k=O.key;S!==null;){if(S.key===k){if(k=O.type,k===se){if(S.tag===7){l(_,S.sibling),j=a(S,O.props.children),ln(j,O),j.return=_,_=j;break e}}else if(S.elementType===k||typeof k=="object"&&k!==null&&k.$$typeof===Je&&qn(k)===S.type){l(_,S.sibling),j=a(S,O.props),ln(j,O),j.return=_,_=j;break e}l(_,S);break}else t(_,S);S=S.sibling}O.type===se?(j=wn(O.props.children,_.mode,j,O.key),ln(j,O),j.return=_,_=j):(j=wi(O.type,O.key,O.props,null,_.mode,j),ln(j,O),j.return=_,_=j)}return o(_);case Ce:e:{for(k=O.key;S!==null;){if(S.key===k)if(S.tag===4&&S.stateNode.containerInfo===O.containerInfo&&S.stateNode.implementation===O.implementation){l(_,S.sibling),j=a(S,O.children||[]),j.return=_,_=j;break e}else{l(_,S);break}else t(_,S);S=S.sibling}j=Qr(O,_.mode,j),j.return=_,_=j}return o(_);case Je:return O=qn(O),de(_,S,O,j)}if(ye(O))return Q(_,S,O,j);if(te(O)){if(k=te(O),typeof k!="function")throw Error(s(150));return O=k.call(O),F(_,S,O,j)}if(typeof O.then=="function")return de(_,S,Qi(O),j);if(O.$$typeof===q)return de(_,S,Gi(_,O),j);Zi(_,O)}return typeof O=="string"&&O!==""||typeof O=="number"||typeof O=="bigint"?(O=""+O,S!==null&&S.tag===6?(l(_,S.sibling),j=a(S,O),j.return=_,_=j):(l(_,S),j=Xr(O,_.mode,j),j.return=_,_=j),o(_)):l(_,S)}return function(_,S,O,j){try{_u=0;var k=de(_,S,O,j);return Sa=null,k}catch(le){if(le===pa||le===Vi)throw le;var pe=Et(29,le,null,_.mode);return pe.lanes=j,pe.return=_,pe}}}var Xn=Wd(!0),Pd=Wd(!1),nn=!1;function eo(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function to(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function an(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function un(e,t,l){var n=e.updateQueue;if(n===null)return null;if(n=n.shared,(_e&2)!==0){var a=n.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),n.pending=t,t=Mi(e),Hd(e,null,l),t}return ji(e,n,t,l),Mi(e)}function Nu(e,t,l){if(t=t.updateQueue,t!==null&&(t=t.shared,(l&4194048)!==0)){var n=t.lanes;n&=e.pendingLanes,l|=n,t.lanes=l,Gf(e,l)}}function lo(e,t){var l=e.updateQueue,n=e.alternate;if(n!==null&&(n=n.updateQueue,l===n)){var a=null,u=null;if(l=l.firstBaseUpdate,l!==null){do{var o={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};u===null?a=u=o:u=u.next=o,l=l.next}while(l!==null);u===null?a=u=t:u=u.next=t}else a=u=t;l={baseState:n.baseState,firstBaseUpdate:a,lastBaseUpdate:u,shared:n.shared,callbacks:n.callbacks},e.updateQueue=l;return}e=l.lastBaseUpdate,e===null?l.firstBaseUpdate=t:e.next=t,l.lastBaseUpdate=t}var no=!1;function Cu(){if(no){var e=ba;if(e!==null)throw e}}function Au(e,t,l,n){no=!1;var a=e.updateQueue;nn=!1;var u=a.firstBaseUpdate,o=a.lastBaseUpdate,d=a.shared.pending;if(d!==null){a.shared.pending=null;var y=d,N=y.next;y.next=null,o===null?u=N:o.next=N,o=y;var R=e.alternate;R!==null&&(R=R.updateQueue,d=R.lastBaseUpdate,d!==o&&(d===null?R.firstBaseUpdate=N:d.next=N,R.lastBaseUpdate=y))}if(u!==null){var U=a.baseState;o=0,R=N=y=null,d=u;do{var T=d.lane&-536870913,z=T!==d.lane;if(z?(be&T)===T:(n&T)===T){T!==0&&T===Yn&&(no=!0),R!==null&&(R=R.next={lane:0,tag:d.tag,payload:d.payload,callback:null,next:null});e:{var Q=e,F=d;T=t;var de=l;switch(F.tag){case 1:if(Q=F.payload,typeof Q=="function"){U=Q.call(de,U,T);break e}U=Q;break e;case 3:Q.flags=Q.flags&-65537|128;case 0:if(Q=F.payload,T=typeof Q=="function"?Q.call(de,U,T):Q,T==null)break e;U=w({},U,T);break e;case 2:nn=!0}}T=d.callback,T!==null&&(e.flags|=64,z&&(e.flags|=8192),z=a.callbacks,z===null?a.callbacks=[T]:z.push(T))}else z={lane:T,tag:d.tag,payload:d.payload,callback:d.callback,next:null},R===null?(N=R=z,y=U):R=R.next=z,o|=T;if(d=d.next,d===null){if(d=a.shared.pending,d===null)break;z=d,d=z.next,z.next=null,a.lastBaseUpdate=z,a.shared.pending=null}}while(!0);R===null&&(y=U),a.baseState=y,a.firstBaseUpdate=N,a.lastBaseUpdate=R,u===null&&(a.shared.lanes=0),mn|=o,e.lanes=o,e.memoizedState=U}}function em(e,t){if(typeof e!="function")throw Error(s(191,e));e.call(t)}function tm(e,t){var l=e.callbacks;if(l!==null)for(e.callbacks=null,e=0;eu?u:8;var o=$.T,d={};d.types=o!==null?o.types:null,$.T=d,_o(e,!1,t,l);try{var y=a(),N=$.S;N!==null&&N(d,y),y!==null&&typeof y=="object"&&typeof y.then=="function"?Du(e,t,M1(y,n),Lt(e)):Du(e,t,n,Lt(e))}catch(R){Du(e,t,{then:function(){},status:"rejected",reason:R},Lt())}finally{re.p=u,o!==null&&d.types!==null&&(o.types=d.types),$.T=o}}function Y1(){}function Eo(e,t,l,n){if(e.tag!==5)throw Error(s(476));var a=Mm(e).queue;jm(e,a,t,St,l===null?Y1:function(){return wm(e),l(n)})}function Mm(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:St,baseState:St,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Hl,lastRenderedState:St},next:null};var l={};return t.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Hl,lastRenderedState:l},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function wm(e){var t=Mm(e);t.next===null&&(t=e.alternate.memoizedState),Du(e,t.next.queue,{},Lt())}function To(){return it(Va)}function Um(){return qe().memoizedState}function Hm(){return qe().memoizedState}function G1(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var l=Lt();e=an(l);var n=un(t,e,l);n!==null&&(Ct(n,t,l),Nu(n,t,l)),t={cache:$r()},e.payload=t;return}t=t.return}}function q1(e,t,l){var n=Lt();l={lane:n,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},tc(e)?Lm(t,l):(l=qr(e,t,l,n),l!==null&&(Ct(l,e,n),Ym(l,t,n)))}function Bm(e,t,l){Du(e,t,l,Lt())}function Du(e,t,l,n){var a={lane:n,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(tc(e))Lm(t,a);else{var u=e.alternate;if(e.lanes===0&&(u===null||u.lanes===0)&&(u=t.lastRenderedReducer,u!==null))try{var o=t.lastRenderedState,d=u(o,l);if(a.hasEagerState=!0,a.eagerState=d,Mt(d,o))return ji(e,t,a,0),je===null&&Di(),!1}catch{}if(l=qr(e,t,a,n),l!==null)return Ct(l,e,n),Ym(l,t,n),!0}return!1}function _o(e,t,l,n){if(n={lane:2,revertLane:vs(),gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},tc(e)){if(t)throw Error(s(479))}else t=qr(e,l,n,2),t!==null&&Ct(t,e,2)}function tc(e){var t=e.alternate;return e===fe||t!==null&&t===fe}function Lm(e,t){xa=Ji=!0;var l=e.pending;l===null?t.next=t:(t.next=l.next,l.next=t),e.pending=t}function Ym(e,t,l){if((l&4194048)!==0){var n=t.lanes;n&=e.pendingLanes,l|=n,t.lanes=l,Gf(e,l)}}var lc={readContext:it,use:Fi,useCallback:Ye,useContext:Ye,useEffect:Ye,useImperativeHandle:Ye,useLayoutEffect:Ye,useInsertionEffect:Ye,useMemo:Ye,useReducer:Ye,useRef:Ye,useState:Ye,useDebugValue:Ye,useDeferredValue:Ye,useTransition:Ye,useSyncExternalStore:Ye,useId:Ye,useHostTransitionStatus:Ye,useFormState:Ye,useActionState:Ye,useOptimistic:Ye,useMemoCache:Ye,useCacheRefresh:Ye,useEffectEvent:Ye},Gm={readContext:it,use:Fi,useCallback:function(e,t){return gt().memoizedState=[e,t===void 0?null:t],e},useContext:it,useEffect:Tm,useImperativeHandle:function(e,t,l){l=l!=null?l.concat([e]):null,Pi(4194308,4,Am.bind(null,t,e),l)},useLayoutEffect:function(e,t){return Pi(4194308,4,e,t)},useInsertionEffect:function(e,t){Pi(4,2,e,t)},useMemo:function(e,t){var l=gt();t=t===void 0?null:t;var n=e();if(Qn){Il(!0);try{e()}finally{Il(!1)}}return l.memoizedState=[n,t],n},useReducer:function(e,t,l){var n=gt();if(l!==void 0){var a=l(t);if(Qn){Il(!0);try{l(t)}finally{Il(!1)}}}else a=t;return n.memoizedState=n.baseState=a,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:a},n.queue=e,e=e.dispatch=q1.bind(null,fe,e),[n.memoizedState,e]},useRef:function(e){var t=gt();return e={current:e},t.memoizedState=e},useState:function(e){e=yo(e);var t=e.queue,l=Bm.bind(null,fe,t);return t.dispatch=l,[e.memoizedState,l]},useDebugValue:So,useDeferredValue:function(e,t){return xo(gt(),e,t)},useTransition:function(){var e=yo(!1);return e=jm.bind(null,fe,e.queue,!0,!1),gt().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,l){var n=fe,a=gt();if(me){if(l===void 0)throw Error(s(407));l=l()}else{if(l=t(),je===null)throw Error(s(349));(be&127)!==0||cm(n,t,l)}a.memoizedState=l;var u={value:l,getSnapshot:t};return a.queue=u,Tm(om.bind(null,n,u,e),[e]),n.flags|=2048,Ta(9,{destroy:void 0},rm.bind(null,n,u,l,t),null),l},useId:function(){var e=gt(),t=je.identifierPrefix;if(me){var l=dl,n=fl;l=(n&~(1<<32-Dt(n)-1)).toString(32)+l,t="_"+t+"R_"+l,l=Ii++,0<\/script>",u=u.removeChild(u.firstChild);break;case"select":u=typeof n.is=="string"?o.createElement("select",{is:n.is}):o.createElement("select"),n.multiple?u.multiple=!0:n.size&&(u.size=n.size);break;default:u=typeof n.is=="string"?o.createElement(a,{is:n.is}):o.createElement(a)}}u[ut]=t,u[xt]=n;e:for(o=t.child;o!==null;){if(o.tag===5||o.tag===6)u.appendChild(o.stateNode);else if(o.tag!==4&&o.tag!==27&&o.child!==null){o.child.return=o,o=o.child;continue}if(o===t)break e;for(;o.sibling===null;){if(o.return===null||o.return===t)break e;o=o.return}o.sibling.return=o.return,o=o.sibling}t.stateNode=u;e:switch(st(u,a,n),a){case"button":case"input":case"select":case"textarea":n=!!n.autoFocus;break e;case"img":n=!0;break e;default:n=!1}n&&Ll(t)}}return Ue(t),t.subtreeFlags&=-33554433,Bo(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,l),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==n&&Ll(t);else{if(typeof n!="string"&&t.stateNode===null)throw Error(s(166));if(e=kl.current,ya(t)){if(e=t.stateNode,l=t.memoizedProps,n=null,a=Pe,a!==null)switch(a.tag){case 27:case 5:n=a.memoizedProps}e[ut]=t,e=!!(e.nodeValue===l||n!==null&&n.suppressHydrationWarning===!0||c0(e.nodeValue,l)),e||en(t,!0)}else e=Qu(e).createTextNode(n),e[ut]=t,t.stateNode=e}return Ue(t),null;case 31:if(l=t.memoizedState,e===null||e.memoizedState!==null){if(n=ya(t),l!==null){if(e===null){if(!n)throw Error(s(318));if(e=t.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(s(557));e[ut]=t}else Un(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;Ue(t),e=!1}else l=kr(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=l),e=!0;if(!e)return t.flags&256?(wt(t),t):(wt(t),null);if((t.flags&128)!==0)throw Error(s(558))}return Ue(t),null;case 13:if(n=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=ya(t),n!==null&&n.dehydrated!==null){if(e===null){if(!a)throw Error(s(318));if(a=t.memoizedState,a=a!==null?a.dehydrated:null,!a)throw Error(s(317));a[ut]=t}else Un(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;Ue(t),a=!1}else a=kr(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(wt(t),t):(wt(t),null)}return wt(t),(t.flags&128)!==0?(t.lanes=l,t):(l=n!==null,e=e!==null&&e.memoizedState!==null,l&&(n=t.child,a=null,n.alternate!==null&&n.alternate.memoizedState!==null&&n.alternate.memoizedState.cachePool!==null&&(a=n.alternate.memoizedState.cachePool.pool),u=null,n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(u=n.memoizedState.cachePool.pool),u!==a&&(n.flags|=2048)),l!==e&&l&&(t.child.flags|=8192),rc(t,t.updateQueue),Ue(t),null);case 4:return la(),e===null&&n0(t.stateNode.containerInfo),t.flags|=67108864,Ue(t),null;case 10:return wl(t.type),Ue(t),null;case 19:if(co(t),n=t.memoizedState,n===null)return Ue(t),null;if(a=(t.flags&128)!==0,u=n.rendering,u===null)if(a)Mu(n,!1);else{if(Ge!==0||e!==null&&(e.flags&128)!==0)for(e=t.child;e!==null;){if(u=ki(e),u!==null){for(t.flags|=128,Mu(n,!1),e=u.updateQueue,t.updateQueue=e,rc(t,e),t.subtreeFlags=0,e=l,l=t.child;l!==null;)Bd(l,e),l=l.sibling;return Ou(t,rt.current&1|2),me&&jl(t,n.treeForkCount),t.child}e=e.sibling}n.tail!==null&&zt()>Sc&&(t.flags|=128,a=!0,Mu(n,!1),t.lanes=4194304)}else{if(!a)if(e=ki(u),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,rc(t,e),Mu(n,!0),n.tail===null&&n.tailMode!=="collapsed"&&n.tailMode!=="visible"&&!u.alternate&&!me)return Ue(t),null}else 2*zt()-n.renderingStartTime>Sc&&l!==536870912&&(t.flags|=128,a=!0,Mu(n,!1),t.lanes=4194304);n.isBackwards?(u.sibling=t.child,t.child=u):(e=n.last,e!==null?e.sibling=u:t.child=u,n.last=u)}if(n.tail!==null){e=n.tail;e:{for(l=e;l!==null;){if(l.alternate!==null){l=!1;break e}l=l.sibling}l=!0}return n.rendering=e,n.tail=e.sibling,n.renderingStartTime=zt(),e.sibling=null,u=rt.current,u=a?u&1|2:u&1,n.tailMode==="visible"||n.tailMode==="collapsed"||!l||me?Ou(t,u):(l=u,Me(ct,t),Me(rt,l),dt===null&&(dt=t)),me&&jl(t,n.treeForkCount),e}return Ue(t),null;case 22:case 23:return wt(t),uo(),n=t.memoizedState!==null,e!==null?e.memoizedState!==null!==n&&(t.flags|=8192):n&&(t.flags|=8192),n?(l&536870912)!==0&&(t.flags&128)===0&&(Ue(t),t.subtreeFlags&6&&(t.flags|=8192)):Ue(t),l=t.updateQueue,l!==null&&rc(t,l.retryQueue),l=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(l=e.memoizedState.cachePool.pool),n=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(n=t.memoizedState.cachePool.pool),n!==l&&(t.flags|=2048),e!==null&&at(Gn),null;case 24:return l=null,e!==null&&(l=e.memoizedState.cache),t.memoizedState.cache!==l&&(t.flags|=2048),wl(Ve),Ue(t),null;case 25:return null;case 30:return t.flags|=33554432,Ue(t),null}throw Error(s(156,t.tag))}function F1(e,t){switch(Zr(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return wl(Ve),la(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return mi(t),null;case 31:if(t.memoizedState!==null){if(wt(t),t.alternate===null)throw Error(s(340));Un()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(wt(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(s(340));Un()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return co(t),e=t.flags,e&65536?(t.flags=e&-65537|128,e=t.memoizedState,e!==null&&(e.rendering=null,e.tail=null),t.flags|=4,t):null;case 4:return la(),null;case 10:return wl(t.type),null;case 22:case 23:return wt(t),uo(),e!==null&&at(Gn),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return wl(Ve),null;case 25:return null;default:return null}}function rv(e,t){switch(Zr(t),t.tag){case 3:wl(Ve),la();break;case 26:case 27:case 5:mi(t);break;case 4:la();break;case 31:t.memoizedState!==null&&wt(t);break;case 13:wt(t);break;case 19:co(t);break;case 10:wl(t.type);break;case 22:case 23:wt(t),uo(),e!==null&&at(Gn);break;case 24:wl(Ve)}}function wu(e,t){try{var l=t.updateQueue,n=l!==null?l.lastEffect:null;if(n!==null){var a=n.next;l=a;do{if((l.tag&e)===e){n=void 0;var u=l.create,o=l.inst;n=u(),o.destroy=n}l=l.next}while(l!==a)}}catch(d){Oe(t,t.return,d)}}function sn(e,t,l){try{var n=t.updateQueue,a=n!==null?n.lastEffect:null;if(a!==null){var u=a.next;n=u;do{if((n.tag&e)===e){var o=n.inst,d=o.destroy;if(d!==void 0){o.destroy=void 0,a=t;var y=l,N=d;try{N()}catch(R){Oe(a,y,R)}}}n=n.next}while(n!==u)}}catch(R){Oe(t,t.return,R)}}function ov(e){var t=e.updateQueue;if(t!==null){var l=e.stateNode;try{tm(t,l)}catch(n){Oe(e,e.return,n)}}}function sv(e,t,l){l.props=Zn(e.type,e.memoizedProps),l.state=e.memoizedState;try{l.componentWillUnmount()}catch(n){Oe(e,t,n)}}function ml(e,t){try{var l=e.ref;if(l!==null){switch(e.tag){case 26:case 27:case 5:var n=e.stateNode;break;case 30:var a=e.stateNode,u=zl(e.memoizedProps,a);(a.ref===null||a.ref.name!==u)&&(a.ref=p0(u)),n=a.ref;break;case 7:if(e.stateNode===null){var o=new Yt(e);g(e.child,!1,Yb,o,void 0,void 0),e.stateNode=o}n=e.stateNode;break;default:n=e.stateNode}typeof l=="function"?e.refCleanup=l(n):l.current=n}}catch(d){Oe(e,t,d)}}function ot(e,t){var l=e.ref,n=e.refCleanup;if(l!==null)if(typeof n=="function")try{n()}catch(a){Oe(e,t,a)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof l=="function")try{l(null)}catch(a){Oe(e,t,a)}else l.current=null}function oc(e,t){if((e.tag===5||e.tag===27||e.tag===6)&&e.alternate===null&&t!==null)for(var l=0;l title"))),st(n,t,l),n[ut]=e,We(n),t=n;break e;case"link":if(u=H0("link","href",a).get(t+(l.href||""))){for(o=0;ode&&(o=de,de=F,F=o);var _=Nd(d,F),S=Nd(d,de);if(_&&S&&(z.rangeCount!==1||z.anchorNode!==_.node||z.anchorOffset!==_.offset||z.focusNode!==S.node||z.focusOffset!==S.offset)){var O=U.createRange();O.setStart(_.node,_.offset),z.removeAllRanges(),F>de?(z.addRange(O),z.extend(S.node,S.offset)):(O.setEnd(S.node,S.offset),z.addRange(O))}}}}for(U=[],z=d;z=z.parentNode;)z.nodeType===1&&U.push({element:z,left:z.scrollLeft,top:z.scrollTop});for(typeof d.focus=="function"&&d.focus(),d=0;dl?32:l,$.T=null,l=as,as=null;var u=al,o=pl;if(Le=0,In=al=null,pl=0,(_e&6)!==0)throw Error(s(331));var d=_e;if(_e|=4,Mv(u.current),Rv(u,u.current,o,l),_e=d,qu(0,!1),Rt&&typeof Rt.onPostCommitFiberRoot=="function")try{Rt.onPostCommitFiberRoot(au,u)}catch{}return!0}finally{re.p=a,$.T=n,Jv(e,t)}}function Iv(e,t,l){t=Qt(l,t),t=Ao(e.stateNode,t,2),e=un(e,t,2),e!==null&&(iu(e,2),Sl(e))}function Oe(e,t,l){if(e.tag===3)Iv(e,e,l);else for(;t!==null;){if(t.tag===3){Iv(t,e,l);break}else if(t.tag===1){var n=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof n.componentDidCatch=="function"&&(vn===null||!vn.has(n))){e=Qt(l,e),l=Zm(2),n=un(t,l,2),n!==null&&(Km(l,n,t,e),iu(n,2),Sl(n));break}}t=t.return}}function fs(e,t,l){var n=e.pingCache;if(n===null){n=e.pingCache=new tb;var a=new Set;n.set(t,a)}else a=n.get(t),a===void 0&&(a=new Set,n.set(t,a));a.has(l)||(ts=!0,a.add(l),e=ob.bind(null,e,t,l),t.then(e,e))}function ob(e,t,l){var n=e.pingCache;n!==null&&n.delete(t),e.pingedLanes|=e.suspendedLanes&l,e.warmLanes&=~l,je===e&&(be&l)===l&&((Ge===4||Ge===3&&(be&62914560)===be&&300>zt()-pc)&&(_e&2)===0?wa(e,0):bc|=l,za===be&&(za=0)),Sl(e)}function $v(e,t){t===0&&(t=Lf()),e=Mn(e,t),e!==null&&(iu(e,t),Sl(e))}function sb(e){var t=e.memoizedState,l=0;t!==null&&(l=t.retryLane),$v(e,l)}function fb(e,t){var l=0;switch(e.tag){case 31:case 13:var n=e.stateNode,a=e.memoizedState;a!==null&&(l=a.retryLane);break;case 19:n=e.stateNode;break;case 22:n=e.stateNode._retryCache;break;default:throw Error(s(314))}n!==null&&n.delete(t),$v(e,l)}function db(e,t){return mr(e,t)}var Ha=null,Ba=null,ds=!1,Ac=!1,ms=!1,gn=0;function Sl(e){e!==Ba&&e.next===null&&(Ba===null?Ha=Ba=e:Ba=Ba.next=e),Ac=!0,ds||(ds=!0,vb())}function qu(e,t){if(!ms&&Ac){ms=!0;do for(var l=!1,n=Ha;n!==null;){if(!t)if(e!==0){var a=n.pendingLanes;if(a===0)var u=0;else{var o=n.suspendedLanes,d=n.pingedLanes;u=(1<<31-Dt(42|e)+1)-1,u&=a&~(o&~d),u=u&201326741?u&201326741|1:u?u|2:0}u!==0&&(l=!0,e0(n,u))}else u=be,u=bi(n,n===je?u:0,n.cancelPendingCommit!==null||n.timeoutHandle!==-1),(u&3)===0||uu(n,u)||(l=!0,e0(n,u));n=n.next}while(l);ms=!1}}function mb(){Fv()}function Fv(){Ac=ds=!1;var e=0;gn!==0&&Tb()&&(e=gn);for(var t=zt(),l=null,n=Ha;n!==null;){var a=n.next,u=Wv(n,t);u===0?(n.next=null,l===null?Ha=a:l.next=a,a===null&&(Ba=l)):(l=n,(e!==0||(u&3)!==0)&&(Ac=!0)),n=a}Le!==0&&Le!==5||qu(e,!1),gn!==0&&(gn=0)}function Wv(e,t){for(var l=e.suspendedLanes,n=e.pingedLanes,a=e.expirationTimes,u=e.pendingLanes&-62914561;0d)break;var R=y.transferSize,U=y.initiatorType;R&&r0(U)&&(y=y.responseEnd,o+=R*(yjc){F.length=Q;break}O=new Promise(zb.bind(O)),F.push(O)}}}if(0"u"?null:document;function j0(e,t,l){var n=Ya;if(n&&typeof t=="string"&&t){var a=Vt(t);a='link[rel="'+e+'"][href="'+a+'"]',typeof l=="string"&&(a+='[crossorigin="'+l+'"]'),D0.has(a)||(D0.add(a),e={rel:e,crossOrigin:l,href:t},n.querySelector(a)===null&&(t=n.createElement("link"),st(t,"link",e),We(t),n.head.appendChild(t)))}}function Jb(e){Gl.D(e),j0("dns-prefetch",e,null)}function Ib(e,t){Gl.C(e,t),j0("preconnect",e,t)}function $b(e,t,l){Gl.L(e,t,l);var n=Ya;if(n&&e&&t){var a='link[rel="preload"][as="'+Vt(t)+'"]';t==="image"&&l&&l.imageSrcSet?(a+='[imagesrcset="'+Vt(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(a+='[imagesizes="'+Vt(l.imageSizes)+'"]')):a+='[href="'+Vt(e)+'"]';var u=a;switch(t){case"style":u=Ga(e);break;case"script":u=qa(e)}if(!($t.has(u)||(e=w({rel:"preload",href:t==="image"&&l&&l.imageSrcSet?void 0:e,as:t},l),$t.set(u,e),n.querySelector(a)!==null||t==="style"&&n.querySelector(Ku(u))||t==="script"&&n.querySelector(ku(u))))){var o=n.createElement("link");st(o,"link",e),t==="style"&&(o[pi]=!0,o.onload=o.onerror=function(){Kf(o)}),We(o),n.head.appendChild(o)}}}function Fb(e,t){Gl.m(e,t);var l=Ya;if(l&&e){var n=t&&typeof t.as=="string"?t.as:"script",a='link[rel="modulepreload"][as="'+Vt(n)+'"][href="'+Vt(e)+'"]',u=a;switch(n){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":u=qa(e)}if(!$t.has(u)&&(e=w({rel:"modulepreload",href:e},t),$t.set(u,e),l.querySelector(a)===null)){switch(n){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(ku(u)))return}n=l.createElement("link"),st(n,"link",e),We(n),l.head.appendChild(n)}}}function Wb(e,t,l){Gl.S(e,t,l);var n=Ya;if(n&&e){var a=aa(n).hoistableStyles,u=Ga(e);t=t||"default";var o=a.get(u);if(!o){var d={loading:0,preload:null};if(o=n.querySelector(Ku(u)))d.loading=5;else{e=w({rel:"stylesheet",href:e,"data-precedence":t},l),(l=$t.get(u))&&Ms(e,l);var y=o=n.createElement("link");We(y),st(y,"link",e),y._p=new Promise(function(N,R){y.onload=N,y.onerror=R}),y.addEventListener("load",function(){d.loading|=1}),y.addEventListener("error",function(){d.loading|=2}),d.loading|=4,Rc(o,t,n)}o={type:"stylesheet",instance:o,count:1,state:d},a.set(u,o)}}}function Pb(e,t){Gl.X(e,t);var l=Ya;if(l&&e){var n=aa(l).hoistableScripts,a=qa(e),u=n.get(a);u||(u=l.querySelector(ku(a)),u||(e=w({src:e,async:!0},t),(t=$t.get(a))&&ws(e,t),u=l.createElement("script"),We(u),st(u,"link",e),l.head.appendChild(u)),u={type:"script",instance:u,count:1,state:null},n.set(a,u))}}function ep(e,t){Gl.M(e,t);var l=Ya;if(l&&e){var n=aa(l).hoistableScripts,a=qa(e),u=n.get(a);u||(u=l.querySelector(ku(a)),u||(e=w({src:e,async:!0,type:"module"},t),(t=$t.get(a))&&ws(e,t),u=l.createElement("script"),We(u),st(u,"link",e),l.head.appendChild(u)),u={type:"script",instance:u,count:1,state:null},n.set(a,u))}}function M0(e,t,l,n){var a=(a=kl.current)?Zu(a):null;if(!a)throw Error(s(446));switch(e){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(l=Ga(l.href),t=aa(a).hoistableStyles,n=t.get(l),n||(n={type:"style",instance:null,count:0,state:null},t.set(l,n)),n):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){e=Ga(l.href);var u=aa(a).hoistableStyles,o=u.get(e);if(o||(a=a.ownerDocument||a,o={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},u.set(e,o),(u=a.querySelector(Ku(e)))?u._p||(o.instance=u,o.state.loading=5):(u=$t.get(e),u||(u={rel:"preload",as:"style",href:l.href,crossOrigin:l.crossOrigin,integrity:l.integrity,media:l.media,hrefLang:l.hrefLang,referrerPolicy:l.referrerPolicy},$t.set(e,u)),tp(a,e,u,o.state))),t&&n===null)throw Error(s(528,""));return o}if(t&&n!==null)throw Error(s(529,""));return null;case"script":return t=l.async,l=l.src,typeof l=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(l=qa(l),t=aa(a).hoistableScripts,n=t.get(l),n||(n={type:"script",instance:null,count:0,state:null},t.set(l,n)),n):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,e))}}function Ga(e){return'href="'+Vt(e)+'"'}function Ku(e){return'link[rel="stylesheet"]['+e+"]"}function w0(e){return w({},e,{"data-precedence":e.precedence,precedence:null})}function tp(e,t,l,n){if(t=e.querySelector('link[rel="preload"][as="style"]['+t+"]")){if(t[pi]!==!0){n.loading=1;return}}else t=e.createElement("link"),t[pi]=!0,t.onload=t.onerror=Kf.bind(null,t),st(t,"link",l),We(t),e.head.appendChild(t);n.preload=t,t.addEventListener("load",function(){return n.loading|=1}),t.addEventListener("error",function(){return n.loading|=2})}function qa(e){return'[src="'+Vt(e)+'"]'}function ku(e){return"script[async]"+e}function U0(e,t,l){if(t.count++,t.instance===null)switch(t.type){case"style":var n=e.querySelector('style[data-href~="'+Vt(l.href)+'"]');if(n)return t.instance=n,We(n),n;var a=w({},l,{"data-href":l.href,"data-precedence":l.precedence,href:null,precedence:null});return n=(e.ownerDocument||e).createElement("style"),We(n),st(n,"style",a),Rc(n,l.precedence,e),t.instance=n;case"stylesheet":a=Ga(l.href);var u=e.querySelector(Ku(a));if(u)return t.state.loading|=4,t.instance=u,We(u),u;n=w0(l),(a=$t.get(a))&&Ms(n,a),u=(e.ownerDocument||e).createElement("link"),We(u);var o=u;return o._p=new Promise(function(d,y){o.onload=d,o.onerror=y}),st(u,"link",n),t.state.loading|=4,Rc(u,l.precedence,e),t.instance=u;case"script":return u=qa(l.src),(a=e.querySelector(ku(u)))?(t.instance=a,We(a),a):(n=l,(a=$t.get(u))&&(n=w({},l),ws(n,a)),e=e.ownerDocument||e,a=e.createElement("script"),We(a),st(a,"link",n),e.head.appendChild(a),t.instance=a);case"void":return null;default:throw Error(s(443,t.type))}else t.type==="stylesheet"&&(t.state.loading&4)===0&&(n=t.instance,t.state.loading|=4,Rc(n,l.precedence,e));return t.instance}function Rc(e,t,l){for(var n=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),a=n.length?n[n.length-1]:null,u=a,o=0;o title"):null)}function lp(e,t,l){if(l===1||t.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof t.precedence!="string"||typeof t.href!="string"||t.href==="")break;return!0;case"link":if(typeof t.rel!="string"||typeof t.href!="string"||t.href===""||t.onLoad||t.onError)break;return t.rel==="stylesheet"?(e=t.disabled,typeof t.precedence=="string"&&e==null):!0;case"script":if(t.async&&typeof t.async!="function"&&typeof t.async!="symbol"&&!t.onLoad&&!t.onError&&t.src&&typeof t.src=="string")return!0}return!1}function B0(e,t){return e==="img"&&t.src!=null&&t.src!==""&&t.onLoad==null&&t.loading!=="lazy"}function L0(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function Y0(e){return(e.width||100)*(e.height||100)*(typeof devicePixelRatio=="number"?devicePixelRatio:1)*.25}function G0(e,t){typeof t.decode=="function"&&(e.imgCount++,t.complete||(e.imgBytes+=Y0(t),e.suspenseyImages.push(t)),e=up.bind(e),t.decode().then(e,e))}function np(e,t,l,n){if(l.type==="stylesheet"&&(typeof n.media!="string"||matchMedia(n.media).matches!==!1)&&(l.state.loading&4)===0){if(l.instance===null){var a=Ga(n.href),u=t.querySelector(Ku(a));if(u){t=u._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=Ju.bind(e),t.then(e,e)),l.state.loading|=4,l.instance=u,We(u);return}u=t.ownerDocument||t,n=w0(n),(a=$t.get(a))&&Ms(n,a),u=u.createElement("link"),We(u);var o=u;o._p=new Promise(function(d,y){o.onload=d,o.onerror=y}),st(u,"link",n),l.instance=u}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(l,t),(t=l.state.preload)&&(l.state.loading&3)===0&&(e.count++,l=Ju.bind(e),t.addEventListener("load",l),t.addEventListener("error",l))}}var jc=0;function ap(e,t){return e.stylesheets&&e.count===0&&wc(e,e.stylesheets),0jc?50:800)+t);return e.unsuspend=l,function(){e.unsuspend=null,clearTimeout(n),clearTimeout(a)}}:null}function q0(e){if(e.count===0&&(e.imgCount===0||!e.waitingForImages)){if(e.stylesheets)wc(e,e.stylesheets);else if(e.unsuspend){var t=e.unsuspend;e.unsuspend=null,t()}}}function Ju(){this.count--,q0(this)}function up(){this.imgCount--,q0(this)}var Mc=null;function wc(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Mc=new Map,t.forEach(ip,e),Mc=null,Ju.call(e))}function ip(e,t){if(!(t.state.loading&4)){var l=Mc.get(e);if(l)var n=l.get(null);else{l=new Map,Mc.set(e,l);for(var a=e.querySelectorAll("link[data-precedence],style[data-precedence]"),u=0;u{function r(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(r)}catch(f){console.error(f)}}r(),c.exports=Cp()})),Op=i=>i?.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();function zp(i,c,r=[]){if(c==null)throw new Error("[lucide]: iconNode is required when icon name is used");return{name:Op(i),size:24,node:c,...r.length>0?{aliases:r}:{}}}var Rp=i=>{let c="",r=!1;for(const f of i){if(f==="-"||f==="_"||f<=" "){r=c.length>0;continue}c.length===0?c+=f.toLowerCase():c+=r?f.toUpperCase():f,r=!1}return c},Dp=i=>{const c=Rp(i);return c.charAt(0).toUpperCase()+c.slice(1)},Ws=(...i)=>i.filter((c,r,f)=>!!c&&c.trim()!==""&&f.indexOf(c)===r).join(" ").trim(),Fn={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round"};function qs(i){return i!=null}function jp(i,c={}){const r=c.attributeNames??{},f=E=>r[E]??E,s=i.size??i.width??Fn.width,v=i.size??i.height??Fn.height,h=i.aliases?.filter(E=>typeof E=="string"&&E.trim()!=="").map(E=>`lucide-${E}`)??[],p=[...i.name?[`lucide-${i.name}`]:[],...h],A=c.className?.split(" ").filter(Boolean)??[],C=c.includeDefaultClasses===!1?Ws(...A):Ws("lucide",...p,...A),H=c.absoluteStrokeWidth?Number(c.strokeWidth??Fn["stroke-width"])*Number(i.size??i.width??Fn.width)/Number(c.size??c.width??Fn.width):c.strokeWidth??Fn["stroke-width"];return["svg",{...Object.entries(Fn).reduce((E,[g,D])=>(E[f(g)]=D,E),{}),..."color"in c&&c.color&&{[f("stroke")]:c.color},..."size"in c&&qs(c.size)&&{[f("width")]:c.size,[f("height")]:c.size},..."width"in c&&qs(c.width)&&{[f("width")]:c.width},..."height"in c&&qs(c.height)&&{[f("height")]:c.height},[f("stroke-width")]:H,...C&&{[f("class")]:C},[f("viewBox")]:`0 0 ${s} ${v}`,...c.hasA11yProp===!1?{[f("aria-hidden")]:"true"}:{},..."attributes"in c&&c.attributes},i.node.map(E=>{const[g,D,G]=E,M=c.nonScalingStroke?{[f("vector-effect")]:"non-scaling-stroke",...D}:D;return G?[g,M,G]:[g,M]})]}function Mp(i,c={}){return jp(i,{...c,attributeNames:{...c.attributeNames,class:"className","stroke-width":"strokeWidth","stroke-linecap":"strokeLinecap","stroke-linejoin":"strokeLinejoin","vector-effect":"vectorEffect"}})}var wp=i=>{for(const c in i)if(c.startsWith("aria-")||c==="role"||c==="title")return!0;return!1},b=Rh(hf(),1),Up=(0,b.createContext)({}),Hp=()=>(0,b.useContext)(Up),Bp=(0,b.forwardRef)(({color:i,size:c,width:r,height:f,strokeWidth:s,absoluteStrokeWidth:v,nonScalingStroke:h,className:p="",children:A,iconNode:C=[],icon:H={node:C,aliases:[],size:24},...E},g)=>{const{size:D=24,strokeWidth:G=2,absoluteStrokeWidth:M=!1,nonScalingStroke:L=!1,color:V="currentColor",className:X=""}=Hp()??{},B=!!A||wp(E),[Z,ue,ee=[]]=Mp(H,{color:i??V,width:r??c??D,height:f??c??D,strokeWidth:s??G,absoluteStrokeWidth:v??M,nonScalingStroke:h??L,className:Ws(X,p),hasA11yProp:B,attributes:E});return(0,b.createElement)(Z,{ref:g,...ue},[...ee.map(([W,w])=>(0,b.createElement)(W,w)),...Array.isArray(A)?A:[A]])});function mt(i,c=[],r=[]){const f=typeof i=="string"?zp(i,c,r):i,s=(0,b.forwardRef)(({className:v,...h},p)=>(0,b.createElement)(Bp,{ref:p,icon:f,className:v,...h}));return f.name&&(s.displayName=Dp(f.name)),s}var jh={name:"bot",size:24,node:[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]};jh.node;var Lp=mt(jh),Mh={name:"calculator",size:24,node:[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]};Mh.node;var Yp=mt(Mh),wh={name:"chevron-down",size:24,node:[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]};wh.node;var Gp=mt(wh),Uh={name:"gauge",size:24,node:[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]};Uh.node;var qp=mt(Uh),Hh={name:"layers",size:24,node:[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],aliases:["layers-3"]};Hh.node;var Vp=mt(Hh),Bh={name:"loader-circle",size:24,node:[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],aliases:["loader-2"]};Bh.node;var Xp=mt(Bh),Lh={name:"menu",size:24,node:[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]]};Lh.node;var Qp=mt(Lh),Yh={name:"search",size:24,node:[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]};Yh.node;var Zp=mt(Yh),Gh={name:"send",size:24,node:[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]};Gh.node;var Pn=mt(Gh),qh={name:"share-2",size:24,node:[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]]};qh.node;var Kp=mt(qh),Vh={name:"shield-check",size:24,node:[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]};Vh.node;var kp=mt(Vh),Xh={name:"shield-question-mark",size:24,node:[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}],["path",{d:"M12 17h.01",key:"p32p05"}]],aliases:["shield-question"]};Xh.node;var Jp=mt(Xh),Qh={name:"sparkles",size:24,node:[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],aliases:["stars"]};Qh.node;var Ip=mt(Qh),Zh={name:"terminal",size:24,node:[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]]};Zh.node;var $p=mt(Zh),Kh={name:"triangle-alert",size:24,node:[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],aliases:["alert-triangle"]};Kh.node;var Fp=mt(Kh),kh={name:"x",size:24,node:[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]};kh.node;var Wp=mt(kh),Pp=Ap();function Jh(i){var c,r,f="";if(typeof i=="string"||typeof i=="number")f+=i;else if(typeof i=="object")if(Array.isArray(i)){var s=i.length;for(c=0;c{const r=new Array(i.length+c.length);for(let f=0;f({classGroupId:i,validator:c}),$h=(i=new Map,c=null,r)=>({nextPart:i,validators:c,classGroupId:r}),Wc="-",eh=[],lS="arbitrary..",nS=i=>{const c=uS(i),{conflictingClassGroups:r,conflictingClassGroupModifiers:f}=i;return{getClassGroupId:h=>{if(h.startsWith("[")&&h.endsWith("]"))return aS(h);const p=h.split(Wc),A=p[0]===""&&p.length>1?1:0;return Fh(p,A,c)},getConflictingClassGroupIds:(h,p)=>{if(p){const A=f[h],C=r[h];return A?C?eS(C,A):A:C||eh}return r[h]||eh}}},Fh=(i,c,r)=>{if(i.length-c===0)return r.classGroupId;const f=i[c],s=r.nextPart.get(f);if(s){const A=Fh(i,c+1,s);if(A)return A}const v=r.validators;if(v===null)return;const h=c===0?i.join(Wc):i.slice(c).join(Wc),p=v.length;for(let A=0;Ai.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const c=i.slice(1,-1),r=c.indexOf(":"),f=c.slice(0,r);return f?lS+f:void 0})(),uS=i=>{const{theme:c,classGroups:r}=i;return iS(r,c)},iS=(i,c)=>{const r=$h();for(const f in i){const s=i[f];gf(s,r,f,c)}return r},gf=(i,c,r,f)=>{const s=i.length;for(let v=0;v{if(typeof i=="string"){rS(i,c,r);return}if(typeof i=="function"){oS(i,c,r,f);return}sS(i,c,r,f)},rS=(i,c,r)=>{const f=i===""?c:Wh(c,i);f.classGroupId=r},oS=(i,c,r,f)=>{if(fS(i)){gf(i(f),c,r,f);return}c.validators===null&&(c.validators=[]),c.validators.push(tS(r,i))},sS=(i,c,r,f)=>{const s=Object.entries(i),v=s.length;for(let h=0;h{let r=i;const f=c.split(Wc),s=f.length;for(let v=0;v"isThemeGetter"in i&&i.isThemeGetter===!0,dS=i=>{if(i<1)return{get:()=>{},set:()=>{}};let c=0,r=Object.create(null),f=Object.create(null);const s=(v,h)=>{r[v]=h,c++,c>i&&(c=0,f=r,r=Object.create(null))};return{get(v){let h=r[v];if(h!==void 0)return h;if((h=f[v])!==void 0)return s(v,h),h},set(v,h){v in r?r[v]=h:s(v,h)}}},Ps="!",th=":",mS=[],lh=(i,c,r,f,s)=>({modifiers:i,hasImportantModifier:c,baseClassName:r,maybePostfixModifierPosition:f,isExternal:s}),vS=i=>{const{prefix:c,experimentalParseClassName:r}=i;let f=s=>{const v=[];let h=0,p=0,A=0,C;const H=s.length;for(let M=0;MA?C-A:void 0;return lh(v,D,g,G)};if(c){const s=c+th,v=f;f=h=>h.startsWith(s)?v(h.slice(s.length)):lh(mS,!1,h,void 0,!0)}if(r){const s=f;f=v=>r({className:v,parseClassName:s})}return f},hS=i=>{const c=new Map;return i.orderSensitiveModifiers.forEach((r,f)=>{c.set(r,1e6+f)}),r=>{const f=[];let s=[];for(let v=0;v0&&(s.sort(),f.push(...s),s=[]),f.push(h)):s.push(h)}return s.length>0&&(s.sort(),f.push(...s)),f}},gS=i=>({cache:dS(i.cacheSize),parseClassName:vS(i),sortModifiers:hS(i),postfixLookupClassGroupIds:yS(i),...nS(i)}),yS=i=>{const c=Object.create(null),r=i.postfixLookupClassGroups;if(r)for(let f=0;f{const{parseClassName:r,getClassGroupId:f,getConflictingClassGroupIds:s,sortModifiers:v,postfixLookupClassGroupIds:h}=c,p=[],A=i.trim().split(bS);let C="";for(let H=A.length-1;H>=0;H-=1){const E=A[H],{isExternal:g,modifiers:D,hasImportantModifier:G,baseClassName:M,maybePostfixModifierPosition:L}=r(E);if(g){C=E+(C.length>0?" "+C:C);continue}let V=!!L,X;if(V){X=f(M.substring(0,L));const W=X&&h[X]?f(M):void 0;W&&W!==X&&(X=W,V=!1)}else X=f(M);if(!X){if(!V){C=E+(C.length>0?" "+C:C);continue}if(X=f(M),!X){C=E+(C.length>0?" "+C:C);continue}V=!1}const B=D.length===0?"":D.length===1?D[0]:v(D).join(":"),Z=G?B+Ps:B,ue=Z+X;if(p.indexOf(ue)>-1)continue;p.push(ue);const ee=s(X,V);for(let W=0;W0?" "+C:C)}return C},SS=(...i)=>{let c=0,r,f,s="";for(;c{if(typeof i=="string")return i;let c,r="";for(let f=0;f{let r,f,s,v;const h=A=>{const C=c.reduce((H,E)=>E(H),i());return r=gS(C),f=r.cache.get,s=r.cache.set,v=p,p(A)},p=A=>{const C=f(A);if(C)return C;const H=pS(A,r);return s(A,H),H};return v=h,(...A)=>v(SS(...A))},ES=[],$e=i=>{const c=r=>r[i]||ES;return c.isThemeGetter=!0,c.themeKey=i,c},eg=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,tg=/^\((?:(\w[\w-]*):)?(.+)\)$/i,TS=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,_S=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,NS=/\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$/,CS=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix|color|light-dark)\(.+\)$/,AS=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,OS=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Tn=i=>TS.test(i),ve=i=>!!i&&!Number.isNaN(Number(i)),xl=i=>!!i&&Number.isInteger(Number(i)),Vs=i=>i.endsWith("%")&&ve(i.slice(0,-1)),ql=i=>_S.test(i),lg=()=>!0,zS=i=>NS.test(i)&&!CS.test(i),yf=()=>!1,RS=i=>AS.test(i),DS=i=>OS.test(i),jS=i=>!J(i)&&!I(i),MS=i=>i.startsWith("@container")&&(i[10]==="/"&&i[11]!==void 0||i[11]==="s"&&i[16]!==void 0&&i.startsWith("-size/",10)||i[11]==="n"&&i[18]!==void 0&&i.startsWith("-normal/",10)),wS=i=>An(i,ug,yf),J=i=>eg.test(i),Wn=i=>An(i,ig,zS),nh=i=>An(i,VS,ve),US=i=>An(i,rg,lg),HS=i=>An(i,cg,yf),ah=i=>An(i,ng,yf),BS=i=>An(i,ag,DS),qc=i=>An(i,og,RS),I=i=>tg.test(i),Wu=i=>ea(i,ig),LS=i=>ea(i,cg),uh=i=>ea(i,ng),YS=i=>ea(i,ug),GS=i=>ea(i,ag),Vc=i=>ea(i,og,!0),qS=i=>ea(i,rg,!0),An=(i,c,r)=>{const f=eg.exec(i);return f?f[1]?c(f[1]):r(f[2]):!1},ea=(i,c,r=!1)=>{const f=tg.exec(i);return f?f[1]?c(f[1]):r:!1},ng=i=>i==="position"||i==="percentage",ag=i=>i==="image"||i==="url",ug=i=>i==="length"||i==="size"||i==="bg-size",ig=i=>i==="length",VS=i=>i==="number",cg=i=>i==="family-name",rg=i=>i==="number"||i==="weight",og=i=>i==="shadow",XS=()=>{const i=$e("color"),c=$e("font"),r=$e("text"),f=$e("font-weight"),s=$e("tracking"),v=$e("leading"),h=$e("breakpoint"),p=$e("container"),A=$e("spacing"),C=$e("radius"),H=$e("shadow"),E=$e("inset-shadow"),g=$e("text-shadow"),D=$e("drop-shadow"),G=$e("blur"),M=$e("perspective"),L=$e("aspect"),V=$e("ease"),X=$e("animate"),B=()=>["auto","avoid","all","avoid-page","page","left","right","column"],Z=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],ue=()=>[...Z(),I,J],ee=()=>["auto","hidden","clip","visible","scroll"],W=()=>["auto","contain","none"],w=()=>[I,J,A],ne=()=>[Tn,"full","auto",...w()],He=()=>[xl,"none","subgrid",I,J],Ce=()=>["auto",{span:["full",xl,I,J]},xl,I,J],se=()=>[xl,"auto",I,J],ke=()=>["auto","min","max","fr",I,J],Fe=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],De=()=>["start","end","center","stretch","center-safe","end-safe"],q=()=>["auto",...w()],ce=()=>[Tn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...w()],ae=()=>[p,Tn,"screen","full","dvw","lvw","svw","min","max","fit",...w()],xe=()=>[Tn,"screen","full","lh","dvh","lvh","svh","min","max","fit",...w()],K=()=>[i,I,J],Je=()=>[...Z(),uh,ah,{position:[I,J]}],pt=()=>["no-repeat",{repeat:["","x","y","space","round"]}],Pt=()=>["auto","cover","contain",YS,wS,{size:[I,J]}],vt=()=>[Vs,Wu,Wn],x=()=>["","none","full",C,I,J],Y=()=>["",ve,Wu,Wn],P=()=>["solid","dashed","dotted","double"],te=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ie=()=>[ve,Vs,uh,ah],Se=()=>["","none",G,I,J],ye=()=>["none",ve,I,J],$=()=>["none",ve,I,J],re=()=>[ve,I,J],St=()=>[Tn,"full",...w()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ql],breakpoint:[ql],color:[lg],container:[ql],"drop-shadow":[ql],ease:["in","out","in-out"],font:[jS],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ql],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ql],shadow:[ql],spacing:["px",ve],text:[ql],"text-shadow":[ql],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Tn,J,I,L]}],container:["container"],"container-type":[{"@container":["","normal","size",I,J]}],"container-named":[MS],columns:[{columns:[ve,"auto",J,I,p]}],"break-after":[{"break-after":B()}],"break-before":[{"break-before":B()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:ue()}],overflow:[{overflow:ee()}],"overflow-x":[{"overflow-x":ee()}],"overflow-y":[{"overflow-y":ee()}],overscroll:[{overscroll:W()}],"overscroll-x":[{"overscroll-x":W()}],"overscroll-y":[{"overscroll-y":W()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:ne()}],"inset-x":[{"inset-x":ne()}],"inset-y":[{"inset-y":ne()}],start:[{"inset-s":ne(),start:ne()}],end:[{"inset-e":ne(),end:ne()}],"inset-bs":[{"inset-bs":ne()}],"inset-be":[{"inset-be":ne()}],top:[{top:ne()}],right:[{right:ne()}],bottom:[{bottom:ne()}],left:[{left:ne()}],visibility:["visible","invisible","collapse"],z:[{z:[xl,"auto",I,J]}],basis:[{basis:[Tn,"full","auto",p,...w()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ve,Tn,"auto","initial","none",J]}],grow:[{grow:["",ve,I,J]}],shrink:[{shrink:["",ve,I,J]}],order:[{order:[xl,"first","last","none",I,J]}],"grid-cols":[{"grid-cols":He()}],"col-start-end":[{col:Ce()}],"col-start":[{"col-start":se()}],"col-end":[{"col-end":se()}],"grid-rows":[{"grid-rows":He()}],"row-start-end":[{row:Ce()}],"row-start":[{"row-start":se()}],"row-end":[{"row-end":se()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ke()}],"auto-rows":[{"auto-rows":ke()}],gap:[{gap:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:[...Fe(),"normal"]}],"justify-items":[{"justify-items":[...De(),"normal"]}],"justify-self":[{"justify-self":["auto",...De()]}],"align-content":[{content:["normal",...Fe()]}],"align-items":[{items:[...De(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...De(),{baseline:["","last"]}]}],"place-content":[{"place-content":Fe()}],"place-items":[{"place-items":[...De(),"baseline"]}],"place-self":[{"place-self":["auto",...De()]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pbs:[{pbs:w()}],pbe:[{pbe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:q()}],mx:[{mx:q()}],my:[{my:q()}],ms:[{ms:q()}],me:[{me:q()}],mbs:[{mbs:q()}],mbe:[{mbe:q()}],mt:[{mt:q()}],mr:[{mr:q()}],mb:[{mb:q()}],ml:[{ml:q()}],"space-x":[{"space-x":w()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":w()}],"space-y-reverse":["space-y-reverse"],size:[{size:ce()}],"inline-size":[{inline:["auto",...ae()]}],"min-inline-size":[{"min-inline":["auto",...ae()]}],"max-inline-size":[{"max-inline":["none",...ae()]}],"block-size":[{block:["auto",...xe()]}],"min-block-size":[{"min-block":["auto",...xe()]}],"max-block-size":[{"max-block":["none",...xe()]}],w:[{w:[p,"screen",...ce()]}],"min-w":[{"min-w":[p,"screen","none",...ce()]}],"max-w":[{"max-w":[p,"screen","none","prose",{screen:[h]},...ce()]}],h:[{h:["screen","lh",...ce()]}],"min-h":[{"min-h":["screen","lh","none",...ce()]}],"max-h":[{"max-h":["screen","lh","none",...ce()]}],"font-size":[{text:["base",r,Wu,Wn]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[f,qS,US]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Vs,J]}],"font-family":[{font:[LS,HS,c]}],"font-features":[{"font-features":[J]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[s,I,J]}],"line-clamp":[{"line-clamp":[ve,"none",I,nh]}],leading:[{leading:["none",v,...w()]}],"list-image":[{"list-image":["none",I,J]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",I,J]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:K()}],"text-color":[{text:K()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...P(),"wavy"]}],"text-decoration-thickness":[{decoration:[ve,"from-font","auto",I,Wn]}],"text-decoration-color":[{decoration:K()}],"underline-offset":[{"underline-offset":[ve,"auto",I,J]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:w()}],"tab-size":[{tab:[xl,I,J]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",I,J]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",I,J]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:Je()}],"bg-repeat":[{bg:pt()}],"bg-size":[{bg:Pt()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},xl,I,J],radial:["",I,J],conic:["",xl,I,J]},GS,BS]}],"bg-color":[{bg:K()}],"gradient-from-pos":[{from:vt()}],"gradient-via-pos":[{via:vt()}],"gradient-to-pos":[{to:vt()}],"gradient-from":[{from:K()}],"gradient-via":[{via:K()}],"gradient-to":[{to:K()}],rounded:[{rounded:x()}],"rounded-s":[{"rounded-s":x()}],"rounded-e":[{"rounded-e":x()}],"rounded-t":[{"rounded-t":x()}],"rounded-r":[{"rounded-r":x()}],"rounded-b":[{"rounded-b":x()}],"rounded-l":[{"rounded-l":x()}],"rounded-ss":[{"rounded-ss":x()}],"rounded-se":[{"rounded-se":x()}],"rounded-ee":[{"rounded-ee":x()}],"rounded-es":[{"rounded-es":x()}],"rounded-tl":[{"rounded-tl":x()}],"rounded-tr":[{"rounded-tr":x()}],"rounded-br":[{"rounded-br":x()}],"rounded-bl":[{"rounded-bl":x()}],"border-w":[{border:Y()}],"border-w-x":[{"border-x":Y()}],"border-w-y":[{"border-y":Y()}],"border-w-s":[{"border-s":Y()}],"border-w-e":[{"border-e":Y()}],"border-w-bs":[{"border-bs":Y()}],"border-w-be":[{"border-be":Y()}],"border-w-t":[{"border-t":Y()}],"border-w-r":[{"border-r":Y()}],"border-w-b":[{"border-b":Y()}],"border-w-l":[{"border-l":Y()}],"divide-x":[{"divide-x":Y()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Y()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...P(),"hidden","none"]}],"divide-style":[{divide:[...P(),"hidden","none"]}],"border-color":[{border:K()}],"border-color-x":[{"border-x":K()}],"border-color-y":[{"border-y":K()}],"border-color-s":[{"border-s":K()}],"border-color-e":[{"border-e":K()}],"border-color-bs":[{"border-bs":K()}],"border-color-be":[{"border-be":K()}],"border-color-t":[{"border-t":K()}],"border-color-r":[{"border-r":K()}],"border-color-b":[{"border-b":K()}],"border-color-l":[{"border-l":K()}],"divide-color":[{divide:K()}],"outline-style":[{outline:[...P(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ve,I,J]}],"outline-w":[{outline:["",ve,Wu,Wn]}],"outline-color":[{outline:K()}],shadow:[{shadow:["","inner","none",H,Vc,qc]}],"shadow-color":[{shadow:K()}],"inset-shadow":[{"inset-shadow":["none",E,Vc,qc]}],"inset-shadow-color":[{"inset-shadow":K()}],"ring-w":[{ring:Y()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:K()}],"ring-offset-w":[{"ring-offset":[ve,Wn]}],"ring-offset-color":[{"ring-offset":K()}],"inset-ring-w":[{"inset-ring":Y()}],"inset-ring-color":[{"inset-ring":K()}],"text-shadow":[{"text-shadow":["none",g,Vc,qc]}],"text-shadow-color":[{"text-shadow":K()}],opacity:[{opacity:[ve,I,J]}],"mix-blend":[{"mix-blend":[...te(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":te()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ve]}],"mask-image-linear-from-pos":[{"mask-linear-from":ie()}],"mask-image-linear-to-pos":[{"mask-linear-to":ie()}],"mask-image-linear-from-color":[{"mask-linear-from":K()}],"mask-image-linear-to-color":[{"mask-linear-to":K()}],"mask-image-t-from-pos":[{"mask-t-from":ie()}],"mask-image-t-to-pos":[{"mask-t-to":ie()}],"mask-image-t-from-color":[{"mask-t-from":K()}],"mask-image-t-to-color":[{"mask-t-to":K()}],"mask-image-r-from-pos":[{"mask-r-from":ie()}],"mask-image-r-to-pos":[{"mask-r-to":ie()}],"mask-image-r-from-color":[{"mask-r-from":K()}],"mask-image-r-to-color":[{"mask-r-to":K()}],"mask-image-b-from-pos":[{"mask-b-from":ie()}],"mask-image-b-to-pos":[{"mask-b-to":ie()}],"mask-image-b-from-color":[{"mask-b-from":K()}],"mask-image-b-to-color":[{"mask-b-to":K()}],"mask-image-l-from-pos":[{"mask-l-from":ie()}],"mask-image-l-to-pos":[{"mask-l-to":ie()}],"mask-image-l-from-color":[{"mask-l-from":K()}],"mask-image-l-to-color":[{"mask-l-to":K()}],"mask-image-x-from-pos":[{"mask-x-from":ie()}],"mask-image-x-to-pos":[{"mask-x-to":ie()}],"mask-image-x-from-color":[{"mask-x-from":K()}],"mask-image-x-to-color":[{"mask-x-to":K()}],"mask-image-y-from-pos":[{"mask-y-from":ie()}],"mask-image-y-to-pos":[{"mask-y-to":ie()}],"mask-image-y-from-color":[{"mask-y-from":K()}],"mask-image-y-to-color":[{"mask-y-to":K()}],"mask-image-radial":[{"mask-radial":[I,J]}],"mask-image-radial-from-pos":[{"mask-radial-from":ie()}],"mask-image-radial-to-pos":[{"mask-radial-to":ie()}],"mask-image-radial-from-color":[{"mask-radial-from":K()}],"mask-image-radial-to-color":[{"mask-radial-to":K()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":Z()}],"mask-image-conic-pos":[{"mask-conic":[ve]}],"mask-image-conic-from-pos":[{"mask-conic-from":ie()}],"mask-image-conic-to-pos":[{"mask-conic-to":ie()}],"mask-image-conic-from-color":[{"mask-conic-from":K()}],"mask-image-conic-to-color":[{"mask-conic-to":K()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:Je()}],"mask-repeat":[{mask:pt()}],"mask-size":[{mask:Pt()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",I,J]}],filter:[{filter:["","none",I,J]}],blur:[{blur:Se()}],brightness:[{brightness:[ve,I,J]}],contrast:[{contrast:[ve,I,J]}],"drop-shadow":[{"drop-shadow":["","none",D,Vc,qc]}],"drop-shadow-color":[{"drop-shadow":K()}],grayscale:[{grayscale:["",ve,I,J]}],"hue-rotate":[{"hue-rotate":[ve,I,J]}],invert:[{invert:["",ve,I,J]}],saturate:[{saturate:[ve,I,J]}],sepia:[{sepia:["",ve,I,J]}],"backdrop-filter":[{"backdrop-filter":["","none",I,J]}],"backdrop-blur":[{"backdrop-blur":Se()}],"backdrop-brightness":[{"backdrop-brightness":[ve,I,J]}],"backdrop-contrast":[{"backdrop-contrast":[ve,I,J]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ve,I,J]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ve,I,J]}],"backdrop-invert":[{"backdrop-invert":["",ve,I,J]}],"backdrop-opacity":[{"backdrop-opacity":[ve,I,J]}],"backdrop-saturate":[{"backdrop-saturate":[ve,I,J]}],"backdrop-sepia":[{"backdrop-sepia":["",ve,I,J]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",I,J]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ve,"initial",I,J]}],ease:[{ease:["linear","initial",V,I,J]}],delay:[{delay:[ve,I,J]}],animate:[{animate:["none",X,I,J]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[M,I,J]}],"perspective-origin":[{"perspective-origin":ue()}],rotate:[{rotate:ye()}],"rotate-x":[{"rotate-x":ye()}],"rotate-y":[{"rotate-y":ye()}],"rotate-z":[{"rotate-z":ye()}],scale:[{scale:$()}],"scale-x":[{"scale-x":$()}],"scale-y":[{"scale-y":$()}],"scale-z":[{"scale-z":$()}],"scale-3d":["scale-3d"],skew:[{skew:re()}],"skew-x":[{"skew-x":re()}],"skew-y":[{"skew-y":re()}],transform:[{transform:[I,J,"","none","gpu","cpu"]}],"transform-origin":[{origin:ue()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:St()}],"translate-x":[{"translate-x":St()}],"translate-y":[{"translate-y":St()}],"translate-z":[{"translate-z":St()}],"translate-none":["translate-none"],zoom:[{zoom:[xl,I,J]}],accent:[{accent:K()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:K()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",I,J]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":K()}],"scrollbar-track-color":[{"scrollbar-track":K()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mbs":[{"scroll-mbs":w()}],"scroll-mbe":[{"scroll-mbe":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pbs":[{"scroll-pbs":w()}],"scroll-pbe":[{"scroll-pbe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"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",I,J]}],fill:[{fill:["none",...K()]}],"stroke-w":[{stroke:[ve,Wu,Wn,nh]}],stroke:[{stroke:["none",...K()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["start","end","right","left"],"inset-y":["inset-bs","inset-be","top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["ps","pe","pr","pl"],py:["pbs","pbe","pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["ms","me","mr","ml"],my:["mbs","mbe","mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-s","border-w-e","border-w-r","border-w-l"],"border-w-y":["border-w-bs","border-w-be","border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-s","border-color-e","border-color-r","border-color-l"],"border-color-y":["border-color-bs","border-color-be","border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-ms","scroll-me","scroll-mr","scroll-ml"],"scroll-my":["scroll-mbs","scroll-mbe","scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-ps","scroll-pe","scroll-pr","scroll-pl"],"scroll-py":["scroll-pbs","scroll-pbe","scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},QS=xS(XS);function ft(...i){return QS(Ih(i))}var Ia="https://your-domain.com",Nn="https://t.me/iishkogatewaybot?start=site",ni="/auth/telegram/start",ai="/api/pricing",ui=`${Ia}/v1`,sg="/chat/completions",ZS="/images/generations",ei="IISHKO GATEWAY",ef=[{label:"Главная",href:"/",page:"home"},{label:"Тарифы",href:"/pricing",page:"pricing"},{label:"Документация",href:"/docs",page:"docs"},{label:"О сервисе",href:"/about",page:"about"}],ii={home:{page:"home",title:"IISHKO GATEWAY — единый API-шлюз к AI-моделям",description:"Единый OpenAI-совместимый API-шлюз к моделям разных вендоров: один ключ, один баланс, прозрачная тарификация по множителям входа и выхода. Подключение через Telegram-бот.",canonical:`${Ia}/`,h1:"Единый API-доступ к AI-моделям"},pricing:{page:"pricing",title:"Тарифы и цены моделей — IISHKO GATEWAY",description:"Актуальные коэффициенты тарификации и цены моделей напрямую из /api/pricing. Без выдуманных сумм: множители входа и выхода либо цена за вызов с собственной единицей измерения.",canonical:`${Ia}/pricing`,h1:"Тарифы моделей"},docs:{page:"docs",title:"Документация и быстрый старт — IISHKO GATEWAY",description:"Как получить ключ, указать base URL и выполнить первый запрос к чату или генерации изображений через OpenAI-совместимый API шлюза IISHKO GATEWAY.",canonical:`${Ia}/docs`,h1:"Документация"},about:{page:"about",title:"О сервисе — IISHKO GATEWAY",description:"Что такое API-шлюз, какие задачи он решает, как устроена модель оплаты и как получить поддержку через Telegram.",canonical:`${Ia}/about`,h1:"О сервисе"},signin:{page:"signin",title:"Вход через Telegram — IISHKO GATEWAY",description:"Авторизация через Telegram-бот: получите API-ключ и доступ к консоли шлюза.",canonical:`${Ia}/sign-in`,h1:"Вход в шлюз",noindex:!0}},KS=Object.defineProperty,bf=(i,c)=>KS(i,"name",{value:c,configurable:!0});function tf(i,c){if(typeof i=="function")return i(c);i!=null&&(i.current=c)}bf(tf,"setRef");function fg(...i){return c=>{let r=!1;const f=i.map(s=>{const v=tf(s,c);return!r&&typeof v=="function"&&(r=!0),v});if(r)return()=>{for(let s=0;skS(i,"name",{value:c,configurable:!0});function Cn(i){const c=b.forwardRef((r,f)=>{let{children:s,...v}=r,h=null,p=!1;const A=[];lf(s)&&typeof Xc=="function"&&(s=Xc(s._payload)),b.Children.forEach(s,g=>{if(hg(g)){p=!0;const D=g;let G="child"in D.props?D.props.child:D.props.children;lf(G)&&typeof Xc=="function"&&(G=Xc(G._payload)),h=$S(D,G),A.push(h?.props?.children)}else A.push(g)}),h?h=b.cloneElement(h,void 0,A):!p&&b.Children.count(s)===1&&b.isValidElement(s)&&(h=s);const C=h?vg(h):void 0,H=At(f,C);if(!h){if(s||s===0)throw new Error(p?PS(i):WS(i));return s}const E=mg(v,h.props??{});return h.type!==b.Fragment&&(E.ref=f?H:C),b.cloneElement(h,E)});return c.displayName=`${i}.Slot`,c}Wt(Cn,"createSlot");var JS=Cn("Slot"),dg=Symbol.for("radix.slottable");function IS(i){const c=Wt(r=>"child"in r?r.children(r.child):r.children,"Slottable");return c.displayName=`${i}.Slottable`,c.__radixId=dg,c}Wt(IS,"createSlottable");var $S=Wt((i,c)=>{if("child"in i.props){const r=i.props.child;return b.isValidElement(r)?b.cloneElement(r,void 0,i.props.children(r.props.children)):null}return b.isValidElement(c)?c:null},"getSlottableElementFromSlottable");function mg(i,c){const r={...c};for(const f in c){const s=i[f],v=c[f];/^on[A-Z]/.test(f)?s&&v?r[f]=(...h)=>{const p=v(...h);return s(...h),p}:s&&(r[f]=s):f==="style"?r[f]={...s,...v}:f==="className"?r[f]=[s,v].filter(Boolean).join(" "):f==="aria-describedby"&&(r[f]=yg(v,s))}return{...i,...r}}Wt(mg,"mergeProps");function vg(i){let c=Object.getOwnPropertyDescriptor(i.props,"ref")?.get,r=c&&"isReactWarning"in c&&c.isReactWarning;return r?i.ref:(c=Object.getOwnPropertyDescriptor(i,"ref")?.get,r=c&&"isReactWarning"in c&&c.isReactWarning,r?i.props.ref:i.props.ref||i.ref)}Wt(vg,"getElementRef");function hg(i){return b.isValidElement(i)&&typeof i.type=="function"&&"__radixId"in i.type&&i.type.__radixId===dg}Wt(hg,"isSlottable");var FS=Symbol.for("react.lazy");function lf(i){return i!=null&&typeof i=="object"&&"$$typeof"in i&&i.$$typeof===FS&&"_payload"in i&&gg(i._payload)}Wt(lf,"isLazyComponent");function gg(i){return typeof i=="object"&&i!==null&&"then"in i}Wt(gg,"isPromiseLike");function yg(...i){const c=new Set;for(const r of i)if(typeof r=="string")for(const f of String(r).trim().split(/\s+/))f&&c.add(f);return c.size>0?Array.from(c).join(" "):void 0}Wt(yg,"concatAriaDescribedby");var WS=Wt(i=>`${i} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),PS=Wt(i=>`${i} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),Xc=b[" use ".trim().toString()],ih=i=>typeof i=="boolean"?`${i}`:i===0?"0":i,ch=Ih,pf=(i,c)=>r=>{var f;if(c?.variants==null)return ch(i,r?.class,r?.className);const{variants:s,defaultVariants:v}=c,h=Object.keys(s).map(C=>{const H=r?.[C],E=v?.[C];if(H===null)return null;const g=ih(H)||ih(E);return s[C][g]}),p=r&&Object.entries(r).reduce((C,H)=>{let[E,g]=H;return g===void 0||(C[E]=g),C},{}),A=c==null||(f=c.compoundVariants)===null||f===void 0?void 0:f.reduce((C,H)=>{let{class:E,className:g,...D}=H;return Object.entries(D).every(G=>{let[M,L]=G;return Array.isArray(L)?L.includes({...v,...p}[M]):{...v,...p}[M]===L})?[...C,E,g]:C},[]);return ch(i,h,A,r?.class,r?.className)},ex=_l((i=>{var c=Symbol.for("react.transitional.element"),r=Symbol.for("react.fragment");function f(s,v,h){var p=null;if(h!==void 0&&(p=""+h),v.key!==void 0&&(p=""+v.key),"key"in v){h={};for(var A in v)A!=="key"&&(h[A]=v[A])}else h=v;return v=h.ref,{$$typeof:c,type:s,key:p,ref:v!==void 0?v:null,props:h}}i.Fragment=r,i.jsx=f,i.jsxs=f})),tx=_l(((i,c)=>{c.exports=ex()})),m=tx(),lx=pf("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg font-medium 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:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/88",destructive:"bg-destructive text-white hover:bg-destructive/90",outline:"border border-input bg-transparent 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-5 text-sm",sm:"h-9 rounded-md px-3 text-sm",lg:"h-11 rounded-md px-7 text-base",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),Tl=b.forwardRef(({className:i,variant:c,size:r,asChild:f=!1,...s},v)=>(0,m.jsx)(f?JS:"button",{className:ft(lx({variant:c,size:r}),i),ref:v,...s}));Tl.displayName="Button";var nx=Object.defineProperty,eu=(i,c)=>nx(i,"name",{value:c,configurable:!0}),bg=!!(typeof window<"u"&&window.document&&window.document.createElement);function il(i,c,{checkForDefaultPrevented:r=!0}={}){return eu(function(s){if(i?.(s),r===!1||!s||!s.defaultPrevented)return c?.(s)},"handleEvent")}eu(il,"composeEventHandlers");function ax(i){if(!bg)throw new Error("Cannot access window outside of the DOM");return i?.ownerDocument?.defaultView??window}eu(ax,"getOwnerWindow");function nf(i){if(!bg)throw new Error("Cannot access document outside of the DOM");return i?.ownerDocument??document}eu(nf,"getOwnerDocument");function pg(i,c=!1){const{activeElement:r}=nf(i);if(!r?.nodeName)return null;if(Sg(r)&&r.contentDocument)return pg(r.contentDocument.body,c);if(c){const f=r.getAttribute("aria-activedescendant");if(f){const s=nf(r).getElementById(f);if(s)return s}}return r}eu(pg,"getActiveElement");function Sg(i){return i.tagName==="IFRAME"}eu(Sg,"isFrame");var ux=Object.defineProperty,Ft=(i,c)=>ux(i,"name",{value:c,configurable:!0});function ix(i,c){const r=b.createContext(c);r.displayName=i+"Context";const f=Ft(v=>{const{children:h,...p}=v,A=b.useMemo(()=>p,Object.values(p));return(0,m.jsx)(r.Provider,{value:A,children:h})},"Provider");f.displayName=i+"Provider";function s(v,h={}){const{optional:p=!1}=h,A=b.useContext(r);if(A)return A;if(c!==void 0)return c;if(!p)throw new Error(`\`${v}\` must be used within \`${i}\``)}return Ft(s,"useContext"),[f,s]}Ft(ix,"createContext");function tu(i,c=[]){let r=[];function f(v,h){const p=b.createContext(h);p.displayName=v+"Context";const A=r.length;r=[...r,h];const C=Ft(E=>{const{scope:g,children:D,...G}=E,M=g?.[i]?.[A]||p,L=b.useMemo(()=>G,Object.values(G));return(0,m.jsx)(M.Provider,{value:L,children:D})},"Provider");C.displayName=v+"Provider";function H(E,g,D={}){const{optional:G=!1}=D,M=g?.[i]?.[A]||p,L=b.useContext(M);if(L)return L;if(h!==void 0)return h;if(!G)throw new Error(`\`${E}\` must be used within \`${v}\``)}return Ft(H,"useContext"),[C,H]}Ft(f,"createContext");const s=Ft(()=>{const v=r.map(h=>b.createContext(h));return Ft(function(p){const A=p?.[i]||v;return b.useMemo(()=>({[`__scope${i}`]:{...p,[i]:A}}),[p,A])},"useScope")},"createScope");return s.scopeName=i,[f,xg(s,...c)]}Ft(tu,"createContextScope");function xg(...i){const c=i[0];if(i.length===1)return c;const r=Ft(()=>{const f=i.map(s=>({useScope:s(),scopeName:s.scopeName}));return Ft(function(v){const h=f.reduce((p,{useScope:A,scopeName:C})=>{const H=A(v)[`__scope${C}`];return{...p,...H}},{});return b.useMemo(()=>({[`__scope${c.scopeName}`]:h}),[h])},"useComposedScopes")},"createScope");return r.scopeName=c.scopeName,r}Ft(xg,"composeContextScopes");var Zl=globalThis?.document?b.useLayoutEffect:()=>{},cx=Object.defineProperty,rx=(i,c)=>cx(i,"name",{value:c,configurable:!0}),ox=b[" useId ".trim().toString()]||(()=>{}),sx=0;function Fa(i){const[c,r]=b.useState(ox());return Zl(()=>{i||r(f=>f??String(sx++))},[i]),i||(c?`radix-${c}`:"")}rx(Fa,"useId");var fx=Object.defineProperty,dx=(i,c)=>fx(i,"name",{value:c,configurable:!0}),rh=b[" useEffectEvent ".trim().toString()],oh=b[" useInsertionEffect ".trim().toString()];function Eg(i){if(typeof rh=="function")return rh(i);const c=b.useRef(()=>{throw new Error("Cannot call an event handler while rendering.")});return typeof oh=="function"?oh(()=>{c.current=i}):Zl(()=>{c.current=i}),b.useMemo(()=>((...r)=>c.current?.(...r)),[])}dx(Eg,"useEffectEvent");var mx=Object.defineProperty,ci=(i,c)=>mx(i,"name",{value:c,configurable:!0}),vx=b[" useInsertionEffect ".trim().toString()]||Zl;function ri({prop:i,defaultProp:c,onChange:r=ci(()=>{},"onChange"),caller:f}){const[s,v,h]=Tg({defaultProp:c,onChange:r}),p=i!==void 0;return[p?i:s,b.useCallback(C=>{if(p){const H=_g(C)?C(i):C;H!==i&&h.current?.(H)}else v(C)},[p,i,v,h])]}ci(ri,"useControllableState");function Tg({defaultProp:i,onChange:c}){const[r,f]=b.useState(i),s=b.useRef(r),v=b.useRef(c);return vx(()=>{v.current=c},[c]),b.useEffect(()=>{s.current!==r&&(v.current?.(r),s.current=r)},[r,s]),[r,f,v]}ci(Tg,"useUncontrolledState");function _g(i){return typeof i=="function"}ci(_g,"isFunction");var sh=Symbol("RADIX:SYNC_STATE");function hx(i,c,r,f){const{prop:s,defaultProp:v,onChange:h,caller:p}=c,A=s!==void 0,C=Eg(h),H=[{...r,state:v}];f&&H.push(f);const[E,g]=b.useReducer((L,V)=>{if(V.type===sh)return{...L,state:V.state};const X=i(L,V);return A&&!Object.is(X.state,L.state)&&C(X.state),X},...H),D=E.state,G=b.useRef(D);b.useEffect(()=>{G.current!==D&&(G.current=D,A||C(D))},[D,G,A]);const M=b.useMemo(()=>s!==void 0?{...E,state:s}:E,[E,s]);return b.useEffect(()=>{A&&!Object.is(s,E.state)&&g({type:sh,state:s})},[s,E.state,A]),[M,g]}ci(hx,"useControllableStateReducer");var Ng=Rh(Dh(),1),gx=Object.defineProperty,yx=(i,c)=>gx(i,"name",{value:c,configurable:!0}),qt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((i,c)=>{const r=Cn(`Primitive.${c}`),f=b.forwardRef((s,v)=>{const{asChild:h,...p}=s,A=h?r:c;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,m.jsx)(A,{...p,ref:v})});return f.displayName=`Primitive.${c}`,{...i,[c]:f}},{});function Cg(i,c){i&&Ng.flushSync(()=>i.dispatchEvent(c))}yx(Cg,"dispatchDiscreteCustomEvent");var bx=Object.defineProperty,px=(i,c)=>bx(i,"name",{value:c,configurable:!0});function Wa(i){const c=b.useRef(i);return b.useEffect(()=>{c.current=i}),b.useMemo(()=>((...r)=>c.current?.(...r)),[])}px(Wa,"useCallbackRef");var Sx=Object.defineProperty,lt=(i,c)=>Sx(i,"name",{value:c,configurable:!0}),af="dismissableLayer.update",xx="dismissableLayer.pointerDownOutside",Ex="dismissableLayer.focusOutside",fh,Ag=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Tx=b.forwardRef(lt(function(c,r){const{disableOutsidePointerEvents:f=!1,deferPointerDownOutside:s=!1,onEscapeKeyDown:v,onPointerDownOutside:h,onFocusOutside:p,onInteractOutside:A,onDismiss:C,...H}=c,E=b.useContext(Ag),[g,D]=b.useState(null),G=g?.ownerDocument??globalThis?.document,[,M]=b.useState({}),L=At(r,D),V=Array.from(E.layers),[X]=[...E.layersWithOutsidePointerEventsDisabled].slice(-1),B=X?V.indexOf(X):-1,Z=g?V.indexOf(g):-1,ue=E.layersWithOutsidePointerEventsDisabled.size>0,ee=Z>=B,W=b.useRef(!1),w=zg(se=>{h?.(se),A?.(se),se.defaultPrevented||C?.()},{ownerDocument:G,deferPointerDownOutside:s,isDeferredPointerDownOutsideRef:W,dismissableSurfaces:E.dismissableSurfaces,shouldHandlePointerDownOutside:b.useCallback(se=>{if(!(se instanceof Node))return!1;const ke=[...E.branches].some(Fe=>Fe.contains(se));return ee&&!ke},[E.branches,ee])}),ne=Rg(se=>{if(s&&W.current)return;const ke=se.target;[...E.branches].some(Fe=>Fe.contains(ke))||(p?.(se),A?.(se),se.defaultPrevented||C?.())},G),He=g?Z===V.length-1:!1,Ce=Wa(se=>{se.key==="Escape"&&(v?.(se),!se.defaultPrevented&&C&&(se.preventDefault(),C()))});return b.useEffect(()=>{if(He)return G.addEventListener("keydown",Ce,{capture:!0}),()=>G.removeEventListener("keydown",Ce,{capture:!0})},[G,He,Ce]),b.useEffect(()=>{if(g)return f&&(E.layersWithOutsidePointerEventsDisabled.size===0&&(fh=G.body.style.pointerEvents,G.body.style.pointerEvents="none"),E.layersWithOutsidePointerEventsDisabled.add(g)),E.layers.add(g),uf(),()=>{f&&(E.layersWithOutsidePointerEventsDisabled.delete(g),E.layersWithOutsidePointerEventsDisabled.size===0&&(G.body.style.pointerEvents=fh))}},[g,G,f,E]),b.useEffect(()=>()=>{g&&(E.layers.delete(g),E.layersWithOutsidePointerEventsDisabled.delete(g),uf())},[g,E]),b.useEffect(()=>{const se=lt(()=>M({}),"handleUpdate");return document.addEventListener(af,se),()=>document.removeEventListener(af,se)},[]),(0,m.jsx)(qt.div,{...H,ref:L,style:{pointerEvents:ue?ee?"auto":"none":void 0,...c.style},onFocusCapture:il(c.onFocusCapture,ne.onFocusCapture),onBlurCapture:il(c.onBlurCapture,ne.onBlurCapture),onPointerDownCapture:il(c.onPointerDownCapture,w.onPointerDownCapture)})},"DismissableLayer"));function Og(){const i=b.useContext(Ag),[c,r]=b.useState(null);return b.useEffect(()=>{if(c)return i.dismissableSurfaces.add(c),()=>{i.dismissableSurfaces.delete(c)}},[c,i.dismissableSurfaces]),r}lt(Og,"useDismissableLayerSurface");var _x=lt(()=>!0,"IS_TRUE");function zg(i,c){const{ownerDocument:r=globalThis?.document,deferPointerDownOutside:f=!1,isDeferredPointerDownOutsideRef:s,dismissableSurfaces:v,shouldHandlePointerDownOutside:h=_x}=c,p=Wa(i),A=b.useRef(!1),C=b.useRef(!1),H=b.useRef(new Map),E=b.useRef(()=>{});return b.useEffect(()=>{function g(){C.current=!1,s.current=!1,H.current.clear()}lt(g,"resetOutsideInteraction");function D(){return Array.from(H.current.values()).some(Boolean)}lt(D,"isOutsideInteractionIntercepted");function G(B){if(!C.current)return;const Z=B.target;Z instanceof Node&&[...v].some(ue=>ue.contains(Z))||H.current.set(B.type,!0),B.type==="click"&&window.setTimeout(()=>{C.current&&E.current()},0)}lt(G,"handleInteractionCapture");function M(B){C.current&&H.current.set(B.type,!1)}lt(M,"handleInteractionBubble");const L=lt(B=>{if(B.target&&!A.current){let Z=function(){r.removeEventListener("click",E.current);const ee=D();g(),ee||Sf(xx,p,ue,{discrete:!0})};if(lt(Z,"handleAndDispatchPointerDownOutsideEvent"),!h(B.target)){r.removeEventListener("click",E.current),g(),A.current=!1;return}const ue={originalEvent:B};C.current=!0,s.current=f&&B.button===0,H.current.clear(),!f||B.button!==0?Z():(r.removeEventListener("click",E.current),E.current=Z,r.addEventListener("click",E.current,{once:!0}))}else r.removeEventListener("click",E.current),g();A.current=!1},"handlePointerDown"),V=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const B of V)r.addEventListener(B,G,!0),r.addEventListener(B,M);const X=window.setTimeout(()=>{r.addEventListener("pointerdown",L)},0);return()=>{window.clearTimeout(X),r.removeEventListener("pointerdown",L),r.removeEventListener("click",E.current);for(const B of V)r.removeEventListener(B,G,!0),r.removeEventListener(B,M)}},[r,p,f,s,v,h]),{onPointerDownCapture:lt(()=>A.current=!0,"onPointerDownCapture")}}lt(zg,"usePointerDownOutside");function Rg(i,c=globalThis?.document){const r=Wa(i),f=b.useRef(!1);return b.useEffect(()=>{const s=lt(v=>{v.target&&!f.current&&Sf(Ex,r,{originalEvent:v},{discrete:!1})},"handleFocus");return c.addEventListener("focusin",s),()=>c.removeEventListener("focusin",s)},[c,r]),{onFocusCapture:lt(()=>f.current=!0,"onFocusCapture"),onBlurCapture:lt(()=>f.current=!1,"onBlurCapture")}}lt(Rg,"useFocusOutside");function uf(){const i=new CustomEvent(af);document.dispatchEvent(i)}lt(uf,"dispatchUpdate");function Sf(i,c,r,{discrete:f}){const s=r.originalEvent.target,v=new CustomEvent(i,{bubbles:!1,cancelable:!0,detail:r});c&&s.addEventListener(i,c,{once:!0}),f?Cg(s,v):s.dispatchEvent(v)}lt(Sf,"handleAndDispatchCustomEvent");var Nx=Object.defineProperty,Ke=(i,c)=>Nx(i,"name",{value:c,configurable:!0}),Xs="focusScope.autoFocusOnMount",Qs="focusScope.autoFocusOnUnmount",dh={bubbles:!1,cancelable:!0},Cx=b.forwardRef(Ke(function(c,r){const{loop:f=!1,trapped:s=!1,branches:v,onMountAutoFocus:h,onUnmountAutoFocus:p,...A}=c,[C,H]=b.useState(null),E=Wa(h),g=Wa(p),D=b.useRef(null),G=At(r,H),M=b.useRef(v);b.useEffect(()=>{M.current=v});const L=b.useCallback(B=>B?C?.contains(B)?!0:!!M.current?.some(Z=>Z.contains(B)):!1,[C]),V=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(s){let B=function(W){if(V.paused||!C)return;const w=W.target;L(w)?D.current=w:Vl(D.current,{select:!0})},Z=function(W){if(V.paused||!C)return;const w=W.relatedTarget;w!==null&&(L(w)||Vl(D.current,{select:!0}))},ue=function(W){if(document.activeElement===document.body)for(const w of W)w.removedNodes.length>0&&Vl(C)};Ke(B,"handleFocusIn"),Ke(Z,"handleFocusOut"),Ke(ue,"handleMutations"),document.addEventListener("focusin",B),document.addEventListener("focusout",Z);const ee=new MutationObserver(ue);return C&&ee.observe(C,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",B),document.removeEventListener("focusout",Z),ee.disconnect()}}},[s,C,V.paused,L]),b.useEffect(()=>{if(C){mh.add(V);const B=document.activeElement;if(!C.contains(B)){const Z=new CustomEvent(Xs,dh);C.addEventListener(Xs,E),C.dispatchEvent(Z),Z.defaultPrevented||(wg(Yg(xf(C)),{select:!0}),document.activeElement===B&&Vl(C))}return()=>{C.removeEventListener(Xs,E),setTimeout(()=>{const Z=new CustomEvent(Qs,dh);C.addEventListener(Qs,g),C.dispatchEvent(Z),Z.defaultPrevented||Vl(B??document.body,{select:!0}),C.removeEventListener(Qs,g),mh.remove(V)},0)}}},[C,E,g,V]);const X=b.useCallback(B=>{if(!f&&!s||V.paused)return;const Z=B.key==="Tab"&&!B.altKey&&!B.ctrlKey&&!B.metaKey,ue=document.activeElement;if(Z&&ue){const ee=B.currentTarget,[W,w]=Ug(ee);W&&w?!B.shiftKey&&ue===w?(B.preventDefault(),f&&Vl(W,{select:!0})):B.shiftKey&&ue===W&&(B.preventDefault(),f&&Vl(w,{select:!0})):ue===ee&&B.preventDefault()}},[f,s,V.paused]);return(0,m.jsx)(qt.div,{tabIndex:-1,...A,ref:G,onKeyDown:X})},"FocusScope")),Dg=b.createContext(null);function jg({registry:i,children:c}){return i?(0,m.jsx)(Dg.Provider,{value:i,children:c}):c}Ke(jg,"FocusScopeBranchProvider");function Mg(){const[i,c]=b.useState([]);return{nodes:i,registry:b.useMemo(()=>({add:Ke(r=>c(f=>f.includes(r)?f:[...f,r]),"add"),remove:Ke(r=>c(f=>f.filter(s=>s!==r)),"remove")}),[])}}Ke(Mg,"useFocusScopeBranchRegistry");function Ax(i){const c=b.useContext(Dg);b.useEffect(()=>{if(!(!i||!c))return c.add(i),()=>c.remove(i)},[i,c])}Ke(Ax,"useFocusScopeBranch");function wg(i,{select:c=!1}={}){const r=document.activeElement;for(const f of i)if(Vl(f,{select:c}),document.activeElement!==r)return}Ke(wg,"focusFirst");function Ug(i){const c=xf(i);return[cf(c,i),cf(c.reverse(),i)]}Ke(Ug,"getTabbableEdges");function xf(i){const c=[],r=document.createTreeWalker(i,NodeFilter.SHOW_ELEMENT,{acceptNode:Ke(f=>{const s=f.tagName==="INPUT"&&f.type==="hidden";return f.disabled||f.hidden||s?NodeFilter.FILTER_SKIP:f.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},"acceptNode")});for(;r.nextNode();)c.push(r.currentNode);return c}Ke(xf,"getTabbableCandidates");function cf(i,c){const r=typeof c.checkVisibility=="function"&&c.checkVisibility({checkVisibilityCSS:!0});for(const f of i)if(!(r?!f.checkVisibility({checkVisibilityCSS:!0}):Hg(f,{upTo:c})))return f}Ke(cf,"findVisible");function Hg(i,{upTo:c}){if(getComputedStyle(i).visibility==="hidden")return!0;for(;i;){if(c!==void 0&&i===c)return!1;if(getComputedStyle(i).display==="none")return!0;i=i.parentElement}return!1}Ke(Hg,"isHidden");function Bg(i){return i instanceof HTMLInputElement&&"select"in i}Ke(Bg,"isSelectableInput");function Vl(i,{select:c=!1}={}){if(i&&i.focus){const r=document.activeElement;i.focus({preventScroll:!0}),i!==r&&Bg(i)&&c&&i.select()}}Ke(Vl,"focus");var mh=Lg();function Lg(){let i=[];return{add(c){const r=i[0];c!==r&&r?.pause(),i=rf(i,c),i.unshift(c)},remove(c){i=rf(i,c),i[0]?.resume()}}}Ke(Lg,"createFocusScopesStack");function rf(i,c){const r=[...i],f=r.indexOf(c);return f!==-1&&r.splice(f,1),r}Ke(rf,"arrayRemove");function Yg(i){return i.filter(c=>c.tagName!=="A")}Ke(Yg,"removeLinks");var Ox=Object.defineProperty,zx=(i,c)=>Ox(i,"name",{value:c,configurable:!0}),Rx=b.forwardRef(zx(function(c,r){const{container:f,...s}=c,[v,h]=b.useState(!1);Zl(()=>h(!0),[]);const p=f||v&&globalThis?.document?.body;return p?Ng.createPortal((0,m.jsx)(qt.div,{...s,ref:r}),p):null},"Portal")),Dx=Object.defineProperty,Kl=(i,c)=>Dx(i,"name",{value:c,configurable:!0});function Gg(i,c){return b.useReducer((r,f)=>c[r][f]??r,i)}Kl(Gg,"useStateMachine");var Pc=Kl(i=>{const{present:c,children:r}=i,f=qg(c),s=typeof r=="function"?r({present:f.isPresent}):b.Children.only(r),v=Vg(f.ref,Xg(s));return typeof r=="function"||f.isPresent?b.cloneElement(s,{ref:v}):null},"Presence");function qg(i){const[c,r]=b.useState(),f=b.useRef(null),s=b.useRef(i),v=b.useRef("none"),h=b.useRef(void 0),[p,A]=Gg(i?"mounted":"unmounted",{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{p==="mounted"?(v.current=h.current??$a(f.current),h.current=void 0):v.current="none"},[p]),Zl(()=>{const C=f.current,H=s.current;if(H!==i){const E=v.current,g=$a(C);i?(h.current=g,A("MOUNT")):g==="none"||C?.display==="none"?A("UNMOUNT"):A(H&&E!==g?"ANIMATION_OUT":"UNMOUNT"),s.current=i}},[i,A]),Zl(()=>{if(c){let C;const H=c.ownerDocument.defaultView??window,E=Kl(D=>{const G=$a(f.current).includes(CSS.escape(D.animationName));if(D.target===c&&G&&(A("ANIMATION_END"),!s.current)){const M=c.style.animationFillMode;c.style.animationFillMode="forwards",C=H.setTimeout(()=>{c.style.animationFillMode==="forwards"&&(c.style.animationFillMode=M)})}},"handleAnimationEnd"),g=Kl(D=>{D.target===c&&(v.current=$a(f.current))},"handleAnimationStart");return c.addEventListener("animationstart",g),c.addEventListener("animationcancel",E),c.addEventListener("animationend",E),()=>{H.clearTimeout(C),c.removeEventListener("animationstart",g),c.removeEventListener("animationcancel",E),c.removeEventListener("animationend",E)}}else A("ANIMATION_END")},[c,A]),{isPresent:["mounted","unmountSuspended"].includes(p),ref:b.useCallback(C=>{if(C){const H=getComputedStyle(C);f.current=H,h.current=$a(H)}else f.current=null;r(C)},[])}}Kl(qg,"usePresence");function of(i,c){if(typeof i=="function")return i(c);i!=null&&(i.current=c)}Kl(of,"setRef");function Vg(...i){const c=b.useRef(i);return c.current=i,b.useCallback(r=>{const f=c.current;let s=!1;const v=f.map(h=>{const p=of(h,r);return!s&&typeof p=="function"&&(s=!0),p});if(s)return()=>{for(let h=0;hjx(i,"name",{value:c,configurable:!0}),Qc=0,Za=null;function Mx(i){return Tf(),i.children}Ef(Mx,"FocusGuards");function Tf(){b.useEffect(()=>{Za||(Za={start:sf(),end:sf()});const{start:i,end:c}=Za;return document.body.firstElementChild!==i&&document.body.insertAdjacentElement("afterbegin",i),document.body.lastElementChild!==c&&document.body.insertAdjacentElement("beforeend",c),Qc++,()=>{Qc===1&&(Za?.start.remove(),Za?.end.remove(),Za=null),Qc=Math.max(0,Qc-1)}},[])}Ef(Tf,"useFocusGuards");function sf(){const i=document.createElement("span");return i.setAttribute("data-radix-focus-guard",""),i.tabIndex=0,i.style.outline="none",i.style.opacity="0",i.style.position="fixed",i.style.pointerEvents="none",i}Ef(sf,"createFocusGuard");var El=function(){return El=Object.assign||function(c){for(var r,f=1,s=arguments.length;f"u")return $x;var c=Fx(i),r=document.documentElement.clientWidth,f=window.innerWidth;return{left:c[0],top:c[1],right:c[2],gap:Math.max(0,f-r+c[2]-c[0])}},Px=kg(),ti="data-scroll-locked",e2=function(i,c,r,f){var s=i.left,v=i.top,h=i.right,p=i.gap;return r===void 0&&(r="margin"),` - .`.concat(Ux,` { - overflow: hidden `).concat(f,`; - padding-right: `).concat(p,"px ").concat(f,`; - } - body[`).concat(ti,`] { - overflow: hidden `).concat(f,`; - overscroll-behavior: contain; - `).concat([c&&"position: relative ".concat(f,";"),r==="margin"&&` - padding-left: `.concat(s,`px; - padding-top: `).concat(v,`px; - padding-right: `).concat(h,`px; - margin-left:0; - margin-top:0; - margin-right: `).concat(p,"px ").concat(f,`; - `),r==="padding"&&"padding-right: ".concat(p,"px ").concat(f,";")].filter(Boolean).join(""),` - } - - .`).concat(Ic,` { - right: `).concat(p,"px ").concat(f,`; - } - - .`).concat($c,` { - margin-right: `).concat(p,"px ").concat(f,`; - } - - .`).concat(Ic," .").concat(Ic,` { - right: 0 `).concat(f,`; - } - - .`).concat($c," .").concat($c,` { - margin-right: 0 `).concat(f,`; - } - - body[`).concat(ti,`] { - `).concat(Hx,": ").concat(p,`px; - } -`)},gh=function(){var i=parseInt(document.body.getAttribute("data-scroll-locked")||"0",10);return isFinite(i)?i:0},t2=function(){b.useEffect(function(){return document.body.setAttribute(ti,(gh()+1).toString()),function(){var i=gh()-1;i<=0?document.body.removeAttribute(ti):document.body.setAttribute(ti,i.toString())}},[])},l2=function(i){var c=i.noRelative,r=i.noImportant,f=i.gapMode,s=f===void 0?"margin":f;t2();var v=b.useMemo(function(){return Wx(s)},[s]);return b.createElement(Px,{styles:e2(v,!c,s,r?"":"!important")})},ff=!1;if(typeof window<"u")try{var Zc=Object.defineProperty({},"passive",{get:function(){return ff=!0,!0}});window.addEventListener("test",Zc,Zc),window.removeEventListener("test",Zc,Zc)}catch{ff=!1}var Ka=ff?{passive:!1}:!1,n2=function(i){return i.tagName==="TEXTAREA"},Jg=function(i,c){if(!(i instanceof Element))return!1;var r=window.getComputedStyle(i);return r[c]!=="hidden"&&!(r.overflowY===r.overflowX&&!n2(i)&&r[c]==="visible")},a2=function(i){return Jg(i,"overflowY")},u2=function(i){return Jg(i,"overflowX")},yh=function(i,c){var r=c.ownerDocument,f=c;do{if(typeof ShadowRoot<"u"&&f instanceof ShadowRoot&&(f=f.host),Ig(i,f)){var s=$g(i,f);if(s[1]>s[2])return!0}f=f.parentNode}while(f&&f!==r.body);return!1},i2=function(i){return[i.scrollTop,i.scrollHeight,i.clientHeight]},c2=function(i){return[i.scrollLeft,i.scrollWidth,i.clientWidth]},Ig=function(i,c){return i==="v"?a2(c):u2(c)},$g=function(i,c){return i==="v"?i2(c):c2(c)},r2=function(i,c){return i==="h"&&c==="rtl"?-1:1},o2=function(i,c,r,f,s){var v=r2(i,window.getComputedStyle(c).direction),h=v*f,p=r.target,A=c.contains(p),C=!1,H=h>0,E=0,g=0;do{if(!p)break;var D=$g(i,p),G=D[0],M=D[1]-D[2]-v*G;(G||M)&&Ig(i,p)&&(E+=M,g+=G);var L=p.parentNode;p=L&&L.nodeType===Node.DOCUMENT_FRAGMENT_NODE?L.host:L}while(!A&&p!==document.body||A&&(c.contains(p)||c===p));return(H&&(s&&Math.abs(E)<1||!s&&h>E)||!H&&(s&&Math.abs(g)<1||!s&&-h>g))&&(C=!0),C},Kc=function(i){return"changedTouches"in i?[i.changedTouches[0].clientX,i.changedTouches[0].clientY]:[0,0]},bh=function(i){return[i.deltaX,i.deltaY]},ph=function(i){return i&&"current"in i?i.current:i},s2=function(i,c){return i[0]===c[0]&&i[1]===c[1]},f2=function(i){return` - .block-interactivity-`.concat(i,` {pointer-events: none;} - .allow-interactivity-`).concat(i,` {pointer-events: all;} -`)},d2=0,ka=[];function m2(i){var c=b.useRef([]),r=b.useRef([0,0]),f=b.useRef(),s=b.useState(d2++)[0],v=b.useState(kg)[0],h=b.useRef(i);b.useEffect(function(){h.current=i},[i]),b.useEffect(function(){if(i.inert){document.body.classList.add("block-interactivity-".concat(s));var M=wx([i.lockRef.current],(i.shards||[]).map(ph),!0).filter(Boolean);return M.forEach(function(L){return L.classList.add("allow-interactivity-".concat(s))}),function(){document.body.classList.remove("block-interactivity-".concat(s)),M.forEach(function(L){return L.classList.remove("allow-interactivity-".concat(s))})}}},[i.inert,i.lockRef.current,i.shards]);var p=b.useCallback(function(M,L){if("touches"in M&&M.touches.length===2||M.type==="wheel"&&M.ctrlKey)return!h.current.allowPinchZoom;var V=Kc(M),X=r.current,B="deltaX"in M?M.deltaX:X[0]-V[0],Z="deltaY"in M?M.deltaY:X[1]-V[1],ue,ee=M.target,W=Math.abs(B)>Math.abs(Z)?"h":"v";if("touches"in M&&W==="h"&&ee.type==="range")return!1;var w=window.getSelection(),ne=w&&w.anchorNode;if(ne&&(ne===ee||ne.contains(ee)))return!1;var He=yh(W,ee);if(!He)return!0;if(He?ue=W:(ue=W==="v"?"h":"v",He=yh(W,ee)),!He)return!1;if(!f.current&&"changedTouches"in M&&(B||Z)&&(f.current=ue),!ue)return!0;var Ce=f.current||ue;return o2(Ce,L,M,Ce==="h"?B:Z,!0)},[]),A=b.useCallback(function(M){var L=M;if(!(!ka.length||ka[ka.length-1]!==v)){var V="deltaY"in L?bh(L):Kc(L),X=c.current.filter(function(Z){return Z.name===L.type&&(Z.target===L.target||L.target===Z.shadowParent)&&s2(Z.delta,V)})[0];if(X&&X.should){L.cancelable&&L.preventDefault();return}if(!X){var B=(h.current.shards||[]).map(ph).filter(Boolean).filter(function(Z){return Z.contains(L.target)});(B.length>0?p(L,B[0]):!h.current.noIsolation)&&L.cancelable&&L.preventDefault()}}},[]),C=b.useCallback(function(M,L,V,X){var B={name:M,delta:L,target:V,should:X,shadowParent:v2(V)};c.current.push(B),setTimeout(function(){c.current=c.current.filter(function(Z){return Z!==B})},1)},[]),H=b.useCallback(function(M){r.current=Kc(M),f.current=void 0},[]),E=b.useCallback(function(M){C(M.type,bh(M),M.target,p(M,i.lockRef.current))},[]),g=b.useCallback(function(M){C(M.type,Kc(M),M.target,p(M,i.lockRef.current))},[]);b.useEffect(function(){return ka.push(v),i.setCallbacks({onScrollCapture:E,onWheelCapture:E,onTouchMoveCapture:g}),document.addEventListener("wheel",A,Ka),document.addEventListener("touchmove",A,Ka),document.addEventListener("touchstart",H,Ka),function(){ka=ka.filter(function(M){return M!==v}),document.removeEventListener("wheel",A,Ka),document.removeEventListener("touchmove",A,Ka),document.removeEventListener("touchstart",H,Ka)}},[]);var D=i.removeScrollBar,G=i.inert;return b.createElement(b.Fragment,null,G?b.createElement(v,{styles:f2(s)}):null,D?b.createElement(l2,{noRelative:i.noRelative,gapMode:i.gapMode}):null)}function v2(i){for(var c=null;i!==null;)i instanceof ShadowRoot&&(c=i.host,i=i.host),i=i.parentNode;return c}var h2=Xx(Kg,m2),Fg=b.forwardRef(function(i,c){return b.createElement(er,El({},i,{ref:c,sideCar:h2}))});Fg.classNames=er.classNames;var g2=function(i){return typeof document>"u"?null:(Array.isArray(i)?i[0]:i).ownerDocument.body},Ja=new WeakMap,kc=new WeakMap,Jc={},Js=0,Wg=function(i){return i&&(i.host||Wg(i.parentNode))},y2=function(i,c){return c.map(function(r){if(i.contains(r))return r;var f=Wg(r);return f&&i.contains(f)?f:(console.error("aria-hidden",r,"in not contained inside",i,". Doing nothing"),null)}).filter(function(r){return!!r})},b2=function(i,c,r,f){var s=y2(c,Array.isArray(i)?i:[i]);Jc[r]||(Jc[r]=new WeakMap);var v=Jc[r],h=[],p=new Set,A=new Set(s),C=function(E){!E||p.has(E)||(p.add(E),C(E.parentNode))};s.forEach(C);var H=function(E){!E||A.has(E)||Array.prototype.forEach.call(E.children,function(g){if(p.has(g))H(g);else try{var D=g.getAttribute(f),G=D!==null&&D!=="false",M=(Ja.get(g)||0)+1,L=(v.get(g)||0)+1;Ja.set(g,M),v.set(g,L),h.push(g),M===1&&G&&kc.set(g,!0),L===1&&g.setAttribute(r,"true"),G||g.setAttribute(f,"true")}catch(V){console.error("aria-hidden: cannot operate on ",g,V)}})};return H(c),p.clear(),Js++,function(){h.forEach(function(E){var g=Ja.get(E)-1,D=v.get(E)-1;Ja.set(E,g),v.set(E,D),g||(kc.has(E)||E.removeAttribute(f),kc.delete(E)),D||E.removeAttribute(r)}),Js--,Js||(Ja=new WeakMap,Ja=new WeakMap,kc=new WeakMap,Jc={})}},p2=function(i,c,r){r===void 0&&(r="data-aria-hidden");var f=Array.from(Array.isArray(i)?i:[i]),s=c||g2(i);return s?(f.push.apply(f,Array.from(s.querySelectorAll("[aria-live], script"))),b2(f,s,r,"aria-hidden")):function(){return null}},S2=Object.defineProperty,Ot=(i,c)=>S2(i,"name",{value:c,configurable:!0}),_f="Dialog",[Pg,QE]=tu(_f),[x2,cl]=Pg(_f),E2=Ot(i=>{const{__scopeDialog:c,children:r,open:f,defaultOpen:s,onOpenChange:v,modal:h=!0}=i,p=b.useRef(null),A=b.useRef(null),{nodes:C,registry:H}=Mg(),[E,g]=ri({prop:f,defaultProp:s??!1,onChange:v,caller:_f}),[D,G]=b.useState(0),[M,L]=b.useState(0);return(0,m.jsx)(x2,{scope:c,triggerRef:p,contentRef:A,contentId:Fa(),titleId:Fa(),descriptionId:Fa(),titlePresent:D>0,descriptionPresent:M>0,setTitleCount:G,setDescriptionCount:L,open:E,onOpenChange:g,onOpenToggle:b.useCallback(()=>g(V=>!V),[g]),modal:h,branchNodes:C,branchRegistry:H,children:r})},"Dialog"),T2="DialogTrigger",_2=b.forwardRef(Ot(function(c,r){const{__scopeDialog:f,...s}=c,v=cl(T2,f),h=At(r,v.triggerRef);return(0,m.jsx)(qt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":v.open,"aria-controls":v.open?v.contentId:void 0,"data-state":tr(v.open),...s,ref:h,onClick:il(c.onClick,v.onOpenToggle)})},"DialogTrigger")),ey="DialogPortal",[N2,ty]=Pg(ey,{forceMount:void 0}),C2=Ot(i=>{const{__scopeDialog:c,forceMount:r,children:f,container:s}=i,v=cl(ey,c);return(0,m.jsx)(N2,{scope:c,forceMount:r,children:b.Children.map(f,h=>(0,m.jsx)(Pc,{present:r||v.open,children:(0,m.jsx)(Rx,{asChild:!0,container:s,children:h})}))})},"DialogPortal"),df="DialogOverlay",ly=b.forwardRef(Ot(function(c,r){const f=ty(df,c.__scopeDialog),{forceMount:s=f.forceMount,...v}=c,h=cl(df,c.__scopeDialog);return h.modal?(0,m.jsx)(Pc,{present:s||h.open,children:(0,m.jsx)(O2,{...v,ref:r})}):null},"DialogOverlay")),A2=Cn("DialogOverlay.RemoveScroll"),O2=b.forwardRef(Ot(function(c,r){const{__scopeDialog:f,...s}=c,v=cl(df,f),h=Og(),p=At(r,h);return(0,m.jsx)(Fg,{as:A2,allowPinchZoom:!0,shards:b.useMemo(()=>[v.contentRef,...v.branchNodes.map(A=>({current:A}))],[v.contentRef,v.branchNodes]),children:(0,m.jsx)(qt.div,{"data-state":tr(v.open),...s,ref:p,style:{pointerEvents:"auto",...s.style}})})},"DialogOverlayImpl")),li="DialogContent",ny=b.forwardRef(Ot(function(c,r){const f=ty(li,c.__scopeDialog),{forceMount:s=f.forceMount,...v}=c,h=cl(li,c.__scopeDialog);return(0,m.jsx)(Pc,{present:s||h.open,children:h.modal?(0,m.jsx)(z2,{...v,ref:r}):(0,m.jsx)(R2,{...v,ref:r})})},"DialogContent")),z2=b.forwardRef(Ot(function(c,r){const f=cl(li,c.__scopeDialog),s=b.useRef(null),v=At(r,f.contentRef,s);return b.useEffect(()=>{const h=s.current;if(h)return p2(h)},[]),(0,m.jsx)(ay,{...c,ref:v,trapFocus:f.open,disableOutsidePointerEvents:f.open,onCloseAutoFocus:il(c.onCloseAutoFocus,h=>{h.preventDefault(),f.triggerRef.current?.focus()}),onPointerDownOutside:il(c.onPointerDownOutside,h=>{const p=h.detail.originalEvent,A=p.button===0&&p.ctrlKey===!0;(p.button===2||A)&&h.preventDefault()}),onFocusOutside:il(c.onFocusOutside,h=>h.preventDefault())})},"DialogContentModal")),R2=b.forwardRef(Ot(function(c,r){const f=cl(li,c.__scopeDialog),s=b.useRef(!1),v=b.useRef(!1);return(0,m.jsx)(ay,{...c,ref:r,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:h=>{c.onCloseAutoFocus?.(h),h.defaultPrevented||(s.current||f.triggerRef.current?.focus(),h.preventDefault()),s.current=!1,v.current=!1},onInteractOutside:h=>{c.onInteractOutside?.(h),h.defaultPrevented||(s.current=!0,h.detail.originalEvent.type==="pointerdown"&&(v.current=!0));const p=h.target;f.triggerRef.current?.contains(p)&&h.preventDefault(),h.detail.originalEvent.type==="focusin"&&v.current&&h.preventDefault()}})},"DialogContentNonModal")),ay=b.forwardRef(Ot(function(c,r){const{__scopeDialog:f,trapFocus:s,onOpenAutoFocus:v,onCloseAutoFocus:h,"aria-describedby":p,children:A,...C}=c,H=cl(li,f);return Tf(),(0,m.jsx)(jg,{registry:H.branchRegistry,children:(0,m.jsx)(Cx,{asChild:!0,loop:!0,trapped:s,branches:H.branchNodes,onMountAutoFocus:v,onUnmountAutoFocus:h,children:(0,m.jsx)(Tx,{role:"dialog",id:H.contentId,"aria-labelledby":H.titlePresent?H.titleId:void 0,"aria-describedby":H.descriptionPresent?cy(p,H.descriptionId):p,"data-state":tr(H.open),...C,ref:r,deferPointerDownOutside:!0,onDismiss:()=>H.onOpenChange(!1),children:A})})})},"DialogContentImpl")),uy=b.forwardRef(Ot(function(c,r){const{__scopeDialog:f,...s}=c,v=cl("DialogTitle",f),{setTitleCount:h}=v;return Zl(()=>(h(p=>p+1),()=>h(p=>p-1)),[h]),(0,m.jsx)(qt.h2,{id:v.titleId,...s,ref:r})},"DialogTitle")),iy=b.forwardRef(Ot(function(c,r){const{__scopeDialog:f,...s}=c,v=cl("DialogDescription",f),{setDescriptionCount:h}=v;return Zl(()=>(h(p=>p+1),()=>h(p=>p-1)),[h]),(0,m.jsx)(qt.p,{id:v.descriptionId,...s,ref:r})},"DialogDescription")),D2="DialogClose",j2=b.forwardRef(Ot(function(c,r){const{__scopeDialog:f,...s}=c,v=cl(D2,f);return(0,m.jsx)(qt.button,{type:"button",...s,ref:r,onClick:il(c.onClick,()=>v.onOpenChange(!1))})},"DialogClose"));function cy(...i){const c=new Set;for(const r of i)if(typeof r=="string")for(const f of String(r).trim().split(/\s+/))f&&c.add(f);return c.size>0?Array.from(c).join(" "):void 0}Ot(cy,"concatAriaDescribedby");function tr(i){return i?"open":"closed"}Ot(tr,"getState");var M2=E2,w2=_2,ry=b.forwardRef(({className:i,...c},r)=>(0,m.jsx)(ly,{ref:r,className:ft("fixed inset-0 z-50 bg-black/60 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",i),...c}));ry.displayName=ly.displayName;var U2=pf("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500 data-[state=open]:animate-in data-[state=closed]:animate-out",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"left"}}),oy=b.forwardRef(({side:i="left",className:c,children:r,...f},s)=>(0,m.jsxs)(C2,{children:[(0,m.jsx)(ry,{}),(0,m.jsxs)(ny,{ref:s,className:ft(U2({side:i}),"flex flex-col",c),...f,children:[r,(0,m.jsxs)(j2,{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",children:[(0,m.jsx)(Wp,{className:"h-5 w-5"}),(0,m.jsx)("span",{className:"sr-only",children:"Закрыть"})]})]})]}));oy.displayName=ny.displayName;var sy=({className:i,...c})=>(0,m.jsx)("div",{className:ft("flex flex-col space-y-2 text-left",i),...c});sy.displayName="SheetHeader";var fy=b.forwardRef(({className:i,...c},r)=>(0,m.jsx)(uy,{ref:r,className:ft("text-lg font-semibold text-foreground",i),...c}));fy.displayName=uy.displayName;var dy=b.forwardRef(({className:i,...c},r)=>(0,m.jsx)(iy,{ref:r,className:ft("text-sm text-muted-foreground",i),...c}));dy.displayName=iy.displayName;function Sh(i){return ft("text-sm transition-colors hover:text-foreground",i?"text-foreground font-medium":"text-muted-foreground")}function xh({size:i="sm"}){return(0,m.jsx)(Tl,{asChild:!0,size:i,children:(0,m.jsxs)("a",{href:ni,rel:"nofollow",children:[(0,m.jsx)(Pn,{"aria-hidden":"true"}),"Войти через Telegram"]})})}function H2({activePage:i}){return(0,m.jsx)("header",{className:"sticky top-0 z-40 w-full border-b border-border/70 bg-background/80 backdrop-blur",children:(0,m.jsxs)("div",{className:"container-x flex h-16 items-center justify-between gap-4",children:[(0,m.jsxs)("a",{href:"/",className:"flex items-center gap-2.5","aria-label":ei,children:[(0,m.jsx)("span",{className:"grid h-8 w-8 place-items-center rounded-lg bg-primary/15 text-primary",children:(0,m.jsx)(Pn,{className:"h-4 w-4","aria-hidden":"true"})}),(0,m.jsx)("span",{className:"text-sm font-semibold tracking-tight",children:ei})]}),(0,m.jsx)("nav",{className:"hidden items-center gap-8 md:flex","aria-label":"Основная навигация",children:ef.map(c=>(0,m.jsx)("a",{href:c.href,className:Sh(c.page===i),children:c.label},c.page))}),(0,m.jsx)("div",{className:"hidden md:block",children:(0,m.jsx)(xh,{})}),(0,m.jsx)("div",{className:"md:hidden",children:(0,m.jsxs)(M2,{children:[(0,m.jsx)(w2,{asChild:!0,children:(0,m.jsx)(Tl,{variant:"ghost",size:"icon","aria-label":"Открыть меню",children:(0,m.jsx)(Qp,{"aria-hidden":"true"})})}),(0,m.jsxs)(oy,{side:"left",className:"w-72 gap-6",children:[(0,m.jsxs)(sy,{children:[(0,m.jsx)(fy,{children:ei}),(0,m.jsx)(dy,{children:"Меню сайта"})]}),(0,m.jsxs)("nav",{className:"flex flex-col gap-4","aria-label":"Мобильная навигация",children:[ef.map(c=>(0,m.jsx)("a",{href:c.href,className:Sh(c.page===i),children:c.label},c.page)),(0,m.jsx)("a",{href:Nn,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-muted-foreground",children:"Telegram-бот"}),(0,m.jsx)(xh,{size:"lg"})]})]})]})})]})})}function B2(){return(0,m.jsxs)("footer",{className:"border-t border-border/70 bg-card/40",children:[(0,m.jsxs)("div",{className:"container-x flex flex-col gap-8 py-12 sm:flex-row sm:justify-between",children:[(0,m.jsxs)("div",{className:"max-w-sm",children:[(0,m.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,m.jsx)("span",{className:"grid h-8 w-8 place-items-center rounded-lg bg-primary/15 text-primary",children:(0,m.jsx)(Pn,{className:"h-4 w-4","aria-hidden":"true"})}),(0,m.jsx)("span",{className:"text-sm font-semibold tracking-tight",children:ei})]}),(0,m.jsx)("p",{className:"mt-3 text-sm leading-relaxed text-muted-foreground",children:"OpenAI-совместимый API-шлюз к моделям разных вендоров. Подключение, ключи и поддержка — через Telegram-бота."})]}),(0,m.jsx)("nav",{className:"flex flex-col gap-3","aria-label":"Ссылки в подвале",children:ef.map(i=>(0,m.jsx)("a",{href:i.href,className:"text-sm text-muted-foreground hover:text-foreground",children:i.label},i.page))}),(0,m.jsxs)("div",{className:"flex flex-col gap-3",children:[(0,m.jsx)("a",{href:ni,rel:"nofollow",className:"text-sm text-primary hover:underline",children:"Войти через Telegram"}),(0,m.jsx)("a",{href:Nn,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-muted-foreground hover:text-foreground",children:"Telegram-бот"}),(0,m.jsx)("a",{href:"/api/pricing",className:"text-sm text-muted-foreground hover:text-foreground",children:"Цены (JSON)"})]})]}),(0,m.jsx)("div",{className:"container-x border-t border-border/60 py-6",children:(0,m.jsxs)("p",{className:"text-xs text-muted-foreground",children:["© ",ei,". Цены и модели — актуальные данные из /api/pricing."]})})]})}var L2=pf("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium transition-colors focus:outline-none",{variants:{variant:{default:"border-transparent bg-primary/15 text-primary",secondary:"border-transparent bg-secondary text-secondary-foreground",destructive:"border-transparent bg-destructive text-white",outline:"border-border text-foreground"}},defaultVariants:{variant:"default"}});function lr({className:i,variant:c,...r}){return(0,m.jsx)("div",{className:ft(L2({variant:c}),i),...r})}var Xl=b.forwardRef(({className:i,...c},r)=>(0,m.jsx)("div",{ref:r,className:ft("rounded-xl border border-border bg-card text-card-foreground shadow-sm",i),...c}));Xl.displayName="Card";var oi=b.forwardRef(({className:i,...c},r)=>(0,m.jsx)("div",{ref:r,className:ft("flex flex-col space-y-1.5 p-6",i),...c}));oi.displayName="CardHeader";var Pa=b.forwardRef(({className:i,...c},r)=>(0,m.jsx)("h3",{ref:r,className:ft("text-lg font-semibold leading-none tracking-tight",i),...c}));Pa.displayName="CardTitle";var lu=b.forwardRef(({className:i,...c},r)=>(0,m.jsx)("p",{ref:r,className:ft("text-sm text-muted-foreground",i),...c}));lu.displayName="CardDescription";var Ql=b.forwardRef(({className:i,...c},r)=>(0,m.jsx)("div",{ref:r,className:ft("p-6 pt-0",i),...c}));Ql.displayName="CardContent";var Y2=b.forwardRef(({className:i,...c},r)=>(0,m.jsx)("div",{ref:r,className:ft("flex items-center p-6 pt-0",i),...c}));Y2.displayName="CardFooter";function nr({title:i="Подключитесь за минуту",description:c="Откройте Telegram-бота, получите API-ключ и начните отправлять запросы через единый шлюз."}){return(0,m.jsx)("section",{className:"rounded-2xl border border-border bg-card p-8 sm:p-10",children:(0,m.jsxs)("div",{className:"flex flex-col gap-6 sm:flex-row sm:items-center sm:justify-between",children:[(0,m.jsxs)("div",{className:"max-w-xl",children:[(0,m.jsx)("h2",{className:"text-2xl font-semibold tracking-tight",children:i}),(0,m.jsx)("p",{className:"mt-2 text-sm leading-relaxed text-muted-foreground",children:c})]}),(0,m.jsxs)("div",{className:"flex shrink-0 flex-col gap-3 sm:flex-row",children:[(0,m.jsx)(Tl,{asChild:!0,size:"lg",children:(0,m.jsxs)("a",{href:ni,rel:"nofollow",children:[(0,m.jsx)(Pn,{"aria-hidden":"true"}),"Войти через Telegram"]})}),(0,m.jsx)(Tl,{asChild:!0,variant:"outline",size:"lg",children:(0,m.jsx)("a",{href:Nn,target:"_blank",rel:"noopener noreferrer",children:"Открыть бота"})})]})]})})}var G2=[{icon:Vp,title:"Один эндпоинт",text:"Единый OpenAI-совместимый API вместо отдельных ключей и SDK для каждого вендора."},{icon:qp,title:"Прозрачная тарификация",text:"Стоимость по множителям входа и выхода либо по цене за вызов — как отдаёт upstream."},{icon:Ip,title:"Каталог моделей",text:"Чат и генерация изображений; список моделей и цен приходит напрямую из /api/pricing."},{icon:kp,title:"Ключи и баланс",text:"Выдача ключа, баланс и usage — в консоли после входа через Telegram-бота."}],q2=[`curl ${ui}${sg} \\`,' -H "Authorization: Bearer $GATEWAY_KEY" \\',' -H "Content-Type: application/json" \\'," -d '{",' "model": "<модель-из-/api/pricing>",',' "messages": [{ "role": "user", "content": "Привет" }]'," }'"].join(` -`);function V2(){const i=ii.home;return(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)("section",{className:"container-x flex flex-col items-start gap-6 py-20 sm:py-28",children:[(0,m.jsx)(lr,{variant:"secondary",children:"OpenAI-совместимый API-шлюз"}),(0,m.jsx)("h1",{className:"max-w-3xl text-4xl font-semibold leading-tight tracking-tight sm:text-5xl",children:i.h1}),(0,m.jsx)("p",{className:"max-w-2xl text-base leading-relaxed text-muted-foreground sm:text-lg",children:i.description}),(0,m.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row",children:[(0,m.jsx)(Tl,{asChild:!0,size:"lg",children:(0,m.jsxs)("a",{href:ni,rel:"nofollow",children:[(0,m.jsx)(Pn,{"aria-hidden":"true"}),"Войти через Telegram"]})}),(0,m.jsx)(Tl,{asChild:!0,variant:"outline",size:"lg",children:(0,m.jsx)("a",{href:"/pricing",children:"Смотреть тарифы"})})]})]}),(0,m.jsxs)("section",{className:"container-x pb-20",children:[(0,m.jsx)("h2",{className:"sr-only",children:"Преимущества"}),(0,m.jsx)("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:G2.map(c=>(0,m.jsx)(Xl,{children:(0,m.jsxs)(Ql,{className:"pt-6",children:[(0,m.jsx)(c.icon,{className:"h-6 w-6 text-primary","aria-hidden":"true"}),(0,m.jsx)(Pa,{className:"mt-4 text-base",children:c.title}),(0,m.jsx)(lu,{className:"mt-2 leading-relaxed",children:c.text})]})},c.title))})]}),(0,m.jsxs)("section",{className:"container-x pb-20",children:[(0,m.jsx)("h2",{className:"sr-only",children:"Быстрый старт"}),(0,m.jsxs)("div",{className:"grid gap-4 lg:grid-cols-3",children:[(0,m.jsx)(Xl,{className:"min-w-0 lg:col-span-2",children:(0,m.jsxs)(Ql,{className:"space-y-4 p-6",children:[(0,m.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[(0,m.jsx)($p,{className:"h-4 w-4","aria-hidden":"true"}),"Первый запрос через шлюз"]}),(0,m.jsx)("pre",{className:"overflow-x-auto rounded-lg border border-border bg-background p-4 text-xs leading-relaxed text-foreground",children:(0,m.jsx)("code",{children:q2})}),(0,m.jsx)("p",{className:"text-sm text-muted-foreground",children:"Подставьте base URL и ключ из консоли. Имя модели возьмите из актуального каталога на странице «Тарифы»."})]})}),(0,m.jsx)(Xl,{children:(0,m.jsxs)(Ql,{className:"space-y-3 p-6",children:[(0,m.jsx)(Pa,{className:"text-base",children:"Как начать"}),(0,m.jsxs)("ol",{className:"list-decimal space-y-2 pl-5 text-sm text-muted-foreground",children:[(0,m.jsx)("li",{children:"Откройте Telegram-бота."}),(0,m.jsx)("li",{children:"Получите API-ключ и доступ в консоль."}),(0,m.jsx)("li",{children:"Укажите base URL шлюза в вашем клиенте."}),(0,m.jsx)("li",{children:"Отправляйте запросы к нужной модели."})]})]})})]})]}),(0,m.jsx)("section",{className:"container-x pb-24",children:(0,m.jsx)(nr,{})})]})}var X2="ps-pricing";function Is(i){if(typeof i=="number"&&Number.isFinite(i))return i;if(typeof i=="string"&&i.trim()!==""){const c=Number(i);if(Number.isFinite(c))return c}return null}function $s(i){return Number.isInteger(i)&&Math.abs(i)<1e21?String(i):i.toFixed(4).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function Q2(i,c){if(c==null)return"";const r=i.find(f=>f.id===c);return r&&typeof r.name=="string"?r.name:""}function Z2(i){const c=i.billing_usage_schema;if(c&&typeof c=="object")for(const r of Object.values(c)){const f=r?.unitLabel;if(f&&typeof f.ru=="string"&&f.ru.length>0)return f.ru}return"запрос"}function K2(i){if(i.quota_type===1){const f=Is(i.model_price);return f==null?"—":`$${$s(f)} / ${Z2(i)}`}const c=Is(i.model_ratio),r=Is(i.completion_ratio);return c===0?"бесплатно":`вход ×${c==null?"—":$s(c)} · выход ×${r==null?"—":$s(r)}`}function k2(i){return typeof i=="object"&&i!==null&&typeof i.model_name=="string"}function J2(i){return typeof i=="object"&&i!==null&&typeof i.id=="number"}function my(i){if(typeof i!="object"||i===null)return null;const c=i;if(typeof c.error=="string")return{error:c.error};if(!Array.isArray(c.data))return null;const r=c.data.filter(k2);return r.some(f=>typeof f.model_name=="string")?{data:r,vendors:Array.isArray(c.vendors)?c.vendors.filter(J2):[],success:c.success===!0,pricing_version:typeof c.pricing_version=="string"?c.pricing_version:void 0}:null}function I2(i){const c=i.getElementById(X2);if(!c)return null;const r=c.textContent;if(!r||r.trim()==="")return null;try{return my(JSON.parse(r))}catch{return null}}var Eh={status:"loading",payload:null};function $2(){const[i,c]=(0,b.useState)(Eh),[r,f]=(0,b.useState)(0);return(0,b.useEffect)(()=>{let s=!1;if(r===0&&typeof document<"u"){const h=I2(document);if(h&&!s)return c(Th(h)),()=>{s=!0}}c(Eh);const v=new AbortController;return fetch(ai,{headers:{accept:"application/json"},signal:v.signal}).then(h=>h.ok?h.json():Promise.reject(new Error(String(h.status)))).then(h=>{if(s)return;const p=my(h);c(p?Th(p):{status:"error",payload:null})}).catch(()=>{s||c({status:"error",payload:null})}),()=>{s=!0,v.abort()}},[r]),{...i,reload:()=>f(s=>s+1)}}function Th(i){return i.error&&!i.data?{status:"error",payload:i}:{status:"ready",payload:i}}function F2(){const i=ii.pricing,{status:c,payload:r,reload:f}=$2(),[s,v]=(0,b.useState)(""),[h,p]=(0,b.useState)("all"),A=r?.data??[],C=r?.vendors??[],H=(0,b.useMemo)(()=>{const g=new Set(A.map(D=>D.vendor_id));return C.filter(D=>g.has(D.id))},[A,C]),E=(0,b.useMemo)(()=>{const g=s.trim().toLowerCase(),D=h==="all"?null:Number(h);return A.filter(G=>{const M=g===""||(G.model_name??"").toLowerCase().includes(g),L=D===null||G.vendor_id===D;return M&&L})},[A,s,h]);return(0,m.jsxs)("div",{className:"container-x py-14 sm:py-20",children:[(0,m.jsxs)("header",{className:"max-w-2xl",children:[(0,m.jsx)(lr,{variant:"secondary",children:"Актуальные данные /api/pricing"}),(0,m.jsx)("h1",{className:"mt-4 text-4xl font-semibold tracking-tight",children:i.h1}),(0,m.jsx)("p",{className:"mt-3 text-base leading-relaxed text-muted-foreground",children:i.description})]}),c==="loading"&&(0,m.jsx)(P2,{}),c==="error"&&(0,m.jsx)(eE,{message:r?.error,onRetry:f}),c==="ready"&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)("div",{className:"mt-8 flex flex-col gap-4 sm:flex-row sm:items-center",children:[(0,m.jsxs)("div",{className:"relative w-full sm:max-w-xs",children:[(0,m.jsx)(Zp,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground","aria-hidden":"true"}),(0,m.jsx)("input",{type:"search",value:s,onChange:g=>v(g.target.value),placeholder:"Поиск модели","aria-label":"Поиск модели",className:"h-10 w-full rounded-lg border border-input bg-background pl-9 pr-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"})]}),(0,m.jsxs)("label",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:["Вендор",(0,m.jsxs)("select",{value:h,onChange:g=>p(g.target.value),className:"h-10 rounded-lg border border-input bg-background px-3 text-sm text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,m.jsx)("option",{value:"all",children:"Все"}),H.map(g=>(0,m.jsx)("option",{value:String(g.id),children:g.name},g.id))]})]}),(0,m.jsxs)("span",{"aria-live":"polite",className:"text-sm text-muted-foreground sm:ml-auto",children:["Показано ",E.length," из ",A.length]})]}),(0,m.jsx)(Xl,{className:"mt-6",children:(0,m.jsx)(Ql,{className:"p-0",children:(0,m.jsx)("div",{className:"overflow-x-auto",children:(0,m.jsxs)("table",{className:"w-full text-sm",children:[(0,m.jsx)("caption",{className:"sr-only",children:"Тарификация моделей из /api/pricing"}),(0,m.jsx)("thead",{children:(0,m.jsxs)("tr",{className:"border-b border-border text-left text-muted-foreground",children:[(0,m.jsx)("th",{scope:"col",className:"px-6 py-3 font-medium",children:"Модель"}),(0,m.jsx)("th",{scope:"col",className:"px-6 py-3 font-medium",children:"Вендор"}),(0,m.jsx)("th",{scope:"col",className:"px-6 py-3 font-medium",children:"Тарификация"})]})}),(0,m.jsxs)("tbody",{children:[E.map((g,D)=>(0,m.jsx)(W2,{row:g,vendors:C},D)),E.length===0&&(0,m.jsx)("tr",{children:(0,m.jsx)("td",{colSpan:3,className:"px-6 py-10 text-center text-muted-foreground",children:"Ничего не найдено по заданным фильтрам."})})]})]})})})}),(0,m.jsx)("p",{className:"mt-4 text-xs text-muted-foreground",children:"Значения тарификации берутся из ответа /api/pricing и не пересчитываются вручную. Множители указаны относительно базовой единицы upstream."})]}),(0,m.jsx)("div",{className:"mt-16",children:(0,m.jsx)(nr,{title:"Нужен ключ и баланс?",description:"Войдите через Telegram-бота, чтобы получить API-ключ и увидеть расход по каждой модели в консоли."})})]})}function W2({row:i,vendors:c}){return(0,m.jsxs)("tr",{className:"border-b border-border/60 last:border-0",children:[(0,m.jsx)("td",{className:"px-6 py-3 font-medium text-foreground",children:i.model_name??"—"}),(0,m.jsx)("td",{className:"px-6 py-3 text-muted-foreground",children:Q2(c??[],i.vendor_id)||"—"}),(0,m.jsx)("td",{className:"px-6 py-3 text-foreground",children:K2(i)})]})}function P2(){return(0,m.jsxs)("div",{className:"mt-10 flex flex-col gap-3",role:"status","aria-live":"polite",children:[(0,m.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[(0,m.jsx)(Xp,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"Загружаем актуальные цены…"]}),[0,1,2,3,4].map(i=>(0,m.jsx)("div",{className:"h-12 w-full animate-pulse rounded-lg border border-border bg-muted/40"},i))]})}function eE({message:i,onRetry:c}){return(0,m.jsxs)(Xl,{className:"mt-10 border-destructive/40",children:[(0,m.jsxs)(oi,{children:[(0,m.jsxs)("div",{className:"flex items-center gap-2 text-destructive",children:[(0,m.jsx)(Fp,{className:"h-5 w-5","aria-hidden":"true"}),(0,m.jsx)(Pa,{className:"text-base",children:"Цены временно недоступны"})]}),(0,m.jsx)(lu,{children:i??"Не удалось получить данные /api/pricing. Попробуйте обновить."})]}),(0,m.jsx)(Ql,{children:(0,m.jsx)(Tl,{variant:"outline",onClick:c,children:"Обновить"})})]})}var tE=Object.defineProperty,nt=(i,c)=>tE(i,"name",{value:c,configurable:!0});function vy(i){const c=i+"CollectionProvider",[r,f]=tu(c),[s,v]=r(c,{collectionRef:{current:null},itemMap:new Map}),h=nt(M=>{const{scope:L,children:V}=M,X=b.useRef(null),B=b.useRef(new Map).current;return(0,m.jsx)(s,{scope:L,itemMap:B,collectionRef:X,children:V})},"CollectionProvider");h.displayName=c;const p=i+"CollectionSlot",A=Cn(p),C=b.forwardRef((M,L)=>{const{scope:V,children:X}=M,B=v(p,V),Z=At(L,B.collectionRef);return(0,m.jsx)(A,{ref:Z,children:X})});C.displayName=p;const H=i+"CollectionItemSlot",E="data-radix-collection-item",g=Cn(H),D=b.forwardRef((M,L)=>{const{scope:V,children:X,...B}=M,Z=b.useRef(null),ue=At(L,Z),ee=v(H,V);return b.useEffect(()=>(ee.itemMap.set(Z,{ref:Z,...B}),()=>{ee.itemMap.delete(Z)})),(0,m.jsx)(g,{[E]:"",ref:ue,children:X})});D.displayName=H;function G(M){const L=v(i+"CollectionConsumer",M);return b.useCallback(()=>{const V=L.collectionRef.current;if(!V)return[];const X=Array.from(V.querySelectorAll(`[${E}]`));return Array.from(L.itemMap.values()).sort((B,Z)=>X.indexOf(B.ref.current)-X.indexOf(Z.ref.current))},[L.collectionRef,L.itemMap])}return nt(G,"useCollection"),[{Provider:h,Slot:C,ItemSlot:D},G,f]}nt(vy,"createCollection");var _h=new WeakMap,Fs=class _n extends Map{static{nt(this,"OrderedDict")}#e;constructor(c){super(c),this.#e=[...super.keys()],_h.set(this,!0)}set(c,r){return _h.get(this)&&(this.has(c)?this.#e[this.#e.indexOf(c)]=c:this.#e.push(c)),super.set(c,r),this}insert(c,r,f){const s=this.has(r),v=this.#e.length,h=Nf(c);let p=h>=0?h:v+h;const A=p<0||p>=v?-1:p;if(A===this.size||s&&A===this.size-1||A===-1)return this.set(r,f),this;const C=this.size+(s?0:1);h<0&&p++;const H=[...this.#e];let E,g=!1;for(let D=p;D=this.size&&(s=this.size-1),this.at(s)}keyFrom(c,r){const f=this.indexOf(c);if(f===-1)return;let s=f+r;return s<0&&(s=0),s>=this.size&&(s=this.size-1),this.keyAt(s)}find(c,r){let f=0;for(const s of this){if(Reflect.apply(c,r,[s,f,this]))return s;f++}}findIndex(c,r){let f=0;for(const s of this){if(Reflect.apply(c,r,[s,f,this]))return f;f++}return-1}filter(c,r){const f=[];let s=0;for(const v of this)Reflect.apply(c,r,[v,s,this])&&f.push(v),s++;return new _n(f)}map(c,r){const f=[];let s=0;for(const v of this)f.push([v[0],Reflect.apply(c,r,[v,s,this])]),s++;return new _n(f)}reduce(...c){const[r,f]=c;let s=0,v=f??this.at(0);for(const h of this)s===0&&c.length===1?v=h:v=Reflect.apply(r,this,[v,h,s,this]),s++;return v}reduceRight(...c){const[r,f]=c;let s=f??this.at(-1);for(let v=this.size-1;v>=0;v--){const h=this.at(v);v===this.size-1&&c.length===1?s=h:s=Reflect.apply(r,this,[s,h,v,this])}return s}toSorted(c){const r=[...this.entries()].sort(c);return new _n(r)}toReversed(){const c=new _n;for(let r=this.size-1;r>=0;r--){const f=this.keyAt(r),s=this.get(f);c.set(f,s)}return c}toSpliced(...c){const r=[...this.entries()];return r.splice(...c),new _n(r)}slice(c,r){const f=new _n;let s=this.size-1;if(c===void 0)return f;c<0&&(c=c+this.size),r!==void 0&&r>0&&(s=r-1);for(let v=c;v<=s;v++){const h=this.keyAt(v),p=this.get(h);f.set(h,p)}return f}every(c,r){let f=0;for(const s of this){if(!Reflect.apply(c,r,[s,f,this]))return!1;f++}return!0}some(c,r){let f=0;for(const s of this){if(Reflect.apply(c,r,[s,f,this]))return!0;f++}return!1}};function Fc(i,c){if("at"in Array.prototype)return Array.prototype.at.call(i,c);const r=hy(i,c);return r===-1?void 0:i[r]}nt(Fc,"at");function hy(i,c){const r=i.length,f=Nf(c),s=f>=0?f:r+f;return s<0||s>=r?-1:s}nt(hy,"toSafeIndex");function Nf(i){return i!==i||i===0?0:Math.trunc(i)}nt(Nf,"toSafeInteger");function lE(i){const c=i+"CollectionProvider",[r,f]=tu(c),[s,v]=r(c,{collectionElement:null,collectionRef:{current:null},collectionRefObject:{current:null},itemMap:new Fs,setItemMap:nt(()=>{},"setItemMap")}),h=nt(({state:X,...B})=>X?(0,m.jsx)(A,{...B,state:X}):(0,m.jsx)(p,{...B}),"CollectionProvider");h.displayName=c;const p=nt(X=>{const B=L();return(0,m.jsx)(A,{...X,state:B})},"CollectionInit");p.displayName=c+"Init";const A=nt(X=>{const{scope:B,children:Z,state:ue}=X,ee=b.useRef(null),[W,w]=b.useState(null),ne=At(ee,w),[He,Ce]=ue;return b.useEffect(()=>{if(!W)return;const se=by(()=>{});return se.observe(W,{childList:!0,subtree:!0}),()=>{se.disconnect()}},[W]),(0,m.jsx)(s,{scope:B,itemMap:He,setItemMap:Ce,collectionRef:ne,collectionRefObject:ee,collectionElement:W,children:Z})},"CollectionProviderImpl");A.displayName=c+"Impl";const C=i+"CollectionSlot",H=Cn(C),E=b.forwardRef((X,B)=>{const{scope:Z,children:ue}=X,ee=v(C,Z),W=At(B,ee.collectionRef);return(0,m.jsx)(H,{ref:W,children:ue})});E.displayName=C;const g=i+"CollectionItemSlot",D="data-radix-collection-item",G=Cn(g),M=b.forwardRef((X,B)=>{const{scope:Z,children:ue,...ee}=X,W=b.useRef(null),[w,ne]=b.useState(null),He=At(B,W,ne),{setItemMap:Ce}=v(g,Z),se=b.useRef(ee);gy(se.current,ee)||(se.current=ee);const ke=se.current;return b.useEffect(()=>{const Fe=ke;return Ce(De=>w?De.has(w)?De.set(w,{...Fe,element:w}).toSorted(mf):(De.set(w,{...Fe,element:w}),De.toSorted(mf)):De),()=>{Ce(De=>!w||!De.has(w)?De:(De.delete(w),new Fs(De)))}},[w,ke,Ce]),(0,m.jsx)(G,{[D]:"",ref:He,children:ue})});M.displayName=g;function L(){return b.useState(new Fs)}nt(L,"useInitCollection");function V(X){const{itemMap:B}=v(i+"CollectionConsumer",X);return B}return nt(V,"useCollection"),[{Provider:h,Slot:E,ItemSlot:M},{createCollectionScope:f,useCollection:V,useInitCollection:L}]}nt(lE,"createCollection");function gy(i,c){if(i===c)return!0;if(typeof i!="object"||typeof c!="object"||i==null||c==null)return!1;const r=Object.keys(i),f=Object.keys(c);if(r.length!==f.length)return!1;for(const s of r)if(!Object.prototype.hasOwnProperty.call(c,s)||i[s]!==c[s])return!1;return!0}nt(gy,"shallowEqual");function yy(i,c){return!!(c.compareDocumentPosition(i)&Node.DOCUMENT_POSITION_PRECEDING)}nt(yy,"isElementPreceding");function mf(i,c){return!i[1].element||!c[1].element?0:yy(i[1].element,c[1].element)?-1:1}nt(mf,"sortByDocumentPosition");function by(i){return new MutationObserver(c=>{for(const r of c)if(r.type==="childList"){i();return}})}nt(by,"getChildListObserver");var nE=Object.defineProperty,si=(i,c)=>nE(i,"name",{value:c,configurable:!0}),Cf="Collapsible",[aE,py]=tu(Cf),[uE,Af]=aE(Cf),iE=b.forwardRef(si(function(c,r){const{__scopeCollapsible:f,open:s,defaultOpen:v,disabled:h,onOpenChange:p,...A}=c,[C,H]=ri({prop:s,defaultProp:v??!1,onChange:p,caller:Cf});return(0,m.jsx)(uE,{scope:f,disabled:h,contentId:Fa(),open:C,onOpenToggle:b.useCallback(()=>H(E=>!E),[H]),children:(0,m.jsx)(qt.div,{"data-state":ar(C),"data-disabled":h?"":void 0,...A,ref:r})})},"Collapsible")),cE="CollapsibleTrigger",rE=b.forwardRef(si(function(c,r){const{__scopeCollapsible:f,...s}=c,v=Af(cE,f);return(0,m.jsx)(qt.button,{type:"button","aria-controls":v.open?v.contentId:void 0,"aria-expanded":v.open||!1,"data-state":ar(v.open),"data-disabled":v.disabled?"":void 0,disabled:v.disabled,...s,ref:r,onClick:il(c.onClick,v.onOpenToggle)})},"CollapsibleTrigger")),Sy="CollapsibleContent",oE=b.forwardRef(si(function(c,r){const{forceMount:f,...s}=c,v=Af(Sy,c.__scopeCollapsible);return(0,m.jsx)(Pc,{present:f||v.open,children:({present:h})=>(0,m.jsx)(sE,{...s,ref:r,present:h})})},"CollapsibleContent")),sE=b.forwardRef(si(function(c,r){const{__scopeCollapsible:f,present:s,children:v,...h}=c,p=Af(Sy,f),[A,C]=b.useState(s),H=b.useRef(null),E=At(r,H),g=b.useRef(0),D=g.current,G=b.useRef(0),M=G.current,L=p.open||A,V=b.useRef(L),X=b.useRef(void 0);return b.useEffect(()=>{const B=requestAnimationFrame(()=>V.current=!1);return()=>cancelAnimationFrame(B)},[]),Zl(()=>{const B=H.current;if(B){X.current=X.current||{transitionDuration:B.style.transitionDuration,animationName:B.style.animationName},B.style.transitionDuration="0s",B.style.animationName="none";const Z=B.getBoundingClientRect();g.current=Z.height,G.current=Z.width,V.current||(B.style.transitionDuration=X.current.transitionDuration,B.style.animationName=X.current.animationName),C(s)}},[p.open,s]),(0,m.jsx)(qt.div,{"data-state":ar(p.open),"data-disabled":p.disabled?"":void 0,id:p.contentId,hidden:!L,...h,ref:E,style:{"--radix-collapsible-content-height":D?`${D}px`:void 0,"--radix-collapsible-content-width":M?`${M}px`:void 0,...c.style},children:L&&v})},"CollapsibleContentImpl"));function ar(i){return i?"open":"closed"}si(ar,"getState");var fE=Object.defineProperty,dE=(i,c)=>fE(i,"name",{value:c,configurable:!0}),mE={LTR:"ltr",RTL:"rtl"},vE=b.createContext(void 0);function xy(i){const c=b.useContext(vE);return i||c||mE.LTR}dE(xy,"useDirection");var hE=Object.defineProperty,Gt=(i,c)=>hE(i,"name",{value:c,configurable:!0}),gE={Single:"single",Multiple:"multiple"},Pu={Vertical:"vertical",Horizontal:"horizontal"},yE={LTR:"ltr",RTL:"rtl"},Nl="Accordion",bE=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[Of,pE,SE]=vy(Nl),[ur,ZE]=tu(Nl,[SE,py]),zf=py(),xE=b.forwardRef(Gt(function(c,r){const{type:f,...s}=c,v=s,h=s;return(0,m.jsx)(Of.Provider,{scope:c.__scopeAccordion,children:f===gE.Multiple?(0,m.jsx)(NE,{...h,ref:r}):(0,m.jsx)(_E,{...v,ref:r})})},"Accordion")),[Ey,EE]=ur(Nl),[Ty,TE]=ur(Nl,{collapsible:!1}),_E=b.forwardRef(Gt(function(c,r){const{value:f,defaultValue:s,onValueChange:v=Gt(()=>{},"onValueChange"),collapsible:h=!1,...p}=c,[A,C]=ri({prop:f,defaultProp:s??"",onChange:v,caller:Nl});return(0,m.jsx)(Ey,{scope:c.__scopeAccordion,value:b.useMemo(()=>A?[A]:[],[A]),onItemOpen:C,onItemClose:b.useCallback(()=>h&&C(""),[h,C]),children:(0,m.jsx)(Ty,{scope:c.__scopeAccordion,collapsible:h,children:(0,m.jsx)(_y,{...p,ref:r})})})},"AccordionImplSingle")),NE=b.forwardRef(Gt(function(c,r){const{value:f,defaultValue:s,onValueChange:v=Gt(()=>{},"onValueChange"),...h}=c,[p,A]=ri({prop:f,defaultProp:s??[],onChange:v,caller:Nl}),C=b.useCallback(E=>A((g=[])=>[...g,E]),[A]),H=b.useCallback(E=>A((g=[])=>g.filter(D=>D!==E)),[A]);return(0,m.jsx)(Ey,{scope:c.__scopeAccordion,value:p,onItemOpen:C,onItemClose:H,children:(0,m.jsx)(Ty,{scope:c.__scopeAccordion,collapsible:!0,children:(0,m.jsx)(_y,{...h,ref:r})})})},"AccordionImplMultiple")),[CE,ir]=ur(Nl),_y=b.forwardRef(Gt(function(c,r){const{__scopeAccordion:f,disabled:s,dir:v,orientation:h=Pu.Vertical,...p}=c,A=b.useRef(null),C=At(A,r),H=pE(f),E=xy(v)===yE.LTR,g=il(c.onKeyDown,D=>{if(!bE.includes(D.key))return;const G=D.target,M=H().filter(W=>!W.ref.current?.disabled),L=M.findIndex(W=>W.ref.current===G),V=M.length;if(L===-1)return;D.preventDefault();let X=L;const B=0,Z=V-1,ue=Gt(()=>{X=L+1,X>Z&&(X=B)},"moveNext"),ee=Gt(()=>{X=L-1,X{g?p.onItemOpen(s):p.onItemClose(s)}})})},"AccordionItem")),zE="AccordionHeader",RE=b.forwardRef(Gt(function(c,r){const{__scopeAccordion:f,...s}=c,v=ir(Nl,f),h=Rf(zE,f);return(0,m.jsx)(qt.h3,{"data-orientation":v.orientation,"data-state":Df(h.open),"data-disabled":h.disabled?"":void 0,...s,ref:r})},"AccordionHeader")),Nh="AccordionTrigger",Ny=b.forwardRef(Gt(function(c,r){const{__scopeAccordion:f,...s}=c,v=ir(Nl,f),h=Rf(Nh,f),p=TE(Nh,f),A=zf(f);return(0,m.jsx)(Of.ItemSlot,{scope:f,children:(0,m.jsx)(rE,{"aria-disabled":h.open&&!p.collapsible||void 0,"data-orientation":v.orientation,id:h.triggerId,...A,...s,ref:r})})},"AccordionTrigger")),DE="AccordionContent",Cy=b.forwardRef(Gt(function(c,r){const{__scopeAccordion:f,...s}=c,v=ir(Nl,f),h=Rf(DE,f),p=zf(f);return(0,m.jsx)(oE,{role:"region","aria-labelledby":h.triggerId,"data-orientation":v.orientation,...p,...s,ref:r,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...c.style}})},"AccordionContent"));function Df(i){return i?"open":"closed"}Gt(Df,"getState");var jE=xE,Ay=b.forwardRef(({className:i,...c},r)=>(0,m.jsx)(OE,{ref:r,className:ft("border-b",i),...c}));Ay.displayName="AccordionItem";var Oy=b.forwardRef(({className:i,children:c,...r},f)=>(0,m.jsx)(RE,{className:"flex",children:(0,m.jsxs)(Ny,{ref:f,className:ft("flex flex-1 items-center justify-between gap-4 py-4 text-left text-base font-medium transition-all hover:text-primary [&[data-state=open]>svg]:rotate-180",i),...r,children:[c,(0,m.jsx)(Gp,{className:"h-5 w-5 shrink-0 text-muted-foreground transition-transform duration-200"})]})}));Oy.displayName=Ny.displayName;var zy=b.forwardRef(({className:i,children:c,...r},f)=>(0,m.jsx)(Cy,{ref:f,className:"overflow-hidden text-sm data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...r,children:(0,m.jsx)("div",{className:ft("pb-4 pt-0 leading-relaxed text-muted-foreground",i),children:c})}));zy.displayName=Cy.displayName;var ME=[`POST ${ui}${sg}`,"Authorization: Bearer $GATEWAY_KEY","Content-Type: application/json","","{",' "model": "<модель-из-/api/pricing>",',' "messages": [',' { "role": "system", "content": "Ты полезный ассистент." },',' { "role": "user", "content": "Кратко объясни, что такое API-шлюз." }'," ]","}"].join(` -`),wE=[`POST ${ui}${ZS}`,"Authorization: Bearer $GATEWAY_KEY","Content-Type: application/json","","{",' "model": "<модель-генерации-из-/api/pricing>",',' "prompt": "Фотореалистичный закат над горами",',' "n": 1',"}"].join(` -`),UE=[{q:"Где взять API-ключ?",a:"Откройте Telegram-бота — ключ и доступ к консоли выдаются после входа. Ключ отображается в консоли, там же виден баланс и расход."},{q:"Какой base URL указывать?",a:`Используйте ${ui} как base URL OpenAI-совместимого клиента. Эндпоинты чата и генерации изображений — ниже в примерах.`},{q:"Как узнать цену модели?",a:"Все коэффициенты и цены приходят из "+ai+" и показаны на странице «Тарифы». Мы не пересчитываем и не добавляем свои значения."},{q:"Какие форматы запросов поддерживаются?",a:"Шлюз отдаёт OpenAI-совместимые эндпоинты: /v1/chat/completions и /v1/images/generations. Полный список эндпоинтов указан в поле supported_endpoint ответа /api/pricing."},{q:"Что если цены не загрузились?",a:"Страница «Тарифы» покажет состояние ошибки с кнопкой обновления. Данные вернутся автоматически, как только /api/pricing снова будет доступен."}];function Ch({label:i,code:c}){return(0,m.jsxs)(Xl,{className:"min-w-0",children:[(0,m.jsxs)(oi,{children:[(0,m.jsx)(Pa,{className:"text-base",children:i}),(0,m.jsx)(lu,{children:"Пример запроса через шлюз."})]}),(0,m.jsx)(Ql,{children:(0,m.jsx)("pre",{className:"overflow-x-auto rounded-lg border border-border bg-background p-4 text-xs leading-relaxed",children:(0,m.jsx)("code",{children:c})})})]})}function HE(){const i=ii.docs;return(0,m.jsxs)("div",{className:"container-x py-14 sm:py-20",children:[(0,m.jsxs)("header",{className:"max-w-2xl",children:[(0,m.jsx)(lr,{variant:"secondary",children:"Быстрый старт"}),(0,m.jsx)("h1",{className:"mt-4 text-4xl font-semibold tracking-tight",children:i.h1}),(0,m.jsx)("p",{className:"mt-3 text-base leading-relaxed text-muted-foreground",children:i.description})]}),(0,m.jsxs)("section",{className:"mt-12 grid gap-4 lg:grid-cols-2",children:[(0,m.jsx)(Ch,{label:"Чат (OpenAI-совместимый)",code:ME}),(0,m.jsx)(Ch,{label:"Генерация изображений",code:wE})]}),(0,m.jsxs)("section",{className:"mt-12 max-w-3xl",children:[(0,m.jsx)("h2",{className:"text-2xl font-semibold tracking-tight",children:"Шаги подключения"}),(0,m.jsxs)("ol",{className:"mt-4 list-decimal space-y-3 pl-5 text-sm leading-relaxed text-muted-foreground",children:[(0,m.jsxs)("li",{children:["Откройте бота и получите API-ключ: ",(0,m.jsx)("a",{href:Nn,className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",children:Nn}),"."]}),(0,m.jsxs)("li",{children:["В клиенте укажите base URL ",(0,m.jsx)("code",{className:"break-all rounded bg-muted px-1.5 py-0.5 text-foreground",children:ui})," и заголовок ",(0,m.jsx)("code",{className:"rounded bg-muted px-1.5 py-0.5 text-foreground",children:"Authorization: Bearer …"}),"."]}),(0,m.jsxs)("li",{children:["Возьмите имя модели из ответа ",(0,m.jsx)("code",{className:"break-all rounded bg-muted px-1.5 py-0.5 text-foreground",children:ai})," или со страницы «Тарифы»."]}),(0,m.jsx)("li",{children:"Отправьте запрос к нужному эндпоинту и проверьте расход в консоли."})]})]}),(0,m.jsxs)("section",{className:"mt-12 max-w-3xl",children:[(0,m.jsx)("h2",{className:"text-2xl font-semibold tracking-tight",children:"Частые вопросы"}),(0,m.jsx)(jE,{type:"single",collapsible:!0,className:"mt-4",children:UE.map((c,r)=>(0,m.jsxs)(Ay,{value:`faq-${r}`,children:[(0,m.jsx)(Oy,{children:c.q}),(0,m.jsx)(zy,{children:c.a})]},c.q))})]}),(0,m.jsx)("div",{className:"mt-16",children:(0,m.jsx)(nr,{})})]})}var BE=[{icon:Kp,title:"Одна точка входа",text:"Вместо набора разных SDK и ключей — единый OpenAI-совместимый интерфейс к моделям нескольких вендоров."},{icon:Yp,title:"Честная тарификация",text:`Цены берутся из ${ai} без ручных надбавок: либо множители входа/выхода, либо цена за вызов с единицей upstream.`},{icon:Lp,title:"Вход через бота",text:"Аккаунт, ключ и консоль связаны с Telegram-ботом — без отдельных паролей и форм регистрации."}];function LE(){const i=ii.about;return(0,m.jsxs)("div",{className:"container-x py-14 sm:py-20",children:[(0,m.jsxs)("header",{className:"max-w-2xl",children:[(0,m.jsx)(lr,{variant:"secondary",children:"О сервисе"}),(0,m.jsx)("h1",{className:"mt-4 text-4xl font-semibold tracking-tight",children:i.h1}),(0,m.jsx)("p",{className:"mt-3 text-base leading-relaxed text-muted-foreground",children:i.description})]}),(0,m.jsxs)("section",{className:"mt-12 max-w-3xl space-y-4 text-sm leading-relaxed text-muted-foreground",children:[(0,m.jsx)("p",{children:"IISHKO GATEWAY — это API-шлюз: промежуточный слой между вашим приложением и моделями разных поставщиков. Вы отправляете обычные OpenAI-совместимые запросы на один base URL, а шлюз маршрутизирует их к нужной модели, ведёт ключи, баланс и учёт расхода."}),(0,m.jsxs)("p",{children:["Каталог моделей и цены динамические: они приходят из ответа ",ai," и отображаются на странице «Тарифы» без изменений. Страница ничего не придумывает и не пересчитывает суммы вручную."]}),(0,m.jsx)("p",{children:"Подключение и поддержка идут через Telegram-бота. Это упрощает выдачу ключа и вход в консоль: отдельной формы регистрации с паролем на публичном сайте нет."})]}),(0,m.jsx)("section",{className:"mt-12 grid gap-4 sm:grid-cols-3",children:BE.map(c=>(0,m.jsxs)(Xl,{children:[(0,m.jsxs)(oi,{children:[(0,m.jsx)(c.icon,{className:"h-6 w-6 text-primary","aria-hidden":"true"}),(0,m.jsx)(Pa,{className:"mt-2 text-base",children:c.title})]}),(0,m.jsx)(Ql,{children:(0,m.jsx)(lu,{className:"leading-relaxed",children:c.text})})]},c.title))}),(0,m.jsxs)("section",{className:"mt-12 max-w-3xl",children:[(0,m.jsx)("h2",{className:"text-2xl font-semibold tracking-tight",children:"Контакты"}),(0,m.jsxs)("p",{className:"mt-3 text-sm leading-relaxed text-muted-foreground",children:["Вопросы по подключению, ключам и тарифам — в Telegram-боте:"," ",(0,m.jsx)("a",{href:Nn,className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",children:Nn}),"."]})]}),(0,m.jsx)("div",{className:"mt-16",children:(0,m.jsx)(nr,{title:"Готовы начать?",description:"Откройте бота, получите ключ и отправьте первый запрос через шлюз."})})]})}function YE(){const i=ii.signin;return(0,m.jsx)("div",{className:"container-x flex min-h-[70vh] items-center justify-center py-16",children:(0,m.jsxs)(Xl,{className:"w-full max-w-md",children:[(0,m.jsxs)(oi,{className:"text-center",children:[(0,m.jsx)("div",{className:"mx-auto grid h-12 w-12 place-items-center rounded-xl bg-primary/15 text-primary",children:(0,m.jsx)(Pn,{className:"h-6 w-6","aria-hidden":"true"})}),(0,m.jsx)("h1",{className:"mt-4 text-2xl font-semibold leading-none tracking-tight",children:i.h1}),(0,m.jsx)(lu,{className:"mt-2 leading-relaxed",children:"Вход через Telegram-бота. Отдельной формы с паролем нет — ключ и консоль выдаются ботом."})]}),(0,m.jsxs)(Ql,{className:"flex flex-col gap-3",children:[(0,m.jsx)(Tl,{asChild:!0,size:"lg",className:"w-full",children:(0,m.jsxs)("a",{href:ni,rel:"nofollow",children:[(0,m.jsx)(Pn,{"aria-hidden":"true"}),"Войти через Telegram"]})}),(0,m.jsx)(Tl,{asChild:!0,variant:"outline",size:"lg",className:"w-full",children:(0,m.jsx)("a",{href:Nn,target:"_blank",rel:"noopener noreferrer",children:"Открыть бота"})}),(0,m.jsxs)("p",{className:"mt-2 flex items-center justify-center gap-2 text-xs text-muted-foreground",children:[(0,m.jsx)(Jp,{className:"h-4 w-4","aria-hidden":"true"}),"После входа вы окажетесь в консоли с API-ключом и балансом."]})]})]})})}function GE({page:i}){return(0,m.jsxs)("div",{className:"flex min-h-screen flex-col bg-background text-foreground",children:[(0,m.jsx)(H2,{activePage:i}),(0,m.jsx)("main",{className:"flex-1",children:qE(i)}),(0,m.jsx)(B2,{})]})}function qE(i){switch(i){case"pricing":return(0,m.jsx)(F2,{});case"docs":return(0,m.jsx)(HE,{});case"about":return(0,m.jsx)(LE,{});case"signin":return(0,m.jsx)(YE,{});default:return(0,m.jsx)(V2,{})}}var VE=["home","pricing","docs","about","signin"];function XE(){const i=document.getElementById("root")?.dataset.page??"home";return VE.includes(i)?i:"home"}var Ah=document.getElementById("root");Ah&&(0,Pp.hydrateRoot)(Ah,(0,m.jsx)(GE,{page:XE()})); diff --git a/site/pages/about.html b/site/pages/about.html deleted file mode 100644 index cbc46a03..00000000 --- a/site/pages/about.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - О сервисе — IISHKO GATEWAY - - - - - - - - - - - - - - -
О сервисе

О сервисе

Что такое API-шлюз, какие задачи он решает, как устроена модель оплаты и как получить поддержку через Telegram.

IISHKO GATEWAY — это API-шлюз: промежуточный слой между вашим приложением и моделями разных поставщиков. Вы отправляете обычные OpenAI-совместимые запросы на один base URL, а шлюз маршрутизирует их к нужной модели, ведёт ключи, баланс и учёт расхода.

Каталог моделей и цены динамические: они приходят из ответа /api/pricing и отображаются на странице «Тарифы» без изменений. Страница ничего не придумывает и не пересчитывает суммы вручную.

Подключение и поддержка идут через Telegram-бота. Это упрощает выдачу ключа и вход в консоль: отдельной формы регистрации с паролем на публичном сайте нет.

Одна точка входа

Вместо набора разных SDK и ключей — единый OpenAI-совместимый интерфейс к моделям нескольких вендоров.

Честная тарификация

Цены берутся из /api/pricing без ручных надбавок: либо множители входа/выхода, либо цена за вызов с единицей upstream.

Вход через бота

Аккаунт, ключ и консоль связаны с Telegram-ботом — без отдельных паролей и форм регистрации.

Контакты

Вопросы по подключению, ключам и тарифам — в Telegram-боте: https://t.me/iishkogatewaybot?start=site.

Готовы начать?

Откройте бота, получите ключ и отправьте первый запрос через шлюз.

- - - diff --git a/site/pages/docs.html b/site/pages/docs.html deleted file mode 100644 index 405264c0..00000000 --- a/site/pages/docs.html +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - Документация и быстрый старт — IISHKO GATEWAY - - - - - - - - - - - - - - -
Быстрый старт

Документация

Как получить ключ, указать base URL и выполнить первый запрос к чату или генерации изображений через OpenAI-совместимый API шлюза IISHKO GATEWAY.

Чат (OpenAI-совместимый)

Пример запроса через шлюз.

POST https://your-domain.com/v1/chat/completions
-Authorization: Bearer $GATEWAY_KEY
-Content-Type: application/json
-
-{
-  "model": "<модель-из-/api/pricing>",
-  "messages": [
-    { "role": "system", "content": "Ты полезный ассистент." },
-    { "role": "user", "content": "Кратко объясни, что такое API-шлюз." }
-  ]
-}

Генерация изображений

Пример запроса через шлюз.

POST https://your-domain.com/v1/images/generations
-Authorization: Bearer $GATEWAY_KEY
-Content-Type: application/json
-
-{
-  "model": "<модель-генерации-из-/api/pricing>",
-  "prompt": "Фотореалистичный закат над горами",
-  "n": 1
-}

Шаги подключения

  1. Откройте бота и получите API-ключ: https://t.me/iishkogatewaybot?start=site.
  2. В клиенте укажите base URL https://your-domain.com/v1 и заголовок Authorization: Bearer ….
  3. Возьмите имя модели из ответа /api/pricing или со страницы «Тарифы».
  4. Отправьте запрос к нужному эндпоинту и проверьте расход в консоли.

Частые вопросы

Подключитесь за минуту

Откройте Telegram-бота, получите API-ключ и начните отправлять запросы через единый шлюз.

- - - diff --git a/site/pages/home.html b/site/pages/home.html deleted file mode 100644 index 08a376c7..00000000 --- a/site/pages/home.html +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - IISHKO GATEWAY — единый API-шлюз к AI-моделям - - - - - - - - - - - - - - -
OpenAI-совместимый API-шлюз

Единый API-доступ к AI-моделям

Единый OpenAI-совместимый API-шлюз к моделям разных вендоров: один ключ, один баланс, прозрачная тарификация по множителям входа и выхода. Подключение через Telegram-бот.

Преимущества

Один эндпоинт

Единый OpenAI-совместимый API вместо отдельных ключей и SDK для каждого вендора.

Прозрачная тарификация

Стоимость по множителям входа и выхода либо по цене за вызов — как отдаёт upstream.

Каталог моделей

Чат и генерация изображений; список моделей и цен приходит напрямую из /api/pricing.

Ключи и баланс

Выдача ключа, баланс и usage — в консоли после входа через Telegram-бота.

Быстрый старт

Первый запрос через шлюз
curl https://your-domain.com/v1/chat/completions \
-  -H "Authorization: Bearer $GATEWAY_KEY" \
-  -H "Content-Type: application/json" \
-  -d '{
-    "model": "<модель-из-/api/pricing>",
-    "messages": [{ "role": "user", "content": "Привет" }]
-  }'

Подставьте base URL и ключ из консоли. Имя модели возьмите из актуального каталога на странице «Тарифы».

Как начать

  1. Откройте Telegram-бота.
  2. Получите API-ключ и доступ в консоль.
  3. Укажите base URL шлюза в вашем клиенте.
  4. Отправляйте запросы к нужной модели.

Подключитесь за минуту

Откройте Telegram-бота, получите API-ключ и начните отправлять запросы через единый шлюз.

- - - diff --git a/site/pages/pricing.html b/site/pages/pricing.html deleted file mode 100644 index bb42e9b3..00000000 --- a/site/pages/pricing.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - Тарифы и цены моделей — IISHKO GATEWAY - - - - - - - - - - - - - - -
Актуальные данные /api/pricing

Тарифы моделей

Актуальные коэффициенты тарификации и цены моделей напрямую из /api/pricing. Без выдуманных сумм: множители входа и выхода либо цена за вызов с собственной единицей измерения.

Загружаем актуальные цены…

Нужен ключ и баланс?

Войдите через Telegram-бота, чтобы получить API-ключ и увидеть расход по каждой модели в консоли.

- - - - - diff --git a/site/pages/signin.html b/site/pages/signin.html deleted file mode 100644 index e37cb287..00000000 --- a/site/pages/signin.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - Вход через Telegram — IISHKO GATEWAY - - - - - - - - - - - - - - - -

Вход в шлюз

Вход через Telegram-бота. Отдельной формы с паролем нет — ключ и консоль выдаются ботом.

Войти через TelegramОткрыть бота

После входа вы окажетесь в консоли с API-ключом и балансом.

- - - diff --git a/tests/test_abilities_guard_cli.py b/tests/test_abilities_guard_cli.py new file mode 100644 index 00000000..b3ddf953 --- /dev/null +++ b/tests/test_abilities_guard_cli.py @@ -0,0 +1,132 @@ +"""Operator route checks are read-only unless an explicit apply is authorized.""" +from contextlib import closing, redirect_stderr +import importlib.util +import io +import os +from pathlib import Path +import sqlite3 +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / "bot" / "abilities_guard.py" +sys.path.insert(0, str(ROOT / "bot")) + + +class AbilitiesGuardCliTests(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.db = self.root / "gateway.db" + self.source = self.root / "catalog.py" + self.source.write_text('TIER_MODELS = {\n 1: ["basic"],\n 4: ["advanced"],\n}\n', + encoding="utf-8") + with closing(sqlite3.connect(self.db)) as con: + con.executescript(''' + CREATE TABLE channels(id INTEGER PRIMARY KEY, status INTEGER, models TEXT); + CREATE TABLE abilities(channel_id INTEGER, model TEXT, "group" TEXT, enabled INTEGER); + CREATE TABLE tokens(id INTEGER PRIMARY KEY, status INTEGER, remain_quota INTEGER); + CREATE TABLE entry_autobans(uid INTEGER PRIMARY KEY, reason TEXT); + INSERT INTO channels VALUES(1,1,'basic, advanced'),(2,2,'basic'),(3,1,'other'); + INSERT INTO abilities VALUES + (1,'basic','t1',0),(1,'advanced','t1',0),(1,'advanced','t4',0), + (1,'basic','default',0),(2,'basic','t1',0),(3,'basic','t1',0); + INSERT INTO tokens VALUES(1,1,5000); + INSERT INTO entry_autobans VALUES(101,'existing-receipt'); + ''') + self.env = {key: value for key, value in os.environ.items() + if not key.startswith(("IISHKO_", "GROK_", "GATE_", "NEWAPI_", "PYTHONPATH"))} + self.env.update(IISHKO_GW_DB=str(self.db), IISHKO_BOT_SOURCE=str(self.source)) + + def run_cli(self, *args): + return subprocess.run([sys.executable, str(SCRIPT), *map(str, args)], + cwd=self.root, env=self.env, capture_output=True, + text=True, encoding="utf-8", timeout=15) + + def rows(self, table): + with closing(sqlite3.connect(self.db)) as con: + return con.execute("SELECT * FROM " + table).fetchall() + + def test_default_is_read_only_with_no_database_changes(self): + before = self.db.read_bytes() + result = self.run_cli() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("mode=dry-run", result.stdout) + self.assertIn("re-enabled=0", result.stdout) + self.assertIn("dark=advanced,basic", result.stdout) + self.assertEqual(self.db.read_bytes(), before) + + def test_apply_requires_both_explicit_paths_even_when_env_is_configured(self): + before = self.db.read_bytes() + for args in (("--apply",), ("--apply", "--db", self.db), + ("--apply", "--source", self.source)): + with self.subTest(args=args): + result = self.run_cli(*args) + self.assertEqual(result.returncode, 2) + self.assertIn("--apply requires explicit --db and --source", result.stderr) + self.assertEqual(self.db.read_bytes(), before) + + def test_missing_and_relative_paths_are_rejected_without_database_creation(self): + missing = self.root / "absent.db" + for args in (("--db", missing), ("--db", "gateway.db"), + ("--source", "catalog.py"), ("--source", self.root / "absent.py")): + with self.subTest(args=args): + result = self.run_cli(*args) + self.assertEqual(result.returncode, 2) + self.assertIn("absolute path to an existing file", result.stderr) + self.assertFalse(missing.exists()) + + def test_empty_catalogue_does_not_touch_database(self): + self.source.write_text("TIER_MODELS = {}\n", encoding="utf-8") + before = self.db.read_bytes() + result = self.run_cli("--apply", "--db", self.db, "--source", self.source) + self.assertEqual(result.returncode, 1) + self.assertIn("no database changes made", result.stdout) + self.assertEqual(self.db.read_bytes(), before) + + def test_apply_repairs_only_matching_live_tier_abilities(self): + tokens, receipts = self.rows("tokens"), self.rows("entry_autobans") + result = self.run_cli("--apply", "--db", self.db, "--source", self.source) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("mode=apply", result.stdout) + self.assertIn("re-enabled=3", result.stdout) + self.assertEqual([row[3] for row in self.rows("abilities")], [1, 0, 1, 1, 0, 0]) + self.assertEqual(self.rows("tokens"), tokens) + self.assertEqual(self.rows("entry_autobans"), receipts) + repeated = self.run_cli("--apply", "--db", self.db, "--source", self.source) + self.assertEqual(repeated.returncode, 0, repeated.stderr) + self.assertIn("re-enabled=0", repeated.stdout) + + def test_schema_failure_returns_nonzero_without_writing(self): + with closing(sqlite3.connect(self.db)) as con: + con.execute("DROP TABLE abilities") + con.commit() + before = self.db.read_bytes() + result = self.run_cli() + self.assertEqual(result.returncode, 2) + self.assertIn("Database check failed: OperationalError", result.stderr) + self.assertEqual(self.db.read_bytes(), before) + + def test_apply_rolls_back_when_repair_fails(self): + spec = importlib.util.spec_from_file_location("abilities_guard_cli_probe", SCRIPT) + assert spec is not None and spec.loader is not None + guard = importlib.util.module_from_spec(spec) + spec.loader.exec_module(guard) + before = self.rows("abilities") + + def fail_after_write(con, tiers): + con.execute("UPDATE abilities SET enabled=1") + raise sqlite3.OperationalError("offline-injected-error") + + with patch.object(guard, "repair_abilities", side_effect=fail_after_write), redirect_stderr(io.StringIO()): + code = guard.main(["--apply", "--db", str(self.db), "--source", str(self.source)]) + self.assertEqual(code, 2) + self.assertEqual(self.rows("abilities"), before) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_account_admin_unban.py b/tests/test_account_admin_unban.py index 6f033b32..00fc672c 100644 --- a/tests/test_account_admin_unban.py +++ b/tests/test_account_admin_unban.py @@ -524,7 +524,7 @@ class AccountAdminUnbanTests(unittest.TestCase): self.assertEqual(self.token(1)["status"], 2) self.assert_finance(finance) # The same receipt is read by entry autoban in the bot database. - self.assertFalse(entry_autoban.ban_user(101)) + self.assertFalse(entry_autoban.ban_user(101, reason="admin_button")) self.assert_finance(finance) def test_manual_unban_receipt_is_bot_scoped_and_explicit_ban_revokes_it(self): diff --git a/tests/test_account_balances.py b/tests/test_account_balances.py index 2d6f4780..462640ce 100644 --- a/tests/test_account_balances.py +++ b/tests/test_account_balances.py @@ -49,6 +49,7 @@ class AccountBalancesTests(unittest.TestCase): tree = ast.parse((ROOT/'bot/webapp/mk_daemon.py').read_text(encoding='utf-8')) functions = [node for node in tree.body if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef))] self.ns = dict(globals(), BOT_DB=self.bot, GW_DB=self.gw, Q=500000, + econ_state_path=lambda: str(Path(temp.name) / 'econ_state.json'), g=SimpleNamespace(MK_CAP={1:4},badge_of=lambda uid:1,KEY_WAIT_SEC=86400)) exec(compile(ast.Module(body=functions,type_ignores=[]), 'isolated-key-daemon', 'exec'), self.ns) diff --git a/tests/test_deploy_contract.py b/tests/test_deploy_contract.py new file mode 100644 index 00000000..02febf98 --- /dev/null +++ b/tests/test_deploy_contract.py @@ -0,0 +1,350 @@ +"""Deploy/docs contract: every documented unit path must resolve inside this repo. + +The tests are static: they parse the files shipped under ``deploy/`` and the two +operator-facing docs. Nothing here starts a service, imports runtime code or +touches the network. + +Mapping source of truth is the table in ``deploy/README.md``; the four core +units under ``deploy/systemd/`` are checked against it. Services this repository +does not implement (healthcheck, alert-watch, media adapter, firewall) ship +nothing at all: no units, no templates, no stubs. +""" + +from __future__ import annotations + +import re +import shlex +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +DEPLOY = REPO_ROOT / "deploy" +SYSTEMD = DEPLOY / "systemd" +CADDY = DEPLOY / "caddy" / "Caddyfile.example" +DEPLOY_README = DEPLOY / "README.md" +RUNTIME_ENV = DEPLOY / "runtime.env.example" +CONTRIBUTING = REPO_ROOT / "CONTRIBUTING.md" +SECURITY = REPO_ROOT / "SECURITY.md" + +# Units that must exist: the first-party services this repo can actually run. +CORE_UNITS = { + "grok-bot.service": "bot", + "iishko-webapp.service": "miniapp", + "grok-web-skin.service": "gateway", + "iishko-moderation.service": None, # native binary, not run through run.py +} + +# Scripts that do not exist in this repository; they belong to the operator. +ABSENT_EXTERNAL_SCRIPTS = ( + "grok-healthcheck.py", + "grok-alert-watch.py", + "media_tts.py", + "iishko-fw.sh", + "/usr/local/sbin/iishko-fw", + "zai_shim.caddy", +) + +# ``scripts/run.py`` is the shared bootstrap; it is part of the repo contract and +# is referenced by every core target unit. If it is missing from a checkout the +# units still point at a documented location, so the path check allows it only +# when deploy/README.md documents it as the launcher. +BOOTSTRAP_REL = "scripts/run.py" + +# Host paths are absolute, so anchoring on "/" keeps the target table (also +# backticked) from being parsed as mapping rows across line breaks. +MAPPING_ROW = re.compile(r"^\|\s*`(?P/[^`]+)`\s*\|\s*(?P[^|]*)\|\s*(?P[^|]*)\|", re.M) +TARGET_ROW = re.compile(r"^\|\s*`(?P[a-z]+)`\s*\|\s*`(?P[^`]+)`", re.M) + + +def read(path: Path) -> str: + return path.read_text(encoding="utf-8", errors="replace") + + +def mapping() -> dict[str, tuple[str, str]]: + """host path -> (repo source description, kind).""" + rows = {} + for match in MAPPING_ROW.finditer(read(DEPLOY_README)): + rows[match.group("host").strip()] = (match.group("source").strip(), match.group("kind").strip()) + return rows + + +def targets() -> dict[str, str]: + """run.py target -> repo module.""" + return {m.group("target"): m.group("module").strip() for m in TARGET_ROW.finditer(read(DEPLOY_README))} + + +def unit_directives(path: Path) -> list[tuple[str, str]]: + out = [] + for line in read(path).splitlines(): + line = line.strip() + if not line or line.startswith(("#", ";", "[")): + continue + if "=" not in line: + continue + key, value = line.split("=", 1) + out.append((key.strip(), value.strip())) + return out + + +def exec_paths(value: str) -> list[str]: + """Absolute filesystem paths from an ExecStart line (argv[0] + path args).""" + try: + argv = shlex.split(value) + except ValueError: + argv = value.split() + paths = [] + for arg in argv: + if arg.startswith(("-", "@", "+", "!", ":")): + arg = arg.lstrip('-@+!:') + if arg.startswith("/") and "$" not in arg: + paths.append(arg) + return paths + + +def map_to_repo(host_path: str, table: dict[str, tuple[str, str]]) -> str | None: + """Translate a host path into a repo-relative path using the mapping table.""" + for host, (_source, _kind) in sorted(table.items(), key=lambda kv: -len(kv[0])): + host = host.rstrip("/") + if host_path == host: + return "." + if host_path.startswith(host + "/"): + return host_path[len(host) + 1 :] + return None + + +class DeployMappingTest(unittest.TestCase): + def test_mapping_table_is_documented(self): + table = mapping() + self.assertIn("/opt/iishko", table, "deploy/README.md must document the repo root mapping") + self.assertIn("/etc/iishko/runtime.env", table, "runtime env file must be documented") + kind = table["/opt/iishko"][1].lower() + self.assertTrue("дерево" in kind or "tree" in kind, "repo root mapping must be documented as a tree") + + def test_core_unit_execstart_paths_resolve(self): + table = mapping() + self.assertTrue(table, "mapping table is unreadable") + deploy_doc = read(DEPLOY_README) + for unit in sorted(SYSTEMD.glob("*.service")): + for key, value in unit_directives(unit): + if key != "ExecStart": + continue + paths = exec_paths(value) + self.assertTrue(paths, f"{unit.name}: ExecStart has no absolute path: {value}") + for host_path in paths: + if host_path == "/etc/iishko/runtime.env": + # Server-side config: seeded from deploy/runtime.env.example. + self.assertIn("/etc/iishko/runtime.env", table) + continue + rel = map_to_repo(host_path, table) + self.assertIsNotNone(rel, f"{unit.name}: {host_path} is outside the documented mapping") + if rel.startswith(".venv/"): + # Generated on the host, documented as such. + self.assertIn(".venv", deploy_doc) + self.assertIn("venv", deploy_doc.lower()) + continue + if rel == BOOTSTRAP_REL: + # Shared bootstrap: documented, may be provided separately. + self.assertIn(BOOTSTRAP_REL, deploy_doc) + self.assertTrue( + (REPO_ROOT / BOOTSTRAP_REL).is_file(), + "scripts/run.py is documented as the launcher but missing from this checkout", + ) + continue + if rel == "bin/iishko-moderation": + self.assertTrue( + (REPO_ROOT / "moderation").is_dir(), + "moderation/ must exist to build bin/iishko-moderation", + ) + continue + self.assertTrue( + (REPO_ROOT / rel).exists(), + f"{unit.name}: {host_path} maps to missing {rel}", + ) + + def test_core_units_use_bootstrap_and_required_env_file(self): + for name, target in CORE_UNITS.items(): + path = SYSTEMD / name + self.assertTrue(path.is_file(), f"missing core unit {name}") + directives = dict(unit_directives(path)) + self.assertEqual(directives.get("WorkingDirectory"), "/opt/iishko", f"{name}: wrong WorkingDirectory") + if target: + execstart = directives.get("ExecStart", "") + self.assertIn(f"/{BOOTSTRAP_REL} {target}", execstart, f"{name}: must start via scripts/run.py {target}") + self.assertIn("--env-file /etc/iishko/runtime.env", execstart, f"{name}: runtime env file not passed") + else: + self.assertIn("/opt/iishko/bin/iishko-moderation", directives.get("ExecStart", ""), f"{name}: binary path") + self.assertEqual( + directives.get("EnvironmentFile"), + "/etc/iishko/runtime.env", + f"{name}: EnvironmentFile must be present and not optional ('-' prefix)", + ) + + def test_run_targets_exist_in_repo(self): + table_targets = targets() + for target in ("bot", "miniapp", "gateway"): + self.assertIn(target, table_targets, f"deploy/README.md must document run.py target {target}") + module = table_targets[target] + self.assertTrue((REPO_ROOT / module).is_file(), f"target {target} points at missing {module}") + + def test_docs_state_the_launcher_semantics(self): + text = read(DEPLOY_README) + self.assertIn(BOOTSTRAP_REL, text) + self.assertIn("bot/iishko_bot.py", text) + self.assertIn("bot/grok_bot.py", text) + self.assertIn("--check", text) + + def test_canonical_resolver_matches_documented_order(self): + module = REPO_ROOT / "bot" / "runtime_config.py" + self.assertTrue(module.is_file(), "deploy/README.md points at bot/runtime_config.py, which is missing") + body = read(module) + for name in ("GROK_BOT_CFG", "GROK_BOT_CONFIG", "GATE_BOT_CONFIG", "IISHKO_SKIN_DB", "GATE_TG_DB"): + self.assertIn(name, body, f"bot/runtime_config.py must resolve {name}") + # Documented precedence: canonical name wins over the legacy alias. + order = [body.index(name) for name in ("GROK_BOT_CFG", "GROK_BOT_CONFIG", "GATE_BOT_CONFIG")] + self.assertEqual( + order, sorted(order), "bot config precedence in runtime_config.py differs from deploy/README.md" + ) + self.assertLess(body.index("IISHKO_SKIN_DB"), body.index("GATE_TG_DB")) + + +class DeployScopeTest(unittest.TestCase): + def test_no_external_script_in_core_units(self): + for unit in SYSTEMD.glob("*"): + body = read(unit) + for absent in ABSENT_EXTERNAL_SCRIPTS: + self.assertNotIn(absent, body, f"{unit.name} references absent {absent}") + + def test_core_dir_has_no_templates(self): + for item in SYSTEMD.iterdir(): + self.assertFalse(item.name.endswith(".example"), f"{item.name} is a template, not a unit") + self.assertEqual(set(CORE_UNITS), {p.name for p in SYSTEMD.glob("*.service")}) + + def test_no_external_template_graveyard(self): + """Dead templates were removed: no directory may hold units the repo cannot run.""" + self.assertFalse((DEPLOY / "external").exists(), "deploy/external must stay removed") + self.assertEqual( + {"systemd", "caddy"}, {p.name for p in DEPLOY.iterdir() if p.is_dir()}, + "deploy/ grew an undocumented subdirectory", + ) + for path in DEPLOY.rglob("*.service*"): + self.assertIn(path.parent, (SYSTEMD,), f"{path} ships a unit outside systemd/") + self.assertIn(path.name, CORE_UNITS, f"{path.name} has no implementation in this repo") + + def test_readme_states_services_are_out_of_scope(self): + text = read(DEPLOY_README).lower() + for absent in ("healthcheck", "alert", "media", "firewall"): + self.assertIn(absent, text, f"deploy/README.md must say {absent} is not included") + self.assertNotIn("external/", text, "deploy/README.md still points at the removed template dir") + self.assertNotIn("template only", text, "deploy/README.md still announces template files") + + +class CaddyTest(unittest.TestCase): + def test_imports_resolve_inside_repo(self): + body = read(CADDY) + defined = set(re.findall(r"\((\w+)\)\s*\{", body)) + for name in re.findall(r"^\s*import\s+(\S+)", body, re.M): + if name.startswith(("http://", "https://")): + continue + if name in defined: + continue + candidates = [DEPLOY / "caddy" / name, DEPLOY / "caddy" / f"{name}.caddy"] + self.assertTrue( + any(candidate.is_file() for candidate in candidates), + f"Caddyfile imports {name}, which is neither an inline snippet nor a file in deploy/caddy/", + ) + + def test_no_absent_media_service_route(self): + body = read(CADDY) + active = "\n".join(line for line in body.splitlines() if not line.strip().startswith("#")) + self.assertNotIn("127.0.0.1:8000", active, "Caddyfile must not route to the absent media adapter") + self.assertNotIn("zai_shim", body) + self.assertIn("reverse_proxy 127.0.0.1:48001", active) + self.assertIn("reverse_proxy 127.0.0.1:8850", active) + + +class DocsTest(unittest.TestCase): + def test_contributing_has_no_symlink_lie(self): + text = read(CONTRIBUTING).lower() + for forbidden in ("symlink", "симлинк", "120000"): + self.assertNotIn(forbidden, text, f"CONTRIBUTING.md still claims a symlink ({forbidden})") + + def test_contributing_does_not_instruct_copying_modules(self): + text = read(CONTRIBUTING) + for pattern in (r"cp\s+bot/iishko_bot\.py", r"cp\s+bot/grok_bot\.py", r"copying the real module"): + self.assertIsNone(re.search(pattern, text, re.I), f"CONTRIBUTING.md still recommends {pattern}") + + def test_contributing_points_at_real_launcher_and_tests(self): + text = read(CONTRIBUTING) + self.assertIn(f"python {BOOTSTRAP_REL} bot", text) + self.assertIn("bot/grok_bot.py", text) + self.assertIn("bot/iishko_bot.py", text) + self.assertIn("pytest", text) + self.assertNotIn("их почти нет", text) + + def test_no_placeholder_maintainer_handle(self): + for doc in (CONTRIBUTING, SECURITY): + text = read(doc) + self.assertNotIn("@your-handle", text, f"{doc.name} still has a placeholder handle") + self.assertIsNone( + re.search(r"(? FILE", text, "shell redirection can create a 0644 session secret") + + def test_documented_env_names_match_example(self): + text = read(RUNTIME_ENV) + for name in ("GROK_BOT_CFG", "IISHKO_SKIN_DB", "IISHKO_UPSTREAM", "IISHKO_MODERATION_TOKEN"): + self.assertIn(name, text, f"runtime.env.example must define {name}") + deploy_doc = read(DEPLOY_README) + for alias in ("GROK_BOT_CFG", "GROK_BOT_CONFIG", "GATE_BOT_CONFIG"): + self.assertIn(alias, deploy_doc, f"deploy/README.md must document config alias {alias}") + + +if __name__ == "__main__": + unittest.main() \ No newline at end of file diff --git a/tests/test_entry_autoban_default.py b/tests/test_entry_autoban_default.py index f91620dd..75245109 100644 --- a/tests/test_entry_autoban_default.py +++ b/tests/test_entry_autoban_default.py @@ -1,4 +1,4 @@ -"""Shared IP is a signal, not a sanction: autoban is opt-in (IISHKO_ENTRY_AUTOBAN=1).""" +"""Shared IP remains an operator signal even when legacy enforcement is enabled.""" from contextlib import closing import os from pathlib import Path @@ -66,11 +66,12 @@ class NatUsersTest(unittest.TestCase): self.assertEqual(banned, [(0,), (0,)]) self.assertEqual(alerts, 1) # operator still gets the signal - def test_opt_in_enforces(self): + def test_opt_in_still_keeps_shared_ip_access_and_quota(self): with mock.patch.dict(os.environ, {"IISHKO_ENTRY_AUTOBAN": "1"}): - tokens, banned, _ = self._visit_both() - self.assertEqual(tokens, [(2, 0), (2, 0)]) - self.assertEqual(banned, [(1,), (1,)]) + tokens, banned, alerts = self._visit_both() + self.assertEqual(tokens, [(1, 5000), (1, 5000)]) + self.assertEqual(banned, [(0,), (0,)]) + self.assertEqual(alerts, 1) if __name__ == "__main__": diff --git a/tests/test_entry_safety.py b/tests/test_entry_safety.py new file mode 100644 index 00000000..5901d25a --- /dev/null +++ b/tests/test_entry_safety.py @@ -0,0 +1,110 @@ +"""Real SQLite regressions: shared networks cannot alter accounts or balances.""" +import ast +from contextlib import closing +import json +import logging +import os +from pathlib import Path +import sqlite3 +import sys +import tempfile +import unittest +from unittest.mock import Mock, patch + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "bot")) +import entry_autoban +from entry_telemetry import EntryTelemetry, delivery_enabled, notification_text +from runtime_config import skin_db_path + + +class EntrySafetyTests(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + root = Path(tmp.name) + self.bot, self.gateway, self.skin = (str(root / name) for name in ("bot.db", "gateway.db", "custom-skin.db")) + with closing(sqlite3.connect(self.bot)) as con, con: + con.executescript("CREATE TABLE users(tg_id INTEGER PRIMARY KEY, username TEXT, banned INTEGER DEFAULT 0," + "privacy_ok INTEGER DEFAULT 1, admin INTEGER DEFAULT 0, token_name TEXT, api_key TEXT," + "key_locked INTEGER DEFAULT 0,chat_key_locked INTEGER DEFAULT 0);" + "INSERT INTO users(tg_id,username,token_name) VALUES(101,'one','tg101'),(202,'two','tg202');") + with closing(sqlite3.connect(self.gateway)) as con, con: + con.executescript("CREATE TABLE tokens(id INTEGER PRIMARY KEY, name TEXT,key TEXT,status INTEGER," + "remain_quota INTEGER,unlimited_quota INTEGER,deleted_at INTEGER);" + "INSERT INTO tokens VALUES(1,'tg101','one',1,777,0,NULL),(2,'tg202','two',1,888,0,NULL);" + "CREATE TABLE users(username TEXT,status INTEGER);" + "INSERT INTO users VALUES('tg101',1),('tg202',1);") + with closing(sqlite3.connect(self.skin)) as con, con: + con.executescript("CREATE TABLE ip_claims(token_name TEXT);INSERT INTO ip_claims VALUES('tg101'),('tg202');") + self.env = patch.dict(os.environ, {"IISHKO_SKIN_DB": self.skin}, clear=True) + self.env.start() + self.addCleanup(self.env.stop) + for name, value in (("BOT_DB", self.bot), ("GW_DB", self.gateway), ("SKIN_DB", self.skin), ("PROTECT", ())): + item = patch.object(entry_autoban, name, value) + item.start() + self.addCleanup(item.stop) + + def rows(self, path, sql): + with closing(sqlite3.connect(path)) as con: + return con.execute(sql).fetchall() + + def test_empty_environment_disables_automatic_sanctions_and_delivery(self): + self.assertFalse(entry_autoban.enabled()) + self.assertFalse(delivery_enabled()) + self.assertEqual(entry_autoban.ban_cluster([101], reason="automatic_signal"), []) + self.assertEqual(self.rows(self.gateway, "SELECT status,remain_quota FROM tokens"), [(1, 777), (1, 888)]) + + def test_shared_public_ip_is_only_a_review_signal_even_if_legacy_flag_is_enabled(self): + os.environ["IISHKO_ENTRY_AUTOBAN"] = "1" + telemetry = EntryTelemetry(self.bot, b"offline-test-secret", [999], clock=lambda: 100000) + telemetry.init_db() + telemetry.record(101, "8.8.4.4") + telemetry.record(202, "8.8.4.4") + self.assertEqual(self.rows(self.bot, "SELECT banned FROM users ORDER BY tg_id"), [(0,), (0,)]) + self.assertEqual(self.rows(self.gateway, "SELECT status,remain_quota FROM tokens ORDER BY id"), [(1, 777), (1, 888)]) + self.assertEqual(self.rows(self.gateway, "SELECT status FROM users"), [(1,), (1,)]) + self.assertEqual(self.rows(self.skin, "SELECT COUNT(*) FROM ip_claims"), [(2,)]) + self.assertEqual(self.rows(self.bot, "SELECT COUNT(*) FROM wa_entry_alerts"), [(1,)]) + claim = telemetry.claim() + self.assertIsNotNone(claim) + self.assertIn("не применяется", notification_text(claim)) + self.assertFalse(entry_autoban.ban_user(101)) + self.assertEqual(entry_autoban.ban_cluster([101, 202]), []) + + def test_explicit_admin_moderation_is_not_disabled_by_safe_automatic_default(self): + with patch.object(entry_autoban, "ban_user", return_value=True) as ban: + self.assertEqual(entry_autoban.ban_cluster([101, 101], reason="admin_button"), [101]) + ban.assert_called_once_with(101, "admin_button") + + def test_unified_custom_skin_path_is_used_for_actual_ip_claim_cleanup(self): + tree = ast.parse((ROOT / "bot/grok_bot.py").read_text(encoding="utf-8")) + function = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "_full_ban") + ns = {"sqlite3": sqlite3, "Path": Path, "skin_db_path": skin_db_path, + "BOT_DB": self.bot, "log": logging.getLogger("offline-cleanup"), "_newapi_exec": Mock()} + exec(compile(ast.Module(body=[function], type_ignores=[]), "real-full-ban", "exec"), ns) + ns["_full_ban"](101, "tg101", "admin_button") + self.assertEqual(self.rows(self.skin, "SELECT token_name FROM ip_claims"), [("tg202",)]) + # The gateway uses the same resolver, not a second hardcoded fallback. + tree = ast.parse((ROOT / "gateway/grok-web-skin.py").read_text(encoding="utf-8")) + assignment = next(node for node in tree.body if isinstance(node, ast.Assign) + and any(isinstance(target, ast.Name) and target.id == "TG_PROVISION_DB" for target in node.targets)) + ns = {"skin_db_path": skin_db_path} + exec(compile(ast.Module(body=[assignment], type_ignores=[]), "gateway-path", "exec"), ns) + self.assertEqual(ns["TG_PROVISION_DB"], self.skin) + + def test_notification_opt_in_and_kill_switches(self): + for value in ("0", "", "false", "no", "off", "unexpected"): + with self.subTest(value=value), patch.dict(os.environ, {"IISHKO_NOTIFICATIONS_ENABLED": value}): + self.assertFalse(delivery_enabled()) + os.environ["IISHKO_NOTIFICATIONS_ENABLED"] = "1" + self.assertTrue(delivery_enabled()) + os.environ["IISHKO_ENTRY_DELIVERY_ENABLED"] = "0" + self.assertFalse(delivery_enabled()) + os.environ["IISHKO_ENTRY_DELIVERY_ENABLED"] = "1" + os.environ["IISHKO_SUPPORT_DELIVERY_ENABLED"] = "0" + self.assertFalse(delivery_enabled()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_file_intake.py b/tests/test_file_intake.py new file mode 100644 index 00000000..cb2d4104 --- /dev/null +++ b/tests/test_file_intake.py @@ -0,0 +1,398 @@ +"""Office-извлечение: обычные файлы, битые архивы и пределы распаковки. + +ZIP раздувает вход: 8 МБ .pptx распаковываются в сотни МБ. Тесты проверяют, +что читаются фактические байты, а не объявленный размер, что лимит общий на +архив, что чтение идёт кусками и что ранний выход срабатывает, когда текста уже +достаточно. Никаких гигантских файлов: лимиты подменяются на маленькие. +""" +import importlib +import io +import sys +import unittest +import warnings +import zipfile +from pathlib import Path +from unittest import mock + +BOT = Path(__file__).resolve().parents[1] / "bot" +sys.path.insert(0, str(BOT)) +file_intake = importlib.import_module("file_intake") +extract = file_intake.extract +_OfficeBudget = file_intake._OfficeBudget + + +def _zip_bytes(entries) -> bytes: + """Собрать zip в памяти. `entries` — список пар (name, bytes); дубликаты разрешены.""" + buf = io.BytesIO() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) # duplicate names are part of the scenario + with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf: + for name, data in entries: + zf.writestr(name, data) + return buf.getvalue() + + +def _docx_bytes(text: str = "Привет, мир") -> bytes: + return _zip_bytes([ + ("[Content_Types].xml", b""), + ("word/document.xml", + f'{text}'.encode()), + ]) + + +def _slide_body(text: str) -> bytes: + return ( + '' + f'{text}' + '' + ).encode() + + +def _pptx_bytes(texts) -> bytes: + entries = [("[Content_Types].xml", b"")] + for i, text in enumerate(texts, start=1): + entries.append((f"ppt/slides/slide{i}.xml", _slide_body(text))) + return _zip_bytes(entries) + + +def _xlsx_bytes(shared, rows) -> bytes: + items = "".join(f"{s}" for s in shared) + cells = "".join( + f'{idx}' for n, idx in enumerate(rows, start=1) + ) + sheet = ( + '' + f'{cells}' + '' + ).encode() + return _zip_bytes([ + ("[Content_Types].xml", b""), + ("xl/sharedStrings.xml", f"{items}".encode()), + ("xl/worksheets/sheet1.xml", sheet), + ]) + + +def _odt_bytes(paras) -> bytes: + body = "".join(f"{p}" for p in paras) + return _zip_bytes([ + ("[Content_Types].xml", b""), + ("content.xml", f'{body}'.encode()), + ]) + + +class _SpyZip: + """Прокси над ZipFile: считает открытия записей и запрошенные размеры read().""" + + def __init__(self, zf: zipfile.ZipFile) -> None: + self._zf = zf + self.opened: list[str] = [] + self.read_sizes: list[int] = [] + + def namelist(self): + return self._zf.namelist() + + def infolist(self): + return self._zf.infolist() + + def getinfo(self, name): + return self._zf.getinfo(name) + + def open(self, name, *args, **kwargs): + self.opened.append(name) + raw = self._zf.open(name, *args, **kwargs) + spy = self + + class _File: + def read(self, n=-1): + spy.read_sizes.append(n) + return raw.read(n) + + def __enter__(self): + return self + + def __exit__(self, *exc): + raw.close() + return False + + return _File() + + +class _RecordingBudget(_OfficeBudget): + """Запоминает созданные читатели, чтобы проверить фактический объём распаковки.""" + + created: list = [] + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + _RecordingBudget.created.append(self) + + +class OfficeExtractionTest(unittest.TestCase): + def setUp(self) -> None: + _RecordingBudget.created = [] + + # --- normal extraction -------------------------------------------------- + + def test_docx_plain_text(self) -> None: + res = extract("заметка.docx", _docx_bytes()) + self.assertTrue(res.ok, res.reason) + self.assertEqual(res.kind, "docx") + self.assertIn("Привет, мир", res.text) + self.assertFalse(res.truncated) + self.assertEqual(res.chars, len(res.text)) + + def test_pptx_slides_order_and_labels(self) -> None: + res = extract("deck.pptx", _pptx_bytes(["первый", "второй", "третий"])) + self.assertTrue(res.ok, res.reason) + self.assertEqual(res.kind, "pptx") + self.assertLess(res.text.index("первый"), res.text.index("второй")) + self.assertLess(res.text.index("второй"), res.text.index("третий")) + self.assertIn("slide1.xml", res.text) + + def test_xlsx_shared_strings_resolved(self) -> None: + res = extract("таблица.xlsx", _xlsx_bytes(["альфа", "бета"], [1, 0])) + self.assertTrue(res.ok, res.reason) + line = [ln for ln in res.text.splitlines() if "\t" in ln][0] + self.assertEqual(line.split("\t"), ["бета", "альфа"]) + + def test_odt_paragraphs(self) -> None: + res = extract("док.odt", _odt_bytes(["первый абзац", "второй абзац"])) + self.assertTrue(res.ok, res.reason) + self.assertEqual(res.kind, "odt") + self.assertIn("первый абзац", res.text) + self.assertIn("второй абзац", res.text) + + # --- refusals ----------------------------------------------------------- + + def test_corrupt_archive_is_reported(self) -> None: + res = extract("битый.pptx", b"PK\x03\x04 definitely not a real zip") + self.assertFalse(res.ok) + self.assertIn("повреждён", res.reason) + + def test_broken_compressed_stream_is_reported(self) -> None: + data = _pptx_bytes(["text"]) + errors = (EOFError("truncated compressed stream"), + file_intake.zlib.error("invalid compressed stream")) + for error in errors: + with self.subTest(error=type(error).__name__): + with mock.patch.object(zipfile.ZipFile, "open", side_effect=error): + result = extract("broken.pptx", data) + self.assertFalse(result.ok) + self.assertIn("повреждён", result.reason) + + def test_zip_without_office_structure(self) -> None: + data = _zip_bytes([("readme.txt", b"just a zip")]) + res = extract("файл.docx", data) + self.assertFalse(res.ok) + self.assertIn("без ожидаемой структуры", res.reason) + + def test_upload_limit_unchanged(self) -> None: + res = extract("big.docx", b"\0" * (file_intake.MAX_FILE_BYTES + 1)) + self.assertFalse(res.ok) + self.assertIn("предел", res.reason) + self.assertEqual(file_intake.MAX_FILE_BYTES, 8 * 1024 * 1024) + + # --- decompression limits ----------------------------------------------- + + def test_entry_limit_bounds_actual_bytes(self) -> None: + payload = ("слово " * 4000).encode() # ~24 KB of text, compresses well + data = _zip_bytes([("word/document.xml", payload)]) + with zipfile.ZipFile(io.BytesIO(data)) as real: + spy = _SpyZip(real) + reader = _OfficeBudget(spy, entry_limit=1000) + text, clipped = reader.read_prefix("word/document.xml") + self.assertTrue(clipped) + self.assertLessEqual(reader.consumed, 1000) + self.assertLessEqual(sum(spy.read_sizes), 1000) # bytes actually read + self.assertEqual(sum(spy.read_sizes), reader.consumed) + self.assertNotIn(-1, spy.read_sizes) + self.assertLessEqual(len(text), 1000) + self.assertEqual(reader.entries_read, 1) + self.assertTrue(reader.cut) + self.assertTrue(reader.warnings) + + def test_exact_cap_needs_no_lookahead(self) -> None: + """Ровно лимит байт: без досмотра лишнего байта, но помечается как обрезанное.""" + payload = b"a" * 1024 + data = _zip_bytes([("word/document.xml", payload)]) + with zipfile.ZipFile(io.BytesIO(data)) as real: + spy = _SpyZip(real) + reader = _OfficeBudget(spy, entry_limit=1024, chunk=4096) + text, clipped = reader.read_prefix("word/document.xml") + self.assertEqual(spy.read_sizes, [1024]) # a single read, exactly the cap + self.assertEqual(sum(spy.read_sizes), reader.consumed) + self.assertLessEqual(sum(spy.read_sizes), 1024) + self.assertEqual(len(text), 1024) + self.assertTrue(clipped) # an entry exactly at the cap is conservatively reported as cut + self.assertTrue(reader.cut) + + def test_entry_limit_does_not_trust_declared_size(self) -> None: + # small input, large decompressed size: only real reads are charged + payload = b"a" * 200_000 + data = _zip_bytes([("word/document.xml", payload)]) + self.assertLess(len(data), 5000) + with zipfile.ZipFile(io.BytesIO(data)) as zf: + reader = _OfficeBudget(zf, entry_limit=5000) + reader.read_prefix("word/document.xml") + self.assertLessEqual(reader.consumed, 5000) + + def test_total_budget_shared_across_entries(self) -> None: + data = _zip_bytes([ + ("ppt/slides/slide1.xml", b"x" * 5000), + ("ppt/slides/slide2.xml", b"x" * 5000), + ("ppt/slides/slide3.xml", b"x" * 5000), + ]) + with zipfile.ZipFile(io.BytesIO(data)) as real: + spy = _SpyZip(real) + reader = _OfficeBudget(spy, entry_limit=5000, total_limit=12_000) + for name in ("ppt/slides/slide1.xml", "ppt/slides/slide2.xml", "ppt/slides/slide3.xml"): + reader.read_prefix(name) + self.assertLessEqual(reader.consumed, 12_000) + self.assertLessEqual(sum(spy.read_sizes), 12_000) + self.assertEqual(sum(spy.read_sizes), reader.consumed) + self.assertTrue(reader.cut) + self.assertTrue(any("предел" in w for w in reader.warnings)) + + def test_entry_cap_bounds_actual_reads(self) -> None: + """Жёсткий предел на число записей: дальше лимита записи не открываются.""" + names = [f"part{i}.xml" for i in range(1, 21)] + data = _zip_bytes([(n, b"tiny") for n in names]) + with zipfile.ZipFile(io.BytesIO(data)) as real: + spy = _SpyZip(real) + reader = _OfficeBudget(spy, max_entries=5) + for name in names[:8]: + reader.read_prefix(name) + self.assertEqual(reader.entries_read, 5) + self.assertEqual(len(spy.opened), 5) # nothing is opened past the entry cap + self.assertTrue(reader.cut) + self.assertTrue(any("не читаются" in w for w in reader.warnings)) + + def test_reads_are_chunked(self) -> None: + data = _zip_bytes([("word/document.xml", b"y" * 20_000)]) + with zipfile.ZipFile(io.BytesIO(data)) as real: + spy = _SpyZip(real) + reader = _OfficeBudget(spy, entry_limit=20_000, chunk=1024) + reader.read_prefix("word/document.xml") + self.assertTrue(spy.read_sizes) + self.assertNotIn(-1, spy.read_sizes) # never read a whole entry at once + self.assertLessEqual(max(spy.read_sizes), 1024) + self.assertGreater(len(spy.read_sizes), 1) + + def test_slide_count_capped(self) -> None: + texts = [f"слайд {i}" for i in range(1, 11)] + with mock.patch.object(file_intake, "_OFFICE_MAX_SLIDES", 3): + with zipfile.ZipFile(io.BytesIO(_pptx_bytes(texts))) as real: + spy = _SpyZip(real) + reader = _OfficeBudget(spy) + text = file_intake._from_pptx(reader) + self.assertEqual(len(spy.opened), 3) + self.assertIn("слайд 3", text) + self.assertNotIn("слайд 4", text) + self.assertTrue(any("прочитаны первые 3" in w for w in reader.warnings)) + + def test_slide_byte_limit(self) -> None: + texts = ["текст " * 2000, "хвост"] + with mock.patch.object(file_intake, "_OFFICE_SLIDE_MAX_BYTES", 400): + with zipfile.ZipFile(io.BytesIO(_pptx_bytes(texts))) as real: + reader = _OfficeBudget(real) + file_intake._from_pptx(reader) + self.assertLessEqual(reader.consumed, 800) # per-slide cap + self.assertTrue(reader.cut) + + def test_markup_heavy_slide_stays_bounded(self) -> None: + markup = ('' + + "i" * 50 + "") * 200 # ~24 KB of markup, ~10 KB of text + data = _zip_bytes([("ppt/slides/slide1.xml", markup.encode())]) + with mock.patch.object(file_intake, "_OFFICE_SLIDE_MAX_BYTES", 2000): + res = extract("тяжёлый.pptx", data) + self.assertTrue(res.truncated) + self.assertLessEqual(len(res.text), file_intake.TEXT_BUDGET) + self.assertTrue(res.warnings) + + def test_early_stop_when_enough_text(self) -> None: + texts = [f"слайд номер {i} " + "z" * 500 for i in range(1, 41)] + with mock.patch.object(file_intake, "TEXT_BUDGET", 300): + with zipfile.ZipFile(io.BytesIO(_pptx_bytes(texts))) as real: + spy = _SpyZip(real) + reader = _OfficeBudget(spy) + res = file_intake._finish( + file_intake._from_pptx(reader), "pptx", reader.warnings, cut=reader.cut, + ) + self.assertTrue(res.ok, res.reason) + self.assertTrue(res.truncated) + self.assertLess(len(spy.opened), len(texts)) # stops before the end + self.assertLessEqual(len(res.text), 300) + self.assertTrue(any("показаны не все слайды" in w for w in res.warnings)) + + def test_eight_compressible_slides_bounded(self) -> None: + """Исходный сценарий: 8 «плотных» слайдов. Объём ограничен байтами, не памятью.""" + texts = [("слайд " + "q" * 3000) for _ in range(8)] + data = _pptx_bytes(texts) + self.assertLess(len(data), 20_000) # small input + with mock.patch.object(file_intake, "_OfficeBudget", _RecordingBudget): + res = extract("amplify.pptx", data) + self.assertTrue(_RecordingBudget.created) + reader = _RecordingBudget.created[-1] + self.assertLessEqual(reader.consumed, file_intake._OFFICE_TOTAL_MAX_BYTES) + self.assertLessEqual(len(res.text), file_intake.TEXT_BUDGET) + self.assertTrue(res.ok, res.reason) + + def test_truncation_is_announced(self) -> None: + data = _pptx_bytes(["а" * 5000, "б" * 5000, "в" * 5000, "г" * 5000, "д" * 5000, "е" * 5000]) + res = extract("long.pptx", data) + self.assertTrue(res.ok, res.reason) + self.assertTrue(res.truncated) + self.assertTrue(any("показаны первые" in w for w in res.warnings)) + + def test_duplicate_entry_read_once(self) -> None: + data = _zip_bytes([ + ("word/document.xml", "старый".encode()), + ("word/document.xml", "новый".encode()), + ]) + with mock.patch.object(file_intake, "_OfficeBudget", _RecordingBudget): + res = extract("dubl.docx", data) + self.assertTrue(res.ok, res.reason) + reader = _RecordingBudget.created[-1] + self.assertEqual(reader.entries_read, 1) + self.assertIn("новый", res.text) + self.assertLessEqual(reader.consumed, len(data) * 8) + + + # --- XLSX: one row must not inflate the text ------------------ + + def test_xlsx_reused_string_cannot_inflate_output(self) -> None: + """Одна короткая строка sharedStrings на 3000 ячеек не даёт длинный текст.""" + data = _xlsx_bytes(["z" * 40], [0] * 3000) + self.assertLess(len(data), 20_000) # small input + with mock.patch.object(file_intake, "TEXT_BUDGET", 500): + with zipfile.ZipFile(io.BytesIO(data)) as real: + reader = _OfficeBudget(real) + text = file_intake._from_xlsx(reader) + self.assertLessEqual(len(text), 600) + self.assertTrue(any("ячейк" in w for w in reader.warnings)) + self.assertTrue(reader.cut) + + def test_xlsx_amplification_marked_truncated(self) -> None: + data = _xlsx_bytes(["z" * 40], [0] * 3000) + self.assertLess(len(data), 20_000) # small input, thousands of cells + with mock.patch.object(file_intake, "TEXT_BUDGET", 500): + res = extract("широкая.xlsx", data) + self.assertEqual(file_intake.TEXT_BUDGET, 500) + self.assertTrue(res.ok, res.reason) + self.assertTrue(res.truncated) + self.assertLessEqual(len(res.text), 500) + self.assertGreater(len(res.text), 100) # useful prefix survives + self.assertTrue(res.warnings) + + def test_xlsx_cell_count_capped(self) -> None: + data = _xlsx_bytes(["z"], [0] * 3000) + with zipfile.ZipFile(io.BytesIO(data)) as real: + reader = _OfficeBudget(real) + text = file_intake._from_xlsx(reader) + self.assertTrue(any(f"ячеек в строке больше {file_intake._MAX_XLSX_CELLS}" in w + for w in reader.warnings)) + self.assertEqual(text.splitlines()[-1].count("\t") + 1, file_intake._MAX_XLSX_CELLS) + + +if __name__ == "__main__": + unittest.main() \ No newline at end of file diff --git a/tests/test_file_intake_pptx_budget.py b/tests/test_file_intake_pptx_budget.py index 59c34bf4..dfd1ebaf 100644 --- a/tests/test_file_intake_pptx_budget.py +++ b/tests/test_file_intake_pptx_budget.py @@ -1,4 +1,4 @@ -"""PPTX: many highly-compressible slides must not be decompressed past the budgets.""" +"""PPTX extraction stops on text and actual decompression budgets.""" import io from pathlib import Path import sys @@ -20,19 +20,36 @@ def _pptx(slides: int, text: str) -> bytes: class PptxBudgetTest(unittest.TestCase): - def test_stops_reading_after_text_budget(self): - data = _pptx(200, "x" * 5000) - with mock.patch.object(file_intake, "_read_entry", wraps=file_intake._read_entry) as rd: - res = file_intake.extract("deck.pptx", data) - self.assertTrue(res.ok) - self.assertTrue(res.truncated) - self.assertLess(rd.call_count, 10) + def _extract_with_budget(self, data, total_limit=None): + readers = [] + original = file_intake._OfficeBudget - def test_total_unpacked_budget_rejects(self): - data = _pptx(20, "" * 262144) # 20 MiB of markup, no text - with mock.patch.object(file_intake, "_MAX_UNPACKED_BYTES", 8 * 1024 * 1024): - res = file_intake.extract("deck.pptx", data) - self.assertFalse(res.ok) + def factory(zf): + kwargs = {} if total_limit is None else {"total_limit": total_limit} + reader = original(zf, **kwargs) + readers.append(reader) + return reader + + with mock.patch.object(file_intake, "_OfficeBudget", side_effect=factory): + result = file_intake.extract("deck.pptx", data) + self.assertEqual(len(readers), 1) + return result, readers[0] + + def test_stops_reading_after_text_budget(self): + result, reader = self._extract_with_budget(_pptx(200, "x" * 5000)) + self.assertTrue(result.ok) + self.assertTrue(result.truncated) + self.assertLess(reader.entries_read, 10) + self.assertLessEqual(len(result.text), file_intake.TEXT_BUDGET) + + def test_total_unpacked_budget_rejects_textless_archive(self): + limit = 8 * 1024 * 1024 + result, reader = self._extract_with_budget(_pptx(20, "" * 262144), limit) + self.assertFalse(result.ok) + self.assertTrue(result.truncated) + self.assertEqual(reader.consumed, limit) + self.assertLess(reader.entries_read, 20) + self.assertTrue(result.warnings) if __name__ == "__main__": diff --git a/tests/test_runtime_bootstrap.py b/tests/test_runtime_bootstrap.py new file mode 100644 index 00000000..8bbd8c26 --- /dev/null +++ b/tests/test_runtime_bootstrap.py @@ -0,0 +1,191 @@ +"""Bootstrap tests use temporary config files, not operator or production settings.""" +from contextlib import closing +import importlib.util +import io +import json +import os +from pathlib import Path +import sqlite3 +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location("runtime_launcher", ROOT / "scripts/run.py") +assert spec is not None and spec.loader is not None +launcher = importlib.util.module_from_spec(spec) +spec.loader.exec_module(launcher) +sys.path.insert(0, str(ROOT / "bot")) +runtime_config = __import__("runtime_config") + + +class BootstrapTests(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + (self.root / "bot").mkdir() + (self.root / "gateway").mkdir() + (self.root / "bot/webapp").mkdir() + self.config = {"bot_token": "123456:offline-token", "main_key": "offline-main", + "newapi_pass": "offline-password", "channel_username": "offline_channel", + "bot_db": "./bot.db", "newapi_db": "./one-api.db", + "newapi_url": "http://127.0.0.1:49100"} + (self.root / "bot/config.json").write_text(json.dumps(self.config), encoding="utf-8") + with closing(sqlite3.connect(self.root / "one-api.db")) as con: + con.execute("CREATE TABLE tokens(id INTEGER PRIMARY KEY)") + con.commit() + (self.root / ".env").write_text("IISHKO_SKIN_DB=./skin.db\n", encoding="utf-8") + + def test_explicit_root_dotenv_loads_without_shell_or_interpolation(self): + (self.root / ".env").write_text( + '\ufeffGROK_BOT_CFG=./bot/config.json\nIISHKO_SKIN_DB="./skin with space.db"\n' + 'IISHKO_ENTRY_AUTOBAN=0 # comment\nOPAQUE="${SHELL_SECRET} $(nothing-executed)"\n', encoding="utf-8") + env = launcher.prepare_environment(self.root, process={"SHELL_SECRET": "must-not-expand"}) + self.assertEqual(env["GROK_BOT_CFG"], str(self.root / "bot/config.json")) + self.assertEqual(env["IISHKO_ENTRY_AUTOBAN"], "0") + self.assertEqual(env["IISHKO_SKIN_DB"], str(self.root / "skin with space.db")) + self.assertEqual(env["GATE_TG_DB"], env["IISHKO_SKIN_DB"]) + self.assertEqual(env["OPAQUE"], "${SHELL_SECRET} $(nothing-executed)") + self.assertEqual(launcher.check_configuration(env), []) + + def test_real_environment_including_legacy_alias_beats_file(self): + (self.root / ".env").write_text("IISHKO_SKIN_DB=./file.db\nIISHKO_NOTIFICATIONS_ENABLED=1\n", encoding="utf-8") + env = launcher.prepare_environment(self.root, process={"GATE_TG_DB": "./service.db", + "IISHKO_NOTIFICATIONS_ENABLED": "0"}) + self.assertEqual(env["IISHKO_SKIN_DB"], str(self.root / "service.db")) + self.assertEqual(env["IISHKO_NOTIFICATIONS_ENABLED"], "0") + env = launcher.prepare_environment(self.root, process={"IISHKO_SKIN_DB": "./canonical.db", "GATE_TG_DB": "./old.db"}) + self.assertEqual(env["GATE_TG_DB"], str(self.root / "canonical.db")) + + def test_legacy_config_and_db_aliases_are_shared_across_components(self): + env = launcher.prepare_environment(self.root, process={"GROK_BOT_CONFIG": "./bot/config.json", + "GATE_NEWAPI_DB": "./one-api.db"}) + with patch.dict(os.environ, env, clear=True): + self.assertEqual(runtime_config.bot_config_path(), env["GROK_BOT_CFG"]) + self.assertEqual(runtime_config.gateway_db_path(), env["IISHKO_GW_DB"]) + self.assertEqual(runtime_config.skin_db_path(), env["IISHKO_SKIN_DB"]) + self.assertEqual(env["GATE_BOT_CONFIG"], env["GROK_BOT_CFG"]) + self.assertEqual(env["GATE_NEWAPI_DB"], env["IISHKO_GW_DB"]) + + def test_no_parent_dotenv_discovery_and_explicit_missing_file_fails(self): + (self.root / ".env").write_text("PARENT_ONLY=not-loaded\n", encoding="utf-8") + child = self.root / "child" + child.mkdir() + self.assertNotIn("PARENT_ONLY", launcher.prepare_environment(child, process={})) + with self.assertRaises(ValueError): + launcher.prepare_environment(self.root, env_file="missing.env", process={}) + + def test_real_platform_module_separator_and_direct_legacy_fallback(self): + env = launcher.prepare_environment(self.root, process={}) + self.assertIn(str(self.root / "bot"), env["PYTHONPATH"].split(os.pathsep)) + self.assertIn(str(self.root / "gateway"), env["PYTHONPATH"].split(os.pathsep)) + with patch.dict(os.environ, {}, clear=True): + self.assertEqual(runtime_config.skin_db_path(), "/opt/grok-web-skin-tg.db") + self.assertFalse(runtime_config.notifications_enabled()) + with patch.dict(os.environ, {"GATE_TG_DB": "legacy.db"}, clear=True): + self.assertEqual(runtime_config.skin_db_path(), "legacy.db") + + def test_check_is_offline_and_never_starts_application(self): + with patch.object(launcher, "ROOT", self.root), patch.object(launcher, "prepare_environment", return_value=launcher.prepare_environment(self.root, process={})), patch.object(launcher.runpy, "run_path") as run, patch("sys.stdout", new_callable=io.StringIO) as out: + self.assertEqual(launcher.main(["bot", "--check"]), 0) + run.assert_not_called() + self.assertIn("no app started", out.getvalue()) + + def test_normal_launch_receives_dotenv_paths_and_selected_entrypoint(self): + env = launcher.prepare_environment(self.root, process={}) + old_cwd, old_path, old_argv = Path.cwd(), list(sys.path), list(sys.argv) + try: + with patch.dict(os.environ, {}, clear=True), patch.object(launcher, "ROOT", self.root), patch.object(launcher, "prepare_environment", return_value=env), patch.object(launcher.runpy, "run_path") as run: + self.assertEqual(launcher.main(["miniapp"]), 0) + run.assert_called_once_with(str(self.root / "bot/webapp/server.py"), run_name="__main__") + self.assertEqual(os.environ["GROK_BOT_CONFIG"], str(self.root / "bot/config.json")) + self.assertEqual(Path.cwd(), self.root) + self.assertIn(str(self.root / "bot"), sys.path) + finally: + os.chdir(old_cwd) + sys.path[:] = old_path + sys.argv[:] = old_argv + + def test_missing_config_and_placeholders_fail_without_leaking_values(self): + config_path = self.root / "bot/config.json" + config_path.write_text('{"bot_token":"REPLACE_ME_PRIVATE_VALUE"}', encoding="utf-8") + errors = launcher.check_configuration(launcher.prepare_environment(self.root, process={})) + self.assertTrue(errors) + self.assertNotIn("PRIVATE_VALUE", str(errors)) + config_path.unlink() + self.assertIn("missing", launcher.check_configuration(launcher.prepare_environment(self.root, process={}))[0]) + + def test_config_upstream_and_db_survive_without_explicit_env_overrides(self): + env = launcher.prepare_environment(self.root, process={}) + self.assertEqual(env["IISHKO_UPSTREAM"], self.config["newapi_url"]) + self.assertEqual(env["NEWAPI_URL"], self.config["newapi_url"]) + self.assertEqual(env["IISHKO_GW_DB"], str(self.root / "one-api.db")) + self.assertNotIn("TG_SID_SECRET_FILE", env) + with patch.dict(os.environ, env, clear=True): + resolved = runtime_config.effective_bot_config(self.config) + self.assertEqual(resolved["newapi_url"], env["IISHKO_UPSTREAM"]) + self.assertEqual(resolved["newapi_db"], env["IISHKO_GW_DB"]) + + def test_env_secrets_override_config_for_validation_and_all_consumers(self): + for key in ("bot_token", "newapi_pass"): + self.config[key] = "REPLACE_ME_PRIVATE_VALUE" + (self.root / "bot/config.json").write_text(json.dumps(self.config), encoding="utf-8") + process = {"GROK_BOT_TOKEN": "123456:env-offline-token", "NEWAPI_PASS": "env-offline-password", + "NEWAPI_URL": "http://127.0.0.1:49101", "TG_SID_SECRET_FILE": "./existing-secret"} + env = launcher.prepare_environment(self.root, process=process) + self.assertEqual(launcher.check_configuration(env), []) + self.assertEqual(env["TG_SID_SECRET_FILE"], str(self.root / "existing-secret")) + with patch.dict(os.environ, env, clear=True): + resolved = runtime_config.effective_bot_config(self.config) + self.assertEqual(resolved["bot_token"], process["GROK_BOT_TOKEN"]) + self.assertEqual(resolved["newapi_pass"], process["NEWAPI_PASS"]) + self.assertEqual(resolved["newapi_url"], process["NEWAPI_URL"]) + + def test_preflight_rejects_invalid_data_directories_without_creating_db(self): + env = launcher.prepare_environment(self.root, process={}) + for key in ("IISHKO_BOT_DB", "IISHKO_SKIN_DB"): + with self.subTest(key=key): + changed = {**env, key: str(self.root / "missing-directory/new.db")} + self.assertTrue(any(key in problem for problem in launcher.check_configuration(changed))) + self.assertFalse(Path(changed[key]).exists()) + + def test_real_cli_reads_explicit_env_outside_repository_cwd(self): + env_file = self.root / "runtime.env" + env_file.write_text("\n".join(( + "GROK_BOT_CFG=" + (self.root / "bot/config.json").as_posix(), + "IISHKO_GW_DB=" + (self.root / "one-api.db").as_posix(), + "IISHKO_APP_ROOT=" + (self.root / "bot").as_posix(), + "IISHKO_BOT_DB=" + (self.root / "bot.db").as_posix(), + "IISHKO_SKIN_DB=" + (self.root / "skin.db").as_posix(), + )), encoding="utf-8") + process = {key: value for key, value in os.environ.items() + if not key.startswith(("IISHKO_", "GATE_", "GROK_", "NEWAPI_", "TG_SID_"))} + for component in launcher.COMPONENTS: + with self.subTest(component=component): + result = subprocess.run([sys.executable, str(ROOT / "scripts/run.py"), component, + "--env-file", str(env_file), "--check"], cwd=self.root, + env=process, capture_output=True, text=True, timeout=15) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("preflight passed", result.stdout) + + def test_selfcheck_accepts_the_same_utf8_bom_config_as_entrypoints(self): + sc_spec = importlib.util.spec_from_file_location("iishko_selfcheck", ROOT / "scripts/selfcheck.py") + assert sc_spec is not None and sc_spec.loader is not None + selfcheck = importlib.util.module_from_spec(sc_spec) + sc_spec.loader.exec_module(selfcheck) + config_path = self.root / "bot/config.json" + config_path.write_text(json.dumps(self.config), encoding="utf-8-sig") + self.assertEqual(config_path.read_bytes()[:3], b"\xef\xbb\xbf") + problems, notes = [], [] + with patch.object(selfcheck, "ROOT", str(self.root)), \ + patch.dict(os.environ, {"GROK_BOT_CFG": str(config_path)}): + selfcheck.check_config_templates(problems, notes) + self.assertEqual(problems, []) + self.assertFalse(any("bot config not found" in note for note in notes)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_runtime_economy_paths.py b/tests/test_runtime_economy_paths.py new file mode 100644 index 00000000..7ed69ff9 --- /dev/null +++ b/tests/test_runtime_economy_paths.py @@ -0,0 +1,281 @@ +"""Economy consumers must honour the shared runtime path helpers. + +Regressions cover non-default paths and conflicting aliases without importing the +whole bot runtime: econ_cap/account_admin are loaded as isolated module instances, +and the Mini App daemon helpers are AST-extracted and executed alone. +""" +import ast +from contextlib import closing +import importlib.util +import itertools +import json +import os +from pathlib import Path +import sqlite3 +import subprocess +import sys +import tempfile +import time +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +BOT = ROOT / "bot" +sys.path.insert(0, str(BOT)) + +COUNTER = itertools.count() + +DEFAULT_BOT_DB = "/opt/grok-bot/bot.db" +DEFAULT_GW_DB = "/opt/grok-gateway/new-api/one-api.db" +DEFAULT_STATE = "/opt/grok-bot/econ_cap_state.json" + + +def _load(relative_path): + """Load a module file by path so each case sees its own environment.""" + path = BOT / relative_path + name = "econ_paths_probe_%s_%d" % (path.stem, next(COUNTER)) + spec = importlib.util.spec_from_file_location(name, path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _daemon_functions(names, environ): + """Execute only the requested functions from mk_daemon, never the module.""" + source = (BOT / "webapp" / "mk_daemon.py").read_text(encoding="utf-8") + tree = ast.parse(source) + wanted = [node for node in tree.body + if isinstance(node, ast.FunctionDef) and node.name in names] + missing = set(names) - {node.name for node in wanted} + assert not missing, "mk_daemon.py no longer defines %s" % sorted(missing) + calls = [] + + def econ_state_path(): + calls.append(True) + return environ["IISHKO_ECON_STATE"] + + namespace = {"json": json, "sqlite3": sqlite3, "econ_state_path": econ_state_path, + "calls": calls} + exec(compile(ast.Module(body=wanted, type_ignores=[]), "", "exec"), namespace) + return namespace, calls + + +def _module_assignments(relative_path): + tree = ast.parse((BOT / relative_path).read_text(encoding="utf-8")) + found = {} + for node in tree.body: + if isinstance(node, ast.Assign): + for target in node.targets: + if isinstance(target, ast.Name): + found[target.id] = node.value + return found + + +def _calls_name(node, name): + return (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) + and node.func.id == name) + + +def _mentions(node, name): + return any(isinstance(item, ast.Attribute) and item.attr == name + or isinstance(item, ast.Name) and item.id == name + for item in ast.walk(node)) + + +class ConsumerPathTests(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + root = Path(tmp.name) + self.bot_db = str(root / "custom" / "bot.db") + self.gw_db = str(root / "custom" / "gateway.db") + self.state = str(root / "custom" / "econ_state.json") + for path in (self.bot_db, self.gw_db, self.state): + Path(path).parent.mkdir(parents=True, exist_ok=True) + + # ---------------------------------------------------------------- econ_cap + def test_econ_cap_prefers_canonical_names(self): + env = { + "IISHKO_BOT_DB": self.bot_db, + "GROK_BOT_DB": "/legacy/bot.db", + "GATE_BOT_DB": "/legacy/gate.db", + "IISHKO_GW_DB": self.gw_db, + "GATE_NEWAPI_DB": "/legacy/gateway.db", + "IISHKO_ECON_STATE": self.state, + } + with patch.dict(os.environ, env, clear=True): + module = _load("econ_cap.py") + self.assertEqual(module.BOT_DB, self.bot_db) + self.assertEqual(module.NA_DB, self.gw_db) + self.assertEqual(module.STATE, self.state) + + def test_econ_cap_keeps_legacy_aliases(self): + env = {"GROK_BOT_DB": self.bot_db, "GATE_NEWAPI_DB": self.gw_db} + with patch.dict(os.environ, env, clear=True): + module = _load("econ_cap.py") + self.assertEqual(module.BOT_DB, self.bot_db) + self.assertEqual(module.NA_DB, self.gw_db) + + def test_econ_cap_ignores_empty_canonical_alias(self): + env = {"IISHKO_BOT_DB": "", "GROK_BOT_DB": self.bot_db, + "IISHKO_ECON_STATE": ""} + with patch.dict(os.environ, env, clear=True): + module = _load("econ_cap.py") + self.assertEqual(module.BOT_DB, self.bot_db) + self.assertEqual(module.STATE, DEFAULT_STATE) + + def test_econ_cap_defaults_when_nothing_is_configured(self): + with patch.dict(os.environ, {}, clear=True): + module = _load("econ_cap.py") + self.assertEqual(module.BOT_DB, DEFAULT_BOT_DB) + self.assertEqual(module.NA_DB, DEFAULT_GW_DB) + self.assertEqual(module.STATE, DEFAULT_STATE) + + def test_econ_cap_state_file_round_trip(self): + Path(self.state).write_text(json.dumps({"v": 2, "paused": {"tg101": {"tid": 7}}}), + encoding="utf-8") + with patch.dict(os.environ, {"IISHKO_ECON_STATE": self.state}, clear=True): + module = _load("econ_cap.py") + paused, migrated = module.load_state(archive=False) + self.assertEqual(paused, {"tg101": {"tid": 7}}) + self.assertEqual(migrated, 0) + + # ------------------------------------------------------------ account_admin + def test_account_admin_pause_path_uses_canonical_helper(self): + with patch.dict(os.environ, {"IISHKO_ECON_STATE": self.state}, clear=True): + module = _load("account_admin.py") + self.assertEqual(module.PAUSE_PATH, self.state) + for name in ("set_banned", "unban_account"): + default = module.__dict__[name].__kwdefaults__["pause_path"] + self.assertEqual(default, self.state, name) + + def test_account_admin_pause_path_falls_back(self): + with patch.dict(os.environ, {}, clear=True): + module = _load("account_admin.py") + self.assertEqual(module.PAUSE_PATH, DEFAULT_STATE) + + # --------------------------------------------------------------- mk_daemon + def test_mk_daemon_module_paths_come_from_helpers(self): + assigns = _module_assignments("webapp/mk_daemon.py") + self.assertTrue(_calls_name(assigns["BOT_DB"], "bot_db_path"), + "mk_daemon BOT_DB must use the shared bot_db_path helper") + self.assertTrue(_mentions(assigns["GW_DB"], "CFG"), + "mk_daemon GW_DB must follow the imported bot CFG") + self.assertNotIn("GROK_BOT_DB", ast.dump(assigns["BOT_DB"]), + "mk_daemon must not re-implement the bot DB alias list") + + def test_mk_daemon_reads_pause_state_from_env_path(self): + Path(self.state).write_text(json.dumps({"v": 2, "paused": {}}), encoding="utf-8") + environ = {"IISHKO_ECON_STATE": self.state} + namespace, calls = _daemon_functions({"_state_path", "_read_pause_state"}, environ) + self.assertEqual(namespace["_read_pause_state"](), {"v": 2, "paused": {}}) + self.assertTrue(calls, "_read_pause_state must resolve the helper by default") + + def test_mk_daemon_explicit_state_override_wins(self): + other = str(Path(self.state).with_name("override.json")) + Path(other).write_text(json.dumps({"v": 2, "paused": {"tg101": {"tid": 1}}}), + encoding="utf-8") + environ = {"IISHKO_ECON_STATE": str(Path(self.state).with_name("missing.json"))} + namespace, _ = _daemon_functions({"_state_path", "_read_pause_state"}, environ) + self.assertEqual(namespace["_read_pause_state"](other), + {"v": 2, "paused": {"tg101": {"tid": 1}}}) + + def test_mk_daemon_daily_pause_info_lazy_read(self): + now = int(time.time()) + Path(self.state).write_text(json.dumps( + {"v": 2, "paused": {"tg101": {"tid": 7, "ts": now, "prev_status": 1}}}), + encoding="utf-8") + environ = {"IISHKO_ECON_STATE": self.state} + namespace, calls = _daemon_functions({"_state_path", "_read_pause_state", "_daily_pause_info"}, + environ) + with closing(sqlite3.connect(":memory:")) as con: + info = namespace["_daily_pause_info"]( + con, {"status": 2, "id": 7, "name": "tg101"}, {}) + self.assertTrue(info.get("daily_paused")) + self.assertGreater(info["retry_at"], now) + self.assertTrue(calls, "_daily_pause_info must read the configured state file") + + def test_mk_daemon_no_hardcoded_economy_paths(self): + source = (BOT / "webapp" / "mk_daemon.py").read_text(encoding="utf-8") + self.assertNotIn("/opt/grok-bot", source) + + def test_consumers_have_no_hardcoded_economy_paths(self): + for relative in ("econ_cap.py", "account_admin.py"): + source = (BOT / relative).read_text(encoding="utf-8") + self.assertNotIn(DEFAULT_STATE, source, relative) + self.assertNotIn(DEFAULT_BOT_DB, source, relative) + self.assertNotIn(DEFAULT_GW_DB, source, relative) + + +class EntryAndNotificationPathsTests(unittest.TestCase): + def test_entry_admin_initializes_only_the_selected_alias_database(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for alias in ("IISHKO_BOT_DB", "GROK_BOT_DB", "GATE_BOT_DB"): + with self.subTest(alias=alias): + db = root / (alias + ".db") + with patch.dict(os.environ, {alias: str(db)}, clear=True): + module = _load("entry_admin.py") + self.assertEqual(module.BOT_DB, str(db)) + module.init_db() + with closing(sqlite3.connect(db)) as con: + self.assertIsNotNone(con.execute( + "SELECT name FROM sqlite_master WHERE name='wa_entry_tags'").fetchone()) + + def test_entry_admin_binding_follows_the_effective_application_database(self): + for relative, module_name in (("grok_bot.py", "_entry_admin"), + ("webapp/server.py", "entry_admin")): + with self.subTest(source=relative): + tree = ast.parse((BOT / relative).read_text(encoding="utf-8")) + bindings = [node for node in tree.body if isinstance(node, ast.Assign) + and any(isinstance(target, ast.Attribute) + and isinstance(target.value, ast.Name) + and target.value.id == module_name and target.attr == "BOT_DB" + for target in node.targets)] + self.assertEqual(len(bindings), 1) + self.assertEqual(ast.dump(bindings[0].value), ast.dump(ast.Name(id="BOT_DB", ctx=ast.Load()))) + bot_db = _module_assignments(relative)["BOT_DB"] + self.assertEqual(ast.dump(bot_db), ast.dump(ast.parse('CFG["bot_db"]', mode="eval").body)) + self.assertTrue(any(isinstance(node, ast.Call) and isinstance(node.func, ast.Name) + and node.func.id == "effective_bot_config" for node in ast.walk(tree))) + + def test_notification_cli_honours_config_env_and_explicit_paths_without_writing(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + config_db, env_db, explicit_db = (root / name for name in ("config.db", "env.db", "explicit.db")) + for db in (config_db, env_db, explicit_db): + with closing(sqlite3.connect(db)) as con: + con.execute("CREATE TABLE users(tg_id INTEGER,created INTEGER,privacy_ok INTEGER,banned INTEGER,lang TEXT)") + con.commit() + config = root / "config.json" + config.write_text(json.dumps({"bot_db": str(config_db), "key_wait_hours": 2}), encoding="utf-8-sig") + before = {db: db.read_bytes() for db in (config_db, env_db, explicit_db)} + base_env = {key: value for key, value in os.environ.items() + if not key.startswith(("IISHKO_", "GROK_", "GATE_"))} + scenarios = [ + ({"GATE_BOT_CONFIG": str(config)}, []), + ({"GROK_BOT_CONFIG": str(config), "IISHKO_BOT_DB": str(env_db)}, []), + ({"GROK_BOT_CFG": str(config), "GATE_BOT_DB": str(env_db)}, []), + ({"GROK_BOT_CFG": str(config), "IISHKO_BOT_DB": str(root / "absent.db")}, + ["--bot-db", str(explicit_db)]), + ] + for variables, args in scenarios: + with self.subTest(variables=sorted(variables), explicit=bool(args)): + configured_db = root / "config-should-not-be-opened.db" if any( + key.endswith("BOT_DB") for key in variables) else config_db + config.write_text(json.dumps({"bot_db": str(configured_db), "key_wait_hours": 2}), + encoding="utf-8-sig") + result = subprocess.run([sys.executable, str(BOT / "key_notifications.py"), "dry-run", *args], + cwd=root, env={**base_env, **variables}, capture_output=True, + text=True, encoding="utf-8", timeout=20) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(json.loads(result.stdout)["wait_seconds"], 7200) + self.assertFalse((root / "absent.db").exists()) + self.assertFalse((root / "config-should-not-be-opened.db").exists()) + self.assertFalse((root / "key_notifications.sqlite3").exists()) + self.assertEqual({db: db.read_bytes() for db in before}, before) + + +if __name__ == "__main__": + unittest.main() \ No newline at end of file diff --git a/tests/test_runtime_startup.py b/tests/test_runtime_startup.py new file mode 100644 index 00000000..39d6d23c --- /dev/null +++ b/tests/test_runtime_startup.py @@ -0,0 +1,470 @@ +"""Startup smoke tests: every entrypoint is launched through ``scripts/run.py``. + +Each test starts a real child interpreter with a scratch ``--env-file``; the +child bootstrap (a temporary ``sitecustomize``) forbids non-loopback network +access, and the bot child replaces the Telegram transport at the boundary with +one that only answers the calls a healthy startup needs. The bot test proves +that the real dispatcher reaches polling and that background workers were +registered and cancelled; the web app and gateway tests prove their listener +answers a request that touches neither SQLite business tables nor upstreams. + +Nothing here starts production services: all writable paths (databases, icons, +key files, secret file, economy state) come from the generated env file, and +all listening ports are loopback ports reserved and released by the test. +""" +from __future__ import annotations + +import hashlib +import json +import os +import socket +import sqlite3 +import subprocess +import sys +import textwrap +import time +import urllib.error +import urllib.parse +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +LAUNCHER = ROOT / "scripts" / "run.py" + +APP_ENV_PREFIXES = ("IISHKO_", "GROK_", "GATE_", "NEWAPI_", "TELEGRAM_", "TG_") +STRIPPED_ENV = frozenset( + {"PYTHONHOME", "PYTHONSTARTUP", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY"}) + +STARTUP_TIMEOUT = 120.0 +HTTP_TIMEOUT = 2.0 +HTTP_POLL_INTERVAL = 0.2 + +# Defaults in bot/grok_bot.py, bot/runtime_config.py and gateway/grok-web-skin.py. +# A test that writes any of these has leaked a production path. +HARDCODED_STARTUP_PATHS = ( + Path("C:/opt/grok-bot/bot.db"), + Path("C:/opt/grok-bot/icons.json"), + Path("C:/opt/grok-bot/econ_cap_state.json"), + Path("C:/opt/grok-gateway/new-api/one-api.db"), + Path("C:/opt/grok-web-skin-tg.db"), + Path("C:/root/.secrets/newapi_admin_token"), + Path("C:/root/iishko_audit.jsonl"), +) + +CHILD_BOOTSTRAP = r''' +"""Temporary bootstrap injected via PYTHONPATH into every smoke child.""" +import atexit +import inspect +import ipaddress +import json +import os +import socket +import sqlite3 +import sys + +_LOOPBACK_NAMES = frozenset({"localhost", "localhost.localdomain", "ip6-localhost"}) +_STATE = {"methods": [], "polling": 0, "routers": 0, "workers_at_polling": 0, "tasks": []} + + +def _blocked(host): + if host is None or host == "" or host is False: + return False # bind on all interfaces / local resolution without a host + if isinstance(host, bytes): + host = host.decode("ascii", "replace") + host = str(host) + if host in _LOOPBACK_NAMES: + return False + try: + return not ipaddress.ip_address(host).is_loopback + except ValueError: + return True # a real DNS name; startup must not need it + + +def _guard(address): + if isinstance(address, str): + return # AF_UNIX path + if not isinstance(address, tuple) or not address: + raise PermissionError("SMOKE_NETGUARD: unsupported socket address %r" % (address,)) + if _blocked(address[0]): + raise PermissionError("SMOKE_NETGUARD: blocked network address %r" % (address,)) + + +def _install_netguard(): + real_connect = socket.socket.connect + real_connect_ex = socket.socket.connect_ex + real_sendto = socket.socket.sendto + real_create_connection = socket.create_connection + real_getaddrinfo = socket.getaddrinfo + real_gethostbyname = socket.gethostbyname + real_gethostbyname_ex = socket.gethostbyname_ex + real_getnameinfo = socket.getnameinfo + + def connect(self, address): + _guard(address) + return real_connect(self, address) + + def connect_ex(self, address): + _guard(address) + return real_connect_ex(self, address) + + def sendto(self, data, *args): + if args: + _guard(args[-1]) + return real_sendto(self, data, *args) + + def create_connection(address, *args, **kwargs): + _guard(address) + return real_create_connection(address, *args, **kwargs) + + def getaddrinfo(host, port, *args, **kwargs): + if _blocked(host): + raise PermissionError("SMOKE_NETGUARD: blocked DNS lookup %r" % (host,)) + return real_getaddrinfo(host, port, *args, **kwargs) + + def gethostbyname(host): + if _blocked(host): + raise PermissionError("SMOKE_NETGUARD: blocked DNS lookup %r" % (host,)) + return real_gethostbyname(host) + + def gethostbyname_ex(host): + if _blocked(host): + raise PermissionError("SMOKE_NETGUARD: blocked DNS lookup %r" % (host,)) + return real_gethostbyname_ex(host) + + def getnameinfo(sockaddr, flags): + if isinstance(sockaddr, tuple) and sockaddr: + _guard(sockaddr) + return real_getnameinfo(sockaddr, flags) + + socket.socket.connect = connect + socket.socket.connect_ex = connect_ex + socket.socket.sendto = sendto + socket.create_connection = create_connection + socket.getaddrinfo = getaddrinfo + socket.gethostbyname = gethostbyname + socket.gethostbyname_ex = gethostbyname_ex + socket.getnameinfo = getnameinfo + + +def _install_bot_fake(): + from aiogram import Dispatcher + from aiogram.client.session.aiohttp import AiohttpSession + + async def make_request(self, bot, method, timeout=None, **kwargs): + from aiogram.types import ChatMemberMember, User + + name = type(method).__name__ + _STATE["methods"].append(name) + if name == "GetMe": + return User(id=424242424, is_bot=True, first_name="Smoke", username="smoke_bot") + if name in ("DeleteWebhook", "SetMyCommands"): + return True + if name == "GetChatMember": + return ChatMemberMember(user=User(id=424242425, is_bot=False, first_name="Smoke")) + raise AssertionError("SMOKE_BOT_FAKE: unexpected Telegram method " + name) + + async def start_polling(self, *args, **kwargs): + _STATE["polling"] += 1 + _STATE["routers"] = len(getattr(self, "sub_routers", ())) + caller = inspect.currentframe().f_back + workers = (caller.f_globals.get("_BG_WORKERS") or {}) if caller is not None else {} + _STATE["workers_at_polling"] = len(workers) + _STATE["tasks"] = [task for task in workers.values() if task is not None] + raise SystemExit(0) + + AiohttpSession.make_request = make_request + Dispatcher.start_polling = start_polling + + +def _dump(): + path = os.environ.get("SMOKE_RESULT_FILE") + if not path: + return + payload = { + "polling": _STATE["polling"], + "routers": _STATE["routers"], + "workers_at_polling": _STATE["workers_at_polling"], + "tasks_pending": sum(1 for task in _STATE["tasks"] if not task.done()), + "methods": list(_STATE["methods"]), + } + database = os.environ.get("IISHKO_BOT_DB") + if database and os.path.isfile(database): + try: + connection = sqlite3.connect(database) + try: + payload["tables"] = connection.execute( + "SELECT count(*) FROM sqlite_master WHERE type='table'").fetchone()[0] + finally: + connection.close() + except sqlite3.Error as error: + payload["tables_error"] = type(error).__name__ + with open(path, "w", encoding="utf-8") as sink: + json.dump(payload, sink) + + +if os.environ.get("SMOKE_NETGUARD") == "1": + _install_netguard() + +if os.environ.get("SMOKE_FAKE_BOT") == "1": + _install_bot_fake() + +atexit.register(_dump) +''' + + +def _fake_secret(seed: str) -> str: + return hashlib.sha256(("iishko-smoke:" + seed).encode("utf-8")).hexdigest() + + +def _free_port() -> int: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +def _free_ports(count: int) -> list[int]: + ports: list[int] = [] + while len(ports) < count: + port = _free_port() + if port not in ports: + ports.append(port) + return ports + + +def _write_json(path: Path, payload: object) -> None: + # utf-8-sig mirrors what operators hand-write on Windows; every entrypoint must accept it. + path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8-sig") + + +def _create_sqlite(path: Path, statements: tuple[str, ...]) -> None: + connection = sqlite3.connect(path) + try: + for statement in statements: + connection.execute(statement) + connection.commit() + finally: + connection.close() + + +def _runtime(tmp_path: Path, target: str) -> dict: + """Write every writable path into an env file; return the launch description.""" + workdir = tmp_path / "runtime" + workdir.mkdir() + bootstrap = tmp_path / "bootstrap" + bootstrap.mkdir() + (bootstrap / "sitecustomize.py").write_text(textwrap.dedent(CHILD_BOOTSTRAP), encoding="utf-8") + + paths = { + "config": workdir / "config.json", + "icons": workdir / "icons.json", + "bot_db": workdir / "bot.db", + "newapi_db": workdir / "newapi.db", + "skin_db": workdir / "skin.db", + "econ_state": workdir / "econ_cap_state.json", + "uptime_db": workdir / "uptime.db", + "support_db": workdir / "support.db", + "bot_source": workdir / "fake_bot_source.py", + "tg_secret": workdir / "tg_sid_secret", + "afkeys": workdir / "afkeys.json", + "kie_pool": workdir / "kie_pool.json", + "kie_dead": workdir / "kie_dead.json", + "pikeys": workdir / "pikeys.json", + "stdout": workdir / "child.stdout", + "stderr": workdir / "child.stderr", + "result": workdir / "result.json", + "env": workdir / "runtime.env", + } + ports = dict(zip(("webapp", "gateway", "upstream"), _free_ports(3))) + + _write_json(paths["config"], { + "bot_token": "424242424:" + _fake_secret("bot-token"), + "main_key": "sk-" + _fake_secret("main-key"), + "channel_username": "@smoke_channel", + "newapi_pass": "np-" + _fake_secret("newapi-pass")[:32], + "newapi_db": paths["newapi_db"].as_posix(), + "newapi_url": "http://127.0.0.1:%d" % ports["upstream"], + }) + _write_json(paths["icons"], {}) + paths["bot_source"].write_text( + "TIER_MODELS = {1: ['smoke-model'], 2: ['smoke-model'], 3: ['smoke-model']}\n" + "MODEL_DESCS = {'smoke-model': 'smoke'}\n" + "TIER_TITLES = {1: 'Smoke', 2: 'Smoke', 3: 'Smoke'}\n" + "MEDIA_MODELS = {}\n", + encoding="utf-8", + ) + paths["tg_secret"].write_bytes(bytes.fromhex(_fake_secret("tg-sid"))) + + _create_sqlite(paths["newapi_db"], ( + "CREATE TABLE tokens (id INTEGER PRIMARY KEY, name TEXT, status INTEGER)", + )) + if target == "gateway": + # gate_boot_selfcheck() counts rows over these columns. + _create_sqlite(paths["bot_db"], ( + "CREATE TABLE users (tg_id INTEGER PRIMARY KEY, api_blocked INTEGER, " + "api_block_reason TEXT, banned INTEGER)", + )) + + values = { + "GROK_BOT_CFG": paths["config"].as_posix(), + "IISHKO_BOT_DB": paths["bot_db"].as_posix(), + "IISHKO_GW_DB": paths["newapi_db"].as_posix(), + "IISHKO_SKIN_DB": paths["skin_db"].as_posix(), + "IISHKO_ECON_STATE": paths["econ_state"].as_posix(), + "GROK_UPTIME_DB": paths["uptime_db"].as_posix(), + "GROK_SUPPORT_DB": paths["support_db"].as_posix(), + "IISHKO_BOT_SOURCE": paths["bot_source"].as_posix(), + "TG_SID_SECRET_FILE": paths["tg_secret"].as_posix(), + "GROK_ICONS": paths["icons"].as_posix(), + "AFKEYS": paths["afkeys"].as_posix(), + "KIE_POOL": paths["kie_pool"].as_posix(), + "KIE_DEAD": paths["kie_dead"].as_posix(), + "PIKEYS": paths["pikeys"].as_posix(), + "GW_NEWAPI_DB": paths["newapi_db"].as_posix(), + "IISHKO_UPSTREAM": "http://127.0.0.1:%d" % ports["upstream"], + "IISHKO_WEBAPP_HOST": "127.0.0.1", + "IISHKO_WEBAPP_PORT": str(ports["webapp"]), + "IISHKO_GATEWAY_HOST": "127.0.0.1", + "IISHKO_GATEWAY_PORT": str(ports["gateway"]), + "GROK_BOT_ALLOW_LOCAL": "1", + "IISHKO_NOTIFICATIONS_ENABLED": "0", + "IISHKO_SUPPORT_DELIVERY_ENABLED": "0", + "IISHKO_ENTRY_DELIVERY_ENABLED": "0", + } + paths["env"].write_text( + "".join("%s=%s\n" % item for item in values.items()), encoding="utf-8") + return {"target": target, "tmp": tmp_path, "bootstrap": bootstrap, + "paths": paths, "ports": ports} + + +def _child_env(runtime: dict, fake_bot: bool) -> dict[str, str]: + env = { + key: value for key, value in os.environ.items() + if not key.upper().startswith(APP_ENV_PREFIXES) and key.upper() not in STRIPPED_ENV + } + env.update({ + "TMP": str(runtime["tmp"]), + "TEMP": str(runtime["tmp"]), + "PYTHONPATH": str(runtime["bootstrap"]), + "PYTHONDONTWRITEBYTECODE": "1", + "PYTHONIOENCODING": "utf-8", + "SMOKE_NETGUARD": "1", + "SMOKE_FAKE_BOT": "1" if fake_bot else "0", + "SMOKE_RESULT_FILE": str(runtime["paths"]["result"]), + }) + return env + + +def _spawn(runtime: dict, fake_bot: bool = False) -> subprocess.Popen: + paths = runtime["paths"] + with open(paths["stdout"], "wb") as out, open(paths["stderr"], "wb") as err: + process = subprocess.Popen( + [sys.executable, str(LAUNCHER), runtime["target"], + "--env-file", str(paths["env"])], + cwd=str(ROOT), env=_child_env(runtime, fake_bot), + stdin=subprocess.DEVNULL, stdout=out, stderr=err, + ) + return process + + +def _tail(path: Path) -> str: + try: + return path.read_text(encoding="utf-8", errors="replace")[-4000:] + except OSError: + return "" + + +def _failure(summary: str, process: subprocess.Popen, runtime: dict) -> str: + paths = runtime["paths"] + return "%s\nreturncode=%r\nstdout:\n%s\nstderr:\n%s" % ( + summary, process.returncode, _tail(paths["stdout"]), _tail(paths["stderr"])) + + +def _terminate(process: subprocess.Popen) -> None: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=20) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=20) + + +def _wait_http(process: subprocess.Popen, url: str, runtime: dict) -> tuple[int, str]: + parts = urllib.parse.urlsplit(url) + if parts.scheme != "http" or parts.hostname not in ("127.0.0.1", "::1"): + raise AssertionError("smoke requests must stay on loopback: " + url) + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + deadline = time.monotonic() + STARTUP_TIMEOUT + while time.monotonic() < deadline: + if process.poll() is not None: + raise AssertionError(_failure("process exited before serving " + url, process, runtime)) + try: + with opener.open(url, timeout=HTTP_TIMEOUT) as response: + return response.status, response.read().decode("utf-8", "replace") + except (urllib.error.URLError, OSError): + time.sleep(HTTP_POLL_INTERVAL) + raise AssertionError(_failure("no HTTP response from " + url, process, runtime)) + + +def _hardcoded_paths_seen() -> set[str]: + return {str(path) for path in HARDCODED_STARTUP_PATHS if path.exists()} + + +def _assert_no_new_hardcoded_paths(before: set[str], runtime: dict) -> None: + created = _hardcoded_paths_seen() - before + assert not created, "startup wrote hardcoded operator paths: %s" % sorted(created) + + +def test_bot_reaches_polling_through_launcher(tmp_path): + runtime = _runtime(tmp_path, "bot") + before = _hardcoded_paths_seen() + process = _spawn(runtime, fake_bot=True) + try: + returncode = process.wait(timeout=STARTUP_TIMEOUT) + finally: + _terminate(process) + assert returncode == 0, _failure("bot child failed", process, runtime) + + result = json.loads((runtime["paths"]["result"]).read_text(encoding="utf-8")) + assert result["polling"] == 1, result + assert result["routers"] >= 1, result + assert result["workers_at_polling"] >= 1, result + assert result["tasks_pending"] == 0, result + assert result.get("tables", 0) >= 5, result + + methods = result["methods"] + assert "GetMe" in methods, methods + assert "GetUpdates" not in methods, methods + assert set(methods) <= {"GetMe", "DeleteWebhook", "SetMyCommands", "GetChatMember"}, methods + # The database exists only at the path handed over by --env-file. + assert runtime["paths"]["bot_db"].is_file() + _assert_no_new_hardcoded_paths(before, runtime) + + +def test_miniapp_serves_healthz_through_launcher(tmp_path): + runtime = _runtime(tmp_path, "miniapp") + before = _hardcoded_paths_seen() + process = _spawn(runtime) + try: + url = "http://127.0.0.1:%d/healthz" % runtime["ports"]["webapp"] + status, body = _wait_http(process, url, runtime) + assert status == 200 and "ok" in body, (status, body) + assert process.poll() is None, _failure("webapp exited after serving", process, runtime) + finally: + _terminate(process) + _assert_no_new_hardcoded_paths(before, runtime) + + +def test_gateway_serves_robots_through_launcher(tmp_path): + runtime = _runtime(tmp_path, "gateway") + before = _hardcoded_paths_seen() + process = _spawn(runtime) + try: + url = "http://127.0.0.1:%d/robots.txt" % runtime["ports"]["gateway"] + status, body = _wait_http(process, url, runtime) + assert status == 200, (status, body) + assert "User-agent: *" in body and "Sitemap:" in body, body + assert process.poll() is None, _failure("gateway exited after serving", process, runtime) + finally: + _terminate(process) + _assert_no_new_hardcoded_paths(before, runtime) \ No newline at end of file