diff --git a/.dockerignore b/.dockerignore index bc16e556..e3e1b9a6 100644 --- a/.dockerignore +++ b/.dockerignore @@ -16,5 +16,8 @@ backups .venv __pycache__ node_modules +**/node_modules +frontend/dist +frontend/.vite evidence .DS_Store diff --git a/.env.example b/.env.example index d99d26a2..dd022e2c 100644 --- a/.env.example +++ b/.env.example @@ -1,7 +1,8 @@ # Copy to .env for your LOCAL synthetic test environment; never commit .env. # These are logical interface suggestions; map actual framework names in REPORT.md. APP_HOST=0.0.0.0 -APP_PORT=8080 +APP_INTERNAL_PORT=8080 +PUBLIC_PORT=8080 APP_ENV=lab SESSION_TTL_SECONDS=3600 # Choose credentials locally. File paths contain no secret values. @@ -11,10 +12,13 @@ SESSION_STORE=postgres CACHE_URL_FILE=/run/secrets/cache_url API_REPLICAS=2 IDEMPOTENCY_TTL_SECONDS=86400 -S3_ENDPOINT=http://s3:9000 +S3_ENDPOINT=http://minio:9000 S3_REGION=us-east-1 S3_BUCKET=messenger-attachments S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key +S3_OPERATION_TIMEOUT=5s MAX_UPLOAD_BYTES=10485760 MAX_IMAGE_PIXELS=40000000 +# Keep the Go soft heap limit below the Compose hard limit (256 MiB by default). +API_GO_MEMORY_LIMIT=220MiB diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..987bb778 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,35 @@ +FROM golang:1.27.1-alpine@sha256:8a5910f31396cd4d89662f56c68b3ae31d374308270a1c3bd96672ee5ed43414 AS builder + +WORKDIR /build + +COPY go.mod go.sum ./ +RUN go mod download + +COPY cmd/ ./cmd/ +COPY internal/ ./internal/ + + +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/server ./cmd/server/main.go +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/reconciler ./cmd/reconciler/main.go + +FROM alpine:3.24@sha256:294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6 + +RUN addgroup -g 1000 appgroup && \ + adduser -u 1000 -G appgroup -s /bin/sh -D appuser + +WORKDIR /app + +COPY --from=builder /build/server /app/server +COPY --from=builder /build/reconciler /app/reconciler + +RUN chown -R appuser:appgroup /app + +USER appuser:appgroup + +EXPOSE 8080 + +HEALTHCHECK --interval=5s --timeout=3s --start-period=5s --retries=10 \ + CMD wget -qO- http://127.0.0.1:8080/health/ready || exit 1 + + +ENTRYPOINT ["/app/server"] diff --git a/Makefile b/Makefile index 5d86d171..c2149e76 100644 --- a/Makefile +++ b/Makefile @@ -2,13 +2,17 @@ PYTHON ?= python3 BASE_URL ?= http://localhost:8080 CA_FILE ?= ACTION_SCRIPT ?= +RECONCILE_GRACE ?= 15m TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence test-failover +.PHONY: help init-secrets check validate test load test-attachment-boundaries test-attachment-memory test-storage-outage test-minio-policy test-persistence test-failover test-reconcile test-reconcile-scale reconcile-dry-run reconcile-apply help: @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" +init-secrets: + ./scripts/init-secrets.sh + check: $(PYTHON) scripts/check_contract.py @@ -21,6 +25,18 @@ test: load: $(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) +test-attachment-memory: + BASE_URL="$(BASE_URL)" $(PYTHON) tests/attachment_memory.py + +test-attachment-boundaries: + BASE_URL="$(BASE_URL)" $(PYTHON) tests/attachment_boundaries.py + +test-storage-outage: + BASE_URL="$(BASE_URL)" $(PYTHON) tests/storage_outage.py + +test-minio-policy: + ./tests/minio_policy.sh + test-persistence: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) @@ -28,3 +44,15 @@ test-persistence: test-failover: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-reconcile: + $(PYTHON) tests/reconcile_integration.py + +test-reconcile-scale: + $(PYTHON) tests/reconcile_scale.py + +reconcile-dry-run: + docker compose run --rm --entrypoint /app/reconciler api --grace-period "$(RECONCILE_GRACE)" + +reconcile-apply: + docker compose run --rm --entrypoint /app/reconciler api --grace-period "$(RECONCILE_GRACE)" --apply diff --git a/REPORT.md b/REPORT.md index 9ad2b84f..a3827848 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,123 @@ # Отчёт — лабораторная 4 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Чурилин, БВТ2301 +- Целевая оценка: **5**, выбран **трек 2 — согласованность PostgreSQL и S3**. +- Commit/PR: TODO после публикации. +- Использованные источники и библиотеки: Go standard library, `pgx/v5`, `minio-go/v7`, официальный исходный код MinIO и `mc`, Redis Go client. OpenAI Codex использовался для анализа контракта, проектирования, реализации и тестов; все утверждения ниже проверены перечисленными воспроизводимыми командами. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Prerequisites: Docker с Compose v2, GNU Make, Python 3.9+, OpenSSL. Локально проверено в WSL2. MinIO и `mc` собираются из официальных Go-модулей в [infrastructure/minio/Dockerfile](infrastructure/minio/Dockerfile): сервер `RELEASE.2025-10-15T17-29-55Z`, клиент `RELEASE.2025-08-13T08-35-41Z`. Базовые образы закреплены digest. + +```sh +cp .env.example .env +make init-secrets +docker compose --env-file .env config --quiet +docker compose --env-file .env up -d --build +docker compose --env-file .env ps +BASE_URL=http://127.0.0.1:8080 make test +python3 -m venv .venv +.venv/bin/pip install -r requirements-dev.txt +make validate PYTHON=.venv/bin/python +``` + +`make init-secrets` создаёт недостающие файлы с mode `600` и никогда не перезаписывает существующие значения. Секреты находятся в игнорируемом каталоге `secrets/` и не передаются через переменные окружения контейнера. Если `8080` занят, задаётся `PUBLIC_PORT`, например `PUBLIC_PORT=18080`; внутренний `APP_INTERNAL_PORT=8080` от него не зависит. + +Безопасная остановка сохраняет named volumes: + +```sh +docker compose --env-file .env down +``` + +Намеренное удаление всех учебных данных выполняется только явно: + +```sh +docker compose --env-file .env down -v +``` ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab3, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Путь запроса: клиент → HAProxy → две API-реплики → PostgreSQL (источник истины метаданных/сессий) + приватный MinIO bucket (байты); Redis остаётся восстанавливаемым кешем чатов. У каждой API-реплики нет постоянного каталога оригиналов. Во время синхронного upload тело ограниченно копируется в файл OS temp, файл имеет случайное имя, удаляется в `defer` и нужен только для двукратной проверки/потокового S3 PUT. + +Из lab3 сохранены два API-инстанса, HAProxy, PostgreSQL, Redis fallback, bearer-сессии, idempotency сообщений, курсоры, graceful shutdown и persistence/failover hooks. В lab4 добавлены: + +- `Attachment` со статусами `pending/ready/failed`, SHA-256, истинным MIME, размером и размерами изображения; +- таблицы `attachments` и `message_attachments`, same-chat foreign keys и deferred constraint «текст или вложение»; +- `attachment_ids` во всех слоях Message без нарушения старого JSON (`[]` по умолчанию); +- binary `POST`, metadata `GET` и авторизованный streaming `GET /content` без redirect; +- общий MinIO volume, idempotent bootstrap приватного bucket и отдельный API user с минимальной policy; +- readiness, зависящий от PostgreSQL и MinIO; +- one-shot reconciler с dry-run по умолчанию, `--apply`, grace period и условными DB updates. + +Upload возвращает `201 ready` только после последовательности: полное ограниченное чтение → проверка MIME/PNG/JPEG/пикселей и SHA-256 → insert `pending` → успешный S3 PUT → update `ready`. Ошибка PUT удаляет возможный объект и фиксирует `failed`. Ошибка ответа на финальный DB update считается неоднозначной: update мог уже закоммититься, поэтому объект не удаляется. API делает best-effort readback и либо восстанавливает успешный `201`, либо возвращает `503`, сохранив metadata+object для reconciler. Это исключает состояние `ready` без оригинала при потере ответа PostgreSQL. + +Лимиты применяются до неограниченной работы: body читается через `LimitReader(10 MiB + 1)`, `DecodeConfig` проверяет максимум 40 млн пикселей до полного `Decode`, а полный `Decode` проверяет поток/CRC/IDAT/SOS до S3 PUT. Filename не участвует в object key и проверяется на valid UTF-8/blank/path/C0+C1 control characters. Object key формируется сервером как `attachments/{chat_id}/{attachment_id}/original`. На реплику допускаются не более четырёх upload pipeline и одного полного decode одновременно; `GOMEMLIMIT=220MiB` ниже container limit 256 MiB. S3 operation timeout — 5 s, HTTP read/write timeout — 15 s, HAProxy server/client timeout — 30 s, DB query timeout задаётся конфигурацией. Компенсация сначала получает отдельный 1 s budget для DB transition и лишь затем отдельный 1 s budget для best-effort S3 delete. + +Публичный `/health/ready` проверяет PostgreSQL и MinIO и возвращает контрактный JSON `503`, если зависимость недоступна. HAProxy использует отдельный внутренний `/health/lb`, отражающий жизнеспособность/drain процесса, поэтому при общем отказе MinIO запросы не заменяются generic HTML-ошибкой балансировщика, а доходят до API и получают согласованный `503 unavailable`. + +Соответствие ключевых переменных: `PUBLIC_PORT` — host port HAProxy; `APP_INTERNAL_PORT` — порт API в сети Compose; `DATABASE_URL_FILE`, `CURSOR_SIGNING_KEY_FILE`, `S3_ACCESS_KEY_ID_FILE`, `S3_SECRET_ACCESS_KEY_FILE` — Docker secrets; `S3_ENDPOINT=http://minio:9000`; `S3_BUCKET=messenger-attachments`; `S3_OPERATION_TIMEOUT=5s`. + +## Механизм согласованности и трек 5 + +Гипотеза: периодический inventory PostgreSQL и MinIO с консервативным grace period способен повторяемо исправлять безопасные orphan/missing состояния, не удаляя свежие объекты и вложения, уже связанные с сообщениями. + +Reconciler сравнивает все `attachments/` objects с метаданными: + +- старый object без metadata удаляется только в apply; +- старый `pending` очищает object и условно становится `failed`; +- старый `ready` без object условно становится `failed`, только если не используется сообщением; +- object у старого `failed` удаляется, только если запись не используется; +- свежие записи/objects игнорируются, а referenced missing помечается `manual_repair_required` без мутации; +- SQL update берёт row lock, затем отдельным statement на свежем READ COMMITTED snapshot повторно проверяет status, cutoff и отсутствие ссылки; concurrent message/reconciler race либо создаёт ссылку, либо переводит attachment в failed, но не оба состояния одновременно; +- object stale-pending удаляется только после успешного условного DB transition, поэтому проигранная гонка приводит к `skipped_concurrent_change`, а не к потере готового оригинала. + +Команды оператора: + +```sh +make reconcile-dry-run RECONCILE_GRACE=15m +# Просмотреть JSON; затем при согласии: +make reconcile-apply RECONCILE_GRACE=15m +``` ## Доказательства критериев -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | +| Критерий README | Команда/сценарий | Наблюдаемый результат | Доказательство | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Публичный smoke | `BASE_URL=http://127.0.0.1:18080 make test` | PASS: upload/message/download/checksum/outsider 404 | [evidence/lab4-results.md](evidence/lab4-results.md) | +| Границы/полная декодировка | `make test-attachment-boundaries` | Ровно 10 MiB и 40 млн пикселей приняты; truncated/corrupt-after-64-KiB отклонены 415; whitespace/C1 filename — 400 | [tests/attachment_boundaries.py](tests/attachment_boundaries.py) | +| Failover API | `make test-failover` с указанными в evidence env | 142 успешных записи, 0 ошибок, recovery 2.771 s; файл читается другой репликой | [evidence/lab4-results.md](evidence/lab4-results.md) | +| Restart и volumes | `make test-persistence` | Сессия, метаданные и bytes пережили restart PostgreSQL/Redis/MinIO/API/frontend/HAProxy | [scripts/restart.sh](scripts/restart.sh) | +| Файловые негативные тесты | `go test ./...` | oversized bytes/pixels, invalid IDAT, truncated PNG/JPEG, corruption after 64 KiB, MIME substitution, unsafe filename, interrupted body, foreign attachment/chat | [internal/application/attachments_test.go](internal/application/attachments_test.go) | +| Неоднозначный DB COMMIT | `go test ./internal/application -count=1` | Потеря ответа после commit восстанавливается readback; при одновременном read outage ready metadata сохраняет оригинал | [internal/application/attachments_test.go](internal/application/attachments_test.go) | +| Реальный отказ MinIO | `make test-storage-outage` | readiness 503 за 2.004 s, upload 503 за 6.016 s; после recovery прежний original неизменен | [tests/storage_outage.py](tests/storage_outage.py) | +| RAM при concurrency ≥10 | `make test-attachment-memory` | 12 × 6,293,028 B, 12/12 success; пики 31,216,107 и 26,214,400 B | [tests/attachment_memory.py](tests/attachment_memory.py) | +| Private bucket / API policy | `make test-minio-policy` | Root secrets/env отсутствуют в API; limited user не создаёт bucket; anonymous GET запрещён | [tests/minio_policy.sh](tests/minio_policy.sh) | +| Reconciler dry-run/apply/repeat | `make test-reconcile` | 4 issues; 2 objects deleted; 2 metadata failed; repeat 0 mutations; referenced защищён | [tests/reconcile_integration.py](tests/reconcile_integration.py) | +| Стоимость обхода | `make test-reconcile-scale` | 100 objects: 9 ms; 1,000 objects: 38 ms core duration | [tests/reconcile_scale.py](tests/reconcile_scale.py) | +| Static/race gates | `go test -race ./...`; `go vet ./...`; `make check`; `git diff --check` | PASS | [evidence/lab4-results.md](evidence/lab4-results.md) | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Memory experiment: один прогон, 12 concurrent uploads, каждый PNG 2048×1024 и 6,293,028 bytes; суммарно 75,516,336 bytes. HAProxy распределил запросы по двум репликам. Docker stats опрашивался во время прогона. 12/12 завершились за 0.599 s, наблюдаемые пики — 29.8 и 25.0 MiB, существенно ниже container limit 256 MiB. После измерения отдельный chat prefix и синтетические DB rows удалены. -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | +Reconciler integration: в отдельном namespace созданы old orphan object, old pending metadata+object, unreferenced ready metadata без object и referenced ready metadata без object. Dry-run нашёл четыре состояния и не мутировал данные. Apply удалил два objects и перевёл две записи в `failed`. Повторный apply сделал ноль мутаций; referenced missing остался ручной задачей. Синтетические данные удалены в `finally`. + +Traversal experiment использовал один и тот же стенд после прогрева, один прогон на размер, отдельный prefix и однобайтовые objects. 100 injected orphans: 109 objects total, 9 ms core и 1,978 ms с запуском one-shot container. 1,000: 1,009 total, 38 ms core и 2,019 ms end-to-end. Это подтверждает повторяемость методики и ожидаемую близкую к линейной стоимость лишь на малом локальном масштабе. + +| Воздействие | Ожидание | Наблюдение | Потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| Stop одной API-реплики | Вторая продолжает запись/чтение общего файла | recovery 2.771 s, 142 writes, 0 errors | Нет | +| Restart общего стенда | Named volumes сохраняют DB и S3 | persistence PASS | Нет | +| S3 PUT error | 503, metadata failed, object отсутствует | Unit injection PASS | Нет ready-данных | +| MinIO недоступен | readiness/upload дают JSON 503 до API/LB timeout | 2.004 s / 6.016 s, реальный stop/recovery PASS | Старый original неизменен | +| DB finalize response потерян после COMMIT | Readback возвращает ready; при DB outage object не удаляется | Два unit fault-теста PASS | Ready не остаётся без original | +| Orphan/missing/stale состояния | Dry-run, безопасный apply, repeat | Integration PASS | Referenced missing не изменён | ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- Inventory materializes metadata и object list в RAM; для большого bucket нужны pagination/checkpoints и пакетная выдача issues. +- Один reconciler предполагается запускать оператором; перед scheduler нужны PostgreSQL advisory lock/lease и метрики длительности/ошибок. +- `referenced_missing_object` намеренно не чинится автоматически: требуется восстановление bytes из backup или операторское решение. +- Один-node MinIO и локальные измерения не доказывают HA самого object storage; это учебный стенд. +- Experiment содержит по одному измерению на размер без статистических повторов; для production нужны warm-up, серии, p50/p95/p99, CPU/IO и существенно больший inventory. +- Оригинал проверяется SHA-256 при upload и клиентом в smoke; каждый download не пересчитывает hash на лету. diff --git a/cmd/reconciler/main.go b/cmd/reconciler/main.go new file mode 100644 index 00000000..97c3097b --- /dev/null +++ b/cmd/reconciler/main.go @@ -0,0 +1,75 @@ +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "log" + "os" + "time" + + "mtusi2026lab4/internal/adapter/objectstore" + "mtusi2026lab4/internal/adapter/postgres" + "mtusi2026lab4/internal/config" + "mtusi2026lab4/internal/database" + "mtusi2026lab4/internal/reconcile" +) + +func main() { + apply := flag.Bool("apply", false, "apply safe repairs; default is dry-run") + gracePeriod := flag.Duration("grace-period", 15*time.Minute, + "ignore metadata and objects newer than this duration") + timeout := flag.Duration("timeout", 2*time.Minute, "maximum reconciliation runtime") + flag.Parse() + + if *gracePeriod <= 0 || *timeout <= 0 { + log.Fatal("[FATAL] grace-period and timeout must be positive") + } + cfg, err := config.Load() + if err != nil { + log.Fatalf("[FATAL] Invalid configuration: %v", err) + } + + ctx, cancel := context.WithTimeout(context.Background(), *timeout) + defer cancel() + databasePool, err := database.Open(ctx, cfg) + if err != nil { + log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err) + } + defer databasePool.Close() + metadataStore := postgres.NewPostgreSQLStore(databasePool, cfg.DatabaseQueryTimeout) + + objectStore, err := objectstore.NewMinIOStore( + cfg.S3Endpoint, + cfg.S3Region, + cfg.S3Bucket, + cfg.S3AccessKeyID, + cfg.S3SecretAccessKey, + cfg.S3OperationTimeout, + ) + if err != nil { + log.Fatalf("[FATAL] Invalid object storage configuration: %v", err) + } + if err = objectStore.Ping(ctx); err != nil { + log.Fatalf("[FATAL] Object storage unavailable: %v", err) + } + + reconciler, err := reconcile.New(metadataStore, objectStore) + if err != nil { + log.Fatalf("[FATAL] Reconciler initialization failed: %v", err) + } + result, err := reconciler.Run(ctx, *gracePeriod, *apply) + if err != nil { + log.Fatalf("[FATAL] Reconciliation failed: %v", err) + } + + encoder := json.NewEncoder(os.Stdout) + encoder.SetIndent("", " ") + if err = encoder.Encode(result); err != nil { + log.Fatalf("[FATAL] Encode reconciliation result: %v", err) + } + if !*apply && len(result.Issues) > 0 { + fmt.Fprintln(os.Stderr, "dry-run found reconciliation issues; rerun with --apply after review") + } +} diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 00000000..ab0603fd --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,259 @@ +package main + +import ( + "context" + "errors" + "log" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + cacheadapter "mtusi2026lab4/internal/adapter/cache" + "mtusi2026lab4/internal/adapter/health" + "mtusi2026lab4/internal/adapter/objectstore" + "mtusi2026lab4/internal/adapter/postgres" + redisadapter "mtusi2026lab4/internal/adapter/redis" + "mtusi2026lab4/internal/application" + "mtusi2026lab4/internal/config" + "mtusi2026lab4/internal/database" + "mtusi2026lab4/internal/transport/http/handlers" + "mtusi2026lab4/internal/transport/http/middleware" +) + +func main() { + cfg, err := config.Load() + if err != nil { + log.Fatalf("[FATAL] Invalid configuration: %v", err) + } + + startupContext, startupCancel := context.WithTimeout( + context.Background(), + cfg.DatabaseConnectTimeout, + ) + + databasePool, err := database.Open(startupContext, cfg) + startupCancel() + + if err != nil { + log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err) + } + defer databasePool.Close() + + postgresStore := postgres.NewPostgreSQLStore( + databasePool, + cfg.DatabaseQueryTimeout, + ) + minioStore, err := objectstore.NewMinIOStore( + cfg.S3Endpoint, + cfg.S3Region, + cfg.S3Bucket, + cfg.S3AccessKeyID, + cfg.S3SecretAccessKey, + cfg.S3OperationTimeout, + ) + if err != nil { + log.Fatalf("[FATAL] Invalid object storage configuration: %v", err) + } + storageContext, storageCancel := context.WithTimeout( + context.Background(), + cfg.S3OperationTimeout, + ) + if err = minioStore.Ping(storageContext); err != nil { + log.Printf("[WARN] Object storage unavailable at startup: %v", err) + } + storageCancel() + + var applicationStore application.Repository = postgresStore + + if cfg.RedisURL != "" { + redisChatCache, cacheError := redisadapter.NewRedisChatCache( + cfg.RedisURL, + cfg.RedisCacheTTL, + cfg.RedisOperationTimeout, + cfg.RedisPoolSize, + ) + if cacheError != nil { + log.Fatalf("[FATAL] Invalid Redis configuration: %v", cacheError) + } + defer func() { + if closeError := redisChatCache.Close(); closeError != nil { + log.Printf("[WARN] Redis client close failed: %v", closeError) + } + }() + + cacheContext, cacheCancel := context.WithTimeout( + context.Background(), + cfg.RedisOperationTimeout, + ) + if cacheError = redisChatCache.Ping(cacheContext); cacheError != nil { + log.Printf("[WARN] Redis unavailable at startup; PostgreSQL fallback is active: %v", cacheError) + } else { + log.Println("[INFO] Redis chat cache is available") + } + cacheCancel() + + applicationStore = cacheadapter.NewCachedRepository( + postgresStore, + redisChatCache, + log.Default(), + ) + } + + cursorCodec, err := application.NewCursorCodec(cfg.CursorSigningKey) + if err != nil { + log.Fatalf("[FATAL] Invalid cursor configuration: %v", err) + } + + service, err := application.NewService( + applicationStore, + cursorCodec, + cfg.SessionTTL, + application.WithIdempotencyTTL(cfg.IdempotencyTTL), + application.WithObjectStore(minioStore), + ) + if err != nil { + log.Fatalf("[FATAL] Application initialization failed: %v", err) + } + + handler := handlers.NewHandler( + service, + handlers.WithReadiness( + health.NewMultiChecker(databasePool, minioStore), + cfg.ReadinessTimeout, + ), + handlers.WithSessionCookieSecure(cfg.SessionCookieSecure), + ) + + mux := http.NewServeMux() + + mux.HandleFunc("GET /health/live", handler.HealthLive) + mux.HandleFunc("GET /health/lb", handler.HealthLive) + mux.HandleFunc("GET /health/ready", handler.HealthReady) + + mux.HandleFunc( + "POST /api/v1/auth/sessions", + handler.CreateSession, + ) + + mux.HandleFunc("POST /api/v1/users", handler.CreateUser) + + requireAuth := func(next http.HandlerFunc) http.HandlerFunc { + return middleware.RequireAuth(service, next) + } + + mux.HandleFunc( + "GET /api/v1/users/me", + requireAuth(handler.GetMe), + ) + + mux.HandleFunc( + "DELETE /api/v1/auth/sessions/current", + requireAuth(handler.DeleteCurrentSession), + ) + + mux.HandleFunc( + "POST /api/v1/chats", + requireAuth(handler.CreateChat), + ) + mux.HandleFunc( + "GET /api/v1/chats", + requireAuth(handler.ListChats), + ) + mux.HandleFunc( + "GET /api/v1/chats/{chat_id}", + requireAuth(handler.GetChat), + ) + mux.HandleFunc( + "POST /api/v1/chats/{chat_id}/messages", + requireAuth(handler.CreateMessage), + ) + mux.HandleFunc( + "GET /api/v1/chats/{chat_id}/messages", + requireAuth(handler.GetMessages), + ) + mux.HandleFunc( + "POST /api/v1/chats/{chat_id}/attachments", + requireAuth(handler.UploadAttachment), + ) + mux.HandleFunc( + "GET /api/v1/attachments/{attachment_id}", + requireAuth(handler.GetAttachment), + ) + mux.HandleFunc( + "GET /api/v1/attachments/{attachment_id}/content", + requireAuth(handler.DownloadAttachment), + ) + + var rootHandler http.Handler = mux + rootHandler = middleware.Recovery(rootHandler) + rootHandler = middleware.Logger(rootHandler) + availabilityGate := middleware.NewAvailabilityGate() + rootHandler = availabilityGate.Middleware(rootHandler) + rootHandler = middleware.RequestID(rootHandler) + rootHandler = middleware.InstanceID(cfg.InstanceID, rootHandler) + + server := &http.Server{ + Addr: cfg.HTTPAddress(), + Handler: rootHandler, + ReadTimeout: 15 * time.Second, + WriteTimeout: 15 * time.Second, + IdleTimeout: 60 * time.Second, + } + + serverErrors := make(chan error, 1) + + go func() { + log.Printf( + "[INFO] Server instance %s starting on %s", + cfg.InstanceID, + server.Addr, + ) + serverErrors <- server.ListenAndServe() + }() + + shutdownSignals := make(chan os.Signal, 1) + signal.Notify( + shutdownSignals, + os.Interrupt, + syscall.SIGTERM, + ) + defer signal.Stop(shutdownSignals) + + select { + case serverError := <-serverErrors: + if !errors.Is(serverError, http.ErrServerClosed) { + log.Fatalf("[FATAL] Server crashed: %v", serverError) + } + + case signalValue := <-shutdownSignals: + log.Printf( + "[INFO] Signal %v received. Starting graceful shutdown...", + signalValue, + ) + + availabilityGate.BeginDrain() + log.Printf( + "[INFO] Readiness disabled; draining new traffic for %s", + cfg.ShutdownDrainDelay, + ) + time.Sleep(cfg.ShutdownDrainDelay) + + shutdownContext, shutdownCancel := context.WithTimeout( + context.Background(), + cfg.ShutdownTimeout, + ) + defer shutdownCancel() + + if err := server.Shutdown(shutdownContext); err != nil { + log.Printf( + "[WARN] Graceful shutdown failed: %v. Forcing close.", + err, + ) + _ = server.Close() + } + + log.Println("[INFO] Server stopped gracefully.") + } +} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..164bd2c9 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,343 @@ +services: + load-balancer: + build: + context: . + dockerfile: infrastructure/haproxy/Dockerfile + image: mtusi2026lab4-load-balancer + ports: + - "127.0.0.1:${PUBLIC_PORT:-8080}:8080" + depends_on: + api: + condition: service_healthy + frontend: + condition: service_healthy + healthcheck: + test: + [ + "CMD-SHELL", + "wget -qO- http://127.0.0.1:8080/health/ready || exit 1", + ] + interval: 5s + timeout: 3s + retries: 10 + start_period: 3s + stop_grace_period: 10s + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.25" + memory: 128M + + frontend: + build: + context: . + dockerfile: infrastructure/nginx/Dockerfile + image: mtusi2026lab4-web + expose: + - "8080" + healthcheck: + test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/ >/dev/null || exit 1"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 3s + stop_grace_period: 10s + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.10" + memory: 64M + + postgres: + image: postgres:16.15-alpine3.24@sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea + environment: + POSTGRES_USER: ${POSTGRES_USER:-messenger} + POSTGRES_DB: ${POSTGRES_DB:-messenger} + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + volumes: + - postgres_data:/var/lib/postgresql/data + healthcheck: + test: + [ + "CMD-SHELL", + "pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_DB:-messenger}", + ] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + restart: unless-stopped + deploy: + resources: + limits: + cpus: "${POSTGRES_CPU_LIMIT:-1.00}" + memory: ${POSTGRES_MEMORY_LIMIT:-512M} + + redis: + image: redis:8.10.2-alpine3.23@sha256:3811787313eba226a2ef38658c6ccb91cd5e110edc89c37767de373120a0e5a0 + command: + [ + "redis-server", + "--save", + "", + "--appendonly", + "no", + "--maxmemory", + "64mb", + "--maxmemory-policy", + "allkeys-lru", + ] + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 3s + stop_grace_period: 10s + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.25" + memory: 128M + + migrate: + image: migrate/migrate:v4.20.1@sha256:76cc2074cb6642631f34a898ced71e6aeaa6b1a4d78c4daa743275a22e0c5be7 + entrypoint: ["/bin/sh", "-ec"] + command: + - > + exec migrate + -path=/migrations + -database="$$(cat /run/secrets/database_url)" + up + secrets: + - database_url + volumes: + - ./migrations:/migrations:ro + depends_on: + postgres: + condition: service_healthy + restart: "no" + deploy: + resources: + limits: + cpus: "0.25" + memory: 64M + + minio: + build: + context: . + dockerfile: infrastructure/minio/Dockerfile + target: server + args: + MINIO_VERSION: RELEASE.2025-10-15T17-29-55Z + image: mtusi2026lab4-minio:RELEASE.2025-10-15T17-29-55Z + command: ["server", "/data", "--address", ":9000"] + environment: + MINIO_ROOT_USER_FILE: /run/secrets/minio_root_user + MINIO_ROOT_PASSWORD_FILE: /run/secrets/minio_root_password + MINIO_BROWSER: "off" + secrets: + - minio_root_user + - minio_root_password + volumes: + - minio_data:/data + expose: + - "9000" + healthcheck: + test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:9000/minio/health/live >/dev/null || exit 1"] + interval: 5s + timeout: 3s + retries: 20 + start_period: 10s + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.75" + memory: 512M + + minio-bootstrap: + build: + context: . + dockerfile: infrastructure/minio/Dockerfile + target: client + args: + MC_VERSION: RELEASE.2025-08-13T08-35-41Z + image: mtusi2026lab4-mc:RELEASE.2025-08-13T08-35-41Z + entrypoint: ["/bin/sh", "-ec"] + command: + - | + root_user="$$(cat /run/secrets/minio_root_user)" + root_password="$$(cat /run/secrets/minio_root_password)" + api_user="$$(cat /run/secrets/s3_access_key_id)" + api_password="$$(cat /run/secrets/s3_secret_access_key)" + mc alias set local http://minio:9000 "$$root_user" "$$root_password" --api S3v4 + mc mb --ignore-existing "local/$${S3_BUCKET}" + mc anonymous set none "local/$${S3_BUCKET}" + sed "s/__BUCKET__/$${S3_BUCKET}/g" /config/api-policy.template.json > /tmp/api-policy.json + mc admin policy create local messenger-api /tmp/api-policy.json + if ! mc admin user info local "$$api_user" >/dev/null 2>&1; then + mc admin user add local "$$api_user" "$$api_password" + fi + mc admin policy attach local messenger-api --user "$$api_user" + environment: + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + secrets: + - minio_root_user + - minio_root_password + - s3_access_key_id + - s3_secret_access_key + volumes: + - ./infrastructure/minio/api-policy.template.json:/config/api-policy.template.json:ro + depends_on: + minio: + condition: service_healthy + restart: "no" + + api: + build: + context: . + dockerfile: Dockerfile + environment: + APP_HOST: ${APP_HOST:-0.0.0.0} + APP_PORT: ${APP_INTERNAL_PORT:-8080} + APP_ENV: ${APP_ENV:-lab} + + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + SESSION_STORE: ${SESSION_STORE:-postgres} + SESSION_COOKIE_SECURE: ${SESSION_COOKIE_SECURE:-false} + CURSOR_SIGNING_KEY_FILE: ${CURSOR_SIGNING_KEY_FILE:-/run/secrets/cursor_signing_key} + + CACHE_URL: ${CACHE_URL:-redis://redis:6379/0} + CACHE_TTL: ${CACHE_TTL:-5m} + CACHE_OPERATION_TIMEOUT: ${CACHE_OPERATION_TIMEOUT:-250ms} + CACHE_POOL_SIZE: ${CACHE_POOL_SIZE:-10} + + S3_ENDPOINT: ${S3_ENDPOINT:-http://minio:9000} + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ACCESS_KEY_ID_FILE: ${S3_ACCESS_KEY_ID_FILE:-/run/secrets/s3_access_key_id} + S3_SECRET_ACCESS_KEY_FILE: ${S3_SECRET_ACCESS_KEY_FILE:-/run/secrets/s3_secret_access_key} + S3_OPERATION_TIMEOUT: ${S3_OPERATION_TIMEOUT:-5s} + + DATABASE_URL_FILE: ${DATABASE_URL_FILE:-/run/secrets/database_url} + + DB_MAX_CONNS: ${DB_MAX_CONNS:-10} + DB_MIN_CONNS: ${DB_MIN_CONNS:-2} + DB_MAX_CONN_LIFETIME: ${DB_MAX_CONN_LIFETIME:-30m} + DB_MAX_CONN_IDLE_TIME: ${DB_MAX_CONN_IDLE_TIME:-5m} + DB_HEALTH_CHECK_PERIOD: ${DB_HEALTH_CHECK_PERIOD:-30s} + DB_CONNECT_TIMEOUT: ${DB_CONNECT_TIMEOUT:-5s} + DB_QUERY_TIMEOUT: ${DB_QUERY_TIMEOUT:-3s} + + READINESS_TIMEOUT: ${READINESS_TIMEOUT:-2s} + SHUTDOWN_DRAIN_DELAY: ${SHUTDOWN_DRAIN_DELAY:-2s} + SHUTDOWN_TIMEOUT: ${SHUTDOWN_TIMEOUT:-10s} + GOMEMLIMIT: ${API_GO_MEMORY_LIMIT:-220MiB} + secrets: + - database_url + - s3_access_key_id + - s3_secret_access_key + - cursor_signing_key + expose: + - "8080" + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + migrate: + condition: service_completed_successfully + minio-bootstrap: + condition: service_completed_successfully + deploy: + replicas: ${API_REPLICAS:-2} + resources: + limits: + cpus: "${API_CPU_LIMIT:-0.50}" + memory: ${API_MEMORY_LIMIT:-256M} + healthcheck: + test: + [ + "CMD-SHELL", + "wget -qO- http://127.0.0.1:$${APP_PORT:-8080}/health/ready || exit 1", + ] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + stop_grace_period: 15s + restart: unless-stopped + + redis-insight: + image: redis/redisinsight:3.8.0@sha256:b5e19ee240abef6edb435871b90ff8a210995422e8e018ab61c0339d318a1f84 + profiles: ["tools"] + ports: + - "127.0.0.1:${REDIS_INSIGHT_PORT:-5540}:5540" + volumes: + - redis_insight_data:/data + depends_on: + redis: + condition: service_healthy + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M + + postgres-restore: + image: postgres:16.15-alpine3.24@sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea + profiles: ["recovery"] + environment: + POSTGRES_USER: ${POSTGRES_USER:-messenger} + POSTGRES_DB: ${POSTGRES_RESTORE_DB:-messenger_restore_admin} + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + volumes: + - postgres_restore_data:/var/lib/postgresql/data + healthcheck: + test: + [ + "CMD-SHELL", + "pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_RESTORE_DB:-messenger_restore_admin}", + ] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + restart: "no" + deploy: + resources: + limits: + cpus: "1.00" + memory: 512M + +volumes: + postgres_data: + redis_insight_data: + minio_data: + postgres_restore_data: + +secrets: + postgres_password: + file: ./secrets/postgres_password.txt + database_url: + file: ./secrets/database_url.txt + cursor_signing_key: + file: ./secrets/cursor_signing_key.txt + minio_root_user: + file: ./secrets/minio_root_user.txt + minio_root_password: + file: ./secrets/minio_root_password.txt + s3_access_key_id: + file: ./secrets/s3_access_key_id.txt + s3_secret_access_key: + file: ./secrets/s3_secret_access_key.txt diff --git a/evidence/lab4-results.md b/evidence/lab4-results.md new file mode 100644 index 00000000..ce92d415 --- /dev/null +++ b/evidence/lab4-results.md @@ -0,0 +1,19 @@ +# Lab 4 verification summary + +Date: 2026-10-29. Environment: local Docker Compose on WSL2; two API replicas; PostgreSQL 16.15; Redis 8.10.2; MinIO release `RELEASE.2025-10-15T17-29-55Z` built from the official source module. + +| Check | Command | Observed result | +| --- | --- | --- | +| Public contract | `BASE_URL=http://127.0.0.1:18080 make test` | PASS: upload, attachment-only message, authorized byte download, checksum/content type and outsider 404 | +| Exact boundaries / decode | `BASE_URL=http://127.0.0.1:18080 make test-attachment-boundaries` | Exact 10 MiB and 40,000,000 pixels accepted; truncated/corrupted-after-64-KiB PNG rejected 415; blank/C1 filename rejected 400 | +| One-replica failover | `PUBLIC_PORT=18080 BASE_URL=http://127.0.0.1:18080 ACTION_SCRIPT=./scripts/stop-one.sh make test-failover` | 2 instances before failure; 142 successful writes; 0 failed attempts; first recovery 2.771 s; attachment unchanged | +| Full persistence restart | `PUBLIC_PORT=18080 BASE_URL=http://127.0.0.1:18080 ACTION_SCRIPT=./scripts/restart.sh make test-persistence` | PASS after restarting PostgreSQL, Redis, MinIO, both API replicas, frontend and HAProxy; existing session, metadata and bytes survived | +| Real MinIO outage | `BASE_URL=http://127.0.0.1:18080 make test-storage-outage` | Public readiness returned JSON 503 in 2.004 s, upload returned JSON 503 in 6.016 s; after recovery the 111,817-byte previous original was byte-identical | +| Private bucket / least privilege | `make test-minio-policy` | API containers had no MinIO root env/secrets; limited credentials could put/read/delete only in configured bucket; creating another bucket and anonymous GET failed | +| Concurrent upload memory | `BASE_URL=http://127.0.0.1:18080 make test-attachment-memory` | 12/12 successful 6,293,028-byte PNG uploads (75,516,336 bytes total) in 0.599 s; peak API memory 31,216,107 and 26,214,400 bytes | +| Reconciler behavior | `make test-reconcile` | Dry-run found 4 injected issues; apply deleted 2 objects and marked 2 attachments failed; repeat made 0 mutations; 1 referenced missing attachment remained protected/manual | +| Reconciler traversal | `make test-reconcile-scale` | 100 orphan objects: 109 objects scanned, 9 ms core / 1,978 ms including container startup. 1,000 orphans: 1,009 scanned, 38 ms core / 2,019 ms including startup | +| Ambiguous DB COMMIT fault | `go test ./internal/application -count=1` | Successful finalize with lost response is recovered by readback; if DB remains unavailable, ready metadata keeps its object and returns an honest error | +| Go quality gates | `go test ./...`; `go test -race ./...`; `go vet ./...`; `make check`; `git diff --check` | PASS | + +The measurements are single local runs, not production capacity claims. The reconciler currently materializes both inventories in memory, so its measured near-linear small-scale cost must be re-evaluated before using it with a large bucket. diff --git a/frontend/.dockerignore b/frontend/.dockerignore new file mode 100644 index 00000000..0e75fe55 --- /dev/null +++ b/frontend/.dockerignore @@ -0,0 +1,3 @@ +node_modules +dist +coverage diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 00000000..74b8e760 --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,17 @@ + + + + + + + + MTUCI Messenger + + +
+ + + diff --git a/frontend/package-lock.json b/frontend/package-lock.json new file mode 100644 index 00000000..556c03bd --- /dev/null +++ b/frontend/package-lock.json @@ -0,0 +1,1688 @@ +{ + "name": "mtusi-messenger-web", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "mtusi-messenger-web", + "version": "0.1.0", + "dependencies": { + "@tanstack/react-query": "^5.104.5", + "lucide-react": "^1.61.0", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "react-router-dom": "^7.18.4" + }, + "devDependencies": { + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "@vitejs/plugin-react": "^6.1.2", + "typescript": "^7.0.2", + "vite": "^8.3.5", + "vitest": "^5.0.5" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz", + "integrity": "sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.15.tgz", + "integrity": "sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.15.tgz", + "integrity": "sha512-xD7DdZCrbThKuxNg7ooQmvp07ys4J/pnSEMTG3/OdOWl6daC67m/Q4fL78sRHMxTH/N4fGUbYhcPM0MF5WFHkg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.15.tgz", + "integrity": "sha512-m2WuQ6r0B4OTYxyPpNLtXaMRbRDUbG8YQV2Q3KTdSSK8Th6KHCnC8jVCJt8bvYeSB5WivkkNbc85mKadaSdOxA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.15.tgz", + "integrity": "sha512-5RtnsHM36nodM9WbMy+zip0LGS/G+y5wro5RHrpOlr4ac24+1zSi9kiV2MP1myZeZ/ifEHfulQcWjnAXzc2C2A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.15.tgz", + "integrity": "sha512-g3l09pyFqhu+135JKkbkwiKGQmwU5hUMUPJ4VdBADvuqR8d33L6H578rh8m7rtxbdp+VmX/+nzI7nvhSZlzpUQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.15.tgz", + "integrity": "sha512-nIe3VugI97nGQtspPxDqA4sXMUpeiocKIP/CqpY/u/vgbT+alX+cVxu1C/oVBPKg4feNTmYovE91v4DgXvXNwQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.15.tgz", + "integrity": "sha512-iTBjXx+B5QSvgI89lJfmqh4wTh8NabR1YZIIN3hNx4zSG0EVfVqkOvLulNpG4251pbd6/IAmZ/LefVk1Y4rPhw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.15.tgz", + "integrity": "sha512-uN26XOnVR7rqQupG3V9oAG2EGGatWjcJHOeDOHUFCh4TBWmP2tHTFoVN13aYbwfm0aHqJAEmcwhAu6sooIjfqQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.15.tgz", + "integrity": "sha512-9nWkcdd+H+XhaA3fQIwpHnKIrfx/PQ6rO0pivr78Og07tXlUlctBBJoEYLPfhTmCR/QxEVdn6uPjHV5SymPhdw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.15.tgz", + "integrity": "sha512-Ggh0ciFjLwIusLSLz7LZYEaGdxOAUJXI+Qu5JCbhPJJHEt8vP+IjRATTJheiJsdzzTYgUiHUiw3X1Ea3ZpMBdA==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.15.tgz", + "integrity": "sha512-FHg60rS6DBePAYZ9X9F67x+JObFdmgn6tupA1C/a3B+CufFmTD4mX+e8M75tCiAO3foR/6xwVBI0KQiI7sn/rw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.15.tgz", + "integrity": "sha512-/cvV/7v5VGz/moiz0XKRj2dE8DzsKyhIu1KpOvJGPjRywg3yscON889UGvAe8zfiJLHup7VLjBduoGWi3HusWQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.15.tgz", + "integrity": "sha512-MyzC5Hrv/sm+Z7TSGKP/j8001RO2xQm1zOpCNVL4j0cY/VhBZviludA2YFQ7i4lH6ZAXxQm0lcMdBzM+99mE7w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.15.tgz", + "integrity": "sha512-+PgYiS+AH5omy6L45ZLxybasauJaj3M8buoT83D+nzPmCayXlxUV9hydhciCKVyIg0B/v0BtXPDE1uGqNwCPpg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.15.tgz", + "integrity": "sha512-HFZd2QNQYn1JbIi+Hpd7H+r/lkWxcfIu28nirZ6eCn2LafuvmExMlb/P96Sfx5tf7pPArw39IdhmCF8vmV+NhQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tanstack/query-core": { + "version": "5.104.5", + "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.104.5.tgz", + "integrity": "sha512-Q94gI8Opd+CbdVNOdj8ZCyV8WqLYitrDq1t96Xc8WZT6lY0r5iRnJLXYDxMex7EEf2v+mXvn4FcjaBKSxXZQ9A==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/react-query": { + "version": "5.104.5", + "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.104.5.tgz", + "integrity": "sha512-RORgFe052U+93weaNuqg7qHq7vNVNzXN/VrXqD4bbAuQCWUqOl2lV5Ui9flWk5CVvMyL/Bh27QWhzwH0aaOx9g==", + "license": "MIT", + "dependencies": { + "@tanstack/query-core": "5.104.5" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "@types/react": "^18 || ^19", + "react": "^18 || ^19" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.1.2.tgz", + "integrity": "sha512-fhJNGUdscQa4HkI0xFxwonWyhnVReCPDbXI7FH7jmzpnVCrFQI7PRrhWecO263610vOrs9tr2Y4xcf8uAdFxbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", + "babel-plugin-react-compiler": "^1.0.0", + "oxc-transform-react": "^0.152.0", + "vite": "^8.0.0" + }, + "peerDependenciesMeta": { + "@rolldown/plugin-babel": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + }, + "oxc-transform-react": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.5.tgz", + "integrity": "sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.0.5", + "estree-walker": "^3.0.3", + "magic-string": "^1.4.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9 || ^3.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.5.tgz", + "integrity": "sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lucide-react": { + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.61.0.tgz", + "integrity": "sha512-v2SQPPPNjnr+BlhL9Spuzmo5yR+hLkftfuE4E3jaxdNPgSH0hJKPcLJBP7yAta87jQNPsSERS59PJjCJ/CorBA==", + "license": "ISC", + "peerDependencies": { + "@types/react": "*", + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/magic-string": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.3.tgz", + "integrity": "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.31", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.31.tgz", + "integrity": "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, + "node_modules/react-router": { + "version": "7.18.4", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.4.tgz", + "integrity": "sha512-PUPQcMhMGRAslLcvtlPz/kmzBEWPhLdgLFrL7pLNepBL6dX0lWj4WD2cUYVgYCuT3jxvghYFg81cDTj44DhetQ==", + "license": "MIT", + "dependencies": { + "cookie": "^1.0.1", + "set-cookie-parser": "^2.6.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "react": ">=18", + "react-dom": ">=18" + }, + "peerDependenciesMeta": { + "react-dom": { + "optional": true + } + } + }, + "node_modules/react-router-dom": { + "version": "7.18.4", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.4.tgz", + "integrity": "sha512-yrfmJHIpDG7taCpqKjT1G5B6q3O2K+RN8/fgNf0lTjCwiPbQ0ei6vXX9ZjQR+7ld8Tr7Z5xmyMnZ8YJrphWQUw==", + "license": "MIT", + "dependencies": { + "react-router": "7.18.4" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "react": ">=18", + "react-dom": ">=18" + } + }, + "node_modules/rolldown": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.15.tgz", + "integrity": "sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.155.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.15", + "@rolldown/binding-android-arm64": "1.2.15", + "@rolldown/binding-darwin-arm64": "1.2.15", + "@rolldown/binding-darwin-x64": "1.2.15", + "@rolldown/binding-freebsd-x64": "1.2.15", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.15", + "@rolldown/binding-linux-arm64-gnu": "1.2.15", + "@rolldown/binding-linux-arm64-musl": "1.2.15", + "@rolldown/binding-linux-ppc64-gnu": "1.2.15", + "@rolldown/binding-linux-s390x-gnu": "1.2.15", + "@rolldown/binding-linux-x64-gnu": "1.2.15", + "@rolldown/binding-linux-x64-musl": "1.2.15", + "@rolldown/binding-openharmony-arm64": "1.2.15", + "@rolldown/binding-win32-arm64-msvc": "1.2.15", + "@rolldown/binding-win32-x64-msvc": "1.2.15" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT" + }, + "node_modules/set-cookie-parser": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", + "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==", + "license": "MIT" + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.2.tgz", + "integrity": "sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/vite": { + "version": "8.3.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.5.tgz", + "integrity": "sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.30", + "rolldown": "~1.2.14", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.5.tgz", + "integrity": "sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.0.5", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.3", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.2", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.0.5", + "@vitest/browser-preview": "5.0.5", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.0.5", + "@vitest/coverage-v8": "5.0.5", + "@vitest/ui": "5.0.5", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + } + } +} diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 00000000..8f151c3e --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,27 @@ +{ + "name": "mtusi-messenger-web", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite --host 0.0.0.0", + "build": "tsc -b && vite build", + "test": "vitest run", + "test:watch": "vitest" + }, + "dependencies": { + "@tanstack/react-query": "^5.104.5", + "lucide-react": "^1.61.0", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "react-router-dom": "^7.18.4" + }, + "devDependencies": { + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "@vitejs/plugin-react": "^6.1.2", + "typescript": "^7.0.2", + "vite": "^8.3.5", + "vitest": "^5.0.5" + } +} diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts new file mode 100644 index 00000000..1e95a48a --- /dev/null +++ b/frontend/src/api/client.ts @@ -0,0 +1,163 @@ +import type { + ApiErrorBody, + Chat, + CreateChatInput, + LoginInput, + Message, + Page, + RegisterInput, + Session, + User, +} from "./types"; + +const publicApi = "/api/v1"; +const browserApi = "/web-api/v1"; + +export class ApiError extends Error { + readonly status: number; + readonly code?: string; + readonly requestId?: string; + + constructor(status: number, body: ApiErrorBody) { + super(body.error?.message || `HTTP ${status}`); + this.name = "ApiError"; + this.status = status; + this.code = body.error?.code; + this.requestId = body.error?.request_id; + } +} + +type RequestOptions = Omit & { + body?: unknown; +}; + +async function request(path: string, options: RequestOptions = {}): Promise { + const headers = new Headers(options.headers); + if (options.body !== undefined) { + headers.set("Content-Type", "application/json"); + } + + const response = await fetch(path, { + ...options, + headers, + credentials: "same-origin", + body: options.body === undefined ? undefined : JSON.stringify(options.body), + }); + + if (!response.ok) { + let body: ApiErrorBody = {}; + try { + body = (await response.json()) as ApiErrorBody; + } catch { + // Preserve a useful HTTP-level error when a proxy returned non-JSON. + } + throw new ApiError(response.status, body); + } + + if (response.status === 204) { + return undefined as T; + } + return (await response.json()) as T; +} + +function encodeBasic({ username, password }: LoginInput): string { + const bytes = new TextEncoder().encode(`${username}:${password}`); + let binary = ""; + for (const byte of bytes) { + binary += String.fromCharCode(byte); + } + return btoa(binary); +} + +async function collectPages(path: string): Promise { + const items: T[] = []; + let cursor: string | null = null; + + for (let pageIndex = 0; pageIndex < 100; pageIndex += 1) { + const search = new URLSearchParams({ limit: "100" }); + if (cursor) { + search.set("cursor", cursor); + } + const page = await request>(`${path}?${search.toString()}`); + items.push(...page.items); + cursor = page.next_cursor; + if (!cursor) { + return items; + } + } + throw new Error("pagination safety limit exceeded"); +} + +export const api = { + register(input: RegisterInput): Promise { + return request(`${publicApi}/users`, { + method: "POST", + body: { + username: input.username, + display_name: input.displayName, + password: input.password, + }, + }); + }, + + login(input: LoginInput): Promise { + return request(`${publicApi}/auth/sessions`, { + method: "POST", + headers: { + Authorization: `Basic ${encodeBasic(input)}`, + }, + }); + }, + + logout(): Promise { + return request(`${browserApi}/auth/sessions/current`, { + method: "DELETE", + }); + }, + + me(): Promise { + return request(`${browserApi}/users/me`); + }, + + chats(): Promise { + return collectPages(`${browserApi}/chats`); + }, + + chat(chatID: string): Promise { + return request(`${browserApi}/chats/${encodeURIComponent(chatID)}`); + }, + + createChat(input: CreateChatInput): Promise { + return request(`${browserApi}/chats`, { + method: "POST", + body: { + title: input.title, + member_ids: input.memberIds, + }, + }); + }, + + messages(chatID: string): Promise { + return collectPages( + `${browserApi}/chats/${encodeURIComponent(chatID)}/messages`, + ); + }, + + sendMessage( + chatID: string, + text: string, + idempotencyKey: string, + attachmentIDs: string[] = [], + ): Promise { + return request( + `${browserApi}/chats/${encodeURIComponent(chatID)}/messages`, + { + method: "POST", + headers: { + "Idempotency-Key": idempotencyKey, + }, + body: { text, attachment_ids: attachmentIDs }, + }, + ); + }, +}; diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts new file mode 100644 index 00000000..0f7110a5 --- /dev/null +++ b/frontend/src/api/types.ts @@ -0,0 +1,58 @@ +export type User = { + id: string; + username: string; + display_name: string; + created_at: string; +}; + +export type Session = { + token: string; + token_type: "Bearer"; + expires_at: string; + user: User; +}; + +export type Chat = { + id: string; + title: string; + member_ids: string[]; + created_at: string; +}; + +export type Message = { + id: string; + chat_id: string; + sender_id: string; + text: string; + attachment_ids: string[]; + created_at: string; +}; + +export type Page = { + items: T[]; + next_cursor: string | null; +}; + +export type ApiErrorBody = { + error?: { + code?: string; + message?: string; + request_id?: string; + }; +}; + +export type RegisterInput = { + username: string; + displayName: string; + password: string; +}; + +export type CreateChatInput = { + title: string; + memberIds: string[]; +}; + +export type LoginInput = { + username: string; + password: string; +}; diff --git a/frontend/src/app/App.tsx b/frontend/src/app/App.tsx new file mode 100644 index 00000000..c6aa7aed --- /dev/null +++ b/frontend/src/app/App.tsx @@ -0,0 +1,51 @@ +import { Navigate, Outlet, Route, Routes, useLocation } from "react-router-dom"; + +import { useAuth } from "../auth/AuthProvider"; +import { LoadingScreen } from "../components/LoadingScreen"; +import { AuthPage } from "../pages/AuthPage"; +import { MessengerPage } from "../pages/MessengerPage"; + +function ProtectedRoute() { + const { user, isLoading } = useAuth(); + const location = useLocation(); + + if (isLoading) { + return ; + } + if (!user) { + return ; + } + return ; +} + +function PublicOnlyRoute() { + const { user, isLoading } = useAuth(); + + if (isLoading) { + return ; + } + if (user) { + return ; + } + return ; +} + +export function App() { + return ( + + }> + } /> + } /> + + + }> + } /> + } /> + } /> + + + } /> + } /> + + ); +} diff --git a/frontend/src/assets/chat-background.jpg b/frontend/src/assets/chat-background.jpg new file mode 100644 index 00000000..899884b3 Binary files /dev/null and b/frontend/src/assets/chat-background.jpg differ diff --git a/frontend/src/auth/AuthProvider.tsx b/frontend/src/auth/AuthProvider.tsx new file mode 100644 index 00000000..5154fad7 --- /dev/null +++ b/frontend/src/auth/AuthProvider.tsx @@ -0,0 +1,90 @@ +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { + createContext, + useCallback, + useContext, + type PropsWithChildren, +} from "react"; + +import { api, ApiError } from "../api/client"; +import type { LoginInput, RegisterInput, User } from "../api/types"; + +type AuthContextValue = { + user: User | null; + isLoading: boolean; + login: (input: LoginInput) => Promise; + register: (input: RegisterInput) => Promise; + logout: () => Promise; +}; + +const AuthContext = createContext(null); +const meQueryKey = ["current-user"] as const; + +async function loadCurrentUser(): Promise { + try { + return await api.me(); + } catch (error) { + if (error instanceof ApiError && error.status === 401) { + return null; + } + throw error; + } +} + +export function AuthProvider({ children }: PropsWithChildren) { + const queryClient = useQueryClient(); + const meQuery = useQuery({ + queryKey: meQueryKey, + queryFn: loadCurrentUser, + retry: false, + staleTime: 30_000, + }); + + const login = useCallback( + async (input: LoginInput) => { + const session = await api.login(input); + queryClient.setQueryData(meQueryKey, session.user); + }, + [queryClient], + ); + + const register = useCallback( + async (input: RegisterInput) => { + await api.register(input); + const session = await api.login({ + username: input.username, + password: input.password, + }); + queryClient.setQueryData(meQueryKey, session.user); + }, + [queryClient], + ); + + const logout = useCallback(async () => { + await api.logout(); + queryClient.setQueryData(meQueryKey, null); + queryClient.removeQueries({ queryKey: ["chats"] }); + }, [queryClient]); + + return ( + + {children} + + ); +} + +export function useAuth(): AuthContextValue { + const context = useContext(AuthContext); + if (!context) { + throw new Error("useAuth must be used within AuthProvider"); + } + return context; +} diff --git a/frontend/src/components/Avatar.tsx b/frontend/src/components/Avatar.tsx new file mode 100644 index 00000000..6fd07fb6 --- /dev/null +++ b/frontend/src/components/Avatar.tsx @@ -0,0 +1,26 @@ +import { initials } from "../lib/format"; + +type AvatarProps = { + label: string; + seed?: string; + size?: "small" | "medium" | "large"; +}; + +function tone(seed: string): number { + let hash = 0; + for (const character of seed) { + hash = (hash * 31 + character.codePointAt(0)!) >>> 0; + } + return hash % 5; +} + +export function Avatar({ label, seed = label, size = "medium" }: AvatarProps) { + return ( + + ); +} diff --git a/frontend/src/components/ChatList.tsx b/frontend/src/components/ChatList.tsx new file mode 100644 index 00000000..1426d013 --- /dev/null +++ b/frontend/src/components/ChatList.tsx @@ -0,0 +1,121 @@ +import { MessageSquarePlus, Search, UsersRound, X } from "lucide-react"; +import { useMemo, useState } from "react"; +import { useNavigate } from "react-router-dom"; + +import type { Chat, User } from "../api/types"; +import { formatMemberCount } from "../lib/format"; +import { Avatar } from "./Avatar"; + +type ChatListProps = { + chats: Chat[]; + currentUser: User; + error: boolean; + isLoading: boolean; + selectedChatID?: string; + onCreateChat: () => void; +}; + +export function ChatList({ + chats, + currentUser, + error, + isLoading, + selectedChatID, + onCreateChat, +}: ChatListProps) { + const navigate = useNavigate(); + const [search, setSearch] = useState(""); + + const filteredChats = useMemo(() => { + const normalized = search.trim().toLocaleLowerCase("ru"); + if (!normalized) { + return chats; + } + return chats.filter((chat) => + chat.title.toLocaleLowerCase("ru").includes(normalized), + ); + }, [chats, search]); + + return ( + + ); +} diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx new file mode 100644 index 00000000..64ffaad6 --- /dev/null +++ b/frontend/src/components/ChatView.tsx @@ -0,0 +1,236 @@ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { + ArrowLeft, + CheckCheck, + RefreshCcw, + Send, + ShieldCheck, + UsersRound, +} from "lucide-react"; +import { + useEffect, + useMemo, + useRef, + useState, + type FormEvent, + type KeyboardEvent, +} from "react"; + +import { api } from "../api/client"; +import type { Chat, Message, User } from "../api/types"; +import { + dayKey, + formatDay, + formatMemberCount, + formatMessageTime, + shortID, +} from "../lib/format"; +import { createIdempotencyKey } from "../lib/idempotency"; +import { Avatar } from "./Avatar"; + +type ChatViewProps = { + chat: Chat; + currentUser: User; + onBack: () => void; +}; + +type SendEnvelope = { + text: string; + idempotencyKey: string; +}; + +export function ChatView({ chat, currentUser, onBack }: ChatViewProps) { + const queryClient = useQueryClient(); + const messagesEnd = useRef(null); + const [draft, setDraft] = useState(""); + const [failedEnvelope, setFailedEnvelope] = useState(null); + + const messagesQuery = useQuery({ + queryKey: ["messages", chat.id], + queryFn: () => api.messages(chat.id), + refetchInterval: 3_000, + staleTime: 1_000, + }); + + const messages = messagesQuery.data ?? []; + + useEffect(() => { + messagesEnd.current?.scrollIntoView({ + behavior: messages.length > 1 ? "smooth" : "auto", + block: "end", + }); + }, [chat.id, messages.length]); + + const mutation = useMutation({ + mutationFn: (envelope: SendEnvelope) => + api.sendMessage(chat.id, envelope.text, envelope.idempotencyKey), + onSuccess: (message) => { + setFailedEnvelope(null); + queryClient.setQueryData( + ["messages", chat.id], + (current = []) => { + if (current.some((item) => item.id === message.id)) { + return current; + } + return [...current, message]; + }, + ); + }, + onError: (_error, envelope) => { + setFailedEnvelope(envelope); + }, + }); + + const groups = useMemo(() => { + const result: Array<{ key: string; label: string; messages: Message[] }> = []; + for (const message of messages) { + const key = dayKey(message.created_at); + const current = result.at(-1); + if (!current || current.key !== key) { + result.push({ + key, + label: formatDay(message.created_at), + messages: [message], + }); + } else { + current.messages.push(message); + } + } + return result; + }, [messages]); + + function send(envelope: SendEnvelope) { + if (!mutation.isPending) { + mutation.mutate(envelope); + } + } + + function submit(event: FormEvent) { + event.preventDefault(); + const text = draft.trim(); + if (!text || Array.from(text).length > 4_000) { + return; + } + const envelope = { text, idempotencyKey: createIdempotencyKey() }; + setDraft(""); + setFailedEnvelope(null); + send(envelope); + } + + function handleKeyDown(event: KeyboardEvent) { + if (event.key === "Enter" && !event.shiftKey) { + event.preventDefault(); + event.currentTarget.form?.requestSubmit(); + } + } + + return ( +
+
+ + +
+ {chat.title} + {formatMemberCount(chat.member_ids.length)} +
+
+
+
+ +
+
+
+ {messagesQuery.isLoading && ( +
+ + Загружаем историю +
+ )} + + {messagesQuery.isError && ( +
+

История временно недоступна

+ +
+ )} + + {!messagesQuery.isLoading && !messagesQuery.isError && messages.length === 0 && ( +
+
+ )} + + {groups.map((group) => ( +
+
{group.label}
+ {group.messages.map((message) => { + const own = message.sender_id === currentUser.id; + return ( +
+ + {own ? "Вы" : shortID(message.sender_id)} + +

{message.text}

+ + {formatMessageTime(message.created_at)} + {own && } + +
+ ); + })} +
+ ))} +
+
+
+ +