Architecture Overview
Purpose
Section titled “Purpose”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.
Monorepo Layout
Section titled “Monorepo Layout”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) |
Tech Stack
Section titled “Tech Stack”Frontend (apps/web)
Section titled “Frontend (apps/web)”| 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 |
Backend (apps/api)
Section titled “Backend (apps/api)”| 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 |
High-Level Layer Diagram
Section titled “High-Level Layer Diagram”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 --> CORSProxyDashed arrow: in production the API process also serves the built web app, so the Better Auth session cookie stays first-party (single origin).
Backend (apps/api)
Section titled “Backend (apps/api)”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:
- CORS (
hono/cors) withcredentials: true, origin =webOrigin— must be first (Better Auth requirement). Relevant only for split-origin deployments. GET /health— liveness check./api/auth/*— handed to the Better Auth handler before the guarded sub-app so sign-in works without an existing session.- Guarded
/apisub-app — asessionMiddlewareruns first, thendbis 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.
Frontend (apps/web)
Section titled “Frontend (apps/web)”Application Shell
Section titled “Application Shell”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.
Feature flags
Section titled “Feature flags”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 fromMobileAccountSheetso 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 byDeckPage,ArchetypeDetailand the coach Deck page.hooks/useFieldAnalysis(window)— field analysis per meta window with request-key tagging (shared byMetaPageand the coach pages).components/tools/ArchetypeMetaSummary(KPI head + trend) andcomponents/tools/TournamentListsPanel(recommendation · tournament · decklists) — the rest of the formerArchetypeDetail, on the Tools page.components/deck/OtherArchetypeDecks(+lib/coach/otherDecks.ts) — decks of other archetypes on Deck › My lists; storereassignDeckArchetype(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 ofArchetypeDetail.hooks/useArchetypeAnalysis,useArchetypeLists(paged, “load more”),useArchetypeTournaments(own failure domain,[]on error) — the per-archetype reads formerly insideArchetypeDetail, shared by Opponents and Tools (Spec 7 Scheibe 2). Same request-key pattern; a 404 of the analysis isnotInWindow.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, namespaceonboarding):- 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 andKNOWN_ARCHETYPES(name or slug); choosing callssetActiveArchetype. - 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#medoidToParsedCardsmaps the cards directly — the PTCGL text parser would drop cards without a print), paste my own list (empty deck +ImportDeckModal) or later. - TCG Live name (first run only, skippable) → localStorage
tcg-player-nameuntil Spec 8 moves it server-side. ModeswitchArchetypereuses steps 1–2 for the header’s archetype switch and can be cancelled. The red strip is the brand surface allowed bytheme/noFilledRed.test.ts.
- Archetype — first “your archetypes” (valid archetypes of the own decks with
their list count,
- 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/DeckSettingsWidgetis extracted fromDeckPage; the onboarding’s list step is exported asListSetup.
State Management Pattern
Section titled “State Management Pattern”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).
Component Tree (frontend)
Section titled “Component Tree (frontend)”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 --> CollapsibleSectionMetaShareChart, 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 --> EquilibriumPanelData Persistence
Section titled “Data Persistence”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.
External API Integration
Section titled “External API Integration”- Limitless TCG API —
metaFetch.tsanddeckComparison.tsfetch directly, falling back tocorsproxy.ioon 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/pairingsper tournament; the round pairings are resolved to per-archetype head-to-heads and stored intournament_matchups— forming an own online-Bo1 matchup matrix. Archetype icons (deck.icons) are persisted intournament_standings.iconsduring sync and surfaced as data-driven sprites throughout the Meta tab. - Matchup matrix —
GET /api/meta/matchups?days&online&bo1returns a blended matrix: real online-Bo1 head-to-heads fromtournament_matchupstake precedence over the external TrainerHill CSV wherever there are enough own games; pairs with insufficient own data fall back to TrainerHill. AmatchupSourcebreakdown 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-sidebattleLogAnalysis.tshas been removed.
Responsive Layout
Section titled “Responsive Layout”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.
Visual design
Section titled “Visual design”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.