diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 0000000..8847bc9 --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,29 @@ +name: docker + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + build: + name: ${{ matrix.service }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + service: [fetcher, generator, edge] + steps: + - uses: actions/checkout@v4 + + - uses: docker/setup-buildx-action@v3 + + - name: Build ${{ matrix.service }} image + uses: docker/build-push-action@v6 + with: + context: ./${{ matrix.service }} + push: false + tags: ghstats-${{ matrix.service }}:ci + cache-from: type=gha,scope=${{ matrix.service }} + cache-to: type=gha,mode=max,scope=${{ matrix.service }} diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..b86860d --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,33 @@ +name: tests + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + pytest: + name: ${{ matrix.service }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + service: [fetcher, generator, edge] + defaults: + run: + working-directory: ${{ matrix.service }} + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + cache: pip + cache-dependency-path: ${{ matrix.service }}/requirements.txt + + - name: Install dependencies + run: pip install -r requirements.txt + + - name: Run pytest + run: pytest -v diff --git a/.gitignore b/.gitignore index b7faf40..cc6f313 100644 --- a/.gitignore +++ b/.gitignore @@ -14,8 +14,8 @@ dist/ downloads/ eggs/ .eggs/ -lib/ -lib64/ +/lib/ +/lib64/ parts/ sdist/ var/ @@ -205,3 +205,32 @@ cython_debug/ marimo/_static/ marimo/_lsp/ __marimo__/ + +# Per-service SQLite databases (runtime data) +fetcher/data/*.db +fetcher/data/*.db-wal +fetcher/data/*.db-shm +generator/data/*.db +generator/data/*.db-wal +generator/data/*.db-shm + +# Built frontend bundle +generator/src/static/ +generator/frontend/dist/ +generator/frontend/node_modules/ + +# Python build artifacts +**/__pycache__/ +**/*.pyc +.pytest_cache/ + +# Widget build artifacts at repo root (retired) +/widget_*.svg +/data/ghstats.db + +# Editor / tooling caches +.idea/ +.claude/ +.superpowers/ +.playwright-mcp/ +screenshots/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..b698548 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,63 @@ +# CLAUDE.md + +Guidance for Claude Code working in this repository. + +## Layout + +This is a monorepo of three independent Python services plus a Vite+React +frontend. Each service has its own `requirements.txt`, `pytest.ini`, +`Dockerfile`, and README: + +- `fetcher/` — port 5001. Owns the GitHub PAT and `fetcher.db`. Refresh + cron polls GitHub, upserts raw payloads, serves `/data/` to internal + callers only. +- `generator/` — port 5002. Owns settings + widgets SQLite DBs. Build + worker renders SVGs from fetcher data. Serves the React SPA from + `src/static/` and all `/api/*` routes. Frontend sources live in + `generator/frontend/` and get built into `src/static/` by the + multi-stage Dockerfile. +- `edge/` — port 5003. Cache-first SVG proxy in front of the generator; + Flask-Caching + Flask-Compress, optional Redis. + +Per-service READMEs cover run/test/Docker commands. The design and +implementation plan live in `docs/superpowers/`. + +## Working on a single service + +Each service is self-contained. `cd && pytest` is the test +entry point; `cd && pip install -r requirements.txt` is the +dependency install. Don't cross-import across services — they talk +over HTTP (generator → fetcher via `generator/src/fetcher_client.py`; +edge → generator via `edge/src/api.py::_fetch_origin`). + +## Configuration + +All runtime tuning is in each service's `src/config.py` and is +overridable via env vars: + +- `fetcher/src/config.py` — `GITHUB_PAT`, `FETCHER_INTERNAL_TOKEN`, + `COLLABORATOR_*`, `COMMIT_*`, `API_TIMEOUT`, refresh cadence. +- `generator/src/config.py` — `FETCHER_URL`, `FETCHER_INTERNAL_TOKEN`, + `ENROLLMENT_DAILY_CAP`, `WIDGET_LRU_PER_USER`, `POLL_INTERVAL_MINUTES`, + `TAG_MAX_COUNT`, `TAG_LANGUAGE_MAP`, `TAG_TOPIC_MAP`, + `ENABLED_WIDGETS`, `WIDGET_ORDER`, `HIDDEN_LANGUAGES`. +- `edge/src/config.py` — `GENERATOR_URL`, `CACHE_TYPE`, + `CACHE_REDIS_URL`, `CACHE_DEFAULT_TIMEOUT`, `CACHE_THRESHOLD`, + `UPSTREAM_TIMEOUT`. + +## Conventions + +- Widget renderers return SVG strings; only `generator/src/worker.py` + persists them (via `db.put_widgets`). +- The `X-Widget-Status` header (`ready | building | rate_limited | + not_found`) is the contract between generator and edge for what to + cache. +- Generator ↔ fetcher traffic uses the shared secret + `FETCHER_INTERNAL_TOKEN` (HTTP header `X-Internal-Token`). Public + routes on the generator don't require auth in v1. +- Adding a widget still means: new `generator/src/widgets/.py`, + export from `generator/src/widgets/__init__.py`, wire into + `generator/src/processor.py::generate_widgets_from_github`, add the + key to `WIDGET_ORDER` / `ENABLED_WIDGETS` in + `generator/src/config.py`. +- Adding a theme: entry in `generator/src/themes/themes.py`. diff --git a/README.md b/README.md index 2f0e425..d213b04 100644 --- a/README.md +++ b/README.md @@ -1,90 +1,43 @@ -# GitHub README Stats +# github-readme-stats -Generate polished SVG profile cards from your GitHub data. Fetches your repos, contributions, languages, and collaborators, then renders them into composable widgets you can drop into your profile README. +[![tests](https://github.com/ShayManor/github-readme-stats/actions/workflows/tests.yml/badge.svg)](https://github.com/ShayManor/github-readme-stats/actions/workflows/tests.yml) +[![docker](https://github.com/ShayManor/github-readme-stats/actions/workflows/docker.yml/badge.svg)](https://github.com/ShayManor/github-readme-stats/actions/workflows/docker.yml) -

- Example composite widget -

+A monorepo of three independent Python services plus a React frontend, +each self-contained. See each service's README for details. -## Widgets +## Services -| Widget | What it shows | -|--------|--------------| -| **Grade** | Letter grade (S through F) with score breakdown, stats, and inferred role tags | -| **Impact** | Contribution timeline over the last 6 months | -| **Collaborators** | Top people you've committed alongside, ranked by shared commits | -| **Focus** | Where your recent work falls (Backend, Frontend, ML, DevOps, etc.) | -| **Languages** | Donut chart of your most-used languages by LOC | -| **Achievements** | Custom badges you define (hackathons, awards, milestones) | +| Folder | Port | Responsibility | +|---|---|---| +| [`fetcher/`](./fetcher/README.md) | 5001 | Owns GitHub PAT + `fetcher.db`; cron-refreshes data | +| [`generator/`](./generator/README.md) | 5002 | Settings + widgets DBs, build worker, serves React SPA + `/api/*` | +| [`edge/`](./edge/README.md) | 5003 | Cache-first SVG proxy; deploy globally | -Each widget is also saved individually as `widget_.svg`. +## Design Docs -## Quick Start +- Spec: [`docs/superpowers/specs/2026-04-17-production-pipeline-design.md`](docs/superpowers/specs/2026-04-17-production-pipeline-design.md) +- Plan: [`docs/superpowers/plans/2026-04-17-production-pipeline.md`](docs/superpowers/plans/2026-04-17-production-pipeline.md) -```bash -# Basic (public data only) -python run.py +## Quick start (local dev, no Docker) -# With a GitHub token for full commit/contribution data -GITHUB_PAT= python run.py + # 1) fetcher + (cd fetcher && pip install -r requirements.txt && + FETCHER_INTERNAL_TOKEN=dev GITHUB_PAT= python -m src.api) & -# Choose a theme -python run.py nord -``` + # 2) generator API, worker, cron (three processes) + cd generator && pip install -r requirements.txt + FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.api & + FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.worker & + FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.cron & -Output lands in the repo root as `widget_.svg`. + # 3) edge + (cd ../edge && pip install -r requirements.txt && + GENERATOR_URL=http://localhost:5002 python -m src.api) & -## Themes + # 4) frontend (dev server) + cd ../generator/frontend && npm install && npm run dev -Five built-in themes: +Test everything: -| Theme | Style | -|-------|-------| -| `midnight` / `dark` | Dark blue-gray (default) | -| `onyx` | High-contrast on near-black | -| `nord` | Muted pastels on slate | -| `clean` / `light` | White background | -| `paper` | Warm off-white, sepia accents | - -## Web UI - -A React frontend lets you customize widgets interactively with live preview and per-widget advanced settings (colors, counts, etc.). - -```bash -# Terminal 1 — start the generator API -python -m src.generator_api # :5002 - -# Terminal 2 — start the frontend -cd frontend && npm install && npm run dev # :3000 -``` - -Open `http://localhost:3000`, enter a GitHub username, tweak settings, and hit Generate. - -## Configuration - -All tuning lives in `src/config.py` and can be overridden with environment variables. Key knobs: - -| Variable | Default | What it does | -|----------|---------|-------------| -| `GITHUB_PAT` | — | GitHub personal access token | -| `COMMIT_MAX_REPOS` | 10 | Max repos to scan for commits | -| `COMMIT_PER_REPO` | 30 | Max commits per repo | -| `COLLABORATOR_MIN_COMMITS` | 3 | Minimum shared commits to show a collaborator | -| `API_TIMEOUT` | 5 | Per-request timeout in seconds | - -See [CONFIGURATION.md](CONFIGURATION.md) for the full list. - -## Project Structure - -``` -src/ - data/ # GitHub API fetching + data processing - widgets/ # One SVG renderer per widget - themes/ # Color palettes - models/ # Typed data structures - utils/ # SVG helpers - config.py # All tunables - generate.py # CLI entry point - generator_api.py # Flask API for the web UI -frontend/ # React + TypeScript + Vite -``` + (cd fetcher && pytest) && (cd generator && pytest) && (cd edge && pytest) diff --git a/data/ghstats.db b/data/ghstats.db deleted file mode 100644 index 4afa5c2..0000000 Binary files a/data/ghstats.db and /dev/null differ diff --git a/docs/superpowers/plans/2026-04-17-production-pipeline.md b/docs/superpowers/plans/2026-04-17-production-pipeline.md new file mode 100644 index 0000000..7e58a28 --- /dev/null +++ b/docs/superpowers/plans/2026-04-17-production-pipeline.md @@ -0,0 +1,2883 @@ +# Production Pipeline Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. +> +> **Commit approval:** Global user rule forbids `git commit` / `git push` without explicit approval. The commit step in each task must ask the user for approval before running. Do not amend prior commits; always create new ones. Never `git push` unless the user explicitly asks. + +**Goal:** Split the existing monolithic widget-generator repo into three independent Python services (`fetcher`, `generator`, `edge`) plus a React/Vite frontend folded into `generator/frontend`, each with its own Dockerfile, tests, and README. End state: a public `GET /` on the edge returns a precomputed SVG (or a clean placeholder) for any GitHub user, with a background pipeline that enrolls, fetches, builds, and refreshes. + +**Architecture:** Three Flask services communicating over HTTP. Fetcher owns the GitHub PAT and `fetcher.db`. Generator owns settings + widgets DBs, runs a build worker + cron, and serves both the React SPA (at `/`) and JSON/SVG APIs (at `/api/*`). Edge is a thin Flask-Caching / Flask-Compress proxy that serves widget SVGs cache-first with the generator as origin. Redis is designed for but not deployed — `cache.py` is a no-op wrapper in v1. + +**Tech Stack:** Python 3.11, Flask, SQLite (WAL mode), Flask-Caching (SimpleCache in v1), Flask-Compress, `requests`, `pytest`, `responses` (HTTP mocking), React + Vite + TypeScript (existing), Docker (multi-stage for generator). + +**Spec:** `docs/superpowers/specs/2026-04-17-production-pipeline-design.md` + +--- + +## Phases + +- **Phase 0** — Scaffolding + removal of retired code +- **Phase 1** — Fetcher service (full) +- **Phase 2** — Generator: DB, cache wrapper, placeholder, processor, fetcher client +- **Phase 3** — Generator: API, worker, cron, integration test +- **Phase 4** — Edge service +- **Phase 5** — Frontend migration into generator + multi-stage Dockerfile +- **Phase 6** — Top-level README, CLAUDE.md update, final gitignore + +--- + +## Phase 0 — Scaffolding + +### Task 0.1: Create service folders and .gitignore + +**Files:** +- Create: `fetcher/`, `fetcher/src/`, `fetcher/tests/`, `fetcher/data/` +- Create: `generator/`, `generator/src/`, `generator/tests/`, `generator/tests/integration/`, `generator/data/` +- Create: `edge/`, `edge/src/`, `edge/tests/` +- Modify: `.gitignore` + +- [ ] **Step 1: Create directories** + +```bash +mkdir -p fetcher/src fetcher/tests fetcher/data +mkdir -p generator/src generator/tests/integration generator/data +mkdir -p edge/src edge/tests +touch fetcher/src/__init__.py fetcher/tests/__init__.py +touch generator/src/__init__.py generator/tests/__init__.py generator/tests/integration/__init__.py +touch edge/src/__init__.py edge/tests/__init__.py +touch fetcher/data/.gitkeep generator/data/.gitkeep +``` + +- [ ] **Step 2: Update `.gitignore`** + +Append to `.gitignore`: + +``` +# Per-service SQLite databases (runtime data) +fetcher/data/*.db +fetcher/data/*.db-wal +fetcher/data/*.db-shm +generator/data/*.db +generator/data/*.db-wal +generator/data/*.db-shm + +# Built frontend bundle +generator/src/static/ +generator/frontend/dist/ +generator/frontend/node_modules/ + +# Python build artifacts +**/__pycache__/ +**/*.pyc +.pytest_cache/ + +# Widget build artifacts at repo root (retired) +/widget_*.svg +/data/ghstats.db +``` + +- [ ] **Step 3: Commit (ask user for approval first)** + +```bash +git add .gitignore fetcher/ generator/ edge/ +git commit -m "chore(scaffold): create fetcher/generator/edge service folders" +``` + +--- + +### Task 0.2: Remove retired top-level code and artifacts + +**Files to delete:** +- `run.py` +- `src/generate.py`, `src/fetcher_api.py`, `src/generator_api.py` +- `src/data/ARCHITECTURE.md` +- `widget_*.svg` at repo root +- `data/ghstats.db` +- `REPORT.md`, `CHANGELOG.md` (stale) +- `src/README.md` + +Do NOT delete yet: `src/config.py`, `src/widgets/`, `src/themes/`, `src/models/`, `src/utils/`, `src/data/fetcher.py`, `src/data/processor.py`, `src/db/`. These move in later phases via `git mv`. + +- [ ] **Step 1: Stage removals** + +```bash +git rm run.py src/generate.py src/fetcher_api.py src/generator_api.py +git rm src/data/ARCHITECTURE.md src/README.md +git rm REPORT.md CHANGELOG.md +git rm widget_achievements.svg widget_collaborators.svg widget_focus.svg widget_grade.svg widget_impact.svg widget_languages.svg widget_shaymanor.svg +git rm data/ghstats.db +``` + +- [ ] **Step 2: Verify no remaining imports of deleted modules** + +Run: `grep -rn "from src.generate\|from src.fetcher_api\|from src.generator_api\|import run" src/ 2>/dev/null || echo "clean"` +Expected: `clean` + +- [ ] **Step 3: Commit (ask user for approval first)** + +```bash +git commit -m "chore(cleanup): remove retired entry points and build artifacts" +``` + +--- + +## Phase 1 — Fetcher Service + +### Task 1.1: Fetcher scaffolding (requirements, config, pytest, Dockerfile) + +**Files:** +- Create: `fetcher/requirements.txt` +- Create: `fetcher/pytest.ini` +- Create: `fetcher/src/config.py` +- Create: `fetcher/Dockerfile` + +- [ ] **Step 1: `fetcher/requirements.txt`** + +``` +flask==3.0.3 +requests==2.32.3 +pytest==8.3.3 +responses==0.25.3 +gunicorn==23.0.0 +``` + +- [ ] **Step 2: `fetcher/pytest.ini`** + +```ini +[pytest] +testpaths = tests +python_files = test_*.py +pythonpath = . +addopts = -ra --strict-markers +``` + +- [ ] **Step 3: `fetcher/src/config.py`** + +```python +"""Fetcher service configuration, overridable via env vars.""" +import os + +PORT = int(os.getenv("FETCHER_PORT", "5001")) +DB_PATH = os.getenv("FETCHER_DB_PATH", "./data/fetcher.db") +GITHUB_PAT = os.getenv("GITHUB_PAT", "") +INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "") +REFRESH_INTERVAL_HOURS = int(os.getenv("FETCHER_REFRESH_INTERVAL_HOURS", "24")) +TRIAL_GC_DAYS = int(os.getenv("FETCHER_TRIAL_GC_DAYS", "7")) +API_TIMEOUT = int(os.getenv("API_TIMEOUT", "15")) +``` + +- [ ] **Step 4: `fetcher/Dockerfile`** + +```dockerfile +FROM python:3.11-slim + +WORKDIR /app +COPY requirements.txt ./ +RUN pip install --no-cache-dir -r requirements.txt + +COPY src ./src +RUN mkdir -p /app/data + +EXPOSE 5001 +ENV FETCHER_DB_PATH=/app/data/fetcher.db + +# Default is the API. Override CMD for cron: ["python", "-m", "src.cron"] +CMD ["gunicorn", "-b", "0.0.0.0:5001", "-w", "2", "src.api:app"] +``` + +- [ ] **Step 5: Commit** + +```bash +git add fetcher/requirements.txt fetcher/pytest.ini fetcher/src/config.py fetcher/Dockerfile +git commit -m "feat(fetcher): scaffold config, requirements, pytest, Dockerfile" +``` + +--- + +### Task 1.2: Fetcher `db.py` — schema, WAL, CRUD, payload hashing + +**Files:** +- Create: `fetcher/src/db.py` +- Create: `fetcher/tests/test_db.py` + +- [ ] **Step 1: Write the failing tests `fetcher/tests/test_db.py`** + +```python +import os +import tempfile +import pytest +from src import db as dbmod + + +@pytest.fixture +def tmp_db(monkeypatch): + with tempfile.TemporaryDirectory() as d: + path = os.path.join(d, "t.db") + monkeypatch.setattr(dbmod, "DB_PATH", path) + dbmod.init_db() + yield path + + +def test_init_creates_schema_with_wal(tmp_db): + with dbmod._connect() as c: + mode = c.execute("PRAGMA journal_mode").fetchone()[0] + assert mode.lower() == "wal" + cols = [r[1] for r in c.execute("PRAGMA table_info(users)").fetchall()] + assert set(cols) == {"username", "data_json", "payload_hash", + "fetched_at", "last_requested_at"} + + +def test_upsert_and_get_round_trip(tmp_db): + dbmod.upsert_user("alice", {"user": {"login": "alice"}, "repos": []}) + row = dbmod.get_user("alice") + assert row["data"]["user"]["login"] == "alice" + assert row["payload_hash"] + assert row["fetched_at"] + + +def test_payload_hash_is_deterministic_and_changes_on_diff(): + h1 = dbmod.payload_hash({"a": 1, "b": 2}) + h2 = dbmod.payload_hash({"b": 2, "a": 1}) + h3 = dbmod.payload_hash({"a": 1, "b": 3}) + assert h1 == h2 + assert h1 != h3 + + +def test_get_updates_last_requested_at(tmp_db): + dbmod.upsert_user("alice", {"user": {"login": "alice"}}) + first = dbmod.get_user("alice")["last_requested_at"] + import time; time.sleep(1.1) + second = dbmod.get_user("alice")["last_requested_at"] + assert second > first + + +def test_delete_stale_removes_old_rows(tmp_db): + dbmod.upsert_user("ghost", {"user": {"login": "ghost"}}) + # Manually backdate last_requested_at + with dbmod._connect() as c: + c.execute("UPDATE users SET last_requested_at='2020-01-01T00:00:00Z' WHERE username='ghost'") + removed = dbmod.delete_stale(days=7) + assert removed == 1 + assert dbmod.get_user("ghost") is None + + +def test_users_due_for_refresh(tmp_db): + dbmod.upsert_user("alice", {"user": {"login": "alice"}}) + # Backdate fetched_at so alice is due + with dbmod._connect() as c: + c.execute("UPDATE users SET fetched_at='2020-01-01T00:00:00Z' WHERE username='alice'") + due = dbmod.users_due_for_refresh(hours=24, active_within_days=7) + assert "alice" in due +``` + +- [ ] **Step 2: Run tests — expect failures** + +Run: `cd fetcher && pytest tests/test_db.py -v` +Expected: `ModuleNotFoundError` or similar (db module not yet complete). + +- [ ] **Step 3: Implement `fetcher/src/db.py`** + +```python +"""SQLite repository for the fetcher service. + +Single table: users (raw GitHub payloads keyed by username). +Uses WAL mode so concurrent readers don't block the writer. +""" +import hashlib +import json +import os +import sqlite3 +from contextlib import contextmanager +from datetime import datetime, timedelta +from typing import Optional + +from . import config + +DB_PATH = config.DB_PATH + +SCHEMA_SQL = """ +CREATE TABLE IF NOT EXISTS users ( + username TEXT PRIMARY KEY, + data_json TEXT NOT NULL, + payload_hash TEXT NOT NULL, + fetched_at TEXT NOT NULL, + last_requested_at TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_users_fetched_at ON users(fetched_at); +CREATE INDEX IF NOT EXISTS idx_users_last_requested_at ON users(last_requested_at); +""" + + +def _now() -> str: + return datetime.utcnow().isoformat(timespec="seconds") + "Z" + + +@contextmanager +def _connect(): + os.makedirs(os.path.dirname(DB_PATH) or ".", exist_ok=True) + conn = sqlite3.connect(DB_PATH, timeout=10) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA journal_mode=WAL") + conn.execute("PRAGMA synchronous=NORMAL") + conn.execute("PRAGMA foreign_keys=ON") + conn.execute("PRAGMA busy_timeout=5000") + try: + yield conn + finally: + conn.close() + + +def init_db() -> None: + with _connect() as c: + c.executescript(SCHEMA_SQL) + c.commit() + + +def payload_hash(data: dict) -> str: + canonical = json.dumps(data, sort_keys=True, separators=(",", ":")) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() + + +def upsert_user(username: str, data: dict) -> str: + h = payload_hash(data) + now = _now() + with _connect() as c: + c.execute( + """INSERT INTO users(username, data_json, payload_hash, fetched_at, last_requested_at) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT(username) DO UPDATE SET + data_json = excluded.data_json, + payload_hash = excluded.payload_hash, + fetched_at = excluded.fetched_at""", + (username, json.dumps(data), h, now, now), + ) + c.commit() + return h + + +def get_user(username: str) -> Optional[dict]: + """Returns {data, payload_hash, fetched_at, last_requested_at} or None. Updates last_requested_at.""" + now = _now() + with _connect() as c: + row = c.execute( + "SELECT data_json, payload_hash, fetched_at, last_requested_at FROM users WHERE username=?", + (username,), + ).fetchone() + if row is None: + return None + c.execute("UPDATE users SET last_requested_at=? WHERE username=?", (now, username)) + c.commit() + return { + "data": json.loads(row["data_json"]), + "payload_hash": row["payload_hash"], + "fetched_at": row["fetched_at"], + "last_requested_at": now, + } + + +def delete_stale(days: int) -> int: + cutoff = (datetime.utcnow() - timedelta(days=days)).isoformat(timespec="seconds") + "Z" + with _connect() as c: + cur = c.execute("DELETE FROM users WHERE last_requested_at < ?", (cutoff,)) + c.commit() + return cur.rowcount + + +def users_due_for_refresh(hours: int, active_within_days: int) -> list[str]: + """Return usernames with fetched_at older than `hours` and last_requested_at within `active_within_days`.""" + stale_before = (datetime.utcnow() - timedelta(hours=hours)).isoformat(timespec="seconds") + "Z" + active_after = (datetime.utcnow() - timedelta(days=active_within_days)).isoformat(timespec="seconds") + "Z" + with _connect() as c: + rows = c.execute( + "SELECT username FROM users WHERE fetched_at < ? AND last_requested_at > ?", + (stale_before, active_after), + ).fetchall() + return [r["username"] for r in rows] + + +def list_usernames() -> list[str]: + with _connect() as c: + return [r["username"] for r in c.execute("SELECT username FROM users ORDER BY username").fetchall()] +``` + +- [ ] **Step 4: Run tests — expect pass** + +Run: `cd fetcher && pytest tests/test_db.py -v` +Expected: all 6 tests PASS. + +- [ ] **Step 5: Commit** + +```bash +git add fetcher/src/db.py fetcher/tests/test_db.py +git commit -m "feat(fetcher): add SQLite db module with WAL, payload hashing, GC" +``` + +--- + +### Task 1.3: Fetcher `github.py` — move from `src/data/fetcher.py` + +**Files:** +- Move: `src/data/fetcher.py` → `fetcher/src/github.py` +- Create: `fetcher/tests/test_github.py` + +- [ ] **Step 1: Move file** + +```bash +git mv src/data/fetcher.py fetcher/src/github.py +``` + +- [ ] **Step 2: Adjust imports inside `fetcher/src/github.py`** + +Inside that file, change `from src.config import ...` to `from . import config` and update all config references to `config.NAME`. Remove any `src.models` or other generator-only imports if present (the fetcher only needs to produce raw JSON — no typed models). + +- [ ] **Step 3: Write smoke tests `fetcher/tests/test_github.py`** + +```python +import responses +import pytest +from src import github + + +@responses.activate +def test_fetch_user_data_returns_user_payload(): + responses.add( + responses.POST, "https://api.github.com/graphql", + json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}}, + status=200, + ) + responses.add( + responses.GET, "https://api.github.com/users/alice", + json={"login": "alice", "public_repos": 3, "followers": 5, "avatar_url": "https://avatars.example/1"}, + status=200, + ) + responses.add( + responses.GET, "https://api.github.com/users/alice/repos", + json=[], status=200, + ) + responses.add( + responses.GET, "https://api.github.com/users/alice/events", + json=[], status=200, + ) + data = github.fetch_github_data("alice", token="t") + assert data["user"]["login"] == "alice" + assert "repos" in data + assert "events" in data + + +@responses.activate +def test_fetch_handles_404(): + responses.add( + responses.GET, "https://api.github.com/users/nope", + json={"message": "Not Found"}, status=404, + ) + responses.add( + responses.POST, "https://api.github.com/graphql", + json={"data": {"user": None}}, status=200, + ) + responses.add( + responses.GET, "https://api.github.com/users/nope/repos", + json={"message": "Not Found"}, status=404, + ) + responses.add( + responses.GET, "https://api.github.com/users/nope/events", + json={"message": "Not Found"}, status=404, + ) + data = github.fetch_github_data("nope", token="t") + # The existing fetcher returns whatever GitHub gave it; we just assert it doesn't crash + # and the caller can detect not_found via data["user"].get("message") + assert data["user"].get("message") == "Not Found" or data["user"] is None +``` + +- [ ] **Step 4: Run tests** + +Run: `cd fetcher && pytest tests/test_github.py -v` +Expected: both PASS. If the second fails because the existing code expects a specific shape, adjust the test to match the actual return shape (read `fetcher/src/github.py` to see what it returns on 404). + +- [ ] **Step 5: Commit** + +```bash +git add fetcher/src/github.py fetcher/tests/test_github.py +git commit -m "feat(fetcher): move GitHub client into fetcher service" +``` + +--- + +### Task 1.4: Fetcher `api.py` — Flask routes + shared-secret auth + +**Files:** +- Create: `fetcher/src/api.py` +- Create: `fetcher/tests/test_api.py` + +- [ ] **Step 1: Write failing tests `fetcher/tests/test_api.py`** + +```python +import os +import tempfile +import pytest +import responses as resp_lib +from src import db as dbmod +from src import api as apimod + + +@pytest.fixture +def client(monkeypatch): + with tempfile.TemporaryDirectory() as d: + monkeypatch.setattr(dbmod, "DB_PATH", os.path.join(d, "t.db")) + monkeypatch.setattr(apimod.config, "INTERNAL_TOKEN", "secret") + monkeypatch.setattr(apimod.config, "GITHUB_PAT", "ghp_test") + dbmod.init_db() + app = apimod.app + app.config["TESTING"] = True + with app.test_client() as c: + yield c + + +def test_health_no_auth_required(client): + r = client.get("/health") + assert r.status_code == 200 + assert r.get_json()["service"] == "fetcher" + + +def test_endpoints_require_internal_token(client): + r = client.get("/data/alice") + assert r.status_code == 401 + + +@resp_lib.activate +def test_data_auto_fetches_on_miss(client, monkeypatch): + resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", + json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}}, status=200) + resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice", + json={"login": "alice", "public_repos": 1, "followers": 0, "avatar_url": "https://avatars.example/a"}, status=200) + resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/repos", json=[], status=200) + resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/events", json=[], status=200) + + r = client.get("/data/alice", headers={"X-Internal-Token": "secret"}) + assert r.status_code == 200 + body = r.get_json() + assert body["payload_hash"] + assert body["data"]["user"]["login"] == "alice" + + +def test_force_fetch_requires_auth(client): + r = client.post("/fetch", json={"username": "alice"}) + assert r.status_code == 401 +``` + +- [ ] **Step 2: Run — expect fail** + +Run: `cd fetcher && pytest tests/test_api.py -v` +Expected: import error (no api module yet). + +- [ ] **Step 3: Implement `fetcher/src/api.py`** + +```python +"""Flask app for the fetcher service. All endpoints require X-Internal-Token.""" +import hmac +import requests +from flask import Flask, jsonify, request, Response +from functools import wraps + +from . import config, db, github + +app = Flask(__name__) + + +def require_internal_token(fn): + @wraps(fn) + def wrapper(*args, **kwargs): + token = request.headers.get("X-Internal-Token", "") + if not config.INTERNAL_TOKEN or not hmac.compare_digest(token, config.INTERNAL_TOKEN): + return jsonify({"error": "unauthorized"}), 401 + return fn(*args, **kwargs) + return wrapper + + +@app.route("/health", methods=["GET"]) +def health(): + return jsonify({"status": "ok", "service": "fetcher", "users": len(db.list_usernames())}) + + +@app.route("/data/", methods=["GET"]) +@require_internal_token +def get_data(username: str): + row = db.get_user(username) + if row is None: + # Auto-fetch path + data = github.fetch_github_data(username, token=config.GITHUB_PAT) + if _is_github_not_found(data): + data = {"error": "not_found"} + h = db.upsert_user(username, data) + return jsonify({"data": data, "payload_hash": h, "fetched": True}) + return jsonify({ + "data": row["data"], + "payload_hash": row["payload_hash"], + "fetched_at": row["fetched_at"], + "fetched": False, + }) + + +@app.route("/fetch", methods=["POST"]) +@require_internal_token +def force_fetch(): + body = request.get_json(silent=True) or {} + username = body.get("username") + if not username: + return jsonify({"error": "username required"}), 400 + try: + data = github.fetch_github_data(username, token=config.GITHUB_PAT) + except Exception as e: + return jsonify({"error": f"fetch failed: {e}"}), 502 + if _is_github_not_found(data): + data = {"error": "not_found"} + old = db.get_user(username) + old_hash = old["payload_hash"] if old else None + new_hash = db.upsert_user(username, data) + return jsonify({"stored": True, "payload_hash": new_hash, "changed": old_hash != new_hash}) + + +@app.route("/avatar/", methods=["GET"]) +@require_internal_token +def avatar(username: str): + r = requests.get(f"https://github.com/{username}.png", timeout=config.API_TIMEOUT, allow_redirects=True) + if r.status_code != 200: + return jsonify({"error": "avatar unavailable"}), 404 + return Response(r.content, mimetype=r.headers.get("Content-Type", "image/png")) + + +def _is_github_not_found(data: dict) -> bool: + user = data.get("user") + if user is None: + return True + if isinstance(user, dict) and user.get("message") == "Not Found": + return True + return False + + +def main(): + db.init_db() + app.run(host="0.0.0.0", port=config.PORT) + + +if __name__ == "__main__": + main() +``` + +- [ ] **Step 4: Run tests — expect pass** + +Run: `cd fetcher && pytest tests/test_api.py -v` +Expected: all PASS. + +- [ ] **Step 5: Commit** + +```bash +git add fetcher/src/api.py fetcher/tests/test_api.py +git commit -m "feat(fetcher): add Flask API with auth, auto-fetch, avatar" +``` + +--- + +### Task 1.5: Fetcher `cron.py` — scheduled refresh + GC + +**Files:** +- Create: `fetcher/src/cron.py` +- Create: `fetcher/tests/test_cron.py` + +- [ ] **Step 1: Write failing tests** + +```python +import os +import tempfile +import pytest +from unittest.mock import patch +from src import db as dbmod +from src import cron as cronmod + + +@pytest.fixture +def tmp_db(monkeypatch): + with tempfile.TemporaryDirectory() as d: + monkeypatch.setattr(dbmod, "DB_PATH", os.path.join(d, "t.db")) + dbmod.init_db() + yield + + +def test_refresh_tick_calls_github_for_due_users(tmp_db): + dbmod.upsert_user("alice", {"user": {"login": "alice"}}) + # Backdate + with dbmod._connect() as c: + c.execute("UPDATE users SET fetched_at='2020-01-01T00:00:00Z', last_requested_at=? WHERE username='alice'", + (dbmod._now(),)) + with patch("src.cron.github.fetch_github_data", return_value={"user": {"login": "alice", "updated": True}}) as gh: + stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7) + assert gh.called + assert stats["refreshed"] == 1 + + +def test_tick_runs_gc_for_abandoned_trial_users(tmp_db): + dbmod.upsert_user("ghost", {"user": {"login": "ghost"}}) + with dbmod._connect() as c: + c.execute("UPDATE users SET last_requested_at='2020-01-01T00:00:00Z' WHERE username='ghost'") + stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7) + assert stats["gc_removed"] == 1 + assert dbmod.get_user("ghost") is None +``` + +- [ ] **Step 2: Run — expect fail** + +Run: `cd fetcher && pytest tests/test_cron.py -v` +Expected: fail. + +- [ ] **Step 3: Implement `fetcher/src/cron.py`** + +```python +"""Scheduled refresh + GC loop. Run as its own container (CMD override).""" +import logging +import time + +from . import config, db, github + +log = logging.getLogger("fetcher.cron") + + +def tick(hours: int, active_within_days: int, gc_days: int) -> dict: + """Refresh due users, then GC abandoned ones. Returns counts.""" + refreshed = 0 + failed = 0 + due = db.users_due_for_refresh(hours=hours, active_within_days=active_within_days) + for username in due: + try: + data = github.fetch_github_data(username, token=config.GITHUB_PAT) + user = data.get("user") + if user is None or (isinstance(user, dict) and user.get("message") == "Not Found"): + data = {"error": "not_found"} + db.upsert_user(username, data) + refreshed += 1 + except Exception as e: + log.warning("refresh failed for %s: %s", username, e) + failed += 1 + gc_removed = db.delete_stale(days=gc_days) + return {"refreshed": refreshed, "failed": failed, "gc_removed": gc_removed} + + +def main(): + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s") + db.init_db() + interval = 3600 # 1h between ticks + while True: + try: + stats = tick( + hours=config.REFRESH_INTERVAL_HOURS, + active_within_days=config.TRIAL_GC_DAYS, + gc_days=config.TRIAL_GC_DAYS, + ) + log.info("tick complete: %s", stats) + except Exception: + log.exception("tick failed") + time.sleep(interval) + + +if __name__ == "__main__": + main() +``` + +- [ ] **Step 4: Run tests — expect pass** + +Run: `cd fetcher && pytest tests/test_cron.py -v` +Expected: PASS. + +- [ ] **Step 5: Write `fetcher/README.md`** + +```markdown +# Fetcher Service + +Owns every GitHub API interaction. Holds the PAT. Exposes cached payloads +over an internal-only HTTP API protected by a shared secret. + +## Run locally + + cd fetcher + pip install -r requirements.txt + FETCHER_INTERNAL_TOKEN=dev GITHUB_PAT=ghp_xxx python -m src.api + +Cron (separate process): + + FETCHER_INTERNAL_TOKEN=dev GITHUB_PAT=ghp_xxx python -m src.cron + +## Test + + cd fetcher && pytest + +## Docker + + docker build -t ghstats-fetcher . + docker run -e GITHUB_PAT=ghp_xxx -e FETCHER_INTERNAL_TOKEN=dev -p 5001:5001 -v $(pwd)/data:/app/data ghstats-fetcher + # cron: override CMD to ["python","-m","src.cron"] + +## Endpoints + +| Method | Path | Auth | Description | +|---|---|---|---| +| GET | /health | none | health check | +| GET | /data/ | X-Internal-Token | return stored payload; auto-fetches on miss | +| POST | /fetch | X-Internal-Token | force re-fetch (body: {username}) | +| GET | /avatar/ | X-Internal-Token | proxied avatar bytes | + +## Env + +See `src/config.py`. +``` + +- [ ] **Step 6: Commit** + +```bash +git add fetcher/src/cron.py fetcher/tests/test_cron.py fetcher/README.md +git commit -m "feat(fetcher): add cron refresh + GC and service README" +``` + +--- + +## Phase 2 — Generator: DB, Cache, Placeholder, Processor, Fetcher client + +### Task 2.1: Generator scaffolding + move widgets/themes/models/utils/processor + +**Files:** +- Create: `generator/requirements.txt`, `generator/pytest.ini` +- Move: `src/widgets/` → `generator/src/widgets/` +- Move: `src/themes/` → `generator/src/themes/` +- Move: `src/models/` → `generator/src/models/` +- Move: `src/utils/` → `generator/src/utils/` +- Move: `src/data/processor.py` → `generator/src/processor.py` +- Move: `src/config.py` → `generator/src/config.py` (merge with new env vars) + +- [ ] **Step 1: `generator/requirements.txt`** + +``` +flask==3.0.3 +flask-caching==2.3.0 +flask-compress==1.15 +requests==2.32.3 +pytest==8.3.3 +responses==0.25.3 +gunicorn==23.0.0 +``` + +- [ ] **Step 2: `generator/pytest.ini`** + +```ini +[pytest] +testpaths = tests +python_files = test_*.py +pythonpath = . +addopts = -ra --strict-markers +``` + +- [ ] **Step 3: Move existing modules** + +```bash +git mv src/widgets generator/src/widgets +git mv src/themes generator/src/themes +git mv src/models generator/src/models +git mv src/utils generator/src/utils +git mv src/data/processor.py generator/src/processor.py +git mv src/config.py generator/src/config.py +``` + +- [ ] **Step 4: Adjust imports in moved files** + +In every moved `.py` file under `generator/src/`, replace: + +- `from src.config` → `from .. import config` (if in subpackage) or `from . import config` (if at top level) +- `from src.widgets` → `from .widgets` (in top-level modules) or `from ..widgets` (in subpackages) +- `from src.themes`, `from src.models`, `from src.utils` similarly +- `from src.data.processor` → `from . import processor` + +Run a sweep: + +```bash +grep -rn "from src\." generator/src/ && echo "FIX THESE" || echo "clean" +``` + +Fix each reported line until the grep prints `clean`. + +- [ ] **Step 5: Extend `generator/src/config.py` with new env vars** + +Append to existing config.py: + +```python +# --- Service-specific additions (v2 of config) --- + +PORT = int(os.getenv("GENERATOR_PORT", "5002")) +SETTINGS_DB_PATH = os.getenv("GENERATOR_SETTINGS_DB_PATH", "./data/settings.db") +WIDGETS_DB_PATH = os.getenv("GENERATOR_WIDGETS_DB_PATH", "./data/widgets.db") +FETCHER_URL = os.getenv("FETCHER_URL", "http://localhost:5001") +FETCHER_INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "") +REDIS_URL = os.getenv("REDIS_URL", "") +ENROLLMENT_DAILY_CAP = int(os.getenv("ENROLLMENT_DAILY_CAP", "50")) +WIDGET_LRU_PER_USER = int(os.getenv("WIDGET_LRU_PER_USER", "10")) +POLL_INTERVAL_MINUTES = int(os.getenv("GENERATOR_POLL_INTERVAL_MINUTES", "15")) +``` + +- [ ] **Step 6: Delete now-empty `src/` tree** + +```bash +# After moves above, src/data/__init__.py and src/__init__.py still exist. +# Remove the retired db module and empty src/ +git rm -r src/db src/data src/__init__.py +rmdir src 2>/dev/null || true +``` + +- [ ] **Step 7: Smoke-check generator-side imports load** + +```bash +cd generator && python -c "from src import processor, widgets, themes, models, utils, config; print('ok')" +``` + +Expected: `ok`. If not, fix the failing import and repeat. + +- [ ] **Step 8: Commit** + +```bash +git add generator/requirements.txt generator/pytest.ini generator/src/ -A +git add -u src/ 2>/dev/null || true +git commit -m "feat(generator): scaffold + move widgets/themes/models/utils/processor/config" +``` + +--- + +### Task 2.2: Generator `db.py` — settings + widgets + jobs + enrollments + +**Files:** +- Create: `generator/src/db.py` +- Create: `generator/tests/test_db.py` + +- [ ] **Step 1: Write failing tests `generator/tests/test_db.py`** + +```python +import os +import tempfile +import pytest +from src import db as dbmod + + +@pytest.fixture +def tmp_dbs(monkeypatch): + with tempfile.TemporaryDirectory() as d: + monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db")) + monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db")) + dbmod.init_dbs() + yield d + + +def test_settings_hash_is_deterministic(): + h1 = dbmod.settings_hash({"theme": "dark", "widgets": ["a", "b"]}) + h2 = dbmod.settings_hash({"widgets": ["a", "b"], "theme": "dark"}) + assert h1 == h2 + + +def test_enroll_and_get_settings(tmp_dbs): + defaults = {"theme": "dark", "widgets": ["grade"]} + job_id = dbmod.enroll("alice", defaults) + assert job_id > 0 + s = dbmod.get_settings("alice") + assert s["settings"] == defaults + assert s["manual_refresh_used"] == 0 + + +def test_enrollments_daily_counter(tmp_dbs): + dbmod.enroll("alice", {"theme": "dark"}) + dbmod.enroll("bob", {"theme": "dark"}) + assert dbmod.enrollments_today() == 2 + + +def test_update_settings_changes_hash(tmp_dbs): + dbmod.enroll("alice", {"theme": "dark"}) + h_before = dbmod.get_settings("alice")["settings_hash"] + dbmod.update_settings("alice", {"theme": "light"}) + h_after = dbmod.get_settings("alice")["settings_hash"] + assert h_before != h_after + + +def test_claim_job_marks_running(tmp_dbs): + job_id = dbmod.enroll("alice", {"theme": "dark"}) + job = dbmod.claim_next_job() + assert job["id"] == job_id + assert job["status"] == "running" + assert dbmod.claim_next_job() is None # already running + + +def test_complete_job(tmp_dbs): + jid = dbmod.enroll("alice", {"theme": "dark"}) + dbmod.claim_next_job() + dbmod.complete_job(jid) + with dbmod._settings_conn() as c: + status = c.execute("SELECT status FROM jobs WHERE id=?", (jid,)).fetchone()[0] + assert status == "done" + + +def test_widgets_put_and_get(tmp_dbs): + dbmod.put_widgets("alice", "hash1", {"composite": "", "grade": ""}) + row = dbmod.get_current_widget("alice", "composite") + assert row == "" + + +def test_current_widget_flips_atomically(tmp_dbs): + dbmod.put_widgets("alice", "hash1", {"composite": "v1"}) + dbmod.put_widgets("alice", "hash2", {"composite": "v2"}) + assert dbmod.get_current_widget("alice", "composite") == "v2" + + +def test_lru_trim_keeps_n_newest(tmp_dbs): + for i in range(12): + dbmod.put_widgets("alice", f"hash{i}", {"composite": f"{i}"}) + dbmod.lru_trim("alice", keep=10) + with dbmod._widgets_conn() as c: + n = c.execute("SELECT COUNT(DISTINCT settings_hash) FROM widgets WHERE username='alice'").fetchone()[0] + assert n == 10 + + +def test_reclaim_stuck_running_jobs(tmp_dbs): + jid = dbmod.enroll("alice", {"theme": "dark"}) + dbmod.claim_next_job() + # Backdate updated_at to simulate dead worker + with dbmod._settings_conn() as c: + c.execute("UPDATE jobs SET updated_at='2020-01-01T00:00:00Z' WHERE id=?", (jid,)) + c.commit() + dbmod.reclaim_stuck_jobs(older_than_minutes=10) + job = dbmod.claim_next_job() + assert job["id"] == jid +``` + +- [ ] **Step 2: Run — expect fail** + +- [ ] **Step 3: Implement `generator/src/db.py`** + +```python +"""Generator's two SQLite DBs: settings.db (settings + jobs + enrollments) and widgets.db (svg cache). + +All access goes through this module so a future Postgres swap is local to here. +Both DBs are opened with WAL mode. +""" +import hashlib +import json +import os +import sqlite3 +from contextlib import contextmanager +from datetime import datetime, timedelta +from typing import Optional + +from . import config + +SETTINGS_DB_PATH = config.SETTINGS_DB_PATH +WIDGETS_DB_PATH = config.WIDGETS_DB_PATH + +_SETTINGS_SCHEMA = """ +CREATE TABLE IF NOT EXISTS users ( + username TEXT PRIMARY KEY, + settings_json TEXT NOT NULL, + settings_hash TEXT NOT NULL, + enrolled_at TEXT NOT NULL, + last_fetcher_payload_hash TEXT, + manual_refresh_used INTEGER DEFAULT 0, + last_requested_at TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS enrollments_daily ( + day TEXT PRIMARY KEY, + count INTEGER NOT NULL +); +CREATE TABLE IF NOT EXISTS jobs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + kind TEXT NOT NULL, + username TEXT NOT NULL, + status TEXT NOT NULL, + attempts INTEGER DEFAULT 0, + last_error TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_jobs_pending ON jobs(status, created_at); +""" + +_WIDGETS_SCHEMA = """ +CREATE TABLE IF NOT EXISTS widgets ( + username TEXT NOT NULL, + settings_hash TEXT NOT NULL, + widget_name TEXT NOT NULL, + svg TEXT NOT NULL, + built_at TEXT NOT NULL, + PRIMARY KEY (username, settings_hash, widget_name) +); +CREATE TABLE IF NOT EXISTS current_widget ( + username TEXT PRIMARY KEY, + settings_hash TEXT NOT NULL, + updated_at TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_widgets_username ON widgets(username); +""" + + +def _now() -> str: + return datetime.utcnow().isoformat(timespec="seconds") + "Z" + + +def _today() -> str: + return datetime.utcnow().strftime("%Y-%m-%d") + + +def _open(path: str) -> sqlite3.Connection: + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + conn = sqlite3.connect(path, timeout=10) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA journal_mode=WAL") + conn.execute("PRAGMA synchronous=NORMAL") + conn.execute("PRAGMA foreign_keys=ON") + conn.execute("PRAGMA busy_timeout=5000") + return conn + + +@contextmanager +def _settings_conn(): + conn = _open(SETTINGS_DB_PATH) + try: + yield conn + finally: + conn.close() + + +@contextmanager +def _widgets_conn(): + conn = _open(WIDGETS_DB_PATH) + try: + yield conn + finally: + conn.close() + + +def init_dbs() -> None: + with _settings_conn() as c: + c.executescript(_SETTINGS_SCHEMA) + c.commit() + with _widgets_conn() as c: + c.executescript(_WIDGETS_SCHEMA) + c.commit() + + +def settings_hash(settings: dict) -> str: + canonical = json.dumps(settings, sort_keys=True, separators=(",", ":")) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() + + +# ---- settings / enrollment ---- + +def enroll(username: str, defaults: dict) -> int: + """Insert a settings row + increment daily counter + enqueue build. Returns job_id.""" + sh = settings_hash(defaults) + now = _now() + with _settings_conn() as c: + c.execute( + """INSERT INTO users(username, settings_json, settings_hash, enrolled_at, last_requested_at) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT(username) DO NOTHING""", + (username, json.dumps(defaults), sh, now, now), + ) + c.execute( + """INSERT INTO enrollments_daily(day, count) VALUES (?, 1) + ON CONFLICT(day) DO UPDATE SET count = count + 1""", + (_today(),), + ) + cur = c.execute( + """INSERT INTO jobs(kind, username, status, created_at, updated_at) + VALUES ('build', ?, 'pending', ?, ?)""", + (username, now, now), + ) + c.commit() + return cur.lastrowid + + +def enrollments_today() -> int: + with _settings_conn() as c: + row = c.execute("SELECT count FROM enrollments_daily WHERE day=?", (_today(),)).fetchone() + return row["count"] if row else 0 + + +def get_settings(username: str) -> Optional[dict]: + with _settings_conn() as c: + row = c.execute("SELECT * FROM users WHERE username=?", (username,)).fetchone() + if row is None: + return None + return { + "settings": json.loads(row["settings_json"]), + "settings_hash": row["settings_hash"], + "manual_refresh_used": row["manual_refresh_used"], + "last_fetcher_payload_hash": row["last_fetcher_payload_hash"], + "enrolled_at": row["enrolled_at"], + } + + +def update_settings(username: str, new_settings: dict) -> int: + """Updates settings + enqueues rebuild. Returns job_id.""" + sh = settings_hash(new_settings) + now = _now() + with _settings_conn() as c: + c.execute( + "UPDATE users SET settings_json=?, settings_hash=? WHERE username=?", + (json.dumps(new_settings), sh, username), + ) + cur = c.execute( + """INSERT INTO jobs(kind, username, status, created_at, updated_at) + VALUES ('build', ?, 'pending', ?, ?)""", + (username, now, now), + ) + c.commit() + return cur.lastrowid + + +def mark_manual_refresh(username: str) -> bool: + """Sets manual_refresh_used=1 only if it was 0. Returns True if successfully flipped.""" + with _settings_conn() as c: + cur = c.execute( + "UPDATE users SET manual_refresh_used=1 WHERE username=? AND manual_refresh_used=0", + (username,), + ) + c.commit() + return cur.rowcount == 1 + + +def touch_last_requested(username: str) -> None: + with _settings_conn() as c: + c.execute("UPDATE users SET last_requested_at=? WHERE username=?", (_now(), username)) + c.commit() + + +def list_enrolled() -> list[str]: + with _settings_conn() as c: + return [r["username"] for r in c.execute("SELECT username FROM users").fetchall()] + + +def set_last_fetcher_hash(username: str, h: str) -> None: + with _settings_conn() as c: + c.execute("UPDATE users SET last_fetcher_payload_hash=? WHERE username=?", (h, username)) + c.commit() + + +# ---- jobs ---- + +def enqueue_build(username: str) -> int: + now = _now() + with _settings_conn() as c: + cur = c.execute( + """INSERT INTO jobs(kind, username, status, created_at, updated_at) + VALUES ('build', ?, 'pending', ?, ?)""", + (username, now, now), + ) + c.commit() + return cur.lastrowid + + +def claim_next_job() -> Optional[dict]: + now = _now() + with _settings_conn() as c: + row = c.execute( + "SELECT * FROM jobs WHERE status='pending' ORDER BY created_at LIMIT 1" + ).fetchone() + if row is None: + return None + c.execute("UPDATE jobs SET status='running', updated_at=?, attempts=attempts+1 WHERE id=?", + (now, row["id"])) + c.commit() + return {"id": row["id"], "username": row["username"], "kind": row["kind"], "status": "running"} + + +def complete_job(job_id: int) -> None: + with _settings_conn() as c: + c.execute("UPDATE jobs SET status='done', updated_at=? WHERE id=?", (_now(), job_id)) + c.commit() + + +def fail_job(job_id: int, err: str, retry: bool) -> None: + status = "pending" if retry else "failed" + with _settings_conn() as c: + c.execute("UPDATE jobs SET status=?, last_error=?, updated_at=? WHERE id=?", + (status, err, _now(), job_id)) + c.commit() + + +def reclaim_stuck_jobs(older_than_minutes: int) -> int: + cutoff = (datetime.utcnow() - timedelta(minutes=older_than_minutes)).isoformat(timespec="seconds") + "Z" + with _settings_conn() as c: + cur = c.execute( + "UPDATE jobs SET status='pending', updated_at=? WHERE status='running' AND updated_at < ?", + (_now(), cutoff), + ) + c.commit() + return cur.rowcount + + +# ---- widgets ---- + +def put_widgets(username: str, hash_: str, widgets: dict[str, str]) -> None: + """Insert widget rows for this (user, hash) and flip current_widget to point at it.""" + now = _now() + with _widgets_conn() as c: + for name, svg in widgets.items(): + c.execute( + """INSERT INTO widgets(username, settings_hash, widget_name, svg, built_at) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT(username, settings_hash, widget_name) DO UPDATE SET + svg = excluded.svg, built_at = excluded.built_at""", + (username, hash_, name, svg, now), + ) + c.execute( + """INSERT INTO current_widget(username, settings_hash, updated_at) + VALUES (?, ?, ?) + ON CONFLICT(username) DO UPDATE SET settings_hash=excluded.settings_hash, updated_at=excluded.updated_at""", + (username, hash_, now), + ) + c.commit() + + +def get_current_widget(username: str, widget_name: str) -> Optional[str]: + with _widgets_conn() as c: + row = c.execute( + """SELECT w.svg FROM widgets w + JOIN current_widget cw ON cw.username=w.username AND cw.settings_hash=w.settings_hash + WHERE w.username=? AND w.widget_name=?""", + (username, widget_name), + ).fetchone() + return row["svg"] if row else None + + +def lru_trim(username: str, keep: int) -> int: + """Keep only the N newest settings_hashes per user; delete older rows.""" + with _widgets_conn() as c: + hashes = [r["settings_hash"] for r in c.execute( + """SELECT settings_hash, MAX(built_at) AS latest FROM widgets + WHERE username=? GROUP BY settings_hash ORDER BY latest DESC""", + (username,), + ).fetchall()] + to_delete = hashes[keep:] + if not to_delete: + return 0 + placeholders = ",".join("?" * len(to_delete)) + cur = c.execute( + f"DELETE FROM widgets WHERE username=? AND settings_hash IN ({placeholders})", + (username, *to_delete), + ) + c.commit() + return cur.rowcount +``` + +- [ ] **Step 4: Run tests — expect pass** + +Run: `cd generator && pytest tests/test_db.py -v` +Expected: all 10 tests PASS. + +- [ ] **Step 5: Commit** + +```bash +git add generator/src/db.py generator/tests/test_db.py +git commit -m "feat(generator): add settings+widgets db with jobs, enrollment, LRU" +``` + +--- + +### Task 2.3: Generator `cache.py` — no-op wrapper (Redis later) + +**Files:** +- Create: `generator/src/cache.py` +- Create: `generator/tests/test_cache.py` + +- [ ] **Step 1: Tests** + +```python +from src import cache + + +def test_noop_when_redis_url_empty(monkeypatch): + monkeypatch.setattr(cache.config, "REDIS_URL", "") + c = cache.Cache() + assert c.get("k") is None + c.set("k", "v", 60) + c.delete("k") + assert c.get("k") is None # still None because no-op + + +def test_enabled_flag_reflects_config(monkeypatch): + monkeypatch.setattr(cache.config, "REDIS_URL", "") + assert cache.Cache().enabled is False +``` + +- [ ] **Step 2: Implement `generator/src/cache.py`** + +```python +"""Tiny cache wrapper. v1 = no-op (REDIS_URL empty). v2 = real Redis.""" +from typing import Optional + +from . import config + + +class Cache: + def __init__(self): + self.enabled = bool(config.REDIS_URL) + self._client = None + if self.enabled: + import redis # local import so v1 doesn't require redis in runtime path + self._client = redis.from_url(config.REDIS_URL, decode_responses=True) + + def get(self, key: str) -> Optional[str]: + if not self.enabled: + return None + try: + return self._client.get(key) + except Exception: + return None + + def set(self, key: str, value: str, ttl_seconds: int) -> None: + if not self.enabled: + return + try: + self._client.setex(key, ttl_seconds, value) + except Exception: + pass + + def delete(self, *keys: str) -> None: + if not self.enabled or not keys: + return + try: + self._client.delete(*keys) + except Exception: + pass +``` + +- [ ] **Step 3: Run tests — pass.** Commit: + +```bash +git add generator/src/cache.py generator/tests/test_cache.py +git commit -m "feat(generator): add no-op cache wrapper (enables Redis later via env)" +``` + +--- + +### Task 2.4: Generator `placeholder.py` — three SVG variants + +**Files:** +- Create: `generator/src/placeholder.py` +- Create: `generator/tests/test_placeholder.py` + +- [ ] **Step 1: Write failing tests** + +```python +from src import placeholder + + +def test_building_contains_username_and_svg_tag(): + svg = placeholder.render("building", "alice", theme="dark") + assert svg.startswith("" in svg + assert "alice" in svg + assert "Building" in svg or "building" in svg.lower() + + +def test_rate_limited_variant(): + svg = placeholder.render("rate_limited", "alice", theme="dark") + assert "tomorrow" in svg.lower() or "try again" in svg.lower() + + +def test_not_found_variant(): + svg = placeholder.render("not_found", "ghost", theme="dark") + assert "ghost" in svg + assert "doesn't exist" in svg or "not found" in svg.lower() + + +def test_unknown_variant_raises(): + import pytest + with pytest.raises(ValueError): + placeholder.render("bogus", "alice", theme="dark") +``` + +- [ ] **Step 2: Implement `generator/src/placeholder.py`** + +```python +"""Placeholder SVG renderer — three variants for unknown / rate-limited / not-found users. + +Uses the same card wrapper + theme system as real widgets so they look consistent. +""" +from .themes.themes import get_theme +from .utils.svg_helpers import card_wrapper + +_MESSAGES = { + "building": ("Building @{u}'s widget…", "This usually takes under a minute."), + "rate_limited": ("Too many new users today", "Try again tomorrow."), + "not_found": ("GitHub user @{u} doesn't exist", "Check the spelling of the username."), +} + + +def render(variant: str, username: str, theme: str = "dark") -> str: + if variant not in _MESSAGES: + raise ValueError(f"unknown placeholder variant: {variant}") + title_tpl, subtitle = _MESSAGES[variant] + title = title_tpl.format(u=username) + palette = get_theme(theme) + + body = f""" + {_esc(title)} + {_esc(subtitle)} +""" + return card_wrapper(body=body, width=400, height=120, theme_name=theme) + + +def _esc(s: str) -> str: + return (s.replace("&", "&").replace("<", "<") + .replace(">", ">").replace('"', """)) +``` + +Note: if `themes.get_theme` or `card_wrapper` have different signatures in the moved code, adjust accordingly — read `generator/src/themes/themes.py` and `generator/src/utils/svg_helpers.py` first and match the actual API. + +- [ ] **Step 3: Run tests — pass.** Commit: + +```bash +git add generator/src/placeholder.py generator/tests/test_placeholder.py +git commit -m "feat(generator): add three placeholder SVG variants" +``` + +--- + +### Task 2.5: Generator `fetcher_client.py` — HTTP client to fetcher service + +**Files:** +- Create: `generator/src/fetcher_client.py` +- Create: `generator/tests/test_fetcher_client.py` + +Rationale: the spec says "fetcher HTTP client inline" — but both `api.py` and `worker.py` need it, and worker should not import Flask. Keeping it as its own 40-line module is the cleanest resolution; it's not a new service, just a DRY helper. + +- [ ] **Step 1: Tests** + +```python +import responses +import pytest +from src import fetcher_client as fc + + +@pytest.fixture(autouse=True) +def cfg(monkeypatch): + monkeypatch.setattr(fc.config, "FETCHER_URL", "http://fetcher:5001") + monkeypatch.setattr(fc.config, "FETCHER_INTERNAL_TOKEN", "secret") + + +@responses.activate +def test_get_data_returns_payload_and_hash(): + responses.add( + responses.GET, "http://fetcher:5001/data/alice", + json={"data": {"user": {"login": "alice"}}, "payload_hash": "abc"}, + status=200, + ) + result = fc.get_data("alice") + assert result["payload_hash"] == "abc" + assert result["data"]["user"]["login"] == "alice" + + +@responses.activate +def test_get_data_sends_auth_header(): + responses.add(responses.GET, "http://fetcher:5001/data/alice", + json={"data": {}, "payload_hash": "h"}, status=200) + fc.get_data("alice") + assert responses.calls[0].request.headers["X-Internal-Token"] == "secret" + + +@responses.activate +def test_force_fetch(): + responses.add(responses.POST, "http://fetcher:5001/fetch", + json={"stored": True, "payload_hash": "new", "changed": True}, status=200) + r = fc.force_fetch("alice") + assert r["changed"] is True +``` + +- [ ] **Step 2: Implement `generator/src/fetcher_client.py`** + +```python +"""HTTP client to the fetcher service. Used by api.py, worker.py, cron.py.""" +import requests + +from . import config + + +def _headers() -> dict: + return {"X-Internal-Token": config.FETCHER_INTERNAL_TOKEN} + + +def get_data(username: str) -> dict: + r = requests.get(f"{config.FETCHER_URL}/data/{username}", headers=_headers(), timeout=30) + r.raise_for_status() + return r.json() + + +def force_fetch(username: str) -> dict: + r = requests.post(f"{config.FETCHER_URL}/fetch", headers=_headers(), + json={"username": username}, timeout=30) + r.raise_for_status() + return r.json() +``` + +- [ ] **Step 3: Run — pass. Commit:** + +```bash +git add generator/src/fetcher_client.py generator/tests/test_fetcher_client.py +git commit -m "feat(generator): add typed HTTP client to the fetcher service" +``` + +--- + +## Phase 3 — Generator API, Worker, Cron, Integration + +### Task 3.1: Generator `worker.py` — build worker loop + +**Files:** +- Create: `generator/src/worker.py` +- Create: `generator/tests/test_worker.py` + +- [ ] **Step 1: Tests** + +```python +import os, tempfile, pytest +from unittest.mock import patch, MagicMock +from src import db as dbmod +from src import worker + + +@pytest.fixture +def tmp_dbs(monkeypatch): + with tempfile.TemporaryDirectory() as d: + monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db")) + monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db")) + dbmod.init_dbs() + yield d + + +def test_process_one_renders_and_stores_widgets(tmp_dbs): + dbmod.enroll("alice", {"theme": "dark", "enabled": ["grade"]}) + fake_payload = {"user": {"login": "alice"}, "repos": [], "events": [], + "commits": [], "total_commits": 0, "recent_commits": [], + "total_prs": 0, "collaborators_data": [], "avatar_b64": ""} + with patch("src.worker.fetcher_client.get_data", + return_value={"data": fake_payload, "payload_hash": "h1"}), \ + patch("src.worker._render_widgets", + return_value={"composite": "c", "grade": "g"}): + worker.process_one() + svg = dbmod.get_current_widget("alice", "composite") + assert svg == "c" + + +def test_not_found_payload_renders_not_found_placeholder(tmp_dbs): + dbmod.enroll("ghost", {"theme": "dark"}) + with patch("src.worker.fetcher_client.get_data", + return_value={"data": {"error": "not_found"}, "payload_hash": "x"}): + worker.process_one() + svg = dbmod.get_current_widget("ghost", "composite") + assert svg and "ghost" in svg + + +def test_worker_retries_on_fetcher_failure(tmp_dbs): + dbmod.enroll("alice", {"theme": "dark"}) + with patch("src.worker.fetcher_client.get_data", side_effect=RuntimeError("boom")): + worker.process_one() + # Job should have been re-queued with an incremented attempt count + with dbmod._settings_conn() as c: + row = c.execute("SELECT status, attempts, last_error FROM jobs WHERE username='alice'").fetchone() + assert row["status"] == "pending" + assert row["attempts"] == 1 + assert "boom" in row["last_error"] + + +def test_worker_marks_failed_after_max_attempts(tmp_dbs): + dbmod.enroll("alice", {"theme": "dark"}) + with patch("src.worker.fetcher_client.get_data", side_effect=RuntimeError("boom")): + for _ in range(4): + worker.process_one() + with dbmod._settings_conn() as c: + row = c.execute("SELECT status, attempts FROM jobs WHERE username='alice'").fetchone() + assert row["status"] == "failed" + assert row["attempts"] >= 3 +``` + +- [ ] **Step 2: Implement `generator/src/worker.py`** + +```python +"""Build worker. Pulls pending jobs and renders widgets. + +Run as its own container: CMD python -m src.worker +""" +import logging +import time +from typing import Optional + +from . import cache, config, db, fetcher_client, placeholder, processor +from .widgets import compose_widget + +log = logging.getLogger("generator.worker") +MAX_ATTEMPTS = 3 + + +def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, str]: + """Wrap the existing processor pipeline.""" + enabled = settings.get("enabled") or config.ENABLED_WIDGETS + order = settings.get("widget_order") or config.WIDGET_ORDER + theme = settings.get("theme", "dark") + widgets = processor.generate_widgets_from_github( + payload, + theme=theme, + custom_tags=settings.get("custom_tags"), + hidden_languages=settings.get("hidden_languages"), + enabled=enabled, + widget_settings=settings.get("widget_settings") or {}, + ) + ordered = [w for w in order if w in enabled and w in widgets and widgets[w]] + composite = compose_widget( + widgets=widgets, enabled=ordered, theme_name=theme, + username=username, avatar_b64=payload.get("avatar_b64", ""), + ) + out = {name: svg for name, svg in widgets.items() if svg} + out["composite"] = composite + return out + + +def process_one() -> bool: + """Process one pending job. Returns True if a job was handled.""" + job = db.claim_next_job() + if job is None: + return False + username = job["username"] + try: + result = fetcher_client.get_data(username) + payload = result.get("data") or {} + if payload.get("error") == "not_found": + svg = placeholder.render("not_found", username, theme="dark") + db.put_widgets(username, "not_found", {"composite": svg}) + db.complete_job(job["id"]) + log.info("not_found marker persisted for %s", username) + return True + + settings_row = db.get_settings(username) + if settings_row is None: + db.fail_job(job["id"], "settings missing", retry=False) + return True + + widgets = _render_widgets(username, payload, settings_row["settings"]) + db.put_widgets(username, settings_row["settings_hash"], widgets) + db.set_last_fetcher_hash(username, result.get("payload_hash", "")) + db.lru_trim(username, config.WIDGET_LRU_PER_USER) + c = cache.Cache() + c.delete(f"widget:composite:{username}", *[f"widget:{n}:{username}" for n in widgets]) + db.complete_job(job["id"]) + log.info("built widgets for %s", username) + return True + except Exception as e: + retry = job.get("attempts", 0) < MAX_ATTEMPTS + db.fail_job(job["id"], str(e)[:500], retry=retry) + log.warning("build failed for %s (retry=%s): %s", username, retry, e) + return True + + +def main(): + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s") + db.init_dbs() + while True: + db.reclaim_stuck_jobs(older_than_minutes=10) + if not process_one(): + time.sleep(0.5) + + +if __name__ == "__main__": + main() +``` + +- [ ] **Step 3: Run tests — pass. Commit:** + +```bash +git add generator/src/worker.py generator/tests/test_worker.py +git commit -m "feat(generator): add build worker with retries and placeholder fallback" +``` + +--- + +### Task 3.2: Generator `api.py` — Flask routes + SPA static + auth stub + +**Files:** +- Create: `generator/src/api.py` +- Create: `generator/tests/test_api.py` + +- [ ] **Step 1: Tests** + +```python +import os, tempfile, pytest +from unittest.mock import patch +from src import db as dbmod +from src import api as apimod + + +@pytest.fixture +def client(monkeypatch): + with tempfile.TemporaryDirectory() as d: + monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db")) + monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db")) + dbmod.init_dbs() + app = apimod.app + app.config["TESTING"] = True + with app.test_client() as c: + yield c + + +def test_health(client): + r = client.get("/api/health") + assert r.status_code == 200 + assert r.get_json()["service"] == "generator" + + +def test_get_unknown_user_auto_enrolls_and_returns_placeholder(client): + r = client.get("/api/alice") + assert r.status_code == 200 + assert r.headers["X-Widget-Status"] == "building" + assert "Building" in r.data.decode() + assert dbmod.get_settings("alice") is not None + + +def test_rate_limit_returns_rate_limited_placeholder(client, monkeypatch): + monkeypatch.setattr(apimod.config, "ENROLLMENT_DAILY_CAP", 1) + client.get("/api/alice") # uses the one slot + r = client.get("/api/bob") + assert r.headers["X-Widget-Status"] == "rate_limited" + + +def test_enrolled_user_with_built_widget_returns_ready(client): + dbmod.enroll("alice", {"theme": "dark"}) + dbmod.put_widgets("alice", "h1", {"composite": "ready"}) + # Force settings_hash to match + with dbmod._settings_conn() as c: + c.execute("UPDATE users SET settings_hash='h1' WHERE username='alice'") + c.commit() + r = client.get("/api/alice") + assert r.status_code == 200 + assert r.headers["X-Widget-Status"] == "ready" + assert b"ready" in r.data + + +def test_settings_patch_enqueues_rebuild(client): + dbmod.enroll("alice", {"theme": "dark"}) + r = client.patch("/api/alice/settings", json={"theme": "light"}) + assert r.status_code == 200 + assert dbmod.get_settings("alice")["settings"]["theme"] == "light" + + +def test_refresh_is_one_shot(client): + dbmod.enroll("alice", {"theme": "dark"}) + with patch("src.api.fetcher_client.force_fetch", return_value={"changed": True, "payload_hash": "x", "stored": True}): + r1 = client.post("/api/alice/refresh") + assert r1.status_code == 200 + r2 = client.post("/api/alice/refresh") + assert r2.status_code == 409 + + +def test_not_found_status_header(client): + dbmod.enroll("ghost", {"theme": "dark"}) + dbmod.put_widgets("ghost", "not_found", {"composite": "404"}) + with dbmod._settings_conn() as c: + c.execute("UPDATE users SET settings_hash='not_found' WHERE username='ghost'") + c.commit() + r = client.get("/api/ghost") + assert r.headers["X-Widget-Status"] == "not_found" +``` + +- [ ] **Step 2: Implement `generator/src/api.py`** + +```python +"""Flask app for the generator service. + +Serves: + / -> React SPA (static/index.html) + /assets/

-> SPA bundles + /api/* -> JSON/SVG API +""" +import os +from functools import wraps +from flask import Flask, jsonify, request, Response, send_from_directory + +from . import config, db, fetcher_client, placeholder + +_STATIC_DIR = os.path.join(os.path.dirname(__file__), "static") + +app = Flask(__name__, static_folder=None) + + +# ---- auth stub (v1: no-op; swap to real OAuth later) ---- + +def require_auth(fn): + @wraps(fn) + def wrapper(*args, **kwargs): + # v1: honor system — no check. Future: verify Authorization header. + return fn(*args, **kwargs) + return wrapper + + +# ---- SPA ---- + +@app.route("/", defaults={"path": ""}) +@app.route("/") +def spa(path: str): + # Reserve /api/* for API; everything else serves the SPA. + if path.startswith("api/"): + return jsonify({"error": "not found"}), 404 + full = os.path.join(_STATIC_DIR, path) if path else os.path.join(_STATIC_DIR, "index.html") + if path and os.path.isfile(full): + return send_from_directory(_STATIC_DIR, path) + index = os.path.join(_STATIC_DIR, "index.html") + if os.path.isfile(index): + return send_from_directory(_STATIC_DIR, "index.html") + return jsonify({"error": "frontend not built"}), 503 + + +# ---- API ---- + +@app.route("/api/health", methods=["GET"]) +def health(): + return jsonify({"status": "ok", "service": "generator"}) + + +@app.route("/api/", methods=["GET"]) +def get_widget(username: str): + return _serve(username, widget_name="composite") + + +@app.route("/api//.svg", methods=["GET"]) +def get_widget_named(username: str, widget: str): + return _serve(username, widget_name=widget) + + +def _serve(username: str, widget_name: str) -> Response: + settings_row = db.get_settings(username) + + # Unknown user -> try to enroll + if settings_row is None: + if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP: + return _placeholder_response("rate_limited", username) + defaults = { + "theme": "dark", + "enabled": config.ENABLED_WIDGETS, + "widget_order": config.WIDGET_ORDER, + } + db.enroll(username, defaults) + return _placeholder_response("building", username) + + db.touch_last_requested(username) + svg = db.get_current_widget(username, widget_name) + if svg is None: + return _placeholder_response("building", username, theme=settings_row["settings"].get("theme", "dark")) + + # Detect "not_found" widget stashed by the worker + if settings_row.get("settings_hash") == "not_found": + return Response(svg, mimetype="image/svg+xml", + headers={"X-Widget-Status": "not_found", "Cache-Control": "no-store"}) + + return Response(svg, mimetype="image/svg+xml", + headers={"X-Widget-Status": "ready", + "Cache-Control": "public, max-age=3600"}) + + +def _placeholder_response(variant: str, username: str, theme: str = "dark") -> Response: + svg = placeholder.render(variant, username, theme=theme) + return Response(svg, mimetype="image/svg+xml", + headers={"X-Widget-Status": variant, "Cache-Control": "no-store"}) + + +@app.route("/api/enroll", methods=["POST"]) +def enroll_endpoint(): + body = request.get_json(silent=True) or {} + username = body.get("username") + if not username: + return jsonify({"error": "username required"}), 400 + if db.get_settings(username) is not None: + return jsonify({"error": "already_enrolled"}), 409 + if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP: + return jsonify({"error": "rate_limited"}), 429 + defaults = {"theme": "dark", "enabled": config.ENABLED_WIDGETS, "widget_order": config.WIDGET_ORDER} + job_id = db.enroll(username, defaults) + return jsonify({"enrolled": True, "job_id": job_id}) + + +@app.route("/api//settings", methods=["GET"]) +@require_auth +def get_settings(username: str): + s = db.get_settings(username) + if s is None: + return jsonify({"error": "not_enrolled"}), 404 + return jsonify(s) + + +@app.route("/api//settings", methods=["PATCH"]) +@require_auth +def patch_settings(username: str): + if db.get_settings(username) is None: + return jsonify({"error": "not_enrolled"}), 404 + body = request.get_json(silent=True) or {} + merged = {**db.get_settings(username)["settings"], **body} + job_id = db.update_settings(username, merged) + return jsonify({"updated": True, "job_id": job_id}) + + +@app.route("/api//refresh", methods=["POST"]) +@require_auth +def refresh(username: str): + s = db.get_settings(username) + if s is None: + return jsonify({"error": "not_enrolled"}), 404 + if not db.mark_manual_refresh(username): + return jsonify({"error": "already_used"}), 409 + try: + fetcher_client.force_fetch(username) + except Exception as e: + return jsonify({"error": f"fetch failed: {e}"}), 502 + job_id = db.enqueue_build(username) + return jsonify({"refreshed": True, "job_id": job_id}) + + +def main(): + db.init_dbs() + app.run(host="0.0.0.0", port=config.PORT) + + +if __name__ == "__main__": + main() +``` + +- [ ] **Step 3: Run tests — pass. Commit:** + +```bash +git add generator/src/api.py generator/tests/test_api.py +git commit -m "feat(generator): add Flask API with SPA static, auth stub, rate limit" +``` + +--- + +### Task 3.3: Generator `cron.py` — poll fetcher, enqueue rebuilds + +**Files:** +- Create: `generator/src/cron.py` +- Create: `generator/tests/test_cron.py` + +- [ ] **Step 1: Tests** + +```python +import os, tempfile, pytest +from unittest.mock import patch +from src import db as dbmod +from src import cron as cronmod + + +@pytest.fixture +def tmp_dbs(monkeypatch): + with tempfile.TemporaryDirectory() as d: + monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db")) + monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db")) + dbmod.init_dbs() + yield + + +def test_tick_enqueues_build_when_hash_changed(tmp_dbs): + dbmod.enroll("alice", {"theme": "dark"}) + dbmod.set_last_fetcher_hash("alice", "old") + # Clear initial enroll job + with dbmod._settings_conn() as c: + c.execute("DELETE FROM jobs") + c.commit() + with patch("src.cron.fetcher_client.get_data", + return_value={"data": {}, "payload_hash": "new"}): + stats = cronmod.tick() + assert stats["enqueued"] == 1 + + +def test_tick_skips_when_hash_unchanged(tmp_dbs): + dbmod.enroll("alice", {"theme": "dark"}) + dbmod.set_last_fetcher_hash("alice", "same") + with dbmod._settings_conn() as c: + c.execute("DELETE FROM jobs") + c.commit() + with patch("src.cron.fetcher_client.get_data", + return_value={"data": {}, "payload_hash": "same"}): + stats = cronmod.tick() + assert stats["enqueued"] == 0 +``` + +- [ ] **Step 2: Implement `generator/src/cron.py`** + +```python +"""Generator cron: poll fetcher for payload-hash changes, enqueue rebuilds. + +Run as its own container: CMD python -m src.cron +""" +import logging +import time + +from . import config, db, fetcher_client + +log = logging.getLogger("generator.cron") + + +def tick() -> dict: + enqueued = 0 + failed = 0 + for username in db.list_enrolled(): + try: + info = db.get_settings(username) + current = info.get("last_fetcher_payload_hash") + r = fetcher_client.get_data(username) + latest = r.get("payload_hash") + if latest and latest != current: + db.enqueue_build(username) + db.set_last_fetcher_hash(username, latest) + enqueued += 1 + except Exception as e: + log.warning("poll failed for %s: %s", username, e) + failed += 1 + return {"enqueued": enqueued, "failed": failed} + + +def main(): + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s") + db.init_dbs() + interval_s = config.POLL_INTERVAL_MINUTES * 60 + while True: + try: + log.info("tick: %s", tick()) + except Exception: + log.exception("tick failed") + time.sleep(interval_s) + + +if __name__ == "__main__": + main() +``` + +- [ ] **Step 3: Run tests — pass. Commit:** + +```bash +git add generator/src/cron.py generator/tests/test_cron.py +git commit -m "feat(generator): add poll cron that enqueues on payload-hash change" +``` + +--- + +### Task 3.4: Integration test + generator README + +**Files:** +- Create: `generator/tests/integration/test_end_to_end.py` +- Create: `generator/README.md` + +- [ ] **Step 1: Integration test** + +```python +"""End-to-end: api + worker in-process + mocked fetcher HTTP.""" +import os, tempfile, threading, time +import pytest +import responses +from unittest.mock import patch +from src import api as apimod, db as dbmod, worker + + +@pytest.fixture +def env(monkeypatch): + with tempfile.TemporaryDirectory() as d: + monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db")) + monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db")) + monkeypatch.setattr(apimod.config, "FETCHER_URL", "http://fetcher-mock") + monkeypatch.setattr(apimod.config, "FETCHER_INTERNAL_TOKEN", "t") + dbmod.init_dbs() + yield + + +@responses.activate +def test_first_request_builds_then_serves_ready(env): + responses.add( + responses.GET, "http://fetcher-mock/data/alice", + json={"data": {"user": {"login": "alice"}, "repos": [], "events": [], + "commits": [], "total_commits": 0, "recent_commits": [], + "total_prs": 0, "collaborators_data": [], "avatar_b64": ""}, + "payload_hash": "h1"}, status=200, + ) + client = apimod.app.test_client() + + r1 = client.get("/api/alice") + assert r1.headers["X-Widget-Status"] == "building" + + # Drain any pending jobs + for _ in range(5): + if not worker.process_one(): + break + + r2 = client.get("/api/alice") + assert r2.headers["X-Widget-Status"] == "ready" + assert r2.data.startswith(b" | none | composite SVG; auto-enrolls unknown users | +| GET | /api//.svg | none | individual widget SVG | +| POST | /api/enroll | none | explicit enroll (body: {username}) | +| GET | /api//settings | stub | current settings | +| PATCH | /api//settings | stub | update settings (enqueues rebuild) | +| POST | /api//refresh | stub | one-shot re-fetch + rebuild | + +Responses carry `X-Widget-Status: ready | building | rate_limited | not_found`. + +## Env + +See `src/config.py`. +``` + +- [ ] **Step 4: Commit** + +```bash +git add generator/tests/integration/test_end_to_end.py generator/README.md +git commit -m "test(generator): add end-to-end integration test + README" +``` + +--- + +## Phase 4 — Edge Service + +### Task 4.1: Edge scaffolding + requirements + Dockerfile + +**Files:** +- Create: `edge/requirements.txt`, `edge/pytest.ini`, `edge/Dockerfile` +- Create: `edge/src/config.py` + +- [ ] **Step 1: `edge/requirements.txt`** + +``` +flask==3.0.3 +flask-caching==2.3.0 +flask-compress==1.15 +requests==2.32.3 +pytest==8.3.3 +responses==0.25.3 +gunicorn==23.0.0 +``` + +- [ ] **Step 2: `edge/pytest.ini`** + +```ini +[pytest] +testpaths = tests +python_files = test_*.py +pythonpath = . +addopts = -ra --strict-markers +``` + +- [ ] **Step 3: `edge/src/config.py`** + +```python +import os + +PORT = int(os.getenv("EDGE_PORT", "5003")) +GENERATOR_URL = os.getenv("GENERATOR_URL", "http://localhost:5002") +CACHE_TYPE = os.getenv("CACHE_TYPE", "SimpleCache") +CACHE_REDIS_URL = os.getenv("CACHE_REDIS_URL", "") +CACHE_DEFAULT_TIMEOUT = int(os.getenv("CACHE_DEFAULT_TIMEOUT", "86400")) +CACHE_THRESHOLD = int(os.getenv("CACHE_THRESHOLD", "10000")) +UPSTREAM_TIMEOUT = int(os.getenv("EDGE_UPSTREAM_TIMEOUT", "10")) +``` + +- [ ] **Step 4: `edge/Dockerfile`** + +```dockerfile +FROM python:3.11-slim + +WORKDIR /app +COPY requirements.txt ./ +RUN pip install --no-cache-dir -r requirements.txt +COPY src ./src + +EXPOSE 5003 +CMD ["gunicorn", "-b", "0.0.0.0:5003", "-w", "2", "src.api:app"] +``` + +- [ ] **Step 5: Commit** + +```bash +git add edge/requirements.txt edge/pytest.ini edge/src/config.py edge/Dockerfile +git commit -m "feat(edge): scaffold config, requirements, Dockerfile" +``` + +--- + +### Task 4.2: Edge `cache.py` + `api.py` with Flask-Caching and Flask-Compress + +**Files:** +- Create: `edge/src/cache.py` +- Create: `edge/src/api.py` +- Create: `edge/tests/test_api.py` + +- [ ] **Step 1: Tests `edge/tests/test_api.py`** + +```python +import pytest +import responses +from src import api as apimod + + +@pytest.fixture +def client(monkeypatch): + monkeypatch.setattr(apimod.config, "GENERATOR_URL", "http://gen:5002") + # Reset cache between tests + apimod.cache_ext.clear() + apimod.app.config["TESTING"] = True + with apimod.app.test_client() as c: + yield c + + +@responses.activate +def test_miss_then_hit_serves_from_cache(client): + responses.add(responses.GET, "http://gen:5002/api/alice", + body=b"ready", status=200, + headers={"X-Widget-Status": "ready", "Content-Type": "image/svg+xml"}) + r1 = client.get("/alice") + assert r1.status_code == 200 + assert r1.data == b"ready" + # second call should not hit origin + responses.reset() + r2 = client.get("/alice") + assert r2.status_code == 200 + assert r2.data == b"ready" + + +@responses.activate +def test_placeholder_not_cached(client): + responses.add(responses.GET, "http://gen:5002/api/alice", + body=b"building", status=200, + headers={"X-Widget-Status": "building", "Content-Type": "image/svg+xml"}) + r1 = client.get("/alice") + assert r1.status_code == 200 + # Origin MUST be called again on the second request because building wasn't cached + r2 = client.get("/alice") + assert len(responses.calls) == 2 + + +@responses.activate +def test_origin_error_returns_503(client): + responses.add(responses.GET, "http://gen:5002/api/alice", status=500) + r = client.get("/alice") + assert r.status_code == 503 + + +def test_health(client): + r = client.get("/health") + assert r.status_code == 200 +``` + +- [ ] **Step 2: `edge/src/cache.py`** + +```python +"""Flask-Caching config. v1 = SimpleCache (in-process). Swap to RedisCache via env.""" +from flask_caching import Cache +from . import config + + +def build_cache(app) -> Cache: + cfg = { + "CACHE_TYPE": config.CACHE_TYPE, + "CACHE_DEFAULT_TIMEOUT": config.CACHE_DEFAULT_TIMEOUT, + "CACHE_THRESHOLD": config.CACHE_THRESHOLD, + } + if config.CACHE_TYPE == "RedisCache" and config.CACHE_REDIS_URL: + cfg["CACHE_REDIS_URL"] = config.CACHE_REDIS_URL + c = Cache(config=cfg) + c.init_app(app) + return c +``` + +- [ ] **Step 3: `edge/src/api.py`** + +```python +"""Edge service — cache-first SVG proxy in front of the generator.""" +import logging +import requests +from flask import Flask, Response, jsonify, request +from flask_compress import Compress + +from . import cache as cache_mod, config + +app = Flask(__name__) +Compress(app) +cache_ext = cache_mod.build_cache(app) +log = logging.getLogger("edge") + + +def _cache_key(path: str) -> str: + return f"edge:{path}" + + +def _fetch_origin(path: str) -> requests.Response: + url = f"{config.GENERATOR_URL}/api/{path}" + return requests.get(url, timeout=config.UPSTREAM_TIMEOUT) + + +@app.route("/health", methods=["GET"]) +def health(): + ok = True + try: + r = requests.get(f"{config.GENERATOR_URL}/api/health", timeout=config.UPSTREAM_TIMEOUT) + ok = r.status_code == 200 + except Exception: + ok = False + return jsonify({"service": "edge", "cache_type": config.CACHE_TYPE, "upstream_ok": ok}) + + +@app.route("/", methods=["GET"]) +def serve(username: str): + return _serve(username, path=username) + + +@app.route("//.svg", methods=["GET"]) +def serve_widget(username: str, widget: str): + return _serve(f"{username}/{widget}", path=f"{username}/{widget}.svg") + + +def _serve(key_suffix: str, path: str) -> Response: + ck = _cache_key(key_suffix) + cached = cache_ext.get(ck) + if cached is not None: + body, content_type = cached + return Response(body, mimetype=content_type, headers={ + "X-Widget-Status": "ready", + "X-Cache": "HIT", + "Cache-Control": "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400", + }) + + try: + r = _fetch_origin(path) + except Exception as e: + log.warning("origin unreachable for %s: %s", path, e) + return jsonify({"error": "origin unreachable"}), 503 + + if r.status_code >= 500: + return jsonify({"error": "origin error"}), 503 + + status = r.headers.get("X-Widget-Status", "ready") + content_type = r.headers.get("Content-Type", "image/svg+xml") + if status == "ready" and r.status_code == 200: + cache_ext.set(ck, (r.content, content_type), timeout=config.CACHE_DEFAULT_TIMEOUT) + cc = "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400" + else: + cc = "no-store" + + return Response(r.content, status=r.status_code, mimetype=content_type, headers={ + "X-Widget-Status": status, + "X-Cache": "MISS", + "Cache-Control": cc, + }) + + +def main(): + app.run(host="0.0.0.0", port=config.PORT) + + +if __name__ == "__main__": + main() +``` + +- [ ] **Step 4: Run tests — pass** + +Run: `cd edge && pytest -v` +Expected: all PASS. + +- [ ] **Step 5: Commit** + +```bash +git add edge/src/cache.py edge/src/api.py edge/tests/test_api.py +git commit -m "feat(edge): add cache-first SVG proxy with Flask-Caching + Flask-Compress" +``` + +--- + +### Task 4.3: Edge README + +**Files:** +- Create: `edge/README.md` + +- [ ] **Step 1: Write** + +```markdown +# Edge Service + +Cache-first SVG proxy in front of the generator. Deploy many instances +around the world. No DB of its own; optional Redis for shared cache. + +## Run locally + + cd edge + pip install -r requirements.txt + GENERATOR_URL=http://localhost:5002 python -m src.api + +## Test + + cd edge && pytest + +## Docker + + docker build -t ghstats-edge . + docker run --rm -e GENERATOR_URL=http://host.docker.internal:5002 -p 5003:5003 ghstats-edge + +## Endpoints + +| Method | Path | Description | +|---|---|---| +| GET | /health | cache type + upstream reachability | +| GET | / | composite SVG (cached on X-Widget-Status: ready) | +| GET | //.svg | individual widget SVG | + +## Env + +- `GENERATOR_URL` — origin (required) +- `CACHE_TYPE` — `SimpleCache` (default) or `RedisCache` +- `CACHE_REDIS_URL` — if using RedisCache +- `CACHE_DEFAULT_TIMEOUT` — seconds, default 86400 +- `CACHE_THRESHOLD` — max entries (SimpleCache only), default 10000 +``` + +- [ ] **Step 2: Commit** + +```bash +git add edge/README.md +git commit -m "docs(edge): add README" +``` + +--- + +## Phase 5 — Frontend Migration + +### Task 5.1: Move frontend into generator + rename API paths + +**Files:** +- Move: `frontend/*` → `generator/frontend/*` +- Modify: any React sources that call the API — change hardcoded paths to `/api/*` + +- [ ] **Step 1: Move** + +```bash +git mv frontend generator/frontend +``` + +- [ ] **Step 2: Update React API calls** + +```bash +grep -rn "'/enroll\|'/users\|'/settings\|'/generate\|'/health\|'/refresh" generator/frontend/src || echo "clean" +``` + +Open each result and prepend `/api` to the path. Do the same for any `fetch('http://localhost:5002/...')` — replace with a `VITE_GENERATOR_URL` env var + `/api/`. + +- [ ] **Step 3: Add `generator/frontend/.env.example`** + +``` +VITE_GENERATOR_URL=http://localhost:5002 +VITE_EDGE_URL=http://localhost:5003 +``` + +- [ ] **Step 4: Update `vite.config.ts` dev proxy** + +In `generator/frontend/vite.config.ts`, add a dev proxy so `/api/*` during `npm run dev` hits the local Flask: + +```typescript +// Inside defineConfig({ server: { ... } }) +server: { + proxy: { + '/api': 'http://localhost:5002', + }, +}, +``` + +- [ ] **Step 5: Verify frontend builds** + +```bash +cd generator/frontend && npm install && npm run build +ls -la dist/ +``` + +Expected: `dist/index.html` and `dist/assets/` present. + +- [ ] **Step 6: Commit** + +```bash +git add generator/frontend/ -A +git commit -m "feat(generator): move frontend into generator + namespace API calls under /api/" +``` + +--- + +### Task 5.2: Multi-stage Dockerfile for generator + +**Files:** +- Create: `generator/Dockerfile` + +- [ ] **Step 1: Write** + +```dockerfile +# --- stage 1: build the React SPA --- +FROM node:20-alpine AS frontend-build +WORKDIR /app/frontend +COPY frontend/package.json frontend/package-lock.json ./ +RUN npm ci +COPY frontend/ ./ +# VITE_* env vars can be injected at build time via --build-arg +ARG VITE_GENERATOR_URL="" +ARG VITE_EDGE_URL="" +ENV VITE_GENERATOR_URL=$VITE_GENERATOR_URL +ENV VITE_EDGE_URL=$VITE_EDGE_URL +RUN npm run build + +# --- stage 2: python runtime --- +FROM python:3.11-slim AS runtime +WORKDIR /app +COPY requirements.txt ./ +RUN pip install --no-cache-dir -r requirements.txt + +COPY src ./src +RUN mkdir -p /app/src/static /app/data +COPY --from=frontend-build /app/frontend/dist/ /app/src/static/ + +EXPOSE 5002 +ENV GENERATOR_SETTINGS_DB_PATH=/app/data/settings.db +ENV GENERATOR_WIDGETS_DB_PATH=/app/data/widgets.db + +# Default is the API. Worker/cron containers override CMD. +CMD ["gunicorn", "-b", "0.0.0.0:5002", "-w", "2", "src.api:app"] +``` + +- [ ] **Step 2: Verify build succeeds** + +```bash +cd generator && docker build -t ghstats-generator-test . +``` + +Expected: image builds successfully. If frontend build fails because of missing env vars, set them via `--build-arg`. + +- [ ] **Step 3: Commit** + +```bash +git add generator/Dockerfile +git commit -m "feat(generator): add multi-stage Dockerfile (node build -> python runtime)" +``` + +--- + +### Task 5.3: `generator/frontend/README.md` + +**Files:** +- Create or overwrite: `generator/frontend/README.md` + +- [ ] **Step 1: Write** + +```markdown +# Frontend (Vite + React) + +Part of the generator service. Sources live here; the production build +is served as static files by the generator's Flask app (at `/`) and +produced by the generator's Dockerfile. + +## Dev + + npm install + VITE_GENERATOR_URL=http://localhost:5002 VITE_EDGE_URL=http://localhost:5003 npm run dev + +Vite proxies `/api/*` to the Flask app at :5002. + +## Build + + npm run build + # produces dist/ which is copied into generator/src/static/ by the Docker build +``` + +- [ ] **Step 2: Commit** + +```bash +git add generator/frontend/README.md +git commit -m "docs(frontend): update README for new location + API contract" +``` + +--- + +## Phase 6 — Polish + +### Task 6.1: Top-level README + CLAUDE.md update + +**Files:** +- Modify: `README.md` +- Modify: `CLAUDE.md` + +- [ ] **Step 1: Replace `README.md` contents** + +```markdown +# github-readme-stats + +A monorepo of three independent Python services plus a React frontend, +each self-contained. See each service's README for details. + +## Services + +| Folder | Port | Responsibility | +|---|---|---| +| [`fetcher/`](./fetcher/README.md) | 5001 | Owns GitHub PAT + `fetcher.db`; cron-refreshes data | +| [`generator/`](./generator/README.md) | 5002 | Settings + widgets DBs, build worker, serves React SPA + `/api/*` | +| [`edge/`](./edge/README.md) | 5003 | Cache-first SVG proxy; deploy globally | + +## Design Docs + +- Spec: [`docs/superpowers/specs/2026-04-17-production-pipeline-design.md`](docs/superpowers/specs/2026-04-17-production-pipeline-design.md) +- Plan: [`docs/superpowers/plans/2026-04-17-production-pipeline.md`](docs/superpowers/plans/2026-04-17-production-pipeline.md) + +## Quick start (local dev, no Docker) + + # 1) fetcher + (cd fetcher && pip install -r requirements.txt && + FETCHER_INTERNAL_TOKEN=dev GITHUB_PAT= python -m src.api) & + + # 2) generator API, worker, cron (three processes) + cd generator && pip install -r requirements.txt + FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.api & + FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.worker & + FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.cron & + + # 3) edge + (cd ../edge && pip install -r requirements.txt && + GENERATOR_URL=http://localhost:5002 python -m src.api) & + + # 4) frontend (dev server) + cd ../generator/frontend && npm install && npm run dev + +Test everything: + + (cd fetcher && pytest) && (cd generator && pytest) && (cd edge && pytest) +``` + +- [ ] **Step 2: Update `CLAUDE.md`** + +Replace its Commands + Architecture sections with a brief pointer to the new layout and per-service READMEs. Leave configuration + conventions sections intact but update paths (e.g., `src/config.py` → `generator/src/config.py`). + +- [ ] **Step 3: Commit** + +```bash +git add README.md CLAUDE.md +git commit -m "docs: top-level README + CLAUDE.md reflect three-service layout" +``` + +--- + +### Task 6.2: Remove stale top-level artifacts + final verification + +**Files:** +- Delete: `CONFIGURATION.md`, `TAG_CUSTOMIZATION.md` (if kept, move their content into `generator/README.md`; if not needed, drop) +- Verify: every service's tests pass end-to-end + +- [ ] **Step 1: Decide stale-docs disposition** + +Inspect `CONFIGURATION.md` and `TAG_CUSTOMIZATION.md`. Either: +- Move their useful sections into `generator/README.md` under an "Advanced config" heading, OR +- `git rm` them if their content is covered in the service READMEs. + +- [ ] **Step 2: Full test sweep** + +```bash +(cd fetcher && pytest -q) && (cd generator && pytest -q) && (cd edge && pytest -q) +``` + +Expected: all green. If anything fails, fix before committing. + +- [ ] **Step 3: Docker build sweep** + +```bash +docker build ./fetcher -t ghstats-fetcher-test +docker build ./generator -t ghstats-generator-test +docker build ./edge -t ghstats-edge-test +``` + +All three must succeed independently (no shared build context). + +- [ ] **Step 4: Commit** + +```bash +git add -A +git commit -m "chore: final cleanup — remove stale docs, verify three-service build" +``` + +--- + +## Completion Criteria + +- [ ] All three services build independently via `docker build ./`. +- [ ] All three services pass their own `pytest`. +- [ ] `GET http:///` returns a placeholder on unknown user; a real SVG after the build worker runs. +- [ ] `PATCH /api//settings` on the generator enqueues a rebuild and the edge serves updated SVG after cache expiry (or via future Redis invalidation). +- [ ] `POST /api//refresh` works once, returns 409 the second time. +- [ ] Retired files (`run.py`, old `src/*_api.py`, root `widget_*.svg`, `data/ghstats.db`, `REPORT.md`, `CHANGELOG.md`) are gone from the working tree. +- [ ] Frontend builds and is served by the generator container at `/`. +- [ ] `REDIS_URL` unset → every `cache.Cache()` call is a no-op; setting it later enables real caching with no code changes. + +--- + +## Execution Handoff + +Plan complete and saved to `docs/superpowers/plans/2026-04-17-production-pipeline.md`. Two execution options: + +**1. Subagent-Driven (recommended)** — dispatch a fresh subagent per task, review between tasks, fast iteration. + +**2. Inline Execution** — execute tasks in this session using `executing-plans`, batch execution with checkpoints. + +Which approach? diff --git a/docs/superpowers/specs/2026-04-17-production-pipeline-design.md b/docs/superpowers/specs/2026-04-17-production-pipeline-design.md new file mode 100644 index 0000000..7a6fe65 --- /dev/null +++ b/docs/superpowers/specs/2026-04-17-production-pipeline-design.md @@ -0,0 +1,531 @@ +# Production Pipeline Design — github-readme-stats + +**Date:** 2026-04-17 +**Status:** Approved for planning +**Scope:** Restructure the repo into three independent Python services (fetcher, generator, edge), each with its own Docker image, tests, README, and API. The existing React/Vite frontend folds into the generator service (built and served by it, but kept as a decoupled React app with its own sources). Redis is designed for but not stood up in v1; the edge uses in-process Flask-Caching + Flask-Compress as free wins. Hosting/orchestration is explicitly out of scope. + +## Goals + +- A public, unauthenticated URL `GET /` returns an SVG profile card suitable for embedding in a GitHub README. +- If the username is unknown at request time, return a clean "we're building your widget" placeholder immediately; fetch and build in the background. +- GitHub API calls are tightly rate-limited and live behind a single internal service (the fetcher) that holds the only GitHub PAT. +- The serving path is always a precomputed SVG lookup — never a render on the hot path. +- The three services must be genuinely independent so the generator can later be split into a build worker + a serverless edge serving layer without reshuffling the other services. + +## Non-Goals (v1) + +- No GitHub OAuth, no login, no per-user auth on the settings API. An auth stub is included so auth can be added later without touching call sites. +- No hosting, CI, cloud config, or docker-compose. +- No analytics, no metrics dashboard, no admin UI. +- No Postgres / remote DB. SQLite with WAL is sufficient for the v1 workload (one writer per DB, small volumes, mostly reads). All DB access lives behind one `db.py` per service so a swap to Postgres is a localized change. +- **No Redis deployment in v1.** Redis is designed in this spec so the integration points are correct, but v1 ships without Redis standing up. Edge uses in-process Flask-Caching; generator/fetcher skip the cache layer and talk directly over HTTP. Enabling Redis later is a config toggle — see the Redis section. + +## Architecture + +``` + GitHub README embed Browser (user visits app) + │ │ + ▼ ▼ + ┌───────────────┐ ┌─────────────────────────────┐ + │ Edge service │ │ Generator service │ + │ (many nodes) │──── HTTP ─────►│ / + /assets/* → React SPA │ + │ Flask- │ origin fetch │ /api/ → widget │ + │ Caching + │ on miss │ /api/enroll → enroll │ + │ Compress │ │ /api//... → settings │ + │ - / │ │ + build worker container │ + │ - // │ │ + poll cron container │ + └───────────────┘ └──────┬──────────┬───────────┘ + │ │ + settings.db widgets.db + ▲ + │ + HTTP (internal, + X-Internal-Token) + │ + ┌─────────────────▼───────┐ + │ Fetcher service │ + │ - /data/ (auto- │ + │ fetches on miss) │ + │ - /fetch (force) │ + │ - /avatar │ + │ + cron container │ + └──────┬──────────────────┘ + ▼ + fetcher.db + │ + ▼ + GitHub API + + (v2) Redis slots between edge↔generator and generator↔fetcher. + cache.py is a no-op wrapper until REDIS_URL is set. +``` + +The edge has no DB of its own and no origin DB access — it's a cache-first proxy. The generator serves both the React SPA (static files at `/`) and the API (`/api/*`). Deploy as many edge instances around the world as you like. + +## Redis (designed, not deployed in v1) + +Specified here so the code knows the integration shape. v1 behavior: every `REDIS_URL` env var is unset → the cache wrapper short-circuits to a no-op, and every caller falls through to the underlying service. No code changes required to enable later — set `REDIS_URL` and it starts caching. + +One Redis instance, accessible from fetcher, generator, and edge. Two key namespaces: + +| Key | Value | TTL | Written by | Read by | +|---|---|---|---|---| +| `fetcher:data:` | JSON payload from fetcher | 1h | fetcher (on miss-fill), generator cron on invalidation | generator API + worker | +| `fetcher:hash:` | Current `payload_hash` | 1h | fetcher | generator cron (cheap change detection) | +| `widget:composite:` | SVG string | 24h | edge (on miss-fill), generator (on rebuild invalidation) | edge | +| `widget::` | SVG string per widget | 24h | same as composite | edge | +| `enroll:day:` | Counter | 48h | generator API | generator API (rate limit check) | + +Rules: + +- **Redis is a cache, never a source of truth.** Every key has a TTL. Losing Redis is a latency event, not a correctness event. +- **Invalidation on write, not just TTL.** When the build worker writes new widget rows, it immediately `DEL`s the matching `widget:*:` keys so the next edge read re-populates. Same for fetcher on re-fetch. +- **Single Redis instance in v1.** If edge latency to a single Redis becomes a problem, swap to an edge-native KV (Cloudflare KV, Upstash) — only `edge/src/api.py` changes. + +## Services + +### 1. Fetcher + +**Purpose:** Own every GitHub API interaction. Hold the PAT. Expose cached payloads to the generator. + +**Endpoints** (all internal; not exposed to the public internet): + +- `GET /data/` — return stored payload JSON. If not stored, fetch from GitHub, store, return. This is the first-enrollment path. 502 on GitHub failure; 404 if GitHub says the user doesn't exist (fetcher stores a `{error: "not_found"}` marker so repeat calls are cheap). +- `POST /fetch {username}` — force re-fetch, ignoring any existing cache. Used by the fetcher's own cron and by manual admin action. Returns `{stored, payload_hash, changed}`. +- `GET /avatar/` — return avatar bytes. GitHub's `https://github.com/.png` is public and requires no PAT, so this is cheap. Used by the generator's placeholder renderer. +- `GET /health` + +**Auth:** every request requires `X-Internal-Token: ` header. The generator holds the matching secret. The fetcher never listens on a public interface. + +**Storage:** `fetcher.db` (SQLite), single table: + +```sql +CREATE TABLE users ( + username TEXT PRIMARY KEY, + data_json TEXT NOT NULL, -- full GitHub payload OR {"error":"not_found"} + payload_hash TEXT NOT NULL, -- sha256 of data_json + fetched_at TEXT NOT NULL, -- UTC ISO 8601 + last_requested_at TEXT NOT NULL -- updated on every GET /data; drives GC +); +``` + +**Cron (`fetcher/src/cron.py`):** runs every hour. Each tick: + +1. Select users with `fetched_at < now - 24h` AND `last_requested_at > now - 7d`. Stagger calls across the hour so we don't burst GitHub. +2. For each, call `POST /fetch` internally (or the equivalent function). Update `payload_hash`. +3. Delete rows where `last_requested_at < now - 7d` (trial GC — unused enrollments drop out automatically). `last_requested_at` is updated on every `GET /data/`, so actively-embedded users are never dropped. + +**Env vars:** + +- `FETCHER_PORT` (default `5001`) +- `FETCHER_DB_PATH` (default `./data/fetcher.db` inside container) +- `GITHUB_PAT` (required) +- `FETCHER_INTERNAL_TOKEN` (required; the shared secret) +- `FETCHER_REFRESH_INTERVAL_HOURS` (default `24`) +- `FETCHER_TRIAL_GC_DAYS` (default `7`) +- `REDIS_URL` (optional; if set, writes to cache on fetch) + +**DB pragmas:** on connection open, run `PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;`. + +### 2. Generator + +**Purpose:** Serve precomputed SVGs to the public internet. Hold user settings. Build widgets in the background. Never call GitHub directly; only talk to the fetcher over HTTP. + +All API endpoints are under the `/api/` prefix. Root `/` and `/assets/*` serve the React SPA built into `src/static/`. + +**Public API endpoints:** + +- `GET /api/` — return composite SVG from `widgets.db`. Placeholder on miss. Sets `X-Widget-Status` header. +- `GET /api//.svg` — individual widget. Same behavior. +- `POST /api/enroll {username}` — explicit enrollment (SPA uses this). Also auto-invoked when `GET /api/` arrives. Enforces daily rate limit. Returns `{enrolled, job_id}` or `{error: "rate_limited"}`. +- `GET /api/health` + +**Auth-gated API endpoints** (auth stub in v1 — passes everything through; real auth later): + +- `GET /api//settings` — current settings. +- `PATCH /api//settings` — update settings; enqueues a rebuild. Unlimited. Does NOT re-fetch GitHub. +- `POST /api//refresh` — one-shot manual re-fetch + rebuild. Calls fetcher's `POST /fetch`, then enqueues a rebuild. Gated by `manual_refresh_used` flag (allowed once per user, ever). Returns 409 `already_used` after the first call. + +**Storage:** + +**`settings.db`** (SQLite): + +```sql +CREATE TABLE users ( + username TEXT PRIMARY KEY, + settings_json TEXT NOT NULL, -- theme, enabled widgets, order, custom_tags, achievements, widget_settings + settings_hash TEXT NOT NULL, -- sha256 of canonicalized settings_json + enrolled_at TEXT NOT NULL, + last_fetcher_payload_hash TEXT, -- last hash we rebuilt from; cron compares + manual_refresh_used INTEGER DEFAULT 0, -- enforces one-shot user-triggered re-fetch + last_requested_at TEXT NOT NULL -- updated on every GET /; drives trial GC +); + +CREATE TABLE enrollments_daily ( + day TEXT PRIMARY KEY, -- YYYY-MM-DD, UTC + count INTEGER NOT NULL +); + +CREATE TABLE jobs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + kind TEXT NOT NULL, -- "build" + username TEXT NOT NULL, + status TEXT NOT NULL, -- "pending" | "running" | "done" | "failed" + attempts INTEGER DEFAULT 0, + last_error TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); +CREATE INDEX idx_jobs_pending ON jobs(status, created_at); +``` + +**`widgets.db`** (SQLite in v1; designed for swap to remote backend later): + +```sql +CREATE TABLE widgets ( + username TEXT NOT NULL, + settings_hash TEXT NOT NULL, + widget_name TEXT NOT NULL, -- "composite" | "grade" | "focus" | ... + svg TEXT NOT NULL, + built_at TEXT NOT NULL, + PRIMARY KEY (username, settings_hash, widget_name) +); + +CREATE TABLE current_widget ( + username TEXT PRIMARY KEY, + settings_hash TEXT NOT NULL, -- pointer to the "live" set + updated_at TEXT NOT NULL +); +CREATE INDEX idx_widgets_username ON widgets(username); +``` + +The `widgets_repo.py` module wraps all access. Future swap to Postgres / Turso / D1 / S3 changes only that one file. + +**Build worker (`generator/src/build_worker.py`):** + +- In-process thread polling `jobs` table every 500ms. +- For each pending job: mark `running`, load settings, `GET {fetcher}/data/` (fetcher auto-fetches on miss), compute `settings_hash`, render all enabled widgets + composite, upsert into `widgets.db`, flip `current_widget` pointer atomically, LRU-trim to 10 rows per user, mark `done`. +- Failure: increment `attempts`, exponential backoff (1min, 5min, 15min); after 3 attempts mark `failed` and leave the existing widget (if any) in place. Placeholder continues to serve for un-built users. +- Extractable to a standalone process later (same DB, same code, separate entrypoint). + +**Generator cron (`generator/src/cron.py`):** runs every 15 minutes. + +1. For each enrolled user, `GET {fetcher}/data/` (response includes `payload_hash`). +2. If `payload_hash != last_fetcher_payload_hash`, enqueue a build job and update `last_fetcher_payload_hash`. +3. LRU-trim widgets per user. + +**Enrollment rate limit:** global cap of 50 new enrollments per UTC day (`ENROLLMENT_DAILY_CAP`). Over cap → `POST /enroll` returns `rate_limited`; `GET /` returns a "try again tomorrow" placeholder. Enrollment counter increments only on *new* users, not on re-requests. + +**Placeholder renderer (`generator/src/placeholder.py`):** produces SVGs matching the card wrapper and theme of real widgets. Three variants: + +- **building**: "Building @username's widget... This usually takes under a minute." Shows avatar if fetched (generator calls `GET {fetcher}/avatar/`). Serves when user is enrolled but widgets not yet built. +- **rate_limited**: "Too many new users today — try again tomorrow." Shown when enrollment cap is hit. +- **not_found**: "GitHub user @username doesn't exist." Shown when fetcher stored a `not_found` marker. + +Placeholders are rendered on the fly (no DB lookup needed) and served with `Cache-Control: no-store`. + +**Env vars:** + +- `GENERATOR_PORT` (default `5002`) +- `GENERATOR_SETTINGS_DB_PATH` (default `./data/settings.db`) +- `GENERATOR_WIDGETS_DB_PATH` (default `./data/widgets.db`) +- `FETCHER_URL` (required, e.g. `http://mini-pc:5001`) +- `FETCHER_INTERNAL_TOKEN` (required, matches fetcher's) +- `REDIS_URL` (optional; if set, read-through to fetcher cache and invalidation on rebuild) +- `ENROLLMENT_DAILY_CAP` (default `50`) +- `WIDGET_LRU_PER_USER` (default `10`) +- `GENERATOR_POLL_INTERVAL_MINUTES` (default `15`) + +**DB pragmas:** same as fetcher (WAL + NORMAL sync + 5s busy_timeout). + +### 3. Edge + +**Purpose:** Serve widget SVGs cache-first, with the generator as origin. Deploy many instances around the world (Cloud Run, Fly, Lambda container, etc.). No DB of its own. + +**Endpoints:** + +- `GET /` — check cache; hit → return; miss → fetch generator `GET /api/`, cache, return. +- `GET //.svg` — same pattern. +- `GET /health` — reports cache type + origin reachability. + +**Caching (v1):** [Flask-Caching](https://flask-caching.readthedocs.io/) with `CACHE_TYPE=SimpleCache` — in-process LRU, per-instance, no external dependency. Wrapped by a thin `cache.py` so `CACHE_TYPE=RedisCache` + `CACHE_REDIS_URL` swaps in Redis later with no call-site changes. TTL: 24h. Max entries per instance: 10000. + +**Compression:** [Flask-Compress](https://github.com/colour-science/flask-compress) on, default settings. SVG is text — gzip typically 70-80%% savings. + +**HTTP cache headers on hits:** +- `Cache-Control: public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400` + +**Placeholder handling:** generator sets `X-Widget-Status: ready | building | rate_limited | not_found`. Edge only caches `ready` responses. Others are passed through with `Cache-Control: no-store` so a CDN in front doesn't memorize them. + +**Implementation:** single `edge/src/api.py` Flask file (~100 lines) + `edge/src/cache.py` (~30 lines). + +**Env vars:** +- `EDGE_PORT` (default `5003`) +- `GENERATOR_URL` (required — origin) +- `CACHE_TYPE` (default `SimpleCache`; later `RedisCache`) +- `CACHE_REDIS_URL` (optional) +- `CACHE_DEFAULT_TIMEOUT` (default `86400`) + +### Frontend (served by the generator) + +**Not a separate service.** The existing React/Vite frontend moves into `generator/frontend/` (source code) and is built by the generator's Dockerfile. The Flask app in `generator/src/api.py` serves the built static bundle from `/` (and `/assets/*`). The architecture stays decoupled — React sources live in their own folder, are built by their own toolchain, and only the static output is served by Flask. + +**URL split on the generator:** + +| Path | Served | Notes | +|---|---|---| +| `/` | `generator/frontend/dist/index.html` | React SPA entry | +| `/assets/*` | `generator/frontend/dist/assets/*` | JS/CSS bundles | +| `/api/` | Flask route | widget origin (called by edge) | +| `/api//.svg` | Flask route | individual widget origin | +| `/api/enroll` | Flask route | enrollment | +| `/api//settings` | Flask route | settings CRUD | +| `/api//refresh` | Flask route | one-shot re-fetch | +| `/api/health` | Flask route | health | + +**Why `/api/` prefix:** keeps the frontend `/` clean for the SPA and keeps widget origin paths from colliding with React routes. The edge rewrites `GET /` → `GET /api/` when calling origin. + +**Dockerfile (one, multi-stage):** + +1. **Stage `frontend-build`** — `node:20-alpine`, `npm ci && npm run build` inside `/app/frontend`, produces `/app/frontend/dist`. +2. **Stage `runtime`** — `python:3.11-slim`, install `requirements.txt`, copy `src/` and the built `frontend/dist` from stage 1 into `src/static/`. Flask serves from there. + +**Flow (v1, no auth):** + +1. User opens `https://generator.example.com/` → React SPA loads. +2. User enters their GitHub username → calls `POST /api/enroll`. +3. UI polls `GET {EDGE_URL}/` preview (placeholder until build completes). +4. Settings form edits go to `PATCH /api//settings`. +5. "Refresh from GitHub" button calls `POST /api//refresh`. Disabled after one use (server enforces 409). +6. UI displays the embeddable edge URL for pasting into their README. + +**Vite env vars:** `VITE_GENERATOR_URL`, `VITE_EDGE_URL` (baked at build time by the Dockerfile). + +## File Layout + +Simplified — each Python service is ~4-6 files plus its rendering assets. + +``` +github-readme-stats/ +├── fetcher/ +│ ├── src/ +│ │ ├── __init__.py +│ │ ├── api.py # Flask app + all routes + auth header check +│ │ ├── github.py # GitHub GraphQL/REST client (from src/data/fetcher.py) +│ │ ├── db.py # SQLite repo, WAL setup, schema migrations +│ │ ├── cron.py # scheduled refresh + GC; run as separate container +│ │ └── config.py +│ ├── tests/ +│ │ ├── test_api.py +│ │ ├── test_github.py +│ │ ├── test_db.py +│ │ └── test_cron.py +│ ├── data/ # gitignored +│ ├── Dockerfile +│ ├── requirements.txt +│ ├── pytest.ini +│ └── README.md +│ +├── generator/ +│ ├── frontend/ # React+Vite sources (moved from top-level frontend/) +│ │ ├── src/ +│ │ ├── package.json +│ │ ├── vite.config.ts +│ │ └── tsconfig.json +│ ├── src/ +│ │ ├── __init__.py +│ │ ├── api.py # Flask app + all /api/* routes + SPA static serve + fetcher HTTP client inline + auth stub inline +│ │ ├── worker.py # build worker loop; run as separate container +│ │ ├── cron.py # polls fetcher, enqueues rebuilds; run as separate container +│ │ ├── db.py # settings_repo + widgets_repo together +│ │ ├── cache.py # no-op in v1 (REDIS_URL unset); real wrapper otherwise +│ │ ├── placeholder.py # three SVG variants +│ │ ├── processor.py # widget rendering pipeline (from src/data/processor.py) +│ │ ├── config.py +│ │ ├── static/ # populated at Docker build time from frontend/dist +│ │ ├── widgets/ # (from src/widgets/) +│ │ ├── themes/ # (from src/themes/) +│ │ ├── models/ # (from src/models/) +│ │ └── utils/ # (from src/utils/) +│ ├── tests/ +│ │ ├── test_api.py +│ │ ├── test_worker.py +│ │ ├── test_cron.py +│ │ ├── test_db.py +│ │ ├── test_placeholder.py +│ │ ├── test_processor.py +│ │ └── integration/ +│ │ └── test_end_to_end.py +│ ├── data/ # gitignored +│ ├── Dockerfile # multi-stage: node build → python runtime (api+worker+cron share image) +│ ├── requirements.txt +│ ├── pytest.ini +│ └── README.md +│ +├── edge/ +│ ├── src/ +│ │ ├── __init__.py +│ │ ├── api.py # Flask app + Flask-Caching + Flask-Compress + origin fetch +│ │ ├── cache.py # Flask-Caching config (SimpleCache now, RedisCache later) +│ │ └── config.py +│ ├── tests/ +│ │ └── test_api.py +│ ├── Dockerfile +│ ├── requirements.txt +│ ├── pytest.ini +│ └── README.md +│ +├── docs/superpowers/specs/2026-04-17-production-pipeline-design.md +├── .gitignore # **/data/*.db, built artifacts +└── README.md # points to each service's README +``` + +**Independence rules:** + +- No Python imports cross service folders. Communication only via HTTP + Redis. +- No shared package. Duplicate any trivial util (e.g., `payload_hash`) per service. +- Each service has its own `requirements.txt`, `pytest.ini`, `Dockerfile`, `README.md`. +- `docker build ./fetcher` etc. succeeds with no repo-root build context. +- Generator ships one Docker image; three containers run from it with different `CMD`s: `python -m src.api`, `python -m src.worker`, `python -m src.cron`. + +## Code to Delete + +The current `src/` layout is retired wholesale. Specifically: + +- `run.py` — CLI entry point replaced by frontend + API. +- `src/generate.py` — replaced by the generator service. +- `src/fetcher_api.py`, `src/generator_api.py` — replaced by `fetcher/src/api.py` and `generator/src/api.py`. +- `src/db/` — schema moves to fetcher's `repository.py`; dummy user pattern replaced by placeholders. +- `src/data/ARCHITECTURE.md` — superseded by this spec. +- `widget_*.svg` at repo root — build artifacts, no longer produced. +- `data/ghstats.db` at repo root — replaced by per-service `data/*.db`. +- `REPORT.md`, `CHANGELOG.md` — stale; drop unless user wants them kept. +- `src/README.md` — superseded by per-service READMEs. + +`CLAUDE.md` is updated to reflect the new layout (sections on commands, architecture, configuration). `CONFIGURATION.md` and `TAG_CUSTOMIZATION.md` move into the generator's `README.md` (or its own `docs/` under `generator/`). + +Existing widget/theme/model code under `src/widgets/`, `src/themes/`, `src/models/`, `src/utils/`, and most of `src/data/processor.py` move into `generator/src/` and are kept. `src/data/fetcher.py` moves into `fetcher/src/github.py`. The top-level `frontend/` folder moves wholesale into `generator/frontend/`. + +## Data Flow + +### First-time `GET /shaymanor` (from a README embed, hitting the edge) + +1. Edge: Flask-Caching lookup for `/shaymanor` → miss. +2. Edge: HTTP `GET {generator}/api/shaymanor` → origin. +3. Generator: `widgets_repo.get_current(shaymanor)` → miss. +4. Generator: `settings_repo.get(shaymanor)` → miss → user unenrolled. +5. Enrollment path: + a. Check today's counter in `enrollments_daily`. If `>= 50`, return `rate_limited` placeholder with `X-Widget-Status: rate_limited` and `Cache-Control: no-store`. + b. Insert default settings row. Increment counter. + c. Insert `build` job. +6. Generator returns `building` placeholder with `X-Widget-Status: building`, `Cache-Control: no-store`. +7. Edge sees non-`ready` status header, returns SVG to the reader without caching. + +### Build worker processing a job + +1. Mark job `running`. +2. `cache.get("fetcher:data:")` via the wrapper (v1 = no-op, always miss). Miss → `GET {fetcher}/data/` with internal token (fetcher auto-fetches from GitHub on miss). Hit → use cached payload. +3. If payload is the `not_found` marker: upsert a `not_found` placeholder into widgets; flip `current_widget`; mark job `done`. No retries on this user. +4. Otherwise: load settings, compute `settings_hash`, render all enabled widgets + composite via the existing `processor.py` pipeline. +5. Transaction: insert widget rows, flip `current_widget`, update `settings.last_fetcher_payload_hash`. +6. `cache.delete("widget:composite:")` and per-widget keys (v1 no-op; real invalidation once Redis is enabled). +7. LRU-trim widgets for this user to 10 hashes. +8. Mark job `done`. + +The edge clears its own Flask-Caching entry via TTL expiry (24h) in v1. Users who want instant invalidation on rebuild can call the edge's `POST /admin/purge/` (added in v2 when Redis comes online — not in v1). + +### Cron-driven refresh + +1. Fetcher cron (hourly) re-fetches due users; updates `payload_hash` on change. +2. Generator cron (15 min) calls fetcher `GET /data/` per enrolled user (response includes `payload_hash`). Compares with `last_fetcher_payload_hash`. On mismatch, enqueues `build` job. (When Redis comes online in v2, this reads `fetcher:hash:` from Redis — HTTP becomes the fallback.) +3. Trial users not requested in 7 days are GC'd by fetcher cron. + +### Settings change from frontend + +1. `PATCH /shaymanor/settings` (auth stub passes through). +2. Generator computes new `settings_hash`, updates `settings_json`. +3. Enqueue `build` job. +4. Old `(username, old_hash)` rows remain in `widgets` until LRU-trimmed. `current_widget` flips once the build completes — no user-visible flicker. + +### Manual refresh (one-shot, user-triggered) + +1. `POST /shaymanor/refresh`. +2. If `manual_refresh_used = 1`, return 409 `already_used`. +3. Otherwise: set `manual_refresh_used = 1`, call fetcher `POST /fetch {username: shaymanor}` (this burns one GitHub-quota hit), enqueue `build` job. The rebuild will pick up the freshly-fetched data on the next poll. + +After this one-shot is spent, the user's data only changes via fetcher cron (every 24h). Settings edits continue to trigger unlimited rebuilds but never re-fetch. + +## Error Handling + +| Failure mode | Behavior | +|---|---| +| Fetcher unreachable from generator | Build job retries with backoff; placeholder continues to serve; `/health` reports degraded. | +| GitHub returns 5xx | Fetcher returns 502 to generator; build job retries. | +| GitHub returns 404 | Fetcher stores `{error: "not_found"}`; generator builds a `not_found` placeholder once, stops retrying. | +| GitHub rate-limit | Fetcher returns 429 to generator; build job retries with longer backoff. | +| Enrollment cap exceeded | `POST /enroll` → `rate_limited`. `GET /` → `rate_limited` placeholder. Next day resets. | +| Settings DB or widgets DB corrupt | Generator serves 503. Intentional — this is a server bug, not a missing-user condition. | +| Build worker dies mid-job | On next start, any `running` job older than 10 minutes is reclaimed to `pending`. | +| Manual refresh reused | 409 `already_used`. | + +## Testing + +Each service has its own `tests/` and runs with `cd && pytest`. + +**Fetcher:** +- `test_repository.py`: upsert, payload_hash stability, last_requested_at update on read. +- `test_github_client.py`: mocked HTTP with the `responses` library; covers GraphQL + REST paths, 404, 429, 502. +- `test_api.py`: auth-header enforcement, auto-fetch on miss, 404 handling. +- `test_cron.py`: staggered refresh, GC of stale trial users. + +**Generator:** +- `test_db.py`: settings + widgets CRUD, settings_hash canonicalization, LRU trimming, `current_widget` pointer atomicity, WAL pragma applied. +- `test_placeholder.py`: each of the three placeholder variants renders valid SVG and matches theme. +- `test_worker.py`: picks jobs, retries on fetcher failures, handles `not_found` marker, invalidates Redis on success. +- `test_api.py`: full surface — auth stub, rate limit, enrollment auto-trigger on `GET /api/`, serves precomputed on hit, placeholder on miss, `X-Widget-Status` header correct per case, SPA served at `/`. +- `test_cron.py`: polls fetcher via HTTP, enqueues only on hash change. +- `test_processor.py`: carry-over tests for widget rendering (from existing code). + +**Edge (`edge/tests/`):** +- `test_api.py`: SimpleCache hit returns cached SVG; miss fetches origin, caches, returns; `X-Widget-Status: ready` is cached, others pass through uncached; gzip content-encoding applied to responses > threshold. + +**Integration (`generator/tests/integration/`):** spin up generator API + worker + cron + edge + a fake fetcher (responses/respx mock) in-process, drive `GET /` end to end via the edge. Assert placeholder → build → real SVG transition and that the edge serves from cache on second request. + +**Frontend:** Vitest smoke tests: form submit, preview fetch, settings save. No E2E required in v1. + +## Security + +- Fetcher's `X-Internal-Token` is required on every endpoint except `/health`. Constant-time comparison. 401 on mismatch. +- No endpoint on the fetcher is exposed to the public internet. Deployment guidance in the fetcher README: bind to `127.0.0.1` or a private interface. +- Generator does not echo stored data anywhere except via the widget SVG — no `/data/` mirror. Prevents the generator from leaking raw GitHub payloads. +- Frontend talks to generator over HTTPS in production (user's responsibility). +- No secrets logged. No `GITHUB_PAT` in generator env at all. + +## Observability + +- Each service logs to stdout in a line-oriented format: `ts level service event key=val ...`. +- `/health` on each service returns `{status, service, db_ok, upstream_ok?}`. +- No metrics backend in v1. + +## Migration Plan (executed by the implementation phase) + +1. Create new folder scaffolding and move code wholesale. Do not keep the old `src/` in parallel — cut over in one branch. +2. Split `src/db/repository.py` into fetcher's `repository.py`. +3. Define new settings_repo and widgets_repo in `generator/src/`. +4. Write placeholder renderer using the existing card wrapper util (moved into `generator/src/utils/`). +5. Wire build worker + cron. +6. Update `.gitignore`; delete retired files and build artifacts. +7. Update the top-level `README.md` to point to the three service READMEs. +8. Update `CLAUDE.md` to reflect the new layout. + +## Open Questions + +None at time of writing. All design choices confirmed in brainstorming. + +## Future Work (out of scope for this spec) + +- GitHub OAuth on settings endpoints. +- Postgres migration (swap `db.py` per service; all call sites unchanged). +- Edge-native KV store (Cloudflare KV / Upstash) if single-Redis latency is a problem from far regions. +- Admin endpoints for cron pause / manual re-fetch / user purge. +- Metrics + alerting. diff --git a/edge/Dockerfile b/edge/Dockerfile new file mode 100644 index 0000000..e23d1fd --- /dev/null +++ b/edge/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.11-slim + +WORKDIR /app +COPY requirements.txt ./ +RUN pip install --no-cache-dir -r requirements.txt +COPY src ./src + +EXPOSE 5003 +CMD ["gunicorn", "-b", "0.0.0.0:5003", "-w", "2", "src.api:app"] diff --git a/edge/README.md b/edge/README.md new file mode 100644 index 0000000..06a4488 --- /dev/null +++ b/edge/README.md @@ -0,0 +1,35 @@ +# Edge Service + +Cache-first SVG proxy in front of the generator. Deploy many instances +around the world. No DB of its own; optional Redis for shared cache. + +## Run locally + + cd edge + pip install -r requirements.txt + GENERATOR_URL=http://localhost:5002 python -m src.api + +## Test + + cd edge && pytest + +## Docker + + docker build -t ghstats-edge . + docker run --rm -e GENERATOR_URL=http://host.docker.internal:5002 -p 5003:5003 ghstats-edge + +## Endpoints + +| Method | Path | Description | +|---|---|---| +| GET | /health | cache type + upstream reachability | +| GET | / | composite SVG (cached on X-Widget-Status: ready) | +| GET | //.svg | individual widget SVG | + +## Env + +- `GENERATOR_URL` — origin (required) +- `CACHE_TYPE` — `SimpleCache` (default) or `RedisCache` +- `CACHE_REDIS_URL` — if using RedisCache +- `CACHE_DEFAULT_TIMEOUT` — seconds, default 86400 +- `CACHE_THRESHOLD` — max entries (SimpleCache only), default 10000 diff --git a/edge/pytest.ini b/edge/pytest.ini new file mode 100644 index 0000000..9d1efdb --- /dev/null +++ b/edge/pytest.ini @@ -0,0 +1,5 @@ +[pytest] +testpaths = tests +python_files = test_*.py +pythonpath = . +addopts = -ra --strict-markers diff --git a/edge/requirements.txt b/edge/requirements.txt new file mode 100644 index 0000000..2a644ec --- /dev/null +++ b/edge/requirements.txt @@ -0,0 +1,7 @@ +flask==3.0.3 +flask-caching==2.3.0 +flask-compress==1.15 +requests==2.32.3 +pytest==8.3.3 +responses==0.25.3 +gunicorn==23.0.0 diff --git a/edge/src/__init__.py b/edge/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/edge/src/api.py b/edge/src/api.py new file mode 100644 index 0000000..109f5fc --- /dev/null +++ b/edge/src/api.py @@ -0,0 +1,85 @@ +"""Edge service — cache-first SVG proxy in front of the generator.""" +import logging +import requests +from flask import Flask, Response, jsonify +from flask_compress import Compress + +from . import cache as cache_mod, config + +app = Flask(__name__) +Compress(app) +cache_ext = cache_mod.build_cache(app) +log = logging.getLogger("edge") + + +def _cache_key(path: str) -> str: + return f"edge:{path}" + + +def _fetch_origin(path: str) -> requests.Response: + url = f"{config.GENERATOR_URL}/api/{path}" + return requests.get(url, timeout=config.UPSTREAM_TIMEOUT) + + +@app.route("/health", methods=["GET"]) +def health(): + ok = True + try: + r = requests.get(f"{config.GENERATOR_URL}/api/health", timeout=config.UPSTREAM_TIMEOUT) + ok = r.status_code == 200 + except Exception: + ok = False + return jsonify({"service": "edge", "cache_type": config.CACHE_TYPE, "upstream_ok": ok}) + + +@app.route("/", methods=["GET"]) +def serve(username: str): + return _serve(username, path=username) + + +@app.route("//.svg", methods=["GET"]) +def serve_widget(username: str, widget: str): + return _serve(f"{username}/{widget}", path=f"{username}/{widget}.svg") + + +def _serve(key_suffix: str, path: str) -> Response: + ck = _cache_key(key_suffix) + cached = cache_ext.get(ck) + if cached is not None: + body, content_type = cached + return Response(body, mimetype=content_type, headers={ + "X-Widget-Status": "ready", + "X-Cache": "HIT", + "Cache-Control": "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400", + }) + + try: + r = _fetch_origin(path) + except Exception as e: + log.warning("origin unreachable for %s: %s", path, e) + return jsonify({"error": "origin unreachable"}), 503 + + if r.status_code >= 500: + return jsonify({"error": "origin error"}), 503 + + status = r.headers.get("X-Widget-Status", "ready") + content_type = r.headers.get("Content-Type", "image/svg+xml") + if status == "ready" and r.status_code == 200: + cache_ext.set(ck, (r.content, content_type), timeout=config.CACHE_DEFAULT_TIMEOUT) + cc = "public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400" + else: + cc = "no-store" + + return Response(r.content, status=r.status_code, mimetype=content_type, headers={ + "X-Widget-Status": status, + "X-Cache": "MISS", + "Cache-Control": cc, + }) + + +def main(): + app.run(host="0.0.0.0", port=config.PORT) + + +if __name__ == "__main__": + main() diff --git a/edge/src/cache.py b/edge/src/cache.py new file mode 100644 index 0000000..b6c19ce --- /dev/null +++ b/edge/src/cache.py @@ -0,0 +1,16 @@ +"""Flask-Caching config. v1 = SimpleCache (in-process). Swap to RedisCache via env.""" +from flask_caching import Cache +from . import config + + +def build_cache(app) -> Cache: + cfg = { + "CACHE_TYPE": config.CACHE_TYPE, + "CACHE_DEFAULT_TIMEOUT": config.CACHE_DEFAULT_TIMEOUT, + "CACHE_THRESHOLD": config.CACHE_THRESHOLD, + } + if config.CACHE_TYPE == "RedisCache" and config.CACHE_REDIS_URL: + cfg["CACHE_REDIS_URL"] = config.CACHE_REDIS_URL + c = Cache(config=cfg) + c.init_app(app) + return c diff --git a/edge/src/config.py b/edge/src/config.py new file mode 100644 index 0000000..c771baf --- /dev/null +++ b/edge/src/config.py @@ -0,0 +1,9 @@ +import os + +PORT = int(os.getenv("EDGE_PORT", "5003")) +GENERATOR_URL = os.getenv("GENERATOR_URL", "http://localhost:5002") +CACHE_TYPE = os.getenv("CACHE_TYPE", "SimpleCache") +CACHE_REDIS_URL = os.getenv("CACHE_REDIS_URL", "") +CACHE_DEFAULT_TIMEOUT = int(os.getenv("CACHE_DEFAULT_TIMEOUT", "86400")) +CACHE_THRESHOLD = int(os.getenv("CACHE_THRESHOLD", "10000")) +UPSTREAM_TIMEOUT = int(os.getenv("EDGE_UPSTREAM_TIMEOUT", "10")) diff --git a/edge/tests/__init__.py b/edge/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/edge/tests/test_api.py b/edge/tests/test_api.py new file mode 100644 index 0000000..bb22e87 --- /dev/null +++ b/edge/tests/test_api.py @@ -0,0 +1,49 @@ +import pytest +import responses +from src import api as apimod + + +@pytest.fixture +def client(monkeypatch): + monkeypatch.setattr(apimod.config, "GENERATOR_URL", "http://gen:5002") + apimod.cache_ext.clear() + apimod.app.config["TESTING"] = True + with apimod.app.test_client() as c: + yield c + + +@responses.activate +def test_miss_then_hit_serves_from_cache(client): + responses.add(responses.GET, "http://gen:5002/api/alice", + body=b"ready", status=200, + headers={"X-Widget-Status": "ready", "Content-Type": "image/svg+xml"}) + r1 = client.get("/alice") + assert r1.status_code == 200 + assert r1.data == b"ready" + responses.reset() + r2 = client.get("/alice") + assert r2.status_code == 200 + assert r2.data == b"ready" + + +@responses.activate +def test_placeholder_not_cached(client): + responses.add(responses.GET, "http://gen:5002/api/alice", + body=b"building", status=200, + headers={"X-Widget-Status": "building", "Content-Type": "image/svg+xml"}) + r1 = client.get("/alice") + assert r1.status_code == 200 + r2 = client.get("/alice") + assert len(responses.calls) == 2 + + +@responses.activate +def test_origin_error_returns_503(client): + responses.add(responses.GET, "http://gen:5002/api/alice", status=500) + r = client.get("/alice") + assert r.status_code == 503 + + +def test_health(client): + r = client.get("/health") + assert r.status_code == 200 diff --git a/fetcher/Dockerfile b/fetcher/Dockerfile new file mode 100644 index 0000000..9a18930 --- /dev/null +++ b/fetcher/Dockerfile @@ -0,0 +1,14 @@ +FROM python:3.11-slim + +WORKDIR /app +COPY requirements.txt ./ +RUN pip install --no-cache-dir -r requirements.txt + +COPY src ./src +RUN mkdir -p /app/data + +EXPOSE 5001 +ENV FETCHER_DB_PATH=/app/data/fetcher.db + +# Default is the API. Override CMD for cron: ["python", "-m", "src.cron"] +CMD ["gunicorn", "-b", "0.0.0.0:5001", "-w", "2", "src.api:app"] diff --git a/fetcher/README.md b/fetcher/README.md new file mode 100644 index 0000000..6b76e56 --- /dev/null +++ b/fetcher/README.md @@ -0,0 +1,37 @@ +# Fetcher Service + +Owns every GitHub API interaction. Holds the PAT. Exposes cached payloads +over an internal-only HTTP API protected by a shared secret. + +## Run locally + + cd fetcher + pip install -r requirements.txt + FETCHER_INTERNAL_TOKEN=dev GITHUB_PAT=ghp_xxx python -m src.api + +Cron (separate process): + + FETCHER_INTERNAL_TOKEN=dev GITHUB_PAT=ghp_xxx python -m src.cron + +## Test + + cd fetcher && pytest + +## Docker + + docker build -t ghstats-fetcher . + docker run -e GITHUB_PAT=ghp_xxx -e FETCHER_INTERNAL_TOKEN=dev -p 5001:5001 -v $(pwd)/data:/app/data ghstats-fetcher + # cron: override CMD to ["python","-m","src.cron"] + +## Endpoints + +| Method | Path | Auth | Description | +|---|---|---|---| +| GET | /health | none | health check | +| GET | /data/ | X-Internal-Token | return stored payload; auto-fetches on miss | +| POST | /fetch | X-Internal-Token | force re-fetch (body: {username}) | +| GET | /avatar/ | X-Internal-Token | proxied avatar bytes | + +## Env + +See `src/config.py`. diff --git a/fetcher/data/.gitkeep b/fetcher/data/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/fetcher/pytest.ini b/fetcher/pytest.ini new file mode 100644 index 0000000..9d1efdb --- /dev/null +++ b/fetcher/pytest.ini @@ -0,0 +1,5 @@ +[pytest] +testpaths = tests +python_files = test_*.py +pythonpath = . +addopts = -ra --strict-markers diff --git a/fetcher/requirements.txt b/fetcher/requirements.txt new file mode 100644 index 0000000..ee8f159 --- /dev/null +++ b/fetcher/requirements.txt @@ -0,0 +1,5 @@ +flask==3.0.3 +requests==2.32.3 +pytest==8.3.3 +responses==0.25.3 +gunicorn==23.0.0 diff --git a/fetcher/src/__init__.py b/fetcher/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/fetcher/src/api.py b/fetcher/src/api.py new file mode 100644 index 0000000..2eeaa51 --- /dev/null +++ b/fetcher/src/api.py @@ -0,0 +1,89 @@ +"""Flask app for the fetcher service. All endpoints require X-Internal-Token.""" +import hmac +import requests +from flask import Flask, jsonify, request, Response +from functools import wraps + +from . import config, db, github + +app = Flask(__name__) + + +def require_internal_token(fn): + @wraps(fn) + def wrapper(*args, **kwargs): + token = request.headers.get("X-Internal-Token", "") + if not config.INTERNAL_TOKEN or not hmac.compare_digest(token, config.INTERNAL_TOKEN): + return jsonify({"error": "unauthorized"}), 401 + return fn(*args, **kwargs) + return wrapper + + +@app.route("/health", methods=["GET"]) +def health(): + return jsonify({"status": "ok", "service": "fetcher", "users": len(db.list_usernames())}) + + +@app.route("/data/", methods=["GET"]) +@require_internal_token +def get_data(username: str): + row = db.get_user(username) + if row is None: + # Auto-fetch path + data = github.fetch_github_data(username, token=config.GITHUB_PAT) + if _is_github_not_found(data): + data = {"error": "not_found"} + h = db.upsert_user(username, data) + return jsonify({"data": data, "payload_hash": h, "fetched": True}) + return jsonify({ + "data": row["data"], + "payload_hash": row["payload_hash"], + "fetched_at": row["fetched_at"], + "fetched": False, + }) + + +@app.route("/fetch", methods=["POST"]) +@require_internal_token +def force_fetch(): + body = request.get_json(silent=True) or {} + username = body.get("username") + if not username: + return jsonify({"error": "username required"}), 400 + try: + data = github.fetch_github_data(username, token=config.GITHUB_PAT) + except Exception as e: + return jsonify({"error": f"fetch failed: {e}"}), 502 + if _is_github_not_found(data): + data = {"error": "not_found"} + old = db.get_user(username) + old_hash = old["payload_hash"] if old else None + new_hash = db.upsert_user(username, data) + return jsonify({"stored": True, "payload_hash": new_hash, "changed": old_hash != new_hash}) + + +@app.route("/avatar/", methods=["GET"]) +@require_internal_token +def avatar(username: str): + r = requests.get(f"https://github.com/{username}.png", timeout=config.API_TIMEOUT, allow_redirects=True) + if r.status_code != 200: + return jsonify({"error": "avatar unavailable"}), 404 + return Response(r.content, mimetype=r.headers.get("Content-Type", "image/png")) + + +def _is_github_not_found(data: dict) -> bool: + user = data.get("user") + if user is None: + return True + if isinstance(user, dict) and user.get("message") == "Not Found": + return True + return False + + +def main(): + db.init_db() + app.run(host="0.0.0.0", port=config.PORT) + + +if __name__ == "__main__": + main() diff --git a/fetcher/src/config.py b/fetcher/src/config.py new file mode 100644 index 0000000..19572a6 --- /dev/null +++ b/fetcher/src/config.py @@ -0,0 +1,25 @@ +"""Fetcher service configuration, overridable via env vars.""" +import os + +PORT = int(os.getenv("FETCHER_PORT", "5001")) +DB_PATH = os.getenv("FETCHER_DB_PATH", "./data/fetcher.db") +GITHUB_PAT = os.getenv("GITHUB_PAT", "") +INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "") +REFRESH_INTERVAL_HOURS = int(os.getenv("FETCHER_REFRESH_INTERVAL_HOURS", "24")) +TRIAL_GC_DAYS = int(os.getenv("FETCHER_TRIAL_GC_DAYS", "7")) +API_TIMEOUT = int(os.getenv("API_TIMEOUT", "15")) + +# Collaborator-detection tuning +COLLABORATOR_MAX_REPO_SIZE = int(os.getenv("COLLABORATOR_MAX_REPO_SIZE", "150")) +COLLABORATOR_TOP_REPOS = int(os.getenv("COLLABORATOR_TOP_REPOS", "30")) +SMALL_OWNED_REPO_SIZE = int(os.getenv("SMALL_OWNED_REPO_SIZE", "10")) +COLLABORATOR_LOOKBACK_DAYS = int(os.getenv("COLLABORATOR_LOOKBACK_DAYS", "365")) +MEANINGFUL_MIN_COMMITS = int(os.getenv("MEANINGFUL_MIN_COMMITS", "3")) +FORK_MIN_COMMITS = int(os.getenv("FORK_MIN_COMMITS", "10")) +OWNER_BOOST = float(os.getenv("OWNER_BOOST", "1.5")) +MIN_SHARED_REPOS = int(os.getenv("MIN_SHARED_REPOS", "2")) +DEEP_COLLAB_THRESHOLD = int(os.getenv("DEEP_COLLAB_THRESHOLD", "25")) + +# Commit-fetching caps +COMMIT_MAX_REPOS = int(os.getenv("COMMIT_MAX_REPOS", "10")) +COMMIT_PER_REPO = int(os.getenv("COMMIT_PER_REPO", "30")) diff --git a/fetcher/src/cron.py b/fetcher/src/cron.py new file mode 100644 index 0000000..da29363 --- /dev/null +++ b/fetcher/src/cron.py @@ -0,0 +1,48 @@ +"""Scheduled refresh + GC loop. Run as its own container (CMD override).""" +import logging +import time + +from . import config, db, github + +log = logging.getLogger("fetcher.cron") + + +def tick(hours: int, active_within_days: int, gc_days: int) -> dict: + """Refresh due users, then GC abandoned ones. Returns counts.""" + refreshed = 0 + failed = 0 + due = db.users_due_for_refresh(hours=hours, active_within_days=active_within_days) + for username in due: + try: + data = github.fetch_github_data(username, token=config.GITHUB_PAT) + user = data.get("user") + if user is None or (isinstance(user, dict) and user.get("message") == "Not Found"): + data = {"error": "not_found"} + db.upsert_user(username, data) + refreshed += 1 + except Exception as e: + log.warning("refresh failed for %s: %s", username, e) + failed += 1 + gc_removed = db.delete_stale(days=gc_days) + return {"refreshed": refreshed, "failed": failed, "gc_removed": gc_removed} + + +def main(): + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s") + db.init_db() + interval = 3600 # 1h between ticks + while True: + try: + stats = tick( + hours=config.REFRESH_INTERVAL_HOURS, + active_within_days=config.TRIAL_GC_DAYS, + gc_days=config.TRIAL_GC_DAYS, + ) + log.info("tick complete: %s", stats) + except Exception: + log.exception("tick failed") + time.sleep(interval) + + +if __name__ == "__main__": + main() diff --git a/fetcher/src/db.py b/fetcher/src/db.py new file mode 100644 index 0000000..4806a59 --- /dev/null +++ b/fetcher/src/db.py @@ -0,0 +1,121 @@ +"""SQLite repository for the fetcher service. + +Single table: users (raw GitHub payloads keyed by username). +Uses WAL mode so concurrent readers don't block the writer. +""" +import hashlib +import json +import os +import sqlite3 +from contextlib import contextmanager +from datetime import datetime, timedelta +from typing import Optional + +from . import config + +DB_PATH = config.DB_PATH + +SCHEMA_SQL = """ +CREATE TABLE IF NOT EXISTS users ( + username TEXT PRIMARY KEY, + data_json TEXT NOT NULL, + payload_hash TEXT NOT NULL, + fetched_at TEXT NOT NULL, + last_requested_at TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_users_fetched_at ON users(fetched_at); +CREATE INDEX IF NOT EXISTS idx_users_last_requested_at ON users(last_requested_at); +""" + + +def _now() -> str: + return datetime.utcnow().isoformat(timespec="seconds") + "Z" + + +@contextmanager +def _connect(): + os.makedirs(os.path.dirname(DB_PATH) or ".", exist_ok=True) + conn = sqlite3.connect(DB_PATH, timeout=10) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA journal_mode=WAL") + conn.execute("PRAGMA synchronous=NORMAL") + conn.execute("PRAGMA foreign_keys=ON") + conn.execute("PRAGMA busy_timeout=5000") + try: + yield conn + conn.commit() + finally: + conn.close() + + +def init_db() -> None: + with _connect() as c: + c.executescript(SCHEMA_SQL) + c.commit() + + +def payload_hash(data: dict) -> str: + canonical = json.dumps(data, sort_keys=True, separators=(",", ":")) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() + + +def upsert_user(username: str, data: dict) -> str: + h = payload_hash(data) + now = _now() + with _connect() as c: + c.execute( + """INSERT INTO users(username, data_json, payload_hash, fetched_at, last_requested_at) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT(username) DO UPDATE SET + data_json = excluded.data_json, + payload_hash = excluded.payload_hash, + fetched_at = excluded.fetched_at""", + (username, json.dumps(data), h, now, now), + ) + c.commit() + return h + + +def get_user(username: str) -> Optional[dict]: + """Returns {data, payload_hash, fetched_at, last_requested_at} or None. Updates last_requested_at.""" + now = _now() + with _connect() as c: + row = c.execute( + "SELECT data_json, payload_hash, fetched_at, last_requested_at FROM users WHERE username=?", + (username,), + ).fetchone() + if row is None: + return None + c.execute("UPDATE users SET last_requested_at=? WHERE username=?", (now, username)) + c.commit() + return { + "data": json.loads(row["data_json"]), + "payload_hash": row["payload_hash"], + "fetched_at": row["fetched_at"], + "last_requested_at": now, + } + + +def delete_stale(days: int) -> int: + cutoff = (datetime.utcnow() - timedelta(days=days)).isoformat(timespec="seconds") + "Z" + with _connect() as c: + cur = c.execute("DELETE FROM users WHERE last_requested_at < ?", (cutoff,)) + c.commit() + return cur.rowcount + + +def users_due_for_refresh(hours: int, active_within_days: int) -> list[str]: + """Return usernames with fetched_at older than `hours` and last_requested_at within `active_within_days`.""" + stale_before = (datetime.utcnow() - timedelta(hours=hours)).isoformat(timespec="seconds") + "Z" + active_after = (datetime.utcnow() - timedelta(days=active_within_days)).isoformat(timespec="seconds") + "Z" + with _connect() as c: + rows = c.execute( + "SELECT username FROM users WHERE fetched_at < ? AND last_requested_at > ?", + (stale_before, active_after), + ).fetchall() + return [r["username"] for r in rows] + + +def list_usernames() -> list[str]: + with _connect() as c: + return [r["username"] for r in c.execute("SELECT username FROM users ORDER BY username").fetchall()] diff --git a/src/data/fetcher.py b/fetcher/src/github.py similarity index 95% rename from src/data/fetcher.py rename to fetcher/src/github.py index 8997ef2..4f8d87d 100644 --- a/src/data/fetcher.py +++ b/fetcher/src/github.py @@ -4,20 +4,7 @@ import requests import base64 from typing import Optional, Protocol -from ..config import ( - COLLABORATOR_MAX_REPO_SIZE, - COLLABORATOR_TOP_REPOS, - COLLABORATOR_LOOKBACK_DAYS, - MEANINGFUL_MIN_COMMITS, - FORK_MIN_COMMITS, - OWNER_BOOST, - MIN_SHARED_REPOS, - DEEP_COLLAB_THRESHOLD, - SMALL_OWNED_REPO_SIZE, - COMMIT_MAX_REPOS, - COMMIT_PER_REPO, - API_TIMEOUT, -) +from . import config class GitHubDataSource(Protocol): @@ -91,7 +78,7 @@ class DirectAPISource: "https://api.github.com/graphql", json=payload, headers=headers, - timeout=API_TIMEOUT, + timeout=config.API_TIMEOUT, ) except Exception as e: print(f" GraphQL request failed: {e}") @@ -203,7 +190,7 @@ class DirectAPISource: 'https://api.github.com/graphql', json={'query': query}, headers=headers, - timeout=API_TIMEOUT + timeout=config.API_TIMEOUT ) if not resp.ok: @@ -287,7 +274,7 @@ class DirectAPISource: 'https://api.github.com/graphql', json={'query': query, 'variables': {'username': username}}, headers=headers, - timeout=API_TIMEOUT + timeout=config.API_TIMEOUT ) if not resp.ok or 'data' not in resp.json(): @@ -322,7 +309,7 @@ class DirectAPISource: 'https://api.github.com/graphql', json={'query': year_query}, headers=headers, - timeout=API_TIMEOUT + timeout=config.API_TIMEOUT ) if year_resp.ok: @@ -371,7 +358,7 @@ class DirectAPISource: 'https://api.github.com/graphql', json={'query': query}, headers=headers, - timeout=API_TIMEOUT + timeout=config.API_TIMEOUT ) if resp.ok: @@ -401,7 +388,7 @@ class DirectAPISource: f"{self.base}/search/issues", headers=self.headers, params={"q": query, "per_page": 1}, - timeout=API_TIMEOUT + timeout=config.API_TIMEOUT ) if resp.ok: @@ -428,7 +415,7 @@ class DirectAPISource: f"{self.base}/repos/{repo_name}/contributors", headers=self.headers, params={"per_page": 100}, - timeout=API_TIMEOUT + timeout=config.API_TIMEOUT ) if resp.ok: @@ -508,7 +495,7 @@ class DirectAPISource: def fetch_avatar(self, avatar_url: str) -> str: """Fetch and encode avatar as base64.""" try: - resp = requests.get(avatar_url + "&s=64", timeout=API_TIMEOUT) + resp = requests.get(avatar_url + "&s=64", timeout=config.API_TIMEOUT) if resp.ok: return base64.b64encode(resp.content).decode("ascii") except Exception: @@ -627,7 +614,7 @@ def _fetch_collaborators_data( low = login.lower() return low in BOT_LOGINS or low.endswith("[bot]") or low.endswith("-bot") - since = (datetime.now() - timedelta(days=COLLABORATOR_LOOKBACK_DAYS)).strftime("%Y-%m-%d") + since = (datetime.now() - timedelta(days=config.COLLABORATOR_LOOKBACK_DAYS)).strftime("%Y-%m-%d") commit_repos = source.fetch_user_commit_repos(username, since) if not commit_repos: return [] @@ -636,15 +623,15 @@ def _fetch_collaborators_data( qualifying = [] for r in commit_repos: user_commits = r.get("user_commits", 0) - if user_commits < MEANINGFUL_MIN_COMMITS: + if user_commits < config.MEANINGFUL_MIN_COMMITS: continue - if r.get("is_fork") and user_commits < FORK_MIN_COMMITS: + if r.get("is_fork") and user_commits < config.FORK_MIN_COMMITS: continue qualifying.append(r) # Rank user's repos by their own commit count, scan top N qualifying.sort(key=lambda r: -r.get("user_commits", 0)) - qualifying = qualifying[:COLLABORATOR_TOP_REPOS] + qualifying = qualifying[:config.COLLABORATOR_TOP_REPOS] print(f" Scoring collaborators across {len(qualifying)} qualifying repos") # Step 3+4: fetch contributors and score @@ -652,17 +639,17 @@ def _fetch_collaborators_data( for r in qualifying: full_name = r["full_name"] user_commits = r["user_commits"] - boost = OWNER_BOOST if r["is_owner"] else 1.0 + boost = config.OWNER_BOOST if r["is_owner"] else 1.0 contributors = source.fetch_repo_contributors(full_name, min_commits=1) # Drop huge OSS projects - if len(contributors) >= COLLABORATOR_MAX_REPO_SIZE: + if len(contributors) >= config.COLLABORATOR_MAX_REPO_SIZE: print(f" skipping {full_name}: too many contributors ({len(contributors)})") continue # A "tight" repo: one the user owns with few contributors — hackathon # and side-project partners qualify from a single such repo. - is_tight_owned = r["is_owner"] and len(contributors) <= SMALL_OWNED_REPO_SIZE + is_tight_owned = r["is_owner"] and len(contributors) <= config.SMALL_OWNED_REPO_SIZE for c in contributors: login = c.get("login", "") @@ -705,8 +692,8 @@ def _fetch_collaborators_data( # or a partner in a tight user-owned project (hackathon/side-project). filtered = [ s for s in scored - if s["shared_repos"] >= MIN_SHARED_REPOS - or s["raw_score"] >= DEEP_COLLAB_THRESHOLD + if s["shared_repos"] >= config.MIN_SHARED_REPOS + or s["raw_score"] >= config.DEEP_COLLAB_THRESHOLD or s["tight_owned_partner"] ] diff --git a/fetcher/tests/__init__.py b/fetcher/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/fetcher/tests/test_api.py b/fetcher/tests/test_api.py new file mode 100644 index 0000000..c161116 --- /dev/null +++ b/fetcher/tests/test_api.py @@ -0,0 +1,73 @@ +import os +import tempfile +import pytest +import responses as resp_lib +from src import db as dbmod +from src import api as apimod + + +@pytest.fixture +def client(monkeypatch): + with tempfile.TemporaryDirectory() as d: + monkeypatch.setattr(dbmod, "DB_PATH", os.path.join(d, "t.db")) + monkeypatch.setattr(apimod.config, "INTERNAL_TOKEN", "secret") + monkeypatch.setattr(apimod.config, "GITHUB_PAT", "ghp_test") + dbmod.init_db() + app = apimod.app + app.config["TESTING"] = True + with app.test_client() as c: + yield c + + +def test_health_no_auth_required(client): + r = client.get("/health") + assert r.status_code == 200 + assert r.get_json()["service"] == "fetcher" + + +def test_endpoints_require_internal_token(client): + r = client.get("/data/alice") + assert r.status_code == 401 + + +@resp_lib.activate +def test_data_auto_fetches_on_miss(client, monkeypatch): + # fetch_commits: contributionCalendar/weeks + resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", + json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}}, status=200) + # fetch_commit_count (alltime) — first call: get createdAt + resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", + json={"data": {"user": {"createdAt": "2020-01-01T00:00:00Z"}}}, status=200) + # fetch_commit_count (alltime) — per-year contribution totals (2020–2026, 7 years) + for _ in range(7): + resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", + json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 10}}}}}, + status=200) + # fetch_commit_count (recent, last 6 months) + resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", + json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 5}}}}}, + status=200) + # fetch_user_commit_repos (for collaborators) + resp_lib.add(resp_lib.POST, "https://api.github.com/graphql", + json={"data": {"user": {"contributionsCollection": {"commitContributionsByRepository": []}}}}, + status=200) + # PR count search + resp_lib.add(resp_lib.GET, "https://api.github.com/search/issues", + json={"total_count": 0, "items": []}, status=200) + resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice", + json={"login": "alice", "public_repos": 1, "followers": 0, "avatar_url": "https://avatars.example/a"}, status=200) + # fetch_repos: two calls (owner + all) + resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/repos", json=[], status=200) + resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/repos", json=[], status=200) + resp_lib.add(resp_lib.GET, "https://api.github.com/users/alice/events", json=[], status=200) + + r = client.get("/data/alice", headers={"X-Internal-Token": "secret"}) + assert r.status_code == 200 + body = r.get_json() + assert body["payload_hash"] + assert body["data"]["user"]["login"] == "alice" + + +def test_force_fetch_requires_auth(client): + r = client.post("/fetch", json={"username": "alice"}) + assert r.status_code == 401 diff --git a/fetcher/tests/test_cron.py b/fetcher/tests/test_cron.py new file mode 100644 index 0000000..bde179e --- /dev/null +++ b/fetcher/tests/test_cron.py @@ -0,0 +1,35 @@ +import os +import tempfile +import pytest +from unittest.mock import patch +from src import db as dbmod +from src import cron as cronmod + + +@pytest.fixture +def tmp_db(monkeypatch): + with tempfile.TemporaryDirectory() as d: + monkeypatch.setattr(dbmod, "DB_PATH", os.path.join(d, "t.db")) + dbmod.init_db() + yield + + +def test_refresh_tick_calls_github_for_due_users(tmp_db): + dbmod.upsert_user("alice", {"user": {"login": "alice"}}) + # Backdate + with dbmod._connect() as c: + c.execute("UPDATE users SET fetched_at='2020-01-01T00:00:00Z', last_requested_at=? WHERE username='alice'", + (dbmod._now(),)) + with patch("src.cron.github.fetch_github_data", return_value={"user": {"login": "alice", "updated": True}}) as gh: + stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7) + assert gh.called + assert stats["refreshed"] == 1 + + +def test_tick_runs_gc_for_abandoned_trial_users(tmp_db): + dbmod.upsert_user("ghost", {"user": {"login": "ghost"}}) + with dbmod._connect() as c: + c.execute("UPDATE users SET last_requested_at='2020-01-01T00:00:00Z' WHERE username='ghost'") + stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7) + assert stats["gc_removed"] == 1 + assert dbmod.get_user("ghost") is None diff --git a/fetcher/tests/test_db.py b/fetcher/tests/test_db.py new file mode 100644 index 0000000..0368735 --- /dev/null +++ b/fetcher/tests/test_db.py @@ -0,0 +1,65 @@ +import os +import tempfile +import pytest +from src import db as dbmod + + +@pytest.fixture +def tmp_db(monkeypatch): + with tempfile.TemporaryDirectory() as d: + path = os.path.join(d, "t.db") + monkeypatch.setattr(dbmod, "DB_PATH", path) + dbmod.init_db() + yield path + + +def test_init_creates_schema_with_wal(tmp_db): + with dbmod._connect() as c: + mode = c.execute("PRAGMA journal_mode").fetchone()[0] + assert mode.lower() == "wal" + cols = [r[1] for r in c.execute("PRAGMA table_info(users)").fetchall()] + assert set(cols) == {"username", "data_json", "payload_hash", + "fetched_at", "last_requested_at"} + + +def test_upsert_and_get_round_trip(tmp_db): + dbmod.upsert_user("alice", {"user": {"login": "alice"}, "repos": []}) + row = dbmod.get_user("alice") + assert row["data"]["user"]["login"] == "alice" + assert row["payload_hash"] + assert row["fetched_at"] + + +def test_payload_hash_is_deterministic_and_changes_on_diff(): + h1 = dbmod.payload_hash({"a": 1, "b": 2}) + h2 = dbmod.payload_hash({"b": 2, "a": 1}) + h3 = dbmod.payload_hash({"a": 1, "b": 3}) + assert h1 == h2 + assert h1 != h3 + + +def test_get_updates_last_requested_at(tmp_db): + dbmod.upsert_user("alice", {"user": {"login": "alice"}}) + first = dbmod.get_user("alice")["last_requested_at"] + import time; time.sleep(1.1) + second = dbmod.get_user("alice")["last_requested_at"] + assert second > first + + +def test_delete_stale_removes_old_rows(tmp_db): + dbmod.upsert_user("ghost", {"user": {"login": "ghost"}}) + # Manually backdate last_requested_at + with dbmod._connect() as c: + c.execute("UPDATE users SET last_requested_at='2020-01-01T00:00:00Z' WHERE username='ghost'") + removed = dbmod.delete_stale(days=7) + assert removed == 1 + assert dbmod.get_user("ghost") is None + + +def test_users_due_for_refresh(tmp_db): + dbmod.upsert_user("alice", {"user": {"login": "alice"}}) + # Backdate fetched_at so alice is due + with dbmod._connect() as c: + c.execute("UPDATE users SET fetched_at='2020-01-01T00:00:00Z' WHERE username='alice'") + due = dbmod.users_due_for_refresh(hours=24, active_within_days=7) + assert "alice" in due diff --git a/fetcher/tests/test_github.py b/fetcher/tests/test_github.py new file mode 100644 index 0000000..e9b6494 --- /dev/null +++ b/fetcher/tests/test_github.py @@ -0,0 +1,88 @@ +import responses +import pytest +from src import github + + +@responses.activate +def test_fetch_user_data_returns_user_payload(): + # fetch_commits: contributionCalendar/weeks + responses.add( + responses.POST, "https://api.github.com/graphql", + json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"weeks": []}}}}}, + status=200, + ) + # fetch_commit_count (alltime) — first call: get createdAt + responses.add( + responses.POST, "https://api.github.com/graphql", + json={"data": {"user": {"createdAt": "2020-01-01T00:00:00Z"}}}, + status=200, + ) + # fetch_commit_count (alltime) — per-year contribution totals (2020–2026) + for _ in range(7): + responses.add( + responses.POST, "https://api.github.com/graphql", + json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 10}}}}}, + status=200, + ) + # fetch_commit_count (recent, last 6 months) + responses.add( + responses.POST, "https://api.github.com/graphql", + json={"data": {"user": {"contributionsCollection": {"contributionCalendar": {"totalContributions": 5}}}}}, + status=200, + ) + # fetch_user_commit_repos (for collaborators) + responses.add( + responses.POST, "https://api.github.com/graphql", + json={"data": {"user": {"contributionsCollection": {"commitContributionsByRepository": []}}}}, + status=200, + ) + # PR count search + responses.add( + responses.GET, "https://api.github.com/search/issues", + json={"total_count": 0, "items": []}, + status=200, + ) + responses.add( + responses.GET, "https://api.github.com/users/alice", + json={"login": "alice", "public_repos": 3, "followers": 5, "avatar_url": "https://avatars.example/1"}, + status=200, + ) + # fetch_repos: two calls (owner + all) + responses.add( + responses.GET, "https://api.github.com/users/alice/repos", + json=[], status=200, + ) + responses.add( + responses.GET, "https://api.github.com/users/alice/repos", + json=[], status=200, + ) + responses.add( + responses.GET, "https://api.github.com/users/alice/events", + json=[], status=200, + ) + data = github.fetch_github_data("alice", token="t") + assert data["user"]["login"] == "alice" + assert "repos" in data + assert "events" in data + + +@responses.activate +def test_fetch_handles_404(): + responses.add( + responses.GET, "https://api.github.com/users/nope", + json={"message": "Not Found"}, status=404, + ) + responses.add( + responses.POST, "https://api.github.com/graphql", + json={"data": {"user": None}}, status=200, + ) + responses.add( + responses.GET, "https://api.github.com/users/nope/repos", + json={"message": "Not Found"}, status=404, + ) + responses.add( + responses.GET, "https://api.github.com/users/nope/events", + json={"message": "Not Found"}, status=404, + ) + data = github.fetch_github_data("nope", token="t") + assert data["user"].get("message") == "Not Found" or data["user"] is None diff --git a/generator/Dockerfile b/generator/Dockerfile new file mode 100644 index 0000000..aa2532d --- /dev/null +++ b/generator/Dockerfile @@ -0,0 +1,27 @@ +# --- stage 1: build the React SPA --- +FROM node:20-alpine AS frontend-build +WORKDIR /app/frontend +COPY frontend/package.json frontend/package-lock.json ./ +RUN npm ci +COPY frontend/ ./ +ARG VITE_GENERATOR_URL="" +ARG VITE_EDGE_URL="" +ENV VITE_GENERATOR_URL=$VITE_GENERATOR_URL +ENV VITE_EDGE_URL=$VITE_EDGE_URL +RUN npm run build + +# --- stage 2: python runtime --- +FROM python:3.11-slim AS runtime +WORKDIR /app +COPY requirements.txt ./ +RUN pip install --no-cache-dir -r requirements.txt + +COPY src ./src +RUN mkdir -p /app/src/static /app/data +COPY --from=frontend-build /app/frontend/dist/ /app/src/static/ + +EXPOSE 5002 +ENV GENERATOR_SETTINGS_DB_PATH=/app/data/settings.db +ENV GENERATOR_WIDGETS_DB_PATH=/app/data/widgets.db + +CMD ["gunicorn", "-b", "0.0.0.0:5002", "-w", "2", "src.api:app"] diff --git a/generator/README.md b/generator/README.md new file mode 100644 index 0000000..8eb6951 --- /dev/null +++ b/generator/README.md @@ -0,0 +1,56 @@ +# Generator Service + +Serves precomputed SVGs to the public internet. Holds user settings and +the widgets cache. Runs a build worker + cron in the background. Also +serves the React SPA (frontend sources live under `frontend/`). + +## Run locally (3 processes) + + cd generator + pip install -r requirements.txt + + # API + FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.api + # Build worker + FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.worker + # Poll cron + FETCHER_URL=http://localhost:5001 FETCHER_INTERNAL_TOKEN=dev python -m src.cron + +## Frontend (dev) + + cd generator/frontend && npm install && npm run dev + # Vite dev server proxies /api to the Flask app. + +## Test + + cd generator && pytest + +## Docker + +Multi-stage (builds the frontend with node, serves everything from Python): + + docker build -t ghstats-generator . + docker run --rm -e FETCHER_URL=http://fetcher:5001 -e FETCHER_INTERNAL_TOKEN=dev \ + -p 5002:5002 -v $(pwd)/data:/app/data ghstats-generator + # Worker: override CMD to ["python","-m","src.worker"] + # Cron: override CMD to ["python","-m","src.cron"] + +## Endpoints + +All API endpoints are under `/api/`. The root and `/assets/*` serve the SPA. + +| Method | Path | Auth | Description | +|---|---|---|---| +| GET | /api/health | none | health | +| GET | /api/ | none | composite SVG; auto-enrolls unknown users | +| GET | /api//.svg | none | individual widget SVG | +| POST | /api/enroll | none | explicit enroll (body: {username}) | +| GET | /api//settings | stub | current settings | +| PATCH | /api//settings | stub | update settings (enqueues rebuild) | +| POST | /api//refresh | stub | one-shot re-fetch + rebuild | + +Responses carry `X-Widget-Status: ready | building | rate_limited | not_found`. + +## Env + +See `src/config.py`. diff --git a/generator/data/.gitkeep b/generator/data/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/generator/frontend/.env.example b/generator/frontend/.env.example new file mode 100644 index 0000000..948400e --- /dev/null +++ b/generator/frontend/.env.example @@ -0,0 +1,2 @@ +VITE_GENERATOR_URL=http://localhost:5002 +VITE_EDGE_URL=http://localhost:5003 diff --git a/generator/frontend/.gitignore b/generator/frontend/.gitignore new file mode 100644 index 0000000..a547bf3 --- /dev/null +++ b/generator/frontend/.gitignore @@ -0,0 +1,24 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/generator/frontend/README.md b/generator/frontend/README.md new file mode 100644 index 0000000..8aa4f52 --- /dev/null +++ b/generator/frontend/README.md @@ -0,0 +1,17 @@ +# Frontend (Vite + React) + +Part of the generator service. Sources live here; the production build +is served as static files by the generator's Flask app (at `/`) and +produced by the generator's Dockerfile. + +## Dev + + npm install + VITE_GENERATOR_URL=http://localhost:5002 VITE_EDGE_URL=http://localhost:5003 npm run dev + +Vite proxies `/api/*` to the Flask app at :5002. + +## Build + + npm run build + # produces dist/ which is copied into generator/src/static/ by the Docker build diff --git a/generator/frontend/eslint.config.js b/generator/frontend/eslint.config.js new file mode 100644 index 0000000..5e6b472 --- /dev/null +++ b/generator/frontend/eslint.config.js @@ -0,0 +1,23 @@ +import js from '@eslint/js' +import globals from 'globals' +import reactHooks from 'eslint-plugin-react-hooks' +import reactRefresh from 'eslint-plugin-react-refresh' +import tseslint from 'typescript-eslint' +import { defineConfig, globalIgnores } from 'eslint/config' + +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + js.configs.recommended, + tseslint.configs.recommended, + reactHooks.configs.flat.recommended, + reactRefresh.configs.vite, + ], + languageOptions: { + ecmaVersion: 2020, + globals: globals.browser, + }, + }, +]) diff --git a/generator/frontend/index.html b/generator/frontend/index.html new file mode 100644 index 0000000..0fca6f0 --- /dev/null +++ b/generator/frontend/index.html @@ -0,0 +1,13 @@ + + + + + + + frontend + + +

+ + + diff --git a/generator/frontend/package-lock.json b/generator/frontend/package-lock.json new file mode 100644 index 0000000..d79fbb2 --- /dev/null +++ b/generator/frontend/package-lock.json @@ -0,0 +1,3333 @@ +{ + "name": "frontend", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "frontend", + "version": "0.0.0", + "dependencies": { + "dompurify": "^3.4.0", + "react": "^19.2.4", + "react-dom": "^19.2.4" + }, + "devDependencies": { + "@eslint/js": "^9.39.4", + "@tailwindcss/vite": "^4.2.2", + "@types/dompurify": "^3.0.5", + "@types/node": "^24.12.2", + "@types/react": "^19.2.14", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^6.0.1", + "eslint": "^9.39.4", + "eslint-plugin-react-hooks": "^7.0.1", + "eslint-plugin-react-refresh": "^0.5.2", + "globals": "^17.4.0", + "tailwindcss": "^4.2.2", + "typescript": "~6.0.2", + "typescript-eslint": "^8.58.0", + "vite": "^8.0.4" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", + "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.28.5", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.0.tgz", + "integrity": "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz", + "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.0", + "@babel/generator": "^7.29.0", + "@babel/helper-compilation-targets": "^7.28.6", + "@babel/helper-module-transforms": "^7.28.6", + "@babel/helpers": "^7.28.6", + "@babel/parser": "^7.29.0", + "@babel/template": "^7.28.6", + "@babel/traverse": "^7.29.0", + "@babel/types": "^7.29.0", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.1", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz", + "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.0", + "@babel/types": "^7.29.0", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.28.6.tgz", + "integrity": "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.28.6", + "@babel/helper-validator-option": "^7.27.1", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz", + "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.28.6.tgz", + "integrity": "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.28.6", + "@babel/types": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.6.tgz", + "integrity": "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.28.6", + "@babel/helper-validator-identifier": "^7.28.5", + "@babel/traverse": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz", + "integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.2.tgz", + "integrity": "sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.28.6", + "@babel/types": "^7.29.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz", + "integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.0" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/template": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz", + "integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.28.6", + "@babel/parser": "^7.28.6", + "@babel/types": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.0.tgz", + "integrity": "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.0", + "@babel/generator": "^7.29.0", + "@babel/helper-globals": "^7.28.0", + "@babel/parser": "^7.29.0", + "@babel/template": "^7.28.6", + "@babel/types": "^7.29.0", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz", + "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@emnapi/core": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.2.tgz", + "integrity": "sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.1", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.2.tgz", + "integrity": "sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz", + "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.9.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz", + "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.21.2", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.2.tgz", + "integrity": "sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^2.1.7", + "debug": "^4.3.1", + "minimatch": "^3.1.5" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz", + "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/core": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz", + "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.5", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.5.tgz", + "integrity": "sha512-4IlJx0X0qftVsN5E+/vGujTRIFtwuLbNsVUe7TO6zYPDR1O6nFwvwhIKEKSrl6dZchmYBITazxKoUYOjdtjlRg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.14.0", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.1", + "minimatch": "^3.1.5", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@eslint/js": { + "version": "9.39.4", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.4.tgz", + "integrity": "sha512-nE7DEIchvtiFTwBw4Lfbu59PG+kCofhjsKaCWzxTpt4lfRjRMqG6uMBzKXuEcyXhOHoUp9riAm7/aWYGhXZ9cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + } + }, + "node_modules/@eslint/object-schema": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz", + "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz", + "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0", + "levn": "^0.4.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", + "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.7", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.7.tgz", + "integrity": "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.1", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.4.tgz", + "integrity": "sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.1" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.124.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.124.0.tgz", + "integrity": "sha512-VBFWMTBvHxS11Z5Lvlr3IWgrwhMTXV+Md+EQF0Xf60+wAdsGFTBx7X7K/hP4pi8N7dcm1RvcHwDxZ16Qx8keUg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/Boshen" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.15.tgz", + "integrity": "sha512-YYe6aWruPZDtHNpwu7+qAHEMbQ/yRl6atqb/AhznLTnD3UY99Q1jE7ihLSahNWkF4EqRPVC4SiR4O0UkLK02tA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-rc.15.tgz", + "integrity": "sha512-oArR/ig8wNTPYsXL+Mzhs0oxhxfuHRfG7Ikw7jXsw8mYOtk71W0OkF2VEVh699pdmzjPQsTjlD1JIOoHkLP1Fg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-rc.15.tgz", + "integrity": "sha512-YzeVqOqjPYvUbJSWJ4EDL8ahbmsIXQpgL3JVipmN+MX0XnXMeWomLN3Fb+nwCmP/jfyqte5I3XRSm7OfQrbyxw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-rc.15.tgz", + "integrity": "sha512-9Erhx956jeQ0nNTyif1+QWAXDRD38ZNjr//bSHrt6wDwB+QkAfl2q6Mn1k6OBPerznjRmbM10lgRb1Pli4xZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-rc.15.tgz", + "integrity": "sha512-cVwk0w8QbZJGTnP/AHQBs5yNwmpgGYStL88t4UIaqcvYJWBfS0s3oqVLZPwsPU6M0zlW4GqjP0Zq5MnAGwFeGA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-rc.15.tgz", + "integrity": "sha512-eBZ/u8iAK9SoHGanqe/jrPnY0JvBN6iXbVOsbO38mbz+ZJsaobExAm1Iu+rxa4S1l2FjG0qEZn4Rc6X8n+9M+w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-rc.15.tgz", + "integrity": "sha512-ZvRYMGrAklV9PEkgt4LQM6MjQX2P58HPAuecwYObY2DhS2t35R0I810bKi0wmaYORt6m/2Sm+Z+nFgb0WhXNcQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.0-rc.15.tgz", + "integrity": "sha512-VDpgGBzgfg5hLg+uBpCLoFG5kVvEyafmfxGUV0UHLcL5irxAK7PKNeC2MwClgk6ZAiNhmo9FLhRYgvMmedLtnQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.0-rc.15.tgz", + "integrity": "sha512-y1uXY3qQWCzcPgRJATPSOUP4tCemh4uBdY7e3EZbVwCJTY3gLJWnQABgeUetvED+bt1FQ01OeZwvhLS2bpNrAQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.15.tgz", + "integrity": "sha512-023bTPBod7J3Y/4fzAN6QtpkSABR0rigtrwaP+qSEabUh5zf6ELr9Nc7GujaROuPY3uwdSIXWrvhn1KxOvurWA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.15.tgz", + "integrity": "sha512-witB2O0/hU4CgfOOKUoeFgQ4GktPi1eEbAhaLAIpgD6+ZnhcPkUtPsoKKHRzmOoWPZue46IThdSgdo4XneOLYw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.0-rc.15.tgz", + "integrity": "sha512-UCL68NJ0Ud5zRipXZE9dF5PmirzJE4E4BCIOOssEnM7wLDsxjc6Qb0sGDxTNRTP53I6MZpygyCpY8Aa8sPfKPg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-rc.15.tgz", + "integrity": "sha512-ApLruZq/ig+nhaE7OJm4lDjayUnOHVUa77zGeqnqZ9pn0ovdVbbNPerVibLXDmWeUZXjIYIT8V3xkT58Rm9u5Q==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "1.9.2", + "@emnapi/runtime": "1.9.2", + "@napi-rs/wasm-runtime": "^1.1.3" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.15.tgz", + "integrity": "sha512-KmoUoU7HnN+Si5YWJigfTws1jz1bKBYDQKdbLspz0UaqjjFkddHsqorgiW1mxcAj88lYUE6NC/zJNwT+SloqtA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.15.tgz", + "integrity": "sha512-3P2A8L+x75qavWLe/Dll3EYBJLQmtkJN8rfh+U/eR3MqMgL/h98PhYI+JFfXuDPgPeCB7iZAKiqii5vqOvnA0g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-rc.7", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.7.tgz", + "integrity": "sha512-qujRfC8sFVInYSPPMLQByRh7zhwkGFS4+tyMQ83srV1qrxL4g8E2tyxVVyxd0+8QeBM1mIk9KbWxkegRr76XzA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tailwindcss/node": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.2.2.tgz", + "integrity": "sha512-pXS+wJ2gZpVXqFaUEjojq7jzMpTGf8rU6ipJz5ovJV6PUGmlJ+jvIwGrzdHdQ80Sg+wmQxUFuoW1UAAwHNEdFA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "^5.19.0", + "jiti": "^2.6.1", + "lightningcss": "1.32.0", + "magic-string": "^0.30.21", + "source-map-js": "^1.2.1", + "tailwindcss": "4.2.2" + } + }, + "node_modules/@tailwindcss/oxide": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.2.2.tgz", + "integrity": "sha512-qEUA07+E5kehxYp9BVMpq9E8vnJuBHfJEC0vPC5e7iL/hw7HR61aDKoVoKzrG+QKp56vhNZe4qwkRmMC0zDLvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.2.2", + "@tailwindcss/oxide-darwin-arm64": "4.2.2", + "@tailwindcss/oxide-darwin-x64": "4.2.2", + "@tailwindcss/oxide-freebsd-x64": "4.2.2", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.2.2", + "@tailwindcss/oxide-linux-arm64-gnu": "4.2.2", + "@tailwindcss/oxide-linux-arm64-musl": "4.2.2", + "@tailwindcss/oxide-linux-x64-gnu": "4.2.2", + "@tailwindcss/oxide-linux-x64-musl": "4.2.2", + "@tailwindcss/oxide-wasm32-wasi": "4.2.2", + "@tailwindcss/oxide-win32-arm64-msvc": "4.2.2", + "@tailwindcss/oxide-win32-x64-msvc": "4.2.2" + } + }, + "node_modules/@tailwindcss/oxide-android-arm64": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.2.2.tgz", + "integrity": "sha512-dXGR1n+P3B6748jZO/SvHZq7qBOqqzQ+yFrXpoOWWALWndF9MoSKAT3Q0fYgAzYzGhxNYOoysRvYlpixRBBoDg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-arm64": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.2.2.tgz", + "integrity": "sha512-iq9Qjr6knfMpZHj55/37ouZeykwbDqF21gPFtfnhCCKGDcPI/21FKC9XdMO/XyBM7qKORx6UIhGgg6jLl7BZlg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-x64": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.2.2.tgz", + "integrity": "sha512-BlR+2c3nzc8f2G639LpL89YY4bdcIdUmiOOkv2GQv4/4M0vJlpXEa0JXNHhCHU7VWOKWT/CjqHdTP8aUuDJkuw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-freebsd-x64": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.2.2.tgz", + "integrity": "sha512-YUqUgrGMSu2CDO82hzlQ5qSb5xmx3RUrke/QgnoEx7KvmRJHQuZHZmZTLSuuHwFf0DJPybFMXMYf+WJdxHy/nQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.2.2.tgz", + "integrity": "sha512-FPdhvsW6g06T9BWT0qTwiVZYE2WIFo2dY5aCSpjG/S/u1tby+wXoslXS0kl3/KXnULlLr1E3NPRRw0g7t2kgaQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.2.2.tgz", + "integrity": "sha512-4og1V+ftEPXGttOO7eCmW7VICmzzJWgMx+QXAJRAhjrSjumCwWqMfkDrNu1LXEQzNAwz28NCUpucgQPrR4S2yw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-musl": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.2.2.tgz", + "integrity": "sha512-oCfG/mS+/+XRlwNjnsNLVwnMWYH7tn/kYPsNPh+JSOMlnt93mYNCKHYzylRhI51X+TbR+ufNhhKKzm6QkqX8ag==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.2.2.tgz", + "integrity": "sha512-rTAGAkDgqbXHNp/xW0iugLVmX62wOp2PoE39BTCGKjv3Iocf6AFbRP/wZT/kuCxC9QBh9Pu8XPkv/zCZB2mcMg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-musl": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.2.2.tgz", + "integrity": "sha512-XW3t3qwbIwiSyRCggeO2zxe3KWaEbM0/kW9e8+0XpBgyKU4ATYzcVSMKteZJ1iukJ3HgHBjbg9P5YPRCVUxlnQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.2.2.tgz", + "integrity": "sha512-eKSztKsmEsn1O5lJ4ZAfyn41NfG7vzCg496YiGtMDV86jz1q/irhms5O0VrY6ZwTUkFy/EKG3RfWgxSI3VbZ8Q==", + "bundleDependencies": [ + "@napi-rs/wasm-runtime", + "@emnapi/core", + "@emnapi/runtime", + "@tybys/wasm-util", + "@emnapi/wasi-threads", + "tslib" + ], + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.8.1", + "@emnapi/runtime": "^1.8.1", + "@emnapi/wasi-threads": "^1.1.0", + "@napi-rs/wasm-runtime": "^1.1.1", + "@tybys/wasm-util": "^0.10.1", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.2.2.tgz", + "integrity": "sha512-qPmaQM4iKu5mxpsrWZMOZRgZv1tOZpUm+zdhhQP0VhJfyGGO3aUKdbh3gDZc/dPLQwW4eSqWGrrcWNBZWUWaXQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.2.2.tgz", + "integrity": "sha512-1T/37VvI7WyH66b+vqHj/cLwnCxt7Qt3WFu5Q8hk65aOvlwAhs7rAp1VkulBJw/N4tMirXjVnylTR72uI0HGcA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/vite": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/vite/-/vite-4.2.2.tgz", + "integrity": "sha512-mEiF5HO1QqCLXoNEfXVA1Tzo+cYsrqV7w9Juj2wdUFyW07JRenqMG225MvPwr3ZD9N1bFQj46X7r33iHxLUW0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@tailwindcss/node": "4.2.2", + "@tailwindcss/oxide": "4.2.2", + "tailwindcss": "4.2.2" + }, + "peerDependencies": { + "vite": "^5.2.0 || ^6 || ^7 || ^8" + } + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz", + "integrity": "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/dompurify": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@types/dompurify/-/dompurify-3.0.5.tgz", + "integrity": "sha512-1Wg0g3BtQF7sSb27fJQAKck1HECM6zV1EB66j8JH9i3LCjYabJa0FSdiSgsD5K/RbrsR0SiraKacLB+T8ZVYAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/trusted-types": "*" + } + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.12.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.2.tgz", + "integrity": "sha512-A1sre26ke7HDIuY/M23nd9gfB+nrmhtYyMINbjI1zHJxYteKR6qSMX56FsmjMcDb3SMcjJg5BiRRgOCC/yBD0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@types/react": { + "version": "19.2.14", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz", + "integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.2.3", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz", + "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.2.0" + } + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.58.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.58.2.tgz", + "integrity": "sha512-aC2qc5thQahutKjP+cl8cgN9DWe3ZUqVko30CMSZHnFEHyhOYoZSzkGtAI2mcwZ38xeImDucI4dnqsHiOYuuCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.12.2", + "@typescript-eslint/scope-manager": "8.58.2", + "@typescript-eslint/type-utils": "8.58.2", + "@typescript-eslint/utils": "8.58.2", + "@typescript-eslint/visitor-keys": "8.58.2", + "ignore": "^7.0.5", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.58.2", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", + "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.58.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.58.2.tgz", + "integrity": "sha512-/Zb/xaIDfxeJnvishjGdcR4jmr7S+bda8PKNhRGdljDM+elXhlvN0FyPSsMnLmJUrVG9aPO6dof80wjMawsASg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.58.2", + "@typescript-eslint/types": "8.58.2", + "@typescript-eslint/typescript-estree": "8.58.2", + "@typescript-eslint/visitor-keys": "8.58.2", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.58.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.58.2.tgz", + "integrity": "sha512-Cq6UfpZZk15+r87BkIh5rDpi38W4b+Sjnb8wQCPPDDweS/LRCFjCyViEbzHk5Ck3f2QDfgmlxqSa7S7clDtlfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.58.2", + "@typescript-eslint/types": "^8.58.2", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.58.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.58.2.tgz", + "integrity": "sha512-SgmyvDPexWETQek+qzZnrG6844IaO02UVyOLhI4wpo82dpZJY9+6YZCKAMFzXb7qhx37mFK1QcPQ18tud+vo6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.58.2", + "@typescript-eslint/visitor-keys": "8.58.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.58.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.58.2.tgz", + "integrity": "sha512-3SR+RukipDvkkKp/d0jP0dyzuls3DbGmwDpVEc5wqk5f38KFThakqAAO0XMirWAE+kT00oTauTbzMFGPoAzB0A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.58.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.58.2.tgz", + "integrity": "sha512-Z7EloNR/B389FvabdGeTo2XMs4W9TjtPiO9DAsmT0yom0bwlPyRjkJ1uCdW1DvrrrYP50AJZ9Xc3sByZA9+dcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.58.2", + "@typescript-eslint/typescript-estree": "8.58.2", + "@typescript-eslint/utils": "8.58.2", + "debug": "^4.4.3", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.58.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.58.2.tgz", + "integrity": "sha512-9TukXyATBQf/Jq9AMQXfvurk+G5R2MwfqQGDR2GzGz28HvY/lXNKGhkY+6IOubwcquikWk5cjlgPvD2uAA7htQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.58.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.58.2.tgz", + "integrity": "sha512-ELGuoofuhhoCvNbQjFFiobFcGgcDCEm0ThWdmO4Z0UzLqPXS3KFvnEZ+SHewwOYHjM09tkzOWXNTv9u6Gqtyuw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.58.2", + "@typescript-eslint/tsconfig-utils": "8.58.2", + "@typescript-eslint/types": "8.58.2", + "@typescript-eslint/visitor-keys": "8.58.2", + "debug": "^4.4.3", + "minimatch": "^10.2.2", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz", + "integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { + "version": "10.2.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", + "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.5" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.58.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.58.2.tgz", + "integrity": "sha512-QZfjHNEzPY8+l0+fIXMvuQ2sJlplB4zgDZvA+NmvZsZv3EQwOcc1DuIU1VJUTWZ/RKouBMhDyNaBMx4sWvrzRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/scope-manager": "8.58.2", + "@typescript-eslint/types": "8.58.2", + "@typescript-eslint/typescript-estree": "8.58.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.58.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.58.2.tgz", + "integrity": "sha512-f1WO2Lx8a9t8DARmcWAUPJbu0G20bJlj8L4z72K00TMeJAoyLr/tHhI/pzYBLrR4dXWkcxO1cWYZEOX8DKHTqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.58.2", + "eslint-visitor-keys": "^5.0.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.0.1.tgz", + "integrity": "sha512-l9X/E3cDb+xY3SWzlG1MOGt2usfEHGMNIaegaUGFsLkb3RCn/k8/TOXBcab+OndDI4TBtktT8/9BwwW8Vi9KUQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "1.0.0-rc.7" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", + "babel-plugin-react-compiler": "^1.0.0", + "vite": "^8.0.0" + }, + "peerDependenciesMeta": { + "@rolldown/plugin-babel": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + } + } + }, + "node_modules/acorn": { + "version": "8.16.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", + "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", + "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/baseline-browser-mapping": { + "version": "2.10.19", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.19.tgz", + "integrity": "sha512-qCkNLi2sfBOn8XhZQ0FXsT1Ki/Yo5P90hrkRamVFRS7/KV9hpfA4HkoWNU152+8w0zPjnxo5psx5NL3PSGgv5g==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.14", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.14.tgz", + "integrity": "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/browserslist": { + "version": "4.28.2", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.2.tgz", + "integrity": "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.10.12", + "caniuse-lite": "^1.0.30001782", + "electron-to-chromium": "^1.5.328", + "node-releases": "^2.0.36", + "update-browserslist-db": "^1.2.3" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001788", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001788.tgz", + "integrity": "sha512-6q8HFp+lOQtcf7wBK+uEenxymVWkGKkjFpCvw5W25cmMwEDU45p1xQFBQv8JDlMMry7eNxyBaR+qxgmTUZkIRQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/dompurify": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.0.tgz", + "integrity": "sha512-nolgK9JcaUXMSmW+j1yaSvaEaoXYHwWyGJlkoCTghc97KgGDDSnpoU/PlEnw63Ah+TGKFOyY+X5LnxaWbCSfXg==", + "license": "(MPL-2.0 OR Apache-2.0)", + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.339", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.339.tgz", + "integrity": "sha512-Is+0BBHJ4NrdpAYiperrmp53pLywG/yV/6lIMTAnhxvzj/Cmn5Q/ogSHC6AKe7X+8kPLxxFk0cs5oc/3j/fxIg==", + "dev": true, + "license": "ISC" + }, + "node_modules/enhanced-resolve": { + "version": "5.20.1", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.20.1.tgz", + "integrity": "sha512-Qohcme7V1inbAfvjItgw0EaxVX5q2rdVEZHRBrEQdRZTssLDGsL8Lwrznl8oQ/6kuTJONLaDcGjkNP247XEhcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.0" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "9.39.4", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.4.tgz", + "integrity": "sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.21.2", + "@eslint/config-helpers": "^0.4.2", + "@eslint/core": "^0.17.0", + "@eslint/eslintrc": "^3.3.5", + "@eslint/js": "9.39.4", + "@eslint/plugin-kit": "^0.4.1", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.14.0", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.5", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-plugin-react-hooks": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.0.1.tgz", + "integrity": "sha512-O0d0m04evaNzEPoSW+59Mezf8Qt0InfgGIBJnpC0h3NH/WjUAR7BIKUfysC6todmtiZ/A0oUVS8Gce0WhBrHsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.24.4", + "@babel/parser": "^7.24.4", + "hermes-parser": "^0.25.1", + "zod": "^3.25.0 || ^4.0.0", + "zod-validation-error": "^3.5.0 || ^4.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0" + } + }, + "node_modules/eslint-plugin-react-refresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-refresh/-/eslint-plugin-react-refresh-0.5.2.tgz", + "integrity": "sha512-hmgTH57GfzoTFjVN0yBwTggnsVUF2tcqi7RJZHqi9lIezSs4eFyAMktA68YD4r5kNw1mxyY4dmkyoFDb3FIqrA==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "eslint": "^9 || ^10" + } + }, + "node_modules/eslint-scope": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz", + "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", + "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.15.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/file-entry-cache": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^4.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/flatted": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz", + "integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==", + "dev": true, + "license": "ISC" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/globals": { + "version": "17.5.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-17.5.0.tgz", + "integrity": "sha512-qoV+HK2yFl/366t2/Cb3+xxPUo5BuMynomoDmiaZBIdbs+0pYbjfZU+twLhGKp4uCZ/+NbtpVepH5bGCxRyy2g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/hermes-estree": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz", + "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==", + "dev": true, + "license": "MIT" + }, + "node_modules/hermes-parser": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz", + "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hermes-estree": "0.25.1" + } + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/jiti": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.1.tgz", + "integrity": "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/lightningcss": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", + "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.32.0", + "lightningcss-darwin-arm64": "1.32.0", + "lightningcss-darwin-x64": "1.32.0", + "lightningcss-freebsd-x64": "1.32.0", + "lightningcss-linux-arm-gnueabihf": "1.32.0", + "lightningcss-linux-arm64-gnu": "1.32.0", + "lightningcss-linux-arm64-musl": "1.32.0", + "lightningcss-linux-x64-gnu": "1.32.0", + "lightningcss-linux-x64-musl": "1.32.0", + "lightningcss-win32-arm64-msvc": "1.32.0", + "lightningcss-win32-x64-msvc": "1.32.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", + "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", + "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", + "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", + "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", + "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", + "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", + "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", + "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", + "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", + "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", + "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-releases": { + "version": "2.0.37", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.37.tgz", + "integrity": "sha512-1h5gKZCF+pO/o3Iqt5Jp7wc9rH3eJJ0+nh/CIoiRwjRxde/hAHyLPXYN4V3CqKAbiZPSeJFSWHmJsbkicta0Eg==", + "dev": true, + "license": "MIT" + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.10", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.10.tgz", + "integrity": "sha512-pMMHxBOZKFU6HgAZ4eyGnwXF/EvPGGqUr0MnZ5+99485wwW41kW91A4LOGxSHhgugZmSChL5AlElNdwlNgcnLQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/react": { + "version": "19.2.5", + "resolved": "https://registry.npmjs.org/react/-/react-19.2.5.tgz", + "integrity": "sha512-llUJLzz1zTUBrskt2pwZgLq59AemifIftw4aB7JxOqf1HY2FDaGDxgwpAPVzHU1kdWabH7FauP4i1oEeer2WCA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.2.5", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.5.tgz", + "integrity": "sha512-J5bAZz+DXMMwW/wV3xzKke59Af6CHY7G4uYLN1OvBcKEsWOs4pQExj86BBKamxl/Ik5bx9whOrvBlSDfWzgSag==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.27.0" + }, + "peerDependencies": { + "react": "^19.2.5" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/rolldown": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.15.tgz", + "integrity": "sha512-Ff31guA5zT6WjnGp0SXw76X6hzGRk/OQq2hE+1lcDe+lJdHSgnSX6nK3erbONHyCbpSj9a9E+uX/OvytZoWp2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.124.0", + "@rolldown/pluginutils": "1.0.0-rc.15" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm64": "1.0.0-rc.15", + "@rolldown/binding-darwin-arm64": "1.0.0-rc.15", + "@rolldown/binding-darwin-x64": "1.0.0-rc.15", + "@rolldown/binding-freebsd-x64": "1.0.0-rc.15", + "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.15", + "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.15", + "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.15", + "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.15", + "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.15", + "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.15", + "@rolldown/binding-linux-x64-musl": "1.0.0-rc.15", + "@rolldown/binding-openharmony-arm64": "1.0.0-rc.15", + "@rolldown/binding-wasm32-wasi": "1.0.0-rc.15", + "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.15", + "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.15" + } + }, + "node_modules/rolldown/node_modules/@rolldown/pluginutils": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.15.tgz", + "integrity": "sha512-UromN0peaE53IaBRe9W7CjrZgXl90fqGpK+mIZbA3qSTeYqg3pqpROBdIPvOG3F5ereDHNwoHBI2e50n1BDr1g==", + "dev": true, + "license": "MIT" + }, + "node_modules/scheduler": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", + "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/tailwindcss": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.2.2.tgz", + "integrity": "sha512-KWBIxs1Xb6NoLdMVqhbhgwZf2PGBpPEiwOqgI4pFIYbNTfBXiKYyWoTsXgBQ9WFg/OlhnvHaY+AEpW7wSmFo2Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/tapable": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.2.tgz", + "integrity": "sha512-1MOpMXuhGzGL5TTCZFItxCc0AARf1EZFQkGqMm7ERKj8+Hgr5oLvJOVFcC+lRmR8hCe2S3jC4T5D7Vg/d7/fhA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.16", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz", + "integrity": "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/ts-api-utils": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", + "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, + "license": "0BSD", + "optional": true + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/typescript": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.2.tgz", + "integrity": "sha512-bGdAIrZ0wiGDo5l8c++HWtbaNCWTS4UTv7RaTH/ThVIgjkveJt83m74bBHMJkuCbslY8ixgLBVZJIOiQlQTjfQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/typescript-eslint": { + "version": "8.58.2", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.58.2.tgz", + "integrity": "sha512-V8iSng9mRbdZjl54VJ9NKr6ZB+dW0J3TzRXRGcSbLIej9jV86ZRtlYeTKDR/QLxXykocJ5icNzbsl2+5TzIvcQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/eslint-plugin": "8.58.2", + "@typescript-eslint/parser": "8.58.2", + "@typescript-eslint/typescript-estree": "8.58.2", + "@typescript-eslint/utils": "8.58.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "dev": true, + "license": "MIT" + }, + "node_modules/update-browserslist-db": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/vite": { + "version": "8.0.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.8.tgz", + "integrity": "sha512-dbU7/iLVa8KZALJyLOBOQ88nOXtNG8vxKuOT4I2mD+Ya70KPceF4IAmDsmU0h1Qsn5bPrvsY9HJstCRh3hG6Uw==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.32.0", + "picomatch": "^4.0.4", + "postcss": "^8.5.8", + "rolldown": "1.0.0-rc.15", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.1.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", + "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-validation-error": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/zod-validation-error/-/zod-validation-error-4.0.2.tgz", + "integrity": "sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + } + } + } +} diff --git a/generator/frontend/package.json b/generator/frontend/package.json new file mode 100644 index 0000000..055fb3d --- /dev/null +++ b/generator/frontend/package.json @@ -0,0 +1,34 @@ +{ + "name": "frontend", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -b && vite build", + "lint": "eslint .", + "preview": "vite preview" + }, + "dependencies": { + "dompurify": "^3.4.0", + "react": "^19.2.4", + "react-dom": "^19.2.4" + }, + "devDependencies": { + "@eslint/js": "^9.39.4", + "@tailwindcss/vite": "^4.2.2", + "@types/dompurify": "^3.0.5", + "@types/node": "^24.12.2", + "@types/react": "^19.2.14", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^6.0.1", + "eslint": "^9.39.4", + "eslint-plugin-react-hooks": "^7.0.1", + "eslint-plugin-react-refresh": "^0.5.2", + "globals": "^17.4.0", + "tailwindcss": "^4.2.2", + "typescript": "~6.0.2", + "typescript-eslint": "^8.58.0", + "vite": "^8.0.4" + } +} diff --git a/generator/frontend/public/favicon.svg b/generator/frontend/public/favicon.svg new file mode 100644 index 0000000..6893eb1 --- /dev/null +++ b/generator/frontend/public/favicon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/generator/frontend/public/icons.svg b/generator/frontend/public/icons.svg new file mode 100644 index 0000000..e952219 --- /dev/null +++ b/generator/frontend/public/icons.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/generator/frontend/src/App.css b/generator/frontend/src/App.css new file mode 100644 index 0000000..d7a5f20 --- /dev/null +++ b/generator/frontend/src/App.css @@ -0,0 +1 @@ +/* Intentionally empty — all styles use Tailwind */ diff --git a/generator/frontend/src/App.tsx b/generator/frontend/src/App.tsx new file mode 100644 index 0000000..ddabc71 --- /dev/null +++ b/generator/frontend/src/App.tsx @@ -0,0 +1,124 @@ +import { useState, useRef, useCallback } from 'react' +import './index.css' +import { SearchScreen } from './screens/SearchScreen' +import { WorkshopScreen } from './screens/WorkshopScreen' +import { ResultScreen } from './screens/ResultScreen' + +export type Achievement = { + title: string + subtitle: string + event_date: string + icon: string +} + +export type PerWidgetSettings = { + grade?: { max_tags?: number } + impact?: { line_color?: string } + collaborators?: { max_count?: number; bar_color?: string } + focus?: { max_categories?: number } + languages?: { max_languages?: number } + achievements?: { max_items?: number } +} + +export type WidgetSettings = { + theme: string + widgets: string[] + impactPeriod: string + customTags: string[] + hiddenLanguages: string[] + achievements: Achievement[] + widgetSettings: PerWidgetSettings +} + +const DEFAULT_SETTINGS: WidgetSettings = { + theme: 'midnight', + widgets: ['grade', 'impact', 'collaborators', 'focus', 'languages'], + impactPeriod: '6mo', + customTags: [], + hiddenLanguages: [], + achievements: [], + widgetSettings: {}, +} + +type Step = 'search' | 'workshop' | 'result' + +export default function App() { + const [step, setStep] = useState('search') + const [username, setUsername] = useState('') + const [settings, setSettings] = useState({ ...DEFAULT_SETTINGS }) + const [fetchDone, setFetchDone] = useState(false) + const [fetchError, setFetchError] = useState(null) + const fetchRef = useRef(null) + + const startFetch = useCallback((user: string) => { + if (fetchRef.current) fetchRef.current.abort() + const ctrl = new AbortController() + fetchRef.current = ctrl + setFetchDone(false) + setFetchError(null) + + fetch('/api/fetch', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username: user }), + signal: ctrl.signal, + }) + .then(r => { + if (!r.ok) throw new Error(`Fetch failed (${r.status})`) + return r.json() + }) + .then(() => setFetchDone(true)) + .catch(e => { + if (e.name !== 'AbortError') { + console.warn('Fetch error:', e) + setFetchError(e.message) + setFetchDone(true) + } + }) + }, []) + + const handleSearch = (user: string) => { + setUsername(user) + startFetch(user) + setStep('workshop') + } + + const handleGenerate = () => { + setStep('result') + } + + const handleBack = () => { + if (step === 'result') setStep('workshop') + else if (step === 'workshop') { + if (fetchRef.current) fetchRef.current.abort() + setStep('search') + } + } + + return ( +
+ {step === 'search' && ( + + )} + {step === 'workshop' && ( + + )} + {step === 'result' && ( + + )} +
+ ) +} diff --git a/generator/frontend/src/assets/hero.png b/generator/frontend/src/assets/hero.png new file mode 100644 index 0000000..cc51a3d Binary files /dev/null and b/generator/frontend/src/assets/hero.png differ diff --git a/generator/frontend/src/assets/react.svg b/generator/frontend/src/assets/react.svg new file mode 100644 index 0000000..6c87de9 --- /dev/null +++ b/generator/frontend/src/assets/react.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/generator/frontend/src/assets/vite.svg b/generator/frontend/src/assets/vite.svg new file mode 100644 index 0000000..5101b67 --- /dev/null +++ b/generator/frontend/src/assets/vite.svg @@ -0,0 +1 @@ +Vite diff --git a/generator/frontend/src/index.css b/generator/frontend/src/index.css new file mode 100644 index 0000000..8daa98a --- /dev/null +++ b/generator/frontend/src/index.css @@ -0,0 +1,36 @@ +@import url('https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,100..1000;1,9..40,100..1000&family=Instrument+Serif:ital@0;1&family=JetBrains+Mono:wght@400;500;600&display=swap'); + +@import "tailwindcss"; + +@theme { + --font-sans: 'DM Sans', system-ui, sans-serif; + --font-serif: 'Instrument Serif', Georgia, serif; + --font-mono: 'JetBrains Mono', monospace; +} + +::-webkit-scrollbar { display: none; } +* { -ms-overflow-style: none; scrollbar-width: none; } + +body { + margin: 0; + font-family: 'DM Sans', system-ui, sans-serif; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +@keyframes fade-in-up { + from { opacity: 0; transform: translateY(16px); } + to { opacity: 1; transform: translateY(0); } +} + +.animate-fade-in-up { + animation: fade-in-up 0.5s ease-out both; +} + +@keyframes spin-slow { + to { transform: rotate(360deg); } +} + +.animate-spin-slow { + animation: spin-slow 1s linear infinite; +} diff --git a/generator/frontend/src/lib/renderWidgets.ts b/generator/frontend/src/lib/renderWidgets.ts new file mode 100644 index 0000000..c0d4fc9 --- /dev/null +++ b/generator/frontend/src/lib/renderWidgets.ts @@ -0,0 +1,333 @@ +import { THEMES, TAG_COLORS, GRADE_COLORS, FOCUS_COLORS, LANG_COLORS, type Theme } from './themes' + +// --- Types matching the API `format=data` response --- + +export type GradeData = { + grade: string; score: number + stats: Record + tags: { tag: string; source: string; confidence: number }[] + breakdown: Record +} +export type ImpactWeek = { week_start: string; commits: number } +export type CollaboratorData = { username: string; shared_repos: number; shared_commits: number } +export type FocusCategory = { category: string; percentage: number; commit_count: number } +export type LanguageData = { language: string; percentage: number; loc: number } +export type AchievementInput = { title: string; subtitle: string; event_date: string; icon: string } + +export type WidgetData = { + grade?: GradeData + impact?: ImpactWeek[] + collaborators?: CollaboratorData[] + focus?: FocusCategory[] + languages?: LanguageData[] +} + +export type PerWidgetSettings = { + grade?: { max_tags?: number } + impact?: { line_color?: string } + collaborators?: { max_count?: number; bar_color?: string } + focus?: { max_categories?: number } + languages?: { max_languages?: number } + achievements?: { max_items?: number } +} + +// --- Helpers --- + +const esc = (s: string) => s.replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"') +const font = '-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif' + +function cardWrapper(inner: string, w: number, h: number, t: Theme, title: string, prefix = '') { + const sid = `${prefix}shadow` + return ` + + + ${title ? `${esc(title.toUpperCase())}` : ''} + ${inner} +` +} + +function iconSvg(kind: string, color: string): string { + const icons: Record = { + commits: ``, + prs: ``, + stars: ``, + repos: ``, + followers: ``, + } + return `${icons[kind] ?? ''}` +} + +// --- Widget renderers --- + +function renderGrade(data: GradeData, t: Theme, s?: { max_tags?: number }): string { + const tags = s?.max_tags ? data.tags.slice(0, s.max_tags) : data.tags + const base = data.grade[0] + const color = GRADE_COLORS[base] ?? t.accent + const radius = 36 + const circ = 2 * Math.PI * radius + const offset = circ * (1 - data.score / 100) + const gf = data.grade.length <= 2 ? 30 : 22 + + const statLabels: Record = { commits:'Commits', prs:'PRs', stars:'Stars', repos:'Repos', followers:'Followers' } + const statKeys = ['commits','prs','stars','repos','followers'].filter(k => k in data.stats) + const sw = 340 / Math.max(statKeys.length, 1) + let statsSvg = '' + for (let i = 0; i < statKeys.length; i++) { + const k = statKeys[i], v = data.stats[k] + const sx = i * sw + sw / 2 + const vs = v < 100000 ? v.toLocaleString() : `${Math.round(v/1000)}k` + statsSvg += `${iconSvg(k, t.text_secondary)}${vs}${statLabels[k]??k}` + } + + let tagsSvg = '', tx = 0, ty = 0 + for (const tag of tags) { + const tc = TAG_COLORS[tag.tag] ?? t.accent + const label = tag.tag.replace(/-/g,' ').replace(/\b\w/g, c => c.toUpperCase()) + const tw = Math.round(label.length * 6.6 + 18) + const po = tag.source === 'earned' ? 0.9 : 0.55 + if (tx + tw > 340) { tx = 0; ty += 30 } + tagsSvg += `${esc(label)}` + tx += tw + 6 + } + + const tagsH = tags.length ? ty + 24 : 0 + const statsY = 100, tagsY = statsY + 54 + const tagPad = tagsH > 24 ? 18 : 14 + const cardH = tags.length ? tagsY + tagsH + tagPad : statsY + 54 + + let inner = `${esc(data.grade)}${data.score.toFixed(0)} / 100 + + Developer ProfileGrade ${esc(data.grade)} · ${data.score.toFixed(0)}/100 + + ${statsSvg}` + + if (tags.length) { + inner += `${tagsSvg}` + } + + return cardWrapper(inner, 380, cardH, t, '') +} + +function renderImpact(weeks: ImpactWeek[], t: Theme, s?: { line_color?: string }): string { + const w = 380, h = 200, cx = 40, cy = 8, cw = 316, ch = 82 + const lineColor = s?.line_color ?? t.accent + + if (!weeks.length) { + const inner = ` + No contribution data yet + 0commits over 6mo` + return cardWrapper(inner, w, h, t, 'Impact Timeline') + } + + const maxC = Math.max(...weeks.map(w => w.commits), 1) + const n = weeks.length + const pts = weeks.map((wk, i) => ({ + x: cx + (i / Math.max(n-1, 1)) * cw, + y: cy + ch - (wk.commits / maxC) * ch, + })) + + let pathD = `M ${pts[0].x.toFixed(1)} ${pts[0].y.toFixed(1)}` + for (let i = 1; i < pts.length; i++) { + const mx = (pts[i-1].x + pts[i].x) / 2 + pathD += ` C ${mx.toFixed(1)} ${pts[i-1].y.toFixed(1)}, ${mx.toFixed(1)} ${pts[i].y.toFixed(1)}, ${pts[i].x.toFixed(1)} ${pts[i].y.toFixed(1)}` + } + const areaD = pathD + ` L ${pts[n-1].x.toFixed(1)} ${cy+ch} L ${pts[0].x.toFixed(1)} ${cy+ch} Z` + + let yLabels = '' + for (let i = 0; i < 3; i++) { + const v = Math.round(maxC * (1 - i/2)) + const yy = cy + (i/2) * ch + yLabels += `${v}` + } + + let xLabels = '' + const li = n > 2 ? [0, Math.floor(n/2), n-1] : Array.from({length: n}, (_, i) => i) + for (const idx of li) { + if (idx < weeks.length) { + const px = cx + (idx / Math.max(n-1,1)) * cw + xLabels += `${weeks[idx].week_start.slice(0,7)}` + } + } + + const total = weeks.reduce((a, w) => a + w.commits, 0) + const sy = cy + ch + 46 + const inner = ` + ${yLabels}${xLabels} + + + ${total.toLocaleString()}commits over 6mo` + + return cardWrapper(inner, w, h, t, 'Impact Timeline') +} + +function renderCollaborators(collabs: CollaboratorData[], t: Theme, s?: { max_count?: number; bar_color?: string }): string { + const maxCount = Math.min(Math.max(s?.max_count ?? 5, 1), 10) + const barColor = s?.bar_color ?? t.purple + const shown = collabs.slice(0, maxCount) + const barMax = Math.max(...shown.map(c => c.shared_commits), 1) + let items = '' + + for (let i = 0; i < shown.length; i++) { + const c = shown[i], y = i * 50 + const hue = [...c.username].reduce((h, ch) => h + ch.charCodeAt(0), 0) % 360 + const avatar = `${esc(c.username[0].toUpperCase())}` + const bw = (c.shared_commits / barMax * 120).toFixed(1) + items += `${avatar}${esc(c.username)}${c.shared_repos} repos · ${c.shared_commits} commits` + } + + return cardWrapper(items, 380, shown.length * 50 + 48, t, 'Top Collaborators') +} + +function renderFocus(cats: FocusCategory[], t: Theme, s?: { max_categories?: number }): string { + const maxCats = Math.min(Math.max(s?.max_categories ?? 6, 1), 10) + const sorted = [...cats].sort((a, b) => b.percentage - a.percentage).slice(0, maxCats) + if (!sorted.length) return '' + + const maxPct = Math.max(sorted[0].percentage, 1) + const barMaxW = 210 + let items = '' + + for (let i = 0; i < sorted.length; i++) { + const cat = sorted[i], y = i * 36 + const color = FOCUS_COLORS[i % FOCUS_COLORS.length] + const bw = (cat.percentage / maxPct * barMaxW).toFixed(1) + items += `${esc(cat.category)}${cat.commit_count} commits${Math.round(cat.percentage)}%` + } + + const subY = sorted.length * 36 + 8 + items += `Recent activity · last year` + + return cardWrapper(items, 380, sorted.length * 36 + 54, t, 'Recent Focus') +} + +function renderLanguages(languages: LanguageData[], t: Theme, s?: { max_languages?: number }): string { + const maxLangs = Math.min(Math.max(s?.max_languages ?? 5, 1), 10) + const topLangs = [...languages].sort((a, b) => b.percentage - a.percentage).slice(0, maxLangs) + if (!topLangs.length) return '' + + const totalPct = topLangs.reduce((a, l) => a + l.percentage, 0) + const langs = [...topLangs] + + if (totalPct < 99.9 && languages.length > maxLangs) { + langs.push({ language: 'Other', percentage: Math.round((100 - totalPct) * 10) / 10, loc: 0 }) + } else if (totalPct < 99.9 && totalPct > 0) { + const f = 100 / totalPct + for (const l of langs) l.percentage = Math.round(l.percentage * f * 10) / 10 + } + + const legendStart = 20, legendH = langs.length * 22 + const ccy = legendStart + legendH / 2, ccx = 60, r = 44, innerR = 28 + const circ = 2 * Math.PI * r + + let arcs = '', legend = '', offset = 0 + for (let i = 0; i < langs.length; i++) { + const lang = langs[i] + const color = lang.language === 'Other' ? t.text_secondary : (LANG_COLORS[lang.language] ?? FOCUS_COLORS[i % FOCUS_COLORS.length]) + const dash = circ * lang.percentage / 100 + const gap = circ - dash + arcs += `` + offset += dash + + const ly = i * 22 + legend += `${esc(lang.language)}${Math.round(lang.percentage)}%` + } + + const center = `${esc(langs[0].language)}` + const inner = `${arcs}${center}${legend}` + const rowsH = Math.max(langs.length * 22 + 40, 120) + return cardWrapper(inner, 380, rowsH + 36, t, 'Languages') +} + +function renderAchievements(achievements: AchievementInput[], t: Theme, s?: { max_items?: number }): string { + const maxItems = Math.min(Math.max(s?.max_items ?? 5, 1), 10) + const shown = achievements.filter(a => a.title.trim()).slice(0, maxItems) + if (!shown.length) return '' + + const accentColors = [t.orange, t.green, t.accent, t.purple, t.pink] + let items = '' + + for (let i = 0; i < shown.length; i++) { + const ach = shown[i], y = i * 56 + const color = accentColors[i % accentColors.length] + items += `${esc(ach.title)}${esc(ach.subtitle)}${ach.event_date ? ' · ' + ach.event_date : ''}` + } + + return cardWrapper(items, 380, shown.length * 56 + 50, t, 'Achievements') +} + +// --- Composite --- + +function extractInner(svg: string, key: string): { inner: string; h: number } { + const hm = svg.match(/height="(\d+)"/) + const h = hm ? parseInt(hm[1]) : 160 + + // Prefix IDs + const ids = [...svg.matchAll(/id="([^"]+)"/g)].map(m => m[1]) + let inner = svg + for (const id of ids) { + const nid = `${key}_${id}` + inner = inner.replaceAll(`id="${id}"`, `id="${nid}"`) + inner = inner.replaceAll(`url(#${id})`, `url(#${nid})`) + inner = inner.replaceAll(`href="#${id}"`, `href="#${nid}"`) + } + inner = inner.replace(/]*>/, '').replace(/<\/svg>\s*$/, '') + return { inner, h } +} + +// --- Main export --- + +export function renderAllWidgets(opts: { + data: WidgetData + theme: string + widgets: string[] + widgetOrder: string[] + achievements: AchievementInput[] + widgetSettings: PerWidgetSettings + username: string +}): string { + const t = THEMES[opts.theme] ?? THEMES.dark + const enabled = new Set(opts.widgets) + const widgetSvgs: Record = {} + + if (enabled.has('grade') && opts.data.grade) + widgetSvgs.grade = renderGrade(opts.data.grade, t, opts.widgetSettings.grade) + if (enabled.has('impact') && opts.data.impact) + widgetSvgs.impact = renderImpact(opts.data.impact, t, opts.widgetSettings.impact) + if (enabled.has('collaborators') && opts.data.collaborators) + widgetSvgs.collaborators = renderCollaborators(opts.data.collaborators, t, opts.widgetSettings.collaborators) + if (enabled.has('focus') && opts.data.focus) + widgetSvgs.focus = renderFocus(opts.data.focus, t, opts.widgetSettings.focus) + if (enabled.has('languages') && opts.data.languages) + widgetSvgs.languages = renderLanguages(opts.data.languages, t, opts.widgetSettings.languages) + if (enabled.has('achievements')) + widgetSvgs.achievements = renderAchievements(opts.achievements, t, opts.widgetSettings.achievements) + + // Compose + const totalW = 420, headerH = 60, padding = 20, gap = 16 + const ordered = opts.widgetOrder.filter(k => enabled.has(k) && widgetSvgs[k]) + + const parts = ordered.map(key => { + const { inner, h } = extractInner(widgetSvgs[key], key) + return { key, inner, h } + }) + + const contentH = parts.reduce((a, p) => a + p.h, 0) + gap * Math.max(parts.length - 1, 0) + const totalH = headerH + contentH + padding * 2 + 10 + + const avatar = `` + const header = `${avatar}${esc(opts.username || 'Developer')}` + + let yOffset = headerH + padding + let embedded = '' + for (const { inner, h } of parts) { + embedded += `${inner}` + yOffset += h + gap + } + + return ` + + + ${header}${embedded} + Generated with ♥ +` +} diff --git a/generator/frontend/src/lib/themes.ts b/generator/frontend/src/lib/themes.ts new file mode 100644 index 0000000..35b681d --- /dev/null +++ b/generator/frontend/src/lib/themes.ts @@ -0,0 +1,37 @@ +export type Theme = { + bg: string; card_bg: string; card_border: string + text: string; text_secondary: string; accent: string + green: string; orange: string; red: string + purple: string; pink: string; grid: string +} + +export const THEMES: Record = { + dark: { bg:"#121820",card_bg:"#1a2230",card_border:"#2a3444",text:"#d1d9e0",text_secondary:"#7d8895",accent:"#58a6ff",green:"#3fb950",orange:"#d29922",red:"#f85149",purple:"#bc8cff",pink:"#f778ba",grid:"#1e2836" }, + onyx: { bg:"#09090b",card_bg:"#18181b",card_border:"#27272a",text:"#fafafa",text_secondary:"#a1a1aa",accent:"#a78bfa",green:"#4ade80",orange:"#fb923c",red:"#f87171",purple:"#c084fc",pink:"#f472b6",grid:"#27272a" }, + nord: { bg:"#1e2433",card_bg:"#2a3142",card_border:"#3d4659",text:"#e5e9f0",text_secondary:"#8892a4",accent:"#88c0d0",green:"#a3be8c",orange:"#ebcb8b",red:"#bf616a",purple:"#b48ead",pink:"#d08770",grid:"#333d50" }, + light: { bg:"#ffffff",card_bg:"#f6f8fa",card_border:"#d8dee4",text:"#24292f",text_secondary:"#656d76",accent:"#0969da",green:"#1a7f37",orange:"#9a6700",red:"#cf222e",purple:"#8250df",pink:"#bf3989",grid:"#eaeef2" }, + paper: { bg:"#faf8f5",card_bg:"#f5f0eb",card_border:"#e0d8cf",text:"#3d3529",text_secondary:"#7a7062",accent:"#b45309",green:"#4d7c0f",orange:"#a16207",red:"#b91c1c",purple:"#7e22ce",pink:"#be185d",grid:"#ebe5dd" }, +} +THEMES.midnight = THEMES.dark +THEMES.clean = THEMES.light + +export const TAG_COLORS: Record = { + "ml-engineer":"#bc8cff","frontend":"#58a6ff","backend":"#3fb950","fullstack":"#d29922", + "devops":"#f0883e","database":"#f778ba","mobile":"#ff6b9d","security":"#f85149", + "data-science":"#79c0ff","systems":"#7ee787","cloud":"#58a6ff","open-source":"#3fb950", +} + +export const GRADE_COLORS: Record = { + S:"#ff6b9d", A:"#3fb950", B:"#58a6ff", C:"#d29922", D:"#f0883e", F:"#f85149", +} + +export const FOCUS_COLORS = [ + "#58a6ff","#3fb950","#bc8cff","#d29922","#f0883e","#f778ba","#f85149","#79c0ff", +] + +export const LANG_COLORS: Record = { + Python:"#3572A5",JavaScript:"#f1e05a",TypeScript:"#3178c6",Go:"#00ADD8", + Rust:"#dea584",Java:"#b07219","C++":"#f34b7d",C:"#555555",Ruby:"#701516", + Shell:"#89e051",HTML:"#e34c26",CSS:"#563d7c",Kotlin:"#A97BFF",Swift:"#F05138", + "Jupyter Notebook":"#DA5B0B",Dockerfile:"#384d54", +} diff --git a/generator/frontend/src/main.tsx b/generator/frontend/src/main.tsx new file mode 100644 index 0000000..bef5202 --- /dev/null +++ b/generator/frontend/src/main.tsx @@ -0,0 +1,10 @@ +import { StrictMode } from 'react' +import { createRoot } from 'react-dom/client' +import './index.css' +import App from './App.tsx' + +createRoot(document.getElementById('root')!).render( + + + , +) diff --git a/generator/frontend/src/screens/ResultScreen.tsx b/generator/frontend/src/screens/ResultScreen.tsx new file mode 100644 index 0000000..d6284ee --- /dev/null +++ b/generator/frontend/src/screens/ResultScreen.tsx @@ -0,0 +1,108 @@ +import { useState, useEffect } from 'react' +import DOMPurify from 'dompurify' +import type { WidgetSettings } from '../App' + +function sanitizeSvg(raw: string): string { + return DOMPurify.sanitize(raw, { + USE_PROFILES: { svg: true, svgFilters: true }, + ADD_TAGS: ['image', 'use', 'clipPath', 'defs', 'style', 'animate', 'animateTransform', 'feDropShadow', 'filter', 'linearGradient', 'stop'], + ADD_ATTR: ['xlink:href', 'href', 'clip-path', 'viewBox', 'preserveAspectRatio', 'xmlns', 'xmlns:xlink', 'rx', 'ry', 'attributeName', 'from', 'to', 'dur', 'fill', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'dominant-baseline', 'letter-spacing', 'opacity', 'filter', 'flood-color', 'flood-opacity', 'stdDeviation'], + }) +} + +type Props = { + username: string + settings: WidgetSettings + fetchDone: boolean + fetchError: string | null + onBack: () => void +} + +export function ResultScreen({ username, settings, fetchDone, fetchError, onBack }: Props) { + const [svgContent, setSvgContent] = useState('') + const [loading, setLoading] = useState(true) + const [generated, setGenerated] = useState(false) + + // Generate the final SVG once fetch completes + useEffect(() => { + if (!fetchDone) return + if (generated) return + + setLoading(true) + fetch('/api/generate', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + username, + theme: settings.theme, + widgets: settings.widgets, + widget_order: ['grade', 'impact', 'collaborators', 'focus', 'languages', 'achievements'], + custom_tags: settings.customTags.length ? settings.customTags : undefined, + hidden_languages: settings.hiddenLanguages.length ? settings.hiddenLanguages : undefined, + achievements: settings.achievements.filter(a => a.title.trim()), + widget_settings: settings.widgetSettings, + format: 'svg', + }), + }) + .then(r => r.text()) + .then(svg => { + // SVG is sanitized via DOMPurify before rendering + setSvgContent(sanitizeSvg(svg)) + setLoading(false) + setGenerated(true) + }) + .catch(() => setLoading(false)) + }, [fetchDone]) + + const waiting = !fetchDone + + return ( +
+ {/* Back button */} +
+ +
+ +
+

+ Your Widget +

+ + {waiting ? ( +
+
+

Generating with real data...

+
+ ) : loading ? ( +
+
+

Rendering...

+
+ ) : ( + <> + {fetchError && ( +

+ Could not fetch live data — showing demo widget +

+ )} + {!fetchError && ( +

+ Generated with real data +

+ )} + {/* SVG content is sanitized with DOMPurify.sanitize() before rendering */} +
+ + )} +
+
+ ) +} diff --git a/generator/frontend/src/screens/SearchScreen.tsx b/generator/frontend/src/screens/SearchScreen.tsx new file mode 100644 index 0000000..c476b12 --- /dev/null +++ b/generator/frontend/src/screens/SearchScreen.tsx @@ -0,0 +1,45 @@ +import { useState } from 'react' + +type Props = { + onSearch: (username: string) => void +} + +export function SearchScreen({ onSearch }: Props) { + const [value, setValue] = useState('') + + const handleSubmit = (e: React.FormEvent) => { + e.preventDefault() + const trimmed = value.trim() + if (trimmed) onSearch(trimmed) + } + + return ( +
+
+

+ GitHub Stats +

+

+ Generate your profile widget +

+
+ setValue(e.target.value)} + placeholder="Enter GitHub username..." + autoFocus + className="flex-1 px-4 py-3 rounded-xl border border-gray-200 bg-white text-sm text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300 transition-colors" + /> + +
+
+
+ ) +} diff --git a/generator/frontend/src/screens/WorkshopScreen.tsx b/generator/frontend/src/screens/WorkshopScreen.tsx new file mode 100644 index 0000000..1eb0922 --- /dev/null +++ b/generator/frontend/src/screens/WorkshopScreen.tsx @@ -0,0 +1,455 @@ +import { useState, useEffect, useRef, useMemo } from 'react' +import type { WidgetSettings, Achievement, PerWidgetSettings } from '../App' +import { renderAllWidgets, type WidgetData } from '../lib/renderWidgets' + +const THEMES = [ + { id: 'midnight', label: 'Midnight', color: '#121820' }, + { id: 'onyx', label: 'Onyx', color: '#09090b' }, + { id: 'nord', label: 'Nord', color: '#1e2433' }, + { id: 'clean', label: 'Clean', color: '#ffffff', border: true }, + { id: 'paper', label: 'Paper', color: '#faf8f5', border: true }, +] + +const ALL_WIDGETS = [ + { id: 'grade', label: 'Grade' }, + { id: 'impact', label: 'Impact Timeline' }, + { id: 'collaborators', label: 'Top Collaborators' }, + { id: 'focus', label: 'Recent Focus' }, + { id: 'languages', label: 'Languages' }, + { id: 'achievements', label: 'Achievements' }, +] + +const ICONS = [ + { id: 'trophy', label: '🏆' }, + { id: 'medal', label: '🥇' }, + { id: 'star', label: '⭐' }, + { id: 'hackathon', label: '💻' }, +] + +const COLOR_PRESETS = [ + '#58a6ff', '#a78bfa', '#4ade80', '#fb923c', '#f472b6', + '#ff6b6b', '#38bdf8', '#facc15', '#34d399', '#c084fc', +] + +function ChevronIcon({ open }: { open: boolean }) { + return ( + + + + ) +} + +function NumberStepper({ value, min, max, onChange }: { + value: number; min: number; max: number; onChange: (v: number) => void +}) { + return ( +
+ + {value} + +
+ ) +} + +function ColorPicker({ value, onChange }: { value: string; onChange: (v: string) => void }) { + return ( +
+ {COLOR_PRESETS.map(c => ( +
+ ) +} + +type Props = { + username: string + settings: WidgetSettings + onSettingsChange: (s: WidgetSettings) => void + onGenerate: () => void + onBack: () => void + fetchDone: boolean +} + +export function WorkshopScreen({ + username, + settings, + onSettingsChange, + onGenerate, + onBack, + fetchDone, +}: Props) { + const [widgetData, setWidgetData] = useState(null) + const [dataLoading, setDataLoading] = useState(true) + const [expandedWidget, setExpandedWidget] = useState(null) + const dataFetched = useRef(false) + + const updateSetting = (key: K, val: WidgetSettings[K]) => { + onSettingsChange({ ...settings, [key]: val }) + } + + const updateWidgetSetting = (widget: keyof PerWidgetSettings, key: string, val: unknown) => { + const current = settings.widgetSettings[widget] || {} + const next = { ...settings.widgetSettings, [widget]: { ...current, [key]: val } } + updateSetting('widgetSettings', next) + } + + const getWidgetSetting = (widget: keyof PerWidgetSettings, key: string, fallback: T): T => { + const ws = settings.widgetSettings[widget] as Record | undefined + return (ws?.[key] as T) ?? fallback + } + + const toggleWidget = (id: string) => { + const next = settings.widgets.includes(id) + ? settings.widgets.filter(w => w !== id) + : [...settings.widgets, id] + updateSetting('widgets', next) + } + + const toggleAdvanced = (id: string) => { + setExpandedWidget(expandedWidget === id ? null : id) + } + + const addAchievement = () => { + updateSetting('achievements', [ + ...settings.achievements, + { title: '', subtitle: '', event_date: '', icon: 'trophy' }, + ]) + } + + const updateAchievement = (idx: number, field: keyof Achievement, val: string) => { + const next = settings.achievements.map((a, i) => + i === idx ? { ...a, [field]: val } : a + ) + updateSetting('achievements', next) + } + + const removeAchievement = (idx: number) => { + updateSetting('achievements', settings.achievements.filter((_, i) => i !== idx)) + } + + // Fetch widget data once on mount (or when fetch completes) + useEffect(() => { + if (dataFetched.current || !fetchDone) return + dataFetched.current = true + setDataLoading(true) + + fetch('/api/generate', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + username, + widgets: ['grade', 'impact', 'collaborators', 'focus', 'languages'], + widget_order: ['grade', 'impact', 'collaborators', 'focus', 'languages'], + custom_tags: settings.customTags.length ? settings.customTags : undefined, + hidden_languages: settings.hiddenLanguages.length ? settings.hiddenLanguages : undefined, + format: 'data', + }), + }) + .then(r => r.json()) + .then(json => { + setWidgetData(json.data) + setDataLoading(false) + }) + .catch(() => setDataLoading(false)) + }, [fetchDone]) + + // Render SVG client-side whenever settings change (instant, no API call) + const svgContent = useMemo(() => { + if (!widgetData) return '' + return renderAllWidgets({ + data: widgetData, + theme: settings.theme, + widgets: settings.widgets, + widgetOrder: ['grade', 'impact', 'collaborators', 'focus', 'languages', 'achievements'], + achievements: settings.achievements, + widgetSettings: settings.widgetSettings, + username, + }) + }, [widgetData, settings, username]) + + return ( +
+
+ {/* Left settings panel */} +
+ {/* Back */} + + +
{username}
+
+ {fetchDone ? ( + <> +
+ Data ready + + ) : ( + <> +
+ Fetching data... + + )} +
+ + {/* Theme */} +
+
Theme
+
+ {THEMES.map(t => ( +
+
+ {THEMES.find(t => t.id === settings.theme)?.label} +
+
+ + {/* Widgets with inline advanced settings */} +
+
Widgets
+
+ {ALL_WIDGETS.map(w => { + const enabled = settings.widgets.includes(w.id) + const hasAdvanced = ['grade', 'impact', 'collaborators', 'focus', 'languages', 'achievements'].includes(w.id) + const isExpanded = expandedWidget === w.id && enabled + + return ( +
+
+ + {hasAdvanced && enabled && ( + + )} +
+ + {isExpanded && ( +
+ {w.id === 'grade' && ( +
+ Max tags + updateWidgetSetting('grade', 'max_tags', v)} + /> +
+ )} + + {w.id === 'impact' && ( +
+ Line color + updateWidgetSetting('impact', 'line_color', v)} + /> +
+ )} + + {w.id === 'collaborators' && ( +
+
+ Max shown + updateWidgetSetting('collaborators', 'max_count', v)} + /> +
+
+ Bar color + updateWidgetSetting('collaborators', 'bar_color', v)} + /> +
+
+ )} + + {w.id === 'focus' && ( +
+ Max categories + updateWidgetSetting('focus', 'max_categories', v)} + /> +
+ )} + + {w.id === 'languages' && ( +
+ Max languages + updateWidgetSetting('languages', 'max_languages', v)} + /> +
+ )} + + {w.id === 'achievements' && ( +
+ Max shown + updateWidgetSetting('achievements', 'max_items', v)} + /> +
+ )} +
+ )} +
+ ) + })} +
+
+ + {/* Achievements editor */} + {settings.widgets.includes('achievements') && ( +
+
Achievements
+
+ {settings.achievements.map((ach, idx) => ( +
+
+ {ICONS.map(ic => ( + + ))} +
+ +
+ updateAchievement(idx, 'title', e.target.value)} + placeholder="Title (e.g. Hackathon Winner)" + className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300 mb-1.5" + /> + updateAchievement(idx, 'subtitle', e.target.value)} + placeholder="Subtitle (e.g. 1st Place · AI Track)" + className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300 mb-1.5" + /> + updateAchievement(idx, 'event_date', e.target.value)} + placeholder="Date (e.g. 2025-01)" + className="w-full px-2 py-1.5 rounded-md border border-gray-200 bg-white text-xs text-gray-800 placeholder:text-gray-300 focus:outline-none focus:ring-1 focus:ring-gray-300" + /> +
+ ))} + +
+
+ )} + + {/* Spacer */} +
+ + {/* Generate button */} + +
+ + {/* Right preview area */} +
+
+ {svgContent ? ( +
+ ) : ( +
+ {dataLoading ? ( +
+ ) : ( +

No data available

+ )} +
+ )} +
+
+
+
+ ) +} diff --git a/generator/frontend/tsconfig.app.json b/generator/frontend/tsconfig.app.json new file mode 100644 index 0000000..1d29c88 --- /dev/null +++ b/generator/frontend/tsconfig.app.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", + "target": "es2023", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "module": "esnext", + "types": ["vite/client"], + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "moduleDetection": "force", + "noEmit": true, + "jsx": "react-jsx", + + /* Linting */ + "noUnusedLocals": true, + "noUnusedParameters": true, + "erasableSyntaxOnly": true, + "noFallthroughCasesInSwitch": true + }, + "include": ["src"] +} diff --git a/generator/frontend/tsconfig.json b/generator/frontend/tsconfig.json new file mode 100644 index 0000000..1ffef60 --- /dev/null +++ b/generator/frontend/tsconfig.json @@ -0,0 +1,7 @@ +{ + "files": [], + "references": [ + { "path": "./tsconfig.app.json" }, + { "path": "./tsconfig.node.json" } + ] +} diff --git a/generator/frontend/tsconfig.node.json b/generator/frontend/tsconfig.node.json new file mode 100644 index 0000000..d3c52ea --- /dev/null +++ b/generator/frontend/tsconfig.node.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", + "target": "es2023", + "lib": ["ES2023"], + "module": "esnext", + "types": ["node"], + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "moduleDetection": "force", + "noEmit": true, + + /* Linting */ + "noUnusedLocals": true, + "noUnusedParameters": true, + "erasableSyntaxOnly": true, + "noFallthroughCasesInSwitch": true + }, + "include": ["vite.config.ts"] +} diff --git a/generator/frontend/vite.config.ts b/generator/frontend/vite.config.ts new file mode 100644 index 0000000..2ae1021 --- /dev/null +++ b/generator/frontend/vite.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' + +export default defineConfig({ + plugins: [react(), tailwindcss()], + server: { + port: 3000, + proxy: { + '/api': 'http://localhost:5002', + }, + }, +}) diff --git a/generator/pytest.ini b/generator/pytest.ini new file mode 100644 index 0000000..9d1efdb --- /dev/null +++ b/generator/pytest.ini @@ -0,0 +1,5 @@ +[pytest] +testpaths = tests +python_files = test_*.py +pythonpath = . +addopts = -ra --strict-markers diff --git a/generator/requirements.txt b/generator/requirements.txt new file mode 100644 index 0000000..2a644ec --- /dev/null +++ b/generator/requirements.txt @@ -0,0 +1,7 @@ +flask==3.0.3 +flask-caching==2.3.0 +flask-compress==1.15 +requests==2.32.3 +pytest==8.3.3 +responses==0.25.3 +gunicorn==23.0.0 diff --git a/generator/src/__init__.py b/generator/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/generator/src/api.py b/generator/src/api.py new file mode 100644 index 0000000..0e55b1d --- /dev/null +++ b/generator/src/api.py @@ -0,0 +1,149 @@ +"""Flask app for the generator service. + +Serves: + / -> React SPA (static/index.html) + /assets/

-> SPA bundles + /api/* -> JSON/SVG API +""" +import os +from functools import wraps +from flask import Flask, jsonify, request, Response, send_from_directory + +from . import config, db, fetcher_client, placeholder + +_STATIC_DIR = os.path.join(os.path.dirname(__file__), "static") + +app = Flask(__name__, static_folder=None) + + +def require_auth(fn): + @wraps(fn) + def wrapper(*args, **kwargs): + return fn(*args, **kwargs) + return wrapper + + +@app.route("/", defaults={"path": ""}) +@app.route("/") +def spa(path: str): + if path.startswith("api/"): + return jsonify({"error": "not found"}), 404 + if path: + try: + return send_from_directory(_STATIC_DIR, path) + except Exception: + pass + index = os.path.join(_STATIC_DIR, "index.html") + if os.path.isfile(index): + return send_from_directory(_STATIC_DIR, "index.html") + return jsonify({"error": "frontend not built"}), 503 + + +@app.route("/api/health", methods=["GET"]) +def health(): + return jsonify({"status": "ok", "service": "generator"}) + + +@app.route("/api/", methods=["GET"]) +def get_widget(username: str): + return _serve(username, widget_name="composite") + + +@app.route("/api//.svg", methods=["GET"]) +def get_widget_named(username: str, widget: str): + return _serve(username, widget_name=widget) + + +def _serve(username: str, widget_name: str) -> Response: + settings_row = db.get_settings(username) + + if settings_row is None: + if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP: + return _placeholder_response("rate_limited", username) + defaults = { + "theme": "dark", + "enabled": config.ENABLED_WIDGETS, + "widget_order": config.WIDGET_ORDER, + } + db.enroll(username, defaults) + return _placeholder_response("building", username) + + db.touch_last_requested(username) + svg = db.get_current_widget(username, widget_name) + if svg is None: + return _placeholder_response("building", username, theme=settings_row["settings"].get("theme", "dark")) + + if settings_row.get("settings_hash") == "not_found": + return Response(svg, mimetype="image/svg+xml", + headers={"X-Widget-Status": "not_found", "Cache-Control": "no-store"}) + + return Response(svg, mimetype="image/svg+xml", + headers={"X-Widget-Status": "ready", + "Cache-Control": "public, max-age=3600"}) + + +def _placeholder_response(variant: str, username: str, theme: str = "dark") -> Response: + svg = placeholder.render(variant, username, theme=theme) + return Response(svg, mimetype="image/svg+xml", + headers={"X-Widget-Status": variant, "Cache-Control": "no-store"}) + + +@app.route("/api/enroll", methods=["POST"]) +def enroll_endpoint(): + body = request.get_json(silent=True) or {} + username = body.get("username") + if not username: + return jsonify({"error": "username required"}), 400 + if db.get_settings(username) is not None: + return jsonify({"error": "already_enrolled"}), 409 + if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP: + return jsonify({"error": "rate_limited"}), 429 + defaults = {"theme": "dark", "enabled": config.ENABLED_WIDGETS, "widget_order": config.WIDGET_ORDER} + job_id = db.enroll(username, defaults) + return jsonify({"enrolled": True, "job_id": job_id}) + + +@app.route("/api//settings", methods=["GET"]) +@require_auth +def get_settings(username: str): + s = db.get_settings(username) + if s is None: + return jsonify({"error": "not_enrolled"}), 404 + return jsonify(s) + + +@app.route("/api//settings", methods=["PATCH"]) +@require_auth +def patch_settings(username: str): + current = db.get_settings(username) + if current is None: + return jsonify({"error": "not_enrolled"}), 404 + body = request.get_json(silent=True) or {} + merged = {**current["settings"], **body} + job_id = db.update_settings(username, merged) + return jsonify({"updated": True, "job_id": job_id}) + + +@app.route("/api//refresh", methods=["POST"]) +@require_auth +def refresh(username: str): + s = db.get_settings(username) + if s is None: + return jsonify({"error": "not_enrolled"}), 404 + if not db.mark_manual_refresh(username): + return jsonify({"error": "already_used"}), 409 + try: + fetcher_client.force_fetch(username) + except Exception as e: + return jsonify({"error": f"fetch failed: {e}"}), 502 + job_id = db.enqueue_build(username) + return jsonify({"refreshed": True, "job_id": job_id}) + + +def main(): + db.init_dbs() + app.run(host="0.0.0.0", port=config.PORT) + + +if __name__ == "__main__": + main() diff --git a/generator/src/cache.py b/generator/src/cache.py new file mode 100644 index 0000000..9a8b491 --- /dev/null +++ b/generator/src/cache.py @@ -0,0 +1,37 @@ +"""Tiny cache wrapper. v1 = no-op (REDIS_URL empty). v2 = real Redis.""" +from typing import Optional + +from . import config + + +class Cache: + def __init__(self): + self.enabled = bool(config.REDIS_URL) + self._client = None + if self.enabled: + import redis # local import so v1 doesn't require redis in runtime path + self._client = redis.from_url(config.REDIS_URL, decode_responses=True) + + def get(self, key: str) -> Optional[str]: + if not self.enabled: + return None + try: + return self._client.get(key) + except Exception: + return None + + def set(self, key: str, value: str, ttl_seconds: int) -> None: + if not self.enabled: + return + try: + self._client.setex(key, ttl_seconds, value) + except Exception: + pass + + def delete(self, *keys: str) -> None: + if not self.enabled or not keys: + return + try: + self._client.delete(*keys) + except Exception: + pass diff --git a/src/config.py b/generator/src/config.py similarity index 85% rename from src/config.py rename to generator/src/config.py index 5206014..8dc6694 100644 --- a/src/config.py +++ b/generator/src/config.py @@ -103,3 +103,15 @@ TAG_TOPIC_MAP = { "gcp": "Cloud", } """Map repository topics to developer role categories.""" + +# --- Service-specific additions (v2 of config) --- + +PORT = int(os.getenv("GENERATOR_PORT", "5002")) +SETTINGS_DB_PATH = os.getenv("GENERATOR_SETTINGS_DB_PATH", "./data/settings.db") +WIDGETS_DB_PATH = os.getenv("GENERATOR_WIDGETS_DB_PATH", "./data/widgets.db") +FETCHER_URL = os.getenv("FETCHER_URL", "http://localhost:5001") +FETCHER_INTERNAL_TOKEN = os.getenv("FETCHER_INTERNAL_TOKEN", "") +REDIS_URL = os.getenv("REDIS_URL", "") +ENROLLMENT_DAILY_CAP = int(os.getenv("ENROLLMENT_DAILY_CAP", "50")) +WIDGET_LRU_PER_USER = int(os.getenv("WIDGET_LRU_PER_USER", "10")) +POLL_INTERVAL_MINUTES = int(os.getenv("GENERATOR_POLL_INTERVAL_MINUTES", "15")) diff --git a/generator/src/cron.py b/generator/src/cron.py new file mode 100644 index 0000000..e82267d --- /dev/null +++ b/generator/src/cron.py @@ -0,0 +1,45 @@ +"""Generator cron: poll fetcher for payload-hash changes, enqueue rebuilds. + +Run as its own container: CMD python -m src.cron +""" +import logging +import time + +from . import config, db, fetcher_client + +log = logging.getLogger("generator.cron") + + +def tick() -> dict: + enqueued = 0 + failed = 0 + for username in db.list_enrolled(): + try: + info = db.get_settings(username) + current = info.get("last_fetcher_payload_hash") + r = fetcher_client.get_data(username) + latest = r.get("payload_hash") + if latest and latest != current: + db.enqueue_build(username) + db.set_last_fetcher_hash(username, latest) + enqueued += 1 + except Exception as e: + log.warning("poll failed for %s: %s", username, e) + failed += 1 + return {"enqueued": enqueued, "failed": failed} + + +def main(): + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s") + db.init_dbs() + interval_s = config.POLL_INTERVAL_MINUTES * 60 + while True: + try: + log.info("tick: %s", tick()) + except Exception: + log.exception("tick failed") + time.sleep(interval_s) + + +if __name__ == "__main__": + main() diff --git a/generator/src/db.py b/generator/src/db.py new file mode 100644 index 0000000..57d3f00 --- /dev/null +++ b/generator/src/db.py @@ -0,0 +1,313 @@ +"""Generator's two SQLite DBs: settings.db (settings + jobs + enrollments) and widgets.db (svg cache). + +All access goes through this module so a future Postgres swap is local to here. +Both DBs are opened with WAL mode. +""" +import hashlib +import json +import os +import sqlite3 +from contextlib import contextmanager +from datetime import datetime, timedelta +from typing import Optional + +from . import config + +SETTINGS_DB_PATH = config.SETTINGS_DB_PATH +WIDGETS_DB_PATH = config.WIDGETS_DB_PATH + +_SETTINGS_SCHEMA = """ +CREATE TABLE IF NOT EXISTS users ( + username TEXT PRIMARY KEY, + settings_json TEXT NOT NULL, + settings_hash TEXT NOT NULL, + enrolled_at TEXT NOT NULL, + last_fetcher_payload_hash TEXT, + manual_refresh_used INTEGER DEFAULT 0, + last_requested_at TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS enrollments_daily ( + day TEXT PRIMARY KEY, + count INTEGER NOT NULL +); +CREATE TABLE IF NOT EXISTS jobs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + kind TEXT NOT NULL, + username TEXT NOT NULL, + status TEXT NOT NULL, + attempts INTEGER DEFAULT 0, + last_error TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_jobs_pending ON jobs(status, created_at); +""" + +_WIDGETS_SCHEMA = """ +CREATE TABLE IF NOT EXISTS widgets ( + username TEXT NOT NULL, + settings_hash TEXT NOT NULL, + widget_name TEXT NOT NULL, + svg TEXT NOT NULL, + built_at TEXT NOT NULL, + PRIMARY KEY (username, settings_hash, widget_name) +); +CREATE TABLE IF NOT EXISTS current_widget ( + username TEXT PRIMARY KEY, + settings_hash TEXT NOT NULL, + updated_at TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_widgets_username ON widgets(username); +""" + + +def _now() -> str: + return datetime.utcnow().isoformat(timespec="seconds") + "Z" + + +def _today() -> str: + return datetime.utcnow().strftime("%Y-%m-%d") + + +def _open(path: str) -> sqlite3.Connection: + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + conn = sqlite3.connect(path, timeout=10) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA journal_mode=WAL") + conn.execute("PRAGMA synchronous=NORMAL") + conn.execute("PRAGMA foreign_keys=ON") + conn.execute("PRAGMA busy_timeout=5000") + return conn + + +@contextmanager +def _settings_conn(): + conn = _open(SETTINGS_DB_PATH) + try: + yield conn + finally: + conn.close() + + +@contextmanager +def _widgets_conn(): + conn = _open(WIDGETS_DB_PATH) + try: + yield conn + finally: + conn.close() + + +def init_dbs() -> None: + with _settings_conn() as c: + c.executescript(_SETTINGS_SCHEMA) + c.commit() + with _widgets_conn() as c: + c.executescript(_WIDGETS_SCHEMA) + c.commit() + + +def settings_hash(settings: dict) -> str: + canonical = json.dumps(settings, sort_keys=True, separators=(",", ":")) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() + + +# ---- settings / enrollment ---- + +def enroll(username: str, defaults: dict) -> int: + """Insert a settings row + increment daily counter + enqueue build. Returns job_id.""" + sh = settings_hash(defaults) + now = _now() + with _settings_conn() as c: + c.execute( + """INSERT INTO users(username, settings_json, settings_hash, enrolled_at, last_requested_at) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT(username) DO NOTHING""", + (username, json.dumps(defaults), sh, now, now), + ) + c.execute( + """INSERT INTO enrollments_daily(day, count) VALUES (?, 1) + ON CONFLICT(day) DO UPDATE SET count = count + 1""", + (_today(),), + ) + cur = c.execute( + """INSERT INTO jobs(kind, username, status, created_at, updated_at) + VALUES ('build', ?, 'pending', ?, ?)""", + (username, now, now), + ) + c.commit() + return cur.lastrowid + + +def enrollments_today() -> int: + with _settings_conn() as c: + row = c.execute("SELECT count FROM enrollments_daily WHERE day=?", (_today(),)).fetchone() + return row["count"] if row else 0 + + +def get_settings(username: str) -> Optional[dict]: + with _settings_conn() as c: + row = c.execute("SELECT * FROM users WHERE username=?", (username,)).fetchone() + if row is None: + return None + return { + "settings": json.loads(row["settings_json"]), + "settings_hash": row["settings_hash"], + "manual_refresh_used": row["manual_refresh_used"], + "last_fetcher_payload_hash": row["last_fetcher_payload_hash"], + "enrolled_at": row["enrolled_at"], + } + + +def update_settings(username: str, new_settings: dict) -> int: + """Updates settings + enqueues rebuild. Returns job_id.""" + sh = settings_hash(new_settings) + now = _now() + with _settings_conn() as c: + c.execute( + "UPDATE users SET settings_json=?, settings_hash=? WHERE username=?", + (json.dumps(new_settings), sh, username), + ) + cur = c.execute( + """INSERT INTO jobs(kind, username, status, created_at, updated_at) + VALUES ('build', ?, 'pending', ?, ?)""", + (username, now, now), + ) + c.commit() + return cur.lastrowid + + +def mark_manual_refresh(username: str) -> bool: + """Sets manual_refresh_used=1 only if it was 0. Returns True if successfully flipped.""" + with _settings_conn() as c: + cur = c.execute( + "UPDATE users SET manual_refresh_used=1 WHERE username=? AND manual_refresh_used=0", + (username,), + ) + c.commit() + return cur.rowcount == 1 + + +def touch_last_requested(username: str) -> None: + with _settings_conn() as c: + c.execute("UPDATE users SET last_requested_at=? WHERE username=?", (_now(), username)) + c.commit() + + +def list_enrolled() -> list[str]: + with _settings_conn() as c: + return [r["username"] for r in c.execute("SELECT username FROM users").fetchall()] + + +def set_last_fetcher_hash(username: str, h: str) -> None: + with _settings_conn() as c: + c.execute("UPDATE users SET last_fetcher_payload_hash=? WHERE username=?", (h, username)) + c.commit() + + +# ---- jobs ---- + +def enqueue_build(username: str) -> int: + now = _now() + with _settings_conn() as c: + cur = c.execute( + """INSERT INTO jobs(kind, username, status, created_at, updated_at) + VALUES ('build', ?, 'pending', ?, ?)""", + (username, now, now), + ) + c.commit() + return cur.lastrowid + + +def claim_next_job() -> Optional[dict]: + now = _now() + with _settings_conn() as c: + row = c.execute( + "SELECT * FROM jobs WHERE status='pending' ORDER BY created_at LIMIT 1" + ).fetchone() + if row is None: + return None + c.execute("UPDATE jobs SET status='running', updated_at=?, attempts=attempts+1 WHERE id=?", + (now, row["id"])) + c.commit() + return {"id": row["id"], "username": row["username"], "kind": row["kind"], + "status": "running", "attempts": row["attempts"] + 1} + + +def complete_job(job_id: int) -> None: + with _settings_conn() as c: + c.execute("UPDATE jobs SET status='done', updated_at=? WHERE id=?", (_now(), job_id)) + c.commit() + + +def fail_job(job_id: int, err: str, retry: bool) -> None: + status = "pending" if retry else "failed" + with _settings_conn() as c: + c.execute("UPDATE jobs SET status=?, last_error=?, updated_at=? WHERE id=?", + (status, err, _now(), job_id)) + c.commit() + + +def reclaim_stuck_jobs(older_than_minutes: int) -> int: + cutoff = (datetime.utcnow() - timedelta(minutes=older_than_minutes)).isoformat(timespec="seconds") + "Z" + with _settings_conn() as c: + cur = c.execute( + "UPDATE jobs SET status='pending', updated_at=? WHERE status='running' AND updated_at < ?", + (_now(), cutoff), + ) + c.commit() + return cur.rowcount + + +# ---- widgets ---- + +def put_widgets(username: str, hash_: str, widgets: dict[str, str]) -> None: + """Insert widget rows for this (user, hash) and flip current_widget to point at it.""" + now = _now() + with _widgets_conn() as c: + for name, svg in widgets.items(): + c.execute( + """INSERT INTO widgets(username, settings_hash, widget_name, svg, built_at) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT(username, settings_hash, widget_name) DO UPDATE SET + svg = excluded.svg, built_at = excluded.built_at""", + (username, hash_, name, svg, now), + ) + c.execute( + """INSERT INTO current_widget(username, settings_hash, updated_at) + VALUES (?, ?, ?) + ON CONFLICT(username) DO UPDATE SET settings_hash=excluded.settings_hash, updated_at=excluded.updated_at""", + (username, hash_, now), + ) + c.commit() + + +def get_current_widget(username: str, widget_name: str) -> Optional[str]: + with _widgets_conn() as c: + row = c.execute( + """SELECT w.svg FROM widgets w + JOIN current_widget cw ON cw.username=w.username AND cw.settings_hash=w.settings_hash + WHERE w.username=? AND w.widget_name=?""", + (username, widget_name), + ).fetchone() + return row["svg"] if row else None + + +def lru_trim(username: str, keep: int) -> int: + """Keep only the N newest settings_hashes per user; delete older rows.""" + with _widgets_conn() as c: + hashes = [r["settings_hash"] for r in c.execute( + """SELECT settings_hash, MAX(built_at) AS latest FROM widgets + WHERE username=? GROUP BY settings_hash ORDER BY latest DESC""", + (username,), + ).fetchall()] + to_delete = hashes[keep:] + if not to_delete: + return 0 + placeholders = ",".join("?" * len(to_delete)) + cur = c.execute( + f"DELETE FROM widgets WHERE username=? AND settings_hash IN ({placeholders})", + (username, *to_delete), + ) + c.commit() + return cur.rowcount diff --git a/generator/src/fetcher_client.py b/generator/src/fetcher_client.py new file mode 100644 index 0000000..44d8fd7 --- /dev/null +++ b/generator/src/fetcher_client.py @@ -0,0 +1,21 @@ +"""HTTP client to the fetcher service. Used by api.py, worker.py, cron.py.""" +import requests + +from . import config + + +def _headers() -> dict: + return {"X-Internal-Token": config.FETCHER_INTERNAL_TOKEN} + + +def get_data(username: str) -> dict: + r = requests.get(f"{config.FETCHER_URL}/data/{username}", headers=_headers(), timeout=30) + r.raise_for_status() + return r.json() + + +def force_fetch(username: str) -> dict: + r = requests.post(f"{config.FETCHER_URL}/fetch", headers=_headers(), + json={"username": username}, timeout=30) + r.raise_for_status() + return r.json() diff --git a/src/models/__init__.py b/generator/src/models/__init__.py similarity index 100% rename from src/models/__init__.py rename to generator/src/models/__init__.py diff --git a/src/models/types.py b/generator/src/models/types.py similarity index 100% rename from src/models/types.py rename to generator/src/models/types.py diff --git a/generator/src/placeholder.py b/generator/src/placeholder.py new file mode 100644 index 0000000..65c3e0d --- /dev/null +++ b/generator/src/placeholder.py @@ -0,0 +1,28 @@ +"""Placeholder SVG renderer — three variants for unknown / rate-limited / not-found users. + +Uses the same card wrapper + theme system as real widgets so they look consistent. +""" +from .themes.themes import THEMES +from .utils.svg_helpers import card_wrapper, escape + +_MESSAGES = { + "building": ("Building @{u}'s widget\u2026", "This usually takes under a minute."), + "rate_limited": ("Too many new users today", "Try again tomorrow."), + "not_found": ("GitHub user @{u} doesn't exist", "Check the spelling of the username."), +} + + +def render(variant: str, username: str, theme: str = "dark") -> str: + if variant not in _MESSAGES: + raise ValueError(f"unknown placeholder variant: {variant}") + title_tpl, subtitle = _MESSAGES[variant] + title = title_tpl.format(u=username) + palette = THEMES.get(theme, THEMES["dark"]) + + inner = ( + f'{escape(title)}' + f'{escape(subtitle)}' + ) + return card_wrapper(inner, width=400, height=120, theme=palette) diff --git a/src/data/processor.py b/generator/src/processor.py similarity index 98% rename from src/data/processor.py rename to generator/src/processor.py index 5e25425..97c8e87 100644 --- a/src/data/processor.py +++ b/generator/src/processor.py @@ -3,7 +3,7 @@ from datetime import datetime, timedelta from collections import defaultdict -from ..models import ( +from .models import ( GradeData, TagData, ImpactWeek, @@ -11,7 +11,7 @@ from ..models import ( FocusCategory, LanguageData, ) -from ..widgets import ( +from .widgets import ( render_grade_widget, render_impact_widget, render_collaborators_widget, @@ -150,7 +150,7 @@ def _compute_tags(github_data: dict, max_tags: int = None, custom_tags: list[str Returns: List of TagData objects with inferred developer roles """ - from ..config import TAG_MAX_COUNT, TAG_LANGUAGE_MAP, TAG_TOPIC_MAP, HIDDEN_LANGUAGES + from .config import TAG_MAX_COUNT, TAG_LANGUAGE_MAP, TAG_TOPIC_MAP, HIDDEN_LANGUAGES if max_tags is None: max_tags = TAG_MAX_COUNT @@ -372,7 +372,7 @@ def compute_focus(github_data: dict, hidden_languages: list[str] = None) -> list github_data: GitHub profile data hidden_languages: Optional list of languages to exclude """ - from ..config import HIDDEN_LANGUAGES + from .config import HIDDEN_LANGUAGES if hidden_languages is None: hidden_languages = HIDDEN_LANGUAGES @@ -465,7 +465,7 @@ def compute_languages(github_data: dict, hidden_languages: list[str] = None) -> github_data: GitHub profile data hidden_languages: Optional list of languages to exclude (e.g., ["HTML", "CSS"]) """ - from ..config import HIDDEN_LANGUAGES + from .config import HIDDEN_LANGUAGES if hidden_languages is None: hidden_languages = HIDDEN_LANGUAGES @@ -510,7 +510,7 @@ def generate_widgets_from_github( widget_settings: Optional per-widget settings dict, keyed by widget name. Each value is a dict of settings for that widget's renderer. """ - from ..config import ENABLED_WIDGETS + from .config import ENABLED_WIDGETS if enabled is None: enabled = ENABLED_WIDGETS diff --git a/src/themes/__init__.py b/generator/src/themes/__init__.py similarity index 100% rename from src/themes/__init__.py rename to generator/src/themes/__init__.py diff --git a/src/themes/themes.py b/generator/src/themes/themes.py similarity index 100% rename from src/themes/themes.py rename to generator/src/themes/themes.py diff --git a/src/utils/__init__.py b/generator/src/utils/__init__.py similarity index 100% rename from src/utils/__init__.py rename to generator/src/utils/__init__.py diff --git a/src/utils/svg_helpers.py b/generator/src/utils/svg_helpers.py similarity index 100% rename from src/utils/svg_helpers.py rename to generator/src/utils/svg_helpers.py diff --git a/src/widgets/__init__.py b/generator/src/widgets/__init__.py similarity index 100% rename from src/widgets/__init__.py rename to generator/src/widgets/__init__.py diff --git a/src/widgets/achievements.py b/generator/src/widgets/achievements.py similarity index 100% rename from src/widgets/achievements.py rename to generator/src/widgets/achievements.py diff --git a/src/widgets/collaborators.py b/generator/src/widgets/collaborators.py similarity index 100% rename from src/widgets/collaborators.py rename to generator/src/widgets/collaborators.py diff --git a/src/widgets/composite.py b/generator/src/widgets/composite.py similarity index 100% rename from src/widgets/composite.py rename to generator/src/widgets/composite.py diff --git a/src/widgets/focus.py b/generator/src/widgets/focus.py similarity index 100% rename from src/widgets/focus.py rename to generator/src/widgets/focus.py diff --git a/src/widgets/grade.py b/generator/src/widgets/grade.py similarity index 100% rename from src/widgets/grade.py rename to generator/src/widgets/grade.py diff --git a/src/widgets/impact.py b/generator/src/widgets/impact.py similarity index 100% rename from src/widgets/impact.py rename to generator/src/widgets/impact.py diff --git a/src/widgets/languages.py b/generator/src/widgets/languages.py similarity index 100% rename from src/widgets/languages.py rename to generator/src/widgets/languages.py diff --git a/generator/src/worker.py b/generator/src/worker.py new file mode 100644 index 0000000..0376075 --- /dev/null +++ b/generator/src/worker.py @@ -0,0 +1,84 @@ +"""Build worker. Pulls pending jobs and renders widgets. + +Run as its own container: CMD python -m src.worker +""" +import logging +import time + +from . import cache, config, db, fetcher_client, placeholder, processor +from .widgets import compose_widget + +log = logging.getLogger("generator.worker") +MAX_ATTEMPTS = 3 + + +def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, str]: + enabled = settings.get("enabled") or config.ENABLED_WIDGETS + order = settings.get("widget_order") or config.WIDGET_ORDER + theme = settings.get("theme", "dark") + widgets = processor.generate_widgets_from_github( + payload, + theme=theme, + custom_tags=settings.get("custom_tags"), + hidden_languages=settings.get("hidden_languages"), + enabled=enabled, + widget_settings=settings.get("widget_settings") or {}, + ) + ordered = [w for w in order if w in enabled and w in widgets and widgets[w]] + composite = compose_widget( + widgets=widgets, enabled=ordered, theme_name=theme, + username=username, avatar_b64=payload.get("avatar_b64", ""), + ) + out = {name: svg for name, svg in widgets.items() if svg} + out["composite"] = composite + return out + + +def process_one() -> bool: + job = db.claim_next_job() + if job is None: + return False + username = job["username"] + try: + result = fetcher_client.get_data(username) + payload = result.get("data") or {} + if payload.get("error") == "not_found": + svg = placeholder.render("not_found", username, theme="dark") + db.put_widgets(username, "not_found", {"composite": svg}) + cache.Cache().delete(f"widget:composite:{username}") + db.complete_job(job["id"]) + log.info("not_found marker persisted for %s", username) + return True + + settings_row = db.get_settings(username) + if settings_row is None: + db.fail_job(job["id"], "settings missing", retry=False) + return True + + widgets = _render_widgets(username, payload, settings_row["settings"]) + db.put_widgets(username, settings_row["settings_hash"], widgets) + db.set_last_fetcher_hash(username, result.get("payload_hash", "")) + db.lru_trim(username, config.WIDGET_LRU_PER_USER) + c = cache.Cache() + c.delete(f"widget:composite:{username}", *[f"widget:{n}:{username}" for n in widgets]) + db.complete_job(job["id"]) + log.info("built widgets for %s", username) + return True + except Exception as e: + retry = job["attempts"] < MAX_ATTEMPTS + db.fail_job(job["id"], str(e)[:500], retry=retry) + log.warning("build failed for %s (retry=%s): %s", username, retry, e) + return True + + +def main(): + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s") + db.init_dbs() + while True: + db.reclaim_stuck_jobs(older_than_minutes=10) + if not process_one(): + time.sleep(0.5) + + +if __name__ == "__main__": + main() diff --git a/generator/tests/__init__.py b/generator/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/generator/tests/integration/__init__.py b/generator/tests/integration/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/generator/tests/integration/test_end_to_end.py b/generator/tests/integration/test_end_to_end.py new file mode 100644 index 0000000..a470d36 --- /dev/null +++ b/generator/tests/integration/test_end_to_end.py @@ -0,0 +1,39 @@ +"""End-to-end: api + worker in-process + mocked fetcher HTTP.""" +import os, tempfile +import pytest +import responses +from src import api as apimod, db as dbmod, worker + + +@pytest.fixture +def env(monkeypatch): + with tempfile.TemporaryDirectory() as d: + monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db")) + monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db")) + monkeypatch.setattr(apimod.config, "FETCHER_URL", "http://fetcher-mock") + monkeypatch.setattr(apimod.config, "FETCHER_INTERNAL_TOKEN", "t") + dbmod.init_dbs() + yield + + +@responses.activate +def test_first_request_builds_then_serves_ready(env): + responses.add( + responses.GET, "http://fetcher-mock/data/alice", + json={"data": {"user": {"login": "alice"}, "repos": [], "events": [], + "commits": [], "total_commits": 0, "recent_commits": 0, + "total_prs": 0, "collaborators_data": [], "avatar_b64": ""}, + "payload_hash": "h1"}, status=200, + ) + client = apimod.app.test_client() + + r1 = client.get("/api/alice") + assert r1.headers["X-Widget-Status"] == "building" + + for _ in range(5): + if not worker.process_one(): + break + + r2 = client.get("/api/alice") + assert r2.headers["X-Widget-Status"] == "ready" + assert r2.data.startswith(b"ready"}) + with dbmod._settings_conn() as c: + c.execute("UPDATE users SET settings_hash='h1' WHERE username='alice'") + c.commit() + r = client.get("/api/alice") + assert r.status_code == 200 + assert r.headers["X-Widget-Status"] == "ready" + assert b"ready" in r.data + + +def test_settings_patch_enqueues_rebuild(client): + dbmod.enroll("alice", {"theme": "dark"}) + r = client.patch("/api/alice/settings", json={"theme": "light"}) + assert r.status_code == 200 + assert dbmod.get_settings("alice")["settings"]["theme"] == "light" + + +def test_refresh_is_one_shot(client): + dbmod.enroll("alice", {"theme": "dark"}) + with patch("src.api.fetcher_client.force_fetch", return_value={"changed": True, "payload_hash": "x", "stored": True}): + r1 = client.post("/api/alice/refresh") + assert r1.status_code == 200 + r2 = client.post("/api/alice/refresh") + assert r2.status_code == 409 + + +def test_not_found_status_header(client): + dbmod.enroll("ghost", {"theme": "dark"}) + dbmod.put_widgets("ghost", "not_found", {"composite": "404"}) + with dbmod._settings_conn() as c: + c.execute("UPDATE users SET settings_hash='not_found' WHERE username='ghost'") + c.commit() + r = client.get("/api/ghost") + assert r.headers["X-Widget-Status"] == "not_found" diff --git a/generator/tests/test_cache.py b/generator/tests/test_cache.py new file mode 100644 index 0000000..947e0e8 --- /dev/null +++ b/generator/tests/test_cache.py @@ -0,0 +1,15 @@ +from src import cache + + +def test_noop_when_redis_url_empty(monkeypatch): + monkeypatch.setattr(cache.config, "REDIS_URL", "") + c = cache.Cache() + assert c.get("k") is None + c.set("k", "v", 60) + c.delete("k") + assert c.get("k") is None # still None because no-op + + +def test_enabled_flag_reflects_config(monkeypatch): + monkeypatch.setattr(cache.config, "REDIS_URL", "") + assert cache.Cache().enabled is False diff --git a/generator/tests/test_cron.py b/generator/tests/test_cron.py new file mode 100644 index 0000000..8477035 --- /dev/null +++ b/generator/tests/test_cron.py @@ -0,0 +1,37 @@ +import os, tempfile, pytest +from unittest.mock import patch +from src import db as dbmod +from src import cron as cronmod + + +@pytest.fixture +def tmp_dbs(monkeypatch): + with tempfile.TemporaryDirectory() as d: + monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db")) + monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db")) + dbmod.init_dbs() + yield + + +def test_tick_enqueues_build_when_hash_changed(tmp_dbs): + dbmod.enroll("alice", {"theme": "dark"}) + dbmod.set_last_fetcher_hash("alice", "old") + with dbmod._settings_conn() as c: + c.execute("DELETE FROM jobs") + c.commit() + with patch("src.cron.fetcher_client.get_data", + return_value={"data": {}, "payload_hash": "new"}): + stats = cronmod.tick() + assert stats["enqueued"] == 1 + + +def test_tick_skips_when_hash_unchanged(tmp_dbs): + dbmod.enroll("alice", {"theme": "dark"}) + dbmod.set_last_fetcher_hash("alice", "same") + with dbmod._settings_conn() as c: + c.execute("DELETE FROM jobs") + c.commit() + with patch("src.cron.fetcher_client.get_data", + return_value={"data": {}, "payload_hash": "same"}): + stats = cronmod.tick() + assert stats["enqueued"] == 0 diff --git a/generator/tests/test_db.py b/generator/tests/test_db.py new file mode 100644 index 0000000..3a4b3f9 --- /dev/null +++ b/generator/tests/test_db.py @@ -0,0 +1,92 @@ +import os +import tempfile +import pytest +from src import db as dbmod + + +@pytest.fixture +def tmp_dbs(monkeypatch): + with tempfile.TemporaryDirectory() as d: + monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db")) + monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db")) + dbmod.init_dbs() + yield d + + +def test_settings_hash_is_deterministic(): + h1 = dbmod.settings_hash({"theme": "dark", "widgets": ["a", "b"]}) + h2 = dbmod.settings_hash({"widgets": ["a", "b"], "theme": "dark"}) + assert h1 == h2 + + +def test_enroll_and_get_settings(tmp_dbs): + defaults = {"theme": "dark", "widgets": ["grade"]} + job_id = dbmod.enroll("alice", defaults) + assert job_id > 0 + s = dbmod.get_settings("alice") + assert s["settings"] == defaults + assert s["manual_refresh_used"] == 0 + + +def test_enrollments_daily_counter(tmp_dbs): + dbmod.enroll("alice", {"theme": "dark"}) + dbmod.enroll("bob", {"theme": "dark"}) + assert dbmod.enrollments_today() == 2 + + +def test_update_settings_changes_hash(tmp_dbs): + dbmod.enroll("alice", {"theme": "dark"}) + h_before = dbmod.get_settings("alice")["settings_hash"] + dbmod.update_settings("alice", {"theme": "light"}) + h_after = dbmod.get_settings("alice")["settings_hash"] + assert h_before != h_after + + +def test_claim_job_marks_running(tmp_dbs): + job_id = dbmod.enroll("alice", {"theme": "dark"}) + job = dbmod.claim_next_job() + assert job["id"] == job_id + assert job["status"] == "running" + assert dbmod.claim_next_job() is None # already running + + +def test_complete_job(tmp_dbs): + jid = dbmod.enroll("alice", {"theme": "dark"}) + dbmod.claim_next_job() + dbmod.complete_job(jid) + with dbmod._settings_conn() as c: + status = c.execute("SELECT status FROM jobs WHERE id=?", (jid,)).fetchone()[0] + assert status == "done" + + +def test_widgets_put_and_get(tmp_dbs): + dbmod.put_widgets("alice", "hash1", {"composite": "", "grade": ""}) + row = dbmod.get_current_widget("alice", "composite") + assert row == "" + + +def test_current_widget_flips_atomically(tmp_dbs): + dbmod.put_widgets("alice", "hash1", {"composite": "v1"}) + dbmod.put_widgets("alice", "hash2", {"composite": "v2"}) + assert dbmod.get_current_widget("alice", "composite") == "v2" + + +def test_lru_trim_keeps_n_newest(tmp_dbs): + for i in range(12): + dbmod.put_widgets("alice", f"hash{i}", {"composite": f"{i}"}) + dbmod.lru_trim("alice", keep=10) + with dbmod._widgets_conn() as c: + n = c.execute("SELECT COUNT(DISTINCT settings_hash) FROM widgets WHERE username='alice'").fetchone()[0] + assert n == 10 + + +def test_reclaim_stuck_running_jobs(tmp_dbs): + jid = dbmod.enroll("alice", {"theme": "dark"}) + dbmod.claim_next_job() + # Backdate updated_at to simulate dead worker + with dbmod._settings_conn() as c: + c.execute("UPDATE jobs SET updated_at='2020-01-01T00:00:00Z' WHERE id=?", (jid,)) + c.commit() + dbmod.reclaim_stuck_jobs(older_than_minutes=10) + job = dbmod.claim_next_job() + assert job["id"] == jid diff --git a/generator/tests/test_fetcher_client.py b/generator/tests/test_fetcher_client.py new file mode 100644 index 0000000..b8da64a --- /dev/null +++ b/generator/tests/test_fetcher_client.py @@ -0,0 +1,37 @@ +import responses +import pytest +from src import fetcher_client as fc + + +@pytest.fixture(autouse=True) +def cfg(monkeypatch): + monkeypatch.setattr(fc.config, "FETCHER_URL", "http://fetcher:5001") + monkeypatch.setattr(fc.config, "FETCHER_INTERNAL_TOKEN", "secret") + + +@responses.activate +def test_get_data_returns_payload_and_hash(): + responses.add( + responses.GET, "http://fetcher:5001/data/alice", + json={"data": {"user": {"login": "alice"}}, "payload_hash": "abc"}, + status=200, + ) + result = fc.get_data("alice") + assert result["payload_hash"] == "abc" + assert result["data"]["user"]["login"] == "alice" + + +@responses.activate +def test_get_data_sends_auth_header(): + responses.add(responses.GET, "http://fetcher:5001/data/alice", + json={"data": {}, "payload_hash": "h"}, status=200) + fc.get_data("alice") + assert responses.calls[0].request.headers["X-Internal-Token"] == "secret" + + +@responses.activate +def test_force_fetch(): + responses.add(responses.POST, "http://fetcher:5001/fetch", + json={"stored": True, "payload_hash": "new", "changed": True}, status=200) + r = fc.force_fetch("alice") + assert r["changed"] is True diff --git a/generator/tests/test_placeholder.py b/generator/tests/test_placeholder.py new file mode 100644 index 0000000..3389c27 --- /dev/null +++ b/generator/tests/test_placeholder.py @@ -0,0 +1,25 @@ +from src import placeholder + + +def test_building_contains_username_and_svg_tag(): + svg = placeholder.render("building", "alice", theme="dark") + assert svg.startswith("" in svg + assert "alice" in svg + assert "Building" in svg or "building" in svg.lower() + + +def test_rate_limited_variant(): + svg = placeholder.render("rate_limited", "alice", theme="dark") + assert "tomorrow" in svg.lower() or "try again" in svg.lower() + + +def test_not_found_variant(): + svg = placeholder.render("not_found", "ghost", theme="dark") + assert "ghost" in svg + assert "doesn't exist" in svg or "not found" in svg.lower() + + +def test_unknown_variant_raises(): + import pytest + with pytest.raises(ValueError): + placeholder.render("bogus", "alice", theme="dark") diff --git a/generator/tests/test_worker.py b/generator/tests/test_worker.py new file mode 100644 index 0000000..f54656b --- /dev/null +++ b/generator/tests/test_worker.py @@ -0,0 +1,58 @@ +import os, tempfile, pytest +from unittest.mock import patch, MagicMock +from src import db as dbmod +from src import worker + + +@pytest.fixture +def tmp_dbs(monkeypatch): + with tempfile.TemporaryDirectory() as d: + monkeypatch.setattr(dbmod, "SETTINGS_DB_PATH", os.path.join(d, "s.db")) + monkeypatch.setattr(dbmod, "WIDGETS_DB_PATH", os.path.join(d, "w.db")) + dbmod.init_dbs() + yield d + + +def test_process_one_renders_and_stores_widgets(tmp_dbs): + dbmod.enroll("alice", {"theme": "dark", "enabled": ["grade"]}) + fake_payload = {"user": {"login": "alice"}, "repos": [], "events": [], + "commits": [], "total_commits": 0, "recent_commits": [], + "total_prs": 0, "collaborators_data": [], "avatar_b64": ""} + with patch("src.worker.fetcher_client.get_data", + return_value={"data": fake_payload, "payload_hash": "h1"}), \ + patch("src.worker._render_widgets", + return_value={"composite": "c", "grade": "g"}): + worker.process_one() + svg = dbmod.get_current_widget("alice", "composite") + assert svg == "c" + + +def test_not_found_payload_renders_not_found_placeholder(tmp_dbs): + dbmod.enroll("ghost", {"theme": "dark"}) + with patch("src.worker.fetcher_client.get_data", + return_value={"data": {"error": "not_found"}, "payload_hash": "x"}): + worker.process_one() + svg = dbmod.get_current_widget("ghost", "composite") + assert svg and "ghost" in svg + + +def test_worker_retries_on_fetcher_failure(tmp_dbs): + dbmod.enroll("alice", {"theme": "dark"}) + with patch("src.worker.fetcher_client.get_data", side_effect=RuntimeError("boom")): + worker.process_one() + with dbmod._settings_conn() as c: + row = c.execute("SELECT status, attempts, last_error FROM jobs WHERE username='alice'").fetchone() + assert row["status"] == "pending" + assert row["attempts"] == 1 + assert "boom" in row["last_error"] + + +def test_worker_marks_failed_after_max_attempts(tmp_dbs): + dbmod.enroll("alice", {"theme": "dark"}) + with patch("src.worker.fetcher_client.get_data", side_effect=RuntimeError("boom")): + for _ in range(4): + worker.process_one() + with dbmod._settings_conn() as c: + row = c.execute("SELECT status, attempts FROM jobs WHERE username='alice'").fetchone() + assert row["status"] == "failed" + assert row["attempts"] >= 3 diff --git a/run.py b/run.py deleted file mode 100644 index 25ba53f..0000000 --- a/run.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python3 -""" -Entry point for running the GitHub profile widget generator. -Run this from the project root directory. -""" - -import sys -from src.generate import main - -if __name__ == "__main__": - main() diff --git a/src/README.md b/src/README.md deleted file mode 100644 index afd41c8..0000000 --- a/src/README.md +++ /dev/null @@ -1,112 +0,0 @@ -# GitHub Profile Widget Generator - -A modular system for generating polished SVG widgets from GitHub profile data. - -## Project Structure - -``` -src/ -├── models/ # Data classes and types -│ ├── __init__.py -│ └── types.py # Widget data models -│ -├── themes/ # Color schemes and styling -│ ├── __init__.py -│ └── themes.py # Theme definitions -│ -├── widgets/ # Widget rendering modules -│ ├── __init__.py -│ ├── grade.py # Developer grade widget -│ ├── impact.py # Impact timeline chart -│ ├── collaborators.py # Top collaborators -│ ├── focus.py # Focus areas bars -│ ├── languages.py # Languages donut chart -│ ├── achievements.py # Achievements list -│ └── composite.py # Full widget composer -│ -├── data/ # Data fetching and processing -│ ├── __init__.py -│ ├── fetcher.py # GitHub API client -│ └── processor.py # Data transformation -│ -├── utils/ # Helper functions -│ ├── __init__.py -│ └── svg_helpers.py # SVG utilities -│ -└── generate.py # Main CLI entry point -``` - -## Usage - -Run from the project root directory: - -```bash -# Generate widgets for a user -python run.py [theme] - -# Or run as a module -python -m src.generate [theme] - -# With GitHub token for higher rate limits -GITHUB_TOKEN=your_token python run.py - -# Use light theme -python run.py light -``` - -## Extending - -### Adding a New Widget - -1. Create a new file in `widgets/` (e.g., `widgets/my_widget.py`) -2. Implement `render_my_widget(data, theme_name="dark") -> str` -3. Add to `widgets/__init__.py` exports -4. Update `data/processor.py` to include it in `generate_widgets_from_github()` - -### Adding a New Theme - -1. Add theme definition to `themes/themes.py` -2. Use the theme name when calling `generate_full_widget(theme="my_theme")` - -## Configuration - -Customize behavior via environment variables: - -```bash -# Collaborator settings -export COLLABORATOR_MIN_COMMITS=10 # Min commits to be a collaborator (default: 10) -export COLLABORATOR_MAX_REPO_SIZE=100 # Skip repos with 100+ contributors (default: 100) -export COLLABORATOR_TOP_REPOS=5 # Check top N repos for collaborators (default: 5) - -# Commit fetching -export COMMIT_MAX_REPOS=10 # Fetch commits from top N repos (default: 10) -export COMMIT_PER_REPO=30 # Commits per repo (default: 30) - -# API settings -export API_TIMEOUT=5 # Request timeout in seconds (default: 5) - -# Run with custom settings -COLLABORATOR_MIN_COMMITS=15 python run.py username -``` - -## How Collaborators Are Detected - -The widget finds **meaningful collaborators** by: - -1. **Identifying shared repositories**: Looks at repos where the user has committed -2. **Fetching contributors**: Gets all contributors from those repos -3. **Applying thresholds**: - - Only includes contributors with 10+ commits (configurable) - - Filters out huge OSS projects (100+ contributors) - - Focuses on user's top 5 most active repos -4. **Ranking by collaboration**: Sorts by total shared commits across all repos - -This ensures collaborators are people you've actually worked with closely, not random contributors from large open-source projects. - -## Development - -All widgets follow the same pattern: -- Accept data models from `models/` -- Use themes from `themes/` -- Return SVG strings -- Use `utils.card_wrapper()` for consistent styling diff --git a/src/__init__.py b/src/__init__.py deleted file mode 100644 index 6048aec..0000000 --- a/src/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -"""GitHub Profile Widget Generator package.""" - -__version__ = "1.0.0" diff --git a/src/data/__init__.py b/src/data/__init__.py deleted file mode 100644 index b02fcbc..0000000 --- a/src/data/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -"""Data fetching and processing for GitHub profiles. - -Note: ``fetch_github_data`` is intentionally NOT re-exported from this package -so that importing :mod:`src.data.processor` (used by the generator service) -does not transitively pull in the fetcher module and its ``requests`` dependency. -Import it directly from ``src.data.fetcher`` when you need it. -""" - -from .processor import ( - compute_grade, - compute_impact_timeline, - compute_collaborators, - compute_focus, - compute_languages, - generate_widgets_from_github, -) - -__all__ = [ - "compute_grade", - "compute_impact_timeline", - "compute_collaborators", - "compute_focus", - "compute_languages", - "generate_widgets_from_github", -] diff --git a/src/db/__init__.py b/src/db/__init__.py deleted file mode 100644 index 3148665..0000000 --- a/src/db/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -from .repository import ( - DB_PATH, - DUMMY_USERNAME, - init_db, - upsert_user, - get_user, - delete_user, - list_users, - seed_dummy_user, - REQUIRED_FIELDS, -) - -__all__ = [ - "DB_PATH", - "DUMMY_USERNAME", - "init_db", - "upsert_user", - "get_user", - "delete_user", - "list_users", - "seed_dummy_user", - "REQUIRED_FIELDS", -] diff --git a/src/db/dummy_seed.py b/src/db/dummy_seed.py deleted file mode 100644 index 6d8eceb..0000000 --- a/src/db/dummy_seed.py +++ /dev/null @@ -1,115 +0,0 @@ -"""Hand-written dummy user payload. - -Shape matches what ``fetch_github_data`` returns, so the generator's processor -code runs unchanged against it. Used as the fallback whenever a requested user -is missing from the DB or has incomplete data. -""" - -from datetime import datetime, timedelta - - -def _recent_iso(days_ago: int) -> str: - return (datetime.utcnow() - timedelta(days=days_ago)).strftime("%Y-%m-%dT%H:%M:%SZ") - - -def _daily_commits() -> list[dict]: - out = [] - for i in range(0, 180, 2): - date = (datetime.utcnow() - timedelta(days=i)).strftime("%Y-%m-%d") - out.append({"date": date, "count": 3 + (i % 5)}) - return out - - -DUMMY_PAYLOAD: dict = { - "user": { - "login": "octocat", - "name": "Demo Developer", - "followers": 120, - "following": 40, - "public_repos": 24, - "avatar_url": "", - "created_at": "2018-01-15T00:00:00Z", - }, - "repos": [ - { - "id": 1, "name": "stellar-api", "full_name": "octocat/stellar-api", - "language": "Python", "stargazers_count": 310, "forks_count": 42, - "pushed_at": _recent_iso(3), "topics": ["backend", "api", "fastapi"], - "size": 2400, - }, - { - "id": 2, "name": "pixel-ui", "full_name": "octocat/pixel-ui", - "language": "TypeScript", "stargazers_count": 180, "forks_count": 19, - "pushed_at": _recent_iso(6), "topics": ["frontend", "react", "design-system"], - "size": 1800, - }, - { - "id": 3, "name": "nimbus-infra", "full_name": "octocat/nimbus-infra", - "language": "Go", "stargazers_count": 95, "forks_count": 12, - "pushed_at": _recent_iso(10), "topics": ["devops", "kubernetes", "terraform"], - "size": 1100, - }, - { - "id": 4, "name": "ml-playground", "full_name": "octocat/ml-playground", - "language": "Jupyter Notebook", "stargazers_count": 64, "forks_count": 8, - "pushed_at": _recent_iso(14), "topics": ["ml", "pytorch"], - "size": 900, - }, - { - "id": 5, "name": "dotfiles", "full_name": "octocat/dotfiles", - "language": "Shell", "stargazers_count": 22, "forks_count": 3, - "pushed_at": _recent_iso(20), "topics": [], "size": 120, - }, - { - "id": 6, "name": "rustle", "full_name": "octocat/rustle", - "language": "Rust", "stargazers_count": 48, "forks_count": 5, - "pushed_at": _recent_iso(30), "topics": ["systems", "cli"], "size": 450, - }, - { - "id": 7, "name": "web-playground", "full_name": "octocat/web-playground", - "language": "JavaScript", "stargazers_count": 30, "forks_count": 4, - "pushed_at": _recent_iso(40), "topics": ["frontend"], "size": 380, - }, - { - "id": 8, "name": "notes-app", "full_name": "octocat/notes-app", - "language": "TypeScript", "stargazers_count": 15, "forks_count": 2, - "pushed_at": _recent_iso(55), "topics": ["frontend"], "size": 260, - }, - ], - "events": [ - {"type": "PushEvent", "created_at": _recent_iso(1), - "actor": {"login": "octocat"}, "repo": {"name": "octocat/stellar-api"}, - "payload": {"commits": [{"sha": "abc"}, {"sha": "def"}]}}, - {"type": "PullRequestEvent", "created_at": _recent_iso(2), - "actor": {"login": "octocat"}, "repo": {"name": "octocat/pixel-ui"}, - "payload": {}}, - {"type": "PushEvent", "created_at": _recent_iso(4), - "actor": {"login": "octocat"}, "repo": {"name": "octocat/nimbus-infra"}, - "payload": {"commits": [{"sha": "ghi"}]}}, - ], - "commits": _daily_commits(), - "total_commits": 2450, - "recent_commits": 680, - "total_prs": 180, - "collaborators_data": [ - { - "login": "alice-dev", "avatar_url": "", - "raw_score": 220.0, "shared_repos": 3, "final_score": 660.0, - "repos": ["octocat/stellar-api", "octocat/pixel-ui", "octocat/nimbus-infra"], - "tight_owned_partner": True, - }, - { - "login": "bob-builder", "avatar_url": "", - "raw_score": 140.0, "shared_repos": 2, "final_score": 280.0, - "repos": ["octocat/stellar-api", "octocat/ml-playground"], - "tight_owned_partner": False, - }, - { - "login": "carol-codes", "avatar_url": "", - "raw_score": 95.0, "shared_repos": 2, "final_score": 190.0, - "repos": ["octocat/pixel-ui", "octocat/web-playground"], - "tight_owned_partner": False, - }, - ], - "avatar_b64": "", -} diff --git a/src/db/repository.py b/src/db/repository.py deleted file mode 100644 index 273ecf2..0000000 --- a/src/db/repository.py +++ /dev/null @@ -1,135 +0,0 @@ -"""SQLite repository: the only communication channel between fetcher and generator. - -Stores each user's fetched GitHub payload as a JSON blob in a single table. -The generator reads from here; the fetcher writes to here. Neither imports the -other. -""" - -import json -import os -import sqlite3 -from datetime import datetime -from typing import Optional - -_PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) -DB_PATH = os.environ.get( - "GHSTATS_DB_PATH", - os.path.join(_PROJECT_ROOT, "data", "ghstats.db"), -) - -DUMMY_USERNAME = "__dummy__" - -# Fields the generator considers load-bearing. If any is missing from a row, -# the generator treats the row as unusable and falls back to the dummy user. -REQUIRED_FIELDS = ( - "user", - "repos", - "events", - "commits", - "total_commits", - "recent_commits", - "total_prs", - "collaborators_data", - "avatar_b64", -) - -SCHEMA_SQL = """ -CREATE TABLE IF NOT EXISTS users ( - username TEXT PRIMARY KEY, - data_json TEXT NOT NULL, - is_dummy INTEGER NOT NULL DEFAULT 0, - updated_at TEXT NOT NULL -); -""" - - -def _connect() -> sqlite3.Connection: - os.makedirs(os.path.dirname(DB_PATH), exist_ok=True) - conn = sqlite3.connect(DB_PATH) - conn.row_factory = sqlite3.Row - return conn - - -def init_db() -> None: - """Create the schema and seed the dummy user if missing.""" - with _connect() as conn: - conn.executescript(SCHEMA_SQL) - conn.commit() - seed_dummy_user(conn=conn) - - -def upsert_user(username: str, data: dict, conn: Optional[sqlite3.Connection] = None) -> None: - payload = json.dumps(data) - now = datetime.utcnow().isoformat(timespec="seconds") + "Z" - sql = """ - INSERT INTO users (username, data_json, is_dummy, updated_at) - VALUES (?, ?, 0, ?) - ON CONFLICT(username) DO UPDATE SET - data_json = excluded.data_json, - is_dummy = 0, - updated_at = excluded.updated_at - """ - if conn is None: - with _connect() as c: - c.execute(sql, (username, payload, now)) - c.commit() - else: - conn.execute(sql, (username, payload, now)) - conn.commit() - - -def get_user(username: str) -> Optional[dict]: - """Return the stored GitHub-data dict for a user, or None if not present.""" - with _connect() as conn: - row = conn.execute( - "SELECT data_json FROM users WHERE username = ?", - (username,), - ).fetchone() - if row is None: - return None - return json.loads(row["data_json"]) - - -def delete_user(username: str) -> bool: - if username == DUMMY_USERNAME: - return False - with _connect() as conn: - cur = conn.execute("DELETE FROM users WHERE username = ?", (username,)) - conn.commit() - return cur.rowcount > 0 - - -def list_users() -> list[dict]: - with _connect() as conn: - rows = conn.execute( - "SELECT username, is_dummy, updated_at FROM users ORDER BY username" - ).fetchall() - return [dict(r) for r in rows] - - -def seed_dummy_user(conn: Optional[sqlite3.Connection] = None) -> None: - """Insert (or replace) the __dummy__ row using an explicit hand-written payload. - - This is the fallback the generator uses whenever a requested user is missing - or has incomplete data. Kept deliberately plausible so every widget has - something to render. - """ - from .dummy_seed import DUMMY_PAYLOAD - - payload = json.dumps(DUMMY_PAYLOAD) - now = datetime.utcnow().isoformat(timespec="seconds") + "Z" - sql = """ - INSERT INTO users (username, data_json, is_dummy, updated_at) - VALUES (?, ?, 1, ?) - ON CONFLICT(username) DO UPDATE SET - data_json = excluded.data_json, - is_dummy = 1, - updated_at = excluded.updated_at - """ - if conn is None: - with _connect() as c: - c.execute(sql, (DUMMY_USERNAME, payload, now)) - c.commit() - else: - conn.execute(sql, (DUMMY_USERNAME, payload, now)) - conn.commit() diff --git a/src/fetcher_api.py b/src/fetcher_api.py deleted file mode 100644 index db7352d..0000000 --- a/src/fetcher_api.py +++ /dev/null @@ -1,78 +0,0 @@ -"""Flask API for the fetcher service. - -Pulls data from the GitHub API and writes it to the shared SQLite database. -Does not render anything. Runs independently from the generator. - - python -m src.fetcher_api # serves on :5001 - -Endpoints: - GET /health - POST /fetch {username, token?} -> fetches + upserts - GET /users -> list stored usernames - GET /users/ -> full stored payload -""" - -import os -from flask import Flask, jsonify, request - -from .data.fetcher import fetch_github_data -from .db import init_db, upsert_user, get_user, list_users, DUMMY_USERNAME - - -app = Flask(__name__) - - -@app.route("/health", methods=["GET"]) -def health(): - return jsonify({"status": "ok", "service": "fetcher"}) - - -@app.route("/fetch", methods=["POST"]) -def fetch(): - body = request.get_json(silent=True) or {} - username = body.get("username") - if not username: - return jsonify({"error": "username is required"}), 400 - if username == DUMMY_USERNAME: - return jsonify({"error": "cannot overwrite dummy user"}), 400 - - token = body.get("token") or os.environ.get("GITHUB_PAT") - - try: - data = fetch_github_data(username, token) - except Exception as e: - return jsonify({"error": f"fetch failed: {e}"}), 502 - - if not data.get("user") or data["user"].get("message") == "Not Found": - return jsonify({"error": f"github user '{username}' not found"}), 404 - - upsert_user(username, data) - return jsonify({ - "username": username, - "stored": True, - "total_commits": data.get("total_commits", 0), - "repos": len(data.get("repos", [])), - }) - - -@app.route("/users", methods=["GET"]) -def users_list(): - return jsonify(list_users()) - - -@app.route("/users/", methods=["GET"]) -def users_get(username: str): - data = get_user(username) - if data is None: - return jsonify({"error": "not found"}), 404 - return jsonify(data) - - -def main(): - init_db() - port = int(os.environ.get("FETCHER_PORT", "5001")) - app.run(host="0.0.0.0", port=port, debug=False) - - -if __name__ == "__main__": - main() diff --git a/src/generate.py b/src/generate.py deleted file mode 100644 index 2fde4f2..0000000 --- a/src/generate.py +++ /dev/null @@ -1,140 +0,0 @@ -#!/usr/bin/env python3 -""" -GitHub Profile Widget Generator -Generates polished SVG mini-widgets from GitHub profile data. -""" - -import sys -import os -from typing import Optional - -from .models import AchievementData -from .data.fetcher import fetch_github_data -from .data.processor import generate_widgets_from_github -from .widgets import render_achievements_widget, compose_widget - - -def generate_full_widget( - username: str, - token: Optional[str] = None, - theme: str = "dark", - enabled: Optional[list[str]] = None, - widget_order: Optional[list[str]] = None, - achievements: Optional[list[AchievementData]] = None, - custom_tags: Optional[list[str]] = None, - hidden_languages: Optional[list[str]] = None, -) -> str: - """ - Generate a complete profile widget for a GitHub user. - - Args: - username: GitHub username - token: GitHub API token - theme: Color theme name - enabled: List of widgets to include (None = use config default) - widget_order: Order of widgets (None = use config default) - achievements: Custom achievements to display - custom_tags: Custom tags to add to grade widget (e.g., ["open-source", "hackathon-winner"]) - hidden_languages: Languages to exclude from stats (e.g., ["HTML", "CSS"]) - """ - from .config import ENABLED_WIDGETS, WIDGET_ORDER, HIDDEN_LANGUAGES - - if enabled is None: - enabled = ENABLED_WIDGETS - - if widget_order is None: - widget_order = WIDGET_ORDER - - if hidden_languages is None: - hidden_languages = HIDDEN_LANGUAGES - - print(f"Fetching GitHub data for {username}...") - github_data = fetch_github_data(username, token) - - # Log contribution counts - total_commits = github_data.get("total_commits", 0) - recent_commits = github_data.get("recent_commits", 0) - total_prs = github_data.get("total_prs", 0) - daily_commits = len(github_data.get("commits", [])) - - if total_commits > 0: - print(f" Total contributions (all-time): {total_commits:,}") - print(f" Recent contributions (6 months): {recent_commits:,}") - print(f" Total PRs (all-time): {total_prs:,}") - print(f" Daily contribution data points: {daily_commits}") - else: - print(f" Warning: Could not fetch contribution count") - if daily_commits == 0: - print(f" Try running with GITHUB_PAT environment variable") - - print("Generating widgets...") - widgets = generate_widgets_from_github( - github_data, - theme, - custom_tags=custom_tags, - hidden_languages=hidden_languages, - enabled=enabled, - ) - - if achievements and "achievements" in enabled: - widgets["achievements"] = render_achievements_widget( - achievements, theme - ) - - # Save individual widgets - for name, svg in widgets.items(): - if svg: - with open(f"widget_{name}.svg", "w") as f: - f.write(svg) - print(f" Saved widget_{name}.svg") - - print("Composing final widget...") - # Order widgets according to widget_order - ordered_enabled = [w for w in widget_order if w in enabled and w in widgets and widgets[w]] - - composite = compose_widget( - widgets=widgets, - enabled=ordered_enabled, - theme_name=theme, - username=username, - avatar_b64=github_data.get("avatar_b64", ""), - ) - - with open(f"widget_{username}.svg", "w") as f: - f.write(composite) - print(f" Saved widget_{username}.svg") - - return composite - - -def main(): - """CLI entry point.""" - username = sys.argv[1] if len(sys.argv) > 1 else "shaymanor" - token = os.environ.get("GITHUB_PAT") - theme = sys.argv[2] if len(sys.argv) > 2 else "dark" - - if username: - achievements = [ - AchievementData( - "MIT IQuHACK Winner", - "1st Place · Quantum Track", - "2025-01", - "trophy", - ), - AchievementData( - "MLH Top 50", "Global Hackathon League", "2025", "medal" - ), - ] - - # Example custom tags - uncomment to add custom badges - # custom_tags = ["open-source", "hackathon-winner", "quantum-computing"] - custom_tags = ["Testing"] - - generate_full_widget(username, token, theme, achievements=achievements, custom_tags=custom_tags) - else: - print("Usage: python generate.py [theme]") - sys.exit(1) - - -if __name__ == "__main__": - main() diff --git a/src/generator_api.py b/src/generator_api.py deleted file mode 100644 index db749b1..0000000 --- a/src/generator_api.py +++ /dev/null @@ -1,149 +0,0 @@ -"""Flask API for the generator service. - -Reads previously-fetched data from the shared SQLite database and renders -SVG widgets. Never calls the fetcher — if the requested user is missing or -has incomplete data, it falls back to the __dummy__ user seeded in the DB. - - python -m src.generator_api # serves on :5002 - -Endpoints: - GET /health - POST /generate {username, theme?, widgets?, widget_order?, - custom_tags?, hidden_languages?, format?} - -> SVG string (format=svg, default) or - JSON {widgets: {...}, composite, used_dummy} -""" - -import os -from flask import Flask, jsonify, request, Response - -from .db import init_db, get_user, DUMMY_USERNAME, REQUIRED_FIELDS -from .data.processor import generate_widgets_from_github -from .models import AchievementData -from .widgets import compose_widget, render_achievements_widget -from .config import ENABLED_WIDGETS, WIDGET_ORDER - - -app = Flask(__name__) - - -def _load_with_fallback(username: str) -> tuple[dict, bool]: - """Return (github_data, used_dummy). - - If the row is missing or is missing any REQUIRED_FIELDS, swap in the dummy - payload wholesale (no partial merging). - """ - data = get_user(username) - if data is None or any(f not in data for f in REQUIRED_FIELDS): - dummy = get_user(DUMMY_USERNAME) - if dummy is None: - raise RuntimeError("dummy user missing from database; run init_db") - return dummy, True - return data, False - - -@app.route("/health", methods=["GET"]) -def health(): - return jsonify({"status": "ok", "service": "generator"}) - - -@app.route("/generate", methods=["POST"]) -def generate(): - body = request.get_json(silent=True) or {} - username = body.get("username") - if not username: - return jsonify({"error": "username is required"}), 400 - - theme = body.get("theme", "dark") - enabled = body.get("widgets") or ENABLED_WIDGETS - widget_order = body.get("widget_order") or WIDGET_ORDER - custom_tags = body.get("custom_tags") - hidden_languages = body.get("hidden_languages") - achievements_raw = body.get("achievements") or [] - widget_settings = body.get("widget_settings") or {} - fmt = body.get("format", "svg") - - github_data, used_dummy = _load_with_fallback(username) - - widgets = generate_widgets_from_github( - github_data, - theme=theme, - custom_tags=custom_tags, - hidden_languages=hidden_languages, - enabled=enabled, - widget_settings=widget_settings, - ) - - # Render achievements if provided and enabled - if "achievements" in enabled and achievements_raw: - achs = [ - AchievementData( - title=a.get("title", ""), - subtitle=a.get("subtitle", ""), - event_date=a.get("event_date", ""), - icon=a.get("icon", "trophy"), - ) - for a in achievements_raw - if a.get("title") - ] - if achs: - widgets["achievements"] = render_achievements_widget(achs, theme, settings=widget_settings.get("achievements")) - - ordered = [w for w in widget_order if w in enabled and w in widgets and widgets[w]] - display_name = username if not used_dummy else username - composite = compose_widget( - widgets=widgets, - enabled=ordered, - theme_name=theme, - username=display_name, - avatar_b64=github_data.get("avatar_b64", ""), - ) - - if fmt == "data": - # Return raw computed data for client-side rendering - from .data.processor import ( - compute_grade, compute_impact_timeline, - compute_collaborators, compute_focus, compute_languages, - ) - raw = {} - if "grade" in enabled: - g = compute_grade(github_data, custom_tags=custom_tags) - raw["grade"] = {"grade": g.grade, "score": g.score, "stats": g.stats, - "tags": [{"tag": t.tag, "source": t.source, "confidence": t.confidence} for t in g.tags], - "breakdown": g.breakdown} - if "impact" in enabled: - raw["impact"] = [{"week_start": w.week_start, "commits": w.commits} - for w in compute_impact_timeline(github_data)] - if "collaborators" in enabled: - raw["collaborators"] = [{"username": c.username, "shared_repos": c.shared_repos, - "shared_commits": c.shared_commits} - for c in compute_collaborators(github_data)] - if "focus" in enabled: - raw["focus"] = [{"category": f.category, "percentage": f.percentage, - "commit_count": f.commit_count} - for f in compute_focus(github_data, hidden_languages=hidden_languages)] - if "languages" in enabled: - raw["languages"] = [{"language": l.language, "percentage": l.percentage, "loc": l.loc} - for l in compute_languages(github_data, hidden_languages=hidden_languages)] - return jsonify({"username": username, "used_dummy": used_dummy, "data": raw}) - - if fmt == "json": - return jsonify({ - "username": username, - "used_dummy": used_dummy, - "widgets": widgets, - "composite": composite, - }) - - headers = {"X-Used-Dummy": "1" if used_dummy else "0"} - return Response(composite, mimetype="image/svg+xml", headers=headers) - - -def main(): - init_db() - port = int(os.environ.get("GENERATOR_PORT", "5002")) - app.run(host="0.0.0.0", port=port, debug=False) - - -if __name__ == "__main__": - main() diff --git a/widget_shaymanor.svg b/widget_shaymanor.svg deleted file mode 100644 index 28cfa93..0000000 --- a/widget_shaymanor.svg +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - shaymanor - - - - - - - - - Generated with ♥ - \ No newline at end of file