import { createSignal, For, Show } from 'solid-js'; import { Button, Switch, Textarea, MultiSelect, ConfirmDialog, Modal } from '@components'; import { useSettings, useLicense } from '@util/context'; import API from '@util/api'; export default function CloudflareStatus(props) { const { settings, saveSettings } = useSettings(); const { isLocked, shakePromo } = useLicense(); const [purgeInput, setPurgeInput] = createSignal(''); const [purging, setPurging] = createSignal(false); const [purgingAll, setPurgingAll] = createSignal(false); const [message, setMessage] = createSignal(null); const [disconnecting, setDisconnecting] = createSignal(false); const [showDisconnect, setShowDisconnect] = createSignal(false); const [paused, setPaused] = createSignal(!!props.status?.paused); const [pausing, setPausing] = createSignal(false); const [health, setHealth] = createSignal(null); const [checkingHealth, setCheckingHealth] = createSignal(false); const [purgeResult, setPurgeResult] = createSignal(null); const [workerStatus, setWorkerStatus] = createSignal(null); const [updatingWorker, setUpdatingWorker] = createSignal(false); const [workerError, setWorkerError] = createSignal(null); const [warming, setWarming] = createSignal(false); const [warmMsg, setWarmMsg] = createSignal(null); // Local state wins after an update, so the line reflects what just // happened without waiting for the parent to refetch. Both the worker // update and the warm run return a fresh status, so they share it. const worker = () => workerStatus() || props.status || {}; // Kick off (or resume) caching the whole site into the edge KV layer. // The connect-time crawl does this automatically, but only on a fresh // connect and only once WP-Cron fires; this is the on-demand button. const warmAll = async () => { if (isLocked()) { shakePromo(); return; } setWarming(true); setWarmMsg(null); try { const res = await API.post('cf/warm'); if (res.data?.success) { if (res.data.status) setWorkerStatus(res.data.status); setWarmMsg({ type: 'ok', text: res.data.message || 'Caching started.' }); } else { setWarmMsg({ type: 'error', text: res.data?.message || 'Could not start caching.' }); } } catch (err) { setWarmMsg({ type: 'error', text: 'Could not reach your site. Please try again.' }); } finally { setWarming(false); } }; const updateWorker = async () => { setUpdatingWorker(true); setWorkerError(null); try { const res = await API.post('cf/redeploy-worker'); if (res.data?.success) { setWorkerStatus(res.data.status); } else { setWorkerError(res.data?.message || 'Could not update the edge worker.'); } } catch (err) { setWorkerError('Could not reach your site. Please try again.'); } finally { setUpdatingWorker(false); } }; const togglePause = async (value) => { if (isLocked()) { shakePromo(); return; } setPausing(true); setPaused(value); try { const res = await API.post('cf/pause', { paused: value }); if (!res.data?.success) { setPaused(!value); setMessage({ type: 'error', text: res.data?.message || 'Could not update' }); } } catch (err) { setPaused(!value); setMessage({ type: 'error', text: 'Connection error' }); } finally { setPausing(false); } }; const checkHealth = async () => { setCheckingHealth(true); setHealth(null); try { const res = await API.get('cf/health'); const urls = res.data?.urls || []; // Probe from the browser (goes through Cloudflare) with credentials // omitted so the request looks anonymous and isn't force-bypassed // as a logged-in admin. const samples = await Promise.all(urls.map(async (url) => { try { const r = await fetch(url, { credentials: 'omit', cache: 'reload' }); const state = (r.headers.get('x-ajaxpress-cache') || 'UNKNOWN').toUpperCase(); return { url, state }; } catch (e) { return { url, state: 'UNKNOWN' }; } })); const hits = samples.filter((s) => s.state === 'HIT').length; setHealth({ samples, measured: samples.length, hit_rate: samples.length ? Math.round((hits / samples.length) * 100) : 0, }); } catch (err) { setMessage({ type: 'error', text: 'Connection error' }); } finally { setCheckingHealth(false); } }; // Backing lookups for the exclude pickers. `include` resolves already // saved values to labels; otherwise it's a plain text search. const contentSearch = async (type, q, include) => { const params = new URLSearchParams({ type }); if (q) params.set('q', q); for (const value of include || []) params.append('include[]', value); const res = await API.get(`cf/content-search?${params.toString()}`); return res.data?.items || []; }; // One control for both. Posts come back as numeric ids and terms as // "taxonomy:id", so a combined selection splits cleanly on save and the // user never has to know there are two settings underneath. const searchContent = (q, include) => contentSearch('any', q, include); const excludedContent = () => [ ...(settings.cf_exclude_posts || []), ...(settings.cf_exclude_terms || []), ]; const setExcludedContent = (next) => { if (isLocked()) { shakePromo(); return; } settings.cf_exclude_posts = next.filter((v) => !v.includes(':')); settings.cf_exclude_terms = next.filter((v) => v.includes(':')); }; // Get domain from route_pattern (e.g., "example.com/*" -> "example.com") const getDomain = () => { const pattern = props.status?.route_pattern || props.status?.zone_name || ''; return pattern.replace(/\/\*$/, ''); }; // Cloudflare answers a bad zone with "Could not route to /client/v4/...", // which tells the user nothing actionable. const readablePurgeError = (raw) => { const text = String(raw || ''); if (text.includes('Could not route') || text.includes('object identifier')) { return 'Cloudflare rejected the zone for this site. Reconnect Super Cache so the zone is set up again.'; } return text || 'Purge failed.'; }; const purge = async () => { const input = purgeInput().trim(); if (!input) return; // Split by newlines for multiple URLs/patterns const urls = input.split('\n').map(u => u.trim()).filter(Boolean); setPurging(true); setPurgeResult({ state: 'working', text: `Purging ${urls.length} URL${urls.length > 1 ? 's' : ''}...` }); try { const res = await API.post('cf/purge', { urls }); if (res.data?.success) { setPurgeResult({ state: 'done', text: `Purged ${urls.length} URL${urls.length > 1 ? 's' : ''}.` }); setPurgeInput(''); } else { setPurgeResult({ state: 'error', text: readablePurgeError(res.data?.message) }); } } catch (err) { setPurgeResult({ state: 'error', text: 'Could not reach your site. Please try again.' }); } finally { setPurging(false); } }; const purgeAll = async () => { setPurgingAll(true); setPurgeResult({ state: 'working', text: 'Purging every cached page...' }); try { const res = await API.post('cf/purge-all'); if (res.data?.success) { setPurgeResult({ state: 'done', text: 'Every cached page has been purged. They will be rebuilt on the next visit.' }); } else { setPurgeResult({ state: 'error', text: readablePurgeError(res.data?.message) }); } } catch (err) { setPurgeResult({ state: 'error', text: 'Could not reach your site. Please try again.' }); } finally { setPurgingAll(false); } }; const disconnect = async () => { setDisconnecting(true); try { const res = await API.post('cf/teardown'); // Teardown clears the site's Cloudflare options before it returns, // even when removing the worker or route hit a snag on Cloudflare's // side (success: false with a message). So once the request comes // back, this site is disconnected either way - flip the UI now // rather than leaving it stuck on the connected view. A partial // cleanup is worth noting, but it does not change that outcome. if (res.data?.success === false && res.data?.message) { console.warn('Cloudflare teardown partial:', res.data.message); } props.onDisconnected?.(); } catch (err) { // Only a request that never completed leaves the state unknown, so // this is the one case where the UI stays connected. console.error('Teardown error:', err); setMessage({ type: 'error', text: 'Could not reach your site. Please try again.' }); } finally { setDisconnecting(false); setShowDisconnect(false); } }; return (
{/* Connection + Purge Card */}
{/* Connected status on the left, pause on the right. Split into two groups rather than using a spacer utility - the ml-auto and w-auto classes are not in the generated CSS, so they silently did nothing. */}
}>
{getDomain()} verifying... |
{/* Kept next to the other actions rather than in settings: pausing is something you do, not something you configure. */}
Pause caching
{/* Compact cache summary: what is cached and when it last synced. */}
{worker().warm_done || props.status?.cached_pages || 0} pages on the edge · Last synced {props.status?.last_synced_human || 'never'} · Global layer active 0}> · Edge worker v{worker().worker_version}
{/* Fill the edge with every page. The connect-time crawl does this on its own, but only on a fresh connect and only once WP-Cron runs, so this is here for the rest of the time. */}
Caching pages in the background - this can take a while on a large site. {warmMsg().text}
{/* The worker updates itself in the background, so this only speaks up when it hasn't: either an update is on its way or it ran out of retries and needs a person. */}
A newer edge worker (v{worker().worker_latest}) is available. It installs itself within a minute or two. You can push it now if you'd rather not wait.

} >

The edge worker could not be updated after several attempts.

{worker().worker_failed?.message}

Your site is still being cached by the worker already installed, so nothing is broken - it just isn't the newest one.

{workerError()}

{/* Purge outcome, so a purge cannot fail silently in a corner of the screen. Not dismissable while it is still running. */} setPurgeResult(null)} >

{purgeResult()?.text}

setShowDisconnect(false)} /> {/* Purge Cache */}
setPurgeInput(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && purge()} /> {message().text}
{/* Cache health Card */}

Cache health

{/* Results are a one-off check, not standing state, so they can be dismissed once read. */}
{health().hit_rate}% of {health().measured} sampled pages served from the edge cache.
{(s) => (
{s.url} {s.state}
)}

A page is a MISS the first time it is requested, then a HIT once cached. Run again after browsing to see the rate climb.

{/* Pages to keep out of the cache. Grouped together because "which pages are dynamic" is one question, not four. */}

Pages to never cache

Anything that changes per visitor - logins, carts, forms, personalised content. Cart, checkout and account pages are handled automatically.