From f8b120c0aadc59000e94a56cdf2cb84d954bf112 Mon Sep 17 00:00:00 2001 From: Kev Date: Thu, 18 Jun 2026 21:34:29 -0400 Subject: [PATCH] Session 45: Snapshot pipeline + GameCard swap + live ticker (2100 tests) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The on-demand "Read" grade model is RETIRED. A scheduled pipeline pre-grades the slate, locks grades to the line, tracks movement; the dashboard shows them already there. Orchestrates existing services — nothing rebuilt. - snapshotService.runSnapshot(sport): getOdds → gradeAndCacheSlate → classify archetype per player → lock gradedAt → line deltas vs previous snapshot → write snapshot:{sport}:latest/previous + grades:{sport} → ticker events. Fully injectable, zero-network unit tests. runAllSnapshots = cron entrypoint. - Internal trigger POST /api/internal/snapshot/:sport + /all (requireInternalAuth). In-process cron (SNAPSHOT_CRON=1, UTC 14,19,22,1,3) in server.js, no new dep. - Public reads: GET /api/snapshot/:sport (cache-only) + GET /api/ticker (merges TICKER_MANUAL pins) + Next proxies. - GameCard swap: live Slate renders vyndr/GameCard (legacy kept for types only), overlays locked grades onto game props → player name once + archetype badge + "Graded Xh ago at -115 · Current 2.5 · ▲ TOWARD +1.0". Ungraded → "Awaiting next scan", NO Read button. On-demand onGrade flow deleted. - Ticker polls /api/ticker every 30s, graceful fallback to hardcoded items. - NBA/WNBA: espnStatsAdapter free fallback (defensive parse → found:false on shape mismatch) wired into resolvePlayerStats after the offline Python service. Env: PROPLINE_API_KEY_1/2/3, VYNDR_INTERNAL_KEY, SNAPSHOT_CRON=1, TICKER_MANUAL. Backend 2061 -> 2100 tests (+39), 173 suites. Web build clean (exit 0). Co-Authored-By: Claude Opus 4.8 (1M context) --- BUILD-STATE.md | 62 +++++- CLAUDE.md | 37 ++++ src/app.js | 7 + src/routes/internal.js | 34 +++ src/routes/snapshot.js | 38 ++++ src/routes/ticker.js | 48 +++++ src/server.js | 5 + src/services/adapters/espnStatsAdapter.js | 111 ++++++++++ src/services/playerIntelService.js | 25 ++- src/services/snapshotService.js | 250 ++++++++++++++++++++++ src/snapshotScheduler.js | 49 +++++ tests/integration/snapshotRoutes.test.js | 96 +++++++++ tests/unit/espnStatsAdapter.test.js | 73 +++++++ tests/unit/snapshotOverlay.test.js | 81 +++++++ tests/unit/snapshotScheduler.test.js | 38 ++++ tests/unit/snapshotService.test.js | 149 +++++++++++++ tests/unit/tickerLive.test.js | 33 +++ web/public/sw.js | 2 +- web/src/app/api/snapshot/[sport]/route.ts | 20 ++ web/src/app/api/ticker/route.ts | 22 ++ web/src/components/Slate.tsx | 132 +++++------- web/src/components/vyndr/StatStrip.tsx | 72 +++++-- web/src/components/vyndr/Ticker.tsx | 72 ++++--- web/src/lib/slateAdapter.js | 98 +++++++++ 24 files changed, 1425 insertions(+), 129 deletions(-) create mode 100644 src/routes/snapshot.js create mode 100644 src/routes/ticker.js create mode 100644 src/services/adapters/espnStatsAdapter.js create mode 100644 src/services/snapshotService.js create mode 100644 src/snapshotScheduler.js create mode 100644 tests/integration/snapshotRoutes.test.js create mode 100644 tests/unit/espnStatsAdapter.test.js create mode 100644 tests/unit/snapshotOverlay.test.js create mode 100644 tests/unit/snapshotScheduler.test.js create mode 100644 tests/unit/snapshotService.test.js create mode 100644 tests/unit/tickerLive.test.js create mode 100644 web/src/app/api/snapshot/[sport]/route.ts create mode 100644 web/src/app/api/ticker/route.ts diff --git a/BUILD-STATE.md b/BUILD-STATE.md index a010aae..80b1cd7 100755 --- a/BUILD-STATE.md +++ b/BUILD-STATE.md @@ -4,9 +4,65 @@ 2026-06-18 ## Current Phase -SHIP BUILD v44.0 — Make it visible: VYNDR Original archetype names, grade-card -intel wiring, stale-game filtering, landing copy, depth proxies. Frontend + -wiring only (no new backend services). +SHIP BUILD v45.0 — Snapshot pipeline + GameCard swap + live ticker. The product +shifted: on-demand "Read" grading is RETIRED; a scheduled pipeline pre-grades the +slate, locks grades to the line, and the dashboard shows them already there. + +## Session 45 (2026-06-18) — SHIPPED ✅ SNAPSHOT PIPELINE + +The on-demand grade model is retired. Backend 2061 → **2100 tests** (+39), 173 +suites. Web build clean (exit 0). + +### Phase 1 — snapshotService (orchestration of existing services) +`src/services/snapshotService.js` `runSnapshot(sport)`: getOdds (PropLine +rotation) → gradeAndCacheSlate (captured via injected cacheSet) → classify each +player's archetype (resolvePlayerStats + archetypeService, pure math) → attach +`gradedAt {line, odds, timestamp}` (LOCKED) → compute line deltas vs the previous +snapshot → write `snapshot:{sport}:latest|previous` + `grades:{sport}` → emit +ticker events. `runAllSnapshots()` loops mlb/nba/wnba/soccer. Everything +injectable → fully unit-tested with zero network. Deltas: `toward` = market +confirming our side, `away` = opposing; noise filtered <0.5. + +### Phase 2 — internal API + cron + ticker API +- `POST /api/internal/snapshot/:sport` + `/snapshot/all` (existing + `requireInternalAuth`; `/all` registered first so it isn't captured as a sport). +- `GET /api/ticker` (public, cache-only, merges `TICKER_MANUAL` pins) + Next proxy. +- In-process cron `src/snapshotScheduler.js` (gated `SNAPSHOT_CRON=1`, UTC hours + 14,19,22,1,3 = 10AM/3PM/6PM/9PM/11PM ET), armed in server.js. No new dep — + 1-min unref'd interval, fires once per slot. Prefer external n8n cron hitting + the internal endpoint for multi-replica deploys. + +### Phase 3 — GameCard swap (THE product shift) +The live Slate now renders `vyndr/GameCard` (legacy kept for TYPES only). Reads +`GET /api/snapshot/:sport` (cache-only, public; falls back to `grades:{sport}`), +overlays the locked grades onto each game's odds-derived props via +`slateAdapter.buildPlayerStripsFromProps` → player name ONCE + archetype badge + +locked grade + "Graded Xh ago at -115 · Current 2.5 · ▲ TOWARD +1.0" line delta. +Ungraded props → "Awaiting next scan" (NO Read button). The on-demand onGrade +flow was deleted. + +### Phase 4 — live ticker +`vyndr/Ticker` now polls `/api/ticker` every 30s (graceful: keeps the passed +hardcoded items as initial/fallback, never blanks). Tag colors: A+/A/SCAN green, +MOVE/CASCADE amber, ALERT white. + +### Phase 5 — NBA/WNBA ESPN fallback +`espnStatsAdapter.getSeasonAverages(name, sport)` — free public ESPN stats, +DEFENSIVE (`parseAthleteStats` returns null on any unrecognized shape → caller +degrades to found:false; never a wrong-but-confident number). Wired as the +NBA/WNBA fallback in `resolvePlayerStats` after the offline Python service. Note: +the live ESPN athlete-stats shape may need tuning against production — the parser +is tolerant and tested against a representative payload. + +### Env vars (set in Coolify) +- `PROPLINE_API_KEY_1/2/3` — PropLine props rotation (snapshot odds source). +- `VYNDR_INTERNAL_KEY` — the internal-auth secret (header `x-internal-key`) for + the snapshot trigger. (This is the existing key, NOT a new INTERNAL_AUTH_TOKEN.) +- `SNAPSHOT_CRON=1` — arm the in-process scheduler (omit if using n8n). +- `TICKER_MANUAL` — JSON array of editorial pins, e.g. + `[{"tag":"ALERT","text":"VYNDR 2.0 is live."}]`. + +## Session 44 (2026-06-18) — SHIPPED ✅ MAKE IT VISIBLE ## Session 44 (2026-06-18) — SHIPPED ✅ MAKE IT VISIBLE diff --git a/CLAUDE.md b/CLAUDE.md index 51489b4..8ec5fee 100755 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -413,6 +413,43 @@ Built from the Claude Design "VYNDR Player Intelligence" bundle. vyndr/GameCard (playerStrips/pitchers) is built for that and swaps in then. Don't swap it before the grades cache is populated (cards would be blank). +## Snapshot Pipeline (Session 45 — the product model) +The on-demand "Read" grade flow is RETIRED. Grades are produced by a scheduled +snapshot, locked to the line, and read from cache. +- **`snapshotService.runSnapshot(sport)`** orchestrates EXISTING services (don't + rebuild): getOdds → gradeAndCacheSlate (captured via an injected cacheSet, so + we re-write an ENRICHED envelope) → classify archetype per player + (resolvePlayerStats + archetypeService) → attach `gradedAt {line,odds,timestamp}` + → `computeLineDeltas` vs previous → write `snapshot:{sport}:latest|previous` + + `grades:{sport}` → `generateTickerEvents` → `ticker:items`. ALL deps injectable + → unit-tested with zero network. `runAllSnapshots()` is the cron entrypoint. +- **Redis keys:** `snapshot:{sport}:latest` (current locked snapshot: + {grades, deltas}), `:previous` (for the next delta), `grades:{sport}` (enriched, + read by GameCard/Explore/leaders), `ticker:items` (capped 50 array). +- **Trigger is INTERNAL-ONLY:** `POST /api/internal/snapshot/:sport|/all` behind + `requireInternalAuth` (header `x-internal-key` == `VYNDR_INTERNAL_KEY`). `/all` + is registered BEFORE `/:sport` or Express captures "all" as a sport. +- **Cron:** `src/snapshotScheduler.js`, gated `SNAPSHOT_CRON=1`, UTC hours + 14,19,22,1,3, armed in server.js (NOT app.js — app.js is imported by tests). + No new dependency. For multi-replica, use an external n8n cron hitting the + internal endpoint instead. +- **Read path:** `GET /api/snapshot/:sport` (public, cache-only, never triggers a + snapshot → can't drain PropLine). `GET /api/ticker` (public, merges + `TICKER_MANUAL` env pins). +- **GameCard swap:** the live Slate renders `vyndr/GameCard` (legacy GameCard kept + for TYPES only — `import type`). It overlays snapshot grades onto each game's + odds-derived props via `slateAdapter.buildPlayerStripsFromProps` (player name + once + archetype + locked grade + line-delta sub-line). Ungraded → "Awaiting + next scan", NO Read button. `StatStrip` renders the gradedAt/delta sub-line when + a prop carries `gradedAt`/`delta`/`awaiting` (snapshot mode), else the inline chip. +- **Ticker** (`vyndr/Ticker`) polls `/api/ticker` every 30s; the passed items are + the initial + graceful fallback (never blanks on fetch failure). +- **NBA/WNBA stats:** `espnStatsAdapter` is the FREE fallback when the Python + nba_api service is offline. `parseAthleteStats` is DEFENSIVE (null on any shape + it doesn't recognize → found:false). Its live ESPN shape may need prod tuning. +- **Env:** PROPLINE_API_KEY_1/2/3, VYNDR_INTERNAL_KEY, SNAPSHOT_CRON=1, + SNAPSHOT_HOURS_UTC (optional), TICKER_MANUAL (JSON array). + ## Active Skills - vyndr-voice (all user-facing output) - prop-analysis (grading methodology) diff --git a/src/app.js b/src/app.js index e3238a7..2f5affc 100644 --- a/src/app.js +++ b/src/app.js @@ -144,6 +144,13 @@ app.use('/api/widget', widgetRoutes); // stat-filtered views over all of them. const scheduleRoutes = require('./routes/schedule'); app.use('/api/schedule', scheduleRoutes); +// Session 45 — live ticker feed (snapshot exhaust + editorial pins). Public, +// cache-only, never triggers a snapshot. +const tickerRoutes = require('./routes/ticker'); +app.use('/api/ticker', tickerRoutes); +// Session 45 — pre-graded slate read (snapshot:{sport}:latest). Public, cache-only. +const snapshotReadRoutes = require('./routes/snapshot'); +app.use('/api/snapshot', snapshotReadRoutes); const gameLinesRoutes = require('./routes/gameLines'); app.use('/api/gamelines', gameLinesRoutes); const streaksRoutes = require('./routes/streaks'); diff --git a/src/routes/internal.js b/src/routes/internal.js index 1316e4b..5c9c977 100644 --- a/src/routes/internal.js +++ b/src/routes/internal.js @@ -82,4 +82,38 @@ router.post('/prefetch/tank01', async (req, res) => { } }); +/** + * POST /api/internal/snapshot/:sport (Session 45) + * + * Trigger one snapshot cycle for a sport (pre-grade the slate, lock grades, + * compute deltas, emit ticker events). Internal-only (requireInternalAuth at the + * router root). This is what the cron / n8n schedule calls — never public, so a + * bad actor can't drain the PropLine quota by spamming it. + */ +/** POST /api/internal/snapshot/all — every active sport, sequentially. + * Registered BEFORE /snapshot/:sport so "all" isn't captured as a sport. */ +router.post('/snapshot/all', async (req, res) => { + const snapshot = require('../services/snapshotService'); + try { + const results = await snapshot.runAllSnapshots(); + return res.json({ ok: true, results }); + } catch (err) { + const message = err && err.message ? err.message : String(err); + console.error('[internal/snapshot/all] failed:', message); + return res.status(500).json({ ok: false, error: message }); + } +}); + +router.post('/snapshot/:sport', async (req, res) => { + const snapshot = require('../services/snapshotService'); + try { + const summary = await snapshot.runSnapshot(req.params.sport); + return res.json({ ok: true, summary }); + } catch (err) { + const message = err && err.message ? err.message : String(err); + console.error('[internal/snapshot] failed:', message); + return res.status(500).json({ ok: false, error: message }); + } +}); + module.exports = router; diff --git a/src/routes/snapshot.js b/src/routes/snapshot.js new file mode 100644 index 0000000..c93c0b4 --- /dev/null +++ b/src/routes/snapshot.js @@ -0,0 +1,38 @@ +'use strict'; + +/** + * GET /api/snapshot/:sport (Session 45) — the latest pre-graded slate. + * + * Public, cache-only read of `snapshot:{sport}:latest` (enriched grades with + * archetype + gradedAt, plus line deltas). Falls back to the `grades:{sport}` + * envelope when no snapshot has run yet. NEVER triggers a snapshot (that's the + * internal cron's job) — so it can't drain the PropLine quota. + */ + +const express = require('express'); +const { createRateLimit } = require('../middleware/rateLimit'); +const { cacheGet } = require('../utils/redis'); + +const router = express.Router(); +router.use(createRateLimit({ windowMs: 60_000, max: 60 })); + +router.get('/:sport', async (req, res) => { + const sport = String(req.params.sport || '').toLowerCase(); + try { + const snap = await cacheGet(`snapshot:${sport}:latest`); + if (snap && Array.isArray(snap.grades)) { + res.set('Cache-Control', 'public, max-age=30'); + return res.json({ sport, updated_at: snap.updated_at, grades: snap.grades, deltas: snap.deltas || [] }); + } + // Fallback: the grades envelope (no deltas yet). + const env = await cacheGet(`grades:${sport}`); + const grades = env && Array.isArray(env.grades) ? env.grades : []; + res.set('Cache-Control', 'public, max-age=30'); + return res.json({ sport, updated_at: env && env.updated_at, grades, deltas: [] }); + } catch (err) { + console.error('[snapshot]', err.message); + return res.status(200).json({ sport, grades: [], deltas: [] }); + } +}); + +module.exports = router; diff --git a/src/routes/ticker.js b/src/routes/ticker.js new file mode 100644 index 0000000..ebe2a70 --- /dev/null +++ b/src/routes/ticker.js @@ -0,0 +1,48 @@ +'use strict'; + +/** + * GET /api/ticker (Session 45) — the live ticker feed. + * + * Returns the latest snapshot-generated events from the `ticker:items` Redis + * list (newest first), merged with editorial pins from the TICKER_MANUAL env + * var (a JSON array of { tag, text, color }). Public + cached 30s. Reads cache + * only — never triggers a snapshot. + */ + +const express = require('express'); +const { createRateLimit } = require('../middleware/rateLimit'); +const { cacheGet } = require('../utils/redis'); + +const router = express.Router(); +router.use(createRateLimit({ windowMs: 60_000, max: 60 })); + +const LIMIT = 30; + +function parseManual() { + const raw = process.env.TICKER_MANUAL; + if (!raw) return []; + try { + const arr = JSON.parse(raw); + return Array.isArray(arr) + ? arr.filter((x) => x && x.text).map((x) => ({ tag: x.tag || 'ALERT', text: String(x.text), color: x.color || 'var(--text-0)' })) + : []; + } catch { + return []; + } +} + +router.get('/', async (req, res) => { + let items = []; + try { + const stored = await cacheGet('ticker:items'); + if (Array.isArray(stored)) items = stored; + } catch { + items = []; + } + // Snapshot events are already newest-first; editorial pins follow. + const merged = [...items, ...parseManual()].slice(0, LIMIT); + res.set('Cache-Control', 'public, max-age=30'); + res.json({ items: merged, count: merged.length }); +}); + +module.exports = router; diff --git a/src/server.js b/src/server.js index bb6240c..1be31b9 100644 --- a/src/server.js +++ b/src/server.js @@ -7,6 +7,8 @@ const { getConfiguredProviders, listProviderIds } = require('./config/providers' // Session 24 — warm the Tank01 cache after boot so streaks / hot lists / // game lines have data on the first page load. Non-blocking; see module. const { scheduleStartupPrefetch } = require('./startupPrefetch'); +// Session 45 — in-process snapshot cron (gated on SNAPSHOT_CRON=1). +const { startSnapshotScheduler } = require('./snapshotScheduler'); // Default 3001 — Next.js owns 3000 locally and in production. The poller, // internal cron, and BASE_URL conventions all assume 3001 for the Express @@ -25,4 +27,7 @@ app.listen(PORT, () => { // Session 24 — fire-and-forget cache warm. 5s delay so Redis is ready. // Skips itself when RAPID_API_KEY is unset; never blocks or crashes boot. scheduleStartupPrefetch(); + + // Session 45 — arm the snapshot cron (no-op unless SNAPSHOT_CRON=1). + startSnapshotScheduler(); }); diff --git a/src/services/adapters/espnStatsAdapter.js b/src/services/adapters/espnStatsAdapter.js new file mode 100644 index 0000000..2c90265 --- /dev/null +++ b/src/services/adapters/espnStatsAdapter.js @@ -0,0 +1,111 @@ +'use strict'; + +/** + * espnStatsAdapter — best-effort NBA/WNBA season averages from ESPN (Session 45). + * + * The primary NBA/WNBA stats source (`nbaStatsClient`) depends on a Python + * nba_api service that is frequently offline in prod. This adapter is a FREE, + * no-auth fallback off ESPN's public site API. It is intentionally DEFENSIVE: + * any shape it doesn't recognize → null (the caller degrades to found:false), + * never a throw and never a wrong-but-confident number. + * + * Parsing is tolerant by design (ESPN's athlete-stats JSON varies by sport and + * season), so `parseAthleteStats` is a pure, unit-tested function. + */ + +const axios = require('axios'); +const { cacheGet, cacheSet } = require('../../utils/redis'); + +const SEARCH = 'https://site.web.api.espn.com/apis/common/v3/search'; +const SPORT_PATH = { nba: 'basketball/nba', wnba: 'basketball/wnba' }; +const TTL = 6 * 3600; +const TIMEOUT = 10_000; + +// ESPN stat label → our classifier-input key. Lowercased, punctuation-stripped. +const STAT_MAP = { + pointspergame: 'ppg', avgpoints: 'ppg', points: 'ppg', ppg: 'ppg', + reboundspergame: 'rpg', avgrebounds: 'rpg', rebounds: 'rpg', rpg: 'rpg', totalrebounds: 'rpg', + assistspergame: 'apg', avgassists: 'apg', assists: 'apg', apg: 'apg', + blockspergame: 'bpg', avgblocks: 'bpg', blocks: 'bpg', bpg: 'bpg', + stealspergame: 'spg', avgsteals: 'spg', steals: 'spg', spg: 'spg', + threepointfieldgoalsmade: 'threes', threepointfieldgoalspergame: 'threes', avg3pointfieldgoalsmade: 'threes', +}; + +const keyify = (s) => String(s || '').toLowerCase().replace(/[^a-z0-9]/g, ''); + +/** + * Walk an ESPN athlete-stats payload and pull out per-game averages we can + * classify. Returns a classifier-input object (possibly partial) or null when + * nothing usable is found. + */ +function parseAthleteStats(payload) { + if (!payload || typeof payload !== 'object') return null; + const out = {}; + // ESPN nests stats under categories[].stats[] with { name|abbreviation, value|displayValue }. + const categories = payload?.statistics?.splits?.categories + || payload?.splits?.categories + || payload?.categories + || []; + const visit = (statArr) => { + for (const st of statArr || []) { + const label = keyify(st.name || st.abbreviation || st.label); + const mapped = STAT_MAP[label]; + if (!mapped) continue; + const val = Number(st.value != null ? st.value : st.displayValue); + if (Number.isFinite(val) && out[mapped] == null) out[mapped] = val; + } + }; + for (const cat of categories) visit(cat.stats); + if (Array.isArray(payload.stats)) visit(payload.stats); // flat fallback + return Object.keys(out).length > 0 ? out : null; +} + +async function fetchJson(url, http) { + const client = http || axios; + const res = await client.get(url, { timeout: TIMEOUT }); + return res && res.data; +} + +/** + * Resolve a player's NBA/WNBA season averages from ESPN. Returns + * { found, team, position, classifierInput } or { found:false }. Never throws. + * opts.http injectable for tests. + */ +async function getSeasonAverages(name, sport, opts = {}) { + const sp = String(sport || '').toLowerCase(); + const path = SPORT_PATH[sp]; + if (!path || !name) return { found: false }; + const cacheKey = `espnstats:${sp}:${keyify(name)}`; + try { + const cached = await cacheGet(cacheKey); + if (cached) return cached; + } catch { /* ignore */ } + + try { + // 1. Resolve the athlete id via ESPN search. + const search = await fetchJson(`${SEARCH}?query=${encodeURIComponent(name)}&limit=5&sport=${encodeURIComponent(path)}`, opts.http); + const items = (search && (search.items || search.results)) || []; + const athlete = items.find((it) => keyify(it.displayName || it.name) === keyify(name)) || items[0]; + const id = athlete && (athlete.id || athlete.uid || (athlete.athlete && athlete.athlete.id)); + if (!id) return { found: false }; + + // 2. Fetch that athlete's stats overview. + const stats = await fetchJson(`https://site.web.api.espn.com/apis/common/v3/sports/${path}/athletes/${id}/stats`, opts.http); + const classifierInput = parseAthleteStats(stats); + if (!classifierInput) return { found: false }; + + const result = { + found: true, + team: (athlete.team && (athlete.team.abbreviation || athlete.team.displayName)) || '', + position: (athlete.position && athlete.position.abbreviation) || '', + classifierInput, + }; + try { await cacheSet(cacheKey, result, TTL); } catch { /* ignore */ } + return result; + } catch (err) { + console.warn('[espnStats] season averages failed:', name, sp, err.message); + return { found: false }; + } +} + +module.exports = { getSeasonAverages, parseAthleteStats, __internals: { STAT_MAP, keyify, SPORT_PATH } }; diff --git a/src/services/playerIntelService.js b/src/services/playerIntelService.js index 562b4d4..96e8da0 100644 --- a/src/services/playerIntelService.js +++ b/src/services/playerIntelService.js @@ -124,15 +124,26 @@ async function resolvePlayerStats(name, sport, opts = {}) { }; } if (sp === 'nba' || sp === 'wnba') { - // NBA/WNBA stats come from the Python nba_api service (nbaStatsClient). - // It's frequently offline in prod (localhost service) — degrade quietly. + // PRIMARY: the Python nba_api service (nbaStatsClient) — often offline in + // prod. FALLBACK: ESPN's free public stats (espnStatsAdapter). Either way, + // a miss degrades quietly to found:false (no badge, never a crash). const nba = opts.nbaClient || require('./nbaStatsClient'); - const data = await nba.getSeasonAvg(name).catch(() => null); - if (!data || typeof data !== 'object') return { found: false }; - const ppg = toNum(data.ppg ?? data.points); - if (!ppg) return { found: false }; + let data = await nba.getSeasonAvg(name).catch(() => null); + if (!data || typeof data !== 'object' || !toNum(data.ppg ?? data.points)) { + const espn = opts.espnStats || require('./adapters/espnStatsAdapter'); + const e = await espn.getSeasonAverages(name, sp).catch(() => ({ found: false })); + if (e && e.found && e.classifierInput) { + const ci = e.classifierInput; + const season = [ + { k: 'PPG', v: String(ci.ppg ?? '—') }, { k: 'RPG', v: String(ci.rpg ?? '—') }, + { k: 'APG', v: String(ci.apg ?? '—') }, { k: 'BLK', v: String(ci.bpg ?? '—') }, + ]; + return { found: true, team: e.team || '', classifierInput: { ...ci, pos: e.position }, season, last10: [], splits: [] }; + } + return { found: false }; + } const classifierInput = { - ppg, rpg: toNum(data.rpg ?? data.rebounds), apg: toNum(data.apg ?? data.assists), + ppg: toNum(data.ppg ?? data.points), rpg: toNum(data.rpg ?? data.rebounds), apg: toNum(data.apg ?? data.assists), bpg: toNum(data.bpg ?? data.blocks), spg: toNum(data.spg ?? data.steals), threes: toNum(data.threes ?? data.fg3m), usg: toNum(data.usg ?? data.usage), pos: data.pos || data.position, }; diff --git a/src/services/snapshotService.js b/src/services/snapshotService.js new file mode 100644 index 0000000..151f055 --- /dev/null +++ b/src/services/snapshotService.js @@ -0,0 +1,250 @@ +/** + * snapshotService — scheduled grade pipeline (Session 45). + * + * Orchestrates ONE snapshot cycle for one sport. The on-demand "Read" model is + * retired: a snapshot pre-grades the full slate, LOCKS each grade to the line at + * snapshot time (`gradedAt`), classifies each player's archetype, computes line + * deltas vs the previous snapshot, and emits ticker events. + * + * Everything is orchestration of EXISTING services (oddsService, + * gradeSlateService, archetypeService, playerIntelService). All I/O is injectable + * so the whole cycle is unit-testable with zero network. + * + * Redis keys written: + * snapshot:{sport}:latest — current locked snapshot { sport, updated_at, grades, deltas } + * snapshot:{sport}:previous — prior snapshot (for the next delta computation) + * grades:{sport} — { grades, updated_at, source } (GameCard / Explore / leaders) + * ticker:items — capped array of ticker events (newest first) + */ + +const SNAP_TTL = 6 * 3600; // 6h — a snapshot is valid until the next run +const GRADES_TTL = 2 * 3600; // matches gradeSlateService +const TICKER_TTL = 24 * 3600; +const TICKER_CAP = 50; +const DELTA_NOISE = 0.5; // ignore movements smaller than this +const DELTA_MOVE = 1.0; // ticker MOVE threshold +const STATS_CONCURRENCY = 5; + +const norm = (s) => String(s == null ? '' : s).toLowerCase().replace(/[^a-z0-9]/g, ''); +const lastName = (full) => { + const parts = String(full || '').trim().split(/\s+/); + return parts.length > 1 ? parts[parts.length - 1] : (parts[0] || ''); +}; +const sideChar = (dir) => (String(dir || 'over').toLowerCase() === 'under' ? 'U' : 'O'); +const propKey = (g) => `${norm(g.player || g.player_name)}|${String(g.stat_type || g.stat || '').toLowerCase()}|${String(g.direction || '').toLowerCase()}`; + +async function mapLimit(items, concurrency, fn) { + const out = new Array(items.length); + let i = 0; + async function worker() { + while (i < items.length) { + const idx = i++; + out[idx] = await fn(items[idx], idx); + } + } + await Promise.all(Array.from({ length: Math.min(concurrency, items.length || 1) }, worker)); + return out; +} + +/** Index original odds props by propKey-ish (player|stat) for odds lookup. */ +function indexOdds(props) { + const map = {}; + for (const p of props || []) { + const k = `${norm(p.player)}|${String(p.stat_type || '').toLowerCase()}`; + map[k] = p; + } + return map; +} + +function gradedAtFor(g, oddsByKey, ts) { + const k = `${norm(g.player || g.player_name)}|${String(g.stat_type || g.stat || '').toLowerCase()}`; + const o = oddsByKey[k]; + let odds = null; + if (o) { + odds = String(g.direction || '').toLowerCase() === 'under' + ? (o.under_odds ?? o.under ?? o.odds ?? null) + : (o.over_odds ?? o.over ?? o.odds ?? null); + } + return { line: g.line, odds, timestamp: ts }; +} + +/** + * Compare current grades to the previous snapshot's locked lines. A delta is + * emitted only when |movement| >= DELTA_NOISE. `direction`: + * 'toward' = market moving in the direction of our graded side (confirming) + * 'away' = market moving against it. + * For an OVER, a rising line confirms (toward); for an UNDER, a falling line. + */ +function computeLineDeltas(current, previous) { + const prevMap = {}; + for (const p of previous || []) prevMap[propKey(p)] = p; + const out = []; + for (const c of current || []) { + const prev = prevMap[propKey(c)]; + if (!prev) continue; + const gradedLine = prev.gradedAt ? prev.gradedAt.line : prev.line; + const currentLine = c.line; + if (gradedLine == null || currentLine == null) continue; + const delta = +(Number(currentLine) - Number(gradedLine)).toFixed(2); + if (Math.abs(delta) < DELTA_NOISE) continue; + const side = String(c.direction || 'over').toLowerCase(); + const toward = side === 'over' ? delta > 0 : delta < 0; + out.push({ + player: c.player || c.player_name, + stat: c.stat_type || c.stat, + side: sideChar(side), + gradedLine: Number(gradedLine), + currentLine: Number(currentLine), + delta, + direction: toward ? 'toward' : 'away', + grade: c.grade, + }); + } + return out; +} + +const isTopGrade = (g) => g === 'A+' || g === 'A'; + +/** + * Build ticker events from a snapshot: a SCAN summary, GRADE events for the top + * grades, and MOVE events for significant deltas. Newest-relevant first. + */ +function generateTickerEvents(sport, grades, deltas, ts) { + const events = []; + events.push({ + tag: 'SCAN', color: 'var(--g-a)', ts, + text: `${sport.toUpperCase()} slate scanned · ${grades.length} props graded`, + }); + for (const g of grades.filter((x) => isTopGrade(x.grade)).slice(0, 6)) { + const arch = g.archetype ? `${g.archetype} ` : ''; + events.push({ + tag: g.grade, color: g.grade === 'A+' ? 'var(--g-ap)' : 'var(--g-a)', ts, + text: `${arch}${lastName(g.player || g.player_name)} ${g.stat_type || g.stat} ${sideChar(g.direction)}${g.line} graded ${g.grade}`, + }); + } + for (const d of deltas.filter((x) => Math.abs(x.delta) >= DELTA_MOVE).slice(0, 6)) { + const arrow = d.delta > 0 ? '▲' : '▼'; + const s = d.side === 'U' ? 'u' : 'o'; + events.push({ + tag: 'MOVE', color: 'var(--amber)', ts, + text: `${lastName(d.player)} ${s}${d.gradedLine} → ${s}${d.currentLine} ${arrow}${d.delta > 0 ? '+' : ''}${d.delta}`, + }); + } + return events; +} + +async function pushTickerItems(events, deps) { + if (!events || events.length === 0) return; + const existing = await deps.cacheGet('ticker:items'); + const arr = Array.isArray(existing) ? existing : []; + const merged = [...events, ...arr].slice(0, TICKER_CAP); + await deps.cacheSet('ticker:items', merged, TICKER_TTL); +} + +const ACTIVE_SPORTS = ['mlb', 'nba', 'wnba', 'soccer']; + +/** + * Run one snapshot cycle for `sport`. Returns a summary; never throws. + * opts (all injectable): getOdds, gradeAndCacheSlate, resolveStats, classify, + * cacheGet, cacheSet, now, nowMs. + */ +async function runSnapshot(sport, opts = {}) { + const sp = String(sport || '').toLowerCase(); + const deps = { + getOdds: opts.getOdds || require('./oddsService').getOdds, + gradeAndCacheSlate: opts.gradeAndCacheSlate || require('./gradeSlateService').gradeAndCacheSlate, + resolveStats: opts.resolveStats || require('./playerIntelService').resolvePlayerStats, + classify: opts.classify || require('./archetypeService').classify, + cacheGet: opts.cacheGet || require('../utils/redis').cacheGet, + cacheSet: opts.cacheSet || require('../utils/redis').cacheSet, + now: opts.now || (() => new Date().toISOString()), + nowMs: opts.nowMs || (() => Date.now()), + }; + const start = deps.nowMs(); + const ts = deps.now(); + + let odds; + try { + odds = await deps.getOdds(sp); + } catch (e) { + return { sport: sp, status: 'error', reason: e.message, gradeCount: 0 }; + } + const props = (odds && Array.isArray(odds.props)) ? odds.props : []; + if (props.length === 0) return { sport: sp, status: 'skipped', reason: 'no props', gradeCount: 0 }; + + // Grade the slate via the existing service; capture the envelope instead of + // letting it write (we re-write an ENRICHED version below). + let envelope = null; + await deps.gradeAndCacheSlate(sp, props, { + source: (odds && odds.provider) || 'odds-api', + now: deps.now, + cacheSet: async (_k, v) => { envelope = v; }, + }); + const graded = (envelope && Array.isArray(envelope.grades)) ? envelope.grades : []; + if (graded.length === 0) return { sport: sp, status: 'skipped', reason: 'no grades', gradeCount: 0 }; + + // Archetype per unique player (pure math once we have stats). Best-effort — + // a missing stat line → no badge (not a fallback archetype). + const oddsByKey = indexOdds(props); + const players = [...new Set(graded.map((g) => g.player || g.player_name).filter(Boolean))]; + const archByPlayer = {}; + await mapLimit(players, STATS_CONCURRENCY, async (player) => { + try { + const stats = await deps.resolveStats(player, sp); + if (stats && stats.found) { + const c = deps.classify(sp, stats.classifierInput || {}); + archByPlayer[player] = c.primary ? c.primary.name : null; + } + } catch { /* graceful — no badge */ } + }); + + const enriched = graded.map((g) => ({ + ...g, + gradedAt: gradedAtFor(g, oddsByKey, ts), + archetype: archByPlayer[g.player || g.player_name] || null, + })); + + // Line deltas vs the previous snapshot's locked lines. + const prev = await deps.cacheGet(`snapshot:${sp}:latest`); + const deltas = computeLineDeltas(enriched, prev && prev.grades); + + // Lock: previous = old latest, latest = new, grades = enriched. + if (prev) await deps.cacheSet(`snapshot:${sp}:previous`, prev, SNAP_TTL); + const snapshot = { sport: sp, updated_at: ts, grades: enriched, deltas, gradeCount: enriched.length }; + await deps.cacheSet(`snapshot:${sp}:latest`, snapshot, SNAP_TTL); + await deps.cacheSet(`grades:${sp}`, { grades: enriched, updated_at: ts, source: (odds && odds.provider) || 'odds-api' }, GRADES_TTL); + + // Ticker exhaust. + const events = generateTickerEvents(sp, enriched, deltas, ts); + await pushTickerItems(events, deps); + + return { + sport: sp, + status: 'ok', + gradeCount: enriched.length, + topGrades: enriched.filter((g) => isTopGrade(g.grade)).slice(0, 5).map((g) => ({ + player: g.player || g.player_name, stat: g.stat_type || g.stat, grade: g.grade, archetype: g.archetype, + })), + deltas: deltas.length, + duration: deps.nowMs() - start, + }; +} + +/** Run snapshots for every active sport sequentially (cron entrypoint). */ +async function runAllSnapshots(opts = {}) { + const results = []; + for (const sp of ACTIVE_SPORTS) { + results.push(await runSnapshot(sp, opts)); + } + return results; +} + +module.exports = { + runSnapshot, + runAllSnapshots, + computeLineDeltas, + generateTickerEvents, + pushTickerItems, + ACTIVE_SPORTS, + __internals: { propKey, gradedAtFor, indexOdds, lastName, isTopGrade, DELTA_NOISE, DELTA_MOVE, TICKER_CAP }, +}; diff --git a/src/snapshotScheduler.js b/src/snapshotScheduler.js new file mode 100644 index 0000000..0306f9f --- /dev/null +++ b/src/snapshotScheduler.js @@ -0,0 +1,49 @@ +'use strict'; + +/** + * snapshotScheduler — in-process snapshot cron (Session 45). + * + * No new dependency: a 1-minute unref'd interval that fires `runAllSnapshots` + * at the configured UTC hours (default 14,19,22,1,3 = 10AM/3PM/6PM/9PM/11PM ET, + * matching the sports cycle — morning research, afternoon news, pre-game lock, + * in-game). Gated on SNAPSHOT_CRON=1 so it never runs in dev/test or on a + * container that shouldn't own the schedule. Prefer an EXTERNAL cron (n8n) hitting + * POST /api/internal/snapshot/all when running multiple API replicas — this + * in-process variant assumes a single scheduler instance. + */ + +const HOURS_UTC = (process.env.SNAPSHOT_HOURS_UTC || '14,19,22,1,3') + .split(',') + .map((n) => parseInt(n, 10)) + .filter((n) => Number.isInteger(n) && n >= 0 && n <= 23); + +function startSnapshotScheduler(opts = {}) { + if (process.env.SNAPSHOT_CRON !== '1') return null; + const runAll = opts.runAllSnapshots || require('./services/snapshotService').runAllSnapshots; + const now = opts.now || (() => new Date()); + let lastFiredSlot = null; + + const tick = async () => { + const d = now(); + if (d.getUTCMinutes() !== 0) return; + const h = d.getUTCHours(); + if (!HOURS_UTC.includes(h)) return; + const slot = `${d.getUTCFullYear()}-${d.getUTCMonth()}-${d.getUTCDate()}-${h}`; + if (slot === lastFiredSlot) return; // fire once per slot + lastFiredSlot = slot; + try { + const results = await runAll(); + const ok = results.filter((r) => r.status === 'ok'); + console.log(`[snapshot] cron fired ${h}:00 UTC — ${ok.length}/${results.length} sports graded`); + } catch (e) { + console.warn('[snapshot] cron run failed:', e.message); + } + }; + + const interval = setInterval(tick, 60_000); + if (interval.unref) interval.unref(); + console.log(`[snapshot] scheduler armed for UTC hours: ${HOURS_UTC.join(', ')}`); + return { interval, tick }; +} + +module.exports = { startSnapshotScheduler, HOURS_UTC }; diff --git a/tests/integration/snapshotRoutes.test.js b/tests/integration/snapshotRoutes.test.js new file mode 100644 index 0000000..4e11744 --- /dev/null +++ b/tests/integration/snapshotRoutes.test.js @@ -0,0 +1,96 @@ +// Session 45 — internal snapshot endpoints (auth-gated) + the public ticker. + +const express = require('express'); +const request = require('supertest'); + +jest.mock('../../scripts/tank01-prefetch', () => ({ main: jest.fn() })); +jest.mock('../../src/services/quotaTracker', () => ({ getAllQuotaStatuses: jest.fn() })); +jest.mock('../../src/services/snapshotService', () => ({ + runSnapshot: jest.fn(async (sport) => ({ sport, status: 'ok', gradeCount: 3 })), + runAllSnapshots: jest.fn(async () => [{ sport: 'mlb', status: 'ok' }, { sport: 'nba', status: 'skipped' }]), +})); +const snapshot = require('../../src/services/snapshotService'); + +beforeEach(() => { + jest.clearAllMocks(); + process.env.VYNDR_INTERNAL_KEY = 'test-key-123'; +}); + +function mountInternal() { + delete require.cache[require.resolve('../../src/routes/internal')]; + const internalRoutes = require('../../src/routes/internal'); + const app = express(); + app.use(express.json()); + app.use('/api/internal', internalRoutes); + return app; +} + +describe('POST /api/internal/snapshot/:sport', () => { + it('rejects without the internal key (401)', async () => { + const res = await request(mountInternal()).post('/api/internal/snapshot/mlb').send({}); + expect(res.status).toBe(401); + expect(snapshot.runSnapshot).not.toHaveBeenCalled(); + }); + + it('runs a single-sport snapshot with the key', async () => { + const res = await request(mountInternal()) + .post('/api/internal/snapshot/mlb') + .set('x-internal-key', 'test-key-123') + .send({}); + expect(res.status).toBe(200); + expect(snapshot.runSnapshot).toHaveBeenCalledWith('mlb'); + expect(res.body.summary.gradeCount).toBe(3); + }); + + it('routes /snapshot/all to runAllSnapshots (not captured as a sport)', async () => { + const res = await request(mountInternal()) + .post('/api/internal/snapshot/all') + .set('x-internal-key', 'test-key-123') + .send({}); + expect(res.status).toBe(200); + expect(snapshot.runAllSnapshots).toHaveBeenCalled(); + expect(snapshot.runSnapshot).not.toHaveBeenCalled(); + expect(res.body.results).toHaveLength(2); + }); +}); + +describe('GET /api/ticker', () => { + const mockCache = { value: null }; + jest.mock('../../src/utils/redis', () => ({ + cacheGet: async () => mockCache.value, + cacheSet: async () => true, + getRedisClient: () => ({}), + isDegraded: () => false, + })); + + function mountTicker() { + delete require.cache[require.resolve('../../src/routes/ticker')]; + const tickerRoutes = require('../../src/routes/ticker'); + const app = express(); + app.use('/api/ticker', tickerRoutes); + return app; + } + + it('returns snapshot items newest-first', async () => { + mockCache.value = [{ tag: 'SCAN', text: 'MLB slate scanned · 248 props graded' }, { tag: 'A+', text: 'BOMBER Judge graded A+' }]; + delete process.env.TICKER_MANUAL; + const res = await request(mountTicker()).get('/api/ticker'); + expect(res.status).toBe(200); + expect(res.body.items[0].tag).toBe('SCAN'); + }); + + it('merges editorial pins from TICKER_MANUAL', async () => { + mockCache.value = [{ tag: 'SCAN', text: 'scanned' }]; + process.env.TICKER_MANUAL = JSON.stringify([{ tag: 'ALERT', text: 'VYNDR 2.0 is live.' }]); + const res = await request(mountTicker()).get('/api/ticker'); + expect(res.body.items.find((i) => i.tag === 'ALERT')).toBeTruthy(); + delete process.env.TICKER_MANUAL; + }); + + it('returns [] gracefully on a cold cache', async () => { + mockCache.value = null; + delete process.env.TICKER_MANUAL; + const res = await request(mountTicker()).get('/api/ticker'); + expect(res.body.items).toEqual([]); + }); +}); diff --git a/tests/unit/espnStatsAdapter.test.js b/tests/unit/espnStatsAdapter.test.js new file mode 100644 index 0000000..7f234ce --- /dev/null +++ b/tests/unit/espnStatsAdapter.test.js @@ -0,0 +1,73 @@ +// Session 45 — ESPN NBA/WNBA stats fallback. parseAthleteStats is pure; the +// fetch path is exercised with an injected http client. + +const espn = require('../../src/services/adapters/espnStatsAdapter'); +const svc = require('../../src/services/playerIntelService'); + +describe('parseAthleteStats (defensive)', () => { + it('pulls per-game averages from the ESPN categories shape', () => { + const payload = { + statistics: { splits: { categories: [ + { stats: [ + { name: 'avgPoints', value: 28.1 }, + { name: 'avgRebounds', value: 8.2 }, + { name: 'avgAssists', value: 6.4 }, + ] }, + ] } }, + }; + const ci = espn.parseAthleteStats(payload); + expect(ci.ppg).toBe(28.1); + expect(ci.rpg).toBe(8.2); + expect(ci.apg).toBe(6.4); + }); + + it('returns null for an unrecognized / empty shape (graceful)', () => { + expect(espn.parseAthleteStats(null)).toBeNull(); + expect(espn.parseAthleteStats({ nonsense: true })).toBeNull(); + expect(espn.parseAthleteStats({ statistics: { splits: { categories: [{ stats: [{ name: 'foo', value: 1 }] }] } } })).toBeNull(); + }); +}); + +describe('getSeasonAverages (injected http)', () => { + it('resolves an athlete and parses stats', async () => { + const http = { + get: async (url) => { + if (url.includes('/search')) return { data: { items: [{ id: 123, displayName: 'Luka Doncic', team: { abbreviation: 'DAL' }, position: { abbreviation: 'G' } }] } }; + return { data: { statistics: { splits: { categories: [{ stats: [{ name: 'avgPoints', value: 33 }, { name: 'avgAssists', value: 9 }] }] } } } }; + }, + }; + const r = await espn.getSeasonAverages('Luka Doncic', 'nba', { http }); + expect(r.found).toBe(true); + expect(r.team).toBe('DAL'); + expect(r.classifierInput.ppg).toBe(33); + }); + + it('degrades to found:false when ESPN errors', async () => { + const http = { get: async () => { throw new Error('espn down'); } }; + expect((await espn.getSeasonAverages('X', 'nba', { http })).found).toBe(false); + }); + + it('returns found:false for non-basketball sports', async () => { + expect((await espn.getSeasonAverages('X', 'mlb')).found).toBe(false); + }); +}); + +describe('resolvePlayerStats wires the ESPN fallback for NBA', () => { + it('falls back to ESPN when nbaStatsClient is offline → classifies', async () => { + const r = await svc.resolvePlayerStats('Luka Doncic', 'nba', { + nbaClient: { getSeasonAvg: async () => { throw new Error('python offline'); } }, + espnStats: { getSeasonAverages: async () => ({ found: true, team: 'DAL', position: 'G', classifierInput: { ppg: 33, apg: 9, rpg: 8 } }) }, + }); + expect(r.found).toBe(true); + expect(r.team).toBe('DAL'); + expect(r.classifierInput.ppg).toBe(33); + }); + + it('found:false when both sources are empty', async () => { + const r = await svc.resolvePlayerStats('Nobody', 'nba', { + nbaClient: { getSeasonAvg: async () => null }, + espnStats: { getSeasonAverages: async () => ({ found: false }) }, + }); + expect(r.found).toBe(false); + }); +}); diff --git a/tests/unit/snapshotOverlay.test.js b/tests/unit/snapshotOverlay.test.js new file mode 100644 index 0000000..061e36f --- /dev/null +++ b/tests/unit/snapshotOverlay.test.js @@ -0,0 +1,81 @@ +// Session 45 — Phase 3: pre-graded snapshot overlay + the GameCard swap. + +const fs = require('fs'); +const path = require('path'); +const WEB = path.join(__dirname, '..', '..', 'web', 'src'); +const read = (rel) => fs.readFileSync(path.join(WEB, rel), 'utf8'); +const a = require('../../web/src/lib/slateAdapter'); + +describe('snapshot overlay adapter', () => { + const grades = [ + { player: 'Aaron Judge', stat_type: 'total_bases', line: 1.5, direction: 'over', grade: 'A+', archetype: 'BOMBER', gradedAt: { line: 1.5, odds: -115, timestamp: '2026-06-18T18:00:00Z' } }, + { player: 'Aaron Judge', stat_type: 'home_runs', line: 0.5, direction: 'over', grade: 'C', archetype: 'BOMBER', gradedAt: { line: 0.5, odds: 120, timestamp: '2026-06-18T18:00:00Z' } }, + ]; + const deltas = [{ player: 'Aaron Judge', stat: 'total_bases', side: 'O', delta: 1.0, direction: 'toward', currentLine: 2.5 }]; + + it('indexes grades + deltas for lookup', () => { + const gi = a.indexGrades(grades); + expect(gi['aaronjudge|total_bases'].grade).toBe('A+'); + const di = a.indexDeltas(deltas); + expect(di['aaronjudge|total_bases|O'].direction).toBe('toward'); + }); + + it('overlays grades onto game props → playerStrips (name once, archetype, gradedAt, delta)', () => { + const gameProps = [ + { player: 'Aaron Judge', stat_type: 'total_bases', line: 1.5 }, + { player: 'Aaron Judge', stat_type: 'home_runs', line: 0.5 }, + ]; + const strips = a.buildPlayerStripsFromProps(gameProps, a.indexGrades(grades), a.indexDeltas(deltas), new Date('2026-06-18T20:00:00Z').getTime()); + expect(strips).toHaveLength(1); // name once + expect(strips[0].archetype).toEqual({ primary: 'BOMBER' }); + const tb = strips[0].props.find((p) => p.stat === 'TB'); + expect(tb.grade).toBe('A+'); + expect(tb.gradedAt.ago).toBe('2h ago'); + expect(tb.gradedAt.odds).toBe(-115); + expect(tb.delta).toEqual({ delta: 1.0, direction: 'toward', currentLine: 2.5 }); + }); + + it('marks ungraded props as awaiting (no Read button)', () => { + const strips = a.buildPlayerStripsFromProps( + [{ player: 'New Guy', stat_type: 'hits', line: 1.5 }], + a.indexGrades(grades), a.indexDeltas(deltas), + ); + expect(strips[0].props[0].awaiting).toBe(true); + expect(strips[0].props[0].grade).toBeNull(); + }); + + it('gradedAgo formats relative time', () => { + const now = new Date('2026-06-18T20:00:00Z').getTime(); + expect(a.gradedAgo('2026-06-18T19:30:00Z', now)).toBe('30m ago'); + expect(a.gradedAgo('2026-06-18T18:00:00Z', now)).toBe('2h ago'); + expect(a.gradedAgo(undefined, now)).toBe(''); + }); +}); + +describe('Slate uses the VYNDR card + pre-graded snapshot (swap is real)', () => { + const src = read('components/Slate.tsx'); + it('imports the VYNDR GameCard component (legacy only for types)', () => { + expect(src).toContain("import VyndrGameCard"); + expect(src).toContain("'@/components/vyndr/GameCard'"); + expect(src).toContain(' { + expect(src).toContain('/api/snapshot/'); + expect(src).toContain('buildPlayerStripsFromProps'); + expect(src).toContain('slateGameToCardData'); + }); + it('retired the on-demand Read grade flow', () => { + expect(src).not.toContain('const onGrade = useCallback'); + }); +}); + +describe('StatStrip renders snapshot states', () => { + const src = read('components/vyndr/StatStrip.tsx'); + it('renders Awaiting next scan + line-delta sub-line', () => { + expect(src).toContain('Awaiting next scan'); + expect(src).toContain('TOWARD'); + expect(src).toContain('Graded '); + }); +}); diff --git a/tests/unit/snapshotScheduler.test.js b/tests/unit/snapshotScheduler.test.js new file mode 100644 index 0000000..9d14bd1 --- /dev/null +++ b/tests/unit/snapshotScheduler.test.js @@ -0,0 +1,38 @@ +// Session 45 — in-process snapshot scheduler (gated, fires once per slot). + +const { startSnapshotScheduler, HOURS_UTC } = require('../../src/snapshotScheduler'); + +afterEach(() => { delete process.env.SNAPSHOT_CRON; }); + +describe('startSnapshotScheduler', () => { + it('no-ops unless SNAPSHOT_CRON=1', () => { + delete process.env.SNAPSHOT_CRON; + expect(startSnapshotScheduler()).toBeNull(); + }); + + it('defaults to the sports-cycle UTC hours', () => { + expect(HOURS_UTC).toEqual([14, 19, 22, 1, 3]); + }); + + it('fires runAllSnapshots at a scheduled hour, once per slot', async () => { + process.env.SNAPSHOT_CRON = '1'; + const runAllSnapshots = jest.fn(async () => [{ sport: 'mlb', status: 'ok' }]); + let d = new Date(Date.UTC(2026, 5, 18, 14, 0, 0)); // 14:00 UTC — scheduled + const sched = startSnapshotScheduler({ runAllSnapshots, now: () => d }); + await sched.tick(); + await sched.tick(); // same slot — must NOT double-fire + expect(runAllSnapshots).toHaveBeenCalledTimes(1); + if (sched.interval && sched.interval.unref) clearInterval(sched.interval); + }); + + it('does not fire off-schedule (wrong hour / non-zero minute)', async () => { + process.env.SNAPSHOT_CRON = '1'; + const runAllSnapshots = jest.fn(); + const sched = startSnapshotScheduler({ runAllSnapshots, now: () => new Date(Date.UTC(2026, 5, 18, 15, 0, 0)) }); + await sched.tick(); + const sched2 = startSnapshotScheduler({ runAllSnapshots, now: () => new Date(Date.UTC(2026, 5, 18, 14, 30, 0)) }); + await sched2.tick(); + expect(runAllSnapshots).not.toHaveBeenCalled(); + [sched, sched2].forEach((s) => s.interval && clearInterval(s.interval)); + }); +}); diff --git a/tests/unit/snapshotService.test.js b/tests/unit/snapshotService.test.js new file mode 100644 index 0000000..47e5e4f --- /dev/null +++ b/tests/unit/snapshotService.test.js @@ -0,0 +1,149 @@ +// Session 45 — snapshot pipeline. Every dependency is injected, so the whole +// cycle runs with zero network / Redis. + +const svc = require('../../src/services/snapshotService'); + +// A tiny in-memory cache to back cacheGet/cacheSet. +function memCache() { + const store = {}; + return { + store, + cacheGet: async (k) => (k in store ? store[k] : null), + cacheSet: async (k, v) => { store[k] = v; }, + }; +} + +const sampleProps = [ + { player: 'Aaron Judge', stat_type: 'total_bases', line: 1.5, over_odds: -115, under_odds: -105, book: 'dk' }, + { player: 'Mookie Betts', stat_type: 'hits', line: 1.5, over_odds: -130, under_odds: 100, book: 'dk' }, +]; + +// Fake grader output captured via gradeAndCacheSlate's cacheSet. +function fakeGradeAndCacheSlate(grades) { + return async (_sport, _props, opts) => { + await opts.cacheSet(`grades:x`, { grades, updated_at: opts.now(), source: 'test' }); + return { written: true, count: grades.length }; + }; +} + +describe('computeLineDeltas', () => { + it('detects movements >= 0.5 and ignores noise', () => { + const prev = [{ player: 'A', stat_type: 'pts', direction: 'over', gradedAt: { line: 26.5 } }]; + const cur = [ + { player: 'A', stat_type: 'pts', direction: 'over', line: 27.5, grade: 'A' }, // +1.0 + { player: 'B', stat_type: 'reb', direction: 'over', line: 9.5, grade: 'B' }, // no prev + ]; + const d = svc.computeLineDeltas(cur, prev); + expect(d).toHaveLength(1); + expect(d[0].delta).toBe(1); + expect(d[0].gradedLine).toBe(26.5); + expect(d[0].currentLine).toBe(27.5); + }); + + it('marks direction toward/away by graded side', () => { + const prev = [ + { player: 'A', stat_type: 'pts', direction: 'over', gradedAt: { line: 26.5 } }, + { player: 'B', stat_type: 'pts', direction: 'under', gradedAt: { line: 20.5 } }, + ]; + const cur = [ + { player: 'A', stat_type: 'pts', direction: 'over', line: 28, grade: 'A' }, // over + rising = toward + { player: 'B', stat_type: 'pts', direction: 'under', line: 22, grade: 'B' }, // under + rising = away + ]; + const d = svc.computeLineDeltas(cur, prev); + expect(d.find((x) => x.player === 'A').direction).toBe('toward'); + expect(d.find((x) => x.player === 'B').direction).toBe('away'); + }); +}); + +describe('generateTickerEvents', () => { + const grades = [ + { player: 'Aaron Judge', stat_type: 'TB', line: 1.5, direction: 'over', grade: 'A+', archetype: 'BOMBER' }, + { player: 'Mookie Betts', stat_type: 'Hits', line: 1.5, direction: 'over', grade: 'B' }, + ]; + it('emits a SCAN summary + GRADE events for A/A+ only', () => { + const ev = svc.generateTickerEvents('mlb', grades, [], '2026-06-18T20:00:00Z'); + expect(ev[0].tag).toBe('SCAN'); + expect(ev[0].text).toContain('2 props graded'); + const grade = ev.find((e) => e.tag === 'A+'); + expect(grade.text).toContain('BOMBER'); + expect(grade.text).toContain('Judge'); + expect(ev.find((e) => e.tag === 'B')).toBeUndefined(); // only top grades + }); + it('emits MOVE events for |delta| >= 1.0', () => { + const deltas = [{ player: 'V Wemby', stat: 'pts', side: 'O', gradedLine: 26.5, currentLine: 27.5, delta: 1.0, direction: 'toward' }]; + const ev = svc.generateTickerEvents('nba', grades, deltas, 't'); + const move = ev.find((e) => e.tag === 'MOVE'); + expect(move.text).toContain('▲+1'); + }); +}); + +describe('runSnapshot (fully injected)', () => { + const baseGrades = [ + { player: 'Aaron Judge', stat_type: 'total_bases', line: 1.5, direction: 'over', grade: 'A+', confidence: 80 }, + { player: 'Mookie Betts', stat_type: 'hits', line: 1.5, direction: 'over', grade: 'B', confidence: 65 }, + ]; + const deps = (cache) => ({ + getOdds: async () => ({ sport: 'mlb', props: sampleProps, provider: 'propline' }), + gradeAndCacheSlate: fakeGradeAndCacheSlate(baseGrades), + resolveStats: async (player) => (player === 'Aaron Judge' + ? { found: true, classifierInput: { hr: 34, avg: 0.28, ops: 0.95, k_rate: 28 } } + : { found: false }), + classify: require('../../src/services/archetypeService').classify, + cacheGet: cache.cacheGet, + cacheSet: cache.cacheSet, + now: () => '2026-06-18T20:00:00Z', + nowMs: () => 1000, + }); + + it('returns an ok summary with gradeCount + topGrades', async () => { + const cache = memCache(); + const r = await svc.runSnapshot('mlb', deps(cache)); + expect(r.status).toBe('ok'); + expect(r.gradeCount).toBe(2); + expect(r.topGrades[0].player).toBe('Aaron Judge'); + expect(r.topGrades[0].archetype).toBe('BOMBER'); // classified from real stats + }); + + it('writes snapshot:{sport}:latest + grades:{sport} with gradedAt + archetype', async () => { + const cache = memCache(); + await svc.runSnapshot('mlb', deps(cache)); + const snap = cache.store['snapshot:mlb:latest']; + expect(snap).toBeTruthy(); + expect(snap.grades[0].gradedAt.line).toBe(1.5); + expect(snap.grades[0].gradedAt.timestamp).toBe('2026-06-18T20:00:00Z'); + expect(snap.grades[0].archetype).toBe('BOMBER'); + expect(cache.store['grades:mlb'].grades).toHaveLength(2); + }); + + it('rotates latest → previous and computes deltas on the second run', async () => { + const cache = memCache(); + let line = 1.5; + const d = deps(cache); + d.gradeAndCacheSlate = (sport, props, opts) => fakeGradeAndCacheSlate([ + { player: 'Aaron Judge', stat_type: 'total_bases', line, direction: 'over', grade: 'A+', confidence: 80 }, + ])(sport, props, opts); + await svc.runSnapshot('mlb', d); + line = 2.5; // line moved +1.0 + const r2 = await svc.runSnapshot('mlb', d); + expect(cache.store['snapshot:mlb:previous']).toBeTruthy(); + expect(r2.deltas).toBe(1); + }); + + it('pushes ticker events (capped) into ticker:items', async () => { + const cache = memCache(); + await svc.runSnapshot('mlb', deps(cache)); + const items = cache.store['ticker:items']; + expect(Array.isArray(items)).toBe(true); + expect(items.find((e) => e.tag === 'SCAN')).toBeTruthy(); + expect(items.length).toBeLessThanOrEqual(50); + }); + + it('skips gracefully on an empty slate', async () => { + const cache = memCache(); + const d = deps(cache); + d.getOdds = async () => ({ sport: 'mlb', props: [] }); + const r = await svc.runSnapshot('mlb', d); + expect(r.status).toBe('skipped'); + expect(r.gradeCount).toBe(0); + }); +}); diff --git a/tests/unit/tickerLive.test.js b/tests/unit/tickerLive.test.js new file mode 100644 index 0000000..ee41674 --- /dev/null +++ b/tests/unit/tickerLive.test.js @@ -0,0 +1,33 @@ +// Session 45 — Phase 4: the ticker polls /api/ticker (snapshot exhaust). + +const fs = require('fs'); +const path = require('path'); +const WEB = path.join(__dirname, '..', '..', 'web', 'src'); +const read = (rel) => fs.readFileSync(path.join(WEB, rel), 'utf8'); + +describe('Ticker live wiring', () => { + const src = read('components/vyndr/Ticker.tsx'); + it('fetches from /api/ticker (not purely hardcoded)', () => { + expect(src).toContain("fetch('/api/ticker'"); + expect(src).toContain('setInterval(load'); + }); + it('polls every 30s by default', () => { + expect(src).toContain('pollMs = 30_000'); + }); + it('falls back to the passed items + keeps current on failure (never blanks)', () => { + expect(src).toContain('feed && feed.length > 0 ? feed : items'); + expect(src).toContain('keep the current items on failure'); + }); + it('colors event tags (A+/MOVE/SCAN/ALERT)', () => { + expect(src).toContain("MOVE: 'var(--amber)'"); + expect(src).toContain("ALERT: 'var(--text-0)'"); + }); +}); + +describe('Ticker Next proxy', () => { + it('exists and forwards to the backend', () => { + const proxy = read('app/api/ticker/route.ts'); + expect(proxy).toContain('/api/ticker'); + expect(proxy).toContain('BACKEND_URL'); + }); +}); diff --git a/web/public/sw.js b/web/public/sw.js index 158e3be..0265ded 100644 --- a/web/public/sw.js +++ b/web/public/sw.js @@ -1,2 +1,2 @@ (()=>{"use strict";let e,t,a,s,r,i={googleAnalytics:"googleAnalytics",precache:"precache-v2",prefix:"serwist",runtime:"runtime",suffix:"u">typeof registration?registration.scope:""},n=e=>[i.prefix,e,i.suffix].filter(e=>e&&e.length>0).join("-"),c=e=>e||n(i.precache),o=e=>e||n(i.runtime);var l=class extends Error{details;constructor(e,t){super(((e,...t)=>{let a=e;return t.length>0&&(a+=` :: ${JSON.stringify(t)}`),a})(e,t)),this.name=e,this.details=t}};function h(e){return new Promise(t=>setTimeout(t,e))}let u=new Set;function d(e,t){let a=new URL(e);for(let e of t)a.searchParams.delete(e);return a.href}async function f(e,t,a,s){let r=d(t.url,a);if(t.url===r)return e.match(t,s);let i={...s,ignoreSearch:!0};for(let n of(await e.keys(t,i)))if(r===d(n.url,a))return e.match(n,s)}var p=class{promise;resolve;reject;constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}};let m=async()=>{for(let e of u)await e()},w="-precache-",g=async(e,t=w)=>{let a=(await self.caches.keys()).filter(a=>a.includes(t)&&a.includes(self.registration.scope)&&a!==e);return await Promise.all(a.map(e=>self.caches.delete(e))),a},y=(e,t)=>{let a=t();return e.waitUntil(a),a},_=(e,t)=>t.some(t=>e instanceof t),b=new WeakMap,v=new WeakMap,R=new WeakMap,E={get(e,t,a){if(e instanceof IDBTransaction){if("done"===t)return b.get(e);if("store"===t)return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return q(e[t])},set:(e,t,a)=>(e[t]=a,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function q(e){if(e instanceof IDBRequest){let t;return t=new Promise((t,a)=>{let s=()=>{e.removeEventListener("success",r),e.removeEventListener("error",i)},r=()=>{t(q(e.result)),s()},i=()=>{a(e.error),s()};e.addEventListener("success",r),e.addEventListener("error",i)}),R.set(t,e),t}if(v.has(e))return v.get(e);let t=function(e){if("function"==typeof e)return(r||(r=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(x(this),t),q(this.request)}:function(...t){return q(e.apply(x(this),t))};return(e instanceof IDBTransaction&&function(e){if(b.has(e))return;let t=new Promise((t,a)=>{let s=()=>{e.removeEventListener("complete",r),e.removeEventListener("error",i),e.removeEventListener("abort",i)},r=()=>{t(),s()},i=()=>{a(e.error||new DOMException("AbortError","AbortError")),s()};e.addEventListener("complete",r),e.addEventListener("error",i),e.addEventListener("abort",i)});b.set(e,t)}(e),_(e,s||(s=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])))?new Proxy(e,E):e}(e);return t!==e&&(v.set(e,t),R.set(t,e)),t}let x=e=>R.get(e);function D(e,t,{blocked:a,upgrade:s,blocking:r,terminated:i}={}){let n=indexedDB.open(e,t),c=q(n);return s&&n.addEventListener("upgradeneeded",e=>{s(q(n.result),e.oldVersion,e.newVersion,q(n.transaction),e)}),a&&n.addEventListener("blocked",e=>a(e.oldVersion,e.newVersion,e)),c.then(e=>{i&&e.addEventListener("close",()=>i()),r&&e.addEventListener("versionchange",e=>r(e.oldVersion,e.newVersion,e))}).catch(()=>{}),c}let S=["get","getKey","getAll","getAllKeys","count"],k=["put","add","delete","clear"],T=new Map;function P(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t))return;if(T.get(t))return T.get(t);let a=t.replace(/FromIndex$/,""),s=t!==a,r=k.includes(a);if(!(a in(s?IDBIndex:IDBObjectStore).prototype)||!(r||S.includes(a)))return;let i=async function(e,...t){let i=this.transaction(e,r?"readwrite":"readonly"),n=i.store;return s&&(n=n.index(t.shift())),(await Promise.all([n[a](...t),r&&i.done]))[0]};return T.set(t,i),i}E={...e=E,get:(t,a,s)=>P(t,a)||e.get(t,a,s),has:(t,a)=>!!P(t,a)||e.has(t,a)};let C=["continue","continuePrimaryKey","advance"],N={},I=new WeakMap,U=new WeakMap,L={get(e,t){if(!C.includes(t))return e[t];let a=N[t];return a||(a=N[t]=function(...e){I.set(this,U.get(this)[t](...e))}),a}};async function*A(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;let a=new Proxy(t,L);for(U.set(a,t),R.set(a,x(t));t;)yield a,t=await (I.get(a)||t.continue()),I.delete(a)}function O(e,t){return t===Symbol.asyncIterator&&_(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&_(e,[IDBIndex,IDBObjectStore])}E={...t=E,get:(e,a,s)=>O(e,a)?A:t.get(e,a,s),has:(e,a)=>O(e,a)||t.has(e,a)};let M=async(e,t)=>{let s=null;if(e.url&&(s=new URL(e.url).origin),s!==self.location.origin)throw new l("cross-origin-copy-response",{origin:s});let r=e.clone(),i={headers:new Headers(r.headers),status:r.status,statusText:r.statusText},n=t?t(i):i,c=!function(){if(void 0===a){let e=new Response("");if("body"in e)try{new Response(e.body),a=!0}catch{a=!1}a=!1}return a}()?await r.blob():r.body;return new Response(c,n)},B="requests",K="queueName";var F=class{_db=null;async addEntry(e){let t=(await this.getDb()).transaction(B,"readwrite",{durability:"relaxed"});await t.store.add(e),await t.done}async getFirstEntryId(){return(await (await this.getDb()).transaction(B).store.openCursor())?.value.id}async getAllEntriesByQueueName(e){return await (await this.getDb()).getAllFromIndex(B,K,IDBKeyRange.only(e))||[]}async getEntryCountByQueueName(e){return(await this.getDb()).countFromIndex(B,K,IDBKeyRange.only(e))}async deleteEntry(e){await (await this.getDb()).delete(B,e)}async getFirstEntryByQueueName(e){return await this.getEndEntryFromIndex(IDBKeyRange.only(e),"next")}async getLastEntryByQueueName(e){return await this.getEndEntryFromIndex(IDBKeyRange.only(e),"prev")}async getEndEntryFromIndex(e,t){return(await (await this.getDb()).transaction(B).store.index(K).openCursor(e,t))?.value}async getDb(){return this._db||(this._db=await D("serwist-background-sync",3,{upgrade:this._upgradeDb})),this._db}_upgradeDb(e,t){t>0&&t<3&&e.objectStoreNames.contains(B)&&e.deleteObjectStore(B),e.createObjectStore(B,{autoIncrement:!0,keyPath:"id"}).createIndex(K,K,{unique:!1})}},W=class{_queueName;_queueDb;constructor(e){this._queueName=e,this._queueDb=new F}async pushEntry(e){delete e.id,e.queueName=this._queueName,await this._queueDb.addEntry(e)}async unshiftEntry(e){let t=await this._queueDb.getFirstEntryId();t?e.id=t-1:delete e.id,e.queueName=this._queueName,await this._queueDb.addEntry(e)}async popEntry(){return this._removeEntry(await this._queueDb.getLastEntryByQueueName(this._queueName))}async shiftEntry(){return this._removeEntry(await this._queueDb.getFirstEntryByQueueName(this._queueName))}async getAll(){return await this._queueDb.getAllEntriesByQueueName(this._queueName)}async size(){return await this._queueDb.getEntryCountByQueueName(this._queueName)}async deleteEntry(e){await this._queueDb.deleteEntry(e)}async _removeEntry(e){return e&&await this.deleteEntry(e.id),e}};let j=["method","referrer","referrerPolicy","mode","credentials","cache","redirect","integrity","keepalive"];var H=class e{_requestData;static async fromRequest(t){let a={url:t.url,headers:{}};for(let e of("GET"!==t.method&&(a.body=await t.clone().arrayBuffer()),t.headers.forEach((e,t)=>{a.headers[t]=e}),j))void 0!==t[e]&&(a[e]=t[e]);return new e(a)}constructor(e){"navigate"===e.mode&&(e.mode="same-origin"),this._requestData=e}toObject(){let e=Object.assign({},this._requestData);return e.headers=Object.assign({},this._requestData.headers),e.body&&(e.body=e.body.slice(0)),e}toRequest(){return new Request(this._requestData.url,this._requestData)}clone(){return new e(this.toObject())}};let $="serwist-background-sync",V=new Set,Q=e=>{let t={request:new H(e.requestData).toRequest(),timestamp:e.timestamp};return e.metadata&&(t.metadata=e.metadata),t};var G=class{_name;_onSync;_maxRetentionTime;_queueStore;_forceSyncFallback;_syncInProgress=!1;_requestsAddedDuringSync=!1;constructor(e,{forceSyncFallback:t,onSync:a,maxRetentionTime:s}={}){if(V.has(e))throw new l("duplicate-queue-name",{name:e});V.add(e),this._name=e,this._onSync=a||this.replayRequests,this._maxRetentionTime=s||10080,this._forceSyncFallback=!!t,this._queueStore=new W(this._name),this._addSyncListener()}get name(){return this._name}async pushRequest(e){await this._addRequest(e,"push")}async unshiftRequest(e){await this._addRequest(e,"unshift")}async popRequest(){return this._removeRequest("pop")}async shiftRequest(){return this._removeRequest("shift")}async getAll(){let e=await this._queueStore.getAll(),t=Date.now(),a=[];for(let s of e){let e=60*this._maxRetentionTime*1e3;t-s.timestamp>e?await this._queueStore.deleteEntry(s.id):a.push(Q(s))}return a}async size(){return await this._queueStore.size()}async _addRequest({request:e,metadata:t,timestamp:a=Date.now()},s){let r={requestData:(await H.fromRequest(e.clone())).toObject(),timestamp:a};switch(t&&(r.metadata=t),s){case"push":await this._queueStore.pushEntry(r);break;case"unshift":await this._queueStore.unshiftEntry(r)}this._syncInProgress?this._requestsAddedDuringSync=!0:await this.registerSync()}async _removeRequest(e){let t,a=Date.now();switch(e){case"pop":t=await this._queueStore.popEntry();break;case"shift":t=await this._queueStore.shiftEntry()}if(t){let s=60*this._maxRetentionTime*1e3;return a-t.timestamp>s?this._removeRequest(e):Q(t)}}async replayRequests(){let e;for(;e=await this.shiftRequest();)try{await fetch(e.request.clone())}catch{throw await this.unshiftRequest(e),new l("queue-replay-failed",{name:this._name})}}async registerSync(){if("sync"in self.registration&&!this._forceSyncFallback)try{await self.registration.sync.register(`${$}:${this._name}`)}catch(e){}}_addSyncListener(){"sync"in self.registration&&!this._forceSyncFallback?self.addEventListener("sync",e=>{if(e.tag===`${$}:${this._name}`){let t=async()=>{let t;this._syncInProgress=!0;try{await this._onSync({queue:this})}catch(e){if(e instanceof Error)throw e}finally{this._requestsAddedDuringSync&&!(t&&!e.lastChance)&&await this.registerSync(),this._syncInProgress=!1,this._requestsAddedDuringSync=!1}};e.waitUntil(t())}}):this._onSync({queue:this})}static get _queueNames(){return V}},z=class{_queue;constructor(e,t){this._queue=new G(e,t)}async fetchDidFail({request:e}){await this._queue.pushRequest({request:e})}};let Y={cacheWillUpdate:async({response:e})=>200===e.status||0===e.status?e:null};function J(e){return"string"==typeof e?new Request(e):e}var X=class{event;request;url;params;_cacheKeys={};_strategy;_handlerDeferred;_extendLifetimePromises;_plugins;_pluginStateMap;constructor(e,t){for(const a of(this.event=t.event,this.request=t.request,t.url&&(this.url=t.url,this.params=t.params),this._strategy=e,this._handlerDeferred=new p,this._extendLifetimePromises=[],this._plugins=[...e.plugins],this._pluginStateMap=new Map,this._plugins))this._pluginStateMap.set(a,{});this.event.waitUntil(this._handlerDeferred.promise)}async fetch(e){let{event:t}=this,a=J(e),s=await this.getPreloadResponse();if(s)return s;let r=this.hasCallback("fetchDidFail")?a.clone():null;try{for(let e of this.iterateCallbacks("requestWillFetch"))a=await e({request:a.clone(),event:t})}catch(e){if(e instanceof Error)throw new l("plugin-error-request-will-fetch",{thrownErrorMessage:e.message})}let i=a.clone();try{let e;for(let s of(e=await fetch(a,"navigate"===a.mode?void 0:this._strategy.fetchOptions),this.iterateCallbacks("fetchDidSucceed")))e=await s({event:t,request:i,response:e});return e}catch(e){throw r&&await this.runCallbacks("fetchDidFail",{error:e,event:t,originalRequest:r.clone(),request:i.clone()}),e}}async fetchAndCachePut(e){let t=await this.fetch(e),a=t.clone();return this.waitUntil(this.cachePut(e,a)),t}async cacheMatch(e){let t,a=J(e),{cacheName:s,matchOptions:r}=this._strategy,i=await this.getCacheKey(a,"read"),n={...r,cacheName:s};for(let e of(t=await caches.match(i,n),this.iterateCallbacks("cachedResponseWillBeUsed")))t=await e({cacheName:s,matchOptions:r,cachedResponse:t,request:i,event:this.event})||void 0;return t}async cachePut(e,t){let a=J(e);await h(0);let s=await this.getCacheKey(a,"write");if(!t)throw new l("cache-put-with-no-response",{url:new URL(String(s.url),location.href).href.replace(RegExp(`^${location.origin}`),"")});let r=await this._ensureResponseSafeToCache(t);if(!r)return!1;let{cacheName:i,matchOptions:n}=this._strategy,c=await self.caches.open(i),o=this.hasCallback("cacheDidUpdate"),u=o?await f(c,s.clone(),["__WB_REVISION__"],n):null;try{await c.put(s,o?r.clone():r)}catch(e){if(e instanceof Error)throw"QuotaExceededError"===e.name&&await m(),e}for(let e of this.iterateCallbacks("cacheDidUpdate"))await e({cacheName:i,oldResponse:u,newResponse:r.clone(),request:s,event:this.event});return!0}async getCacheKey(e,t){let a=`${e.url} | ${t}`;if(!this._cacheKeys[a]){let s=e;for(let e of this.iterateCallbacks("cacheKeyWillBeUsed"))s=J(await e({mode:t,request:s,event:this.event,params:this.params}));this._cacheKeys[a]=s}return this._cacheKeys[a]}hasCallback(e){for(let t of this._strategy.plugins)if(e in t)return!0;return!1}async runCallbacks(e,t){for(let a of this.iterateCallbacks(e))await a(t)}*iterateCallbacks(e){for(let t of this._strategy.plugins)if("function"==typeof t[e]){let a=this._pluginStateMap.get(t),s=s=>{let r={...s,state:a};return t[e](r)};yield s}}waitUntil(e){return this._extendLifetimePromises.push(e),e}async doneWaiting(){let e;for(;e=this._extendLifetimePromises.shift();)await e}destroy(){this._handlerDeferred.resolve(null)}async getPreloadResponse(){if(this.event instanceof FetchEvent&&"navigate"===this.event.request.mode&&"preloadResponse"in this.event)try{let e=await this.event.preloadResponse;if(e)return e}catch(e){return}}async _ensureResponseSafeToCache(e){let t=e,a=!1;for(let e of this.iterateCallbacks("cacheWillUpdate"))if(t=await e({request:this.request,response:t,event:this.event})||void 0,a=!0,!t)break;return!a&&t&&200!==t.status&&(t=void 0),t}},Z=class{cacheName;plugins;fetchOptions;matchOptions;constructor(e={}){this.cacheName=o(e.cacheName),this.plugins=e.plugins||[],this.fetchOptions=e.fetchOptions,this.matchOptions=e.matchOptions}handle(e){let[t]=this.handleAll(e);return t}handleAll(e){e instanceof FetchEvent&&(e={event:e,request:e.request});let t=e.event,a="string"==typeof e.request?new Request(e.request):e.request,s=new X(this,e.url?{event:t,request:a,url:e.url,params:e.params}:{event:t,request:a}),r=this._getResponse(s,a,t);return[r,this._awaitComplete(r,s,a,t)]}async _getResponse(e,t,a){let s;await e.runCallbacks("handlerWillStart",{event:a,request:t});try{if(s=await this._handle(t,e),void 0===s||"error"===s.type)throw new l("no-response",{url:t.url})}catch(r){if(r instanceof Error){for(let i of e.iterateCallbacks("handlerDidError"))if(void 0!==(s=await i({error:r,event:a,request:t})))break}if(!s)throw r}for(let r of e.iterateCallbacks("handlerWillRespond"))s=await r({event:a,request:t,response:s});return s}async _awaitComplete(e,t,a,s){let r,i;try{r=await e}catch{}try{await t.runCallbacks("handlerDidRespond",{event:s,request:a,response:r}),await t.doneWaiting()}catch(e){e instanceof Error&&(i=e)}if(await t.runCallbacks("handlerDidComplete",{event:s,request:a,response:r,error:i}),t.destroy(),i)throw i}},ee=class extends Z{_networkTimeoutSeconds;constructor(e={}){super(e),this.plugins.some(e=>"cacheWillUpdate"in e)||this.plugins.unshift(Y),this._networkTimeoutSeconds=e.networkTimeoutSeconds||0}async _handle(e,t){let a,s=[],r=[];if(this._networkTimeoutSeconds){let{id:i,promise:n}=this._getTimeoutPromise({request:e,logs:s,handler:t});a=i,r.push(n)}let i=this._getNetworkPromise({timeoutId:a,request:e,logs:s,handler:t});r.push(i);let n=await t.waitUntil((async()=>await t.waitUntil(Promise.race(r))||await i)());if(!n)throw new l("no-response",{url:e.url});return n}_getTimeoutPromise({request:e,logs:t,handler:a}){let s;return{promise:new Promise(t=>{s=setTimeout(async()=>{t(await a.cacheMatch(e))},1e3*this._networkTimeoutSeconds)}),id:s}}async _getNetworkPromise({timeoutId:e,request:t,logs:a,handler:s}){let r,i;try{i=await s.fetchAndCachePut(t)}catch(e){e instanceof Error&&(r=e)}return e&&clearTimeout(e),(r||!i)&&(i=await s.cacheMatch(t)),i}},et=class extends Z{_networkTimeoutSeconds;constructor(e={}){super(e),this._networkTimeoutSeconds=e.networkTimeoutSeconds||0}async _handle(e,t){let a,s;try{let a=[t.fetch(e)];if(this._networkTimeoutSeconds){let e=h(1e3*this._networkTimeoutSeconds);a.push(e)}if(!(s=await Promise.race(a)))throw Error(`Timed out the network response after ${this._networkTimeoutSeconds} seconds.`)}catch(e){e instanceof Error&&(a=e)}if(!s)throw new l("no-response",{url:e.url,error:a});return s}};let ea=e=>e&&"object"==typeof e?e:{handle:e};var es=class{handler;match;method;catchHandler;constructor(e,t,a="GET"){this.handler=ea(t),this.match=e,this.method=a}setCatchHandler(e){this.catchHandler=ea(e)}},er=class e extends Z{_fallbackToNetwork;static defaultPrecacheCacheabilityPlugin={cacheWillUpdate:async({response:e})=>!e||e.status>=400?null:e};static copyRedirectedCacheableResponsesPlugin={cacheWillUpdate:async({response:e})=>e.redirected?await M(e):e};constructor(t={}){t.cacheName=c(t.cacheName),super(t),this._fallbackToNetwork=!1!==t.fallbackToNetwork,this.plugins.push(e.copyRedirectedCacheableResponsesPlugin)}async _handle(e,t){let a=await t.getPreloadResponse();if(a)return a;let s=await t.cacheMatch(e);return s||(t.event&&"install"===t.event.type?await this._handleInstall(e,t):await this._handleFetch(e,t))}async _handleFetch(e,t){let a,s=t.params||{};if(this._fallbackToNetwork){let r=s.integrity,i=e.integrity,n=!i||i===r;a=await t.fetch(new Request(e,{integrity:"no-cors"!==e.mode?i||r:void 0})),r&&n&&"no-cors"!==e.mode&&(this._useDefaultCacheabilityPluginIfNeeded(),await t.cachePut(e,a.clone()))}else throw new l("missing-precache-entry",{cacheName:this.cacheName,url:e.url});return a}async _handleInstall(e,t){this._useDefaultCacheabilityPluginIfNeeded();let a=await t.fetch(e);if(!await t.cachePut(e,a.clone()))throw new l("bad-precaching-response",{url:e.url,status:a.status});return a}_useDefaultCacheabilityPluginIfNeeded(){let t=null,a=0;for(let[s,r]of this.plugins.entries())r!==e.copyRedirectedCacheableResponsesPlugin&&(r===e.defaultPrecacheCacheabilityPlugin&&(t=s),r.cacheWillUpdate&&a++);0===a?this.plugins.push(e.defaultPrecacheCacheabilityPlugin):a>1&&null!==t&&this.plugins.splice(t,1)}},ei=class extends es{_allowlist;_denylist;constructor(e,{allowlist:t=[/./],denylist:a=[]}={}){super(e=>this._match(e),e),this._allowlist=t,this._denylist=a}_match({url:e,request:t}){if(t&&"navigate"!==t.mode)return!1;let a=e.pathname+e.search;for(let e of this._denylist)if(e.test(a))return!1;return!!this._allowlist.some(e=>e.test(a))}},en=class extends es{constructor(e,t,a){super(({url:t})=>{let a=e.exec(t.href);if(a)return t.origin!==location.origin&&0!==a.index?void 0:a.slice(1)},t,a)}};let ec=e=>{if(!e)throw new l("add-to-cache-list-unexpected-type",{entry:e});if("string"==typeof e){let t=new URL(e,location.href);return{cacheKey:t.href,url:t.href}}let{revision:t,url:a}=e;if(!a)throw new l("add-to-cache-list-unexpected-type",{entry:e});if(!t){let e=new URL(a,location.href);return{cacheKey:e.href,url:e.href}}let s=new URL(a,location.href),r=new URL(a,location.href);return s.searchParams.set("__WB_REVISION__",t),{cacheKey:s.href,url:r.href}};var eo=class{updatedURLs=[];notUpdatedURLs=[];handlerWillStart=async({request:e,state:t})=>{t&&(t.originalRequest=e)};cachedResponseWillBeUsed=async({event:e,state:t,cachedResponse:a})=>{if("install"===e.type&&t?.originalRequest&&t.originalRequest instanceof Request){let e=t.originalRequest.url;a?this.notUpdatedURLs.push(e):this.updatedURLs.push(e)}return a}};let el=async(e,t,a)=>{let s=t.map((e,t)=>({index:t,item:e})),r=async e=>{let t=[];for(;;){let r=s.pop();if(!r)return e(t);let i=await a(r.item);t.push({result:i,index:r.index})}},i=Array.from({length:e},()=>new Promise(r));return(await Promise.all(i)).flat().sort((e,t)=>e.indexe.result)};"u">typeof navigator&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent);let eh="cache-entries",eu=e=>{let t=new URL(e,location.href);return t.hash="",t.href};var ed=class{_cacheName;_db=null;constructor(e){this._cacheName=e}_getId(e){return`${this._cacheName}|${eu(e)}`}_upgradeDb(e){let t=e.createObjectStore(eh,{keyPath:"id"});t.createIndex("cacheName","cacheName",{unique:!1}),t.createIndex("timestamp","timestamp",{unique:!1})}_upgradeDbAndDeleteOldDbs(e){this._upgradeDb(e),this._cacheName&&function(e,{blocked:t}={}){let a=indexedDB.deleteDatabase(e);t&&a.addEventListener("blocked",e=>t(e.oldVersion,e)),q(a).then(()=>void 0)}(this._cacheName)}async setTimestamp(e,t){e=eu(e);let a={id:this._getId(e),cacheName:this._cacheName,url:e,timestamp:t},s=(await this.getDb()).transaction(eh,"readwrite",{durability:"relaxed"});await s.store.put(a),await s.done}async getTimestamp(e){return(await (await this.getDb()).get(eh,this._getId(e)))?.timestamp}async expireEntries(e,t){let a=await (await this.getDb()).transaction(eh,"readwrite").store.index("timestamp").openCursor(null,"prev"),s=[],r=0;for(;a;){let i=a.value;i.cacheName===this._cacheName&&(e&&i.timestamp=t?(a.delete(),s.push(i.url)):r++),a=await a.continue()}return s}async getDb(){return this._db||(this._db=await D("serwist-expiration",1,{upgrade:this._upgradeDbAndDeleteOldDbs.bind(this)})),this._db}},ef=class{_isRunning=!1;_rerunRequested=!1;_maxEntries;_maxAgeSeconds;_matchOptions;_cacheName;_timestampModel;constructor(e,t={}){this._maxEntries=t.maxEntries,this._maxAgeSeconds=t.maxAgeSeconds,this._matchOptions=t.matchOptions,this._cacheName=e,this._timestampModel=new ed(e)}async expireEntries(){if(this._isRunning){this._rerunRequested=!0;return}this._isRunning=!0;let e=this._maxAgeSeconds?Date.now()-1e3*this._maxAgeSeconds:0,t=await this._timestampModel.expireEntries(e,this._maxEntries),a=await self.caches.open(this._cacheName);for(let e of t)await a.delete(e,this._matchOptions);this._isRunning=!1,this._rerunRequested&&(this._rerunRequested=!1,this.expireEntries())}async updateTimestamp(e){await this._timestampModel.setTimestamp(e,Date.now())}async isURLExpired(e){if(!this._maxAgeSeconds)return!1;let t=await this._timestampModel.getTimestamp(e),a=Date.now()-1e3*this._maxAgeSeconds;return void 0===t||t{u.add(e)})(()=>this.deleteCacheAndMetadata())}_getCacheExpiration(e){if(e===o())throw new l("expire-custom-caches-only");let t=this._cacheExpirations.get(e);return t||(t=new ef(e,this._config),this._cacheExpirations.set(e,t)),t}cachedResponseWillBeUsed({event:e,cacheName:t,request:a,cachedResponse:s}){if(!s)return null;let r=this._isResponseDateFresh(s),i=this._getCacheExpiration(t),n="last-used"===this._config.maxAgeFrom,c=(async()=>{n&&await i.updateTimestamp(a.url),await i.expireEntries()})();try{e.waitUntil(c)}catch{}return r?s:null}_isResponseDateFresh(e){if("last-used"===this._config.maxAgeFrom)return!0;let t=Date.now();if(!this._config.maxAgeSeconds)return!0;let a=this._getDateHeaderTimestamp(e);return null===a||a>=t-1e3*this._config.maxAgeSeconds}_getDateHeaderTimestamp(e){if(!e.headers.has("date"))return null;let t=new Date(e.headers.get("date")).getTime();return Number.isNaN(t)?null:t}async cacheDidUpdate({cacheName:e,request:t}){let a=this._getCacheExpiration(e);await a.updateTimestamp(t.url),await a.expireEntries()}async deleteCacheAndMetadata(){for(let[e,t]of this._cacheExpirations)await self.caches.delete(e),await t.delete();this._cacheExpirations=new Map}};let em=/^\/(\w+\/)?collect/,ew=({serwist:e,cacheName:t,...a})=>{let s,r,c=t||n(i.googleAnalytics),o=new z("serwist-google-analytics",{maxRetentionTime:2880,onSync:async({queue:e})=>{let t;for(;t=await e.shiftRequest();){let{request:s,timestamp:r}=t,i=new URL(s.url);try{let e="POST"===s.method?new URLSearchParams(await s.clone().text()):i.searchParams,t=r-(Number(e.get("qt"))||0),n=Date.now()-t;if(e.set("qt",String(n)),a.parameterOverrides)for(let t of Object.keys(a.parameterOverrides)){let s=a.parameterOverrides[t];e.set(t,s)}"function"==typeof a.hitFilter&&a.hitFilter.call(null,e),await fetch(new Request(i.origin+i.pathname,{body:e.toString(),method:"POST",mode:"cors",credentials:"omit",headers:{"Content-Type":"text/plain"}}))}catch(a){throw await e.unshiftRequest(t),a}}}});for(let t of[new es(({url:e})=>"www.googletagmanager.com"===e.hostname&&"/gtm.js"===e.pathname,new ee({cacheName:c}),"GET"),new es(({url:e})=>"www.google-analytics.com"===e.hostname&&"/analytics.js"===e.pathname,new ee({cacheName:c}),"GET"),new es(({url:e})=>"www.googletagmanager.com"===e.hostname&&"/gtag/js"===e.pathname,new ee({cacheName:c}),"GET"),new es(s=({url:e})=>"www.google-analytics.com"===e.hostname&&em.test(e.pathname),r=new et({plugins:[o]}),"GET"),new es(s,r,"POST")])e.registerRoute(t)};var eg=class{_fallbackUrls;_serwist;constructor({fallbackUrls:e,serwist:t}){this._fallbackUrls=e,this._serwist=t}async handlerDidError(e){for(let t of this._fallbackUrls)if("string"==typeof t){let e=await this._serwist.matchPrecache(t);if(void 0!==e)return e}else if(t.matcher(e)){let e=await this._serwist.matchPrecache(t.url);if(void 0!==e)return e}}},ey=class extends Z{async _handle(e,t){let a,s=await t.cacheMatch(e);if(s);else try{s=await t.fetchAndCachePut(e)}catch(e){e instanceof Error&&(a=e)}if(!s)throw new l("no-response",{url:e.url,error:a});return s}},e_=class extends es{constructor(e,t){super(({request:a})=>{let s=e.getUrlsToPrecacheKeys();for(let r of function*(e,{directoryIndex:t="index.html",ignoreURLParametersMatching:a=[/^utm_/,/^fbclid$/],cleanURLs:s=!0,urlManipulation:r}={}){let i=new URL(e,location.href);i.hash="",yield i.href;let n=((e,t=[])=>{for(let a of[...e.searchParams.keys()])t.some(e=>e.test(a))&&e.searchParams.delete(a);return e})(i,a);if(yield n.href,t&&n.pathname.endsWith("/")){let e=new URL(n.href);e.pathname+=t,yield e.href}if(s){let e=new URL(n.href);e.pathname+=".html",yield e.href}if(r)for(let e of r({url:i}))yield e.href}(a.url,t)){let t=s.get(r);if(t)return{cacheKey:t,integrity:e.getIntegrityForPrecacheKey(t)}}},e.precacheStrategy)}},eb=class{_precacheController;constructor({precacheController:e}){this._precacheController=e}cacheKeyWillBeUsed=async({request:e,params:t})=>{let a=t?.cacheKey||this._precacheController.getPrecacheKeyForUrl(e.url);return a?new Request(a,{headers:e.headers}):e}},ev=class{_urlsToCacheKeys=new Map;_urlsToCacheModes=new Map;_cacheKeysToIntegrities=new Map;_concurrentPrecaching;_precacheStrategy;_routes;_defaultHandlerMap;_catchHandler;_requestRules;constructor({precacheEntries:e,precacheOptions:t,skipWaiting:a=!1,importScripts:s,navigationPreload:r=!1,cacheId:n,clientsClaim:o=!1,runtimeCaching:l,offlineAnalyticsConfig:h,disableDevLogs:u=!1,fallbacks:d,requestRules:f}={}){const{precacheStrategyOptions:p,precacheRouteOptions:m,precacheMiscOptions:w}=((e,t={})=>{let{cacheName:a,plugins:s=[],fetchOptions:r,matchOptions:i,fallbackToNetwork:n,directoryIndex:o,ignoreURLParametersMatching:l,cleanURLs:h,urlManipulation:u,cleanupOutdatedCaches:d,concurrency:f=10,navigateFallback:p,navigateFallbackAllowlist:m,navigateFallbackDenylist:w}=t??{};return{precacheStrategyOptions:{cacheName:c(a),plugins:[...s,new eb({precacheController:e})],fetchOptions:r,matchOptions:i,fallbackToNetwork:n},precacheRouteOptions:{directoryIndex:o,ignoreURLParametersMatching:l,cleanURLs:h,urlManipulation:u},precacheMiscOptions:{cleanupOutdatedCaches:d,concurrency:f,navigateFallback:p,navigateFallbackAllowlist:m,navigateFallbackDenylist:w}}})(this,t);if(this._concurrentPrecaching=w.concurrency,this._precacheStrategy=new er(p),this._routes=new Map,this._defaultHandlerMap=new Map,this._requestRules=f,this.handleInstall=this.handleInstall.bind(this),this.handleActivate=this.handleActivate.bind(this),this.handleFetch=this.handleFetch.bind(this),this.handleCache=this.handleCache.bind(this),s&&s.length>0&&self.importScripts(...s),r&&self.registration?.navigationPreload&&self.addEventListener("activate",e=>{e.waitUntil(self.registration.navigationPreload.enable().then(()=>{}))}),void 0!==n&&(e=>{var t=e;for(let e of Object.keys(i))(e=>{let a=t[e];"string"==typeof a&&(i[e]=a)})(e)})({prefix:n}),a?self.skipWaiting():self.addEventListener("message",e=>{e.data&&"SKIP_WAITING"===e.data.type&&self.skipWaiting()}),o&&self.addEventListener("activate",()=>self.clients.claim()),e&&e.length>0&&this.addToPrecacheList(e),w.cleanupOutdatedCaches&&(e=>{self.addEventListener("activate",t=>{t.waitUntil(g(c(e)).then(e=>{}))})})(p.cacheName),this.registerRoute(new e_(this,m)),w.navigateFallback&&this.registerRoute(new ei(this.createHandlerBoundToUrl(w.navigateFallback),{allowlist:w.navigateFallbackAllowlist,denylist:w.navigateFallbackDenylist})),void 0!==h&&("boolean"==typeof h?h&&ew({serwist:this}):ew({...h,serwist:this})),void 0!==l){if(void 0!==d){const e=new eg({fallbackUrls:d.entries,serwist:this});l.forEach(t=>{t.handler instanceof Z&&!t.handler.plugins.some(e=>"handlerDidError"in e)&&t.handler.plugins.push(e)})}for(const e of l)this.registerCapture(e.matcher,e.handler,e.method)}u&&(self.__WB_DISABLE_DEV_LOGS=!0)}get precacheStrategy(){return this._precacheStrategy}get routes(){return this._routes}addEventListeners(){self.addEventListener("install",this.handleInstall),self.addEventListener("activate",this.handleActivate),self.addEventListener("fetch",this.handleFetch),self.addEventListener("message",this.handleCache)}addToPrecacheList(e){let t=[];for(let a of e){"string"==typeof a?t.push(a):a&&!a.integrity&&void 0===a.revision&&t.push(a.url);let{cacheKey:e,url:s}=ec(a),r="string"!=typeof a&&a.revision?"reload":"default";if(this._urlsToCacheKeys.has(s)&&this._urlsToCacheKeys.get(s)!==e)throw new l("add-to-cache-list-conflicting-entries",{firstEntry:this._urlsToCacheKeys.get(s),secondEntry:e});if("string"!=typeof a&&a.integrity){if(this._cacheKeysToIntegrities.has(e)&&this._cacheKeysToIntegrities.get(e)!==a.integrity)throw new l("add-to-cache-list-conflicting-integrities",{url:s});this._cacheKeysToIntegrities.set(e,a.integrity)}this._urlsToCacheKeys.set(s,e),this._urlsToCacheModes.set(s,r)}t.length>0&&console.warn(`Serwist is precaching URLs without revision info: ${t.join(", ")} -This is generally NOT safe. Learn more at https://bit.ly/wb-precache`)}handleInstall(e){return this.registerRequestRules(e),y(e,async()=>{let t=new eo;this.precacheStrategy.plugins.push(t),await el(this._concurrentPrecaching,Array.from(this._urlsToCacheKeys.entries()),async([t,a])=>{let s=this._cacheKeysToIntegrities.get(a),r=this._urlsToCacheModes.get(t),i=new Request(t,{integrity:s,cache:r,credentials:"same-origin"});await Promise.all(this.precacheStrategy.handleAll({event:e,request:i,url:new URL(i.url),params:{cacheKey:a}}))});let{updatedURLs:a,notUpdatedURLs:s}=t;return{updatedURLs:a,notUpdatedURLs:s}})}async registerRequestRules(e){if(this._requestRules&&e?.addRoutes)try{await e.addRoutes(this._requestRules),this._requestRules=void 0}catch(e){throw e}}handleActivate(e){return y(e,async()=>{let e=await self.caches.open(this.precacheStrategy.cacheName),t=await e.keys(),a=new Set(this._urlsToCacheKeys.values()),s=[];for(let r of t)a.has(r.url)||(await e.delete(r),s.push(r.url));return{deletedCacheRequests:s}})}handleFetch(e){let{request:t}=e,a=this.handleRequest({request:t,event:e});a&&e.respondWith(a)}handleCache(e){if(e.data&&"CACHE_URLS"===e.data.type){let{payload:t}=e.data,a=Promise.all(t.urlsToCache.map(t=>{let a;return a="string"==typeof t?new Request(t):new Request(...t),this.handleRequest({request:a,event:e})}));e.waitUntil(a),e.ports?.[0]&&a.then(()=>e.ports[0].postMessage(!0))}}setDefaultHandler(e,t="GET"){this._defaultHandlerMap.set(t,ea(e))}setCatchHandler(e){this._catchHandler=ea(e)}registerCapture(e,t,a){let s=((e,t,a)=>{if("string"==typeof e){let s=new URL(e,location.href);return new es(({url:e})=>e.href===s.href,t,a)}if(e instanceof RegExp)return new en(e,t,a);if("function"==typeof e)return new es(e,t,a);if(e instanceof es)return e;throw new l("unsupported-route-type",{moduleName:"serwist",funcName:"parseRoute",paramName:"capture"})})(e,t,a);return this.registerRoute(s),s}registerRoute(e){this._routes.has(e.method)||this._routes.set(e.method,[]),this._routes.get(e.method).push(e)}unregisterRoute(e){if(!this._routes.has(e.method))throw new l("unregister-route-but-not-found-with-method",{method:e.method});let t=this._routes.get(e.method).indexOf(e);if(t>-1)this._routes.get(e.method).splice(t,1);else throw new l("unregister-route-route-not-registered")}getUrlsToPrecacheKeys(){return this._urlsToCacheKeys}getPrecachedUrls(){return[...this._urlsToCacheKeys.keys()]}getPrecacheKeyForUrl(e){let t=new URL(e,location.href);return this._urlsToCacheKeys.get(t.href)}getIntegrityForPrecacheKey(e){return this._cacheKeysToIntegrities.get(e)}async matchPrecache(e){let t=e instanceof Request?e.url:e,a=this.getPrecacheKeyForUrl(t);if(a)return(await self.caches.open(this.precacheStrategy.cacheName)).match(a)}createHandlerBoundToUrl(e){let t=this.getPrecacheKeyForUrl(e);if(!t)throw new l("non-precached-url",{url:e});return a=>(a.request=new Request(e),a.params={cacheKey:t,...a.params},this.precacheStrategy.handle(a))}handleRequest({request:e,event:t}){let a,s=new URL(e.url,location.href);if(!s.protocol.startsWith("http"))return;let r=s.origin===location.origin,{params:i,route:n}=this.findMatchingRoute({event:t,request:e,sameOrigin:r,url:s}),c=n?.handler,o=e.method;if(!c&&this._defaultHandlerMap.has(o)&&(c=this._defaultHandlerMap.get(o)),!c)return;try{a=c.handle({url:s,request:e,event:t,params:i})}catch(e){a=Promise.reject(e)}let l=n?.catchHandler;return a instanceof Promise&&(this._catchHandler||l)&&(a=a.catch(async a=>{if(l)try{return await l.handle({url:s,request:e,event:t,params:i})}catch(e){e instanceof Error&&(a=e)}if(this._catchHandler)return this._catchHandler.handle({url:s,request:e,event:t});throw a})),a}findMatchingRoute({url:e,sameOrigin:t,request:a,event:s}){for(let r of this._routes.get(a.method)||[]){let i,n=r.match({url:e,sameOrigin:t,request:a,event:s});if(n)return Array.isArray(i=n)&&0===i.length||n.constructor===Object&&0===Object.keys(n).length?i=void 0:"boolean"==typeof n&&(i=void 0),{route:r,params:i}}return{}}};let eR="/offline",eE=["pages","api-responses","next-static","static-media","fallback","offline-fallback"],eq=[{matcher:({url:e,sameOrigin:t})=>t&&e.pathname.startsWith("/api/"),handler:new ee({cacheName:"api-responses",networkTimeoutSeconds:5,plugins:[new ep({maxEntries:100,maxAgeSeconds:3600})]})},{matcher:({request:e})=>"navigate"===e.mode,handler:new ee({cacheName:"pages",networkTimeoutSeconds:5,plugins:[new ep({maxEntries:50,maxAgeSeconds:86400}),{handlerDidError:async()=>await caches.match(eR)||Response.error()}]})},{matcher:({url:e,sameOrigin:t})=>t&&e.pathname.startsWith("/_next/static/"),handler:new ey({cacheName:"next-static",plugins:[new ep({maxEntries:200,maxAgeSeconds:2592e3})]})},{matcher:({url:e})=>e.pathname.startsWith("/images/")||e.pathname.startsWith("/icons/")||/\.(?:png|jpe?g|gif|svg|webp|ico|woff2?)$/.test(e.pathname),handler:new ey({cacheName:"static-media",plugins:[new ep({maxEntries:100,maxAgeSeconds:2592e3})]})},{matcher:()=>!0,handler:new ee({cacheName:"fallback",networkTimeoutSeconds:5,plugins:[new ep({maxEntries:50,maxAgeSeconds:86400})]})}];new ev({precacheEntries:[{'revision':null,'url':'/_next/static/chunks/1079-304a546a4a673437.js'},{'revision':null,'url':'/_next/static/chunks/1896-359ed2e68a8c4f1d.js'},{'revision':null,'url':'/_next/static/chunks/1958-56cbbb8dba15fd2f.js'},{'revision':null,'url':'/_next/static/chunks/2346-36e36720a5f6591a.js'},{'revision':null,'url':'/_next/static/chunks/3268-0a7190b483de059a.js'},{'revision':null,'url':'/_next/static/chunks/4bd1b696-e356ca5ba0218e27.js'},{'revision':null,'url':'/_next/static/chunks/52774a7f.f2ab7a9b4b8ba576.js'},{'revision':null,'url':'/_next/static/chunks/5838-7e0aa455e9f24259.js'},{'revision':null,'url':'/_next/static/chunks/7117-207a7246fa92b547.js'},{'revision':null,'url':'/_next/static/chunks/7363-209a1a709d8f324d.js'},{'revision':null,'url':'/_next/static/chunks/7602.2868ff821d53ee09.js'},{'revision':null,'url':'/_next/static/chunks/7918-9cfe56e3ee27ed27.js'},{'revision':null,'url':'/_next/static/chunks/8500-f62a38ff68ab7f42.js'},{'revision':null,'url':'/_next/static/chunks/983-3a3522324101948e.js'},{'revision':null,'url':'/_next/static/chunks/9da6db1e-9623f3245f088d02.js'},{'revision':null,'url':'/_next/static/chunks/app/_global-error/page-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/_not-found/page-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/about/page-b78d804f2759f7dc.js'},{'revision':null,'url':'/_next/static/chunks/app/account/page-9300f08c33aa8887.js'},{'revision':null,'url':'/_next/static/chunks/app/admin/page-b3b6af59ae9681bb.js'},{'revision':null,'url':'/_next/static/chunks/app/api/admin/stats/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/books/%5B...path%5D/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/checkout/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/content/%5B...path%5D/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/gamelines/%5Bsport%5D/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/games/%5Bid%5D/props/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/games/%5Bid%5D/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/games/tonight/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/hero-prop/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/hotlist/%5Bsport%5D/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/intelligence/feed/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ledger/accuracy/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ledger/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/lines/%5B...path%5D/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/mlb/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/nba/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/soccer/%5Bleague%5D/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/wnba/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/parlay/add-leg/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/parlay/calculate/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/parlay/grade/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/players/search/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/props/live/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/props/most-parlayed/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/props/top-graded/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/scan/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/schedule/%5Bsport%5D/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/cascade/%5Bplayer%5D/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/depth/%5Bteam%5D/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/leaders/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/lineup/%5Bteam%5D/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/parlays-graded/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/player/%5Bname%5D/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/public/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/streaks/%5Bsport%5D/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/user/profile/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/user/recent-scans/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/user/scans/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/waitlist/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/webhook/nexapay/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/api/welcome-email/route-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/auth/callback/page-e6df9771a50edb87.js'},{'revision':null,'url':'/_next/static/chunks/app/blog/%5Bslug%5D/page-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/blog/page-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/compare/page-5e631b0c698c6f5f.js'},{'revision':null,'url':'/_next/static/chunks/app/dashboard/page-a0dbaaf9df3645f2.js'},{'revision':null,'url':'/_next/static/chunks/app/explore/page-8856c642532e2773.js'},{'revision':null,'url':'/_next/static/chunks/app/forgot-password/page-a251f52b4206e8d1.js'},{'revision':null,'url':'/_next/static/chunks/app/game/%5Bid%5D/page-ac9d9a479ea7ab89.js'},{'revision':null,'url':'/_next/static/chunks/app/help/page-03c6534f006d09da.js'},{'revision':null,'url':'/_next/static/chunks/app/intelligence/page-772d69c9ecfe1503.js'},{'revision':null,'url':'/_next/static/chunks/app/invite/page-e1e3f46af5f1e44b.js'},{'revision':null,'url':'/_next/static/chunks/app/layout-94ab8755a348e2ac.js'},{'revision':null,'url':'/_next/static/chunks/app/ledger/page-47459e4f664b707a.js'},{'revision':null,'url':'/_next/static/chunks/app/login/page-fb8804a2532d10b8.js'},{'revision':null,'url':'/_next/static/chunks/app/marketplace/page-cbada49ae96a7527.js'},{'revision':null,'url':'/_next/static/chunks/app/not-found-c8c8c338b54c2369.js'},{'revision':null,'url':'/_next/static/chunks/app/notifications/page-b78d804f2759f7dc.js'},{'revision':null,'url':'/_next/static/chunks/app/offline/page-a7a57ff039afc1af.js'},{'revision':null,'url':'/_next/static/chunks/app/page-a5e46597b4d1d6b1.js'},{'revision':null,'url':'/_next/static/chunks/app/player/%5Bname%5D/page-a9a1a22752478255.js'},{'revision':null,'url':'/_next/static/chunks/app/pricing/page-049fa136ce667e3e.js'},{'revision':null,'url':'/_next/static/chunks/app/privacy/page-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/profile/page-d607627acb1b73ab.js'},{'revision':null,'url':'/_next/static/chunks/app/report/page-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/responsible-gambling/page-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/scan/page-9cf453400fd9bd5b.js'},{'revision':null,'url':'/_next/static/chunks/app/settings/page-25678f7d56db0a16.js'},{'revision':null,'url':'/_next/static/chunks/app/settings/security/page-697d02aa2d05cf7e.js'},{'revision':null,'url':'/_next/static/chunks/app/signup/page-b6917fd30dbecebe.js'},{'revision':null,'url':'/_next/static/chunks/app/soccer/page-5a64e650908111d7.js'},{'revision':null,'url':'/_next/static/chunks/app/terminal/page-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/terms/page-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/app/tracker/page-e23baec2b3735bb1.js'},{'revision':null,'url':'/_next/static/chunks/app/upgrade/cancel/page-3702e818a6853705.js'},{'revision':null,'url':'/_next/static/chunks/app/upgrade/desk/page-24eaa80743986159.js'},{'revision':null,'url':'/_next/static/chunks/app/upgrade/success/page-ea358cb8f714f1ea.js'},{'revision':null,'url':'/_next/static/chunks/app/verify/page-9df376f065215168.js'},{'revision':null,'url':'/_next/static/chunks/app/welcome/page-259277230533599f.js'},{'revision':null,'url':'/_next/static/chunks/framework-95da69ac6843d788.js'},{'revision':null,'url':'/_next/static/chunks/main-a354262253293123.js'},{'revision':null,'url':'/_next/static/chunks/main-app-4231d5f500f33972.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/app-error-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/forbidden-eebe9d0829c9ea07.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/global-error-756d787dba63aa4d.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/unauthorized-eebe9d0829c9ea07.js'},{'revision':'846118c33b2c0e922d7b3a7676f81f6f','url':'/_next/static/chunks/polyfills-42372ed130431b0a.js'},{'revision':null,'url':'/_next/static/chunks/webpack-42b9616650231776.js'},{'revision':null,'url':'/_next/static/css/e3440a4469d87735.css'},{'revision':'cd34c7793d9776838308cfbe5d93922b','url':'/_next/static/media/011e180705008d6f-s.woff2'},{'revision':'324703f03c390d2e2a4f387de85fe63d','url':'/_next/static/media/0aa834ed78bf6d07-s.woff2'},{'revision':'9dda5cfc9a46f256d0e131bb535e46f8','url':'/_next/static/media/19cfc7226ec3afaa-s.woff2'},{'revision':'7de6d31e5076eb437418b6e01998ee12','url':'/_next/static/media/20535187d867b7b9-s.woff2'},{'revision':'4e2553027f1d60eff32898367dd4d541','url':'/_next/static/media/21350d82a1f187e9-s.woff2'},{'revision':'0d11e07b5aaafda6ae2efc53256932ec','url':'/_next/static/media/37786be940ec402b-s.p.woff2'},{'revision':'5de0bff80f9f432b5cf52c1c2f80fe20','url':'/_next/static/media/46e154b2fcbd6033-s.woff2'},{'revision':'6041b3192dc3e1a50141d5d418a24199','url':'/_next/static/media/5356a6a4f2c8c8d8-s.woff2'},{'revision':'f572f7b57d27ec7fd8373961f0b762b0','url':'/_next/static/media/58f386aa6b1a2a92-s.woff2'},{'revision':'e829cbe042e8b2b2e6b99c0eec9e230d','url':'/_next/static/media/656feb427634a431-s.woff2'},{'revision':'54f02056e07c55023315568c637e3a96','url':'/_next/static/media/67957d42bae0796d-s.woff2'},{'revision':'e220ad1849c282590e47db0ff88fc3f3','url':'/_next/static/media/704b853f32d191d5-s.woff2'},{'revision':'662cde3543f3375874e26c26845cec22','url':'/_next/static/media/73cb51aac9c97f90-s.woff2'},{'revision':'afac1fab355fe8db5c2dcaa7623dffb3','url':'/_next/static/media/7ba5fb2a8c88521c-s.woff2'},{'revision':'c94e6e6c23e789fcb0fc60d790c9d2c1','url':'/_next/static/media/886030b0b59bc5a7-s.woff2'},{'revision':'01ba6c2a184b8cba08b0d57167664d75','url':'/_next/static/media/8e9860b6e62d6359-s.woff2'},{'revision':'17a5b2a15bf5647b49cadb9a3bb02e1c','url':'/_next/static/media/92eeb95d069020cc-s.woff2'},{'revision':'4a4e74bed5809194e4bc6538eb1a1e30','url':'/_next/static/media/939c4f875ee75fbb-s.woff2'},{'revision':'6708425c446b05de1c2d471a0eaf4099','url':'/_next/static/media/98e207f02528a563-s.p.woff2'},{'revision':'13dface50f6dc0bff1015561c84119e6','url':'/_next/static/media/991629005c80bdf1-s.woff2'},{'revision':'216ee1a35b060106ed2852cdd8c026c7','url':'/_next/static/media/99dcf268bda04fe5-s.woff2'},{'revision':'9e494903d6b0ffec1a1e14d34427d44d','url':'/_next/static/media/ba9851c3c22cd980-s.woff2'},{'revision':'782150e6836b9b074d1a798807adcb18','url':'/_next/static/media/bb3ef058b751a6ad-s.p.woff2'},{'revision':'027a89e9ab733a145db70f09b8a18b42','url':'/_next/static/media/c5fe6dc8356a8c31-s.woff2'},{'revision':'75fa2e527eaae805bbf44e3378d1232c','url':'/_next/static/media/d26bbd13d6b70f89-s.woff2'},{'revision':'0ba762bde65aaa682fcc089f8c57288e','url':'/_next/static/media/d29838c109ef09b4-s.woff2'},{'revision':'814fe1615d4dbc7bbd92d26a6bda0905','url':'/_next/static/media/d3ebbfd689654d3a-s.p.woff2'},{'revision':'e71a597e376ed91862e822b5a5de8c04','url':'/_next/static/media/db96af6b531dc71f-s.p.woff2'},{'revision':'d54db44de5ccb18886ece2fda72bdfe0','url':'/_next/static/media/df0a9ae256c0569c-s.woff2'},{'revision':'9fb609fe01d739bb9df558e1fba2498e','url':'/_next/static/media/e40af3453d7c920a-s.woff2'},{'revision':'65850a373e258f1c897a2b3d75eb74de','url':'/_next/static/media/e4af272ccee01ff0-s.p.woff2'},{'revision':'de1d49f26130d43f91829088086625f4','url':'/_next/static/media/ef4d5661765d0e49-s.woff2'},{'revision':'0f8d347d49960d05c9430d83e49edeb7','url':'/_next/static/media/f911b923c6adde36-s.woff2'},{'revision':'4bc708c55b4aa5e00744888c6e3e39eb','url':'/_next/static/wiWR1WsBdedvPC0hW5N-t/_buildManifest.js'},{'revision':'b6652df95db52feb4daf4eca35380933','url':'/_next/static/wiWR1WsBdedvPC0hW5N-t/_ssgManifest.js'},{'revision':'d7bc0f63f9618b8b700d028d7d242de8','url':'/apple-touch-icon.png'},{'revision':'5616f81ec5f8a9f726a17fb7ac66a54a','url':'/favicon-16.png'},{'revision':'1fc285cfb0116a0523eb34c779a7d282','url':'/favicon-32.png'},{'revision':'583b034f36839a8af92841771eef38b6','url':'/favicon.ico'},{'revision':'b15795128b3691e5703d0ce14ce10827','url':'/favicon.png'},{'revision':'44e9d71551be13574ac2e10063d03aa9','url':'/favicon.svg'},{'revision':'252b8f8c4d0f64c7cd120f182a6c74ab','url':'/icon-192.png'},{'revision':'3e3b53bbd210bd772b36b70165657e7c','url':'/icon-512.png'},{'revision':'252b8f8c4d0f64c7cd120f182a6c74ab','url':'/icons/icon-192.png'},{'revision':'3e3b53bbd210bd772b36b70165657e7c','url':'/icons/icon-512.png'},{'revision':'3e3b53bbd210bd772b36b70165657e7c','url':'/icons/icon-maskable-512.png'},{'revision':'bf670b1fafa1b3127bd50abe86d723b9','url':'/images/player-silhouette.svg'},{'revision':'d692f690fbd1564f090131e02be5ba9c','url':'/manifest.json'},{'revision':'9f61cf51298661d5c57a782534216240','url':'/og-image.png'},{'revision':'7c759c20b35840eacf9344692cb51061','url':'/og-image.svg'},{'revision':'9327802333275f11e68c3f19f20c160d','url':'/widget.js'}],skipWaiting:!0,clientsClaim:!0,navigationPreload:!0,runtimeCaching:eq}).addEventListeners(),self.addEventListener("install",e=>{e.waitUntil(caches.open("offline-fallback").then(e=>e.add(eR)).catch(()=>{}))}),self.addEventListener("activate",e=>{e.waitUntil(caches.keys().then(e=>Promise.all(e.filter(e=>!eE.includes(e)&&!e.startsWith("serwist")).map(e=>(console.log("[SW] deleting stale cache:",e),caches.delete(e))))))}),self.addEventListener("push",e=>{let t;if(!e.data)return;try{t=e.data.json()}catch{t={title:"VYNDR",body:e.data.text()}}let{title:a="VYNDR",body:s="",icon:r="/icons/icon-192.png",url:i="/",tag:n="vyndr-notification"}=t;e.waitUntil(self.registration.showNotification(a,{body:s,icon:r,badge:"/icons/icon-192.png",tag:n,data:{url:i}}))}),self.addEventListener("notificationclick",e=>{e.notification.close();let t=e.notification.data?.url??"/";e.waitUntil(self.clients.matchAll({type:"window",includeUncontrolled:!0}).then(e=>{let a=e.find(e=>e.url.endsWith(t));return a?a.focus():self.clients.openWindow(t)}))})})(); \ No newline at end of file +This is generally NOT safe. Learn more at https://bit.ly/wb-precache`)}handleInstall(e){return this.registerRequestRules(e),y(e,async()=>{let t=new eo;this.precacheStrategy.plugins.push(t),await el(this._concurrentPrecaching,Array.from(this._urlsToCacheKeys.entries()),async([t,a])=>{let s=this._cacheKeysToIntegrities.get(a),r=this._urlsToCacheModes.get(t),i=new Request(t,{integrity:s,cache:r,credentials:"same-origin"});await Promise.all(this.precacheStrategy.handleAll({event:e,request:i,url:new URL(i.url),params:{cacheKey:a}}))});let{updatedURLs:a,notUpdatedURLs:s}=t;return{updatedURLs:a,notUpdatedURLs:s}})}async registerRequestRules(e){if(this._requestRules&&e?.addRoutes)try{await e.addRoutes(this._requestRules),this._requestRules=void 0}catch(e){throw e}}handleActivate(e){return y(e,async()=>{let e=await self.caches.open(this.precacheStrategy.cacheName),t=await e.keys(),a=new Set(this._urlsToCacheKeys.values()),s=[];for(let r of t)a.has(r.url)||(await e.delete(r),s.push(r.url));return{deletedCacheRequests:s}})}handleFetch(e){let{request:t}=e,a=this.handleRequest({request:t,event:e});a&&e.respondWith(a)}handleCache(e){if(e.data&&"CACHE_URLS"===e.data.type){let{payload:t}=e.data,a=Promise.all(t.urlsToCache.map(t=>{let a;return a="string"==typeof t?new Request(t):new Request(...t),this.handleRequest({request:a,event:e})}));e.waitUntil(a),e.ports?.[0]&&a.then(()=>e.ports[0].postMessage(!0))}}setDefaultHandler(e,t="GET"){this._defaultHandlerMap.set(t,ea(e))}setCatchHandler(e){this._catchHandler=ea(e)}registerCapture(e,t,a){let s=((e,t,a)=>{if("string"==typeof e){let s=new URL(e,location.href);return new es(({url:e})=>e.href===s.href,t,a)}if(e instanceof RegExp)return new en(e,t,a);if("function"==typeof e)return new es(e,t,a);if(e instanceof es)return e;throw new l("unsupported-route-type",{moduleName:"serwist",funcName:"parseRoute",paramName:"capture"})})(e,t,a);return this.registerRoute(s),s}registerRoute(e){this._routes.has(e.method)||this._routes.set(e.method,[]),this._routes.get(e.method).push(e)}unregisterRoute(e){if(!this._routes.has(e.method))throw new l("unregister-route-but-not-found-with-method",{method:e.method});let t=this._routes.get(e.method).indexOf(e);if(t>-1)this._routes.get(e.method).splice(t,1);else throw new l("unregister-route-route-not-registered")}getUrlsToPrecacheKeys(){return this._urlsToCacheKeys}getPrecachedUrls(){return[...this._urlsToCacheKeys.keys()]}getPrecacheKeyForUrl(e){let t=new URL(e,location.href);return this._urlsToCacheKeys.get(t.href)}getIntegrityForPrecacheKey(e){return this._cacheKeysToIntegrities.get(e)}async matchPrecache(e){let t=e instanceof Request?e.url:e,a=this.getPrecacheKeyForUrl(t);if(a)return(await self.caches.open(this.precacheStrategy.cacheName)).match(a)}createHandlerBoundToUrl(e){let t=this.getPrecacheKeyForUrl(e);if(!t)throw new l("non-precached-url",{url:e});return a=>(a.request=new Request(e),a.params={cacheKey:t,...a.params},this.precacheStrategy.handle(a))}handleRequest({request:e,event:t}){let a,s=new URL(e.url,location.href);if(!s.protocol.startsWith("http"))return;let r=s.origin===location.origin,{params:i,route:n}=this.findMatchingRoute({event:t,request:e,sameOrigin:r,url:s}),c=n?.handler,o=e.method;if(!c&&this._defaultHandlerMap.has(o)&&(c=this._defaultHandlerMap.get(o)),!c)return;try{a=c.handle({url:s,request:e,event:t,params:i})}catch(e){a=Promise.reject(e)}let l=n?.catchHandler;return a instanceof Promise&&(this._catchHandler||l)&&(a=a.catch(async a=>{if(l)try{return await l.handle({url:s,request:e,event:t,params:i})}catch(e){e instanceof Error&&(a=e)}if(this._catchHandler)return this._catchHandler.handle({url:s,request:e,event:t});throw a})),a}findMatchingRoute({url:e,sameOrigin:t,request:a,event:s}){for(let r of this._routes.get(a.method)||[]){let i,n=r.match({url:e,sameOrigin:t,request:a,event:s});if(n)return Array.isArray(i=n)&&0===i.length||n.constructor===Object&&0===Object.keys(n).length?i=void 0:"boolean"==typeof n&&(i=void 0),{route:r,params:i}}return{}}};let eR="/offline",eE=["pages","api-responses","next-static","static-media","fallback","offline-fallback"],eq=[{matcher:({url:e,sameOrigin:t})=>t&&e.pathname.startsWith("/api/"),handler:new ee({cacheName:"api-responses",networkTimeoutSeconds:5,plugins:[new ep({maxEntries:100,maxAgeSeconds:3600})]})},{matcher:({request:e})=>"navigate"===e.mode,handler:new ee({cacheName:"pages",networkTimeoutSeconds:5,plugins:[new ep({maxEntries:50,maxAgeSeconds:86400}),{handlerDidError:async()=>await caches.match(eR)||Response.error()}]})},{matcher:({url:e,sameOrigin:t})=>t&&e.pathname.startsWith("/_next/static/"),handler:new ey({cacheName:"next-static",plugins:[new ep({maxEntries:200,maxAgeSeconds:2592e3})]})},{matcher:({url:e})=>e.pathname.startsWith("/images/")||e.pathname.startsWith("/icons/")||/\.(?:png|jpe?g|gif|svg|webp|ico|woff2?)$/.test(e.pathname),handler:new ey({cacheName:"static-media",plugins:[new ep({maxEntries:100,maxAgeSeconds:2592e3})]})},{matcher:()=>!0,handler:new ee({cacheName:"fallback",networkTimeoutSeconds:5,plugins:[new ep({maxEntries:50,maxAgeSeconds:86400})]})}];new ev({precacheEntries:[{'revision':null,'url':'/_next/static/chunks/1079-304a546a4a673437.js'},{'revision':null,'url':'/_next/static/chunks/1896-359ed2e68a8c4f1d.js'},{'revision':null,'url':'/_next/static/chunks/1958-56cbbb8dba15fd2f.js'},{'revision':null,'url':'/_next/static/chunks/2346-36e36720a5f6591a.js'},{'revision':null,'url':'/_next/static/chunks/3268-0a7190b483de059a.js'},{'revision':null,'url':'/_next/static/chunks/4bd1b696-e356ca5ba0218e27.js'},{'revision':null,'url':'/_next/static/chunks/52774a7f.f2ab7a9b4b8ba576.js'},{'revision':null,'url':'/_next/static/chunks/5562-75754cf72635a351.js'},{'revision':null,'url':'/_next/static/chunks/5838-7e0aa455e9f24259.js'},{'revision':null,'url':'/_next/static/chunks/7363-209a1a709d8f324d.js'},{'revision':null,'url':'/_next/static/chunks/7602.2868ff821d53ee09.js'},{'revision':null,'url':'/_next/static/chunks/8078-0cb13480a43e9ef1.js'},{'revision':null,'url':'/_next/static/chunks/8500-f62a38ff68ab7f42.js'},{'revision':null,'url':'/_next/static/chunks/9da6db1e-9623f3245f088d02.js'},{'revision':null,'url':'/_next/static/chunks/app/_global-error/page-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/_not-found/page-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/about/page-fdb7d7bffef68ad1.js'},{'revision':null,'url':'/_next/static/chunks/app/account/page-9300f08c33aa8887.js'},{'revision':null,'url':'/_next/static/chunks/app/admin/page-b3b6af59ae9681bb.js'},{'revision':null,'url':'/_next/static/chunks/app/api/admin/stats/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/books/%5B...path%5D/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/checkout/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/content/%5B...path%5D/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/gamelines/%5Bsport%5D/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/games/%5Bid%5D/props/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/games/%5Bid%5D/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/games/tonight/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/hero-prop/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/hotlist/%5Bsport%5D/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/intelligence/feed/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ledger/accuracy/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ledger/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/lines/%5B...path%5D/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/mlb/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/nba/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/soccer/%5Bleague%5D/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/odds/wnba/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/parlay/add-leg/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/parlay/calculate/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/parlay/grade/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/players/search/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/props/live/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/props/most-parlayed/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/props/top-graded/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/scan/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/schedule/%5Bsport%5D/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/snapshot/%5Bsport%5D/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/cascade/%5Bplayer%5D/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/depth/%5Bteam%5D/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/leaders/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/lineup/%5Bteam%5D/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/parlays-graded/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/player/%5Bname%5D/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/stats/public/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/streaks/%5Bsport%5D/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/ticker/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/user/profile/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/user/recent-scans/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/user/scans/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/waitlist/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/webhook/nexapay/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/api/welcome-email/route-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/auth/callback/page-e6df9771a50edb87.js'},{'revision':null,'url':'/_next/static/chunks/app/blog/%5Bslug%5D/page-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/blog/page-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/compare/page-5e631b0c698c6f5f.js'},{'revision':null,'url':'/_next/static/chunks/app/dashboard/page-023ebc1f3cc4e064.js'},{'revision':null,'url':'/_next/static/chunks/app/explore/page-8856c642532e2773.js'},{'revision':null,'url':'/_next/static/chunks/app/forgot-password/page-a251f52b4206e8d1.js'},{'revision':null,'url':'/_next/static/chunks/app/game/%5Bid%5D/page-ac9d9a479ea7ab89.js'},{'revision':null,'url':'/_next/static/chunks/app/help/page-03c6534f006d09da.js'},{'revision':null,'url':'/_next/static/chunks/app/intelligence/page-772d69c9ecfe1503.js'},{'revision':null,'url':'/_next/static/chunks/app/invite/page-e1e3f46af5f1e44b.js'},{'revision':null,'url':'/_next/static/chunks/app/layout-5e3e0f90e35563f5.js'},{'revision':null,'url':'/_next/static/chunks/app/ledger/page-47459e4f664b707a.js'},{'revision':null,'url':'/_next/static/chunks/app/login/page-b82f3975255d56a8.js'},{'revision':null,'url':'/_next/static/chunks/app/marketplace/page-cbada49ae96a7527.js'},{'revision':null,'url':'/_next/static/chunks/app/not-found-898edc4d76c31251.js'},{'revision':null,'url':'/_next/static/chunks/app/notifications/page-fdb7d7bffef68ad1.js'},{'revision':null,'url':'/_next/static/chunks/app/offline/page-a7a57ff039afc1af.js'},{'revision':null,'url':'/_next/static/chunks/app/page-0dcd8f18c52c3ce3.js'},{'revision':null,'url':'/_next/static/chunks/app/player/%5Bname%5D/page-a9a1a22752478255.js'},{'revision':null,'url':'/_next/static/chunks/app/pricing/page-2182e68653f4cedc.js'},{'revision':null,'url':'/_next/static/chunks/app/privacy/page-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/profile/page-d607627acb1b73ab.js'},{'revision':null,'url':'/_next/static/chunks/app/report/page-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/responsible-gambling/page-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/scan/page-9cf453400fd9bd5b.js'},{'revision':null,'url':'/_next/static/chunks/app/settings/page-25678f7d56db0a16.js'},{'revision':null,'url':'/_next/static/chunks/app/settings/security/page-697d02aa2d05cf7e.js'},{'revision':null,'url':'/_next/static/chunks/app/signup/page-b6917fd30dbecebe.js'},{'revision':null,'url':'/_next/static/chunks/app/soccer/page-5a64e650908111d7.js'},{'revision':null,'url':'/_next/static/chunks/app/terminal/page-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/terms/page-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/app/tracker/page-e23baec2b3735bb1.js'},{'revision':null,'url':'/_next/static/chunks/app/upgrade/cancel/page-3702e818a6853705.js'},{'revision':null,'url':'/_next/static/chunks/app/upgrade/desk/page-24eaa80743986159.js'},{'revision':null,'url':'/_next/static/chunks/app/upgrade/success/page-ea358cb8f714f1ea.js'},{'revision':null,'url':'/_next/static/chunks/app/verify/page-9df376f065215168.js'},{'revision':null,'url':'/_next/static/chunks/app/welcome/page-259277230533599f.js'},{'revision':null,'url':'/_next/static/chunks/framework-95da69ac6843d788.js'},{'revision':null,'url':'/_next/static/chunks/main-a354262253293123.js'},{'revision':null,'url':'/_next/static/chunks/main-app-4231d5f500f33972.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/app-error-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/forbidden-3f6e5af651dae09a.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/global-error-756d787dba63aa4d.js'},{'revision':null,'url':'/_next/static/chunks/next/dist/client/components/builtin/unauthorized-3f6e5af651dae09a.js'},{'revision':'846118c33b2c0e922d7b3a7676f81f6f','url':'/_next/static/chunks/polyfills-42372ed130431b0a.js'},{'revision':null,'url':'/_next/static/chunks/webpack-42b9616650231776.js'},{'revision':null,'url':'/_next/static/css/6ee3c69ef5f8952b.css'},{'revision':'e2e5e726167556b094cd62a8df8f0d76','url':'/_next/static/ioKRllwkc9BTH_EYm2m4q/_buildManifest.js'},{'revision':'b6652df95db52feb4daf4eca35380933','url':'/_next/static/ioKRllwkc9BTH_EYm2m4q/_ssgManifest.js'},{'revision':'cd34c7793d9776838308cfbe5d93922b','url':'/_next/static/media/011e180705008d6f-s.woff2'},{'revision':'324703f03c390d2e2a4f387de85fe63d','url':'/_next/static/media/0aa834ed78bf6d07-s.woff2'},{'revision':'9dda5cfc9a46f256d0e131bb535e46f8','url':'/_next/static/media/19cfc7226ec3afaa-s.woff2'},{'revision':'7de6d31e5076eb437418b6e01998ee12','url':'/_next/static/media/20535187d867b7b9-s.woff2'},{'revision':'4e2553027f1d60eff32898367dd4d541','url':'/_next/static/media/21350d82a1f187e9-s.woff2'},{'revision':'0d11e07b5aaafda6ae2efc53256932ec','url':'/_next/static/media/37786be940ec402b-s.p.woff2'},{'revision':'5de0bff80f9f432b5cf52c1c2f80fe20','url':'/_next/static/media/46e154b2fcbd6033-s.woff2'},{'revision':'6041b3192dc3e1a50141d5d418a24199','url':'/_next/static/media/5356a6a4f2c8c8d8-s.woff2'},{'revision':'f572f7b57d27ec7fd8373961f0b762b0','url':'/_next/static/media/58f386aa6b1a2a92-s.woff2'},{'revision':'e829cbe042e8b2b2e6b99c0eec9e230d','url':'/_next/static/media/656feb427634a431-s.woff2'},{'revision':'54f02056e07c55023315568c637e3a96','url':'/_next/static/media/67957d42bae0796d-s.woff2'},{'revision':'e220ad1849c282590e47db0ff88fc3f3','url':'/_next/static/media/704b853f32d191d5-s.woff2'},{'revision':'662cde3543f3375874e26c26845cec22','url':'/_next/static/media/73cb51aac9c97f90-s.woff2'},{'revision':'afac1fab355fe8db5c2dcaa7623dffb3','url':'/_next/static/media/7ba5fb2a8c88521c-s.woff2'},{'revision':'c94e6e6c23e789fcb0fc60d790c9d2c1','url':'/_next/static/media/886030b0b59bc5a7-s.woff2'},{'revision':'01ba6c2a184b8cba08b0d57167664d75','url':'/_next/static/media/8e9860b6e62d6359-s.woff2'},{'revision':'17a5b2a15bf5647b49cadb9a3bb02e1c','url':'/_next/static/media/92eeb95d069020cc-s.woff2'},{'revision':'4a4e74bed5809194e4bc6538eb1a1e30','url':'/_next/static/media/939c4f875ee75fbb-s.woff2'},{'revision':'6708425c446b05de1c2d471a0eaf4099','url':'/_next/static/media/98e207f02528a563-s.p.woff2'},{'revision':'13dface50f6dc0bff1015561c84119e6','url':'/_next/static/media/991629005c80bdf1-s.woff2'},{'revision':'216ee1a35b060106ed2852cdd8c026c7','url':'/_next/static/media/99dcf268bda04fe5-s.woff2'},{'revision':'9e494903d6b0ffec1a1e14d34427d44d','url':'/_next/static/media/ba9851c3c22cd980-s.woff2'},{'revision':'782150e6836b9b074d1a798807adcb18','url':'/_next/static/media/bb3ef058b751a6ad-s.p.woff2'},{'revision':'027a89e9ab733a145db70f09b8a18b42','url':'/_next/static/media/c5fe6dc8356a8c31-s.woff2'},{'revision':'75fa2e527eaae805bbf44e3378d1232c','url':'/_next/static/media/d26bbd13d6b70f89-s.woff2'},{'revision':'0ba762bde65aaa682fcc089f8c57288e','url':'/_next/static/media/d29838c109ef09b4-s.woff2'},{'revision':'814fe1615d4dbc7bbd92d26a6bda0905','url':'/_next/static/media/d3ebbfd689654d3a-s.p.woff2'},{'revision':'e71a597e376ed91862e822b5a5de8c04','url':'/_next/static/media/db96af6b531dc71f-s.p.woff2'},{'revision':'d54db44de5ccb18886ece2fda72bdfe0','url':'/_next/static/media/df0a9ae256c0569c-s.woff2'},{'revision':'9fb609fe01d739bb9df558e1fba2498e','url':'/_next/static/media/e40af3453d7c920a-s.woff2'},{'revision':'65850a373e258f1c897a2b3d75eb74de','url':'/_next/static/media/e4af272ccee01ff0-s.p.woff2'},{'revision':'de1d49f26130d43f91829088086625f4','url':'/_next/static/media/ef4d5661765d0e49-s.woff2'},{'revision':'0f8d347d49960d05c9430d83e49edeb7','url':'/_next/static/media/f911b923c6adde36-s.woff2'},{'revision':'d7bc0f63f9618b8b700d028d7d242de8','url':'/apple-touch-icon.png'},{'revision':'5616f81ec5f8a9f726a17fb7ac66a54a','url':'/favicon-16.png'},{'revision':'1fc285cfb0116a0523eb34c779a7d282','url':'/favicon-32.png'},{'revision':'583b034f36839a8af92841771eef38b6','url':'/favicon.ico'},{'revision':'b15795128b3691e5703d0ce14ce10827','url':'/favicon.png'},{'revision':'44e9d71551be13574ac2e10063d03aa9','url':'/favicon.svg'},{'revision':'252b8f8c4d0f64c7cd120f182a6c74ab','url':'/icon-192.png'},{'revision':'3e3b53bbd210bd772b36b70165657e7c','url':'/icon-512.png'},{'revision':'252b8f8c4d0f64c7cd120f182a6c74ab','url':'/icons/icon-192.png'},{'revision':'3e3b53bbd210bd772b36b70165657e7c','url':'/icons/icon-512.png'},{'revision':'3e3b53bbd210bd772b36b70165657e7c','url':'/icons/icon-maskable-512.png'},{'revision':'bf670b1fafa1b3127bd50abe86d723b9','url':'/images/player-silhouette.svg'},{'revision':'d692f690fbd1564f090131e02be5ba9c','url':'/manifest.json'},{'revision':'9f61cf51298661d5c57a782534216240','url':'/og-image.png'},{'revision':'7c759c20b35840eacf9344692cb51061','url':'/og-image.svg'},{'revision':'9327802333275f11e68c3f19f20c160d','url':'/widget.js'}],skipWaiting:!0,clientsClaim:!0,navigationPreload:!0,runtimeCaching:eq}).addEventListeners(),self.addEventListener("install",e=>{e.waitUntil(caches.open("offline-fallback").then(e=>e.add(eR)).catch(()=>{}))}),self.addEventListener("activate",e=>{e.waitUntil(caches.keys().then(e=>Promise.all(e.filter(e=>!eE.includes(e)&&!e.startsWith("serwist")).map(e=>(console.log("[SW] deleting stale cache:",e),caches.delete(e))))))}),self.addEventListener("push",e=>{let t;if(!e.data)return;try{t=e.data.json()}catch{t={title:"VYNDR",body:e.data.text()}}let{title:a="VYNDR",body:s="",icon:r="/icons/icon-192.png",url:i="/",tag:n="vyndr-notification"}=t;e.waitUntil(self.registration.showNotification(a,{body:s,icon:r,badge:"/icons/icon-192.png",tag:n,data:{url:i}}))}),self.addEventListener("notificationclick",e=>{e.notification.close();let t=e.notification.data?.url??"/";e.waitUntil(self.clients.matchAll({type:"window",includeUncontrolled:!0}).then(e=>{let a=e.find(e=>e.url.endsWith(t));return a?a.focus():self.clients.openWindow(t)}))})})(); \ No newline at end of file diff --git a/web/src/app/api/snapshot/[sport]/route.ts b/web/src/app/api/snapshot/[sport]/route.ts new file mode 100644 index 0000000..8b5f412 --- /dev/null +++ b/web/src/app/api/snapshot/[sport]/route.ts @@ -0,0 +1,20 @@ +import { NextRequest, NextResponse } from 'next/server'; + +export const dynamic = 'force-dynamic'; + +const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3000'; + +/** Snapshot proxy (Session 45) — forwards GET /api/snapshot/:sport (pre-graded slate). */ +export async function GET(_req: NextRequest, ctx: { params: Promise<{ sport: string }> }) { + const { sport } = await ctx.params; + try { + const upstream = await fetch(`${BACKEND_URL}/api/snapshot/${encodeURIComponent(sport)}`, { + method: 'GET', + headers: { Accept: 'application/json' }, + }); + const data = await upstream.json().catch(() => ({ grades: [], deltas: [] })); + return NextResponse.json(data, { status: upstream.ok ? 200 : upstream.status }); + } catch { + return NextResponse.json({ sport, grades: [], deltas: [] }, { status: 200 }); + } +} diff --git a/web/src/app/api/ticker/route.ts b/web/src/app/api/ticker/route.ts new file mode 100644 index 0000000..cacfd57 --- /dev/null +++ b/web/src/app/api/ticker/route.ts @@ -0,0 +1,22 @@ +import { NextResponse } from 'next/server'; + +export const dynamic = 'force-dynamic'; + +const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3000'; + +/** + * Ticker proxy (Session 45) — forwards GET /api/ticker to Express (snapshot + * exhaust + editorial pins). Thin pass-through; the page polls this every 30s. + */ +export async function GET() { + try { + const upstream = await fetch(`${BACKEND_URL}/api/ticker`, { + method: 'GET', + headers: { Accept: 'application/json' }, + }); + const data = await upstream.json().catch(() => ({ items: [] })); + return NextResponse.json(data, { status: upstream.ok ? 200 : upstream.status }); + } catch { + return NextResponse.json({ items: [] }, { status: 200 }); + } +} diff --git a/web/src/components/Slate.tsx b/web/src/components/Slate.tsx index 31571d1..210e10c 100644 --- a/web/src/components/Slate.tsx +++ b/web/src/components/Slate.tsx @@ -2,9 +2,12 @@ import { useCallback, useEffect, useMemo, useState } from 'react'; import { useRouter } from 'next/navigation'; -import GameCard, { SlateSport, GameLines, GameStreak } from '@/components/GameCard'; -import { PropRowProp, PropRowResult, propRowKey, Tier } from '@/components/PropRow'; -import { isRelevantGame } from '@/lib/slateAdapter'; +// Session 45 — the live Slate now renders the pre-graded snapshot via the +// VYNDR 2.0 card. Legacy GameCard is kept ONLY for its shared types. +import VyndrGameCard, { type GameCardData } from '@/components/vyndr/GameCard'; +import type { SlateSport, GameLines, GameStreak } from '@/components/GameCard'; +import { PropRowProp, Tier } from '@/components/PropRow'; +import { isRelevantGame, detectBestLines, indexGrades, indexDeltas, buildPlayerStripsFromProps, formatGameTime } from '@/lib/slateAdapter'; import { useAuth } from '@/contexts/AuthContext'; // Session 23 — all-day intelligence layer. The stat filter is the // navigation system; streaks + hot lists layer ON TOP of the odds the @@ -157,6 +160,31 @@ interface StreakApiRow { } interface StreaksResponse { streaks?: StreakApiRow[] } +// Session 45 — pre-graded snapshot response (snapshot:{sport}:latest). +interface SnapshotGrade { player?: string; player_name?: string; stat_type?: string; line?: number; direction?: string; grade?: string; archetype?: string | null; gradedAt?: { line: number; odds?: number | null; timestamp?: string } | null } +interface SnapshotDelta { player?: string; stat?: string; side?: string; delta?: number; direction?: string; currentLine?: number } +interface SnapshotResponse { grades?: SnapshotGrade[]; deltas?: SnapshotDelta[] } + +// Session 45 — map a merged SlateGame + the pre-graded snapshot indices into the +// VYNDR 2.0 GameCardData (player name once, archetype, locked grades + deltas). +type GradeIndex = ReturnType; +type DeltaIndex = ReturnType; +function slateGameToCardData(g: SlateGame, gradeIndex: GradeIndex, deltaIndex: DeltaIndex): GameCardData { + return { + id: `${g.sport}-${g.awayAbbr || g.awayTeam}-${g.homeAbbr || g.homeTeam}`, + sport: g.sport, + live: g.status === 'in', + score: g.score ? { away: g.score.away, home: g.score.home } : undefined, + away: { abbr: g.awayAbbr || g.awayTeam, name: g.awayTeam }, + home: { abbr: g.homeAbbr || g.homeTeam, name: g.homeTeam }, + time: formatGameTime(g.gameTime), + venue: g.venue, + lines: g.gameLines?.books ? detectBestLines(g.gameLines.books) : [], + playerStrips: buildPlayerStripsFromProps(g.props, gradeIndex, deltaIndex), + streaks: (g.streaks || []).map((s) => ({ player: s.player, text: s.description || '' })), + }; +} + // ---- Session 24: schedule + game-lines response shapes ---- interface ScheduleTeam { name?: string | null; abbreviation?: string | null } interface ScheduleGame { @@ -321,6 +349,9 @@ export default function Slate({ initialTab = 'all', tier = 'free' }: SlateProps) // and game lines stay visible regardless (handled inside GameCard). const [activeStat, setActiveStat] = useState('all'); const [games, setGames] = useState([]); + // Session 45 — merged pre-graded snapshot across the loaded sports. + const [snapGrades, setSnapGrades] = useState([]); + const [snapDeltas, setSnapDeltas] = useState([]); const [loading, setLoading] = useState(false); const [fetchError, setFetchError] = useState(null); // Session 26 — per-sport schedule counts for the tab labels, fetched @@ -333,11 +364,6 @@ export default function Slate({ initialTab = 'all', tier = 'free' }: SlateProps) // games, this becomes a soft inline notice instead of a wall-of-error. const [oddsNotice, setOddsNotice] = useState(false); - // Grade state — Map keyed by propRowKey. - const [gradedProps, setGradedProps] = useState>(() => new Map()); - const [gradingKey, setGradingKey] = useState(null); - const [errorByKey, setErrorByKey] = useState>({}); - // Search filter (Phase 3.4 — kept here so the Slate owns its own filtering). const [searchQuery, setSearchQuery] = useState(''); @@ -385,11 +411,13 @@ export default function Slate({ initialTab = 'all', tier = 'free' }: SlateProps) const perSport = await Promise.all( sportsToFetch.map(async (sport) => { const oddsUrls = FETCH_URLS[sport] as string[]; - const [oddsResults, schedule, lines, streaksRes] = await Promise.all([ + const [oddsResults, schedule, lines, streaksRes, snap] = await Promise.all([ Promise.all(oddsUrls.map((u) => getJson(u))), SCHEDULE_SPORTS.has(sport) ? getJson(`/api/schedule/${sport}`) : Promise.resolve(null), SCHEDULE_SPORTS.has(sport) ? getJson(`/api/gamelines/${sport}`) : Promise.resolve(null), SCHEDULE_SPORTS.has(sport) ? getJson(`/api/streaks/${sport}`) : Promise.resolve(null), + // Session 45 — pre-graded snapshot (locked grades + line deltas). + getJson(`/api/snapshot/${sport}`), ]); const oddsOk = oddsResults.some((o) => o !== null); @@ -397,20 +425,26 @@ export default function Slate({ initialTab = 'all', tier = 'free' }: SlateProps) const oddsGames = groupByGame(oddsProps, sport); const scheduleGames = schedule?.games || []; const merged = mergeSlate(sport, scheduleGames, oddsGames, lines?.games, streaksRes?.streaks); - return { sport, merged, oddsOk, hadSchedule: scheduleGames.length > 0 }; + return { sport, merged, oddsOk, hadSchedule: scheduleGames.length > 0, snapGrades: snap?.grades || [], snapDeltas: snap?.deltas || [] }; }), ); const allGames: SlateGame[] = []; + const allSnapGrades: SnapshotGrade[] = []; + const allSnapDeltas: SnapshotDelta[] = []; let anyOddsOk = false; let anyScheduleShown = false; for (const s of perSport) { allGames.push(...s.merged); + allSnapGrades.push(...s.snapGrades); + allSnapDeltas.push(...s.snapDeltas); if (s.oddsOk) anyOddsOk = true; if (s.hadSchedule) anyScheduleShown = true; } setGames(allGames); + setSnapGrades(allSnapGrades); + setSnapDeltas(allSnapDeltas); // Odds down but schedule carried the slate → soft notice, not a wall. if (!anyOddsOk && anyScheduleShown) setOddsNotice(true); @@ -455,58 +489,15 @@ export default function Slate({ initialTab = 'all', tier = 'free' }: SlateProps) return () => { cancelled = true; }; }, []); - // Grading call site. Single source of truth so we never have two - // PropRows in-flight from the same prop (the loadingKey enforces it). - const onGrade = useCallback(async (prop: PropRowProp) => { - const key = propRowKey(prop); - if (gradingKey) return; // already a grade in flight — defer - setGradingKey(key); - setErrorByKey((prev) => ({ ...prev, [key]: undefined })); - try { - const res = await fetch('/api/scan', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - ...(session?.access_token ? { Authorization: `Bearer ${session.access_token}` } : {}), - }, - body: JSON.stringify({ - sport: 'NBA', // overwritten below per game card sport - player: prop.player, - stat: prop.stat_type, - line: prop.line, - direction: prop.direction, - book: prop.book || 'draftkings', - }), - }); - const body = (await res.json().catch(() => ({}))) as Record & { error?: string }; - if (!res.ok) { - setErrorByKey((prev) => ({ ...prev, [key]: body.error || `HTTP ${res.status}` })); - return; - } - const result: PropRowResult = { - grade: String(body.grade || 'C'), - confidence: typeof body.confidence === 'number' ? body.confidence : undefined, - edge_pct: typeof body.edge_pct === 'number' ? body.edge_pct : undefined, - reasoning: (body.reasoning as PropRowResult['reasoning']) || undefined, - kill_conditions_triggered: (body.kill_conditions_triggered as PropRowResult['kill_conditions_triggered']) || [], - tier_gated: !!body.tier_gated, - upgrade_hint: typeof body.upgrade_hint === 'string' ? body.upgrade_hint : undefined, - }; - setGradedProps((prev) => { - const next = new Map(prev); - next.set(key, result); - return next; - }); - } catch { - setErrorByKey((prev) => ({ ...prev, [key]: 'Network error. Try again.' })); - } finally { - setGradingKey(null); - } - }, [gradingKey, session]); - - const onUpgrade = useCallback(() => router.push('/pricing'), [router]); + // Session 45 — the on-demand "Read" grade flow is RETIRED. Grades come from + // the scheduled snapshot pipeline (snapshot:{sport}:latest), overlaid onto the + // slate below. The legacy onGrade call site was removed with the legacy card. // Filter pipeline — searchQuery applied to games + props. + // Session 45 — index the pre-graded snapshot once for the overlay. + const gradeIndex = useMemo(() => indexGrades(snapGrades), [snapGrades]); + const deltaIndex = useMemo(() => indexDeltas(snapDeltas), [snapDeltas]); + const filteredGames = useMemo(() => { // Session 44 — drop completed games >24h old so a 5-day-old FINAL never // lingers on the dashboard. Upcoming + live always show. @@ -742,25 +733,10 @@ export default function Slate({ initialTab = 'all', tier = 'free' }: SlateProps)
{filteredGames.map((g, i) => ( - onGrade({ ...p })} - onUpgrade={onUpgrade} + game={slateGameToCardData(g, gradeIndex, deltaIndex)} + onOpen={() => router.push('/scan')} /> ))}
diff --git a/web/src/components/vyndr/StatStrip.tsx b/web/src/components/vyndr/StatStrip.tsx index 60908b1..f8945b6 100644 --- a/web/src/components/vyndr/StatStrip.tsx +++ b/web/src/components/vyndr/StatStrip.tsx @@ -9,7 +9,11 @@ export interface StripProp { stat: string; line: number | string; side: string; // O / U / Over / Under - grade: string; + grade: string | null; + // Session 45 — pre-graded snapshot model: the locked grade + market movement. + gradedAt?: { line: number; odds?: number | null; timestamp?: string; ago?: string } | null; + delta?: { delta: number; direction: 'toward' | 'away'; currentLine: number } | null; + awaiting?: boolean; // not yet graded by a snapshot → "Awaiting next scan" } export interface StripArchetype { primary: string; @@ -127,19 +131,59 @@ export default function StatStrip({ ))} - {props && props.length > 0 && ( -
- PROPS - {props.map((p, i) => ( - - {i > 0 && ·} - - {p.stat} {p.side}{p.line} - - - ))} -
- )} + {props && props.length > 0 && (() => { + // Session 45 — snapshot mode renders each prop as a block with its + // locked grade + market-movement sub-line; otherwise the inline chip row. + const snapshotMode = props.some((p) => p.gradedAt || p.delta || p.awaiting); + if (!snapshotMode) { + return ( +
+ PROPS + {props.map((p, i) => ( + + {i > 0 && ·} + + {p.stat} {p.side}{p.line} {p.grade && } + + + ))} +
+ ); + } + return ( +
+ {props.map((p, i) => { + if (p.awaiting) { + return ( +
+ {p.stat} {p.line} + Awaiting next scan +
+ ); + } + const toward = p.delta?.direction === 'toward'; + return ( +
+
+ {p.stat} {p.side}{p.line} + {p.grade && } + {p.gradedAt?.ago && ( + + Graded {p.gradedAt.ago}{p.gradedAt.odds != null ? ` at ${p.gradedAt.odds}` : ''} + + )} +
+ {p.delta && ( +
+ Current {p.delta.currentLine} · {p.delta.delta > 0 ? '▲' : '▼'} {toward ? 'TOWARD' : 'AWAY'} {p.delta.delta > 0 ? '+' : ''}{p.delta.delta} +
+ )} +
+ ); + })} +
+ ); + })()} ); } diff --git a/web/src/components/vyndr/Ticker.tsx b/web/src/components/vyndr/Ticker.tsx index 4ac1945..d82603a 100644 --- a/web/src/components/vyndr/Ticker.tsx +++ b/web/src/components/vyndr/Ticker.tsx @@ -1,3 +1,7 @@ +'use client'; + +import { useEffect, useState } from 'react'; + type TickerItem = { tag: string; text: string; @@ -12,31 +16,58 @@ type TickerItem = { type TickerProps = { items: TickerItem[]; height?: number; + /** Poll /api/ticker for live snapshot events (Session 45). Default true. */ + live?: boolean; + /** Poll interval ms (default 30s). */ + pollMs?: number; +}; + +const TAG_COLORS: Record = { + 'A+': 'var(--g-ap)', A: 'var(--g-a)', SCAN: 'var(--g-a)', + MOVE: 'var(--amber)', CASCADE: 'var(--amber)', ALERT: 'var(--text-0)', }; /** * Scrolling marquee (§5). Continuous `ticker-scroll`; content duplicated so the - * loop is seamless. Edge fades mask the wrap. Tags glow; values stay crisp. + * loop is seamless. Session 45 — polls /api/ticker for live snapshot exhaust + * (top grades, line moves, slate-scanned events); the passed `items` are the + * initial + graceful fallback so the bar is never empty. */ -export default function Ticker({ items, height = 34 }: TickerProps) { - const content = items.map((it, i) => ( +export default function Ticker({ items, height = 34, live = true, pollMs = 30_000 }: TickerProps) { + const [feed, setFeed] = useState(null); + + useEffect(() => { + if (!live) return; + let active = true; + const load = async () => { + try { + const r = await fetch('/api/ticker', { cache: 'no-store' }); + if (!r.ok) return; + const data = (await r.json()) as { items?: TickerItem[] }; + if (active && Array.isArray(data.items) && data.items.length > 0) { + setFeed(data.items.map((it) => ({ ...it, color: it.color || TAG_COLORS[it.tag] || 'var(--amber)' }))); + } + } catch { + /* keep the current items on failure — never blank the bar */ + } + }; + load(); + const id = setInterval(load, pollMs); + return () => { active = false; clearInterval(id); }; + }, [live, pollMs]); + + const display = feed && feed.length > 0 ? feed : items; + + const content = display.map((it, i) => ( @@ -44,9 +75,7 @@ export default function Ticker({ items, height = 34 }: TickerProps) { {it.text} {it.delta && ( - - {it.delta} - + {it.delta} )} · @@ -54,16 +83,7 @@ export default function Ticker({ items, height = 34 }: TickerProps) { return (
{content} diff --git a/web/src/lib/slateAdapter.js b/web/src/lib/slateAdapter.js index 65d8dbd..0234702 100644 --- a/web/src/lib/slateAdapter.js +++ b/web/src/lib/slateAdapter.js @@ -192,6 +192,99 @@ function isRelevantGame(game, now = Date.now()) { return (now - t) / 3_600_000 < 24; } +// ── Pre-graded snapshot overlay (Session 45) ──────────────────────── +const snorm = (s) => String(s == null ? '' : s).toLowerCase().replace(/[^a-z0-9]/g, ''); +const gradeKey = (player, stat) => `${snorm(player)}|${String(stat || '').toLowerCase()}`; +const sideCh = (dir) => (String(dir || 'over').toLowerCase() === 'under' ? 'U' : 'O'); + +/** Index snapshot grades by player|stat → the locked grade record. */ +function indexGrades(grades) { + const map = {}; + for (const g of grades || []) { + map[gradeKey(g.player || g.player_name, g.stat_type || g.stat)] = g; + } + return map; +} + +/** Index line deltas by player|stat|side → delta record. */ +function indexDeltas(deltas) { + const map = {}; + for (const d of deltas || []) { + map[`${gradeKey(d.player, d.stat)}|${d.side}`] = d; + } + return map; +} + +const STAT_SHORT = { + total_bases: 'TB', home_runs: 'HR', hits: 'Hits', rbi: 'RBI', runs: 'Runs', + strikeouts: 'Ks', hits_allowed: 'HA', earned_runs: 'ER', innings_pitched: 'IP', + stolen_bases: 'SB', points: 'Pts', rebounds: 'Reb', assists: 'Ast', threes: '3PT', + steals: 'Stl', blocks: 'Blk', pra: 'PRA', turnovers: 'TO', +}; +function statShort(stat) { + if (!stat) return ''; + return STAT_SHORT[stat] || String(stat).replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()); +} + +/** Relative "Graded Xh ago" from an ISO timestamp. */ +function gradedAgo(iso, now = Date.now()) { + const t = iso ? new Date(iso).getTime() : NaN; + if (Number.isNaN(t)) return ''; + const mins = Math.max(0, Math.round((now - t) / 60000)); + if (mins < 1) return 'just now'; + if (mins < 60) return `${mins}m ago`; + const hrs = Math.round(mins / 60); + if (hrs < 24) return `${hrs}h ago`; + return `${Math.round(hrs / 24)}d ago`; +} + +/** + * Build pre-graded `playerStrips` for one game by OVERLAYING the snapshot's + * locked grades onto the game's odds-derived props (which already carry the + * correct game grouping). Each prop is either graded (grade + gradedAt + delta) + * or `awaiting:true` (no snapshot match yet → "Awaiting next scan", no Read + * button). Archetype comes from the snapshot's per-player classification. + */ +function buildPlayerStripsFromProps(gameProps, gradeIndex, deltaIndex, now = Date.now()) { + const byPlayer = {}; + const order = []; + for (const p of gameProps || []) { + if (!p || !p.player) continue; + const rec = gradeIndex[gradeKey(p.player, p.stat_type || p.stat)]; + if (!byPlayer[p.player]) { + byPlayer[p.player] = { + player: p.player, + team: p.team || '', + archetype: rec && rec.archetype ? { primary: rec.archetype } : undefined, + stats: [], + props: [], + }; + order.push(p.player); + } else if (!byPlayer[p.player].archetype && rec && rec.archetype) { + byPlayer[p.player].archetype = { primary: rec.archetype }; + } + if (rec) { + const side = sideCh(rec.direction); + const delta = deltaIndex[`${gradeKey(p.player, p.stat_type || p.stat)}|${side}`]; + byPlayer[p.player].props.push({ + stat: statShort(rec.stat_type || rec.stat), + line: rec.line, + side, + grade: rec.grade, + gradedAt: rec.gradedAt + ? { ...rec.gradedAt, ago: gradedAgo(rec.gradedAt.timestamp, now) } + : null, + delta: delta ? { delta: delta.delta, direction: delta.direction, currentLine: delta.currentLine } : null, + }); + } else { + byPlayer[p.player].props.push({ + stat: statShort(p.stat_type || p.stat), line: p.line, side: '', grade: null, awaiting: true, + }); + } + } + return order.map((name) => byPlayer[name]); +} + module.exports = { parseAmericanOdds, detectBestLines, @@ -201,4 +294,9 @@ module.exports = { groupPropsByPlayer, mapPitchers, isRelevantGame, + indexGrades, + indexDeltas, + statShort, + gradedAgo, + buildPlayerStripsFromProps, };