35 lines
1.2 KiB
JavaScript
35 lines
1.2 KiB
JavaScript
import { readFile } from 'node:fs/promises';
|
|
|
|
// Production deployment must also remove old entries that predate Cache-Tag support.
|
|
const config = JSON.parse(await readFile(new URL('../wrangler.jsonc', import.meta.url), 'utf8'));
|
|
const domain = new URL(config.vars.CF_DOMAIN);
|
|
if (
|
|
domain.protocol !== 'https:' ||
|
|
domain.pathname !== '/' ||
|
|
domain.search ||
|
|
domain.hash ||
|
|
domain.username ||
|
|
domain.password ||
|
|
domain.port
|
|
) {
|
|
throw new Error('CF_DOMAIN must be an HTTPS origin');
|
|
}
|
|
const token = process.env.CLOUDFLARE_API_TOKEN;
|
|
const zone = process.env.CLOUDFLARE_ZONE_ID;
|
|
if (!token || !zone) throw new Error('Missing Cloudflare purge credentials');
|
|
const response = await fetch(
|
|
`https://api.cloudflare.com/client/v4/zones/${encodeURIComponent(zone)}/purge_cache`,
|
|
{
|
|
method: 'POST',
|
|
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ hosts: [domain.hostname] }),
|
|
signal: AbortSignal.timeout(15000)
|
|
}
|
|
);
|
|
const result = await response.json();
|
|
if (!response.ok || result.success !== true)
|
|
throw new Error(
|
|
`Blog cache purge failed (HTTP ${response.status}): ${JSON.stringify(result.errors || [])}`
|
|
);
|
|
console.log(`Cloudflare accepted the cache purge for ${domain.hostname}`);
|