import { useEffect, useState } from 'react'; export type Plan = 'free' | 'basic' | 'pro'; interface ResicomaData { restUrl: string; nonce: string; apiUrl: string; apiKey: string; plan: string; siteUrl: string; pluginUrl: string; version: string; adminUrl: string; locale?: string; debug?: boolean; } declare const resicomaData: ResicomaData | undefined; export interface Config extends ResicomaData { plan: Plan; /** An API key is saved, so the ResilienceWP service can be used. */ connected: boolean; /** Basic or Pro. */ paid: boolean; } export const PLAN_OVERRIDE_KEY = 'resicoma_plan_override'; const PLAN_OVERRIDE_EVENT = 'resicoma-plan-override-changed'; /** True in the Vite dev server (no resicomaData) or when PHP passes debug: true. */ export const isDevMode = (): boolean => { if (typeof resicomaData === 'undefined') return true; return resicomaData.debug === true; }; export const dispatchPlanChange = () => { window.dispatchEvent(new Event(PLAN_OVERRIDE_EVENT)); }; function readStorage(key: string): string | null { try { return window.localStorage.getItem(key); } catch { return null; } } export function toPlan(value: string | null | undefined): Plan { return value === 'basic' || value === 'pro' ? value : 'free'; } const DEV_DEFAULTS: ResicomaData = { restUrl: '/wp-json/resicoma/v1/', nonce: '', apiUrl: 'https://api.resiliencewp.com', apiKey: '', plan: 'free', siteUrl: 'http://localhost', pluginUrl: '', version: '1.3.3', adminUrl: '/wp-admin/', }; /** * The plan the service reported in this session (see usePlanSync). It replaces * the copy WordPress saved when the API key was entered, which goes out of date * when the account is upgraded or downgraded. */ let servicePlan: Plan | null = null; /** The plan WordPress has saved, updated when this session saves a newer one. */ let storedPlan: Plan | null = null; export function setServicePlan(plan: Plan) { if (servicePlan === plan) return; servicePlan = plan; dispatchPlanChange(); } export function getStoredPlan(): Plan { if (storedPlan) return storedPlan; return toPlan(typeof resicomaData !== 'undefined' ? resicomaData.plan : DEV_DEFAULTS.plan); } export function markPlanStored(plan: Plan) { storedPlan = plan; } export function getConfig(): Config { const base = typeof resicomaData !== 'undefined' ? resicomaData : DEV_DEFAULTS; let plan = servicePlan ?? toPlan(base.plan); if (isDevMode()) { const override = readStorage(PLAN_OVERRIDE_KEY); if (override) plan = toPlan(override); } const connected = Boolean(base.apiKey) || (isDevMode() && readStorage(PLAN_OVERRIDE_KEY) !== null); return { ...base, plan, connected, paid: connected && plan !== 'free' }; } export function useConfig(): Config { const [, forceUpdate] = useState(0); useEffect(() => { const handler = () => forceUpdate((n) => n + 1); window.addEventListener(PLAN_OVERRIDE_EVENT, handler); return () => window.removeEventListener(PLAN_OVERRIDE_EVENT, handler); }, []); return getConfig(); } export class ApiError extends Error { status: number; /** * "plan_required" when the plan does not include the feature (HTTP 402), * "scan_limit" when the month's scans are used up, "rate_limited" for the * per-minute request limit. */ code?: string; requiredPlan?: string; constructor(message: string, status: number, code?: string, requiredPlan?: string) { super(message); this.status = status; this.code = code; this.requiredPlan = requiredPlan; } } export function isPlanRequired(error: unknown): error is ApiError { return error instanceof ApiError && error.code === 'plan_required'; } /** The month's scan allowance is used up. Waiting a minute does not help; the message says when it resets. */ export function isScanLimit(error: unknown): error is ApiError { return error instanceof ApiError && error.code === 'scan_limit'; } async function readError(response: Response, fallback: string): Promise { const body = await response.json().catch(() => null) as { message?: string; error?: string } | null; return body?.error || body?.message || fallback; } /** Calls to this site's REST API (resicoma/v1). */ export async function wpApiFetch(endpoint: string, options: RequestInit = {}): Promise { const config = getConfig(); let response: Response; try { response = await fetch(`${config.restUrl}${endpoint}`, { credentials: 'same-origin', ...options, headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': config.nonce, ...options.headers, }, }); } catch { throw new ApiError('Could not reach this site. Check your connection and try again.', 0); } if (!response.ok) { // WordPress REST nonces expire after 12 to 24 hours. if (response.status === 403 || response.status === 401) { throw new ApiError('Your session has expired. Reload the page and try again.', response.status); } throw new ApiError(await readError(response, 'The request failed.'), response.status); } return response.json() as Promise; } /** Calls to the ResilienceWP API with the saved API key. */ export async function externalApiFetch(endpoint: string, options: RequestInit = {}): Promise { const config = getConfig(); let response: Response; try { response = await fetch(`${config.apiUrl}${endpoint}`, { ...options, // React Query is the cache; never answer a refetch from the HTTP cache. cache: options.cache ?? 'no-store', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${config.apiKey}`, ...options.headers, }, }); } catch { throw new ApiError('Could not reach the ResilienceWP service. Check your connection and try again.', 0); } if (!response.ok) { if (response.status === 401) { throw new ApiError('The ResilienceWP service did not accept your API key. Check it in Settings.', 401); } if (response.status === 429) { // Two different limits answer with 429. A used-up monthly scan allowance // comes with code "scan_limit" and a sentence that names the reset date; // anything else is the per-minute request limit. const body = await response.json().catch(() => null) as { error?: string; code?: string } | null; if (body?.code === 'scan_limit') { throw new ApiError(body.error || 'You have used all of this month\'s scans on your plan.', 429, 'scan_limit'); } throw new ApiError('Too many requests. Wait a minute and try again.', 429, 'rate_limited'); } if (response.status === 402) { const body = await response.json().catch(() => null) as { error?: string; code?: string; required_plan?: string } | null; throw new ApiError( body?.error || 'Your plan does not include this.', 402, body?.code || 'plan_required', body?.required_plan, ); } throw new ApiError(await readError(response, 'The ResilienceWP service returned an error.'), response.status); } return response.json() as Promise; } export function errorMessage(error: unknown, fallback = 'Something went wrong.'): string { return error instanceof Error && error.message ? error.message : fallback; }