Branchwell

Lumen & Gesso / website / cloudflare-worker.mjs

1import { Resvg } from '@cf-wasm/resvg/workerd';
2import handler from './.open-next/worker.js';
3
4async function rasterizeSvg(svg) {
5 const renderer = await Resvg.async(svg);
6 try {
7 const image = renderer.render();
8 try {
9 return image.asPng();
10 } finally {
11 image.free();
12 }
13 } finally {
14 renderer.free();
15 }
16}
17
18export default {
19 fetch(request, env, ctx) {
20 if (env.LUMEN_DATA_PAUSED === 'true') {
21 const { pathname } = new URL(request.url);
22 const readOnly = request.method === 'GET' || request.method === 'HEAD';
23 const studioAction = pathname.startsWith('/admin/') || pathname === '/admin';
24 const appApi = pathname.startsWith('/api/');
25 if ((!readOnly && (appApi || studioAction)) || pathname.startsWith('/api/cron/')) {
26 return new Response('The studio is updating. Try again shortly.', {
27 status: 503,
28 headers: { 'Cache-Control': 'no-store', 'Retry-After': '30' },
29 });
30 }
31 }
32 return handler.fetch(request, { ...env, rasterizeSvg }, ctx);
33 },
34
35 async scheduled(_event, env, ctx) {
36 // Turn this on after the previous scheduler has stopped.
37 if (env.CLOUDFLARE_CRON_ACTIVE !== 'true' || env.LUMEN_DATA_PAUSED === 'true') return;
38 if (!env.CRON_SECRET) throw new Error('Cart-reminder cron secret is missing');
39 const request = new Request('https://lumengesso.com/api/cron/cart-reminders', {
40 headers: { Authorization: `Bearer ${env.CRON_SECRET}` },
41 });
42 const result = await handler.fetch(request, env, ctx);
43 if (!result.ok) throw new Error(`Cart reminder returned ${result.status}`);
44 const { considered, due, sent, failed } = await result.json();
45 console.info('[cart reminders] tick completed', { considered, due, sent, failed });
46 },
47};