Skip to content

Architecture Overview

Pokékon is a Pokémon-TCG meta dashboard that helps competitive players track their own games, analyze the tournament meta, and improve both deck and play.

The system is a local-first React SPA backed by a Hono + PostgreSQL service. The web app started fully local-first (all data in the browser via IndexedDB) and is now migrating toward the server as the source of truth. Both layers coexist today — see Data Persistence — and the direction is set in backend-evolution-plan.md.

Earlier revisions of this document described the app as a “zero-backend SPA.” That is no longer accurate: a Hono + Drizzle + PostgreSQL backend (apps/api) with Better Auth runs on Railway and is being expanded from CRUD/auth into the analytics backend. This page reflects the real two-app architecture.


npm-workspace monorepo (pokekon):

Workspace Stack Role
apps/web React 19 · Vite · Zustand · Dexie (IndexedDB) · TanStack Query local-first frontend; still holds most analysis logic
apps/api Hono · Drizzle ORM · PostgreSQL · Better Auth runs on Railway; migrating from CRUD/auth toward analytics backend
apps/docs Astro · Starlight this living documentation site (static, GitHub Pages)

Layer Library / Tool
UI framework React 19
Build tool Vite 8
Language TypeScript ~6
State management Zustand 5
Local database Dexie (IndexedDB) 4
Server-state caching TanStack Query 5
Auth client better-auth
i18n i18next / react-i18next
Charts Recharts 3
Icons Lucide React
CSS Tailwind CSS 3
Layer Library / Tool
HTTP framework Hono 4 (@hono/node-server)
ORM Drizzle ORM
Database PostgreSQL (pg)
Auth Better Auth + @better-auth/drizzle-adapter
Transactional email Resend (password reset)
Validation Zod 4
Migrations Drizzle Kit (db:generate / db:migrate)
Hosting Railway

flowchart TD
subgraph Browser["Browser — apps/web (React SPA)"]
UI["Pages & Components"]
Store["dashboardStore (Zustand)"]
Logic["src/lib (analysis logic)<br/>metaFetch · deckComparison<br/>deckPerformanceStats · deckImport"]
ApiClient["api.ts (typed REST client)"]
Dexie["Dexie / IndexedDB<br/>(local-first store)"]
end
subgraph Server["Railway — apps/api (Hono)"]
Health["/health (DB-free)"]
AuthH["/api/auth/* (Better Auth)"]
ApiRoutes["/api/decks · /api/snapshots · /api/logs<br/>/api/analytics · /api/analysis<br/>/api/meta · /api/demo · /api/preferences<br/>(session-guarded)"]
AiLayer["ai/ provider abstraction<br/>(GitHub Models adapter)"]
Static["Static serving of built SPA<br/>(single-origin)"]
Drizzle["Drizzle ORM"]
end
subgraph Data["Data"]
PG[("PostgreSQL")]
end
subgraph External["External"]
LimitlessAPI["Limitless TCG API"]
CORSProxy["corsproxy.io (legacy fallback)"]
LLMProvider["LLM provider API<br/>(GitHub Models)"]
end
UI --> Store
Store --> ApiClient
Store --> Dexie
Store --> Logic
ApiClient -->|"fetch, credentials: include"| ApiRoutes
ApiClient -->|sign-in / session| AuthH
Static -.serves.-> UI
ApiRoutes --> Drizzle
ApiRoutes -->|battle-log analysis| AiLayer
AiLayer -->|"server-side, BYOK key"| LLMProvider
AuthH --> Drizzle
Drizzle --> PG
Logic -->|legacy, browser-side| LimitlessAPI
Logic --> CORSProxy

Dashed arrow: in production the API process also serves the built web app, so the Better Auth session cookie stays first-party (single origin).


createApp() (app.ts) is a Hono app factory. Creating the app needs no database: /health is fully DB-free and both the Better Auth handler and the pg pool are initialized lazily on the first matching /api request.

Registration order matters:

  1. CORS (hono/cors) with credentials: true, origin = webOrigin — must be first (Better Auth requirement). Relevant only for split-origin deployments.
  2. GET /health — liveness check.
  3. /api/auth/* — handed to the Better Auth handler before the guarded sub-app so sign-in works without an existing session.
  4. Guarded /api sub-app — a sessionMiddleware runs first, then db is injected into the context, then the domain routes mount: /api/decks, /api/snapshots, /api/logs, /api/analytics, /api/analysis, /api/meta (server meta snapshots), /api/demo (guest/demo mode), /api/preferences (per-user app preferences: active archetype, last active deck per archetype).

Battle-log pipeline & analytics — POST /api/logs parses the log server-side once on write into match_log_parsed (plan §4); GET /api/analytics/deck/:id?weeks= reads the turn-quality aggregates. See data-flow.md.

LLM analysis (ai/): a provider-agnostic AnalysisProvider abstraction (GitHub Models adapter today) powers POST /api/analysis/log. The per-user API key is stored AES-256-GCM-encrypted (lib/crypto.ts, key from ENCRYPTION_KEY) in user_ai_settings and only decrypted server-side — never sent to the browser. Anti-hallucination (verbatim evidence, temperature=0) lives in the shared engine so every provider is grounded.

Auth (auth.ts): Better Auth with the Drizzle adapter (provider: 'pg'). Email + password is always on (password reset emails via Resend, email.ts); Google OAuth turns on when GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET are present.

Single-origin deployment (static.ts): the API process serves the built web SPA (apps/web/dist, overridable via WEB_DIST_PATH), so the browser talks to exactly one origin for both the app shell and /api/* and the session cookie remains first-party.

Secrets (DATABASE_URL, Better-Auth secret, Resend key, ENCRYPTION_KEY for per-user LLM keys) are Railway variables — never in the browser bundle. User LLM keys themselves are BYOK: entered by the user, stored encrypted, server-side only.


App.tsx renders one of two layouts, chosen once per page load by the archetypeCoachUi flag (§Feature flags). Flag on: components/coach/CoachLayout (Spec 7) — .coach-ui root, sprite background, CoachSidebar (desktop: Start · Deck · Coaching · Opponents · Tools + account area), CoachHeader (red brand band with yellow edge: archetype switcher, active-list chip, mobile menu with Tools + account instead of the floating avatar chip), CoachBottomNav (mobile: [Start, Deck] · + paste a log · [Coaching, Opponents]) and one lazily loaded page from pages/coach/ per store.coachTab. Onboarding gate: no archetype and preferences ready → OnboardingFlow; while preferences load, before the first refresh, or for a demo guest without decks (seed in flight) → skeleton; a failed preferences load keeps the pages usable with a retry hint. The header’s switcher opens the onboarding in switchArchetype mode. Flag off (unchanged): Sidebar + BottomNav and one page based on store.activeTab (overview · deck · meta) — the match log has no top-level tab of its own. Within DeckPage, opponent-log functionality is not its own section either (plan personal-data-role-rework.md §3.8): the page has two co-equal sections (Deck List / Analytics), a small always-visible “Log match” button opens AddLogModal from either, and the log list itself is an initially-collapsed section at the end of Analytics (OpponentLog with chrome="bare", nested in a CollapsibleSection) — demoting the area, not the logging action.

apps/web/src/lib/featureFlags.ts — client-side runtime flags. Currently one flag, archetypeCoachUi, gating the archetype-first UI of specs/archetype-first-ui.md (Spec 7 Scheibe 1–2). Resolution order: ?ff=archetypeCoachUi in the URL (turns it on and remembers it in localStorage pokekon-ff-archetypeCoachUi) or ?ff=-archetypeCoachUi (turns it off and forgets it) > localStorage > build-time VITE_FF_ARCHETYPE_COACH_UI (exactly "true") > off. Evaluated once per page load via isArchetypeCoachUiEnabled(). Web and API ship as one Railway service, so the per-browser override lets the new UI be tried in production without switching it on for everyone. A pure UI switch, not a security boundary — the API remains the authority for all data.

Archetype-first UI (Spec 7, in progress behind archetypeCoachUi)

Section titled “Archetype-first UI (Spec 7, in progress behind archetypeCoachUi)”

Building blocks shared by the coach layout (specs/archetype-first-ui.md, plan .claude/plans/archetype-first-ui.md):

  • components/coach/ArchetypeSwitcherButton — header control: icon + name of the coached archetype (or “choose archetype”), opens the archetype switch.
  • components/coach/ActiveListChip — header chip with the active list and its newest snapshot label; opens Deck › My lists (where “copy for TCG Live” lives).
  • components/auth/AccountPanel — account content (identity, AI settings, sync, language, sign-out, legal links), extracted from MobileAccountSheet so the coach header menu can reuse it. Sync stays available to everyone (no admin role, E16).
  • components/shared/SegmentedTabs — segment bar (≥44 px tabs), used by DeckPage, ArchetypeDetail and the coach Deck page.
  • hooks/useFieldAnalysis(window) — field analysis per meta window with request-key tagging (shared by MetaPage and the coach pages).
  • components/tools/ArchetypeMetaSummary (KPI head + trend) and components/tools/TournamentListsPanel (recommendation · tournament · decklists) — the rest of the former ArchetypeDetail, on the Tools page.
  • components/deck/OtherArchetypeDecks (+ lib/coach/otherDecks.ts) — decks of other archetypes on Deck › My lists; store reassignDeckArchetype(deckId).
  • components/tools/CardStatsPanel + hooks/useArchetypeCardStats — card statistics tool.
  • components/opponents/GlobalFieldPanel — the coached archetype vs the global field (Opponents › Global field), formerly the Matchups tab of ArchetypeDetail.
  • hooks/useArchetypeAnalysis, useArchetypeLists (paged, “load more”), useArchetypeTournaments (own failure domain, [] on error) — the per-archetype reads formerly inside ArchetypeDetail, shared by Opponents and Tools (Spec 7 Scheibe 2). Same request-key pattern; a 404 of the analysis is notInWindow.
  • lib/coach/archetypeName.ts — display name for a slug: curated list → field analysis → own deck → slug.
  • DE/EN key parity for every namespace is guarded by i18n/actionLabels.test.ts (A5).
  • components/coach/onboarding/OnboardingFlow (Spec 7 §5.1, namespace onboarding):
    1. Archetype — first “your archetypes” (valid archetypes of the own decks with their list count, ownDeckArchetypes), then the 10 most-played archetypes of the last 7 days (useFieldAnalysis) with share, plus a search over the field and KNOWN_ARCHETYPES (name or slug); choosing calls setActiveArchetype.
    2. List (skipped when a deck of that archetype exists) — take the meta list (Spec 7 E7: until Spec 5 the medoid of the best cluster from GET /api/analysis/archetype/:id, 90 days, global; disabled with a hint when there are no clusters; lib/coach/onboarding.ts#medoidToParsedCards maps the cards directly — the PTCGL text parser would drop cards without a print), paste my own list (empty deck + ImportDeckModal) or later.
    3. TCG Live name (first run only, skippable) → localStorage tcg-player-name until Spec 8 moves it server-side. Mode switchArchetype reuses steps 1–2 for the header’s archetype switch and can be cancelled. The red strip is the brand surface allowed by theme/noFilledRed.test.ts.
  • Coach pages in pages/coach/: StartPage, DeckHubPage (more follow). Shared deck components got opt-in props for the coach layout, defaults keep the old layout: DeckSwitcher({ archetypeFilter }), DeckAnalyticsPanel({ omitTurnQuality }), DeckTipsSection({ onOpenLocalMeta }); components/deck/DeckSettingsWidget is extracted from DeckPage; the onboarding’s list step is exported as ListSetup.

A single Zustand store (useDashboardStore) owns the data arrays (decks, deckCards, deckSnapshots, opponentLogs, metaSnapshots, archetypeStats, recentTournaments), the active-deck cursor, localStorage-backed preferences, async-operation flags, and UI state. The refresh() action is the single entry point to reload data; mutations end with await get().refresh() to keep the store consistent.

Server-side preferences (Spec 7 §5.1). hydrate() is the initial load once a session exists (App.tsx, and WelcomeScreen after seeding the demo): refresh() → loadPreferences() (GET /api/preferences → activeArchetypeId, activeDeckIdByArchetype, preferencesStatus) → with archetypeCoachUi on, a second refresh(). When the server has no archetype yet, loadPreferences() migrates once: a valid legacy localStorage slug (tcg-deck-arch-slug-v1, deleted only after the migrated value was saved), else the active deck’s archetype, else the newest deck with a valid slug, else null (→ onboarding). This runs for every account, flag on or off — a single extra GET per load (plus at most one PATCH for the migration); nothing changes visibly with the flag off except that the deck comparison now knows the archetype. Active-deck resolution lives in the pure lib/coach/activeDeck.ts: flag off = legacy rule (current deck if it exists, else the first); flag on = remembered deck of the coached archetype → current deck if same archetype → newest deck of that archetype → none. setActiveDeck() remembers the deck per archetype server-side (best effort, never blocks the switch); setActiveArchetype() persists and re-resolves. deckArchSlug is now a derived value (activeArchetypeId ?? '') — which also fixes the deck comparison showing “not set up” for accounts that never had the legacy key. With the flag on and an archetype set, archetypeStats (own record per opponent) is computed from the coached archetype’s decks only (lib/archetypeStats.ts#computeArchetypeStats over logsOfArchetype, Spec 7 AC 4); otherwise it covers all decks. Coach-only UI state: coachTab (start · deck · coaching · opponents · tools), deckView (metaList · myLists), metaWindow (shared meta window, default 30 days, online, Bo1).

graph TD
App --> Sidebar
App --> BottomNav
App --> OverviewPage
App --> DeckPage
App --> MetaPage
OverviewPage --> StatCard
DeckPage --> DeckSwitcher
DeckPage --> MyMatchupsTable["MyMatchupsTable"]
DeckPage --> DeckPanel
DeckPage --> DeckAnalyticsPanel
DeckPage --> DeckTipsSection
DeckPage --> OpponentLog
DeckPage --> SidePanel
DeckPanel --> AddCardModal
DeckPanel --> ImportDeckModal
DeckAnalyticsPanel --> DeckTurnQualityPanel
DeckAnalyticsPanel --> MatchupMatrix_Deck["MatchupMatrix"]
DeckTipsSection --> RecommendationsPanel
DeckTipsSection --> DeckComparisonPanel
DeckTipsSection --> DeckSynthesisPanel
OpponentLog --> AddLogModal
OpponentLog --> MatchDetailModal
OpponentLog --> MatchStatsTab
MetaPage --> LocalMetaPanel
MetaPage --> MatchupMatrix
MetaPage --> TournamentMetaTable["TournamentMetaTable"]
MetaPage --> CollapsibleSection

MetaShareChart, WinRateChart and DeckPerformancePanel exist as files but are rendered nowhere (removed from the tree above; candidates for deletion).

Archetype-first UI (archetypeCoachUi flag on, Spec 7):

graph TD
App --> CoachLayout
CoachLayout --> CoachHeader
CoachLayout --> CoachSidebar
CoachLayout --> CoachBottomNav
CoachLayout --> OnboardingFlow
CoachHeader --> ArchetypeSwitcherButton
CoachHeader --> ActiveListChip
CoachHeader --> HeaderMenuSheet
HeaderMenuSheet --> AccountPanel
CoachSidebar --> AccountPanel
CoachBottomNav --> AddLogModal
CoachLayout --> StartPage
CoachLayout --> DeckHubPage
CoachLayout --> CoachingPage
CoachLayout --> OpponentsPage
CoachLayout --> ToolsPage
DeckHubPage --> DeckSwitcher
DeckHubPage --> DeckPanel
DeckHubPage --> DeckSettingsWidget
DeckHubPage --> DeckAnalyticsPanel
DeckHubPage --> DeckTipsSection
CoachingPage --> OpponentLog
CoachingPage --> DeckTurnQualityPanel
OpponentsPage --> LocalMetaPanel
OpponentsPage --> PredictionPanel
OpponentsPage --> MyMatchupsTable
ToolsPage --> ArchetypeDetail
ToolsPage --> MatchupMatrix
ToolsPage --> EquilibriumPanel

The migration “IndexedDB → API as the source of truth” is in progress, so two stores coexist:

Data Storage Notes
Decks, cards, logs, snapshots PostgreSQL via apps/api server-side source of truth (target state)
Parsed logs, meta snapshots, AI settings PostgreSQL (match_log_parsed, meta_snapshots, user_ai_settings) server-side; see database.md
Decks, cards, logs, snapshots, meta IndexedDB via Dexie (TCGMetaDashboard) local-first store, still authoritative for parts of the app
LLM API key PostgreSQL (user_ai_settings, AES-256-GCM encrypted) BYOK, server-side only — never localStorage
Active archetype, last active deck per archetype PostgreSQL (user_preferences) Spec 7; follows the user across devices
Active deck ID localStorage (tcg-active-deck-id-v3) + per archetype in user_preferences UI preference; the server map is used by the coach layout
Local meta archetypes localStorage (tcg-local-meta-v1) UI preference
Active archetype PostgreSQL (user_preferences) Spec 7; the old localStorage key tcg-deck-arch-slug-v1 is migrated once and deleted
Player name (battle-log parsing) localStorage (tcg-player-name) parser input

The typed client api.ts talks to apps/api with credentials: 'include' (Better Auth session cookie); base URL is VITE_API_URL in split-origin deployments or the empty string for same-origin. It applies a few boundary adapters between the client types and the wire format (DeckSnapshot.cards string ↔ jsonb array, the DeckCard.cardId sentinel, null ↔ undefined for optional log columns).

The meta_snapshots table now exists server-side (plan §5.1), but the sync job that populates it is still the browser-side metaFetch.ts — porting that to a server cron (plan §6.2) is the next migration step.


  • Limitless TCG API — metaFetch.ts and deckComparison.ts fetch directly, falling back to corsproxy.io on CORS/HTTP failure. This browser-side path is legacy: it moves to a server-side cron job (no CORS proxy needed) per plan §6.2. The sync job (jobs/syncMeta.ts) fetches standings and /pairings per tournament; the round pairings are resolved to per-archetype head-to-heads and stored in tournament_matchups — forming an own online-Bo1 matchup matrix. Archetype icons (deck.icons) are persisted in tournament_standings.icons during sync and surfaced as data-driven sprites throughout the Meta tab.
  • Matchup matrix — GET /api/meta/matchups?days&online&bo1 returns a blended matrix: real online-Bo1 head-to-heads from tournament_matchups take precedence over the external TrainerHill CSV wherever there are enough own games; pairs with insufficient own data fall back to TrainerHill. A matchupSource breakdown in the response lets the UI flag real vs approximate coverage.
  • LLM analysis — now server-side and provider-agnostic (ai/, POST /api/analysis/log). The default provider is GitHub Models; the per-user API key is BYOK, stored encrypted server-side and never in the browser bundle (plan §6.3 / CLAUDE.md golden rule 3). The former browser-side battleLogAnalysis.ts has been removed.

The app uses sidebar navigation on medium+ screens and a bottom nav bar on mobile. The main content area is capped at max-w-screen-2xl with p-3 md:p-4 padding, on the light “playmat” surface (#eef3fb, see design-system.md) using Tailwind utilities throughout.

The desktop Sidebar is hidden md:flex, so any global action it hosts must also be reachable on mobile. Sync Live Meta is extracted into the shared SyncControls component: the desktop Sidebar renders it at the foot (unchanged), and the mobile MobileAccountSheet (accessible via the account chip, top right) renders the same block, ensuring every user can reload tournament data regardless of viewport.

In the archetype-first UI (archetypeCoachUi) the sticky CoachHeader replaces the floating avatar chip on mobile; its menu (HeaderMenuSheet) and the desktop CoachSidebar both render AccountPanel (incl. SyncControls). Content is capped at max-w-screen-lg, with bottom padding for the mobile nav.

The UI is a light, playful, WCAG-AA theme — white “cards” on a deck-tinted light playmat, with the self-hosted Nunito font and Pokémon blue/yellow accents. The token layer lives in apps/web/src/index.css and tailwind.config.js. Full reference, palette and accessibility baseline: design-system.md.