import type { SourceModule } from "../registry"; import { MarketsConfig, MarketsPayload, type MarketsConfig as Config, type MarketsPayload as Payload, } from "@/lib/schemas/sources/markets"; const CHART = "https://query1.finance.yahoo.com/v8/finance/chart"; // Yahoo's chart endpoint carries everything we need in `meta` and works for both // equities and crypto pairs (BTC-USD). One request per symbol; failures are // skipped rather than failing the whole card. async function quote(symbol: string, signal?: AbortSignal): Promise { try { const res = await fetch(`${CHART}/${encodeURIComponent(symbol)}?range=5d&interval=1d`, { headers: { "User-Agent": "Mozilla/5.0 (PersonalDashboard)" }, signal, }); if (!res.ok) return null; const j = (await res.json()) as { chart?: { result?: Array<{ meta?: Record }> }; }; const meta = j.chart?.result?.[0]?.meta as | { regularMarketPrice?: number; chartPreviousClose?: number; previousClose?: number; currency?: string; shortName?: string; symbol?: string; } | undefined; if (!meta || typeof meta.regularMarketPrice !== "number") return null; const price = meta.regularMarketPrice; const prev = meta.chartPreviousClose ?? meta.previousClose; const changePct = typeof prev === "number" && prev !== 0 ? ((price - prev) / prev) * 100 : null; return { symbol: meta.symbol ?? symbol, name: meta.shortName ?? symbol, price, changePct: changePct == null ? null : Math.round(changePct * 100) / 100, currency: meta.currency ?? "USD", }; } catch { return null; } } export const marketsModule: SourceModule = { kind: "markets", label: "Markets", keyless: true, defaultRefreshSeconds: 900, configSchema: MarketsConfig, payloadSchema: MarketsPayload, isConfigured: (config) => config.symbols.length > 0, async fetch({ config, signal }) { const results = await Promise.all(config.symbols.map((s) => quote(s.trim().toUpperCase(), signal))); return { quotes: results.filter((q): q is NonNullable => q !== null) }; }, };