/** * Where the Brainerce traffic pixel (`/t.js`) is loaded from, or `null` for "do not load it". * * The pixel host must follow the API host. A scaffold created with * `--api-url http://localhost:4000` talks to a local backend, and if the pixel still came from * production, every pageview of a dev session would be recorded against the real sales channel id. * * 1. `NEXT_PUBLIC_BRAINERCE_PIXEL_URL`, when set, wins. An explicit value is an opt-in, even for a * local host. * 2. Otherwise the origin of the configured API URL (`NEXT_PUBLIC_BRAINERCE_API_URL`, then * `BRAINERCE_API_URL`; the scaffolder writes both with the same value). * 3. When that origin is a local host (localhost, `*.localhost`, 127.x.x.x, 0.0.0.0, ::1) there is * no pixel at all: nothing to load, nothing sent. * 4. Nothing configured (or an unparseable value): `https://api.brainerce.com`. * * Server-only in practice (the root layout renders the tag); the `process.env.X` reads are literal * so a bundler can still inline them. */ const DEFAULT_API_ORIGIN = 'https://api.brainerce.com'; function isLocalHost(hostname: string): boolean { const host = hostname.toLowerCase().replace(/^\[|\]$/g, ''); return ( host === 'localhost' || host.endsWith('.localhost') || host === '0.0.0.0' || host === '::1' || /^127(\.\d{1,3}){3}$/.test(host) ); } /** The decision itself, free of `process.env` so it can be checked in isolation. */ export function pixelScriptUrlFor( pixelUrl: string | undefined, apiUrl: string | undefined ): string | null { const explicit = pixelUrl?.trim(); if (explicit) return `${explicit.replace(/\/+$/, '')}/t.js`; let origin = DEFAULT_API_ORIGIN; try { const parsed = new URL(apiUrl?.trim() || DEFAULT_API_ORIGIN); if (isLocalHost(parsed.hostname)) return null; origin = parsed.origin; } catch { // Unparseable API URL: fall back to production, the same fallback the middleware uses. } return `${origin}/t.js`; } export function getPixelScriptUrl(): string | null { return pixelScriptUrlFor( process.env.NEXT_PUBLIC_BRAINERCE_PIXEL_URL, process.env.NEXT_PUBLIC_BRAINERCE_API_URL || process.env.BRAINERCE_API_URL ); }