// GENERATED copy of integrations/shared/src/prebaked-edge.ts. Do not edit here; edit the source and // regenerate (integrations/README.md). // Prebaked edge integration core: bot and Markdown request detection, service URL, fallbacks. // Web APIs only (Request, Response, fetch, AbortController), no imports, so the same file runs in // Cloudflare Workers, Netlify Edge Functions (Deno), Vercel / Next.js middleware and Node. // Protocol: docs/protocol.md. Decisions: D-9 (bots never see a Prebaked auth error), D-11 (HTTPS), // D-14 (X-Prerender loop guard). /** SPEC sec 8: the edge integrations wait at most 5 s for Prebaked, then serve the origin. */ export const DEFAULT_TIMEOUT_MS = 5000; // BEGIN GENERATED BOT_UA_TOKENS (from @prebake/bots; update: see integrations/README.md) export const BOT_UA_TOKENS: readonly string[] = [ 'GPTBot', 'OAI-SearchBot', 'ChatGPT-User', 'ClaudeBot', 'Claude-User', 'Claude-SearchBot', 'CCBot', 'PerplexityBot', 'Perplexity-User', 'meta-externalagent', 'Bytespider', 'Googlebot', 'Applebot', 'bingbot', 'facebookexternalhit', 'TelegramBot', 'Twitterbot', 'LinkedInBot', 'Slackbot-LinkExpanding', 'Discordbot', 'WhatsApp', ]; // END GENERATED BOT_UA_TOKENS // AI crawlers (group `ai` in @prebake/bots): the bots Prebaked answers in `ai` mode. // BEGIN GENERATED AI_BOT_UA_TOKENS (from @prebake/bots; update: see integrations/README.md) export const AI_BOT_UA_TOKENS: readonly string[] = [ 'GPTBot', 'OAI-SearchBot', 'ChatGPT-User', 'ClaudeBot', 'Claude-User', 'Claude-SearchBot', 'CCBot', 'PerplexityBot', 'Perplexity-User', 'meta-externalagent', 'Bytespider', ]; // END GENERATED AI_BOT_UA_TOKENS /** * Paths ending with these are static files and never prerendered: the prerender-node 3.8.3 * `extensionsToIgnore` list plus `.otf`, `.eot`, `.avif` from its GitHub master (docs/protocol.md 3.1). */ export const IGNORED_EXTENSIONS: readonly string[] = [ '.js', '.css', '.xml', '.less', '.png', '.jpg', '.jpeg', '.gif', '.pdf', '.doc', '.txt', '.ico', '.rss', '.zip', '.mp3', '.rar', '.exe', '.wmv', '.avi', '.ppt', '.mpg', '.mpeg', '.tif', '.wav', '.mov', '.psd', '.ai', '.xls', '.mp4', '.m4a', '.swf', '.dat', '.dmg', '.iso', '.flv', '.m4v', '.torrent', '.woff', '.woff2', '.ttf', '.otf', '.eot', '.svg', '.webmanifest', '.webp', '.avif', ]; const escapeRegExp = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); /** Same rule as @prebake/bots: the token as a whole word, case-insensitive. */ const tokenRegex = (tokens: readonly string[]): RegExp => new RegExp(tokens.map((t) => `(? lower.endsWith(ext)); } /** * Loop guard (D-14): Prebaked's own fetches of the page carry `X-Prerender: 1`. Only that value * counts: Netlify adds `X-Prerender: On` to every bot request it classifies, and treating any * value as the guard sent every bot on Netlify past Prebaked (found 2026-11-19). */ export function isPrebakedLoopRequest(request: Request): boolean { return request.headers.get('x-prerender')?.trim() === '1'; } /** * Decide whether a request goes to Prebaked: GET or HEAD, not Prebaked's own fetch * ({@link isPrebakedLoopRequest}), not a static file, and a known bot user agent. */ export function shouldPrerender(request: Request): boolean { if (request.method !== 'GET' && request.method !== 'HEAD') return false; if (isPrebakedLoopRequest(request)) return false; let pathname: string; try { pathname = new URL(request.url).pathname; } catch { return false; } if (hasIgnoredExtension(pathname)) return false; return isBotUserAgent(request.headers.get('user-agent')); } /** * `/`, the page URL appended unencoded, as prerender-node does * (docs/protocol.md 1.2). A path prefix on the service URL is kept. */ export function buildServiceRequestUrl(serviceUrl: string, pageUrl: string): string { return `${serviceUrl}${serviceUrl.endsWith('/') ? '' : '/'}${pageUrl}`; } /** * Prebaked answers that reach the bot: 2xx, redirects, 404 and 410 (the page's own status). * Everything else (401/403 auth errors, 400, 5xx, 508 loop guard, ...) falls back to the origin. */ export function isPassThroughStatus(status: number): boolean { return (status >= 200 && status < 400) || status === 404 || status === 410; } export interface PrebakedConfig { /** e.g. `https://service.prebaked.io/`. Missing: every request goes to the origin. */ serviceUrl?: string | undefined; /** Sent as `X-Prerender-Token`. Missing: every request goes to the origin. */ token?: string | undefined; /** Default {@link DEFAULT_TIMEOUT_MS}. Covers the whole Prebaked response, body included. */ timeoutMs?: number | undefined; /** Visitor IP as reported by the platform; sent as `X-Forwarded-For` for bot verification. */ clientIp?: string | null | undefined; /** Sent as `X-Prerender-Int-Type`, e.g. `cloudflare-worker`. */ integration?: string | undefined; /** Injectable for tests; defaults to the global `fetch`. */ fetch?: ((input: string, init: RequestInit) => Promise) | undefined; /** Extra request headers for Prebaked (e.g. {@link SHADOW_HEADER}). */ extraHeaders?: Record | undefined; } // Not copied to the bot: the body is re-sent decoded and with a new length; Prebaked sets no // cookies on the customer's site. const DROP_RESPONSE_HEADERS = [ 'set-cookie', 'content-encoding', 'content-length', 'transfer-encoding', 'connection', 'keep-alive', ]; const NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]); // ---- Agent-ready responses: Markdown requests (docs/protocol.md sec 8, AR-3) ---- /** Opt-in request header: this integration takes Markdown and falls back on `X-Prebaked-Markdown`. */ export const FORMATS_HEADER = 'x-prebaked-formats'; /** Response header meaning "serve the origin response" (`off` or `unavailable`). */ export const MARKDOWN_STATUS_HEADER = 'x-prebaked-markdown'; const MARKDOWN_TYPES = new Set(['text/markdown', 'text/x-markdown']); /** True when the path (query excluded) ends in `.md`, any case. */ export function hasMarkdownPath(pathname: string): boolean { return pathname.toLowerCase().endsWith('.md'); } /** * True when the Accept header prefers Markdown over HTML (docs/protocol.md 8.1): `text/markdown` * (or `text/x-markdown`) listed with q > 0 and either a higher q than HTML, or the same q while * HTML is only matched by `text/*` / `*\/*` or listed after it. `*\/*` alone never selects Markdown. */ export function prefersMarkdown(accept: string | null | undefined): boolean { const ranges: { type: string; q: number; index: number }[] = []; (accept ?? '').split(',').forEach((part, index) => { const [rawType, ...params] = part.split(';'); const type = rawType?.trim().toLowerCase(); if (!type) return; let q = 1; for (const p of params) { const [k, v] = p.split('=').map((s) => s.trim()); if (k?.toLowerCase() === 'q') { const n = Number(v); q = Number.isFinite(n) ? Math.min(Math.max(n, 0), 1) : 0; } } ranges.push({ type, q, index }); }); const md = ranges .filter((r) => MARKDOWN_TYPES.has(r.type)) .sort((a, b) => b.q - a.q || a.index - b.index)[0]; if (!md || md.q <= 0) return false; const html = ranges.find((r) => r.type === 'text/html') ?? ranges.find((r) => r.type === 'text/*') ?? ranges.find((r) => r.type === '*/*'); if (!html) return true; if (md.q !== html.q) return md.q > html.q; return html.type !== 'text/html' || md.index < html.index; } /** * A Markdown request, whatever the user agent: GET or HEAD, not Prebaked's own fetch, and a * `.md` path or an Accept header that prefers Markdown. */ export function isMarkdownRequest(request: Request): boolean { if (request.method !== 'GET' && request.method !== 'HEAD') return false; if (isPrebakedLoopRequest(request)) return false; let pathname: string; try { pathname = new URL(request.url).pathname; } catch { return false; } return hasMarkdownPath(pathname) || prefersMarkdown(request.headers.get('accept')); } type Ask = { response: Response | null; markdownOff: boolean }; /** * One request to Prebaked. `markdown` adds `X-Prebaked-Formats: markdown` and the client's Accept * header; an answer with `X-Prebaked-Markdown` then gives `markdownOff`. */ async function askPrebaked( request: Request, config: PrebakedConfig, markdown: boolean, ): Promise { const none: Ask = { response: null, markdownOff: false }; if (!config.serviceUrl || !config.token) return none; const headers: Record = { 'x-prerender-token': config.token }; const userAgent = request.headers.get('user-agent'); if (userAgent) headers['user-agent'] = userAgent; if (config.clientIp) headers['x-forwarded-for'] = config.clientIp; if (config.integration) headers['x-prerender-int-type'] = config.integration; if (markdown) { headers[FORMATS_HEADER] = 'markdown'; const accept = request.headers.get('accept'); if (accept) headers['accept'] = accept; } Object.assign(headers, config.extraHeaders); const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), config.timeoutMs ?? DEFAULT_TIMEOUT_MS); try { const doFetch = config.fetch ?? ((input: string, init: RequestInit) => fetch(input, init)); const res = await doFetch(buildServiceRequestUrl(config.serviceUrl, request.url), { method: 'GET', headers, redirect: 'manual', signal: controller.signal, }); if (markdown && res.headers.has(MARKDOWN_STATUS_HEADER)) { await res.body?.cancel().catch(() => undefined); return { response: null, markdownOff: true }; } if (!isPassThroughStatus(res.status)) { await res.body?.cancel().catch(() => undefined); return none; } // Read the whole body inside the timeout, so a stalled body also falls back. const body = await res.arrayBuffer(); const outHeaders = new Headers(res.headers); for (const name of DROP_RESPONSE_HEADERS) outHeaders.delete(name); const sendBody = request.method !== 'HEAD' && !NULL_BODY_STATUSES.has(res.status); return { response: new Response(sendBody ? body : null, { status: res.status, headers: outHeaders }), markdownOff: false, }; } catch { return none; } finally { clearTimeout(timer); } } /** * Markdown first for a Markdown request (any user agent), then, when `botHtml` is set, the normal * bot HTML route. A Markdown `off`/`unavailable` answer for a `.md` path goes to the origin; for an * Accept-only request from a bot it takes the normal bot route (docs/protocol.md 8.2). */ async function route( request: Request, config: PrebakedConfig, botHtml: boolean, ): Promise { if (!config.serviceUrl || !config.token) return null; if (isMarkdownRequest(request)) { const md = await askPrebaked(request, config, true); if (md.response || !md.markdownOff) return md.response; if (hasMarkdownPath(new URL(request.url).pathname)) return null; } if (!botHtml || !shouldPrerender(request)) return null; return (await askPrebaked(request, config, false)).response; } /** * Ask Prebaked for the prerendered page, or for Markdown when the request asks for it * ({@link isMarkdownRequest}). Returns `null` when the origin should answer instead: neither a bot * nor a Markdown request, not configured, network error, timeout, a status that is not passed * through ({@link isPassThroughStatus}), or Markdown `off`/`unavailable`. Never throws. */ export async function fetchPrerendered( request: Request, config: PrebakedConfig, ): Promise { return route(request, config, true); } /** Prebaked's page for bots, otherwise (and on any Prebaked failure) `origin()`. */ export async function prebaked( request: Request, config: PrebakedConfig, origin: () => Promise, ): Promise { return (await fetchPrerendered(request, config)) ?? origin(); } // ---- Switch trial modes (docs/switch-trial-plan.md) ---- /** * - `shadow`: the request goes on untouched (to the origin, where the customer's existing prerender * setup keeps answering bots); Prebaked gets a background copy marked with {@link SHADOW_HEADER}, * whose answer is discarded. * - `ai`: Prebaked answers AI crawlers; every other request goes on untouched. * - `all`: Prebaked answers every bot (the default). */ export type PrebakedMode = 'shadow' | 'ai' | 'all'; /** Header and value that mark a shadow request: Prebaked renders and caches, the answer is unused. */ export const SHADOW_HEADER = 'x-prebaked-mode'; export const SHADOW_VALUE = 'shadow'; /** A shadow request runs in the background; it is cut off after this long. */ export const SHADOW_TIMEOUT_MS = 20_000; /** Mode lookups are cached this long (the endpoint sends `Cache-Control: max-age=60`). */ export const MODE_CACHE_MS = 60_000; /** A mode lookup delays the bot response at most this long, then the fallback mode is used. */ export const MODE_LOOKUP_TIMEOUT_MS = 1000; /** `shadow`, `ai` or `all` (any case, trimmed); anything else, `auto` and unset give `undefined`. */ export function parseMode(value: string | null | undefined): PrebakedMode | undefined { const v = value?.trim().toLowerCase(); return v === 'shadow' || v === 'ai' || v === 'all' ? v : undefined; } export interface ModeConfig extends PrebakedConfig { /** Default `all`. */ mode?: PrebakedMode | undefined; /** Keeps the shadow request alive after the response (`waitUntil`). Missing: fire and forget. */ waitUntil?: ((promise: Promise) => void) | undefined; } /** * Background copy of a bot request for Prebaked, marked as shadow. The body is read and dropped. * Resolves when done; never rejects. */ export async function sendShadow(request: Request, config: PrebakedConfig): Promise { if (!config.serviceUrl || !config.token || !shouldPrerender(request)) return; const copy = new Request(request.url, { method: 'GET', headers: request.headers }); // HTML only: shadow mode is for comparing the bot HTML route. await askPrebaked( copy, { ...config, timeoutMs: SHADOW_TIMEOUT_MS, extraHeaders: { ...config.extraHeaders, [SHADOW_HEADER]: SHADOW_VALUE }, }, false, ).catch(() => null); } /** * {@link fetchPrerendered} by mode: Prebaked's page for the bot, or `null` when the request should * go on untouched. In `shadow` mode the result is always `null`; the Prebaked copy is started and * handed to `waitUntil`, so it never delays or changes the response. Markdown requests are routed * in `ai` and `all` mode, not in `shadow` mode. */ export async function fetchWithMode( request: Request, config: ModeConfig, ): Promise { const mode = config.mode ?? 'all'; if (mode === 'all') return fetchPrerendered(request, config); if (mode === 'ai') { // AI crawlers: the full route. Other requests: Markdown only, other bots go on untouched. return route(request, config, isAiBotUserAgent(request.headers.get('user-agent'))); } if (mode === 'shadow') { try { const copy = sendShadow(request, config); config.waitUntil?.(copy); } catch { // The shadow copy must never break serving. } } return null; } /** {@link fetchWithMode}, otherwise (and on any failure) `origin()`. */ export async function prebakedWithMode( request: Request, config: ModeConfig, origin: () => Promise, ): Promise { return (await fetchWithMode(request, config)) ?? origin(); } const modeCache = new Map(); /** Clears the in-memory mode cache (tests). */ export function clearModeCache(): void { modeCache.clear(); } export interface ModeLookup { serviceUrl?: string | undefined; token?: string | undefined; /** Used when the lookup fails and no earlier answer is cached. */ fallback: PrebakedMode; fetch?: ((input: string, init: RequestInit) => Promise) | undefined; /** Injectable clock for tests. */ now?: (() => number) | undefined; } /** * The domain's mode from `GET /_prebaked/mode?host=`, cached in memory for * {@link MODE_CACHE_MS}. On a failed lookup the last known mode is kept, else `fallback`. Never * throws. */ export async function lookupMode(host: string, lookup: ModeLookup): Promise { const now = (lookup.now ?? Date.now)(); const cached = modeCache.get(host); if (cached && cached.expires > now) return cached.mode; if (!lookup.serviceUrl || !lookup.token) return lookup.fallback; const base = lookup.serviceUrl.endsWith('/') ? lookup.serviceUrl : `${lookup.serviceUrl}/`; const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), MODE_LOOKUP_TIMEOUT_MS); let mode: PrebakedMode | undefined; try { const doFetch = lookup.fetch ?? ((input: string, init: RequestInit) => fetch(input, init)); const res = await doFetch(`${base}_prebaked/mode?host=${encodeURIComponent(host)}`, { method: 'GET', headers: { 'x-prerender-token': lookup.token }, signal: controller.signal, }); if (res.ok) { const body = (await res.json()) as { mode?: unknown }; mode = parseMode(typeof body.mode === 'string' ? body.mode : undefined); } else { await res.body?.cancel().catch(() => undefined); } } catch { mode = undefined; } finally { clearTimeout(timer); } const resolved = mode ?? cached?.mode ?? lookup.fallback; modeCache.set(host, { mode: resolved, expires: now + MODE_CACHE_MS }); return resolved; } /** Env values the edge integrations read for the switch trial. */ export interface ModeEnv { PREBAKED_MODE?: string | undefined; } /** * Mode from `PREBAKED_MODE`. `auto` (or unset, when `unsetMeansAuto`) asks Prebaked's mode * endpoint, for bot and Markdown requests only, so other human requests never wait for it. Unset otherwise: `all`. */ export async function resolveMode( request: Request, env: ModeEnv, config: PrebakedConfig, unsetMeansAuto: boolean, ): Promise { const fixed = parseMode(env.PREBAKED_MODE); if (fixed) return fixed; const raw = env.PREBAKED_MODE?.trim().toLowerCase(); const auto = raw === 'auto' || (!raw && unsetMeansAuto); if (!auto || !(shouldPrerender(request) || isMarkdownRequest(request))) return 'all'; let host: string; try { host = new URL(request.url).hostname; } catch { return 'all'; } return lookupMode(host, { serviceUrl: config.serviceUrl, token: config.token, fallback: 'all', fetch: config.fetch, }); } /** Mode config from env: mode and `waitUntil`, on top of `config`. */ export async function modeConfigFromEnv( request: Request, env: ModeEnv, config: PrebakedConfig, options: { unsetMeansAuto: boolean; waitUntil?: ((promise: Promise) => void) | undefined; }, ): Promise { return { ...config, mode: await resolveMode(request, env, config, options.unsetMeansAuto), waitUntil: options.waitUntil, }; }