// Build step, runs before the build: asks the CMS for the shoot packages and // writes src/content/offerings.generated.json, which the site imports. With // no address, a failing CMS or an unusable answer the committed snapshot // (src/content/offerings.snapshot.json) is used, so the build never fails // and never shows empty prices. The log says which one was used. // // OFFERINGS_URL: the site's own address that serves the API, for example // https://test.andreaslop.nl (the API is same-origin, /api/v1/offerings). import { readFileSync, writeFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { mapOfferings, type SiteOfferings } from './offerings.ts'; const SNAPSHOT = fileURLToPath( new URL('../src/content/offerings.snapshot.json', import.meta.url), ); const GENERATED = fileURLToPath( new URL('../src/content/offerings.generated.json', import.meta.url), ); const TIMEOUT_MS = 10_000; const ATTEMPTS = 2; async function fetchAnswer(base: string): Promise { const url = new URL('/api/v1/offerings', base); for (let attempt = 1; ; attempt++) { try { const response = await fetch(url, { signal: AbortSignal.timeout(TIMEOUT_MS), headers: { Accept: 'application/json' }, }); if (!response.ok) throw new Error(`status ${response.status}`); return await response.json(); } catch (error) { if (attempt >= ATTEMPTS) throw error; } } } async function main() { const snapshot = JSON.parse( readFileSync(SNAPSHOT, 'utf8'), ) as SiteOfferings; const base = process.env.OFFERINGS_URL?.trim(); let result = { ...snapshot, source: 'snapshot' }; if (!base) { console.log('[offerings] no OFFERINGS_URL: using the snapshot'); } else { try { const mapped = mapOfferings(await fetchAnswer(base)); if (mapped) { result = { ...mapped, source: 'cms' }; console.log( `[offerings] ${mapped.packages.length} packages` + `${mapped.banner ? ' and a banner' : ''} from ${base}`, ); } else { console.warn( `[offerings] answer of ${base} has no valid package: using the snapshot`, ); } } catch (error) { console.warn( `[offerings] ${base} not reachable (${String(error)}): using the snapshot`, ); } } writeFileSync(GENERATED, JSON.stringify(result, null, 4) + '\n'); } await main();