async function handle(request, env, io, now) { const url = new URL(request.url); const path = url.pathname.replace(/\/+$/, '') || '/'; if (path === '/' || path === '/api') return json({ service: 'hwc-api', version: VERSION }); if (path === '/api/contact') return handleContact(request, env, io, now); if (path === '/api/site' || path === '/api/health') { if (request.method !== 'GET' && request.method !== 'HEAD') return json({ error: 'method not allowed' }, 405, { allow: 'GET, HEAD' }); const isSite = path === '/api/site'; return cached(io, request, path, isSite ? 60 : 20, async () => { const state = await loadState(io); if (!state || !state.status.updatedAt) return json({ error: 'no data yet' }, 503); if (isSite) return json(buildSite(state, now), 200); const h = buildHealth(state, now); return json(h, h.ok ? 200 : 503); }); } return json({ error: 'not found' }, 404); } function makeIO(env, ctx) { return { get: () => env.HWC.get(STATE_KEY), put: (s) => env.HWC.put(STATE_KEY, s), fetch: (url, init) => fetch(url, init), sleep: (ms) => new Promise((r) => setTimeout(r, ms)), mail: async (m) => { if (!env.EMAIL || typeof env.EMAIL.send !== 'function') throw new Error('EMAIL binding is missing'); return env.EMAIL.send(m); }, cache: typeof caches !== 'undefined' && caches.default ? caches.default : null, wait: ctx && ctx.waitUntil ? (p) => ctx.waitUntil(p) : null, }; } export default { async fetch(request, env, ctx) { try { return await handle(request, env, makeIO(env, ctx), Date.now()); } catch (e) { console.log('request failed: ' + scrub(e)); return json({ error: 'internal error' }, 500); } }, async scheduled(event, env, ctx) { ctx.waitUntil(runCron(env, Date.now(), makeIO(env, ctx)).catch((e) => console.log('cron failed: ' + scrub(e)))); }, };