diff --git a/src/index.ts b/src/index.ts index 3ffdd1c..38f7cc3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -158,32 +158,35 @@ async function handlePng( const svgUrl = `https://codewar.dev/api/svg?users=${usernames.join(",")}&range=${range}${selfParam}${themeParam}`; const browser = await puppeteer.launch(env.BROWSER); - const page = await browser.newPage(); - await page.setViewport({ width: 1200, height: 628 }); + try { + const page = await browser.newPage(); + await page.setViewport({ width: 1200, height: 628 }); - // Render SVG centered in OG-standard 1200×628 frame (1.91:1 ratio for X/Twitter) - const html = ``; - await page.setContent(html, { waitUntil: "networkidle0" }); + // Render SVG centered in OG-standard 1200×628 frame (1.91:1 ratio for X/Twitter) + const html = ``; + await page.setContent(html, { waitUntil: "networkidle0" }); - // Wait for draw animation to complete - await new Promise(r => setTimeout(r, 1500)); + // Wait for draw animation to complete + await new Promise(r => setTimeout(r, 1500)); - const pngBuffer = await page.screenshot({ - type: "png", - clip: { x: 0, y: 0, width: 1200, height: 628 }, - }) as Buffer; - await browser.close(); + const pngBuffer = await page.screenshot({ + type: "png", + clip: { x: 0, y: 0, width: 1200, height: 628 }, + }) as Buffer; - // Cache PNG for 24 hours - await env.CACHE.put(pngCacheKey, pngBuffer, { expirationTtl: 86400 }); + // Cache PNG for 24 hours + await env.CACHE.put(pngCacheKey, pngBuffer, { expirationTtl: 86400 }); - return new Response(pngBuffer, { - headers: { - "Content-Type": "image/png", - "Cache-Control": "public, max-age=1800", - ...corsHeaders(), - }, - }); + return new Response(pngBuffer, { + headers: { + "Content-Type": "image/png", + "Cache-Control": "public, max-age=1800", + ...corsHeaders(), + }, + }); + } finally { + await browser.close(); + } } async function handleApi( @@ -219,7 +222,7 @@ async function handleApi( for (const result of results) { if (result.status === "fulfilled") { const filtered = filterByRange(result.value.daily, range); - const smoothed = applyMovingAverage(filtered, 3); + const smoothed = applyMovingAverage(filtered, 3); datasets.push({ username: result.value.username, points: smoothed, diff --git a/src/smoothing.ts b/src/smoothing.ts index 2249ce4..8307790 100644 --- a/src/smoothing.ts +++ b/src/smoothing.ts @@ -30,7 +30,7 @@ export function filterByRange( } /** - * Apply a 7-day moving average to smooth the contribution data. + * Apply a centered moving average to smooth the contribution data. * Returns one smoothed point per day. */ export function applyMovingAverage(