/** * Automatic analytics head tag (stacksjs/stacks#3578), opt-in. * * With `injectHead: true` in `config/analytics.ts`, the stx servers (`buddy * dev` and `buddy serve`) put the configured driver's tag before `` on * every full HTML page, so configuring a driver is enough. Off by default, * and with it off the page is untouched. * * - The tag is `getAnalyticsHead(config)`, so `enabled` and `environments` * decide whether there is one, exactly as when a layout renders it. * - Paths in `injectHeadExcept` (default: the dashboard) get no tag. * - Do Not Track / GPC are the driver's own settings (`respectDnt`, * `honorDnt`), which its script applies. The page itself is the same for * every visitor, so a shared cache can still serve it. * - A page that already carries the tag (a layout or `config/ui.ts` renders * it) is left alone, with a warning once per path, so there is never a * second tag. */ import type { AnalyticsConfig } from '@stacksjs/types' import type { AnalyticsHeadTag } from './drivers/shared' import { brotliCompressSync, brotliDecompressSync, deflateSync, gunzipSync, gzipSync, inflateSync } from 'node:zlib' import { renderHeadTags } from './drivers/shared' import { getAnalyticsHead } from './registry' /** Paths that get no tag unless `injectHeadExcept` says otherwise. */ export const DEFAULT_INJECT_HEAD_EXCEPT: readonly string[] = ['/dashboard/**'] /** * Does `pathname` match `pattern`? `*` matches within one segment, `**` across * segments, and a trailing `/**` also matches the path itself (`/dashboard/**` * matches `/dashboard`). */ export function matchesPathPattern(pattern: string, pathname: string): boolean { if (pattern.endsWith('/**') && pathname === pattern.slice(0, -3)) return true const source = pattern .split(/(\*\*|\*)/) .map(part => (part === '**' ? '.*' : part === '*' ? '[^/]*' : part.replace(/[.+?^${}()|[\]\\]/g, '\\$&'))) .join('') return new RegExp(`^${source}$`).test(pathname) } /** Is automatic injection on, and does it apply to this path? */ export function injectsAnalyticsHead(config: AnalyticsConfig | undefined, pathname: string): boolean { if (config?.injectHead !== true) return false const except = config.injectHeadExcept ?? DEFAULT_INJECT_HEAD_EXCEPT return !except.some(pattern => matchesPathPattern(pattern, pathname)) } export type AnalyticsHeadInsertion = | { outcome: 'injected', html: string } | { outcome: 'duplicate' | 'no-head' | 'no-tags', html: string } function escapeAttribute(value: string): string { return value.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(//g, '>') } /** Whether the page already loads one of the tags' scripts. */ function alreadyCarries(html: string, tags: AnalyticsHeadTag[]): boolean { return tags.some(([, attributes]) => { const src = attributes.src return Boolean(src) && (html.includes(src!) || html.includes(escapeAttribute(src!))) }) } /** * Put the tags before the document's ``. Leaves the page as it is when * there are no tags, no ``, or the page already loads the script. */ export function insertAnalyticsHead(html: string, tags: AnalyticsHeadTag[]): AnalyticsHeadInsertion { if (tags.length === 0) return { outcome: 'no-tags', html } if (alreadyCarries(html, tags)) return { outcome: 'duplicate', html } const close = html.search(/<\/head\s*>/i) if (close < 0) return { outcome: 'no-head', html } return { outcome: 'injected', html: `${html.slice(0, close)}${renderHeadTags(tags)}\n${html.slice(close)}` } } type Encoding = 'gzip' | 'br' | 'deflate' function encodingOf(response: Response): Encoding | null | undefined { const raw = response.headers.get('content-encoding')?.trim().toLowerCase() if (!raw || raw === 'identity') return null return raw === 'gzip' || raw === 'br' || raw === 'deflate' ? raw : undefined } function decode(bytes: Uint8Array, encoding: Encoding | null): string { const raw = encoding === 'gzip' ? gunzipSync(bytes) : encoding === 'br' ? brotliDecompressSync(bytes) : encoding === 'deflate' ? inflateSync(bytes) : bytes return new TextDecoder().decode(raw) } function encode(html: string, encoding: Encoding | null): Uint8Array { const bytes = new TextEncoder().encode(html) return encoding === null ? bytes : new Uint8Array(encoding === 'gzip' ? gzipSync(bytes) : encoding === 'br' ? brotliCompressSync(bytes) : deflateSync(bytes)) } export interface InjectAnalyticsHeadOptions { /** Told about a page that already carries the tag, and a driver that could not build one. */ onWarning?: (message: string) => void } const warned = new Set() function warnOnce(key: string, message: string, onWarning: (message: string) => void): void { if (warned.has(key)) return warned.add(key) onWarning(message) } function isFullDocument(request: Request, response: Response): boolean { const method = request.method.toUpperCase() return (method === 'GET' || method === 'HEAD') && response.status === 200 && Boolean(response.body) && response.headers.get('x-stx-fragment') !== 'true' && response.headers.get('content-type')?.toLowerCase().startsWith('text/html') === true } /** * The page with the analytics tag in its head, or undefined when it is left * as it was: injection off, an excluded path, not a full HTML page, no tag for * this environment, or a page that already carries it. */ export async function injectAnalyticsHead( request: Request, response: Response, config: AnalyticsConfig | undefined, options: InjectAnalyticsHeadOptions = {}, ): Promise { const pathname = new URL(request.url).pathname if (!injectsAnalyticsHead(config, pathname) || !isFullDocument(request, response)) return undefined const encoding = encodingOf(response) if (encoding === undefined) return undefined const onWarning = options.onWarning ?? (message => console.warn(message)) let tags: AnalyticsHeadTag[] try { tags = getAnalyticsHead(config!) } catch (error) { // A misconfigured driver is reported, not a failed page. warnOnce(`config:${(error as Error).message}`, `[analytics] No tag injected: ${(error as Error).message}`, onWarning) return undefined } if (tags.length === 0) return undefined let html: string try { html = decode(new Uint8Array(await response.clone().arrayBuffer()), encoding) } catch { return undefined } const inserted = insertAnalyticsHead(html, tags) if (inserted.outcome === 'duplicate') { warnOnce(`duplicate:${pathname}`, `[analytics] ${pathname} already loads the analytics script (from a layout or config/ui.ts), so injectHead added none. Remove one of the two.`, onWarning) return undefined } if (inserted.outcome !== 'injected') return undefined const headers = new Headers(response.headers) headers.delete('content-length') headers.delete('etag') return new Response(encode(inserted.html, encoding), { status: response.status, statusText: response.statusText, headers, }) } /** Forget which warnings were given. For tests. */ export function resetAnalyticsHeadWarnings(): void { warned.clear() }