/** * The church profile from the church's Accounts (3.7.0, docs/WEBSITE-1.0-PLAN.md ยง9): the brand * style (fonts and corners) and what the shared footer shows (service times, address, contact, * social, the church's other sites). Accounts owns it and serves it publicly at * `GET /api/church/v1`; this keeps a copy in memory for the public pages (`GET /api/v2/church`). * * Fetched again after 10 minutes, or at once when Accounts sends `church.changed` * (`POST /api/church/v1/changed`, src/links/routes.ts). While Accounts can't be reached the last * copy is kept and it's tried again after a minute; a site without Accounts has none, and its * pages look as they always have. */ import { CHURCH_PATHS, churchSchema, type Church } from '@crosscode/contracts'; import { accountsLink } from './client'; const FRESH_MS = 10 * 60e3; const RETRY_MS = 60e3; const TIMEOUT_MS = 5000; type Cached = { url: string; church: Church | null; at: number; ok: boolean }; let cached: Cached | null = null; let pending: Promise | null = null; async function fetchProfile(accountsUrl: string): Promise { const res = await fetch(`${accountsUrl.replace(/\/+$/, '')}${CHURCH_PATHS.profile}`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(TIMEOUT_MS) }); if (!res.ok) throw new Error(`Accounts answered ${res.status}`); const parsed = churchSchema.safeParse(await res.json()); if (!parsed.success) throw new Error(`the profile isn't crosscode.church/1 (${parsed.error.issues[0]?.message ?? 'invalid'})`); return parsed.data; } /** The church's profile, or null when Accounts isn't connected or hasn't answered yet. Never throws. */ export async function churchProfile(): Promise { let link; try { link = await accountsLink(); } catch { return cached?.church ?? null; } if (!link) return null; const url = link.url; if (cached && cached.url === url && Date.now() - cached.at < (cached.ok ? FRESH_MS : RETRY_MS)) return cached.church; if (!pending) { const last = cached?.url === url ? cached.church : null; pending = fetchProfile(url) .then((church) => { cached = { url, church, at: Date.now(), ok: true }; return church; }, (e: Error) => { console.warn('[church] profile not fetched from Accounts:', e.message); cached = { url, church: last, at: Date.now(), ok: false }; return last; }) .finally(() => { pending = null; }); } return pending; } /** `church.changed`: the next `churchProfile()` fetches it again (the last copy is shown meanwhile). */ export function churchChanged(): void { if (cached) cached = { ...cached, at: 0 }; } /** Tests: start with nothing. */ export function resetChurchProfile(): void { cached = null; pending = null; }