From f035fcef4fe0ebc0ded4743ab75bb29ce2e340b8 Mon Sep 17 00:00:00 2001 From: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Tue, 14 Jul 2026 12:51:36 +0330 Subject: [PATCH] init --- .dockerignore | 14 + .env.example | 37 + .github/workflows/ci.yml | 20 + .gitignore | 17 + .nvmrc | 1 + README.md | 105 + SECURITY.md | 7 + apps/api/package.json | 34 + apps/api/src/app.ts | 558 +++ apps/api/src/config.ts | 199 + apps/api/src/crypto.ts | 59 + apps/api/src/domain.ts | 136 + apps/api/src/errors.ts | 13 + apps/api/src/index.ts | 23 + apps/api/src/repositories/in-memory.ts | 280 ++ apps/api/src/repositories/postgres.ts | 450 +++ apps/api/src/server.ts | 31 + apps/api/src/services/admin.ts | 228 ++ apps/api/src/services/cache-status.ts | 226 ++ apps/api/src/services/media-preparation.ts | 239 ++ apps/api/src/services/playback.ts | 152 + apps/api/src/services/tmdb.ts | 216 + apps/api/test/app.test.ts | 346 ++ apps/api/test/cache-status.test.ts | 127 + apps/api/test/config.test.ts | 74 + apps/api/test/fixtures.ts | 65 + apps/api/test/media-preparation.test.ts | 82 + apps/api/test/tmdb.test.ts | 77 + apps/api/tsconfig.json | 14 + apps/api/tsconfig.test.json | 9 + apps/web/index.html | 18 + apps/web/package.json | 29 + apps/web/public/favicon.svg | 19 + apps/web/public/site.webmanifest | 20 + apps/web/src/App.vue | 31 + apps/web/src/api/client.test.ts | 50 + apps/web/src/api/client.ts | 444 ++ apps/web/src/components/AppHeader.vue | 64 + apps/web/src/components/BrandMark.test.ts | 17 + apps/web/src/components/BrandMark.vue | 33 + apps/web/src/components/LoadingState.vue | 10 + apps/web/src/components/MediaCard.test.ts | 54 + apps/web/src/components/MediaCard.vue | 68 + apps/web/src/components/PlayerShell.vue | 713 ++++ .../composables/spatial-navigation.test.ts | 41 + .../web/src/composables/spatial-navigation.ts | 108 + apps/web/src/env.d.ts | 9 + apps/web/src/i18n.ts | 139 + apps/web/src/main.ts | 17 + apps/web/src/router.ts | 18 + apps/web/src/storage/viewer-db.test.ts | 37 + apps/web/src/storage/viewer-db.ts | 104 + apps/web/src/stores/player.ts | 42 + apps/web/src/stores/ui.ts | 47 + apps/web/src/styles.css | 1358 +++++++ apps/web/src/test/setup.ts | 19 + apps/web/src/types.ts | 137 + apps/web/src/views/AdminView.vue | 218 + apps/web/src/views/CatalogView.vue | 116 + apps/web/src/views/SearchView.vue | 97 + apps/web/src/views/TitleView.vue | 132 + apps/web/tsconfig.json | 16 + apps/web/vite.config.ts | 36 + apps/worker/package.json | 31 + apps/worker/src/cache-lifecycle.ts | 52 + apps/worker/src/catalog.ts | 339 ++ apps/worker/src/cli.ts | 567 +++ apps/worker/src/index.ts | 16 + apps/worker/src/registry.ts | 155 + apps/worker/src/work.ts | 70 + apps/worker/test/cache-lifecycle.test.ts | 63 + apps/worker/test/catalog.test.ts | 23 + apps/worker/test/registry.test.ts | 100 + apps/worker/test/work.test.ts | 13 + apps/worker/tsconfig.json | 15 + compose.yaml | 177 + docs/architecture.md | 56 + docs/operations.md | 74 + infra/docker/node.Dockerfile | 77 + infra/nginx/default.conf.template | 118 + infra/nginx/security-headers.conf | 8 + package.json | 23 + packages/contracts/package.json | 27 + packages/contracts/src/admin.ts | 134 + packages/contracts/src/catalog.ts | 134 + packages/contracts/src/common.ts | 42 + packages/contracts/src/events.ts | 98 + packages/contracts/src/index.ts | 5 + packages/contracts/src/playback.ts | 98 + packages/contracts/test/contracts.test.ts | 38 + packages/contracts/tsconfig.json | 9 + packages/database/drizzle.config.ts | 13 + packages/database/migrations/0000_initial.sql | 213 + .../0001_playback_generation_external.sql | 3 + .../database/migrations/meta/_journal.json | 20 + packages/database/package.json | 37 + packages/database/src/catalog-sync.ts | 160 + packages/database/src/client.ts | 21 + packages/database/src/index.ts | 4 + packages/database/src/job-status.ts | 56 + packages/database/src/schema.ts | 324 ++ packages/database/test/catalog-sync.test.ts | 100 + packages/database/tsconfig.json | 12 + packages/media/package.json | 23 + packages/media/src/cache.ts | 286 ++ packages/media/src/classify.ts | 103 + packages/media/src/encode.ts | 194 + packages/media/src/ffprobe.ts | 51 + packages/media/src/fingerprint.ts | 61 + packages/media/src/fonts.ts | 220 + packages/media/src/hls.ts | 185 + packages/media/src/index.ts | 14 + packages/media/src/language.ts | 63 + packages/media/src/packager.ts | 355 ++ packages/media/src/paths.ts | 151 + packages/media/src/process.ts | 122 + packages/media/src/single-flight.ts | 44 + packages/media/src/subtitles.ts | 127 + packages/media/src/types.ts | 125 + .../media/test/cache-singleflight.test.ts | 154 + packages/media/test/classify.test.ts | 44 + packages/media/test/encode.test.ts | 29 + packages/media/test/fixtures.ts | 44 + packages/media/test/fonts.test.ts | 93 + packages/media/test/hls.test.ts | 71 + packages/media/test/paths-fingerprint.test.ts | 34 + packages/media/test/process.test.ts | 17 + packages/media/test/subtitles.test.ts | 17 + packages/media/tsconfig.json | 10 + pnpm-lock.yaml | 3565 +++++++++++++++++ pnpm-workspace.yaml | 12 + scripts/setup-ubuntu.sh | 713 ++++ scripts/test-setup-ubuntu.sh | 103 + tsconfig.base.json | 23 + 134 files changed, 18678 insertions(+) create mode 100644 .dockerignore create mode 100644 .env.example create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 .nvmrc create mode 100644 README.md create mode 100644 SECURITY.md create mode 100644 apps/api/package.json create mode 100644 apps/api/src/app.ts create mode 100644 apps/api/src/config.ts create mode 100644 apps/api/src/crypto.ts create mode 100644 apps/api/src/domain.ts create mode 100644 apps/api/src/errors.ts create mode 100644 apps/api/src/index.ts create mode 100644 apps/api/src/repositories/in-memory.ts create mode 100644 apps/api/src/repositories/postgres.ts create mode 100644 apps/api/src/server.ts create mode 100644 apps/api/src/services/admin.ts create mode 100644 apps/api/src/services/cache-status.ts create mode 100644 apps/api/src/services/media-preparation.ts create mode 100644 apps/api/src/services/playback.ts create mode 100644 apps/api/src/services/tmdb.ts create mode 100644 apps/api/test/app.test.ts create mode 100644 apps/api/test/cache-status.test.ts create mode 100644 apps/api/test/config.test.ts create mode 100644 apps/api/test/fixtures.ts create mode 100644 apps/api/test/media-preparation.test.ts create mode 100644 apps/api/test/tmdb.test.ts create mode 100644 apps/api/tsconfig.json create mode 100644 apps/api/tsconfig.test.json create mode 100644 apps/web/index.html create mode 100644 apps/web/package.json create mode 100644 apps/web/public/favicon.svg create mode 100644 apps/web/public/site.webmanifest create mode 100644 apps/web/src/App.vue create mode 100644 apps/web/src/api/client.test.ts create mode 100644 apps/web/src/api/client.ts create mode 100644 apps/web/src/components/AppHeader.vue create mode 100644 apps/web/src/components/BrandMark.test.ts create mode 100644 apps/web/src/components/BrandMark.vue create mode 100644 apps/web/src/components/LoadingState.vue create mode 100644 apps/web/src/components/MediaCard.test.ts create mode 100644 apps/web/src/components/MediaCard.vue create mode 100644 apps/web/src/components/PlayerShell.vue create mode 100644 apps/web/src/composables/spatial-navigation.test.ts create mode 100644 apps/web/src/composables/spatial-navigation.ts create mode 100644 apps/web/src/env.d.ts create mode 100644 apps/web/src/i18n.ts create mode 100644 apps/web/src/main.ts create mode 100644 apps/web/src/router.ts create mode 100644 apps/web/src/storage/viewer-db.test.ts create mode 100644 apps/web/src/storage/viewer-db.ts create mode 100644 apps/web/src/stores/player.ts create mode 100644 apps/web/src/stores/ui.ts create mode 100644 apps/web/src/styles.css create mode 100644 apps/web/src/test/setup.ts create mode 100644 apps/web/src/types.ts create mode 100644 apps/web/src/views/AdminView.vue create mode 100644 apps/web/src/views/CatalogView.vue create mode 100644 apps/web/src/views/SearchView.vue create mode 100644 apps/web/src/views/TitleView.vue create mode 100644 apps/web/tsconfig.json create mode 100644 apps/web/vite.config.ts create mode 100644 apps/worker/package.json create mode 100644 apps/worker/src/cache-lifecycle.ts create mode 100644 apps/worker/src/catalog.ts create mode 100644 apps/worker/src/cli.ts create mode 100644 apps/worker/src/index.ts create mode 100644 apps/worker/src/registry.ts create mode 100644 apps/worker/src/work.ts create mode 100644 apps/worker/test/cache-lifecycle.test.ts create mode 100644 apps/worker/test/catalog.test.ts create mode 100644 apps/worker/test/registry.test.ts create mode 100644 apps/worker/test/work.test.ts create mode 100644 apps/worker/tsconfig.json create mode 100644 compose.yaml create mode 100644 docs/architecture.md create mode 100644 docs/operations.md create mode 100644 infra/docker/node.Dockerfile create mode 100644 infra/nginx/default.conf.template create mode 100644 infra/nginx/security-headers.conf create mode 100644 package.json create mode 100644 packages/contracts/package.json create mode 100644 packages/contracts/src/admin.ts create mode 100644 packages/contracts/src/catalog.ts create mode 100644 packages/contracts/src/common.ts create mode 100644 packages/contracts/src/events.ts create mode 100644 packages/contracts/src/index.ts create mode 100644 packages/contracts/src/playback.ts create mode 100644 packages/contracts/test/contracts.test.ts create mode 100644 packages/contracts/tsconfig.json create mode 100644 packages/database/drizzle.config.ts create mode 100644 packages/database/migrations/0000_initial.sql create mode 100644 packages/database/migrations/0001_playback_generation_external.sql create mode 100644 packages/database/migrations/meta/_journal.json create mode 100644 packages/database/package.json create mode 100644 packages/database/src/catalog-sync.ts create mode 100644 packages/database/src/client.ts create mode 100644 packages/database/src/index.ts create mode 100644 packages/database/src/job-status.ts create mode 100644 packages/database/src/schema.ts create mode 100644 packages/database/test/catalog-sync.test.ts create mode 100644 packages/database/tsconfig.json create mode 100644 packages/media/package.json create mode 100644 packages/media/src/cache.ts create mode 100644 packages/media/src/classify.ts create mode 100644 packages/media/src/encode.ts create mode 100644 packages/media/src/ffprobe.ts create mode 100644 packages/media/src/fingerprint.ts create mode 100644 packages/media/src/fonts.ts create mode 100644 packages/media/src/hls.ts create mode 100644 packages/media/src/index.ts create mode 100644 packages/media/src/language.ts create mode 100644 packages/media/src/packager.ts create mode 100644 packages/media/src/paths.ts create mode 100644 packages/media/src/process.ts create mode 100644 packages/media/src/single-flight.ts create mode 100644 packages/media/src/subtitles.ts create mode 100644 packages/media/src/types.ts create mode 100644 packages/media/test/cache-singleflight.test.ts create mode 100644 packages/media/test/classify.test.ts create mode 100644 packages/media/test/encode.test.ts create mode 100644 packages/media/test/fixtures.ts create mode 100644 packages/media/test/fonts.test.ts create mode 100644 packages/media/test/hls.test.ts create mode 100644 packages/media/test/paths-fingerprint.test.ts create mode 100644 packages/media/test/process.test.ts create mode 100644 packages/media/test/subtitles.test.ts create mode 100644 packages/media/tsconfig.json create mode 100644 pnpm-lock.yaml create mode 100644 pnpm-workspace.yaml create mode 100755 scripts/setup-ubuntu.sh create mode 100755 scripts/test-setup-ubuntu.sh create mode 100644 tsconfig.base.json diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..ba05b4f --- /dev/null +++ b/.dockerignore @@ -0,0 +1,14 @@ +.git +.github +.DS_Store +.env +movies +data +cache +derived +node_modules +**/node_modules +**/dist +coverage +playwright-report +test-results diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..0e77ccb --- /dev/null +++ b/.env.example @@ -0,0 +1,37 @@ +NODE_ENV=development +HOST=0.0.0.0 +PORT=3000 +POSTGRES_PASSWORD=replace-with-a-long-alphanumeric-password +REPOSITORY_DRIVER=memory +# Production requires one HTTPS origin for the SPA, API, and media cookie path. +WEB_ORIGIN=http://localhost:5173 +PUBLIC_ORIGIN=http://localhost:8080 +GATEWAY_BIND_ADDRESS=0.0.0.0 +DATABASE_URL= +REDIS_URL=redis://localhost:6379 +ARCHIVE_ROOT=./movies +CACHE_ROOT=./data/cache +DERIVED_ROOT=./data/derived +METADATA_ROOT=./data/metadata +CATALOG_SNAPSHOT_PATH=./data/metadata/catalog.json +INVENTORY_SNAPSHOT_PATH=./data/metadata/inventory.json +PACKAGE_REGISTRY_PATH=./data/metadata/package-registry.json +MEDIA_COMMANDS_PATH=./data/metadata/media-commands.jsonl +FFMPEG_PATH=ffmpeg +FFPROBE_PATH=ffprobe +PLAYBACK_PROFILE=cmaf-v1 +# Use two different random hex/base64url values (for example: openssl rand -hex 32). +PLAYBACK_SIGNING_SECRET=replace-with-at-least-32-random-characters +MEDIA_AUTH_SHARED_SECRET=replace-with-another-32-random-character-secret +PLAYBACK_TTL_SECONDS=14400 +ADMIN_BOOTSTRAP_EMAIL=admin@example.com +ADMIN_BOOTSTRAP_PASSWORD=change-me-before-production +ADMIN_SESSION_TTL_SECONDS=28800 +TMDB_API_TOKEN= +TMDB_COMMERCIAL_LICENSE_CONFIRMED=false +MEDIA_PUBLIC_BASE_URL=http://localhost:8080/media +JIT_REMUX_CONCURRENCY=2 +ENCODE_CONCURRENCY=1 +CACHE_HIGH_WATERMARK=0.85 +CACHE_LOW_WATERMARK=0.75 +CACHE_MAX_BYTES=2147483648000 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..334ec20 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,20 @@ +name: ci + +on: + push: + pull_request: + +jobs: + verify: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 24 + - run: corepack enable && corepack prepare pnpm@11.13.0 --activate + - run: corepack pnpm install --frozen-lockfile + - run: corepack pnpm typecheck + - run: corepack pnpm test + - run: corepack pnpm build + - run: bash -n scripts/setup-ubuntu.sh && bash scripts/test-setup-ubuntu.sh diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b8bfc7a --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +movies/ +.DS_Store +.idea/ +node_modules/ +.pnpm-store/ +dist/ +coverage/ +.env +.env.* +!.env.example +data/ +cache/ +derived/ +*.log +*.tsbuildinfo +playwright-report/ +test-results/ diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..a45fd52 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +24 diff --git a/README.md b/README.md new file mode 100644 index 0000000..feb9ff8 --- /dev/null +++ b/README.md @@ -0,0 +1,105 @@ +# Easy Stream + +Easy Stream is a browser-first streaming layer for a read-only Matroska archive. It keeps the original MKV files untouched, remuxes compatible H.264/AAC sources to CMAF/fMP4 HLS only when requested, and bounds those generated files with a 2 TB LRU cache. Incompatible SDR sources can be prepared once as a durable, same-resolution H.264/AAC representation; HDR is held for review in v1. + +The first version targets Chrome, Firefox, and modern MSE-capable Android TV browsers. The UI is guest-first, Persian/RTL by default, remote-control friendly, and stores viewer preferences and resume progress only in IndexedDB. + +## Repository layout + +- `apps/web`: Vue/Vite catalog, TV navigation, player, local progress, and admin UI. +- `apps/api`: Fastify catalog, playback sessions, signed media authorization, admin, and TMDB metadata endpoints. +- `apps/worker`: archive scanner, BullMQ worker, JIT packager, offline compatibility encoder, and cache maintenance. +- `packages/contracts`: closed TypeBox API, queue, snapshot, and registry contracts. +- `packages/media`: FFmpeg, subtitle, font, HLS validation, path-safety, and LRU primitives. +- `packages/database`: Drizzle schema, migrations, catalog synchronization, and job lifecycle helpers. +- `infra`: production Node/FFmpeg images and the same-origin Nginx gateway. + +See [architecture.md](docs/architecture.md) for the media decisions and [operations.md](docs/operations.md) for deployment gates. + +## What happens to a movie + +| Source | v1 behavior | Storage | +|---|---|---| +| Browser-compatible H.264/AAC SDR | Stream-copy to progressive fMP4 HLS on first play | Bounded, disposable cache | +| H.264 SDR with incompatible audio | Copy video and encode audio to AAC | Bounded, disposable cache | +| Other SDR video | One offline H.264/AAC encode at the source resolution | Durable derived disk | +| HDR, Dolby Vision, invalid, or incomplete media | Not published | Original only | + +ASS subtitles are preserved for JASSUB/libass rendering, with WebVTT fallback. Embedded fonts are validated, content-addressed, and exposed only inside the signed generation path. + +## Local verification + +Requirements: Node.js 24 LTS (22 is supported for development), pnpm 11 through Corepack, and FFmpeg/ffprobe 8.x. + +```sh +cp .env.example .env +corepack pnpm install +corepack pnpm typecheck +corepack pnpm test +corepack pnpm build +corepack pnpm scan:samples +``` + +`scan:samples` writes a public `data/metadata/catalog.json` and a private `data/metadata/inventory.json`. Source paths and probe details never enter the public snapshot. + +To package one scanned media item with the locally installed FFmpeg, copy its UUID from `inventory.json` and run: + +```sh +node apps/worker/dist/cli.js package \ + --root ./movies \ + --cache ./data/cache \ + --inventory ./data/metadata/inventory.json \ + --registry ./data/metadata/package-registry.json \ + --media-item MEDIA_ITEM_UUID +``` + +The original file is opened read-only. Generated media is written under `data/cache/generations/`. + +## Ubuntu / Docker Compose + +On a fresh Ubuntu server, clone this repository and run the interactive bootstrap. It asks for the real HTTPS origin, storage paths, cache size, administrator account, passwords, signing secrets, concurrency, playback lifetime, and optional licensed TMDB access. Secret input is hidden; blank infrastructure secrets are generated securely. + +```sh +chmod +x scripts/setup-ubuntu.sh +bash scripts/setup-ubuntu.sh +``` + +The script installs Docker Engine and the Compose plugin from Docker's official apt repository, asks which host address may expose port 8080 (loopback by default), creates the writable host directories for UID/GID 1000, backs up an existing `.env`, writes the replacement with mode `0600`, validates the rendered Compose configuration, and asks before building or starting containers. Use `--no-start` to configure without launching, or `--skip-docker-install` when a supported Docker installation already exists. + +It does not configure DNS, TLS certificates, CDN edge authorization, origin firewall rules, archive mounts, or backups. Complete those production gates separately. + +### Manual alternative + +1. Copy `.env.example` to `.env` and replace every bootstrap password and signing secret. Keep `PLAYBACK_SIGNING_SECRET` and `MEDIA_AUTH_SHARED_SECRET` different. +2. Set absolute `ARCHIVE_ROOT`, `CACHE_ROOT`, `DERIVED_ROOT`, and `METADATA_ROOT` paths. The archive is mounted read-only. +3. Make the three writable directories available to UID/GID `1000:1000`, used by the unprivileged worker image. +4. Set `WEB_ORIGIN`, `PUBLIC_ORIGIN`, and `MEDIA_PUBLIC_BASE_URL` to the same public HTTPS origin. Put port 8080 behind the CDN/TLS edge and restrict direct origin access. +5. Start the stack: + +```sh +docker compose build +docker compose up -d +docker compose ps +``` + +Compose waits for PostgreSQL, applies migrations once, then starts the API, worker, and gateway. On a new installation, open `/admin`, sign in with the bootstrap administrator, and start the first archive scan. The worker writes the snapshots and transactionally imports public catalog rows into PostgreSQL. + +Cold playback is automatic. For a media item classified `VIDEO_TRANSCODE`, run the deliberate offline preparation command before publishing it: + +```sh +docker compose exec worker node apps/worker/dist/cli.js prepare \ + --root /archive \ + --derived /data/derived \ + --inventory /data/metadata/inventory.json \ + --registry /data/metadata/package-registry.json \ + --media-item MEDIA_ITEM_UUID +``` + +## Important v1 boundaries + +- There is one representation, not an adaptive-bitrate ladder. A slow connection cannot switch to a lower quality. +- Compatible media still occupies temporary HLS cache space; “no duplication” means no permanent HLS copy for every title. +- Durable compatibility encoding is intentionally operator-controlled and CPU-limited to one job at a time. +- TMDB stays disabled until both an API token and explicit commercial-license confirmation are configured. +- The gateway deliberately marks media responses `private`. Do not override that at a CDN until the CDN validates a signed playback grant **before every cache lookup**; merely forwarding the cookie on cache misses is not authorization. +- Physical Android TV, CDN, Redis/PostgreSQL failure recovery, incompatible-SDR encoding, and the full 100 TB census remain production acceptance gates. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..340ce21 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,7 @@ +# Security policy + +Please report vulnerabilities privately to the project operator rather than opening a public issue. Include the affected endpoint or media workflow, reproduction steps, and expected impact. + +The original archive is outside the web trust boundary. A report showing that a browser can obtain an archive path, bypass a generation-scoped playback token, cause a worker to write outside its configured output root, or execute a source filename through a shell is considered critical. + +Production deployments must use patched Node.js, FFmpeg, PostgreSQL, Redis, and Nginx releases and rotate playback/admin secrets after any suspected disclosure. diff --git a/apps/api/package.json b/apps/api/package.json new file mode 100644 index 0000000..a4a0ed8 --- /dev/null +++ b/apps/api/package.json @@ -0,0 +1,34 @@ +{ + "name": "@easy-stream/api", + "version": "0.1.0", + "private": true, + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "scripts": { + "build": "tsc -p tsconfig.json", + "dev": "tsx watch src/server.ts", + "start": "node dist/server.js", + "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.test.json", + "test": "vitest run" + }, + "dependencies": { + "@easy-stream/contracts": "workspace:*", + "@easy-stream/database": "workspace:*", + "@fastify/cookie": "^11.0.2", + "@fastify/cors": "^11.1.0", + "@fastify/helmet": "^13.0.2", + "@fastify/rate-limit": "^10.3.0", + "@sinclair/typebox": "^0.34.41", + "argon2": "^0.44.0", + "bullmq": "^5.61.2", + "drizzle-orm": "^0.45.2", + "fastify": "^5.6.1" + }, + "devDependencies": { + "@types/node": "^24.7.2", + "tsx": "^4.20.6", + "typescript": "^5.9.3", + "vitest": "^3.2.4" + } +} diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts new file mode 100644 index 0000000..b30d0d6 --- /dev/null +++ b/apps/api/src/app.ts @@ -0,0 +1,558 @@ +import { randomUUID } from 'node:crypto'; +import cookie from '@fastify/cookie'; +import cors from '@fastify/cors'; +import helmet from '@fastify/helmet'; +import rateLimit from '@fastify/rate-limit'; +import { + AdminLoginSchema, + AdminSessionResponseSchema, + CacheParamsSchema, + CacheStatusSchema, + CatalogQuerySchema, + CatalogResponseSchema, + CreatePlaybackSessionSchema, + DateTimeSchema, + ErrorResponseSchema, + JobParamsSchema, + JobSchema, + MetadataCandidateSchema, + MetadataMatchBodySchema, + MetadataMatchParamsSchema, + MetadataSearchQuerySchema, + MetadataSearchResponseSchema, + PlaybackSessionParamsSchema, + PlaybackSessionSchema, + PublicationBodySchema, + PublicationParamsSchema, + SearchQuerySchema, + SearchResponseSchema, + StartScanSchema, + TitleDetailSchema, + UuidSchema, + type AdminLogin, + type CatalogQuery, + type CreatePlaybackSession, + type MetadataMatchBody, + type MetadataSearchQuery, + type SearchQuery, + type StartScan, +} from '@easy-stream/contracts'; +import { createDatabase } from '@easy-stream/database'; +import { Type, type Static } from '@sinclair/typebox'; +import Fastify, { + type FastifyInstance, + type FastifyReply, + type FastifyRequest, +} from 'fastify'; +import { loadConfig, type ApiConfig } from './config.js'; +import { PlaybackGrantSigner, playbackCookieName } from './crypto.js'; +import type { + AppRepository, + MediaCommandPublisher, + MediaPreparationService, + MetadataProvider, + PasswordHasher, + StoredPlaybackSession, + TotpVerifier, +} from './domain.js'; +import { AppError } from './errors.js'; +import { InMemoryRepository, loadCatalogSnapshot } from './repositories/in-memory.js'; +import { PostgresRepository } from './repositories/postgres.js'; +import { AdminService, Argon2PasswordHasher, DenyEncryptedTotpVerifier } from './services/admin.js'; +import { + FileMediaPreparationService, + BullMqMediaBridge, + JsonlMediaCommandPublisher, +} from './services/media-preparation.js'; +import { PlaybackService } from './services/playback.js'; +import { + FilesystemCacheStatusService, + type CacheStatusService, +} from './services/cache-status.js'; +import { createMetadataProvider } from './services/tmdb.js'; + +interface BuildAppOptions { + config?: ApiConfig; + repository?: AppRepository; + mediaPreparation?: MediaPreparationService; + commandPublisher?: MediaCommandPublisher; + metadataProvider?: MetadataProvider; + passwordHasher?: PasswordHasher; + totpVerifier?: TotpVerifier; + cacheStatus?: CacheStatusService; + fetch?: typeof globalThis.fetch; + logger?: boolean; +} + +const SlugParamsSchema = Type.Object( + { slug: Type.String({ minLength: 1, maxLength: 240 }) }, + { additionalProperties: false }, +); +const OkSchema = Type.Object({ ok: Type.Literal(true) }, { additionalProperties: false }); +const HealthSchema = Type.Object( + { + status: Type.Literal('ok'), + time: Type.String(), + repository: Type.Union([Type.Literal('memory'), Type.Literal('postgres')]), + }, + { additionalProperties: false }, +); +const JobsResponseSchema = Type.Object( + { items: Type.Array(JobSchema) }, + { additionalProperties: false }, +); +const ClientEventSchema = Type.Object( + { + name: Type.String({ minLength: 1, maxLength: 64, pattern: '^[a-z0-9._-]+$' }), + mediaItemId: Type.Optional(UuidSchema), + sessionId: Type.Optional(UuidSchema), + occurredAt: DateTimeSchema, + details: Type.Optional( + Type.Record( + Type.String({ minLength: 1, maxLength: 64 }), + Type.Union([ + Type.String({ maxLength: 2048 }), + Type.Number(), + Type.Boolean(), + Type.Null(), + ]), + ), + ), + }, + { additionalProperties: false }, +); + +type PublicationBody = Static; + +export async function buildApp(options: BuildAppOptions = {}): Promise { + const config = options.config ?? loadConfig(); + const app = Fastify({ + logger: options.logger ?? config.nodeEnv !== 'test', + genReqId: (request) => + typeof request.headers['x-request-id'] === 'string' + ? request.headers['x-request-id'].slice(0, 128) + : randomUUID(), + bodyLimit: 64 * 1024, + trustProxy: config.nodeEnv === 'production' ? 1 : false, + }); + + await app.register(cookie); + await app.register(cors, { + origin: config.webOrigin, + credentials: true, + methods: ['GET', 'HEAD', 'POST', 'PATCH', 'DELETE', 'OPTIONS'], + allowedHeaders: ['content-type', 'x-csrf-token', 'x-request-id'], + }); + await app.register(helmet, { + contentSecurityPolicy: false, + crossOriginEmbedderPolicy: false, + }); + await app.register(rateLimit, { + global: true, + max: 300, + timeWindow: '1 minute', + }); + + const runtime = await createRepository(app, config, options.repository); + const repository = runtime.repository; + const cacheStatus = options.cacheStatus ?? new FilesystemCacheStatusService({ + cacheRoot: config.cacheRoot, + maxBytes: config.cacheMaxBytes, + highWatermark: config.cacheHighWatermark, + lowWatermark: config.cacheLowWatermark, + }); + const redisBridge = + config.redisUrl && (!options.commandPublisher || !options.mediaPreparation) + ? new BullMqMediaBridge(config.redisUrl, config.packageRegistryPath, config.playbackProfile) + : undefined; + if (redisBridge) app.addHook('onClose', async () => redisBridge.close()); + const commands = + options.commandPublisher ?? + redisBridge ?? + new JsonlMediaCommandPublisher(config.mediaCommandsPath); + const media = + options.mediaPreparation ?? + redisBridge ?? + new FileMediaPreparationService(config.packageRegistryPath, commands); + const metadata = + options.metadataProvider ?? createMetadataProvider(config, options.fetch ?? globalThis.fetch); + const playback = new PlaybackService(repository, media, config); + const admin = new AdminService( + repository, + commands, + media, + metadata, + options.passwordHasher ?? new Argon2PasswordHasher(), + options.totpVerifier ?? new DenyEncryptedTotpVerifier(), + config, + ); + await admin.initialize(); + const grantSigner = new PlaybackGrantSigner(config.playbackSigningSecret); + + app.setErrorHandler((error, request, reply) => { + if (error instanceof AppError) { + return reply.code(error.statusCode).send({ + error: { + code: error.code, + message: error.message, + requestId: request.id, + ...(error.details !== undefined ? { details: error.details } : {}), + }, + }); + } + if (typeof error === 'object' && error && 'validation' in error && error.validation) { + return reply.code(400).send({ + error: { + code: 'VALIDATION_ERROR', + message: 'Request validation failed', + requestId: request.id, + details: error.validation, + }, + }); + } + request.log.error({ err: error }, 'unhandled request error'); + return reply.code(500).send({ + error: { code: 'INTERNAL_ERROR', message: 'Internal server error', requestId: request.id }, + }); + }); + + app.get('/health', { schema: { response: { 200: HealthSchema } } }, async () => ({ + status: 'ok' as const, + time: new Date().toISOString(), + repository: config.repositoryDriver, + })); + + app.get<{ Querystring: CatalogQuery }>( + '/api/v1/catalog', + { + schema: { + querystring: CatalogQuerySchema, + response: { 200: CatalogResponseSchema, 400: ErrorResponseSchema }, + }, + }, + async (request) => repository.listCatalog(request.query), + ); + + app.get<{ Params: Static }>( + '/api/v1/titles/:slug', + { + schema: { + params: SlugParamsSchema, + response: { 200: TitleDetailSchema, 404: ErrorResponseSchema }, + }, + }, + async (request) => { + const title = await repository.getTitleBySlug(request.params.slug); + if (!title) throw new AppError(404, 'NOT_FOUND', 'Title not found'); + return title; + }, + ); + + app.get<{ Querystring: SearchQuery }>( + '/api/v1/search', + { + schema: { + querystring: SearchQuerySchema, + response: { 200: SearchResponseSchema, 400: ErrorResponseSchema }, + }, + }, + async (request) => ({ items: await repository.searchTitles(request.query) }), + ); + + app.post<{ Body: Static }>( + '/api/v1/client-events', + { + config: { rateLimit: { max: 120, timeWindow: '1 minute' } }, + schema: { + body: ClientEventSchema, + response: { 202: OkSchema, 400: ErrorResponseSchema }, + }, + }, + async (request, reply) => { + request.log.info({ clientEvent: request.body }, 'client playback event'); + return reply.code(202).send({ ok: true as const }); + }, + ); + + app.post<{ Body: CreatePlaybackSession }>( + '/api/v1/playback-sessions', + { + config: { rateLimit: { max: 60, timeWindow: '1 minute' } }, + schema: { + body: CreatePlaybackSessionSchema, + response: { + 200: PlaybackSessionSchema, + 202: PlaybackSessionSchema, + 400: ErrorResponseSchema, + 404: ErrorResponseSchema, + }, + }, + }, + async (request, reply) => { + const session = await playback.create(request.body); + if (session.state === 'READY') issuePlaybackCookie(reply, session, grantSigner, config); + return reply.code(session.state === 'PREPARING' ? 202 : 200).send(playback.toPublic(session)); + }, + ); + + app.get<{ Params: Static }>( + '/api/v1/playback-sessions/:id', + { + schema: { + params: PlaybackSessionParamsSchema, + response: { 200: PlaybackSessionSchema, 202: PlaybackSessionSchema, 404: ErrorResponseSchema }, + }, + }, + async (request, reply) => { + const session = await playback.get(request.params.id); + if (session.state === 'READY') issuePlaybackCookie(reply, session, grantSigner, config); + return reply.code(session.state === 'PREPARING' ? 202 : 200).send(playback.toPublic(session)); + }, + ); + + app.get( + '/internal/media-auth', + { config: { rateLimit: false } }, + async (request, reply) => { + if (header(request, 'x-media-auth-secret') !== config.mediaAuthSharedSecret) { + throw new AppError(401, 'UNAUTHORIZED', 'Invalid media authorization secret'); + } + const originalUri = header(request, 'x-original-uri'); + if (!originalUri || /%2f|%5c|%2e/i.test(originalUri)) { + throw new AppError(401, 'UNAUTHORIZED', 'Invalid media request path'); + } + const pathname = new URL(originalUri, config.publicOrigin).pathname; + const match = pathname.match( + /^\/media\/(?:derived\/)?generations\/([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})\//i, + ); + const generationId = match?.[1]; + if (!generationId) throw new AppError(401, 'UNAUTHORIZED', 'Invalid media request path'); + const token = request.cookies[playbackCookieName(generationId)]; + const grant = token ? grantSigner.verify(token) : undefined; + if ( + !grant || + grant.generationId !== generationId || + grant.expiresAtEpochSeconds <= Math.floor(Date.now() / 1000) || + !pathname.startsWith(grant.path) + ) { + throw new AppError(401, 'UNAUTHORIZED', 'Media authorization expired or invalid'); + } + const session = await repository.getPlaybackSession(grant.sessionId); + if ( + !session || + session.state !== 'READY' || + session.generationId !== generationId || + Date.parse(session.expiresAt) <= Date.now() + ) { + throw new AppError(401, 'UNAUTHORIZED', 'Playback session expired or invalid'); + } + return reply.code(204).send(); + }, + ); + + app.post<{ Body: AdminLogin }>( + '/api/v1/admin/login', + { + config: { rateLimit: { max: 5, timeWindow: '1 minute' } }, + schema: { + body: AdminLoginSchema, + response: { 200: AdminSessionResponseSchema, 401: ErrorResponseSchema }, + }, + }, + async (request, reply) => { + const result = await admin.login(request.body); + reply.setCookie('es_admin_session', result.rawToken, adminCookie(config)); + return result.response; + }, + ); + + const adminRead = async (request: FastifyRequest) => { + await admin.authenticate(request.cookies.es_admin_session); + }; + const adminWrite = async (request: FastifyRequest) => { + const csrf = header(request, 'x-csrf-token'); + if (!csrf) throw new AppError(403, 'FORBIDDEN', 'CSRF token is required'); + await admin.authenticate(request.cookies.es_admin_session, csrf); + }; + + app.post( + '/api/v1/admin/logout', + { preHandler: adminWrite, schema: { response: { 200: OkSchema } } }, + async (request, reply) => { + await admin.logout(request.cookies.es_admin_session, header(request, 'x-csrf-token')); + reply.clearCookie('es_admin_session', { path: '/' }); + return { ok: true as const }; + }, + ); + + app.post<{ Body: StartScan }>( + '/api/v1/admin/scans', + { + preHandler: adminWrite, + schema: { body: StartScanSchema, response: { 202: JobSchema } }, + }, + async (request, reply) => reply.code(202).send(await admin.startScan(request.body.full ?? false)), + ); + + app.patch<{ + Params: Static; + Body: PublicationBody; + }>( + '/api/v1/admin/media/:mediaItemId/publication', + { + preHandler: adminWrite, + schema: { + params: PublicationParamsSchema, + body: PublicationBodySchema, + response: { 200: OkSchema }, + }, + }, + async (request) => { + await admin.setPublished(request.params.mediaItemId, request.body.published); + return { ok: true as const }; + }, + ); + + app.get( + '/api/v1/admin/jobs', + { preHandler: adminRead, schema: { response: { 200: JobsResponseSchema } } }, + async () => ({ items: await repository.listJobs() }), + ); + + app.post<{ Params: Static }>( + '/api/v1/admin/jobs/:jobId/retry', + { + preHandler: adminWrite, + schema: { params: JobParamsSchema, response: { 202: JobSchema } }, + }, + async (request, reply) => reply.code(202).send(await admin.retryJob(request.params.jobId)), + ); + + app.get( + '/api/v1/admin/cache', + { preHandler: adminRead, schema: { response: { 200: CacheStatusSchema } } }, + async () => cacheStatus.getStatus(), + ); + + app.post<{ Params: Static }>( + '/api/v1/admin/cache/:generationId/evict', + { + preHandler: adminWrite, + schema: { params: CacheParamsSchema, response: { 202: OkSchema } }, + }, + async (request, reply) => { + await admin.evict(request.params.generationId); + return reply.code(202).send({ ok: true as const }); + }, + ); + + app.get<{ Querystring: MetadataSearchQuery }>( + '/api/v1/admin/metadata/tmdb/search', + { + preHandler: adminRead, + schema: { + querystring: MetadataSearchQuerySchema, + response: { 200: MetadataSearchResponseSchema }, + }, + }, + async (request) => ({ items: await admin.searchMetadata(request.query) }), + ); + + app.post<{ + Params: Static; + Body: MetadataMatchBody; + }>( + '/api/v1/admin/titles/:titleId/metadata-match', + { + preHandler: adminWrite, + schema: { + params: MetadataMatchParamsSchema, + body: MetadataMatchBodySchema, + response: { 200: MetadataCandidateSchema }, + }, + }, + async (request) => admin.matchMetadata(request.params.titleId, request.body), + ); + + await app.ready(); + return app; +} + +async function createRepository( + app: FastifyInstance, + config: ApiConfig, + injected: AppRepository | undefined, +): Promise<{ repository: AppRepository }> { + if (injected) return { repository: injected }; + if (config.repositoryDriver === 'memory') { + const snapshot = await loadCatalogSnapshot(config.catalogSnapshotPath); + const repository = new InMemoryRepository({ + ...(snapshot ? { titles: snapshot.titles } : {}), + cache: { + maxBytes: config.cacheMaxBytes, + highWatermark: config.cacheHighWatermark, + lowWatermark: config.cacheLowWatermark, + }, + }); + if (snapshot) app.log.info({ path: config.catalogSnapshotPath }, 'loaded catalog snapshot'); + else app.log.warn({ path: config.catalogSnapshotPath }, 'catalog snapshot not found; catalog is empty'); + return { repository }; + } + const connection = createDatabase(config.databaseUrl!); + app.addHook('onClose', async () => connection.close()); + return { + repository: new PostgresRepository(connection.db, { + cacheMaxBytes: config.cacheMaxBytes, + cacheHighWatermark: config.cacheHighWatermark, + cacheLowWatermark: config.cacheLowWatermark, + }), + }; +} + +function issuePlaybackCookie( + reply: FastifyReply, + session: StoredPlaybackSession, + signer: PlaybackGrantSigner, + config: ApiConfig, +): void { + if (!session.generationId || !session.manifestUrl) return; + const manifestPath = new URL(session.manifestUrl).pathname; + const match = manifestPath.match( + /^\/media\/(?:derived\/)?generations\/([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})\//i, + ); + if (!match || match[1]?.toLowerCase() !== session.generationId.toLowerCase()) return; + const path = match[0]; + const expiresAtEpochSeconds = Math.floor(Date.parse(session.expiresAt) / 1000); + reply.setCookie( + playbackCookieName(session.generationId), + signer.sign({ + version: 1, + sessionId: session.id, + generationId: session.generationId, + path, + expiresAtEpochSeconds, + }), + { + httpOnly: true, + secure: config.nodeEnv === 'production', + sameSite: 'lax', + path, + expires: new Date(session.expiresAt), + }, + ); +} + +function adminCookie(config: ApiConfig) { + return { + httpOnly: true, + secure: config.nodeEnv === 'production', + sameSite: 'strict' as const, + path: '/', + maxAge: config.adminSessionTtlSeconds, + }; +} + +function header(request: FastifyRequest, name: string): string | undefined { + const value = request.headers[name]; + return Array.isArray(value) ? value[0] : value; +} diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts new file mode 100644 index 0000000..6ea98d2 --- /dev/null +++ b/apps/api/src/config.ts @@ -0,0 +1,199 @@ +import { Type } from '@sinclair/typebox'; +import { Value } from '@sinclair/typebox/value'; + +const ConfigSchema = Type.Object( + { + nodeEnv: Type.Union([ + Type.Literal('development'), + Type.Literal('test'), + Type.Literal('production'), + ]), + host: Type.String({ minLength: 1 }), + port: Type.Integer({ minimum: 1, maximum: 65535 }), + webOrigin: Type.String({ pattern: '^https?://[^\\s]+$' }), + publicOrigin: Type.String({ pattern: '^https?://[^\\s]+$' }), + mediaPublicBaseUrl: Type.String({ pattern: '^https?://[^\\s]+$' }), + repositoryDriver: Type.Union([Type.Literal('memory'), Type.Literal('postgres')]), + databaseUrl: Type.Optional(Type.String({ minLength: 1 })), + redisUrl: Type.Optional(Type.String({ pattern: '^rediss?://[^\\s]+$' })), + catalogSnapshotPath: Type.String({ minLength: 1 }), + packageRegistryPath: Type.String({ minLength: 1 }), + mediaCommandsPath: Type.String({ minLength: 1 }), + cacheRoot: Type.String({ minLength: 1 }), + playbackProfile: Type.String({ + minLength: 1, + maxLength: 64, + pattern: '^[a-zA-Z0-9._-]+$', + }), + playbackSigningSecret: Type.String({ minLength: 32 }), + // This value is substituted into an Nginx quoted string, so keep it to a + // portable base64url/hex alphabet rather than accepting config syntax. + mediaAuthSharedSecret: Type.String({ + minLength: 32, + maxLength: 256, + pattern: '^[A-Za-z0-9_-]+$', + }), + playbackTtlSeconds: Type.Integer({ minimum: 300, maximum: 86400 }), + adminSessionTtlSeconds: Type.Integer({ minimum: 300, maximum: 86400 }), + adminBootstrapEmail: Type.Optional( + Type.String({ maxLength: 320, pattern: '^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$' }), + ), + adminBootstrapPassword: Type.Optional(Type.String({ minLength: 12 })), + tmdbApiToken: Type.Optional(Type.String({ minLength: 1 })), + tmdbCommercialLicenseConfirmed: Type.Boolean(), + tmdbBaseUrl: Type.String({ pattern: '^https?://[^\\s]+$' }), + tmdbTimeoutMs: Type.Integer({ minimum: 250, maximum: 30000 }), + tmdbMaxRetries: Type.Integer({ minimum: 0, maximum: 5 }), + cacheMaxBytes: Type.Integer({ minimum: 1 }), + cacheHighWatermark: Type.Number({ exclusiveMinimum: 0, maximum: 1 }), + cacheLowWatermark: Type.Number({ minimum: 0, exclusiveMaximum: 1 }), + }, + { additionalProperties: false }, +); + +export interface ApiConfig { + nodeEnv: 'development' | 'test' | 'production'; + host: string; + port: number; + webOrigin: string; + publicOrigin: string; + mediaPublicBaseUrl: string; + repositoryDriver: 'memory' | 'postgres'; + databaseUrl?: string; + redisUrl?: string; + catalogSnapshotPath: string; + packageRegistryPath: string; + mediaCommandsPath: string; + cacheRoot: string; + playbackProfile: string; + playbackSigningSecret: string; + mediaAuthSharedSecret: string; + playbackTtlSeconds: number; + adminSessionTtlSeconds: number; + adminBootstrapEmail?: string; + adminBootstrapPassword?: string; + tmdbApiToken?: string; + tmdbCommercialLicenseConfirmed: boolean; + tmdbBaseUrl: string; + tmdbTimeoutMs: number; + tmdbMaxRetries: number; + cacheMaxBytes: number; + cacheHighWatermark: number; + cacheLowWatermark: number; +} + +function integer(value: string | undefined, fallback: number): number { + if (value === undefined || value === '') return fallback; + if (!/^-?[0-9]+$/.test(value)) return Number.NaN; + return Number(value); +} + +function decimal(value: string | undefined, fallback: number): number { + if (value === undefined || value === '') return fallback; + return Number(value); +} + +function bool(value: string | undefined, fallback: boolean): boolean { + if (value === undefined || value === '') return fallback; + if (value === 'true') return true; + if (value === 'false') return false; + throw new Error(`Expected a boolean, received ${JSON.stringify(value)}`); +} + +export function loadConfig(env: NodeJS.ProcessEnv = process.env): ApiConfig { + const nodeEnv = env.NODE_ENV ?? 'development'; + const signingSecret = env.PLAYBACK_SIGNING_SECRET ?? ''; + const config: ApiConfig = { + nodeEnv: nodeEnv as ApiConfig['nodeEnv'], + host: env.HOST ?? '0.0.0.0', + port: integer(env.PORT, 3000), + webOrigin: env.WEB_ORIGIN ?? 'http://localhost:5173', + publicOrigin: env.PUBLIC_ORIGIN ?? 'http://localhost:8080', + mediaPublicBaseUrl: env.MEDIA_PUBLIC_BASE_URL ?? 'http://localhost:8080/media', + repositoryDriver: + (env.REPOSITORY_DRIVER as ApiConfig['repositoryDriver'] | undefined) ?? + (nodeEnv === 'production' ? 'postgres' : 'memory'), + ...(env.DATABASE_URL ? { databaseUrl: env.DATABASE_URL } : {}), + ...(env.REDIS_URL ? { redisUrl: env.REDIS_URL } : {}), + catalogSnapshotPath: env.CATALOG_SNAPSHOT_PATH ?? './data/catalog.json', + packageRegistryPath: env.PACKAGE_REGISTRY_PATH ?? './data/package-registry.json', + mediaCommandsPath: env.MEDIA_COMMANDS_PATH ?? './data/media-commands.jsonl', + cacheRoot: env.CACHE_ROOT ?? './data/cache', + playbackProfile: env.PLAYBACK_PROFILE ?? 'cmaf-v1', + playbackSigningSecret: signingSecret, + mediaAuthSharedSecret: env.MEDIA_AUTH_SHARED_SECRET ?? signingSecret, + playbackTtlSeconds: integer(env.PLAYBACK_TTL_SECONDS, 4 * 60 * 60), + adminSessionTtlSeconds: integer(env.ADMIN_SESSION_TTL_SECONDS, 8 * 60 * 60), + ...(env.ADMIN_BOOTSTRAP_EMAIL ? { adminBootstrapEmail: env.ADMIN_BOOTSTRAP_EMAIL } : {}), + ...(env.ADMIN_BOOTSTRAP_PASSWORD + ? { adminBootstrapPassword: env.ADMIN_BOOTSTRAP_PASSWORD } + : {}), + ...(env.TMDB_API_TOKEN ? { tmdbApiToken: env.TMDB_API_TOKEN } : {}), + tmdbCommercialLicenseConfirmed: bool(env.TMDB_COMMERCIAL_LICENSE_CONFIRMED, false), + tmdbBaseUrl: env.TMDB_BASE_URL ?? 'https://api.themoviedb.org/3', + tmdbTimeoutMs: integer(env.TMDB_TIMEOUT_MS, 4000), + tmdbMaxRetries: integer(env.TMDB_MAX_RETRIES, 2), + cacheMaxBytes: integer(env.CACHE_MAX_BYTES, 2_147_483_648_000), + cacheHighWatermark: decimal(env.CACHE_HIGH_WATERMARK, 0.85), + cacheLowWatermark: decimal(env.CACHE_LOW_WATERMARK, 0.75), + }; + + if (!Value.Check(ConfigSchema, config)) { + const errors = [...Value.Errors(ConfigSchema, config)] + .map((error) => `${error.path || '/'} ${error.message}`) + .join('; '); + throw new Error(`Invalid API configuration: ${errors}`); + } + if (config.repositoryDriver === 'postgres' && !config.databaseUrl) { + throw new Error('DATABASE_URL is required when REPOSITORY_DRIVER=postgres'); + } + if (config.cacheLowWatermark >= config.cacheHighWatermark) { + throw new Error('CACHE_LOW_WATERMARK must be lower than CACHE_HIGH_WATERMARK'); + } + const mediaBase = new URL(config.mediaPublicBaseUrl); + if (mediaBase.pathname.replace(/\/+$/u, '') !== '/media' || mediaBase.search || mediaBase.hash) { + throw new Error('MEDIA_PUBLIC_BASE_URL must use the /media path without query or fragment'); + } + if ( + config.nodeEnv === 'production' && + config.adminBootstrapPassword === 'change-me-before-production' + ) { + throw new Error('The example administrator password is forbidden in production'); + } + if ( + config.nodeEnv === 'production' && + [ + 'replace-with-at-least-32-random-characters', + 'replace-with-another-32-random-character-secret', + ].includes(config.playbackSigningSecret) + ) { + throw new Error('The example playback signing secret is forbidden in production'); + } + if ( + config.nodeEnv === 'production' && + [ + 'replace-with-at-least-32-random-characters', + 'replace-with-another-32-random-character-secret', + ].includes(config.mediaAuthSharedSecret) + ) { + throw new Error('The example media auth secret is forbidden in production'); + } + if ( + config.nodeEnv === 'production' && + config.mediaAuthSharedSecret === config.playbackSigningSecret + ) { + throw new Error('MEDIA_AUTH_SHARED_SECRET must differ from PLAYBACK_SIGNING_SECRET in production'); + } + if (config.nodeEnv === 'production') { + const publicOrigin = new URL(config.publicOrigin).origin; + if ( + new URL(config.webOrigin).origin !== publicOrigin || + mediaBase.origin !== publicOrigin + ) { + throw new Error( + 'WEB_ORIGIN, PUBLIC_ORIGIN, and MEDIA_PUBLIC_BASE_URL must use one origin in production', + ); + } + } + return config; +} diff --git a/apps/api/src/crypto.ts b/apps/api/src/crypto.ts new file mode 100644 index 0000000..a8ac1fd --- /dev/null +++ b/apps/api/src/crypto.ts @@ -0,0 +1,59 @@ +import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'; + +export function randomToken(bytes = 32): string { + return randomBytes(bytes).toString('base64url'); +} + +export function sha256(value: string): string { + return createHash('sha256').update(value).digest('hex'); +} + +function safeEqual(left: string, right: string): boolean { + const a = Buffer.from(left); + const b = Buffer.from(right); + return a.length === b.length && timingSafeEqual(a, b); +} + +export interface PlaybackGrant { + version: 1; + sessionId: string; + generationId: string; + path: string; + expiresAtEpochSeconds: number; +} + +export class PlaybackGrantSigner { + constructor(private readonly secret: string) {} + + sign(grant: PlaybackGrant): string { + const payload = Buffer.from(JSON.stringify(grant)).toString('base64url'); + const signature = createHmac('sha256', this.secret).update(payload).digest('base64url'); + return `${payload}.${signature}`; + } + + verify(token: string): PlaybackGrant | undefined { + const [payload, signature, extra] = token.split('.'); + if (!payload || !signature || extra) return undefined; + const expected = createHmac('sha256', this.secret).update(payload).digest('base64url'); + if (!safeEqual(signature, expected)) return undefined; + try { + const value = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as PlaybackGrant; + if ( + value.version !== 1 || + !value.sessionId || + !value.generationId || + !value.path.startsWith('/media/') || + !Number.isInteger(value.expiresAtEpochSeconds) + ) { + return undefined; + } + return value; + } catch { + return undefined; + } + } +} + +export function playbackCookieName(generationId: string): string { + return `es_playback_${generationId.replaceAll('-', '')}`; +} diff --git a/apps/api/src/domain.ts b/apps/api/src/domain.ts new file mode 100644 index 0000000..326bea1 --- /dev/null +++ b/apps/api/src/domain.ts @@ -0,0 +1,136 @@ +import type { + AdminSessionResponse, + AudioTrack, + CacheStatus, + CatalogCard, + CatalogQuery, + ClientCapabilities, + Job, + MetadataCandidate, + MediaCommand, + PlaybackSession, + SearchQuery, + SubtitleTrack, + TitleDetail, +} from '@easy-stream/contracts'; + +export interface MediaItemForPlayback { + id: string; + titleId: string; + durationSeconds: number; + compatibility: 'COPY' | 'AUDIO_TRANSCODE' | 'VIDEO_TRANSCODE' | 'HOLD_HDR' | 'INVALID'; + published: boolean; +} + +export interface CatalogPage { + items: CatalogCard[]; + nextCursor?: string; +} + +export interface CatalogRepository { + listCatalog(query: CatalogQuery): Promise; + searchTitles(query: SearchQuery): Promise; + getTitleBySlug(slug: string): Promise; + getMediaItem(id: string): Promise; + setMediaPublished(mediaItemId: string, published: boolean): Promise; + applyTitleMetadata(titleId: string, metadata: MetadataCandidate): Promise; +} + +export interface StoredPlaybackSession extends PlaybackSession { + capabilities: ClientCapabilities; +} + +export interface PlaybackRepository { + createPlaybackSession(session: StoredPlaybackSession): Promise; + getPlaybackSession(id: string): Promise; + updatePlaybackSession(session: StoredPlaybackSession): Promise; +} + +export interface AdminRecord { + id: string; + email: string; + passwordHash: string; + totpSecretEncrypted?: string; + disabled: boolean; +} + +export interface StoredAdminSession { + id: string; + adminId: string; + tokenHash: string; + csrfTokenHash: string; + expiresAt: string; + revokedAt?: string; +} + +export interface AdminRepository { + findAdminByEmail(email: string): Promise; + findAdminById(id: string): Promise; + createAdmin(admin: AdminRecord): Promise; + createAdminSession(session: StoredAdminSession): Promise; + findAdminSessionByTokenHash(tokenHash: string): Promise; + revokeAdminSession(id: string): Promise; + createJob(job: Job, payload: Record): Promise; + listJobs(): Promise; + findJob(id: string): Promise; + retryJob(id: string): Promise; + getCacheStatus(): Promise; +} + +export type AppRepository = CatalogRepository & PlaybackRepository & AdminRepository; + +export interface MediaPreparation { + state: PlaybackSession['state']; + playable: boolean; + generationId?: string; + manifestPath?: string; + reasonCode?: string; + pollAfterMs?: number; + durationSeconds?: number; + audioTracks?: AudioTrack[]; + subtitleTracks?: SubtitleTrack[]; +} + +export interface MediaPreparationService { + prepare(input: { + sessionId: string; + mediaItem: MediaItemForPlayback; + capabilities: ClientCapabilities; + protectUntil?: string; + }): Promise; + getStatus(input: { + sessionId: string; + mediaItem: MediaItemForPlayback; + protectUntil?: string; + }): Promise; +} + +export interface MediaCommandPublisher { + publish(command: MediaCommand): Promise; +} + +export interface PasswordHasher { + hash(password: string): Promise; + verify(hash: string, password: string): Promise; +} + +export interface TotpVerifier { + verify(encryptedSecret: string, code: string): Promise; +} + +export interface MetadataProvider { + search(input: { + query: string; + kind: 'MOVIE' | 'SERIES'; + year?: number; + }): Promise; + getDetails(input: { + externalId: number; + kind: 'MOVIE' | 'SERIES'; + }): Promise; +} + +export interface AuthenticatedAdmin extends AdminSessionResponse { + sessionId: string; + rawToken: string; +} diff --git a/apps/api/src/errors.ts b/apps/api/src/errors.ts new file mode 100644 index 0000000..76af730 --- /dev/null +++ b/apps/api/src/errors.ts @@ -0,0 +1,13 @@ +import type { ErrorCode } from '@easy-stream/contracts'; + +export class AppError extends Error { + constructor( + public readonly statusCode: number, + public readonly code: ErrorCode, + message: string, + public readonly details?: unknown, + ) { + super(message); + this.name = 'AppError'; + } +} diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts new file mode 100644 index 0000000..2c36927 --- /dev/null +++ b/apps/api/src/index.ts @@ -0,0 +1,23 @@ +export { buildApp } from './app.js'; +export { loadConfig, type ApiConfig } from './config.js'; +export type { + AppRepository, + MediaCommandPublisher, + MediaPreparation, + MediaPreparationService, + MetadataProvider, +} from './domain.js'; +export { InMemoryRepository, loadCatalogSnapshot } from './repositories/in-memory.js'; +export { PostgresRepository } from './repositories/postgres.js'; +export { + FilesystemCacheStatusService, + type CacheStatusService, + type FilesystemCacheStatusOptions, +} from './services/cache-status.js'; +export { + FileMediaPreparationService, + BullMqMediaBridge, + InMemoryMediaCommandPublisher, + JsonlMediaCommandPublisher, +} from './services/media-preparation.js'; +export { DisabledMetadataProvider, TmdbMetadataProvider } from './services/tmdb.js'; diff --git a/apps/api/src/repositories/in-memory.ts b/apps/api/src/repositories/in-memory.ts new file mode 100644 index 0000000..7fe034b --- /dev/null +++ b/apps/api/src/repositories/in-memory.ts @@ -0,0 +1,280 @@ +import { readFile } from 'node:fs/promises'; +import { + CatalogSnapshotSchema, + type CacheStatus, + type CatalogQuery, + type CatalogSnapshot, + type Job, + type MetadataCandidate, + type SearchQuery, + type TitleDetail, +} from '@easy-stream/contracts'; +import { Value } from '@sinclair/typebox/value'; +import type { + AdminRecord, + AppRepository, + MediaItemForPlayback, + StoredAdminSession, + StoredPlaybackSession, +} from '../domain.js'; + +interface InMemoryRepositoryOptions { + titles?: TitleDetail[]; + cache?: Partial; +} + +export class InMemoryRepository implements AppRepository { + private readonly titles = new Map(); + private readonly playbackSessions = new Map(); + private readonly admins = new Map(); + private readonly adminSessions = new Map(); + private readonly jobs = new Map }>(); + private readonly cache: CacheStatus; + + constructor(options: InMemoryRepositoryOptions = {}) { + for (const title of options.titles ?? []) this.titles.set(title.id, structuredClone(title)); + this.cache = { + usedBytes: options.cache?.usedBytes ?? 0, + maxBytes: options.cache?.maxBytes ?? 2_147_483_648_000, + highWatermark: options.cache?.highWatermark ?? 0.85, + lowWatermark: options.cache?.lowWatermark ?? 0.75, + activePackages: options.cache?.activePackages ?? 0, + }; + } + + replaceCatalog(titles: TitleDetail[]): void { + this.titles.clear(); + for (const title of titles) this.titles.set(title.id, structuredClone(title)); + } + + async listCatalog(query: CatalogQuery) { + const limit = query.limit ?? 24; + const published = [...this.titles.values()] + .filter((title) => title.mediaItems.some((item) => item.published)) + .filter((title) => !query.kind || title.kind === query.kind) + .sort((left, right) => left.slug.localeCompare(right.slug)); + const cursorId = decodeCursor(query.cursor); + const start = cursorId ? Math.max(0, published.findIndex((title) => title.id === cursorId) + 1) : 0; + const page = published.slice(start, start + limit); + const next = published[start + limit]; + return { + items: page.map(toCard), + ...(next && page.at(-1) ? { nextCursor: encodeCursor(page.at(-1)!.id) } : {}), + }; + } + + async searchTitles(query: SearchQuery) { + const needle = normalizeSearch(query.q); + const limit = query.limit ?? 20; + return [...this.titles.values()] + .filter((title) => title.mediaItems.some((item) => item.published)) + .filter((title) => + [title.name.fa, title.name.en] + .filter((value): value is string => Boolean(value)) + .some((value) => normalizeSearch(value).includes(needle)), + ) + .slice(0, limit) + .map(toCard); + } + + async getTitleBySlug(slug: string): Promise { + const title = [...this.titles.values()].find( + (candidate) => candidate.slug === slug && candidate.mediaItems.some((item) => item.published), + ); + return title ? publicTitle(title) : undefined; + } + + async getMediaItem(id: string): Promise { + for (const title of this.titles.values()) { + const item = title.mediaItems.find((candidate) => candidate.id === id); + if (item) { + return { + id: item.id, + titleId: title.id, + durationSeconds: item.durationSeconds, + compatibility: item.compatibility, + published: item.published, + }; + } + } + return undefined; + } + + async setMediaPublished(mediaItemId: string, published: boolean): Promise { + for (const [titleId, title] of this.titles) { + const index = title.mediaItems.findIndex((item) => item.id === mediaItemId); + if (index < 0) continue; + const existing = title.mediaItems[index]; + if (!existing) return false; + const mediaItems = [...title.mediaItems]; + mediaItems[index] = { ...existing, published }; + this.titles.set(titleId, { + ...title, + playable: mediaItems.some((item) => item.published), + mediaItems, + updatedAt: new Date().toISOString(), + }); + return true; + } + return false; + } + + async applyTitleMetadata(titleId: string, metadata: MetadataCandidate): Promise { + const title = this.titles.get(titleId); + if (!title || title.kind !== metadata.kind) return false; + const { + posterUrl: _posterUrl, + backdropUrl: _backdropUrl, + year: _year, + name: _name, + synopsis: _synopsis, + ...unchanged + } = title; + this.titles.set(titleId, { + ...unchanged, + name: structuredClone(metadata.name), + synopsis: structuredClone(metadata.synopsis), + ...(metadata.posterUrl ? { posterUrl: metadata.posterUrl } : {}), + ...(metadata.backdropUrl ? { backdropUrl: metadata.backdropUrl } : {}), + ...(metadata.year !== undefined ? { year: metadata.year } : {}), + updatedAt: new Date().toISOString(), + }); + return true; + } + + async createPlaybackSession(session: StoredPlaybackSession): Promise { + this.playbackSessions.set(session.id, structuredClone(session)); + } + + async getPlaybackSession(id: string): Promise { + const session = this.playbackSessions.get(id); + return session ? structuredClone(session) : undefined; + } + + async updatePlaybackSession(session: StoredPlaybackSession): Promise { + this.playbackSessions.set(session.id, structuredClone(session)); + } + + async findAdminByEmail(email: string): Promise { + const normalized = email.trim().toLowerCase(); + const record = [...this.admins.values()].find((admin) => admin.email === normalized); + return record ? structuredClone(record) : undefined; + } + + async findAdminById(id: string): Promise { + const record = this.admins.get(id); + return record ? structuredClone(record) : undefined; + } + + async createAdmin(admin: AdminRecord): Promise { + const normalized = admin.email.trim().toLowerCase(); + if ([...this.admins.values()].some((entry) => entry.email === normalized)) return; + this.admins.set(admin.id, { ...structuredClone(admin), email: normalized }); + } + + async createAdminSession(session: StoredAdminSession): Promise { + this.adminSessions.set(session.id, structuredClone(session)); + } + + async findAdminSessionByTokenHash(tokenHash: string): Promise { + const session = [...this.adminSessions.values()].find((entry) => entry.tokenHash === tokenHash); + return session ? structuredClone(session) : undefined; + } + + async revokeAdminSession(id: string): Promise { + const session = this.adminSessions.get(id); + if (session) this.adminSessions.set(id, { ...session, revokedAt: new Date().toISOString() }); + } + + async createJob(job: Job, payload: Record): Promise { + this.jobs.set(job.id, { job: structuredClone(job), payload: structuredClone(payload) }); + } + + async listJobs(): Promise { + return [...this.jobs.values()] + .map(({ job }) => structuredClone(job)) + .sort((left, right) => right.createdAt.localeCompare(left.createdAt)); + } + + async findJob(id: string): Promise { + const entry = this.jobs.get(id); + return entry ? structuredClone(entry.job) : undefined; + } + + async retryJob(id: string): Promise { + const entry = this.jobs.get(id); + if (!entry || (entry.job.state !== 'FAILED' && entry.job.state !== 'CANCELLED')) return undefined; + const now = new Date().toISOString(); + const job: Job = { ...entry.job, state: 'QUEUED', progress: 0, error: null, updatedAt: now }; + this.jobs.set(id, { ...entry, job }); + return structuredClone(job); + } + + async getCacheStatus(): Promise { + return structuredClone(this.cache); + } +} + +export async function loadCatalogSnapshot(path: string): Promise { + let source: string; + try { + source = await readFile(path, 'utf8'); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; + throw error; + } + const parsed: unknown = JSON.parse(source); + if (!Value.Check(CatalogSnapshotSchema, parsed)) { + const errors = [...Value.Errors(CatalogSnapshotSchema, parsed)] + .map((error) => `${error.path || '/'} ${error.message}`) + .join('; '); + throw new Error(`Invalid catalog snapshot at ${path}: ${errors}`); + } + return parsed; +} + +function toCard(title: TitleDetail) { + const { synopsis: _synopsis, seasons: _seasons, mediaItems: _mediaItems, updatedAt: _updatedAt, ...card } = + title; + return card; +} + +function normalizeSearch(value: string): string { + return value.normalize('NFKC').trim().toLocaleLowerCase('fa-IR'); +} + +function publicTitle(title: TitleDetail): TitleDetail { + const mediaItems = title.mediaItems.filter((item) => item.published); + const { seasons: _seasons, resumeMediaItemId: _resumeMediaItemId, ...base } = title; + const seasonNumbers = [...new Set(mediaItems.map((item) => item.seasonNumber))].filter( + (value): value is number => value !== undefined, + ); + return structuredClone({ + ...base, + playable: mediaItems.length > 0, + ...(mediaItems[0] ? { resumeMediaItemId: mediaItems[0].id } : {}), + ...(seasonNumbers.length + ? { + seasons: seasonNumbers.map((number) => ({ + number, + episodeCount: mediaItems.filter((item) => item.seasonNumber === number).length, + })), + } + : {}), + mediaItems, + }); +} + +function encodeCursor(id: string): string { + return Buffer.from(JSON.stringify({ id })).toString('base64url'); +} + +function decodeCursor(cursor: string | undefined): string | undefined { + if (!cursor) return undefined; + try { + const value = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as { id?: unknown }; + return typeof value.id === 'string' ? value.id : undefined; + } catch { + return undefined; + } +} diff --git a/apps/api/src/repositories/postgres.ts b/apps/api/src/repositories/postgres.ts new file mode 100644 index 0000000..f260ea6 --- /dev/null +++ b/apps/api/src/repositories/postgres.ts @@ -0,0 +1,450 @@ +import type { + CacheStatus, + CatalogCard, + CatalogQuery, + Job, + MetadataCandidate, + SearchQuery, + TitleDetail, +} from '@easy-stream/contracts'; +import { + adminSessions, + admins, + jobs, + mediaItems, + mediaPackages, + playbackSessions, + titles, + type Database, +} from '@easy-stream/database'; +import { and, asc, desc, eq, ilike, inArray, or, sql } from 'drizzle-orm'; +import type { + AdminRecord, + AppRepository, + MediaItemForPlayback, + StoredAdminSession, + StoredPlaybackSession, +} from '../domain.js'; + +interface PostgresRepositoryOptions { + cacheMaxBytes: number; + cacheHighWatermark: number; + cacheLowWatermark: number; +} + +export class PostgresRepository implements AppRepository { + constructor( + private readonly db: Database, + private readonly options: PostgresRepositoryOptions, + ) {} + + async listCatalog(query: CatalogQuery) { + const limit = query.limit ?? 24; + const offset = decodeOffset(query.cursor); + const rows = await this.db + .select() + .from(titles) + .where(and(eq(titles.published, true), query.kind ? eq(titles.kind, query.kind) : undefined)) + .orderBy(asc(titles.slug), asc(titles.id)) + .limit(limit + 1) + .offset(offset); + const visible = rows.slice(0, limit); + const cards = await this.cardsForRows(visible); + return { + items: cards, + ...(rows.length > limit ? { nextCursor: encodeOffset(offset + limit) } : {}), + }; + } + + async searchTitles(query: SearchQuery): Promise { + const needle = `%${query.q.trim().replaceAll('%', '\\%').replaceAll('_', '\\_')}%`; + const rows = await this.db + .select() + .from(titles) + .where( + and( + eq(titles.published, true), + or(ilike(titles.nameFa, needle), ilike(titles.nameEn, needle)), + ), + ) + .orderBy(asc(titles.slug)) + .limit(query.limit ?? 20); + return this.cardsForRows(rows); + } + + async getTitleBySlug(slug: string): Promise { + const [title] = await this.db + .select() + .from(titles) + .where(and(eq(titles.slug, slug), eq(titles.published, true))) + .limit(1); + if (!title) return undefined; + const media = await this.db + .select() + .from(mediaItems) + .where(and(eq(mediaItems.titleId, title.id), eq(mediaItems.published, true))) + .orderBy(asc(mediaItems.seasonNumber), asc(mediaItems.episodeNumber), asc(mediaItems.id)); + return toTitleDetail(title, media); + } + + async getMediaItem(id: string): Promise { + const [row] = await this.db + .select({ media: mediaItems, titlePublished: titles.published }) + .from(mediaItems) + .innerJoin(titles, eq(mediaItems.titleId, titles.id)) + .where(eq(mediaItems.id, id)) + .limit(1); + if (!row) return undefined; + return { + id: row.media.id, + titleId: row.media.titleId, + durationSeconds: row.media.durationSeconds ?? 0, + compatibility: row.media.compatibility, + published: row.media.published && row.titlePublished, + }; + } + + async setMediaPublished(mediaItemId: string, published: boolean): Promise { + return this.db.transaction(async (transaction) => { + const [media] = await transaction + .update(mediaItems) + .set({ + published, + publishedAt: published ? new Date() : null, + updatedAt: new Date(), + }) + .where(eq(mediaItems.id, mediaItemId)) + .returning({ titleId: mediaItems.titleId }); + if (!media) return false; + const [countRow] = await transaction + .select({ count: sql`count(*)::int` }) + .from(mediaItems) + .where(and(eq(mediaItems.titleId, media.titleId), eq(mediaItems.published, true))); + const titlePublished = (countRow?.count ?? 0) > 0; + await transaction + .update(titles) + .set({ + published: titlePublished, + publishedAt: titlePublished ? new Date() : null, + updatedAt: new Date(), + }) + .where(eq(titles.id, media.titleId)); + return true; + }); + } + + async applyTitleMetadata(titleId: string, metadata: MetadataCandidate): Promise { + const [title] = await this.db + .update(titles) + .set({ + tmdbId: metadata.externalId, + nameFa: metadata.name.fa, + nameEn: metadata.name.en ?? null, + synopsisFa: metadata.synopsis.fa ?? null, + synopsisEn: metadata.synopsis.en ?? null, + posterUrl: metadata.posterUrl ?? null, + backdropUrl: metadata.backdropUrl ?? null, + releaseYear: metadata.year ?? null, + updatedAt: new Date(), + }) + .where(and(eq(titles.id, titleId), eq(titles.kind, metadata.kind))) + .returning({ id: titles.id }); + return Boolean(title); + } + + async createPlaybackSession(session: StoredPlaybackSession): Promise { + await this.db.insert(playbackSessions).values({ + id: session.id, + mediaItemId: session.mediaItemId, + ...(session.generationId ? { generationId: session.generationId } : {}), + state: session.state, + capabilities: session.capabilities, + ...(session.reasonCode ? { reasonCode: session.reasonCode } : {}), + ...(session.pollAfterMs ? { pollAfterMs: session.pollAfterMs } : {}), + responseJson: publicSessionDetails(session), + expiresAt: new Date(session.expiresAt), + }); + } + + async getPlaybackSession(id: string): Promise { + const [row] = await this.db + .select() + .from(playbackSessions) + .where(eq(playbackSessions.id, id)) + .limit(1); + if (!row) return undefined; + const details = row.responseJson as Partial; + return { + id: row.id, + mediaItemId: row.mediaItemId, + state: row.state, + capabilities: row.capabilities as StoredPlaybackSession['capabilities'], + expiresAt: row.expiresAt.toISOString(), + ...(row.generationId ? { generationId: row.generationId } : {}), + ...(row.reasonCode ? { reasonCode: row.reasonCode } : {}), + ...(row.pollAfterMs ? { pollAfterMs: row.pollAfterMs } : {}), + ...(details.manifestUrl ? { manifestUrl: details.manifestUrl } : {}), + ...(details.durationSeconds !== undefined ? { durationSeconds: details.durationSeconds } : {}), + ...(details.audioTracks ? { audioTracks: details.audioTracks } : {}), + ...(details.subtitleTracks ? { subtitleTracks: details.subtitleTracks } : {}), + }; + } + + async updatePlaybackSession(session: StoredPlaybackSession): Promise { + await this.db + .update(playbackSessions) + .set({ + state: session.state, + generationId: session.generationId ?? null, + reasonCode: session.reasonCode ?? null, + pollAfterMs: session.pollAfterMs ?? null, + responseJson: publicSessionDetails(session), + updatedAt: new Date(), + }) + .where(eq(playbackSessions.id, session.id)); + } + + async findAdminByEmail(email: string): Promise { + const [admin] = await this.db + .select() + .from(admins) + .where(eq(admins.email, email.trim().toLowerCase())) + .limit(1); + return admin ? toAdmin(admin) : undefined; + } + + async findAdminById(id: string): Promise { + const [admin] = await this.db.select().from(admins).where(eq(admins.id, id)).limit(1); + return admin ? toAdmin(admin) : undefined; + } + + async createAdmin(admin: AdminRecord): Promise { + await this.db + .insert(admins) + .values({ + id: admin.id, + email: admin.email.trim().toLowerCase(), + passwordHash: admin.passwordHash, + ...(admin.totpSecretEncrypted + ? { totpSecretEncrypted: admin.totpSecretEncrypted } + : {}), + disabled: admin.disabled, + }) + .onConflictDoNothing({ target: admins.email }); + } + + async createAdminSession(session: StoredAdminSession): Promise { + await this.db.insert(adminSessions).values({ + id: session.id, + adminId: session.adminId, + tokenHash: session.tokenHash, + csrfTokenHash: session.csrfTokenHash, + expiresAt: new Date(session.expiresAt), + }); + } + + async findAdminSessionByTokenHash(tokenHash: string): Promise { + const [session] = await this.db + .select() + .from(adminSessions) + .where(eq(adminSessions.tokenHash, tokenHash)) + .limit(1); + return session + ? { + id: session.id, + adminId: session.adminId, + tokenHash: session.tokenHash, + csrfTokenHash: session.csrfTokenHash, + expiresAt: session.expiresAt.toISOString(), + ...(session.revokedAt ? { revokedAt: session.revokedAt.toISOString() } : {}), + } + : undefined; + } + + async revokeAdminSession(id: string): Promise { + await this.db + .update(adminSessions) + .set({ revokedAt: new Date() }) + .where(eq(adminSessions.id, id)); + } + + async createJob(job: Job, payload: Record): Promise { + await this.db.insert(jobs).values({ + id: job.id, + type: job.type, + state: job.state, + progress: job.progress, + payload, + ...(job.error ? { error: job.error } : {}), + }); + } + + async listJobs(): Promise { + const rows = await this.db.select().from(jobs).orderBy(desc(jobs.createdAt)).limit(200); + return rows.map(toJob); + } + + async findJob(id: string): Promise { + const [job] = await this.db.select().from(jobs).where(eq(jobs.id, id)).limit(1); + return job ? toJob(job) : undefined; + } + + async retryJob(id: string): Promise { + const [job] = await this.db + .update(jobs) + .set({ state: 'QUEUED', progress: 0, error: null, updatedAt: new Date() }) + .where(and(eq(jobs.id, id), inArray(jobs.state, ['FAILED', 'CANCELLED']))) + .returning(); + return job ? toJob(job) : undefined; + } + + async getCacheStatus(): Promise { + const [summary] = await this.db + .select({ + usedBytes: sql`coalesce(sum(case when ${mediaPackages.cacheResident} then ${mediaPackages.sizeBytes} else 0 end), 0)::bigint`, + activePackages: sql`count(*) filter (where ${mediaPackages.state} = 'BUILDING')::int`, + }) + .from(mediaPackages); + return { + usedBytes: Number(summary?.usedBytes ?? 0), + maxBytes: this.options.cacheMaxBytes, + highWatermark: this.options.cacheHighWatermark, + lowWatermark: this.options.cacheLowWatermark, + activePackages: summary?.activePackages ?? 0, + }; + } + + private async cardsForRows(rows: (typeof titles.$inferSelect)[]): Promise { + if (rows.length === 0) return []; + const media = await this.db + .select() + .from(mediaItems) + .where(and(inArray(mediaItems.titleId, rows.map((row) => row.id)), eq(mediaItems.published, true))) + .orderBy(asc(mediaItems.seasonNumber), asc(mediaItems.episodeNumber), asc(mediaItems.id)); + return rows.map((title) => + toCatalogCard( + title, + media.filter((item) => item.titleId === title.id), + ), + ); + } +} + +function toCatalogCard( + title: typeof titles.$inferSelect, + media: (typeof mediaItems.$inferSelect)[], +): CatalogCard { + const first = media[0]; + return { + id: title.id, + slug: title.slug, + kind: title.kind, + name: localizedRequired(title.nameFa, title.nameEn), + playable: media.length > 0, + ...(title.posterUrl ? { posterUrl: title.posterUrl } : {}), + ...(title.backdropUrl ? { backdropUrl: title.backdropUrl } : {}), + ...(title.releaseYear !== null ? { year: title.releaseYear } : {}), + ...(first ? { resumeMediaItemId: first.id } : {}), + }; +} + +function toTitleDetail( + title: typeof titles.$inferSelect, + media: (typeof mediaItems.$inferSelect)[], +): TitleDetail { + const card = toCatalogCard( + title, + media.filter((item) => item.published), + ); + const seasonNumbers = [...new Set(media.map((item) => item.seasonNumber).filter(isNumber))]; + return { + ...card, + synopsis: { + ...(title.synopsisFa ? { fa: title.synopsisFa } : {}), + ...(title.synopsisEn ? { en: title.synopsisEn } : {}), + }, + ...(seasonNumbers.length > 0 + ? { + seasons: seasonNumbers.map((number) => ({ + number, + episodeCount: media.filter((item) => item.seasonNumber === number).length, + })), + } + : {}), + mediaItems: media.map((item) => ({ + id: item.id, + kind: item.kind, + ...(item.seasonNumber !== null ? { seasonNumber: item.seasonNumber } : {}), + ...(item.episodeNumber !== null ? { episodeNumber: item.episodeNumber } : {}), + ...(item.nameFa || item.nameEn + ? { + name: { + ...(item.nameFa ? { fa: item.nameFa } : {}), + ...(item.nameEn ? { en: item.nameEn } : {}), + }, + } + : {}), + durationSeconds: item.durationSeconds ?? 0, + compatibility: item.compatibility, + published: item.published, + })), + updatedAt: title.updatedAt.toISOString(), + }; +} + +function localizedRequired(fa: string | null, en: string | null) { + return { fa: fa ?? en ?? 'بدون عنوان', ...(en ? { en } : {}) }; +} + +function toAdmin(admin: typeof admins.$inferSelect): AdminRecord { + return { + id: admin.id, + email: admin.email, + passwordHash: admin.passwordHash, + disabled: admin.disabled, + ...(admin.totpSecretEncrypted ? { totpSecretEncrypted: admin.totpSecretEncrypted } : {}), + }; +} + +function toJob(job: typeof jobs.$inferSelect): Job { + return { + id: job.id, + type: job.type, + state: job.state, + progress: job.progress, + error: job.error, + createdAt: job.createdAt.toISOString(), + updatedAt: job.updatedAt.toISOString(), + }; +} + +function publicSessionDetails(session: StoredPlaybackSession): Record { + return { + ...(session.manifestUrl ? { manifestUrl: session.manifestUrl } : {}), + ...(session.durationSeconds !== undefined ? { durationSeconds: session.durationSeconds } : {}), + ...(session.audioTracks ? { audioTracks: session.audioTracks } : {}), + ...(session.subtitleTracks ? { subtitleTracks: session.subtitleTracks } : {}), + }; +} + +function isNumber(value: number | null): value is number { + return value !== null; +} + +function encodeOffset(offset: number): string { + return Buffer.from(JSON.stringify({ offset })).toString('base64url'); +} + +function decodeOffset(cursor: string | undefined): number { + if (!cursor) return 0; + try { + const value = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as { + offset?: unknown; + }; + return typeof value.offset === 'number' && Number.isSafeInteger(value.offset) && value.offset >= 0 + ? value.offset + : 0; + } catch { + return 0; + } +} diff --git a/apps/api/src/server.ts b/apps/api/src/server.ts new file mode 100644 index 0000000..75853b6 --- /dev/null +++ b/apps/api/src/server.ts @@ -0,0 +1,31 @@ +import { buildApp } from './app.js'; +import { loadConfig } from './config.js'; + +for (const candidate of [process.env.ENV_FILE, '.env', '../../.env']) { + if (!candidate) continue; + try { + process.loadEnvFile?.(candidate); + break; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } +} + +const config = loadConfig(); +const app = await buildApp({ config }); + +const shutdown = async (signal: string) => { + app.log.info({ signal }, 'shutting down'); + await app.close(); + process.exitCode = 0; +}; + +process.once('SIGINT', () => void shutdown('SIGINT')); +process.once('SIGTERM', () => void shutdown('SIGTERM')); + +try { + await app.listen({ host: config.host, port: config.port }); +} catch (error) { + app.log.fatal({ err: error }, 'API startup failed'); + process.exitCode = 1; +} diff --git a/apps/api/src/services/admin.ts b/apps/api/src/services/admin.ts new file mode 100644 index 0000000..8e92a71 --- /dev/null +++ b/apps/api/src/services/admin.ts @@ -0,0 +1,228 @@ +import { randomUUID } from 'node:crypto'; +import { argon2id, hash, verify } from 'argon2'; +import type { + AdminLogin, + AdminSessionResponse, + Job, + MetadataMatchBody, + MetadataSearchQuery, +} from '@easy-stream/contracts'; +import type { ApiConfig } from '../config.js'; +import { randomToken, sha256 } from '../crypto.js'; +import type { + AdminRecord, + AppRepository, + MediaCommandPublisher, + MediaPreparationService, + MetadataProvider, + PasswordHasher, + TotpVerifier, +} from '../domain.js'; +import { AppError } from '../errors.js'; + +export class Argon2PasswordHasher implements PasswordHasher { + async hash(password: string): Promise { + return hash(password, { + type: argon2id, + memoryCost: 65_536, + timeCost: 3, + parallelism: 1, + }); + } + + async verify(passwordHash: string, password: string): Promise { + try { + return await verify(passwordHash, password); + } catch { + return false; + } + } +} + +export class DenyEncryptedTotpVerifier implements TotpVerifier { + async verify(): Promise { + return false; + } +} + +interface AdminPrincipal { + admin: AdminRecord; + sessionId: string; +} + +export class AdminService { + private dummyPasswordHash?: string; + + constructor( + private readonly repository: AppRepository, + private readonly commands: MediaCommandPublisher, + private readonly media: MediaPreparationService, + private readonly metadata: MetadataProvider, + private readonly passwordHasher: PasswordHasher, + private readonly totpVerifier: TotpVerifier, + private readonly config: ApiConfig, + ) {} + + async initialize(): Promise { + this.dummyPasswordHash = await this.passwordHasher.hash(randomToken()); + if (!this.config.adminBootstrapEmail || !this.config.adminBootstrapPassword) return; + const existing = await this.repository.findAdminByEmail(this.config.adminBootstrapEmail); + if (existing) return; + await this.repository.createAdmin({ + id: randomUUID(), + email: this.config.adminBootstrapEmail, + passwordHash: await this.passwordHasher.hash(this.config.adminBootstrapPassword), + disabled: false, + }); + } + + async login(input: AdminLogin): Promise<{ + response: AdminSessionResponse; + rawToken: string; + }> { + const admin = await this.repository.findAdminByEmail(input.email); + const validPassword = await this.passwordHasher.verify( + admin?.passwordHash ?? this.dummyPasswordHash ?? '$argon2id$invalid', + input.password, + ); + if (!admin || !validPassword || admin.disabled) throw invalidCredentials(); + if ( + admin.totpSecretEncrypted && + (!input.totp || !(await this.totpVerifier.verify(admin.totpSecretEncrypted, input.totp))) + ) { + throw invalidCredentials(); + } + + const rawToken = randomToken(); + const csrfToken = randomToken(); + const expiresAt = new Date( + Date.now() + this.config.adminSessionTtlSeconds * 1000, + ).toISOString(); + await this.repository.createAdminSession({ + id: randomUUID(), + adminId: admin.id, + tokenHash: sha256(rawToken), + csrfTokenHash: sha256(csrfToken), + expiresAt, + }); + return { + rawToken, + response: { + admin: { id: admin.id, email: admin.email }, + csrfToken, + expiresAt, + }, + }; + } + + async authenticate(rawToken: string | undefined, csrfToken?: string): Promise { + if (!rawToken) throw new AppError(401, 'UNAUTHORIZED', 'Administrator authentication required'); + const session = await this.repository.findAdminSessionByTokenHash(sha256(rawToken)); + if ( + !session || + session.revokedAt || + Date.parse(session.expiresAt) <= Date.now() || + (csrfToken !== undefined && sha256(csrfToken) !== session.csrfTokenHash) + ) { + throw new AppError(401, 'UNAUTHORIZED', 'Administrator session is invalid or expired'); + } + const admin = await this.repository.findAdminById(session.adminId); + if (!admin || admin.disabled) { + throw new AppError(401, 'UNAUTHORIZED', 'Administrator session is invalid or expired'); + } + return { admin, sessionId: session.id }; + } + + async logout(rawToken: string | undefined, csrfToken: string | undefined): Promise { + const principal = await this.authenticate(rawToken, csrfToken); + await this.repository.revokeAdminSession(principal.sessionId); + } + + async startScan(full: boolean): Promise { + const now = new Date().toISOString(); + const job: Job = { + id: randomUUID(), + type: 'ARCHIVE_SCAN', + state: 'QUEUED', + progress: 0, + error: null, + createdAt: now, + updatedAt: now, + }; + await this.repository.createJob(job, { full }); + await this.commands.publish({ type: 'archive.scan.requested', jobId: job.id, full }); + return job; + } + + async setPublished(mediaItemId: string, published: boolean): Promise { + const item = await this.repository.getMediaItem(mediaItemId); + if (!item) throw new AppError(404, 'NOT_FOUND', 'Media item not found'); + if (published && (item.compatibility === 'INVALID' || item.compatibility === 'HOLD_HDR')) { + throw new AppError(409, 'CONFLICT', 'This media item is not eligible for publication'); + } + if ( + published && + (item.compatibility === 'AUDIO_TRANSCODE' || item.compatibility === 'VIDEO_TRANSCODE') + ) { + const preparation = await this.media.getStatus({ + sessionId: randomUUID(), + mediaItem: item, + }); + if (preparation.state !== 'READY' && !preparation.playable) { + throw new AppError( + 409, + 'CONFLICT', + 'The browser-compatible representation must be ready before publication', + ); + } + } + if (!(await this.repository.setMediaPublished(mediaItemId, published))) { + throw new AppError(404, 'NOT_FOUND', 'Media item not found'); + } + await this.commands.publish({ + type: 'media.publication.changed', + mediaItemId, + published, + }); + } + + async retryJob(jobId: string): Promise { + const existing = await this.repository.findJob(jobId); + if (existing !== undefined && existing.type !== 'ARCHIVE_SCAN') { + throw new AppError(409, 'CONFLICT', `Retry is not implemented for job type ${existing.type}`); + } + const job = await this.repository.retryJob(jobId); + if (!job) throw new AppError(409, 'CONFLICT', 'Only failed or cancelled jobs can be retried'); + // A full scan is the conservative retry when the public Job contract does not expose + // the original private payload. + await this.commands.publish({ type: 'archive.scan.requested', jobId: job.id, full: true }); + return job; + } + + async evict(generationId: string): Promise { + await this.commands.publish({ type: 'package.eviction.requested', generationId }); + } + + async searchMetadata(query: MetadataSearchQuery) { + return this.metadata.search({ + query: query.q, + kind: query.kind, + ...(query.year !== undefined ? { year: query.year } : {}), + }); + } + + async matchMetadata(titleId: string, body: MetadataMatchBody) { + const candidate = await this.metadata.getDetails({ + externalId: body.externalId, + kind: body.kind, + }); + if (!(await this.repository.applyTitleMetadata(titleId, candidate))) { + throw new AppError(404, 'NOT_FOUND', 'Title not found or title kind does not match'); + } + return candidate; + } +} + +function invalidCredentials(): AppError { + return new AppError(401, 'UNAUTHORIZED', 'Invalid email, password, or verification code'); +} diff --git a/apps/api/src/services/cache-status.ts b/apps/api/src/services/cache-status.ts new file mode 100644 index 0000000..d471728 --- /dev/null +++ b/apps/api/src/services/cache-status.ts @@ -0,0 +1,226 @@ +import { constants } from 'node:fs'; +import { lstat, open, opendir } from 'node:fs/promises'; +import path from 'node:path'; +import type { CacheStatus } from '@easy-stream/contracts'; +import { Type } from '@sinclair/typebox'; +import { Value } from '@sinclair/typebox/value'; + +const CACHE_METADATA = '.cache-entry.json'; +const MAX_METADATA_BYTES = 64 * 1024; +const CacheEntryMetadataSchema = Type.Object( + { + version: Type.Literal(1), + key: Type.String({ minLength: 8, maxLength: 128, pattern: '^[a-z0-9][a-z0-9._-]+$' }), + bytes: Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }), + lastAccessedAt: Type.String({ minLength: 1, maxLength: 64 }), + protectedUntil: Type.Optional(Type.String({ minLength: 1, maxLength: 64 })), + active: Type.Boolean(), + building: Type.Boolean(), + pinned: Type.Boolean(), + }, + { additionalProperties: false }, +); + +interface CacheEntryMetadata { + version: 1; + key: string; + bytes: number; + lastAccessedAt: string; + protectedUntil?: string; + active: boolean; + building: boolean; + pinned: boolean; +} + +export interface CacheStatusService { + getStatus(): Promise; +} + +export interface FilesystemCacheStatusOptions { + cacheRoot: string; + maxBytes: number; + highWatermark: number; + lowWatermark: number; +} + +/** Reads the worker-owned cache projection without mutating or walking media payloads. */ +export class FilesystemCacheStatusService implements CacheStatusService { + private readonly root: string; + + constructor(private readonly options: FilesystemCacheStatusOptions) { + this.root = path.resolve(options.cacheRoot); + } + + async getStatus(): Promise { + if (!(await managedDirectoryExists(this.root, 'cache root'))) return this.result(0, 0); + const generations = await readGenerations(path.join(this.root, 'generations')); + const fontStore = path.join(this.root, 'assets', 'fonts', 'sha256'); + const fontBytes = await managedSubdirectoryExists( + this.root, + ['assets', 'fonts', 'sha256'], + 'global font store', + ) ? await readFontStoreBytes(fontStore) : 0; + return this.result( + safeAdd(generations.bytes, fontBytes, 'cache usage'), + generations.building, + ); + } + + private result(usedBytes: number, activePackages: number): CacheStatus { + return { + usedBytes, + maxBytes: this.options.maxBytes, + highWatermark: this.options.highWatermark, + lowWatermark: this.options.lowWatermark, + activePackages, + }; + } +} + +async function readGenerations( + directory: string, +): Promise<{ bytes: number; building: number }> { + if (!(await managedDirectoryExists(directory, 'cache generations root'))) { + return { bytes: 0, building: 0 }; + } + let bytes = 0; + let building = 0; + const handle = await opendir(directory); + for await (const entry of handle) { + const candidate = path.join(directory, entry.name); + if (entry.isSymbolicLink()) throw new Error(`Symlink found in cache generations: ${candidate}`); + if (!entry.isDirectory()) continue; + let metadata: CacheEntryMetadata | undefined; + try { + metadata = await readCacheMetadata(path.join(candidate, CACHE_METADATA), entry.name); + } catch (error) { + if (isMissing(error)) continue; + throw error; + } + if (metadata === undefined) continue; + bytes = safeAdd(bytes, metadata.bytes, 'generation cache usage'); + if (metadata.building) building += 1; + } + return { bytes, building }; +} + +async function readCacheMetadata( + metadataPath: string, + expectedKey: string, +): Promise { + let handle: Awaited>; + try { + handle = await open(metadataPath, constants.O_RDONLY | constants.O_NOFOLLOW); + } catch (error) { + if (isMissing(error)) return undefined; + if ((error as NodeJS.ErrnoException).code === 'ELOOP') { + throw new Error(`Symlink found at cache metadata: ${metadataPath}`); + } + throw error; + } + try { + const details = await handle.stat(); + if (!details.isFile() || details.size > MAX_METADATA_BYTES) { + throw new Error(`Cache metadata is not a bounded regular file: ${metadataPath}`); + } + let parsed: unknown; + try { + parsed = JSON.parse(await handle.readFile('utf8')); + } catch (error) { + throw new Error(`Invalid cache metadata JSON: ${metadataPath}`, { cause: error }); + } + if (!Value.Check(CacheEntryMetadataSchema, parsed)) { + throw new Error(`Invalid cache metadata shape: ${metadataPath}`); + } + const metadata = parsed as CacheEntryMetadata; + const archivedGeneration = expectedKey.match( + /^failed-[0-9]{10,16}-([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$/u, + )?.[1]; + if ( + (metadata.key !== expectedKey && metadata.key !== archivedGeneration) + || !Number.isFinite(Date.parse(metadata.lastAccessedAt)) + ) { + throw new Error(`Cache metadata does not match its generation: ${metadataPath}`); + } + if ( + metadata.protectedUntil !== undefined + && !Number.isFinite(Date.parse(metadata.protectedUntil)) + ) { + throw new Error(`Cache metadata has an invalid protection timestamp: ${metadataPath}`); + } + // If packaging could not rewrite metadata after archiving a failed build, its original + // UUID key/building flag can remain. The exact archive name relationship makes this safe + // to count as diagnostic disk usage without reporting a live build forever. + return archivedGeneration === undefined ? metadata : { ...metadata, building: false }; + } finally { + await handle.close(); + } +} + +async function readFontStoreBytes(directory: string): Promise { + let bytes = 0; + const handle = await opendir(directory); + for await (const entry of handle) { + const candidate = path.join(directory, entry.name); + if (entry.isSymbolicLink()) throw new Error(`Symlink found in global font store: ${candidate}`); + if (!entry.isFile()) { + throw new Error(`Non-regular entry found in global font store: ${candidate}`); + } + let file: Awaited>; + try { + file = await open(candidate, constants.O_RDONLY | constants.O_NOFOLLOW); + } catch (error) { + // Font pruning can remove an entry after opendir returned it. + if (isMissing(error)) continue; + if ((error as NodeJS.ErrnoException).code === 'ELOOP') { + throw new Error(`Symlink found in global font store: ${candidate}`); + } + throw error; + } + try { + const details = await file.stat(); + if (!details.isFile()) throw new Error(`Non-regular entry found in global font store: ${candidate}`); + bytes = safeAdd(bytes, details.size, 'global font cache usage'); + } finally { + await file.close(); + } + } + return bytes; +} + +async function managedSubdirectoryExists( + root: string, + components: readonly string[], + label: string, +): Promise { + let current = root; + for (const component of components) { + current = path.join(current, component); + if (!(await managedDirectoryExists(current, label))) return false; + } + return true; +} + +async function managedDirectoryExists(directory: string, label: string): Promise { + let details: Awaited>; + try { + details = await lstat(directory); + } catch (error) { + if (isMissing(error)) return false; + throw error; + } + if (details.isSymbolicLink() || !details.isDirectory()) { + throw new Error(`Managed ${label} is not a regular directory: ${directory}`); + } + return true; +} + +function safeAdd(left: number, right: number, label: string): number { + const result = left + right; + if (!Number.isSafeInteger(result) || result < 0) throw new Error(`${label} exceeds safe limits`); + return result; +} + +function isMissing(error: unknown): boolean { + return (error as NodeJS.ErrnoException).code === 'ENOENT'; +} diff --git a/apps/api/src/services/media-preparation.ts b/apps/api/src/services/media-preparation.ts new file mode 100644 index 0000000..620a97a --- /dev/null +++ b/apps/api/src/services/media-preparation.ts @@ -0,0 +1,239 @@ +import { appendFile, mkdir, readFile } from 'node:fs/promises'; +import { dirname } from 'node:path'; +import { + CACHE_GENERATION_LEASES_KEY, + PackageRegistrySchema, + type MediaCommand, + type PackageRegistry, +} from '@easy-stream/contracts'; +import { Value } from '@sinclair/typebox/value'; +import { Queue, type ConnectionOptions } from 'bullmq'; +import type { + MediaCommandPublisher, + MediaPreparation, + MediaPreparationService, +} from '../domain.js'; + +export class JsonlMediaCommandPublisher implements MediaCommandPublisher { + constructor(private readonly path: string) {} + + async publish(command: MediaCommand): Promise { + await mkdir(dirname(this.path), { recursive: true }); + await appendFile(this.path, `${JSON.stringify(command)}\n`, { + encoding: 'utf8', + mode: 0o600, + }); + } +} + +export class InMemoryMediaCommandPublisher implements MediaCommandPublisher { + readonly commands: MediaCommand[] = []; + + async publish(command: MediaCommand): Promise { + this.commands.push(structuredClone(command)); + } +} + +export class FileMediaPreparationService implements MediaPreparationService { + private readonly requested = new Set(); + + constructor( + private readonly registryPath: string, + private readonly publisher: MediaCommandPublisher, + ) {} + + async prepare(input: Parameters[0]) { + const status = await this.find(input.mediaItem.id); + if (status) { + if (status.playable || status.state === 'READY' || status.state === 'FAILED') { + this.requested.delete(input.mediaItem.id); + } + await this.recordCacheAccess(input, status); + return status; + } + if (!this.requested.has(input.mediaItem.id)) { + this.requested.add(input.mediaItem.id); + try { + await this.publisher.publish({ + type: 'media.playback.requested', + sessionId: input.sessionId, + mediaItemId: input.mediaItem.id, + }); + } catch (error) { + this.requested.delete(input.mediaItem.id); + throw error; + } + } + return { + state: 'PREPARING' as const, + playable: false, + pollAfterMs: 1500, + reasonCode: 'PACKAGE_REQUESTED', + }; + } + + async getStatus(input: Parameters[0]) { + const status = await this.find(input.mediaItem.id); + if (status?.playable || status?.state === 'READY' || status?.state === 'FAILED') { + this.requested.delete(input.mediaItem.id); + } + const result = status ?? { + state: 'PREPARING' as const, + playable: false, + pollAfterMs: 1500, + reasonCode: 'PACKAGE_REQUESTED', + }; + await this.recordCacheAccess(input, result); + return result; + } + + private async recordCacheAccess( + input: { sessionId: string; protectUntil?: string }, + status: MediaPreparation, + ): Promise { + if (input.protectUntil === undefined || !status.playable || !status.generationId + || !status.manifestPath?.startsWith('/media/generations/')) return; + await this.publisher.publish({ + type: 'cache.generation.accessed', + sessionId: input.sessionId, + generationId: status.generationId, + accessedAt: new Date().toISOString(), + protectedUntil: input.protectUntil, + }); + } + + private async find(mediaItemId: string): Promise { + const registry = await readPackageRegistry(this.registryPath); + const entry = registry?.packages.find((candidate) => candidate.mediaItemId === mediaItemId); + if (!entry) return undefined; + return { + state: entry.state, + playable: entry.playable, + ...(entry.generationId ? { generationId: entry.generationId } : {}), + ...(entry.manifestPath ? { manifestPath: entry.manifestPath } : {}), + ...(entry.reasonCode ? { reasonCode: entry.reasonCode } : {}), + ...(entry.pollAfterMs ? { pollAfterMs: entry.pollAfterMs } : {}), + ...(entry.durationSeconds !== undefined ? { durationSeconds: entry.durationSeconds } : {}), + ...(entry.audioTracks ? { audioTracks: entry.audioTracks } : {}), + ...(entry.subtitleTracks ? { subtitleTracks: entry.subtitleTracks } : {}), + }; + } +} + +export async function readPackageRegistry(path: string): Promise { + let source: string; + try { + source = await readFile(path, 'utf8'); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; + throw error; + } + const parsed: unknown = JSON.parse(source); + if (!Value.Check(PackageRegistrySchema, parsed)) { + const errors = [...Value.Errors(PackageRegistrySchema, parsed)] + .map((error) => `${error.path || '/'} ${error.message}`) + .join('; '); + throw new Error(`Invalid package registry at ${path}: ${errors}`); + } + return parsed; +} + +export class BullMqMediaBridge implements MediaPreparationService, MediaCommandPublisher { + private readonly fileStatus: FileMediaPreparationService; + private readonly queue: Queue; + private leaseCommandReady?: Promise; + + constructor( + redisUrl: string, + registryPath: string, + private readonly profile: string, + ) { + this.queue = new Queue('easy-stream-media', { + connection: redisConnection(redisUrl), + defaultJobOptions: { + attempts: 2, + backoff: { type: 'exponential', delay: 1000 }, + removeOnComplete: { age: 3600, count: 2000 }, + removeOnFail: { age: 86_400, count: 2000 }, + }, + }); + this.fileStatus = new FileMediaPreparationService(registryPath, this); + } + + async prepare(input: Parameters[0]) { + return this.fileStatus.prepare(input); + } + + async getStatus(input: Parameters[0]) { + return this.fileStatus.getStatus(input); + } + + async publish(command: MediaCommand): Promise { + if (command.type === 'cache.generation.accessed') { + const protectedUntil = Date.parse(command.protectedUntil); + if (!Number.isFinite(protectedUntil)) throw new Error('Invalid cache lease expiration'); + const client = await this.queue.client; + this.leaseCommandReady ??= Promise.resolve(client.defineCommand( + 'easyStreamExtendCacheLease', + { + numberOfKeys: 1, + lua: "return redis.call('ZADD', KEYS[1], 'GT', ARGV[1], ARGV[2])", + }, + )); + await this.leaseCommandReady; + await client.runCommand('easyStreamExtendCacheLease', [ + CACHE_GENERATION_LEASES_KEY, + protectedUntil, + command.generationId, + ]); + } + const jobId = commandJobId(command, this.profile); + if (command.type === 'archive.scan.requested') { + const existing = await this.queue.getJob(jobId); + if (existing !== undefined && await existing.getState() === 'failed') { + await existing.retry('failed'); + return; + } + } + await this.queue.add(command.type, command, { + jobId, + ...(['media.playback.requested', 'cache.generation.accessed'].includes(command.type) + ? { removeOnComplete: true } + : {}), + }); + } + + async close(): Promise { + await this.queue.close(); + } +} + +function redisConnection(redisUrl: string): ConnectionOptions { + const url = new URL(redisUrl); + const database = url.pathname.length > 1 ? Number(url.pathname.slice(1)) : 0; + if (!Number.isInteger(database) || database < 0) throw new Error('REDIS_URL has an invalid database'); + return { + host: url.hostname, + port: url.port ? Number(url.port) : 6379, + ...(url.username ? { username: decodeURIComponent(url.username) } : {}), + ...(url.password ? { password: decodeURIComponent(url.password) } : {}), + db: database, + ...(url.protocol === 'rediss:' ? { tls: {} } : {}), + maxRetriesPerRequest: null, + }; +} + +function commandJobId(command: MediaCommand, profile: string): string { + switch (command.type) { + case 'media.playback.requested': + return `playback-${command.mediaItemId}-${profile}`; + case 'archive.scan.requested': + return `scan-${command.jobId}`; + case 'media.publication.changed': + return `publication-${command.mediaItemId}-${command.published ? 'on' : 'off'}-${Date.now()}`; + case 'package.eviction.requested': + return `eviction-${command.generationId}`; + case 'cache.generation.accessed': + return `cache-access-${command.sessionId}-${command.generationId}`; + } +} diff --git a/apps/api/src/services/playback.ts b/apps/api/src/services/playback.ts new file mode 100644 index 0000000..cd133c5 --- /dev/null +++ b/apps/api/src/services/playback.ts @@ -0,0 +1,152 @@ +import { randomUUID } from 'node:crypto'; +import type { + ClientCapabilities, + CreatePlaybackSession, + PlaybackSession, +} from '@easy-stream/contracts'; +import type { ApiConfig } from '../config.js'; +import type { + AppRepository, + MediaItemForPlayback, + MediaPreparation, + MediaPreparationService, + StoredPlaybackSession, +} from '../domain.js'; +import { AppError } from '../errors.js'; + +export class PlaybackService { + constructor( + private readonly repository: AppRepository, + private readonly media: MediaPreparationService, + private readonly config: ApiConfig, + ) {} + + async create(input: CreatePlaybackSession): Promise { + const item = await this.requirePlayableMedia(input.mediaItemId); + const now = Date.now(); + const base: StoredPlaybackSession = { + id: randomUUID(), + mediaItemId: item.id, + state: 'PREPARING', + capabilities: input.clientCapabilities, + expiresAt: new Date(now + this.config.playbackTtlSeconds * 1000).toISOString(), + }; + + if (!supportsHls(input.clientCapabilities)) { + const unsupported: StoredPlaybackSession = { + ...base, + state: 'UNSUPPORTED_CLIENT', + reasonCode: 'HLS_MSE_UNAVAILABLE', + }; + await this.repository.createPlaybackSession(unsupported); + return unsupported; + } + if (item.compatibility === 'HOLD_HDR') { + const unsupported: StoredPlaybackSession = { + ...base, + state: 'UNSUPPORTED_CLIENT', + reasonCode: 'HDR_UNSUPPORTED_V1', + }; + await this.repository.createPlaybackSession(unsupported); + return unsupported; + } + if (item.compatibility === 'INVALID') { + const failed: StoredPlaybackSession = { + ...base, + state: 'FAILED', + reasonCode: 'MEDIA_NOT_VALIDATED', + }; + await this.repository.createPlaybackSession(failed); + return failed; + } + + await this.repository.createPlaybackSession(base); + const preparation = await this.media.prepare({ + sessionId: base.id, + mediaItem: item, + capabilities: input.clientCapabilities, + protectUntil: base.expiresAt, + }); + const session = this.mergePreparation(base, preparation); + await this.repository.updatePlaybackSession(session); + return session; + } + + async get(id: string): Promise { + const session = await this.repository.getPlaybackSession(id); + if (!session || Date.parse(session.expiresAt) <= Date.now()) { + throw new AppError(404, 'NOT_FOUND', 'Playback session not found'); + } + if (session.state !== 'PREPARING') return session; + const item = await this.requirePlayableMedia(session.mediaItemId); + const preparation = await this.media.getStatus({ + sessionId: id, + mediaItem: item, + protectUntil: session.expiresAt, + }); + const updated = this.mergePreparation(session, preparation); + await this.repository.updatePlaybackSession(updated); + return updated; + } + + toPublic(session: StoredPlaybackSession): PlaybackSession { + const { capabilities: _capabilities, ...publicSession } = session; + return publicSession; + } + + private async requirePlayableMedia(id: string): Promise { + const item = await this.repository.getMediaItem(id); + if (!item || !item.published) { + throw new AppError(404, 'NOT_FOUND', 'Media item not found'); + } + return item; + } + + private mergePreparation( + session: StoredPlaybackSession, + preparation: MediaPreparation, + ): StoredPlaybackSession { + if (preparation.state === 'READY' || (preparation.state === 'PREPARING' && preparation.playable)) { + if (!preparation.generationId || !preparation.manifestPath) { + throw new AppError(500, 'INTERNAL_ERROR', 'Ready media preparation is incomplete'); + } + const expectedPrefix = new RegExp( + `^/media/(?:derived/)?generations/${preparation.generationId}/`, + ); + if (!expectedPrefix.test(preparation.manifestPath)) { + throw new AppError(500, 'INTERNAL_ERROR', 'Media preparation returned an unsafe path'); + } + return { + ...session, + state: 'READY', + generationId: preparation.generationId, + manifestUrl: publicMediaUrl(this.config.mediaPublicBaseUrl, preparation.manifestPath), + durationSeconds: preparation.durationSeconds ?? 0, + audioTracks: preparation.audioTracks ?? [], + subtitleTracks: preparation.subtitleTracks ?? [], + }; + } + return { + ...session, + state: preparation.state, + ...(preparation.pollAfterMs ? { pollAfterMs: preparation.pollAfterMs } : {}), + ...(preparation.reasonCode ? { reasonCode: preparation.reasonCode } : {}), + }; + } +} + +function supportsHls(capabilities: ClientCapabilities): boolean { + return capabilities.nativeHls || (capabilities.mse && capabilities.hlsJs); +} + +function publicMediaUrl(baseUrl: string, manifestPath: string): string { + const base = new URL(baseUrl); + const mediaBasePath = base.pathname.replace(/\/$/, ''); + if (!manifestPath.startsWith(`${mediaBasePath}/`) && mediaBasePath !== '/media') { + throw new AppError(500, 'INTERNAL_ERROR', 'Manifest path does not match media base URL'); + } + base.pathname = manifestPath; + base.search = ''; + base.hash = ''; + return base.toString(); +} diff --git a/apps/api/src/services/tmdb.ts b/apps/api/src/services/tmdb.ts new file mode 100644 index 0000000..da63c0a --- /dev/null +++ b/apps/api/src/services/tmdb.ts @@ -0,0 +1,216 @@ +import type { MetadataCandidate } from '@easy-stream/contracts'; +import type { ApiConfig } from '../config.js'; +import type { MetadataProvider } from '../domain.js'; +import { AppError } from '../errors.js'; + +type Fetch = typeof globalThis.fetch; + +interface TmdbListResponse { + results?: unknown[]; +} + +export class DisabledMetadataProvider implements MetadataProvider { + async search(): Promise { + throw disabledError(); + } + + async getDetails(): Promise { + throw disabledError(); + } +} + +export class TmdbMetadataProvider implements MetadataProvider { + constructor( + private readonly token: string, + private readonly options: { + baseUrl: string; + timeoutMs: number; + maxRetries: number; + }, + private readonly fetchImpl: Fetch = globalThis.fetch, + ) {} + + async search(input: { + query: string; + kind: 'MOVIE' | 'SERIES'; + year?: number; + }): Promise { + const mediaPath = input.kind === 'MOVIE' ? 'movie' : 'tv'; + const query: Record = { + query: input.query, + include_adult: 'false', + language: 'fa-IR', + }; + if (input.year !== undefined) { + query[input.kind === 'MOVIE' ? 'year' : 'first_air_date_year'] = String(input.year); + } + let result = await this.request(`/search/${mediaPath}`, query); + if (!Array.isArray(result.results) || result.results.length === 0) { + result = await this.request(`/search/${mediaPath}`, { + ...query, + language: 'en-US', + }); + } + return (result.results ?? []) + .map((entry) => toCandidate(entry, input.kind)) + .filter((entry): entry is MetadataCandidate => Boolean(entry)) + .slice(0, 20); + } + + async getDetails(input: { + externalId: number; + kind: 'MOVIE' | 'SERIES'; + }): Promise { + const mediaPath = input.kind === 'MOVIE' ? 'movie' : 'tv'; + const fa = await this.request(`/${mediaPath}/${input.externalId}`, { + language: 'fa-IR', + }); + const en = await this.request(`/${mediaPath}/${input.externalId}`, { + language: 'en-US', + }); + const faCandidate = toCandidate(fa, input.kind); + const enCandidate = toCandidate(en, input.kind); + if (!faCandidate && !enCandidate) { + throw new AppError(502, 'MEDIA_UNAVAILABLE', 'TMDB returned invalid title metadata'); + } + const primary = faCandidate ?? enCandidate!; + const posterUrl = faCandidate?.posterUrl ?? enCandidate?.posterUrl; + const backdropUrl = faCandidate?.backdropUrl ?? enCandidate?.backdropUrl; + return { + ...primary, + name: { + fa: faCandidate?.name.fa || enCandidate?.name.fa || 'بدون عنوان', + ...(enCandidate?.name.fa ? { en: enCandidate.name.fa } : {}), + }, + synopsis: { + ...(faCandidate?.synopsis.fa + ? { fa: faCandidate.synopsis.fa } + : enCandidate?.synopsis.fa + ? { fa: enCandidate.synopsis.fa } + : {}), + ...(enCandidate?.synopsis.fa ? { en: enCandidate.synopsis.fa } : {}), + }, + ...(posterUrl ? { posterUrl } : {}), + ...(backdropUrl ? { backdropUrl } : {}), + ...((faCandidate?.year ?? enCandidate?.year) !== undefined + ? { year: (faCandidate?.year ?? enCandidate?.year)! } + : {}), + }; + } + + private async request(path: string, query: Record): Promise { + const url = new URL(`${this.options.baseUrl.replace(/\/$/, '')}${path}`); + for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value); + let lastError: unknown; + for (let attempt = 0; attempt <= this.options.maxRetries; attempt += 1) { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), this.options.timeoutMs); + try { + const response = await this.fetchImpl(url, { + method: 'GET', + headers: { + accept: 'application/json', + authorization: `Bearer ${this.token}`, + }, + signal: controller.signal, + }); + if (response.ok) return (await response.json()) as T; + if ((response.status === 429 || response.status >= 500) && attempt < this.options.maxRetries) { + await delay(retryDelay(response.headers.get('retry-after'), attempt)); + continue; + } + if (response.status === 404) { + throw new AppError(404, 'NOT_FOUND', 'TMDB title not found'); + } + throw new AppError(502, 'MEDIA_UNAVAILABLE', `TMDB request failed (${response.status})`); + } catch (error) { + lastError = error; + if (error instanceof AppError) throw error; + if (attempt >= this.options.maxRetries) break; + await delay(100 * 2 ** attempt); + } finally { + clearTimeout(timeout); + } + } + throw new AppError(502, 'MEDIA_UNAVAILABLE', 'TMDB request timed out or was unavailable', { + cause: lastError instanceof Error ? lastError.message : 'unknown', + }); + } +} + +export function createMetadataProvider( + config: ApiConfig, + fetchImpl: Fetch = globalThis.fetch, +): MetadataProvider { + if (!config.tmdbApiToken || !config.tmdbCommercialLicenseConfirmed) { + return new DisabledMetadataProvider(); + } + return new TmdbMetadataProvider( + config.tmdbApiToken, + { + baseUrl: config.tmdbBaseUrl, + timeoutMs: config.tmdbTimeoutMs, + maxRetries: config.tmdbMaxRetries, + }, + fetchImpl, + ); +} + +function toCandidate(value: unknown, kind: 'MOVIE' | 'SERIES'): MetadataCandidate | undefined { + if (!isObject(value) || typeof value.id !== 'number') return undefined; + const name = string(value[kind === 'MOVIE' ? 'title' : 'name']); + const originalName = string(value[kind === 'MOVIE' ? 'original_title' : 'original_name']); + if (!name && !originalName) return undefined; + const date = string(value[kind === 'MOVIE' ? 'release_date' : 'first_air_date']); + const year = date && /^[0-9]{4}/.test(date) ? Number(date.slice(0, 4)) : undefined; + const posterPath = imagePath(value.poster_path); + const backdropPath = imagePath(value.backdrop_path); + const overview = string(value.overview); + return { + provider: 'TMDB', + externalId: value.id, + kind, + name: { + fa: name ?? originalName!, + ...(originalName && originalName !== name ? { en: originalName } : {}), + }, + synopsis: { ...(overview ? { fa: overview } : {}) }, + ...(posterPath ? { posterUrl: `/images/tmdb/w500${posterPath}` } : {}), + ...(backdropPath + ? { backdropUrl: `/images/tmdb/w1280${backdropPath}` } + : {}), + ...(year !== undefined ? { year } : {}), + }; +} + +function isObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +function string(value: unknown): string | undefined { + return typeof value === 'string' && value.trim() ? value.trim() : undefined; +} + +function imagePath(value: unknown): string | undefined { + const path = string(value); + return path?.startsWith('/') ? path : undefined; +} + +function retryDelay(retryAfter: string | null, attempt: number): number { + if (retryAfter && /^[0-9]+$/.test(retryAfter)) { + return Math.min(Number(retryAfter) * 1000, 2000); + } + return 100 * 2 ** attempt; +} + +function delay(milliseconds: number): Promise { + return new Promise((resolve) => setTimeout(resolve, milliseconds)); +} + +function disabledError(): AppError { + return new AppError( + 409, + 'CONFLICT', + 'TMDB is disabled until TMDB_API_TOKEN and TMDB_COMMERCIAL_LICENSE_CONFIRMED=true are configured', + ); +} diff --git a/apps/api/test/app.test.ts b/apps/api/test/app.test.ts new file mode 100644 index 0000000..5025161 --- /dev/null +++ b/apps/api/test/app.test.ts @@ -0,0 +1,346 @@ +import type { MetadataCandidate } from '@easy-stream/contracts'; +import { afterEach, describe, expect, it } from 'vitest'; +import { buildApp } from '../src/app.js'; +import type { + MediaPreparationService, + MetadataProvider, + PasswordHasher, +} from '../src/domain.js'; +import type { CacheStatusService } from '../src/services/cache-status.js'; +import { InMemoryRepository } from '../src/repositories/in-memory.js'; +import { InMemoryMediaCommandPublisher } from '../src/services/media-preparation.js'; +import { ids, testConfig, titleFixture } from './fixtures.js'; + +const passwordHasher: PasswordHasher = { + async hash(password) { + return `test:${password}`; + }, + async verify(hash, password) { + return hash === `test:${password}`; + }, +}; + +const readyMedia: MediaPreparationService = { + async prepare() { + return readyPreparation(); + }, + async getStatus() { + return readyPreparation(); + }, +}; + +const metadataCandidate: MetadataCandidate = { + provider: 'TMDB', + externalId: 42, + kind: 'SERIES', + name: { fa: 'عنوان تازه', en: 'Fresh title' }, + synopsis: { fa: 'خلاصه تازه' }, + year: 2026, +}; + +const metadataProvider: MetadataProvider = { + async search() { + return [metadataCandidate]; + }, + async getDetails() { + return metadataCandidate; + }, +}; + +const apps: Awaited>[] = []; +afterEach(async () => { + await Promise.all(apps.splice(0).map((app) => app.close())); +}); + +describe('viewer API', () => { + it('lists and searches published catalog titles', async () => { + const app = await makeApp(); + const catalog = await app.inject({ method: 'GET', url: '/api/v1/catalog' }); + expect(catalog.statusCode).toBe(200); + expect(catalog.json().items).toEqual([ + expect.objectContaining({ id: ids.title, playable: true }), + ]); + + const search = await app.inject({ method: 'GET', url: '/api/v1/search?q=Sample' }); + expect(search.statusCode).toBe(200); + expect(search.json().items[0].slug).toBe('sample-series'); + + const detail = await app.inject({ method: 'GET', url: '/api/v1/titles/sample-series' }); + expect(detail.statusCode).toBe(200); + expect(detail.json().mediaItems[0].id).toBe(ids.media); + + const event = await app.inject({ + method: 'POST', + url: '/api/v1/client-events', + payload: { + name: 'playback_started', + mediaItemId: ids.media, + occurredAt: '2026-07-14T00:00:00.000Z', + details: { subtitleDelivery: 'ASS_JASSUB' }, + }, + }); + expect(event.statusCode).toBe(202); + }); + + it('creates a ready session and authorizes only its generation path', async () => { + const app = await makeApp(); + const response = await app.inject({ + method: 'POST', + url: '/api/v1/playback-sessions', + payload: { + mediaItemId: ids.media, + clientCapabilities: capabilities(), + }, + }); + expect(response.statusCode).toBe(200); + expect(response.json()).toEqual( + expect.objectContaining({ + state: 'READY', + manifestUrl: `http://localhost:8080/media/generations/${ids.generation}/master.m3u8`, + }), + ); + expect(response.json().subtitleTracks[0]).toEqual( + expect.objectContaining({ assUrl: expect.any(String), vttUrl: expect.any(String) }), + ); + const setCookie = response.headers['set-cookie']; + const cookie = (Array.isArray(setCookie) ? setCookie[0] : setCookie)?.split(';', 1)[0]; + expect(cookie).toBeTruthy(); + + const allowed = await app.inject({ + method: 'GET', + url: '/internal/media-auth', + headers: { + cookie: cookie!, + 'x-media-auth-secret': testConfig().mediaAuthSharedSecret, + 'x-original-uri': `/media/generations/${ids.generation}/video/segment-00001.m4s`, + }, + }); + expect(allowed.statusCode).toBe(204); + + const denied = await app.inject({ + method: 'GET', + url: '/internal/media-auth', + headers: { + cookie: cookie!, + 'x-media-auth-secret': testConfig().mediaAuthSharedSecret, + 'x-original-uri': '/media/generations/30000000-0000-4000-8000-000000000002/master.m3u8', + }, + }); + expect(denied.statusCode).toBe(401); + }); + + it('promotes a playable EVENT package while it is still preparing', async () => { + const progressive: MediaPreparationService = { + async prepare() { + return { ...readyPreparation(), state: 'PREPARING' }; + }, + async getStatus() { + return { ...readyPreparation(), state: 'PREPARING' }; + }, + }; + const app = await makeApp(progressive); + const response = await app.inject({ + method: 'POST', + url: '/api/v1/playback-sessions', + payload: { mediaItemId: ids.media, clientCapabilities: capabilities() }, + }); + expect(response.statusCode).toBe(200); + expect(response.json().state).toBe('READY'); + }); + + it('scopes durable compatibility media to the derived generation path', async () => { + const derivedMedia: MediaPreparationService = { + async prepare() { + return { + ...readyPreparation(), + manifestPath: `/media/derived/generations/${ids.generation}/master.m3u8`, + subtitleTracks: [ + { + id: ids.subtitle, + language: 'fa', + label: 'فارسی', + default: true, + forced: false, + assUrl: `/media/derived/generations/${ids.generation}/subtitles/fa.ass`, + vttUrl: `/media/derived/generations/${ids.generation}/subtitles/fa.vtt`, + fontUrls: [`/media/derived/generations/${ids.generation}/fonts/a.ttf`], + }, + ], + }; + }, + async getStatus() { + throw new Error('not used'); + }, + }; + const app = await makeApp(derivedMedia); + const response = await app.inject({ + method: 'POST', + url: '/api/v1/playback-sessions', + payload: { mediaItemId: ids.media, clientCapabilities: capabilities() }, + }); + expect(response.statusCode).toBe(200); + expect(response.json().manifestUrl).toBe( + `http://localhost:8080/media/derived/generations/${ids.generation}/master.m3u8`, + ); + const setCookie = response.headers['set-cookie']; + const cookieHeader = Array.isArray(setCookie) ? setCookie[0] : setCookie; + expect(cookieHeader).toContain(`Path=/media/derived/generations/${ids.generation}/`); + const cookie = cookieHeader?.split(';', 1)[0]; + + const allowed = await app.inject({ + method: 'GET', + url: '/internal/media-auth', + headers: { + cookie: cookie!, + 'x-media-auth-secret': testConfig().mediaAuthSharedSecret, + 'x-original-uri': `/media/derived/generations/${ids.generation}/fonts/a.ttf`, + }, + }); + expect(allowed.statusCode).toBe(204); + + const wrongStore = await app.inject({ + method: 'GET', + url: '/internal/media-auth', + headers: { + cookie: cookie!, + 'x-media-auth-secret': testConfig().mediaAuthSharedSecret, + 'x-original-uri': `/media/generations/${ids.generation}/master.m3u8`, + }, + }); + expect(wrongStore.statusCode).toBe(401); + }); + + it('returns a stable unsupported-client session without enqueueing media', async () => { + const app = await makeApp(); + const response = await app.inject({ + method: 'POST', + url: '/api/v1/playback-sessions', + payload: { + mediaItemId: ids.media, + clientCapabilities: { ...capabilities(), mse: false, hlsJs: false }, + }, + }); + expect(response.statusCode).toBe(200); + expect(response.json()).toEqual( + expect.objectContaining({ state: 'UNSUPPORTED_CLIENT', reasonCode: 'HLS_MSE_UNAVAILABLE' }), + ); + }); +}); + +describe('administrator API', () => { + it('enforces session and CSRF, enqueues scans, and applies a metadata match', async () => { + const commands = new InMemoryMediaCommandPublisher(); + const cacheStatus: CacheStatusService = { + async getStatus() { + return { + usedBytes: 321, + maxBytes: 1_000, + highWatermark: 0.85, + lowWatermark: 0.75, + activePackages: 2, + }; + }, + }; + const app = await makeApp(readyMedia, commands, cacheStatus); + const login = await app.inject({ + method: 'POST', + url: '/api/v1/admin/login', + payload: { email: 'admin@example.com', password: 'a-good-test-password' }, + }); + expect(login.statusCode).toBe(200); + const csrf = login.json().csrfToken as string; + const setCookie = login.headers['set-cookie']; + const cookie = (Array.isArray(setCookie) ? setCookie[0] : setCookie)?.split(';', 1)[0]; + + const blocked = await app.inject({ + method: 'POST', + url: '/api/v1/admin/scans', + headers: { cookie: cookie! }, + payload: { full: false }, + }); + expect(blocked.statusCode).toBe(403); + + const scan = await app.inject({ + method: 'POST', + url: '/api/v1/admin/scans', + headers: { cookie: cookie!, 'x-csrf-token': csrf }, + payload: { full: true }, + }); + expect(scan.statusCode).toBe(202); + expect(commands.commands).toContainEqual( + expect.objectContaining({ type: 'archive.scan.requested', full: true }), + ); + + const match = await app.inject({ + method: 'POST', + url: `/api/v1/admin/titles/${ids.title}/metadata-match`, + headers: { cookie: cookie!, 'x-csrf-token': csrf }, + payload: { provider: 'TMDB', externalId: 42, kind: 'SERIES' }, + }); + expect(match.statusCode).toBe(200); + const detail = await app.inject({ method: 'GET', url: '/api/v1/titles/sample-series' }); + expect(detail.json().name.fa).toBe('عنوان تازه'); + + const cache = await app.inject({ + method: 'GET', + url: '/api/v1/admin/cache', + headers: { cookie: cookie! }, + }); + expect(cache.statusCode).toBe(200); + expect(cache.json()).toEqual(expect.objectContaining({ usedBytes: 321, activePackages: 2 })); + }); +}); + +async function makeApp( + media: MediaPreparationService = readyMedia, + commands = new InMemoryMediaCommandPublisher(), + cacheStatus?: CacheStatusService, +) { + const app = await buildApp({ + config: testConfig(), + repository: new InMemoryRepository({ titles: [titleFixture] }), + mediaPreparation: media, + commandPublisher: commands, + metadataProvider, + passwordHasher, + ...(cacheStatus === undefined ? {} : { cacheStatus }), + logger: false, + }); + apps.push(app); + return app; +} + +function capabilities() { + return { + mse: true, + nativeHls: false, + hlsJs: true, + assRenderer: true, + supportedCodecs: ['avc1.64001f', 'mp4a.40.2'], + }; +} + +function readyPreparation() { + return { + state: 'READY' as const, + playable: true, + generationId: ids.generation, + manifestPath: `/media/generations/${ids.generation}/master.m3u8`, + durationSeconds: 1420, + audioTracks: [ + { id: ids.audio, language: 'ja', label: '日本語', default: true }, + ], + subtitleTracks: [ + { + id: ids.subtitle, + language: 'fa', + label: 'فارسی', + default: true, + forced: false, + assUrl: `/media/generations/${ids.generation}/subtitles/fa.ass`, + vttUrl: `/media/generations/${ids.generation}/subtitles/fa.vtt`, + fontUrls: [`/media/generations/${ids.generation}/fonts/a.ttf`], + }, + ], + }; +} diff --git a/apps/api/test/cache-status.test.ts b/apps/api/test/cache-status.test.ts new file mode 100644 index 0000000..4a674ef --- /dev/null +++ b/apps/api/test/cache-status.test.ts @@ -0,0 +1,127 @@ +import { mkdtemp, mkdir, rm, symlink, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; +import { FilesystemCacheStatusService } from '../src/services/cache-status.js'; + +const temporaryRoots: string[] = []; +afterEach(async () => { + await Promise.all(temporaryRoots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); +}); + +describe('filesystem cache status', () => { + it('sums valid generation metadata and global font-store files', async () => { + const root = await temporaryRoot(); + const generations = path.join(root, 'generations'); + await Promise.all([ + writeEntry(generations, '11111111-1111-4111-8111-111111111111', 120, false), + writeEntry(generations, '22222222-2222-4222-8222-222222222222', 230, true), + mkdir(path.join(generations, 'incomplete-generation'), { recursive: true }), + ]); + const fontStore = path.join(root, 'assets', 'fonts', 'sha256'); + await mkdir(fontStore, { recursive: true }); + await Promise.all([ + writeFile(path.join(fontStore, `${'a'.repeat(64)}.ttf`), Buffer.alloc(11)), + writeFile(path.join(fontStore, `${'b'.repeat(64)}.otf`), Buffer.alloc(19)), + ]); + + await expect(service(root).getStatus()).resolves.toEqual({ + usedBytes: 380, + maxBytes: 1_000, + highWatermark: 0.85, + lowWatermark: 0.75, + activePackages: 1, + }); + }); + + it('treats a missing cache root as an empty cache', async () => { + const base = await temporaryRoot(); + await expect(service(path.join(base, 'missing')).getStatus()).resolves.toMatchObject({ + usedBytes: 0, + activePackages: 0, + }); + }); + + it('rejects invalid managed generation metadata', async () => { + const root = await temporaryRoot(); + const generations = path.join(root, 'generations'); + const generation = '11111111-1111-4111-8111-111111111111'; + const directory = path.join(generations, generation); + await mkdir(directory, { recursive: true }); + await writeFile(path.join(directory, '.cache-entry.json'), JSON.stringify({ + ...metadata('different-generation', 10, false), + })); + + await expect(service(root).getStatus()).rejects.toThrow(/does not match its generation/u); + }); + + it('counts a known archived failure without treating stale metadata as a live build', async () => { + const root = await temporaryRoot(); + const generations = path.join(root, 'generations'); + const generation = '11111111-1111-4111-8111-111111111111'; + const archived = `failed-1784023200000-${generation}`; + const directory = path.join(generations, archived); + await mkdir(directory, { recursive: true }); + await writeFile(path.join(directory, '.cache-entry.json'), JSON.stringify( + metadata(generation, 77, true), + )); + + await expect(service(root).getStatus()).resolves.toMatchObject({ + usedBytes: 77, + activePackages: 0, + }); + }); + + it('fails closed on symlinks in managed cache namespaces', async () => { + const root = await temporaryRoot(); + const outside = await temporaryRoot(); + const generations = path.join(root, 'generations'); + await mkdir(generations, { recursive: true }); + await symlink(outside, path.join(generations, 'linked-generation')); + await expect(service(root).getStatus()).rejects.toThrow(/Symlink found in cache generations/u); + + await rm(generations, { recursive: true, force: true }); + await symlink(outside, path.join(root, 'assets')); + await expect(service(root).getStatus()).rejects.toThrow(/not a regular directory/u); + }); +}); + +function service(cacheRoot: string): FilesystemCacheStatusService { + return new FilesystemCacheStatusService({ + cacheRoot, + maxBytes: 1_000, + highWatermark: 0.85, + lowWatermark: 0.75, + }); +} + +async function temporaryRoot(): Promise { + const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-api-cache-')); + temporaryRoots.push(root); + return root; +} + +async function writeEntry( + generations: string, + generation: string, + bytes: number, + building: boolean, +): Promise { + const directory = path.join(generations, generation); + await mkdir(directory, { recursive: true }); + await writeFile(path.join(directory, '.cache-entry.json'), JSON.stringify( + metadata(generation, bytes, building), + )); +} + +function metadata(key: string, bytes: number, building: boolean) { + return { + version: 1, + key, + bytes, + lastAccessedAt: '2026-07-14T10:00:00.000Z', + active: false, + building, + pinned: false, + }; +} diff --git a/apps/api/test/config.test.ts b/apps/api/test/config.test.ts new file mode 100644 index 0000000..0f619d1 --- /dev/null +++ b/apps/api/test/config.test.ts @@ -0,0 +1,74 @@ +import { describe, expect, it } from 'vitest'; +import { loadConfig } from '../src/config.js'; + +describe('loadConfig', () => { + it('loads a secure in-memory development configuration', () => { + const config = loadConfig({ + NODE_ENV: 'development', + PLAYBACK_SIGNING_SECRET: 'this-is-a-development-secret-with-32-chars', + }); + expect(config.repositoryDriver).toBe('memory'); + expect(config.catalogSnapshotPath).toBe('./data/catalog.json'); + expect(config.cacheRoot).toBe('./data/cache'); + expect(config.cacheLowWatermark).toBeLessThan(config.cacheHighWatermark); + }); + + it('accepts an explicit read-only cache root', () => { + const config = loadConfig({ + NODE_ENV: 'test', + CACHE_ROOT: '/srv/easy-stream/cache', + PLAYBACK_SIGNING_SECRET: 'this-is-a-development-secret-with-32-chars', + }); + expect(config.cacheRoot).toBe('/srv/easy-stream/cache'); + }); + + it('rejects short signing secrets', () => { + expect(() => + loadConfig({ NODE_ENV: 'test', PLAYBACK_SIGNING_SECRET: 'short' }), + ).toThrow(/playbackSigningSecret/); + }); + + it('requires a database URL for PostgreSQL', () => { + expect(() => + loadConfig({ + NODE_ENV: 'test', + REPOSITORY_DRIVER: 'postgres', + PLAYBACK_SIGNING_SECRET: 'this-is-a-development-secret-with-32-chars', + }), + ).toThrow(/DATABASE_URL/); + }); + + it('accepts only a base64url-safe media auth secret', () => { + expect(() => + loadConfig({ + NODE_ENV: 'test', + PLAYBACK_SIGNING_SECRET: 'this-is-a-development-secret-with-32-chars', + MEDIA_AUTH_SHARED_SECRET: 'invalid-secret-with-a-quote-"-inside', + }), + ).toThrow(/mediaAuthSharedSecret/); + }); + + it('requires the web, API, and media URLs to remain same-origin in production', () => { + expect(() => + loadConfig({ + NODE_ENV: 'production', + DATABASE_URL: 'postgres://easy-stream:test@postgres/easy-stream', + WEB_ORIGIN: 'https://watch.example.com', + PUBLIC_ORIGIN: 'https://watch.example.com', + MEDIA_PUBLIC_BASE_URL: 'https://media.example.com/media', + PLAYBACK_SIGNING_SECRET: 'production-playback-signing-secret-000000000', + MEDIA_AUTH_SHARED_SECRET: 'production_media_auth_secret_11111111111', + }), + ).toThrow(/must use one origin/); + }); + + it('requires the canonical media base path', () => { + expect(() => + loadConfig({ + NODE_ENV: 'test', + PLAYBACK_SIGNING_SECRET: 'this-is-a-development-secret-with-32-chars', + MEDIA_PUBLIC_BASE_URL: 'http://localhost:8080/not-media', + }), + ).toThrow(/\/media path/); + }); +}); diff --git a/apps/api/test/fixtures.ts b/apps/api/test/fixtures.ts new file mode 100644 index 0000000..47bd973 --- /dev/null +++ b/apps/api/test/fixtures.ts @@ -0,0 +1,65 @@ +import type { ApiConfig } from '../src/config.js'; +import type { TitleDetail } from '@easy-stream/contracts'; + +export const ids = { + title: '10000000-0000-4000-8000-000000000001', + media: '20000000-0000-4000-8000-000000000001', + generation: '30000000-0000-4000-8000-000000000001', + audio: '40000000-0000-4000-8000-000000000001', + subtitle: '50000000-0000-4000-8000-000000000001', +}; + +export const titleFixture: TitleDetail = { + id: ids.title, + slug: 'sample-series', + kind: 'SERIES', + name: { fa: 'سریال نمونه', en: 'Sample Series' }, + synopsis: { fa: 'خلاصه نمونه', en: 'Sample synopsis' }, + playable: true, + resumeMediaItemId: ids.media, + seasons: [{ number: 1, episodeCount: 1 }], + mediaItems: [ + { + id: ids.media, + kind: 'EPISODE', + seasonNumber: 1, + episodeNumber: 1, + name: { fa: 'قسمت یک', en: 'Episode One' }, + durationSeconds: 1420, + compatibility: 'COPY', + published: true, + }, + ], + updatedAt: '2026-07-14T00:00:00.000Z', +}; + +export function testConfig(overrides: Partial = {}): ApiConfig { + return { + nodeEnv: 'test', + host: '127.0.0.1', + port: 3000, + webOrigin: 'http://localhost:5173', + publicOrigin: 'http://localhost:8080', + mediaPublicBaseUrl: 'http://localhost:8080/media', + repositoryDriver: 'memory', + catalogSnapshotPath: '/tmp/easy-stream-test-catalog-does-not-exist.json', + packageRegistryPath: '/tmp/easy-stream-test-registry-does-not-exist.json', + mediaCommandsPath: '/tmp/easy-stream-test-commands.jsonl', + cacheRoot: '/tmp/easy-stream-test-cache-does-not-exist', + playbackProfile: 'cmaf-v1', + playbackSigningSecret: 'playback-signing-secret-that-is-long-enough', + mediaAuthSharedSecret: 'media-auth-shared-secret-that-is-long-enough', + playbackTtlSeconds: 14_400, + adminSessionTtlSeconds: 28_800, + adminBootstrapEmail: 'admin@example.com', + adminBootstrapPassword: 'a-good-test-password', + tmdbCommercialLicenseConfirmed: false, + tmdbBaseUrl: 'https://api.themoviedb.org/3', + tmdbTimeoutMs: 1000, + tmdbMaxRetries: 1, + cacheMaxBytes: 2_000_000, + cacheHighWatermark: 0.85, + cacheLowWatermark: 0.75, + ...overrides, + }; +} diff --git a/apps/api/test/media-preparation.test.ts b/apps/api/test/media-preparation.test.ts new file mode 100644 index 0000000..dbe2c75 --- /dev/null +++ b/apps/api/test/media-preparation.test.ts @@ -0,0 +1,82 @@ +import { mkdtemp, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { + FileMediaPreparationService, + InMemoryMediaCommandPublisher, +} from '../src/services/media-preparation.js'; +import { ids } from './fixtures.js'; + +describe('file media preparation cache access', () => { + it('records a cache lease through the playback session expiry', async () => { + const registry = await readyRegistry(`/media/generations/${ids.generation}/master.m3u8`); + const commands = new InMemoryMediaCommandPublisher(); + const service = new FileMediaPreparationService(registry, commands); + const protectedUntil = '2026-07-14T14:00:00.000Z'; + const result = await service.prepare({ + sessionId: ids.title, + mediaItem: mediaItem(), + capabilities: capabilities(), + protectUntil: protectedUntil, + }); + expect(result.state).toBe('READY'); + expect(commands.commands).toEqual([ + expect.objectContaining({ + type: 'cache.generation.accessed', + generationId: ids.generation, + protectedUntil, + }), + ]); + }); + + it('does not put durable derived generations in the disposable cache lifecycle', async () => { + const registry = await readyRegistry(`/media/derived/generations/${ids.generation}/master.m3u8`); + const commands = new InMemoryMediaCommandPublisher(); + const service = new FileMediaPreparationService(registry, commands); + await service.prepare({ + sessionId: ids.title, + mediaItem: mediaItem(), + capabilities: capabilities(), + protectUntil: '2026-07-14T14:00:00.000Z', + }); + expect(commands.commands).toEqual([]); + }); +}); + +async function readyRegistry(manifestPath: string): Promise { + const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-api-registry-')); + const registry = path.join(directory, 'registry.json'); + await writeFile(registry, JSON.stringify({ + version: 1, + updatedAt: '2026-07-14T10:00:00.000Z', + packages: [{ + mediaItemId: ids.media, + state: 'READY', + playable: true, + generationId: ids.generation, + manifestPath, + }], + })); + return registry; +} + +function mediaItem() { + return { + id: ids.media, + titleId: ids.title, + durationSeconds: 100, + compatibility: 'COPY' as const, + published: true, + }; +} + +function capabilities() { + return { + mse: true, + nativeHls: false, + hlsJs: true, + assRenderer: true, + supportedCodecs: ['avc1.64001f'], + }; +} diff --git a/apps/api/test/tmdb.test.ts b/apps/api/test/tmdb.test.ts new file mode 100644 index 0000000..ce7cd50 --- /dev/null +++ b/apps/api/test/tmdb.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it, vi } from 'vitest'; +import { TmdbMetadataProvider } from '../src/services/tmdb.js'; + +describe('TmdbMetadataProvider', () => { + it('falls back from Persian search to English and sends a bearer token', async () => { + const fetch = vi + .fn() + .mockResolvedValueOnce(Response.json({ results: [] })) + .mockResolvedValueOnce( + Response.json({ + results: [ + { + id: 42, + name: 'Sample Series', + original_name: 'Sample Series', + overview: 'Overview', + first_air_date: '2026-01-02', + poster_path: '/sample-poster.jpg', + backdrop_path: '/sample-backdrop.jpg', + }, + ], + }), + ); + const provider = new TmdbMetadataProvider( + 'secret-token', + { baseUrl: 'https://api.themoviedb.org/3', timeoutMs: 1000, maxRetries: 0 }, + fetch, + ); + + const result = await provider.search({ query: 'Sample', kind: 'SERIES' }); + expect(result[0]).toEqual(expect.objectContaining({ + externalId: 42, + year: 2026, + posterUrl: '/images/tmdb/w500/sample-poster.jpg', + backdropUrl: '/images/tmdb/w1280/sample-backdrop.jpg', + })); + expect(new URL(String(fetch.mock.calls[0]?.[0])).searchParams.get('language')).toBe('fa-IR'); + expect(new URL(String(fetch.mock.calls[1]?.[0])).searchParams.get('language')).toBe('en-US'); + expect(fetch.mock.calls[0]?.[1]?.headers).toEqual( + expect.objectContaining({ authorization: 'Bearer secret-token' }), + ); + }); + + it('merges Persian and English detail responses', async () => { + const fetch = vi + .fn() + .mockResolvedValueOnce( + Response.json({ id: 42, title: 'عنوان فارسی', overview: 'خلاصه', release_date: '2025-01-01' }), + ) + .mockResolvedValueOnce( + Response.json({ id: 42, title: 'English title', overview: 'Synopsis', release_date: '2025-01-01' }), + ); + const provider = new TmdbMetadataProvider( + 'token', + { baseUrl: 'https://api.themoviedb.org/3', timeoutMs: 1000, maxRetries: 0 }, + fetch, + ); + const result = await provider.getDetails({ externalId: 42, kind: 'MOVIE' }); + expect(result.name).toEqual({ fa: 'عنوان فارسی', en: 'English title' }); + expect(result.synopsis).toEqual({ fa: 'خلاصه', en: 'Synopsis' }); + }); + + it('retries transient upstream failures', async () => { + const fetch = vi + .fn() + .mockResolvedValueOnce(new Response('', { status: 503 })) + .mockResolvedValueOnce(Response.json({ results: [] })) + .mockResolvedValueOnce(Response.json({ results: [] })); + const provider = new TmdbMetadataProvider( + 'token', + { baseUrl: 'https://api.themoviedb.org/3', timeoutMs: 1000, maxRetries: 1 }, + fetch, + ); + await expect(provider.search({ query: 'x', kind: 'MOVIE' })).resolves.toEqual([]); + expect(fetch).toHaveBeenCalledTimes(3); + }); +}); diff --git a/apps/api/tsconfig.json b/apps/api/tsconfig.json new file mode 100644 index 0000000..7fd22ee --- /dev/null +++ b/apps/api/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist", + "tsBuildInfoFile": "dist/.tsbuildinfo", + "types": ["node"], + "paths": { + "@easy-stream/contracts": ["packages/contracts/dist/index.d.ts"], + "@easy-stream/database": ["packages/database/dist/index.d.ts"] + } + }, + "include": ["src/**/*.ts"] +} diff --git a/apps/api/tsconfig.test.json b/apps/api/tsconfig.test.json new file mode 100644 index 0000000..631119f --- /dev/null +++ b/apps/api/tsconfig.test.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": true, + "rootDir": ".", + "tsBuildInfoFile": "../../node_modules/.cache/easy-stream-api-test.tsbuildinfo" + }, + "include": ["src/**/*.ts", "test/**/*.ts"] +} diff --git a/apps/web/index.html b/apps/web/index.html new file mode 100644 index 0000000..5b5a6a7 --- /dev/null +++ b/apps/web/index.html @@ -0,0 +1,18 @@ + + + + + + + + + + + Easy Stream + + + +
+ + + diff --git a/apps/web/package.json b/apps/web/package.json new file mode 100644 index 0000000..ec70094 --- /dev/null +++ b/apps/web/package.json @@ -0,0 +1,29 @@ +{ + "name": "@easy-stream/web", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vite --host 0.0.0.0", + "build": "vue-tsc --noEmit && vite build", + "typecheck": "vue-tsc --noEmit", + "test": "vitest run", + "test:watch": "vitest" + }, + "dependencies": { + "@fontsource/vazirmatn": "^5.2.8", + "hls.js": "^1.6.15", + "jassub": "^2.5.7", + "pinia": "^3.0.3", + "vue": "^3.5.22", + "vue-router": "^4.6.3" + }, + "devDependencies": { + "@vitejs/plugin-vue": "^6.0.1", + "@vue/test-utils": "^2.4.6", + "jsdom": "^26.1.0", + "vite": "^7.1.9", + "vitest": "^3.2.4", + "vue-tsc": "^3.1.1" + } +} diff --git a/apps/web/public/favicon.svg b/apps/web/public/favicon.svg new file mode 100644 index 0000000..146dbf5 --- /dev/null +++ b/apps/web/public/favicon.svg @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/apps/web/public/site.webmanifest b/apps/web/public/site.webmanifest new file mode 100644 index 0000000..e58c524 --- /dev/null +++ b/apps/web/public/site.webmanifest @@ -0,0 +1,20 @@ +{ + "name": "Easy Stream", + "short_name": "Easy Stream", + "description": "Your movie archive, ready to stream.", + "lang": "fa", + "dir": "rtl", + "start_url": "/", + "scope": "/", + "display": "standalone", + "background_color": "#070a12", + "theme_color": "#111722", + "icons": [ + { + "src": "/favicon.svg", + "sizes": "any", + "type": "image/svg+xml", + "purpose": "any maskable" + } + ] +} diff --git a/apps/web/src/App.vue b/apps/web/src/App.vue new file mode 100644 index 0000000..10c9c91 --- /dev/null +++ b/apps/web/src/App.vue @@ -0,0 +1,31 @@ + + + diff --git a/apps/web/src/api/client.test.ts b/apps/web/src/api/client.test.ts new file mode 100644 index 0000000..2ab2827 --- /dev/null +++ b/apps/web/src/api/client.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'vitest' + +import { normalizePlaybackSession } from '@/api/client' + +describe('normalizePlaybackSession', () => { + it('normalizes the canonical playback response', () => { + const session = normalizePlaybackSession({ + id: 'session-1', + state: 'READY', + manifestUrl: '/media/session-1/master.m3u8', + durationSeconds: 1420, + audioTracks: [{ id: 'audio-ja', language: 'ja', label: 'Japanese', default: true }], + subtitleTracks: [{ + id: 'sub-fa', + language: 'fa', + label: 'فارسی', + assUrl: '/subtitles/fa.ass', + vttUrl: '/subtitles/fa.vtt', + fontUrls: ['/fonts/one.ttf'], + }], + }) + + expect(session.state).toBe('READY') + expect(session.manifestUrl).toBe('/media/session-1/master.m3u8') + expect(session.audioTracks[0]).toMatchObject({ language: 'ja', default: true }) + expect(session.subtitles[0]).toMatchObject({ + language: 'fa', + assUrl: '/subtitles/fa.ass', + vttUrl: '/subtitles/fa.vtt', + fonts: ['/fonts/one.ttf'], + }) + }) + + it('splits and merges a legacy mixed track array', () => { + const session = normalizePlaybackSession({ + sessionId: 'session-2', + status: 'building', + tracks: [ + { id: 'fa-ass', kind: 'SUBTITLE', language: 'fa', delivery: 'ASS', url: '/fa.ass' }, + { id: 'fa-vtt', kind: 'SUBTITLE', language: 'fa', delivery: 'WEBVTT', url: '/fa.vtt' }, + { id: 'ja', kind: 'AUDIO', language: 'ja', name: 'Japanese' }, + ], + }) + + expect(session.state).toBe('PREPARING') + expect(session.subtitles).toHaveLength(1) + expect(session.subtitles[0]).toMatchObject({ assUrl: '/fa.ass', vttUrl: '/fa.vtt' }) + expect(session.audioTracks).toHaveLength(1) + }) +}) diff --git a/apps/web/src/api/client.ts b/apps/web/src/api/client.ts new file mode 100644 index 0000000..815b301 --- /dev/null +++ b/apps/web/src/api/client.ts @@ -0,0 +1,444 @@ +import type { + AdminDashboard, + AdminJob, + CatalogItem, + CatalogPage, + ClientCapabilities, + EpisodeItem, + LocalizedText, + PlaybackAudioTrack, + PlaybackSession, + PlaybackState, + PlaybackSubtitleTrack, + SeasonItem, + TitleDetail, +} from '@/types' + +const API_BASE = (import.meta.env.VITE_API_BASE_URL ?? '/api/v1').replace(/\/$/, '') +const ADMIN_CSRF_KEY = 'easy-stream-admin-csrf' +const ADMIN_EMAIL_KEY = 'easy-stream-admin-email' + +export class ApiError extends Error { + readonly status: number + readonly code: string | undefined + + constructor(message: string, status: number, code?: string) { + super(message) + this.name = 'ApiError' + this.status = status + this.code = code + } +} + +type JsonRecord = Record + +function record(value: unknown): JsonRecord { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? (value as JsonRecord) + : {} +} + +function text(value: unknown): string | undefined { + return typeof value === 'string' && value.trim() ? value : undefined +} + +function number(value: unknown): number | undefined { + if (typeof value === 'number' && Number.isFinite(value)) return value + if (typeof value === 'string' && value.trim() && Number.isFinite(Number(value))) return Number(value) + return undefined +} + +function boolean(value: unknown, fallback = false): boolean { + return typeof value === 'boolean' ? value : fallback +} + +function localized(value: unknown, fallback?: unknown): LocalizedText { + if (typeof value === 'string') return { fa: value, en: value } + const source = record(value) + const fa = text(source.fa) ?? text(source.faIR) ?? text(source.persian) + const en = text(source.en) ?? text(source.enUS) ?? text(source.english) ?? text(fallback) + return { + ...(fa ? { fa } : {}), + ...(en ? { en } : {}), + } +} + +function array(value: unknown): unknown[] { + return Array.isArray(value) ? value : [] +} + +function normalizeCatalogItem(input: unknown): CatalogItem { + const item = record(input) + const metadata = record(item.metadata) + const titleValue = item.name ?? item.title ?? metadata.title + const title = typeof titleValue === 'string' + ? { fa: titleValue, en: text(item.titleEn ?? metadata.titleEn) ?? titleValue } + : localized(titleValue, item.name ?? metadata.name) + const id = text(item.id) ?? text(item.titleId) ?? text(item.mediaItemId) ?? '' + const mediaItemId = text(item.resumeMediaItemId) ?? text(item.mediaItemId) ?? text(item.playableMediaItemId) ?? id + const kindValue = (text(item.kind) ?? text(item.type) ?? 'MOVIE').toUpperCase() + const posterUrl = text(item.posterUrl) ?? text(metadata.posterUrl) ?? text(record(item.images).poster) + const backdropUrl = text(item.backdropUrl) ?? text(metadata.backdropUrl) ?? text(record(item.images).backdrop) + + return { + id, + mediaItemId, + slug: text(item.slug) ?? id, + kind: kindValue === 'SERIES' || kindValue === 'SHOW' ? 'SERIES' : 'MOVIE', + title, + overview: typeof (item.synopsis ?? item.overview ?? metadata.overview) === 'string' + ? { + fa: text(item.synopsis ?? item.overview ?? metadata.overview), + en: text(item.overviewEn ?? metadata.overviewEn) ?? text(item.synopsis ?? item.overview ?? metadata.overview), + } + : localized(item.synopsis ?? item.overview ?? metadata.overview, item.description ?? metadata.description), + ...(posterUrl ? { posterUrl } : {}), + ...(backdropUrl ? { backdropUrl } : {}), + ...(number(item.year ?? metadata.year) !== undefined ? { year: number(item.year ?? metadata.year) } : {}), + ...(number(item.runtimeSeconds ?? item.durationSeconds) !== undefined + ? { runtimeSeconds: number(item.runtimeSeconds ?? item.durationSeconds) } + : {}), + ...(number(item.seasonCount) !== undefined ? { seasonCount: number(item.seasonCount) } : {}), + ...(number(item.episodeCount) !== undefined ? { episodeCount: number(item.episodeCount) } : {}), + ...(text(item.compatibility) ? { compatibility: text(item.compatibility) } : {}), + playable: item.playable === undefined ? Boolean(mediaItemId) : boolean(item.playable), + ...(number(item.progress) !== undefined ? { progress: number(item.progress) } : {}), + } +} + +function normalizeEpisode(input: unknown, seasonNumber: number): EpisodeItem { + const item = record(input) + const id = text(item.id) ?? text(item.mediaItemId) ?? '' + return { + id, + mediaItemId: text(item.mediaItemId) ?? id, + number: number(item.number ?? item.episodeNumber) ?? 0, + seasonNumber: number(item.seasonNumber) ?? seasonNumber, + title: localized(item.name ?? item.title), + overview: localized(item.synopsis ?? item.overview, item.description), + ...(text(item.posterUrl ?? item.stillUrl) ? { posterUrl: text(item.posterUrl ?? item.stillUrl) } : {}), + ...(number(item.durationSeconds ?? item.runtimeSeconds) !== undefined + ? { durationSeconds: number(item.durationSeconds ?? item.runtimeSeconds) } + : {}), + published: item.published === undefined ? true : boolean(item.published), + } +} + +function normalizeSeason(input: unknown): SeasonItem { + const item = record(input) + const seasonNumber = number(item.number ?? item.seasonNumber) ?? 0 + return { + number: seasonNumber, + title: localized(item.title, `Season ${seasonNumber}`), + episodes: array(item.episodes).map((episode) => normalizeEpisode(episode, seasonNumber)), + } +} + +function normalizeSubtitle(input: unknown, index: number): PlaybackSubtitleTrack { + const item = record(input) + const urls = record(item.urls) + const language = text(item.language ?? item.lang) ?? 'und' + const delivery = text(item.delivery ?? item.format)?.toUpperCase() + const assUrl = text(item.assUrl) ?? text(urls.ass) ?? (delivery === 'ASS' || delivery === 'ASS_JASSUB' ? text(item.url) : undefined) + const vttUrl = text(item.vttUrl) ?? text(urls.vtt) ?? (delivery === 'VTT' || delivery === 'WEBVTT' ? text(item.url) : undefined) + return { + id: text(item.id) ?? `subtitle-${index}`, + language, + label: text(item.label) ?? language.toUpperCase(), + default: boolean(item.default ?? item.isDefault), + forced: boolean(item.forced ?? item.isForced), + ...(assUrl ? { assUrl } : {}), + ...(vttUrl ? { vttUrl } : {}), + fonts: array(item.fontUrls ?? item.fonts).flatMap((font) => (typeof font === 'string' ? [font] : [])), + } +} + +function normalizeAudio(input: unknown, index: number): PlaybackAudioTrack { + const item = record(input) + const language = text(item.language ?? item.lang) ?? 'und' + return { + id: text(item.id) ?? `audio-${index}`, + language, + label: text(item.label ?? item.name) ?? language.toUpperCase(), + default: boolean(item.default ?? item.isDefault), + } +} + +function normalizeState(value: unknown): PlaybackState { + const state = (text(value) ?? 'FAILED').toUpperCase() + if (state === 'READY' || state === 'PREPARING' || state === 'UNSUPPORTED_CLIENT') return state + if (state === 'PENDING' || state === 'BUILDING' || state === 'QUEUED') return 'PREPARING' + return 'FAILED' +} + +export function normalizePlaybackSession(input: unknown): PlaybackSession { + const source = record(input) + const payload = Object.keys(record(source.data)).length ? record(source.data) : source + const trackObject = record(payload.tracks) + const mixedTracks = array(payload.tracks) + const id = text(payload.id) ?? text(payload.sessionId) ?? '' + const manifestUrl = text(payload.manifestUrl) ?? text(payload.masterPlaylistUrl) ?? text(payload.url) + const subtitleInputs = array(payload.subtitles ?? payload.subtitleTracks ?? trackObject.subtitles) + const audioInputs = array(payload.audioTracks ?? payload.audio ?? trackObject.audio) + if (!subtitleInputs.length) { + subtitleInputs.push(...mixedTracks.filter((track) => { + const kind = text(record(track).kind ?? record(track).type)?.toUpperCase() + return kind === 'SUBTITLE' || kind === 'TEXT' + })) + } + if (!audioInputs.length) { + audioInputs.push(...mixedTracks.filter((track) => text(record(track).kind ?? record(track).type)?.toUpperCase() === 'AUDIO')) + } + const normalizedSubtitles = subtitleInputs.map(normalizeSubtitle) + const mergedSubtitles = [...normalizedSubtitles.reduce((tracks, track) => { + const key = track.id.replace(/[-_:]?(ass|webvtt|vtt)$/i, '') || track.language + const existing = tracks.get(key) ?? [...tracks.values()].find((candidate) => candidate.language === track.language) + if (existing) { + if (track.assUrl) existing.assUrl = track.assUrl + if (track.vttUrl) existing.vttUrl = track.vttUrl + existing.fonts = [...new Set([...existing.fonts, ...track.fonts])] + } else { + tracks.set(key, track) + } + return tracks + }, new Map()).values()] + + return { + id, + state: normalizeState(payload.state ?? payload.status), + mediaItemId: text(payload.mediaItemId) ?? '', + ...(manifestUrl ? { manifestUrl } : {}), + ...(number(payload.durationSeconds ?? payload.duration) !== undefined + ? { durationSeconds: number(payload.durationSeconds ?? payload.duration) } + : {}), + pollAfterMs: Math.max(500, number(payload.pollAfterMs) ?? 1_500), + ...(number(payload.progress ?? payload.progressPercent) !== undefined + ? { progress: number(payload.progress ?? payload.progressPercent) } + : {}), + ...(text(payload.message) ? { message: text(payload.message) } : {}), + ...(text(payload.reasonCode ?? payload.code) ? { reasonCode: text(payload.reasonCode ?? payload.code) } : {}), + ...(text(payload.expiresAt) ? { expiresAt: text(payload.expiresAt) } : {}), + ...(text(payload.videoCodec) ? { videoCodec: text(payload.videoCodec) } : {}), + ...(text(payload.audioCodec) ? { audioCodec: text(payload.audioCodec) } : {}), + subtitles: mergedSubtitles, + audioTracks: audioInputs.map(normalizeAudio), + } +} + +async function request(path: string, init: RequestInit = {}): Promise { + const headers = new Headers(init.headers) + if (init.body && !headers.has('content-type')) headers.set('content-type', 'application/json') + headers.set('accept', 'application/json') + + const response = await fetch(`${API_BASE}${path}`, { + ...init, + headers, + credentials: 'include', + }) + + const contentType = response.headers.get('content-type') ?? '' + const body: unknown = response.status === 204 + ? undefined + : contentType.includes('application/json') + ? await response.json() + : await response.text() + + if (!response.ok) { + const outerError = record(body) + const error = Object.keys(record(outerError.error)).length ? record(outerError.error) : outerError + throw new ApiError( + text(error.message) ?? text(error.error) ?? `Request failed (${response.status})`, + response.status, + text(error.code ?? error.reasonCode), + ) + } + + return body +} + +function queryString(params: Record): string { + const query = new URLSearchParams() + Object.entries(params).forEach(([key, value]) => { + if (value !== undefined && value !== '') query.set(key, String(value)) + }) + const encoded = query.toString() + return encoded ? `?${encoded}` : '' +} + +function withSignal(signal: AbortSignal | undefined, init: RequestInit = {}): RequestInit { + return signal ? { ...init, signal } : init +} + +export const api = { + async catalog(options: { cursor?: string; limit?: number; kind?: string } = {}, signal?: AbortSignal): Promise { + const body = await request(`/catalog${queryString({ ...options })}`, withSignal(signal)) + const source = record(body) + const payload = Object.keys(record(source.data)).length ? record(source.data) : source + const rawItems = Array.isArray(body) ? body : array(payload.items ?? payload.results) + const nextCursor = text(payload.nextCursor ?? record(payload.pagination).nextCursor) + const total = number(payload.total ?? record(payload.pagination).total) + return { + items: rawItems.map(normalizeCatalogItem).filter((item) => item.id), + ...(nextCursor ? { nextCursor } : {}), + ...(total !== undefined ? { total } : {}), + } + }, + + async search(term: string, signal?: AbortSignal): Promise { + const body = await request(`/search${queryString({ q: term, limit: 40 })}`, withSignal(signal)) + const source = record(body) + const payload = Object.keys(record(source.data)).length ? record(source.data) : source + const rawItems = Array.isArray(body) ? body : array(payload.items ?? payload.results) + return { + items: rawItems.map(normalizeCatalogItem).filter((item) => item.id), + ...(number(payload.total) !== undefined ? { total: number(payload.total) } : {}), + } + }, + + async title(slug: string, signal?: AbortSignal): Promise { + const body = await request(`/titles/${encodeURIComponent(slug)}`, withSignal(signal)) + const source = record(body) + const payload = Object.keys(record(source.data)).length ? record(source.data) : source + const base = normalizeCatalogItem(payload) + const explicitSeasons = array(payload.seasons).map(normalizeSeason) + const mediaItems = array(payload.mediaItems).map((entry) => record(entry)) + const groupedSeasons = new Map() + mediaItems.forEach((entry) => { + const seasonNumber = number(entry.seasonNumber) ?? 0 + const episodes = groupedSeasons.get(seasonNumber) ?? [] + episodes.push(normalizeEpisode(entry, seasonNumber)) + groupedSeasons.set(seasonNumber, episodes) + }) + const seasons = explicitSeasons.some((season) => season.episodes.length) + ? explicitSeasons + : [...groupedSeasons.entries()] + .sort(([left], [right]) => left - right) + .map(([seasonNumber, episodes]) => ({ + number: seasonNumber, + title: { fa: `فصل ${seasonNumber}`, en: `Season ${seasonNumber}` }, + episodes: episodes.sort((left, right) => left.number - right.number), + })) + const firstPublishedMediaItem = mediaItems.find((item) => item.published !== false) + const playableMediaItemId = text(payload.resumeMediaItemId) + ?? text(payload.playableMediaItemId) + ?? text(firstPublishedMediaItem?.id) + return { + ...base, + mediaItemId: playableMediaItemId ?? '', + genres: array(payload.genres).map((genre) => localized(genre, record(genre).name)), + seasons, + ...(playableMediaItemId ? { playableMediaItemId } : {}), + } + }, + + async createPlaybackSession( + mediaItemId: string, + clientCapabilities: ClientCapabilities, + signal?: AbortSignal, + ): Promise { + const body = await request('/playback-sessions', withSignal(signal, { + method: 'POST', + body: JSON.stringify({ mediaItemId, clientCapabilities }), + })) + const session = normalizePlaybackSession(body) + return { ...session, mediaItemId: session.mediaItemId || mediaItemId } + }, + + async playbackSession(id: string, signal?: AbortSignal): Promise { + return normalizePlaybackSession(await request(`/playback-sessions/${encodeURIComponent(id)}`, withSignal(signal))) + }, + + async clientEvent(event: Record): Promise { + await request('/client-events', { method: 'POST', body: JSON.stringify(event), keepalive: true }) + }, + + async adminSession(signal?: AbortSignal): Promise<{ authenticated: boolean; name?: string }> { + const csrfToken = typeof sessionStorage === 'undefined' ? undefined : sessionStorage.getItem(ADMIN_CSRF_KEY) + if (!csrfToken) return { authenticated: false } + try { + await request('/admin/jobs', withSignal(signal)) + const email = typeof sessionStorage === 'undefined' ? undefined : sessionStorage.getItem(ADMIN_EMAIL_KEY) ?? undefined + return { authenticated: true, ...(email ? { name: email } : {}) } + } catch (error) { + if (error instanceof ApiError && error.status === 401) return { authenticated: false } + throw error + } + }, + + async adminLogin(email: string, password: string, totp?: string): Promise { + const body = record(await request('/admin/login', { + method: 'POST', + body: JSON.stringify({ email, password, ...(totp ? { totp } : {}) }), + })) + const csrfToken = text(body.csrfToken) + if (!csrfToken) throw new ApiError('Administrator login did not return a CSRF token', 500, 'CSRF_TOKEN_MISSING') + if (typeof sessionStorage !== 'undefined') { + sessionStorage.setItem(ADMIN_CSRF_KEY, csrfToken) + sessionStorage.setItem(ADMIN_EMAIL_KEY, text(record(body.admin).email) ?? email) + } + }, + + async adminLogout(): Promise { + const csrfToken = typeof sessionStorage === 'undefined' ? undefined : sessionStorage.getItem(ADMIN_CSRF_KEY) + try { + await request('/admin/logout', { + method: 'POST', + ...(csrfToken ? { headers: { 'x-csrf-token': csrfToken } } : {}), + }) + } finally { + if (typeof sessionStorage !== 'undefined') { + sessionStorage.removeItem(ADMIN_CSRF_KEY) + sessionStorage.removeItem(ADMIN_EMAIL_KEY) + } + } + }, + + async adminDashboard(signal?: AbortSignal): Promise { + const [jobsBody, cacheBody, catalogBody] = await Promise.all([ + request('/admin/jobs', withSignal(signal)), + request('/admin/cache', withSignal(signal)), + request('/catalog?limit=100', withSignal(signal)), + ]) + const jobsPayload = record(jobsBody) + const cache = record(cacheBody) + const catalog = record(catalogBody) + const jobs: AdminJob[] = array(jobsPayload.items ?? jobsPayload.jobs).map((input, index) => { + const item = record(input) + const rawProgress = number(item.progress) + return { + id: text(item.id) ?? `job-${index}`, + type: text(item.type) ?? 'UNKNOWN', + state: text(item.state ?? item.status) ?? 'UNKNOWN', + ...(rawProgress !== undefined ? { progress: rawProgress <= 1 ? rawProgress * 100 : rawProgress } : {}), + ...(text(item.message ?? item.error) ? { message: text(item.message ?? item.error) } : {}), + ...(text(item.createdAt) ? { createdAt: text(item.createdAt) } : {}), + } + }) + const catalogItems = array(catalog.items) + return { + catalogCount: catalogItems.length, + publishedCount: catalogItems.filter((item) => record(item).playable === true).length, + reviewCount: 0, + activeJobs: jobs.filter((job) => job.state === 'RUNNING' || job.state === 'QUEUED').length, + ...(number(cache.usedBytes) !== undefined + ? { cacheUsedBytes: number(cache.usedBytes) } + : {}), + ...(number(cache.maxBytes) !== undefined + ? { cacheCapacityBytes: number(cache.maxBytes) } + : {}), + jobs, + } + }, + + async startScan(): Promise<{ jobId?: string }> { + const csrfToken = typeof sessionStorage === 'undefined' ? undefined : sessionStorage.getItem(ADMIN_CSRF_KEY) + if (!csrfToken) throw new ApiError('Administrator session must be renewed', 401, 'ADMIN_SESSION_REQUIRED') + const body = record(await request('/admin/scans', { + method: 'POST', + headers: { 'x-csrf-token': csrfToken }, + body: JSON.stringify({ full: false }), + })) + const jobId = text(body.id ?? body.jobId ?? record(body.data).jobId) + return { ...(jobId ? { jobId } : {}) } + }, +} diff --git a/apps/web/src/components/AppHeader.vue b/apps/web/src/components/AppHeader.vue new file mode 100644 index 0000000..a53545a --- /dev/null +++ b/apps/web/src/components/AppHeader.vue @@ -0,0 +1,64 @@ + + + diff --git a/apps/web/src/components/BrandMark.test.ts b/apps/web/src/components/BrandMark.test.ts new file mode 100644 index 0000000..975f934 --- /dev/null +++ b/apps/web/src/components/BrandMark.test.ts @@ -0,0 +1,17 @@ +import { mount } from '@vue/test-utils' + +import BrandMark from './BrandMark.vue' + +describe('BrandMark', () => { + it('keeps SVG paint references unique across multiple instances', () => { + const wrapper = mount({ + components: { BrandMark }, + template: '
', + }) + const ids = wrapper.findAll('linearGradient').map((gradient) => gradient.attributes('id')) + + expect(new Set(ids).size).toBe(4) + expect(wrapper.findAll('svg')).toHaveLength(2) + expect(wrapper.findAll('svg').every((svg) => svg.attributes('aria-hidden') === 'true')).toBe(true) + }) +}) diff --git a/apps/web/src/components/BrandMark.vue b/apps/web/src/components/BrandMark.vue new file mode 100644 index 0000000..fc33d2a --- /dev/null +++ b/apps/web/src/components/BrandMark.vue @@ -0,0 +1,33 @@ + + + diff --git a/apps/web/src/components/LoadingState.vue b/apps/web/src/components/LoadingState.vue new file mode 100644 index 0000000..9430916 --- /dev/null +++ b/apps/web/src/components/LoadingState.vue @@ -0,0 +1,10 @@ + + + diff --git a/apps/web/src/components/MediaCard.test.ts b/apps/web/src/components/MediaCard.test.ts new file mode 100644 index 0000000..5ff74a7 --- /dev/null +++ b/apps/web/src/components/MediaCard.test.ts @@ -0,0 +1,54 @@ +import { createPinia } from 'pinia' +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' + +import MediaCard from '@/components/MediaCard.vue' +import { usePlayerStore } from '@/stores/player' +import type { CatalogItem } from '@/types' + +const item: CatalogItem = { + id: 'title-1', + mediaItemId: 'media-1', + slug: 'sample-title', + kind: 'MOVIE', + title: { fa: 'فیلم نمونه', en: 'Sample movie' }, + overview: {}, + playable: true, + year: 2026, +} + +describe('MediaCard', () => { + it('starts playback directly from the main card action', async () => { + const pinia = createPinia() + const start = vi.fn() + const store = usePlayerStore(pinia) + store.register({ start, close: vi.fn() }) + const wrapper = mount(MediaCard, { + props: { item }, + global: { + plugins: [pinia], + stubs: { + RouterLink: { template: '' }, + }, + }, + }) + + await wrapper.get('.media-card-play').trigger('click') + + expect(start).toHaveBeenCalledWith(expect.objectContaining({ mediaItemId: 'media-1', title: 'فیلم نمونه' })) + expect(store.visible).toBe(true) + }) + + it('disables direct play for unpublished media', () => { + const pinia = createPinia() + const wrapper = mount(MediaCard, { + props: { item: { ...item, playable: false } }, + global: { + plugins: [pinia], + stubs: { RouterLink: { template: '' } }, + }, + }) + + expect(wrapper.get('.media-card-play').attributes('disabled')).toBeDefined() + }) +}) diff --git a/apps/web/src/components/MediaCard.vue b/apps/web/src/components/MediaCard.vue new file mode 100644 index 0000000..1c41a98 --- /dev/null +++ b/apps/web/src/components/MediaCard.vue @@ -0,0 +1,68 @@ + + + diff --git a/apps/web/src/components/PlayerShell.vue b/apps/web/src/components/PlayerShell.vue new file mode 100644 index 0000000..dab4cca --- /dev/null +++ b/apps/web/src/components/PlayerShell.vue @@ -0,0 +1,713 @@ + + + diff --git a/apps/web/src/composables/spatial-navigation.test.ts b/apps/web/src/composables/spatial-navigation.test.ts new file mode 100644 index 0000000..c0dd568 --- /dev/null +++ b/apps/web/src/composables/spatial-navigation.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it, vi } from 'vitest' + +import { moveSpatialFocus } from '@/composables/spatial-navigation' + +function rect(left: number, top: number): DOMRect { + return { left, top, right: left + 100, bottom: top + 60, width: 100, height: 60, x: left, y: top, toJSON: () => ({}) } +} + +describe('moveSpatialFocus', () => { + it('moves to the nearest element in the requested physical direction', () => { + const root = document.createElement('div') + const first = document.createElement('button') + const right = document.createElement('button') + const below = document.createElement('button') + for (const button of [first, right, below]) { + button.dataset.tvFocus = '' + root.append(button) + } + document.body.append(root) + vi.spyOn(first, 'getBoundingClientRect').mockReturnValue(rect(0, 0)) + vi.spyOn(right, 'getBoundingClientRect').mockReturnValue(rect(180, 0)) + vi.spyOn(below, 'getBoundingClientRect').mockReturnValue(rect(0, 120)) + first.focus() + + expect(moveSpatialFocus(root, 'right')).toBe(true) + expect(document.activeElement).toBe(right) + expect(moveSpatialFocus(root, 'down')).toBe(true) + expect(document.activeElement).toBe(below) + }) + + it('focuses the first TV target when focus starts outside the region', () => { + const root = document.createElement('div') + const button = document.createElement('button') + button.dataset.tvFocus = '' + root.append(button) + document.body.append(root) + + expect(moveSpatialFocus(root, 'down')).toBe(true) + expect(document.activeElement).toBe(button) + }) +}) diff --git a/apps/web/src/composables/spatial-navigation.ts b/apps/web/src/composables/spatial-navigation.ts new file mode 100644 index 0000000..2f03677 --- /dev/null +++ b/apps/web/src/composables/spatial-navigation.ts @@ -0,0 +1,108 @@ +import { nextTick, onBeforeUnmount, onMounted, type Ref } from 'vue' + +type Direction = 'left' | 'right' | 'up' | 'down' + +function isTypingTarget(target: EventTarget | null): boolean { + return target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement +} + +function candidates(root: HTMLElement): HTMLElement[] { + return [...root.querySelectorAll('[data-tv-focus]:not([disabled])')] + .filter((element) => element.offsetParent !== null && element.getAttribute('aria-hidden') !== 'true') +} + +function scoreCandidate(current: DOMRect, candidate: DOMRect, direction: Direction): number | undefined { + const currentX = current.left + current.width / 2 + const currentY = current.top + current.height / 2 + const candidateX = candidate.left + candidate.width / 2 + const candidateY = candidate.top + candidate.height / 2 + const dx = candidateX - currentX + const dy = candidateY - currentY + + if (direction === 'left' && dx >= -1) return undefined + if (direction === 'right' && dx <= 1) return undefined + if (direction === 'up' && dy >= -1) return undefined + if (direction === 'down' && dy <= 1) return undefined + + const primary = direction === 'left' || direction === 'right' ? Math.abs(dx) : Math.abs(dy) + const secondary = direction === 'left' || direction === 'right' ? Math.abs(dy) : Math.abs(dx) + return primary + secondary * 2.25 +} + +export function moveSpatialFocus(root: HTMLElement, direction: Direction): boolean { + const focusable = candidates(root) + if (!focusable.length) return false + const active = document.activeElement instanceof HTMLElement && root.contains(document.activeElement) + ? document.activeElement + : undefined + if (!active) { + focusable[0]?.focus() + return true + } + + const currentRect = active.getBoundingClientRect() + const ranked = focusable + .filter((element) => element !== active) + .map((element) => ({ element, score: scoreCandidate(currentRect, element.getBoundingClientRect(), direction) })) + .filter((result): result is { element: HTMLElement; score: number } => result.score !== undefined) + .sort((left, right) => left.score - right.score) + const next = ranked[0]?.element + if (!next) return false + next.focus() + next.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'nearest' }) + return true +} + +export function useSpatialNavigation( + root: Ref, + options: { onBack?: () => void; restoreKey?: string } = {}, +) { + const onKeydown = (event: KeyboardEvent) => { + if (event.defaultPrevented) return + const element = root.value + if (!element || element.offsetParent === null || isTypingTarget(event.target)) return + const directionByKey: Partial> = { + ArrowLeft: 'left', + ArrowRight: 'right', + ArrowUp: 'up', + ArrowDown: 'down', + } + const direction = directionByKey[event.key] + if (direction && moveSpatialFocus(element, direction)) { + event.preventDefault() + return + } + if ((event.key === 'Escape' || event.key === 'BrowserBack' || event.key === 'Backspace') && options.onBack) { + event.preventDefault() + options.onBack() + } + } + + const rememberFocus = (event: FocusEvent) => { + const target = event.target + if (options.restoreKey && target instanceof HTMLElement && target.dataset.focusId) { + sessionStorage.setItem(options.restoreKey, target.dataset.focusId) + } + } + + const restoreFocus = async () => { + await nextTick() + const element = root.value + if (!element) return + const id = options.restoreKey ? sessionStorage.getItem(options.restoreKey) : undefined + const escapedId = id && typeof CSS !== 'undefined' && typeof CSS.escape === 'function' ? CSS.escape(id) : id + const previous = escapedId ? element.querySelector(`[data-focus-id="${escapedId}"]`) : undefined + ;(previous ?? candidates(element)[0])?.focus() + } + + onMounted(() => { + document.addEventListener('keydown', onKeydown) + root.value?.addEventListener('focusin', rememberFocus) + }) + onBeforeUnmount(() => { + document.removeEventListener('keydown', onKeydown) + root.value?.removeEventListener('focusin', rememberFocus) + }) + + return { restoreFocus } +} diff --git a/apps/web/src/env.d.ts b/apps/web/src/env.d.ts new file mode 100644 index 0000000..17aa348 --- /dev/null +++ b/apps/web/src/env.d.ts @@ -0,0 +1,9 @@ +/// + +interface ImportMetaEnv { + readonly VITE_API_BASE_URL?: string +} + +interface ImportMeta { + readonly env: ImportMetaEnv +} diff --git a/apps/web/src/i18n.ts b/apps/web/src/i18n.ts new file mode 100644 index 0000000..e30ab3a --- /dev/null +++ b/apps/web/src/i18n.ts @@ -0,0 +1,139 @@ +import { computed } from 'vue' + +import { useUiStore } from '@/stores/ui' + +const fa = { + home: 'خانه', + search: 'جستجو', + searchPlaceholder: 'نام فیلم یا سریال…', + admin: 'مدیریت', + language: 'زبان', + switchLanguage: 'English', + featured: 'پیشنهاد برای تماشا', + allTitles: 'همه عنوان‌ها', + movies: 'فیلم‌ها', + series: 'سریال‌ها', + play: 'پخش', + resume: 'ادامه پخش', + details: 'جزئیات', + retry: 'تلاش دوباره', + close: 'بستن', + back: 'بازگشت', + loading: 'در حال بارگذاری…', + loadingCatalog: 'در حال آماده‌کردن آرشیو…', + emptyCatalog: 'هنوز عنوان منتشرشده‌ای وجود ندارد.', + noResults: 'نتیجه‌ای پیدا نشد.', + networkError: 'ارتباط با سرور برقرار نشد.', + preparing: 'فیلم برای اولین پخش آماده می‌شود', + preparingHint: 'این صفحه را باز نگه دارید؛ پخش به‌صورت خودکار شروع می‌شود.', + incompatibleTitle: 'این مرورگر امکان پخش این ویدیو را ندارد', + incompatibleBody: 'برای پخش از نسخه جدید Chrome یا Firefox روی دستگاهی با پشتیبانی MSE استفاده کنید.', + playbackFailed: 'پخش ویدیو با مشکل روبه‌رو شد', + pressPlay: 'برای شروع، دکمه پخش را بزنید', + pause: 'مکث', + seekBack: '۱۰ ثانیه عقب', + seekForward: '۱۰ ثانیه جلو', + fullscreen: 'تمام‌صفحه', + exitFullscreen: 'خروج از تمام‌صفحه', + subtitles: 'زیرنویس', + audio: 'صدا', + subtitleOff: 'خاموش', + season: 'فصل', + episode: 'قسمت', + minutes: 'دقیقه', + loginTitle: 'ورود مدیر', + email: 'ایمیل', + password: 'رمز عبور', + totp: 'کد یک‌بارمصرف (اختیاری)', + login: 'ورود', + logout: 'خروج', + invalidLogin: 'اطلاعات ورود پذیرفته نشد.', + dashboard: 'وضعیت سامانه', + catalogCount: 'کل عنوان‌ها', + publishedCount: 'منتشرشده', + reviewCount: 'نیازمند بررسی', + activeJobs: 'کارهای فعال', + cache: 'حافظه موقت', + recentJobs: 'کارهای اخیر', + scanArchive: 'اسکن آرشیو', + scanStarted: 'اسکن آرشیو در صف قرار گرفت.', + refresh: 'به‌روزرسانی', + unavailable: 'ناموجود', + unsupported: 'پشتیبانی‌نشده', + year: 'سال', +} as const + +const en: Record = { + home: 'Home', + search: 'Search', + searchPlaceholder: 'Movie or series name…', + admin: 'Admin', + language: 'Language', + switchLanguage: 'فارسی', + featured: 'Featured', + allTitles: 'All titles', + movies: 'Movies', + series: 'Series', + play: 'Play', + resume: 'Resume', + details: 'Details', + retry: 'Try again', + close: 'Close', + back: 'Back', + loading: 'Loading…', + loadingCatalog: 'Loading the archive…', + emptyCatalog: 'No published titles yet.', + noResults: 'No results found.', + networkError: 'Could not reach the server.', + preparing: 'Preparing this title for its first stream', + preparingHint: 'Keep this screen open; playback starts automatically.', + incompatibleTitle: 'This browser cannot play this video', + incompatibleBody: 'Use a recent Chrome or Firefox on a device with Media Source Extensions.', + playbackFailed: 'Playback ran into a problem', + pressPlay: 'Press Play to begin', + pause: 'Pause', + seekBack: 'Back 10 seconds', + seekForward: 'Forward 10 seconds', + fullscreen: 'Fullscreen', + exitFullscreen: 'Exit fullscreen', + subtitles: 'Subtitles', + audio: 'Audio', + subtitleOff: 'Off', + season: 'Season', + episode: 'Episode', + minutes: 'min', + loginTitle: 'Administrator sign in', + email: 'Email', + password: 'Password', + totp: 'One-time code (optional)', + login: 'Sign in', + logout: 'Sign out', + invalidLogin: 'Those credentials were not accepted.', + dashboard: 'System status', + catalogCount: 'Catalog titles', + publishedCount: 'Published', + reviewCount: 'Needs review', + activeJobs: 'Active jobs', + cache: 'Hot cache', + recentJobs: 'Recent jobs', + scanArchive: 'Scan archive', + scanStarted: 'Archive scan was queued.', + refresh: 'Refresh', + unavailable: 'Unavailable', + unsupported: 'Unsupported', + year: 'Year', +} + +export type TranslationKey = keyof typeof fa + +export function useI18n() { + const ui = useUiStore() + const language = computed(() => ui.preferences.uiLanguage) + const isRtl = computed(() => language.value === 'fa') + const t = (key: TranslationKey): string => (language.value === 'fa' ? fa[key] : en[key]) + const localize = (value: { fa?: string | undefined; en?: string | undefined } | undefined, fallback = ''): string => { + if (!value) return fallback + return language.value === 'fa' ? value.fa ?? value.en ?? fallback : value.en ?? value.fa ?? fallback + } + return { language, isRtl, t, localize } +} diff --git a/apps/web/src/main.ts b/apps/web/src/main.ts new file mode 100644 index 0000000..65f1f7f --- /dev/null +++ b/apps/web/src/main.ts @@ -0,0 +1,17 @@ +import '@fontsource/vazirmatn/400.css' +import '@fontsource/vazirmatn/700.css' +import { createPinia } from 'pinia' +import { createApp } from 'vue' + +import App from '@/App.vue' +import { router } from '@/router' +import { useUiStore } from '@/stores/ui' +import '@/styles.css' + +const app = createApp(App) +const pinia = createPinia() +app.use(pinia) +app.use(router) +app.mount('#app') + +void useUiStore(pinia).hydrate() diff --git a/apps/web/src/router.ts b/apps/web/src/router.ts new file mode 100644 index 0000000..f66356a --- /dev/null +++ b/apps/web/src/router.ts @@ -0,0 +1,18 @@ +import { createRouter, createWebHistory } from 'vue-router' + +import AdminView from '@/views/AdminView.vue' +import CatalogView from '@/views/CatalogView.vue' +import SearchView from '@/views/SearchView.vue' +import TitleView from '@/views/TitleView.vue' + +export const router = createRouter({ + history: createWebHistory(), + scrollBehavior: (_to, _from, savedPosition) => savedPosition ?? { top: 0 }, + routes: [ + { path: '/', name: 'catalog', component: CatalogView }, + { path: '/search', name: 'search', component: SearchView }, + { path: '/title/:slug', name: 'title', component: TitleView }, + { path: '/admin', name: 'admin', component: AdminView }, + { path: '/:pathMatch(.*)*', redirect: '/' }, + ], +}) diff --git a/apps/web/src/storage/viewer-db.test.ts b/apps/web/src/storage/viewer-db.test.ts new file mode 100644 index 0000000..c39666e --- /dev/null +++ b/apps/web/src/storage/viewer-db.test.ts @@ -0,0 +1,37 @@ +import { beforeEach, describe, expect, it } from 'vitest' + +import { + __resetMemoryStorageForTests, + readPreferences, + readProgress, + writePreferences, + writeProgress, +} from '@/storage/viewer-db' + +describe('viewer storage', () => { + beforeEach(() => __resetMemoryStorageForTests()) + + it('persists viewer preferences without requiring an account', async () => { + await writePreferences({ + uiLanguage: 'en', + subtitleLanguage: 'en', + audioLanguage: 'ja', + volume: 0.7, + muted: false, + }) + + await expect(readPreferences()).resolves.toMatchObject({ uiLanguage: 'en', subtitleLanguage: 'en', volume: 0.7 }) + }) + + it('stores resume progress by media item', async () => { + await writeProgress({ + mediaItemId: 'episode-1', + positionSeconds: 640, + durationSeconds: 1420, + updatedAt: 10, + completed: false, + }) + + await expect(readProgress('episode-1')).resolves.toMatchObject({ positionSeconds: 640, completed: false }) + }) +}) diff --git a/apps/web/src/storage/viewer-db.ts b/apps/web/src/storage/viewer-db.ts new file mode 100644 index 0000000..1cdd67c --- /dev/null +++ b/apps/web/src/storage/viewer-db.ts @@ -0,0 +1,104 @@ +import type { ProgressRecord, ViewerPreferences } from '@/types' + +const DATABASE_NAME = 'easy-stream-viewer' +const DATABASE_VERSION = 1 +const SETTINGS_STORE = 'settings' +const PROGRESS_STORE = 'progress' + +export const defaultPreferences: ViewerPreferences = { + uiLanguage: 'fa', + subtitleLanguage: 'fa', + audioLanguage: 'ja', + volume: 1, + muted: false, +} + +let databasePromise: Promise | undefined +let memoryPreferences: ViewerPreferences = { ...defaultPreferences } +const memoryProgress = new Map() + +function openDatabase(): Promise { + if (databasePromise) return databasePromise + databasePromise = new Promise((resolve) => { + if (typeof indexedDB === 'undefined') { + resolve(null) + return + } + + const request = indexedDB.open(DATABASE_NAME, DATABASE_VERSION) + request.onupgradeneeded = () => { + const database = request.result + if (!database.objectStoreNames.contains(SETTINGS_STORE)) { + database.createObjectStore(SETTINGS_STORE, { keyPath: 'key' }) + } + if (!database.objectStoreNames.contains(PROGRESS_STORE)) { + database.createObjectStore(PROGRESS_STORE, { keyPath: 'mediaItemId' }) + } + } + request.onsuccess = () => resolve(request.result) + request.onerror = () => resolve(null) + request.onblocked = () => resolve(null) + }) + return databasePromise +} + +async function getRecord(storeName: string, key: IDBValidKey): Promise { + const database = await openDatabase() + if (!database) return undefined + return new Promise((resolve) => { + const transaction = database.transaction(storeName, 'readonly') + const request = transaction.objectStore(storeName).get(key) + request.onsuccess = () => resolve(request.result as T | undefined) + request.onerror = () => resolve(undefined) + }) +} + +async function putRecord(storeName: string, value: unknown): Promise { + const database = await openDatabase() + if (!database) return + await new Promise((resolve) => { + const transaction = database.transaction(storeName, 'readwrite') + transaction.objectStore(storeName).put(value) + transaction.oncomplete = () => resolve() + transaction.onerror = () => resolve() + transaction.onabort = () => resolve() + }) +} + +export async function readPreferences(): Promise { + const result = await getRecord<{ key: string; value: Partial }>(SETTINGS_STORE, 'viewer') + if (!result) return { ...memoryPreferences } + memoryPreferences = { ...defaultPreferences, ...result.value } + return { ...memoryPreferences } +} + +export async function writePreferences(preferences: ViewerPreferences): Promise { + memoryPreferences = { ...preferences } + await putRecord(SETTINGS_STORE, { key: 'viewer', value: preferences }) +} + +export async function readProgress(mediaItemId: string): Promise { + const result = await getRecord(PROGRESS_STORE, mediaItemId) + return result ?? memoryProgress.get(mediaItemId) +} + +export async function writeProgress(progress: ProgressRecord): Promise { + memoryProgress.set(progress.mediaItemId, progress) + await putRecord(PROGRESS_STORE, progress) +} + +export async function listProgress(): Promise { + const database = await openDatabase() + if (!database) return [...memoryProgress.values()] + return new Promise((resolve) => { + const transaction = database.transaction(PROGRESS_STORE, 'readonly') + const request = transaction.objectStore(PROGRESS_STORE).getAll() + request.onsuccess = () => resolve(request.result as ProgressRecord[]) + request.onerror = () => resolve([...memoryProgress.values()]) + }) +} + +export function __resetMemoryStorageForTests(): void { + memoryPreferences = { ...defaultPreferences } + memoryProgress.clear() +} diff --git a/apps/web/src/stores/player.ts b/apps/web/src/stores/player.ts new file mode 100644 index 0000000..557f02b --- /dev/null +++ b/apps/web/src/stores/player.ts @@ -0,0 +1,42 @@ +import { defineStore } from 'pinia' +import { markRaw } from 'vue' + +export interface PlayRequest { + mediaItemId: string + title: string + posterUrl?: string +} + +export interface PlayerController { + start(request: PlayRequest): void + close(): void +} + +export const usePlayerStore = defineStore('player', { + state: () => ({ + visible: false, + controller: undefined as PlayerController | undefined, + current: undefined as PlayRequest | undefined, + }), + + actions: { + register(controller: PlayerController) { + this.controller = markRaw(controller) + }, + + unregister(controller: PlayerController) { + if (this.controller === controller) this.controller = undefined + }, + + play(request: PlayRequest) { + this.current = request + this.visible = true + this.controller?.start(request) + }, + + close() { + this.controller?.close() + this.visible = false + }, + }, +}) diff --git a/apps/web/src/stores/ui.ts b/apps/web/src/stores/ui.ts new file mode 100644 index 0000000..a418f68 --- /dev/null +++ b/apps/web/src/stores/ui.ts @@ -0,0 +1,47 @@ +import { defineStore } from 'pinia' + +import { defaultPreferences, readPreferences, writePreferences } from '@/storage/viewer-db' +import type { UiLanguage, ViewerPreferences } from '@/types' + +function applyDocumentLanguage(language: UiLanguage): void { + if (typeof document === 'undefined') return + document.documentElement.lang = language + document.documentElement.dir = language === 'fa' ? 'rtl' : 'ltr' +} + +export const useUiStore = defineStore('ui', { + state: () => ({ + preferences: { ...defaultPreferences } as ViewerPreferences, + hydrated: false, + }), + + actions: { + async hydrate() { + this.preferences = await readPreferences() + this.hydrated = true + applyDocumentLanguage(this.preferences.uiLanguage) + }, + + async setLanguage(language: UiLanguage) { + this.preferences.uiLanguage = language + applyDocumentLanguage(language) + await writePreferences({ ...this.preferences }) + }, + + async setSubtitleLanguage(language: string) { + this.preferences.subtitleLanguage = language + await writePreferences({ ...this.preferences }) + }, + + async setAudioLanguage(language: string) { + this.preferences.audioLanguage = language + await writePreferences({ ...this.preferences }) + }, + + async setVolume(volume: number, muted: boolean) { + this.preferences.volume = Math.min(1, Math.max(0, volume)) + this.preferences.muted = muted + await writePreferences({ ...this.preferences }) + }, + }, +}) diff --git a/apps/web/src/styles.css b/apps/web/src/styles.css new file mode 100644 index 0000000..1f11859 --- /dev/null +++ b/apps/web/src/styles.css @@ -0,0 +1,1358 @@ +:root { + color-scheme: dark; + font-family: Vazirmatn, Tahoma, "Segoe UI", system-ui, -apple-system, sans-serif; + color: #f7f8fc; + background: #070a12; + font-synthesis: none; + text-rendering: optimizeLegibility; + --bg: #070a12; + --panel: #101522; + --panel-raised: #171d2b; + --text: #f7f8fc; + --muted: #a9b0c0; + --line: rgb(255 255 255 / 12%); + --accent: #efb52f; + --accent-strong: #ffd56f; + --danger: #ff707d; + --success: #58d6a1; + --header-height: 76px; +} + +* { + box-sizing: border-box; +} + +html { + min-width: 320px; + min-height: 100%; + background: var(--bg); +} + +body { + min-width: 320px; + min-height: 100vh; + margin: 0; + overflow-x: hidden; + background: + radial-gradient(circle at 75% -10%, rgb(40 57 93 / 35%), transparent 36rem), + var(--bg); +} + +button, +input { + font: inherit; +} + +button, +a { + -webkit-tap-highlight-color: transparent; +} + +button { + color: inherit; +} + +a { + color: inherit; + text-decoration: none; +} + +img { + display: block; + max-width: 100%; +} + +svg { + width: 1.35em; + height: 1.35em; + fill: currentColor; + stroke: currentColor; + stroke-width: 1.8; + stroke-linecap: round; + stroke-linejoin: round; +} + +.skip-link { + position: fixed; + z-index: 10000; + inset-block-start: 0.75rem; + inset-inline-start: 0.75rem; + padding: 0.75rem 1rem; + color: #111; + background: var(--accent-strong); + border-radius: 0.5rem; + transform: translateY(-150%); +} + +.skip-link:focus { + transform: translateY(0); +} + +.app-shell { + min-height: 100vh; +} + +.app-header { + position: sticky; + z-index: 40; + inset-block-start: 0; + display: flex; + align-items: center; + gap: clamp(0.75rem, 2vw, 2.25rem); + height: var(--header-height); + padding: 0 clamp(1rem, 4vw, 4.5rem); + background: rgb(7 10 18 / 84%); + border-block-end: 1px solid rgb(255 255 255 / 6%); + backdrop-filter: blur(18px); +} + +.brand { + display: inline-flex; + flex: 0 0 auto; + align-items: center; + gap: 0.72rem; + padding: 0.28rem; + margin: -0.28rem; + border-radius: 0.9rem; +} + +.brand-symbol { + display: block; + flex: 0 0 auto; + width: 2.65rem; + height: 2.65rem; + filter: drop-shadow(0 0.6rem 1rem rgb(239 181 47 / 18%)); +} + +.brand-wordmark { + direction: ltr; + color: var(--text); + font-family: "Segoe UI", system-ui, sans-serif; + font-size: 1.04rem; + font-weight: 760; + letter-spacing: -0.025em; + line-height: 1; + white-space: nowrap; +} + +.brand-wordmark strong { + color: var(--accent-strong); + font-weight: 820; +} + +.brand-easy { + margin-inline-end: 0.24em; +} + +.primary-nav { + display: flex; + align-items: center; + gap: 0.25rem; +} + +.nav-link, +.language-button { + min-height: 2.75rem; + padding: 0.65rem 0.9rem; + color: var(--muted); + font-size: 0.94rem; + font-weight: 650; + background: transparent; + border: 0; + border-radius: 0.7rem; + cursor: pointer; +} + +.nav-link:hover, +.nav-link.router-link-exact-active, +.language-button:hover { + color: var(--text); + background: rgb(255 255 255 / 7%); +} + +.header-search { + display: flex; + flex: 1 1 18rem; + align-items: center; + gap: 0.65rem; + max-width: 30rem; + min-width: 9rem; + margin-inline-start: auto; + padding: 0 0.9rem; + color: var(--muted); + background: rgb(255 255 255 / 7%); + border: 1px solid transparent; + border-radius: 0.8rem; +} + +.header-search:focus-within { + color: var(--text); + border-color: var(--accent); + box-shadow: 0 0 0 3px rgb(239 181 47 / 16%); +} + +.header-search svg, +.large-search svg { + flex: 0 0 auto; + fill: none; +} + +.header-search input { + width: 100%; + height: 2.75rem; + color: var(--text); + background: transparent; + border: 0; + outline: 0; +} + +.header-search input::placeholder, +.large-search input::placeholder { + color: #8991a3; +} + +.main-content { + min-height: calc(100vh - var(--header-height) - 7rem); + outline: 0; +} + +.app-footer { + display: flex; + justify-content: center; + gap: 0.65rem; + padding: 3.5rem 1rem 2.5rem; + color: #737c90; + font-size: 0.78rem; + direction: ltr; +} + +.footer-brand { + display: inline-flex; + align-items: center; + gap: 0.45rem; + color: #9299a8; + font-weight: 650; +} + +.footer-brand .brand-symbol { + width: 1.35rem; + height: 1.35rem; + filter: none; +} + +.app-footer a:hover { + color: var(--text); +} + +.footer-dot { + color: #394052; +} + +.focus-ring:focus, +[data-tv-focus]:focus { + outline: 3px solid var(--accent-strong); + outline-offset: 4px; +} + +@supports selector(:focus-visible) { + .focus-ring:focus:not(:focus-visible), + [data-tv-focus]:focus:not(:focus-visible) { + outline: none; + } + + .focus-ring:focus-visible, + [data-tv-focus]:focus-visible { + outline: 3px solid var(--accent-strong); + outline-offset: 4px; + } +} + +.catalog-view, +.page-view, +.title-view { + min-height: calc(100vh - var(--header-height)); +} + +.hero, +.detail-hero { + position: relative; + display: flex; + min-height: min(68vh, 48rem); + align-items: flex-end; + overflow: hidden; + isolation: isolate; + background-color: #101522; + background-repeat: no-repeat; + background-position: center 24%; + background-size: cover; +} + +.hero::before, +.detail-hero::before { + position: absolute; + z-index: -2; + inset: 0; + background: + radial-gradient(circle at 70% 25%, rgb(73 91 127 / 38%), transparent 40%), + linear-gradient(125deg, #151c2e, #090c15 65%); + content: ""; +} + +.hero-scrim { + position: absolute; + z-index: -1; + inset: 0; + background: + linear-gradient(to top, var(--bg) 0%, rgb(7 10 18 / 78%) 25%, transparent 65%), + linear-gradient(to left, rgb(7 10 18 / 84%), rgb(7 10 18 / 12%) 70%); +} + +[dir="ltr"] .hero-scrim { + background: + linear-gradient(to top, var(--bg) 0%, rgb(7 10 18 / 78%) 25%, transparent 65%), + linear-gradient(to right, rgb(7 10 18 / 84%), rgb(7 10 18 / 12%) 70%); +} + +.hero-content, +.detail-copy { + width: min(47rem, 90%); + padding: clamp(3rem, 9vw, 8rem) clamp(1.25rem, 6vw, 6.5rem) clamp(3rem, 8vw, 6.5rem); +} + +.eyebrow { + margin: 0 0 0.8rem; + color: var(--accent-strong); + font-size: 0.75rem; + font-weight: 800; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.hero h1, +.detail-copy h1, +.page-heading h1, +.admin-heading h1 { + max-width: 18ch; + margin: 0; + font-size: clamp(2rem, 5vw, 4.6rem); + line-height: 1.08; + text-wrap: balance; +} + +.hero-overview { + display: -webkit-box; + max-width: 62ch; + margin: 1.3rem 0 1.8rem; + overflow: hidden; + color: #d4d8e1; + font-size: clamp(0.95rem, 1.4vw, 1.13rem); + line-height: 1.9; + -webkit-box-orient: vertical; + -webkit-line-clamp: 4; +} + +.hero-actions, +.admin-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.85rem; +} + +.primary-button, +.secondary-button, +.text-button { + display: inline-flex; + min-height: 2.9rem; + align-items: center; + justify-content: center; + gap: 0.55rem; + padding: 0.7rem 1.15rem; + font-weight: 750; + border: 0; + border-radius: 0.75rem; + cursor: pointer; +} + +.primary-button { + color: #171108; + background: var(--accent-strong); + box-shadow: 0 0.6rem 1.7rem rgb(239 181 47 / 16%); +} + +.primary-button:hover { + background: #ffe195; + transform: translateY(-1px); +} + +.secondary-button { + color: var(--text); + background: rgb(255 255 255 / 12%); + border: 1px solid rgb(255 255 255 / 8%); +} + +.secondary-button:hover { + background: rgb(255 255 255 / 18%); +} + +.text-button { + color: var(--muted); + background: transparent; +} + +.large { + min-height: 3.35rem; + padding-inline: 1.55rem; + font-size: 1.02rem; +} + +button:disabled, +.primary-button:disabled { + cursor: not-allowed; + opacity: 0.45; + transform: none; +} + +.catalog-section, +.episodes-section, +.jobs-panel { + padding: 1.5rem clamp(1rem, 4vw, 4.5rem) 2.5rem; +} + +.catalog-section h2, +.episodes-section h2, +.jobs-panel h2 { + margin: 0 0 1.2rem; + font-size: clamp(1.25rem, 2vw, 1.65rem); +} + +.media-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(min(10rem, 42vw), 1fr)); + gap: clamp(1rem, 2vw, 1.6rem); +} + +.media-card { + min-width: 0; +} + +.media-card-play { + position: relative; + display: block; + width: 100%; + padding: 0; + overflow: hidden; + color: white; + aspect-ratio: 2 / 3; + background: #151b29; + border: 1px solid rgb(255 255 255 / 8%); + border-radius: 0.75rem; + cursor: pointer; + box-shadow: 0 1rem 2.5rem rgb(0 0 0 / 14%); + transition: transform 160ms ease, box-shadow 160ms ease, border-color 160ms ease; +} + +.media-card-play img, +.poster-placeholder, +.card-gradient { + position: absolute; + width: 100%; + height: 100%; + inset: 0; + object-fit: cover; +} + +.poster-placeholder { + display: grid; + place-items: center; + background: + radial-gradient(circle at 70% 20%, rgb(239 181 47 / 20%), transparent 45%), + linear-gradient(145deg, #242c40, #111622); +} + +.poster-placeholder span { + color: rgb(255 255 255 / 16%); + font-size: clamp(4rem, 10vw, 8rem); + font-weight: 900; +} + +.card-gradient { + background: linear-gradient(to top, rgb(5 7 12 / 88%), transparent 42%); + opacity: 0.5; +} + +.card-play-icon { + position: absolute; + display: grid; + width: 3.2rem; + height: 3.2rem; + place-items: center; + inset-block-start: 50%; + inset-inline-start: 50%; + background: rgb(255 213 111 / 94%); + border-radius: 50%; + color: #171108; + opacity: 0; + transform: translate(50%, -40%) scale(0.9); + transition: 160ms ease; +} + +[dir="ltr"] .card-play-icon { + transform: translate(-50%, -40%) scale(0.9); +} + +.media-card-play:hover, +.media-card-play:focus { + z-index: 2; + border-color: rgb(255 213 111 / 55%); + box-shadow: 0 1.3rem 3rem rgb(0 0 0 / 42%); + transform: translateY(-0.35rem) scale(1.015); +} + +.media-card-play:hover .card-play-icon, +.media-card-play:focus .card-play-icon { + opacity: 1; + transform: translate(50%, -50%) scale(1); +} + +[dir="ltr"] .media-card-play:hover .card-play-icon, +[dir="ltr"] .media-card-play:focus .card-play-icon { + transform: translate(-50%, -50%) scale(1); +} + +.availability-badge { + position: absolute; + inset-block-start: 0.7rem; + inset-inline-end: 0.7rem; + padding: 0.4rem 0.6rem; + color: #eee; + font-size: 0.7rem; + background: rgb(15 18 26 / 86%); + border-radius: 0.45rem; +} + +.progress-track { + position: absolute; + height: 4px; + inset: auto 0.55rem 0.55rem; + overflow: hidden; + background: rgb(255 255 255 / 28%); + border-radius: 10rem; +} + +.progress-track span { + display: block; + height: 100%; + background: var(--accent-strong); +} + +.is-unavailable .media-card-play { + filter: saturate(0.3); +} + +.card-copy { + position: relative; + padding: 0.85rem 0.25rem 0; +} + +.card-copy h3 { + margin: 0; + overflow: hidden; + font-size: 0.96rem; + font-weight: 700; + line-height: 1.6; + text-overflow: ellipsis; + white-space: nowrap; +} + +.card-meta { + display: flex; + gap: 0.6rem; + color: var(--muted); + font-size: 0.75rem; +} + +.card-meta span + span::before, +.detail-meta span + span::before { + margin-inline-end: 0.6rem; + color: #50586a; + content: "•"; +} + +.card-info { + display: inline-block; + margin-block-start: 0.45rem; + color: #c6ccda; + font-size: 0.78rem; + border-radius: 0.3rem; +} + +.card-info:hover { + color: var(--accent-strong); +} + +.center-state { + display: flex; + min-height: 45vh; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 1rem; + padding: 2rem; + color: var(--muted); + text-align: center; +} + +.center-state h1, +.center-state h2, +.center-state p { + margin: 0; +} + +.error-state h1, +.error-state h2 { + color: var(--text); +} + +.spinner { + display: block; + width: 2.2rem; + height: 2.2rem; + border: 3px solid rgb(255 255 255 / 14%); + border-block-start-color: var(--accent-strong); + border-radius: 50%; + animation: spin 0.8s linear infinite; +} + +.spinner.large { + width: 3.8rem; + height: 3.8rem; + border-width: 4px; +} + +@keyframes spin { + to { transform: rotate(360deg); } +} + +.page-view { + padding: clamp(2rem, 5vw, 5rem) clamp(1rem, 4vw, 4.5rem); +} + +.page-view .catalog-section { + padding-inline: 0; +} + +.page-heading { + margin-block-end: 2rem; +} + +.page-heading h1 { + font-size: clamp(2rem, 4vw, 3.6rem); +} + +.large-search { + display: flex; + width: min(46rem, 100%); + align-items: center; + gap: 0.85rem; + margin-block-start: 1.6rem; + padding-inline: 1.1rem; + color: var(--muted); + background: var(--panel-raised); + border: 1px solid var(--line); + border-radius: 1rem; +} + +.large-search:focus-within { + border-color: var(--accent); + box-shadow: 0 0 0 4px rgb(239 181 47 / 14%); +} + +.large-search input { + width: 100%; + height: 4rem; + color: var(--text); + font-size: 1.05rem; + background: transparent; + border: 0; + outline: 0; +} + +.detail-hero { + min-height: min(72vh, 50rem); + align-items: center; +} + +.detail-copy { + padding-block-start: 7rem; +} + +.detail-meta { + display: flex; + flex-wrap: wrap; + margin-block-start: 1rem; + color: #c7ccda; + font-size: 0.86rem; +} + +.back-button { + position: absolute; + inset-block-start: 2rem; + inset-inline-start: clamp(1rem, 4vw, 4.5rem); + display: flex; + min-height: 2.8rem; + align-items: center; + gap: 0.5rem; + padding: 0.6rem 0.85rem; + color: var(--text); + background: rgb(7 10 18 / 62%); + border: 1px solid var(--line); + border-radius: 0.7rem; + backdrop-filter: blur(8px); + cursor: pointer; +} + +[dir="rtl"] .back-button svg, +[dir="rtl"] .player-topbar .player-icon-button svg { + transform: rotate(180deg); +} + +.episodes-section { + padding-block-start: 2.5rem; +} + +.episode-list { + display: grid; + gap: 0.65rem; + max-width: 72rem; +} + +.episode-row { + display: grid; + grid-template-columns: 3rem minmax(0, 1fr) 2rem; + align-items: center; + gap: 1rem; + width: 100%; + padding: 1rem; + color: var(--text); + text-align: start; + background: var(--panel); + border: 1px solid var(--line); + border-radius: 0.8rem; + cursor: pointer; +} + +.episode-row:hover, +.episode-row:focus { + background: var(--panel-raised); + border-color: rgb(255 213 111 / 42%); +} + +.episode-number { + display: grid; + width: 2.6rem; + height: 2.6rem; + place-items: center; + color: var(--accent-strong); + font-weight: 800; + background: rgb(239 181 47 / 10%); + border-radius: 50%; +} + +.episode-copy { + min-width: 0; +} + +.episode-copy strong, +.episode-copy small { + display: block; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.episode-copy small { + margin-block-start: 0.3rem; + color: var(--muted); +} + +.episode-play { + color: var(--accent-strong); +} + +.login-panel { + width: min(30rem, 100%); + margin: 4vh auto; + padding: clamp(1.4rem, 4vw, 2.5rem); + background: linear-gradient(145deg, rgb(23 29 43 / 96%), rgb(13 17 27 / 96%)); + border: 1px solid var(--line); + border-radius: 1.2rem; + box-shadow: 0 2rem 5rem rgb(0 0 0 / 28%); +} + +.login-panel h1 { + margin: 0 0 2rem; + font-size: 1.8rem; +} + +.login-panel form, +.login-panel label { + display: grid; + gap: 0.55rem; +} + +.login-panel form { + gap: 1.2rem; +} + +.login-panel label span { + color: #c8cedb; + font-size: 0.84rem; + font-weight: 650; +} + +.login-panel input { + width: 100%; + height: 3.25rem; + padding: 0 0.9rem; + color: var(--text); + background: #0b0f19; + border: 1px solid var(--line); + border-radius: 0.7rem; + outline: 0; +} + +.login-panel input:focus { + border-color: var(--accent); + box-shadow: 0 0 0 3px rgb(239 181 47 / 13%); +} + +.form-error { + margin: 0.5rem 0; + padding: 0.8rem 1rem; + color: #ffd0d4; + background: rgb(255 86 103 / 10%); + border: 1px solid rgb(255 112 125 / 28%); + border-radius: 0.7rem; +} + +.notice { + padding: 0.8rem 1rem; + color: #caffea; + background: rgb(88 214 161 / 10%); + border: 1px solid rgb(88 214 161 / 25%); + border-radius: 0.7rem; +} + +.admin-heading { + display: flex; + align-items: flex-end; + justify-content: space-between; + gap: 2rem; + margin-block-end: 2rem; +} + +.admin-heading h1 { + font-size: clamp(2rem, 4vw, 3.4rem); +} + +.dashboard-grid { + display: grid; + grid-template-columns: repeat(4, minmax(9rem, 1fr)); + gap: 1rem; +} + +.stat-card { + min-height: 8.5rem; + padding: 1.2rem; + background: linear-gradient(145deg, var(--panel-raised), var(--panel)); + border: 1px solid var(--line); + border-radius: 0.9rem; +} + +.stat-card span { + display: block; + color: var(--muted); + font-size: 0.82rem; +} + +.stat-card strong { + display: inline-block; + margin-block-start: 0.9rem; + font-size: 2rem; +} + +.stat-card small { + color: var(--muted); +} + +.cache-card { + grid-column: span 2; +} + +.cache-card progress { + display: block; + width: 100%; + height: 0.45rem; + margin-block-start: 0.8rem; + overflow: hidden; + accent-color: var(--accent); + border-radius: 1rem; +} + +.jobs-panel { + margin-block-start: 2rem; + padding-inline: 0; +} + +.jobs-table-wrap { + overflow-x: auto; + border: 1px solid var(--line); + border-radius: 0.9rem; +} + +.jobs-panel table { + width: 100%; + min-width: 42rem; + border-collapse: collapse; + background: var(--panel); +} + +.jobs-panel th, +.jobs-panel td { + padding: 0.9rem 1rem; + text-align: start; + border-block-end: 1px solid var(--line); +} + +.jobs-panel th { + color: var(--muted); + font-size: 0.75rem; + text-transform: uppercase; +} + +.status-pill { + padding: 0.25rem 0.55rem; + font-size: 0.7rem; + background: rgb(255 255 255 / 8%); + border-radius: 2rem; +} + +.player-shell { + position: fixed; + z-index: 1000; + inset: 0; + overflow: hidden; + color: white; + background: #000; + outline: 0; + direction: ltr; +} + +.player-video { + position: absolute; + width: 100%; + height: 100%; + inset: 0; + object-fit: contain; + background: #000; +} + +.player-shell > .JASSUB { + z-index: 2; + inset: 0; + width: 100%; + height: 100%; +} + +.player-status { + position: absolute; + z-index: 8; + display: flex; + width: min(42rem, calc(100% - 2rem)); + min-height: 18rem; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 0.9rem; + inset-block-start: 50%; + inset-inline-start: 50%; + padding: 2rem; + color: white; + text-align: center; + background: rgb(10 13 21 / 88%); + border: 1px solid rgb(255 255 255 / 12%); + border-radius: 1.1rem; + box-shadow: 0 2rem 5rem rgb(0 0 0 / 40%); + transform: translate(-50%, -50%); + backdrop-filter: blur(16px); + direction: var(--player-text-direction, rtl); +} + +[dir="ltr"] .player-status { + --player-text-direction: ltr; +} + +.player-status h2, +.player-status p { + max-width: 40rem; + margin: 0; +} + +.player-status p, +.player-status small { + color: #c7ccda; +} + +.status-symbol { + display: grid; + width: 4rem; + height: 4rem; + place-items: center; + color: #231012; + font-size: 2rem; + font-weight: 900; + background: var(--danger); + border-radius: 50%; +} + +.preparing-progress { + width: min(25rem, 90%); + height: 0.45rem; + overflow: hidden; + background: rgb(255 255 255 / 15%); + border-radius: 10rem; +} + +.preparing-progress span { + display: block; + height: 100%; + background: var(--accent-strong); + transition: width 300ms ease; +} + +.gesture-play { + position: absolute; + z-index: 9; + display: flex; + flex-direction: column; + align-items: center; + gap: 0.8rem; + inset-block-start: 50%; + inset-inline-start: 50%; + padding: 1.4rem 1.8rem; + color: white; + background: rgb(8 11 18 / 82%); + border: 1px solid rgb(255 255 255 / 20%); + border-radius: 1rem; + transform: translate(-50%, -50%); + cursor: pointer; +} + +.gesture-play svg { + width: 3.5rem; + height: 3.5rem; + padding: 0.8rem; + color: #161008; + background: var(--accent-strong); + border-radius: 50%; +} + +.player-topbar, +.player-controls { + position: absolute; + z-index: 7; + inset-inline: 0; + opacity: 1; + transition: opacity 200ms ease, transform 200ms ease; +} + +.player-topbar { + display: flex; + align-items: center; + gap: 1rem; + inset-block-start: 0; + padding: max(1.25rem, env(safe-area-inset-top)) max(1.5rem, env(safe-area-inset-right)) 4rem; + background: linear-gradient(to bottom, rgb(0 0 0 / 82%), transparent); + direction: var(--player-text-direction, rtl); +} + +[dir="ltr"] .player-topbar { + --player-text-direction: ltr; +} + +.player-topbar strong { + overflow: hidden; + font-size: clamp(1rem, 2vw, 1.35rem); + text-overflow: ellipsis; + white-space: nowrap; +} + +.player-controls { + inset-block-end: 0; + padding: 5rem max(1.5rem, env(safe-area-inset-right)) max(1.25rem, env(safe-area-inset-bottom)); + background: linear-gradient(to top, rgb(0 0 0 / 94%), transparent); +} + +.controls-hidden .player-topbar, +.controls-hidden .player-controls { + pointer-events: none; + opacity: 0; +} + +.controls-hidden .player-topbar { + transform: translateY(-1rem); +} + +.controls-hidden .player-controls { + transform: translateY(1rem); +} + +.timeline-wrap { + display: grid; + grid-template-columns: auto minmax(5rem, 1fr) auto; + align-items: center; + gap: 0.8rem; + color: #e0e3e9; + font-size: 0.78rem; +} + +.timeline { + position: relative; + display: flex; + align-items: center; + height: 1.5rem; +} + +.timeline .buffered { + position: absolute; + height: 4px; + inset-inline-start: 0; + background: rgb(255 255 255 / 42%); + border-radius: 1rem; + pointer-events: none; +} + +.timeline input { + z-index: 2; + width: 100%; + height: 4px; + margin: 0; + accent-color: var(--accent-strong); + cursor: pointer; +} + +.control-row { + display: flex; + align-items: center; + gap: clamp(0.25rem, 1vw, 0.75rem); + margin-block-start: 0.7rem; +} + +.control-spacer { + flex: 1; +} + +.player-icon-button, +.player-text-button { + display: inline-grid; + min-width: 2.8rem; + min-height: 2.8rem; + place-items: center; + color: white; + background: transparent; + border: 0; + border-radius: 0.6rem; + cursor: pointer; +} + +.player-icon-button:hover, +.player-text-button:hover { + background: rgb(255 255 255 / 13%); +} + +.player-icon-button svg { + width: 1.6rem; + height: 1.6rem; +} + +.player-icon-button small { + position: absolute; + font-size: 0.58rem; + font-weight: 900; +} + +.player-text-button { + display: inline-flex; + padding-inline: 0.75rem; + font-size: 0.82rem; +} + +.control-menu-wrap { + position: relative; +} + +.track-menu { + position: absolute; + display: grid; + width: max-content; + min-width: 10rem; + max-height: 17rem; + inset-inline-end: 0; + inset-block-end: calc(100% + 0.75rem); + padding: 0.4rem; + overflow-y: auto; + background: rgb(18 23 34 / 97%); + border: 1px solid rgb(255 255 255 / 14%); + border-radius: 0.7rem; + box-shadow: 0 1rem 2.5rem rgb(0 0 0 / 44%); + direction: var(--player-text-direction, rtl); +} + +[dir="ltr"] .track-menu { + --player-text-direction: ltr; +} + +.track-menu button { + min-height: 2.7rem; + padding: 0.55rem 0.8rem; + color: #d7dbe4; + text-align: start; + background: transparent; + border: 0; + border-radius: 0.45rem; + cursor: pointer; +} + +.track-menu button:hover, +.track-menu button:focus, +.track-menu button.selected { + color: white; + background: rgb(255 255 255 / 10%); +} + +.track-menu button.selected::before { + margin-inline-end: 0.5rem; + color: var(--accent-strong); + content: "✓"; +} + +@media (min-width: 1500px) { + :root { + --header-height: 92px; + font-size: 18px; + } + + .app-header { + gap: 2.5rem; + } + + .media-grid { + grid-template-columns: repeat(auto-fill, minmax(12.5rem, 1fr)); + } + + .nav-link, + .language-button, + .header-search input { + min-height: 3.2rem; + } + + .player-icon-button, + .player-text-button { + min-width: 3.5rem; + min-height: 3.5rem; + } +} + +@media (max-width: 800px) { + :root { + --header-height: 64px; + } + + .app-header { + padding-inline: 0.8rem; + } + + .brand-wordmark, + .primary-nav, + .header-search { + display: none; + } + + .language-button { + margin-inline-start: auto; + } + + .hero, + .detail-hero { + min-height: 70vh; + background-position: center; + } + + .hero-content, + .detail-copy { + width: 100%; + padding-inline: 1.25rem; + } + + .hero-overview { + -webkit-line-clamp: 3; + } + + .media-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .admin-heading { + align-items: flex-start; + flex-direction: column; + } + + .dashboard-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .cache-card { + grid-column: span 2; + } + + .player-controls { + padding-inline: 0.8rem; + } + + .player-text-button { + padding-inline: 0.4rem; + font-size: 0.72rem; + } +} + +@media (max-width: 420px) { + .dashboard-grid { + grid-template-columns: 1fr; + } + + .cache-card { + grid-column: auto; + } + + .control-row { + gap: 0; + } + + .player-icon-button, + .player-text-button { + min-width: 2.55rem; + padding-inline: 0.25rem; + } +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + scroll-behavior: auto !important; + transition-duration: 0.01ms !important; + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + } +} diff --git a/apps/web/src/test/setup.ts b/apps/web/src/test/setup.ts new file mode 100644 index 0000000..6e59064 --- /dev/null +++ b/apps/web/src/test/setup.ts @@ -0,0 +1,19 @@ +import { afterEach, vi } from 'vitest' + +Object.defineProperty(HTMLElement.prototype, 'offsetParent', { + configurable: true, + get() { + return this.parentElement + }, +}) + +if (typeof CSS === 'undefined') { + vi.stubGlobal('CSS', { escape: (value: string) => value.replace(/["\\]/g, '\\$&') }) +} + +HTMLElement.prototype.scrollIntoView = vi.fn() + +afterEach(() => { + document.body.innerHTML = '' + vi.restoreAllMocks() +}) diff --git a/apps/web/src/types.ts b/apps/web/src/types.ts new file mode 100644 index 0000000..e50e25e --- /dev/null +++ b/apps/web/src/types.ts @@ -0,0 +1,137 @@ +export type UiLanguage = 'fa' | 'en' +export type MediaKind = 'MOVIE' | 'SERIES' + +export interface LocalizedText { + fa?: string | undefined + en?: string | undefined +} + +export interface CatalogItem { + id: string + mediaItemId: string + slug: string + kind: MediaKind + title: LocalizedText + overview: LocalizedText + posterUrl?: string | undefined + backdropUrl?: string | undefined + year?: number | undefined + runtimeSeconds?: number | undefined + seasonCount?: number | undefined + episodeCount?: number | undefined + compatibility?: string | undefined + playable: boolean + progress?: number | undefined +} + +export interface EpisodeItem { + id: string + mediaItemId: string + number: number + seasonNumber: number + title: LocalizedText + overview: LocalizedText + posterUrl?: string | undefined + durationSeconds?: number | undefined + published: boolean +} + +export interface SeasonItem { + number: number + title: LocalizedText + episodes: EpisodeItem[] +} + +export interface TitleDetail extends CatalogItem { + genres: LocalizedText[] + seasons: SeasonItem[] + playableMediaItemId?: string | undefined +} + +export interface CatalogPage { + items: CatalogItem[] + nextCursor?: string | undefined + total?: number | undefined +} + +export type PlaybackState = 'PREPARING' | 'READY' | 'UNSUPPORTED_CLIENT' | 'FAILED' +export type SubtitleDelivery = 'ASS_JASSUB' | 'WEBVTT' | 'OFF' + +export interface PlaybackSubtitleTrack { + id: string + language: string + label: string + default: boolean + forced: boolean + assUrl?: string | undefined + vttUrl?: string | undefined + fonts: string[] +} + +export interface PlaybackAudioTrack { + id: string + language: string + label: string + default: boolean +} + +export interface PlaybackSession { + id: string + state: PlaybackState + mediaItemId: string + manifestUrl?: string | undefined + durationSeconds?: number | undefined + pollAfterMs: number + progress?: number | undefined + message?: string | undefined + reasonCode?: string | undefined + expiresAt?: string | undefined + videoCodec?: string | undefined + audioCodec?: string | undefined + subtitles: PlaybackSubtitleTrack[] + audioTracks: PlaybackAudioTrack[] +} + +export interface ClientCapabilities { + nativeHls: boolean + mse: boolean + hlsJs: boolean + assRenderer: boolean + supportedCodecs: string[] + userAgent?: string | undefined +} + +export interface ProgressRecord { + mediaItemId: string + positionSeconds: number + durationSeconds: number + updatedAt: number + completed: boolean +} + +export interface ViewerPreferences { + uiLanguage: UiLanguage + subtitleLanguage: string + audioLanguage: string + volume: number + muted: boolean +} + +export interface AdminJob { + id: string + type: string + state: string + progress?: number | undefined + message?: string | undefined + createdAt?: string | undefined +} + +export interface AdminDashboard { + catalogCount: number + publishedCount: number + reviewCount: number + activeJobs: number + cacheUsedBytes?: number | undefined + cacheCapacityBytes?: number | undefined + jobs: AdminJob[] +} diff --git a/apps/web/src/views/AdminView.vue b/apps/web/src/views/AdminView.vue new file mode 100644 index 0000000..253b118 --- /dev/null +++ b/apps/web/src/views/AdminView.vue @@ -0,0 +1,218 @@ + + + diff --git a/apps/web/src/views/CatalogView.vue b/apps/web/src/views/CatalogView.vue new file mode 100644 index 0000000..17c2df1 --- /dev/null +++ b/apps/web/src/views/CatalogView.vue @@ -0,0 +1,116 @@ + + + diff --git a/apps/web/src/views/SearchView.vue b/apps/web/src/views/SearchView.vue new file mode 100644 index 0000000..ea10b4f --- /dev/null +++ b/apps/web/src/views/SearchView.vue @@ -0,0 +1,97 @@ + + + diff --git a/apps/web/src/views/TitleView.vue b/apps/web/src/views/TitleView.vue new file mode 100644 index 0000000..a348fe8 --- /dev/null +++ b/apps/web/src/views/TitleView.vue @@ -0,0 +1,132 @@ + + + diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json new file mode 100644 index 0000000..5d2aef5 --- /dev/null +++ b/apps/web/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "baseUrl": ".", + "module": "ESNext", + "moduleResolution": "Bundler", + "noEmit": true, + "declaration": false, + "paths": { + "@/*": ["src/*"], + "@easy-stream/contracts": ["../../packages/contracts/src/index.ts"] + }, + "types": ["vite/client", "vitest/globals"] + }, + "include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts"] +} diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts new file mode 100644 index 0000000..84dd7e9 --- /dev/null +++ b/apps/web/vite.config.ts @@ -0,0 +1,36 @@ +import { fileURLToPath, URL } from 'node:url' + +import vue from '@vitejs/plugin-vue' +import { defineConfig } from 'vite' + +export default defineConfig({ + plugins: [vue()], + resolve: { + alias: { + '@': fileURLToPath(new URL('./src', import.meta.url)), + }, + }, + server: { + port: 5173, + proxy: { + '/api': { + target: process.env.API_ORIGIN ?? 'http://127.0.0.1:3000', + changeOrigin: true, + }, + '/images/tmdb': { + target: 'https://image.tmdb.org', + changeOrigin: true, + rewrite: (requestPath) => requestPath.replace(/^\/images\/tmdb/, '/t/p'), + }, + }, + }, + worker: { + format: 'es', + }, + test: { + environment: 'jsdom', + globals: true, + setupFiles: ['./src/test/setup.ts'], + css: false, + }, +}) diff --git a/apps/worker/package.json b/apps/worker/package.json new file mode 100644 index 0000000..21b556d --- /dev/null +++ b/apps/worker/package.json @@ -0,0 +1,31 @@ +{ + "name": "@easy-stream/worker", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "tsc -p tsconfig.json", + "typecheck": "tsc -p ../../packages/contracts/tsconfig.json && tsc -p ../../packages/media/tsconfig.json && tsc -p ../../packages/database/tsconfig.json && tsc -p tsconfig.json --noEmit", + "test": "tsc -p ../../packages/contracts/tsconfig.json && tsc -p ../../packages/media/tsconfig.json && tsc -p ../../packages/database/tsconfig.json && vitest run", + "dev": "tsx watch src/cli.ts work", + "scan": "tsx src/cli.ts scan", + "package": "tsx src/cli.ts package", + "prepare:media": "tsx src/cli.ts prepare", + "work": "tsx src/cli.ts work", + "clean": "rm -rf dist" + }, + "dependencies": { + "@easy-stream/contracts": "workspace:*", + "@easy-stream/database": "workspace:*", + "@easy-stream/media": "workspace:*", + "@sinclair/typebox": "^0.34.41", + "bullmq": "^5.61.2", + "ioredis": "^5.10.1" + }, + "devDependencies": { + "@types/node": "^24.10.0", + "tsx": "^4.20.6", + "typescript": "^5.9.3", + "vitest": "^3.2.4" + } +} diff --git a/apps/worker/src/cache-lifecycle.ts b/apps/worker/src/cache-lifecycle.ts new file mode 100644 index 0000000..75c1630 --- /dev/null +++ b/apps/worker/src/cache-lifecycle.ts @@ -0,0 +1,52 @@ +import path from 'node:path'; +import { evictCache, pruneOrphanedFonts, type EvictionResult } from '@easy-stream/media'; +import { removeGenerationsFromRegistry } from './registry.js'; + +export interface CacheSweepOptions { + cacheRoot: string; + registryPath: string; + capacityBytes: number; + highWatermark: number; + lowWatermark: number; + playbackTtlMs: number; + protectedKeys?: ReadonlySet; + fontOrphanMinimumAgeMs?: number; + now?: Date; +} + +export interface CacheSweepResult extends EvictionResult { + registryEntriesRemoved: string[]; + orphanFontsRemoved: string[]; +} + +/** Sweeps only disposable cache generations. Durable derived media is deliberately out of scope. */ +export async function sweepCache(options: CacheSweepOptions): Promise { + const now = options.now ?? new Date(); + const fontOptions = { + minimumAgeMs: options.fontOrphanMinimumAgeMs ?? 60 * 60 * 1000, + now, + }; + const beforeFonts = await pruneOrphanedFonts(options.cacheRoot, fontOptions); + const eviction = await evictCache(path.join(options.cacheRoot, 'generations'), { + capacityBytes: options.capacityBytes, + highWatermark: options.highWatermark, + lowWatermark: options.lowWatermark, + ...(options.protectedKeys === undefined ? {} : { protectedKeys: options.protectedKeys }), + overheadBytes: beforeFonts.retainedBytes, + minimumRetentionMs: options.playbackTtlMs, + now, + }); + const registryEntriesRemoved = await removeGenerationsFromRegistry( + options.registryPath, + new Set(eviction.evicted), + ); + const afterFonts = eviction.evicted.length === 0 + ? { removed: [] as string[], retainedBytes: beforeFonts.retainedBytes } + : await pruneOrphanedFonts(options.cacheRoot, fontOptions); + return { + ...eviction, + afterBytes: Math.max(0, eviction.afterBytes - beforeFonts.retainedBytes + afterFonts.retainedBytes), + registryEntriesRemoved, + orphanFontsRemoved: [...beforeFonts.removed, ...afterFonts.removed], + }; +} diff --git a/apps/worker/src/catalog.ts b/apps/worker/src/catalog.ts new file mode 100644 index 0000000..930b70a --- /dev/null +++ b/apps/worker/src/catalog.ts @@ -0,0 +1,339 @@ +import { createHash } from 'node:crypto'; +import path from 'node:path'; +import { + assDialogueText, + classifyMedia, + fingerprintSource, + normalizeStreamLanguage, + normalizeTracks, + probeMedia, + readSubtitleAsAss, + walkArchive, + type Classification, + type NormalizedTrack, + type ProbeStream, + type SourceFingerprint, +} from '@easy-stream/media'; + +export type CatalogKind = 'MOVIE' | 'SERIES'; + +export interface ParsedMediaIdentity { + kind: CatalogKind; + title: string; + seasonNumber?: number; + episodeNumber?: number; + episodeTitle?: string; +} + +export interface SnapshotSubtitle { + id: string; + streamIndex: number; + codec: string; + sourceLanguage: string; + language: string; + label: string; + sourceDefault: boolean; + sourceForced: boolean; + default: boolean; + forced: false; +} + +export interface SnapshotMediaItem { + id: string; + titleId: string; + kind: 'MOVIE' | 'EPISODE'; + sourcePath: string; + durationSeconds: number; + seasonNumber?: number; + episodeNumber?: number; + title: { en: string; fa?: string }; + published: boolean; + compatibility: Classification['class']; + compatibilityReasons: string[]; + fingerprint: SourceFingerprint; + streams: NormalizedTrack[]; + subtitles: SnapshotSubtitle[]; +} + +export interface SnapshotSeason { + number: number; + title: { en: string }; + episodes: SnapshotMediaItem[]; +} + +export interface SnapshotTitle { + id: string; + slug: string; + kind: CatalogKind; + title: { en: string; fa?: string }; + published: boolean; + playable: boolean; + mediaItemId: string; + resumeMediaItemId: string; + runtimeSeconds?: number; + seasonCount?: number; + episodeCount?: number; + seasons: SnapshotSeason[]; + mediaItems: SnapshotMediaItem[]; +} + +export interface InventorySnapshot { + version: 1; + generatedAt: string; + archiveRoot: string; + items: SnapshotTitle[]; +} + +export interface PublicMediaItem { + id: string; + kind: 'MOVIE' | 'EPISODE'; + seasonNumber?: number; + episodeNumber?: number; + name?: { fa?: string; en?: string }; + durationSeconds: number; + compatibility: Classification['class']; + published: boolean; +} + +export interface PublicTitleDetail { + id: string; + slug: string; + kind: CatalogKind; + name: { fa: string; en?: string }; + playable: boolean; + resumeMediaItemId?: string; + synopsis: { fa?: string; en?: string }; + seasons?: Array<{ number: number; episodeCount: number }>; + mediaItems: PublicMediaItem[]; + updatedAt: string; +} + +export interface CatalogSnapshot { + version: 1; + generatedAt: string; + titles: PublicTitleDetail[]; +} + +export interface ScanArchiveResult { + catalog: CatalogSnapshot; + inventory: InventorySnapshot; +} + +export function deterministicUuid(value: string): string { + const bytes = createHash('sha256').update(value).digest().subarray(0, 16); + bytes[6] = (bytes[6] ?? 0) & 0x0f | 0x50; + bytes[8] = (bytes[8] ?? 0) & 0x3f | 0x80; + const hex = bytes.toString('hex'); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} + +function cleanName(value: string): string { + return value + .replace(/\[[^\]]*\]/gu, ' ') + .replace(/[._]+/gu, ' ') + .replace(/\s+/gu, ' ') + .trim(); +} + +export function slugify(value: string): string { + return value.normalize('NFKD').toLocaleLowerCase('en-US') + .replace(/\p{Mark}+/gu, '') + .replace(/[^\p{Letter}\p{Number}]+/gu, '-') + .replace(/^-+|-+$/gu, '') + .slice(0, 180) || deterministicUuid(value); +} + +export function parseMediaIdentity(relativePath: string): ParsedMediaIdentity { + const extension = path.extname(relativePath); + const filename = path.basename(relativePath, extension); + const parent = path.basename(path.dirname(relativePath)); + const combined = filename.match(/\bS(?:eason)?\s*(\d{1,3})\s*E(?:p(?:isode)?)?\s*(\d{1,4})\b/iu); + const parentSeason = parent.match(/^(.*?)(?:[\s._-]+S(?:eason)?\s*(\d{1,3}))$/iu); + const episode = combined?.[2] + ?? filename.match(/(?:-|–)\s*(\d{1,4})(?=(?:[.\s_\[]|$))/u)?.[1] + ?? filename.match(/\bE(?:p(?:isode)?)?\s*(\d{1,4})\b/iu)?.[1]; + if (episode !== undefined) { + const season = Number(combined?.[1] ?? parentSeason?.[2] ?? 1); + const title = cleanName(parentSeason?.[1] ?? parent); + return { + kind: 'SERIES', + title: title || cleanName(filename), + seasonNumber: season, + episodeNumber: Number(episode), + episodeTitle: `Episode ${Number(episode)}`, + }; + } + return { kind: 'MOVIE', title: cleanName(filename) }; +} + +export interface ScanArchiveOptions { + archiveRoot: string; + ffmpegPath?: string; + ffprobePath?: string; + onFile?: (relativePath: string, current: number) => void; +} + +const TEXT_SUBTITLE_CODECS = new Set(['ass', 'ssa', 'subrip', 'srt', 'webvtt', 'mov_text']); + +export function shouldInspectSubtitleContent(stream: ProbeStream): boolean { + return stream.codec_type === 'subtitle' + && TEXT_SUBTITLE_CODECS.has(stream.codec_name ?? '') + && normalizeStreamLanguage(stream) === 'und'; +} + +async function inspectFile( + sourcePath: string, + archiveRoot: string, + options: ScanArchiveOptions, +): Promise<{ identity: ParsedMediaIdentity; media: SnapshotMediaItem }> { + const relativePath = path.relative(archiveRoot, sourcePath).split(path.sep).join('/'); + const identity = parseMediaIdentity(relativePath); + const [probe, fingerprint] = await Promise.all([ + probeMedia(sourcePath, options.ffprobePath === undefined ? {} : { ffprobePath: options.ffprobePath }), + fingerprintSource(archiveRoot, sourcePath), + ]); + const compatibility = classifyMedia(probe); + const titleId = deterministicUuid(`title:${identity.kind}:${identity.title.toLocaleLowerCase('en-US')}`); + const mediaId = deterministicUuid(`media:${relativePath}`); + const tracks = normalizeTracks(probe); + const subtitles: SnapshotSubtitle[] = []; + for (const stream of probe.streams.filter((candidate) => candidate.codec_type === 'subtitle')) { + let content: string | undefined; + const declaredLanguage = normalizeStreamLanguage(stream); + if (shouldInspectSubtitleContent(stream)) { + try { + content = await readSubtitleAsAss(sourcePath, stream.index, { + archiveRoot, + maxDurationSeconds: 10 * 60, + ...(options.ffmpegPath === undefined ? {} : { ffmpegPath: options.ffmpegPath }), + }); + } catch { + // Preserve the track as undetermined; packaging will report extraction failures. + } + } + const language = content === undefined + ? declaredLanguage + : normalizeStreamLanguage(stream, assDialogueText(content)); + const track = tracks.find((candidate) => candidate.index === stream.index); + if (track !== undefined) { + track.language = language; + track.default = language === 'fa'; + track.forced = false; + } + subtitles.push({ + id: deterministicUuid(`subtitle:${relativePath}:${stream.index}`), + streamIndex: stream.index, + codec: stream.codec_name ?? 'unknown', + sourceLanguage: stream.tags?.language ?? 'und', + language, + label: stream.tags?.title ?? language, + sourceDefault: stream.disposition?.default === 1, + sourceForced: stream.disposition?.forced === 1, + default: language === 'fa', + forced: false, + }); + } + const duration = Number(probe.format.duration); + const published = ['COPY', 'AUDIO_TRANSCODE'].includes(compatibility.class); + return { + identity, + media: { + id: mediaId, + titleId, + kind: identity.kind === 'SERIES' ? 'EPISODE' : 'MOVIE', + sourcePath: relativePath, + durationSeconds: Number.isFinite(duration) ? duration : 0, + ...(identity.seasonNumber === undefined ? {} : { seasonNumber: identity.seasonNumber }), + ...(identity.episodeNumber === undefined ? {} : { episodeNumber: identity.episodeNumber }), + title: { en: identity.episodeTitle ?? identity.title }, + published, + compatibility: compatibility.class, + compatibilityReasons: compatibility.reasons, + fingerprint, + streams: tracks, + subtitles, + }, + }; +} + +export async function scanArchive(options: ScanArchiveOptions): Promise { + const root = path.resolve(options.archiveRoot); + const grouped = new Map(); + let current = 0; + for await (const sourcePath of walkArchive(root)) { + current += 1; + const relative = path.relative(root, sourcePath).split(path.sep).join('/'); + options.onFile?.(relative, current); + const inspected = await inspectFile(sourcePath, root, options); + const key = `${inspected.identity.kind}:${inspected.identity.title.toLocaleLowerCase('en-US')}`; + const group = grouped.get(key) ?? { identity: inspected.identity, media: [] }; + group.media.push(inspected.media); + grouped.set(key, group); + } + const items: SnapshotTitle[] = [...grouped.values()].map(({ identity, media }) => { + media.sort((left, right) => (left.seasonNumber ?? 0) - (right.seasonNumber ?? 0) + || (left.episodeNumber ?? 0) - (right.episodeNumber ?? 0)); + const first = media[0]; + if (first === undefined) throw new Error('Internal catalog group is empty'); + const seasonsByNumber = new Map(); + for (const item of media) { + if (item.kind !== 'EPISODE') continue; + const season = item.seasonNumber ?? 1; + const episodes = seasonsByNumber.get(season) ?? []; + episodes.push(item); + seasonsByNumber.set(season, episodes); + } + const seasons = [...seasonsByNumber.entries()].sort(([left], [right]) => left - right) + .map(([number, episodes]) => ({ number, title: { en: `Season ${number}` }, episodes })); + const published = media.some((item) => item.published); + return { + id: first.titleId, + slug: slugify(identity.title), + kind: identity.kind, + title: { en: identity.title }, + published, + playable: published, + mediaItemId: first.id, + resumeMediaItemId: first.id, + ...(identity.kind === 'MOVIE' ? { runtimeSeconds: first.durationSeconds } : {}), + ...(identity.kind === 'SERIES' ? { seasonCount: seasons.length, episodeCount: media.length } : {}), + seasons, + mediaItems: media, + }; + }); + items.sort((left, right) => left.title.en.localeCompare(right.title.en)); + const generatedAt = new Date().toISOString(); + const titles: PublicTitleDetail[] = items.map((item) => ({ + id: item.id, + slug: item.slug, + kind: item.kind, + // Filename-derived text is a safe temporary fallback until metadata matching supplies Persian. + name: { fa: item.title.fa ?? item.title.en, en: item.title.en }, + playable: item.playable, + ...(item.playable ? { resumeMediaItemId: item.resumeMediaItemId } : {}), + synopsis: {}, + ...(item.kind === 'SERIES' + ? { seasons: item.seasons.map((season) => ({ number: season.number, episodeCount: season.episodes.length })) } + : {}), + mediaItems: item.mediaItems.map((media): PublicMediaItem => ({ + id: media.id, + kind: media.kind, + ...(media.seasonNumber === undefined ? {} : { seasonNumber: media.seasonNumber }), + ...(media.episodeNumber === undefined ? {} : { episodeNumber: media.episodeNumber }), + name: { fa: media.title.fa ?? media.title.en, en: media.title.en }, + durationSeconds: media.durationSeconds, + compatibility: media.compatibility, + published: media.published, + })), + updatedAt: generatedAt, + })); + return { + catalog: { version: 1, generatedAt, titles }, + inventory: { version: 1, generatedAt, archiveRoot: root, items }, + }; +} + +export function findMediaItem(snapshot: InventorySnapshot, idOrPath: string): SnapshotMediaItem | undefined { + return snapshot.items.flatMap((item) => item.mediaItems) + .find((media) => media.id === idOrPath || media.sourcePath === idOrPath); +} diff --git a/apps/worker/src/cli.ts b/apps/worker/src/cli.ts new file mode 100644 index 0000000..461d222 --- /dev/null +++ b/apps/worker/src/cli.ts @@ -0,0 +1,567 @@ +#!/usr/bin/env node +import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { + createDatabase, + markArchiveScanFailed, + markArchiveScanRunning, + markArchiveScanSucceeded, + syncCatalogSnapshot, + type Database, +} from '@easy-stream/database'; +import { + classifyMedia, + extractAndStoreFonts, + extractSubtitleVariants, + evictCacheGeneration, + fingerprintSource, + isPathInside, + normalizeStreamLanguage, + packageProgressiveHls, + prepareCompatibilityHls, + probeMedia, + publishGenerationFonts, + pruneOrphanedFonts, + resolveInside, + touchCacheGeneration, + writeCacheMetadata, +} from '@easy-stream/media'; +import { + deterministicUuid, + findMediaItem, + scanArchive, + type InventorySnapshot, + type SnapshotMediaItem, +} from './catalog.js'; +import { sweepCache } from './cache-lifecycle.js'; +import { + normalizeTrackLabel, + removeGenerationFromRegistry, + updateRegistry, +} from './registry.js'; + +for (const candidate of [process.env.ENV_FILE, '.env', '../../.env']) { + if (!candidate) continue; + try { + process.loadEnvFile?.(candidate); + break; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } +} + +interface Arguments { + command?: string; + flags: Map; +} + +interface CommandRuntime { + protectedCacheKeys?: () => Promise>; +} + +function parseArguments(argv: readonly string[]): Arguments { + const flags = new Map(); + let command: string | undefined; + for (let index = 0; index < argv.length; index += 1) { + const value = argv[index]; + if (value === undefined || value === '--') continue; + if (!value.startsWith('--') && command === undefined) { + command = value; + continue; + } + if (!value.startsWith('--')) throw new Error(`Unexpected positional argument: ${value}`); + const equals = value.indexOf('='); + if (equals >= 0) { + flags.set(value.slice(2, equals), value.slice(equals + 1)); + continue; + } + const next = argv[index + 1]; + if (next !== undefined && !next.startsWith('--')) { + flags.set(value.slice(2), next); + index += 1; + } else { + flags.set(value.slice(2), true); + } + } + return { ...(command === undefined ? {} : { command }), flags }; +} + +function flag(arguments_: Arguments, name: string, fallback?: string): string | undefined { + const value = arguments_.flags.get(name); + if (value === true) throw new Error(`--${name} requires a value`); + return value ?? fallback; +} + +async function writeJsonAtomic(destinationPath: string, value: unknown): Promise { + const destination = path.resolve(destinationPath); + await mkdir(path.dirname(destination), { recursive: true, mode: 0o750 }); + const temporary = `${destination}.${process.pid}.tmp`; + await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o640 }); + await rename(temporary, destination); +} + +async function scanCommand(arguments_: Arguments): Promise { + const archiveRoot = path.resolve(flag(arguments_, 'root', './movies') ?? './movies'); + const output = flag(arguments_, 'output'); + const inventoryOutput = flag(arguments_, 'inventory-output') + ?? (output === undefined ? undefined : path.join(path.dirname(output), 'inventory.json')); + if ((output !== undefined && isPathInside(archiveRoot, path.resolve(output))) + || (inventoryOutput !== undefined && isPathInside(archiveRoot, path.resolve(inventoryOutput)))) { + throw new Error('Catalog output must not be written into the read-only archive'); + } + const result = await scanArchive({ + archiveRoot, + ...(flag(arguments_, 'ffmpeg') === undefined ? {} : { ffmpegPath: flag(arguments_, 'ffmpeg') as string }), + ...(flag(arguments_, 'ffprobe') === undefined ? {} : { ffprobePath: flag(arguments_, 'ffprobe') as string }), + onFile(relativePath, current) { + process.stderr.write(`[scan ${current}] ${relativePath}\n`); + }, + }); + if (output !== undefined) { + await Promise.all([ + writeJsonAtomic(output, result.catalog), + ...(inventoryOutput === undefined ? [] : [writeJsonAtomic(inventoryOutput, result.inventory)]), + ]); + } + + // Direct scans stay portable; the long-running worker passes DATABASE_URL explicitly. + const databaseUrl = flag(arguments_, 'database'); + const databaseSync = databaseUrl === undefined + ? undefined + : await withDatabase(databaseUrl, (database) => syncCatalogSnapshot(database, result.catalog)); + + if (output === undefined) process.stdout.write(`${JSON.stringify(result.catalog, null, 2)}\n`); + else { + process.stdout.write(`${JSON.stringify({ + output: path.resolve(output), + ...(inventoryOutput === undefined ? {} : { inventoryOutput: path.resolve(inventoryOutput) }), + titles: result.catalog.titles.length, + mediaItems: result.catalog.titles.reduce((sum, item) => sum + item.mediaItems.length, 0), + ...(databaseSync === undefined ? {} : { databaseSync }), + })}\n`); + } +} + +async function withDatabase( + connectionString: string, + action: (database: Database) => Promise, +): Promise { + const connection = createDatabase(connectionString, { max: 2 }); + try { + return await action(connection.db); + } finally { + await connection.close(); + } +} + +async function loadInventory(snapshotPath: string): Promise { + const value = JSON.parse(await readFile(snapshotPath, 'utf8')) as InventorySnapshot; + if (value.version !== 1 || !Array.isArray(value.items)) throw new Error('Unsupported catalog snapshot'); + return value; +} + +async function sourceSelection( + arguments_: Arguments, + archiveRoot: string, +): Promise<{ media: SnapshotMediaItem; sourcePath: string }> { + const mediaItem = flag(arguments_, 'media-item'); + const requestedSource = flag(arguments_, 'source'); + const inventoryPath = flag(arguments_, 'inventory', './data/inventory.json') ?? './data/inventory.json'; + let inventory: InventorySnapshot | undefined; + try { + inventory = await loadInventory(inventoryPath); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || mediaItem !== undefined) throw error; + } + const selected = mediaItem === undefined + ? (requestedSource === undefined ? undefined : inventory === undefined ? undefined : findMediaItem(inventory, requestedSource)) + : inventory === undefined ? undefined : findMediaItem(inventory, mediaItem); + if (selected !== undefined) { + return { media: selected, sourcePath: await resolveInside(archiveRoot, path.join(archiveRoot, selected.sourcePath)) }; + } + if (mediaItem !== undefined) throw new Error(`Media item was not found in ${inventoryPath}: ${mediaItem}`); + if (requestedSource === undefined) throw new Error('package requires --media-item ID or --source PATH'); + const sourcePath = await resolveInside( + archiveRoot, + path.isAbsolute(requestedSource) ? requestedSource : path.join(archiveRoot, requestedSource), + ); + const relative = path.relative(archiveRoot, sourcePath).split(path.sep).join('/'); + const ffprobePath = flag(arguments_, 'ffprobe'); + const probe = await probeMedia(sourcePath, ffprobePath === undefined ? {} : { ffprobePath }); + const fingerprint = await fingerprintSource(archiveRoot, sourcePath); + const classification = classifyMedia(probe); + return { + sourcePath, + media: { + id: deterministicUuid(`media:${relative}`), + titleId: deterministicUuid(`title:${relative}`), + kind: 'MOVIE', + sourcePath: relative, + durationSeconds: Number(probe.format.duration) || 0, + title: { en: path.basename(relative, path.extname(relative)) }, + published: ['COPY', 'AUDIO_TRANSCODE'].includes(classification.class), + compatibility: classification.class, + compatibilityReasons: classification.reasons, + fingerprint, + streams: [], + subtitles: [], + }, + }; +} + +async function packageCommand(arguments_: Arguments, runtime: CommandRuntime): Promise { + const archiveRoot = path.resolve(flag(arguments_, 'root', './movies') ?? './movies'); + const cacheRoot = path.resolve(flag(arguments_, 'cache', './data/media-cache') ?? './data/media-cache'); + const registryPath = path.resolve(flag(arguments_, 'registry', './data/package-registry.json') ?? './data/package-registry.json'); + if (isPathInside(archiveRoot, cacheRoot) || isPathInside(archiveRoot, registryPath)) { + throw new Error('Cache and registry must be outside the read-only archive'); + } + const selected = await sourceSelection(arguments_, archiveRoot); + const [probe, fingerprint] = await Promise.all([ + probeMedia(selected.sourcePath, flag(arguments_, 'ffprobe') === undefined ? {} : { ffprobePath: flag(arguments_, 'ffprobe') as string }), + fingerprintSource(archiveRoot, selected.sourcePath), + ]); + const classification = classifyMedia(probe); + if (!['COPY', 'AUDIO_TRANSCODE'].includes(classification.class)) { + throw new Error(`Media requires offline preparation (${classification.class}): ${classification.reasons.join(', ')}`); + } + const generationId = deterministicUuid(`generation:cmaf-v1:${fingerprint.digest}`); + const generationPath = `generations/${generationId}`; + const ffmpegPath = flag(arguments_, 'ffmpeg'); + const ffprobePath = flag(arguments_, 'ffprobe'); + const preparing = async (error?: string): Promise => { + await updateRegistry(registryPath, selected.media.id, { + mediaItemId: selected.media.id, + generationId, + state: error === undefined ? 'PREPARING' : 'FAILED', + playable: false, + ...(error === undefined ? { pollAfterMs: 1000 } : { reasonCode: 'PACKAGE_FAILED' }), + durationSeconds: Number(probe.format.duration) || selected.media.durationSeconds, + }); + }; + type Assets = { + subtitles: Awaited>; + fonts: Awaited>; + }; + let assetError: unknown; + let assetsPromise: Promise | undefined; + const startAssets = (): void => { + if (assetsPromise !== undefined) return; + assetsPromise = Promise.all([ + extractSubtitleVariants(selected.sourcePath, probe, { + archiveRoot, + outputRoot: cacheRoot, + generation: generationPath, + ...(ffmpegPath === undefined ? {} : { ffmpegPath }), + }), + extractAndStoreFonts(selected.sourcePath, probe, { + archiveRoot, + fontRoot: path.join(cacheRoot, 'assets', 'fonts'), + ...(ffmpegPath === undefined ? {} : { ffmpegPath }), + ...(flag(arguments_, 'font-sanitizer') === undefined ? {} : { sanitizerPath: flag(arguments_, 'font-sanitizer') as string }), + }), + ]).then(async ([subtitles, storedFonts]) => ({ + subtitles, + fonts: await publishGenerationFonts(storedFonts, cacheRoot, path.join(cacheRoot, generationPath)), + })).catch((error: unknown) => { + assetError = error; + return undefined; + }); + }; + let result: Awaited>; + try { + result = await packageProgressiveHls({ + archiveRoot, + cacheRoot, + sourcePath: selected.sourcePath, + fingerprint, + probe, + classification, + generation: generationId, + ...(ffmpegPath === undefined ? {} : { ffmpegPath }), + ...(ffprobePath === undefined ? {} : { ffprobePath }), + async onProgress(progress) { + startAssets(); + await preparing(progress.state === 'FAILED' + ? progress.error ?? 'Unknown packaging error' + : undefined); + }, + }); + } catch (error) { + await assetsPromise; + await preparing(error instanceof Error ? error.message : String(error)); + throw error; + } + startAssets(); + const assets = await assetsPromise; + if (assetError !== undefined || assets === undefined) { + const error = assetError instanceof Error ? assetError : new Error(String(assetError ?? 'Asset preparation failed')); + await preparing(error.message); + throw error; + } + const { subtitles, fonts } = assets; + const audioStreams = probe.streams.filter((stream) => stream.codec_type === 'audio'); + const fontUrls = fonts.map((font) => `/media/${generationPath}/fonts/${font.sha256}.${font.format}`); + await updateRegistry(registryPath, selected.media.id, { + mediaItemId: selected.media.id, + generationId, + state: 'READY', + playable: true, + manifestPath: `/media/${generationPath}/master.m3u8`, + durationSeconds: Number(probe.format.duration) || selected.media.durationSeconds, + audioTracks: audioStreams.map((stream, index) => ({ + id: deterministicUuid(`audio:${selected.media.id}:${stream.index}`), + language: normalizeStreamLanguage(stream), + label: normalizeTrackLabel(stream.tags?.title, normalizeStreamLanguage(stream)), + default: index === 0, + })), + subtitleTracks: subtitles.map((subtitle) => ({ + id: deterministicUuid(`subtitle:${selected.media.id}:${subtitle.streamIndex}`), + language: subtitle.language, + label: subtitle.language, + default: subtitle.default, + forced: subtitle.forced, + assUrl: `/media/${path.relative(cacheRoot, subtitle.assPath).split(path.sep).join('/')}`, + vttUrl: `/media/${path.relative(cacheRoot, subtitle.vttPath).split(path.sep).join('/')}`, + fontUrls, + })), + }); + await writeCacheMetadata(path.join(cacheRoot, 'generations'), path.join(cacheRoot, generationPath), { + key: generationId, + lastAccessedAt: new Date().toISOString(), + active: false, + building: false, + pinned: false, + }); + const protectedKeys = await runtime.protectedCacheKeys?.(); + const cacheSweep = await sweepCache({ + cacheRoot, + registryPath, + capacityBytes: numericFlag(arguments_, 'cache-max-bytes', process.env.CACHE_MAX_BYTES, 2_147_483_648_000), + highWatermark: numericFlag(arguments_, 'cache-high-watermark', process.env.CACHE_HIGH_WATERMARK, 0.85), + lowWatermark: numericFlag(arguments_, 'cache-low-watermark', process.env.CACHE_LOW_WATERMARK, 0.75), + playbackTtlMs: numericFlag(arguments_, 'playback-ttl-seconds', process.env.PLAYBACK_TTL_SECONDS, 4 * 60 * 60) * 1000, + ...(protectedKeys === undefined ? {} : { protectedKeys }), + }); + process.stdout.write(`${JSON.stringify({ mediaItemId: selected.media.id, generationId, manifestPath: `/media/${generationPath}/master.m3u8`, knownAacRepairs: result.knownAacRepairs, subtitles: subtitles.length, fonts: fonts.length, cacheSweep })}\n`); +} + +function numericFlag( + arguments_: Arguments, + name: string, + environmentValue: string | undefined, + fallback: number, +): number { + const value = flag(arguments_, name, environmentValue); + const number = value === undefined ? fallback : Number(value); + if (!Number.isFinite(number)) throw new Error(`--${name} must be a finite number`); + return number; +} + +async function prepareCommand(arguments_: Arguments): Promise { + const archiveRoot = path.resolve(flag(arguments_, 'root', './movies') ?? './movies'); + const derivedRoot = path.resolve(flag(arguments_, 'derived', process.env.DERIVED_ROOT ?? './data/media-derived') ?? './data/media-derived'); + const registryPath = path.resolve(flag(arguments_, 'registry', './data/package-registry.json') ?? './data/package-registry.json'); + if (isPathInside(archiveRoot, derivedRoot) || isPathInside(archiveRoot, registryPath)) { + throw new Error('Derived output and registry must be outside the read-only archive'); + } + const selected = await sourceSelection(arguments_, archiveRoot); + const [probe, fingerprint] = await Promise.all([ + probeMedia(selected.sourcePath, flag(arguments_, 'ffprobe') === undefined ? {} : { ffprobePath: flag(arguments_, 'ffprobe') as string }), + fingerprintSource(archiveRoot, selected.sourcePath), + ]); + const classification = classifyMedia(probe); + if (classification.class === 'HOLD_HDR') throw new Error('HDR_UNSUPPORTED_V1'); + if (classification.class !== 'VIDEO_TRANSCODE') { + throw new Error(`Offline video compatibility encoding is not applicable to ${classification.class}`); + } + const generationId = deterministicUuid(`generation:compat-h264-v1:${fingerprint.digest}`); + await updateRegistry(registryPath, selected.media.id, { + mediaItemId: selected.media.id, + generationId, + state: 'PREPARING', + playable: false, + pollAfterMs: 5000, + durationSeconds: Number(probe.format.duration) || selected.media.durationSeconds, + }); + try { + const result = await prepareCompatibilityHls({ + archiveRoot, + derivedRoot, + sourcePath: selected.sourcePath, + fingerprint, + probe, + classification, + generation: generationId, + ...(flag(arguments_, 'ffmpeg') === undefined ? {} : { ffmpegPath: flag(arguments_, 'ffmpeg') as string }), + ...(flag(arguments_, 'ffprobe') === undefined ? {} : { ffprobePath: flag(arguments_, 'ffprobe') as string }), + }); + const generationPath = `generations/${generationId}`; + const [subtitles, storedFonts] = await Promise.all([ + extractSubtitleVariants(selected.sourcePath, probe, { + archiveRoot, + outputRoot: derivedRoot, + generation: generationPath, + ...(flag(arguments_, 'ffmpeg') === undefined ? {} : { ffmpegPath: flag(arguments_, 'ffmpeg') as string }), + }), + extractAndStoreFonts(selected.sourcePath, probe, { + archiveRoot, + fontRoot: path.join(derivedRoot, 'assets', 'fonts'), + ...(flag(arguments_, 'ffmpeg') === undefined ? {} : { ffmpegPath: flag(arguments_, 'ffmpeg') as string }), + ...(flag(arguments_, 'font-sanitizer') === undefined ? {} : { sanitizerPath: flag(arguments_, 'font-sanitizer') as string }), + }), + ]); + const fonts = await publishGenerationFonts(storedFonts, derivedRoot, path.join(derivedRoot, generationPath)); + const fontUrls = fonts.map((font) => `/media/derived/${generationPath}/fonts/${font.sha256}.${font.format}`); + const audioStreams = probe.streams.filter((stream) => stream.codec_type === 'audio'); + await updateRegistry(registryPath, selected.media.id, { + mediaItemId: selected.media.id, + generationId, + state: 'READY', + playable: true, + manifestPath: `/media/derived/${generationPath}/master.m3u8`, + durationSeconds: Number(probe.format.duration) || selected.media.durationSeconds, + audioTracks: audioStreams.map((stream, index) => ({ + id: deterministicUuid(`audio:${selected.media.id}:${stream.index}`), + language: normalizeStreamLanguage(stream), + label: normalizeTrackLabel(stream.tags?.title, normalizeStreamLanguage(stream)), + default: index === 0, + })), + subtitleTracks: subtitles.map((subtitle) => ({ + id: deterministicUuid(`subtitle:${selected.media.id}:${subtitle.streamIndex}`), + language: subtitle.language, + label: subtitle.language, + default: subtitle.default, + forced: subtitle.forced, + assUrl: `/media/derived/${path.relative(derivedRoot, subtitle.assPath).split(path.sep).join('/')}`, + vttUrl: `/media/derived/${path.relative(derivedRoot, subtitle.vttPath).split(path.sep).join('/')}`, + fontUrls, + })), + }); + process.stdout.write(`${JSON.stringify({ mediaItemId: selected.media.id, generationId, manifestPath: `/media/derived/${generationPath}/master.m3u8`, knownAacRepairs: result.knownAacRepairs })}\n`); + } catch (error) { + await updateRegistry(registryPath, selected.media.id, { + mediaItemId: selected.media.id, + generationId, + state: 'FAILED', + playable: false, + reasonCode: 'COMPATIBILITY_ENCODE_FAILED', + durationSeconds: Number(probe.format.duration) || selected.media.durationSeconds, + }); + throw error; + } +} + +async function workCommand(arguments_: Arguments): Promise { + const redisUrl = flag(arguments_, 'redis', process.env.REDIS_URL); + if (redisUrl === undefined) throw new Error('REDIS_URL or --redis is required'); + const archiveRoot = flag(arguments_, 'root', process.env.ARCHIVE_ROOT ?? './movies') ?? './movies'; + const cacheRoot = flag(arguments_, 'cache', process.env.MEDIA_CACHE_ROOT ?? process.env.CACHE_ROOT ?? './data/media-cache') ?? './data/media-cache'; + const catalog = flag(arguments_, 'catalog', process.env.CATALOG_SNAPSHOT_PATH ?? './data/catalog.json') ?? './data/catalog.json'; + const inventory = flag(arguments_, 'inventory', process.env.MEDIA_INVENTORY_PATH ?? process.env.INVENTORY_SNAPSHOT_PATH ?? './data/inventory.json') ?? './data/inventory.json'; + const registry = flag(arguments_, 'registry', process.env.PACKAGE_REGISTRY_PATH ?? './data/package-registry.json') ?? './data/package-registry.json'; + const configuredDatabaseUrl = flag(arguments_, 'database', process.env.DATABASE_URL); + const databaseUrl = configuredDatabaseUrl?.trim() ? configuredDatabaseUrl : undefined; + const concurrency = Number(flag( + arguments_, + 'concurrency', + process.env.MEDIA_WORKER_CONCURRENCY ?? process.env.JIT_REMUX_CONCURRENCY ?? '2', + )); + const ffmpegPath = flag(arguments_, 'ffmpeg', process.env.FFMPEG_PATH); + const ffprobePath = flag(arguments_, 'ffprobe', process.env.FFPROBE_PATH); + const mediaTools = [ + ...(ffmpegPath === undefined ? [] : ['--ffmpeg', ffmpegPath]), + ...(ffprobePath === undefined ? [] : ['--ffprobe', ffprobePath]), + ]; + const { startMediaQueueWorker } = await import('./work.js'); + let running: ReturnType; + running = startMediaQueueWorker({ + redisUrl, + concurrency, + async dispatch(command) { + if (command.type === 'media.playback.requested') { + await main([ + 'package', '--root', archiveRoot, '--cache', cacheRoot, '--inventory', inventory, + '--registry', registry, '--media-item', command.mediaItemId, ...mediaTools, + ], { protectedCacheKeys: () => running.protectedCacheGenerations() }); + } else if (command.type === 'archive.scan.requested') { + if (databaseUrl !== undefined) { + const updated = await withDatabase(databaseUrl, (database) => markArchiveScanRunning(database, command.jobId)); + if (!updated) throw new Error(`Archive scan job is missing or not runnable: ${command.jobId}`); + } + await main([ + 'scan', '--root', archiveRoot, '--output', catalog, '--inventory-output', inventory, + ...(databaseUrl === undefined ? [] : ['--database', databaseUrl]), + ...mediaTools, + ]); + } else if (command.type === 'package.eviction.requested') { + if ((await running.protectedCacheGenerations()).has(command.generationId)) { + throw new Error(`Cache generation has an active playback lease: ${command.generationId}`); + } + const evicted = await evictCacheGeneration(cacheRoot, command.generationId); + if (evicted) { + await removeGenerationFromRegistry(registry, command.generationId); + await pruneOrphanedFonts(cacheRoot); + } + } else if (command.type === 'cache.generation.accessed') { + await running.recordCacheLease(command.generationId, command.protectedUntil); + await touchCacheGeneration(cacheRoot, command.generationId, { + accessedAt: command.accessedAt, + protectedUntil: command.protectedUntil, + }); + } else if (command.type === 'media.publication.changed') { + // Publication state is owned by the API/database; no media mutation is necessary. + } else { + const exhaustive: never = command; + throw new Error(`Unsupported media command: ${String(exhaustive)}`); + } + }, + async onCompleted(command) { + if (command.type !== 'archive.scan.requested' || databaseUrl === undefined) return; + const updated = await withDatabase(databaseUrl, (database) => markArchiveScanSucceeded( + database, + command.jobId, + { catalogPath: path.resolve(catalog), inventoryPath: path.resolve(inventory) }, + )); + if (!updated) throw new Error(`Archive scan job did not remain RUNNING: ${command.jobId}`); + }, + async onFailed(command, error, job) { + if (command?.type === 'archive.scan.requested' && databaseUrl !== undefined) { + try { + await withDatabase(databaseUrl, (database) => markArchiveScanFailed(database, command.jobId, error.message)); + } catch (statusError) { + process.stderr.write(`${JSON.stringify({ level: 'error', queue: 'easy-stream-media', jobId: job?.id, command: command.type, error: 'Unable to persist failed job status', detail: statusError instanceof Error ? statusError.message : String(statusError) })}\n`); + } + } + process.stderr.write(`${JSON.stringify({ level: 'error', queue: 'easy-stream-media', jobId: job?.id, command: command?.type, error: error.message })}\n`); + }, + }); + process.stdout.write(`${JSON.stringify({ state: 'WORKING', queue: 'easy-stream-media', concurrency })}\n`); + await new Promise((resolve) => { + process.once('SIGINT', resolve); + process.once('SIGTERM', resolve); + }); + await running.close(); +} + +export async function main( + argv = process.argv.slice(2), + runtime: CommandRuntime = {}, +): Promise { + const arguments_ = parseArguments(argv); + if (arguments_.command === 'scan') await scanCommand(arguments_); + else if (arguments_.command === 'package') await packageCommand(arguments_, runtime); + else if (arguments_.command === 'prepare') await prepareCommand(arguments_); + else if (arguments_.command === 'work') await workCommand(arguments_); + else { + process.stderr.write('Usage:\n worker scan --root DIR [--output FILE] [--inventory-output FILE] [--database URL]\n worker package --root DIR --cache DIR (--media-item ID | --source FILE) [--inventory FILE] [--registry FILE]\n worker prepare --root DIR --derived DIR (--media-item ID | --source FILE) [--inventory FILE]\n worker work --redis URL [--database URL] [--concurrency N]\n'); + process.exitCode = arguments_.command === undefined ? 0 : 2; + } +} + +if (import.meta.url === new URL(process.argv[1] ?? '', 'file:').href) { + main().catch((error: unknown) => { + process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`); + process.exitCode = 1; + }); +} diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts new file mode 100644 index 0000000..463de16 --- /dev/null +++ b/apps/worker/src/index.ts @@ -0,0 +1,16 @@ +import { pathToFileURL } from 'node:url'; +import { main } from './cli.js'; + +export * from './catalog.js'; +export * from './registry.js'; +export * from './cache-lifecycle.js'; +export * from './work.js'; + +export { main } from './cli.js'; + +if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) { + main().catch((error: unknown) => { + process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`); + process.exitCode = 1; + }); +} diff --git a/apps/worker/src/registry.ts b/apps/worker/src/registry.ts new file mode 100644 index 0000000..68070ed --- /dev/null +++ b/apps/worker/src/registry.ts @@ -0,0 +1,155 @@ +import { randomUUID } from 'node:crypto'; +import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { PackageRegistrySchema } from '@easy-stream/contracts'; +import { Value } from '@sinclair/typebox/value'; + +const MAX_TRACK_LABEL_LENGTH = 100; +const UNSAFE_LABEL_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu; + +/** Converts untrusted container metadata into a bounded, single-line UI label. */ +export function normalizeTrackLabel(value: string | undefined, fallback: string): string { + const clean = (candidate: string | undefined): string => (candidate ?? '') + .normalize('NFKC') + .replace(UNSAFE_LABEL_CHARACTERS, ' ') + .replace(/\s+/gu, ' ') + .trim(); + const label = clean(value) || clean(fallback) || 'und'; + if (label.length <= MAX_TRACK_LABEL_LENGTH) return label; + + // JSON Schema maxLength is enforced at this boundary. Avoid leaving a lone + // high surrogate when the UTF-16 limit cuts through an astral character. + let end = MAX_TRACK_LABEL_LENGTH; + const finalCodeUnit = label.charCodeAt(end - 1); + if (finalCodeUnit >= 0xd800 && finalCodeUnit <= 0xdbff) end -= 1; + return label.slice(0, end).trimEnd(); +} + +export interface RegistryAudioTrack { + id: string; + language: string; + label: string; + default: boolean; +} + +export interface RegistrySubtitleTrack { + id: string; + language: string; + label: string; + default: boolean; + forced: boolean; + assUrl?: string; + vttUrl?: string; + fontUrls: string[]; +} + +export interface RegistryGeneration { + mediaItemId: string; + state: 'PREPARING' | 'READY' | 'UNSUPPORTED_CLIENT' | 'FAILED'; + generationId?: string; + manifestPath?: string; + /** True once a progressive EVENT manifest has enough validated media. */ + playable: boolean; + reasonCode?: string; + pollAfterMs?: number; + durationSeconds?: number; + audioTracks?: RegistryAudioTrack[]; + subtitleTracks?: RegistrySubtitleTrack[]; +} + +export interface PackageRegistry { + version: 1; + updatedAt: string; + packages: RegistryGeneration[]; +} + +const writes = new Map>(); + +export async function readRegistry(registryPath: string): Promise { + try { + const value: unknown = JSON.parse(await readFile(registryPath, 'utf8')); + assertValidRegistry(value, `Invalid package registry at ${registryPath}`); + return value; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + return { version: 1, updatedAt: new Date(0).toISOString(), packages: [] }; + } +} + +export async function writeRegistry(registryPath: string, registry: PackageRegistry): Promise { + assertValidRegistry(registry, `Refusing to publish invalid package registry at ${registryPath}`); + const destination = path.resolve(registryPath); + await mkdir(path.dirname(destination), { recursive: true, mode: 0o750 }); + const temporary = `${destination}.${process.pid}.${randomUUID()}.tmp`; + await writeFile(temporary, `${JSON.stringify(registry, null, 2)}\n`, { mode: 0o640 }); + await rename(temporary, destination); +} + +function assertValidRegistry(value: unknown, message: string): asserts value is PackageRegistry { + if (Value.Check(PackageRegistrySchema, value)) return; + const detail = [...Value.Errors(PackageRegistrySchema, value)] + .slice(0, 8) + .map((error) => `${error.path || '/'} ${error.message}`) + .join('; '); + throw new Error(`${message}: ${detail}`); +} + +export async function updateRegistry( + registryPath: string, + mediaItemId: string, + generation: RegistryGeneration, +): Promise { + const key = path.resolve(registryPath); + const previous = writes.get(key) ?? Promise.resolve(); + const current = previous.catch(() => undefined).then(async () => { + const registry = await readRegistry(key); + registry.updatedAt = new Date().toISOString(); + const index = registry.packages.findIndex((entry) => entry.mediaItemId === mediaItemId); + if (index < 0) registry.packages.push(generation); + else { + const current = registry.packages[index]; + // An idempotent package verification must never make an already served generation + // disappear or regress to PREPARING/FAILED. + if (current !== undefined && current.generationId === generation.generationId + && current.state === 'READY' && generation.state !== 'READY') return; + registry.packages[index] = generation; + } + await writeRegistry(key, registry); + }); + writes.set(key, current); + try { + await current; + } finally { + if (writes.get(key) === current) writes.delete(key); + } +} + +export async function removeGenerationFromRegistry(registryPath: string, generationId: string): Promise { + return (await removeGenerationsFromRegistry(registryPath, new Set([generationId]))).length > 0; +} + +export async function removeGenerationsFromRegistry( + registryPath: string, + generationIds: ReadonlySet, +): Promise { + const key = path.resolve(registryPath); + const previous = writes.get(key) ?? Promise.resolve(); + let removed: string[] = []; + const current = previous.catch(() => undefined).then(async () => { + const registry = await readRegistry(key); + removed = registry.packages + .flatMap((entry) => entry.generationId && generationIds.has(entry.generationId) ? [entry.generationId] : []); + if (removed.length === 0) return; + const packages = registry.packages.filter((entry) => entry.generationId === undefined || !generationIds.has(entry.generationId)); + registry.packages = packages; + registry.updatedAt = new Date().toISOString(); + await writeRegistry(key, registry); + }); + writes.set(key, current); + try { + await current; + return removed; + } finally { + if (writes.get(key) === current) writes.delete(key); + } +} diff --git a/apps/worker/src/work.ts b/apps/worker/src/work.ts new file mode 100644 index 0000000..dbd505c --- /dev/null +++ b/apps/worker/src/work.ts @@ -0,0 +1,70 @@ +import { + CACHE_GENERATION_LEASES_KEY, + MediaCommandSchema, + type MediaCommand, +} from '@easy-stream/contracts'; +import { Value } from '@sinclair/typebox/value'; +import { Worker, type Job } from 'bullmq'; +import { Redis } from 'ioredis'; + +export const MEDIA_QUEUE_NAME = 'easy-stream-media'; + +export interface MediaQueueWorkerOptions { + redisUrl: string; + concurrency?: number; + dispatch: (command: MediaCommand, job: Job) => Promise; + onCompleted?: (command: MediaCommand, job: Job) => Promise; + onFailed?: (command: MediaCommand | undefined, error: Error, job: Job | undefined) => Promise; +} + +export interface RunningMediaWorker { + worker: Worker; + recordCacheLease(generationId: string, protectedUntil: string): Promise; + protectedCacheGenerations(now?: Date): Promise>; + close(): Promise; +} + +export function startMediaQueueWorker(options: MediaQueueWorkerOptions): RunningMediaWorker { + const concurrency = options.concurrency ?? 2; + if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 32) { + throw new RangeError('Worker concurrency must be between 1 and 32'); + } + const redisOptions = { + maxRetriesPerRequest: null, + enableReadyCheck: true, + } as const; + const connection = new Redis(options.redisUrl, redisOptions); + const leases = new Redis(options.redisUrl, redisOptions); + const worker = new Worker( + MEDIA_QUEUE_NAME, + async (job) => { + if (!Value.Check(MediaCommandSchema, job.data)) throw new Error(`Invalid media command in job ${job.id ?? 'unknown'}`); + await options.dispatch(job.data, job); + await options.onCompleted?.(job.data, job); + }, + { connection, concurrency }, + ); + worker.on('failed', (job, error) => { + void options.onFailed?.(job?.data, error, job); + }); + worker.on('error', (error) => { + void options.onFailed?.(undefined, error, undefined); + }); + return { + worker, + async recordCacheLease(generationId, protectedUntil) { + const expiration = Date.parse(protectedUntil); + if (!Number.isFinite(expiration)) throw new Error('Invalid cache lease expiration'); + await leases.zadd(CACHE_GENERATION_LEASES_KEY, 'GT', expiration, generationId); + }, + async protectedCacheGenerations(now = new Date()) { + const timestamp = now.getTime(); + await leases.zremrangebyscore(CACHE_GENERATION_LEASES_KEY, '-inf', timestamp); + return new Set(await leases.zrangebyscore(CACHE_GENERATION_LEASES_KEY, timestamp + 1, '+inf')); + }, + async close() { + await worker.close(); + await Promise.all([connection.quit(), leases.quit()]); + }, + }; +} diff --git a/apps/worker/test/cache-lifecycle.test.ts b/apps/worker/test/cache-lifecycle.test.ts new file mode 100644 index 0000000..2772b54 --- /dev/null +++ b/apps/worker/test/cache-lifecycle.test.ts @@ -0,0 +1,63 @@ +import { mkdtemp, mkdir, stat, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { writeCacheMetadata } from '@easy-stream/media'; +import { describe, expect, it } from 'vitest'; +import { sweepCache } from '../src/cache-lifecycle.js'; +import { readRegistry, updateRegistry } from '../src/registry.js'; + +describe('worker cache lifecycle', () => { + it('evicts to the low watermark, removes registry rows, and prunes font orphans', async () => { + const base = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-cache-sweep-')); + const cacheRoot = path.join(base, 'cache'); + const generations = path.join(cacheRoot, 'generations'); + const registryPath = path.join(base, 'registry.json'); + const oldGeneration = '11111111-1111-4111-8111-111111111111'; + const protectedGeneration = '22222222-2222-4222-8222-222222222222'; + for (const generation of [oldGeneration, protectedGeneration]) { + const directory = path.join(generations, generation); + await mkdir(directory, { recursive: true }); + await writeFile(path.join(directory, 'segment.m4s'), Buffer.alloc(60)); + await writeCacheMetadata(generations, directory, { + key: generation, + bytes: 60, + lastAccessedAt: '2020-01-01T00:00:00.000Z', + active: false, + building: false, + pinned: false, + }); + await updateRegistry(registryPath, generation, { + mediaItemId: generation, + generationId: generation, + state: 'READY', + playable: true, + manifestPath: `/media/generations/${generation}/master.m3u8`, + }); + } + const fontStore = path.join(cacheRoot, 'assets', 'fonts', 'sha256'); + const orphanFont = path.join(fontStore, `${'a'.repeat(64)}.ttf`); + await mkdir(fontStore, { recursive: true }); + await writeFile(orphanFont, Buffer.alloc(10)); + + const result = await sweepCache({ + cacheRoot, + registryPath, + capacityBytes: 100, + highWatermark: 0.85, + lowWatermark: 0.75, + playbackTtlMs: 0, + protectedKeys: new Set([protectedGeneration]), + fontOrphanMinimumAgeMs: 0, + now: new Date('2999-01-01T00:00:00.000Z'), + }); + + expect(result.evicted).toEqual([oldGeneration]); + expect(result.registryEntriesRemoved).toEqual([oldGeneration]); + expect(result.orphanFontsRemoved).toEqual([path.basename(orphanFont)]); + expect((await readRegistry(registryPath)).packages).toEqual([ + expect.objectContaining({ generationId: protectedGeneration }), + ]); + await expect(stat(path.join(generations, oldGeneration))).rejects.toMatchObject({ code: 'ENOENT' }); + await expect(stat(path.join(generations, protectedGeneration))).resolves.toBeDefined(); + }); +}); diff --git a/apps/worker/test/catalog.test.ts b/apps/worker/test/catalog.test.ts new file mode 100644 index 0000000..a38ebf8 --- /dev/null +++ b/apps/worker/test/catalog.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest'; +import { deterministicUuid, parseMediaIdentity, shouldInspectSubtitleContent, slugify } from '../src/catalog.js'; + +describe('catalog filename parsing', () => { + it('groups the supplied season folder and episode filename', () => { + expect(parseMediaIdentity('Mushoku Tensei S3/Mushoku Tensei S3 - 01.[SS][720p][MixFlixTop].mkv')) + .toEqual({ kind: 'SERIES', title: 'Mushoku Tensei', seasonNumber: 3, episodeNumber: 1, episodeTitle: 'Episode 1' }); + }); + + it('creates stable UUIDs and Unicode-safe slugs', () => { + expect(deterministicUuid('same')).toBe(deterministicUuid('same')); + expect(deterministicUuid('same')).toMatch(/^[0-9a-f-]{36}$/u); + expect(slugify('فیلم نمونه')).toBe('فیلم-نمونه'); + }); + + it('samples only unknown textual subtitle languages during archive scans', () => { + expect(shouldInspectSubtitleContent({ index: 2, codec_type: 'subtitle', codec_name: 'ass', tags: { language: 'qad' } })).toBe(true); + expect(shouldInspectSubtitleContent({ index: 3, codec_type: 'subtitle', codec_name: 'ass', tags: { language: 'und' } })).toBe(true); + expect(shouldInspectSubtitleContent({ index: 4, codec_type: 'subtitle', codec_name: 'ass', tags: { language: 'per' } })).toBe(false); + expect(shouldInspectSubtitleContent({ index: 5, codec_type: 'subtitle', codec_name: 'subrip', tags: { language: 'eng' } })).toBe(false); + expect(shouldInspectSubtitleContent({ index: 6, codec_type: 'subtitle', codec_name: 'hdmv_pgs_subtitle' })).toBe(false); + }); +}); diff --git a/apps/worker/test/registry.test.ts b/apps/worker/test/registry.test.ts new file mode 100644 index 0000000..ec3eaa0 --- /dev/null +++ b/apps/worker/test/registry.test.ts @@ -0,0 +1,100 @@ +import { mkdtemp, readFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { PackageRegistrySchema } from '@easy-stream/contracts'; +import { Value } from '@sinclair/typebox/value'; +import { + normalizeTrackLabel, + readRegistry, + removeGenerationFromRegistry, + updateRegistry, +} from '../src/registry.js'; + +describe('local generation registry', () => { + it('atomically records API-loadable per-media status', async () => { + const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-registry-')); + const registryPath = path.join(directory, 'package-registry.json'); + const mediaItemId = '11111111-1111-4111-8111-111111111111'; + const generationId = '22222222-2222-4222-8222-222222222222'; + await updateRegistry(registryPath, mediaItemId, { + mediaItemId, generationId, state: 'READY', playable: true, + manifestPath: `/media/generations/${generationId}/master.m3u8`, + }); + const registry = await readRegistry(registryPath); + expect(registry.packages[0]).toMatchObject({ state: 'READY', playable: true }); + expect(Value.Check(PackageRegistrySchema, registry)).toBe(true); + expect(JSON.parse(await readFile(registryPath, 'utf8'))).toMatchObject({ version: 1 }); + await updateRegistry(registryPath, mediaItemId, { + mediaItemId, generationId, state: 'PREPARING', playable: false, + }); + expect((await readRegistry(registryPath)).packages[0]).toMatchObject({ + state: 'READY', playable: true, manifestPath: `/media/generations/${generationId}/master.m3u8`, + }); + expect(await removeGenerationFromRegistry(registryPath, generationId)).toBe(true); + expect((await readRegistry(registryPath)).packages).toEqual([]); + }); + + it('normalizes oversized and control-character container labels for the API contract', async () => { + const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-registry-label-')); + const registryPath = path.join(directory, 'package-registry.json'); + const mediaItemId = '11111111-1111-4111-8111-111111111111'; + const generationId = '22222222-2222-4222-8222-222222222222'; + const rawMkvTitle = ` Persian\u0000\n\tAudio\u202e ${'x'.repeat(180)} `; + const label = normalizeTrackLabel(rawMkvTitle, 'fa'); + + expect(label.length).toBeLessThanOrEqual(100); + expect(label).toBe(`Persian Audio ${'x'.repeat(86)}`); + expect(label).not.toMatch(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u); + + await updateRegistry(registryPath, mediaItemId, { + mediaItemId, + generationId, + state: 'READY', + playable: true, + manifestPath: `/media/generations/${generationId}/master.m3u8`, + audioTracks: [{ + id: '33333333-3333-4333-8333-333333333333', + language: 'fa', + label, + default: true, + }], + }); + + const registry = await readRegistry(registryPath); + expect(Value.Check(PackageRegistrySchema, registry)).toBe(true); + expect(registry.packages[0]?.audioTracks?.[0]?.label).toBe(label); + }); + + it('rejects an invalid update before replacing a valid registry file', async () => { + const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-registry-invalid-')); + const registryPath = path.join(directory, 'package-registry.json'); + const mediaItemId = '11111111-1111-4111-8111-111111111111'; + const generationId = '22222222-2222-4222-8222-222222222222'; + await updateRegistry(registryPath, mediaItemId, { + mediaItemId, + generationId, + state: 'READY', + playable: true, + manifestPath: `/media/generations/${generationId}/master.m3u8`, + }); + const before = await readFile(registryPath, 'utf8'); + + await expect(updateRegistry(registryPath, mediaItemId, { + mediaItemId, + generationId, + state: 'READY', + playable: true, + manifestPath: `/media/generations/${generationId}/master.m3u8`, + audioTracks: [{ + id: '33333333-3333-4333-8333-333333333333', + language: 'en', + label: 'x'.repeat(101), + default: true, + }], + })).rejects.toThrow(/Refusing to publish invalid package registry/u); + + expect(await readFile(registryPath, 'utf8')).toBe(before); + expect(Value.Check(PackageRegistrySchema, await readRegistry(registryPath))).toBe(true); + }); +}); diff --git a/apps/worker/test/work.test.ts b/apps/worker/test/work.test.ts new file mode 100644 index 0000000..d7c7a16 --- /dev/null +++ b/apps/worker/test/work.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from 'vitest'; +import { MEDIA_QUEUE_NAME, startMediaQueueWorker } from '../src/work.js'; + +describe('BullMQ media worker', () => { + it('uses the API queue name and rejects unsafe concurrency before connecting', () => { + expect(MEDIA_QUEUE_NAME).toBe('easy-stream-media'); + expect(() => startMediaQueueWorker({ + redisUrl: 'redis://127.0.0.1:1', + concurrency: 0, + async dispatch() {}, + })).toThrow('concurrency'); + }); +}); diff --git a/apps/worker/tsconfig.json b/apps/worker/tsconfig.json new file mode 100644 index 0000000..8a9d625 --- /dev/null +++ b/apps/worker/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist", + "types": ["node"], + "paths": { + "@easy-stream/contracts": ["packages/contracts/dist/index.d.ts"], + "@easy-stream/database": ["packages/database/dist/index.d.ts"], + "@easy-stream/media": ["packages/media/dist/index.d.ts"] + } + }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.test.ts"] +} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..fd44d4c --- /dev/null +++ b/compose.yaml @@ -0,0 +1,177 @@ +name: easy-stream + +services: + postgres: + image: postgres:18-alpine + restart: unless-stopped + environment: + POSTGRES_DB: easy_stream + POSTGRES_USER: easy_stream + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env} + volumes: + - postgres-data:/var/lib/postgresql + healthcheck: + test: ["CMD-SHELL", "pg_isready -U easy_stream -d easy_stream"] + interval: 5s + timeout: 3s + retries: 20 + networks: + - backend + + redis: + image: redis:8-alpine + restart: unless-stopped + command: ["redis-server", "--appendonly", "yes"] + volumes: + - redis-data:/data + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 20 + networks: + - backend + + migrate: + build: + context: . + dockerfile: infra/docker/node.Dockerfile + target: api + command: ["./node_modules/.bin/drizzle-kit", "migrate", "--config", "drizzle.config.ts"] + working_dir: /app/packages/database + environment: + DATABASE_URL: postgres://easy_stream:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}@postgres:5432/easy_stream + read_only: true + tmpfs: + - /tmp + security_opt: + - no-new-privileges:true + cap_drop: + - ALL + depends_on: + postgres: + condition: service_healthy + networks: + - backend + + api: + build: + context: . + dockerfile: infra/docker/node.Dockerfile + target: api + restart: unless-stopped + init: true + env_file: .env + environment: + NODE_ENV: production + REPOSITORY_DRIVER: postgres + DATABASE_URL: postgres://easy_stream:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}@postgres:5432/easy_stream + REDIS_URL: redis://redis:6379 + METADATA_ROOT: /data/metadata + CATALOG_SNAPSHOT_PATH: /data/metadata/catalog.json + PACKAGE_REGISTRY_PATH: /data/metadata/package-registry.json + CACHE_ROOT: /data/cache + # Use the same Compose interpolation source as the gateway. Values from + # env_file alone can diverge when operators use --env-file or shell + # overrides, which would make every media authorization request fail. + MEDIA_AUTH_SHARED_SECRET: ${MEDIA_AUTH_SHARED_SECRET:?set MEDIA_AUTH_SHARED_SECRET in .env} + volumes: + - ${METADATA_ROOT:-./data/metadata}:/data/metadata:ro + - ${CACHE_ROOT:-./data/cache}:/data/cache:ro + read_only: true + tmpfs: + - /tmp + security_opt: + - no-new-privileges:true + cap_drop: + - ALL + healthcheck: + test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:3000/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"] + interval: 10s + timeout: 3s + retries: 12 + depends_on: + migrate: + condition: service_completed_successfully + redis: + condition: service_healthy + networks: + - backend + - edge + + worker: + build: + context: . + dockerfile: infra/docker/node.Dockerfile + target: worker + restart: unless-stopped + init: true + environment: + NODE_ENV: production + DATABASE_URL: postgres://easy_stream:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}@postgres:5432/easy_stream + REDIS_URL: redis://redis:6379 + ARCHIVE_ROOT: /archive + CACHE_ROOT: /data/cache + DERIVED_ROOT: /data/derived + METADATA_ROOT: /data/metadata + CATALOG_SNAPSHOT_PATH: /data/metadata/catalog.json + INVENTORY_SNAPSHOT_PATH: /data/metadata/inventory.json + PACKAGE_REGISTRY_PATH: /data/metadata/package-registry.json + FFMPEG_PATH: /opt/ffmpeg/bin/ffmpeg + FFPROBE_PATH: /opt/ffmpeg/bin/ffprobe + PLAYBACK_PROFILE: ${PLAYBACK_PROFILE:-cmaf-v1} + PLAYBACK_TTL_SECONDS: ${PLAYBACK_TTL_SECONDS:-14400} + CACHE_MAX_BYTES: ${CACHE_MAX_BYTES:-2147483648000} + CACHE_HIGH_WATERMARK: ${CACHE_HIGH_WATERMARK:-0.85} + CACHE_LOW_WATERMARK: ${CACHE_LOW_WATERMARK:-0.75} + MEDIA_WORKER_CONCURRENCY: ${JIT_REMUX_CONCURRENCY:-2} + volumes: + - ${ARCHIVE_ROOT:-./movies}:/archive:ro + - ${CACHE_ROOT:-./data/cache}:/data/cache + - ${DERIVED_ROOT:-./data/derived}:/data/derived + - ${METADATA_ROOT:-./data/metadata}:/data/metadata + read_only: true + tmpfs: + - /tmp + security_opt: + - no-new-privileges:true + cap_drop: + - ALL + depends_on: + migrate: + condition: service_completed_successfully + redis: + condition: service_healthy + networks: + - backend + + gateway: + build: + context: . + dockerfile: infra/docker/node.Dockerfile + target: gateway + restart: unless-stopped + ports: + - "${GATEWAY_BIND_ADDRESS:-0.0.0.0}:8080:8080" + environment: + MEDIA_AUTH_SHARED_SECRET: ${MEDIA_AUTH_SHARED_SECRET:?set MEDIA_AUTH_SHARED_SECRET in .env} + volumes: + - ${CACHE_ROOT:-./data/cache}:/srv/easy-stream/cache:ro + - ${DERIVED_ROOT:-./data/derived}:/srv/easy-stream/derived:ro + depends_on: + api: + condition: service_healthy + security_opt: + - no-new-privileges:true + networks: + - backend + - edge + +volumes: + postgres-data: + redis-data: + +networks: + backend: + internal: true + edge: diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..455fe09 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,56 @@ +# Easy Stream architecture + +## Runtime topology + +```text +Browser / TV browser + | + v +CDN (production, provider managed externally) + | + v +Nginx gateway ───────> Vue SPA + | | + | └─────────> versioned CMAF/HLS cache + v +Fastify API ─────────> PostgreSQL + | | + └───────────────> Redis/BullMQ + | + v + FFmpeg media worker + | | + v v + read-only MKV cache/derived volumes + archive +``` + +The archive is never exposed over HTTP and is never writable by an application container. Nginx serves only generated, versioned media after a signed playback-cookie check. Media is private-cache by default. A production CDN may turn on shared caching only when its edge validates an equivalent grant before checking its cache; forwarding a cookie only on an origin miss is insufficient. + +## Media lifecycle + +1. The worker walks regular `.mkv` files under `ARCHIVE_ROOT`, rejects escaping symlinks, fingerprints the file, and records ffprobe stream metadata. +2. Sources are classified as `COPY`, `AUDIO_TRANSCODE`, `VIDEO_TRANSCODE`, `HOLD_HDR`, or `INVALID`. +3. Publication is allowed immediately for `COPY`; incompatible SDR media must finish its single H.264/AAC compatibility representation first. HDR is held in v1. +4. A cold playback request creates one packaging job per source/profile fingerprint. FFmpeg copies supported elementary streams to separate fragmented-MP4 HLS playlists. +5. EVENT manifests may grow privately, but the registry remains `PREPARING` until HLS, subtitles, and generation-scoped fonts are all ready. The worker then publishes one complete `READY` record and finalizes immutable VOD playlists. +6. Compatible generations live in the 2 TB LRU cache. A playback session records a Redis lease and persistent access timestamp through the signed-cookie expiry; high/low-watermark sweeps skip leased, building, pinned, and recently touched entries. Encoded compatibility components live on separately sized durable storage and are never swept. +7. Eviction removes the matching package-registry entry so the next request regenerates it. Aged global font objects with no generation hardlinks are pruned during packaging sweeps. + +There is deliberately no adaptive bitrate ladder. Slow connections or devices that reject the original resolution receive a clear compatibility/connection error rather than an undisclosed quality reduction. + +## Trust boundaries + +- Archive filenames, Matroska flags, subtitle text, fonts, and metadata are untrusted input. +- FFmpeg and ffprobe are spawned with argument arrays and no shell. +- Worker processes run unprivileged with a read-only archive and receive only their database, Redis, path, and media settings—not playback, administrator, media-auth, or TMDB secrets. FFmpeg/ffprobe children receive a further allowlisted environment without database or Redis credentials. +- Generated paths use server identifiers rather than source filenames. +- The gateway applies CSP, COOP, COEP, nosniff, frame, and referrer protections. +- Playback cookies are scoped to one media generation and expire after four hours. +- Viewer state stays in IndexedDB; there is no viewer identity database in v1. + +## Scale boundaries + +The first deployment targets 1,000 peak concurrent viewers behind a CDN. JIT packaging defaults to two concurrent jobs and compatibility encoding to one CPU-limited job. PostgreSQL, Redis, the API, workers, cache, and gateway have explicit boundaries so they can be moved to separate hosts without changing public API contracts. + +The implemented scanner produces codec/HDR compatibility, duration, stream, subtitle, and fingerprint inventory. Before production disk capacity is purchased, extend the archive census with measured GOP distribution, corruption sampling, aggregate bitrate, and projected derived-storage reports; those expensive archive-wide reports are an acceptance gate, not part of the request-time path. diff --git a/docs/operations.md b/docs/operations.md new file mode 100644 index 0000000..61ef029 --- /dev/null +++ b/docs/operations.md @@ -0,0 +1,74 @@ +# Operations + +## Interactive Ubuntu bootstrap + +After cloning the repository on an Ubuntu server, run: + +```sh +bash scripts/setup-ubuntu.sh +``` + +The bootstrap uses Docker's signed Ubuntu apt repository, prompts for production values without echoing secrets, optionally generates 256-bit secrets, creates a mode-`0600` `.env`, and validates Compose before it offers to start the stack. It refuses overlapping archive/cache/derived/metadata paths and warns when the host archive mount is writable or the configured cache exceeds available disk space. Its gateway bind address defaults to `127.0.0.1`; select `0.0.0.0` or a specific interface only when network-level origin restrictions are ready. + +The script intentionally does not add the operator to the `docker` group because that group grants root-equivalent privileges. It uses `sudo` for Docker when needed. It also leaves DNS, HTTPS termination, CDN authorization, firewall policy, storage mounting, and backup automation to the operator. + +## Host layout + +- `/srv/easy-stream/archive`: read-only archive mount +- `/srv/easy-stream/cache`: 2 TB NVMe hot package cache +- `/srv/easy-stream/derived`: persistent compatibility components +- `/srv/easy-stream/metadata`: extracted subtitles, approved fonts, and cached metadata +- Docker named volume `postgres-data`: PostgreSQL data (PostgreSQL 18 layout) + +Use a dedicated unprivileged service account. Confirm the archive mount is read-only with `findmnt -no OPTIONS /srv/easy-stream/archive` before starting workers. + +Create bind-mount destinations before the first Compose start; otherwise Docker may create root-owned directories that UID/GID 1000 cannot write: + +```sh +sudo install -d -o 1000 -g 1000 -m 0750 \ + /srv/easy-stream/cache \ + /srv/easy-stream/derived \ + /srv/easy-stream/metadata +``` + +Use one public HTTPS origin for the SPA, API, and media routes. The v1 playback grant is a host-only, generation-path cookie, so a second media hostname will not receive it. A split hostname requires CDN-native edge authorization instead. + +The API and media worker run as UID 1000, and the gateway's Nginx workers are configured to the same UID for read-only media access. Keep the bind mounts owned by that account rather than making generated media world-readable. + +## Required production gates + +1. Complete the archive census and size the durable derived volume to 125% of the projected output. +2. Validate current and previous-two Chrome/Firefox releases plus the named physical TV test devices. +3. Load test 1,000 concurrent playback patterns through the selected CDN. +4. Restrict origin ingress to the CDN and administration network. +5. Replace all bootstrap credentials and signing secrets. +6. Confirm movie, audio, subtitle, font, poster, and territorial distribution rights. +7. Confirm a written TMDB commercial agreement before using TMDB in a commercial production service. +8. Run migrations against an empty PostgreSQL database and verify API/worker startup before importing the archive. + +## CDN authorization + +The origin sends `Cache-Control: private` for immutable media and `no-store` for manifests. Keep that behavior for initial deployment. Forwarding the playback cookie to the origin secures only cache misses; it does not protect a shared cache hit. + +Enable shared media caching only after the chosen CDN validates a signed cookie or URL before cache lookup and rejects expired grants. Keep manifests uncacheable, cache generation assets by their canonical path after authorization, restrict direct origin ingress to the CDN, and test unauthorized warm-cache requests as part of acceptance. + +Before relying on per-client rate limits or logs, configure Nginx `real_ip_from` only for the selected CDN's published address ranges and map its authenticated client-IP header. The safe default discards client-supplied forwarding chains, which means an unconfigured CDN will otherwise group viewers by edge address. + +## Cache lifecycle + +Playback creation writes a Redis lease through the session expiry and queues a metadata touch. After a successful JIT package, the worker sweeps from the configured high watermark down to the low watermark. It skips active, building, pinned, recently built, or leased generations, removes evicted registry entries atomically, and prunes aged unreferenced global fonts. Durable files under `DERIVED_ROOT` are outside this lifecycle. + +Manual eviction is intentionally refused while a generation has an active lease. If cache pressure cannot fall below the target because every candidate is protected, add capacity or wait for sessions to expire; never remove generation directories by hand while viewers are active. + +## Backups and recovery + +- Back up PostgreSQL and deployment configuration every night and test restoration monthly. +- Cache media is disposable and must not be backed up. +- Metadata and subtitles are reproducible, but snapshots reduce archive rereads. +- Derived compatibility media is reproducible but expensive; snapshot it according to recovery-time requirements. +- On source replacement, retain an active old generation until its playback cookies expire, then evict it. +- Keep Redis persistence enabled: cache leases are written synchronously before a READY session is returned, then mirrored into generation metadata by the worker. The four-hour recency grace also protects a newly completed cold package before its first poll. + +## Alerts + +Alert on API 5xx rate, playback-session failures, FFmpeg failures, job age, cache pressure, derived disk pressure, archive I/O latency, cold-start p95, origin throughput, invalid signed-cookie spikes, and client fatal-player events. diff --git a/infra/docker/node.Dockerfile b/infra/docker/node.Dockerfile new file mode 100644 index 0000000..f6d25ce --- /dev/null +++ b/infra/docker/node.Dockerfile @@ -0,0 +1,77 @@ +FROM node:24-bookworm-slim AS build + +ENV PNPM_HOME=/pnpm +ENV PATH=$PNPM_HOME:$PATH +WORKDIR /workspace +RUN corepack enable + +COPY package.json pnpm-lock.yaml pnpm-workspace.yaml tsconfig.base.json ./ +COPY apps ./apps +COPY packages ./packages +RUN corepack pnpm install --frozen-lockfile +RUN corepack pnpm build + +FROM node:24-bookworm-slim AS ffmpeg-build +ARG FFMPEG_VERSION=8.1.2 +ARG FFMPEG_SHA256=464beb5e7bf0c311e68b45ae2f04e9cc2af88851abb4082231742a74d97b524c +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + build-essential ca-certificates curl libass-dev libfontconfig1-dev \ + libfreetype6-dev libfribidi-dev libharfbuzz-dev libssl-dev libx264-dev \ + nasm pkg-config xz-utils yasm zlib1g-dev \ + && rm -rf /var/lib/apt/lists/* +WORKDIR /tmp/ffmpeg +RUN curl --fail --location --silent --show-error \ + "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz" \ + --output ffmpeg.tar.xz \ + && echo "${FFMPEG_SHA256} ffmpeg.tar.xz" | sha256sum --check --strict \ + && tar --extract --file ffmpeg.tar.xz --strip-components=1 \ + && ./configure \ + --prefix=/opt/ffmpeg \ + --disable-debug \ + --disable-doc \ + --disable-ffplay \ + --disable-static \ + --enable-shared \ + --enable-gpl \ + --enable-version3 \ + --enable-libass \ + --enable-libfontconfig \ + --enable-libfreetype \ + --enable-libx264 \ + --enable-openssl \ + && make -j"$(nproc)" \ + && make install + +FROM node:24-bookworm-slim AS api +ENV NODE_ENV=production +WORKDIR /app +COPY --from=build /workspace /app +USER node +CMD ["node", "apps/api/dist/server.js"] + +FROM node:24-bookworm-slim AS worker +ARG DEBIAN_FRONTEND=noninteractive +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + ca-certificates libass9 libfontconfig1 libfreetype6 libfribidi0 \ + libharfbuzz0b libssl3 libx264-164 zlib1g \ + && rm -rf /var/lib/apt/lists/* +COPY --from=ffmpeg-build /opt/ffmpeg /opt/ffmpeg +ENV NODE_ENV=production +ENV PATH=/opt/ffmpeg/bin:$PATH +ENV LD_LIBRARY_PATH=/opt/ffmpeg/lib +WORKDIR /app +COPY --from=build /workspace /app +USER node +CMD ["node", "apps/worker/dist/index.js", "work"] + +FROM nginx:1.28-alpine AS gateway +RUN apk add --no-cache ca-certificates \ + && addgroup -g 1000 easy-stream \ + && adduser -D -H -u 1000 -G easy-stream easy-stream \ + && sed -i 's/^user[[:space:]][[:space:]]*nginx;/user easy-stream;/' /etc/nginx/nginx.conf \ + && chown -R easy-stream:easy-stream /var/cache/nginx +COPY infra/nginx/default.conf.template /etc/nginx/templates/default.conf.template +COPY infra/nginx/security-headers.conf /etc/nginx/security-headers.conf +COPY --from=build /workspace/apps/web/dist /usr/share/nginx/html diff --git a/infra/nginx/default.conf.template b/infra/nginx/default.conf.template new file mode 100644 index 0000000..81d2c4a --- /dev/null +++ b/infra/nginx/default.conf.template @@ -0,0 +1,118 @@ +map $uri $media_cache_control { + default "no-store"; + ~*\.m3u8$ "private, no-cache, no-store, must-revalidate"; + # Safe origin default: browsers may retain immutable generation assets, but a + # shared CDN must not cache them until it enforces playback authorization at + # the edge before cache lookup. + ~*\.(m4s|mp4|vtt|ass|ttf|otf)$ "private, max-age=31536000, immutable"; +} + +upstream easy_stream_api { + server api:3000; + keepalive 64; +} + +server { + listen 8080; + server_name _; + server_tokens off; + root /usr/share/nginx/html; + + include /etc/nginx/security-headers.conf; + + # Cache bookkeeping is mounted beside public generations but is never media. + location ~ (^|/)\. { + deny all; + } + + location /api/ { + proxy_http_version 1.1; + proxy_set_header Host $host; + # Never trust a client-supplied forwarding chain. Configure real_ip_from + # for the selected CDN at deployment time if end-user IPs are required. + proxy_set_header X-Forwarded-For $remote_addr; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_pass http://easy_stream_api; + add_header Cache-Control "no-store" always; + include /etc/nginx/security-headers.conf; + } + + location = /_media_auth { + internal; + proxy_pass_request_body off; + proxy_set_header Content-Length ""; + proxy_set_header X-Original-URI $request_uri; + proxy_set_header Cookie $http_cookie; + proxy_set_header X-Media-Auth-Secret "${MEDIA_AUTH_SHARED_SECRET}"; + proxy_pass http://easy_stream_api/internal/media-auth; + } + + # Offline compatibility encodes are durable and live on a separate disk. + # Keep the more-specific prefix ahead of the bounded JIT cache route. + location /media/derived/ { + auth_request /_media_auth; + alias /srv/easy-stream/derived/; + disable_symlinks on; + types { + application/vnd.apple.mpegurl m3u8; + video/iso.segment m4s; + video/mp4 mp4; + text/vtt vtt; + text/x-ssa ass; + font/ttf ttf; + font/otf otf; + } + add_header Cache-Control $media_cache_control always; + include /etc/nginx/security-headers.conf; + } + + location /media/ { + auth_request /_media_auth; + alias /srv/easy-stream/cache/; + disable_symlinks on; + types { + application/vnd.apple.mpegurl m3u8; + video/iso.segment m4s; + video/mp4 mp4; + text/vtt vtt; + text/x-ssa ass; + font/ttf ttf; + font/otf otf; + } + add_header Cache-Control $media_cache_control always; + include /etc/nginx/security-headers.conf; + } + + # TMDB artwork stays same-origin for CSP/COEP and can be cached by the outer CDN. + location /images/tmdb/ { + limit_except GET HEAD { deny all; } + rewrite ^/images/tmdb/(w500|w1280)(/.*)$ /t/p/$1$2 break; + proxy_ssl_server_name on; + proxy_ssl_verify on; + proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt; + proxy_ssl_verify_depth 3; + proxy_set_header Host image.tmdb.org; + proxy_hide_header Set-Cookie; + proxy_hide_header Cache-Control; + proxy_pass https://image.tmdb.org; + add_header Cache-Control "public, max-age=86400, stale-while-revalidate=604800" always; + include /etc/nginx/security-headers.conf; + } + + location /healthz { + access_log off; + return 200 "ok\n"; + } + + location /assets/ { + try_files $uri =404; + add_header Cache-Control "public, max-age=31536000, immutable" always; + include /etc/nginx/security-headers.conf; + } + + location / { + try_files $uri $uri/ /index.html; + add_header Cache-Control "no-cache"; + include /etc/nginx/security-headers.conf; + } +} diff --git a/infra/nginx/security-headers.conf b/infra/nginx/security-headers.conf new file mode 100644 index 0000000..84e26bf --- /dev/null +++ b/infra/nginx/security-headers.conf @@ -0,0 +1,8 @@ +add_header X-Content-Type-Options nosniff always; +add_header Referrer-Policy no-referrer always; +add_header X-Frame-Options DENY always; +add_header Cross-Origin-Opener-Policy same-origin always; +add_header Cross-Origin-Embedder-Policy require-corp always; +add_header Cross-Origin-Resource-Policy same-origin always; +add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; +add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; worker-src 'self' blob:; font-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'" always; diff --git a/package.json b/package.json new file mode 100644 index 0000000..884b4e5 --- /dev/null +++ b/package.json @@ -0,0 +1,23 @@ +{ + "name": "easy-stream", + "version": "0.1.0", + "private": true, + "type": "module", + "packageManager": "pnpm@11.13.0", + "engines": { + "node": ">=22" + }, + "scripts": { + "build": "corepack pnpm -r --if-present build", + "dev": "corepack pnpm --parallel --filter @easy-stream/api --filter @easy-stream/worker --filter @easy-stream/web dev", + "test": "corepack pnpm -r --if-present test", + "typecheck": "corepack pnpm -r --if-present typecheck", + "scan:samples": "corepack pnpm --filter @easy-stream/worker scan -- --root ./movies --output ./data/metadata/catalog.json --inventory-output ./data/metadata/inventory.json", + "migrate": "corepack pnpm --filter @easy-stream/database migrate", + "clean": "corepack pnpm -r --if-present clean" + }, + "devDependencies": { + "typescript": "^5.9.3", + "vitest": "^3.2.4" + } +} diff --git a/packages/contracts/package.json b/packages/contracts/package.json new file mode 100644 index 0000000..8b7716a --- /dev/null +++ b/packages/contracts/package.json @@ -0,0 +1,27 @@ +{ + "name": "@easy-stream/contracts", + "version": "0.1.0", + "private": true, + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "files": ["dist"], + "scripts": { + "build": "tsc -p tsconfig.json", + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest run" + }, + "dependencies": { + "@sinclair/typebox": "^0.34.41" + }, + "devDependencies": { + "typescript": "^5.9.3", + "vitest": "^3.2.4" + } +} diff --git a/packages/contracts/src/admin.ts b/packages/contracts/src/admin.ts new file mode 100644 index 0000000..ffd2598 --- /dev/null +++ b/packages/contracts/src/admin.ts @@ -0,0 +1,134 @@ +import { Type, type Static } from '@sinclair/typebox'; +import { DateTimeSchema, EmailSchema, UuidSchema } from './common.js'; + +export const AdminLoginSchema = Type.Object( + { + email: EmailSchema, + password: Type.String({ minLength: 12, maxLength: 1024 }), + totp: Type.Optional(Type.String({ pattern: '^[0-9]{6}$' })), + }, + { additionalProperties: false }, +); + +export const AdminSessionResponseSchema = Type.Object( + { + admin: Type.Object( + { id: UuidSchema, email: EmailSchema }, + { additionalProperties: false }, + ), + csrfToken: Type.String(), + expiresAt: DateTimeSchema, + }, + { additionalProperties: false }, +); + +export const StartScanSchema = Type.Object( + { full: Type.Optional(Type.Boolean({ default: false })) }, + { additionalProperties: false }, +); + +export const PublicationParamsSchema = Type.Object( + { mediaItemId: UuidSchema }, + { additionalProperties: false }, +); + +export const PublicationBodySchema = Type.Object( + { published: Type.Boolean() }, + { additionalProperties: false }, +); + +export const JobStateSchema = Type.Union([ + Type.Literal('QUEUED'), + Type.Literal('RUNNING'), + Type.Literal('SUCCEEDED'), + Type.Literal('FAILED'), + Type.Literal('CANCELLED'), +]); + +export const JobSchema = Type.Object( + { + id: UuidSchema, + type: Type.String(), + state: JobStateSchema, + progress: Type.Number({ minimum: 0, maximum: 1 }), + error: Type.Union([Type.String(), Type.Null()]), + createdAt: DateTimeSchema, + updatedAt: DateTimeSchema, + }, + { additionalProperties: false }, +); + +export const JobParamsSchema = Type.Object({ jobId: UuidSchema }, { additionalProperties: false }); +export const CacheParamsSchema = Type.Object( + { generationId: UuidSchema }, + { additionalProperties: false }, +); + +export const CacheStatusSchema = Type.Object( + { + usedBytes: Type.Integer({ minimum: 0 }), + maxBytes: Type.Integer({ minimum: 1 }), + highWatermark: Type.Number({ minimum: 0, maximum: 1 }), + lowWatermark: Type.Number({ minimum: 0, maximum: 1 }), + activePackages: Type.Integer({ minimum: 0 }), + }, + { additionalProperties: false }, +); + +export const MetadataSearchQuerySchema = Type.Object( + { + q: Type.String({ minLength: 1, maxLength: 200 }), + kind: Type.Union([Type.Literal('MOVIE'), Type.Literal('SERIES')]), + year: Type.Optional(Type.Integer({ minimum: 1888, maximum: 2200 })), + }, + { additionalProperties: false }, +); + +export const MetadataCandidateSchema = Type.Object( + { + provider: Type.Literal('TMDB'), + externalId: Type.Integer({ minimum: 1 }), + kind: Type.Union([Type.Literal('MOVIE'), Type.Literal('SERIES')]), + name: Type.Object( + { fa: Type.String(), en: Type.Optional(Type.String()) }, + { additionalProperties: false }, + ), + synopsis: Type.Object( + { fa: Type.Optional(Type.String()), en: Type.Optional(Type.String()) }, + { additionalProperties: false }, + ), + posterUrl: Type.Optional(Type.String()), + backdropUrl: Type.Optional(Type.String()), + year: Type.Optional(Type.Integer()), + }, + { additionalProperties: false }, +); + +export const MetadataSearchResponseSchema = Type.Object( + { items: Type.Array(MetadataCandidateSchema) }, + { additionalProperties: false }, +); + +export const MetadataMatchParamsSchema = Type.Object( + { titleId: UuidSchema }, + { additionalProperties: false }, +); + +export const MetadataMatchBodySchema = Type.Object( + { + provider: Type.Literal('TMDB'), + externalId: Type.Integer({ minimum: 1 }), + kind: Type.Union([Type.Literal('MOVIE'), Type.Literal('SERIES')]), + }, + { additionalProperties: false }, +); + +export type AdminLogin = Static; +export type AdminSessionResponse = Static; +export type StartScan = Static; +export type Job = Static; +export type JobState = Static; +export type CacheStatus = Static; +export type MetadataSearchQuery = Static; +export type MetadataCandidate = Static; +export type MetadataMatchBody = Static; diff --git a/packages/contracts/src/catalog.ts b/packages/contracts/src/catalog.ts new file mode 100644 index 0000000..df9d966 --- /dev/null +++ b/packages/contracts/src/catalog.ts @@ -0,0 +1,134 @@ +import { Type, type Static } from '@sinclair/typebox'; +import { DateTimeSchema, UuidSchema } from './common.js'; + +export const TitleKindSchema = Type.Union([Type.Literal('MOVIE'), Type.Literal('SERIES')]); +export const MediaKindSchema = Type.Union([Type.Literal('MOVIE'), Type.Literal('EPISODE')]); + +export const LocalizedTextSchema = Type.Object( + { + fa: Type.String(), + en: Type.Optional(Type.String()), + }, + { additionalProperties: false }, +); + +export const OptionalLocalizedTextSchema = Type.Object( + { + fa: Type.Optional(Type.String()), + en: Type.Optional(Type.String()), + }, + { additionalProperties: false }, +); + +export const CatalogCardSchema = Type.Object( + { + id: UuidSchema, + slug: Type.String(), + kind: TitleKindSchema, + name: LocalizedTextSchema, + posterUrl: Type.Optional(Type.String()), + backdropUrl: Type.Optional(Type.String()), + year: Type.Optional(Type.Integer()), + playable: Type.Boolean(), + resumeMediaItemId: Type.Optional(UuidSchema), + }, + { additionalProperties: false }, +); + +export const MediaItemSummarySchema = Type.Object( + { + id: UuidSchema, + kind: MediaKindSchema, + seasonNumber: Type.Optional(Type.Integer({ minimum: 0 })), + episodeNumber: Type.Optional(Type.Integer({ minimum: 0 })), + name: Type.Optional(OptionalLocalizedTextSchema), + durationSeconds: Type.Number({ minimum: 0 }), + compatibility: Type.Union([ + Type.Literal('COPY'), + Type.Literal('AUDIO_TRANSCODE'), + Type.Literal('VIDEO_TRANSCODE'), + Type.Literal('HOLD_HDR'), + Type.Literal('INVALID'), + ]), + published: Type.Boolean(), + }, + { additionalProperties: false }, +); + +export const SeasonSummarySchema = Type.Object( + { + number: Type.Integer({ minimum: 0 }), + episodeCount: Type.Integer({ minimum: 0 }), + }, + { additionalProperties: false }, +); + +export const TitleDetailSchema = Type.Object( + { + id: UuidSchema, + slug: Type.String(), + kind: TitleKindSchema, + name: LocalizedTextSchema, + posterUrl: Type.Optional(Type.String()), + backdropUrl: Type.Optional(Type.String()), + year: Type.Optional(Type.Integer()), + playable: Type.Boolean(), + resumeMediaItemId: Type.Optional(UuidSchema), + synopsis: OptionalLocalizedTextSchema, + seasons: Type.Optional(Type.Array(SeasonSummarySchema)), + mediaItems: Type.Array(MediaItemSummarySchema), + updatedAt: DateTimeSchema, + }, + { additionalProperties: false }, +); + +export const CatalogQuerySchema = Type.Object( + { + cursor: Type.Optional(Type.String({ maxLength: 512 })), + limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 100, default: 24 })), + kind: Type.Optional(TitleKindSchema), + }, + { additionalProperties: false }, +); + +export const SearchQuerySchema = Type.Object( + { + q: Type.String({ minLength: 1, maxLength: 200 }), + limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 50, default: 20 })), + }, + { additionalProperties: false }, +); + +export const CatalogResponseSchema = Type.Object( + { + items: Type.Array(CatalogCardSchema), + nextCursor: Type.Optional(Type.String()), + }, + { additionalProperties: false }, +); + +export const SearchResponseSchema = Type.Object( + { items: Type.Array(CatalogCardSchema) }, + { additionalProperties: false }, +); + +export const CatalogSnapshotSchema = Type.Object( + { + version: Type.Literal(1), + generatedAt: DateTimeSchema, + titles: Type.Array(TitleDetailSchema), + }, + { additionalProperties: false }, +); + +export type TitleKind = Static; +export type MediaKind = Static; +export type LocalizedText = Static; +export type OptionalLocalizedText = Static; +export type CatalogCard = Static; +export type MediaItemSummary = Static; +export type TitleDetail = Static; +export type CatalogQuery = Static; +export type SearchQuery = Static; +export type CatalogResponse = Static; +export type CatalogSnapshot = Static; diff --git a/packages/contracts/src/common.ts b/packages/contracts/src/common.ts new file mode 100644 index 0000000..d390058 --- /dev/null +++ b/packages/contracts/src/common.ts @@ -0,0 +1,42 @@ +import { Type, type Static } from '@sinclair/typebox'; + +export const UuidSchema = Type.String({ + pattern: '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$', +}); +export const DateTimeSchema = Type.String({ + pattern: '^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$', +}); +export const EmailSchema = Type.String({ + maxLength: 320, + pattern: '^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$', +}); + +export const ErrorCodeSchema = Type.Union([ + Type.Literal('BAD_REQUEST'), + Type.Literal('NOT_FOUND'), + Type.Literal('UNAUTHORIZED'), + Type.Literal('FORBIDDEN'), + Type.Literal('CONFLICT'), + Type.Literal('VALIDATION_ERROR'), + Type.Literal('UNSUPPORTED_CLIENT'), + Type.Literal('MEDIA_UNAVAILABLE'), + Type.Literal('INTERNAL_ERROR'), +]); + +export const ErrorResponseSchema = Type.Object( + { + error: Type.Object( + { + code: ErrorCodeSchema, + message: Type.String(), + requestId: Type.String(), + details: Type.Optional(Type.Unknown()), + }, + { additionalProperties: false }, + ), + }, + { additionalProperties: false }, +); + +export type ErrorCode = Static; +export type ErrorResponse = Static; diff --git a/packages/contracts/src/events.ts b/packages/contracts/src/events.ts new file mode 100644 index 0000000..7839c43 --- /dev/null +++ b/packages/contracts/src/events.ts @@ -0,0 +1,98 @@ +import { Type, type Static } from '@sinclair/typebox'; +import { DateTimeSchema, UuidSchema } from './common.js'; +import { AudioTrackSchema, SubtitleTrackSchema } from './playback.js'; + +export const MediaCommandSchema = Type.Union([ + Type.Object( + { + type: Type.Literal('media.playback.requested'), + sessionId: UuidSchema, + mediaItemId: UuidSchema, + }, + { additionalProperties: false }, + ), + Type.Object( + { type: Type.Literal('archive.scan.requested'), jobId: UuidSchema, full: Type.Boolean() }, + { additionalProperties: false }, + ), + Type.Object( + { + type: Type.Literal('media.publication.changed'), + mediaItemId: UuidSchema, + published: Type.Boolean(), + }, + { additionalProperties: false }, + ), + Type.Object( + { type: Type.Literal('package.eviction.requested'), generationId: UuidSchema }, + { additionalProperties: false }, + ), + Type.Object( + { + type: Type.Literal('cache.generation.accessed'), + sessionId: UuidSchema, + generationId: UuidSchema, + accessedAt: DateTimeSchema, + protectedUntil: DateTimeSchema, + }, + { additionalProperties: false }, + ), +]); + +/** Shared by the API lease writer and worker eviction reader. */ +export const CACHE_GENERATION_LEASES_KEY = 'easy-stream:cache-generation-leases:v1'; + +export const MediaPreparationResultSchema = Type.Object( + { + sessionId: UuidSchema, + state: Type.Union([ + Type.Literal('PREPARING'), + Type.Literal('READY'), + Type.Literal('UNSUPPORTED_CLIENT'), + Type.Literal('FAILED'), + ]), + playable: Type.Boolean(), + generationId: Type.Optional(UuidSchema), + manifestPath: Type.Optional(Type.String({ pattern: '^/media/' })), + reasonCode: Type.Optional(Type.String()), + pollAfterMs: Type.Optional(Type.Integer({ minimum: 250, maximum: 30000 })), + }, + { additionalProperties: false }, +); + +export const PackageRegistryEntrySchema = Type.Object( + { + mediaItemId: UuidSchema, + state: Type.Union([ + Type.Literal('PREPARING'), + Type.Literal('READY'), + Type.Literal('UNSUPPORTED_CLIENT'), + Type.Literal('FAILED'), + ]), + playable: Type.Boolean(), + generationId: Type.Optional(UuidSchema), + manifestPath: Type.Optional(Type.String({ pattern: '^/media/' })), + reasonCode: Type.Optional(Type.String()), + pollAfterMs: Type.Optional(Type.Integer({ minimum: 250, maximum: 30000 })), + durationSeconds: Type.Optional(Type.Number({ minimum: 0 })), + audioTracks: Type.Optional(Type.Array(AudioTrackSchema)), + subtitleTracks: Type.Optional(Type.Array(SubtitleTrackSchema)), + }, + { additionalProperties: false }, +); + +export const PackageRegistrySchema = Type.Object( + { + version: Type.Literal(1), + updatedAt: Type.String({ + pattern: '^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$', + }), + packages: Type.Array(PackageRegistryEntrySchema), + }, + { additionalProperties: false }, +); + +export type MediaCommand = Static; +export type MediaPreparationResult = Static; +export type PackageRegistryEntry = Static; +export type PackageRegistry = Static; diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts new file mode 100644 index 0000000..9fd8ee9 --- /dev/null +++ b/packages/contracts/src/index.ts @@ -0,0 +1,5 @@ +export * from './admin.js'; +export * from './catalog.js'; +export * from './common.js'; +export * from './events.js'; +export * from './playback.js'; diff --git a/packages/contracts/src/playback.ts b/packages/contracts/src/playback.ts new file mode 100644 index 0000000..b48b6f3 --- /dev/null +++ b/packages/contracts/src/playback.ts @@ -0,0 +1,98 @@ +import { Type, type Static } from '@sinclair/typebox'; +import { DateTimeSchema, UuidSchema } from './common.js'; + +export const CompatibilityClassSchema = Type.Union([ + Type.Literal('COPY'), + Type.Literal('AUDIO_TRANSCODE'), + Type.Literal('VIDEO_TRANSCODE'), + Type.Literal('HOLD_HDR'), + Type.Literal('INVALID'), +]); + +export const PlaybackStateSchema = Type.Union([ + Type.Literal('PREPARING'), + Type.Literal('READY'), + Type.Literal('UNSUPPORTED_CLIENT'), + Type.Literal('FAILED'), +]); + +export const SubtitleDeliverySchema = Type.Union([ + Type.Literal('ASS_JASSUB'), + Type.Literal('WEBVTT'), + Type.Literal('OFF'), +]); + +export const ClientCapabilitiesSchema = Type.Object( + { + mse: Type.Boolean(), + nativeHls: Type.Boolean(), + hlsJs: Type.Boolean(), + assRenderer: Type.Boolean(), + supportedCodecs: Type.Array(Type.String({ maxLength: 128 }), { maxItems: 32 }), + userAgent: Type.Optional(Type.String({ maxLength: 512 })), + }, + { additionalProperties: false }, +); + +export const AudioTrackSchema = Type.Object( + { + id: UuidSchema, + language: Type.String({ minLength: 2, maxLength: 35 }), + label: Type.String({ maxLength: 100 }), + default: Type.Boolean(), + }, + { additionalProperties: false }, +); + +export const SubtitleTrackSchema = Type.Object( + { + id: UuidSchema, + language: Type.String({ minLength: 2, maxLength: 35 }), + label: Type.String({ maxLength: 100 }), + default: Type.Boolean(), + forced: Type.Boolean(), + assUrl: Type.Optional(Type.String()), + vttUrl: Type.Optional(Type.String()), + fontUrls: Type.Array(Type.String()), + }, + { additionalProperties: false }, +); + +export const CreatePlaybackSessionSchema = Type.Object( + { + mediaItemId: UuidSchema, + clientCapabilities: ClientCapabilitiesSchema, + }, + { additionalProperties: false }, +); + +export const PlaybackSessionSchema = Type.Object( + { + id: UuidSchema, + mediaItemId: UuidSchema, + state: PlaybackStateSchema, + manifestUrl: Type.Optional(Type.String()), + generationId: Type.Optional(UuidSchema), + durationSeconds: Type.Optional(Type.Number({ minimum: 0 })), + audioTracks: Type.Optional(Type.Array(AudioTrackSchema)), + subtitleTracks: Type.Optional(Type.Array(SubtitleTrackSchema)), + pollAfterMs: Type.Optional(Type.Integer({ minimum: 250, maximum: 30000 })), + reasonCode: Type.Optional(Type.String()), + expiresAt: DateTimeSchema, + }, + { additionalProperties: false }, +); + +export const PlaybackSessionParamsSchema = Type.Object( + { id: UuidSchema }, + { additionalProperties: false }, +); + +export type CompatibilityClass = Static; +export type PlaybackState = Static; +export type SubtitleDelivery = Static; +export type ClientCapabilities = Static; +export type AudioTrack = Static; +export type SubtitleTrack = Static; +export type CreatePlaybackSession = Static; +export type PlaybackSession = Static; diff --git a/packages/contracts/test/contracts.test.ts b/packages/contracts/test/contracts.test.ts new file mode 100644 index 0000000..2319e0d --- /dev/null +++ b/packages/contracts/test/contracts.test.ts @@ -0,0 +1,38 @@ +import { Value } from '@sinclair/typebox/value'; +import { describe, expect, it } from 'vitest'; +import { CreatePlaybackSessionSchema, MediaCommandSchema } from '../src/index.js'; + +describe('public contracts', () => { + it('accepts a valid browser capability report', () => { + expect( + Value.Check(CreatePlaybackSessionSchema, { + mediaItemId: '00000000-0000-4000-8000-000000000001', + clientCapabilities: { + mse: true, + nativeHls: false, + hlsJs: true, + assRenderer: true, + supportedCodecs: ['avc1.64001f', 'mp4a.40.2'], + }, + }), + ).toBe(true); + }); + + it('keeps worker commands discriminated and closed', () => { + expect( + Value.Check(MediaCommandSchema, { + type: 'archive.scan.requested', + jobId: '00000000-0000-4000-8000-000000000002', + full: false, + unexpected: true, + }), + ).toBe(false); + expect(Value.Check(MediaCommandSchema, { + type: 'cache.generation.accessed', + sessionId: '00000000-0000-4000-8000-000000000001', + generationId: '00000000-0000-4000-8000-000000000002', + accessedAt: '2026-07-14T10:00:00.000Z', + protectedUntil: '2026-07-14T14:00:00.000Z', + })).toBe(true); + }); +}); diff --git a/packages/contracts/tsconfig.json b/packages/contracts/tsconfig.json new file mode 100644 index 0000000..40963af --- /dev/null +++ b/packages/contracts/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist", + "tsBuildInfoFile": "dist/.tsbuildinfo" + }, + "include": ["src/**/*.ts"] +} diff --git a/packages/database/drizzle.config.ts b/packages/database/drizzle.config.ts new file mode 100644 index 0000000..ee1c427 --- /dev/null +++ b/packages/database/drizzle.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'drizzle-kit'; + +if (!process.env.DATABASE_URL) { + throw new Error('DATABASE_URL is required to run Drizzle commands'); +} + +export default defineConfig({ + dialect: 'postgresql', + schema: './src/schema.ts', + out: './migrations', + dbCredentials: { url: process.env.DATABASE_URL }, + strict: true, +}); diff --git a/packages/database/migrations/0000_initial.sql b/packages/database/migrations/0000_initial.sql new file mode 100644 index 0000000..511674e --- /dev/null +++ b/packages/database/migrations/0000_initial.sql @@ -0,0 +1,213 @@ +CREATE TYPE "title_kind" AS ENUM ('MOVIE', 'SERIES'); +CREATE TYPE "media_kind" AS ENUM ('MOVIE', 'EPISODE'); +CREATE TYPE "stream_kind" AS ENUM ('VIDEO', 'AUDIO'); +CREATE TYPE "compatibility_class" AS ENUM ('COPY', 'AUDIO_TRANSCODE', 'VIDEO_TRANSCODE', 'HOLD_HDR', 'INVALID'); +CREATE TYPE "package_state" AS ENUM ('QUEUED', 'BUILDING', 'READY', 'FAILED', 'EVICTED'); +CREATE TYPE "job_state" AS ENUM ('QUEUED', 'RUNNING', 'SUCCEEDED', 'FAILED', 'CANCELLED'); +CREATE TYPE "playback_state" AS ENUM ('PREPARING', 'READY', 'UNSUPPORTED_CLIENT', 'FAILED'); +--> statement-breakpoint +CREATE TABLE "titles" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "slug" varchar(240) NOT NULL, + "kind" "title_kind" NOT NULL, + "name_fa" text, + "name_en" text, + "synopsis_fa" text, + "synopsis_en" text, + "poster_url" text, + "backdrop_url" text, + "release_year" integer, + "tmdb_id" integer, + "published" boolean DEFAULT false NOT NULL, + "published_at" timestamp with time zone, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "media_items" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "title_id" uuid NOT NULL, + "kind" "media_kind" NOT NULL, + "season_number" integer, + "episode_number" integer, + "name_fa" text, + "name_en" text, + "duration_seconds" double precision, + "compatibility" "compatibility_class" DEFAULT 'INVALID' NOT NULL, + "compatibility_reason" text, + "published" boolean DEFAULT false NOT NULL, + "published_at" timestamp with time zone, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "source_files" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "media_item_id" uuid NOT NULL, + "relative_path" text NOT NULL, + "size_bytes" bigint NOT NULL, + "modified_at_ns" bigint NOT NULL, + "matroska_uid" varchar(128), + "head_hash" varchar(128) NOT NULL, + "tail_hash" varchar(128) NOT NULL, + "fingerprint" varchar(128) NOT NULL, + "probe_json" jsonb, + "present" boolean DEFAULT true NOT NULL, + "last_seen_at" timestamp with time zone DEFAULT now() NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "media_streams" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "source_file_id" uuid NOT NULL, + "stream_index" integer NOT NULL, + "kind" "stream_kind" NOT NULL, + "codec" varchar(64) NOT NULL, + "codec_string" varchar(128), + "language" varchar(35), + "label" varchar(200), + "is_default" boolean DEFAULT false NOT NULL, + "channels" integer, + "sample_rate" integer, + "width" integer, + "height" integer, + "frame_rate" varchar(32), + "bit_depth" integer, + "pixel_format" varchar(64), + "color_transfer" varchar(64), + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "subtitle_tracks" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "source_file_id" uuid NOT NULL, + "stream_index" integer NOT NULL, + "codec" varchar(64) NOT NULL, + "source_language" varchar(35), + "normalized_language" varchar(35) NOT NULL, + "label" varchar(200) NOT NULL, + "source_default" boolean DEFAULT false NOT NULL, + "source_forced" boolean DEFAULT false NOT NULL, + "is_default" boolean DEFAULT false NOT NULL, + "is_forced" boolean DEFAULT false NOT NULL, + "ass_path" text, + "webvtt_path" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "font_attachments" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "source_file_id" uuid NOT NULL, + "stream_index" integer NOT NULL, + "sha256" varchar(64) NOT NULL, + "mime_type" varchar(100) NOT NULL, + "original_name" text NOT NULL, + "storage_path" text, + "approved" boolean DEFAULT false NOT NULL, + "size_bytes" bigint NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "media_packages" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "media_item_id" uuid NOT NULL, + "source_fingerprint" varchar(128) NOT NULL, + "profile_version" varchar(64) NOT NULL, + "state" "package_state" DEFAULT 'QUEUED' NOT NULL, + "manifest_path" text, + "size_bytes" bigint DEFAULT 0 NOT NULL, + "cache_resident" boolean DEFAULT false NOT NULL, + "pinned" boolean DEFAULT false NOT NULL, + "last_accessed_at" timestamp with time zone, + "error_code" varchar(100), + "error_detail" text, + "ready_at" timestamp with time zone, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "jobs" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "type" varchar(100) NOT NULL, + "state" "job_state" DEFAULT 'QUEUED' NOT NULL, + "progress" real DEFAULT 0 NOT NULL, + "payload" jsonb DEFAULT '{}'::jsonb NOT NULL, + "result" jsonb, + "error" text, + "attempts" integer DEFAULT 0 NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "admins" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "email" varchar(320) NOT NULL, + "password_hash" text NOT NULL, + "totp_secret_encrypted" text, + "disabled" boolean DEFAULT false NOT NULL, + "last_login_at" timestamp with time zone, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "admin_sessions" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "admin_id" uuid NOT NULL, + "token_hash" varchar(64) NOT NULL, + "csrf_token_hash" varchar(64) NOT NULL, + "expires_at" timestamp with time zone NOT NULL, + "revoked_at" timestamp with time zone, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "playback_sessions" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "media_item_id" uuid NOT NULL, + "generation_id" uuid, + "state" "playback_state" DEFAULT 'PREPARING' NOT NULL, + "capabilities" jsonb NOT NULL, + "reason_code" varchar(100), + "poll_after_ms" integer, + "response_json" jsonb DEFAULT '{}'::jsonb NOT NULL, + "expires_at" timestamp with time zone NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "media_items" ADD CONSTRAINT "media_items_title_id_titles_id_fk" FOREIGN KEY ("title_id") REFERENCES "titles"("id") ON DELETE cascade; +ALTER TABLE "source_files" ADD CONSTRAINT "source_files_media_item_id_media_items_id_fk" FOREIGN KEY ("media_item_id") REFERENCES "media_items"("id") ON DELETE cascade; +ALTER TABLE "media_streams" ADD CONSTRAINT "media_streams_source_file_id_source_files_id_fk" FOREIGN KEY ("source_file_id") REFERENCES "source_files"("id") ON DELETE cascade; +ALTER TABLE "subtitle_tracks" ADD CONSTRAINT "subtitle_tracks_source_file_id_source_files_id_fk" FOREIGN KEY ("source_file_id") REFERENCES "source_files"("id") ON DELETE cascade; +ALTER TABLE "font_attachments" ADD CONSTRAINT "font_attachments_source_file_id_source_files_id_fk" FOREIGN KEY ("source_file_id") REFERENCES "source_files"("id") ON DELETE cascade; +ALTER TABLE "media_packages" ADD CONSTRAINT "media_packages_media_item_id_media_items_id_fk" FOREIGN KEY ("media_item_id") REFERENCES "media_items"("id") ON DELETE cascade; +ALTER TABLE "admin_sessions" ADD CONSTRAINT "admin_sessions_admin_id_admins_id_fk" FOREIGN KEY ("admin_id") REFERENCES "admins"("id") ON DELETE cascade; +ALTER TABLE "playback_sessions" ADD CONSTRAINT "playback_sessions_media_item_id_media_items_id_fk" FOREIGN KEY ("media_item_id") REFERENCES "media_items"("id") ON DELETE cascade; +--> statement-breakpoint +CREATE UNIQUE INDEX "titles_slug_uidx" ON "titles" ("slug"); +CREATE INDEX "titles_published_idx" ON "titles" ("published", "published_at"); +CREATE INDEX "titles_tmdb_idx" ON "titles" ("tmdb_id"); +CREATE INDEX "media_items_title_idx" ON "media_items" ("title_id"); +CREATE UNIQUE INDEX "media_items_episode_uidx" ON "media_items" ("title_id", "season_number", "episode_number"); +CREATE INDEX "media_items_published_idx" ON "media_items" ("published"); +CREATE UNIQUE INDEX "source_files_path_uidx" ON "source_files" ("relative_path"); +CREATE UNIQUE INDEX "source_files_fingerprint_uidx" ON "source_files" ("fingerprint"); +CREATE INDEX "source_files_media_item_idx" ON "source_files" ("media_item_id"); +CREATE UNIQUE INDEX "media_streams_source_index_uidx" ON "media_streams" ("source_file_id", "stream_index"); +CREATE INDEX "media_streams_source_idx" ON "media_streams" ("source_file_id"); +CREATE UNIQUE INDEX "subtitle_tracks_source_index_uidx" ON "subtitle_tracks" ("source_file_id", "stream_index"); +CREATE INDEX "subtitle_tracks_source_idx" ON "subtitle_tracks" ("source_file_id"); +CREATE UNIQUE INDEX "font_attachments_source_index_uidx" ON "font_attachments" ("source_file_id", "stream_index"); +CREATE INDEX "font_attachments_hash_idx" ON "font_attachments" ("sha256"); +CREATE UNIQUE INDEX "media_packages_generation_uidx" ON "media_packages" ("media_item_id", "source_fingerprint", "profile_version"); +CREATE INDEX "media_packages_lru_idx" ON "media_packages" ("cache_resident", "pinned", "last_accessed_at"); +CREATE INDEX "jobs_state_created_idx" ON "jobs" ("state", "created_at"); +CREATE UNIQUE INDEX "admins_email_uidx" ON "admins" ("email"); +CREATE UNIQUE INDEX "admin_sessions_token_uidx" ON "admin_sessions" ("token_hash"); +CREATE INDEX "admin_sessions_admin_idx" ON "admin_sessions" ("admin_id"); +CREATE INDEX "playback_sessions_media_idx" ON "playback_sessions" ("media_item_id"); +CREATE INDEX "playback_sessions_generation_idx" ON "playback_sessions" ("generation_id"); +CREATE INDEX "playback_sessions_expires_idx" ON "playback_sessions" ("expires_at"); diff --git a/packages/database/migrations/0001_playback_generation_external.sql b/packages/database/migrations/0001_playback_generation_external.sql new file mode 100644 index 0000000..0603302 --- /dev/null +++ b/packages/database/migrations/0001_playback_generation_external.sql @@ -0,0 +1,3 @@ +ALTER TABLE "playback_sessions" DROP CONSTRAINT IF EXISTS "playback_sessions_generation_id_media_packages_id_fk"; +--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "playback_sessions_generation_idx" ON "playback_sessions" ("generation_id"); diff --git a/packages/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.json new file mode 100644 index 0000000..114c4b6 --- /dev/null +++ b/packages/database/migrations/meta/_journal.json @@ -0,0 +1,20 @@ +{ + "version": "7", + "dialect": "postgresql", + "entries": [ + { + "idx": 0, + "version": "7", + "when": 1783987200000, + "tag": "0000_initial", + "breakpoints": true + }, + { + "idx": 1, + "version": "7", + "when": 1784016000000, + "tag": "0001_playback_generation_external", + "breakpoints": true + } + ] +} diff --git a/packages/database/package.json b/packages/database/package.json new file mode 100644 index 0000000..1d76d9a --- /dev/null +++ b/packages/database/package.json @@ -0,0 +1,37 @@ +{ + "name": "@easy-stream/database", + "version": "0.1.0", + "private": true, + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + }, + "./schema": { + "types": "./dist/schema.d.ts", + "import": "./dist/schema.js" + } + }, + "files": ["dist", "migrations"], + "scripts": { + "build": "tsc -p tsconfig.json", + "typecheck": "tsc -p ../contracts/tsconfig.json && tsc -p tsconfig.json", + "test": "tsc -p ../contracts/tsconfig.json && vitest run", + "migrate": "drizzle-kit migrate", + "generate": "drizzle-kit generate" + }, + "dependencies": { + "@easy-stream/contracts": "workspace:*", + "@sinclair/typebox": "^0.34.41", + "drizzle-orm": "^0.45.2", + "postgres": "^3.4.7" + }, + "devDependencies": { + "drizzle-kit": "^0.31.10", + "typescript": "^5.9.3", + "vitest": "^3.2.4" + } +} diff --git a/packages/database/src/catalog-sync.ts b/packages/database/src/catalog-sync.ts new file mode 100644 index 0000000..258f3f1 --- /dev/null +++ b/packages/database/src/catalog-sync.ts @@ -0,0 +1,160 @@ +import { CatalogSnapshotSchema, type CatalogSnapshot } from '@easy-stream/contracts'; +import { Value } from '@sinclair/typebox/value'; +import { sql } from 'drizzle-orm'; +import type { Database } from './client.js'; +import { mediaItems, titles } from './schema.js'; + +const UPSERT_BATCH_SIZE = 500; + +export interface PreparedCatalogSync { + scannedAt: Date; + titleRows: Array; + mediaItemRows: Array; +} + +export interface CatalogSyncResult { + titlesSeen: number; + mediaItemsSeen: number; +} + +/** + * Validates and converts the public scan snapshot into database insert rows. Keeping this + * conversion separate also makes the scanner/database boundary testable without PostgreSQL. + */ +export function prepareCatalogSync(snapshot: unknown): PreparedCatalogSync { + if (!Value.Check(CatalogSnapshotSchema, snapshot)) { + const detail = [...Value.Errors(CatalogSnapshotSchema, snapshot)] + .slice(0, 8) + .map((error) => `${error.path || '/'} ${error.message}`) + .join('; '); + throw new Error(`Invalid catalog snapshot: ${detail}`); + } + + const catalog = snapshot as CatalogSnapshot; + const scannedAt = new Date(catalog.generatedAt); + const titleIds = new Set(); + const slugs = new Set(); + const mediaItemIds = new Set(); + const titleRows: PreparedCatalogSync['titleRows'] = []; + const mediaItemRows: PreparedCatalogSync['mediaItemRows'] = []; + + for (const title of catalog.titles) { + assertUnique(titleIds, title.id, 'title ID'); + assertUnique(slugs, title.slug, 'title slug'); + const published = title.mediaItems.some((item) => item.published); + titleRows.push({ + id: title.id, + slug: title.slug, + kind: title.kind, + nameFa: title.name.fa, + nameEn: title.name.en ?? null, + synopsisFa: title.synopsis.fa ?? null, + synopsisEn: title.synopsis.en ?? null, + posterUrl: title.posterUrl ?? null, + backdropUrl: title.backdropUrl ?? null, + releaseYear: title.year ?? null, + published, + publishedAt: published ? scannedAt : null, + createdAt: scannedAt, + updatedAt: scannedAt, + }); + + for (const item of title.mediaItems) { + assertUnique(mediaItemIds, item.id, 'media item ID'); + if ((title.kind === 'MOVIE') !== (item.kind === 'MOVIE')) { + throw new Error(`Catalog media item ${item.id} has kind ${item.kind} under ${title.kind}`); + } + mediaItemRows.push({ + id: item.id, + titleId: title.id, + kind: item.kind, + seasonNumber: item.seasonNumber ?? null, + episodeNumber: item.episodeNumber ?? null, + nameFa: item.name?.fa ?? null, + nameEn: item.name?.en ?? null, + durationSeconds: item.durationSeconds, + compatibility: item.compatibility, + published: item.published, + publishedAt: item.published ? scannedAt : null, + createdAt: scannedAt, + updatedAt: scannedAt, + }); + } + } + + return { scannedAt, titleRows, mediaItemRows }; +} + +/** + * Safely imports scanner-owned catalog facts. Existing names, artwork, TMDB matches and all + * publication fields are intentionally excluded from conflict updates so an archive rescan + * cannot undo an administrator's choices. Rows absent from a snapshot are retained. + */ +export async function syncCatalogSnapshot( + db: Database, + snapshot: unknown, +): Promise { + const prepared = prepareCatalogSync(snapshot); + await db.transaction(async (transaction) => { + // Prevent two worker processes from interleaving catalog snapshots. + await transaction.execute(sql`select pg_advisory_xact_lock(hashtext('easy-stream.catalog-sync'))`); + + for (const batch of batches(prepared.titleRows, UPSERT_BATCH_SIZE)) { + await transaction + .insert(titles) + .values(batch) + .onConflictDoUpdate({ + target: titles.id, + set: { + slug: sql`excluded.slug`, + kind: sql`excluded.kind`, + updatedAt: prepared.scannedAt, + }, + setWhere: sql`${titles.slug} is distinct from excluded.slug or ${titles.kind} is distinct from excluded.kind`, + }); + } + + for (const batch of batches(prepared.mediaItemRows, UPSERT_BATCH_SIZE)) { + await transaction + .insert(mediaItems) + .values(batch) + .onConflictDoUpdate({ + target: mediaItems.id, + set: { + titleId: sql`excluded.title_id`, + kind: sql`excluded.kind`, + seasonNumber: sql`excluded.season_number`, + episodeNumber: sql`excluded.episode_number`, + durationSeconds: sql`excluded.duration_seconds`, + compatibility: sql`excluded.compatibility`, + updatedAt: prepared.scannedAt, + }, + setWhere: sql` + ${mediaItems.titleId} is distinct from excluded.title_id + or ${mediaItems.kind} is distinct from excluded.kind + or ${mediaItems.seasonNumber} is distinct from excluded.season_number + or ${mediaItems.episodeNumber} is distinct from excluded.episode_number + or ${mediaItems.durationSeconds} is distinct from excluded.duration_seconds + or ${mediaItems.compatibility} is distinct from excluded.compatibility + `, + }); + } + }); + return { + titlesSeen: prepared.titleRows.length, + mediaItemsSeen: prepared.mediaItemRows.length, + }; +} + +function assertUnique(values: Set, value: string, label: string): void { + if (values.has(value)) throw new Error(`Catalog contains duplicate ${label}: ${value}`); + values.add(value); +} + +function batches(values: readonly T[], size: number): T[][] { + const result: T[][] = []; + for (let index = 0; index < values.length; index += size) { + result.push(values.slice(index, index + size)); + } + return result; +} diff --git a/packages/database/src/client.ts b/packages/database/src/client.ts new file mode 100644 index 0000000..cec3327 --- /dev/null +++ b/packages/database/src/client.ts @@ -0,0 +1,21 @@ +import { drizzle } from 'drizzle-orm/postgres-js'; +import postgres from 'postgres'; +import * as schema from './schema.js'; + +export function createDatabase(connectionString: string, options?: { max?: number }) { + const client = postgres(connectionString, { + max: options?.max ?? 10, + prepare: false, + transform: { undefined: null }, + }); + + return { + client, + db: drizzle(client, { schema }), + async close(): Promise { + await client.end({ timeout: 5 }); + }, + }; +} + +export type Database = ReturnType['db']; diff --git a/packages/database/src/index.ts b/packages/database/src/index.ts new file mode 100644 index 0000000..805b5aa --- /dev/null +++ b/packages/database/src/index.ts @@ -0,0 +1,4 @@ +export * from './catalog-sync.js'; +export * from './client.js'; +export * from './job-status.js'; +export * from './schema.js'; diff --git a/packages/database/src/job-status.ts b/packages/database/src/job-status.ts new file mode 100644 index 0000000..fc284ee --- /dev/null +++ b/packages/database/src/job-status.ts @@ -0,0 +1,56 @@ +import { and, eq, inArray, sql } from 'drizzle-orm'; +import type { Database } from './client.js'; +import { jobs } from './schema.js'; + +export async function markArchiveScanRunning(db: Database, jobId: string): Promise { + const [updated] = await db.update(jobs).set({ + state: 'RUNNING', + progress: 0, + error: null, + attempts: sql`${jobs.attempts} + 1`, + updatedAt: new Date(), + }).where(and( + eq(jobs.id, jobId), + eq(jobs.type, 'ARCHIVE_SCAN'), + // BullMQ may start a retry immediately after its failed event; accept either side of that + // transition so automatic retries can move the same logical job back to RUNNING. + inArray(jobs.state, ['QUEUED', 'RUNNING', 'FAILED']), + )).returning({ id: jobs.id }); + return updated !== undefined; +} + +export async function markArchiveScanSucceeded( + db: Database, + jobId: string, + result: Record, +): Promise { + const [updated] = await db.update(jobs).set({ + state: 'SUCCEEDED', + progress: 1, + result, + error: null, + updatedAt: new Date(), + }).where(and( + eq(jobs.id, jobId), + eq(jobs.type, 'ARCHIVE_SCAN'), + eq(jobs.state, 'RUNNING'), + )).returning({ id: jobs.id }); + return updated !== undefined; +} + +export async function markArchiveScanFailed( + db: Database, + jobId: string, + error: string, +): Promise { + const [updated] = await db.update(jobs).set({ + state: 'FAILED', + error: error.slice(0, 16_000), + updatedAt: new Date(), + }).where(and( + eq(jobs.id, jobId), + eq(jobs.type, 'ARCHIVE_SCAN'), + inArray(jobs.state, ['QUEUED', 'RUNNING']), + )).returning({ id: jobs.id }); + return updated !== undefined; +} diff --git a/packages/database/src/schema.ts b/packages/database/src/schema.ts new file mode 100644 index 0000000..498b236 --- /dev/null +++ b/packages/database/src/schema.ts @@ -0,0 +1,324 @@ +import { + bigint, + boolean, + doublePrecision, + index, + integer, + jsonb, + pgEnum, + pgTable, + real, + text, + timestamp, + uniqueIndex, + uuid, + varchar, +} from 'drizzle-orm/pg-core'; + +export const titleKind = pgEnum('title_kind', ['MOVIE', 'SERIES']); +export const mediaKind = pgEnum('media_kind', ['MOVIE', 'EPISODE']); +export const streamKind = pgEnum('stream_kind', ['VIDEO', 'AUDIO']); +export const compatibilityClass = pgEnum('compatibility_class', [ + 'COPY', + 'AUDIO_TRANSCODE', + 'VIDEO_TRANSCODE', + 'HOLD_HDR', + 'INVALID', +]); +export const packageState = pgEnum('package_state', [ + 'QUEUED', + 'BUILDING', + 'READY', + 'FAILED', + 'EVICTED', +]); +export const jobState = pgEnum('job_state', [ + 'QUEUED', + 'RUNNING', + 'SUCCEEDED', + 'FAILED', + 'CANCELLED', +]); +export const playbackState = pgEnum('playback_state', [ + 'PREPARING', + 'READY', + 'UNSUPPORTED_CLIENT', + 'FAILED', +]); + +const timestamps = { + createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(), +}; + +export const titles = pgTable( + 'titles', + { + id: uuid('id').primaryKey().defaultRandom(), + slug: varchar('slug', { length: 240 }).notNull(), + kind: titleKind('kind').notNull(), + nameFa: text('name_fa'), + nameEn: text('name_en'), + synopsisFa: text('synopsis_fa'), + synopsisEn: text('synopsis_en'), + posterUrl: text('poster_url'), + backdropUrl: text('backdrop_url'), + releaseYear: integer('release_year'), + tmdbId: integer('tmdb_id'), + published: boolean('published').notNull().default(false), + publishedAt: timestamp('published_at', { withTimezone: true }), + ...timestamps, + }, + (table) => [ + uniqueIndex('titles_slug_uidx').on(table.slug), + index('titles_published_idx').on(table.published, table.publishedAt), + index('titles_tmdb_idx').on(table.tmdbId), + ], +); + +export const mediaItems = pgTable( + 'media_items', + { + id: uuid('id').primaryKey().defaultRandom(), + titleId: uuid('title_id') + .notNull() + .references(() => titles.id, { onDelete: 'cascade' }), + kind: mediaKind('kind').notNull(), + seasonNumber: integer('season_number'), + episodeNumber: integer('episode_number'), + nameFa: text('name_fa'), + nameEn: text('name_en'), + durationSeconds: doublePrecision('duration_seconds'), + compatibility: compatibilityClass('compatibility').notNull().default('INVALID'), + compatibilityReason: text('compatibility_reason'), + published: boolean('published').notNull().default(false), + publishedAt: timestamp('published_at', { withTimezone: true }), + ...timestamps, + }, + (table) => [ + index('media_items_title_idx').on(table.titleId), + uniqueIndex('media_items_episode_uidx').on( + table.titleId, + table.seasonNumber, + table.episodeNumber, + ), + index('media_items_published_idx').on(table.published), + ], +); + +export const sourceFiles = pgTable( + 'source_files', + { + id: uuid('id').primaryKey().defaultRandom(), + mediaItemId: uuid('media_item_id') + .notNull() + .references(() => mediaItems.id, { onDelete: 'cascade' }), + relativePath: text('relative_path').notNull(), + sizeBytes: bigint('size_bytes', { mode: 'number' }).notNull(), + modifiedAtNs: bigint('modified_at_ns', { mode: 'bigint' }).notNull(), + matroskaUid: varchar('matroska_uid', { length: 128 }), + headHash: varchar('head_hash', { length: 128 }).notNull(), + tailHash: varchar('tail_hash', { length: 128 }).notNull(), + fingerprint: varchar('fingerprint', { length: 128 }).notNull(), + probeJson: jsonb('probe_json').$type>(), + present: boolean('present').notNull().default(true), + lastSeenAt: timestamp('last_seen_at', { withTimezone: true }).notNull().defaultNow(), + ...timestamps, + }, + (table) => [ + uniqueIndex('source_files_path_uidx').on(table.relativePath), + uniqueIndex('source_files_fingerprint_uidx').on(table.fingerprint), + index('source_files_media_item_idx').on(table.mediaItemId), + ], +); + +export const mediaStreams = pgTable( + 'media_streams', + { + id: uuid('id').primaryKey().defaultRandom(), + sourceFileId: uuid('source_file_id') + .notNull() + .references(() => sourceFiles.id, { onDelete: 'cascade' }), + streamIndex: integer('stream_index').notNull(), + kind: streamKind('kind').notNull(), + codec: varchar('codec', { length: 64 }).notNull(), + codecString: varchar('codec_string', { length: 128 }), + language: varchar('language', { length: 35 }), + label: varchar('label', { length: 200 }), + isDefault: boolean('is_default').notNull().default(false), + channels: integer('channels'), + sampleRate: integer('sample_rate'), + width: integer('width'), + height: integer('height'), + frameRate: varchar('frame_rate', { length: 32 }), + bitDepth: integer('bit_depth'), + pixelFormat: varchar('pixel_format', { length: 64 }), + colorTransfer: varchar('color_transfer', { length: 64 }), + ...timestamps, + }, + (table) => [ + uniqueIndex('media_streams_source_index_uidx').on(table.sourceFileId, table.streamIndex), + index('media_streams_source_idx').on(table.sourceFileId), + ], +); + +export const subtitleTracks = pgTable( + 'subtitle_tracks', + { + id: uuid('id').primaryKey().defaultRandom(), + sourceFileId: uuid('source_file_id') + .notNull() + .references(() => sourceFiles.id, { onDelete: 'cascade' }), + streamIndex: integer('stream_index').notNull(), + codec: varchar('codec', { length: 64 }).notNull(), + sourceLanguage: varchar('source_language', { length: 35 }), + normalizedLanguage: varchar('normalized_language', { length: 35 }).notNull(), + label: varchar('label', { length: 200 }).notNull(), + sourceDefault: boolean('source_default').notNull().default(false), + sourceForced: boolean('source_forced').notNull().default(false), + isDefault: boolean('is_default').notNull().default(false), + isForced: boolean('is_forced').notNull().default(false), + assPath: text('ass_path'), + webvttPath: text('webvtt_path'), + ...timestamps, + }, + (table) => [ + uniqueIndex('subtitle_tracks_source_index_uidx').on(table.sourceFileId, table.streamIndex), + index('subtitle_tracks_source_idx').on(table.sourceFileId), + ], +); + +export const fontAttachments = pgTable( + 'font_attachments', + { + id: uuid('id').primaryKey().defaultRandom(), + sourceFileId: uuid('source_file_id') + .notNull() + .references(() => sourceFiles.id, { onDelete: 'cascade' }), + streamIndex: integer('stream_index').notNull(), + sha256: varchar('sha256', { length: 64 }).notNull(), + mimeType: varchar('mime_type', { length: 100 }).notNull(), + originalName: text('original_name').notNull(), + storagePath: text('storage_path'), + approved: boolean('approved').notNull().default(false), + sizeBytes: bigint('size_bytes', { mode: 'number' }).notNull(), + ...timestamps, + }, + (table) => [ + uniqueIndex('font_attachments_source_index_uidx').on(table.sourceFileId, table.streamIndex), + index('font_attachments_hash_idx').on(table.sha256), + ], +); + +export const mediaPackages = pgTable( + 'media_packages', + { + id: uuid('id').primaryKey().defaultRandom(), + mediaItemId: uuid('media_item_id') + .notNull() + .references(() => mediaItems.id, { onDelete: 'cascade' }), + sourceFingerprint: varchar('source_fingerprint', { length: 128 }).notNull(), + profileVersion: varchar('profile_version', { length: 64 }).notNull(), + state: packageState('state').notNull().default('QUEUED'), + manifestPath: text('manifest_path'), + sizeBytes: bigint('size_bytes', { mode: 'number' }).notNull().default(0), + cacheResident: boolean('cache_resident').notNull().default(false), + pinned: boolean('pinned').notNull().default(false), + lastAccessedAt: timestamp('last_accessed_at', { withTimezone: true }), + errorCode: varchar('error_code', { length: 100 }), + errorDetail: text('error_detail'), + readyAt: timestamp('ready_at', { withTimezone: true }), + ...timestamps, + }, + (table) => [ + uniqueIndex('media_packages_generation_uidx').on( + table.mediaItemId, + table.sourceFingerprint, + table.profileVersion, + ), + index('media_packages_lru_idx').on(table.cacheResident, table.pinned, table.lastAccessedAt), + ], +); + +export const jobs = pgTable( + 'jobs', + { + id: uuid('id').primaryKey().defaultRandom(), + type: varchar('type', { length: 100 }).notNull(), + state: jobState('state').notNull().default('QUEUED'), + progress: real('progress').notNull().default(0), + payload: jsonb('payload').$type>().notNull().default({}), + result: jsonb('result').$type>(), + error: text('error'), + attempts: integer('attempts').notNull().default(0), + ...timestamps, + }, + (table) => [index('jobs_state_created_idx').on(table.state, table.createdAt)], +); + +export const admins = pgTable( + 'admins', + { + id: uuid('id').primaryKey().defaultRandom(), + email: varchar('email', { length: 320 }).notNull(), + passwordHash: text('password_hash').notNull(), + totpSecretEncrypted: text('totp_secret_encrypted'), + disabled: boolean('disabled').notNull().default(false), + lastLoginAt: timestamp('last_login_at', { withTimezone: true }), + ...timestamps, + }, + (table) => [uniqueIndex('admins_email_uidx').on(table.email)], +); + +export const adminSessions = pgTable( + 'admin_sessions', + { + id: uuid('id').primaryKey().defaultRandom(), + adminId: uuid('admin_id') + .notNull() + .references(() => admins.id, { onDelete: 'cascade' }), + tokenHash: varchar('token_hash', { length: 64 }).notNull(), + csrfTokenHash: varchar('csrf_token_hash', { length: 64 }).notNull(), + expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(), + revokedAt: timestamp('revoked_at', { withTimezone: true }), + createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), + }, + (table) => [ + uniqueIndex('admin_sessions_token_uidx').on(table.tokenHash), + index('admin_sessions_admin_idx').on(table.adminId), + ], +); + +export const playbackSessions = pgTable( + 'playback_sessions', + { + id: uuid('id').primaryKey().defaultRandom(), + mediaItemId: uuid('media_item_id') + .notNull() + .references(() => mediaItems.id, { onDelete: 'cascade' }), + // Packaging generation IDs are deterministic UUIDs owned by the media worker. They are + // deliberately not media_packages.id, so this column must not reference that primary key. + generationId: uuid('generation_id'), + state: playbackState('state').notNull().default('PREPARING'), + capabilities: jsonb('capabilities').$type>().notNull(), + reasonCode: varchar('reason_code', { length: 100 }), + pollAfterMs: integer('poll_after_ms'), + responseJson: jsonb('response_json').$type>().notNull().default({}), + expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(), + createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(), + }, + (table) => [ + index('playback_sessions_media_idx').on(table.mediaItemId), + index('playback_sessions_generation_idx').on(table.generationId), + index('playback_sessions_expires_idx').on(table.expiresAt), + ], +); + +export type TitleRow = typeof titles.$inferSelect; +export type MediaItemRow = typeof mediaItems.$inferSelect; +export type SourceFileRow = typeof sourceFiles.$inferSelect; +export type MediaPackageRow = typeof mediaPackages.$inferSelect; +export type AdminRow = typeof admins.$inferSelect; +export type AdminSessionRow = typeof adminSessions.$inferSelect; +export type PlaybackSessionRow = typeof playbackSessions.$inferSelect; diff --git a/packages/database/test/catalog-sync.test.ts b/packages/database/test/catalog-sync.test.ts new file mode 100644 index 0000000..d2eaddd --- /dev/null +++ b/packages/database/test/catalog-sync.test.ts @@ -0,0 +1,100 @@ +import type { CatalogSnapshot } from '@easy-stream/contracts'; +import { getTableConfig } from 'drizzle-orm/pg-core'; +import { describe, expect, it } from 'vitest'; +import { + prepareCatalogSync, + syncCatalogSnapshot, + type Database, +} from '../src/index.js'; +import { mediaItems, playbackSessions, titles } from '../src/schema.js'; + +const snapshot: CatalogSnapshot = { + version: 1, + generatedAt: '2026-07-14T10:00:00.000Z', + titles: [{ + id: '11111111-1111-5111-8111-111111111111', + slug: 'sample-film', + kind: 'MOVIE', + name: { fa: 'فیلم نمونه', en: 'Sample Film' }, + playable: true, + resumeMediaItemId: '22222222-2222-5222-8222-222222222222', + synopsis: {}, + mediaItems: [{ + id: '22222222-2222-5222-8222-222222222222', + kind: 'MOVIE', + durationSeconds: 90, + compatibility: 'COPY', + published: true, + }], + updatedAt: '2026-07-14T10:00:00.000Z', + }], +}; + +describe('catalog snapshot synchronization', () => { + it('validates and maps deterministic scanner IDs and initial publication', () => { + const prepared = prepareCatalogSync(snapshot); + expect(prepared.titleRows).toMatchObject([{ + id: snapshot.titles[0]?.id, + nameFa: 'فیلم نمونه', + nameEn: 'Sample Film', + published: true, + }]); + expect(prepared.mediaItemRows).toMatchObject([{ + id: snapshot.titles[0]?.mediaItems[0]?.id, + titleId: snapshot.titles[0]?.id, + compatibility: 'COPY', + published: true, + }]); + }); + + it('rejects ambiguous duplicate IDs before opening a transaction', () => { + const duplicate = structuredClone(snapshot); + duplicate.titles.push({ ...structuredClone(duplicate.titles[0]!), slug: 'another-slug' }); + expect(() => prepareCatalogSync(duplicate)).toThrow(/duplicate title ID/u); + }); + + it('only updates scanner-owned fields on conflicts', async () => { + const conflicts: Array<{ table: unknown; set: Record }> = []; + const transaction = { + async execute() {}, + insert(table: unknown) { + return { + values() { + return { + async onConflictDoUpdate(config: { set: Record }) { + conflicts.push({ table, set: config.set }); + }, + }; + }, + }; + }, + }; + const database = { + async transaction(action: (value: typeof transaction) => Promise): Promise { + return action(transaction); + }, + } as unknown as Database; + + await syncCatalogSnapshot(database, snapshot); + + expect(Object.keys(conflicts.find((entry) => entry.table === titles)!.set).sort()) + .toEqual(['kind', 'slug', 'updatedAt']); + expect(Object.keys(conflicts.find((entry) => entry.table === mediaItems)!.set).sort()) + .toEqual([ + 'compatibility', + 'durationSeconds', + 'episodeNumber', + 'kind', + 'seasonNumber', + 'titleId', + 'updatedAt', + ]); + }); + + it('does not constrain a worker generation UUID to media_packages.id', () => { + const configuration = getTableConfig(playbackSessions); + const generationForeignKey = configuration.foreignKeys.some((foreignKey) => + foreignKey.reference().columns.includes(playbackSessions.generationId)); + expect(generationForeignKey).toBe(false); + }); +}); diff --git a/packages/database/tsconfig.json b/packages/database/tsconfig.json new file mode 100644 index 0000000..1ef9e64 --- /dev/null +++ b/packages/database/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist", + "tsBuildInfoFile": "dist/.tsbuildinfo", + "paths": { + "@easy-stream/contracts": ["packages/contracts/dist/index.d.ts"] + } + }, + "include": ["src/**/*.ts"] +} diff --git a/packages/media/package.json b/packages/media/package.json new file mode 100644 index 0000000..f63bb55 --- /dev/null +++ b/packages/media/package.json @@ -0,0 +1,23 @@ +{ + "name": "@easy-stream/media", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "scripts": { + "build": "tsc -p tsconfig.json", + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest run", + "clean": "rm -rf dist" + }, + "devDependencies": { + "@types/node": "^24.10.0", + "typescript": "^5.9.3", + "vitest": "^3.2.4" + } +} diff --git a/packages/media/src/cache.ts b/packages/media/src/cache.ts new file mode 100644 index 0000000..b694a31 --- /dev/null +++ b/packages/media/src/cache.ts @@ -0,0 +1,286 @@ +import { randomUUID } from 'node:crypto'; +import { lstat, opendir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { assertWritableDestination, assertWritableRoot, isPathInside, UnsafePathError } from './paths.js'; + +const METADATA = '.cache-entry.json'; +let lifecycleTail: Promise = Promise.resolve(); + +async function serializeLifecycle(operation: () => Promise): Promise { + const previous = lifecycleTail; + let release!: () => void; + lifecycleTail = new Promise((resolve) => { release = resolve; }); + await previous; + try { + return await operation(); + } finally { + release(); + } +} + +export interface CacheEntryMetadata { + version: 1; + key: string; + bytes: number; + lastAccessedAt: string; + /** Do not evict before the latest playback grant expires. */ + protectedUntil?: string; + active: boolean; + building: boolean; + pinned: boolean; +} + +async function readCacheMetadata(directory: string): Promise { + const destination = path.join(directory, METADATA); + const details = await lstat(destination); + if (details.isSymbolicLink() || !details.isFile()) { + throw new UnsafePathError(`Cache metadata is not a regular file: ${destination}`); + } + return JSON.parse(await readFile(destination, 'utf8')) as CacheEntryMetadata; +} + +async function assertSafeDeletion(root: string, directory: string): Promise { + await assertWritableRoot(root); + await assertWritableDestination(root, directory); + const details = await lstat(directory); + if (details.isSymbolicLink() || !details.isDirectory()) { + throw new UnsafePathError(`Cache deletion target is not a regular directory: ${directory}`); + } + const [canonicalRoot, canonicalDirectory] = await Promise.all([realpath(root), realpath(directory)]); + if (!isPathInside(canonicalRoot, canonicalDirectory) || canonicalDirectory === canonicalRoot) { + throw new UnsafePathError(`Refusing unsafe cache deletion: ${directory}`); + } +} + +async function directorySize(directory: string): Promise { + let total = 0; + const handle = await opendir(directory); + for await (const entry of handle) { + const candidate = path.join(directory, entry.name); + const details = await lstat(candidate); + if (details.isSymbolicLink()) throw new Error(`Symlink found in media cache: ${candidate}`); + if (details.isDirectory()) total += await directorySize(candidate); + // Generation-local font hardlinks do not consume additional blocks while the global + // content-addressed store owns another link. Cross-device copy fallbacks have nlink=1. + else if (details.isFile()) total += details.nlink > 1 ? 0 : details.size; + } + return total; +} + +export async function writeCacheMetadata( + cacheRoot: string, + entryDirectory: string, + metadata: Omit & { bytes?: number }, +): Promise { + const directory = await assertWritableDestination(cacheRoot, entryDirectory); + const details = await stat(directory); + if (!details.isDirectory()) throw new Error('Cache entry is not a directory'); + const value: CacheEntryMetadata = { + version: 1, + ...metadata, + bytes: metadata.bytes ?? await directorySize(directory), + }; + const destination = path.join(directory, METADATA); + try { + const existing = await lstat(destination); + if (existing.isSymbolicLink() || !existing.isFile()) { + throw new UnsafePathError(`Cache metadata is not a regular file: ${destination}`); + } + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } + const temporary = `${destination}.${randomUUID()}.tmp`; + try { + await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o640, flag: 'wx' }); + await rename(temporary, destination); + } finally { + await rm(temporary, { force: true }); + } + return value; +} + +export async function touchCacheEntry(cacheRoot: string, entryDirectory: string): Promise { + const directory = await assertWritableDestination(cacheRoot, entryDirectory); + const value = await readCacheMetadata(directory); + await writeCacheMetadata(cacheRoot, directory, { ...value, lastAccessedAt: new Date().toISOString() }); +} + +export interface CacheTouchOptions { + accessedAt?: string; + protectedUntil?: string; +} + +/** Updates one cache generation without allowing a caller-controlled filesystem path. */ +export async function touchCacheGeneration( + cacheRoot: string, + generation: string, + options: CacheTouchOptions = {}, +): Promise { + return await serializeLifecycle(async () => await touchCacheGenerationUnlocked(cacheRoot, generation, options)); +} + +async function touchCacheGenerationUnlocked( + cacheRoot: string, + generation: string, + options: CacheTouchOptions, +): Promise { + if (!/^[a-z0-9][a-z0-9._-]{7,127}$/u.test(generation)) throw new Error('Invalid generation identifier'); + const accessedAt = options.accessedAt ?? new Date().toISOString(); + if (!Number.isFinite(Date.parse(accessedAt))) throw new Error('Invalid cache access timestamp'); + if (options.protectedUntil !== undefined && !Number.isFinite(Date.parse(options.protectedUntil))) { + throw new Error('Invalid cache protection timestamp'); + } + await assertWritableRoot(cacheRoot); + const generationsRoot = path.join(path.resolve(cacheRoot), 'generations'); + const directory = await assertWritableDestination(generationsRoot, path.join(generationsRoot, generation)); + let value: CacheEntryMetadata; + try { + const details = await lstat(directory); + if (details.isSymbolicLink() || !details.isDirectory()) throw new Error('Cache generation is not a regular directory'); + value = await readCacheMetadata(directory); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false; + throw error; + } + if (value.version !== 1 || value.key !== generation) throw new Error('Cache generation metadata does not match request'); + const existingAccess = Date.parse(value.lastAccessedAt); + const requestedAccess = Date.parse(accessedAt); + const existingProtection = Date.parse(value.protectedUntil ?? ''); + const requestedProtection = Date.parse(options.protectedUntil ?? ''); + await writeCacheMetadata(generationsRoot, directory, { + ...value, + lastAccessedAt: new Date(Math.max( + Number.isFinite(existingAccess) ? existingAccess : 0, + requestedAccess, + )).toISOString(), + ...(Number.isFinite(existingProtection) || Number.isFinite(requestedProtection) + ? { + protectedUntil: new Date(Math.max( + Number.isFinite(existingProtection) ? existingProtection : 0, + Number.isFinite(requestedProtection) ? requestedProtection : 0, + )).toISOString(), + } + : {}), + }); + return true; +} + +export interface EvictionOptions { + capacityBytes: number; + highWatermark?: number; + lowWatermark?: number; + protectedKeys?: ReadonlySet; + /** Bytes owned by the cache but stored outside the per-generation directories. */ + overheadBytes?: number; + now?: Date; + /** Grace window for newly built/touched entries while access events propagate. */ + minimumRetentionMs?: number; + dryRun?: boolean; +} + +export interface EvictionResult { + beforeBytes: number; + afterBytes: number; + evicted: string[]; +} + +export async function evictCacheGeneration(cacheRoot: string, generation: string): Promise { + return await serializeLifecycle(async () => await evictCacheGenerationUnlocked(cacheRoot, generation)); +} + +async function evictCacheGenerationUnlocked(cacheRoot: string, generation: string): Promise { + if (!/^[a-z0-9][a-z0-9._-]{7,127}$/u.test(generation)) throw new Error('Invalid generation identifier'); + await assertWritableRoot(cacheRoot); + const generationsRoot = path.join(path.resolve(cacheRoot), 'generations'); + const directory = await assertWritableDestination(generationsRoot, path.join(generationsRoot, generation)); + let metadata: CacheEntryMetadata; + try { + const details = await lstat(directory); + if (details.isSymbolicLink() || !details.isDirectory()) throw new Error('Cache generation is not a regular directory'); + metadata = await readCacheMetadata(directory); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false; + throw error; + } + if (metadata.version !== 1 || metadata.key !== generation) throw new Error('Cache generation metadata does not match request'); + if (metadata.active || metadata.building) throw new Error(`Cache generation is active: ${generation}`); + if (metadata.pinned) throw new Error(`Cache generation is pinned: ${generation}`); + if (isTimeProtected(metadata, Date.now())) throw new Error(`Cache generation has an active playback lease: ${generation}`); + await assertSafeDeletion(generationsRoot, directory); + await rm(directory, { recursive: true, force: false }); + return true; +} + +export async function evictCache(cacheRoot: string, options: EvictionOptions): Promise { + return await serializeLifecycle(async () => await evictCacheUnlocked(cacheRoot, options)); +} + +async function evictCacheUnlocked(cacheRoot: string, options: EvictionOptions): Promise { + const root = path.resolve(cacheRoot); + const high = options.highWatermark ?? 0.85; + const low = options.lowWatermark ?? 0.75; + if (!(options.capacityBytes > 0) || !(low >= 0 && low < high && high <= 1)) { + throw new RangeError('Invalid cache capacity or watermarks'); + } + const entries: Array<{ directory: string; metadata: CacheEntryMetadata }> = []; + const overheadBytes = options.overheadBytes ?? 0; + if (!Number.isFinite(overheadBytes) || overheadBytes < 0) throw new RangeError('Invalid cache overhead'); + const minimumRetentionMs = options.minimumRetentionMs ?? 0; + if (!Number.isFinite(minimumRetentionMs) || minimumRetentionMs < 0) { + throw new RangeError('Invalid cache retention window'); + } + const now = (options.now ?? new Date()).getTime(); + let beforeBytes = overheadBytes; + await assertWritableRoot(root); + try { + await lstat(root); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + return { beforeBytes, afterBytes: beforeBytes, evicted: [] }; + } + throw error; + } + const handle = await opendir(root); + for await (const entry of handle) { + if (entry.isSymbolicLink()) throw new UnsafePathError(`Symlink found in cache generations: ${path.join(root, entry.name)}`); + if (!entry.isDirectory()) continue; + const directory = path.join(root, entry.name); + try { + const metadata = await readCacheMetadata(directory); + if (metadata.version !== 1 || metadata.key !== entry.name + || !Number.isFinite(metadata.bytes) || metadata.bytes < 0 + || !Number.isFinite(Date.parse(metadata.lastAccessedAt))) continue; + entries.push({ directory, metadata }); + beforeBytes += metadata.bytes; + } catch (error) { + if (error instanceof UnsafePathError) throw error; + // Incomplete/unmanaged directories are never deleted by the LRU. + } + } + if (beforeBytes <= options.capacityBytes * high) return { beforeBytes, afterBytes: beforeBytes, evicted: [] }; + entries.sort((left, right) => Date.parse(left.metadata.lastAccessedAt) - Date.parse(right.metadata.lastAccessedAt)); + const target = options.capacityBytes * low; + let afterBytes = beforeBytes; + const evicted: string[] = []; + for (const entry of entries) { + if (afterBytes <= target) break; + const protectedEntry = entry.metadata.active || entry.metadata.building || entry.metadata.pinned + || isTimeProtected(entry.metadata, now) + || Date.parse(entry.metadata.lastAccessedAt) > now - minimumRetentionMs + || options.protectedKeys?.has(entry.metadata.key) === true; + if (protectedEntry) continue; + await assertSafeDeletion(root, entry.directory); + if (options.dryRun !== true) await rm(entry.directory, { recursive: true, force: false }); + afterBytes -= entry.metadata.bytes; + evicted.push(entry.metadata.key); + } + return { beforeBytes, afterBytes, evicted }; +} + +function isTimeProtected(metadata: CacheEntryMetadata, now: number): boolean { + if (metadata.protectedUntil === undefined) return false; + const protectedUntil = Date.parse(metadata.protectedUntil); + // Corrupt protection metadata fails closed: an operator can inspect/fix it rather than + // evicting files that might still be in use. + return !Number.isFinite(protectedUntil) || protectedUntil > now; +} diff --git a/packages/media/src/classify.ts b/packages/media/src/classify.ts new file mode 100644 index 0000000..50d6282 --- /dev/null +++ b/packages/media/src/classify.ts @@ -0,0 +1,103 @@ +import { normalizeStreamLanguage } from './language.js'; +import type { Classification, MediaProbe, NormalizedTrack, ProbeStream } from './types.js'; + +function isHdr(stream: ProbeStream): boolean { + const transfer = stream.color_transfer?.toLowerCase(); + const primaries = stream.color_primaries?.toLowerCase(); + if (transfer === 'smpte2084' || transfer === 'arib-std-b67' || primaries === 'bt2020') return true; + return (stream.side_data_list ?? []).some((data) => { + const encoded = JSON.stringify(data).toLowerCase(); + return encoded.includes('dolby vision') || encoded.includes('hdr10+') || encoded.includes('mastering display'); + }); +} + +function isCopySafeVideo(stream: ProbeStream): boolean { + const depth = Number.parseInt(stream.bits_per_raw_sample ?? '8', 10); + const profile = stream.profile?.toLowerCase() ?? ''; + return stream.codec_name === 'h264' + && ['yuv420p', 'yuvj420p'].includes(stream.pix_fmt ?? '') + && (Number.isNaN(depth) || depth <= 8) + && !profile.includes('high 10') + && !profile.includes('high 4:2') + && (stream.field_order === undefined || ['progressive', 'unknown'].includes(stream.field_order)); +} + +function isCopySafeAudio(stream: ProbeStream): boolean { + const profile = stream.profile?.toLowerCase(); + return stream.codec_name === 'aac' + && (profile === undefined || profile === 'lc' || profile.includes('low complexity')) + && (stream.channels ?? 2) <= 6; +} + +export interface ClassificationOptions { + maxCopySegmentDuration?: number; + measuredMaxGopSeconds?: number; +} + +export function classifyMedia(probe: MediaProbe, options: ClassificationOptions = {}): Classification { + const videos = probe.streams.filter((stream) => stream.codec_type === 'video' && stream.disposition?.attached_pic !== 1); + const audios = probe.streams.filter((stream) => stream.codec_type === 'audio'); + const reasons: string[] = []; + const duration = Number.parseFloat(probe.format.duration ?? 'NaN'); + if (videos.length === 0) reasons.push('NO_VIDEO'); + if (audios.length === 0) reasons.push('NO_AUDIO'); + if (!Number.isFinite(duration) || duration <= 0) reasons.push('INVALID_DURATION'); + if ((probe.format.probe_score ?? 100) < 25) reasons.push('LOW_PROBE_SCORE'); + const video = videos[0]; + if (video === undefined || audios.length === 0 || reasons.length > 0) { + return { class: 'INVALID', reasons, audioStreamIndexes: audios.map((stream) => stream.index) }; + } + if (isHdr(video)) { + return { class: 'HOLD_HDR', reasons: ['HDR_UNSUPPORTED_V1'], videoStreamIndex: video.index, audioStreamIndexes: audios.map((stream) => stream.index) }; + } + if (!isCopySafeVideo(video)) { + return { + class: 'VIDEO_TRANSCODE', + reasons: [`VIDEO_CODEC_UNSUPPORTED:${video.codec_name ?? 'unknown'}`, `VIDEO_PIXEL_FORMAT:${video.pix_fmt ?? 'unknown'}`], + videoStreamIndex: video.index, + audioStreamIndexes: audios.map((stream) => stream.index), + }; + } + const maxGop = options.measuredMaxGopSeconds; + if (maxGop !== undefined && maxGop > (options.maxCopySegmentDuration ?? 18)) { + return { + class: 'VIDEO_TRANSCODE', + reasons: [`GOP_TOO_LONG:${maxGop.toFixed(3)}`], + videoStreamIndex: video.index, + audioStreamIndexes: audios.map((stream) => stream.index), + }; + } + const unsupportedAudio = audios.filter((stream) => !isCopySafeAudio(stream)); + if (unsupportedAudio.length > 0) { + return { + class: 'AUDIO_TRANSCODE', + reasons: unsupportedAudio.map((stream) => `AUDIO_CODEC_UNSUPPORTED:${stream.index}:${stream.codec_name ?? 'unknown'}`), + videoStreamIndex: video.index, + audioStreamIndexes: audios.map((stream) => stream.index), + }; + } + return { + class: 'COPY', + reasons: [], + videoStreamIndex: video.index, + audioStreamIndexes: audios.map((stream) => stream.index), + }; +} + +export function normalizeTracks(probe: MediaProbe): NormalizedTrack[] { + return probe.streams.flatMap((stream): NormalizedTrack[] => { + if (!['video', 'audio', 'subtitle', 'attachment'].includes(stream.codec_type ?? '')) return []; + const type = stream.codec_type as NormalizedTrack['type']; + const language = normalizeStreamLanguage(stream); + return [{ + index: stream.index, + type, + codec: stream.codec_name ?? 'unknown', + language, + ...(stream.tags?.title === undefined ? {} : { label: stream.tags.title }), + default: type === 'subtitle' ? language === 'fa' : stream.disposition?.default === 1, + // Embedded flags are advisory; full-track ASS marked forced is common in this archive. + forced: false, + }]; + }); +} diff --git a/packages/media/src/encode.ts b/packages/media/src/encode.ts new file mode 100644 index 0000000..a7a8323 --- /dev/null +++ b/packages/media/src/encode.ts @@ -0,0 +1,194 @@ +import { randomUUID } from 'node:crypto'; +import { rename, rm, stat, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { probeMedia } from './ffprobe.js'; +import { fingerprintSource } from './fingerprint.js'; +import { assessFfmpegWarnings, buildMasterPlaylist, validateMediaPlaylist, type MasterAudio } from './hls.js'; +import { languageDisplayName, normalizeStreamLanguage } from './language.js'; +import { assertWritableDestination, ensureWritableDirectory, resolveInside } from './paths.js'; +import { runProcess } from './process.js'; +import type { Classification, MediaProbe, PackageResult, SourceFingerprint } from './types.js'; + +export interface CompatibilityEncodeOptions { + archiveRoot: string; + derivedRoot: string; + sourcePath: string; + fingerprint: SourceFingerprint; + probe: MediaProbe; + classification: Classification; + generation: string; + ffmpegPath?: string; + ffprobePath?: string; + segmentSeconds?: number; +} + +function frameRate(probe: MediaProbe, videoIndex: number): number { + const stream = probe.streams.find((candidate) => candidate.index === videoIndex); + const raw = stream?.avg_frame_rate ?? stream?.r_frame_rate ?? '24/1'; + const [numeratorRaw, denominatorRaw] = raw.split('/'); + const numerator = Number(numeratorRaw); + const denominator = Number(denominatorRaw ?? 1); + const value = numerator / denominator; + return Number.isFinite(value) && value > 0 && value <= 240 ? value : 24; +} + +function renditions(probe: MediaProbe, indexes: readonly number[]): MasterAudio[] { + return indexes.map((streamIndex, index) => { + const stream = probe.streams.find((candidate) => candidate.index === streamIndex); + if (stream === undefined) throw new Error(`Audio stream ${streamIndex} is missing`); + const language = normalizeStreamLanguage(stream); + return { + streamIndex, + language, + name: languageDisplayName(language), + uri: `audio-${streamIndex}-${language.replace(/[^a-z0-9-]/giu, '') || 'und'}/index.m3u8`, + ...(stream.channels === undefined ? {} : { channels: stream.channels }), + default: index === 0, + }; + }); +} + +export function buildCompatibilityEncodeArguments( + source: string, + output: string, + probe: MediaProbe, + classification: Classification, + segmentSeconds = 6, +): string[] { + if (classification.class === 'HOLD_HDR') throw new Error('HDR_UNSUPPORTED_V1'); + if (classification.class === 'INVALID') throw new Error('INVALID_SOURCE'); + const videoIndex = classification.videoStreamIndex; + if (videoIndex === undefined) throw new Error('No video stream selected'); + const audio = renditions(probe, classification.audioStreamIndexes); + const gop = Math.max(1, Math.ceil(frameRate(probe, videoIndex) * segmentSeconds)); + const args = [ + '-hide_banner', '-loglevel', 'warning', '-nostdin', '-y', + '-i', source, + '-map', `0:${videoIndex}`, + ]; + for (const item of audio) args.push('-map', `0:${item.streamIndex}`); + args.push( + '-map_metadata', '-1', '-map_chapters', '-1', '-sn', '-dn', + '-c:v', 'libx264', '-crf', '18', '-preset', 'medium', + '-profile:v', 'high', '-pix_fmt', 'yuv420p', '-flags', '+cgop', + '-g', String(gop), '-keyint_min', String(gop), '-sc_threshold', '0', + '-force_key_frames', `expr:gte(t,n_forced*${segmentSeconds})`, + ); + audio.forEach((item, index) => { + args.push(`-c:a:${index}`, 'aac', `-b:a:${index}`, (item.channels ?? 2) > 2 ? '384k' : '192k'); + }); + const variants = [ + 'v:0,agroup:audio,name:video', + ...audio.map((item, index) => `a:${index},agroup:audio,language:${item.language},default:${item.default ? 'yes' : 'no'},name:${path.dirname(item.uri)}`), + ].join(' '); + args.push( + '-f', 'hls', '-hls_time', String(segmentSeconds), + '-hls_segment_type', 'fmp4', '-hls_playlist_type', 'vod', + '-hls_flags', 'independent_segments+temp_file', + '-master_pl_name', 'master.ffmpeg.m3u8', '-var_stream_map', variants, + '-hls_fmp4_init_filename', 'init-%v.mp4', + '-hls_segment_filename', path.join(output, '%v', 'segment-%06d.m4s'), + path.join(output, '%v', 'index.m3u8'), + ); + return args; +} + +function outputProbe(source: MediaProbe, videoIndex: number): MediaProbe { + const { bit_rate: _ignoredBitrate, ...format } = source.format; + return { + ...source, + streams: source.streams.map((stream) => { + if (stream.index === videoIndex) { + const pixels = (stream.width ?? 1920) * (stream.height ?? 1080); + return { + ...stream, + codec_name: 'h264', + profile: 'High', + pix_fmt: 'yuv420p', + bits_per_raw_sample: '8', + mime_codec_string: 'avc1.640028', + bit_rate: String(pixels > 1920 * 1080 ? 20_000_000 : 8_000_000), + }; + } + if (stream.codec_type === 'audio') return { ...stream, codec_name: 'aac', profile: 'LC', mime_codec_string: 'mp4a.40.2' }; + return stream; + }), + format, + }; +} + +async function validateEncodedCodecs(videoPlaylist: string, audioPlaylists: readonly string[], ffprobePath: string): Promise { + const video = await probeMedia(videoPlaylist, { ffprobePath, timeoutMs: 120_000 }); + if (!video.streams.some((stream) => stream.codec_type === 'video' && stream.codec_name === 'h264' && stream.pix_fmt === 'yuv420p')) { + throw new Error('Compatibility output is not 8-bit H.264 yuv420p'); + } + for (const playlist of audioPlaylists) { + const audio = await probeMedia(playlist, { ffprobePath, timeoutMs: 120_000 }); + if (!audio.streams.some((stream) => stream.codec_type === 'audio' && stream.codec_name === 'aac')) { + throw new Error('Compatibility audio output is not AAC'); + } + } +} + +export async function prepareCompatibilityHls(options: CompatibilityEncodeOptions): Promise { + if (options.classification.class === 'HOLD_HDR') throw new Error('HDR_UNSUPPORTED_V1'); + if (options.classification.class !== 'VIDEO_TRANSCODE') { + throw new Error(`Compatibility video encode is not required for ${options.classification.class}`); + } + if (!/^[a-z0-9][a-z0-9._-]{7,127}$/u.test(options.generation)) throw new Error('Invalid generation identifier'); + const source = await resolveInside(options.archiveRoot, options.sourcePath); + const videoIndex = options.classification.videoStreamIndex; + if (videoIndex === undefined) throw new Error('No video stream selected'); + const audio = renditions(options.probe, options.classification.audioStreamIndexes); + const generationsRoot = path.join(options.derivedRoot, 'generations'); + await ensureWritableDirectory(options.derivedRoot, generationsRoot); + const finalDirectory = await assertWritableDestination(options.derivedRoot, path.join(generationsRoot, options.generation)); + try { + if ((await stat(path.join(finalDirectory, 'master.m3u8'))).isFile()) { + const videoPlaylist = await validateMediaPlaylist(path.join(finalDirectory, 'video', 'index.m3u8'), { requireEnded: true, maxTargetDuration: 7 }); + const audioPlaylists = await Promise.all(audio.map((item) => validateMediaPlaylist(path.join(finalDirectory, item.uri), { requireEnded: true, maxTargetDuration: 7 }))); + return { generation: options.generation, outputDirectory: finalDirectory, masterPlaylist: path.join(finalDirectory, 'master.m3u8'), videoPlaylist, audioPlaylists, knownAacRepairs: 0 }; + } + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } + const staging = await assertWritableDestination(options.derivedRoot, path.join(options.derivedRoot, `.building-${options.generation}-${randomUUID()}`)); + await ensureWritableDirectory(options.derivedRoot, staging); + let moved = false; + try { + const result = await runProcess(options.ffmpegPath ?? 'ffmpeg', buildCompatibilityEncodeArguments( + source, staging, options.probe, options.classification, options.segmentSeconds ?? 6, + ), { timeoutMs: 7 * 24 * 60 * 60 * 1000, maxOutputBytes: 64 * 1024 * 1024 }); + const warnings = assessFfmpegWarnings(result.stderr); + if (warnings.unknown.length > 0) throw new Error(`Unrecognized FFmpeg warning(s): ${warnings.unknown.slice(0, 5).join(' | ')}`); + const videoStaging = path.join(staging, 'video', 'index.m3u8'); + const audioStaging = audio.map((item) => path.join(staging, item.uri)); + const [videoValidation, ...audioValidation] = await Promise.all([ + validateMediaPlaylist(videoStaging, { requireEnded: true, maxTargetDuration: 7 }), + ...audioStaging.map((playlist) => validateMediaPlaylist(playlist, { requireEnded: true, maxTargetDuration: 7 })), + ]); + if (videoValidation === undefined) throw new Error('Encoded video playlist is missing'); + for (const item of audioValidation) { + if (Math.abs(item.totalDuration - videoValidation.totalDuration) > 0.25) throw new Error('Encoded A/V durations differ by more than 250 ms'); + } + await validateEncodedCodecs(videoStaging, audioStaging, options.ffprobePath ?? 'ffprobe'); + const after = await fingerprintSource(options.archiveRoot, source, options.fingerprint.edgeBytes); + if (after.digest !== options.fingerprint.digest) throw new Error('Source changed during compatibility encoding'); + const master = buildMasterPlaylist(outputProbe(options.probe, videoIndex), videoIndex, 'video/index.m3u8', audio); + await writeFile(path.join(staging, 'master.m3u8'), master, { encoding: 'utf8', mode: 0o640 }); + await rename(staging, finalDirectory); + moved = true; + const videoPlaylist = await validateMediaPlaylist(path.join(finalDirectory, 'video', 'index.m3u8'), { requireEnded: true, maxTargetDuration: 7 }); + const audioPlaylists = await Promise.all(audio.map((item) => validateMediaPlaylist(path.join(finalDirectory, item.uri), { requireEnded: true, maxTargetDuration: 7 }))); + return { + generation: options.generation, + outputDirectory: finalDirectory, + masterPlaylist: path.join(finalDirectory, 'master.m3u8'), + videoPlaylist, + audioPlaylists, + knownAacRepairs: warnings.knownAacRepairs, + }; + } finally { + if (!moved) await rm(staging, { recursive: true, force: true }); + } +} diff --git a/packages/media/src/ffprobe.ts b/packages/media/src/ffprobe.ts new file mode 100644 index 0000000..a30e689 --- /dev/null +++ b/packages/media/src/ffprobe.ts @@ -0,0 +1,51 @@ +import { runProcess, type RunProcessOptions } from './process.js'; +import type { MediaProbe, ProbeFormat, ProbeStream } from './types.js'; + +export interface ProbeOptions extends RunProcessOptions { + ffprobePath?: string; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function parseProbeJson(raw: string): MediaProbe { + let value: unknown; + try { + value = JSON.parse(raw); + } catch (error) { + throw new Error(`ffprobe returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`); + } + if (!isRecord(value) || !Array.isArray(value.streams) || !isRecord(value.format)) { + throw new Error('ffprobe JSON is missing streams or format'); + } + const streams = value.streams.filter(isRecord) as unknown as ProbeStream[]; + if (!streams.every((stream) => Number.isInteger(stream.index))) { + throw new Error('ffprobe returned a stream without a numeric index'); + } + return { + streams, + format: value.format as ProbeFormat, + chapters: Array.isArray(value.chapters) ? value.chapters.filter(isRecord) : [], + }; +} + +export async function probeMedia(sourcePath: string, options: ProbeOptions = {}): Promise { + const result = await runProcess(options.ffprobePath ?? 'ffprobe', [ + '-v', 'error', + '-print_format', 'json', + '-show_format', + '-show_streams', + '-show_chapters', + sourcePath, + ], { + timeoutMs: options.timeoutMs ?? 120_000, + maxOutputBytes: options.maxOutputBytes ?? 64 * 1024 * 1024, + ...(options.cwd === undefined ? {} : { cwd: options.cwd }), + ...(options.env === undefined ? {} : { env: options.env }), + ...(options.signal === undefined ? {} : { signal: options.signal }), + }); + return parseProbeJson(result.stdout); +} + +export { parseProbeJson }; diff --git a/packages/media/src/fingerprint.ts b/packages/media/src/fingerprint.ts new file mode 100644 index 0000000..8e07cfd --- /dev/null +++ b/packages/media/src/fingerprint.ts @@ -0,0 +1,61 @@ +import { createHash } from 'node:crypto'; +import { open, realpath, stat } from 'node:fs/promises'; +import path from 'node:path'; +import { isPathInside, UnsafePathError } from './paths.js'; +import type { SourceFingerprint } from './types.js'; + +const DEFAULT_EDGE_BYTES = 4 * 1024 * 1024; + +export async function fingerprintSource( + archiveRoot: string, + sourcePath: string, + edgeBytes = DEFAULT_EDGE_BYTES, +): Promise { + if (!Number.isSafeInteger(edgeBytes) || edgeBytes < 1 || edgeBytes > 64 * 1024 * 1024) { + throw new RangeError('edgeBytes must be between 1 byte and 64 MiB'); + } + const [root, source] = await Promise.all([realpath(archiveRoot), realpath(sourcePath)]); + if (!isPathInside(root, source)) throw new UnsafePathError('Source is outside the archive root'); + + const before = await stat(source, { bigint: true }); + if (!before.isFile()) throw new UnsafePathError('Source is not a regular file'); + const size = before.size; + const chunkSize = Number(size < BigInt(edgeBytes) ? size : BigInt(edgeBytes)); + const first = Buffer.alloc(chunkSize); + const last = Buffer.alloc(chunkSize); + const file = await open(source, 'r'); + try { + await file.read(first, 0, chunkSize, 0); + const lastOffset = size > BigInt(chunkSize) ? size - BigInt(chunkSize) : 0n; + await file.read(last, 0, chunkSize, lastOffset); + } finally { + await file.close(); + } + + const after = await stat(source, { bigint: true }); + if (after.size !== before.size || after.mtimeNs !== before.mtimeNs) { + throw new Error('Source changed while it was being fingerprinted'); + } + const relativePath = path.relative(root, source).split(path.sep).join('/'); + const hash = createHash('sha256'); + hash.update('easy-stream-source-fingerprint-v1\0'); + hash.update(relativePath); + hash.update('\0'); + hash.update(size.toString()); + hash.update('\0'); + hash.update(before.mtimeNs.toString()); + hash.update('\0'); + hash.update(first); + hash.update('\0'); + hash.update(last); + + return { + version: 1, + algorithm: 'sha256', + relativePath, + size: size.toString(), + mtimeNs: before.mtimeNs.toString(), + edgeBytes: chunkSize, + digest: hash.digest('hex'), + }; +} diff --git a/packages/media/src/fonts.ts b/packages/media/src/fonts.ts new file mode 100644 index 0000000..aaf73d7 --- /dev/null +++ b/packages/media/src/fonts.ts @@ -0,0 +1,220 @@ +import { createHash, randomUUID } from 'node:crypto'; +import { constants } from 'node:fs'; +import { access, copyFile, link, lstat, opendir, readFile, realpath, rm } from 'node:fs/promises'; +import path from 'node:path'; +import { assertWritableDestination, assertWritableRoot, ensureWritableDirectory, resolveInside, UnsafePathError } from './paths.js'; +import { runProcess } from './process.js'; +import type { ProcessResult, RunProcessOptions } from './process.js'; +import type { MediaProbe, ProbeStream, StoredFont } from './types.js'; + +const MAX_FONT_BYTES = 10 * 1024 * 1024; +const MAX_FONT_COUNT = 128; +const MAX_TOTAL_FONT_BYTES = 128 * 1024 * 1024; + +function attachmentLooksLikeFont(stream: ProbeStream): boolean { + const mime = stream.tags?.mimetype?.toLowerCase() ?? ''; + const name = stream.tags?.filename?.toLowerCase() ?? ''; + return stream.codec_type === 'attachment' + && (stream.codec_name === 'ttf' || stream.codec_name === 'otf' + || mime.includes('font') || mime.includes('truetype') || mime.includes('opentype') + || /\.(?:ttf|otf)$/iu.test(name)); +} + +export function validateSfntFont(data: Buffer): 'ttf' | 'otf' { + if (data.length < 12 || data.length > MAX_FONT_BYTES) throw new Error('Font size is outside accepted bounds'); + const signature = data.subarray(0, 4).toString('ascii'); + let format: 'ttf' | 'otf'; + if (data.readUInt32BE(0) === 0x00010000 || signature === 'true' || signature === 'typ1') format = 'ttf'; + else if (signature === 'OTTO') format = 'otf'; + else throw new Error(`Unsupported font signature ${JSON.stringify(signature)}`); + const numTables = data.readUInt16BE(4); + if (numTables < 1 || numTables > 256 || 12 + numTables * 16 > data.length) { + throw new Error('Malformed SFNT table directory'); + } + for (let index = 0; index < numTables; index += 1) { + const record = 12 + index * 16; + const offset = data.readUInt32BE(record + 8); + const length = data.readUInt32BE(record + 12); + if (offset > data.length || length > data.length || offset + length > data.length) { + throw new Error('SFNT table points outside the attachment'); + } + } + return format; +} + +export interface FontExtractionOptions { + archiveRoot: string; + fontRoot: string; + ffmpegPath?: string; + sanitizerPath?: string; + timeoutMs?: number; + runner?: (binary: string, args: readonly string[], options?: RunProcessOptions) => Promise; +} + +export function fontDumpArguments(streamIndex: number, destination: string, source: string): string[] { + return [ + '-hide_banner', '-loglevel', 'error', '-nostdin', '-y', + `-dump_attachment:${streamIndex}`, destination, + '-i', source, + // Attachment dumping happens as the input header opens. Do not decode the movie. + '-t', '0', + '-f', 'null', '-', + ]; +} + +export async function extractAndStoreFonts( + sourcePath: string, + probe: MediaProbe, + options: FontExtractionOptions, +): Promise { + const source = await resolveInside(options.archiveRoot, sourcePath); + const staging = await ensureWritableDirectory(options.fontRoot, path.join(options.fontRoot, '.staging'), 0o700); + const store = await ensureWritableDirectory(options.fontRoot, path.join(options.fontRoot, 'sha256')); + const attachments = probe.streams.filter(attachmentLooksLikeFont); + if (attachments.length > MAX_FONT_COUNT) throw new Error(`File has too many font attachments (${attachments.length})`); + const declaredTotal = attachments.reduce((sum, stream) => sum + (stream.extradata_size ?? 0), 0); + if (declaredTotal > MAX_TOTAL_FONT_BYTES) throw new Error('Declared font attachments exceed the total size limit'); + const output: StoredFont[] = []; + const execute = options.runner ?? runProcess; + + for (const attachment of attachments) { + if ((attachment.extradata_size ?? 0) > MAX_FONT_BYTES) { + throw new Error(`Font attachment ${attachment.index} exceeds ${MAX_FONT_BYTES} bytes`); + } + const temporary = path.join(staging, `${randomUUID()}.font`); + try { + await execute( + options.ffmpegPath ?? 'ffmpeg', + fontDumpArguments(attachment.index, temporary, source), + { timeoutMs: options.timeoutMs ?? 120_000 }, + ); + const data = await readFile(temporary); + const format = validateSfntFont(data); + if (options.sanitizerPath !== undefined) { + await execute(options.sanitizerPath, [temporary], { timeoutMs: 30_000 }); + } + const sha256 = createHash('sha256').update(data).digest('hex'); + const destination = path.join(store, `${sha256}.${format}`); + try { + await link(temporary, destination); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code !== 'EEXIST') throw error; + } + const stored = await lstat(destination); + if (stored.isSymbolicLink() || !stored.isFile()) { + throw new UnsafePathError(`Stored font is not a regular file: ${destination}`); + } + await access(destination, constants.R_OK); + output.push({ + streamIndex: attachment.index, + sha256, + path: destination, + originalName: path.basename(attachment.tags?.filename ?? `attachment-${attachment.index}`), + size: data.length, + format, + }); + } finally { + await rm(temporary, { force: true }); + } + } + return output; +} + +/** Publishes hash-named generation-local font links while retaining one global content store. */ +export async function publishGenerationFonts( + fonts: readonly StoredFont[], + mediaRoot: string, + generationDirectory: string, +): Promise { + await assertWritableRoot(mediaRoot); + const root = await realpath(mediaRoot); + const generation = await resolveInside(root, generationDirectory); + const directory = await ensureWritableDirectory(root, path.join(generation, 'fonts')); + const published: StoredFont[] = []; + for (const font of fonts) { + const source = await resolveInside(root, font.path); + const destination = path.join(directory, `${font.sha256}.${font.format}`); + try { + await link(source, destination); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === 'EXDEV') { + try { + await copyFile(source, destination, constants.COPYFILE_EXCL); + } catch (copyError) { + if ((copyError as NodeJS.ErrnoException).code !== 'EEXIST') throw copyError; + } + } else if (code !== 'EEXIST') { + throw error; + } + } + const details = await lstat(destination); + if (details.isSymbolicLink() || !details.isFile() || details.size !== font.size) { + throw new Error(`Published font failed verification: ${font.sha256}`); + } + published.push({ ...font, path: destination }); + } + return published; +} + +export interface FontPruneOptions { + /** Avoid racing a package that extracted a font but has not published its hardlink yet. */ + minimumAgeMs?: number; + now?: Date; +} + +export interface FontPruneResult { + removed: string[]; + retainedBytes: number; +} + +/** Removes aged content-store files that have no generation hardlinks. */ +export async function pruneOrphanedFonts( + mediaRoot: string, + options: FontPruneOptions = {}, +): Promise { + const minimumAgeMs = options.minimumAgeMs ?? 60 * 60 * 1000; + if (!Number.isFinite(minimumAgeMs) || minimumAgeMs < 0) throw new RangeError('Invalid font prune age'); + let root: string; + try { + await assertWritableRoot(mediaRoot); + root = await realpath(mediaRoot); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { removed: [], retainedBytes: 0 }; + throw error; + } + let store: string; + try { + const storeCandidate = path.join(root, 'assets', 'fonts', 'sha256'); + await assertWritableDestination(root, storeCandidate); + store = await resolveInside(root, storeCandidate); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { removed: [], retainedBytes: 0 }; + throw error; + } + let handle: Awaited>; + try { + handle = await opendir(store); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { removed: [], retainedBytes: 0 }; + throw error; + } + const cutoff = (options.now ?? new Date()).getTime() - minimumAgeMs; + const removed: string[] = []; + let retainedBytes = 0; + for await (const entry of handle) { + if (!/^[a-f0-9]{64}\.(?:ttf|otf)$/u.test(entry.name)) continue; + const candidate = path.join(store, entry.name); + const details = await lstat(candidate); + if (details.isSymbolicLink()) throw new Error(`Symlink found in global font store: ${candidate}`); + if (!details.isFile()) continue; + if (details.nlink <= 1 && details.mtimeMs <= cutoff) { + await rm(candidate, { force: false }); + removed.push(entry.name); + } else { + retainedBytes += details.size; + } + } + return { removed, retainedBytes }; +} diff --git a/packages/media/src/hls.ts b/packages/media/src/hls.ts new file mode 100644 index 0000000..6cbc63c --- /dev/null +++ b/packages/media/src/hls.ts @@ -0,0 +1,185 @@ +import { readFile, stat, writeFile, rename } from 'node:fs/promises'; +import path from 'node:path'; +import type { HlsPlaylistValidation, MediaProbe, ProbeStream } from './types.js'; + +const URI_PATTERN = /^(?![a-z][a-z0-9+.-]*:)(?!\/)(?!.*(?:^|\/)\.\.(?:\/|$))[^\0]+$/iu; + +export interface ParsedMediaPlaylist { + targetDuration: number; + playlistType?: string; + mapUri?: string; + segments: Array<{ duration: number; uri: string }>; + ended: boolean; +} + +function attribute(line: string, name: string): string | undefined { + const match = line.match(new RegExp(`(?:^|,)${name}=(?:"([^"]*)"|([^,]*))`, 'u')); + return match?.[1] ?? match?.[2]; +} + +export function parseMediaPlaylist(content: string): ParsedMediaPlaylist { + const lines = content.split(/\r?\n/u).map((line) => line.trim()).filter(Boolean); + if (lines[0] !== '#EXTM3U') throw new Error('Playlist is missing EXTM3U'); + let targetDuration = 0; + let playlistType: string | undefined; + let mapUri: string | undefined; + let pendingDuration: number | undefined; + const segments: ParsedMediaPlaylist['segments'] = []; + let ended = false; + for (const line of lines.slice(1)) { + if (line.startsWith('#EXT-X-TARGETDURATION:')) targetDuration = Number(line.slice(22)); + else if (line.startsWith('#EXT-X-PLAYLIST-TYPE:')) playlistType = line.slice(21); + else if (line.startsWith('#EXT-X-MAP:')) mapUri = attribute(line.slice(11), 'URI'); + else if (line.startsWith('#EXTINF:')) pendingDuration = Number(line.slice(8).split(',')[0]); + else if (line === '#EXT-X-ENDLIST') ended = true; + else if (!line.startsWith('#')) { + if (pendingDuration === undefined || !Number.isFinite(pendingDuration) || pendingDuration <= 0) { + throw new Error(`Segment URI has no valid EXTINF: ${line}`); + } + segments.push({ duration: pendingDuration, uri: line }); + pendingDuration = undefined; + } + } + if (!Number.isInteger(targetDuration) || targetDuration < 1) throw new Error('Invalid HLS target duration'); + if (mapUri === undefined) throw new Error('Fragmented MP4 playlist has no EXT-X-MAP'); + return { targetDuration, ...(playlistType === undefined ? {} : { playlistType }), mapUri, segments, ended }; +} + +function assertSafeUri(uri: string): void { + if (!URI_PATTERN.test(uri)) throw new Error(`Unsafe or external HLS URI: ${uri}`); +} + +export async function validateMediaPlaylist( + playlistPath: string, + options: { requireEnded?: boolean; maxTargetDuration?: number; minSegments?: number } = {}, +): Promise { + const content = await readFile(playlistPath, 'utf8'); + const parsed = parseMediaPlaylist(content); + if (options.requireEnded === true && !parsed.ended) throw new Error(`${playlistPath} has no ENDLIST`); + if (parsed.targetDuration > (options.maxTargetDuration ?? 18)) { + throw new Error(`${playlistPath} target duration ${parsed.targetDuration} exceeds the compatibility limit`); + } + if (parsed.segments.length < (options.minSegments ?? 1)) throw new Error(`${playlistPath} has too few segments`); + const directory = path.dirname(playlistPath); + const mapUri = parsed.mapUri; + if (mapUri === undefined) throw new Error('Fragmented MP4 playlist has no EXT-X-MAP'); + const referenced = [mapUri, ...parsed.segments.map((segment) => segment.uri)]; + for (const uri of referenced) { + assertSafeUri(uri); + const file = path.resolve(directory, uri); + if (!file.startsWith(`${path.resolve(directory)}${path.sep}`)) throw new Error(`HLS URI escapes playlist directory: ${uri}`); + const details = await stat(file); + if (!details.isFile() || details.size === 0) throw new Error(`HLS resource is missing or empty: ${uri}`); + } + const durations = parsed.segments.map((segment) => segment.duration); + return { + path: playlistPath, + segmentCount: durations.length, + targetDuration: parsed.targetDuration, + minDuration: Math.min(...durations), + maxDuration: Math.max(...durations), + totalDuration: durations.reduce((sum, duration) => sum + duration, 0), + ended: parsed.ended, + }; +} + +export async function finalizeEventPlaylist(playlistPath: string): Promise { + const content = await readFile(playlistPath, 'utf8'); + const parsed = parseMediaPlaylist(content); + if (!parsed.ended) throw new Error('Cannot finalize an incomplete EVENT playlist'); + const vod = content.replace('#EXT-X-PLAYLIST-TYPE:EVENT', '#EXT-X-PLAYLIST-TYPE:VOD'); + const temporary = `${playlistPath}.vod.tmp`; + await writeFile(temporary, vod, { encoding: 'utf8', mode: 0o640 }); + await rename(temporary, playlistPath); +} + +function escapeAttribute(value: string): string { + return value.replace(/["\r\n]/gu, ''); +} + +function streamBitrate(stream: ProbeStream, fallback: number): number { + const raw = stream.bit_rate ?? stream.tags?.BPS ?? stream.tags?.bps; + const value = Number(raw); + return Number.isFinite(value) && value > 0 ? value : fallback; +} + +export interface MasterAudio { + streamIndex: number; + language: string; + name: string; + uri: string; + channels?: number; + default: boolean; +} + +export function buildMasterPlaylist( + probe: MediaProbe, + videoStreamIndex: number, + videoUri: string, + audio: readonly MasterAudio[], +): string { + const video = probe.streams.find((stream) => stream.index === videoStreamIndex); + if (video === undefined) throw new Error('Video stream is missing from probe'); + if (audio.length === 0) throw new Error('At least one audio rendition is required'); + const audioStreams = audio.map((item) => probe.streams.find((stream) => stream.index === item.streamIndex)); + const audioBandwidth = Math.max(...audioStreams.map((stream) => stream === undefined ? 384_000 : streamBitrate(stream, 384_000))); + const containerBitrate = Number(probe.format.bit_rate); + const conservativeVideoFallback = Number.isFinite(containerBitrate) && containerBitrate > audioBandwidth + ? containerBitrate - audioBandwidth + : 8_000_000; + const videoBandwidth = streamBitrate(video, conservativeVideoFallback); + const bandwidth = Math.ceil((videoBandwidth + audioBandwidth) * 1.15); + const average = videoBandwidth + audioBandwidth; + const codecs = [video.mime_codec_string ?? 'avc1.640028', 'mp4a.40.2'].join(','); + const resolution = video.width !== undefined && video.height !== undefined ? `,RESOLUTION=${video.width}x${video.height}` : ''; + const lines = ['#EXTM3U', '#EXT-X-VERSION:7', '#EXT-X-INDEPENDENT-SEGMENTS']; + for (const item of audio) { + assertSafeUri(item.uri); + lines.push( + `#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",NAME="${escapeAttribute(item.name)}",LANGUAGE="${escapeAttribute(item.language)}",AUTOSELECT=YES,DEFAULT=${item.default ? 'YES' : 'NO'}${item.channels === undefined ? '' : `,CHANNELS="${item.channels}"`},URI="${item.uri}"`, + ); + } + assertSafeUri(videoUri); + lines.push( + `#EXT-X-STREAM-INF:BANDWIDTH=${bandwidth},AVERAGE-BANDWIDTH=${average}${resolution},CODECS="${escapeAttribute(codecs)}",AUDIO="audio"`, + videoUri, + '', + ); + return lines.join('\n'); +} + +export interface WarningAssessment { + knownAacRepairs: number; + ignoredProbeWarnings: number; + unknown: string[]; +} + +/** Only the observed one-sample AAC rounding repair is accepted. */ +export function assessFfmpegWarnings(stderr: string): WarningAssessment { + const lines = stderr.split(/\r?\n/u).map((line) => line.trim()).filter(Boolean); + let knownAacRepairs = 0; + let ignoredProbeWarnings = 0; + const unknown: string[] = []; + for (const line of lines) { + const packet = line.match(/Packet duration:\s*(-?\d+)\s*\/\s*dts:/u); + if (packet !== null) { + if (Number(packet[1]) === -32) knownAacRepairs += 1; + else unknown.push(line); + continue; + } + if (line.includes('Could not find codec parameters for stream') && line.includes('Attachment: none')) { + ignoredProbeWarnings += 1; + continue; + } + if (line.startsWith('Consider increasing the value for the \'analyzeduration\'')) { + ignoredProbeWarnings += 1; + continue; + } + if (line === 'Bandwidth info not available, set audio and video bitrates') { + ignoredProbeWarnings += 1; + continue; + } + unknown.push(line); + } + return { knownAacRepairs, ignoredProbeWarnings, unknown }; +} diff --git a/packages/media/src/index.ts b/packages/media/src/index.ts new file mode 100644 index 0000000..0e214c2 --- /dev/null +++ b/packages/media/src/index.ts @@ -0,0 +1,14 @@ +export * from './cache.js'; +export * from './classify.js'; +export * from './encode.js'; +export * from './ffprobe.js'; +export * from './fingerprint.js'; +export * from './fonts.js'; +export * from './hls.js'; +export * from './language.js'; +export * from './packager.js'; +export * from './paths.js'; +export * from './process.js'; +export * from './single-flight.js'; +export * from './subtitles.js'; +export type * from './types.js'; diff --git a/packages/media/src/language.ts b/packages/media/src/language.ts new file mode 100644 index 0000000..f51ac18 --- /dev/null +++ b/packages/media/src/language.ts @@ -0,0 +1,63 @@ +import type { ProbeStream } from './types.js'; + +const LANGUAGE_ALIASES: Record = { + ara: 'ar', ar: 'ar', + chi: 'zh', zho: 'zh', zh: 'zh', + dut: 'nl', nld: 'nl', nl: 'nl', + eng: 'en', en: 'en', + fas: 'fa', per: 'fa', fa: 'fa', pes: 'fa', + fre: 'fr', fra: 'fr', fr: 'fr', + ger: 'de', deu: 'de', de: 'de', + heb: 'he', he: 'he', + hin: 'hi', hi: 'hi', + ita: 'it', it: 'it', + jpn: 'ja', ja: 'ja', + kor: 'ko', ko: 'ko', + por: 'pt', pt: 'pt', + rus: 'ru', ru: 'ru', + spa: 'es', es: 'es', + tur: 'tr', tr: 'tr', + und: 'und', unknown: 'und', qad: 'und', +}; + +export function detectTextLanguage(text: string): string | undefined { + const clean = text.replace(/\{[^}]*\}/g, '').replace(/\\[Nnh]/g, ' '); + const arabicScript = (clean.match(/[\u0600-\u06ff]/gu) ?? []).length; + const persianSpecific = (clean.match(/[پچژگک‌ی]/gu) ?? []).length; + const kana = (clean.match(/[\u3040-\u30ff]/gu) ?? []).length; + const han = (clean.match(/[\u3400-\u9fff]/gu) ?? []).length; + const cjk = kana + han; + const hangul = (clean.match(/[\uac00-\ud7af]/gu) ?? []).length; + const cyrillic = (clean.match(/[\u0400-\u04ff]/gu) ?? []).length; + const latin = (clean.match(/[A-Za-z]/g) ?? []).length; + const largest = Math.max(arabicScript, cjk, hangul, cyrillic, latin); + if (largest < 12) return undefined; + if (largest === arabicScript) return persianSpecific >= 2 ? 'fa' : 'ar'; + if (largest === cjk) return kana >= 2 ? 'ja' : 'zh'; + if (largest === hangul) return 'ko'; + if (largest === cyrillic) return 'ru'; + return 'en'; +} + +export function normalizeLanguage(raw: string | undefined, content?: string): string { + const value = raw?.trim().toLowerCase().replaceAll('_', '-'); + const primary = value?.split('-')[0]; + const normalized = primary === undefined ? undefined : LANGUAGE_ALIASES[primary]; + const detected = content === undefined ? undefined : detectTextLanguage(content); + if (normalized === undefined || normalized === 'und') return detected ?? 'und'; + // Script evidence wins over unreliable private-use and plainly wrong archive tags. + if (detected !== undefined && detected !== normalized) return detected; + return normalized; +} + +export function normalizeStreamLanguage(stream: ProbeStream, content?: string): string { + return normalizeLanguage(stream.tags?.language, content); +} + +export function languageDisplayName(language: string, locale = 'en'): string { + try { + return new Intl.DisplayNames([locale], { type: 'language' }).of(language) ?? language; + } catch { + return language; + } +} diff --git a/packages/media/src/packager.ts b/packages/media/src/packager.ts new file mode 100644 index 0000000..4add04d --- /dev/null +++ b/packages/media/src/packager.ts @@ -0,0 +1,355 @@ +import { mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { writeCacheMetadata } from './cache.js'; +import { probeMedia } from './ffprobe.js'; +import { fingerprintSource } from './fingerprint.js'; +import { + assessFfmpegWarnings, + buildMasterPlaylist, + finalizeEventPlaylist, + validateMediaPlaylist, + type MasterAudio, +} from './hls.js'; +import { languageDisplayName, normalizeStreamLanguage } from './language.js'; +import { assertWritableDestination, ensureWritableDirectory, resolveInside } from './paths.js'; +import { runProcess } from './process.js'; +import { SingleFlight } from './single-flight.js'; +import type { Classification, MediaProbe, PackageResult, SourceFingerprint } from './types.js'; + +const GENERATION_PATTERN = /^[a-z0-9][a-z0-9._-]{7,127}$/u; + +export interface PackagingProgress { + state: 'PREPARING' | 'READY' | 'FAILED'; + generation: string; + outputDirectory: string; + playable?: boolean; + error?: string; +} + +export interface PackageHlsOptions { + archiveRoot: string; + cacheRoot: string; + sourcePath: string; + fingerprint: SourceFingerprint; + probe: MediaProbe; + classification: Classification; + generation?: string; + ffmpegPath?: string; + ffprobePath?: string; + segmentSeconds?: number; + maxTargetDuration?: number; + profileVersion?: string; + progressIntervalMs?: number; + activeBuildMaxAgeMs?: number; + onProgress?: (progress: PackagingProgress) => void | Promise; +} + +function buildGeneration(fingerprint: SourceFingerprint, profileVersion: string): string { + const profile = profileVersion.toLowerCase().replace(/[^a-z0-9._-]/gu, '-').slice(0, 32); + return `${profile}-${fingerprint.digest.slice(0, 32)}`; +} + +function audioRenditions(probe: MediaProbe, indexes: readonly number[]): MasterAudio[] { + return indexes.map((streamIndex, index) => { + const stream = probe.streams.find((candidate) => candidate.index === streamIndex); + if (stream === undefined) throw new Error(`Audio stream ${streamIndex} is missing`); + const language = normalizeStreamLanguage(stream); + const safeLanguage = language.replace(/[^a-z0-9-]/giu, '').toLowerCase() || 'und'; + return { + streamIndex, + language, + name: languageDisplayName(language), + uri: `audio-${streamIndex}-${safeLanguage}/index.m3u8`, + ...(stream.channels === undefined ? {} : { channels: stream.channels }), + default: index === 0, + }; + }); +} + +function ffmpegArguments( + source: string, + output: string, + videoIndex: number, + audio: readonly MasterAudio[], + classification: Classification, + segmentSeconds: number, +): string[] { + const arguments_: string[] = [ + '-hide_banner', '-loglevel', 'warning', '-nostdin', '-y', + '-i', source, + '-map', `0:${videoIndex}`, + ]; + for (const item of audio) arguments_.push('-map', `0:${item.streamIndex}`); + arguments_.push('-map_metadata', '-1', '-map_chapters', '-1', '-sn', '-dn', '-c:v', 'copy'); + if (classification.class === 'AUDIO_TRANSCODE') { + audio.forEach((item, index) => { + arguments_.push(`-c:a:${index}`, 'aac', `-b:a:${index}`, (item.channels ?? 2) > 2 ? '384k' : '192k'); + }); + } else { + arguments_.push('-c:a', 'copy'); + } + const variants = [ + 'v:0,agroup:audio,name:video', + ...audio.map((item, index) => { + const folder = path.dirname(item.uri); + return `a:${index},agroup:audio,language:${item.language},default:${item.default ? 'yes' : 'no'},name:${folder}`; + }), + ].join(' '); + arguments_.push( + '-f', 'hls', + '-hls_time', String(segmentSeconds), + '-hls_segment_type', 'fmp4', + '-hls_playlist_type', 'event', + '-hls_flags', 'independent_segments+temp_file', + '-master_pl_name', 'master.live.m3u8', + '-var_stream_map', variants, + '-hls_fmp4_init_filename', 'init-%v.mp4', + '-hls_segment_filename', path.join(output, '%v', 'segment-%06d.m4s'), + path.join(output, '%v', 'index.m3u8'), + ); + return arguments_; +} + +export class GenerationBuildActiveError extends Error { + constructor(readonly generation: string) { + super(`Generation is already being built: ${generation}`); + this.name = 'GenerationBuildActiveError'; + } +} + +async function existingPackage( + generation: string, + outputDirectory: string, + masterPlaylist: string, + videoPlaylistPath: string, + audioPlaylistPaths: readonly string[], + ffprobePath: string, + maxTargetDuration: number, +): Promise { + try { + const [videoPlaylist, ...audioPlaylists] = await Promise.all([ + validateMediaPlaylist(videoPlaylistPath, { requireEnded: true, maxTargetDuration }), + ...audioPlaylistPaths.map((playlist) => validateMediaPlaylist(playlist, { requireEnded: true, maxTargetDuration })), + ]); + if (videoPlaylist === undefined) return undefined; + const master = await readFile(masterPlaylist, 'utf8'); + if (!master.startsWith('#EXTM3U') || !master.includes('video/index.m3u8')) return undefined; + await validateCodecs(videoPlaylistPath, audioPlaylistPaths, ffprobePath); + return { generation, outputDirectory, masterPlaylist, videoPlaylist, audioPlaylists, knownAacRepairs: 0 }; + } catch { + return undefined; + } +} + +async function validateCodecs(videoPlaylist: string, audioPlaylists: readonly string[], ffprobePath: string): Promise { + const video = await probeMedia(videoPlaylist, { ffprobePath, timeoutMs: 120_000 }); + if (!video.streams.some((stream) => stream.codec_type === 'video' && stream.codec_name === 'h264')) { + throw new Error('Packaged video does not probe as H.264'); + } + for (const playlist of audioPlaylists) { + const audio = await probeMedia(playlist, { ffprobePath, timeoutMs: 120_000 }); + if (!audio.streams.some((stream) => stream.codec_type === 'audio' && stream.codec_name === 'aac')) { + throw new Error(`Packaged audio does not probe as AAC: ${playlist}`); + } + } +} + +async function writeMaster(destination: string, content: string): Promise { + const temporary = `${destination}.tmp`; + await writeFile(temporary, content, { encoding: 'utf8', mode: 0o640 }); + await rename(temporary, destination); +} + +function delay(milliseconds: number): Promise { + return new Promise((resolve) => setTimeout(resolve, milliseconds)); +} + +export async function packageProgressiveHls(options: PackageHlsOptions): Promise { + if (!['COPY', 'AUDIO_TRANSCODE'].includes(options.classification.class)) { + throw new Error(`Source cannot be JIT packaged: ${options.classification.class}`); + } + const source = await resolveInside(options.archiveRoot, options.sourcePath); + const generation = options.generation ?? buildGeneration(options.fingerprint, options.profileVersion ?? 'cmaf-v1'); + if (!GENERATION_PATTERN.test(generation)) throw new Error('Invalid generation identifier'); + const generationsRoot = path.join(options.cacheRoot, 'generations'); + await ensureWritableDirectory(options.cacheRoot, generationsRoot); + const outputDirectory = await assertWritableDestination(options.cacheRoot, path.join(generationsRoot, generation)); + const videoIndex = options.classification.videoStreamIndex; + if (videoIndex === undefined) throw new Error('Classification selected no video stream'); + const audio = audioRenditions(options.probe, options.classification.audioStreamIndexes); + const videoPlaylistPath = path.join(outputDirectory, 'video', 'index.m3u8'); + const audioPlaylistPaths = audio.map((item) => path.join(outputDirectory, item.uri)); + const masterPlaylist = path.join(outputDirectory, 'master.m3u8'); + const master = buildMasterPlaylist(options.probe, videoIndex, 'video/index.m3u8', audio); + let outputExists = false; + try { + outputExists = (await stat(outputDirectory)).isDirectory(); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } + if (outputExists) { + const ready = await existingPackage( + generation, + outputDirectory, + masterPlaylist, + videoPlaylistPath, + audioPlaylistPaths, + options.ffprobePath ?? 'ffprobe', + options.maxTargetDuration ?? 18, + ); + if (ready !== undefined) { + await options.onProgress?.({ state: 'READY', generation, outputDirectory, playable: true }); + return ready; + } + let building = false; + let lastAccessedAt = 0; + try { + const metadata = JSON.parse(await readFile(path.join(outputDirectory, '.cache-entry.json'), 'utf8')) as { + building?: boolean; lastAccessedAt?: string; + }; + building = metadata.building === true; + lastAccessedAt = Date.parse(metadata.lastAccessedAt ?? ''); + } catch { + // An unrecognized partial directory is treated as a failed build and archived. + } + if (building && Number.isFinite(lastAccessedAt) + && Date.now() - lastAccessedAt < (options.activeBuildMaxAgeMs ?? 26 * 60 * 60 * 1000)) { + throw new GenerationBuildActiveError(generation); + } + const failedName = `failed-${Date.now()}-${generation}`; + const failedDirectory = path.join(generationsRoot, failedName); + await rename(outputDirectory, failedDirectory); + try { + await writeCacheMetadata(generationsRoot, failedDirectory, { + key: failedName, + lastAccessedAt: new Date().toISOString(), + active: false, + building: false, + pinned: false, + }); + } catch { + // The archived directory remains diagnostic-only even without cache metadata. + } + } + try { + await mkdir(outputDirectory, { recursive: false, mode: 0o750 }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw new GenerationBuildActiveError(generation); + throw error; + } + // This stable URL exists before playable=true; it references atomically published EVENT playlists. + await writeMaster(masterPlaylist, master); + await writeCacheMetadata(generationsRoot, outputDirectory, { + key: generation, + lastAccessedAt: new Date().toISOString(), + active: false, + building: true, + pinned: false, + bytes: 0, + }); + await options.onProgress?.({ state: 'PREPARING', generation, outputDirectory, playable: false }); + + let settled = false; + let processResult: Awaited> | undefined; + let processError: unknown; + const processPromise = runProcess(options.ffmpegPath ?? 'ffmpeg', ffmpegArguments( + source, + outputDirectory, + videoIndex, + audio, + options.classification, + options.segmentSeconds ?? 6, + ), { timeoutMs: 24 * 60 * 60 * 1000, maxOutputBytes: 64 * 1024 * 1024 }).then( + (result) => { processResult = result; }, + (error: unknown) => { processError = error; }, + ).finally(() => { settled = true; }); + + let playableReported = false; + try { + while (!settled && !playableReported) { + await delay(options.progressIntervalMs ?? 250); + try { + await Promise.all([ + validateMediaPlaylist(videoPlaylistPath, { minSegments: 2, maxTargetDuration: options.maxTargetDuration ?? 18 }), + ...audioPlaylistPaths.map((playlist) => validateMediaPlaylist(playlist, { minSegments: 2, maxTargetDuration: options.maxTargetDuration ?? 18 })), + ]); + playableReported = true; + await options.onProgress?.({ state: 'PREPARING', generation, outputDirectory, playable: true }); + } catch { + // The producer publishes manifests and segments atomically; absence here means not ready yet. + } + } + await processPromise; + if (processError !== undefined) throw processError; + if (processResult === undefined) throw new Error('FFmpeg completed without a result'); + const afterFingerprint = await fingerprintSource(options.archiveRoot, source, options.fingerprint.edgeBytes); + if (afterFingerprint.digest !== options.fingerprint.digest) throw new Error('Source changed during packaging'); + const warnings = assessFfmpegWarnings(processResult.stderr); + if (warnings.unknown.length > 0) { + throw new Error(`Unrecognized FFmpeg warning(s): ${warnings.unknown.slice(0, 5).join(' | ')}`); + } + const initial = await Promise.all([ + validateMediaPlaylist(videoPlaylistPath, { requireEnded: true, maxTargetDuration: options.maxTargetDuration ?? 18 }), + ...audioPlaylistPaths.map((playlist) => validateMediaPlaylist(playlist, { requireEnded: true, maxTargetDuration: options.maxTargetDuration ?? 18 })), + ]); + const [videoInitial, ...audioInitial] = initial; + if (videoInitial === undefined) throw new Error('Video playlist validation did not run'); + for (const item of audioInitial) { + if (Math.abs(item.totalDuration - videoInitial.totalDuration) > 0.25) { + throw new Error(`A/V duration differs by more than 250 ms (${videoInitial.totalDuration} vs ${item.totalDuration})`); + } + } + await validateCodecs(videoPlaylistPath, audioPlaylistPaths, options.ffprobePath ?? 'ffprobe'); + await Promise.all([videoPlaylistPath, ...audioPlaylistPaths].map(finalizeEventPlaylist)); + const [videoPlaylist, ...audioPlaylists] = await Promise.all([ + validateMediaPlaylist(videoPlaylistPath, { requireEnded: true, maxTargetDuration: options.maxTargetDuration ?? 18 }), + ...audioPlaylistPaths.map((playlist) => validateMediaPlaylist(playlist, { requireEnded: true, maxTargetDuration: options.maxTargetDuration ?? 18 })), + ]); + if (videoPlaylist === undefined) throw new Error('Final video playlist is missing'); + await writeCacheMetadata(generationsRoot, outputDirectory, { + key: generation, + lastAccessedAt: new Date().toISOString(), + active: false, + building: false, + pinned: false, + }); + await options.onProgress?.({ state: 'READY', generation, outputDirectory, playable: true }); + return { generation, outputDirectory, masterPlaylist, videoPlaylist, audioPlaylists, knownAacRepairs: warnings.knownAacRepairs }; + } catch (error) { + try { + const details = await stat(outputDirectory); + if (details.isDirectory()) { + await writeCacheMetadata(generationsRoot, outputDirectory, { + key: generation, + lastAccessedAt: new Date().toISOString(), + active: false, + building: false, + pinned: false, + }); + } + } catch { + // Preserve the original packaging error. + } + await options.onProgress?.({ + state: 'FAILED', + generation, + outputDirectory, + playable: false, + error: error instanceof Error ? error.message : String(error), + }); + throw error; + } +} + +export class ProgressiveHlsPackager { + readonly #singleFlight = new SingleFlight(); + + package(options: PackageHlsOptions): Promise { + const generation = options.generation ?? buildGeneration(options.fingerprint, options.profileVersion ?? 'cmaf-v1'); + return this.#singleFlight.run(generation, async () => await packageProgressiveHls({ ...options, generation })); + } +} + +export async function readGeneratedMaster(outputDirectory: string): Promise { + return await readFile(path.join(outputDirectory, 'master.m3u8'), 'utf8'); +} diff --git a/packages/media/src/paths.ts b/packages/media/src/paths.ts new file mode 100644 index 0000000..2aec616 --- /dev/null +++ b/packages/media/src/paths.ts @@ -0,0 +1,151 @@ +import { lstat, mkdir, opendir, realpath, stat } from 'node:fs/promises'; +import path from 'node:path'; + +export class UnsafePathError extends Error { + constructor(message: string) { + super(message); + this.name = 'UnsafePathError'; + } +} + +function withSeparator(value: string): string { + return value.endsWith(path.sep) ? value : `${value}${path.sep}`; +} + +export function isPathInside(root: string, candidate: string): boolean { + const normalizedRoot = path.resolve(root); + const normalizedCandidate = path.resolve(candidate); + return normalizedCandidate === normalizedRoot || normalizedCandidate.startsWith(withSeparator(normalizedRoot)); +} + +export async function resolveInside(root: string, candidate: string): Promise { + const realRoot = await realpath(root); + const realCandidate = await realpath(candidate); + if (!isPathInside(realRoot, realCandidate)) { + throw new UnsafePathError(`Path escapes configured root: ${candidate}`); + } + return realCandidate; +} + +export async function assertWritableDestination(root: string, candidate: string): Promise { + const resolvedRoot = path.resolve(root); + const resolvedCandidate = path.resolve(candidate); + if (resolvedCandidate === resolvedRoot || !isPathInside(resolvedRoot, resolvedCandidate)) { + throw new UnsafePathError(`Output must be a child of its configured root: ${candidate}`); + } + await assertWritableRoot(resolvedRoot); + let canonicalRoot: string; + try { + canonicalRoot = await realpath(resolvedRoot); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return resolvedCandidate; + throw error; + } + let current = canonicalRoot; + for (const component of path.relative(resolvedRoot, resolvedCandidate).split(path.sep)) { + current = path.join(current, component); + try { + const details = await lstat(current); + if (details.isSymbolicLink()) throw new UnsafePathError(`Symlink found in writable path: ${current}`); + if (!details.isDirectory()) throw new UnsafePathError(`Writable path component is not a directory: ${current}`); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') break; + throw error; + } + } + return resolvedCandidate; +} + +/** Rejects a configured writable root that is itself a symlink. Missing roots are allowed. */ +export async function assertWritableRoot(root: string): Promise { + const resolvedRoot = path.resolve(root); + try { + const details = await lstat(resolvedRoot); + if (details.isSymbolicLink()) throw new UnsafePathError(`Configured writable root is a symlink: ${resolvedRoot}`); + if (!details.isDirectory()) throw new UnsafePathError(`Configured writable root is not a directory: ${resolvedRoot}`); + await realpath(resolvedRoot); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } + return resolvedRoot; +} + +/** Creates a managed child directory one component at a time without following planted symlinks. */ +export async function ensureWritableDirectory( + root: string, + candidate: string, + mode = 0o750, +): Promise { + const resolvedRoot = path.resolve(root); + const resolvedCandidate = path.resolve(candidate); + if (resolvedCandidate === resolvedRoot || !isPathInside(resolvedRoot, resolvedCandidate)) { + throw new UnsafePathError(`Output must be a child of its configured root: ${candidate}`); + } + await assertWritableRoot(resolvedRoot); + try { + await lstat(resolvedRoot); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + await mkdir(resolvedRoot, { recursive: true, mode }); + await assertWritableRoot(resolvedRoot); + } + const canonicalRoot = await realpath(resolvedRoot); + let current = canonicalRoot; + for (const component of path.relative(resolvedRoot, resolvedCandidate).split(path.sep)) { + current = path.join(current, component); + try { + const details = await lstat(current); + if (details.isSymbolicLink()) throw new UnsafePathError(`Symlink found in writable path: ${current}`); + if (!details.isDirectory()) throw new UnsafePathError(`Writable path component is not a directory: ${current}`); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + try { + await mkdir(current, { mode }); + } catch (mkdirError) { + if ((mkdirError as NodeJS.ErrnoException).code !== 'EEXIST') throw mkdirError; + } + const details = await lstat(current); + if (details.isSymbolicLink() || !details.isDirectory()) { + throw new UnsafePathError(`Refusing unsafe writable directory: ${current}`); + } + } + } + // Re-check the complete chain after creation so callers never receive a path whose + // ancestor was replaced with a symlink while the components were being created. + await assertWritableDestination(resolvedRoot, resolvedCandidate); + return resolvedCandidate; +} + +export interface WalkArchiveOptions { + extensions?: readonly string[]; + maxDepth?: number; +} + +/** Walks regular files only and never follows archive symlinks. */ +export async function* walkArchive( + archiveRoot: string, + options: WalkArchiveOptions = {}, +): AsyncGenerator { + const root = await realpath(archiveRoot); + const rootStat = await stat(root); + if (!rootStat.isDirectory()) throw new UnsafePathError(`Archive root is not a directory: ${root}`); + const allowed = new Set((options.extensions ?? ['.mkv']).map((extension) => extension.toLowerCase())); + const maxDepth = options.maxDepth ?? 32; + + async function* visit(directory: string, depth: number): AsyncGenerator { + if (depth > maxDepth) throw new UnsafePathError(`Archive tree exceeds maximum depth ${maxDepth}`); + const handle = await opendir(directory); + for await (const entry of handle) { + const candidate = path.join(directory, entry.name); + if (entry.isSymbolicLink()) continue; + if (entry.isDirectory()) { + yield* visit(candidate, depth + 1); + } else if (entry.isFile() && allowed.has(path.extname(entry.name).toLowerCase())) { + const verified = await resolveInside(root, candidate); + yield verified; + } + } + } + + yield* visit(root, 0); +} diff --git a/packages/media/src/process.ts b/packages/media/src/process.ts new file mode 100644 index 0000000..a8ee8fe --- /dev/null +++ b/packages/media/src/process.ts @@ -0,0 +1,122 @@ +import { spawn } from 'node:child_process'; + +export interface ProcessResult { + code: number; + stdout: string; + stderr: string; +} + +export interface RunProcessOptions { + cwd?: string; + timeoutMs?: number; + maxOutputBytes?: number; + env?: NodeJS.ProcessEnv; + signal?: AbortSignal; +} + +export class ProcessFailure extends Error { + constructor( + message: string, + readonly command: string, + readonly result?: ProcessResult, + ) { + super(message); + this.name = 'ProcessFailure'; + } +} + +const MEDIA_PROCESS_ENV_KEYS = [ + 'PATH', + 'HOME', + 'TMPDIR', + 'TMP', + 'TEMP', + 'LANG', + 'LC_ALL', + 'LD_LIBRARY_PATH', + 'DYLD_LIBRARY_PATH', + 'FONTCONFIG_FILE', + 'FONTCONFIG_PATH', + 'XDG_CACHE_HOME', + 'SSL_CERT_FILE', + 'SSL_CERT_DIR', + // Required for child-process startup on Windows development hosts. + 'SystemRoot', + 'WINDIR', + 'PATHEXT', + 'COMSPEC', +] as const; + +/** Prevents FFmpeg/ffprobe from inheriting database, Redis, or application secrets. */ +export function mediaProcessEnvironment( + source: NodeJS.ProcessEnv = process.env, +): NodeJS.ProcessEnv { + const environment: NodeJS.ProcessEnv = {}; + for (const key of MEDIA_PROCESS_ENV_KEYS) { + const value = source[key]; + if (value !== undefined) environment[key] = value; + } + return environment; +} + +/** Runs a binary directly. Arguments never pass through a shell. */ +export async function runProcess( + binary: string, + args: readonly string[], + options: RunProcessOptions = {}, +): Promise { + const maxOutput = options.maxOutputBytes ?? 16 * 1024 * 1024; + return await new Promise((resolve, reject) => { + const child = spawn(binary, [...args], { + cwd: options.cwd, + env: options.env ?? mediaProcessEnvironment(), + shell: false, + windowsHide: true, + stdio: ['ignore', 'pipe', 'pipe'], + signal: options.signal, + }); + + let stdout = ''; + let stderr = ''; + let stdoutBytes = 0; + let stderrBytes = 0; + let overflow = false; + const append = (current: string, currentBytes: number, chunk: Buffer): [string, number] => { + if (currentBytes + chunk.length > maxOutput) { + overflow = true; + child.kill('SIGKILL'); + return [current, currentBytes]; + } + return [`${current}${chunk.toString('utf8')}`, currentBytes + chunk.length]; + }; + + child.stdout.on('data', (chunk: Buffer) => { + [stdout, stdoutBytes] = append(stdout, stdoutBytes, chunk); + }); + child.stderr.on('data', (chunk: Buffer) => { + [stderr, stderrBytes] = append(stderr, stderrBytes, chunk); + }); + child.once('error', (error) => reject(error)); + + const timer = options.timeoutMs === undefined + ? undefined + : setTimeout(() => child.kill('SIGKILL'), options.timeoutMs); + timer?.unref(); + + child.once('close', (code, signal) => { + if (timer !== undefined) clearTimeout(timer); + const result: ProcessResult = { + code: code ?? -1, + stdout, + stderr, + }; + if (overflow) { + reject(new ProcessFailure(`Process output exceeded ${maxOutput} bytes`, binary, result)); + } else if (code !== 0) { + reject(new ProcessFailure(`${binary} exited with ${String(code)} (${signal ?? 'no signal'})`, binary, result)); + } else { + resolve(result); + } + }); + }); +} diff --git a/packages/media/src/single-flight.ts b/packages/media/src/single-flight.ts new file mode 100644 index 0000000..11e41d2 --- /dev/null +++ b/packages/media/src/single-flight.ts @@ -0,0 +1,44 @@ +export interface DistributedLease { + release(): Promise; +} + +export interface DistributedLock { + acquire(key: string, ttlMs: number): Promise; +} + +export class SingleFlight { + readonly #running = new Map>(); + + run(key: string, operation: () => Promise): Promise { + const existing = this.#running.get(key); + if (existing !== undefined) return existing as Promise; + const promise = operation().finally(() => { + if (this.#running.get(key) === promise) this.#running.delete(key); + }); + this.#running.set(key, promise); + return promise; + } + + has(key: string): boolean { + return this.#running.has(key); + } + + get size(): number { + return this.#running.size; + } +} + +export async function withDistributedSingleFlight( + lock: DistributedLock, + key: string, + ttlMs: number, + operation: () => Promise, +): Promise { + const lease = await lock.acquire(key, ttlMs); + if (lease === undefined) return undefined; + try { + return await operation(); + } finally { + await lease.release(); + } +} diff --git a/packages/media/src/subtitles.ts b/packages/media/src/subtitles.ts new file mode 100644 index 0000000..c7cebdf --- /dev/null +++ b/packages/media/src/subtitles.ts @@ -0,0 +1,127 @@ +import { randomUUID } from 'node:crypto'; +import { readFile, rename } from 'node:fs/promises'; +import path from 'node:path'; +import { normalizeStreamLanguage } from './language.js'; +import { ensureWritableDirectory, resolveInside } from './paths.js'; +import { runProcess } from './process.js'; +import type { ExtractedSubtitle, MediaProbe } from './types.js'; + +const TEXT_SUBTITLE_CODECS = new Set(['ass', 'ssa', 'subrip', 'srt', 'webvtt', 'mov_text']); + +export interface SubtitleExtractionOptions { + archiveRoot: string; + outputRoot: string; + generation: string; + ffmpegPath?: string; + timeoutMs?: number; +} + +export function assDialogueText(ass: string): string { + return ass + .split(/\r?\n/u) + .filter((line) => /^Dialogue\s*:/iu.test(line)) + .map((line) => line.split(',').slice(9).join(',')) + .join('\n'); +} + +export function countAssCues(ass: string): number { + return ass.split(/\r?\n/u).filter((line) => /^Dialogue\s*:/iu.test(line)).length; +} + +export interface SubtitleReadOptions { + archiveRoot: string; + ffmpegPath?: string; + timeoutMs?: number; + maxDurationSeconds?: number; +} + +export function subtitleAssArguments( + source: string, + streamIndex: number, + maxDurationSeconds?: number, +): string[] { + if (!Number.isInteger(streamIndex) || streamIndex < 0) throw new RangeError('streamIndex must be non-negative'); + if (maxDurationSeconds !== undefined + && (!Number.isFinite(maxDurationSeconds) || maxDurationSeconds <= 0 || maxDurationSeconds > 86_400)) { + throw new RangeError('maxDurationSeconds must be greater than 0 and at most 86400'); + } + return [ + '-hide_banner', '-loglevel', 'error', '-nostdin', + '-i', source, + '-map', `0:${streamIndex}`, + ...(maxDurationSeconds === undefined ? [] : ['-t', String(maxDurationSeconds)]), + '-c:s', 'ass', + '-f', 'ass', + 'pipe:1', + ]; +} + +export async function readSubtitleAsAss( + sourcePath: string, + streamIndex: number, + options: SubtitleReadOptions, +): Promise { + const source = await resolveInside(options.archiveRoot, sourcePath); + const result = await runProcess( + options.ffmpegPath ?? 'ffmpeg', + subtitleAssArguments(source, streamIndex, options.maxDurationSeconds), + { timeoutMs: options.timeoutMs ?? 120_000, maxOutputBytes: 16 * 1024 * 1024 }, + ); + return result.stdout; +} + +async function atomicRename(temp: string, destination: string): Promise { + await rename(temp, destination); +} + +export async function extractSubtitleVariants( + sourcePath: string, + probe: MediaProbe, + options: SubtitleExtractionOptions, +): Promise { + const source = await resolveInside(options.archiveRoot, sourcePath); + const directory = await ensureWritableDirectory( + options.outputRoot, + path.join(options.outputRoot, options.generation, 'subtitles'), + ); + const streams = probe.streams.filter( + (stream) => stream.codec_type === 'subtitle' && TEXT_SUBTITLE_CODECS.has(stream.codec_name ?? ''), + ); + const extracted: ExtractedSubtitle[] = []; + + for (const stream of streams) { + const token = randomUUID(); + const tempAss = path.join(directory, `.${stream.index}-${token}.ass`); + const tempVtt = path.join(directory, `.${stream.index}-${token}.vtt`); + await runProcess(options.ffmpegPath ?? 'ffmpeg', [ + '-hide_banner', '-loglevel', 'error', '-nostdin', '-y', + '-i', source, + '-map', `0:${stream.index}`, + '-c:s', 'ass', + tempAss, + ], { timeoutMs: options.timeoutMs ?? 120_000 }); + const ass = await readFile(tempAss, 'utf8'); + const language = normalizeStreamLanguage(stream, assDialogueText(ass)); + const stem = `${String(stream.index).padStart(3, '0')}-${language}`; + const assPath = path.join(directory, `${stem}.ass`); + const vttPath = path.join(directory, `${stem}.vtt`); + await runProcess(options.ffmpegPath ?? 'ffmpeg', [ + '-hide_banner', '-loglevel', 'error', '-nostdin', '-y', + '-i', tempAss, + '-c:s', 'webvtt', + tempVtt, + ], { timeoutMs: options.timeoutMs ?? 120_000 }); + await atomicRename(tempAss, assPath); + await atomicRename(tempVtt, vttPath); + extracted.push({ + streamIndex: stream.index, + language, + assPath, + vttPath, + cueCount: countAssCues(ass), + default: language === 'fa', + forced: false, + }); + } + return extracted; +} diff --git a/packages/media/src/types.ts b/packages/media/src/types.ts new file mode 100644 index 0000000..b38f2a8 --- /dev/null +++ b/packages/media/src/types.ts @@ -0,0 +1,125 @@ +export type CompatibilityClass = + | 'COPY' + | 'AUDIO_TRANSCODE' + | 'VIDEO_TRANSCODE' + | 'HOLD_HDR' + | 'INVALID'; + +export interface ProbeDisposition { + default?: number; + forced?: number; + attached_pic?: number; + [key: string]: number | undefined; +} + +export interface ProbeStream { + index: number; + codec_name?: string; + codec_long_name?: string; + codec_type?: 'video' | 'audio' | 'subtitle' | 'attachment' | string; + profile?: string; + mime_codec_string?: string; + bit_rate?: string; + width?: number; + height?: number; + pix_fmt?: string; + level?: number; + field_order?: string; + avg_frame_rate?: string; + r_frame_rate?: string; + bits_per_raw_sample?: string; + sample_rate?: string; + channels?: number; + channel_layout?: string; + color_transfer?: string; + color_primaries?: string; + color_space?: string; + duration?: string; + extradata_size?: number; + disposition?: ProbeDisposition; + tags?: Record; + side_data_list?: Array>; + [key: string]: unknown; +} + +export interface ProbeFormat { + filename?: string; + format_name?: string; + duration?: string; + size?: string; + bit_rate?: string; + probe_score?: number; + tags?: Record; + [key: string]: unknown; +} + +export interface MediaProbe { + streams: ProbeStream[]; + format: ProbeFormat; + chapters: Array>; +} + +export interface SourceFingerprint { + version: 1; + algorithm: 'sha256'; + relativePath: string; + size: string; + mtimeNs: string; + edgeBytes: number; + digest: string; +} + +export interface NormalizedTrack { + index: number; + type: 'video' | 'audio' | 'subtitle' | 'attachment'; + codec: string; + language: string; + label?: string; + default: boolean; + forced: boolean; +} + +export interface Classification { + class: CompatibilityClass; + reasons: string[]; + videoStreamIndex?: number; + audioStreamIndexes: number[]; +} + +export interface ExtractedSubtitle { + streamIndex: number; + language: string; + assPath: string; + vttPath: string; + cueCount: number; + default: boolean; + forced: boolean; +} + +export interface StoredFont { + streamIndex: number; + sha256: string; + path: string; + originalName: string; + size: number; + format: 'ttf' | 'otf'; +} + +export interface HlsPlaylistValidation { + path: string; + segmentCount: number; + targetDuration: number; + minDuration: number; + maxDuration: number; + totalDuration: number; + ended: boolean; +} + +export interface PackageResult { + generation: string; + outputDirectory: string; + masterPlaylist: string; + videoPlaylist: HlsPlaylistValidation; + audioPlaylists: HlsPlaylistValidation[]; + knownAacRepairs: number; +} diff --git a/packages/media/test/cache-singleflight.test.ts b/packages/media/test/cache-singleflight.test.ts new file mode 100644 index 0000000..babf736 --- /dev/null +++ b/packages/media/test/cache-singleflight.test.ts @@ -0,0 +1,154 @@ +import { mkdtemp, mkdir, readFile, stat, symlink, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { + evictCache, + evictCacheGeneration, + SingleFlight, + touchCacheGeneration, + writeCacheMetadata, +} from '../src/index.js'; + +describe('single flight and cache pressure', () => { + it('shares one running promise per generation', async () => { + const flight = new SingleFlight(); + let calls = 0; + const operation = async (): Promise => { + calls += 1; + await new Promise((resolve) => setTimeout(resolve, 10)); + return 42; + }; + const [left, right] = await Promise.all([flight.run('generation', operation), flight.run('generation', operation)]); + expect([left, right]).toEqual([42, 42]); + expect(calls).toBe(1); + }); + + it('evicts oldest unprotected entries down to the low watermark', async () => { + const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-cache-')); + for (const [key, date, pinned] of [['old', '2020-01-01T00:00:00.000Z', false], ['new', '2021-01-01T00:00:00.000Z', false], ['pin', '2019-01-01T00:00:00.000Z', true]] as const) { + const directory = path.join(root, key); + await mkdir(directory); + await writeFile(path.join(directory, 'data'), Buffer.alloc(40)); + await writeCacheMetadata(root, directory, { key, lastAccessedAt: date, active: false, building: false, pinned, bytes: 40 }); + } + const result = await evictCache(root, { capacityBytes: 100, highWatermark: 0.85, lowWatermark: 0.75 }); + expect(result.evicted).toEqual(['old', 'new']); + expect(result.afterBytes).toBe(40); + }); + + it('evicts only inactive, unpinned cache generations', async () => { + const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-generation-')); + const generations = path.join(root, 'generations'); + const active = path.join(generations, 'active-generation'); + const ready = path.join(generations, 'ready-generation'); + await Promise.all([mkdir(active, { recursive: true }), mkdir(ready, { recursive: true })]); + await Promise.all([writeFile(path.join(active, 'data'), 'active'), writeFile(path.join(ready, 'data'), 'ready')]); + await writeCacheMetadata(generations, active, { key: 'active-generation', lastAccessedAt: new Date().toISOString(), active: true, building: false, pinned: false }); + await writeCacheMetadata(generations, ready, { key: 'ready-generation', lastAccessedAt: new Date().toISOString(), active: false, building: false, pinned: false }); + await expect(evictCacheGeneration(root, 'active-generation')).rejects.toThrow('active'); + expect(await evictCacheGeneration(root, 'ready-generation')).toBe(true); + await expect(stat(ready)).rejects.toMatchObject({ code: 'ENOENT' }); + }); + + it('touches recency and keeps the longest playback protection window', async () => { + const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-generation-touch-')); + const generations = path.join(root, 'generations'); + const generation = '11111111-1111-4111-8111-111111111111'; + const directory = path.join(generations, generation); + await mkdir(directory, { recursive: true }); + await writeFile(path.join(directory, 'data'), 'ready'); + await writeCacheMetadata(generations, directory, { + key: generation, + lastAccessedAt: '2026-01-01T00:00:00.000Z', + protectedUntil: '2999-07-14T10:00:00.000Z', + active: false, + building: false, + pinned: false, + }); + await touchCacheGeneration(root, generation, { + accessedAt: '2026-07-14T09:00:00.000Z', + protectedUntil: '2026-07-14T09:30:00.000Z', + }); + const metadata = JSON.parse(await readFile(path.join(directory, '.cache-entry.json'), 'utf8')); + expect(metadata).toMatchObject({ + lastAccessedAt: '2026-07-14T09:00:00.000Z', + protectedUntil: '2999-07-14T10:00:00.000Z', + }); + await expect(evictCacheGeneration(root, generation)).rejects.toThrow('playback lease'); + }); + + it('protects recently touched entries while evicting older pressure', async () => { + const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-cache-retention-')); + for (const [key, date] of [ + ['old-entry', '2026-07-14T00:00:00.000Z'], + ['recent-entry', '2026-07-14T09:59:00.000Z'], + ] as const) { + const directory = path.join(root, key); + await mkdir(directory); + await writeFile(path.join(directory, 'data'), Buffer.alloc(60)); + await writeCacheMetadata(root, directory, { + key, + lastAccessedAt: date, + active: false, + building: false, + pinned: false, + bytes: 60, + }); + } + const result = await evictCache(root, { + capacityBytes: 100, + highWatermark: 0.85, + lowWatermark: 0.75, + minimumRetentionMs: 60 * 60 * 1000, + now: new Date('2026-07-14T10:00:00.000Z'), + }); + expect(result.evicted).toEqual(['old-entry']); + expect(result.afterBytes).toBe(60); + }); + + it('rejects a planted writable-path symlink without writing outside the cache', async () => { + const base = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-cache-write-link-')); + const root = path.join(base, 'cache'); + const outside = path.join(base, 'outside'); + await Promise.all([mkdir(root), mkdir(outside)]); + const marker = path.join(outside, 'marker'); + await writeFile(marker, 'untouched'); + await symlink(outside, path.join(root, 'linked-entry')); + + await expect(writeCacheMetadata(root, path.join(root, 'linked-entry'), { + key: 'linked-entry', + lastAccessedAt: new Date().toISOString(), + active: false, + building: false, + pinned: false, + bytes: 1, + })).rejects.toThrow(/Symlink found in writable path/u); + + expect(await readFile(marker, 'utf8')).toBe('untouched'); + await expect(stat(path.join(outside, '.cache-entry.json'))).rejects.toMatchObject({ code: 'ENOENT' }); + }); + + it('rejects a planted generations symlink without deleting outside the cache', async () => { + const base = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-cache-delete-link-')); + const root = path.join(base, 'cache'); + const outside = path.join(base, 'outside'); + const generation = '33333333-3333-4333-8333-333333333333'; + const outsideGeneration = path.join(outside, generation); + await Promise.all([mkdir(root), mkdir(outsideGeneration, { recursive: true })]); + const marker = path.join(outsideGeneration, 'marker'); + await writeFile(marker, 'untouched'); + await writeCacheMetadata(outside, outsideGeneration, { + key: generation, + lastAccessedAt: '2020-01-01T00:00:00.000Z', + active: false, + building: false, + pinned: false, + }); + await symlink(outside, path.join(root, 'generations')); + + await expect(evictCacheGeneration(root, generation)).rejects.toThrow(/writable root is a symlink/u); + expect(await readFile(marker, 'utf8')).toBe('untouched'); + await expect(stat(outsideGeneration)).resolves.toBeDefined(); + }); +}); diff --git a/packages/media/test/classify.test.ts b/packages/media/test/classify.test.ts new file mode 100644 index 0000000..ba80783 --- /dev/null +++ b/packages/media/test/classify.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest'; +import { classifyMedia, detectTextLanguage, normalizeLanguage } from '../src/index.js'; +import { audio, probe, video } from './fixtures.js'; + +describe('media compatibility', () => { + it('copy-packages browser-safe H.264 and AAC-LC', () => { + expect(classifyMedia(probe())).toMatchObject({ class: 'COPY', videoStreamIndex: 0, audioStreamIndexes: [1] }); + }); + + it('selects audio-only transcoding for DTS', () => { + expect(classifyMedia(probe([video(), audio({ codec_name: 'dts', profile: undefined })])).class) + .toBe('AUDIO_TRANSCODE'); + }); + + it('selects video transcoding for HEVC SDR', () => { + expect(classifyMedia(probe([video({ codec_name: 'hevc', pix_fmt: 'yuv420p10le' }), audio()])).class) + .toBe('VIDEO_TRANSCODE'); + }); + + it('holds HDR independently of codec', () => { + expect(classifyMedia(probe([video({ color_transfer: 'smpte2084', color_primaries: 'bt2020' }), audio()]))).toMatchObject({ + class: 'HOLD_HDR', reasons: ['HDR_UNSUPPORTED_V1'], + }); + }); + + it('rejects media without an audio stream', () => { + expect(classifyMedia(probe([video()]))).toMatchObject({ class: 'INVALID', reasons: ['NO_AUDIO'] }); + }); +}); + +describe('language normalization', () => { + it('maps ISO-639 aliases', () => { + expect(normalizeLanguage('per')).toBe('fa'); + expect(normalizeLanguage('jpn')).toBe('ja'); + }); + + it('uses script evidence for private or wrong tags', () => { + const english = 'This is enough English dialogue text for reliable script detection.'; + expect(normalizeLanguage('qad', english)).toBe('en'); + expect(normalizeLanguage('eng', 'این یک زیرنویس فارسی برای تشخیص زبان است')).toBe('fa'); + expect(detectTextLanguage('این یک زیرنویس فارسی برای تشخیص زبان است')).toBe('fa'); + expect(detectTextLanguage('هذا نص عربي واضح لاختبار اكتشاف لغة الترجمة العربية')).toBe('ar'); + }); +}); diff --git a/packages/media/test/encode.test.ts b/packages/media/test/encode.test.ts new file mode 100644 index 0000000..c2c67a7 --- /dev/null +++ b/packages/media/test/encode.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest'; +import { buildCompatibilityEncodeArguments, classifyMedia } from '../src/index.js'; +import { audio, probe, video } from './fixtures.js'; + +describe('offline compatibility encode profile', () => { + it('builds same-resolution H.264 CRF18 CMAF with bounded closed GOP and channel-aware AAC', () => { + const media = probe([ + video({ codec_name: 'hevc', pix_fmt: 'yuv420p10le', avg_frame_rate: '24000/1001' }), + audio({ index: 1, codec_name: 'dts', channels: 2 }), + audio({ index: 2, codec_name: 'truehd', channels: 6, tags: { language: 'eng' } }), + ]); + const classification = classifyMedia(media); + const args = buildCompatibilityEncodeArguments('/archive/source.mkv', '/derived/build', media, classification); + expect(args).toContain('libx264'); + expect(args.slice(args.indexOf('-crf'), args.indexOf('-crf') + 2)).toEqual(['-crf', '18']); + expect(args.slice(args.indexOf('-pix_fmt'), args.indexOf('-pix_fmt') + 2)).toEqual(['-pix_fmt', 'yuv420p']); + expect(args.slice(args.indexOf('-g'), args.indexOf('-g') + 2)).toEqual(['-g', '144']); + expect(args).toContain('expr:gte(t,n_forced*6)'); + expect(args.slice(args.indexOf('-b:a:0'), args.indexOf('-b:a:0') + 2)).toEqual(['-b:a:0', '192k']); + expect(args.slice(args.indexOf('-b:a:1'), args.indexOf('-b:a:1') + 2)).toEqual(['-b:a:1', '384k']); + expect(args).toContain('vod'); + expect(args).toContain('fmp4'); + }); + + it('hard-refuses HDR input', () => { + const media = probe([video({ codec_name: 'hevc', color_transfer: 'smpte2084' }), audio()]); + expect(() => buildCompatibilityEncodeArguments('/a', '/b', media, classifyMedia(media))).toThrow('HDR_UNSUPPORTED_V1'); + }); +}); diff --git a/packages/media/test/fixtures.ts b/packages/media/test/fixtures.ts new file mode 100644 index 0000000..e321c24 --- /dev/null +++ b/packages/media/test/fixtures.ts @@ -0,0 +1,44 @@ +import type { MediaProbe, ProbeStream } from '../src/index.js'; + +export function video(overrides: Partial = {}): ProbeStream { + return { + index: 0, + codec_type: 'video', + codec_name: 'h264', + profile: 'High', + mime_codec_string: 'avc1.64001f', + width: 1280, + height: 720, + pix_fmt: 'yuv420p', + bits_per_raw_sample: '8', + field_order: 'progressive', + tags: { BPS: '652016' }, + ...overrides, + }; +} + +export function audio(overrides: Partial = {}): ProbeStream { + return { + index: 1, + codec_type: 'audio', + codec_name: 'aac', + profile: 'LC', + channels: 2, + sample_rate: '48000', + tags: { language: 'jpn', BPS: '200416' }, + ...overrides, + }; +} + +export function probe(streams: ProbeStream[] = [video(), audio()]): MediaProbe { + return { + streams, + format: { + format_name: 'matroska,webm', + duration: '1420.095', + bit_rate: '899640', + probe_score: 100, + }, + chapters: [], + }; +} diff --git a/packages/media/test/fonts.test.ts b/packages/media/test/fonts.test.ts new file mode 100644 index 0000000..07dbf4f --- /dev/null +++ b/packages/media/test/fonts.test.ts @@ -0,0 +1,93 @@ +import { link, mkdtemp, mkdir, readFile, readdir, realpath, stat, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { + extractAndStoreFonts, + fontDumpArguments, + pruneOrphanedFonts, + publishGenerationFonts, + validateSfntFont, +} from '../src/index.js'; +import { probe } from './fixtures.js'; + +function minimalSfnt(): Buffer { + const data = Buffer.alloc(28); + data.writeUInt32BE(0x00010000, 0); + data.writeUInt16BE(1, 4); + data.write('head', 12, 'ascii'); + data.writeUInt32BE(28, 20); + data.writeUInt32BE(0, 24); + return data; +} + +describe('font attachment safety', () => { + it('validates the SFNT directory rather than trusting an extension', () => { + expect(validateSfntFont(minimalSfnt())).toBe('ttf'); + expect(() => validateSfntFont(Buffer.from('not a font'))).toThrow(); + }); + + it('builds a header-only FFmpeg dump command', () => { + const args = fontDumpArguments(4, '/cache/font', '/archive/movie.mkv'); + expect(args).toContain('-dump_attachment:4'); + expect(args.slice(args.indexOf('-i') + 2)).toContain('-t'); + expect(args[args.indexOf('-t') + 1]).toBe('0'); + }); + + it('cleans staging data when extracted font validation fails', async () => { + const base = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-font-')); + const archive = path.join(base, 'archive'); + const fontRoot = path.join(base, 'fonts'); + await mkdir(archive); + const source = path.join(archive, 'movie.mkv'); + await writeFile(source, 'archive'); + const mediaProbe = probe([{ index: 4, codec_type: 'attachment', codec_name: 'ttf', extradata_size: 10, tags: { filename: 'bad.ttf' } }]); + await expect(extractAndStoreFonts(source, mediaProbe, { + archiveRoot: archive, + fontRoot, + async runner(_binary, args) { + const destination = args[args.indexOf('-dump_attachment:4') + 1]; + if (destination === undefined) throw new Error('Missing mock destination'); + await writeFile(destination, 'invalid'); + return { code: 0, stdout: '', stderr: '' }; + }, + })).rejects.toThrow('Font size'); + expect(await readdir(path.join(fontRoot, '.staging'))).toEqual([]); + }); + + it('publishes deduplicated fonts under the signed generation path', async () => { + const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-font-publish-')); + const sourceDirectory = path.join(root, 'assets', 'fonts', 'sha256'); + const generation = path.join(root, 'generations', '11111111-1111-4111-8111-111111111111'); + await Promise.all([mkdir(sourceDirectory, { recursive: true }), mkdir(generation, { recursive: true })]); + const data = minimalSfnt(); + const sha256 = 'a'.repeat(64); + const source = path.join(sourceDirectory, `${sha256}.ttf`); + await writeFile(source, data); + const font = { streamIndex: 4, sha256, path: source, originalName: 'source.ttf', size: data.length, format: 'ttf' as const }; + const first = await publishGenerationFonts([font], root, generation); + const second = await publishGenerationFonts([font], root, generation); + expect(first[0]?.path).toBe(path.join(await realpath(generation), 'fonts', `${sha256}.ttf`)); + expect(second[0]?.path).toBe(first[0]?.path); + expect(await readFile(first[0]!.path)).toEqual(data); + }); + + it('prunes only global fonts with no generation hardlinks', async () => { + const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-font-prune-')); + const store = path.join(root, 'assets', 'fonts', 'sha256'); + const generationFonts = path.join(root, 'generations', 'generation-id', 'fonts'); + await Promise.all([mkdir(store, { recursive: true }), mkdir(generationFonts, { recursive: true })]); + const orphan = `${'a'.repeat(64)}.ttf`; + const retained = `${'b'.repeat(64)}.otf`; + await Promise.all([ + writeFile(path.join(store, orphan), minimalSfnt()), + writeFile(path.join(store, retained), minimalSfnt()), + ]); + await link(path.join(store, retained), path.join(generationFonts, retained)); + const result = await pruneOrphanedFonts(root, { minimumAgeMs: 0, now: new Date(Date.now() + 1000) }); + expect(result.removed).toEqual([orphan]); + expect(result.retainedBytes).toBe(minimalSfnt().length); + await expect(stat(path.join(store, orphan))).rejects.toMatchObject({ code: 'ENOENT' }); + expect((await stat(path.join(store, retained))).nlink).toBe(2); + }); +}); diff --git a/packages/media/test/hls.test.ts b/packages/media/test/hls.test.ts new file mode 100644 index 0000000..639ffab --- /dev/null +++ b/packages/media/test/hls.test.ts @@ -0,0 +1,71 @@ +import { mkdtemp, mkdir, readFile, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { + assessFfmpegWarnings, + buildMasterPlaylist, + finalizeEventPlaylist, + parseMediaPlaylist, + validateMediaPlaylist, +} from '../src/index.js'; +import { audio, probe, video } from './fixtures.js'; + +async function playlistFixture(): Promise { + const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-hls-')); + await Promise.all([ + writeFile(path.join(directory, 'init.mp4'), 'init'), + writeFile(path.join(directory, 'segment-000.m4s'), 'one'), + writeFile(path.join(directory, 'segment-001.m4s'), 'two'), + ]); + const playlist = path.join(directory, 'index.m3u8'); + await writeFile(playlist, [ + '#EXTM3U', '#EXT-X-VERSION:7', '#EXT-X-TARGETDURATION:10', '#EXT-X-PLAYLIST-TYPE:EVENT', + '#EXT-X-MAP:URI="init.mp4"', '#EXTINF:9.2,', 'segment-000.m4s', '#EXTINF:4.0,', + 'segment-001.m4s', '#EXT-X-ENDLIST', '', + ].join('\n')); + return playlist; +} + +describe('HLS validation', () => { + it('checks all local fMP4 references and finalizes EVENT to VOD atomically', async () => { + const playlist = await playlistFixture(); + const result = await validateMediaPlaylist(playlist, { requireEnded: true, minSegments: 2, maxTargetDuration: 18 }); + expect(result).toMatchObject({ segmentCount: 2, maxDuration: 9.2, totalDuration: 13.2 }); + await finalizeEventPlaylist(playlist); + expect(await readFile(playlist, 'utf8')).toContain('#EXT-X-PLAYLIST-TYPE:VOD'); + }); + + it('rejects traversal and remote segment URIs', async () => { + const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-hls-unsafe-')); + await writeFile(path.join(directory, 'init.mp4'), 'init'); + const traversal = path.join(directory, 'traversal.m3u8'); + await writeFile(traversal, '#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXT-X-MAP:URI="init.mp4"\n#EXTINF:5,\n../secret.m4s'); + await expect(validateMediaPlaylist(traversal)).rejects.toThrow('Unsafe or external HLS URI'); + const remote = path.join(directory, 'remote.m3u8'); + await writeFile(remote, '#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXT-X-MAP:URI="init.mp4"\n#EXTINF:5,\nhttps://evil.invalid/a.m4s'); + await expect(validateMediaPlaylist(remote)).rejects.toThrow('Unsafe or external HLS URI'); + }); + + it('permits only the bounded -32 AAC rounding warning', () => { + const known = assessFfmpegWarnings('[mp4 @ a] Packet duration: -32 / dts: 580456 in stream 0 is out of range'); + expect(known).toMatchObject({ knownAacRepairs: 1, unknown: [] }); + expect(assessFfmpegWarnings('[mp4 @ a] Packet duration: -64 / dts: 10 in stream 0 is out of range').unknown) + .toHaveLength(1); + expect(assessFfmpegWarnings('Non-monotonous DTS').unknown).toHaveLength(1); + }); + + it('uses declared/container bitrate and a conservative video fallback', () => { + const declared = buildMasterPlaylist(probe(), 0, 'video/index.m3u8', [{ + streamIndex: 1, language: 'ja', name: 'Japanese', uri: 'audio/index.m3u8', default: true, + }]); + expect(declared).toContain('AVERAGE-BANDWIDTH=852432'); + const missing = probe([video({ tags: {}, bit_rate: undefined }), audio({ tags: {}, bit_rate: undefined })]); + missing.format.bit_rate = undefined; + const conservative = buildMasterPlaylist(missing, 0, 'video/index.m3u8', [{ + streamIndex: 1, language: 'ja', name: 'Japanese', uri: 'audio/index.m3u8', default: true, + }]); + const bandwidth = Number(conservative.match(/BANDWIDTH=(\d+)/u)?.[1]); + expect(bandwidth).toBeGreaterThan(8_000_000); + }); +}); diff --git a/packages/media/test/paths-fingerprint.test.ts b/packages/media/test/paths-fingerprint.test.ts new file mode 100644 index 0000000..3827b84 --- /dev/null +++ b/packages/media/test/paths-fingerprint.test.ts @@ -0,0 +1,34 @@ +import { mkdtemp, mkdir, realpath, symlink, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { fingerprintSource, isPathInside, walkArchive } from '../src/index.js'; + +describe('archive boundaries', () => { + it('walks regular MKV files without following symlinks', async () => { + const base = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-walk-')); + const root = path.join(base, 'archive'); + const outside = path.join(base, 'outside'); + await Promise.all([mkdir(path.join(root, 'series'), { recursive: true }), mkdir(outside)]); + await writeFile(path.join(root, 'series', 'one.mkv'), 'safe'); + await writeFile(path.join(outside, 'secret.mkv'), 'secret'); + await symlink(path.join(outside, 'secret.mkv'), path.join(root, 'linked.mkv')); + const files: string[] = []; + for await (const file of walkArchive(root)) files.push(file); + expect(files).toEqual([await realpath(path.join(root, 'series', 'one.mkv'))]); + expect(isPathInside(root, path.join(root, 'series', 'one.mkv'))).toBe(true); + expect(isPathInside(root, path.join(outside, 'secret.mkv'))).toBe(false); + }); + + it('fingerprints path, stat and both file edges', async () => { + const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-fingerprint-')); + const source = path.join(root, 'movie.mkv'); + await writeFile(source, 'HEAD-middle-TAIL'); + const first = await fingerprintSource(root, source, 4); + const same = await fingerprintSource(root, source, 4); + expect(same.digest).toBe(first.digest); + await writeFile(source, 'HEAd-middle-TAIL'); + const changed = await fingerprintSource(root, source, 4); + expect(changed.digest).not.toBe(first.digest); + }); +}); diff --git a/packages/media/test/process.test.ts b/packages/media/test/process.test.ts new file mode 100644 index 0000000..f3b2ea6 --- /dev/null +++ b/packages/media/test/process.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest'; +import { mediaProcessEnvironment } from '../src/index.js'; + +describe('media child process environment', () => { + it('keeps runtime paths but strips application secrets', () => { + expect(mediaProcessEnvironment({ + PATH: '/usr/bin', + LD_LIBRARY_PATH: '/opt/ffmpeg/lib', + DATABASE_URL: 'postgres://secret', + REDIS_URL: 'redis://secret', + PLAYBACK_SIGNING_SECRET: 'secret', + })).toEqual({ + PATH: '/usr/bin', + LD_LIBRARY_PATH: '/opt/ffmpeg/lib', + }); + }); +}); diff --git a/packages/media/test/subtitles.test.ts b/packages/media/test/subtitles.test.ts new file mode 100644 index 0000000..8101dff --- /dev/null +++ b/packages/media/test/subtitles.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest'; +import { subtitleAssArguments } from '../src/index.js'; + +describe('bounded subtitle inspection', () => { + it('adds a numeric output duration only when requested', () => { + const bounded = subtitleAssArguments('/archive/movie.mkv', 3, 600); + expect(bounded.slice(bounded.indexOf('-t'), bounded.indexOf('-t') + 2)).toEqual(['-t', '600']); + expect(bounded).toContain('0:3'); + expect(subtitleAssArguments('/archive/movie.mkv', 3)).not.toContain('-t'); + }); + + it('rejects invalid stream and duration values before invoking FFmpeg', () => { + expect(() => subtitleAssArguments('/archive/movie.mkv', -1, 600)).toThrow('streamIndex'); + expect(() => subtitleAssArguments('/archive/movie.mkv', 2, Number.POSITIVE_INFINITY)).toThrow('maxDurationSeconds'); + expect(() => subtitleAssArguments('/archive/movie.mkv', 2, 86_401)).toThrow('maxDurationSeconds'); + }); +}); diff --git a/packages/media/tsconfig.json b/packages/media/tsconfig.json new file mode 100644 index 0000000..b0c55e9 --- /dev/null +++ b/packages/media/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist", + "types": ["node"] + }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.test.ts"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..f9bb011 --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,3565 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + devDependencies: + typescript: + specifier: ^5.9.3 + version: 5.9.3 + vitest: + specifier: ^3.2.4 + version: 3.2.7(@types/node@24.13.3)(jsdom@26.1.0)(tsx@4.23.1) + + apps/api: + dependencies: + '@easy-stream/contracts': + specifier: workspace:* + version: link:../../packages/contracts + '@easy-stream/database': + specifier: workspace:* + version: link:../../packages/database + '@fastify/cookie': + specifier: ^11.0.2 + version: 11.1.1 + '@fastify/cors': + specifier: ^11.1.0 + version: 11.3.0 + '@fastify/helmet': + specifier: ^13.0.2 + version: 13.1.0 + '@fastify/rate-limit': + specifier: ^10.3.0 + version: 10.3.0 + '@sinclair/typebox': + specifier: ^0.34.41 + version: 0.34.52 + argon2: + specifier: ^0.44.0 + version: 0.44.0 + bullmq: + specifier: ^5.61.2 + version: 5.80.2 + drizzle-orm: + specifier: ^0.45.2 + version: 0.45.2(postgres@3.4.9) + fastify: + specifier: ^5.6.1 + version: 5.10.0 + devDependencies: + '@types/node': + specifier: ^24.7.2 + version: 24.13.3 + tsx: + specifier: ^4.20.6 + version: 4.23.1 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + vitest: + specifier: ^3.2.4 + version: 3.2.7(@types/node@24.13.3)(jsdom@26.1.0)(tsx@4.23.1) + + apps/web: + dependencies: + '@fontsource/vazirmatn': + specifier: ^5.2.8 + version: 5.2.8 + hls.js: + specifier: ^1.6.15 + version: 1.6.16 + jassub: + specifier: ^2.5.7 + version: 2.5.7 + pinia: + specifier: ^3.0.3 + version: 3.0.4(typescript@5.9.3)(vue@3.5.39(typescript@5.9.3)) + vue: + specifier: ^3.5.22 + version: 3.5.39(typescript@5.9.3) + vue-router: + specifier: ^4.6.3 + version: 4.6.4(vue@3.5.39(typescript@5.9.3)) + devDependencies: + '@vitejs/plugin-vue': + specifier: ^6.0.1 + version: 6.0.7(vite@7.3.6(@types/node@24.13.3)(tsx@4.23.1))(vue@3.5.39(typescript@5.9.3)) + '@vue/test-utils': + specifier: ^2.4.6 + version: 2.4.11(@vue/compiler-dom@3.5.39)(@vue/server-renderer@3.5.39(vue@3.5.39(typescript@5.9.3)))(vue@3.5.39(typescript@5.9.3)) + jsdom: + specifier: ^26.1.0 + version: 26.1.0 + vite: + specifier: ^7.1.9 + version: 7.3.6(@types/node@24.13.3)(tsx@4.23.1) + vitest: + specifier: ^3.2.4 + version: 3.2.7(@types/node@24.13.3)(jsdom@26.1.0)(tsx@4.23.1) + vue-tsc: + specifier: ^3.1.1 + version: 3.3.7(typescript@5.9.3) + + apps/worker: + dependencies: + '@easy-stream/contracts': + specifier: workspace:* + version: link:../../packages/contracts + '@easy-stream/database': + specifier: workspace:* + version: link:../../packages/database + '@easy-stream/media': + specifier: workspace:* + version: link:../../packages/media + '@sinclair/typebox': + specifier: ^0.34.41 + version: 0.34.52 + bullmq: + specifier: ^5.61.2 + version: 5.80.2 + ioredis: + specifier: ^5.10.1 + version: 5.10.1 + devDependencies: + '@types/node': + specifier: ^24.10.0 + version: 24.13.3 + tsx: + specifier: ^4.20.6 + version: 4.23.1 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + vitest: + specifier: ^3.2.4 + version: 3.2.7(@types/node@24.13.3)(jsdom@26.1.0)(tsx@4.23.1) + + packages/contracts: + dependencies: + '@sinclair/typebox': + specifier: ^0.34.41 + version: 0.34.52 + devDependencies: + typescript: + specifier: ^5.9.3 + version: 5.9.3 + vitest: + specifier: ^3.2.4 + version: 3.2.7(@types/node@24.13.3)(jsdom@26.1.0)(tsx@4.23.1) + + packages/database: + dependencies: + '@easy-stream/contracts': + specifier: workspace:* + version: link:../contracts + '@sinclair/typebox': + specifier: ^0.34.41 + version: 0.34.52 + drizzle-orm: + specifier: ^0.45.2 + version: 0.45.2(postgres@3.4.9) + postgres: + specifier: ^3.4.7 + version: 3.4.9 + devDependencies: + drizzle-kit: + specifier: ^0.31.10 + version: 0.31.10 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + vitest: + specifier: ^3.2.4 + version: 3.2.7(@types/node@24.13.3)(jsdom@26.1.0)(tsx@4.23.1) + + packages/media: + devDependencies: + '@types/node': + specifier: ^24.10.0 + version: 24.13.3 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + vitest: + specifier: ^3.2.4 + version: 3.2.7(@types/node@24.13.3)(jsdom@26.1.0)(tsx@4.23.1) + +packages: + + '@asamuzakjp/css-color@3.2.0': + resolution: {integrity: sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==} + + '@babel/helper-string-parser@7.29.7': + resolution: {integrity: sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-identifier@7.29.7': + resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} + engines: {node: '>=6.9.0'} + + '@babel/parser@7.29.7': + resolution: {integrity: sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==} + engines: {node: '>=6.0.0'} + hasBin: true + + '@babel/types@7.29.7': + resolution: {integrity: sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==} + engines: {node: '>=6.9.0'} + + '@csstools/color-helpers@5.1.0': + resolution: {integrity: sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==} + engines: {node: '>=18'} + + '@csstools/css-calc@2.1.4': + resolution: {integrity: sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==} + engines: {node: '>=18'} + peerDependencies: + '@csstools/css-parser-algorithms': ^3.0.5 + '@csstools/css-tokenizer': ^3.0.4 + + '@csstools/css-color-parser@3.1.0': + resolution: {integrity: sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==} + engines: {node: '>=18'} + peerDependencies: + '@csstools/css-parser-algorithms': ^3.0.5 + '@csstools/css-tokenizer': ^3.0.4 + + '@csstools/css-parser-algorithms@3.0.5': + resolution: {integrity: sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==} + engines: {node: '>=18'} + peerDependencies: + '@csstools/css-tokenizer': ^3.0.4 + + '@csstools/css-tokenizer@3.0.4': + resolution: {integrity: sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==} + engines: {node: '>=18'} + + '@drizzle-team/brocli@0.10.2': + resolution: {integrity: sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w==} + + '@epic-web/invariant@1.0.0': + resolution: {integrity: sha512-lrTPqgvfFQtR/eY/qkIzp98OGdNJu0m5ji3q/nJI8v3SXkRKEnWiOxMmbvcSoAIzv/cGiuvRy57k4suKQSAdwA==} + + '@esbuild-kit/core-utils@3.3.2': + resolution: {integrity: sha512-sPRAnw9CdSsRmEtnsl2WXWdyquogVpB3yZ3dgwJfe8zrOzTsV7cJvmwrKVa+0ma5BoiGJ+BoqkMvawbayKUsqQ==} + deprecated: 'Merged into tsx: https://tsx.hirok.io' + + '@esbuild-kit/esm-loader@2.6.5': + resolution: {integrity: sha512-FxEMIkJKnodyA1OaCUoEvbYRkoZlLZ4d/eXFu9Fh8CbBBgP5EmZxrfTRyN0qpXZ4vOvqnE5YdRdcrmUUXuU+dA==} + deprecated: 'Merged into tsx: https://tsx.hirok.io' + + '@esbuild/aix-ppc64@0.25.12': + resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/aix-ppc64@0.28.1': + resolution: {integrity: sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.18.20': + resolution: {integrity: sha512-Nz4rJcchGDtENV0eMKUNa6L12zz2zBDXuhj/Vjh18zGqB44Bi7MBMSXjgunJgjRhCmKOjnPuZp4Mb6OKqtMHLQ==} + engines: {node: '>=12'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm64@0.25.12': + resolution: {integrity: sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm64@0.28.1': + resolution: {integrity: sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.18.20': + resolution: {integrity: sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw==} + engines: {node: '>=12'} + cpu: [arm] + os: [android] + + '@esbuild/android-arm@0.25.12': + resolution: {integrity: sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-arm@0.28.1': + resolution: {integrity: sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.18.20': + resolution: {integrity: sha512-8GDdlePJA8D6zlZYJV/jnrRAi6rOiNaCC/JclcXpB+KIuvfBN4owLtgzY2bsxnx666XjJx2kDPUmnTtR8qKQUg==} + engines: {node: '>=12'} + cpu: [x64] + os: [android] + + '@esbuild/android-x64@0.25.12': + resolution: {integrity: sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/android-x64@0.28.1': + resolution: {integrity: sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.18.20': + resolution: {integrity: sha512-bxRHW5kHU38zS2lPTPOyuyTm+S+eobPUnTNkdJEfAddYgEcll4xkT8DB9d2008DtTbl7uJag2HuE5NZAZgnNEA==} + engines: {node: '>=12'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-arm64@0.25.12': + resolution: {integrity: sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-arm64@0.28.1': + resolution: {integrity: sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.18.20': + resolution: {integrity: sha512-pc5gxlMDxzm513qPGbCbDukOdsGtKhfxD1zJKXjCCcU7ju50O7MeAZ8c4krSJcOIJGFR+qx21yMMVYwiQvyTyQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [darwin] + + '@esbuild/darwin-x64@0.25.12': + resolution: {integrity: sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/darwin-x64@0.28.1': + resolution: {integrity: sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.18.20': + resolution: {integrity: sha512-yqDQHy4QHevpMAaxhhIwYPMv1NECwOvIpGCZkECn8w2WFHXjEwrBn3CeNIYsibZ/iZEUemj++M26W3cNR5h+Tw==} + engines: {node: '>=12'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-arm64@0.25.12': + resolution: {integrity: sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-arm64@0.28.1': + resolution: {integrity: sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.18.20': + resolution: {integrity: sha512-tgWRPPuQsd3RmBZwarGVHZQvtzfEBOreNuxEMKFcd5DaDn2PbBxfwLcj4+aenoh7ctXcbXmOQIn8HI6mCSw5MQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.25.12': + resolution: {integrity: sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.28.1': + resolution: {integrity: sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.18.20': + resolution: {integrity: sha512-2YbscF+UL7SQAVIpnWvYwM+3LskyDmPhe31pE7/aoTMFKKzIc9lLbyGUpmmb8a8AixOL61sQ/mFh3jEjHYFvdA==} + engines: {node: '>=12'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm64@0.25.12': + resolution: {integrity: sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm64@0.28.1': + resolution: {integrity: sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.18.20': + resolution: {integrity: sha512-/5bHkMWnq1EgKr1V+Ybz3s1hWXok7mDFUMQ4cG10AfW3wL02PSZi5kFpYKrptDsgb2WAJIvRcDm+qIvXf/apvg==} + engines: {node: '>=12'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-arm@0.25.12': + resolution: {integrity: sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-arm@0.28.1': + resolution: {integrity: sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.18.20': + resolution: {integrity: sha512-P4etWwq6IsReT0E1KHU40bOnzMHoH73aXp96Fs8TIT6z9Hu8G6+0SHSw9i2isWrD2nbx2qo5yUqACgdfVGx7TA==} + engines: {node: '>=12'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-ia32@0.25.12': + resolution: {integrity: sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-ia32@0.28.1': + resolution: {integrity: sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.18.20': + resolution: {integrity: sha512-nXW8nqBTrOpDLPgPY9uV+/1DjxoQ7DoB2N8eocyq8I9XuqJ7BiAMDMf9n1xZM9TgW0J8zrquIb/A7s3BJv7rjg==} + engines: {node: '>=12'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-loong64@0.25.12': + resolution: {integrity: sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-loong64@0.28.1': + resolution: {integrity: sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.18.20': + resolution: {integrity: sha512-d5NeaXZcHp8PzYy5VnXV3VSd2D328Zb+9dEq5HE6bw6+N86JVPExrA6O68OPwobntbNJ0pzCpUFZTo3w0GyetQ==} + engines: {node: '>=12'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-mips64el@0.25.12': + resolution: {integrity: sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-mips64el@0.28.1': + resolution: {integrity: sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.18.20': + resolution: {integrity: sha512-WHPyeScRNcmANnLQkq6AfyXRFr5D6N2sKgkFo2FqguP44Nw2eyDlbTdZwd9GYk98DZG9QItIiTlFLHJHjxP3FA==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-ppc64@0.25.12': + resolution: {integrity: sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-ppc64@0.28.1': + resolution: {integrity: sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.18.20': + resolution: {integrity: sha512-WSxo6h5ecI5XH34KC7w5veNnKkju3zBRLEQNY7mv5mtBmrP/MjNBCAlsM2u5hDBlS3NGcTQpoBvRzqBcRtpq1A==} + engines: {node: '>=12'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-riscv64@0.25.12': + resolution: {integrity: sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-riscv64@0.28.1': + resolution: {integrity: sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.18.20': + resolution: {integrity: sha512-+8231GMs3mAEth6Ja1iK0a1sQ3ohfcpzpRLH8uuc5/KVDFneH6jtAJLFGafpzpMRO6DzJ6AvXKze9LfFMrIHVQ==} + engines: {node: '>=12'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-s390x@0.25.12': + resolution: {integrity: sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-s390x@0.28.1': + resolution: {integrity: sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.18.20': + resolution: {integrity: sha512-UYqiqemphJcNsFEskc73jQ7B9jgwjWrSayxawS6UVFZGWrAAtkzjxSqnoclCXxWtfwLdzU+vTpcNYhpn43uP1w==} + engines: {node: '>=12'} + cpu: [x64] + os: [linux] + + '@esbuild/linux-x64@0.25.12': + resolution: {integrity: sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/linux-x64@0.28.1': + resolution: {integrity: sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-arm64@0.25.12': + resolution: {integrity: sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-arm64@0.28.1': + resolution: {integrity: sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.18.20': + resolution: {integrity: sha512-iO1c++VP6xUBUmltHZoMtCUdPlnPGdBom6IrO4gyKPFFVBKioIImVooR5I83nTew5UOYrk3gIJhbZh8X44y06A==} + engines: {node: '>=12'} + cpu: [x64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.25.12': + resolution: {integrity: sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.28.1': + resolution: {integrity: sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-arm64@0.25.12': + resolution: {integrity: sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-arm64@0.28.1': + resolution: {integrity: sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.18.20': + resolution: {integrity: sha512-e5e4YSsuQfX4cxcygw/UCPIEP6wbIL+se3sxPdCiMbFLBWu0eiZOJ7WoD+ptCLrmjZBK1Wk7I6D/I3NglUGOxg==} + engines: {node: '>=12'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.25.12': + resolution: {integrity: sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.28.1': + resolution: {integrity: sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.25.12': + resolution: {integrity: sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/openharmony-arm64@0.28.1': + resolution: {integrity: sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.18.20': + resolution: {integrity: sha512-kDbFRFp0YpTQVVrqUd5FTYmWo45zGaXe0X8E1G/LKFC0v8x0vWrhOWSLITcCn63lmZIxfOMXtCfti/RxN/0wnQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [sunos] + + '@esbuild/sunos-x64@0.25.12': + resolution: {integrity: sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/sunos-x64@0.28.1': + resolution: {integrity: sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.18.20': + resolution: {integrity: sha512-ddYFR6ItYgoaq4v4JmQQaAI5s7npztfV4Ag6NrhiaW0RrnOXqBkgwZLofVTlq1daVTQNhtI5oieTvkRPfZrePg==} + engines: {node: '>=12'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-arm64@0.25.12': + resolution: {integrity: sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-arm64@0.28.1': + resolution: {integrity: sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.18.20': + resolution: {integrity: sha512-Wv7QBi3ID/rROT08SABTS7eV4hX26sVduqDOTe1MvGMjNd3EjOz4b7zeexIR62GTIEKrfJXKL9LFxTYgkyeu7g==} + engines: {node: '>=12'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-ia32@0.25.12': + resolution: {integrity: sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-ia32@0.28.1': + resolution: {integrity: sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.18.20': + resolution: {integrity: sha512-kTdfRcSiDfQca/y9QIkng02avJ+NCaQvrMejlsB3RRv5sE9rRoeBPISaZpKxHELzRxZyLvNts1P27W3wV+8geQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [win32] + + '@esbuild/win32-x64@0.25.12': + resolution: {integrity: sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@esbuild/win32-x64@0.28.1': + resolution: {integrity: sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@fastify/ajv-compiler@4.0.5': + resolution: {integrity: sha512-KoWKW+MhvfTRWL4qrhUwAAZoaChluo0m0vbiJlGMt2GXvL4LVPQEjt8kSpHI3IBq5Rez8fg+XeH3cneztq+C7A==} + + '@fastify/cookie@11.1.1': + resolution: {integrity: sha512-sJ0NXzGVYjUB4OynPZRsIcQ1mKSP4rW45xLCN0aelRq5Vl37xVVbz5kJ6Y0a9m2T0mCUjYCuvlUA9QlTafrZWw==} + + '@fastify/cors@11.3.0': + resolution: {integrity: sha512-ggQGua+xHv1MvePbPr0v//xLYEsCXbWspquXCJS9Ot5YoRXq8J8ZWzHnxDBVnbtXosvistXo6LtNzOJswf64Fw==} + + '@fastify/error@4.2.0': + resolution: {integrity: sha512-RSo3sVDXfHskiBZKBPRgnQTtIqpi/7zhJOEmAxCiBcM7d0uwdGdxLlsCaLzGs8v8NnxIRlfG0N51p5yFaOentQ==} + + '@fastify/fast-json-stringify-compiler@5.1.0': + resolution: {integrity: sha512-PxcYtKLbQ8Z+yApiqjK8FwxIwvEj38k2OiLc17u8dkJSlmfi2wHHPaSnaoqBPQqtvF8YVsDgDpP2snDCfFrpfw==} + + '@fastify/forwarded@3.0.1': + resolution: {integrity: sha512-JqDochHFqXs3C3Ml3gOY58zM7OqO9ENqPo0UqAjAjH8L01fRZqwX9iLeX34//kiJubF7r2ZQHtBRU36vONbLlw==} + + '@fastify/helmet@13.1.0': + resolution: {integrity: sha512-SvVOU0IrzYJW1BvSkfq9G1WUdW3dnaRUvg6m0BtgGMBmML62No0VmSu087jecH58SFbicbREgZTPJ89mAguupA==} + + '@fastify/merge-json-schemas@0.2.1': + resolution: {integrity: sha512-OA3KGBCy6KtIvLf8DINC5880o5iBlDX4SxzLQS8HorJAbqluzLRn80UXU0bxZn7UOFhFgpRJDasfwn9nG4FG4A==} + + '@fastify/proxy-addr@5.1.0': + resolution: {integrity: sha512-INS+6gh91cLUjB+PVHfu1UqcB76Sqtpyp7bnL+FYojhjygvOPA9ctiD/JDKsyD9Xgu4hUhCSJBPig/w7duNajw==} + + '@fastify/rate-limit@10.3.0': + resolution: {integrity: sha512-eIGkG9XKQs0nyynatApA3EVrojHOuq4l6fhB4eeCk4PIOeadvOJz9/4w3vGI44Go17uaXOWEcPkaD8kuKm7g6Q==} + + '@fontsource/vazirmatn@5.2.8': + resolution: {integrity: sha512-WoDgv8R/y1gwgTS8Q2uL8d2ayeSGNv2IrYQ4wHmJkVwYPb8KVODrqbbvEjBqLOo5WP5kLJIrO06FRDMnSFuCaA==} + + '@ioredis/commands@1.5.1': + resolution: {integrity: sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw==} + + '@isaacs/cliui@8.0.2': + resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==} + engines: {node: '>=12'} + + '@jridgewell/sourcemap-codec@1.5.5': + resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} + + '@lukeed/ms@2.0.2': + resolution: {integrity: sha512-9I2Zn6+NJLfaGoz9jN3lpwDgAYvfGeNYdbAIjJOqzs4Tpc+VU3Jqq4IofSUBKajiDS8k9fZIg18/z13mpk1bsA==} + engines: {node: '>=8'} + + '@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.4': + resolution: {integrity: sha512-LCkGo6JDfaBhgST7UpPWgNgLINpcpabaHfyz5OBx75nUYxBsaEPxjnyNjWpeb/xBup/682QnBfRBy2/LvPutZQ==} + cpu: [arm64] + os: [darwin] + + '@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.4': + resolution: {integrity: sha512-zExlW9zUJKZH/tOtVMttwjKa4Xm/3KcNjnE3dPN92uCktwavMxpgCA3MoJK/DOnTWsQgo224OaST27/mPNAf+w==} + cpu: [x64] + os: [darwin] + + '@msgpackr-extract/msgpackr-extract-linux-arm64@3.0.4': + resolution: {integrity: sha512-dgX0P/9wGPJeHFBG+ZmhgE6bmtMt7NP5CRBGyyktpopdk/mW4POnrpQsSLtKI1dwpc+pPLuXHDh6vvskyQE/sw==} + cpu: [arm64] + os: [linux] + + '@msgpackr-extract/msgpackr-extract-linux-arm@3.0.4': + resolution: {integrity: sha512-Tg3yX65f5GbtXLkrYEHE5oibZG9epyYWas7FogTTEJeDEF9JlXJzKgXaNhT3UXlTOeA+AfZpYZYZ0uPj7Cfquw==} + cpu: [arm] + os: [linux] + + '@msgpackr-extract/msgpackr-extract-linux-x64@3.0.4': + resolution: {integrity: sha512-8TNXMEjJc3QEy7R/x1INhgiU+XakDAFUzBhaz7+Rbrs8NH5UQeHQxxmzsSBJGyV6I1jW79undiQm8tOI+D+8FQ==} + cpu: [x64] + os: [linux] + + '@msgpackr-extract/msgpackr-extract-win32-x64@3.0.4': + resolution: {integrity: sha512-CmCXPQrkbwExx3j946/PtHWHbYJiCRBRDl4BlkRQcJB/YOwQxJRTpoo7aTsortjgoJ1x7opzTSxn7C+ASSLVjQ==} + cpu: [x64] + os: [win32] + + '@one-ini/wasm@0.1.1': + resolution: {integrity: sha512-XuySG1E38YScSJoMlqovLru4KTUNSjgVTIjyh7qMX6aNN5HY5Ct5LhRJdxO79JtTzKfzV/bnWpz+zquYrISsvw==} + + '@phc/format@1.0.0': + resolution: {integrity: sha512-m7X9U6BG2+J+R1lSOdCiITLLrxm+cWlNI3HUFA92oLO77ObGNzaKdh8pMLqdZcshtkKuV84olNNXDfMc4FezBQ==} + engines: {node: '>=10'} + + '@pinojs/redact@0.4.0': + resolution: {integrity: sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==} + + '@pkgjs/parseargs@0.11.0': + resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==} + engines: {node: '>=14'} + + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + + '@rollup/rollup-android-arm-eabi@4.62.2': + resolution: {integrity: sha512-6o7ZLZK+BeenkZCFNDXqpbjw9bD6nuWonvS/lwQJp7NoVVxm6p3qE7qQ5jGuBjiFsgvqjD8mZAU5oWxTmbOeOg==} + cpu: [arm] + os: [android] + + '@rollup/rollup-android-arm64@4.62.2': + resolution: {integrity: sha512-BaH7BllCACHoH1LguOU56UItGfUWjujlO65kS9LAodViaN4bwIKd7oeW/ZHJ/4ljr/7MIiENnNy3HJ0zXv8Zkw==} + cpu: [arm64] + os: [android] + + '@rollup/rollup-darwin-arm64@4.62.2': + resolution: {integrity: sha512-v39RCCvj4He82I9sFmk+M1VZ0PLM9sfsLVikjfx2hYBNALhrrOR2D3JjQA6AhlaSOgcR+RzrKY7e1+bT6SUO/A==} + cpu: [arm64] + os: [darwin] + + '@rollup/rollup-darwin-x64@4.62.2': + resolution: {integrity: sha512-yl0y2vq3S3lHeuXhEdss6TWfKW8vkujImO12tn4ZkG/4oghr09LvdYm2RElVjokTQiUvDUGXLGsYeLqUMCKpGA==} + cpu: [x64] + os: [darwin] + + '@rollup/rollup-freebsd-arm64@4.62.2': + resolution: {integrity: sha512-tT4pvt4qXD+vEoezupCWi+a1F0vvDiksiHc+PxRlYTOH1I6/X4id9jPxTP+Fg+545euaFT1jJVs4CEdHZAU1vw==} + cpu: [arm64] + os: [freebsd] + + '@rollup/rollup-freebsd-x64@4.62.2': + resolution: {integrity: sha512-6nU5F2wCW+qvCBhTn1pdIU3bzsIoF7EUwsCDRxilWGprQR6yd508YnH9+OKFCwpfS8pjZqDUmnCAr7exax0XCg==} + cpu: [x64] + os: [freebsd] + + '@rollup/rollup-linux-arm-gnueabihf@4.62.2': + resolution: {integrity: sha512-n1GJHPOvpIfhi3TmrCeh6S6URt9BFCt0KQE3qvexyGCTAKpR4Lg+eWvNZEqu7epxwus/8ElT3hacYEucm49SZg==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-arm-musleabihf@4.62.2': + resolution: {integrity: sha512-JqgflS8wEB+UXV/vS1RpRbifGBeN4D5lz8D8oOFbFZw4vedvdOgCFAjfBmIMdW3yL10XpQQ0Ambepw6MXrhOnA==} + cpu: [arm] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-arm64-gnu@4.62.2': + resolution: {integrity: sha512-wnFJkogWvN4jm/hQRF2UBaeUmk20j5+DmHvoyWii2b8HJDyvz1MF2OU/6ynXt2KR63rbZLWkFpoytpdc/yBuSA==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-arm64-musl@4.62.2': + resolution: {integrity: sha512-HVu2bp0zhvJ8xHEV9+UUs7S90VadmBSY3LcIMvozbPo4AuMGDWlz3ymHLHZPX4hR67TKTt8Qp5PJ5RBg/i+RMQ==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-loong64-gnu@4.62.2': + resolution: {integrity: sha512-mQqqAV8QaoSgr9I2fKDLY2BAVvmKjWoGiu/cSYQonsLvtqwEn1E4QYfnCOcp5zoEqNhsDYin1s6jx/VJmrxlZg==} + cpu: [loong64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-loong64-musl@4.62.2': + resolution: {integrity: sha512-IxKLoxCQ2IWi6bT2akyDUBGsOImDKB+sPp4EsTmwFQ/fMwpCKm8uLSSgP/Kx/QYUgKis6SEZ5/Nlhup0DIA0PQ==} + cpu: [loong64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-ppc64-gnu@4.62.2': + resolution: {integrity: sha512-Mk5ha2RQSgyFfmYYLkBpPnUk8D8FriBxesO1u9O75X0mHgXL1UQcH5Itl2lurWL2tj0RxV9b9tJgipac0hRY9A==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-ppc64-musl@4.62.2': + resolution: {integrity: sha512-CjvEnqJL/0/TQ3TXX3OPIJ/kmBellrWd4heXUmHeJlTnmwjKpSJzoehLaL6Xk0ZnMHBu9dZuFADNOrtjF4v+2w==} + cpu: [ppc64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-riscv64-gnu@4.62.2': + resolution: {integrity: sha512-1SiZbzwdkaDURsew/tSOrooKiYy7EQGT6m8ufavAi9NEyQb/6VuIxFXAL1fqa4iZe3g4NbNk4P7J32z2tw5Mgg==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-riscv64-musl@4.62.2': + resolution: {integrity: sha512-nQts12zJ3NQRoE6uYljOH89v7szzLDvG2JD/vsX+vGXU8w/At1GowTZ5/7qeFQ8m7L55rpR8Okugnuo5bgjy2Q==} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-s390x-gnu@4.62.2': + resolution: {integrity: sha512-E9/ll019jhPIJgpzfZoIkBGhcz+kKNgVWYRY0zr9srBdPPFVpvOKW8VaJKUbeK+eZXyQF9ltME+Kk6affeaPgg==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-x64-gnu@4.62.2': + resolution: {integrity: sha512-5BqxR/pshjey51iliyzTD5Xi3EN0aLmQ2lZ3lvefVV9c82BvrLo2/6OT55iifpWBufs6kdwWbuOKS841DrmK9A==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-x64-musl@4.62.2': + resolution: {integrity: sha512-uNN83XxQrRAh/w0/pmAfibcwyb6YWt4gP+dpnQKPVJshAloQ785ii8CT8ZCIxkGg9opVsvAlGhFitSm6D1Jjpg==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rollup/rollup-openbsd-x64@4.62.2': + resolution: {integrity: sha512-srjEIxSH3LRnJN6THczDHWQplqEMFiAJrTab0msUryh9kwNpkICf3Ea6q6MN/2cZwRFUNx5w+h6Hpi4QuHS6Zg==} + cpu: [x64] + os: [openbsd] + + '@rollup/rollup-openharmony-arm64@4.62.2': + resolution: {integrity: sha512-8hOJnxgbyObnCm5AlRA3A931xX19xq80RjVTKgJOvEKWqJruP/Uf12IbAOaDjjEXYRewwHLfmF0YRIdK3OwKWA==} + cpu: [arm64] + os: [openharmony] + + '@rollup/rollup-win32-arm64-msvc@4.62.2': + resolution: {integrity: sha512-mmF4AY1i0hG/bLWUctUq59gtmgaSIRa3cu/A3JFRp/sCNEme2bgDEiDS22P9FbnJB8NJNF4jPJiSP5RHQpUTDg==} + cpu: [arm64] + os: [win32] + + '@rollup/rollup-win32-ia32-msvc@4.62.2': + resolution: {integrity: sha512-DZgkknc6jhHrk46V25vbAM0zZkyP0nSDkJB8/dRkLTxv470dOmWDqGoEJl/9A0dFfS7yE3REOwNDxpHwSLSt0Q==} + cpu: [ia32] + os: [win32] + + '@rollup/rollup-win32-x64-gnu@4.62.2': + resolution: {integrity: sha512-T6xr6ucWSFto+VGajA8YH26LdpHRuP4YLHEKAtCWvJDOlnmWcDZVCI2Jmjr+IFHDlt2zRaTAKE4tfjTaWLgJBg==} + cpu: [x64] + os: [win32] + + '@rollup/rollup-win32-x64-msvc@4.62.2': + resolution: {integrity: sha512-BfzEnDJOt9T8M989/lA37EcJgat01wLRnoi5dQf3QzOH7jzpqTAzdDbVfRljVr5r+jzKqpbHeyOfAaXxAd0PAA==} + cpu: [x64] + os: [win32] + + '@sinclair/typebox@0.34.52': + resolution: {integrity: sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@types/node@24.13.3': + resolution: {integrity: sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==} + + '@vitejs/plugin-vue@6.0.7': + resolution: {integrity: sha512-km+p+XdSz9Sxm5rqUbqcSfZYaAniKxWBj1KURl+Jr7UaPvvX7BmaWMdP69I5rrFDeQGyxAG7NXdc57vz+snhWg==} + engines: {node: ^20.19.0 || >=22.12.0} + peerDependencies: + vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0 + vue: ^3.2.25 + + '@vitest/expect@3.2.7': + resolution: {integrity: sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==} + + '@vitest/mocker@3.2.7': + resolution: {integrity: sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==} + peerDependencies: + msw: ^2.4.9 + vite: ^5.0.0 || ^6.0.0 || ^7.0.0-0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@3.2.7': + resolution: {integrity: sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==} + + '@vitest/runner@3.2.7': + resolution: {integrity: sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==} + + '@vitest/snapshot@3.2.7': + resolution: {integrity: sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==} + + '@vitest/spy@3.2.7': + resolution: {integrity: sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==} + + '@vitest/utils@3.2.7': + resolution: {integrity: sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==} + + '@volar/language-core@2.4.28': + resolution: {integrity: sha512-w4qhIJ8ZSitgLAkVay6AbcnC7gP3glYM3fYwKV3srj8m494E3xtrCv6E+bWviiK/8hs6e6t1ij1s2Endql7vzQ==} + + '@volar/source-map@2.4.28': + resolution: {integrity: sha512-yX2BDBqJkRXfKw8my8VarTyjv48QwxdJtvRgUpNE5erCsgEUdI2DsLbpa+rOQVAJYshY99szEcRDmyHbF10ggQ==} + + '@volar/typescript@2.4.28': + resolution: {integrity: sha512-Ja6yvWrbis2QtN4ClAKreeUZPVYMARDYZl9LMEv1iQ1QdepB6wn0jTRxA9MftYmYa4DQ4k/DaSZpFPUfxl8giw==} + + '@vue/compiler-core@3.5.39': + resolution: {integrity: sha512-16KBTEXAJCpDr0mwlw+AZyhu8iyC7R3S2vBwsI7QnWJU6X3WKc9VKeNEZpiMdZ569qWhz9574L3vV55qRL0Vtw==} + + '@vue/compiler-dom@3.5.39': + resolution: {integrity: sha512-oQPigALqYbNxTNPvNgSOe+czwVExfbVF02lz8jP0S3AXJiu3jxYDygNUiqSep4ezzW8XgnubqH63My2A7JR/vg==} + + '@vue/compiler-sfc@3.5.39': + resolution: {integrity: sha512-d0ki86iOyN8LoZPBmk5SJWNwHP19CnDDCfuo//+2WJa2g5Ke0Jay983PIBIcSSzldC68I8DrD5GrHV3OSDfodg==} + + '@vue/compiler-ssr@3.5.39': + resolution: {integrity: sha512-Ce7/wvwMHai74bdszfXExdazFigYnlF9zgCmEQUcM1j0fOymlouZ7XilTYNo8oUjhlnjYOZbGrcYKuqjz89Ucw==} + + '@vue/devtools-api@6.6.4': + resolution: {integrity: sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==} + + '@vue/devtools-api@7.7.10': + resolution: {integrity: sha512-KxtEpUOOpFz/qOGRrAwA36QF7DqIA+FXgCYit9mk9wjbaZt0sXOFz81ElOZtKA4HbWHUdwNjZHBFsFFyp5BZiA==} + + '@vue/devtools-kit@7.7.10': + resolution: {integrity: sha512-3WNi2Kq4tbpVbmhml7RiphmAt0279oh3fKNeWMQIrltfX8Q91b4i5PL8DtyNKdwmcsGrV4fg+erwWOmD05CLIw==} + + '@vue/devtools-shared@7.7.10': + resolution: {integrity: sha512-wOPslzB8vTvpxwdaOcR2qAbwmuSP0L+rhpoC6Cf56V3Jip+HWb7PQQXOUPgBNQARpXsbQX/+mvi8kKucmBGRwQ==} + + '@vue/language-core@3.3.7': + resolution: {integrity: sha512-LzmkKinXAMMoh8Jfi/jMUSDUjuPdv8mynH5WJGKfXyZtDw3hQ6GBaoI6Bcnl/Xqlu32q/0Z6i/trp4VXykzyLw==} + + '@vue/reactivity@3.5.39': + resolution: {integrity: sha512-TpsuBJ9gGlZa5d23XcM2y8EXanz9dZeVDQBXRwzy46ItgvM+rWpzs+UVM0wcRLxGvcav0HE5jz2gNL53xlRAog==} + + '@vue/runtime-core@3.5.39': + resolution: {integrity: sha512-9GLtNyRvPAUMbX+7ono0RC2j0guo2LXVi8LvcmAooImACUKm0oFf0jjwbX8/H0AE/t1nxhAkn8RSl9PMCzzxZw==} + + '@vue/runtime-dom@3.5.39': + resolution: {integrity: sha512-7Y6aAGboKcXAZ3ECuUy7RrS5yy2r47dhTp2SKaJmYxjopImaVFaNa5Ne66NwGovsrxVAl5S5rwc7m22UG7Lmww==} + + '@vue/server-renderer@3.5.39': + resolution: {integrity: sha512-yZSakiAGw85rZfG7UM8akMnIF+FmeiNk47uvHf2nVBBSe+dIKUhZuZq9+XgJhbV3nS5Z4ALH23/MpXofW+mbcw==} + peerDependencies: + vue: 3.5.39 + + '@vue/shared@3.5.39': + resolution: {integrity: sha512-l1rrBtBfTnmxvtsvdQDXltUUy8S1Y+ZaqdfUzmAnJkTd8Z8rv5v/ytW+TKiqEOWyHPoqtPlNFSs0lhRmYVSHVA==} + + '@vue/test-utils@2.4.11': + resolution: {integrity: sha512-GDqaqZsA6m2E5vNzej0aYiIb6BX8xV9pNSbbbXKOfEYwg7ZNblVX8suyqmUBThq8VIrgAJNxn+z72hVtUeiWHA==} + peerDependencies: + '@vue/compiler-dom': 3.x + '@vue/server-renderer': 3.x + vue: 3.x + peerDependenciesMeta: + '@vue/server-renderer': + optional: true + + abbrev@2.0.0: + resolution: {integrity: sha512-6/mh1E2u2YgEsCHdY0Yx5oW+61gZU+1vXaoiHHrpKeuRNNgFvS+/jrwHiQhB5apAf5oB7UB7E19ol2R2LKH8hQ==} + engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} + + abslink@1.2.2: + resolution: {integrity: sha512-HCOItvzORPjMzddCmEpbH8+W1VM3yjH+CR7DLtxlxFKX/jz5twJbm7KLfblO7eKLnXINLah8Hk2ZAJqxXeSkOg==} + + abstract-logging@2.0.1: + resolution: {integrity: sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==} + + agent-base@7.1.4: + resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==} + engines: {node: '>= 14'} + + ajv-formats@3.0.1: + resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==} + peerDependencies: + ajv: ^8.0.0 + peerDependenciesMeta: + ajv: + optional: true + + ajv@8.20.0: + resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} + + alien-signals@3.2.1: + resolution: {integrity: sha512-I8FjmltrfnDFoZedi5CG8DghVYNhzb/Ijluz7tCSJH0xpd0484Kowhbb1XDYOxfJpU1p5wnM2X54dA+IfGyD1g==} + + ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + + ansi-regex@6.2.2: + resolution: {integrity: sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==} + engines: {node: '>=12'} + + ansi-styles@4.3.0: + resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} + engines: {node: '>=8'} + + ansi-styles@6.2.3: + resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==} + engines: {node: '>=12'} + + argon2@0.44.0: + resolution: {integrity: sha512-zHPGN3S55sihSQo0dBbK0A5qpi2R31z7HZDZnry3ifOyj8bZZnpZND2gpmhnRGO1V/d555RwBqIK5W4Mrmv3ig==} + engines: {node: '>=16.17.0'} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + atomic-sleep@1.0.0: + resolution: {integrity: sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==} + engines: {node: '>=8.0.0'} + + avvio@9.2.0: + resolution: {integrity: sha512-2t/sy01ArdHHE0vRH5Hsay+RtCZt3dLPji7W7/MMOCEgze5b7SNDC4j5H6FnVgPkI1MTNFGzHdHrVXDDl7QSSQ==} + + balanced-match@1.0.2: + resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + + birpc@2.9.0: + resolution: {integrity: sha512-KrayHS5pBi69Xi9JmvoqrIgYGDkD6mcSe/i6YKi3w5kekCLzrX4+nawcXqrj2tIp50Kw/mT/s3p+GVK0A0sKxw==} + + brace-expansion@2.1.2: + resolution: {integrity: sha512-w5JZcKgdhDOgOwm8H+KgbosopHMuGcl6qbulwjtz3SM7I7P3yW1eAjzMPLrIE+NQ9vjgANKHWeMHnrT0OXW1oA==} + + buffer-from@1.1.2: + resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} + + bullmq@5.80.2: + resolution: {integrity: sha512-IobIZd0xFtpnw9W9RdqDX45nfdI2QSmq8rudMj99p3V5mIm9v4I3uPObqKj7i+6Xfd8Lzs3n1p+YNB7s6ykF4Q==} + engines: {node: '>=12.22.0'} + peerDependencies: + redis: '>=5.0.0' + peerDependenciesMeta: + redis: + optional: true + + cac@6.7.14: + resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==} + engines: {node: '>=8'} + + chai@5.3.3: + resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==} + engines: {node: '>=18'} + + check-error@2.1.3: + resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==} + engines: {node: '>= 16'} + + cluster-key-slot@1.1.2: + resolution: {integrity: sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==} + engines: {node: '>=0.10.0'} + + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + + commander@10.0.1: + resolution: {integrity: sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==} + engines: {node: '>=14'} + + config-chain@1.1.13: + resolution: {integrity: sha512-qj+f8APARXHrM0hraqXYb2/bOVSV4PvJQlNZ/DVj0QrmNM2q2euizkeuVckQ57J+W0mRH6Hvi+k50M4Jul2VRQ==} + + cookie@1.1.1: + resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} + engines: {node: '>=18'} + + cookie@2.0.1: + resolution: {integrity: sha512-yuToqVvRrj6pfDXREyQAAv8SkAEk/8GS3jQRTiUMm66TVtBYmqQeoEjL2Lmq8Rpo6271vH76InTChTitEAm65w==} + engines: {node: '>=22'} + + copy-anything@4.0.5: + resolution: {integrity: sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA==} + engines: {node: '>=18'} + + cron-parser@4.9.0: + resolution: {integrity: sha512-p0SaNjrHOnQeR8/VnfGbmg9te2kfyYSQ7Sc/j/6DtPL3JQvKxmjO9TSjNFpujqV3vEYYBvNNvXSxzyksBWAx1Q==} + engines: {node: '>=12.0.0'} + + cross-env@10.1.0: + resolution: {integrity: sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==} + engines: {node: '>=20'} + hasBin: true + + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + + cssstyle@4.6.0: + resolution: {integrity: sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==} + engines: {node: '>=18'} + + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + + data-urls@5.0.0: + resolution: {integrity: sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==} + engines: {node: '>=18'} + + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + decimal.js@10.6.0: + resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==} + + deep-eql@5.0.2: + resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==} + engines: {node: '>=6'} + + denque@2.1.0: + resolution: {integrity: sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==} + engines: {node: '>=0.10'} + + dequal@2.0.3: + resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} + engines: {node: '>=6'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + drizzle-kit@0.31.10: + resolution: {integrity: sha512-7OZcmQUrdGI+DUNNsKBn1aW8qSoKuTH7d0mYgSP8bAzdFzKoovxEFnoGQp2dVs82EOJeYycqRtciopszwUf8bw==} + hasBin: true + + drizzle-orm@0.45.2: + resolution: {integrity: sha512-kY0BSaTNYWnoDMVoyY8uxmyHjpJW1geOmBMdSSicKo9CIIWkSxMIj2rkeSR51b8KAPB7m+qysjuHme5nKP+E5Q==} + peerDependencies: + '@aws-sdk/client-rds-data': '>=3' + '@cloudflare/workers-types': '>=4' + '@electric-sql/pglite': '>=0.2.0' + '@libsql/client': '>=0.10.0' + '@libsql/client-wasm': '>=0.10.0' + '@neondatabase/serverless': '>=0.10.0' + '@op-engineering/op-sqlite': '>=2' + '@opentelemetry/api': ^1.4.1 + '@planetscale/database': '>=1.13' + '@prisma/client': '*' + '@tidbcloud/serverless': '*' + '@types/better-sqlite3': '*' + '@types/pg': '*' + '@types/sql.js': '*' + '@upstash/redis': '>=1.34.7' + '@vercel/postgres': '>=0.8.0' + '@xata.io/client': '*' + better-sqlite3: '>=7' + bun-types: '*' + expo-sqlite: '>=14.0.0' + gel: '>=2' + knex: '*' + kysely: '*' + mysql2: '>=2' + pg: '>=8' + postgres: '>=3' + prisma: '*' + sql.js: '>=1' + sqlite3: '>=5' + peerDependenciesMeta: + '@aws-sdk/client-rds-data': + optional: true + '@cloudflare/workers-types': + optional: true + '@electric-sql/pglite': + optional: true + '@libsql/client': + optional: true + '@libsql/client-wasm': + optional: true + '@neondatabase/serverless': + optional: true + '@op-engineering/op-sqlite': + optional: true + '@opentelemetry/api': + optional: true + '@planetscale/database': + optional: true + '@prisma/client': + optional: true + '@tidbcloud/serverless': + optional: true + '@types/better-sqlite3': + optional: true + '@types/pg': + optional: true + '@types/sql.js': + optional: true + '@upstash/redis': + optional: true + '@vercel/postgres': + optional: true + '@xata.io/client': + optional: true + better-sqlite3: + optional: true + bun-types: + optional: true + expo-sqlite: + optional: true + gel: + optional: true + knex: + optional: true + kysely: + optional: true + mysql2: + optional: true + pg: + optional: true + postgres: + optional: true + prisma: + optional: true + sql.js: + optional: true + sqlite3: + optional: true + + eastasianwidth@0.2.0: + resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} + + editorconfig@1.0.7: + resolution: {integrity: sha512-e0GOtq/aTQhVdNyDU9e02+wz9oDDM+SIOQxWME2QRjzRX5yyLAuHDE+0aE8vHb9XRC8XD37eO2u57+F09JqFhw==} + engines: {node: '>=14'} + hasBin: true + + emoji-regex@8.0.0: + resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + + emoji-regex@9.2.2: + resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==} + + entities@6.0.1: + resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==} + engines: {node: '>=0.12'} + + entities@7.0.1: + resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==} + engines: {node: '>=0.12'} + + es-module-lexer@1.7.0: + resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==} + + esbuild@0.18.20: + resolution: {integrity: sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA==} + engines: {node: '>=12'} + hasBin: true + + esbuild@0.25.12: + resolution: {integrity: sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==} + engines: {node: '>=18'} + hasBin: true + + esbuild@0.28.1: + resolution: {integrity: sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==} + engines: {node: '>=18'} + hasBin: true + + estree-walker@2.0.2: + resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==} + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + + fast-decode-uri-component@1.0.1: + resolution: {integrity: sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==} + + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + + fast-json-stringify@7.0.1: + resolution: {integrity: sha512-eRSayARSbbwlBjpP4vnTTIRD5QPcIrmihPxDeN1DtKnHPg66UuJLx+8hlK1kaFdjvzyQ/dzALoi4vwAQ+T+iZA==} + + fast-querystring@1.1.2: + resolution: {integrity: sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==} + + fast-uri@3.1.3: + resolution: {integrity: sha512-i70LwGWUduXqzicKXWshooq+sWL1K3WUU5rKZNG/0i3a1OSoX3HqhH5WbWwTmqWfor4urUakGPiRQcleRZTwOg==} + + fast-uri@4.1.0: + resolution: {integrity: sha512-ZodJ2cRiLVWGi9IgPb3mbgSqM4CD3LexCHkuv0FfBXHJI1ADfucTD06m6clO2Cy5RZYsw/SiCVl/dyrFI/SYWA==} + + fastify-plugin@5.1.0: + resolution: {integrity: sha512-FAIDA8eovSt5qcDgcBvDuX/v0Cjz0ohGhENZ/wpc3y+oZCY2afZ9Baqql3g/lC+OHRnciQol4ww7tuthOb9idw==} + + fastify-plugin@6.0.0: + resolution: {integrity: sha512-fZOty7z3O7vOliF6d8bHE3wiEh1KcNnKEQensSgTk9C1DvN6nRLS++XVd86v33Hw/8u9Un8A1zDrQ8ujcQDHEg==} + + fastify@5.10.0: + resolution: {integrity: sha512-A9L0ziuWGQHgEEVgF3davQ9vbD93IuX+lo2IsxapQmu5b/Y/ynn9m9K5JHt9dvyJXOFc5iN0Zk5GHEOqnzhWjg==} + + fastq@1.20.1: + resolution: {integrity: sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + find-my-way@9.6.0: + resolution: {integrity: sha512-Zf4Xve4RymLl7NgaavNebZ01joJ8MfVerOG43wy7SHLO+r+K0C6d/SE0BiR7AV5V1VOCFlOP7ecdo+I4qmiHrQ==} + engines: {node: '>=20'} + + foreground-child@3.3.1: + resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==} + engines: {node: '>=14'} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + get-tsconfig@4.14.0: + resolution: {integrity: sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==} + + glob@10.5.0: + resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==} + deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + hasBin: true + + helmet@8.3.0: + resolution: {integrity: sha512-Qgpiaws3Sm30Av8Eah6sjMCZZwjlBu+E68rhpCWBshY1lb09HtLwj5GviX0OyQIn+ulUS0iX0AxN5n3tLZzz1w==} + engines: {node: '>=18.0.0'} + + hls.js@1.6.16: + resolution: {integrity: sha512-VSIRpLfRwlAAdGL4wiTucx2ScRipo0ed1FBatWkyt832jC4CReKstga6yIhYVwGu9LOBjuX9wzmRMeQdBJtzEA==} + + hookable@5.5.3: + resolution: {integrity: sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==} + + html-encoding-sniffer@4.0.0: + resolution: {integrity: sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==} + engines: {node: '>=18'} + + http-proxy-agent@7.0.2: + resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==} + engines: {node: '>= 14'} + + https-proxy-agent@7.0.6: + resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==} + engines: {node: '>= 14'} + + iconv-lite@0.6.3: + resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==} + engines: {node: '>=0.10.0'} + + ini@1.3.8: + resolution: {integrity: sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==} + + ioredis@5.10.1: + resolution: {integrity: sha512-HuEDBTI70aYdx1v6U97SbNx9F1+svQKBDo30o0b9fw055LMepzpOOd0Ccg9Q6tbqmBSJaMuY0fB7yw9/vjBYCA==} + engines: {node: '>=12.22.0'} + + ipaddr.js@2.4.0: + resolution: {integrity: sha512-9VGk3HGanVE6JoZXHiCpnGy5X0jYDnN4EA4lntFPj+1vIWlFhIylq2CrrCOJH9EAhc5CYhq18F2Av2tgoAPsYQ==} + engines: {node: '>= 10'} + + is-fullwidth-code-point@3.0.0: + resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} + engines: {node: '>=8'} + + is-potential-custom-element-name@1.0.1: + resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} + + is-what@5.5.0: + resolution: {integrity: sha512-oG7cgbmg5kLYae2N5IVd3jm2s+vldjxJzK1pcu9LfpGuQ93MQSzo0okvRna+7y5ifrD+20FE8FvjusyGaz14fw==} + engines: {node: '>=18'} + + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + + jackspeak@3.4.3: + resolution: {integrity: sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==} + + jassub@2.5.7: + resolution: {integrity: sha512-ynn0D65lsQwkBhnTi7WqJ7upy7jHMq+ePP637rI2x7cQYVJlsG8zrAacP5DCq9nO+W3lY0IXRT2VzjBwSpHzWA==} + + js-beautify@1.15.4: + resolution: {integrity: sha512-9/KXeZUKKJwqCXUdBxFJ3vPh467OCckSBmYDwSK/EtV090K+iMJ7zx2S3HLVDIWFQdqMIsZWbnaGiba18aWhaA==} + engines: {node: '>=14'} + hasBin: true + + js-cookie@3.0.8: + resolution: {integrity: sha512-yeJd4aNAdYZQjaon2bpD/Gb0B/omw7HQOsynXXcOiWVCacbBcPlgn8S/d1X6blFSaHao7ozqtW7NZW19xpCtIw==} + + js-tokens@9.0.1: + resolution: {integrity: sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==} + + jsdom@26.1.0: + resolution: {integrity: sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==} + engines: {node: '>=18'} + peerDependencies: + canvas: ^3.0.0 + peerDependenciesMeta: + canvas: + optional: true + + json-schema-ref-resolver@3.0.0: + resolution: {integrity: sha512-hOrZIVL5jyYFjzk7+y7n5JDzGlU8rfWDuYyHwGa2WA8/pcmMHezp2xsVwxrebD/Q9t8Nc5DboieySDpCp4WG4A==} + + json-schema-traverse@1.0.0: + resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==} + + lfa-ponyfill@1.1.1: + resolution: {integrity: sha512-Had4tsGEHtIj58MRtf6SlubNDltxinxMSdxIn1GdwrWbye8TD+pZ+D6qKETnJ9+vQOfG9q/Ds4WUPskhyAMp5Q==} + + light-my-request@6.6.0: + resolution: {integrity: sha512-CHYbu8RtboSIoVsHZ6Ye4cj4Aw/yg2oAFimlF7mNvfDV192LR7nDiKtSIfCuLT7KokPSTn/9kfVLm5OGN0A28A==} + + lodash.defaults@4.2.0: + resolution: {integrity: sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==} + + lodash.isarguments@3.1.0: + resolution: {integrity: sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==} + + loupe@3.2.1: + resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==} + + lru-cache@10.4.3: + resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==} + + luxon@3.7.2: + resolution: {integrity: sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==} + engines: {node: '>=12'} + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + minimatch@9.0.9: + resolution: {integrity: sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==} + engines: {node: '>=16 || 14 >=14.17'} + + minipass@7.1.3: + resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} + engines: {node: '>=16 || 14 >=14.17'} + + mitt@3.0.1: + resolution: {integrity: sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==} + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + msgpackr-extract@3.0.4: + resolution: {integrity: sha512-4kmO/MdyUIkLIvTPr8VHLil4AtoKIoniWPIEk5+CDy0xnWC84azhSFmuJ7PxZdsYtiP5kEeQsORAVIeMgxT+Hw==} + hasBin: true + + msgpackr@2.0.4: + resolution: {integrity: sha512-o1C5KRmuRt+apqMr1HuGSqWStZoRBUpEsCsl15uM9VdAF1qHLtvMOU2En747EnTyEl6c4pzPewRMFF31s1CNbA==} + + muggle-string@0.4.1: + resolution: {integrity: sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==} + + nanoid@3.3.16: + resolution: {integrity: sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + node-abort-controller@3.1.1: + resolution: {integrity: sha512-AGK2yQKIjRuqnc6VkX2Xj5d+QW8xZ87pa1UK6yA6ouUyuxfHuMP6umE5QK7UmTeOAymo+Zx1Fxiuw9rVx8taHQ==} + + node-addon-api@8.9.0: + resolution: {integrity: sha512-ekZMeaaIzSQTSpr7X2X3iJM7lTzgnx8ahAG9pJfT/7+14mlEM8ZYQ9cgCDvSSRbReFK0oHli3WrZdCiRsgAT9Q==} + engines: {node: ^18 || ^20 || >= 21} + + node-gyp-build-optional-packages@5.2.2: + resolution: {integrity: sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw==} + hasBin: true + + node-gyp-build@4.8.4: + resolution: {integrity: sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==} + hasBin: true + + nopt@7.2.1: + resolution: {integrity: sha512-taM24ViiimT/XntxbPyJQzCG+p4EKOpgD3mxFwW38mGjVUrfERQOeY4EDHjdnptttfHuHQXFx+lTP08Q+mLa/w==} + engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} + hasBin: true + + nwsapi@2.2.24: + resolution: {integrity: sha512-7YRhZ3jS45LwmSCT4b2sVFHt/WuovaktDU07QrtOBY2PXskss5a9jfmR9jptyumwXST+rFjrmppMY1KT/yn35A==} + + on-exit-leak-free@2.1.2: + resolution: {integrity: sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==} + engines: {node: '>=14.0.0'} + + package-json-from-dist@1.0.1: + resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==} + + parse5@7.3.0: + resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==} + + path-browserify@1.0.1: + resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==} + + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + + path-scurry@1.11.1: + resolution: {integrity: sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==} + engines: {node: '>=16 || 14 >=14.18'} + + pathe@2.0.3: + resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + + pathval@2.0.1: + resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==} + engines: {node: '>= 14.16'} + + perfect-debounce@1.0.0: + resolution: {integrity: sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.5: + resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==} + engines: {node: '>=12'} + + pinia@3.0.4: + resolution: {integrity: sha512-l7pqLUFTI/+ESXn6k3nu30ZIzW5E2WZF/LaHJEpoq6ElcLD+wduZoB2kBN19du6K/4FDpPMazY2wJr+IndBtQw==} + peerDependencies: + typescript: '>=4.5.0' + vue: ^3.5.11 + peerDependenciesMeta: + typescript: + optional: true + + pino-abstract-transport@3.0.0: + resolution: {integrity: sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==} + + pino-std-serializers@7.1.0: + resolution: {integrity: sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==} + + pino@10.3.1: + resolution: {integrity: sha512-r34yH/GlQpKZbU1BvFFqOjhISRo1MNx1tWYsYvmj6KIRHSPMT2+yHOEb1SG6NMvRoHRF0a07kCOox/9yakl1vg==} + hasBin: true + + postcss@8.5.18: + resolution: {integrity: sha512-xdB1oSLHbz1vRWgCDalrCqEFTWzFlhqFC5tIHLMOSUIjhm3XXQ1qrFy8S/ESr1JYRRXqM3c1QFiMZUJdUTqyMQ==} + engines: {node: ^10 || ^12 || >=14} + + postgres@3.4.9: + resolution: {integrity: sha512-GD3qdB0x1z9xgFI6cdRD6xu2Sp2WCOEoe3mtnyB5Ee0XrrL5Pe+e4CCnJrRMnL1zYtRDZmQQVbvOttLnKDLnaw==} + engines: {node: '>=12'} + + process-warning@4.0.1: + resolution: {integrity: sha512-3c2LzQ3rY9d0hc1emcsHhfT9Jwz0cChib/QN89oME2R451w5fy3f0afAhERFZAwrbDU43wk12d0ORBpDVME50Q==} + + process-warning@5.0.0: + resolution: {integrity: sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA==} + + proto-list@1.2.4: + resolution: {integrity: sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA==} + + punycode@2.3.1: + resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} + engines: {node: '>=6'} + + quick-format-unescaped@4.0.4: + resolution: {integrity: sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==} + + real-require@0.2.0: + resolution: {integrity: sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==} + engines: {node: '>= 12.13.0'} + + real-require@1.0.0: + resolution: {integrity: sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==} + + redis-errors@1.2.0: + resolution: {integrity: sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==} + engines: {node: '>=4'} + + redis-parser@3.0.0: + resolution: {integrity: sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==} + engines: {node: '>=4'} + + require-from-string@2.0.2: + resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} + engines: {node: '>=0.10.0'} + + resolve-pkg-maps@1.0.0: + resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} + + ret@0.5.0: + resolution: {integrity: sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw==} + engines: {node: '>=10'} + + reusify@1.1.0: + resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==} + engines: {iojs: '>=1.0.0', node: '>=0.10.0'} + + rfdc@1.4.1: + resolution: {integrity: sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==} + + rollup@4.62.2: + resolution: {integrity: sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA==} + engines: {node: '>=18.0.0', npm: '>=8.0.0'} + hasBin: true + + rrweb-cssom@0.8.0: + resolution: {integrity: sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==} + + rvfc-polyfill@1.0.8: + resolution: {integrity: sha512-uA+0wwTkZ4OT8v45pfDfH+7Yq8mY6MvNngiF5Sq6VBgjJsvsfgt7Q18cyZqZjfAhW9rhkgXPX0cW0R9uw7yElA==} + + safe-regex2@5.1.1: + resolution: {integrity: sha512-mOSBvHGDZMuIEZMdOz/aCEYDCv0E7nfcNsIhUF+/P+xC7Hyf3FkvymqgPbg9D1EdSGu+uKbJgy09K/RKKc7kJA==} + hasBin: true + + safe-stable-stringify@2.5.0: + resolution: {integrity: sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==} + engines: {node: '>=10'} + + safer-buffer@2.1.2: + resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + + saxes@6.0.0: + resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} + engines: {node: '>=v12.22.7'} + + secure-json-parse@4.1.0: + resolution: {integrity: sha512-l4KnYfEyqYJxDwlNVyRfO2E4NTHfMKAWdUuA8J0yve2Dz/E/PdBepY03RvyJpssIpRFwJoCD55wA+mEDs6ByWA==} + + semver@7.8.5: + resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} + engines: {node: '>=10'} + hasBin: true + + set-cookie-parser@2.7.2: + resolution: {integrity: sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==} + + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + + signal-exit@4.1.0: + resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} + engines: {node: '>=14'} + + sonic-boom@4.2.1: + resolution: {integrity: sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==} + + source-map-js@1.2.1: + resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + engines: {node: '>=0.10.0'} + + source-map-support@0.5.21: + resolution: {integrity: sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==} + + source-map@0.6.1: + resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} + engines: {node: '>=0.10.0'} + + speakingurl@14.0.1: + resolution: {integrity: sha512-1POYv7uv2gXoyGFpBCmpDVSNV74IfsWlDW216UPjbWufNf+bSU6GdbDsxdcxtfwb4xlI3yxzOTKClUosxARYrQ==} + engines: {node: '>=0.10.0'} + + split2@4.2.0: + resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==} + engines: {node: '>= 10.x'} + + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + standard-as-callback@2.1.0: + resolution: {integrity: sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==} + + std-env@3.10.0: + resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==} + + string-width@4.2.3: + resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} + engines: {node: '>=8'} + + string-width@5.1.2: + resolution: {integrity: sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==} + engines: {node: '>=12'} + + strip-ansi@6.0.1: + resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} + engines: {node: '>=8'} + + strip-ansi@7.2.0: + resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==} + engines: {node: '>=12'} + + strip-literal@3.1.0: + resolution: {integrity: sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==} + + superjson@2.2.6: + resolution: {integrity: sha512-H+ue8Zo4vJmV2nRjpx86P35lzwDT3nItnIsocgumgr0hHMQ+ZGq5vrERg9kJBo5AWGmxZDhzDo+WVIJqkB0cGA==} + engines: {node: '>=16'} + + symbol-tree@3.2.4: + resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==} + + thread-stream@4.2.0: + resolution: {integrity: sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ==} + engines: {node: '>=20'} + + throughput@1.0.2: + resolution: {integrity: sha512-jvK1ZXuhsggjb3qYQjMiU/AVYYiTeqT5thWvYR2yuy2LGM84P5MSSyAinwHahGsdBYKR9m9HncVR/3f3nFKkxg==} + + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@0.3.2: + resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + tinypool@1.1.1: + resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==} + engines: {node: ^18.0.0 || >=20.0.0} + + tinyrainbow@2.0.0: + resolution: {integrity: sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==} + engines: {node: '>=14.0.0'} + + tinyspy@4.0.4: + resolution: {integrity: sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==} + engines: {node: '>=14.0.0'} + + tldts-core@6.1.86: + resolution: {integrity: sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==} + + tldts@6.1.86: + resolution: {integrity: sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==} + hasBin: true + + toad-cache@3.7.4: + resolution: {integrity: sha512-m1TdR/rvT7kgGJZhspNtXdsdYk0fddFpJJFlG5s+UkPFo6lkLoZ3YLOaovPYjq1R75NP5JfeTlSHaOsE09peCg==} + engines: {node: '>=20'} + + tough-cookie@5.1.2: + resolution: {integrity: sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==} + engines: {node: '>=16'} + + tr46@5.1.1: + resolution: {integrity: sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==} + engines: {node: '>=18'} + + tslib@2.8.1: + resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + + tsx@4.23.1: + resolution: {integrity: sha512-GQHnkIfxyx1wYCOS/wonik5MVRZU9hi1TEZmzGZSCJB1y9YgoZ8H6itNE/u4suE+yLmOzuE4E5S4TZ/ZX2wcWQ==} + engines: {node: '>=18.0.0'} + hasBin: true + + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@7.18.2: + resolution: {integrity: sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==} + + vite-node@3.2.4: + resolution: {integrity: sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==} + engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} + hasBin: true + + vite@7.3.6: + resolution: {integrity: sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + jiti: '>=1.21.0' + less: ^4.0.0 + lightningcss: ^1.21.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 + jiti: + optional: true + less: + optional: true + lightningcss: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@3.2.7: + resolution: {integrity: sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==} + engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@types/debug': ^4.1.12 + '@types/node': ^18.0.0 || ^20.0.0 || >=22.0.0 + '@vitest/browser': 3.2.7 + '@vitest/ui': 3.2.7 + happy-dom: '*' + jsdom: '*' + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@types/debug': + optional: true + '@types/node': + optional: true + '@vitest/browser': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + vscode-uri@3.1.0: + resolution: {integrity: sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==} + + vue-component-type-helpers@3.3.7: + resolution: {integrity: sha512-Skkhw9agYSgsWqv7bxSOGJZa9SaiJbZVGdXuFWnrzKaQYHnw9qbjD630rw6RyMqDbp54nfLCLw5SZA55if7JLg==} + + vue-router@4.6.4: + resolution: {integrity: sha512-Hz9q5sa33Yhduglwz6g9skT8OBPii+4bFn88w6J+J4MfEo4KRRpmiNG/hHHkdbRFlLBOqxN8y8gf2Fb0MTUgVg==} + peerDependencies: + vue: ^3.5.0 + + vue-tsc@3.3.7: + resolution: {integrity: sha512-+C+rgD49wAQ5bUTl2sp5a8Bzg4YoldMNXM+g7CFe604MYcQ8PrZPMQhIjJSzKXtPBCa+C5ayMipqjbA7splekQ==} + hasBin: true + peerDependencies: + typescript: '>=5.0.0' + + vue@3.5.39: + resolution: {integrity: sha512-xmZCYabFGcirU8r0fTuvl/LICc1OU620rnqepaJDL/a141ZigkG7AyaxQLdqJ02ZRYzWe6YPaDHeQx7MfknQfA==} + peerDependencies: + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + w3c-xmlserializer@5.0.0: + resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==} + engines: {node: '>=18'} + + webidl-conversions@7.0.0: + resolution: {integrity: sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==} + engines: {node: '>=12'} + + whatwg-encoding@3.1.1: + resolution: {integrity: sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==} + engines: {node: '>=18'} + deprecated: Use @exodus/bytes instead for a more spec-conformant and faster implementation + + whatwg-mimetype@4.0.0: + resolution: {integrity: sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==} + engines: {node: '>=18'} + + whatwg-url@14.2.0: + resolution: {integrity: sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==} + engines: {node: '>=18'} + + which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true + + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + + wrap-ansi@7.0.0: + resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} + engines: {node: '>=10'} + + wrap-ansi@8.1.0: + resolution: {integrity: sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==} + engines: {node: '>=12'} + + ws@8.21.0: + resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + + xml-name-validator@5.0.0: + resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==} + engines: {node: '>=18'} + + xmlchars@2.2.0: + resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} + +snapshots: + + '@asamuzakjp/css-color@3.2.0': + dependencies: + '@csstools/css-calc': 2.1.4(@csstools/css-parser-algorithms@3.0.5(@csstools/css-tokenizer@3.0.4))(@csstools/css-tokenizer@3.0.4) + '@csstools/css-color-parser': 3.1.0(@csstools/css-parser-algorithms@3.0.5(@csstools/css-tokenizer@3.0.4))(@csstools/css-tokenizer@3.0.4) + '@csstools/css-parser-algorithms': 3.0.5(@csstools/css-tokenizer@3.0.4) + '@csstools/css-tokenizer': 3.0.4 + lru-cache: 10.4.3 + + '@babel/helper-string-parser@7.29.7': {} + + '@babel/helper-validator-identifier@7.29.7': {} + + '@babel/parser@7.29.7': + dependencies: + '@babel/types': 7.29.7 + + '@babel/types@7.29.7': + dependencies: + '@babel/helper-string-parser': 7.29.7 + '@babel/helper-validator-identifier': 7.29.7 + + '@csstools/color-helpers@5.1.0': {} + + '@csstools/css-calc@2.1.4(@csstools/css-parser-algorithms@3.0.5(@csstools/css-tokenizer@3.0.4))(@csstools/css-tokenizer@3.0.4)': + dependencies: + '@csstools/css-parser-algorithms': 3.0.5(@csstools/css-tokenizer@3.0.4) + '@csstools/css-tokenizer': 3.0.4 + + '@csstools/css-color-parser@3.1.0(@csstools/css-parser-algorithms@3.0.5(@csstools/css-tokenizer@3.0.4))(@csstools/css-tokenizer@3.0.4)': + dependencies: + '@csstools/color-helpers': 5.1.0 + '@csstools/css-calc': 2.1.4(@csstools/css-parser-algorithms@3.0.5(@csstools/css-tokenizer@3.0.4))(@csstools/css-tokenizer@3.0.4) + '@csstools/css-parser-algorithms': 3.0.5(@csstools/css-tokenizer@3.0.4) + '@csstools/css-tokenizer': 3.0.4 + + '@csstools/css-parser-algorithms@3.0.5(@csstools/css-tokenizer@3.0.4)': + dependencies: + '@csstools/css-tokenizer': 3.0.4 + + '@csstools/css-tokenizer@3.0.4': {} + + '@drizzle-team/brocli@0.10.2': {} + + '@epic-web/invariant@1.0.0': {} + + '@esbuild-kit/core-utils@3.3.2': + dependencies: + esbuild: 0.18.20 + source-map-support: 0.5.21 + + '@esbuild-kit/esm-loader@2.6.5': + dependencies: + '@esbuild-kit/core-utils': 3.3.2 + get-tsconfig: 4.14.0 + + '@esbuild/aix-ppc64@0.25.12': + optional: true + + '@esbuild/aix-ppc64@0.28.1': + optional: true + + '@esbuild/android-arm64@0.18.20': + optional: true + + '@esbuild/android-arm64@0.25.12': + optional: true + + '@esbuild/android-arm64@0.28.1': + optional: true + + '@esbuild/android-arm@0.18.20': + optional: true + + '@esbuild/android-arm@0.25.12': + optional: true + + '@esbuild/android-arm@0.28.1': + optional: true + + '@esbuild/android-x64@0.18.20': + optional: true + + '@esbuild/android-x64@0.25.12': + optional: true + + '@esbuild/android-x64@0.28.1': + optional: true + + '@esbuild/darwin-arm64@0.18.20': + optional: true + + '@esbuild/darwin-arm64@0.25.12': + optional: true + + '@esbuild/darwin-arm64@0.28.1': + optional: true + + '@esbuild/darwin-x64@0.18.20': + optional: true + + '@esbuild/darwin-x64@0.25.12': + optional: true + + '@esbuild/darwin-x64@0.28.1': + optional: true + + '@esbuild/freebsd-arm64@0.18.20': + optional: true + + '@esbuild/freebsd-arm64@0.25.12': + optional: true + + '@esbuild/freebsd-arm64@0.28.1': + optional: true + + '@esbuild/freebsd-x64@0.18.20': + optional: true + + '@esbuild/freebsd-x64@0.25.12': + optional: true + + '@esbuild/freebsd-x64@0.28.1': + optional: true + + '@esbuild/linux-arm64@0.18.20': + optional: true + + '@esbuild/linux-arm64@0.25.12': + optional: true + + '@esbuild/linux-arm64@0.28.1': + optional: true + + '@esbuild/linux-arm@0.18.20': + optional: true + + '@esbuild/linux-arm@0.25.12': + optional: true + + '@esbuild/linux-arm@0.28.1': + optional: true + + '@esbuild/linux-ia32@0.18.20': + optional: true + + '@esbuild/linux-ia32@0.25.12': + optional: true + + '@esbuild/linux-ia32@0.28.1': + optional: true + + '@esbuild/linux-loong64@0.18.20': + optional: true + + '@esbuild/linux-loong64@0.25.12': + optional: true + + '@esbuild/linux-loong64@0.28.1': + optional: true + + '@esbuild/linux-mips64el@0.18.20': + optional: true + + '@esbuild/linux-mips64el@0.25.12': + optional: true + + '@esbuild/linux-mips64el@0.28.1': + optional: true + + '@esbuild/linux-ppc64@0.18.20': + optional: true + + '@esbuild/linux-ppc64@0.25.12': + optional: true + + '@esbuild/linux-ppc64@0.28.1': + optional: true + + '@esbuild/linux-riscv64@0.18.20': + optional: true + + '@esbuild/linux-riscv64@0.25.12': + optional: true + + '@esbuild/linux-riscv64@0.28.1': + optional: true + + '@esbuild/linux-s390x@0.18.20': + optional: true + + '@esbuild/linux-s390x@0.25.12': + optional: true + + '@esbuild/linux-s390x@0.28.1': + optional: true + + '@esbuild/linux-x64@0.18.20': + optional: true + + '@esbuild/linux-x64@0.25.12': + optional: true + + '@esbuild/linux-x64@0.28.1': + optional: true + + '@esbuild/netbsd-arm64@0.25.12': + optional: true + + '@esbuild/netbsd-arm64@0.28.1': + optional: true + + '@esbuild/netbsd-x64@0.18.20': + optional: true + + '@esbuild/netbsd-x64@0.25.12': + optional: true + + '@esbuild/netbsd-x64@0.28.1': + optional: true + + '@esbuild/openbsd-arm64@0.25.12': + optional: true + + '@esbuild/openbsd-arm64@0.28.1': + optional: true + + '@esbuild/openbsd-x64@0.18.20': + optional: true + + '@esbuild/openbsd-x64@0.25.12': + optional: true + + '@esbuild/openbsd-x64@0.28.1': + optional: true + + '@esbuild/openharmony-arm64@0.25.12': + optional: true + + '@esbuild/openharmony-arm64@0.28.1': + optional: true + + '@esbuild/sunos-x64@0.18.20': + optional: true + + '@esbuild/sunos-x64@0.25.12': + optional: true + + '@esbuild/sunos-x64@0.28.1': + optional: true + + '@esbuild/win32-arm64@0.18.20': + optional: true + + '@esbuild/win32-arm64@0.25.12': + optional: true + + '@esbuild/win32-arm64@0.28.1': + optional: true + + '@esbuild/win32-ia32@0.18.20': + optional: true + + '@esbuild/win32-ia32@0.25.12': + optional: true + + '@esbuild/win32-ia32@0.28.1': + optional: true + + '@esbuild/win32-x64@0.18.20': + optional: true + + '@esbuild/win32-x64@0.25.12': + optional: true + + '@esbuild/win32-x64@0.28.1': + optional: true + + '@fastify/ajv-compiler@4.0.5': + dependencies: + ajv: 8.20.0 + ajv-formats: 3.0.1(ajv@8.20.0) + fast-uri: 3.1.3 + + '@fastify/cookie@11.1.1': + dependencies: + cookie: 2.0.1 + fastify-plugin: 6.0.0 + + '@fastify/cors@11.3.0': + dependencies: + fastify-plugin: 6.0.0 + toad-cache: 3.7.4 + + '@fastify/error@4.2.0': {} + + '@fastify/fast-json-stringify-compiler@5.1.0': + dependencies: + fast-json-stringify: 7.0.1 + + '@fastify/forwarded@3.0.1': {} + + '@fastify/helmet@13.1.0': + dependencies: + fastify-plugin: 6.0.0 + helmet: 8.3.0 + + '@fastify/merge-json-schemas@0.2.1': + dependencies: + dequal: 2.0.3 + + '@fastify/proxy-addr@5.1.0': + dependencies: + '@fastify/forwarded': 3.0.1 + ipaddr.js: 2.4.0 + + '@fastify/rate-limit@10.3.0': + dependencies: + '@lukeed/ms': 2.0.2 + fastify-plugin: 5.1.0 + toad-cache: 3.7.4 + + '@fontsource/vazirmatn@5.2.8': {} + + '@ioredis/commands@1.5.1': {} + + '@isaacs/cliui@8.0.2': + dependencies: + string-width: 5.1.2 + string-width-cjs: string-width@4.2.3 + strip-ansi: 7.2.0 + strip-ansi-cjs: strip-ansi@6.0.1 + wrap-ansi: 8.1.0 + wrap-ansi-cjs: wrap-ansi@7.0.0 + + '@jridgewell/sourcemap-codec@1.5.5': {} + + '@lukeed/ms@2.0.2': {} + + '@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.4': + optional: true + + '@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.4': + optional: true + + '@msgpackr-extract/msgpackr-extract-linux-arm64@3.0.4': + optional: true + + '@msgpackr-extract/msgpackr-extract-linux-arm@3.0.4': + optional: true + + '@msgpackr-extract/msgpackr-extract-linux-x64@3.0.4': + optional: true + + '@msgpackr-extract/msgpackr-extract-win32-x64@3.0.4': + optional: true + + '@one-ini/wasm@0.1.1': {} + + '@phc/format@1.0.0': {} + + '@pinojs/redact@0.4.0': {} + + '@pkgjs/parseargs@0.11.0': + optional: true + + '@rolldown/pluginutils@1.0.1': {} + + '@rollup/rollup-android-arm-eabi@4.62.2': + optional: true + + '@rollup/rollup-android-arm64@4.62.2': + optional: true + + '@rollup/rollup-darwin-arm64@4.62.2': + optional: true + + '@rollup/rollup-darwin-x64@4.62.2': + optional: true + + '@rollup/rollup-freebsd-arm64@4.62.2': + optional: true + + '@rollup/rollup-freebsd-x64@4.62.2': + optional: true + + '@rollup/rollup-linux-arm-gnueabihf@4.62.2': + optional: true + + '@rollup/rollup-linux-arm-musleabihf@4.62.2': + optional: true + + '@rollup/rollup-linux-arm64-gnu@4.62.2': + optional: true + + '@rollup/rollup-linux-arm64-musl@4.62.2': + optional: true + + '@rollup/rollup-linux-loong64-gnu@4.62.2': + optional: true + + '@rollup/rollup-linux-loong64-musl@4.62.2': + optional: true + + '@rollup/rollup-linux-ppc64-gnu@4.62.2': + optional: true + + '@rollup/rollup-linux-ppc64-musl@4.62.2': + optional: true + + '@rollup/rollup-linux-riscv64-gnu@4.62.2': + optional: true + + '@rollup/rollup-linux-riscv64-musl@4.62.2': + optional: true + + '@rollup/rollup-linux-s390x-gnu@4.62.2': + optional: true + + '@rollup/rollup-linux-x64-gnu@4.62.2': + optional: true + + '@rollup/rollup-linux-x64-musl@4.62.2': + optional: true + + '@rollup/rollup-openbsd-x64@4.62.2': + optional: true + + '@rollup/rollup-openharmony-arm64@4.62.2': + optional: true + + '@rollup/rollup-win32-arm64-msvc@4.62.2': + optional: true + + '@rollup/rollup-win32-ia32-msvc@4.62.2': + optional: true + + '@rollup/rollup-win32-x64-gnu@4.62.2': + optional: true + + '@rollup/rollup-win32-x64-msvc@4.62.2': + optional: true + + '@sinclair/typebox@0.34.52': {} + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/deep-eql@4.0.2': {} + + '@types/estree@1.0.9': {} + + '@types/node@24.13.3': + dependencies: + undici-types: 7.18.2 + + '@vitejs/plugin-vue@6.0.7(vite@7.3.6(@types/node@24.13.3)(tsx@4.23.1))(vue@3.5.39(typescript@5.9.3))': + dependencies: + '@rolldown/pluginutils': 1.0.1 + vite: 7.3.6(@types/node@24.13.3)(tsx@4.23.1) + vue: 3.5.39(typescript@5.9.3) + + '@vitest/expect@3.2.7': + dependencies: + '@types/chai': 5.2.3 + '@vitest/spy': 3.2.7 + '@vitest/utils': 3.2.7 + chai: 5.3.3 + tinyrainbow: 2.0.0 + + '@vitest/mocker@3.2.7(vite@7.3.6(@types/node@24.13.3)(tsx@4.23.1))': + dependencies: + '@vitest/spy': 3.2.7 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 7.3.6(@types/node@24.13.3)(tsx@4.23.1) + + '@vitest/pretty-format@3.2.7': + dependencies: + tinyrainbow: 2.0.0 + + '@vitest/runner@3.2.7': + dependencies: + '@vitest/utils': 3.2.7 + pathe: 2.0.3 + strip-literal: 3.1.0 + + '@vitest/snapshot@3.2.7': + dependencies: + '@vitest/pretty-format': 3.2.7 + magic-string: 0.30.21 + pathe: 2.0.3 + + '@vitest/spy@3.2.7': + dependencies: + tinyspy: 4.0.4 + + '@vitest/utils@3.2.7': + dependencies: + '@vitest/pretty-format': 3.2.7 + loupe: 3.2.1 + tinyrainbow: 2.0.0 + + '@volar/language-core@2.4.28': + dependencies: + '@volar/source-map': 2.4.28 + + '@volar/source-map@2.4.28': {} + + '@volar/typescript@2.4.28': + dependencies: + '@volar/language-core': 2.4.28 + path-browserify: 1.0.1 + vscode-uri: 3.1.0 + + '@vue/compiler-core@3.5.39': + dependencies: + '@babel/parser': 7.29.7 + '@vue/shared': 3.5.39 + entities: 7.0.1 + estree-walker: 2.0.2 + source-map-js: 1.2.1 + + '@vue/compiler-dom@3.5.39': + dependencies: + '@vue/compiler-core': 3.5.39 + '@vue/shared': 3.5.39 + + '@vue/compiler-sfc@3.5.39': + dependencies: + '@babel/parser': 7.29.7 + '@vue/compiler-core': 3.5.39 + '@vue/compiler-dom': 3.5.39 + '@vue/compiler-ssr': 3.5.39 + '@vue/shared': 3.5.39 + estree-walker: 2.0.2 + magic-string: 0.30.21 + postcss: 8.5.18 + source-map-js: 1.2.1 + + '@vue/compiler-ssr@3.5.39': + dependencies: + '@vue/compiler-dom': 3.5.39 + '@vue/shared': 3.5.39 + + '@vue/devtools-api@6.6.4': {} + + '@vue/devtools-api@7.7.10': + dependencies: + '@vue/devtools-kit': 7.7.10 + + '@vue/devtools-kit@7.7.10': + dependencies: + '@vue/devtools-shared': 7.7.10 + birpc: 2.9.0 + hookable: 5.5.3 + mitt: 3.0.1 + perfect-debounce: 1.0.0 + speakingurl: 14.0.1 + superjson: 2.2.6 + + '@vue/devtools-shared@7.7.10': + dependencies: + rfdc: 1.4.1 + + '@vue/language-core@3.3.7': + dependencies: + '@volar/language-core': 2.4.28 + '@vue/compiler-dom': 3.5.39 + '@vue/shared': 3.5.39 + alien-signals: 3.2.1 + muggle-string: 0.4.1 + path-browserify: 1.0.1 + picomatch: 4.0.5 + + '@vue/reactivity@3.5.39': + dependencies: + '@vue/shared': 3.5.39 + + '@vue/runtime-core@3.5.39': + dependencies: + '@vue/reactivity': 3.5.39 + '@vue/shared': 3.5.39 + + '@vue/runtime-dom@3.5.39': + dependencies: + '@vue/reactivity': 3.5.39 + '@vue/runtime-core': 3.5.39 + '@vue/shared': 3.5.39 + csstype: 3.2.3 + + '@vue/server-renderer@3.5.39(vue@3.5.39(typescript@5.9.3))': + dependencies: + '@vue/compiler-ssr': 3.5.39 + '@vue/shared': 3.5.39 + vue: 3.5.39(typescript@5.9.3) + + '@vue/shared@3.5.39': {} + + '@vue/test-utils@2.4.11(@vue/compiler-dom@3.5.39)(@vue/server-renderer@3.5.39(vue@3.5.39(typescript@5.9.3)))(vue@3.5.39(typescript@5.9.3))': + dependencies: + '@vue/compiler-dom': 3.5.39 + js-beautify: 1.15.4 + vue: 3.5.39(typescript@5.9.3) + vue-component-type-helpers: 3.3.7 + optionalDependencies: + '@vue/server-renderer': 3.5.39(vue@3.5.39(typescript@5.9.3)) + + abbrev@2.0.0: {} + + abslink@1.2.2: {} + + abstract-logging@2.0.1: {} + + agent-base@7.1.4: {} + + ajv-formats@3.0.1(ajv@8.20.0): + optionalDependencies: + ajv: 8.20.0 + + ajv@8.20.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-uri: 3.1.3 + json-schema-traverse: 1.0.0 + require-from-string: 2.0.2 + + alien-signals@3.2.1: {} + + ansi-regex@5.0.1: {} + + ansi-regex@6.2.2: {} + + ansi-styles@4.3.0: + dependencies: + color-convert: 2.0.1 + + ansi-styles@6.2.3: {} + + argon2@0.44.0: + dependencies: + '@phc/format': 1.0.0 + cross-env: 10.1.0 + node-addon-api: 8.9.0 + node-gyp-build: 4.8.4 + + assertion-error@2.0.1: {} + + atomic-sleep@1.0.0: {} + + avvio@9.2.0: + dependencies: + '@fastify/error': 4.2.0 + fastq: 1.20.1 + + balanced-match@1.0.2: {} + + birpc@2.9.0: {} + + brace-expansion@2.1.2: + dependencies: + balanced-match: 1.0.2 + + buffer-from@1.1.2: {} + + bullmq@5.80.2: + dependencies: + cron-parser: 4.9.0 + ioredis: 5.10.1 + msgpackr: 2.0.4 + node-abort-controller: 3.1.1 + semver: 7.8.5 + tslib: 2.8.1 + transitivePeerDependencies: + - supports-color + + cac@6.7.14: {} + + chai@5.3.3: + dependencies: + assertion-error: 2.0.1 + check-error: 2.1.3 + deep-eql: 5.0.2 + loupe: 3.2.1 + pathval: 2.0.1 + + check-error@2.1.3: {} + + cluster-key-slot@1.1.2: {} + + color-convert@2.0.1: + dependencies: + color-name: 1.1.4 + + color-name@1.1.4: {} + + commander@10.0.1: {} + + config-chain@1.1.13: + dependencies: + ini: 1.3.8 + proto-list: 1.2.4 + + cookie@1.1.1: {} + + cookie@2.0.1: {} + + copy-anything@4.0.5: + dependencies: + is-what: 5.5.0 + + cron-parser@4.9.0: + dependencies: + luxon: 3.7.2 + + cross-env@10.1.0: + dependencies: + '@epic-web/invariant': 1.0.0 + cross-spawn: 7.0.6 + + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + + cssstyle@4.6.0: + dependencies: + '@asamuzakjp/css-color': 3.2.0 + rrweb-cssom: 0.8.0 + + csstype@3.2.3: {} + + data-urls@5.0.0: + dependencies: + whatwg-mimetype: 4.0.0 + whatwg-url: 14.2.0 + + debug@4.4.3: + dependencies: + ms: 2.1.3 + + decimal.js@10.6.0: {} + + deep-eql@5.0.2: {} + + denque@2.1.0: {} + + dequal@2.0.3: {} + + detect-libc@2.1.2: + optional: true + + drizzle-kit@0.31.10: + dependencies: + '@drizzle-team/brocli': 0.10.2 + '@esbuild-kit/esm-loader': 2.6.5 + esbuild: 0.25.12 + tsx: 4.23.1 + + drizzle-orm@0.45.2(postgres@3.4.9): + optionalDependencies: + postgres: 3.4.9 + + eastasianwidth@0.2.0: {} + + editorconfig@1.0.7: + dependencies: + '@one-ini/wasm': 0.1.1 + commander: 10.0.1 + minimatch: 9.0.9 + semver: 7.8.5 + + emoji-regex@8.0.0: {} + + emoji-regex@9.2.2: {} + + entities@6.0.1: {} + + entities@7.0.1: {} + + es-module-lexer@1.7.0: {} + + esbuild@0.18.20: + optionalDependencies: + '@esbuild/android-arm': 0.18.20 + '@esbuild/android-arm64': 0.18.20 + '@esbuild/android-x64': 0.18.20 + '@esbuild/darwin-arm64': 0.18.20 + '@esbuild/darwin-x64': 0.18.20 + '@esbuild/freebsd-arm64': 0.18.20 + '@esbuild/freebsd-x64': 0.18.20 + '@esbuild/linux-arm': 0.18.20 + '@esbuild/linux-arm64': 0.18.20 + '@esbuild/linux-ia32': 0.18.20 + '@esbuild/linux-loong64': 0.18.20 + '@esbuild/linux-mips64el': 0.18.20 + '@esbuild/linux-ppc64': 0.18.20 + '@esbuild/linux-riscv64': 0.18.20 + '@esbuild/linux-s390x': 0.18.20 + '@esbuild/linux-x64': 0.18.20 + '@esbuild/netbsd-x64': 0.18.20 + '@esbuild/openbsd-x64': 0.18.20 + '@esbuild/sunos-x64': 0.18.20 + '@esbuild/win32-arm64': 0.18.20 + '@esbuild/win32-ia32': 0.18.20 + '@esbuild/win32-x64': 0.18.20 + + esbuild@0.25.12: + optionalDependencies: + '@esbuild/aix-ppc64': 0.25.12 + '@esbuild/android-arm': 0.25.12 + '@esbuild/android-arm64': 0.25.12 + '@esbuild/android-x64': 0.25.12 + '@esbuild/darwin-arm64': 0.25.12 + '@esbuild/darwin-x64': 0.25.12 + '@esbuild/freebsd-arm64': 0.25.12 + '@esbuild/freebsd-x64': 0.25.12 + '@esbuild/linux-arm': 0.25.12 + '@esbuild/linux-arm64': 0.25.12 + '@esbuild/linux-ia32': 0.25.12 + '@esbuild/linux-loong64': 0.25.12 + '@esbuild/linux-mips64el': 0.25.12 + '@esbuild/linux-ppc64': 0.25.12 + '@esbuild/linux-riscv64': 0.25.12 + '@esbuild/linux-s390x': 0.25.12 + '@esbuild/linux-x64': 0.25.12 + '@esbuild/netbsd-arm64': 0.25.12 + '@esbuild/netbsd-x64': 0.25.12 + '@esbuild/openbsd-arm64': 0.25.12 + '@esbuild/openbsd-x64': 0.25.12 + '@esbuild/openharmony-arm64': 0.25.12 + '@esbuild/sunos-x64': 0.25.12 + '@esbuild/win32-arm64': 0.25.12 + '@esbuild/win32-ia32': 0.25.12 + '@esbuild/win32-x64': 0.25.12 + + esbuild@0.28.1: + optionalDependencies: + '@esbuild/aix-ppc64': 0.28.1 + '@esbuild/android-arm': 0.28.1 + '@esbuild/android-arm64': 0.28.1 + '@esbuild/android-x64': 0.28.1 + '@esbuild/darwin-arm64': 0.28.1 + '@esbuild/darwin-x64': 0.28.1 + '@esbuild/freebsd-arm64': 0.28.1 + '@esbuild/freebsd-x64': 0.28.1 + '@esbuild/linux-arm': 0.28.1 + '@esbuild/linux-arm64': 0.28.1 + '@esbuild/linux-ia32': 0.28.1 + '@esbuild/linux-loong64': 0.28.1 + '@esbuild/linux-mips64el': 0.28.1 + '@esbuild/linux-ppc64': 0.28.1 + '@esbuild/linux-riscv64': 0.28.1 + '@esbuild/linux-s390x': 0.28.1 + '@esbuild/linux-x64': 0.28.1 + '@esbuild/netbsd-arm64': 0.28.1 + '@esbuild/netbsd-x64': 0.28.1 + '@esbuild/openbsd-arm64': 0.28.1 + '@esbuild/openbsd-x64': 0.28.1 + '@esbuild/openharmony-arm64': 0.28.1 + '@esbuild/sunos-x64': 0.28.1 + '@esbuild/win32-arm64': 0.28.1 + '@esbuild/win32-ia32': 0.28.1 + '@esbuild/win32-x64': 0.28.1 + + estree-walker@2.0.2: {} + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.9 + + expect-type@1.4.0: {} + + fast-decode-uri-component@1.0.1: {} + + fast-deep-equal@3.1.3: {} + + fast-json-stringify@7.0.1: + dependencies: + '@fastify/merge-json-schemas': 0.2.1 + ajv: 8.20.0 + ajv-formats: 3.0.1(ajv@8.20.0) + fast-uri: 4.1.0 + json-schema-ref-resolver: 3.0.0 + rfdc: 1.4.1 + + fast-querystring@1.1.2: + dependencies: + fast-decode-uri-component: 1.0.1 + + fast-uri@3.1.3: {} + + fast-uri@4.1.0: {} + + fastify-plugin@5.1.0: {} + + fastify-plugin@6.0.0: {} + + fastify@5.10.0: + dependencies: + '@fastify/ajv-compiler': 4.0.5 + '@fastify/error': 4.2.0 + '@fastify/fast-json-stringify-compiler': 5.1.0 + '@fastify/proxy-addr': 5.1.0 + abstract-logging: 2.0.1 + avvio: 9.2.0 + fast-json-stringify: 7.0.1 + find-my-way: 9.6.0 + light-my-request: 6.6.0 + pino: 10.3.1 + process-warning: 5.0.0 + rfdc: 1.4.1 + secure-json-parse: 4.1.0 + semver: 7.8.5 + toad-cache: 3.7.4 + + fastq@1.20.1: + dependencies: + reusify: 1.1.0 + + fdir@6.5.0(picomatch@4.0.5): + optionalDependencies: + picomatch: 4.0.5 + + find-my-way@9.6.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-querystring: 1.1.2 + safe-regex2: 5.1.1 + + foreground-child@3.3.1: + dependencies: + cross-spawn: 7.0.6 + signal-exit: 4.1.0 + + fsevents@2.3.3: + optional: true + + get-tsconfig@4.14.0: + dependencies: + resolve-pkg-maps: 1.0.0 + + glob@10.5.0: + dependencies: + foreground-child: 3.3.1 + jackspeak: 3.4.3 + minimatch: 9.0.9 + minipass: 7.1.3 + package-json-from-dist: 1.0.1 + path-scurry: 1.11.1 + + helmet@8.3.0: {} + + hls.js@1.6.16: {} + + hookable@5.5.3: {} + + html-encoding-sniffer@4.0.0: + dependencies: + whatwg-encoding: 3.1.1 + + http-proxy-agent@7.0.2: + dependencies: + agent-base: 7.1.4 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + https-proxy-agent@7.0.6: + dependencies: + agent-base: 7.1.4 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + iconv-lite@0.6.3: + dependencies: + safer-buffer: 2.1.2 + + ini@1.3.8: {} + + ioredis@5.10.1: + dependencies: + '@ioredis/commands': 1.5.1 + cluster-key-slot: 1.1.2 + debug: 4.4.3 + denque: 2.1.0 + lodash.defaults: 4.2.0 + lodash.isarguments: 3.1.0 + redis-errors: 1.2.0 + redis-parser: 3.0.0 + standard-as-callback: 2.1.0 + transitivePeerDependencies: + - supports-color + + ipaddr.js@2.4.0: {} + + is-fullwidth-code-point@3.0.0: {} + + is-potential-custom-element-name@1.0.1: {} + + is-what@5.5.0: {} + + isexe@2.0.0: {} + + jackspeak@3.4.3: + dependencies: + '@isaacs/cliui': 8.0.2 + optionalDependencies: + '@pkgjs/parseargs': 0.11.0 + + jassub@2.5.7: + dependencies: + abslink: 1.2.2 + lfa-ponyfill: 1.1.1 + rvfc-polyfill: 1.0.8 + throughput: 1.0.2 + + js-beautify@1.15.4: + dependencies: + config-chain: 1.1.13 + editorconfig: 1.0.7 + glob: 10.5.0 + js-cookie: 3.0.8 + nopt: 7.2.1 + + js-cookie@3.0.8: {} + + js-tokens@9.0.1: {} + + jsdom@26.1.0: + dependencies: + cssstyle: 4.6.0 + data-urls: 5.0.0 + decimal.js: 10.6.0 + html-encoding-sniffer: 4.0.0 + http-proxy-agent: 7.0.2 + https-proxy-agent: 7.0.6 + is-potential-custom-element-name: 1.0.1 + nwsapi: 2.2.24 + parse5: 7.3.0 + rrweb-cssom: 0.8.0 + saxes: 6.0.0 + symbol-tree: 3.2.4 + tough-cookie: 5.1.2 + w3c-xmlserializer: 5.0.0 + webidl-conversions: 7.0.0 + whatwg-encoding: 3.1.1 + whatwg-mimetype: 4.0.0 + whatwg-url: 14.2.0 + ws: 8.21.0 + xml-name-validator: 5.0.0 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + + json-schema-ref-resolver@3.0.0: + dependencies: + dequal: 2.0.3 + + json-schema-traverse@1.0.0: {} + + lfa-ponyfill@1.1.1: {} + + light-my-request@6.6.0: + dependencies: + cookie: 1.1.1 + process-warning: 4.0.1 + set-cookie-parser: 2.7.2 + + lodash.defaults@4.2.0: {} + + lodash.isarguments@3.1.0: {} + + loupe@3.2.1: {} + + lru-cache@10.4.3: {} + + luxon@3.7.2: {} + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + + minimatch@9.0.9: + dependencies: + brace-expansion: 2.1.2 + + minipass@7.1.3: {} + + mitt@3.0.1: {} + + ms@2.1.3: {} + + msgpackr-extract@3.0.4: + dependencies: + node-gyp-build-optional-packages: 5.2.2 + optionalDependencies: + '@msgpackr-extract/msgpackr-extract-darwin-arm64': 3.0.4 + '@msgpackr-extract/msgpackr-extract-darwin-x64': 3.0.4 + '@msgpackr-extract/msgpackr-extract-linux-arm': 3.0.4 + '@msgpackr-extract/msgpackr-extract-linux-arm64': 3.0.4 + '@msgpackr-extract/msgpackr-extract-linux-x64': 3.0.4 + '@msgpackr-extract/msgpackr-extract-win32-x64': 3.0.4 + optional: true + + msgpackr@2.0.4: + optionalDependencies: + msgpackr-extract: 3.0.4 + + muggle-string@0.4.1: {} + + nanoid@3.3.16: {} + + node-abort-controller@3.1.1: {} + + node-addon-api@8.9.0: {} + + node-gyp-build-optional-packages@5.2.2: + dependencies: + detect-libc: 2.1.2 + optional: true + + node-gyp-build@4.8.4: {} + + nopt@7.2.1: + dependencies: + abbrev: 2.0.0 + + nwsapi@2.2.24: {} + + on-exit-leak-free@2.1.2: {} + + package-json-from-dist@1.0.1: {} + + parse5@7.3.0: + dependencies: + entities: 6.0.1 + + path-browserify@1.0.1: {} + + path-key@3.1.1: {} + + path-scurry@1.11.1: + dependencies: + lru-cache: 10.4.3 + minipass: 7.1.3 + + pathe@2.0.3: {} + + pathval@2.0.1: {} + + perfect-debounce@1.0.0: {} + + picocolors@1.1.1: {} + + picomatch@4.0.5: {} + + pinia@3.0.4(typescript@5.9.3)(vue@3.5.39(typescript@5.9.3)): + dependencies: + '@vue/devtools-api': 7.7.10 + vue: 3.5.39(typescript@5.9.3) + optionalDependencies: + typescript: 5.9.3 + + pino-abstract-transport@3.0.0: + dependencies: + split2: 4.2.0 + + pino-std-serializers@7.1.0: {} + + pino@10.3.1: + dependencies: + '@pinojs/redact': 0.4.0 + atomic-sleep: 1.0.0 + on-exit-leak-free: 2.1.2 + pino-abstract-transport: 3.0.0 + pino-std-serializers: 7.1.0 + process-warning: 5.0.0 + quick-format-unescaped: 4.0.4 + real-require: 0.2.0 + safe-stable-stringify: 2.5.0 + sonic-boom: 4.2.1 + thread-stream: 4.2.0 + + postcss@8.5.18: + dependencies: + nanoid: 3.3.16 + picocolors: 1.1.1 + source-map-js: 1.2.1 + + postgres@3.4.9: {} + + process-warning@4.0.1: {} + + process-warning@5.0.0: {} + + proto-list@1.2.4: {} + + punycode@2.3.1: {} + + quick-format-unescaped@4.0.4: {} + + real-require@0.2.0: {} + + real-require@1.0.0: {} + + redis-errors@1.2.0: {} + + redis-parser@3.0.0: + dependencies: + redis-errors: 1.2.0 + + require-from-string@2.0.2: {} + + resolve-pkg-maps@1.0.0: {} + + ret@0.5.0: {} + + reusify@1.1.0: {} + + rfdc@1.4.1: {} + + rollup@4.62.2: + dependencies: + '@types/estree': 1.0.9 + optionalDependencies: + '@rollup/rollup-android-arm-eabi': 4.62.2 + '@rollup/rollup-android-arm64': 4.62.2 + '@rollup/rollup-darwin-arm64': 4.62.2 + '@rollup/rollup-darwin-x64': 4.62.2 + '@rollup/rollup-freebsd-arm64': 4.62.2 + '@rollup/rollup-freebsd-x64': 4.62.2 + '@rollup/rollup-linux-arm-gnueabihf': 4.62.2 + '@rollup/rollup-linux-arm-musleabihf': 4.62.2 + '@rollup/rollup-linux-arm64-gnu': 4.62.2 + '@rollup/rollup-linux-arm64-musl': 4.62.2 + '@rollup/rollup-linux-loong64-gnu': 4.62.2 + '@rollup/rollup-linux-loong64-musl': 4.62.2 + '@rollup/rollup-linux-ppc64-gnu': 4.62.2 + '@rollup/rollup-linux-ppc64-musl': 4.62.2 + '@rollup/rollup-linux-riscv64-gnu': 4.62.2 + '@rollup/rollup-linux-riscv64-musl': 4.62.2 + '@rollup/rollup-linux-s390x-gnu': 4.62.2 + '@rollup/rollup-linux-x64-gnu': 4.62.2 + '@rollup/rollup-linux-x64-musl': 4.62.2 + '@rollup/rollup-openbsd-x64': 4.62.2 + '@rollup/rollup-openharmony-arm64': 4.62.2 + '@rollup/rollup-win32-arm64-msvc': 4.62.2 + '@rollup/rollup-win32-ia32-msvc': 4.62.2 + '@rollup/rollup-win32-x64-gnu': 4.62.2 + '@rollup/rollup-win32-x64-msvc': 4.62.2 + fsevents: 2.3.3 + + rrweb-cssom@0.8.0: {} + + rvfc-polyfill@1.0.8: {} + + safe-regex2@5.1.1: + dependencies: + ret: 0.5.0 + + safe-stable-stringify@2.5.0: {} + + safer-buffer@2.1.2: {} + + saxes@6.0.0: + dependencies: + xmlchars: 2.2.0 + + secure-json-parse@4.1.0: {} + + semver@7.8.5: {} + + set-cookie-parser@2.7.2: {} + + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@3.0.0: {} + + siginfo@2.0.0: {} + + signal-exit@4.1.0: {} + + sonic-boom@4.2.1: + dependencies: + atomic-sleep: 1.0.0 + + source-map-js@1.2.1: {} + + source-map-support@0.5.21: + dependencies: + buffer-from: 1.1.2 + source-map: 0.6.1 + + source-map@0.6.1: {} + + speakingurl@14.0.1: {} + + split2@4.2.0: {} + + stackback@0.0.2: {} + + standard-as-callback@2.1.0: {} + + std-env@3.10.0: {} + + string-width@4.2.3: + dependencies: + emoji-regex: 8.0.0 + is-fullwidth-code-point: 3.0.0 + strip-ansi: 6.0.1 + + string-width@5.1.2: + dependencies: + eastasianwidth: 0.2.0 + emoji-regex: 9.2.2 + strip-ansi: 7.2.0 + + strip-ansi@6.0.1: + dependencies: + ansi-regex: 5.0.1 + + strip-ansi@7.2.0: + dependencies: + ansi-regex: 6.2.2 + + strip-literal@3.1.0: + dependencies: + js-tokens: 9.0.1 + + superjson@2.2.6: + dependencies: + copy-anything: 4.0.5 + + symbol-tree@3.2.4: {} + + thread-stream@4.2.0: + dependencies: + real-require: 1.0.0 + + throughput@1.0.2: {} + + tinybench@2.9.0: {} + + tinyexec@0.3.2: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.5) + picomatch: 4.0.5 + + tinypool@1.1.1: {} + + tinyrainbow@2.0.0: {} + + tinyspy@4.0.4: {} + + tldts-core@6.1.86: {} + + tldts@6.1.86: + dependencies: + tldts-core: 6.1.86 + + toad-cache@3.7.4: {} + + tough-cookie@5.1.2: + dependencies: + tldts: 6.1.86 + + tr46@5.1.1: + dependencies: + punycode: 2.3.1 + + tslib@2.8.1: {} + + tsx@4.23.1: + dependencies: + esbuild: 0.28.1 + optionalDependencies: + fsevents: 2.3.3 + + typescript@5.9.3: {} + + undici-types@7.18.2: {} + + vite-node@3.2.4(@types/node@24.13.3)(tsx@4.23.1): + dependencies: + cac: 6.7.14 + debug: 4.4.3 + es-module-lexer: 1.7.0 + pathe: 2.0.3 + vite: 7.3.6(@types/node@24.13.3)(tsx@4.23.1) + transitivePeerDependencies: + - '@types/node' + - jiti + - less + - lightningcss + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + - tsx + - yaml + + vite@7.3.6(@types/node@24.13.3)(tsx@4.23.1): + dependencies: + esbuild: 0.28.1 + fdir: 6.5.0(picomatch@4.0.5) + picomatch: 4.0.5 + postcss: 8.5.18 + rollup: 4.62.2 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 24.13.3 + fsevents: 2.3.3 + tsx: 4.23.1 + + vitest@3.2.7(@types/node@24.13.3)(jsdom@26.1.0)(tsx@4.23.1): + dependencies: + '@types/chai': 5.2.3 + '@vitest/expect': 3.2.7 + '@vitest/mocker': 3.2.7(vite@7.3.6(@types/node@24.13.3)(tsx@4.23.1)) + '@vitest/pretty-format': 3.2.7 + '@vitest/runner': 3.2.7 + '@vitest/snapshot': 3.2.7 + '@vitest/spy': 3.2.7 + '@vitest/utils': 3.2.7 + chai: 5.3.3 + debug: 4.4.3 + expect-type: 1.4.0 + magic-string: 0.30.21 + pathe: 2.0.3 + picomatch: 4.0.5 + std-env: 3.10.0 + tinybench: 2.9.0 + tinyexec: 0.3.2 + tinyglobby: 0.2.17 + tinypool: 1.1.1 + tinyrainbow: 2.0.0 + vite: 7.3.6(@types/node@24.13.3)(tsx@4.23.1) + vite-node: 3.2.4(@types/node@24.13.3)(tsx@4.23.1) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 24.13.3 + jsdom: 26.1.0 + transitivePeerDependencies: + - jiti + - less + - lightningcss + - msw + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + - tsx + - yaml + + vscode-uri@3.1.0: {} + + vue-component-type-helpers@3.3.7: {} + + vue-router@4.6.4(vue@3.5.39(typescript@5.9.3)): + dependencies: + '@vue/devtools-api': 6.6.4 + vue: 3.5.39(typescript@5.9.3) + + vue-tsc@3.3.7(typescript@5.9.3): + dependencies: + '@volar/typescript': 2.4.28 + '@vue/language-core': 3.3.7 + typescript: 5.9.3 + + vue@3.5.39(typescript@5.9.3): + dependencies: + '@vue/compiler-dom': 3.5.39 + '@vue/compiler-sfc': 3.5.39 + '@vue/runtime-dom': 3.5.39 + '@vue/server-renderer': 3.5.39(vue@3.5.39(typescript@5.9.3)) + '@vue/shared': 3.5.39 + optionalDependencies: + typescript: 5.9.3 + + w3c-xmlserializer@5.0.0: + dependencies: + xml-name-validator: 5.0.0 + + webidl-conversions@7.0.0: {} + + whatwg-encoding@3.1.1: + dependencies: + iconv-lite: 0.6.3 + + whatwg-mimetype@4.0.0: {} + + whatwg-url@14.2.0: + dependencies: + tr46: 5.1.1 + webidl-conversions: 7.0.0 + + which@2.0.2: + dependencies: + isexe: 2.0.0 + + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + + wrap-ansi@7.0.0: + dependencies: + ansi-styles: 4.3.0 + string-width: 4.2.3 + strip-ansi: 6.0.1 + + wrap-ansi@8.1.0: + dependencies: + ansi-styles: 6.2.3 + string-width: 5.1.2 + strip-ansi: 7.2.0 + + ws@8.21.0: {} + + xml-name-validator@5.0.0: {} + + xmlchars@2.2.0: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 0000000..5528e1f --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,12 @@ +packages: + - "apps/*" + - "packages/*" + +allowBuilds: + argon2: true + esbuild: true + lfa-ponyfill: false + msgpackr-extract: false + +minimumReleaseAgeExclude: + - jassub@2.5.7 diff --git a/scripts/setup-ubuntu.sh b/scripts/setup-ubuntu.sh new file mode 100755 index 0000000..6886f73 --- /dev/null +++ b/scripts/setup-ubuntu.sh @@ -0,0 +1,713 @@ +#!/usr/bin/env bash + +set -Eeuo pipefail +IFS=$'\n\t' +umask 077 + +readonly SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)" +readonly DEFAULT_PROJECT_ROOT="$(cd -- "${SCRIPT_DIR}/.." && pwd -P)" +readonly PROJECT_ROOT="${EASY_STREAM_PROJECT_ROOT:-${DEFAULT_PROJECT_ROOT}}" +readonly ENV_FILE="${PROJECT_ROOT}/.env" + +NO_START=false +SKIP_DOCKER_INSTALL=false +VALIDATION_ERROR='' +CREATE_ARCHIVE=false +ENV_BACKUP='' +declare -a ROOT_COMMAND=() +declare -a DOCKER_COMMAND=() +declare -a CLEANUP_FILES=() + +cleanup() { + local file + for file in "${CLEANUP_FILES[@]:-}"; do + [[ -n "${file}" ]] && rm -f -- "${file}" + done + return 0 +} +trap cleanup EXIT + +info() { + printf '\n\033[1;34m==>\033[0m %s\n' "$*" +} + +success() { + printf '\033[1;32mOK:\033[0m %s\n' "$*" +} + +warn() { + printf '\033[1;33mWARNING:\033[0m %s\n' "$*" >&2 +} + +die() { + printf '\033[1;31mERROR:\033[0m %s\n' "$*" >&2 + exit 1 +} + +usage() { + cat <<'EOF' +Usage: bash scripts/setup-ubuntu.sh [options] + +Interactively configures Easy Stream on a fresh Ubuntu server. + +Options: + --no-start Write and validate configuration without building/starting containers. + --skip-docker-install Require an existing Docker Engine + Compose plugin installation. + -h, --help Show this help. + +The script must run from an interactive terminal. It never prints entered secrets. +EOF +} + +validation_failure() { + VALIDATION_ERROR="$1" + return 1 +} + +validate_nonempty() { + [[ -n "$1" ]] || validation_failure 'A value is required.' +} + +validate_env_string() { + local value="$1" + [[ -n "${value}" ]] || return 0 + if [[ "${value}" == *$'\n'* || "${value}" == *$'\r'* ]]; then + validation_failure 'Line breaks are not allowed.' + return 1 + fi + if [[ "${value}" == *"'"* ]]; then + validation_failure "Single quotes are not supported in generated .env values." + return 1 + fi +} + +validate_origin() { + local value="$1" + local authority port + if [[ "${value}" != https://* ]]; then + validation_failure 'Use an HTTPS origin, for example https://stream.example.com.' + return 1 + fi + authority="${value#https://}" + if [[ -z "${authority}" || "${authority}" == *'/'* || "${authority}" == *'?'* \ + || "${authority}" == *'#'* || "${authority}" == *' '* ]]; then + validation_failure 'Enter only the origin, without a path, query, fragment, or trailing slash.' + return 1 + fi + if [[ ! "${authority}" =~ ^([A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?|\[[0-9A-Fa-f:]+\])(:[0-9]{1,5})?$ ]]; then + validation_failure 'The HTTPS hostname or optional port is invalid.' + return 1 + fi + if [[ "${authority}" =~ :([0-9]{1,5})$ ]]; then + port="${BASH_REMATCH[1]}" + if ((10#${port} < 1 || 10#${port} > 65535)); then + validation_failure 'The HTTPS port must be between 1 and 65535.' + return 1 + fi + fi +} + +validate_email() { + local value="$1" + if [[ ! "${value}" =~ ^[^[:space:]@]+@[^[:space:]@]+\.[^[:space:]@]+$ ]]; then + validation_failure 'Enter a valid administrator email address.' + return 1 + fi + if ((${#value} > 320)); then + validation_failure 'The email address is too long.' + return 1 + fi + validate_env_string "${value}" +} + +validate_bind_address() { + local value="$1" + local -a octets=() + local octet + local IFS='.' + read -r -a octets <<< "${value}" + ((${#octets[@]} == 4)) \ + || validation_failure 'Enter an IPv4 bind address such as 127.0.0.1, 0.0.0.0, or a private interface address.' + ((${#octets[@]} == 4)) || return 1 + for octet in "${octets[@]}"; do + if [[ ! "${octet}" =~ ^[0-9]{1,3}$ ]] || ((10#${octet} > 255)); then + validation_failure 'Enter a valid IPv4 bind address.' + return 1 + fi + done +} + +validate_absolute_path() { + local value="$1" + if [[ "${value}" != /* ]]; then + validation_failure 'Use an absolute filesystem path.' + return 1 + fi + if [[ "${value}" == '/' ]]; then + validation_failure 'The filesystem root cannot be used here.' + return 1 + fi + if [[ "${value}" == *:* ]]; then + validation_failure 'Colon is not supported in Docker bind-mount paths.' + return 1 + fi + validate_env_string "${value}" +} + +validate_positive_integer() { + local value="$1" + [[ "${value}" =~ ^[1-9][0-9]*$ ]] \ + || validation_failure 'Enter a positive whole number.' +} + +validate_concurrency() { + local value="$1" + validate_positive_integer "${value}" || return 1 + ((value <= 64)) || validation_failure 'Concurrency must be 64 or lower.' +} + +validate_cache_gib() { + local value="$1" + validate_positive_integer "${value}" || return 1 + ((value >= 10 && value <= 1048576)) \ + || validation_failure 'Cache capacity must be between 10 GiB and 1 PiB.' +} + +validate_ttl() { + local value="$1" + validate_positive_integer "${value}" || return 1 + ((value >= 300 && value <= 86400)) \ + || validation_failure 'Playback TTL must be between 300 and 86400 seconds.' +} + +validate_postgres_password() { + local value="$1" + if ((${#value} < 24)); then + validation_failure 'Use at least 24 characters.' + return 1 + fi + if [[ ! "${value}" =~ ^[A-Za-z0-9_-]+$ ]]; then + validation_failure 'Use only letters, digits, underscore, and hyphen (the value is embedded in a database URL).' + return 1 + fi +} + +validate_safe_secret() { + local value="$1" + if ((${#value} < 32)); then + validation_failure 'Use at least 32 characters.' + return 1 + fi + if [[ ! "${value}" =~ ^[A-Za-z0-9_-]+$ ]]; then + validation_failure 'Use only base64url-safe letters, digits, underscore, and hyphen.' + return 1 + fi +} + +validate_admin_password() { + local value="$1" + if ((${#value} < 12)); then + validation_failure 'Use at least 12 characters.' + return 1 + fi + if [[ "${value}" == 'change-me-before-production' ]]; then + validation_failure 'The example password is forbidden.' + return 1 + fi + validate_env_string "${value}" +} + +validate_optional_token() { + validate_env_string "$1" +} + +prompt_value() { + local destination="$1" + local label="$2" + local default_value="$3" + local validator="$4" + local value + while true; do + VALIDATION_ERROR='' + if [[ -n "${default_value}" ]]; then + read -r -p "${label} [${default_value}]: " value + value="${value:-${default_value}}" + else + read -r -p "${label}: " value + fi + if "${validator}" "${value}"; then + printf -v "${destination}" '%s' "${value}" + return 0 + fi + warn "${VALIDATION_ERROR:-Invalid value.}" + done +} + +prompt_secret() { + local destination="$1" + local label="$2" + local validator="$3" + local allow_generate="$4" + local value confirmation + while true; do + VALIDATION_ERROR='' + if [[ "${allow_generate}" == true ]]; then + read -r -s -p "${label} (leave blank to generate): " value + else + read -r -s -p "${label}: " value + fi + printf '\n' + if [[ -z "${value}" && "${allow_generate}" == true ]]; then + value="$(generate_secret)" + printf -v "${destination}" '%s' "${value}" + return 0 + fi + if ! "${validator}" "${value}"; then + warn "${VALIDATION_ERROR:-Invalid value.}" + continue + fi + read -r -s -p "Confirm ${label}: " confirmation + printf '\n' + if [[ "${value}" != "${confirmation}" ]]; then + warn 'Values did not match; please try again.' + continue + fi + printf -v "${destination}" '%s' "${value}" + return 0 + done +} + +confirm() { + local prompt="$1" + local default_answer="${2:-no}" + local hint answer + if [[ "${default_answer}" == yes ]]; then + hint='Y/n' + else + hint='y/N' + fi + while true; do + read -r -p "${prompt} [${hint}]: " answer + answer="${answer:-${default_answer}}" + case "${answer,,}" in + y|yes) return 0 ;; + n|no) return 1 ;; + *) warn 'Answer yes or no.' ;; + esac + done +} + +generate_secret() { + od -An -N32 -tx1 /dev/urandom | tr -d ' \n' +} + +canonical_path() { + local input="$1" + if realpath -m -- "${input}" 2>/dev/null; then + return 0 + fi + # BSD realpath (useful when testing the helpers on macOS) has no -m. Resolve + # the nearest existing parent and append missing components. Ubuntu always + # takes the GNU realpath branch above. + local probe suffix='' + probe="${input%/}" + [[ -n "${probe}" ]] || probe='/' + while [[ ! -e "${probe}" && "${probe}" != '/' ]]; do + suffix="/$(basename -- "${probe}")${suffix}" + probe="$(dirname -- "${probe}")" + done + printf '%s%s\n' "$(realpath -- "${probe}")" "${suffix}" +} + +path_is_within() { + local root candidate + root="$(canonical_path "$1")" + candidate="$(canonical_path "$2")" + [[ "${candidate}" == "${root}" || "${candidate}" == "${root}/"* ]] +} + +assert_separate_paths() { + local -a labels=('archive' 'cache' 'derived' 'metadata') + local -a values=("${ARCHIVE_ROOT}" "${CACHE_ROOT}" "${DERIVED_ROOT}" "${METADATA_ROOT}") + local left right + for ((left = 0; left < ${#values[@]}; left += 1)); do + for ((right = left + 1; right < ${#values[@]}; right += 1)); do + if path_is_within "${values[left]}" "${values[right]}" \ + || path_is_within "${values[right]}" "${values[left]}"; then + die "${labels[left]} and ${labels[right]} paths must not overlap: ${values[left]} / ${values[right]}" + fi + done + done + for ((left = 1; left < ${#values[@]}; left += 1)); do + if path_is_within "${values[left]}" "${PROJECT_ROOT}"; then + die "The ${labels[left]} root must not contain the project checkout: ${values[left]}" + fi + done +} + +env_quote() { + local value="$1" + validate_env_string "${value}" || die "Cannot write .env value: ${VALIDATION_ERROR}" + printf "'%s'" "${value}" +} + +write_env_pair() { + local destination="$1" + local key="$2" + local value="$3" + printf '%s=%s\n' "${key}" "$(env_quote "${value}")" >> "${destination}" +} + +check_host() { + [[ -r /etc/os-release ]] || die 'Cannot identify this operating system.' + # shellcheck disable=SC1091 + source /etc/os-release + [[ "${ID:-}" == ubuntu ]] || die 'This bootstrap script supports Ubuntu only.' + [[ -n "${UBUNTU_CODENAME:-${VERSION_CODENAME:-}}" ]] \ + || die 'Ubuntu release codename is missing from /etc/os-release.' + command -v apt-get >/dev/null || die 'apt-get is required.' + command -v systemctl >/dev/null || die 'systemd is required.' + command -v realpath >/dev/null || die 'GNU realpath is required.' + [[ -f "${PROJECT_ROOT}/compose.yaml" && -f "${PROJECT_ROOT}/.env.example" ]] \ + || die "Run this script from a complete Easy Stream checkout (${PROJECT_ROOT})." + success "Detected Ubuntu ${VERSION_ID:-unknown} (${UBUNTU_CODENAME:-${VERSION_CODENAME}})." +} + +initialize_privilege() { + if ((EUID == 0)); then + ROOT_COMMAND=() + return 0 + fi + command -v sudo >/dev/null || die 'sudo is required when not running as root.' + info 'Requesting sudo access for package installation and host directories' + sudo -v + ROOT_COMMAND=(sudo) +} + +run_root() { + if ((${#ROOT_COMMAND[@]} == 0)); then + "$@" + else + "${ROOT_COMMAND[@]}" "$@" + fi +} + +docker_cli_available() { + command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1 +} + +install_docker() { + if docker_cli_available; then + run_root systemctl enable --now docker.service + success 'Docker Engine CLI and Compose plugin are already installed.' + return 0 + fi + if [[ "${SKIP_DOCKER_INSTALL}" == true ]]; then + die 'Docker Engine with the Compose plugin is required, but --skip-docker-install was used.' + fi + + info "Installing Docker Engine from Docker's official Ubuntu apt repository" + run_root apt-get update + run_root env DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates curl + + local -a conflicting=() + local package status + for package in docker.io docker-compose docker-compose-v2 docker-doc podman-docker containerd runc; do + status="$(dpkg-query -W -f='${db:Status-Abbrev}' "${package}" 2>/dev/null || true)" + [[ "${status}" == ii* ]] && conflicting+=("${package}") + done + if ((${#conflicting[@]} > 0)); then + warn "Conflicting distribution packages are installed: ${conflicting[*]}" + confirm 'Remove these packages before installing official Docker Engine?' no \ + || die 'Docker installation cancelled; remove conflicting packages manually or rerun with an existing supported Docker installation.' + run_root env DEBIAN_FRONTEND=noninteractive apt-get remove -y "${conflicting[@]}" + fi + + local key_tmp sources_tmp codename architecture + key_tmp="$(mktemp)" + sources_tmp="$(mktemp)" + CLEANUP_FILES+=("${key_tmp}" "${sources_tmp}") + curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o "${key_tmp}" + codename="${UBUNTU_CODENAME:-${VERSION_CODENAME}}" + architecture="$(dpkg --print-architecture)" + cat > "${sources_tmp}" </dev/null + success 'Docker Engine and the Compose plugin are installed and enabled.' +} + +select_docker_command() { + if docker info >/dev/null 2>&1; then + DOCKER_COMMAND=(docker) + elif run_root docker info >/dev/null 2>&1; then + DOCKER_COMMAND=("${ROOT_COMMAND[@]}" docker) + warn 'Docker commands require sudo for this user. The script does not add users to the root-equivalent docker group.' + else + die 'Docker daemon is not reachable after installation.' + fi +} + +prepare_directories() { + info 'Preparing read-only archive and writable media directories' + if [[ "${CREATE_ARCHIVE}" == true ]]; then + run_root install -d -o 1000 -g 1000 -m 0750 "${ARCHIVE_ROOT}" + fi + [[ -d "${ARCHIVE_ROOT}" ]] || die "Archive directory does not exist: ${ARCHIVE_ROOT}" + + local directory + for directory in "${CACHE_ROOT}" "${DERIVED_ROOT}" "${METADATA_ROOT}"; do + [[ ! -L "${directory}" ]] || die "Writable roots cannot be symlinks: ${directory}" + run_root install -d -o 1000 -g 1000 -m 0750 "${directory}" + done + + if command -v setpriv >/dev/null 2>&1; then + if ! run_root setpriv --reuid=1000 --regid=1000 --clear-groups /usr/bin/test -r "${ARCHIVE_ROOT}" \ + || ! run_root setpriv --reuid=1000 --regid=1000 --clear-groups /usr/bin/test -x "${ARCHIVE_ROOT}"; then + warn 'Container UID/GID 1000 cannot read/traverse the archive root. Adjust mount ownership or ACLs before scanning.' + fi + fi + + if command -v findmnt >/dev/null 2>&1; then + local mount_options + mount_options="$(findmnt -no OPTIONS --target "${ARCHIVE_ROOT}" 2>/dev/null || true)" + if [[ -n "${mount_options}" && ",${mount_options}," != *,ro,* ]]; then + warn 'The host archive filesystem is writable. Compose still mounts it read-only, but a read-only host mount is safer.' + fi + fi + + local available_bytes + available_bytes="$(df --output=avail -B1 "${CACHE_ROOT}" | tail -n 1 | tr -d ' ')" + if [[ "${available_bytes}" =~ ^[0-9]+$ ]] && ((available_bytes < CACHE_MAX_BYTES)); then + warn "Cache limit (${CACHE_GIB} GiB) exceeds currently available space ($((${available_bytes} / 1073741824)) GiB)." + fi + success 'Host directories are ready for container UID/GID 1000.' +} + +write_environment() { + info 'Writing protected production environment configuration' + local temporary + temporary="$(mktemp "${PROJECT_ROOT}/.env.tmp.XXXXXX")" + CLEANUP_FILES+=("${temporary}") + chmod 0600 "${temporary}" + cat > "${temporary}" <<'EOF' +# Generated by scripts/setup-ubuntu.sh. Keep this file secret and out of backups shared with developers. +NODE_ENV=production +HOST=0.0.0.0 +PORT=3000 +REPOSITORY_DRIVER=postgres +EOF + write_env_pair "${temporary}" POSTGRES_PASSWORD "${POSTGRES_PASSWORD}" + write_env_pair "${temporary}" WEB_ORIGIN "${PUBLIC_ORIGIN}" + write_env_pair "${temporary}" PUBLIC_ORIGIN "${PUBLIC_ORIGIN}" + write_env_pair "${temporary}" MEDIA_PUBLIC_BASE_URL "${PUBLIC_ORIGIN}/media" + write_env_pair "${temporary}" GATEWAY_BIND_ADDRESS "${GATEWAY_BIND_ADDRESS}" + write_env_pair "${temporary}" ARCHIVE_ROOT "${ARCHIVE_ROOT}" + write_env_pair "${temporary}" CACHE_ROOT "${CACHE_ROOT}" + write_env_pair "${temporary}" DERIVED_ROOT "${DERIVED_ROOT}" + write_env_pair "${temporary}" METADATA_ROOT "${METADATA_ROOT}" + write_env_pair "${temporary}" PLAYBACK_PROFILE 'cmaf-v1' + write_env_pair "${temporary}" PLAYBACK_SIGNING_SECRET "${PLAYBACK_SIGNING_SECRET}" + write_env_pair "${temporary}" MEDIA_AUTH_SHARED_SECRET "${MEDIA_AUTH_SHARED_SECRET}" + printf 'PLAYBACK_TTL_SECONDS=%s\n' "${PLAYBACK_TTL_SECONDS}" >> "${temporary}" + write_env_pair "${temporary}" ADMIN_BOOTSTRAP_EMAIL "${ADMIN_BOOTSTRAP_EMAIL}" + write_env_pair "${temporary}" ADMIN_BOOTSTRAP_PASSWORD "${ADMIN_BOOTSTRAP_PASSWORD}" + printf 'ADMIN_SESSION_TTL_SECONDS=28800\n' >> "${temporary}" + write_env_pair "${temporary}" TMDB_API_TOKEN "${TMDB_API_TOKEN}" + printf 'TMDB_COMMERCIAL_LICENSE_CONFIRMED=%s\n' "${TMDB_COMMERCIAL_LICENSE_CONFIRMED}" >> "${temporary}" + printf 'JIT_REMUX_CONCURRENCY=%s\n' "${JIT_REMUX_CONCURRENCY}" >> "${temporary}" + printf 'ENCODE_CONCURRENCY=1\n' >> "${temporary}" + printf 'CACHE_HIGH_WATERMARK=0.85\n' >> "${temporary}" + printf 'CACHE_LOW_WATERMARK=0.75\n' >> "${temporary}" + printf 'CACHE_MAX_BYTES=%s\n' "${CACHE_MAX_BYTES}" >> "${temporary}" + + if [[ -e "${ENV_FILE}" ]]; then + ENV_BACKUP="${ENV_FILE}.backup.$(date -u +%Y%m%dT%H%M%SZ).$$" + run_root cp -p -- "${ENV_FILE}" "${ENV_BACKUP}" + run_root chmod 0600 "${ENV_BACKUP}" + fi + mv -f -- "${temporary}" "${ENV_FILE}" + local owner_uid owner_gid + owner_uid="${SUDO_UID:-$(id -u)}" + owner_gid="${SUDO_GID:-$(id -g)}" + run_root chown "${owner_uid}:${owner_gid}" "${ENV_FILE}" + chmod 0600 "${ENV_FILE}" + success "Wrote ${ENV_FILE} with mode 0600." + [[ -z "${ENV_BACKUP}" ]] || success "Preserved the previous environment at ${ENV_BACKUP}." +} + +restore_environment() { + if [[ -n "${ENV_BACKUP}" && -f "${ENV_BACKUP}" ]]; then + run_root cp -p -- "${ENV_BACKUP}" "${ENV_FILE}" + warn "Restored the previous ${ENV_FILE} because Compose validation failed." + else + rm -f -- "${ENV_FILE}" + warn "Removed the invalid ${ENV_FILE}." + fi +} + +validate_compose() { + info 'Validating the generated Compose configuration' + if ! (cd "${PROJECT_ROOT}" && "${DOCKER_COMMAND[@]}" compose --env-file .env config --quiet); then + restore_environment + die 'Docker Compose rejected the generated configuration.' + fi + success 'Docker Compose accepted the generated production configuration.' +} + +start_stack() { + info 'Building Easy Stream images (the first FFmpeg build can take several minutes)' + (cd "${PROJECT_ROOT}" && "${DOCKER_COMMAND[@]}" compose --env-file .env build) + info 'Starting PostgreSQL, Redis, migrations, API, worker, and gateway' + (cd "${PROJECT_ROOT}" && "${DOCKER_COMMAND[@]}" compose --env-file .env up -d) + (cd "${PROJECT_ROOT}" && "${DOCKER_COMMAND[@]}" compose --env-file .env ps) +} + +collect_configuration() { + info 'Production values (secrets are hidden and never printed)' + prompt_value PUBLIC_ORIGIN 'Public HTTPS origin' '' validate_origin + prompt_value GATEWAY_BIND_ADDRESS 'Gateway host bind address' '127.0.0.1' validate_bind_address + + local archive_input + prompt_value archive_input 'Archive directory' '/srv/easy-stream/archive' validate_absolute_path + ARCHIVE_ROOT="$(canonical_path "${archive_input}")" + if [[ ! -d "${ARCHIVE_ROOT}" ]]; then + warn "Archive directory does not exist: ${ARCHIVE_ROOT}" + if confirm 'Create an empty archive directory during setup?' no; then + CREATE_ARCHIVE=true + else + die 'Mount or create the archive directory, then rerun setup.' + fi + fi + + local path_input + prompt_value path_input 'Disposable HLS cache directory' '/srv/easy-stream/cache' validate_absolute_path + CACHE_ROOT="$(canonical_path "${path_input}")" + prompt_value path_input 'Durable compatibility-media directory' '/srv/easy-stream/derived' validate_absolute_path + DERIVED_ROOT="$(canonical_path "${path_input}")" + prompt_value path_input 'Metadata and registry directory' '/srv/easy-stream/metadata' validate_absolute_path + METADATA_ROOT="$(canonical_path "${path_input}")" + assert_separate_paths + + prompt_value CACHE_GIB 'Maximum disposable cache size in GiB' '2048' validate_cache_gib + CACHE_MAX_BYTES=$((CACHE_GIB * 1073741824)) + local default_concurrency=2 + if command -v nproc >/dev/null 2>&1 && (( $(nproc) < 4 )); then + default_concurrency=1 + fi + prompt_value JIT_REMUX_CONCURRENCY 'Concurrent on-demand remux jobs' "${default_concurrency}" validate_concurrency + prompt_value PLAYBACK_TTL_SECONDS 'Playback authorization lifetime in seconds' '14400' validate_ttl + prompt_value ADMIN_BOOTSTRAP_EMAIL 'Initial administrator email' '' validate_email + + prompt_secret POSTGRES_PASSWORD 'PostgreSQL password' validate_postgres_password true + prompt_secret PLAYBACK_SIGNING_SECRET 'Playback signing secret' validate_safe_secret true + while true; do + prompt_secret MEDIA_AUTH_SHARED_SECRET 'Gateway media-auth secret' validate_safe_secret true + [[ "${MEDIA_AUTH_SHARED_SECRET}" != "${PLAYBACK_SIGNING_SECRET}" ]] && break + warn 'The gateway and playback signing secrets must be different.' + done + prompt_secret ADMIN_BOOTSTRAP_PASSWORD 'Initial administrator password' validate_admin_password false + + read -r -s -p 'TMDB API token (optional; leave blank to disable): ' TMDB_API_TOKEN + printf '\n' + VALIDATION_ERROR='' + validate_optional_token "${TMDB_API_TOKEN}" \ + || die "Invalid TMDB token: ${VALIDATION_ERROR}" + TMDB_COMMERCIAL_LICENSE_CONFIRMED=false + if [[ -n "${TMDB_API_TOKEN}" ]]; then + if confirm 'Do you have written confirmation permitting commercial TMDB use?' no; then + TMDB_COMMERCIAL_LICENSE_CONFIRMED=true + else + warn 'TMDB integration will remain disabled because commercial permission was not confirmed.' + TMDB_API_TOKEN='' + fi + fi + + if [[ -e "${ENV_FILE}" ]]; then + warn "An existing ${ENV_FILE} will be backed up before replacement." + confirm 'Replace the current environment configuration?' no \ + || die 'Setup cancelled without changing the existing environment.' + fi +} + +show_summary() { + info 'Review configuration' + cat <