@nukleus-sports/core 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1325 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +510 -1
- package/dist/index.d.ts +510 -1
- package/dist/index.js +1267 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/dealStatus.ts","../src/currency.ts","../src/projectPermissions.ts","../src/marketingPermission.ts","../src/personName.ts"],"sourcesContent":["import { format, parseISO } from \"date-fns\";\n\nexport type DealStatus = \"Active\" | \"Upcoming\" | \"Complete\";\n\ninterface DealLike {\n deal_terms?: {\n startDate?: string | null;\n } | null;\n}\n\n/** Identical logic in both nukleus-app and nukleus-clientapp's ProjectDealCard. */\nexport function getDealStatus(deal: DealLike, isCompleted: boolean): DealStatus {\n if (isCompleted) return \"Complete\";\n const start = deal.deal_terms?.startDate;\n if (start && parseISO(start) > new Date()) return \"Upcoming\";\n return \"Active\";\n}\n\n/** Identical logic in both apps' ProjectDealCard. */\nexport function formatDealDate(dateStr?: string | null): string {\n if (!dateStr) return \"—\";\n try {\n return format(parseISO(dateStr), \"MMM d, yyyy\");\n } catch {\n return dateStr;\n }\n}\n","/** Full-precision USD, e.g. \"$1,234.56\". */\nexport function fmtUSD(n: number): string {\n return new Intl.NumberFormat(\"en-US\", {\n style: \"currency\",\n currency: \"USD\",\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n }).format(n);\n}\n\n// Reconciled from both apps -- see RECONCILIATION.md#currencyts\n/** Whole-dollar USD, e.g. \"$1,235\"; null-safe, falls back to \"--\". */\nexport function fmtUSDWhole(n?: number): string {\n return n != null\n ? new Intl.NumberFormat(\"en-US\", {\n style: \"currency\",\n currency: \"USD\",\n maximumFractionDigits: 0,\n }).format(n)\n : \"--\";\n}\n\n/** \"$54,000\" for whole dollars, \"$84.50\" otherwise. */\nexport function fmtUSDCompact(n: number): string {\n const cents = Math.round(n * 100);\n return new Intl.NumberFormat(\"en-US\", {\n style: \"currency\",\n currency: \"USD\",\n minimumFractionDigits: cents % 100 === 0 ? 0 : 2,\n maximumFractionDigits: 2,\n }).format(cents / 100);\n}\n\n/** Generic \"--\"-on-empty stringifier. */\nexport function fmt(value: string | number | null | undefined, fallback = \"--\"): string {\n if (value === null || value === undefined || value === \"\") return fallback;\n return String(value);\n}\n\n/** Whole-dollar \"$\"-prefixed display via toLocaleString, no Intl currency\n * formatting -- kept distinct from fmtUSDWhole to match an exact call site. */\nexport function fmtCurrency(amount: number | null | undefined): string {\n if (amount === null || amount === undefined) return \"--\";\n return `$${Number(amount).toLocaleString(\"en-US\", {\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n })}`;\n}\n\n/** MM/DD/YYYY, \"--\" on empty/invalid. */\nexport function fmtDate(dateStr: string | null | undefined): string {\n if (!dateStr) return \"--\";\n try {\n return new Date(dateStr).toLocaleDateString(\"en-US\", {\n month: \"2-digit\",\n day: \"2-digit\",\n year: \"numeric\",\n });\n } catch {\n return dateStr;\n }\n}\n","export type ProjectMemberRole = \"Owner\" | \"Editor\" | \"Viewer\";\n\n// Reconciled from both apps -- see RECONCILIATION.md#projectpermissionsts\nexport function canEditProject(role: ProjectMemberRole | null | undefined): boolean {\n return role === \"Owner\" || role === \"Editor\";\n}\n\n/** Changing task status requires Editor specifically, not just edit access. */\nexport function canEditTaskStatus(role: ProjectMemberRole | null | undefined): boolean {\n return role === \"Editor\";\n}\n\n/** Owner-only; nukleus-clientapp has no equivalent affordance today. */\nexport function canManageMembers(role: ProjectMemberRole | null | undefined): boolean {\n return role === \"Owner\";\n}\n\ninterface ProjectLike {\n status?: string | null;\n}\n\n/** Drives UI gating only -- server-side RLS already blocks writes regardless. */\nexport function isProjectCancelled(project: ProjectLike | null | undefined): boolean {\n return project?.status === \"Cancelled\";\n}\n\n// Reconciled from both apps -- see RECONCILIATION.md#projectpermissionsts\nexport function getEffectiveMemberRole(\n role: ProjectMemberRole | null | undefined,\n isCancelled: boolean,\n): ProjectMemberRole | null | undefined {\n return isCancelled ? \"Viewer\" : role;\n}\n","// Reconciled from both apps -- see RECONCILIATION.md#marketingpermissionts\nexport type MarketingPermission =\n { kind: \"levels\"; level: \"No Access\" | \"View\" | \"Edit\" } | { kind: \"linked\"; isLinked: boolean };\n\nexport function canViewMarketingDeals(permission: MarketingPermission): boolean {\n return permission.kind === \"levels\" ? permission.level !== \"No Access\" : permission.isLinked;\n}\n\n/** Always false for the \"linked\" shape -- clients never get write access. */\nexport function canEditMarketingDeals(permission: MarketingPermission): boolean {\n return permission.kind === \"levels\" && permission.level === \"Edit\";\n}\n","/** \"J. Smith\" from \"John Smith\" -- both apps' real current behavior for a\n * project deal's owner name (nukleus-app's pre-retrofit local helper and\n * clientapp's current `getInitialFullName(name, null, true)`), reconciled\n * here as the single implementation. Matches the exact algorithm both\n * apps already use: first initial of the first word + the second word\n * verbatim, dropping anything beyond that (e.g. \"John Van Buren\" -> \"J.\n * Van\", not \"J. Buren\") -- not fixed here, since fixing it would make this\n * package's output diverge from what both apps' real data already looks\n * like today. */\nexport function abbreviatePersonName(name: string | null | undefined): string | null {\n const trimmed = name?.trim();\n if (!trimmed) return null;\n const parts = trimmed.split(\" \");\n const initial = parts[0]?.charAt(0).toUpperCase() ?? \"\";\n const last = parts[1] ?? \"\";\n return `${initial}. ${last}`;\n}\n"],"mappings":";AAAA,SAAS,QAAQ,gBAAgB;AAW1B,SAAS,cAAc,MAAgB,aAAkC;AAC9E,MAAI,YAAa,QAAO;AACxB,QAAM,QAAQ,KAAK,YAAY;AAC/B,MAAI,SAAS,SAAS,KAAK,IAAI,oBAAI,KAAK,EAAG,QAAO;AAClD,SAAO;AACT;AAGO,SAAS,eAAe,SAAiC;AAC9D,MAAI,CAAC,QAAS,QAAO;AACrB,MAAI;AACF,WAAO,OAAO,SAAS,OAAO,GAAG,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D;AAClF,SAAO,SAAS,WAAW,SAAS;AACtC;AAGO,SAAS,kBAAkB,MAAqD;AACrF,SAAO,SAAS;AAClB;AAGO,SAAS,iBAAiB,MAAqD;AACpF,SAAO,SAAS;AAClB;AAOO,SAAS,mBAAmB,SAAkD;AACnF,SAAO,SAAS,WAAW;AAC7B;AAGO,SAAS,uBACd,MACA,aACsC;AACtC,SAAO,cAAc,WAAW;AAClC;;;AC5BO,SAAS,sBAAsB,YAA0C;AAC9E,SAAO,WAAW,SAAS,WAAW,WAAW,UAAU,cAAc,WAAW;AACtF;AAGO,SAAS,sBAAsB,YAA0C;AAC9E,SAAO,WAAW,SAAS,YAAY,WAAW,UAAU;AAC9D;;;ACFO,SAAS,qBAAqB,MAAgD;AACnF,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,QAAQ,QAAQ,MAAM,GAAG;AAC/B,QAAM,UAAU,MAAM,CAAC,GAAG,OAAO,CAAC,EAAE,YAAY,KAAK;AACrD,QAAM,OAAO,MAAM,CAAC,KAAK;AACzB,SAAO,GAAG,OAAO,KAAK,IAAI;AAC5B;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/dealStatus.ts","../src/currency.ts","../src/projectPermissions.ts","../src/marketingPermission.ts","../src/personName.ts","../src/teamSeasonRecord.ts","../src/teamRosterColumns.ts","../src/jsonValue.ts","../src/teamPlaceSummary.ts","../src/teamStaffSort.ts","../src/teamSeasonStats.ts","../src/teamSeasonSelector.ts","../src/recentGamesSelection.ts","../src/statRanking.ts","../src/teamFacts.ts","../src/recentGames.ts"],"sourcesContent":["import { format, parseISO } from \"date-fns\";\n\nexport type DealStatus = \"Active\" | \"Upcoming\" | \"Complete\";\n\ninterface DealLike {\n deal_terms?: {\n startDate?: string | null;\n } | null;\n}\n\n/** Identical logic in both nukleus-app and nukleus-clientapp's ProjectDealCard. */\nexport function getDealStatus(deal: DealLike, isCompleted: boolean): DealStatus {\n if (isCompleted) return \"Complete\";\n const start = deal.deal_terms?.startDate;\n if (start && parseISO(start) > new Date()) return \"Upcoming\";\n return \"Active\";\n}\n\n/** Identical logic in both apps' ProjectDealCard. */\nexport function formatDealDate(dateStr?: string | null): string {\n if (!dateStr) return \"—\";\n try {\n return format(parseISO(dateStr), \"MMM d, yyyy\");\n } catch {\n return dateStr;\n }\n}\n","/** Full-precision USD, e.g. \"$1,234.56\". */\nexport function fmtUSD(n: number): string {\n return new Intl.NumberFormat(\"en-US\", {\n style: \"currency\",\n currency: \"USD\",\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n }).format(n);\n}\n\n// Reconciled from both apps -- see RECONCILIATION.md#currencyts\n/** Whole-dollar USD, e.g. \"$1,235\"; null-safe, falls back to \"--\". */\nexport function fmtUSDWhole(n?: number): string {\n return n != null\n ? new Intl.NumberFormat(\"en-US\", {\n style: \"currency\",\n currency: \"USD\",\n maximumFractionDigits: 0,\n }).format(n)\n : \"--\";\n}\n\n/** \"$54,000\" for whole dollars, \"$84.50\" otherwise. */\nexport function fmtUSDCompact(n: number): string {\n const cents = Math.round(n * 100);\n return new Intl.NumberFormat(\"en-US\", {\n style: \"currency\",\n currency: \"USD\",\n minimumFractionDigits: cents % 100 === 0 ? 0 : 2,\n maximumFractionDigits: 2,\n }).format(cents / 100);\n}\n\n/** Generic \"--\"-on-empty stringifier. */\nexport function fmt(value: string | number | null | undefined, fallback = \"--\"): string {\n if (value === null || value === undefined || value === \"\") return fallback;\n return String(value);\n}\n\n/** Whole-dollar \"$\"-prefixed display via toLocaleString, no Intl currency\n * formatting -- kept distinct from fmtUSDWhole to match an exact call site. */\nexport function fmtCurrency(amount: number | null | undefined): string {\n if (amount === null || amount === undefined) return \"--\";\n return `$${Number(amount).toLocaleString(\"en-US\", {\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n })}`;\n}\n\n/** MM/DD/YYYY, \"--\" on empty/invalid. */\nexport function fmtDate(dateStr: string | null | undefined): string {\n if (!dateStr) return \"--\";\n try {\n return new Date(dateStr).toLocaleDateString(\"en-US\", {\n month: \"2-digit\",\n day: \"2-digit\",\n year: \"numeric\",\n });\n } catch {\n return dateStr;\n }\n}\n","export type ProjectMemberRole = \"Owner\" | \"Editor\" | \"Viewer\";\n\n// Reconciled from both apps -- see RECONCILIATION.md#projectpermissionsts\nexport function canEditProject(role: ProjectMemberRole | null | undefined): boolean {\n return role === \"Owner\" || role === \"Editor\";\n}\n\n/** Changing task status requires Editor specifically, not just edit access. */\nexport function canEditTaskStatus(role: ProjectMemberRole | null | undefined): boolean {\n return role === \"Editor\";\n}\n\n/** Owner-only; nukleus-clientapp has no equivalent affordance today. */\nexport function canManageMembers(role: ProjectMemberRole | null | undefined): boolean {\n return role === \"Owner\";\n}\n\ninterface ProjectLike {\n status?: string | null;\n}\n\n/** Drives UI gating only -- server-side RLS already blocks writes regardless. */\nexport function isProjectCancelled(project: ProjectLike | null | undefined): boolean {\n return project?.status === \"Cancelled\";\n}\n\n// Reconciled from both apps -- see RECONCILIATION.md#projectpermissionsts\nexport function getEffectiveMemberRole(\n role: ProjectMemberRole | null | undefined,\n isCancelled: boolean,\n): ProjectMemberRole | null | undefined {\n return isCancelled ? \"Viewer\" : role;\n}\n","// Reconciled from both apps -- see RECONCILIATION.md#marketingpermissionts\nexport type MarketingPermission =\n { kind: \"levels\"; level: \"No Access\" | \"View\" | \"Edit\" } | { kind: \"linked\"; isLinked: boolean };\n\nexport function canViewMarketingDeals(permission: MarketingPermission): boolean {\n return permission.kind === \"levels\" ? permission.level !== \"No Access\" : permission.isLinked;\n}\n\n/** Always false for the \"linked\" shape -- clients never get write access. */\nexport function canEditMarketingDeals(permission: MarketingPermission): boolean {\n return permission.kind === \"levels\" && permission.level === \"Edit\";\n}\n","/** \"J. Smith\" from \"John Smith\" -- both apps' real current behavior for a\n * project deal's owner name (nukleus-app's pre-retrofit local helper and\n * clientapp's current `getInitialFullName(name, null, true)`), reconciled\n * here as the single implementation. Matches the exact algorithm both\n * apps already use: first initial of the first word + the second word\n * verbatim, dropping anything beyond that (e.g. \"John Van Buren\" -> \"J.\n * Van\", not \"J. Buren\") -- not fixed here, since fixing it would make this\n * package's output diverge from what both apps' real data already looks\n * like today. */\nexport function abbreviatePersonName(name: string | null | undefined): string | null {\n const trimmed = name?.trim();\n if (!trimmed) return null;\n const parts = trimmed.split(\" \");\n const initial = parts[0]?.charAt(0).toUpperCase() ?? \"\";\n const last = parts[1] ?? \"\";\n return `${initial}. ${last}`;\n}\n","export interface SeasonSummary {\n record: string;\n gamesPlayed: number;\n totalGames: number;\n}\n\ninterface SeasonRecordCompetitor {\n id: string;\n score: { value: number };\n winner?: boolean;\n}\n\ninterface SeasonRecordGameDetails {\n competitions?: {\n status?: { type?: { id?: string }; period?: number };\n competitors?: SeasonRecordCompetitor[];\n }[];\n}\n\nexport interface SeasonRecordGame {\n game_details: SeasonRecordGameDetails | null;\n}\n\n/** NHL's league id — the only league that reports overtime losses as a distinct record column. */\nconst HOCKEY_LEAGUE_ID = 14;\n\n/** ESPN's status.type.id for a completed game. */\nconst STATUS_FINAL = \"3\";\n\n/** Derives a W-L(-OTL/-T) record from a season's raw ESPN game payloads -- see RECONCILIATION.md. */\nexport function computeSeasonSummary(\n games: SeasonRecordGame[],\n espnId: string,\n leagueId: number,\n): SeasonSummary {\n const totalGames = games.length;\n const isHockey = leagueId === HOCKEY_LEAGUE_ID;\n\n let wins = 0;\n let losses = 0;\n let otLosses = 0;\n let ties = 0;\n let completedGames = 0;\n\n for (const game of games) {\n const competition = game.game_details?.competitions?.[0];\n const status = competition?.status?.type?.id;\n const competitors = competition?.competitors;\n\n if (status !== STATUS_FINAL || !competitors || competitors.length !== 2) continue;\n\n const [c0, c1] = competitors;\n const myCompetitor = c0.id === espnId ? c0 : c1.id === espnId ? c1 : null;\n if (!myCompetitor) continue;\n\n completedGames++;\n\n if (c0.score.value === c1.score.value) {\n ties++;\n } else if (myCompetitor.winner === true) {\n wins++;\n } else if (isHockey && (competition?.status?.period ?? 0) > 3) {\n otLosses++;\n } else {\n losses++;\n }\n }\n\n const record = isHockey\n ? `${wins}-${losses}-${otLosses}`\n : ties > 0\n ? `${wins}-${losses}-${ties}`\n : `${wins}-${losses}`;\n\n return { record, gamesPlayed: completedGames, totalGames };\n}\n","export type RosterColumnKey =\n | \"first_name\"\n | \"number\"\n | \"position\"\n | \"height\"\n | \"weight\"\n | \"age\"\n | \"experience\"\n | \"college\"\n | \"birthplace\"\n | \"hometown\";\n\nexport interface RosterColumnDef {\n key: RosterColumnKey;\n label: string;\n}\n\n/** The subset of a player's specific_data (jsonb) the roster table reads. */\nexport interface RosterPlayerSpecificData {\n height?: string | number | null;\n weight?: string | number | null;\n birth_date?: string | null;\n college_name?: string | null;\n birth_city?: string | null;\n birth_state?: string | null;\n birth_country?: string | null;\n}\n\nexport interface RosterPlayerLike {\n first_name: string | null;\n last_name: string | null;\n number: string | number | null;\n position: string | null;\n experience: string | null;\n specific_data: RosterPlayerSpecificData | null;\n}\n\n/** League ids sharing one roster column set — identical groupings in both apps. */\nconst NFL_NBA_WNBA_LEAGUE_IDS = [1, 4, 5];\nconst MLB_NHL_LEAGUE_IDS = [7, 14];\nconst NCAAF_LEAGUE_IDS = [2, 13];\nconst NCAAM_LEAGUE_ID = 6;\nconst MLS_LEAGUE_ID = 10;\nconst MLB_LEAGUE_ID = 7;\n\nconst BASE_COLUMNS: RosterColumnDef[] = [\n { key: \"first_name\", label: \"Name\" },\n { key: \"number\", label: \"No.\" },\n { key: \"position\", label: \"Position\" },\n { key: \"height\", label: \"Height\" },\n { key: \"weight\", label: \"Weight\" },\n { key: \"age\", label: \"Age\" },\n];\n\n/** Per-league roster column set, identical in both apps -- see RECONCILIATION.md. */\nexport function getRosterColumns(leagueId: number): RosterColumnDef[] {\n if (NFL_NBA_WNBA_LEAGUE_IDS.includes(leagueId)) {\n return [\n ...BASE_COLUMNS,\n { key: \"experience\", label: \"Exp.\" },\n { key: \"college\", label: \"College\" },\n ];\n }\n if (MLB_NHL_LEAGUE_IDS.includes(leagueId)) {\n return [\n ...BASE_COLUMNS,\n { key: \"experience\", label: \"Exp\" },\n { key: \"birthplace\", label: \"Birthplace\" },\n ];\n }\n if (NCAAF_LEAGUE_IDS.includes(leagueId)) {\n return [\n ...BASE_COLUMNS,\n { key: \"experience\", label: \"Class\" },\n { key: \"hometown\", label: \"Hometown\" },\n ];\n }\n if (leagueId === NCAAM_LEAGUE_ID) {\n return [\n ...BASE_COLUMNS,\n { key: \"experience\", label: \"Class\" },\n { key: \"birthplace\", label: \"Birthplace\" },\n ];\n }\n if (leagueId === MLS_LEAGUE_ID) {\n return [...BASE_COLUMNS, { key: \"birthplace\", label: \"Birthplace\" }];\n }\n return [];\n}\n\nfunction calculateAge(birthDateString: string): number {\n const birthDate = new Date(birthDateString);\n const today = new Date();\n let age = today.getFullYear() - birthDate.getFullYear();\n const monthDiff = today.getMonth() - birthDate.getMonth();\n if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {\n age--;\n }\n return age;\n}\n\n/** Identical in both apps' `formatBirthplace` -- MLS/MLB have their own rules; see RECONCILIATION.md. */\nfunction formatBirthplace(specificData: RosterPlayerSpecificData | null, leagueId: number): string {\n if (!specificData) return \"--\";\n\n if (leagueId === MLS_LEAGUE_ID) {\n const country = specificData.birth_country;\n return country ? String(country).trim() : \"--\";\n }\n\n const city = typeof specificData.birth_city === \"string\" ? specificData.birth_city.trim() : \"\";\n const state = typeof specificData.birth_state === \"string\" ? specificData.birth_state.trim() : \"\";\n const country =\n typeof specificData.birth_country === \"string\" ? specificData.birth_country.trim() : \"\";\n\n const hasCity = city.length > 0;\n const hasState = state.length > 0;\n const hasCountry = country.length > 0;\n const isUsa = country === \"USA\" || country === \"United States\";\n\n if (!hasCity && !hasState) {\n if (hasCountry && leagueId === MLB_LEAGUE_ID && isUsa) return \"--\";\n return hasCountry ? country : \"--\";\n }\n\n let result = \"\";\n if (hasCity && hasState) result = `${city}, ${state}`;\n else if (hasCity) result = city;\n else if (hasState) result = state;\n\n if (hasCountry) {\n const excludeCountry = leagueId === MLB_LEAGUE_ID ? isUsa : country === \"USA\";\n if (!excludeCountry) {\n if (hasState) result += ` ${country}`;\n else if (hasCity) result += `, ${country}`;\n else result += ` ${country}`;\n }\n }\n\n return result || \"--\";\n}\n\n/** Reconciled from both apps' identical `formatHometown`. */\nfunction formatHometown(specificData: RosterPlayerSpecificData | null): string {\n if (!specificData) return \"--\";\n const city = specificData.birth_city || \"\";\n const state = specificData.birth_state || \"\";\n if (city && state) return `${city}, ${state}`;\n if (city) return city;\n if (state) return state;\n return \"--\";\n}\n\n/**\n * Formats one roster cell's display value. `leagueId` is only read for `birthplace`'s\n * league-specific formatting (MLS/MLB rules above).\n */\nexport function getRosterCellValue(\n player: RosterPlayerLike,\n columnKey: RosterColumnKey,\n leagueId: number,\n): string {\n switch (columnKey) {\n case \"first_name\":\n return player.first_name\n ? [player.first_name, player.last_name].filter(Boolean).join(\" \")\n : \"-\";\n case \"number\":\n return player.number !== null && player.number !== undefined && player.number !== \"\"\n ? String(player.number)\n : \"-\";\n case \"position\":\n return player.position || \"-\";\n case \"height\":\n return player.specific_data?.height ? String(player.specific_data.height) : \"-\";\n case \"weight\":\n return player.specific_data?.weight ? `${player.specific_data.weight} lbs` : \"-\";\n case \"age\":\n return player.specific_data?.birth_date\n ? String(calculateAge(player.specific_data.birth_date))\n : \"-\";\n case \"experience\":\n return player.experience === \"0\" ? \"R\" : player.experience || \"-\";\n case \"college\":\n return player.specific_data?.college_name || \"-\";\n case \"birthplace\":\n return formatBirthplace(player.specific_data ?? null, leagueId);\n case \"hometown\":\n return formatHometown(player.specific_data ?? null);\n default:\n return \"-\";\n }\n}\n","/** Small guards for reading untyped JSON (e.g. `teams.specific_data`) without casts at every call site. */\n\n/** True for a plain JSON object -- not null, not an array. */\nexport function isJsonRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** The value as a JSON object, or `{}` when it isn't one. */\nexport function toJsonRecord(value: unknown): Record<string, unknown> {\n return isJsonRecord(value) ? value : {};\n}\n\n/** Trimmed text, or null for non-strings and blank strings. */\nexport function toTrimmedText(value: unknown): string | null {\n if (typeof value !== \"string\") return null;\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n","import { toJsonRecord } from \"./jsonValue\";\n\n/** The venue a team plays in: a stadium, or an arena for indoor leagues. */\nexport type TeamVenueKind = \"stadium\" | \"arena\";\n/** The practice facility a team uses. */\nexport type TeamFacilityKind = \"training_facility\" | \"coaches_facility\";\nexport type TeamPlaceKind = TeamVenueKind | TeamFacilityKind;\n\nexport interface TeamPlace {\n name: string;\n street: string;\n city: string;\n state: string;\n zipcode: string;\n}\n\nexport interface TeamPlaceSummary {\n /** \"Stadium\", \"Arena\", \"Training Facility\" or \"Coaches Facility\" -- picked by the league. */\n label: string;\n /** null when the place has no name saved. */\n name: string | null;\n /** \"1 Main St, Seattle, WA, 98134\"; empty when no address part is saved. */\n address: string;\n}\n\nconst TEAM_PLACE_PARTS = [\"name\", \"street\", \"city\", \"state\", \"zipcode\"] as const;\n\nconst EMPTY_TEAM_PLACE: TeamPlace = { name: \"\", street: \"\", city: \"\", state: \"\", zipcode: \"\" };\n\n/** Indoor leagues play in arenas. */\nconst ARENA_LEAGUES = new Set([\"NBA\", \"WNBA\", \"NCAAM\", \"NHL\"]);\n\n/** College leagues (NCAAF (FBS), NCAAF (FCS), NCAAM) have a coaches facility instead of a training facility. */\nfunction isCollegeLeague(abbreviation: string): boolean {\n return abbreviation.startsWith(\"NCAA\");\n}\n\n/** Which venue (stadium or arena) a league uses -- the one rule for Team Facts, the Team Info\n * card, and the Team page. */\nexport function getTeamVenueConfig(leagueAbbreviation: string | null | undefined): {\n kind: TeamVenueKind;\n label: \"Stadium\" | \"Arena\";\n} {\n return leagueAbbreviation && ARENA_LEAGUES.has(leagueAbbreviation)\n ? { kind: \"arena\", label: \"Arena\" }\n : { kind: \"stadium\", label: \"Stadium\" };\n}\n\n/** Which practice facility a league uses. */\nexport function getTeamFacilityConfig(leagueAbbreviation: string | null | undefined): {\n kind: TeamFacilityKind;\n label: \"Training Facility\" | \"Coaches Facility\";\n} {\n return leagueAbbreviation && isCollegeLeague(leagueAbbreviation)\n ? { kind: \"coaches_facility\", label: \"Coaches Facility\" }\n : { kind: \"training_facility\", label: \"Training Facility\" };\n}\n\n/** Storage key for one part of a place, e.g. `arena_city`. */\nfunction teamPlaceKey(kind: TeamPlaceKind, part: (typeof TEAM_PLACE_PARTS)[number]): string {\n return `${kind}_${part}`;\n}\n\n/** Reads one place's flat `<kind>_name`/`_street`/`_city`/`_state`/`_zipcode` keys out of `specific_data`. */\nexport function parseTeamPlace(\n specificData: Record<string, unknown>,\n kind: TeamPlaceKind,\n): TeamPlace {\n const place: TeamPlace = { ...EMPTY_TEAM_PLACE };\n for (const part of TEAM_PLACE_PARTS) {\n const value = specificData[teamPlaceKey(kind, part)];\n place[part] = typeof value === \"string\" ? value : \"\";\n }\n return place;\n}\n\nexport function formatTeamPlaceAddress(place: TeamPlace): string {\n return [place.street, place.city, place.state, place.zipcode]\n .map((part) => part.trim())\n .filter(Boolean)\n .join(\", \");\n}\n\nfunction summarize(label: string, place: TeamPlace): TeamPlaceSummary {\n const name = place.name.trim();\n return { label, name: name || null, address: name ? formatTeamPlaceAddress(place) : \"\" };\n}\n\n/** The league's venue and practice facility -- see RECONCILIATION.md. */\nexport function getTeamPlaceSummaries(\n specificData: unknown,\n leagueAbbreviation: string | null | undefined,\n): { venue: TeamPlaceSummary; facility: TeamPlaceSummary } {\n const data = toJsonRecord(specificData);\n const venue = getTeamVenueConfig(leagueAbbreviation);\n const facility = getTeamFacilityConfig(leagueAbbreviation);\n return {\n venue: summarize(venue.label, parseTeamPlace(data, venue.kind)),\n facility: summarize(facility.label, parseTeamPlace(data, facility.kind)),\n };\n}\n\n/** \"Seattle Seahawks\" from the `team` + `nickname` columns; either part may be missing. */\nexport function formatTeamName(\n team: string | null | undefined,\n nickname: string | null | undefined,\n): string {\n return [team, nickname]\n .map((part) => part?.trim())\n .filter(Boolean)\n .join(\" \");\n}\n","export interface StaffMember {\n id: number;\n first_name: string;\n last_name: string;\n position: string | null;\n display_order: number;\n}\n\nexport interface StaffSort {\n id: string;\n desc: boolean;\n}\n\nconst EMPTY_VALUES = new Set([\"\", \"-\"]);\n\nfunction compareValues(left: string | number, right: string | number, desc: boolean): number {\n const leftMissing = typeof left === \"string\" && EMPTY_VALUES.has(left);\n const rightMissing = typeof right === \"string\" && EMPTY_VALUES.has(right);\n if (leftMissing && rightMissing) return 0;\n if (leftMissing) return 1;\n if (rightMissing) return -1;\n\n const direction = desc ? -1 : 1;\n if (typeof left === \"number\" && typeof right === \"number\") {\n return (left - right) * direction;\n }\n return (\n String(left).localeCompare(String(right), undefined, { numeric: true, sensitivity: \"base\" }) *\n direction\n );\n}\n\n/** Sorts staff by name, position, or (by default) saved display order -- see RECONCILIATION.md. */\nexport function sortTeamStaff<T extends StaffMember>(staff: T[], sorting: StaffSort[]): T[] {\n const activeSort = sorting[0];\n if (!activeSort) return staff;\n return [...staff].sort((left, right) => {\n const value = (member: T): string | number => {\n switch (activeSort.id) {\n case \"name\":\n return `${member.first_name} ${member.last_name}`.trim();\n case \"position\":\n return member.position ?? \"-\";\n default:\n return member.display_order;\n }\n };\n return compareValues(value(left), value(right), activeSort.desc);\n });\n}\n","export interface StatColumnDef {\n label: string;\n suffix?: string;\n}\n\nexport interface TeamSeasonStatsResult {\n /** Generic 4-value result -- meaning varies by sport. */\n values: [string, string, string, string];\n}\n\nexport interface TeamSeasonStatEntry {\n stat_id: number;\n stat_value: string | number | null;\n}\n\nexport interface TeamSeasonStatRecord {\n stat_details: { stats?: TeamSeasonStatEntry[] } | null;\n}\n\nexport const FOOTBALL_TEAM_STAT_IDS = {\n PASSING_YARDS: 255,\n RUSHING_YARDS: 261,\n POINTS_FOR: 271,\n POINTS_AGAINST: 272,\n};\n\nexport const BASKETBALL_TEAM_STAT_IDS = {\n POINTS_FOR: 300,\n REBOUNDS: 279,\n ASSISTS: 285,\n POINTS_AGAINST: 301,\n};\n\nexport const BASEBALL_TEAM_STAT_IDS = {\n HITS: 303,\n AT_BATS: 308,\n HOMERUNS: 309,\n STRIKEOUTS: 315,\n EARNED_RUNS: 317,\n INNINGS_PITCHED: 325,\n};\n\nexport const HOCKEY_TEAM_STAT_IDS = {\n GOALS_FOR: 346,\n GOALS_AGAINST: 347,\n SHOTS: 332,\n POWER_PLAY_GOALS: 334,\n POWER_PLAY_ATTEMPTS: 336,\n};\n\n/** Team ranking config ids per league, in the same order as `getTeamStatColumns` for that sport. */\nconst TEAM_RANKING_CONFIG_IDS: Record<number, Record<number, number[]>> = {\n 1: {\n 1: [100, 101, 102, 103], // NFL\n 2: [104, 105, 106, 107], // NCAAF (FBS)\n 13: [108, 109, 110, 111], // NCAAF (FCS)\n },\n 2: {\n 4: [112, 113, 114, 115], // NBA\n 5: [116, 117, 118, 119], // WNBA\n 6: [120, 121, 122, 123], // NCAAM\n },\n 3: { 7: [124, 125, 126, 127] }, // MLB\n 5: { 14: [128, 129, 130, 131] }, // NHL\n};\n\n/** The ranking config ids behind a team's 4 headline stats, or `null` when that league has none. */\nexport function getTeamRankingConfigIds(\n sportId: number | null | undefined,\n leagueId: number | null | undefined,\n): number[] | null {\n if (!sportId || !leagueId) return null;\n const ids = TEAM_RANKING_CONFIG_IDS[sportId]?.[leagueId];\n // A copy, so a caller editing the result can't change later lookups.\n return ids ? [...ids] : null;\n}\n\nconst SUPPORTED_TEAM_STATS_SPORT_IDS = [1, 2, 3, 5];\n\n/** Whether `getTeamStatColumns`/`computeTeamSeasonStats` has a real implementation for this sport. */\nexport function isSupportedTeamStatsSport(sportId: number): boolean {\n return SUPPORTED_TEAM_STATS_SPORT_IDS.includes(sportId);\n}\n\n/** Get the 4 stat column definitions for a team based on sport. */\nexport function getTeamStatColumns(sportId: number): StatColumnDef[] {\n if (sportId === 1) {\n return [\n { label: \"Passing Yards\" },\n { label: \"Rushing Yards\" },\n { label: \"Points For\" },\n { label: \"Points Against\" },\n ];\n }\n if (sportId === 2) {\n return [\n { label: \"Points For\" },\n { label: \"Points Against\" },\n { label: \"Rebounds\" },\n { label: \"Assists\" },\n ];\n }\n if (sportId === 3) {\n return [\n { label: \"Batting Average\" },\n { label: \"Homeruns\" },\n { label: \"ERA\" },\n { label: \"Strikeouts\" },\n ];\n }\n if (sportId === 5) {\n return [\n { label: \"Goals For\" },\n { label: \"Goals Against\" },\n { label: \"Shots\" },\n { label: \"Power Play %\" },\n ];\n }\n return [];\n}\n\nfunction sumStatsByIds(\n statsData: TeamSeasonStatRecord[],\n idMap: Record<string, number>,\n): Record<string, number> {\n const totals: Record<string, number> = {};\n const idToKey: Record<number, string> = {};\n for (const [key, id] of Object.entries(idMap)) {\n idToKey[id] = key;\n totals[key] = 0;\n }\n\n for (const record of statsData) {\n const stats = record.stat_details?.stats ?? [];\n for (const s of stats) {\n const key = idToKey[s.stat_id];\n if (key) totals[key] += parseFloat(String(s.stat_value ?? 0));\n }\n }\n\n return totals;\n}\n\nfunction parseInningsPitched(value: string | number): { wholeInnings: number; thirds: number } {\n const numValue = typeof value === \"string\" ? parseFloat(value) : value;\n if (isNaN(numValue)) return { wholeInnings: 0, thirds: 0 };\n const wholeInnings = Math.floor(numValue);\n const decimalPart = Math.round((numValue - wholeInnings) * 10);\n return { wholeInnings, thirds: decimalPart };\n}\n\nfunction computeFootball(statsData: TeamSeasonStatRecord[]): TeamSeasonStatsResult {\n const totals = sumStatsByIds(statsData, FOOTBALL_TEAM_STAT_IDS);\n const g = statsData.length;\n const avg = (key: string) => (g > 0 ? (totals[key] / g).toFixed(1) : \"0.0\");\n return {\n values: [avg(\"PASSING_YARDS\"), avg(\"RUSHING_YARDS\"), avg(\"POINTS_FOR\"), avg(\"POINTS_AGAINST\")],\n };\n}\n\nfunction computeBasketball(statsData: TeamSeasonStatRecord[]): TeamSeasonStatsResult {\n const totals = sumStatsByIds(statsData, BASKETBALL_TEAM_STAT_IDS);\n const g = statsData.length;\n const avg = (key: string) => (g > 0 ? (totals[key] / g).toFixed(1) : \"0.0\");\n return { values: [avg(\"POINTS_FOR\"), avg(\"POINTS_AGAINST\"), avg(\"REBOUNDS\"), avg(\"ASSISTS\")] };\n}\n\nfunction computeBaseball(statsData: TeamSeasonStatRecord[]): TeamSeasonStatsResult {\n let totalHits = 0;\n let totalAtBats = 0;\n let totalHomeruns = 0;\n let totalStrikeouts = 0;\n let totalEarnedRuns = 0;\n let totalWholeInnings = 0;\n let totalThirds = 0;\n\n for (const record of statsData) {\n const stats = record.stat_details?.stats ?? [];\n for (const s of stats) {\n const numValue = parseFloat(String(s.stat_value ?? 0));\n if (s.stat_id === BASEBALL_TEAM_STAT_IDS.HITS) totalHits += numValue;\n if (s.stat_id === BASEBALL_TEAM_STAT_IDS.AT_BATS) totalAtBats += numValue;\n if (s.stat_id === BASEBALL_TEAM_STAT_IDS.HOMERUNS) totalHomeruns += numValue;\n if (s.stat_id === BASEBALL_TEAM_STAT_IDS.STRIKEOUTS) totalStrikeouts += numValue;\n if (s.stat_id === BASEBALL_TEAM_STAT_IDS.EARNED_RUNS) totalEarnedRuns += numValue;\n if (s.stat_id === BASEBALL_TEAM_STAT_IDS.INNINGS_PITCHED) {\n const { wholeInnings, thirds } = parseInningsPitched(s.stat_value ?? 0);\n totalWholeInnings += wholeInnings;\n totalThirds += thirds;\n }\n }\n }\n\n const battingAverage = totalAtBats > 0 ? totalHits / totalAtBats : 0;\n const additionalWholeInnings = Math.floor(totalThirds / 3);\n const remainderThirds = totalThirds % 3;\n const totalInningsPitched = totalWholeInnings + additionalWholeInnings + remainderThirds / 3;\n const era = totalInningsPitched > 0 ? (totalEarnedRuns * 9) / totalInningsPitched : 0;\n\n return {\n values: [\n battingAverage.toFixed(3),\n totalHomeruns.toString(),\n era.toFixed(2),\n totalStrikeouts.toString(),\n ],\n };\n}\n\nfunction computeHockey(statsData: TeamSeasonStatRecord[]): TeamSeasonStatsResult {\n const totals = sumStatsByIds(statsData, HOCKEY_TEAM_STAT_IDS);\n const g = statsData.length;\n const avg = (key: string) => (g > 0 ? (totals[key] / g).toFixed(1) : \"0.0\");\n const ppPct =\n totals[\"POWER_PLAY_ATTEMPTS\"] > 0\n ? ((totals[\"POWER_PLAY_GOALS\"] / totals[\"POWER_PLAY_ATTEMPTS\"]) * 100).toFixed(1)\n : \"0.0\";\n\n return { values: [avg(\"GOALS_FOR\"), avg(\"GOALS_AGAINST\"), avg(\"SHOTS\"), ppPct] };\n}\n\n/** A team's 4 headline season-stat values, or `null` for an empty list/unsupported sport. */\nexport function computeTeamSeasonStats(\n statsData: TeamSeasonStatRecord[],\n sportId: number,\n): TeamSeasonStatsResult | null {\n if (!statsData || statsData.length === 0) return null;\n\n if (sportId === 1) return computeFootball(statsData);\n if (sportId === 2) return computeBasketball(statsData);\n if (sportId === 3) return computeBaseball(statsData);\n if (sportId === 5) return computeHockey(statsData);\n\n return null;\n}\n\n/** One stat's precomputed season totals; which field is set depends on how the stat aggregates. */\nexport interface TeamSeasonStatTotal {\n sum?: number;\n num?: number;\n avg?: number;\n value?: number;\n}\n\nexport interface TeamSeasonSummaryRecord {\n games_played: number | null;\n stat_totals: Record<string, TeamSeasonStatTotal> | null;\n}\n\n/** Season total for a stat id, tolerating rate/compound shapes. */\nfunction summaryTotal(totals: Record<string, TeamSeasonStatTotal>, statId: number): number {\n const entry = totals[String(statId)];\n if (!entry) return 0;\n const raw = entry.sum ?? entry.value ?? entry.avg ?? entry.num;\n const parsed = typeof raw === \"number\" ? raw : parseFloat(String(raw ?? \"\"));\n return Number.isNaN(parsed) ? 0 : parsed;\n}\n\n/** The 4 headline values from a precomputed season summary, or `null` for no summary/unsupported sport. */\nexport function computeTeamSeasonStatsFromSummary(\n summary: TeamSeasonSummaryRecord | null | undefined,\n sportId: number,\n): TeamSeasonStatsResult | null {\n if (!summary || !summary.stat_totals) return null;\n\n const totals = summary.stat_totals;\n const g = summary.games_played || 0;\n const avgOf = (statId: number) => (g > 0 ? (summaryTotal(totals, statId) / g).toFixed(1) : \"0.0\");\n\n if (sportId === 1) {\n return {\n values: [\n avgOf(FOOTBALL_TEAM_STAT_IDS.PASSING_YARDS),\n avgOf(FOOTBALL_TEAM_STAT_IDS.RUSHING_YARDS),\n avgOf(FOOTBALL_TEAM_STAT_IDS.POINTS_FOR),\n avgOf(FOOTBALL_TEAM_STAT_IDS.POINTS_AGAINST),\n ],\n };\n }\n\n if (sportId === 2) {\n return {\n values: [\n avgOf(BASKETBALL_TEAM_STAT_IDS.POINTS_FOR),\n avgOf(BASKETBALL_TEAM_STAT_IDS.POINTS_AGAINST),\n avgOf(BASKETBALL_TEAM_STAT_IDS.REBOUNDS),\n avgOf(BASKETBALL_TEAM_STAT_IDS.ASSISTS),\n ],\n };\n }\n\n if (sportId === 3) {\n const hits = summaryTotal(totals, BASEBALL_TEAM_STAT_IDS.HITS);\n const atBats = summaryTotal(totals, BASEBALL_TEAM_STAT_IDS.AT_BATS);\n const earnedRuns = summaryTotal(totals, BASEBALL_TEAM_STAT_IDS.EARNED_RUNS);\n // Innings are stored as true decimals in the summary (5 1/3 -> 5.333).\n const innings = summaryTotal(totals, BASEBALL_TEAM_STAT_IDS.INNINGS_PITCHED);\n const battingAverage = atBats > 0 ? hits / atBats : 0;\n const era = innings > 0 ? (earnedRuns * 9) / innings : 0;\n return {\n values: [\n battingAverage.toFixed(3),\n summaryTotal(totals, BASEBALL_TEAM_STAT_IDS.HOMERUNS).toString(),\n era.toFixed(2),\n summaryTotal(totals, BASEBALL_TEAM_STAT_IDS.STRIKEOUTS).toString(),\n ],\n };\n }\n\n if (sportId === 5) {\n const ppGoals = summaryTotal(totals, HOCKEY_TEAM_STAT_IDS.POWER_PLAY_GOALS);\n const ppAttempts = summaryTotal(totals, HOCKEY_TEAM_STAT_IDS.POWER_PLAY_ATTEMPTS);\n return {\n values: [\n avgOf(HOCKEY_TEAM_STAT_IDS.GOALS_FOR),\n avgOf(HOCKEY_TEAM_STAT_IDS.GOALS_AGAINST),\n avgOf(HOCKEY_TEAM_STAT_IDS.SHOTS),\n ppAttempts > 0 ? ((ppGoals / ppAttempts) * 100).toFixed(1) : \"0.0\",\n ],\n };\n }\n\n return null;\n}\n","export interface SeasonSelectorSeason {\n season_year: number;\n season_type: number;\n year_display: string;\n type_name: string;\n}\n\nexport interface SeasonSelectorOption {\n value: number;\n label: string;\n}\n\n/** Prefers Regular Season (type 2) when available, otherwise the newest type. */\nexport function getPreferredSeasonType(types: number[]): number | null {\n if (types.length === 0) return null;\n if (types.includes(2)) return 2;\n return Math.max(...types);\n}\n\n/** Distinct years, newest first, each labeled from its first matching season. */\nexport function getSeasonYearOptions(seasons: SeasonSelectorSeason[]): SeasonSelectorOption[] {\n const years = [...new Set(seasons.map((s) => s.season_year))].sort((a, b) => b - a);\n return years.map((year) => ({\n value: year,\n label: seasons.find((s) => s.season_year === year)?.year_display ?? String(year),\n }));\n}\n\n/** The season types available for one year, newest type first. */\nexport function getSeasonTypeOptions(\n seasons: SeasonSelectorSeason[],\n selectedYear: number | null,\n): SeasonSelectorOption[] {\n if (selectedYear === null) return [];\n return seasons\n .filter((s) => s.season_year === selectedYear)\n .sort((a, b) => b.season_type - a.season_type)\n .map((s) => ({ value: s.season_type, label: s.type_name }));\n}\n","export interface DatedGame {\n id: number;\n}\n\n/**\n * Selects up to 3 past + 3 upcoming games (6 total), backfilling from whichever side has fewer than\n * 3 so a short side still leaves 6 shown. `pastGames` must be most-recent-first and `upcomingGames`\n * soonest-first; the result reads chronologically, past to future.\n */\nexport function selectRecentGames<T extends DatedGame>(upcomingGames: T[], pastGames: T[]): T[] {\n let selectedPastGames: T[];\n let selectedUpcomingGames: T[];\n\n if (upcomingGames.length >= 3 && pastGames.length >= 3) {\n selectedPastGames = pastGames.slice(0, 3);\n selectedUpcomingGames = upcomingGames.slice(0, 3);\n } else if (upcomingGames.length < 3) {\n selectedUpcomingGames = upcomingGames;\n selectedPastGames = pastGames.slice(0, Math.min(6 - upcomingGames.length, pastGames.length));\n } else {\n selectedPastGames = pastGames;\n selectedUpcomingGames = upcomingGames.slice(\n 0,\n Math.min(6 - pastGames.length, upcomingGames.length),\n );\n }\n\n // Copy before reversing: callers pass RTK Query's shared cached arrays, and reverse() mutates.\n return [...[...selectedPastGames].reverse(), ...selectedUpcomingGames];\n}\n","export interface StatRanking {\n stat_type_id: number;\n config_id: number;\n rank: number;\n tied: boolean;\n}\n\n/** Ordinal for a rank (1 -> \"1st\", 12 -> \"12th\", 23 -> \"23rd\"). */\nexport function toOrdinal(rank: number): string {\n const mod10 = rank % 10;\n const mod100 = rank % 100;\n if (mod10 === 1 && mod100 !== 11) return `${rank}st`;\n if (mod10 === 2 && mod100 !== 12) return `${rank}nd`;\n if (mod10 === 3 && mod100 !== 13) return `${rank}rd`;\n return `${rank}th`;\n}\n\nfunction formatOrdinal(rank: number, tied: boolean): string {\n return tied ? `T-${toOrdinal(rank)}` : toOrdinal(rank);\n}\n\n/** A ranking's ordinal (\"1st\", \"T-2nd\") looked up by `stat_type_id`, or null when unranked. */\nexport function formatStatRank(rankings: StatRanking[], statTypeId: number): string | null {\n const ranking = rankings.find((r) => r.stat_type_id === statTypeId);\n return ranking ? formatOrdinal(ranking.rank, ranking.tied) : null;\n}\n\n/** A ranking's ordinal looked up by `config_id`, or null when unranked. */\nexport function formatStatRankByConfig(\n rankings: Pick<StatRanking, \"config_id\" | \"rank\" | \"tied\">[],\n configId: number,\n): string | null {\n const ranking = rankings.find((r) => r.config_id === configId);\n return ranking ? formatOrdinal(ranking.rank, ranking.tied) : null;\n}\n\n/**\n * A stat value at the precision `stat_ranking_configs` declares. Percentages (already normalized by\n * the caller) always show exactly one decimal. `locale` defaults to the runtime's; pass one\n * explicitly where output must be deterministic (tests, SSR).\n */\nexport function formatStatNumber(\n value: number,\n decimals: number | null,\n isPercent?: boolean,\n locale?: string | string[],\n): string {\n const places = isPercent\n ? 1\n : decimals !== null && decimals >= 0\n ? decimals\n : value % 1 === 0\n ? 0\n : 1;\n return value.toLocaleString(locale, {\n minimumFractionDigits: places,\n maximumFractionDigits: places,\n });\n}\n\n/** League-rank pill copy: only the top 10% and top 20% are badged, anything lower returns null. */\nexport function topPercentileLabel(rank: number | null, total: number | null): string | null {\n if (!rank || !total || rank < 1 || total < 1) return null;\n const percentile = (rank / total) * 100;\n if (percentile <= 10) return \"Top 10%\";\n if (percentile <= 20) return \"Top 20%\";\n return null;\n}\n\nexport interface StatRankingFootnoteConfig {\n position_filter?: string[] | null;\n minimum_games?: number | null;\n}\n\n/** The qualifier footnotes under a leaderboard (position filter, minimum games played). */\nexport function getStatRankingFootnotes(\n config: StatRankingFootnoteConfig | null | undefined,\n): string[] {\n const footnotes: string[] = [];\n if (config?.position_filter && config.position_filter.length > 0) {\n footnotes.push(`Filtered by position: ${config.position_filter.join(\", \")}`);\n }\n if (config?.minimum_games && config.minimum_games > 0) {\n footnotes.push(`Min. ${config.minimum_games}% of team games played`);\n }\n return footnotes;\n}\n","import {\n getTeamFacilityConfig,\n getTeamVenueConfig,\n formatTeamName,\n type TeamVenueKind,\n} from \"./teamPlaceSummary\";\nimport { isJsonRecord, toTrimmedText } from \"./jsonValue\";\n\n// ---- Facts: the team's own trivia, stored at `teams.specific_data.facts` ----\n\nexport interface TeamFacts {\n championships_won: number | null;\n championship_years: number[];\n /** College: national titles below the top level or claimed, e.g. FCS, DII, NAIA. */\n other_national_titles: number | null;\n /** Year with an optional level, e.g. \"2005 (FCS)\" or \"1970\". */\n other_title_years: string[];\n championship_appearances: number | null;\n appearance_years: number[];\n conference_titles: number | null;\n /** FCS: the years of each conference title, listed under the count. */\n conference_title_years: number[];\n /** College: conference titles across every conference the school has played in. */\n total_conference_titles: number | null;\n /** College: one entry per conference with its title count, e.g. \"SEC (31)\". */\n conference_history: string[];\n division_titles: number | null;\n fan_nicknames: string[];\n traditions: string[];\n primary_rival_team_id: number | null;\n owner: string | null;\n stadium_capacity: number | null;\n year_established: number | null;\n /** College: the program's first season of play. */\n first_season: number | null;\n summary: string | null;\n}\n\nexport type TeamFactKey = keyof TeamFacts;\n\nconst EMPTY_TEAM_FACTS: TeamFacts = {\n championships_won: null,\n championship_years: [],\n other_national_titles: null,\n other_title_years: [],\n championship_appearances: null,\n appearance_years: [],\n conference_titles: null,\n conference_title_years: [],\n total_conference_titles: null,\n conference_history: [],\n division_titles: null,\n fan_nicknames: [],\n traditions: [],\n primary_rival_team_id: null,\n owner: null,\n stadium_capacity: null,\n year_established: null,\n first_season: null,\n summary: null,\n};\n\n/** Safe integers only: a 309-digit string parses to `Infinity`, and 1e300 is an \"integer\" too. */\nfunction toInt(value: unknown): number | null {\n if (typeof value === \"number\") return Number.isSafeInteger(value) ? value : null;\n if (typeof value === \"string\" && /^\\d+$/.test(value.trim())) {\n const parsed = Number(value.trim());\n return Number.isSafeInteger(parsed) ? parsed : null;\n }\n return null;\n}\n\nfunction toIntList(value: unknown): number[] {\n if (!Array.isArray(value)) return [];\n return value.map(toInt).filter((n): n is number => n !== null);\n}\n\nfunction toTextList(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.map(toTrimmedText).filter((s): s is string => s !== null);\n}\n\n/** True when the team has a `facts` object at all (even if every field is empty). */\nexport function hasTeamFacts(raw: unknown): boolean {\n return isJsonRecord(raw);\n}\n\n/** Safely reads a `facts` JSON value; missing/malformed fields fall back to empty values. */\nexport function parseTeamFacts(raw: unknown): TeamFacts {\n if (!isJsonRecord(raw)) return { ...EMPTY_TEAM_FACTS };\n return {\n championships_won: toInt(raw.championships_won),\n championship_years: toIntList(raw.championship_years),\n other_national_titles: toInt(raw.other_national_titles),\n other_title_years: toTextList(raw.other_title_years),\n championship_appearances: toInt(raw.championship_appearances),\n appearance_years: toIntList(raw.appearance_years),\n conference_titles: toInt(raw.conference_titles),\n conference_title_years: toIntList(raw.conference_title_years),\n total_conference_titles: toInt(raw.total_conference_titles),\n conference_history: toTextList(raw.conference_history),\n division_titles: toInt(raw.division_titles),\n fan_nicknames: toTextList(raw.fan_nicknames),\n traditions: toTextList(raw.traditions),\n primary_rival_team_id: toInt(raw.primary_rival_team_id),\n owner: toTrimmedText(raw.owner),\n stadium_capacity: toInt(raw.stadium_capacity),\n year_established: toInt(raw.year_established),\n first_season: toInt(raw.first_season),\n summary: toTrimmedText(raw.summary),\n };\n}\n\n// ---- Venue photo: stored at `teams.specific_data.facility_images.<kind>` ----\n\nconst FACILITY_NAME_KEYS: Record<TeamVenueKind, string> = {\n stadium: \"stadium_name\",\n arena: \"arena_name\",\n};\n\nexport interface TeamFacilityImage {\n path: string;\n title: string | null;\n sourceUrl: string | null;\n artist: string | null;\n license: string | null;\n licenseUrl: string | null;\n width: number | null;\n height: number | null;\n updatedAt: string | null;\n}\n\nfunction httpsUrl(value: unknown): string | null {\n const raw = toTrimmedText(value);\n if (!raw) return null;\n try {\n return new URL(raw).protocol === \"https:\" ? raw : null;\n } catch {\n return null;\n }\n}\n\nfunction num(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\n\n/** Reads one stored facility image; null when missing or not in the facilities bucket. */\nfunction parseTeamFacilityImage(\n specificData: unknown,\n kind: TeamVenueKind,\n): TeamFacilityImage | null {\n if (!isJsonRecord(specificData)) return null;\n const images = specificData.facility_images;\n if (!isJsonRecord(images)) return null;\n const entry = images[kind];\n if (!isJsonRecord(entry)) return null;\n const path = toTrimmedText(entry.path);\n if (!path || !path.startsWith(\"facilities/\")) return null;\n return {\n path,\n title: toTrimmedText(entry.title),\n sourceUrl: httpsUrl(entry.source_url),\n artist: toTrimmedText(entry.artist),\n license: toTrimmedText(entry.license),\n licenseUrl: httpsUrl(entry.license_url),\n width: num(entry.width),\n height: num(entry.height),\n updatedAt: toTrimmedText(entry.updated_at),\n };\n}\n\nexport interface TeamVenue {\n name: string | null;\n image: TeamFacilityImage | null;\n}\n\n/** The venue's name and stored photo. `kind` is always \"stadium\"/\"arena\" -- Team Facts' own venue config narrows it. */\nexport function parseTeamVenue(specificData: unknown, kind: TeamVenueKind): TeamVenue {\n const record = isJsonRecord(specificData) ? specificData : {};\n return {\n name: toTrimmedText(record[FACILITY_NAME_KEYS[kind]]),\n image: parseTeamFacilityImage(specificData, kind),\n };\n}\n\n/** \"SounderBruce · CC BY-SA 4.0\" style credit, or null when nothing is known. */\nexport function facilityImageCredit(image: TeamFacilityImage): string | null {\n const parts = [image.artist, image.license].filter((p): p is string => Boolean(p));\n return parts.length ? parts.join(\" · \") : null;\n}\n\n// ---- Display formatting ----\n\n/** Shown wherever a fact hasn't been filled in. */\nexport const EMPTY_FACT_VALUE = \"—\";\n\n/** Capacities get thousands separators; years and counts never do (\"1976\", not \"1,976\"). */\nexport function formatTeamFactNumber(kind: TeamFactKind, value: number | null): string {\n if (value === null) return EMPTY_FACT_VALUE;\n if (kind === \"number\") return value.toLocaleString(\"en-US\");\n return String(value);\n}\n\nconst ROMAN_NUMERALS: [number, string][] = [\n [1000, \"M\"],\n [900, \"CM\"],\n [500, \"D\"],\n [400, \"CD\"],\n [100, \"C\"],\n [90, \"XC\"],\n [50, \"L\"],\n [40, \"XL\"],\n [10, \"X\"],\n [9, \"IX\"],\n [5, \"V\"],\n [4, \"IV\"],\n [1, \"I\"],\n];\n\n/** Standard Roman numerals stop at 3999; beyond that (or non-integer) this returns the plain number. */\nconst MAX_ROMAN_NUMERAL = 3999;\n\nexport function toRomanNumeral(value: number): string {\n if (!Number.isInteger(value) || value < 1 || value > MAX_ROMAN_NUMERAL) return String(value);\n let rest = value;\n let out = \"\";\n for (const [n, numeral] of ROMAN_NUMERALS) {\n while (rest >= n) {\n out += numeral;\n rest -= n;\n }\n }\n return out;\n}\n\n/** Super Bowl I followed the 1966 season, so a season year maps to Super Bowl (year - 1965). */\nconst FIRST_SUPER_BOWL_SEASON = 1966;\n\n/** \"XVII · 1982\" for a Super Bowl season year; the bare year for anything before Super Bowl I. */\nexport function formatSuperBowlYear(year: number): string {\n const number = year - FIRST_SUPER_BOWL_SEASON + 1;\n if (year < FIRST_SUPER_BOWL_SEASON || number > MAX_ROMAN_NUMERAL) return String(year);\n return `${toRomanNumeral(number)} · ${year}`;\n}\n\n/** Year pills use the league's formatter (NFL \"XVII · 1982\"); labelled years (\"2005 (FCS)\") stay as typed. */\nexport function formatYearPills(\n years: (string | number)[],\n formatYear: ((year: number) => string) | undefined,\n): (string | number)[] {\n if (!formatYear) return years;\n return years.map((year) => (typeof year === \"number\" ? formatYear(year) : year));\n}\n\n// ---- Per-league config: which facts a league shows, their labels, and section layout ----\n\n/** How a fact is entered and stored. */\nexport type TeamFactKind =\n \"count\" | \"years\" | \"labeled_years\" | \"list\" | \"rival\" | \"text\" | \"number\" | \"year\" | \"longtext\";\n\nexport const TEAM_FACT_KINDS: Record<TeamFactKey, TeamFactKind> = {\n championships_won: \"count\",\n championship_years: \"years\",\n other_national_titles: \"count\",\n other_title_years: \"labeled_years\",\n championship_appearances: \"count\",\n appearance_years: \"years\",\n conference_titles: \"count\",\n conference_title_years: \"years\",\n total_conference_titles: \"count\",\n conference_history: \"list\",\n division_titles: \"count\",\n fan_nicknames: \"list\",\n traditions: \"list\",\n primary_rival_team_id: \"rival\",\n owner: \"text\",\n stadium_capacity: \"number\",\n year_established: \"year\",\n first_season: \"year\",\n summary: \"longtext\",\n};\n\n/** Year lists shown under their matching count (e.g. win years under \"Super Bowls Won\"). */\nexport const TEAM_FACT_YEAR_PAIRS: Partial<Record<TeamFactKey, TeamFactKey>> = {\n championships_won: \"championship_years\",\n other_national_titles: \"other_title_years\",\n championship_appearances: \"appearance_years\",\n conference_titles: \"conference_title_years\",\n};\n\n/** How the widget lays out a section's fields: Trophy Case two-up, the profile in one row, the rest stacked. */\nexport type TeamFactsSectionLayout = \"grid\" | \"row\" | \"column\";\n\nexport interface TeamFactsSectionConfig {\n title: string;\n fields: TeamFactKey[];\n layout: TeamFactsSectionLayout;\n /** The venue (stadium/arena) name, photo and photo credit sit at the bottom of this section. */\n showsVenuePhoto?: boolean;\n}\n\ntype TeamFactsVenueConfig = ReturnType<typeof getTeamVenueConfig>;\ntype TeamFactsFacilityConfig = ReturnType<typeof getTeamFacilityConfig>;\n\nexport interface TeamFactsLeagueConfig {\n labels: Record<TeamFactKey, string>;\n venue: TeamFactsVenueConfig;\n facility: TeamFactsFacilityConfig;\n sections: TeamFactsSectionConfig[];\n /** Formats championship/appearance year pills (e.g. NFL \"XVII · 1982\"); plain year when absent. */\n formatChampionshipYear?: (year: number) => string;\n /** Another league whose teams can also be picked as the rival (e.g. FBS schools with FCS rivals). */\n rivalPartnerLeague?: string;\n}\n\nconst PAIRED_YEAR_KEYS = new Set<TeamFactKey>(Object.values(TEAM_FACT_YEAR_PAIRS));\n\n/** The fields the widget renders for a section: year lists are shown under their count, not on their own. */\nexport function teamFactsDisplayFields(section: TeamFactsSectionConfig): TeamFactKey[] {\n return section.fields.filter((key) => !PAIRED_YEAR_KEYS.has(key));\n}\n\nconst DEFAULT_LABELS: Record<TeamFactKey, string> = {\n championships_won: \"Championships Won\",\n championship_years: \"Championship Years\",\n other_national_titles: \"Other National Titles\",\n other_title_years: \"Other National Title Years\",\n championship_appearances: \"Championship Appearances\",\n appearance_years: \"Championship Appearance Years\",\n conference_titles: \"Conference Titles\",\n conference_title_years: \"Conference Title Years\",\n total_conference_titles: \"Total Conference Titles\",\n conference_history: \"Conference History\",\n division_titles: \"Division Titles\",\n fan_nicknames: \"Fan Nicknames\",\n traditions: \"Traditions\",\n primary_rival_team_id: \"Primary Rival\",\n owner: \"Team Owner\",\n stadium_capacity: \"Stadium Capacity\",\n year_established: \"Year Established\",\n first_season: \"First Season\",\n summary: \"Team Summary\",\n};\n\n/** Pro-league sections. The college-only facts (other titles, conference history, traditions, first season) aren't in them. */\nconst DEFAULT_SECTIONS: TeamFactsSectionConfig[] = [\n {\n title: \"Trophy Case\",\n layout: \"grid\",\n fields: [\n \"championships_won\",\n \"championship_years\",\n \"championship_appearances\",\n \"appearance_years\",\n \"conference_titles\",\n \"division_titles\",\n ],\n },\n {\n title: \"Tradition\",\n layout: \"column\",\n fields: [\"fan_nicknames\", \"primary_rival_team_id\", \"summary\"],\n },\n {\n title: \"Franchise Profile\",\n layout: \"row\",\n showsVenuePhoto: true,\n fields: [\"owner\", \"year_established\", \"stadium_capacity\"],\n },\n];\n\n/**\n * Facts a league doesn't show or edit, keyed by `leagues.abbreviation` -- e.g. conference titles\n * repeat the NFL's Super Bowl appearances, and the WNBA has no divisions. Any saved value stays\n * in the database untouched; it just isn't shown.\n */\nconst LEAGUE_HIDDEN_FIELDS: Record<string, TeamFactKey[]> = {\n NFL: [\"conference_titles\"],\n MLB: [\"conference_titles\"],\n NHL: [\"conference_titles\"],\n WNBA: [\"division_titles\"],\n};\n\n/** College football: national titles at every level, CFP, conference history and a school profile. */\nconst COLLEGE_FOOTBALL_SECTIONS: TeamFactsSectionConfig[] = [\n {\n title: \"Trophy Case\",\n layout: \"grid\",\n fields: [\n \"championships_won\",\n \"championship_years\",\n \"other_national_titles\",\n \"other_title_years\",\n \"championship_appearances\",\n \"appearance_years\",\n \"conference_titles\",\n \"total_conference_titles\",\n \"conference_history\",\n ],\n },\n {\n title: \"Tradition\",\n layout: \"column\",\n fields: [\"fan_nicknames\", \"traditions\", \"primary_rival_team_id\", \"summary\"],\n },\n {\n title: \"School Profile\",\n layout: \"row\",\n showsVenuePhoto: true,\n fields: [\"year_established\", \"first_season\", \"stadium_capacity\"],\n },\n];\n\n/**\n * FCS: national titles (any level other than FCS sits in Other National Titles, e.g. \"1980 (D-II)\"),\n * conference titles with their years, and the program's first season.\n */\nconst FCS_SECTIONS: TeamFactsSectionConfig[] = [\n {\n title: \"Trophy Case\",\n layout: \"grid\",\n fields: [\n \"championships_won\",\n \"championship_years\",\n \"other_national_titles\",\n \"other_title_years\",\n \"conference_titles\",\n \"conference_title_years\",\n ],\n },\n {\n title: \"Tradition\",\n layout: \"column\",\n fields: [\"fan_nicknames\", \"primary_rival_team_id\", \"summary\"],\n },\n {\n title: \"School Profile\",\n layout: \"row\",\n showsVenuePhoto: true,\n fields: [\"first_season\", \"stadium_capacity\"],\n },\n];\n\n/** College basketball: national titles, Final Fours, conference history and a school profile. */\nconst COLLEGE_BASKETBALL_SECTIONS: TeamFactsSectionConfig[] = [\n {\n title: \"Trophy Case\",\n layout: \"grid\",\n fields: [\n \"championships_won\",\n \"championship_years\",\n \"championship_appearances\",\n \"appearance_years\",\n \"conference_titles\",\n \"total_conference_titles\",\n \"conference_history\",\n ],\n },\n {\n title: \"Tradition\",\n layout: \"column\",\n fields: [\"fan_nicknames\", \"traditions\", \"primary_rival_team_id\", \"summary\"],\n },\n {\n title: \"School Profile\",\n layout: \"row\",\n showsVenuePhoto: true,\n fields: [\"year_established\", \"first_season\", \"stadium_capacity\"],\n },\n];\n\n/** Leagues with their own section layout instead of the pro-league default. */\nconst LEAGUE_SECTIONS: Record<string, TeamFactsSectionConfig[]> = {\n \"NCAAF (FBS)\": COLLEGE_FOOTBALL_SECTIONS,\n \"NCAAF (FCS)\": FCS_SECTIONS,\n NCAAM: COLLEGE_BASKETBALL_SECTIONS,\n};\n\n/** FBS rivals can be FCS schools (e.g. Villanova, Holy Cross) and vice versa. */\nconst LEAGUE_RIVAL_PARTNERS: Record<string, string> = {\n \"NCAAF (FBS)\": \"NCAAF (FCS)\",\n \"NCAAF (FCS)\": \"NCAAF (FBS)\",\n};\n\nfunction sectionsWithout(hidden: TeamFactKey[] | undefined): TeamFactsSectionConfig[] {\n if (!hidden || hidden.length === 0) return DEFAULT_SECTIONS;\n const hiddenFields = new Set(hidden);\n return DEFAULT_SECTIONS.map((section) => ({\n ...section,\n fields: section.fields.filter((field) => !hiddenFields.has(field)),\n }));\n}\n\nconst LEAGUE_YEAR_FORMATTERS: Record<string, (year: number) => string> = {\n NFL: formatSuperBowlYear,\n};\n\n/** Per-league label overrides, keyed by `leagues.abbreviation`. */\nconst LEAGUE_LABEL_OVERRIDES: Record<string, Partial<Record<TeamFactKey, string>>> = {\n NFL: {\n championships_won: \"Super Bowls Won\",\n championship_years: \"Super Bowl Win Years\",\n championship_appearances: \"Super Bowl Appearances\",\n appearance_years: \"Super Bowl Appearance Years\",\n conference_titles: \"Conference Championships\",\n division_titles: \"Division Championships\",\n fan_nicknames: \"Fan Nickname(s)\",\n summary: \"Short Team Summary\",\n },\n NBA: {\n championships_won: \"NBA Championships\",\n championship_years: \"NBA Championship Years\",\n championship_appearances: \"NBA Finals Appearances\",\n appearance_years: \"NBA Finals Appearance Years\",\n fan_nicknames: \"Fan Nickname(s)\",\n stadium_capacity: \"Arena Capacity\",\n summary: \"Short Team Summary\",\n },\n NHL: {\n championships_won: \"Stanley Cup Wins\",\n championship_years: \"Stanley Cup Winning Years\",\n championship_appearances: \"Stanley Cup Finals Appearances\",\n appearance_years: \"Stanley Cup Finals Years\",\n conference_titles: \"Conference Championships\",\n fan_nicknames: \"Fan Nickname(s)\",\n stadium_capacity: \"Arena Capacity\",\n summary: \"Short Team Summary\",\n },\n MLB: {\n championships_won: \"World Series Wins\",\n championship_years: \"World Series Winning Years\",\n championship_appearances: \"Pennants Won\",\n appearance_years: \"Pennant Years\",\n conference_titles: \"League Championships\",\n fan_nicknames: \"Fan Nickname(s)\",\n summary: \"Short Team Summary\",\n },\n WNBA: {\n championships_won: \"WNBA Championships\",\n championship_years: \"WNBA Championship Years\",\n championship_appearances: \"WNBA Finals Appearances\",\n appearance_years: \"WNBA Finals Appearance Years\",\n fan_nicknames: \"Fan Nickname(s)\",\n stadium_capacity: \"Arena Capacity\",\n summary: \"Short Team Summary\",\n },\n \"NCAAF (FBS)\": {\n championships_won: \"FBS Championships\",\n championship_years: \"FBS Championship Years\",\n other_national_titles: \"Other National Titles\",\n other_title_years: \"Other National Title Years\",\n championship_appearances: \"CFP Appearances\",\n appearance_years: \"CFP Appearance Years\",\n conference_titles: \"Current Conference Titles\",\n total_conference_titles: \"Total Conference Titles\",\n conference_history: \"Conference History\",\n fan_nicknames: \"Fan Nickname(s)\",\n traditions: \"Traditions\",\n year_established: \"University Founded\",\n first_season: \"First Season\",\n summary: \"Short Team Summary\",\n },\n \"NCAAF (FCS)\": {\n championships_won: \"National Championships\",\n championship_years: \"National Championship Years\",\n other_national_titles: \"Other National Titles\",\n other_title_years: \"Other National Title Years\",\n conference_titles: \"Conference Championships\",\n conference_title_years: \"Conference Championship Years\",\n fan_nicknames: \"Fan Nickname(s)\",\n first_season: \"First Season\",\n summary: \"Short Team Summary\",\n },\n NCAAM: {\n championships_won: \"National Championships\",\n championship_years: \"National Championship Years\",\n championship_appearances: \"Final Four Appearances\",\n appearance_years: \"Final Four Years\",\n conference_titles: \"Current Conference Titles\",\n total_conference_titles: \"Total Conference Titles\",\n conference_history: \"Conference History\",\n fan_nicknames: \"Fan Nickname(s)\",\n traditions: \"Traditions\",\n stadium_capacity: \"Arena Capacity\",\n year_established: \"University Founded\",\n first_season: \"First Season\",\n summary: \"Short Program History\",\n },\n};\n\n/** League abbreviations that have their own labels configured. */\nexport const CONFIGURED_TEAM_FACTS_LEAGUES = Object.keys(LEAGUE_LABEL_OVERRIDES);\n\nfunction buildTeamFactsConfig(\n leagueAbbreviation: string | null | undefined,\n): TeamFactsLeagueConfig {\n const overrides = leagueAbbreviation ? LEAGUE_LABEL_OVERRIDES[leagueAbbreviation] : undefined;\n const venue = getTeamVenueConfig(leagueAbbreviation);\n const facility = getTeamFacilityConfig(leagueAbbreviation);\n const rivalPartnerLeague = leagueAbbreviation\n ? LEAGUE_RIVAL_PARTNERS[leagueAbbreviation]\n : undefined;\n // `getTeamVenueConfig`/`getTeamFacilityConfig` return a fresh object each call (unlike the\n // original apps' cached singletons), so \"is this the default venue/facility\" is compared by\n // value here, not by reference -- same effect, just adapted to the shared core functions.\n const isDefaultVenue = venue.kind === DEFAULT_TEAM_FACTS_CONFIG.venue.kind;\n const isDefaultFacility = facility.kind === DEFAULT_TEAM_FACTS_CONFIG.facility.kind;\n if (!overrides && isDefaultVenue && isDefaultFacility && !rivalPartnerLeague) {\n return DEFAULT_TEAM_FACTS_CONFIG;\n }\n return {\n labels: { ...DEFAULT_LABELS, ...overrides },\n venue,\n facility,\n sections:\n (leagueAbbreviation ? LEAGUE_SECTIONS[leagueAbbreviation] : undefined) ??\n sectionsWithout(leagueAbbreviation ? LEAGUE_HIDDEN_FIELDS[leagueAbbreviation] : undefined),\n formatChampionshipYear: leagueAbbreviation\n ? LEAGUE_YEAR_FORMATTERS[leagueAbbreviation]\n : undefined,\n rivalPartnerLeague,\n };\n}\n\nconst DEFAULT_TEAM_FACTS_CONFIG: TeamFactsLeagueConfig = {\n labels: DEFAULT_LABELS,\n venue: getTeamVenueConfig(null),\n facility: getTeamFacilityConfig(null),\n sections: DEFAULT_SECTIONS,\n};\n\n/** Built once per league, so callers always get the same object (safe as a memo/effect dependency). */\nconst CONFIG_CACHE = new Map<string, TeamFactsLeagueConfig>();\n\nexport function getTeamFactsConfig(\n leagueAbbreviation: string | null | undefined,\n): TeamFactsLeagueConfig {\n const cacheKey = leagueAbbreviation ?? \"\";\n const cached = CONFIG_CACHE.get(cacheKey);\n if (cached) return cached;\n const config = buildTeamFactsConfig(leagueAbbreviation);\n CONFIG_CACHE.set(cacheKey, config);\n return config;\n}\n\n// ---- Widget derivation: combines the above into what TeamFactsWidget renders ----\n\nexport interface TeamFactsRival {\n id: number;\n name: string;\n /** Raw, possibly-relative stored value -- the caller resolves it (e.g. via `EntityAvatar`). */\n teamLogoUrl: string | null;\n}\n\nexport type TeamFactsRivalState =\n | { status: \"none\" }\n | { status: \"loading\" }\n | { status: \"error\" }\n | { status: \"ready\"; rival: TeamFactsRival };\n\nexport interface TeamFactsWidgetData {\n teamId: number;\n hasFacts: boolean;\n facts: TeamFacts;\n config: TeamFactsLeagueConfig;\n /** The league's venue (stadium or arena) name and photo. */\n venue: TeamVenue;\n rival: TeamFactsRivalState;\n}\n\nexport type TeamFactsWidgetState =\n | { status: \"loading\" }\n | { status: \"error\"; retry?: () => void; devMessage?: string }\n | { status: \"ready\"; data: TeamFactsWidgetData };\n\n/** The minimal team-row fields `toTeamFactsView` reads -- not the full `Team`/`TeamWithDetails` row. */\nexport interface TeamFactsTeamRow {\n id: number;\n specific_data: unknown;\n league?: { abbreviation: string | null } | null;\n}\n\n/** The minimal rival-row fields `toRivalState` reads. */\nexport interface TeamFactsRivalTeamRow {\n team: string | null;\n nickname: string | null;\n team_logo_url: string | null;\n}\n\ntype TeamFactsView = Omit<TeamFactsWidgetData, \"rival\">;\n\n/** Everything the widget shows that comes from the team's own row. */\nexport function toTeamFactsView(team: TeamFactsTeamRow): TeamFactsView {\n const data = isJsonRecord(team.specific_data) ? team.specific_data : {};\n const rawFacts = data.facts;\n const config = getTeamFactsConfig(team.league?.abbreviation);\n return {\n teamId: team.id,\n hasFacts: hasTeamFacts(rawFacts),\n facts: parseTeamFacts(rawFacts),\n config,\n venue: parseTeamVenue(team.specific_data, config.venue.kind),\n };\n}\n\n/** A missing rival row (resolved as null) is as unshowable as a failed lookup. */\nexport function toRivalState(\n rivalId: number | null,\n rivalTeam: TeamFactsRivalTeamRow | null | undefined,\n isError: boolean,\n): TeamFactsRivalState {\n if (!rivalId) return { status: \"none\" };\n if (rivalTeam) {\n return {\n status: \"ready\",\n rival: {\n id: rivalId,\n name: formatTeamName(rivalTeam.team, rivalTeam.nickname),\n teamLogoUrl: rivalTeam.team_logo_url,\n },\n };\n }\n return isError || rivalTeam === null ? { status: \"error\" } : { status: \"loading\" };\n}\n","import { formatTeamName } from \"./teamPlaceSummary\";\n\n// The subset of a `season_games` row (and its ESPN `game_details` payload) the Recent Games card\n// reads -- deliberately not a full ESPN schema.\n\nexport interface RecentGameCompetitor {\n id: string;\n homeAway?: string;\n team?: {\n displayName?: string;\n shortDisplayName?: string;\n name?: string;\n logo?: string;\n };\n score?: {\n value?: number;\n displayValue?: string;\n };\n winner?: boolean;\n}\n\nexport interface RecentGameRecord {\n id: number;\n game_date: string;\n home_team_id: number | null;\n away_team_id: number | null;\n /** Nullable in the DB: not every game has an ESPN payload yet. */\n game_details: {\n competitions?: {\n status?: { type?: { id?: string; altDetail?: string } };\n /** ESPN payloads can carry holes, so entries may be null. */\n competitors?: (RecentGameCompetitor | null)[];\n }[];\n /** Kickoff time text for a not-yet-started game. */\n time?: string;\n } | null;\n}\n\n/** The team-row fields opponent resolution reads. */\nexport interface RecentGameTeamRow {\n id: number;\n team: string | null;\n nickname?: string | null;\n team_logo_url: string | null;\n espn_id?: number | null;\n}\n\n/** ESPN's status id for a finished game. */\nconst COMPLETED_STATUS_ID = \"3\";\n\n/** Local midnight, as a timestamp: the boundary between \"past\" and \"today onward\". */\nexport function startOfLocalDay(now: Date = new Date()): number {\n const day = new Date(now);\n day.setHours(0, 0, 0, 0);\n return day.getTime();\n}\n\nfunction firstCompetition(game: RecentGameRecord) {\n return game.game_details?.competitions?.[0];\n}\n\nexport function isGameCompleted(game: RecentGameRecord): boolean {\n return firstCompetition(game)?.status?.type?.id === COMPLETED_STATUS_ID;\n}\n\nexport function isGameBeforeDay(game: RecentGameRecord, dayStart: number): boolean {\n return new Date(game.game_date).getTime() < dayStart;\n}\n\n/**\n * `getRecentGames`' \"upcoming\" bucket is a calendar-day split (today onward), not a completion\n * split: a game already finished earlier today still lands in it. So a truly upcoming fixture is\n * one that is neither completed nor before today.\n */\nexport function isTrueUpcomingGame(game: RecentGameRecord, todayStart: number): boolean {\n return !isGameCompleted(game) && !isGameBeforeDay(game, todayStart);\n}\n\nexport type RecentGameOutcome = \"win\" | \"loss\" | \"tie\" | \"none\";\n\nexport interface RecentGameResult {\n outcome: RecentGameOutcome;\n /** \"24-17\", or \"24-17 OT\" when the status carries extra detail; empty for \"none\". */\n detail: string;\n}\n\nconst NO_RESULT: RecentGameResult = { outcome: \"none\", detail: \"\" };\n\n/** A finished game's result from the viewed team's side, or \"none\" when it can't be determined. */\nexport function getRecentGameResult(\n game: RecentGameRecord,\n teamEspnId: number | null | undefined,\n): RecentGameResult {\n const competition = firstCompetition(game);\n const competitors = competition?.competitors;\n if (\n competition?.status?.type?.id !== COMPLETED_STATUS_ID ||\n !competitors ||\n competitors.length !== 2 ||\n !teamEspnId\n ) {\n return NO_RESULT;\n }\n\n const [first, second] = competitors;\n if (!first || !second) return NO_RESULT;\n\n const extra = competition.status?.type?.altDetail;\n const withExtra = (score: string) => (extra ? `${score} ${extra}` : score);\n const scoreFor = (own: RecentGameCompetitor, other: RecentGameCompetitor) =>\n `${own.score?.displayValue || \"0\"}-${other.score?.displayValue || \"0\"}`;\n\n // The viewed team must be one of the two competitors before anything else: a tie between two\n // other teams is not a result for this one.\n const teamId = String(teamEspnId);\n const own = first.id === teamId ? first : second.id === teamId ? second : null;\n if (!own) return NO_RESULT;\n const other = own === first ? second : first;\n\n if (first.score?.value === second.score?.value) {\n return { outcome: \"tie\", detail: withExtra(scoreFor(own, other)) };\n }\n return {\n outcome: own.winner === true ? \"win\" : \"loss\",\n detail: withExtra(scoreFor(own, other)),\n };\n}\n\n/** The distinct, sorted team ids a set of games names (sorted: RTK Query keys on array args). */\nexport function collectRecentGameTeamIds(games: RecentGameRecord[]): number[] {\n const ids = new Set<number>();\n for (const game of games) {\n if (game.home_team_id) ids.add(game.home_team_id);\n if (game.away_team_id) ids.add(game.away_team_id);\n }\n return [...ids].sort((a, b) => a - b);\n}\n\n/**\n * ESPN competitor ids for games missing a home/away team id. The opponent of a cross-league\n * matchup lives in a different league than the game row, so it's looked up by ESPN id instead.\n */\nexport function collectRecentGameEspnIds(games: RecentGameRecord[]): number[] {\n const ids = new Set<number>();\n for (const game of games) {\n if (game.home_team_id && game.away_team_id) continue;\n const competitors = firstCompetition(game)?.competitors;\n if (!Array.isArray(competitors)) continue;\n for (const competitor of competitors) {\n const parsed = Number(competitor?.id);\n if (Number.isFinite(parsed)) ids.add(parsed);\n }\n }\n return [...ids].sort((a, b) => a - b);\n}\n\nexport interface RecentGameLogo {\n url: string;\n /** True for a stored (possibly relative) team logo the caller must resolve; false for an absolute ESPN URL. */\n stored: boolean;\n}\n\nexport interface RecentGameOpponent {\n name: string;\n logo: RecentGameLogo | null;\n}\n\nconst TBD_OPPONENT: RecentGameOpponent = { name: \"TBD\", logo: null };\n\nfunction teamName(row: Pick<RecentGameTeamRow, \"team\" | \"nickname\">): string {\n return formatTeamName(row.team, row.nickname) || \"Unknown\";\n}\n\nfunction logoOf(row: RecentGameTeamRow, fallbackUrl?: string): RecentGameLogo | null {\n if (row.team_logo_url) return { url: row.team_logo_url, stored: true };\n return fallbackUrl ? { url: fallbackUrl, stored: false } : null;\n}\n\n/**\n * Whether a competitor is the opponent: not the viewed team when its ESPN id is known, else the\n * side opposite the one the viewed team plays. ESPN payloads can carry holes, so a missing entry\n * is skipped rather than read.\n */\nfunction isOpponentCompetitor(\n competitor: RecentGameCompetitor | null | undefined,\n teamEspnId: number | null | undefined,\n isHome: boolean,\n): boolean {\n if (!competitor) return false;\n if (teamEspnId) return competitor.id !== String(teamEspnId);\n return competitor.homeAway === (isHome ? \"away\" : \"home\");\n}\n\nexport interface ResolveOpponentArgs {\n game: RecentGameRecord;\n /** The opponent's team id on the game row, when it has one. */\n opponentTeamId: number | null;\n isHome: boolean;\n teamEspnId: number | null | undefined;\n teamsById: ReadonlyMap<number, RecentGameTeamRow>;\n teamsByEspnId: ReadonlyMap<string, RecentGameTeamRow>;\n}\n\n/**\n * The opponent's name and logo: the team row when the game names one, else the ESPN competitor\n * that isn't the viewed team (preferring the stored team found by ESPN id, so its stored logo is\n * used -- ESPN payloads often omit `team.logo`), else \"TBD\".\n */\nexport function resolveRecentGameOpponent({\n game,\n opponentTeamId,\n isHome,\n teamEspnId,\n teamsById,\n teamsByEspnId,\n}: ResolveOpponentArgs): RecentGameOpponent {\n const known = opponentTeamId ? teamsById.get(opponentTeamId) : undefined;\n if (known) return { name: teamName(known), logo: logoOf(known) };\n\n const competitors = firstCompetition(game)?.competitors;\n if (!competitors) return TBD_OPPONENT;\n\n const opponent = competitors.find((c) => isOpponentCompetitor(c, teamEspnId, isHome));\n if (!opponent) return TBD_OPPONENT;\n\n const stored = opponent.id ? teamsByEspnId.get(String(opponent.id)) : undefined;\n if (stored) return { name: teamName(stored), logo: logoOf(stored, opponent.team?.logo) };\n\n const payload = opponent.team;\n if (!payload) return TBD_OPPONENT;\n return {\n name: payload.displayName || payload.shortDisplayName || payload.name || \"Unknown\",\n logo: payload.logo ? { url: payload.logo, stored: false } : null,\n };\n}\n\nexport interface RecentGameRow {\n id: number;\n gameDate: string;\n isHome: boolean;\n opponent: RecentGameOpponent;\n /** Only for a game that is finished or already past; null for a fixture still to come. */\n result: RecentGameResult | null;\n /** Kickoff time text, only for a fixture still to come. */\n time: string | null;\n /** The first not-yet-played fixture: where the \"Upcoming\" header goes. */\n isFirstUpcoming: boolean;\n}\n\nexport interface BuildRecentGameRowsArgs {\n games: RecentGameRecord[];\n teamId: number | null;\n teamEspnId: number | null | undefined;\n /** Rows for the ids from `collectRecentGameTeamIds`. */\n teams: RecentGameTeamRow[];\n /** Rows for the ids from `collectRecentGameEspnIds`, matched by `espn_id`. */\n espnTeams: RecentGameTeamRow[];\n /** From `startOfLocalDay`; recompute each render so the split follows midnight. */\n todayStart: number;\n}\n\n/** One render-ready row per game, in the order given. */\nexport function buildRecentGameRows({\n games,\n teamId,\n teamEspnId,\n teams,\n espnTeams,\n todayStart,\n}: BuildRecentGameRowsArgs): RecentGameRow[] {\n const teamsById = new Map(teams.map((team) => [team.id, team] as const));\n const teamsByEspnId = new Map<string, RecentGameTeamRow>();\n for (const team of espnTeams) {\n if (team.espn_id !== null && team.espn_id !== undefined) {\n teamsByEspnId.set(String(team.espn_id), team);\n }\n }\n\n return games.map((game, index) => {\n const isHome = teamId !== null && game.home_team_id === teamId;\n const completed = isGameCompleted(game);\n const past = isGameBeforeDay(game, todayStart);\n const previous = games[index - 1];\n return {\n id: game.id,\n gameDate: game.game_date,\n isHome,\n opponent: resolveRecentGameOpponent({\n game,\n opponentTeamId: isHome ? game.away_team_id : game.home_team_id,\n isHome,\n teamEspnId,\n teamsById,\n teamsByEspnId,\n }),\n result: completed || past ? getRecentGameResult(game, teamEspnId) : null,\n time: !completed && !past ? (game.game_details?.time ?? null) : null,\n isFirstUpcoming:\n isTrueUpcomingGame(game, todayStart) &&\n (!previous || !isTrueUpcomingGame(previous, todayStart)),\n };\n });\n}\n"],"mappings":";AAAA,SAAS,QAAQ,gBAAgB;AAW1B,SAAS,cAAc,MAAgB,aAAkC;AAC9E,MAAI,YAAa,QAAO;AACxB,QAAM,QAAQ,KAAK,YAAY;AAC/B,MAAI,SAAS,SAAS,KAAK,IAAI,oBAAI,KAAK,EAAG,QAAO;AAClD,SAAO;AACT;AAGO,SAAS,eAAe,SAAiC;AAC9D,MAAI,CAAC,QAAS,QAAO;AACrB,MAAI;AACF,WAAO,OAAO,SAAS,OAAO,GAAG,aAAa;AAAA,EAChD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;;;ACzBO,SAAS,OAAO,GAAmB;AACxC,SAAO,IAAI,KAAK,aAAa,SAAS;AAAA,IACpC,OAAO;AAAA,IACP,UAAU;AAAA,IACV,uBAAuB;AAAA,IACvB,uBAAuB;AAAA,EACzB,CAAC,EAAE,OAAO,CAAC;AACb;AAIO,SAAS,YAAY,GAAoB;AAC9C,SAAO,KAAK,OACR,IAAI,KAAK,aAAa,SAAS;AAAA,IAC7B,OAAO;AAAA,IACP,UAAU;AAAA,IACV,uBAAuB;AAAA,EACzB,CAAC,EAAE,OAAO,CAAC,IACX;AACN;AAGO,SAAS,cAAc,GAAmB;AAC/C,QAAM,QAAQ,KAAK,MAAM,IAAI,GAAG;AAChC,SAAO,IAAI,KAAK,aAAa,SAAS;AAAA,IACpC,OAAO;AAAA,IACP,UAAU;AAAA,IACV,uBAAuB,QAAQ,QAAQ,IAAI,IAAI;AAAA,IAC/C,uBAAuB;AAAA,EACzB,CAAC,EAAE,OAAO,QAAQ,GAAG;AACvB;AAGO,SAAS,IAAI,OAA2C,WAAW,MAAc;AACtF,MAAI,UAAU,QAAQ,UAAU,UAAa,UAAU,GAAI,QAAO;AAClE,SAAO,OAAO,KAAK;AACrB;AAIO,SAAS,YAAY,QAA2C;AACrE,MA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