@active-reach/web-sdk 1.48.0 → 1.50.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aegis.min.js +1 -1
- package/dist/aegis.min.js.map +1 -1
- package/dist/{analytics-zA6ckfKP.mjs → analytics-DMY0Q0rI.mjs} +911 -312
- package/dist/analytics-DMY0Q0rI.mjs.map +1 -0
- package/dist/chat/AegisChat.d.ts +20 -0
- package/dist/chat/AegisChat.d.ts.map +1 -1
- package/dist/chat/index.d.ts +1 -1
- package/dist/chat/index.d.ts.map +1 -1
- package/dist/core/analytics.d.ts.map +1 -1
- package/dist/core/bootstrap.d.ts +2 -1
- package/dist/core/bootstrap.d.ts.map +1 -1
- package/dist/core/prefetch-bundle-client.d.ts.map +1 -1
- package/dist/core/purchase-backlog.d.ts +141 -0
- package/dist/core/purchase-backlog.d.ts.map +1 -0
- package/dist/core/purchase-events.d.ts +25 -0
- package/dist/core/purchase-events.d.ts.map +1 -0
- package/dist/core/queue.d.ts +39 -0
- package/dist/core/queue.d.ts.map +1 -1
- package/dist/core/sdk-config-poller.d.ts.map +1 -1
- package/dist/core/transport.d.ts +74 -1
- package/dist/core/transport.d.ts.map +1 -1
- package/dist/ecommerce/index.d.ts +1 -1
- package/dist/ecommerce/index.d.ts.map +1 -1
- package/dist/ecommerce/types.d.ts +10 -0
- package/dist/ecommerce/types.d.ts.map +1 -1
- package/dist/governance/trait-governor.d.ts +13 -6
- package/dist/governance/trait-governor.d.ts.map +1 -1
- package/dist/inapp/AegisInAppManager.d.ts +94 -6
- package/dist/inapp/AegisInAppManager.d.ts.map +1 -1
- package/dist/inapp/anon-claim.d.ts +36 -0
- package/dist/inapp/anon-claim.d.ts.map +1 -0
- package/dist/inapp/index.d.ts +1 -1
- package/dist/inapp/index.d.ts.map +1 -1
- package/dist/inapp/prize-retry.d.ts +51 -0
- package/dist/inapp/prize-retry.d.ts.map +1 -0
- package/dist/inapp/rail-fallback.d.ts +83 -0
- package/dist/inapp/rail-fallback.d.ts.map +1 -0
- package/dist/inapp/renderers/games.d.ts.map +1 -1
- package/dist/inapp/renderers/types.d.ts +12 -0
- package/dist/inapp/renderers/types.d.ts.map +1 -1
- package/dist/inapp/section-spot-lineup.d.ts +43 -0
- package/dist/inapp/section-spot-lineup.d.ts.map +1 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +986 -145
- package/dist/index.js.map +1 -1
- package/dist/react.js +1 -1
- package/dist/runtime/AegisMessageRuntime.d.ts +17 -0
- package/dist/runtime/AegisMessageRuntime.d.ts.map +1 -1
- package/dist/utils/fetch-abort.d.ts +23 -0
- package/dist/utils/fetch-abort.d.ts.map +1 -0
- package/dist/utils/preview-as-of.d.ts +21 -0
- package/dist/utils/preview-as-of.d.ts.map +1 -0
- package/package.json +2 -2
- package/dist/analytics-zA6ckfKP.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"analytics-DMY0Q0rI.mjs","sources":["../src/types/config.ts","../src/utils/uuid.ts","../src/utils/logger.ts","../src/utils/identity.ts","../src/core/session.ts","../src/utils/meta-cookies.ts","../src/core/purchase-events.ts","../src/core/transport.ts","../src/core/purchase-backlog.ts","../src/core/queue.ts","../src/utils/storage.ts","../src/utils/redact-url.ts","../src/utils/url-parser.ts","../src/utils/device.ts","../src/plugins/registry.ts","../src/utils/consent.ts","../src/utils/preview-as-of.ts","../src/inapp/item-touch.ts","../src/ecommerce/index.ts","../src/core/rate-limiter.ts","../src/governance/murmur3.ts","../src/governance/bloom-filter.ts","../src/governance/name-governor.ts","../src/governance/trait-governor.ts","../src/core/user-namespace.ts","../src/core/analytics.ts"],"sourcesContent":["export type CellRegion = 'us-east' | 'us-west' | 'eu-central' | 'ap-south' | 'ap-southeast';\n\nexport interface CellEndpoint {\n region: CellRegion;\n url: string;\n priority: number;\n healthy: boolean;\n}\n\nexport interface AegisConfig {\n write_key: string;\n\n workspace_id?: string;\n \n api_host?: string;\n \n cell_endpoints?: CellEndpoint[];\n \n preferred_region?: CellRegion;\n \n auto_region_detection?: boolean;\n \n batch_size?: number;\n \n batch_interval?: number;\n \n capture_utm?: boolean;\n \n capture_referrer?: boolean;\n \n auto_page_view?: boolean;\n \n session_timeout?: number;\n \n debug?: boolean;\n \n respect_dnt?: boolean;\n \n cross_domain_tracking?: boolean;\n \n cookie_domain?: string;\n \n secure_cookie?: boolean;\n \n enable_offline_mode?: boolean;\n \n max_offline_events?: number;\n \n retry_failed_requests?: boolean;\n \n max_retries?: number;\n \n retry_backoff_multiplier?: number;\n \n request_timeout?: number;\n\n /** Client-side rate limiter — burst (token bucket capacity). Default 100. */\n rate_limit_burst?: number;\n\n /** Client-side rate limiter — sustained tokens per second. Default 20. */\n rate_limit_per_second?: number;\n\n plugins?: string[];\n\n wait_for_consent?: boolean;\n\n default_consent?: {\n analytics?: boolean;\n marketing?: boolean;\n functional?: boolean;\n };\n\n enable_consent_mode?: boolean;\n\n integrate_onetrust?: boolean;\n\n integrate_cookiebot?: boolean;\n\n integrate_google_consent_mode?: boolean;\n\n /** Push notification configuration. When provided, AegisWebPush is initialized. */\n push?: {\n /** VAPID public key for Web Push subscription. */\n vapidPublicKey: string;\n /** Automatically prompt for push permission after SDK init. Default: false. */\n autoPrompt?: boolean;\n /** Delay in ms before showing auto-prompt. Default: 5000. */\n promptDelay?: number;\n /** Path to the service worker file. Default: '/aegis-sw.js'. */\n serviceWorkerPath?: string;\n /** Scope for the service worker registration. Default: '/'. Critical for e-commerce platforms. */\n serviceWorkerScope?: string;\n };\n}\n\nexport interface AegisConfigInternal extends Required<Omit<AegisConfig, 'api_host' | 'cell_endpoints' | 'preferred_region' | 'cookie_domain' | 'plugins' | 'default_consent' | 'workspace_id'>> {\n initialized: boolean;\n workspace_id: string | null;\n api_host: string | null;\n cell_endpoints: CellEndpoint[];\n preferred_region: CellRegion | null;\n cookie_domain: string | null;\n plugins: string[];\n active_cell: CellEndpoint | null;\n default_consent: {\n analytics: boolean;\n marketing: boolean;\n functional: boolean;\n };\n}\n\nexport const DEFAULT_CONFIG: Partial<AegisConfigInternal> = {\n workspace_id: null,\n batch_size: 10,\n batch_interval: 1000,\n capture_utm: true,\n capture_referrer: true,\n auto_page_view: false,\n session_timeout: 30,\n debug: false,\n respect_dnt: true,\n cross_domain_tracking: false,\n secure_cookie: true,\n enable_offline_mode: true,\n max_offline_events: 100,\n retry_failed_requests: true,\n max_retries: 3,\n retry_backoff_multiplier: 2,\n request_timeout: 5000,\n rate_limit_burst: 100,\n rate_limit_per_second: 20,\n auto_region_detection: true,\n wait_for_consent: false,\n enable_consent_mode: false,\n integrate_onetrust: false,\n integrate_cookiebot: false,\n integrate_google_consent_mode: false,\n default_consent: {\n analytics: false,\n marketing: false,\n functional: true,\n },\n initialized: false,\n api_host: null,\n cell_endpoints: [],\n preferred_region: null,\n cookie_domain: null,\n plugins: [],\n active_cell: null,\n};\n","export function generateUUID(): string {\n if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n return crypto.randomUUID();\n }\n\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\nexport function generateSessionId(): string {\n return `sess_${Date.now()}_${generateUUID().slice(0, 8)}`;\n}\n\nexport function generateMessageId(): string {\n return `msg_${Date.now()}_${generateUUID().slice(0, 8)}`;\n}\n","export type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nclass Logger {\n private enabled: boolean = false;\n private prefix: string = '[Active Reach SDK]';\n\n enable(): void {\n this.enabled = true;\n }\n\n disable(): void {\n this.enabled = false;\n }\n\n isEnabled(): boolean {\n return this.enabled;\n }\n\n debug(message: string, ...args: any[]): void {\n if (!this.enabled) return;\n console.debug(`${this.prefix} ${message}`, ...args);\n }\n\n info(message: string, ...args: any[]): void {\n if (!this.enabled) return;\n console.info(`${this.prefix} ${message}`, ...args);\n }\n\n warn(message: string, ...args: any[]): void {\n console.warn(`${this.prefix} ${message}`, ...args);\n }\n\n error(message: string, ...args: any[]): void {\n console.error(`${this.prefix} ${message}`, ...args);\n }\n}\n\nexport const logger = new Logger();\n","import { generateUUID } from './uuid';\nimport { Storage } from './storage';\nimport { logger } from './logger';\n\nexport interface IdentityState {\n anonymousId: string;\n userId: string | null;\n traits: Record<string, any>;\n}\n\nexport class Identity {\n private storage: Storage;\n private anonymousId: string;\n private userId: string | null = null;\n private traits: Record<string, any> = {};\n\n constructor(storage: Storage) {\n this.storage = storage;\n this.anonymousId = this.getOrCreateAnonymousId();\n this.loadUserIdentity();\n }\n\n private getOrCreateAnonymousId(): string {\n let id = this.storage.get('anon_id');\n\n if (!id) {\n id = generateUUID();\n this.storage.set('anon_id', id, 365);\n logger.debug('Created new anonymous ID:', id);\n } else {\n logger.debug('Loaded existing anonymous ID:', id);\n }\n\n return id;\n }\n\n private loadUserIdentity(): void {\n const storedUserId = this.storage.get('user_id');\n const storedTraits = this.storage.get('user_traits');\n\n if (storedUserId) {\n this.userId = storedUserId;\n logger.debug('Loaded user ID:', storedUserId);\n }\n\n if (storedTraits) {\n try {\n this.traits = JSON.parse(storedTraits);\n logger.debug('Loaded user traits:', this.traits);\n } catch (error) {\n logger.warn('Failed to parse stored traits:', error);\n this.traits = {};\n }\n }\n }\n\n getAnonymousId(): string {\n return this.anonymousId;\n }\n\n setUserId(userId: string, traits?: Record<string, any>): void {\n this.userId = userId;\n this.storage.set('user_id', userId, 365);\n logger.info('User identified:', userId);\n\n if (traits) {\n this.setTraits(traits);\n }\n }\n\n getUserId(): string | null {\n return this.userId;\n }\n\n setTraits(traits: Record<string, any>): void {\n this.traits = { ...this.traits, ...traits };\n this.storage.set('user_traits', JSON.stringify(this.traits), 365);\n logger.debug('User traits updated:', this.traits);\n }\n\n getTraits(): Record<string, any> {\n return { ...this.traits };\n }\n\n reset(): void {\n this.userId = null;\n this.traits = {};\n this.anonymousId = generateUUID();\n\n this.storage.remove('user_id');\n this.storage.remove('user_traits');\n this.storage.set('anon_id', this.anonymousId, 365);\n\n logger.info('Identity reset, new anonymous ID:', this.anonymousId);\n }\n\n alias(newUserId: string): { previousId: string; newUserId: string } {\n const previousId = this.userId || this.anonymousId;\n\n this.setUserId(newUserId);\n\n logger.info('User aliased:', { previousId, newUserId });\n\n return { previousId, newUserId };\n }\n\n getState(): IdentityState {\n return {\n anonymousId: this.anonymousId,\n userId: this.userId,\n traits: this.getTraits(),\n };\n }\n}\n","import { Storage } from '../utils/storage';\nimport { generateSessionId } from '../utils/uuid';\nimport { logger } from '../utils/logger';\nimport { AdClickIDs, LinkAttribution } from '../utils/url-parser';\n\n/**\n * How long a landing's Aegis link attribution survives a closed session —\n * the same 30-day window `click_attribution_bridge_worker.ATTRIBUTION_WINDOW_DAYS`\n * uses to attribute a short-link click, so the browser never claims a send\n * the server would already have aged out.\n */\nconst LINK_ATTRIBUTION_DURABLE_DAYS = 30;\n\nexport interface SessionState {\n sessionId: string;\n startTime: number;\n lastActivityTime: number;\n eventCount: number;\n adClickIDs?: AdClickIDs;\n landingPage?: string;\n linkAttribution?: LinkAttribution;\n}\n\nexport class SessionManager {\n private storage: Storage;\n private sessionId: string;\n private sessionTimeout: number;\n private lastActivityTime: number;\n private sessionStartTime: number;\n private eventCount: number = 0;\n private checkInterval: number | null = null;\n private activityThrottle: number = 1000;\n private lastActivityUpdate: number = 0;\n private adClickIDs: AdClickIDs = {};\n private landingPage?: string;\n private linkAttribution: LinkAttribution = {};\n\n constructor(storage: Storage, sessionTimeoutMinutes: number = 30) {\n this.storage = storage;\n this.sessionTimeout = sessionTimeoutMinutes * 60 * 1000;\n this.lastActivityTime = Date.now();\n this.sessionStartTime = Date.now();\n\n const session = this.loadSession();\n if (session) {\n this.sessionId = session.sessionId;\n this.sessionStartTime = session.startTime;\n this.lastActivityTime = session.lastActivityTime;\n this.eventCount = session.eventCount;\n this.adClickIDs = session.adClickIDs || {};\n this.landingPage = session.landingPage;\n this.linkAttribution = session.linkAttribution || {};\n logger.debug('Session loaded:', session);\n } else {\n this.sessionId = this.createNewSession();\n }\n\n this.startActivityTracking();\n this.startExpiryCheck();\n }\n\n private loadSession(): SessionState | null {\n const sessionData = this.storage.get('session');\n\n if (!sessionData) {\n return null;\n }\n\n try {\n const session: SessionState = JSON.parse(sessionData);\n const elapsed = Date.now() - session.lastActivityTime;\n\n if (elapsed < this.sessionTimeout) {\n return session;\n } else {\n logger.debug('Session expired, creating new session');\n this.storage.remove('session');\n return null;\n }\n } catch (error) {\n logger.warn('Failed to parse session data:', error);\n this.storage.remove('session');\n return null;\n }\n }\n\n private createNewSession(): string {\n const newSessionId = generateSessionId();\n this.sessionStartTime = Date.now();\n this.lastActivityTime = Date.now();\n this.eventCount = 0;\n // Assign BEFORE persisting — persistSession reads `this.sessionId`,\n // and prior to this assignment that field is still uninitialized\n // (the constructor only assigns it from createNewSession's return\n // value AFTER this call returns). Pre-fix, the first cookie write\n // contained the session JSON minus its sessionId field\n // (JSON.stringify drops undefined keys), and the next instance\n // reading that cookie would adopt the broken state.\n this.sessionId = newSessionId;\n\n this.persistSession();\n logger.info('New session created:', newSessionId);\n\n return newSessionId;\n }\n\n private persistSession(): void {\n const sessionData: SessionState = {\n sessionId: this.sessionId,\n startTime: this.sessionStartTime,\n lastActivityTime: this.lastActivityTime,\n eventCount: this.eventCount,\n adClickIDs: this.adClickIDs,\n landingPage: this.landingPage,\n linkAttribution: this.linkAttribution,\n };\n\n this.storage.set('session', JSON.stringify(sessionData));\n }\n\n private startActivityTracking(): void {\n const events = ['click', 'scroll', 'keypress', 'mousemove', 'touchstart'];\n\n const activityHandler = () => this.onActivity();\n\n events.forEach((event) => {\n window.addEventListener(event, activityHandler, { passive: true });\n });\n\n window.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'visible') {\n this.onActivity();\n }\n });\n }\n\n private startExpiryCheck(): void {\n this.checkInterval = window.setInterval(() => {\n this.checkSessionExpiry();\n }, 60000);\n }\n\n private onActivity(): void {\n const now = Date.now();\n const timeSinceLastUpdate = now - this.lastActivityUpdate;\n\n if (timeSinceLastUpdate < this.activityThrottle) {\n return;\n }\n\n this.lastActivityUpdate = now;\n const timeSinceLastActivity = now - this.lastActivityTime;\n\n if (timeSinceLastActivity > this.sessionTimeout) {\n logger.info('Session expired due to inactivity, creating new session');\n this.sessionId = this.createNewSession();\n } else {\n this.lastActivityTime = now;\n this.persistSession();\n }\n }\n\n private checkSessionExpiry(): void {\n const elapsed = Date.now() - this.lastActivityTime;\n\n if (elapsed > this.sessionTimeout) {\n logger.info('Session expired during check, creating new session');\n this.sessionId = this.createNewSession();\n }\n }\n\n getSessionId(): string {\n return this.sessionId;\n }\n\n incrementEventCount(): void {\n this.eventCount++;\n this.lastActivityTime = Date.now();\n this.persistSession();\n }\n\n getSessionDuration(): number {\n return Date.now() - this.sessionStartTime;\n }\n\n getEventCount(): number {\n return this.eventCount;\n }\n\n getState(): SessionState {\n return {\n sessionId: this.sessionId,\n startTime: this.sessionStartTime,\n lastActivityTime: this.lastActivityTime,\n eventCount: this.eventCount,\n adClickIDs: this.adClickIDs,\n landingPage: this.landingPage,\n linkAttribution: this.linkAttribution,\n };\n }\n\n setAdClickIDs(adClickIDs: AdClickIDs, landingPage?: string): void {\n if (Object.keys(adClickIDs).length > 0) {\n this.adClickIDs = { ...this.adClickIDs, ...adClickIDs };\n if (landingPage) {\n this.landingPage = landingPage;\n }\n this.persistSession();\n // Also persist DURABLY (365d, like anon_id/user_id) — NOT only in the\n // 30-min session. An ad click must survive to a LATER-session login on\n // the same device: the visitor clicks anonymously, returns/logs in days\n // later, identify() re-injects these ids → the click is attributed. If\n // they lived only in the session they'd expire in 30 min of inactivity,\n // long before the platform attribution window (7-90d). Keyed durably so\n // getAdClickIDs() hydrates them on a fresh session.\n try {\n this.storage.set('ad_click_ids', JSON.stringify(this.adClickIDs), 365);\n if (this.landingPage) {\n this.storage.set('ad_landing_page', this.landingPage, 365);\n }\n } catch {\n // best-effort; the session copy still works in-session\n }\n logger.info('Ad click IDs stored (session + durable):', this.adClickIDs);\n }\n }\n\n getAdClickIDs(): AdClickIDs {\n // Hydrate from durable storage when the (30-min) session had none — this is\n // what lets a later-session login attribute an earlier anonymous ad click.\n if (Object.keys(this.adClickIDs).length === 0) {\n try {\n const durable = this.storage.get('ad_click_ids');\n if (durable) {\n const parsed = JSON.parse(durable) as AdClickIDs;\n if (parsed && Object.keys(parsed).length > 0) {\n this.adClickIDs = parsed;\n if (!this.landingPage) {\n this.landingPage = this.storage.get('ad_landing_page') || undefined;\n }\n }\n }\n } catch {\n // ignore parse/storage errors — fall back to the in-memory value\n }\n }\n return this.adClickIDs;\n }\n\n getLandingPage(): string | undefined {\n return this.landingPage;\n }\n\n /**\n * Record the landing's Aegis link attribution. LAST touch: a new `aegis_code`\n * replaces the previous set whole — never merged, because the fields are the\n * attributes of ONE link and a mix of two links describes neither.\n * Session + durable (30d, the server's short-link attribution window) so a\n * checkout in a later session can still name the send that brought them.\n */\n setLinkAttribution(attribution: LinkAttribution): void {\n if (!attribution.aegis_code) return;\n this.linkAttribution = { ...attribution };\n this.persistSession();\n try {\n this.storage.set(\n 'link_attribution',\n JSON.stringify(this.linkAttribution),\n LINK_ATTRIBUTION_DURABLE_DAYS,\n );\n } catch {\n // best-effort; the session copy still works in-session\n }\n }\n\n getLinkAttribution(): LinkAttribution {\n if (!this.linkAttribution.aegis_code) {\n try {\n const durable = this.storage.get('link_attribution');\n if (durable) {\n const parsed = JSON.parse(durable) as LinkAttribution;\n if (parsed && parsed.aegis_code) {\n this.linkAttribution = parsed;\n }\n }\n } catch {\n // ignore parse/storage errors — fall back to the in-memory value\n }\n }\n return this.linkAttribution;\n }\n\n destroy(): void {\n if (this.checkInterval) {\n clearInterval(this.checkInterval);\n this.checkInterval = null;\n }\n }\n}\n","/**\n * Meta Pixel companion cookies (_fbp, _fbc) — B1.2 of META_CAPI_PHASE1_TRACKER.\n *\n * We do NOT fire `fbq()` browser-side. We write the cookies Meta uses to\n * identify the same browser so server-side CAPI events (forwarded from\n * `meta_conversions_api_service.py`) carry the high-EMQ match keys\n * (fbp + fbc) without the cost of running a full Meta Pixel.\n *\n * Cookie spec (Meta docs, verified May 2026):\n * _fbp = fb.<subdomain_index>.<creation_ms>.<random>\n * _fbc = fb.<subdomain_index>.<click_ms>.<fbclid>\n * subdomain_index = number of dots in cookie domain\n * (example.com → 1, sub.example.com → 2)\n * random = 10-digit random integer\n * Lifetime: 90 days (Meta's default; longer doesn't increase EMQ)\n *\n * Reasoning for raw document.cookie writes (instead of utils/storage.ts):\n * The Storage helper prefixes every key with `aegis_` so writes go to\n * `aegis__fbp` / `aegis__fbc`. Meta only honors the exact names\n * `_fbp` and `_fbc`. We bypass the helper and write directly.\n *\n * Domain scope: written to the eTLD+1 (root domain) so a tenant who\n * later wires their own Meta Pixel via GTM sees the same cookies a\n * subdomain-rooted set would not.\n *\n * SSR-safe: every helper is no-op when `document` / `window` are\n * undefined. Callers don't need to guard.\n */\n\nconst FBP_COOKIE = '_fbp';\nconst FBC_COOKIE = '_fbc';\nconst COOKIE_LIFETIME_DAYS = 90;\n\nexport interface MetaCookies {\n fbp: string | null;\n fbc: string | null;\n fbclid: string | null;\n}\n\n/** Read a cookie value or null. SSR-safe. */\nfunction readCookie(name: string): string | null {\n if (typeof document === 'undefined') return null;\n try {\n const target = `${name}=`;\n const parts = document.cookie.split(';');\n for (let i = 0; i < parts.length; i++) {\n let c = parts[i];\n while (c.charAt(0) === ' ') c = c.substring(1);\n if (c.indexOf(target) === 0) {\n return decodeURIComponent(c.substring(target.length));\n }\n }\n } catch {\n /* swallow — cookie access can throw in cross-origin / sandboxed iframes */\n }\n return null;\n}\n\n/** Write a cookie at root-domain scope so cross-subdomain reads work. SSR-safe. */\nfunction writeCookie(name: string, value: string, days: number): void {\n if (typeof document === 'undefined' || typeof window === 'undefined') return;\n try {\n const expiry = new Date(Date.now() + days * 24 * 60 * 60 * 1000).toUTCString();\n const domain = getRootDomain();\n const isHttps = window.location.protocol === 'https:';\n let cookieStr = `${name}=${encodeURIComponent(value)};expires=${expiry};path=/;SameSite=Lax`;\n if (isHttps) cookieStr += ';Secure';\n if (domain) cookieStr += `;domain=${domain}`;\n document.cookie = cookieStr;\n } catch {\n /* ignore — best effort */\n }\n}\n\n/**\n * Get eTLD+1 of current host. Returns null on localhost / IP / single-label\n * hosts so we fall through to host-only cookie scope (browser default).\n *\n * Heuristic, not PSL-perfect: produces `example.com` for `a.b.example.com`.\n * Edge cases (`co.uk` etc.) get the wrong answer, but Meta itself uses\n * the same heuristic when their own pixel writes _fbp, so we stay aligned.\n */\nfunction getRootDomain(): string | null {\n if (typeof window === 'undefined') return null;\n const host = window.location.hostname;\n if (!host || host === 'localhost') return null;\n // IP address — host-only cookie scope.\n if (/^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(host)) return null;\n const parts = host.split('.');\n if (parts.length < 2) return null;\n return '.' + parts.slice(-2).join('.');\n}\n\n/**\n * Subdomain index per Meta spec — count of dots in the cookie domain.\n * Counts components, not literal dots:\n * example.com → 1\n * sub.example.com → 2\n * sub.sub.example.com → 3\n */\nfunction subdomainIndex(): number {\n if (typeof window === 'undefined') return 1;\n const host = window.location.hostname;\n if (!host || host === 'localhost' || /^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(host)) return 1;\n const parts = host.split('.');\n return Math.max(1, parts.length - 1);\n}\n\n/** 10-digit random integer (Meta's spec format). */\nfunction randomToken(): string {\n // Math.random() * 1e10 produces a 10-digit-ish integer; pad-left to be safe.\n const n = Math.floor(Math.random() * 1e10);\n return n.toString().padStart(10, '0');\n}\n\n/**\n * Read `_fbp` from cookies, write a fresh one if absent.\n * Returns the resulting `_fbp` value or null if cookies unavailable.\n */\nexport function ensureFbp(): string | null {\n const existing = readCookie(FBP_COOKIE);\n if (existing) return existing;\n const fbp = `fb.${subdomainIndex()}.${Date.now()}.${randomToken()}`;\n writeCookie(FBP_COOKIE, fbp, COOKIE_LIFETIME_DAYS);\n return fbp;\n}\n\n/**\n * Read `_fbc` from cookies. If absent and the URL carries `fbclid`, write\n * a fresh `_fbc` per Meta's spec. Returns the resulting value or null.\n *\n * Note: `_fbc` has no value to write without an `fbclid` source — unlike\n * `_fbp` which is browser-identity-only and can be self-generated.\n */\nexport function ensureFbc(): string | null {\n const existing = readCookie(FBC_COOKIE);\n if (existing) return existing;\n const fbclid = readFbclidFromUrl();\n if (!fbclid) return null;\n const fbc = `fb.${subdomainIndex()}.${Date.now()}.${fbclid}`;\n writeCookie(FBC_COOKIE, fbc, COOKIE_LIFETIME_DAYS);\n return fbc;\n}\n\n/** Pull `fbclid` from `?fbclid=...` query string. Null if absent or SSR. */\nexport function readFbclidFromUrl(): string | null {\n if (typeof window === 'undefined') return null;\n try {\n return new URLSearchParams(window.location.search).get('fbclid');\n } catch {\n return null;\n }\n}\n\n/**\n * Single call that returns `{fbp, fbc, fbclid}` for injection into every\n * event's `properties` (which lands in ClickHouse `in_app_events.metadata`,\n * which the cell-side CAPI service reads directly).\n *\n * Side effects: ensures both cookies are present before returning. Idempotent\n * — safe to call on every event capture.\n */\nexport function captureMetaCookies(): MetaCookies {\n return {\n fbp: ensureFbp(),\n fbc: ensureFbc(),\n fbclid: readFbclidFromUrl(),\n };\n}\n\n/**\n * A copy of `event` safe to hand to a logger: `properties.fbc` / `properties.fbp`\n * masked. They are Meta cookie values — match keys for CAPI only, and must\n * stay out of every log line (ACS tracking tracker §V.3). The event itself is\n * never mutated; only the logged copy is.\n */\nexport function redactMetaCookies<T>(event: T): T {\n const props = (event as { properties?: Record<string, unknown> } | null)?.properties;\n if (!props || (props.fbc === undefined && props.fbp === undefined)) return event;\n const masked: Record<string, unknown> = { ...props };\n if (masked.fbc !== undefined) masked.fbc = '[redacted]';\n if (masked.fbp !== undefined) masked.fbp = '[redacted]';\n return { ...(event as object), properties: masked } as T;\n}\n","/**\n * Which SDK events are PURCHASES (Aman 11-02, Q13 / WP19 SDK half): a purchase\n * event is never dropped by the SDK. The queue keeps purchases in their own\n * persisted backlog and retries them until the gateway accepts them; the\n * client rate limiter and the event-name governor let them through.\n *\n * A purchase is any track event whose name the gateway canonicalises to\n * `transaction.purchase` (libs/gateway-core/src/canonical-event.ts, the ONE\n * name mapper; docs/agent-rules/EVENT_VOCABULARY.md). The SDK cannot import\n * gateway-core (a Node lib, not part of the browser bundle), so the spellings\n * are listed here and `tests/drift-purchase-never-dropped.test.ts` fails the\n * build when the mapper gains a purchase spelling this list lacks.\n *\n * Matching mirrors the mapper: the exact lower-cased name, then the\n * normalised form (`.`, `/`, `-` and spaces → `_`), so `Order Completed`,\n * `Purchase` and `order.completed` all count.\n */\nimport type { AegisEvent, TrackEvent } from '../types/events';\n\n/** Every spelling the gateway maps to `transaction.purchase`, plus the canonical name itself. */\nexport const PURCHASE_EVENT_NAMES: ReadonlySet<string> = new Set([\n 'transaction.purchase',\n 'transaction_purchase',\n 'bulk_order',\n 'historical_order',\n 'lookalike_first_purchase',\n 'offline_order',\n 'order.completed',\n 'order_completed',\n 'order_import',\n 'order_placed',\n 'order_placed_cod',\n 'orders_create',\n 'order_success',\n 'order_upload',\n 'pos_first_transaction',\n 'pos_transaction_completed',\n 'purchase',\n 'purchase.completed',\n 'purchase_completed',\n 'sales_order_place_after',\n 'transaction',\n 'woocommerce_order_completed',\n 'woocommerce_order_placed',\n]);\n\nfunction normalise(raw: string): string {\n return raw\n .trim()\n .toLowerCase()\n .replace(/[./\\-\\s]+/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_|_$/g, '');\n}\n\n/** True when `name` is a purchase event name (see the module doc). */\nexport function isPurchaseEventName(name: unknown): boolean {\n if (typeof name !== 'string' || name.length === 0) return false;\n const lower = name.toLowerCase();\n return PURCHASE_EVENT_NAMES.has(lower) || PURCHASE_EVENT_NAMES.has(normalise(name));\n}\n\n/** True when `event` is a track event carrying a purchase name. */\nexport function isPurchaseEvent(event: AegisEvent | null | undefined): boolean {\n if (!event || event.type !== 'track') return false;\n return isPurchaseEventName((event as TrackEvent).event);\n}\n","import { AegisEvent, BatchPayload, BatchResponse } from '../types/events';\nimport { CellEndpoint, CellRegion } from '../types/config';\nimport { logger } from '../utils/logger';\nimport { Storage } from '../utils/storage';\n\nexport interface TransportConfig {\n writeKey: string;\n apiHost: string | null;\n cellEndpoints: CellEndpoint[];\n preferredRegion: CellRegion | null;\n autoRegionDetection: boolean;\n requestTimeout: number;\n retryFailedRequests: boolean;\n maxRetries: number;\n retryBackoffMultiplier: number;\n}\n\nexport interface SendResult {\n success: boolean;\n response?: BatchResponse;\n error?: Error;\n endpoint?: string;\n /** HTTP status of the last attempt (0 = network error / abort). */\n status?: number;\n /** Server-asked wait before the next try (a 429/503 `Retry-After`), ms. */\n retryAfterMs?: number;\n /**\n * CLIENT-SIDE bookkeeping, not a gateway contract: when this send went out\n * as several requests (chunks of MAX_BATCH_EVENTS, halves after a 413 / an\n * oversize keepalive body / a 400 on a purchase drain), the events whose\n * request did not get a 2xx (or was not tried after a refusal). The caller\n * keeps exactly these, so a chunk that got a 2xx is never re-sent. Absent\n * on a single-request failure: then every event is unaccepted.\n */\n rejected?: AegisEvent[];\n /**\n * A single event the gateway refused on its own (400, or 413 at one event):\n * re-sending it can never succeed. Set only when `splitOnBadRequest` let the\n * transport narrow a refusal down to one event.\n */\n terminalEvent?: AegisEvent;\n}\n\n/**\n * Browsers refuse a `keepalive` fetch (and `sendBeacon`) whose body is over\n * 64 KB, with a TypeError that looks like status 0. A keepalive body is kept\n * under this many bytes: a larger multi-event request is split before it is\n * sent; a single event over it goes without keepalive.\n */\nexport const KEEPALIVE_BODY_MAX_BYTES = 60_000;\n/**\n * The 64 KB keepalive quota is shared by every keepalive request in flight,\n * so a keepalive request over this size that fails with status 0 may have\n * been refused for quota: it is halved and retried. A smaller one failing\n * with status 0 is a network error (halving it would only multiply requests\n * while offline).\n */\nconst KEEPALIVE_SPLIT_ON_ZERO_BYTES = 16_000;\n\n/** UTF-8 byte length (the browser's 64 KB limit counts bytes, not chars). */\nexport function utf8Bytes(text: string): number {\n if (typeof TextEncoder !== 'undefined') return new TextEncoder().encode(text).length;\n return unescape(encodeURIComponent(text)).length;\n}\n\n/**\n * The most events one `/v1/batch` request carries. The gateway answers 413\n * above `SDK_BATCH_MAX_EVENTS` (default 100, docs/architecture/\n * GATEWAY_SDK_RATE_LIMITS.md), so EVERY send — a normal batch, an offline\n * flush, a purchase drain, a beacon — is cut into requests of at most this\n * many. A 413 anyway (an org set a lower cap) splits the request in half and\n * sends each half; a 413 never drops an event.\n */\nexport const MAX_BATCH_EVENTS = 100;\n\nexport interface SendOptions {\n /**\n * The caller owns retries and needs to know the server ACCEPTED the batch:\n * never use `sendBeacon` (it reports \"queued by the browser\", not\n * \"accepted\"), and make one attempt — the caller re-tries on its own\n * backoff. The purchase backlog (queue.ts) sends this way so a 429 is never\n * the end of a purchase.\n */\n confirmDelivery?: boolean;\n /**\n * Send with `keepalive` (default true: the request survives the page\n * unloading, but its body must stay under 64 KB). The purchase drain of a\n * live page passes false so a large chunk is never refused by the browser.\n */\n keepalive?: boolean;\n /**\n * Halve a request the gateway answers 400 and narrow the refusal down to\n * the one event it is about (`SendResult.terminalEvent`). The purchase\n * drain uses it so one bad event cannot block the backlog.\n */\n splitOnBadRequest?: boolean;\n}\n\n/** Parse a `Retry-After` header (seconds or an HTTP date) into ms, capped at 5 min. */\nexport function parseRetryAfterMs(value: string | null | undefined, now: number = Date.now()): number | undefined {\n if (!value) return undefined;\n const trimmed = value.trim();\n let ms: number;\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n ms = Number(trimmed) * 1000;\n } else {\n const at = Date.parse(trimmed);\n if (Number.isNaN(at)) return undefined;\n ms = at - now;\n }\n if (!Number.isFinite(ms) || ms < 0) return undefined;\n return Math.min(ms, 5 * 60 * 1000);\n}\n\nexport class Transport {\n private config: TransportConfig;\n private storage: Storage;\n private activeCell: CellEndpoint | null = null;\n private healthCheckInterval: number | null = null;\n private regionLatencyMap: Map<string, number> = new Map();\n\n constructor(config: TransportConfig, storage: Storage) {\n this.config = config;\n this.storage = storage;\n\n if (config.cellEndpoints.length > 0) {\n this.initializeCellularArchitecture();\n }\n }\n\n private async initializeCellularArchitecture(): Promise<void> {\n const cachedCell = this.loadCachedCell();\n\n if (cachedCell && this.isCellHealthy(cachedCell)) {\n this.activeCell = cachedCell;\n logger.info('Using cached cell:', cachedCell);\n } else {\n await this.selectOptimalCell();\n }\n\n this.startHealthChecks();\n }\n\n private loadCachedCell(): CellEndpoint | null {\n const cached = this.storage.get('active_cell');\n\n if (!cached) {\n return null;\n }\n\n try {\n return JSON.parse(cached) as CellEndpoint;\n } catch (error) {\n logger.warn('Failed to parse cached cell:', error);\n return null;\n }\n }\n\n private saveCachedCell(cell: CellEndpoint): void {\n this.storage.set('active_cell', JSON.stringify(cell), 7);\n }\n\n private isCellHealthy(cell: CellEndpoint): boolean {\n return (\n cell.healthy &&\n this.config.cellEndpoints.some(\n (c) => c.region === cell.region && c.url === cell.url\n )\n );\n }\n\n private async selectOptimalCell(): Promise<void> {\n logger.info('Selecting optimal cell...');\n\n if (this.config.preferredRegion) {\n const preferredCell = this.config.cellEndpoints.find(\n (cell) => cell.region === this.config.preferredRegion && cell.healthy\n );\n\n if (preferredCell) {\n this.activeCell = preferredCell;\n this.saveCachedCell(preferredCell);\n logger.info('Using preferred region cell:', preferredCell);\n return;\n }\n }\n\n if (this.config.autoRegionDetection) {\n await this.detectOptimalRegion();\n } else {\n this.selectCellByPriority();\n }\n }\n\n private async detectOptimalRegion(): Promise<void> {\n const healthyCells = this.config.cellEndpoints.filter((cell) => cell.healthy);\n\n if (healthyCells.length === 0) {\n logger.error('No healthy cells available');\n return;\n }\n\n const latencyPromises = healthyCells.map(async (cell) => {\n const latency = await this.measureLatency(cell);\n this.regionLatencyMap.set(cell.region, latency);\n return { cell, latency };\n });\n\n const results = await Promise.all(latencyPromises);\n results.sort((a, b) => a.latency - b.latency);\n\n const optimalCell = results[0].cell;\n this.activeCell = optimalCell;\n this.saveCachedCell(optimalCell);\n\n logger.info('Optimal cell selected:', {\n region: optimalCell.region,\n latency: results[0].latency,\n });\n }\n\n private async measureLatency(cell: CellEndpoint): Promise<number> {\n const startTime = performance.now();\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 2000);\n\n const response = await fetch(`${cell.url}/health`, {\n method: 'GET',\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (response.ok) {\n return performance.now() - startTime;\n } else {\n return Infinity;\n }\n } catch (error) {\n logger.warn(`Health check failed for ${cell.region}:`, error);\n return Infinity;\n }\n }\n\n private selectCellByPriority(): void {\n const sortedCells = [...this.config.cellEndpoints]\n .filter((cell) => cell.healthy)\n .sort((a, b) => a.priority - b.priority);\n\n if (sortedCells.length > 0) {\n this.activeCell = sortedCells[0];\n this.saveCachedCell(sortedCells[0]);\n logger.info('Cell selected by priority:', sortedCells[0]);\n } else {\n logger.error('No healthy cells available');\n }\n }\n\n private startHealthChecks(): void {\n this.healthCheckInterval = window.setInterval(() => {\n this.performHealthChecks();\n }, 60000);\n }\n\n private async performHealthChecks(): Promise<void> {\n const healthPromises = this.config.cellEndpoints.map(async (cell) => {\n const isHealthy = await this.checkCellHealth(cell);\n cell.healthy = isHealthy;\n return { cell, isHealthy };\n });\n\n const results = await Promise.all(healthPromises);\n\n if (this.activeCell && !this.activeCell.healthy) {\n logger.warn('Active cell unhealthy, selecting new cell');\n await this.selectOptimalCell();\n }\n\n logger.debug('Health check results:', results);\n }\n\n private async checkCellHealth(cell: CellEndpoint): Promise<boolean> {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 3000);\n\n const response = await fetch(`${cell.url}/health`, {\n method: 'GET',\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n return response.ok;\n } catch (error) {\n return false;\n }\n }\n\n async send(events: AegisEvent[], options: SendOptions = {}): Promise<SendResult> {\n if (events.length === 0) {\n return { success: true };\n }\n\n const endpoint = this.getActiveEndpoint();\n\n // Requests of at most MAX_BATCH_EVENTS, in order. After the first refused\n // chunk the rest are not tried (the gateway is refusing: back off), and are\n // reported unaccepted with it.\n if (events.length > MAX_BATCH_EVENTS) {\n let last: SendResult = { success: true, endpoint };\n for (let i = 0; i < events.length; i += MAX_BATCH_EVENTS) {\n const chunk = events.slice(i, i + MAX_BATCH_EVENTS);\n last = await this.sendChunk(endpoint, chunk, options);\n if (!last.success) {\n const rejected = [...(last.rejected ?? chunk), ...events.slice(i + MAX_BATCH_EVENTS)];\n return { ...last, success: false, rejected };\n }\n }\n return last;\n }\n return this.sendChunk(endpoint, events, options);\n }\n\n /**\n * One request (<= MAX_BATCH_EVENTS). Halved, never dropped, when:\n * - it is a keepalive request whose body is over KEEPALIVE_BODY_MAX_BYTES\n * (split before sending; the browser would refuse it);\n * - the gateway answers 413;\n * - a keepalive request over KEEPALIVE_SPLIT_ON_ZERO_BYTES fails with\n * status 0 (a browser quota refusal looks like a network error);\n * - the gateway answers 400 and `splitOnBadRequest` is set.\n */\n private async sendChunk(\n endpoint: string,\n events: AegisEvent[],\n options: SendOptions\n ): Promise<SendResult> {\n const keepalive = options.keepalive !== false;\n const bytes = keepalive ? utf8Bytes(JSON.stringify(this.buildPayload(events))) : 0;\n const oversize = keepalive && bytes > KEEPALIVE_BODY_MAX_BYTES;\n if (oversize && events.length > 1) {\n return this.sendHalves(endpoint, events, options, 'keepalive body over 60 KB');\n }\n // A single event too big for keepalive goes without it.\n const sendOpts = oversize ? { ...options, keepalive: false } : options;\n const result = await this.sendOne(endpoint, events, sendOpts);\n if (result.success) return result;\n const status = result.status;\n const splittable =\n status === 413 ||\n (status === 0 && sendOpts.keepalive !== false && bytes > KEEPALIVE_SPLIT_ON_ZERO_BYTES) ||\n (status === 400 && options.splitOnBadRequest === true);\n if (!splittable) return result;\n if (events.length <= 1) {\n // One event refused on its own (400 / 413): resending cannot help.\n if (status === 400 || status === 413) {\n return { ...result, rejected: events, terminalEvent: events[0] };\n }\n return result;\n }\n return this.sendHalves(endpoint, events, options, `HTTP ${status}`);\n }\n\n private async sendHalves(\n endpoint: string,\n events: AegisEvent[],\n options: SendOptions,\n why: string\n ): Promise<SendResult> {\n const mid = Math.ceil(events.length / 2);\n const head = events.slice(0, mid);\n const tail = events.slice(mid);\n logger.warn(`Batch of ${events.length} split (${why}); sending halves of ${head.length} and ${tail.length}`);\n const first = await this.sendChunk(endpoint, head, options);\n if (!first.success) {\n return { ...first, success: false, rejected: [...(first.rejected ?? head), ...tail] };\n }\n const second = await this.sendChunk(endpoint, tail, options);\n if (!second.success) {\n return { ...second, success: false, rejected: second.rejected ?? tail };\n }\n return second;\n }\n\n private async sendOne(\n endpoint: string,\n events: AegisEvent[],\n options: SendOptions\n ): Promise<SendResult> {\n const payload = this.buildPayload(events);\n\n logger.debug('Sending batch:', { endpoint, eventCount: events.length });\n\n const keepalive = options.keepalive !== false;\n\n if (options.confirmDelivery) {\n // One fetch; the caller re-tries (see SendOptions).\n return this.sendViaFetch(endpoint, payload, this.config.maxRetries, keepalive);\n }\n\n if (!keepalive) {\n return this.sendViaFetch(endpoint, payload, 1, false);\n }\n\n if (document.visibilityState === 'hidden' && typeof navigator.sendBeacon === 'function') {\n const result = this.sendViaBeacon(endpoint, payload);\n return Promise.resolve(result);\n } else {\n return this.sendViaFetch(endpoint, payload);\n }\n }\n\n private getActiveEndpoint(): string {\n if (this.activeCell) {\n return `${this.activeCell.url}/v1/batch`;\n }\n\n if (this.config.apiHost) {\n return `${this.config.apiHost}/v1/batch`;\n }\n\n throw new Error('No active endpoint available');\n }\n\n private buildPayload(events: AegisEvent[]): BatchPayload {\n return {\n batch: events,\n sentAt: new Date().toISOString(),\n writeKey: this.config.writeKey,\n context: this.activeCell\n ? {\n cell: {\n region: this.activeCell.region,\n endpoint: this.activeCell.url,\n },\n }\n : undefined,\n };\n }\n\n private sendViaBeacon(endpoint: string, payload: BatchPayload): SendResult | Promise<SendResult> {\n try {\n const blob = new Blob([JSON.stringify(payload)], {\n type: 'application/json',\n });\n\n const sent = navigator.sendBeacon(endpoint, blob);\n\n if (sent) {\n logger.debug('Batch sent via Beacon');\n return { success: true, endpoint };\n } else {\n logger.warn('Beacon send failed, falling back to fetch');\n return this.sendViaFetch(endpoint, payload);\n }\n } catch (error) {\n logger.error('Beacon send error:', error);\n return {\n success: false,\n error: error as Error,\n endpoint,\n };\n }\n }\n\n private async sendViaFetch(\n endpoint: string,\n payload: BatchPayload,\n attempt: number = 1,\n keepalive: boolean = true\n ): Promise<SendResult> {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n this.config.requestTimeout\n );\n\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.config.writeKey}`,\n },\n body: JSON.stringify(payload),\n keepalive,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (response.ok) {\n const result: BatchResponse = await response.json();\n logger.debug('Batch sent successfully:', result);\n return { success: true, response: result, endpoint };\n } else {\n const errorText = await response.text();\n const error = new Error(\n `HTTP ${response.status}: ${errorText || response.statusText}`\n );\n\n logger.error('Batch send failed:', error);\n\n const retryAfterMs = parseRetryAfterMs(response.headers?.get?.('Retry-After'));\n if (this.shouldRetry(response.status, attempt)) {\n return this.retryRequest(endpoint, payload, attempt, retryAfterMs, keepalive);\n }\n\n // Not the end of the events: the queue keeps them (purchases in their\n // own backlog that re-tries until accepted, queue.ts).\n return {\n success: false,\n error,\n endpoint,\n status: response.status,\n retryAfterMs,\n };\n }\n } catch (error) {\n logger.error('Fetch error:', error);\n\n if (this.shouldRetry(0, attempt)) {\n return this.retryRequest(endpoint, payload, attempt, undefined, keepalive);\n }\n\n return {\n success: false,\n error: error as Error,\n endpoint,\n status: 0,\n };\n }\n }\n\n private shouldRetry(statusCode: number, attempt: number): boolean {\n if (!this.config.retryFailedRequests) {\n return false;\n }\n\n if (attempt >= this.config.maxRetries) {\n return false;\n }\n\n if (statusCode === 0) {\n return true;\n }\n\n return statusCode >= 500 || statusCode === 429;\n }\n\n private async retryRequest(\n endpoint: string,\n payload: BatchPayload,\n attempt: number,\n retryAfterMs?: number,\n keepalive: boolean = true\n ): Promise<SendResult> {\n // At least the server's Retry-After (the per-visitor 429,\n // GATEWAY_SDK_RATE_LIMITS.md): an earlier try is refused again.\n const delay = Math.max(\n Math.pow(this.config.retryBackoffMultiplier, attempt) * 1000,\n retryAfterMs ?? 0\n );\n\n logger.info(`Retrying request in ${delay}ms (attempt ${attempt + 1})`);\n\n await new Promise((resolve) => setTimeout(resolve, delay));\n\n return this.sendViaFetch(endpoint, payload, attempt + 1, keepalive);\n }\n\n getActiveCell(): CellEndpoint | null {\n return this.activeCell;\n }\n\n getRegionLatencies(): Map<string, number> {\n return new Map(this.regionLatencyMap);\n }\n\n destroy(): void {\n if (this.healthCheckInterval) {\n clearInterval(this.healthCheckInterval);\n this.healthCheckInterval = null;\n }\n }\n}\n","/**\n * PURCHASE BACKLOG (Aman 11-02, Q13 / WP19 SDK half): the SDK never drops a\n * purchase event except under the bounds below, each one logged and counted.\n *\n * Durable first. A purchase (purchase-events.ts) is written to localStorage\n * BEFORE the first send, so a reload, a closed tab or a crash mid-send loses\n * nothing; the next page load re-sends it.\n *\n * Sending.\n * - A live page drains with a NON-keepalive fetch (a keepalive body over\n * 64 KB is refused by the browser), at most PURCHASE_SEND_CHUNK events a\n * request, and never via `sendBeacon` (that only says \"queued\").\n * - On unload (`flushOnUnload`, called synchronously from pagehide /\n * visibilitychange / beforeunload) one keepalive fetch starts before the\n * handler returns, carrying only the purchases that fit in\n * KEEPALIVE_BODY_MAX_BYTES. The rest stay on disk for the next load.\n * - Re-tried until a 2xx: 1 s to 60 s jittered backoff, never sooner than the\n * gateway's `Retry-After` (the per-visitor 429), an immediate try on\n * `online` and on every page load. A 429 is never the end of a purchase.\n * - The transport halves a request on 413, on 400 (`splitOnBadRequest`) and\n * on an oversize keepalive body; only events without a 2xx are kept.\n *\n * Several tabs. Every write re-reads localStorage and merges by messageId:\n * the union of the stored and in-memory purchases, minus every id any tab has\n * SETTLED (got a 2xx for, or terminally refused). Settled ids are kept for\n * SETTLED_RETENTION_MS so a slower tab never writes a sent purchase back.\n *\n * Re-sends are at-least-once by design. The cell consumer claims each\n * purchase once (event_engine/consumer.py `order_dedup_key(ENGINE_TXN, ...)`):\n * on its order natural key for 24 h, and, when the event names no order, on\n * the SDK messageId (gateway -> `external_event_id`) for 8 days, longer than\n * MAX_PURCHASE_AGE_MS, so a re-sent purchase is dropped there, not counted\n * twice.\n *\n * THE BOUNDS (each eviction is `logger.error` + a counter, never silent):\n * - COUNT: MAX_PURCHASE_BACKLOG (200) per tenant per browser. A shopper places\n * about one order a visit; 200 unsent in ONE browser is a host loop or a key\n * refused for days. At ~2-4 KB an event that is 0.4-0.8 MB of the origin's\n * ~5 MB localStorage. The oldest goes first (`droppedOverBound`).\n * - AGE: MAX_PURCHASE_AGE_MS (7 days) from the event's own timestamp\n * (`droppedExpired`).\n * - TERMINAL: one event the gateway refuses on its own (400, or 413 at a\n * single event): resending cannot succeed, and it must not block the rest\n * (`droppedTerminal`).\n *\n * A REFUSED KEY (401/403) is a key-level problem, not an event-level one, so\n * it evicts NOTHING (Aman: purchases are never dropped). Drains for this\n * write key pause for AUTH_PAUSE_BASE_MS (5 min), doubling per refusal up to\n * AUTH_PAUSE_MAX_MS (1 h); the pause is persisted, so a reload honours it.\n * Each refusal is a warning and is counted (`authPaused`). The next 2xx\n * clears the pause. During a pause two sends still get ONE try each: the\n * unload send and the first send after a NEW purchase is added. A 2xx clears\n * the pause; a refusal keeps it as it is.\n *\n * A gateway answering 400 to everything must not empty the backlog through\n * the terminal path: after MAX_TERMINAL_STREAK (3) single-event refusals in a\n * row with no 2xx between, no further event is evicted; drains pause instead\n * (the same persisted pause) and an error is logged.\n *\n * A changed write key. The backlog is scoped by a hash of the write key, so a\n * purchase is never sent with another tenant's key. A backlog left under a\n * DIFFERENT key on this origin is not adopted (it could be another brand);\n * it stays on disk, is sent if that key loads again, and is counted at load\n * (`orphaned`) with a warning.\n */\nimport type { AegisEvent } from '../types/events';\nimport type { Transport } from './transport';\nimport { KEEPALIVE_BODY_MAX_BYTES, utf8Bytes } from './transport';\nimport { logger } from '../utils/logger';\nimport { redactMetaCookies } from '../utils/meta-cookies';\n\nexport const MAX_PURCHASE_BACKLOG = 200;\nexport const MAX_PURCHASE_AGE_MS = 7 * 24 * 60 * 60 * 1000;\n/** Purchases per request while a live page drains the backlog. */\nexport const PURCHASE_SEND_CHUNK = 50;\nexport const PURCHASE_RETRY_BASE_MS = 1000;\nexport const PURCHASE_RETRY_MAX_MS = 60_000;\n/** Settled ids are remembered this long (past MAX_PURCHASE_AGE_MS). */\nexport const SETTLED_RETENTION_MS = 8 * 24 * 60 * 60 * 1000;\nconst SETTLED_MAX = 2000;\nexport const PURCHASE_BACKLOG_PREFIX = 'aegis_purchase_backlog:v1:';\n/** Room left in a keepalive body for the batch envelope (writeKey, sentAt, context). */\nconst ENVELOPE_BYTES = 2_000;\nexport const AUTH_PAUSE_BASE_MS = 5 * 60 * 1000;\nexport const AUTH_PAUSE_MAX_MS = 60 * 60 * 1000;\n\n/** Terminal (single-event 400/413) evictions in a row before evicting stops. */\nexport const MAX_TERMINAL_STREAK = 3;\n\ninterface AuthPause {\n until: number;\n level: number;\n /** The terminal streak when the pause was set (a reload keeps it). */\n streak?: number;\n}\n\n/** Short stable hash so the write key itself is not spelled into a storage key. */\nexport function fnv1a(input: string): string {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193) >>> 0;\n }\n return h.toString(16);\n}\n\nexport function purchaseBacklogKey(namespace?: string): string {\n return PURCHASE_BACKLOG_PREFIX + (namespace ? fnv1a(namespace) : 'default');\n}\n\ninterface Stored {\n events: AegisEvent[];\n settled: Record<string, number>;\n}\n\nexport interface PurchaseDropCounts {\n overBound: number;\n expired: number;\n terminal: number;\n}\n\nfunction idOf(e: AegisEvent): string {\n return (e as { messageId?: string }).messageId || '';\n}\n\nfunction eventTime(e: AegisEvent, now: number): number {\n const t = Date.parse((e as { timestamp?: string }).timestamp || '');\n return Number.isNaN(t) ? now : t;\n}\n\nexport class PurchaseBacklog {\n private events: AegisEvent[] = [];\n private settled = new Map<string, number>();\n private inFlight = false;\n private attempt = 0;\n private timer: ReturnType<typeof setTimeout> | null = null;\n private destroyed = false;\n private readonly key: string;\n readonly dropped: PurchaseDropCounts = { overBound: 0, expired: 0, terminal: 0 };\n /** Purchases found under another write key's backlog on this origin at load. */\n orphaned = 0;\n /** 401/403 refusals of a purchase drain (each paused drains; nothing evicted). */\n authPaused = 0;\n /** Single-event refusals in a row with no 2xx between (MAX_TERMINAL_STREAK). */\n private terminalStreak = 0;\n /** A purchase was added: its first send may try once through a pause. */\n private bypassPauseOnce = false;\n\n constructor(private readonly transport: Transport, namespace?: string) {\n this.key = purchaseBacklogKey(namespace);\n this.terminalStreak = this.readAuthPause()?.streak ?? 0;\n this.countOrphans();\n this.persist();\n if (this.events.length > 0) {\n logger.info(`Loaded ${this.events.length} unsent purchase events`);\n this.retryNow();\n }\n }\n\n size(): number {\n return this.events.length;\n }\n\n totalDropped(): number {\n return this.dropped.overBound + this.dropped.expired + this.dropped.terminal;\n }\n\n add(event: AegisEvent): void {\n const id = idOf(event);\n if (id && (this.settled.has(id) || this.events.some((e) => idOf(e) === id))) return;\n this.events.push(event);\n this.persist();\n this.bypassPauseOnce = true;\n this.retryNow();\n }\n\n /** Cancel any pending backoff and try on the next tick (live page). */\n retryNow(): void {\n if (this.destroyed || this.events.length === 0) return;\n this.clearTimer();\n this.attempt = 0;\n this.schedule(0);\n }\n\n /**\n * Called SYNCHRONOUSLY from an unload handler: the keepalive fetch starts\n * before this returns (timers do not run after pagehide). Sends only what\n * fits in one keepalive body; the rest stay on disk for the next load.\n */\n flushOnUnload(): void {\n if (this.events.length === 0) return;\n // The live retry timer is kept: `visibilitychange: hidden` is not always\n // an unload, and a page that comes back must keep draining.\n void this.drain(true);\n }\n\n /** Forget every held purchase (an explicit embedder wipe). */\n clear(): void {\n for (const e of this.events) this.settle(idOf(e));\n this.events = [];\n this.clearTimer();\n this.persist();\n }\n\n destroy(): void {\n this.flushOnUnload();\n this.clearTimer();\n this.destroyed = true;\n }\n\n static retryDelayMs(attempt: number, retryAfterMs?: number, jitter: number = Math.random()): number {\n const exp = Math.min(PURCHASE_RETRY_MAX_MS, PURCHASE_RETRY_BASE_MS * Math.pow(2, Math.max(0, attempt - 1)));\n return Math.max(Math.round(exp * (0.8 + 0.4 * jitter)), retryAfterMs ?? 0);\n }\n\n /** Send one request's worth; keep every purchase until a 2xx accepts it. */\n async drain(unloading: boolean = false): Promise<void> {\n if (this.events.length === 0) return;\n if (this.inFlight && !unloading) return;\n const pause = this.readAuthPause();\n const paused = !!pause && Date.now() < pause.until;\n if (paused && !unloading && !this.bypassPauseOnce) {\n // Wait out the pause (persisted across reloads).\n this.schedule(pause!.until - Date.now());\n return;\n }\n // The unload send and a new purchase's first send try once through it.\n if (!unloading) this.bypassPauseOnce = false;\n const chunk = unloading ? this.unloadChunk() : this.events.slice(0, PURCHASE_SEND_CHUNK);\n if (chunk.length === 0) return;\n if (!unloading) this.inFlight = true;\n\n let success = false;\n let retryAfterMs: number | undefined;\n let accepted: AegisEvent[] = [];\n const terminal: AegisEvent[] = [];\n let keyRefused = false;\n let streakPause = false;\n try {\n // The fetch is issued synchronously inside this call, before its first await.\n const result = await this.transport.send(chunk, {\n confirmDelivery: true,\n keepalive: unloading,\n splitOnBadRequest: true,\n });\n success = result.success;\n retryAfterMs = result.retryAfterMs;\n if (success) {\n accepted = chunk;\n } else {\n // Matched by messageId (persist() may have swapped in stored copies).\n const left = new Set((result.rejected ?? chunk).map(idOf));\n accepted = chunk.filter((e) => !left.has(idOf(e)));\n if (result.terminalEvent) {\n if (this.terminalStreak >= MAX_TERMINAL_STREAK) {\n // Too many single-event refusals in a row: a gateway answering\n // 400 to everything. Stop evicting; pause instead.\n streakPause = true;\n } else {\n terminal.push(result.terminalEvent);\n }\n } else if (result.status === 401 || result.status === 403) {\n keyRefused = true;\n }\n logger.warn(`Purchase send not accepted (status ${result.status ?? 'n/a'}); kept for retry`, result.error);\n }\n } catch (error) {\n logger.warn('Purchase send error; kept for retry:', error);\n } finally {\n if (!unloading) this.inFlight = false;\n }\n\n for (const e of terminal) {\n this.dropped.terminal += 1;\n logger.error('Purchase refused by the gateway and cannot succeed on retry; evicted', redactMetaCookies(e));\n }\n const done = [...accepted, ...terminal];\n if (done.length > 0) {\n const ids = new Set(done.map(idOf));\n for (const id of ids) this.settle(id);\n this.events = this.events.filter((e) => !ids.has(idOf(e)));\n this.persist();\n }\n if (accepted.length > 0) this.terminalStreak = 0;\n this.terminalStreak += terminal.length;\n if (success) this.clearAuthPause();\n if (keyRefused || streakPause) {\n const prev = this.readAuthPause();\n let wait: number;\n if (prev && Date.now() < prev.until) {\n // A refusal during the pause (a bypass try) keeps it as it is.\n wait = prev.until - Date.now();\n } else {\n const level = prev ? prev.level + 1 : 0;\n wait = Math.min(AUTH_PAUSE_MAX_MS, AUTH_PAUSE_BASE_MS * Math.pow(2, level));\n this.writeAuthPause({ until: Date.now() + wait, level, streak: this.terminalStreak });\n }\n this.authPaused += 1;\n if (streakPause) {\n logger.error(\n `Purchase drain: ${MAX_TERMINAL_STREAK}+ events refused in a row (400/413); evicting stopped, ` +\n `pausing ${Math.round(wait / 60000)} min`\n );\n } else {\n logger.warn(\n `Purchase drain refused (key rejected, 401/403); nothing evicted, pausing ${Math.round(wait / 60000)} min`\n );\n }\n if (!unloading && !this.destroyed) this.schedule(wait);\n return;\n }\n if (unloading || this.destroyed) return;\n\n if (success || terminal.length > 0) {\n // Progress: keep draining at once.\n this.attempt = 0;\n if (this.events.length > 0) this.schedule(0);\n return;\n }\n this.attempt += 1;\n this.schedule(PurchaseBacklog.retryDelayMs(this.attempt, retryAfterMs));\n }\n\n // ── internals ───────────────────────────────────────────────────────────\n\n /** The oldest purchases whose batch body fits one keepalive request. */\n private unloadChunk(): AegisEvent[] {\n const out: AegisEvent[] = [];\n let bytes = ENVELOPE_BYTES;\n for (const e of this.events) {\n const b = utf8Bytes(JSON.stringify(e)) + 1;\n if (bytes + b > KEEPALIVE_BODY_MAX_BYTES) break;\n out.push(e);\n bytes += b;\n if (out.length >= PURCHASE_SEND_CHUNK) break;\n }\n return out;\n }\n\n private readAuthPause(): AuthPause | null {\n try {\n if (typeof localStorage === 'undefined') return null;\n const raw = localStorage.getItem(`${this.key}:auth_pause`);\n if (!raw) return null;\n const p = JSON.parse(raw) as Partial<AuthPause>;\n return typeof p.until === 'number' && typeof p.level === 'number' ? (p as AuthPause) : null;\n } catch {\n return null;\n }\n }\n\n private writeAuthPause(p: AuthPause): void {\n try {\n if (typeof localStorage !== 'undefined') localStorage.setItem(`${this.key}:auth_pause`, JSON.stringify(p));\n } catch {\n // blocked storage: the in-page schedule still waits\n }\n }\n\n private clearAuthPause(): void {\n try {\n if (typeof localStorage !== 'undefined') localStorage.removeItem(`${this.key}:auth_pause`);\n } catch {\n // blocked storage\n }\n }\n\n private schedule(delayMs: number): void {\n if (this.destroyed || this.timer) return;\n this.timer = setTimeout(() => {\n this.timer = null;\n void this.drain(false);\n }, delayMs);\n }\n\n private clearTimer(): void {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n private settle(id: string): void {\n if (id) this.settled.set(id, Date.now());\n }\n\n private read(): Stored {\n try {\n if (typeof localStorage === 'undefined') return { events: [], settled: {} };\n const raw = localStorage.getItem(this.key);\n if (!raw) return { events: [], settled: {} };\n const parsed = JSON.parse(raw) as unknown;\n if (Array.isArray(parsed)) return { events: parsed as AegisEvent[], settled: {} };\n const obj = (parsed || {}) as Partial<Stored>;\n return {\n events: Array.isArray(obj.events) ? obj.events : [],\n settled: obj.settled && typeof obj.settled === 'object' ? obj.settled : {},\n };\n } catch (error) {\n logger.warn('Failed to read purchase backlog:', error);\n return { events: [], settled: {} };\n }\n }\n\n /**\n * Merge with what other tabs wrote, apply the bounds, write back. The\n * union of events by messageId, minus every id any tab has settled.\n */\n private persist(): void {\n const now = Date.now();\n const stored = this.read();\n for (const [id, t] of Object.entries(stored.settled)) {\n if (typeof t === 'number' && (this.settled.get(id) ?? 0) < t) this.settled.set(id, t);\n }\n for (const [id, t] of this.settled) {\n if (now - t > SETTLED_RETENTION_MS) this.settled.delete(id);\n }\n if (this.settled.size > SETTLED_MAX) {\n const newest = [...this.settled.entries()].sort((a, b) => b[1] - a[1]).slice(0, SETTLED_MAX);\n this.settled = new Map(newest);\n }\n\n const byId = new Map<string, AegisEvent>();\n const anon: AegisEvent[] = [];\n // In-memory copies first, so the objects a send is holding stay the ones kept.\n for (const e of [...this.events, ...stored.events]) {\n if (!e || typeof e !== 'object') continue;\n const id = idOf(e);\n if (!id) {\n anon.push(e);\n continue;\n }\n if (this.settled.has(id) || byId.has(id)) continue;\n byId.set(id, e);\n }\n let merged = [...byId.values(), ...anon].sort((a, b) => eventTime(a, now) - eventTime(b, now));\n\n const fresh: AegisEvent[] = [];\n for (const e of merged) {\n if (now - eventTime(e, now) > MAX_PURCHASE_AGE_MS) {\n this.dropped.expired += 1;\n this.settle(idOf(e));\n logger.error('Purchase older than 7 days never accepted; evicted', redactMetaCookies(e));\n } else {\n fresh.push(e);\n }\n }\n merged = fresh;\n while (merged.length > MAX_PURCHASE_BACKLOG) {\n const evicted = merged.shift()!;\n this.dropped.overBound += 1;\n this.settle(idOf(evicted));\n logger.error(\n `Purchase backlog past its bound (${MAX_PURCHASE_BACKLOG}); evicting the oldest purchase`,\n redactMetaCookies(evicted)\n );\n }\n this.events = merged;\n\n try {\n if (typeof localStorage === 'undefined') return;\n if (this.events.length === 0 && this.settled.size === 0) {\n localStorage.removeItem(this.key);\n return;\n }\n // Straight to localStorage, never Storage.set: that also writes a\n // cookie, and a purchase list must not ride every request header.\n const settled: Record<string, number> = {};\n for (const [id, t] of this.settled) settled[id] = t;\n localStorage.setItem(this.key, JSON.stringify({ events: this.events, settled }));\n } catch (error) {\n // Quota / blocked storage: still held in memory for this page's life.\n logger.warn('Failed to persist purchase backlog:', error);\n }\n }\n\n private countOrphans(): void {\n try {\n if (typeof localStorage === 'undefined') return;\n for (let i = 0; i < localStorage.length; i++) {\n const k = localStorage.key(i);\n if (!k || !k.startsWith(PURCHASE_BACKLOG_PREFIX) || k === this.key) continue;\n const raw = localStorage.getItem(k);\n const parsed = raw ? (JSON.parse(raw) as { events?: unknown[] } | unknown[]) : null;\n const list = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.events) ? parsed!.events! : [];\n this.orphaned += list.length;\n }\n if (this.orphaned > 0) {\n logger.warn(\n `${this.orphaned} unsent purchase(s) are held under another write key on this origin; ` +\n 'they are sent only when that key loads again'\n );\n }\n } catch {\n // unreadable: nothing to count\n }\n }\n}\n","import { AegisEvent } from '../types/events';\nimport { Transport } from './transport';\nimport { Storage } from '../utils/storage';\nimport { logger } from '../utils/logger';\nimport { redactMetaCookies } from '../utils/meta-cookies';\nimport { isPurchaseEvent } from './purchase-events';\nimport { PurchaseBacklog } from './purchase-backlog';\n\nexport interface QueueConfig {\n batchSize: number;\n batchInterval: number;\n enableOfflineMode: boolean;\n maxOfflineEvents: number;\n /**\n * Scopes the persisted purchase backlog to one tenant (the write key): a\n * purchase saved under one key is never sent with another. Optional so an\n * embedder that builds the queue directly keeps working (one shared slot).\n */\n persistNamespace?: string;\n}\n\n/**\n * Purchases never enter this queue's drop-oldest offline list: they go to the\n * PurchaseBacklog (purchase-backlog.ts), which holds them durably and re-tries\n * until the gateway accepts them. When the offline list is full it still\n * drops its oldest event, and it only ever holds NON-purchase events.\n *\n * No request carries more than 100 events (transport.ts MAX_BATCH_EVENTS, the\n * gateway's 413 cap) on any flush path. A 413 halves the request and is never\n * a failure that ends in drop-oldest; after a partial send only the events\n * without a 2xx (`SendResult.rejected`, client-side bookkeeping) are kept.\n */\nexport {\n MAX_PURCHASE_BACKLOG,\n MAX_PURCHASE_AGE_MS,\n PURCHASE_SEND_CHUNK,\n PURCHASE_RETRY_BASE_MS,\n PURCHASE_RETRY_MAX_MS,\n} from './purchase-backlog';\n\nexport class EventQueue {\n private buffer: AegisEvent[] = [];\n private config: QueueConfig;\n private transport: Transport;\n private storage: Storage;\n private flushInterval: number | null = null;\n private isFlushing: boolean = false;\n private offlineQueue: AegisEvent[] = [];\n private isOnline: boolean = navigator.onLine;\n /** Purchases not yet accepted by the gateway (purchase-backlog.ts). */\n private purchases: PurchaseBacklog;\n\n constructor(config: QueueConfig, transport: Transport, storage: Storage) {\n this.config = config;\n this.transport = transport;\n this.storage = storage;\n this.purchases = new PurchaseBacklog(transport, config.persistNamespace);\n\n if (config.enableOfflineMode) {\n this.loadOfflineQueue();\n this.setupOnlineListener();\n } else {\n this.setupPurchaseOnlineListener();\n }\n\n this.startFlushTimer();\n this.setupUnloadHandlers();\n }\n\n private loadOfflineQueue(): void {\n const offlineData = this.storage.get('offline_queue');\n\n if (!offlineData) {\n return;\n }\n\n try {\n const events = JSON.parse(offlineData) as AegisEvent[];\n\n if (Array.isArray(events) && events.length > 0) {\n // A queue saved by an older SDK may hold purchases: they move to the\n // purchase backlog, never into the drop-oldest queue.\n const rest = this.takePurchases(events);\n this.offlineQueue = rest.slice(0, this.config.maxOfflineEvents);\n logger.info(`Loaded ${this.offlineQueue.length} offline events`);\n\n if (this.isOnline) {\n this.flushOfflineQueue();\n }\n }\n } catch (error) {\n logger.warn('Failed to load offline queue:', error);\n this.storage.remove('offline_queue');\n }\n }\n\n private saveOfflineQueue(): void {\n if (this.offlineQueue.length === 0) {\n this.storage.remove('offline_queue');\n return;\n }\n\n try {\n const data = JSON.stringify(this.offlineQueue);\n this.storage.set('offline_queue', data);\n logger.debug(`Saved ${this.offlineQueue.length} events to offline queue`);\n } catch (error) {\n logger.warn('Failed to save offline queue:', error);\n }\n }\n\n private setupOnlineListener(): void {\n window.addEventListener('online', () => {\n logger.info('Connection restored');\n this.isOnline = true;\n this.purchases.retryNow();\n this.flushOfflineQueue();\n this.flush();\n });\n\n window.addEventListener('offline', () => {\n logger.warn('Connection lost, entering offline mode');\n this.isOnline = false;\n });\n }\n\n private async flushOfflineQueue(): Promise<void> {\n if (this.offlineQueue.length === 0) {\n return;\n }\n\n logger.info(`Flushing ${this.offlineQueue.length} offline events`);\n\n const events = [...this.offlineQueue];\n this.offlineQueue = [];\n this.storage.remove('offline_queue');\n\n const result = await this.transport.send(events);\n\n if (!result.success) {\n logger.warn('Failed to send offline events, re-queueing');\n // Only what the gateway did not accept (transport chunks of <= 100 and\n // 413 halves): an accepted chunk is never re-sent.\n const unaccepted = this.takePurchases(result.rejected ?? events);\n this.offlineQueue = [...unaccepted, ...this.offlineQueue].slice(\n 0,\n this.config.maxOfflineEvents\n );\n this.saveOfflineQueue();\n } else {\n logger.info('Offline events sent successfully');\n }\n }\n\n push(event: AegisEvent): void {\n if (isPurchaseEvent(event)) {\n // Persisted first, then sent: see purchase-backlog.ts.\n this.purchases.add(event);\n logger.debug('Purchase queued:', event.type, redactMetaCookies(event));\n return;\n }\n\n if (!this.isOnline && this.config.enableOfflineMode) {\n this.addToOfflineQueue(event);\n return;\n }\n\n this.buffer.push(event);\n logger.debug('Event queued:', event.type, redactMetaCookies(event));\n\n if (this.buffer.length >= this.config.batchSize) {\n this.flush();\n }\n }\n\n private addToOfflineQueue(event: AegisEvent): void {\n if (isPurchaseEvent(event)) {\n this.purchases.add(event);\n return;\n }\n // Only non-purchase events live here, so the oldest dropped is never a\n // purchase.\n if (this.offlineQueue.length >= this.config.maxOfflineEvents) {\n logger.warn('Offline queue full, dropping oldest event');\n this.offlineQueue.shift();\n }\n\n this.offlineQueue.push(event);\n this.saveOfflineQueue();\n logger.debug('Event added to offline queue');\n }\n\n async flush(): Promise<void> {\n if (this.isFlushing) {\n logger.debug('Flush already in progress, skipping');\n return;\n }\n\n if (this.buffer.length === 0) {\n return;\n }\n\n this.isFlushing = true;\n\n // Purchases never ride the drop-oldest path (defensive: push() already\n // routes them to the backlog).\n const events = this.takePurchases([...this.buffer]);\n this.buffer = [];\n if (events.length === 0) {\n this.isFlushing = false;\n return;\n }\n\n logger.info(`Flushing ${events.length} events`);\n\n try {\n const result = await this.transport.send(events);\n\n if (!result.success) {\n logger.error('Failed to send events:', result.error);\n // Only what the gateway did not accept (see flushOfflineQueue).\n const unaccepted = result.rejected ?? events;\n\n if (this.config.enableOfflineMode) {\n this.offlineQueue = [...this.offlineQueue, ...unaccepted].slice(\n 0,\n this.config.maxOfflineEvents\n );\n this.saveOfflineQueue();\n logger.info('Events saved to offline queue');\n } else {\n this.buffer.unshift(...unaccepted);\n logger.warn('Events re-queued for retry');\n }\n } else {\n logger.info('Events sent successfully');\n }\n } catch (error) {\n logger.error('Flush error:', error);\n\n if (this.config.enableOfflineMode) {\n this.offlineQueue = [...this.offlineQueue, ...events].slice(\n 0,\n this.config.maxOfflineEvents\n );\n this.saveOfflineQueue();\n }\n } finally {\n this.isFlushing = false;\n }\n }\n\n private startFlushTimer(): void {\n if (this.flushInterval) {\n clearInterval(this.flushInterval);\n }\n\n this.flushInterval = window.setInterval(() => {\n this.flush();\n }, this.config.batchInterval);\n\n logger.debug(\n `Flush timer started with interval: ${this.config.batchInterval}ms`\n );\n }\n\n private setupUnloadHandlers(): void {\n const flushBeforeUnload = () => {\n // The backlog is already on disk. One keepalive fetch, started\n // SYNCHRONOUSLY here: timers never run after pagehide.\n this.purchases.flushOnUnload();\n if (this.buffer.length > 0 || this.offlineQueue.length > 0) {\n this.persistBufferToOfflineQueue();\n this.flush();\n }\n };\n\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'hidden') {\n flushBeforeUnload();\n }\n });\n\n window.addEventListener('beforeunload', flushBeforeUnload);\n\n window.addEventListener('pagehide', flushBeforeUnload);\n }\n\n private persistBufferToOfflineQueue(): void {\n if (this.buffer.length === 0) {\n return;\n }\n\n if (this.config.enableOfflineMode) {\n const rest = this.takePurchases([...this.buffer]);\n this.offlineQueue = [...this.offlineQueue, ...rest].slice(\n 0,\n this.config.maxOfflineEvents\n );\n this.saveOfflineQueue();\n logger.debug('Buffer persisted to offline queue before unload');\n }\n }\n\n // ── purchase backlog ────────────────────────────────────────────────────\n\n /** Move every purchase in `events` to the backlog; return the rest. */\n private takePurchases(events: AegisEvent[]): AegisEvent[] {\n const rest: AegisEvent[] = [];\n for (const e of events) {\n if (isPurchaseEvent(e)) this.purchases.add(e);\n else rest.push(e);\n }\n return rest;\n }\n\n private setupPurchaseOnlineListener(): void {\n if (typeof window === 'undefined') return;\n window.addEventListener('online', () => {\n this.isOnline = true;\n this.purchases.retryNow();\n });\n }\n\n /** Send the backlog now (one request's worth; re-tries are scheduled). */\n flushPurchases(): Promise<void> {\n return this.purchases.drain(false);\n }\n\n /** Backoff before purchase try `attempt` (1-based), honouring Retry-After. */\n static purchaseRetryDelayMs(attempt: number, retryAfterMs?: number, jitter: number = Math.random()): number {\n return PurchaseBacklog.retryDelayMs(attempt, retryAfterMs, jitter);\n }\n\n getPurchaseBacklogSize(): number {\n return this.purchases.size();\n }\n\n /** Purchases evicted under a bound this page life (0 in normal use). */\n getDroppedPurchaseCount(): number {\n return this.purchases.totalDropped();\n }\n\n /** 401/403 refusals that paused purchase drains (nothing is evicted for them). */\n getAuthPausedCount(): number {\n return this.purchases.authPaused;\n }\n\n /** Purchases held under another write key's backlog on this origin. */\n getOrphanedPurchaseCount(): number {\n return this.purchases.orphaned;\n }\n\n getQueueSize(): number {\n return this.buffer.length;\n }\n\n getOfflineQueueSize(): number {\n return this.offlineQueue.length;\n }\n\n /**\n * Forget everything queued, purchases included. An explicit wipe by the\n * embedder (no SDK path calls it): the only way a held purchase is removed\n * without a 2xx, besides the MAX_PURCHASE_BACKLOG eviction.\n */\n clear(): void {\n this.buffer = [];\n this.offlineQueue = [];\n this.storage.remove('offline_queue');\n this.purchases.clear();\n logger.info('Queue cleared');\n }\n\n destroy(): void {\n if (this.flushInterval) {\n clearInterval(this.flushInterval);\n this.flushInterval = null;\n }\n\n // One last keepalive try; the backlog stays on disk for the next load.\n this.purchases.destroy();\n\n this.flush();\n }\n}\n","const STORAGE_PREFIX = 'aegis_';\n\nexport interface StorageOptions {\n cookieDomain?: string | null;\n secureCookie?: boolean;\n crossDomain?: boolean;\n}\n\nexport class Storage {\n private useLocalStorage: boolean;\n private options: StorageOptions;\n\n constructor(options: StorageOptions = {}) {\n this.options = options;\n this.useLocalStorage = this.isLocalStorageAvailable();\n }\n\n private isLocalStorageAvailable(): boolean {\n try {\n const test = '__aegis_test__';\n localStorage.setItem(test, test);\n localStorage.removeItem(test);\n return true;\n } catch {\n return false;\n }\n }\n\n set(key: string, value: string, expiryDays: number = 365): void {\n const fullKey = STORAGE_PREFIX + key;\n\n if (this.useLocalStorage) {\n try {\n const item = {\n value,\n expiry: Date.now() + expiryDays * 24 * 60 * 60 * 1000,\n };\n localStorage.setItem(fullKey, JSON.stringify(item));\n } catch (error) {\n console.warn('[Active Reach Storage] localStorage.setItem failed:', error);\n }\n }\n\n this.setCookie(fullKey, value, expiryDays);\n }\n\n get(key: string): string | null {\n const fullKey = STORAGE_PREFIX + key;\n\n if (this.useLocalStorage) {\n try {\n const itemStr = localStorage.getItem(fullKey);\n if (itemStr) {\n const item = JSON.parse(itemStr);\n if (Date.now() < item.expiry) {\n return item.value;\n } else {\n localStorage.removeItem(fullKey);\n }\n }\n } catch (error) {\n console.warn('[Active Reach Storage] localStorage.getItem failed:', error);\n }\n }\n\n return this.getCookie(fullKey);\n }\n\n remove(key: string): void {\n const fullKey = STORAGE_PREFIX + key;\n\n if (this.useLocalStorage) {\n try {\n localStorage.removeItem(fullKey);\n } catch (error) {\n console.warn('[Active Reach Storage] localStorage.removeItem failed:', error);\n }\n }\n\n this.deleteCookie(fullKey);\n }\n\n clear(): void {\n if (this.useLocalStorage) {\n try {\n const keys = Object.keys(localStorage);\n keys.forEach((key) => {\n if (key.startsWith(STORAGE_PREFIX)) {\n localStorage.removeItem(key);\n }\n });\n } catch (error) {\n console.warn('[Active Reach Storage] localStorage.clear failed:', error);\n }\n }\n\n const cookies = document.cookie.split(';');\n cookies.forEach((cookie) => {\n const key = cookie.split('=')[0].trim();\n if (key.startsWith(STORAGE_PREFIX)) {\n this.deleteCookie(key);\n }\n });\n }\n\n private setCookie(name: string, value: string, days: number): void {\n try {\n const date = new Date();\n date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);\n const expires = `expires=${date.toUTCString()}`;\n \n let cookieStr = `${name}=${value};${expires};path=/`;\n \n if (this.options.secureCookie && window.location.protocol === 'https:') {\n cookieStr += ';Secure';\n }\n \n cookieStr += ';SameSite=Lax';\n \n if (this.options.cookieDomain) {\n cookieStr += `;domain=${this.options.cookieDomain}`;\n } else if (this.options.crossDomain) {\n const domain = this.getRootDomain();\n if (domain) {\n cookieStr += `;domain=${domain}`;\n }\n }\n \n document.cookie = cookieStr;\n } catch (error) {\n console.warn('[Active Reach Storage] setCookie failed:', error);\n }\n }\n\n private getCookie(name: string): string | null {\n try {\n const nameEQ = name + '=';\n const ca = document.cookie.split(';');\n \n for (let i = 0; i < ca.length; i++) {\n let c = ca[i];\n while (c.charAt(0) === ' ') {\n c = c.substring(1, c.length);\n }\n if (c.indexOf(nameEQ) === 0) {\n return c.substring(nameEQ.length, c.length);\n }\n }\n } catch (error) {\n console.warn('[Active Reach Storage] getCookie failed:', error);\n }\n \n return null;\n }\n\n private deleteCookie(name: string): void {\n try {\n let cookieStr = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/`;\n \n if (this.options.cookieDomain) {\n cookieStr += `;domain=${this.options.cookieDomain}`;\n } else if (this.options.crossDomain) {\n const domain = this.getRootDomain();\n if (domain) {\n cookieStr += `;domain=${domain}`;\n }\n }\n \n document.cookie = cookieStr;\n } catch (error) {\n console.warn('[Active Reach Storage] deleteCookie failed:', error);\n }\n }\n\n private getRootDomain(): string | null {\n try {\n const hostname = window.location.hostname;\n \n if (/^(\\d{1,3}\\.){3}\\d{1,3}$/.test(hostname)) {\n return null;\n }\n \n if (hostname === 'localhost') {\n return null;\n }\n \n const parts = hostname.split('.');\n \n if (parts.length <= 2) {\n return `.${hostname}`;\n }\n \n return `.${parts.slice(-2).join('.')}`;\n } catch (error) {\n console.warn('[Active Reach Storage] getRootDomain failed:', error);\n return null;\n }\n }\n}\n","/**\n * URL credential redaction — the browser-SDK layer (Aman 2026-09-13).\n *\n * A landing URL can carry a credential: `k` (one order's view key), `t` (the\n * server-verified landing token), `code` / `session_code` (claim codes),\n * `aegis_pair` (a device-pairing code) and `u` (a contact token). The SDK must\n * never SEND one of those values — not in a page object, an event property, a\n * beacon or a query string to our own API. What it sends instead is the key\n * with its value replaced by `REDACTED`, so the shape of the URL (and the fact\n * that a credential was present) survives while the secret does not.\n *\n * The server twin is `libs/data-governance/data_governance/credential_params.py`\n * (`CREDENTIAL_URL_PARAMS`, `REDACTED`). The two lists MUST stay identical; a\n * parity guard compares them. Change both in the same commit or neither.\n *\n * Deliberately NOT in the list: `aegis_code`. It is the attribution join key\n * (the short link's own code), not a credential — redacting it would sever\n * the link from the order it brought in.\n *\n * Reading is untouched. The SDK's own inbound param readers (`aegis_code`,\n * gclid / fbclid, utm, `aegis_pair` for pairing) still read `location.search`\n * directly; only what leaves the browser is redacted.\n *\n * Why a targeted regex and not `new URL()`: a URL round-trip re-encodes and\n * reorders the rest of the string, so the value we send would no longer be\n * the page the visitor was on. The regex touches only the credential values.\n *\n * What it does not see: a percent-encoded key (`%6B=` for `k`), a `;`\n * separator, or a key whose case differs (`K=`). The server list has the same\n * shape, so both layers agree on what counts as a match.\n */\n\nexport const CREDENTIAL_URL_PARAMS = [\n 't',\n 'k',\n 'code',\n 'session_code',\n 'aegis_pair',\n 'u',\n // The Shopify CarrierService callback token (2026-09-18). Server-to-server\n // today, so the SDK never sees one — it is here because the two lists are\n // ONE rule, and a list that is only correct for today's callers is not.\n 'carrier_token',\n] as const;\n\nexport const REDACTED = 'REDACTED';\n\n// Byte-identical to the server's rule (credential_params.py):\n// - a key counts ONLY when introduced by `?` or `&` — `utm_t=` is not `t=`,\n// and prose such as \"k=3 cakes\" (even at the start of a string) is untouched;\n// - the value stops at `& # whitespace \" ' < >`, so a URL inside JSON, HTML\n// or a sentence keeps its closing quote / bracket / following words (the\n// first cut used `[^&#]*` and swallowed `\"}` out of `{\"href\":\"…?k=9\"}`);\n// - an EMPTY value is left alone — there is nothing to hide.\n// Shared cases: libs/data-governance/tests/fixtures/credential_param_cases.json.\nconst CREDENTIAL_PARAM_PATTERN = new RegExp(\n `([?&])(${CREDENTIAL_URL_PARAMS.join('|')})=([^&#\\\\s\"'<>]+)`,\n 'g',\n);\n\n/**\n * Replace the value of every credential query param with `REDACTED`.\n * Idempotent, fragment-preserving, and it never throws: input it cannot\n * handle is returned unchanged.\n */\nexport function redactUrl(value: string): string {\n if (typeof value !== 'string' || value.length === 0) return value;\n try {\n return value.replace(CREDENTIAL_PARAM_PATTERN, `$1$2=${REDACTED}`);\n } catch {\n return value;\n }\n}\n\n/**\n * Walk plain objects / arrays and apply `redactUrl` to every string — the TS\n * twin of the server's `redact_credentials_deep` (same depth cap, 12).\n *\n * Added for the SERVER consumers of `channel.delivery.status_{cell}` (BK-87,\n * 2026-09-13): that topic is a dual-route that never passes the governance\n * engine, and its click/receipt payloads carry URLs (`metadata.original_url`,\n * `referrer`, provider echoes). analytics-consumer and event-ingress's\n * delivery-status bridge import THIS module by relative path, so there is one\n * TS rule, not a copy. Redacting per string value (before serialisation) keeps\n * JSON valid even when a value itself holds escaped JSON.\n *\n * Only plain objects and arrays are walked; anything else (Date, Buffer, class\n * instances) is returned as is.\n */\nexport function redactCredentialsDeep<T>(value: T, depth = 0): T {\n if (depth > 12) return value;\n if (typeof value === 'string') return redactUrl(value) as unknown as T;\n if (Array.isArray(value)) {\n return value.map((v: unknown) => redactCredentialsDeep(v, depth + 1)) as unknown as T;\n }\n if (value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype) {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n out[k] = redactCredentialsDeep(v, depth + 1);\n }\n return out as T;\n }\n return value;\n}\n","import { redactUrl } from './redact-url';\n\nexport interface UTMParams {\n source?: string;\n medium?: string;\n campaign?: string;\n term?: string;\n content?: string;\n name?: string;\n}\n\nexport function parseUTMParameters(url?: string): UTMParams {\n try {\n const searchParams = url\n ? new URL(url).searchParams\n : new URLSearchParams(window.location.search);\n\n const utm: UTMParams = {};\n\n const utmKeys: Array<keyof UTMParams> = [\n 'source',\n 'medium',\n 'campaign',\n 'term',\n 'content',\n 'name',\n ];\n\n utmKeys.forEach((key) => {\n const value = searchParams.get(`utm_${key}`);\n if (value) {\n utm[key] = value;\n }\n });\n\n return utm;\n } catch (error) {\n console.warn('[Active Reach URL Parser] parseUTMParameters failed:', error);\n return {};\n }\n}\n\nexport function parseQueryParameters(url?: string): Record<string, string> {\n try {\n const searchParams = url\n ? new URL(url).searchParams\n : new URLSearchParams(window.location.search);\n\n const params: Record<string, string> = {};\n\n searchParams.forEach((value, key) => {\n params[key] = value;\n });\n\n return params;\n } catch (error) {\n console.warn('[Active Reach URL Parser] parseQueryParameters failed:', error);\n return {};\n }\n}\n\n/**\n * The page's URL for REPORTING — so it is credential-redacted (`redactUrl`),\n * the canonical `<link>` included. No caller in the SDK today; redacted so a\n * future one cannot send a raw `?k=` / `?t=` by reaching for this helper.\n */\nexport function getCanonicalURL(): string {\n try {\n const canonical = document.querySelector('link[rel=\"canonical\"]');\n if (canonical && canonical.getAttribute('href')) {\n return redactUrl(canonical.getAttribute('href')!);\n }\n \n return redactUrl(window.location.href);\n } catch (error) {\n console.warn('[Active Reach URL Parser] getCanonicalURL failed:', error);\n return redactUrl(window.location.href);\n }\n}\n\nexport function stripQueryParameters(url: string): string {\n try {\n const urlObj = new URL(url);\n return `${urlObj.protocol}//${urlObj.host}${urlObj.pathname}`;\n } catch (error) {\n console.warn('[Active Reach URL Parser] stripQueryParameters failed:', error);\n return url;\n }\n}\n\nexport interface AdClickIDs {\n gclid?: string;\n /** Google click id for iOS app→web traffic (Apple ATT). NOT a gclid. */\n gbraid?: string;\n /** Google click id for iOS web→app traffic (Apple ATT). NOT a gclid. */\n wbraid?: string;\n fbclid?: string;\n msclkid?: string;\n ctwa_clid?: string;\n ttclid?: string;\n li_fat_id?: string;\n}\n\nexport function parseAdClickIDs(url?: string): AdClickIDs {\n try {\n const searchParams = url\n ? new URL(url).searchParams\n : new URLSearchParams(window.location.search);\n\n const adClickIDs: AdClickIDs = {};\n\n const clickIDKeys: Array<keyof AdClickIDs> = [\n 'gclid',\n 'gbraid',\n 'wbraid',\n 'fbclid',\n 'msclkid',\n 'ctwa_clid',\n 'ttclid',\n 'li_fat_id',\n ];\n\n clickIDKeys.forEach((key) => {\n const value = searchParams.get(key);\n if (value) {\n adClickIDs[key] = value;\n }\n });\n\n return adClickIDs;\n } catch (error) {\n console.warn('[Active Reach URL Parser] parseAdClickIDs failed:', error);\n return {};\n }\n}\n\nexport function hasAdClickIDs(adClickIDs: AdClickIDs): boolean {\n return Object.keys(adClickIDs).length > 0;\n}\n\n/**\n * Which Aegis send brought the visitor — the `aegis_*` params the short-link\n * redirect stamps from the LINK row (`link_shortener` `aegis_params`).\n *\n * `aegis_code` is the join key (the short link's own code); the send is then\n * `aegis_campaign` (campaign sends only) OR `aegis_journey` (journey sends —\n * order confirmation, delivery, win-back). Present only when the link row has\n * a value, so never assume `aegis_campaign` exists.\n *\n * Deliberately NOT read here:\n * - `utm_*` — the tenant's own / third-party analytics; never identifies an\n * Aegis send (a tenant-set utm can sit on our own link).\n * - `k` — a credential for ONE order. Never read, copied or logged.\n * - `t` — server-verified landing token; never parsed client-side.\n * - `u` — consumed at the redirect, never forwarded.\n */\nexport interface LinkAttribution {\n aegis_code?: string;\n aegis_campaign?: string;\n aegis_journey?: string;\n aegis_playbook?: string;\n aegis_button?: string;\n}\n\nconst LINK_ATTRIBUTION_KEYS: Array<keyof LinkAttribution> = [\n 'aegis_code',\n 'aegis_campaign',\n 'aegis_journey',\n 'aegis_playbook',\n 'aegis_button',\n];\n\n/**\n * Parse the landing URL's Aegis link attribution. Returns `{}` unless\n * `aegis_code` is present — the rest of the set only means something as the\n * attributes OF that code.\n */\nexport function parseLinkAttribution(url?: string): LinkAttribution {\n try {\n const searchParams = url\n ? new URL(url).searchParams\n : new URLSearchParams(window.location.search);\n\n if (!searchParams.get('aegis_code')) return {};\n\n const attribution: LinkAttribution = {};\n LINK_ATTRIBUTION_KEYS.forEach((key) => {\n const value = searchParams.get(key);\n if (value) {\n attribution[key] = value;\n }\n });\n return attribution;\n } catch (error) {\n console.warn('[Active Reach URL Parser] parseLinkAttribution failed:', error);\n return {};\n }\n}\n","import { EventContext } from '../types/events';\nimport { parseUTMParameters } from './url-parser';\nimport { redactUrl } from './redact-url';\nimport { AegisConfigInternal } from '../types/config';\nimport type { SessionManager } from '../core/session';\n\nexport function buildContext(config: AegisConfigInternal, session?: SessionManager): EventContext {\n const utm = config.capture_utm ? parseUTMParameters() : undefined;\n const device = detectDevice();\n const os = detectOS();\n const browser = detectBrowser();\n const network = detectNetworkInfo();\n\n const adClickIDs = session?.getAdClickIDs();\n // Redacted again on the way out, not only at capture: the landing page is\n // persisted for 365 days (`ad_landing_page`), so a value stored by an SDK\n // build that predates redaction would otherwise keep being sent.\n const storedLandingPage = session?.getLandingPage();\n const landingPage = storedLandingPage ? redactUrl(storedLandingPage) : undefined;\n\n return {\n library: {\n name: '@active-reach/web-sdk',\n version: '1.0.0',\n },\n // Credential params (`k`, `t`, `code`, ...) keep their key and lose their\n // value here, where the URL enters the page object. The referrer is\n // redacted too: the previous page can be our own order/landing link.\n page: {\n path: window.location.pathname,\n referrer: config.capture_referrer ? redactUrl(document.referrer) : '',\n search: redactUrl(window.location.search),\n title: document.title,\n url: redactUrl(window.location.href),\n hash: window.location.hash,\n },\n userAgent: navigator.userAgent,\n locale: navigator.language,\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n screen: {\n width: window.screen.width,\n height: window.screen.height,\n density: window.devicePixelRatio || 1,\n },\n viewport: {\n width: window.innerWidth,\n height: window.innerHeight,\n },\n ...(utm && Object.keys(utm).length > 0 && { campaign: utm }),\n ...(adClickIDs && Object.keys(adClickIDs).length > 0 && { adClickIDs }),\n ...(landingPage && { landingPage }),\n ...(network && { network }),\n ...(device && { device }),\n ...(os && { os }),\n ...(browser && { browser }),\n ...(config.active_cell && {\n cell: {\n region: config.active_cell.region,\n endpoint: config.active_cell.url,\n },\n }),\n };\n}\n\nfunction detectDevice(): EventContext['device'] {\n const ua = navigator.userAgent;\n\n if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {\n return { type: 'tablet' };\n }\n\n if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) {\n return { type: 'mobile' };\n }\n\n return { type: 'desktop' };\n}\n\nfunction detectOS(): EventContext['os'] {\n const ua = navigator.userAgent;\n\n if (/Windows NT 10/i.test(ua)) return { name: 'Windows', version: '10' };\n if (/Windows NT 6.3/i.test(ua)) return { name: 'Windows', version: '8.1' };\n if (/Windows NT 6.2/i.test(ua)) return { name: 'Windows', version: '8' };\n if (/Windows NT 6.1/i.test(ua)) return { name: 'Windows', version: '7' };\n if (/Windows/i.test(ua)) return { name: 'Windows', version: 'Unknown' };\n\n if (/Mac OS X (\\d+)[._](\\d+)/.test(ua)) {\n const match = ua.match(/Mac OS X (\\d+)[._](\\d+)/);\n return { name: 'macOS', version: `${match![1]}.${match![2]}` };\n }\n if (/Mac/i.test(ua)) return { name: 'macOS', version: 'Unknown' };\n\n if (/Android (\\d+\\.\\d+)/.test(ua)) {\n const match = ua.match(/Android (\\d+\\.\\d+)/);\n return { name: 'Android', version: match![1] };\n }\n if (/Android/i.test(ua)) return { name: 'Android', version: 'Unknown' };\n\n if (/iPhone OS (\\d+)_(\\d+)/.test(ua)) {\n const match = ua.match(/iPhone OS (\\d+)_(\\d+)/);\n return { name: 'iOS', version: `${match![1]}.${match![2]}` };\n }\n if (/iPad.*OS (\\d+)_(\\d+)/.test(ua)) {\n const match = ua.match(/iPad.*OS (\\d+)_(\\d+)/);\n return { name: 'iOS', version: `${match![1]}.${match![2]}` };\n }\n if (/iPhone|iPad/i.test(ua)) return { name: 'iOS', version: 'Unknown' };\n\n if (/Linux/i.test(ua)) return { name: 'Linux', version: 'Unknown' };\n\n return { name: 'Unknown', version: 'Unknown' };\n}\n\nfunction detectBrowser(): EventContext['browser'] {\n const ua = navigator.userAgent;\n\n if (/Edg\\/(\\d+\\.\\d+)/.test(ua)) {\n const match = ua.match(/Edg\\/(\\d+\\.\\d+)/);\n return { name: 'Edge', version: match![1] };\n }\n\n if (/Chrome\\/(\\d+\\.\\d+)/.test(ua) && !/Edg/.test(ua)) {\n const match = ua.match(/Chrome\\/(\\d+\\.\\d+)/);\n return { name: 'Chrome', version: match![1] };\n }\n\n if (/Firefox\\/(\\d+\\.\\d+)/.test(ua)) {\n const match = ua.match(/Firefox\\/(\\d+\\.\\d+)/);\n return { name: 'Firefox', version: match![1] };\n }\n\n if (/Safari\\/(\\d+\\.\\d+)/.test(ua) && !/Chrome/.test(ua)) {\n const match = ua.match(/Version\\/(\\d+\\.\\d+)/);\n return { name: 'Safari', version: match ? match[1] : 'Unknown' };\n }\n\n if (/MSIE (\\d+\\.\\d+)/.test(ua) || /Trident\\//.test(ua)) {\n const match = ua.match(/MSIE (\\d+\\.\\d+)/) || ua.match(/rv:(\\d+\\.\\d+)/);\n return { name: 'Internet Explorer', version: match ? match[1] : 'Unknown' };\n }\n\n return { name: 'Unknown', version: 'Unknown' };\n}\n\nfunction detectNetworkInfo(): EventContext['network'] | undefined {\n try {\n const connection =\n (navigator as any).connection ||\n (navigator as any).mozConnection ||\n (navigator as any).webkitConnection;\n\n if (connection) {\n return {\n effectiveType: connection.effectiveType,\n downlink: connection.downlink,\n rtt: connection.rtt,\n };\n }\n } catch (error) {\n console.warn('[Active Reach Device] detectNetworkInfo failed:', error);\n }\n\n return undefined;\n}\n\nexport function isBot(): boolean {\n const ua = navigator.userAgent.toLowerCase();\n const botPatterns = [\n 'bot',\n 'crawl',\n 'spider',\n 'slurp',\n 'mediapartners',\n 'googlebot',\n 'bingbot',\n 'yahoo',\n 'duckduckbot',\n 'baiduspider',\n 'yandex',\n 'facebookexternalhit',\n 'linkedinbot',\n 'twitterbot',\n 'slackbot',\n 'telegrambot',\n 'whatsapp',\n 'pingdom',\n 'uptimerobot',\n ];\n\n return botPatterns.some((pattern) => ua.includes(pattern));\n}\n","import { Plugin } from '../types/plugin';\nimport { logger } from '../utils/logger';\n\nexport class PluginRegistry {\n private plugins: Map<string, Plugin> = new Map();\n\n register(plugin: Plugin): void {\n if (this.plugins.has(plugin.name)) {\n logger.warn(`Plugin \"${plugin.name}\" already registered, skipping`);\n return;\n }\n\n this.plugins.set(plugin.name, plugin);\n logger.info(`Plugin registered: ${plugin.name} v${plugin.version}`);\n }\n\n unregister(pluginName: string): void {\n const plugin = this.plugins.get(pluginName);\n\n if (!plugin) {\n logger.warn(`Plugin \"${pluginName}\" not found`);\n return;\n }\n\n if (plugin.destroy) {\n try {\n plugin.destroy();\n } catch (error) {\n logger.error(`Error destroying plugin \"${pluginName}\":`, error);\n }\n }\n\n this.plugins.delete(pluginName);\n logger.info(`Plugin unregistered: ${pluginName}`);\n }\n\n get(pluginName: string): Plugin | undefined {\n return this.plugins.get(pluginName);\n }\n\n getAll(): Plugin[] {\n return Array.from(this.plugins.values());\n }\n\n async executeHook<T = any>(\n hookName: keyof Plugin,\n ...args: any[]\n ): Promise<T | undefined> {\n for (const plugin of this.plugins.values()) {\n const hook = plugin[hookName];\n\n if (typeof hook === 'function') {\n try {\n const result = await (hook as Function).apply(plugin, args);\n\n if (result !== undefined) {\n return result as T;\n }\n } catch (error) {\n logger.error(\n `Error executing ${String(hookName)} in plugin \"${plugin.name}\":`,\n error\n );\n\n if (plugin.onError) {\n try {\n plugin.onError(error as Error, { hookName, args });\n } catch (onErrorError) {\n logger.error(\n `Error in onError handler for plugin \"${plugin.name}\":`,\n onErrorError\n );\n }\n }\n }\n }\n }\n\n return undefined;\n }\n\n async executeHookChain<T = any>(\n hookName: keyof Plugin,\n initialValue: T,\n ...additionalArgs: any[]\n ): Promise<T> {\n let value = initialValue;\n\n for (const plugin of this.plugins.values()) {\n const hook = plugin[hookName];\n\n if (typeof hook === 'function') {\n try {\n const result = await (hook as Function).apply(plugin, [\n value,\n ...additionalArgs,\n ]);\n\n if (result !== undefined && result !== null) {\n value = result;\n }\n } catch (error) {\n logger.error(\n `Error executing ${String(hookName)} in plugin \"${plugin.name}\":`,\n error\n );\n\n if (plugin.onError) {\n try {\n plugin.onError(error as Error, { hookName, value, additionalArgs });\n } catch (onErrorError) {\n logger.error(\n `Error in onError handler for plugin \"${plugin.name}\":`,\n onErrorError\n );\n }\n }\n }\n }\n }\n\n return value;\n }\n\n async executeHookParallel<T = any>(\n hookName: keyof Plugin,\n ...args: any[]\n ): Promise<T[]> {\n const promises: Promise<T>[] = [];\n\n for (const plugin of this.plugins.values()) {\n const hook = plugin[hookName];\n\n if (typeof hook === 'function') {\n const promise = (async () => {\n try {\n return await (hook as Function).apply(plugin, args);\n } catch (error) {\n logger.error(\n `Error executing ${String(hookName)} in plugin \"${plugin.name}\":`,\n error\n );\n\n if (plugin.onError) {\n try {\n plugin.onError(error as Error, { hookName, args });\n } catch (onErrorError) {\n logger.error(\n `Error in onError handler for plugin \"${plugin.name}\":`,\n onErrorError\n );\n }\n }\n\n return undefined;\n }\n })();\n\n promises.push(promise);\n }\n }\n\n const results = await Promise.all(promises);\n return results.filter((r) => r !== undefined) as T[];\n }\n\n clear(): void {\n for (const plugin of this.plugins.values()) {\n if (plugin.destroy) {\n try {\n plugin.destroy();\n } catch (error) {\n logger.error(`Error destroying plugin \"${plugin.name}\":`, error);\n }\n }\n }\n\n this.plugins.clear();\n logger.info('All plugins cleared');\n }\n}\n","import { Storage } from './storage';\nimport { logger } from './logger';\n\nexport type ConsentCategory =\n | 'analytics'\n | 'marketing'\n | 'functional'\n | 'necessary';\n\nexport interface ConsentPreferences {\n analytics: boolean;\n marketing: boolean;\n functional: boolean;\n necessary: boolean;\n}\n\nexport type ConsentStatus = 'granted' | 'denied' | 'pending';\n\nexport interface ConsentManagerConfig {\n defaultConsent?: Partial<ConsentPreferences>;\n waitForConsent?: boolean;\n consentStorageKey?: string;\n}\n\nexport class ConsentManager {\n private storage: Storage;\n private config: Required<ConsentManagerConfig>;\n private preferences: ConsentPreferences;\n private listeners: Array<(preferences: ConsentPreferences) => void> = [];\n\n constructor(storage: Storage, config: ConsentManagerConfig = {}) {\n this.storage = storage;\n this.config = {\n defaultConsent: config.defaultConsent || {},\n waitForConsent: config.waitForConsent ?? false,\n consentStorageKey: config.consentStorageKey || 'aegis_consent',\n };\n\n this.preferences = this.loadPreferences();\n }\n\n private loadPreferences(): ConsentPreferences {\n const stored = this.storage.get(this.config.consentStorageKey);\n\n if (stored) {\n try {\n const parsed = JSON.parse(stored);\n logger.info('Loaded consent preferences:', parsed);\n return this.mergeWithDefaults(parsed);\n } catch (error) {\n logger.warn('Failed to parse consent preferences:', error);\n }\n }\n\n return this.getDefaultPreferences();\n }\n\n private getDefaultPreferences(): ConsentPreferences {\n return {\n analytics: this.config.defaultConsent.analytics ?? false,\n marketing: this.config.defaultConsent.marketing ?? false,\n functional: this.config.defaultConsent.functional ?? true,\n necessary: true,\n };\n }\n\n private mergeWithDefaults(\n preferences: Partial<ConsentPreferences>\n ): ConsentPreferences {\n return {\n necessary: true,\n analytics: preferences.analytics ?? this.config.defaultConsent.analytics ?? false,\n marketing: preferences.marketing ?? this.config.defaultConsent.marketing ?? false,\n functional: preferences.functional ?? this.config.defaultConsent.functional ?? true,\n };\n }\n\n private savePreferences(): void {\n try {\n this.storage.set(\n this.config.consentStorageKey,\n JSON.stringify(this.preferences),\n 365\n );\n logger.info('Saved consent preferences:', this.preferences);\n } catch (error) {\n logger.error('Failed to save consent preferences:', error);\n }\n }\n\n setConsent(preferences: Partial<ConsentPreferences>): void {\n const updated = { ...this.preferences, ...preferences };\n updated.necessary = true;\n\n this.preferences = updated;\n this.savePreferences();\n this.notifyListeners();\n\n logger.info('Consent updated:', this.preferences);\n }\n\n grantAll(): void {\n this.setConsent({\n analytics: true,\n marketing: true,\n functional: true,\n necessary: true,\n });\n }\n\n denyAll(): void {\n this.setConsent({\n analytics: false,\n marketing: false,\n functional: false,\n necessary: true,\n });\n }\n\n hasConsent(category: ConsentCategory): boolean {\n return this.preferences[category];\n }\n\n getPreferences(): ConsentPreferences {\n return { ...this.preferences };\n }\n\n getStatus(category: ConsentCategory): ConsentStatus {\n if (this.hasConsent(category)) {\n return 'granted';\n }\n\n const stored = this.storage.get(this.config.consentStorageKey);\n if (!stored && this.config.waitForConsent) {\n return 'pending';\n }\n\n return 'denied';\n }\n\n isAnalyticsEnabled(): boolean {\n return this.hasConsent('analytics');\n }\n\n isMarketingEnabled(): boolean {\n return this.hasConsent('marketing');\n }\n\n onChange(callback: (preferences: ConsentPreferences) => void): () => void {\n this.listeners.push(callback);\n\n return () => {\n const index = this.listeners.indexOf(callback);\n if (index > -1) {\n this.listeners.splice(index, 1);\n }\n };\n }\n\n private notifyListeners(): void {\n this.listeners.forEach((listener) => {\n try {\n listener(this.getPreferences());\n } catch (error) {\n logger.error('Consent listener error:', error);\n }\n });\n }\n\n reset(): void {\n this.storage.remove(this.config.consentStorageKey);\n this.preferences = this.getDefaultPreferences();\n this.notifyListeners();\n logger.info('Consent preferences reset');\n }\n\n integrateOneTrust(): void {\n if (typeof window === 'undefined') return;\n\n const oneTrust = (window as any).OneTrust;\n if (!oneTrust) {\n logger.warn('OneTrust not detected');\n return;\n }\n\n const syncWithOneTrust = () => {\n const activeGroups = (window as any).OnetrustActiveGroups || '';\n\n this.setConsent({\n necessary: true,\n functional: activeGroups.includes('C0003'),\n analytics: activeGroups.includes('C0002'),\n marketing: activeGroups.includes('C0004'),\n });\n\n logger.info('Synced with OneTrust consent');\n };\n\n if ((window as any).OptanonWrapper) {\n const originalWrapper = (window as any).OptanonWrapper;\n (window as any).OptanonWrapper = function () {\n originalWrapper();\n syncWithOneTrust();\n };\n } else {\n (window as any).OptanonWrapper = syncWithOneTrust;\n }\n\n syncWithOneTrust();\n }\n\n integrateCookiebot(): void {\n if (typeof window === 'undefined') return;\n\n const cookiebot = (window as any).Cookiebot;\n if (!cookiebot) {\n logger.warn('Cookiebot not detected');\n return;\n }\n\n const syncWithCookiebot = () => {\n const consent = cookiebot.consent || {};\n\n this.setConsent({\n necessary: true,\n functional: consent.preferences || false,\n analytics: consent.statistics || false,\n marketing: consent.marketing || false,\n });\n\n logger.info('Synced with Cookiebot consent');\n };\n\n window.addEventListener('CookiebotOnAccept', syncWithCookiebot);\n window.addEventListener('CookiebotOnDecline', syncWithCookiebot);\n\n if (cookiebot.consent) {\n syncWithCookiebot();\n }\n }\n\n integrateGoogleConsentMode(): void {\n if (typeof window === 'undefined') return;\n\n // Consent Mode v2 is driven through the gtag command queue, which is just\n // `window.dataLayer`. The Google tag (gtag.js) loads async, so SDK init can\n // win the race and find no `gtag` yet. The old behaviour bailed with a\n // \"Google Tag Manager not detected\" warning — misleading (the tag usually\n // loads a tick later) and lossy (the consent signal was dropped). Instead\n // we define the canonical gtag stub so our consent commands queue on\n // `dataLayer` and gtag.js replays them when it boots. This is exactly\n // Google's documented bootstrap snippet. Callers gate this integration on a\n // Google tag actually being configured (see storefront provider), so we\n // never spin up an inert dataLayer for tenants with no Google tag.\n const w = window as unknown as {\n gtag?: (...args: unknown[]) => void;\n dataLayer?: unknown[];\n };\n if (typeof w.gtag !== 'function') {\n w.dataLayer = w.dataLayer ?? [];\n w.gtag = (...args: unknown[]) => {\n w.dataLayer?.push(args);\n };\n logger.debug('Google tag not yet loaded — queuing consent via dataLayer');\n }\n const gtag = w.gtag;\n\n const updateGoogleConsent = () => {\n gtag('consent', 'update', {\n ad_storage: this.preferences.marketing ? 'granted' : 'denied',\n analytics_storage: this.preferences.analytics ? 'granted' : 'denied',\n ad_user_data: this.preferences.marketing ? 'granted' : 'denied',\n ad_personalization: this.preferences.marketing ? 'granted' : 'denied',\n functionality_storage: this.preferences.functional ? 'granted' : 'denied',\n personalization_storage: this.preferences.functional ? 'granted' : 'denied',\n security_storage: 'granted',\n });\n\n logger.debug('Updated Google Consent Mode');\n };\n\n this.onChange(updateGoogleConsent);\n updateGoogleConsent();\n }\n}\n","/**\n * The store editor's dated whole-page preview (Amita RULED 11-12): the preview\n * link carries a SIGNED `preview_as_of` token for one brand. The token reaches\n * /v1/in-app/active unchanged (the cell honours it only for that brand).\n *\n * A page whose address carries the token, or any other editor preview marker\n * (`isPreviewPage`), is a PREVIEW, never a visit, whatever runtime the host\n * mounted on it: the in-app runtime treats it as previewOnly (reads and draws,\n * writes nothing) and the analytics core records nothing. One reader, so every\n * runtime agrees on what a preview is.\n */\n\n/** Longest token the SDK forwards (a signed `{org, as_of}` pair is far shorter). */\nconst MAX_TOKEN_LENGTH = 600;\n\n/** The dated whole-page preview's signed token from the page address, or null. */\nexport function previewAsOfToken(): string | null {\n if (typeof window === 'undefined' || !window.location) return null;\n try {\n const v = new URLSearchParams(window.location.search || '').get('preview_as_of');\n return v && v.length <= MAX_TOKEN_LENGTH ? v : null;\n } catch {\n return null;\n }\n}\n\n/** True on a dated preview page (the link carries the Date's token). */\nexport function isDatedPreviewPage(): boolean {\n return previewAsOfToken() !== null;\n}\n\n/**\n * The address markers of every editor preview link (Amita RULED 11-12: a\n * preview never records engagement, dated or not):\n * - `preview_as_of` the whole-page preview with a Date;\n * - `section_names=1` the whole-page preview (page-model `scopedPreviewUrl`\n * always adds it, with or without a Date or Store);\n * - `preview_store` the whole-page preview's Store on a page without a\n * per-store address;\n * - `campaign_preview` the campaign editor's live-page iframe;\n * - `preview=admin` the storefront admin's iframe.\n * A customer link carries none of them; a customer who adds one only stops\n * their own page from writing.\n */\nfunction hasEditorPreviewMarker(search: URLSearchParams): boolean {\n return (\n search.has('preview_as_of') ||\n search.get('section_names') === '1' ||\n search.has('preview_store') ||\n search.has('campaign_preview') ||\n search.get('preview') === 'admin'\n );\n}\n\n/** True on ANY editor preview page: nothing on it may write (no page view, no\n * identify, no impression, no returning-visitor mark, no consumed state).\n * The one reader every runtime (analytics core, in-app runtime, the host's\n * pixels) asks, so they all agree on what a preview is. */\nexport function isPreviewPage(): boolean {\n if (typeof window === 'undefined' || !window.location) return false;\n try {\n return hasEditorPreviewMarker(new URLSearchParams(window.location.search || ''));\n } catch {\n return false;\n }\n}\n","/**\n * \"Last in-app item touch\" (IN_APP_CAMPAIGN_ATTRIBUTION_TRACKER.md IA6).\n *\n * When an in-app CTA adds or opens a product, the campaign that showed it is\n * remembered for a short while so a LATER add-to-cart of the same sku (for\n * example from the product page) still carries `source_campaign_id`. Storage is\n * sessionStorage and every access is guarded: with storage blocked the\n * explicit path (the action itself) still carries the id, only the later\n * product-page add loses it.\n */\n\nexport interface InAppItemTouch {\n campaign_id: string;\n sku: string;\n ts: number;\n variant_id?: string;\n surface?: string;\n}\n\nexport const ITEM_TOUCH_KEY = 'aegis_inapp_item_touch';\n/** A touch older than this no longer labels a cart add. */\nexport const ITEM_TOUCH_TTL_MS = 30 * 60 * 1000;\n\nfunction store(): Storage | null {\n try {\n return typeof sessionStorage === 'undefined' ? null : sessionStorage;\n } catch {\n return null;\n }\n}\n\nexport function recordInAppItemTouch(touch: Omit<InAppItemTouch, 'ts'> & { ts?: number }): void {\n if (!touch.campaign_id || !touch.sku) return;\n const s = store();\n if (!s) return;\n try {\n const rec: InAppItemTouch = { ...touch, ts: touch.ts ?? Date.now() };\n s.setItem(ITEM_TOUCH_KEY, JSON.stringify(rec));\n } catch {\n /* storage blocked or full: the touch is best-effort */\n }\n}\n\n/** The stored touch when it is for `sku` and still inside the TTL, else null. */\nexport function readInAppItemTouch(sku: string | undefined, now: number = Date.now()): InAppItemTouch | null {\n if (!sku) return null;\n const s = store();\n if (!s) return null;\n try {\n const raw = s.getItem(ITEM_TOUCH_KEY);\n if (!raw) return null;\n const rec = JSON.parse(raw) as Partial<InAppItemTouch>;\n if (\n typeof rec.campaign_id !== 'string' ||\n typeof rec.sku !== 'string' ||\n typeof rec.ts !== 'number'\n ) {\n return null;\n }\n if (rec.sku !== sku) return null;\n if (now - rec.ts > ITEM_TOUCH_TTL_MS || now < rec.ts) return null;\n return rec as InAppItemTouch;\n } catch {\n return null;\n }\n}\n","/**\n * E-Commerce helper methods for the Active Reach SDK.\n *\n * Provides standardized e-commerce event tracking that maps to the\n * Active Reach Intelligence data governance pipeline.\n *\n * Event names follow the canonical mapper (libs/gateway-core/src/canonical-event.ts).\n * The dotted-vs-flat split is intentional, not accidental: HIGH-VALUE lifecycle\n * moments are namespaced `domain.action` (transaction.*, engagement.*); raw\n * funnel telemetry that maps 1:1 to a Meta-standard event stays flat snake_case\n * (its name is a frozen contract with the Meta CAPI/pixel maps). Don't \"tidy\"\n * either side — see the convention block in canonical-event.ts.\n * product_viewed → product_viewed (flat)\n * product_list_viewed → product_list_viewed (flat)\n * product_clicked → engagement.product_click (dotted)\n * cart_item_added → cart_item_added (flat)\n * cart_item_removed → cart_item_removed (flat)\n * cart_viewed → cart_viewed (flat)\n * checkout_started → checkout_started (flat)\n * order_completed → transaction.purchase (dotted)\n * order_refunded → transaction.refund (dotted)\n * coupon_applied → coupon_applied (flat)\n * search_performed → engagement.search (dotted)\n * wishlist_item_added → wishlist_item_added (flat)\n * product_waitlisted → product_waitlisted (back-in-stock waitlist opt-in;\n * copied by outlet_restock_worker into product_waitlist;\n * fires catalog.back_in_stock when the item is back at\n * the outlet)\n * promotion_viewed → promotion_viewed\n * promotion_clicked → promotion_clicked\n */\n\nimport type { Aegis } from '../core/analytics';\nimport { readInAppItemTouch } from '../inapp/item-touch';\nimport type {\n EcommerceProduct,\n EcommerceCart,\n EcommerceCheckout,\n EcommerceOrder,\n EcommerceFulfillmentMode,\n EcommerceCoupon,\n EcommerceSearch,\n EcommerceProductList,\n EcommerceWishlist,\n EcommerceWaitlist,\n EcommercePromotion,\n} from './types';\n\nfunction sumItems(products: EcommerceProduct[]): number {\n return products.reduce((sum, p) => sum + (p.quantity ?? 1), 0);\n}\n\n/** The SDK's orders are placed on the brand's own website. */\nconst ORDER_CHANNEL = 'online_store';\n\nconst FULFILLMENT_MODES: ReadonlySet<string> = new Set<EcommerceFulfillmentMode>(['pickup', 'delivery']);\n\n/**\n * The order's `fulfillment_mode` as the order journey reads it (Aman 2026-11-03).\n * A declared `pickup` / `delivery` is forwarded. With none, a positive shipping\n * charge means the order ships: `delivery`, the default the server intake uses\n * for e-commerce platforms (`order_ingest.py`). Anything else is left out: the\n * journey admits an order with no mode and lets the order's own events decide\n * the steps, while a guessed mode would disable the step that applies.\n */\nfunction orderFulfillmentMode(order: EcommerceOrder): EcommerceFulfillmentMode | undefined {\n const raw: unknown = order.fulfillment_mode;\n const declared = typeof raw === 'string' ? raw.trim().toLowerCase() : '';\n if (FULFILLMENT_MODES.has(declared)) return declared as EcommerceFulfillmentMode;\n if (typeof order.shipping === 'number' && order.shipping > 0) return 'delivery';\n return undefined;\n}\n\n// Cart abandonment detection is SERVER-SIDE. The SDK fires the canonical\n// e-commerce events (`cart_item_added`, `cart_item_removed`, `cart_viewed`,\n// `transaction.purchase`); a Celery beat task on cell-plane scans\n// `aegis.events_with_ttl` every 5 minutes for shoppers with a\n// `cart_item_added` >30 min old and no subsequent purchase, emitting\n// `cart_abandoned` to the `behavioral-events_{cell_id}` Kafka topic.\n//\n// The SPA storefront has no persistent server-side cart object, so cart\n// identity is keyed off the shopper themselves: `COALESCE(user_id,\n// anonymous_id)`. Provider-issued cart tokens (Shopify/Woo/Magento pixel\n// bridge via Widget Manager) are surfaced on the emitted event when\n// present but are not required for detection.\n//\n// We deliberately do NOT run a JS timer on the client — mobile browsers\n// throttle background timers to ~1Hz and they're unreliable for any\n// abandonment threshold beyond a few seconds. Industry alignment: WebEngage,\n// MoEngage, CleverTap, Bitespeed, Klaviyo all detect server-side.\n//\n// See: `apps/cell-plane/app/workers/storefront_cart_abandonment_scanner.py`\n\nfunction mapProducts(products: EcommerceProduct[]) {\n return products.map((p) => ({\n product_id: p.product_id,\n sku: p.sku,\n name: p.name,\n price: p.price,\n quantity: p.quantity ?? 1,\n currency: p.currency,\n category: p.category,\n brand: p.brand,\n variant_id: p.variant_id,\n variant_label: p.variant_label,\n position: p.position,\n }));\n}\n\nexport class EcommerceTracker {\n constructor(private aegis: Aegis) {}\n\n // -- Cart model (CEP-canonical: the cart is DERIVED from the ecommerce events\n // the host already fires, so on-page cart-reactive surfaces — the\n // Free-Delivery progress card, the progress-bar widget, rule evaluation —\n // all light up without a separate `setCartState` call). `cartViewed` is\n // authoritative (full snapshot); add/remove apply best-effort deltas. The\n // sink (wired by `runtime.bindEcommerce`) forwards every change to the ONE\n // cart store. See docs/architecture/CART_STORE_UNIFICATION_TRACKER.md.\n private _cart: { total: number; itemCount: number; currency: string } = {\n total: 0,\n itemCount: 0,\n currency: 'INR',\n };\n private _cartSink: ((c: { total: number; itemCount: number; currency: string }) => void) | null = null;\n\n /** Register a sink that receives the derived cart on every cart event.\n * Wired once by `AegisMessageRuntime.bindEcommerce(...)`. Emits the current\n * snapshot immediately so a late binding still gets the latest cart. */\n onCartChange(sink: (c: { total: number; itemCount: number; currency: string }) => void): void {\n this._cartSink = sink;\n sink({ ...this._cart });\n }\n\n private _emitCart(): void {\n if (this._cart.total < 0) this._cart.total = 0;\n if (this._cart.itemCount < 0) this._cart.itemCount = 0;\n this._cartSink?.({ ...this._cart });\n }\n\n // -- Product Discovery --\n\n productViewed(product: EcommerceProduct): void {\n this.aegis.track('product_viewed', {\n product_id: product.product_id,\n sku: product.sku,\n name: product.name,\n price: product.price,\n currency: product.currency ?? 'INR',\n category: product.category,\n brand: product.brand,\n variant_id: product.variant_id,\n variant_label: product.variant_label,\n image_url: product.image_url,\n url: product.url,\n });\n }\n\n productListViewed(list: EcommerceProductList): void {\n const products = mapProducts(list.products);\n this.aegis.track('product_list_viewed', {\n list_id: list.list_id,\n list_name: list.list_name,\n category: list.category,\n products,\n // `items` as well as `products` — a THIRD spelling of the same fact was\n // one spelling too many. Every product reader in the platform looks for\n // `items` (or `line_items`, the Shopify shape); this event alone said\n // `products`, so a list view showed N products and contributed nothing to\n // any of them. On ST that was 4 views recorded as `not measured`, and it\n // is the same defect that made every Shopify order invisible.\n //\n // `products` is kept so nothing already reading it breaks. mapProducts\n // already emits product_id / sku / name / price / quantity, which is\n // exactly the canonical item shape — no second mapping to drift.\n items: products,\n });\n }\n\n productClicked(product: EcommerceProduct, source?: { list_id?: string; position?: number; section?: string }): void {\n this.aegis.track('product_clicked', {\n product_id: product.product_id,\n sku: product.sku,\n name: product.name,\n price: product.price,\n currency: product.currency ?? 'INR',\n category: product.category,\n brand: product.brand,\n variant_id: product.variant_id,\n list_id: source?.list_id,\n position: source?.position ?? product.position,\n section: source?.section,\n });\n }\n\n productImpressed(product: EcommerceProduct, source?: { list_id?: string; position?: number; section?: string }): void {\n this.aegis.track('product_impression', {\n product_id: product.product_id,\n sku: product.sku,\n name: product.name,\n price: product.price,\n currency: product.currency ?? 'INR',\n category: product.category,\n list_id: source?.list_id,\n position: source?.position ?? product.position,\n section: source?.section,\n });\n }\n\n categoryFiltered(category: string, options?: { previous_category?: string; result_count?: number }): void {\n this.aegis.track('category_filtered', {\n category,\n previous_category: options?.previous_category,\n result_count: options?.result_count,\n });\n }\n\n searchPerformed(search: EcommerceSearch): void {\n this.aegis.track('search_performed', {\n query: search.query,\n results_count: search.results_count,\n filters: search.filters,\n });\n }\n\n // -- Cart --\n\n addToCart(product: EcommerceProduct): void {\n const qty = product.quantity ?? 1;\n // IA6: an explicit source wins; else the last in-app touch of the same sku.\n const touch = product.source_campaign_id ? null : readInAppItemTouch(product.sku);\n const sourceCampaignId = product.source_campaign_id ?? touch?.campaign_id;\n this.aegis.track('cart_item_added', {\n source_campaign_id: sourceCampaignId,\n source_variant_id: sourceCampaignId ? (product.source_variant_id ?? touch?.variant_id) : undefined,\n source_surface: sourceCampaignId ? (product.source_surface ?? touch?.surface) : undefined,\n product_id: product.product_id,\n sku: product.sku,\n name: product.name,\n price: product.price,\n quantity: qty,\n currency: product.currency ?? 'INR',\n category: product.category,\n brand: product.brand,\n variant_id: product.variant_id,\n variant_label: product.variant_label,\n });\n // Best-effort delta — `cartViewed` corrects to the authoritative snapshot.\n this._cart.total += (product.price || 0) * qty;\n this._cart.itemCount += qty;\n if (product.currency) this._cart.currency = product.currency;\n this._emitCart();\n }\n\n removeFromCart(product: EcommerceProduct): void {\n const qty = product.quantity ?? 1;\n this.aegis.track('cart_item_removed', {\n product_id: product.product_id,\n sku: product.sku,\n name: product.name,\n price: product.price,\n quantity: qty,\n currency: product.currency ?? 'INR',\n variant_id: product.variant_id,\n });\n this._cart.total -= (product.price || 0) * qty;\n this._cart.itemCount -= qty;\n this._emitCart();\n }\n\n cartViewed(cart: EcommerceCart): void {\n this.aegis.track('cart_viewed', {\n cart_id: cart.cart_id,\n value: cart.value,\n currency: cart.currency ?? 'INR',\n num_items: sumItems(cart.products),\n products: mapProducts(cart.products),\n });\n // Authoritative snapshot — overwrites the running deltas.\n this._cart = {\n total: cart.value || 0,\n itemCount: sumItems(cart.products),\n currency: cart.currency ?? this._cart.currency ?? 'INR',\n };\n this._emitCart();\n }\n\n // -- Checkout --\n\n checkoutStarted(checkout: EcommerceCheckout): void {\n this.aegis.track('checkout_started', {\n checkout_id: checkout.checkout_id,\n value: checkout.value,\n currency: checkout.currency ?? 'INR',\n num_items: sumItems(checkout.products),\n coupon: checkout.coupon,\n shipping: checkout.shipping,\n tax: checkout.tax,\n products: mapProducts(checkout.products),\n });\n }\n\n checkoutStep(step: number, options?: Record<string, unknown>): void {\n this.aegis.track('checkout_step', {\n step,\n ...options,\n });\n }\n\n checkoutOption(option: {\n step?: number;\n payment_method?: string;\n shipping_method?: string;\n option_id?: string;\n option_label?: string;\n }): void {\n this.aegis.track('checkout_option', { ...option });\n }\n\n // -- Order --\n\n orderCompleted(order: EcommerceOrder): void {\n this.aegis.track('order_completed', {\n order_id: order.order_id,\n value: order.value,\n revenue: order.revenue ?? order.value,\n currency: order.currency ?? 'INR',\n num_items: sumItems(order.products),\n coupon: order.coupon,\n shipping: order.shipping,\n tax: order.tax,\n discount: order.discount,\n payment_method: order.payment_method,\n fulfillment_mode: orderFulfillmentMode(order),\n // Where the order was placed: the brand's own website. Said outright,\n // because a channel-less order with fulfillment_mode=delivery resolves to\n // the delivery-apps group server-side, and the order journey then sends\n // no confirmation. `online_store` is a value the resolver maps to online.\n channel: ORDER_CHANNEL,\n products: mapProducts(order.products),\n });\n }\n\n orderRefunded(orderId: string, value?: number, products?: EcommerceProduct[]): void {\n this.aegis.track('order_refunded', {\n order_id: orderId,\n value,\n products: products ? mapProducts(products) : undefined,\n });\n }\n\n orderShipped(\n orderId: string,\n tracking?: { carrier?: string; tracking_code?: string; tracking_url?: string },\n ): void {\n this.aegis.track('order_shipped', {\n order_id: orderId,\n carrier: tracking?.carrier,\n tracking_code: tracking?.tracking_code,\n tracking_url: tracking?.tracking_url,\n });\n }\n\n // -- Coupons --\n\n couponApplied(coupon: EcommerceCoupon): void {\n this.aegis.track('coupon_applied', { ...coupon });\n }\n\n couponRemoved(coupon: EcommerceCoupon): void {\n this.aegis.track('coupon_removed', { ...coupon });\n }\n\n couponDenied(coupon: EcommerceCoupon, reason?: string): void {\n this.aegis.track('coupon_denied', { ...coupon, reason });\n }\n\n // -- Wishlist --\n\n wishlistItemAdded(wishlist: EcommerceWishlist): void {\n this.aegis.track('wishlist_item_added', {\n wishlist_id: wishlist.wishlist_id,\n wishlist_name: wishlist.wishlist_name,\n product_id: wishlist.product.product_id,\n sku: wishlist.product.sku,\n name: wishlist.product.name,\n price: wishlist.product.price,\n variant_id: wishlist.product.variant_id,\n });\n }\n\n productRemovedFromWishlist(wishlist: EcommerceWishlist): void {\n this.aegis.track('wishlist_item_removed', {\n wishlist_id: wishlist.wishlist_id,\n wishlist_name: wishlist.wishlist_name,\n product_id: wishlist.product.product_id,\n sku: wishlist.product.sku,\n name: wishlist.product.name,\n price: wishlist.product.price,\n variant_id: wishlist.product.variant_id,\n });\n }\n\n // -- Back-in-stock waitlist --\n //\n // Server side: outlet_restock_worker copies event_name='product_waitlisted'\n // (with event_properties['product_id'] and the outlet) into the durable\n // product_waitlist and, when the SKU is back at that outlet, emits\n // product_restocked, which fires the catalog.back_in_stock journey.\n productWaitlisted(waitlist: EcommerceWaitlist): void {\n this.aegis.track('product_waitlisted', {\n product_id: waitlist.product.product_id,\n sku: waitlist.product.sku,\n variant_id: waitlist.product.variant_id,\n name: waitlist.product.name,\n price: waitlist.product.price,\n channels: waitlist.channels,\n });\n }\n\n // -- Promotions --\n\n promotionViewed(promo: EcommercePromotion): void {\n this.aegis.track('promotion_viewed', { ...promo });\n }\n\n promotionClicked(promo: EcommercePromotion): void {\n this.aegis.track('promotion_clicked', { ...promo });\n }\n}\n\nexport type {\n EcommerceProduct,\n EcommerceCart,\n EcommerceCheckout,\n EcommerceOrder,\n EcommerceFulfillmentMode,\n EcommerceCoupon,\n EcommerceSearch,\n EcommerceProductList,\n EcommerceWishlist,\n EcommerceWaitlist,\n EcommercePromotion,\n} from './types';\n","/**\n * Token bucket rate limiter for client-side event throttling.\n *\n * Limits per session: burst (default 100) + sustained (default 20/sec).\n * Drops events with a console warning once a burst sustains. Drops are\n * emitted as a single coalesced `aegis.client.rate_limited` meta-event\n * per second so we don't flood ingress with drop notifications.\n *\n * Defaults are deliberately generous — the goal is to prevent runaway\n * loops (a buggy app firing 10k events/sec) without affecting normal use.\n */\n\nimport { logger } from '../utils/logger';\n\nexport interface RateLimiterOptions {\n /** Max tokens (burst size). Default 100. */\n burstCapacity?: number;\n /** Sustained rate per second. Default 20. */\n refillPerSecond?: number;\n /** Window in ms over which dropped events are coalesced. Default 1000. */\n dropCoalesceWindowMs?: number;\n /** Optional callback fired with the count of dropped events per coalesce window. */\n onDropBatch?: (droppedCount: number, sampleEventName: string | null) => void;\n}\n\nexport class RateLimiter {\n private tokens: number;\n private readonly capacity: number;\n private readonly refillPerSecond: number;\n private lastRefillMs: number;\n\n private droppedThisWindow = 0;\n private firstDroppedName: string | null = null;\n private windowFlushTimer: ReturnType<typeof setTimeout> | null = null;\n private readonly windowMs: number;\n private readonly onDropBatch?: (droppedCount: number, sampleEventName: string | null) => void;\n\n constructor(options: RateLimiterOptions = {}) {\n this.capacity = Math.max(1, options.burstCapacity ?? 100);\n this.refillPerSecond = Math.max(1, options.refillPerSecond ?? 20);\n this.windowMs = options.dropCoalesceWindowMs ?? 1000;\n this.onDropBatch = options.onDropBatch;\n this.tokens = this.capacity;\n this.lastRefillMs = Date.now();\n }\n\n /**\n * Try to consume 1 token. Returns true if allowed, false if throttled.\n * Throttled events are coalesced into a single onDropBatch callback per window.\n */\n tryConsume(eventName: string): boolean {\n this.refill();\n\n if (this.tokens >= 1) {\n this.tokens -= 1;\n return true;\n }\n\n this.droppedThisWindow += 1;\n if (this.firstDroppedName === null) {\n this.firstDroppedName = eventName;\n logger.warn(\n `[Aegis] Rate limit reached — dropping event \"${eventName}\" and any further events for ${this.windowMs}ms. Burst=${this.capacity}, refill=${this.refillPerSecond}/s.`,\n );\n }\n\n if (!this.windowFlushTimer) {\n this.windowFlushTimer = setTimeout(() => this.flushWindow(), this.windowMs);\n }\n\n return false;\n }\n\n /** Diagnostics — current token count (rounded down). */\n getAvailableTokens(): number {\n this.refill();\n return Math.floor(this.tokens);\n }\n\n /** Cleanup. Idempotent. */\n destroy(): void {\n if (this.windowFlushTimer) {\n clearTimeout(this.windowFlushTimer);\n this.windowFlushTimer = null;\n }\n this.flushWindow();\n }\n\n // ---------------------------------------------------------------------\n\n private refill(): void {\n const now = Date.now();\n const elapsedSec = (now - this.lastRefillMs) / 1000;\n if (elapsedSec <= 0) return;\n\n const newTokens = elapsedSec * this.refillPerSecond;\n this.tokens = Math.min(this.capacity, this.tokens + newTokens);\n this.lastRefillMs = now;\n }\n\n private flushWindow(): void {\n if (this.windowFlushTimer) {\n clearTimeout(this.windowFlushTimer);\n this.windowFlushTimer = null;\n }\n if (this.droppedThisWindow > 0 && this.onDropBatch) {\n try {\n this.onDropBatch(this.droppedThisWindow, this.firstDroppedName);\n } catch (err) {\n logger.warn('[Active Reach] RateLimiter.onDropBatch threw:', err);\n }\n }\n this.droppedThisWindow = 0;\n this.firstDroppedName = null;\n }\n}\n","/**\n * MurmurHash3 x86-32 — deterministic, byte-identical with Python `mmh3.hash`.\n *\n * We hand-roll rather than pull a dep because (a) our bundle-budget is\n * aggressive for storefront first-paint, and (b) this is the authoritative\n * cross-language hash for the event-governance bloom filter — any behavior\n * drift between Python and JS produces silent FP-rate spikes in prod.\n *\n * Contract:\n * • Input is a JS string. It is UTF-8 encoded via TextEncoder before hashing.\n * • Output is an unsigned 32-bit integer (0 .. 2^32-1).\n * • Matches `mmh3.hash(s.encode('utf-8'), seed=seed, signed=False)` in\n * Python exactly — verified by libs/shared-types/bloom-test-vectors.json\n * in CI.\n *\n * Reference: Austin Appleby, MurmurHash3 (public domain).\n * https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp\n *\n * Implementation notes:\n * • All arithmetic on 32-bit ints. JS does bitwise ops on 32-bit ints natively;\n * `Math.imul` gives us correct 32-bit multiplication without overflow.\n * • We use `>>> 0` to coerce to unsigned after every step that could produce\n * a negative or >32-bit value.\n * • UTF-8 encoding matters — a naive `charCodeAt` loop would mis-hash any\n * string with non-ASCII characters (e.g. emoji, accented chars) and the\n * Python side would disagree. We always encode via TextEncoder first.\n */\n\nconst C1 = 0xcc9e2d51;\nconst C2 = 0x1b873593;\n\n/**\n * Compute MurmurHash3 x86-32 of a UTF-8 encoded string.\n *\n * @param input The string to hash.\n * @param seed 32-bit unsigned seed.\n * @returns Unsigned 32-bit integer hash.\n */\nexport function murmurhash3_x86_32(input: string, seed: number = 0): number {\n // Encode to UTF-8 bytes — matches Python's `s.encode('utf-8')`.\n const bytes = new TextEncoder().encode(input);\n return murmurhash3_bytes(bytes, seed);\n}\n\n/**\n * Compute MurmurHash3 x86-32 over a byte buffer directly.\n *\n * Exposed for callers that already have UTF-8 bytes and want to skip the\n * encode step (e.g., internal bloom-hash paths).\n */\nexport function murmurhash3_bytes(bytes: Uint8Array, seed: number = 0): number {\n const len = bytes.length;\n const nBlocks = Math.floor(len / 4);\n\n let h1 = seed >>> 0;\n\n // Body — consume 4-byte blocks.\n for (let i = 0; i < nBlocks; i++) {\n const offset = i * 4;\n let k1 =\n bytes[offset] |\n (bytes[offset + 1] << 8) |\n (bytes[offset + 2] << 16) |\n (bytes[offset + 3] << 24);\n\n k1 = Math.imul(k1, C1);\n k1 = (k1 << 15) | (k1 >>> 17);\n k1 = Math.imul(k1, C2);\n\n h1 ^= k1;\n h1 = (h1 << 13) | (h1 >>> 19);\n h1 = (Math.imul(h1, 5) + 0xe6546b64) >>> 0;\n }\n\n // Tail — up to 3 trailing bytes.\n const tailStart = nBlocks * 4;\n let k1 = 0;\n const tailLen = len - tailStart;\n if (tailLen === 3) k1 ^= bytes[tailStart + 2] << 16;\n if (tailLen >= 2) k1 ^= bytes[tailStart + 1] << 8;\n if (tailLen >= 1) {\n k1 ^= bytes[tailStart];\n k1 = Math.imul(k1, C1);\n k1 = (k1 << 15) | (k1 >>> 17);\n k1 = Math.imul(k1, C2);\n h1 ^= k1;\n }\n\n // Finalization — avalanche (fmix32).\n h1 ^= len;\n h1 ^= h1 >>> 16;\n h1 = Math.imul(h1, 0x85ebca6b);\n h1 ^= h1 >>> 13;\n h1 = Math.imul(h1, 0xc2b2ae35);\n h1 ^= h1 >>> 16;\n\n return h1 >>> 0;\n}\n","/**\n * Bloom filter — wire-compatible with the Python builder in\n * apps/control-plane/app/services/event_governance_bloom.py\n *\n * This SDK-side variant is QUERY-ONLY. The filter is built server-side\n * from the org's registered event-name set, base64-encoded, and shipped\n * to the browser on `/v1/sdk/bootstrap`. The SDK reads it once, uses it\n * to gate `track()` calls, and discards it on the next bootstrap.\n *\n * Wire format:\n * • `m` bits of storage, represented as m/8 bytes, base64-encoded.\n * • Bit `i` is at byte `i >> 3`, bitmask `1 << (i & 7)` — LSB-first.\n * • `m` MUST be a power of two — allows `idx & (m-1)` modulo.\n * • `k` hash functions synthesized via Kirsch-Mitzenmacher from two\n * MurmurHash3 x86-32 hashes with seeds (seedA, seedB):\n * h_i(x) = (h1(x) + i * h2(x)) mod m\n * • Input strings are UTF-8 encoded (handled inside murmurhash3_x86_32).\n */\n\nimport { murmurhash3_x86_32 } from './murmur3';\n\n/** Decode a base64 string to a Uint8Array. Accepts web (atob) and node (Buffer). */\nfunction base64ToBytes(b64: string): Uint8Array {\n if (typeof atob !== 'undefined') {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n }\n // Node.js fallback — used by tests and SSR integrations.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const B = (globalThis as any).Buffer;\n if (B && typeof B.from === 'function') {\n const buf: Uint8Array = B.from(b64, 'base64');\n // Copy into a plain Uint8Array so callers don't observe Buffer semantics.\n return new Uint8Array(buf);\n }\n throw new Error('No base64 decoder available (neither atob nor Buffer)');\n}\n\nexport interface BloomFilterParams {\n /** Bits in the filter (must be power of 2). */\n m: number;\n /** Number of hash functions (Kirsch-Mitzenmacher synthesized). */\n k: number;\n /** Seed for the first MurmurHash3 call. */\n seedA: number;\n /** Seed for the second MurmurHash3 call. */\n seedB: number;\n}\n\nexport class BloomFilter {\n private readonly buf: Uint8Array;\n private readonly mask: number;\n\n constructor(buf: Uint8Array, private readonly params: BloomFilterParams) {\n if ((params.m & (params.m - 1)) !== 0) {\n throw new Error(`Bloom filter m must be a power of 2, got ${params.m}`);\n }\n if (buf.length !== params.m >> 3) {\n throw new Error(\n `Bloom filter buffer size mismatch: expected ${params.m >> 3} bytes, got ${buf.length}`\n );\n }\n this.buf = buf;\n this.mask = params.m - 1;\n }\n\n /** Build from the wire format (base64 bytes + explicit params). */\n static fromBase64(bloomB64: string, params: BloomFilterParams): BloomFilter {\n const bytes = base64ToBytes(bloomB64);\n return new BloomFilter(bytes, params);\n }\n\n /**\n * Returns true if `name` is probably in the set — possibly with the\n * filter's configured false-positive rate. FALSE is always authoritative.\n *\n * FP here means: SDK thinks a name is already registered when it isn't.\n * That costs one wasted server round-trip (gateway does the exact check\n * and catches it) — strictly safer than a false-negative, which could\n * leak a novel name past the SDK.\n */\n has(name: string): boolean {\n const h1 = murmurhash3_x86_32(name, this.params.seedA);\n const h2 = murmurhash3_x86_32(name, this.params.seedB);\n\n for (let i = 0; i < this.params.k; i++) {\n // >>> 0 at each step to keep arithmetic in unsigned 32-bit land;\n // we can't just take & mask at the end because h1 + i*h2 could\n // overflow past 2^32 when i*h2 is large.\n const combined = (h1 + Math.imul(i, h2)) >>> 0;\n const idx = combined & this.mask;\n const bit = this.buf[idx >> 3] & (1 << (idx & 7));\n if (bit === 0) return false;\n }\n return true;\n }\n}\n","/**\n * NameGovernor — client-side event-name cap enforcement.\n *\n * The governor consumes an `EventGovernanceHint` from the bootstrap response\n * and decides whether to let a `track()` call proceed to the network or drop\n * it locally.\n *\n * Why this exists:\n * Without it, a page that calls `track('new_btn_' + Date.now())` in a\n * render loop would (a) pass the local rate-limiter if within burst, (b)\n * force the gateway to ask control-plane for a verdict on every unique\n * name, and (c) amplify the CP `/event-governance/check` load quadratically\n * in the number of tabs firing the same bug. The bloom filter gives the\n * SDK enough information to drop novel names locally once the org hits\n * its cap, collapsing the amplification to zero.\n *\n * Design constraints:\n * • FAIL-OPEN — missing hint (Enterprise org, Redis outage) lets every\n * name through. The gateway is still the authoritative cap.\n * • FALSE-POSITIVE-SAFE — if the bloom says \"known\" for a name that isn't\n * actually registered, we send to gateway and the gateway's exact check\n * catches it. FPs cost one round trip, not a cap bypass.\n * • LOCAL-MEMO — a novel name that has already charged `remainingNewNames`\n * in this tab must NOT charge again on subsequent calls within the same\n * hint TTL. Without this, `track('new_btn_click')` fired 50 times would\n * drain 50 from the counter and block every OTHER legitimate novel name.\n * See `localNovelNames`.\n *\n * See docs/architecture/RFC_2026_04_SDK_GOVERNANCE_HINTS.md §3.3.\n */\n\nimport { BloomFilter } from './bloom-filter';\n\n/** Shape of the hint delivered by `/v1/sdk/bootstrap`. */\nexport interface EventGovernanceHint {\n bloom_algo: string;\n seed_a: number;\n seed_b: number;\n k: number;\n m: number;\n bloom_b64: string;\n remaining_new_names: number | null;\n /**\n * When true, the server is in its 7-day soft-cap grace window: it accepts\n * novel event names past the cap. SDK must NOT drop locally in this mode —\n * doing so would enforce harder than the server. See\n * apps/control-plane/app/schemas/event_governance_hint.py for the canonical\n * contract.\n */\n grace_active?: boolean;\n ttl_seconds: number;\n}\n\nexport interface DropReport {\n /** Map of event_name → count of local drops since last drain. */\n events: Record<string, number>;\n /** Total events dropped across all names (sum of values). */\n total: number;\n /** When the report window started (ms since epoch). */\n since: number;\n}\n\n/** Matches the `bloom_algo` tag shipped by the current control-plane build. */\nconst SUPPORTED_ALGO = 'mmh3_x86_32_km';\n\n/**\n * Best-effort console.warn — coalesced so a runaway render loop doesn't\n * flood the dev console. We only warn on the FIRST distinct dropped name;\n * subsequent names silently increment the telemetry counter.\n */\nfunction warnOncePerSession(message: string): void {\n if (typeof console === 'undefined' || typeof console.warn !== 'function') return;\n console.warn(message);\n}\n\nexport class NameGovernor {\n private bloom: BloomFilter | null = null;\n private remainingNewNames: number = Infinity;\n private graceActive: boolean = false;\n\n /**\n * Names this SDK instance has seen AS NOVEL and already charged against\n * `remainingNewNames`. Reset on every `ingestHint()` so we don't leak\n * accounting across hint refreshes.\n */\n private localNovelNames: Set<string> = new Set();\n\n /** Coalesced telemetry — flushed to the transport via drainDropReport(). */\n private droppedSinceLastReport: Map<string, number> = new Map();\n private reportWindowStart: number = Date.now();\n private hasWarnedThisSession = false;\n\n /**\n * Ingest a freshly-bootstrapped hint. Call on every successful bootstrap.\n * Passing `null` disables governance (fail-open).\n */\n ingestHint(hint: EventGovernanceHint | null): void {\n if (!hint || hint.bloom_algo !== SUPPORTED_ALGO) {\n // Unknown algo — a newer CP ships a version this SDK can't decode.\n // Silently disable governance; gateway remains authoritative.\n this.bloom = null;\n this.remainingNewNames = Infinity;\n this.graceActive = false;\n this.localNovelNames.clear();\n return;\n }\n\n try {\n this.bloom = BloomFilter.fromBase64(hint.bloom_b64, {\n m: hint.m,\n k: hint.k,\n seedA: hint.seed_a,\n seedB: hint.seed_b,\n });\n } catch {\n // Malformed hint — fail-open. Logged by the caller.\n this.bloom = null;\n }\n\n this.remainingNewNames = hint.remaining_new_names ?? Infinity;\n this.graceActive = hint.grace_active === true;\n this.localNovelNames.clear();\n }\n\n /**\n * Decide whether a `track()` call should proceed.\n *\n * Returns true = send to network (rate-limiter still runs after).\n * Returns false = drop locally; caller should return early.\n */\n shouldSend(eventName: string): boolean {\n // No hint = unlimited plan or fail-open. Send everything.\n if (!this.bloom) return true;\n\n // 7-day soft-cap grace window is active — server accepts novel names\n // past the cap, so SDK must not enforce harder. Fail-open to gateway.\n if (this.graceActive) return true;\n\n // Known name — send.\n if (this.bloom.has(eventName)) return true;\n\n // Already charged in this session — send (gateway has it cached too).\n if (this.localNovelNames.has(eventName)) return true;\n\n // Novel name, within headroom — charge once, send.\n if (this.remainingNewNames > 0) {\n this.localNovelNames.add(eventName);\n this.remainingNewNames -= 1;\n return true;\n }\n\n // Novel name, over the cap — drop locally, record for telemetry.\n const prev = this.droppedSinceLastReport.get(eventName) ?? 0;\n this.droppedSinceLastReport.set(eventName, prev + 1);\n\n // Only warn once per session, only on the first distinct dropped name —\n // a runaway loop will fill droppedSinceLastReport silently.\n if (!this.hasWarnedThisSession) {\n this.hasWarnedThisSession = true;\n warnOncePerSession(\n `[aegis] Event-name cap reached — \"${eventName}\" dropped locally. ` +\n `Upgrade your plan or remove dynamically-generated event names.`\n );\n }\n return false;\n }\n\n /**\n * Snapshot + reset the dropped-names counter. Called by the telemetry\n * beacon on batch flush so the gateway gets visibility into client-side\n * drops for ops dashboards.\n */\n drainDropReport(): DropReport | null {\n if (this.droppedSinceLastReport.size === 0) return null;\n\n const events: Record<string, number> = {};\n let total = 0;\n for (const [name, count] of this.droppedSinceLastReport) {\n events[name] = count;\n total += count;\n }\n\n const since = this.reportWindowStart;\n this.droppedSinceLastReport.clear();\n this.reportWindowStart = Date.now();\n\n return { events, total, since };\n }\n\n // Test-only accessors — not part of public API but easier than reflection.\n /** @internal */\n _debugState(): {\n hasBloom: boolean;\n remaining: number;\n localNovel: number;\n graceActive: boolean;\n } {\n return {\n hasBloom: this.bloom !== null,\n remaining: this.remainingNewNames,\n localNovel: this.localNovelNames.size,\n graceActive: this.graceActive,\n };\n }\n}\n","/**\n * TraitGovernor — client-side guards for trait writes (P10.5).\n *\n * Runs, client-side, stage 1 of the trait-key rule the cell-plane backend\n * applies at EVERY write of `contacts.attributes`\n * (`data_governance.trait_keys.govern_trait_payload`; docs/agent-rules/\n * TRAIT_VOCABULARY.md), plus the value guards, so the SDK can warn developers\n * about problematic keys/values BEFORE network send.\n *\n * Why two chokepoints:\n * - **Backend** (`govern_trait_payload` → DLQ): authoritative; it decides the\n * stored key for payloads that bypass the SDK (direct HTTP, CSV import,\n * integration workers) and for older SDKs, and adds stage 2 (ASCII only,\n * accent fold, <= 64 chars). Operators see refused keys, with their value,\n * in the Validation tab.\n * - Key-rule parity: libs/mobile-sdk/tests/drift/trait-governor-verdicts.json\n * (`key_vectors`) is read by tests/trait-governor-vectors.test.ts and the\n * Python guard test_drift_guard_trait_key_rule_parity.py.\n * - **SDK** (this file): developer-facing; warns in console.warn at dev\n * time so the issue is caught BEFORE the bad data hits production. We\n * normalize what we can (key casing, value truncation, date format)\n * and warn-then-drop what we can't (reserved prefixes).\n *\n * \"First-3 per verdict per session\" — we warn at most 3 times for each\n * verdict per `(workspace_id, verdict)` key in any given page load. After\n * that, silent — the developer got the message; further warnings would\n * just spam the console and obscure other issues.\n *\n * Canonical contract: the verdict codes here MUST match\n * `data_governance.ingestion_guards.GuardResult.verdict` codes + the\n * `ingestion_dlq.verdict` DB CHECK + the FE `IngestionDLQVerdict` union.\n * Real-env smoke asserts BE ↔ DB drift; TS narrowing catches FE drift;\n * this file completes the four-surface drift protection.\n */\n\nexport type TraitVerdict =\n | 'bad_key_format'\n | 'value_too_long'\n | 'bad_date_format'\n | 'name_too_long' // not used here (event-name guard); kept in union for symmetry\n | 'reserved_prefix';\n\nexport interface TraitDrop {\n /** Original key as the developer wrote it. */\n originalKey: string;\n /** What the guard decided. */\n verdict: TraitVerdict;\n /** Human-readable reason — same text we'd log to ingestion_dlq.reason. */\n reason: string;\n}\n\nexport interface TraitResult {\n /**\n * Sanitized traits to actually send. Reserved-prefix keys are absent;\n * camelCase keys are rewritten to snake_case; long values truncated;\n * ISO dates → epoch ms.\n */\n sanitized: Record<string, unknown>;\n /** Keys that were dropped or modified (one row per change). */\n drops: TraitDrop[];\n}\n\n// Reserved namespace prefixes — mirrors\n// data_governance.ingestion_guards.DEFAULT_RESERVED_PREFIXES.\nconst RESERVED_PREFIXES: readonly string[] = [\n 'system.',\n 'user.',\n 'loyalty.',\n 'review.',\n 'cart.',\n 'checkout.',\n 'product.',\n 'pos.',\n 'bill.',\n 'feedback.',\n 'chat.',\n 'delivery.',\n 'event.',\n '$',\n '_',\n];\n\n// PII not detected here — that's done server-side by the canonical\n// is_likely_pii helper. SDK side handles only normalization + format\n// rejections that benefit from early warning.\n\nconst KEY_SOFT_VALUE_CAP = 512; // truncate\nconst KEY_HARD_VALUE_CAP = 10_000; // reject (DoS protection)\n\nconst CAMEL_BOUNDARY_1 = /(.)([A-Z][a-z]+)/g;\nconst CAMEL_BOUNDARY_2 = /([a-z0-9])([A-Z])/g;\nconst NON_SNAKE = /[\\s\\-.]+/g;\nconst DUPE_UNDERSCORE = /_+/g;\nconst ISO_8601 = /^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?)?$/;\n\nconst DATE_KEY_HINTS = new Set([\n 'at', 'on', 'date', 'time', 'timestamp', 'dob', 'birthday',\n 'joined', 'expired', 'expires', 'created', 'updated', 'started', 'ended',\n]);\n\n/**\n * Normalize camelCase / PascalCase / dash-or-space-separated keys to\n * snake_case. Returns `null` if the key reduces to empty (caller treats\n * as `bad_key_format`).\n */\nfunction normalizeKey(key: string): string | null {\n if (!key) return null;\n const stage1 = key.replace(CAMEL_BOUNDARY_1, '$1_$2').replace(CAMEL_BOUNDARY_2, '$1_$2');\n const stage2 = stage1.replace(NON_SNAKE, '_').toLowerCase();\n const result = stage2.replace(DUPE_UNDERSCORE, '_').replace(/^_+|_+$/g, '');\n return result || null;\n}\n\nfunction startsWithReserved(key: string): string | null {\n const lower = key.toLowerCase();\n for (const prefix of RESERVED_PREFIXES) {\n if (lower.startsWith(prefix)) return prefix;\n }\n return null;\n}\n\nfunction looksLikeDateKey(key: string): boolean {\n for (const part of key.toLowerCase().split(/[_\\-.\\s]+/)) {\n if (DATE_KEY_HINTS.has(part)) return true;\n }\n return false;\n}\n\n/**\n * ISO-8601 / epoch string → epoch ms (number). Returns null on parse\n * failure. Numeric inputs assumed epoch (seconds if <1e11, else ms).\n */\nfunction parseDateValue(value: unknown): number | null {\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value < 1e11 ? Math.floor(value * 1000) : Math.floor(value);\n }\n if (typeof value === 'string' && value) {\n const s = value.trim();\n if (ISO_8601.test(s)) {\n const ms = Date.parse(s);\n if (!Number.isNaN(ms)) return ms;\n }\n const asNum = Number(s);\n if (Number.isFinite(asNum)) {\n return asNum < 1e11 ? Math.floor(asNum * 1000) : Math.floor(asNum);\n }\n }\n return null;\n}\n\nfunction warnOnConsole(message: string): void {\n if (typeof console === 'undefined' || typeof console.warn !== 'function') return;\n console.warn(message);\n}\n\nexport class TraitGovernor {\n /** Cap warnings at 3 per (workspace_id, verdict) per session. */\n private static readonly WARN_CAP = 3;\n /** workspace_id || '__no_workspace__' → verdict → count. */\n private warnCounts: Map<string, Map<TraitVerdict, number>> = new Map();\n\n /**\n * Apply all guards to a traits object. Returns the sanitized payload\n * to send + a list of drops/modifications.\n *\n * Pass `workspace_id` so warning rate-limits scope per workspace; an\n * agency user switching workspaces won't have their warning budget\n * consumed cross-workspace.\n */\n process(\n traits: Record<string, unknown> | null | undefined,\n workspace_id?: string | null,\n ): TraitResult {\n const sanitized: Record<string, unknown> = {};\n const drops: TraitDrop[] = [];\n if (!traits || typeof traits !== 'object') {\n return { sanitized, drops };\n }\n\n for (const rawKey of Object.keys(traits)) {\n // 1. Reserved-prefix check runs on the ORIGINAL key, BEFORE\n // normalization. Otherwise `system.foo` would normalize to\n // `system_foo` (the `.` collapses to `_`) and bypass the\n // reserved check. This is the same order-of-operations bug\n // we caught at smoke time on the backend (2026-05-13).\n const prefix = startsWithReserved(rawKey);\n if (prefix !== null) {\n drops.push({\n originalKey: rawKey,\n verdict: 'reserved_prefix',\n reason: `key uses reserved namespace ${JSON.stringify(prefix)}`,\n });\n continue;\n }\n\n // 2. Normalize key casing.\n const normalizedKey = normalizeKey(rawKey);\n if (normalizedKey === null) {\n drops.push({\n originalKey: rawKey,\n verdict: 'bad_key_format',\n reason: `key reduced to empty after normalization`,\n });\n continue;\n }\n\n // 3. Re-check reserved on normalized form (belt-and-braces).\n if (startsWithReserved(normalizedKey) !== null) {\n drops.push({\n originalKey: rawKey,\n verdict: 'reserved_prefix',\n reason: `normalized key ${JSON.stringify(normalizedKey)} still uses a reserved namespace`,\n });\n continue;\n }\n\n // 4. Value-side guards.\n let value = traits[rawKey];\n\n // 4a. Truncate long strings (soft cap); reject huge strings (hard cap).\n if (typeof value === 'string') {\n if (value.length > KEY_HARD_VALUE_CAP) {\n drops.push({\n originalKey: rawKey,\n verdict: 'value_too_long',\n reason: `value length ${value.length} exceeds hard cap ${KEY_HARD_VALUE_CAP}`,\n });\n continue;\n }\n if (value.length > KEY_SOFT_VALUE_CAP) {\n drops.push({\n originalKey: rawKey,\n verdict: 'value_too_long',\n reason: `value truncated from ${value.length} to ${KEY_SOFT_VALUE_CAP} chars`,\n });\n value = value.slice(0, KEY_SOFT_VALUE_CAP);\n }\n }\n\n // 4b. Date normalization — only when the key hints at date semantics\n // AND the value looks string-shaped. Numeric values are assumed\n // epoch already. Free-form strings on non-date-keyed properties\n // pass through (caller meant a string).\n if (looksLikeDateKey(normalizedKey) && typeof value === 'string') {\n const parsed = parseDateValue(value);\n if (parsed === null) {\n drops.push({\n originalKey: rawKey,\n verdict: 'bad_date_format',\n reason: `value ${JSON.stringify(value)} on date-keyed field ${JSON.stringify(normalizedKey)} didn't parse as ISO-8601 / epoch`,\n });\n continue;\n }\n value = parsed;\n }\n\n sanitized[normalizedKey] = value;\n }\n\n // Emit first-3-per-verdict warnings (silent past the cap).\n for (const drop of drops) {\n this.maybeWarn(workspace_id ?? null, drop);\n }\n\n return { sanitized, drops };\n }\n\n private maybeWarn(workspace_id: string | null, drop: TraitDrop): void {\n const ws = workspace_id ?? '__no_workspace__';\n let perVerdict = this.warnCounts.get(ws);\n if (!perVerdict) {\n perVerdict = new Map();\n this.warnCounts.set(ws, perVerdict);\n }\n const count = perVerdict.get(drop.verdict) ?? 0;\n if (count >= TraitGovernor.WARN_CAP) return;\n perVerdict.set(drop.verdict, count + 1);\n warnOnConsole(\n `[Active Reach SDK] trait ${drop.verdict}: ${drop.reason} ` +\n `(original key: ${JSON.stringify(drop.originalKey)}). ` +\n `Backend will reject; fix the SDK call to silence this warning.`,\n );\n }\n}\n","/**\n * UserNamespace — typed PII + per-channel opt-in setters that delegate to\n * `Aegis.identify()`. WebEngage-/CleverTap-parity ergonomics.\n *\n * Pre-login `setX` calls accumulate in `pendingTraits` and flush as one\n * identify() when `login()` fires — avoids polluting the contact graph\n * with anonymous-id-as-userId rows.\n *\n * See docs/architecture/SDK_USER_NAMESPACE_AND_SCREEN.md.\n */\n\nimport type { Aegis } from './analytics';\nimport { logger } from '../utils/logger';\n\nexport type OptInChannel =\n | 'email'\n | 'sms'\n | 'push'\n | 'webpush'\n | 'whatsapp'\n | 'rcs'\n | 'inapp';\n\nconst VALID_CHANNELS: ReadonlySet<OptInChannel> = new Set<OptInChannel>([\n 'email',\n 'sms',\n 'push',\n 'webpush',\n 'whatsapp',\n 'rcs',\n 'inapp',\n]);\n\n// Conservative RFC 5322 subset — same shape every CEP peer uses on the\n// browser side. Server-side validation is authoritative.\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n// E.164: leading '+' then 8–15 digits.\nconst PHONE_RE = /^\\+[1-9]\\d{7,14}$/;\n// SHA-256 hex string: exactly 64 hex chars.\nconst SHA256_HEX_RE = /^[a-f0-9]{64}$/i;\n// ISO date: YYYY-MM-DD (we don't accept full ISO datetime — birth dates\n// don't have a time component).\nconst ISO_DATE_RE = /^\\d{4}-\\d{2}-\\d{2}$/;\n\nexport class UserNamespace {\n private readonly aegis: Aegis;\n private pendingTraits: Record<string, unknown> = {};\n\n constructor(aegis: Aegis) {\n this.aegis = aegis;\n }\n\n /**\n * Authoritative identity write. Flushes any pending pre-login traits\n * along with the supplied `traits` argument as a single identify call.\n */\n login(userId: string, traits?: Record<string, unknown>): void {\n if (typeof userId !== 'string' || userId.length === 0) {\n logger.warn('[user.login] userId must be a non-empty string');\n return;\n }\n const merged = { ...this.pendingTraits, ...(traits || {}) };\n this.pendingTraits = {};\n this.aegis.identify(userId, merged);\n }\n\n /**\n * Drops the current userId and any pending pre-login traits. Does NOT\n * fire a server-side logout event — that's a separate explicit `track`.\n */\n logout(): void {\n this.pendingTraits = {};\n this.aegis.reset();\n }\n\n setAttribute(key: string, value: unknown): void {\n if (typeof key !== 'string' || key.length === 0) {\n logger.warn('[user.setAttribute] key must be a non-empty string');\n return;\n }\n this.writeTraits({ [key]: value });\n }\n\n setAttributes(map: Record<string, unknown>): void {\n if (!map || typeof map !== 'object') {\n logger.warn('[user.setAttributes] map must be an object');\n return;\n }\n this.writeTraits(map);\n }\n\n setEmail(email: string): void {\n if (!EMAIL_RE.test(email)) {\n logger.warn('[user.setEmail] invalid email format');\n return;\n }\n this.writeTraits({ email: email.toLowerCase() });\n }\n\n setPhone(phone: string): void {\n if (!PHONE_RE.test(phone)) {\n logger.warn('[user.setPhone] phone must be E.164 (e.g. +15551234567)');\n return;\n }\n this.writeTraits({ phone });\n }\n\n setHashedEmail(sha256Hex: string): void {\n if (!SHA256_HEX_RE.test(sha256Hex)) {\n logger.warn('[user.setHashedEmail] expected 64-char hex SHA-256');\n return;\n }\n this.writeTraits({ email_sha256: sha256Hex.toLowerCase() });\n }\n\n setHashedPhone(sha256Hex: string): void {\n if (!SHA256_HEX_RE.test(sha256Hex)) {\n logger.warn('[user.setHashedPhone] expected 64-char hex SHA-256');\n return;\n }\n this.writeTraits({ phone_sha256: sha256Hex.toLowerCase() });\n }\n\n setBirthDate(iso: string): void {\n if (!ISO_DATE_RE.test(iso)) {\n logger.warn('[user.setBirthDate] expected YYYY-MM-DD');\n return;\n }\n this.writeTraits({ birth_date: iso });\n }\n\n setOptIn(channel: OptInChannel, granted: boolean): void {\n if (!VALID_CHANNELS.has(channel)) {\n logger.warn(`[user.setOptIn] unknown channel: ${channel}`);\n return;\n }\n if (typeof granted !== 'boolean') {\n logger.warn('[user.setOptIn] granted must be a boolean');\n return;\n }\n this.writeTraits({ [`opt_in_${channel}`]: granted });\n }\n\n /**\n * HMAC-signed identity token. Ingress-side verification not yet wired —\n * the trait is forwarded as-is and persisted on the contact record\n * until that lands.\n */\n setSecureToken(token: string): void {\n if (typeof token !== 'string' || token.length === 0) {\n logger.warn('[user.setSecureToken] token must be a non-empty string');\n return;\n }\n this.writeTraits({ _secure_token: token });\n }\n\n /**\n * Test/inspection hook — returns a copy of the pending traits buffer.\n * Used by the e2e smoke test to assert pre-login accumulation.\n */\n _getPendingTraits(): Record<string, unknown> {\n return { ...this.pendingTraits };\n }\n\n // ---------------------------------------------------------------------------\n\n private writeTraits(traits: Record<string, unknown>): void {\n const userId = this.aegis.getUserId();\n if (userId) {\n this.aegis.identify(userId, traits);\n return;\n }\n Object.assign(this.pendingTraits, traits);\n }\n}\n","import {\n AegisConfig,\n AegisConfigInternal,\n DEFAULT_CONFIG,\n CellEndpoint,\n} from '../types/config';\nimport {\n TrackEvent,\n IdentifyEvent,\n PageEvent,\n GroupEvent,\n AliasEvent,\n ScreenEvent,\n AegisEvent,\n} from '../types/events';\nimport { Plugin } from '../types/plugin';\nimport { Identity } from '../utils/identity';\nimport { SessionManager } from './session';\nimport { EventQueue } from './queue';\nimport { isPurchaseEvent } from './purchase-events';\nimport { Transport } from './transport';\nimport { Storage } from '../utils/storage';\nimport { buildContext, isBot } from '../utils/device';\nimport { generateMessageId } from '../utils/uuid';\nimport { logger } from '../utils/logger';\nimport { PluginRegistry } from '../plugins/registry';\nimport { ConsentManager, ConsentPreferences, ConsentCategory } from '../utils/consent';\nimport { captureMetaCookies, redactMetaCookies } from '../utils/meta-cookies';\nimport {\n parseAdClickIDs,\n hasAdClickIDs,\n parseLinkAttribution,\n type LinkAttribution,\n} from '../utils/url-parser';\nimport { redactUrl } from '../utils/redact-url';\nimport { isPreviewPage } from '../utils/preview-as-of';\nimport { EcommerceTracker } from '../ecommerce';\nimport { RateLimiter } from './rate-limiter';\nimport { NameGovernor, EventGovernanceHint, TraitGovernor } from '../governance';\nimport { UserNamespace } from './user-namespace';\n\n/** One redeemable reward for the identified contact (from `contact_entitlements`). */\nexport interface EntitlementItem {\n id: string;\n /** coupon | discount | points | free_delivery | freebie */\n type: string;\n label: string | null;\n /** Real, redeemable code (coupon/discount) — apply at checkout. */\n coupon_code: string | null;\n /** Awarded points (points grants). */\n points: number | null;\n /** Outlet the grant is attributed to; null = org-wide. */\n location_id: string | null;\n /** ISO 8601 expiry, or null for no expiry. */\n expires_at: string | null;\n}\n\n/**\n * An earned reward the brand's reward item gate WITHHELD (e.g. the free item is\n * not available right now). Never redeemable and never carries a code; show it\n * as a \"Reward withheld\" line with `message`, apart from `entitlements`.\n */\nexport interface WithheldRewardItem {\n id: string;\n status: 'withheld';\n label: string | null;\n /** Customer-facing reason, e.g. \"Choco pastry isn't available right now. ...\" */\n message: string;\n /** ISO 8601 time the reward was earned and withheld. */\n withheld_at: string | null;\n}\n\n/** Response of `aegis.getRewards()` / `GET /api/v1/sdk/entitlements`. */\nexport interface RewardsResponse {\n contact_id: string;\n loyalty: { points_balance: number; tier: string | null };\n entitlements: EntitlementItem[];\n /** Withheld rewards (last 30 days). Absent from an older cell. */\n withheld?: WithheldRewardItem[];\n}\n\nexport class Aegis {\n private config: AegisConfigInternal | null = null;\n private storage!: Storage;\n private identity!: Identity;\n /** Server-minted proof of the current contact (C1b). No setter is wired\n * from `identify()` today — a host with a runtime (AegisMessageRuntime)\n * calls `setContactToken()` alongside `runtime.updateContactId()`. */\n private contactToken?: string;\n private session: SessionManager | null = null;\n private queue: EventQueue | null = null;\n private transport: Transport | null = null;\n private plugins: PluginRegistry = new PluginRegistry();\n private initPromise: Promise<void> | null = null;\n private consent: ConsentManager | null = null;\n private _ecommerce: EcommerceTracker | null = null;\n private _user: UserNamespace | null = null;\n private rateLimiter: RateLimiter | null = null;\n private nameGovernor: NameGovernor = new NameGovernor();\n // P10.5 — client-side guards for trait writes. Mirrors the BE\n // chokepoint in `record_attribute_keys` so developers see console\n // warnings about reserved-prefix / bad-key / bad-date traits at\n // dev time, BEFORE the data hits production.\n private traitGovernor: TraitGovernor = new TraitGovernor();\n private _lastPageUrl: string | null = null;\n private _popstateHandler: (() => void) | null = null;\n private _originalPushState: typeof history.pushState | null = null;\n private _originalReplaceState: typeof history.replaceState | null = null;\n\n // B1.2 — last messageId per event name. Tenants who run their own Meta\n // Pixel via GTM call `aegis.lastEventId('Purchase')` to retrieve the id\n // we generated, then pass it as `eventID` to their `fbq('track', ...)`\n // call. Meta dedups on (pixel_id, event_name, event_id) so the\n // browser-fired Pixel event and our server-side CAPI event collapse to\n // one. See docs/integrations/META_PIXEL_COEXISTENCE.md.\n private _lastEventIds: Map<string, string> = new Map();\n\n // Plugin-handshake P1 — workspace_code allowlist for path-segment\n // detection. Ingested from the bootstrap response via\n // `ingestWorkspaceCodes()`. Empty set = no codes registered for this\n // org (single-outlet tenant); path-detection cascade is skipped.\n private _workspaceCodes: Set<string> = new Set();\n\n // Plugin-handshake P1 (Track E) — runtime workspace selection via\n // aegis.setWorkspace(). Persisted to sessionStorage for the page-load\n // session so SPA navigations + reloads on the same outlet inherit it.\n private _runtimeWorkspace: string | null = null;\n\n // P15.1 — runtime LOCATION selection (outlet code or id), via\n // aegis.setLocation(). Independent of _runtimeWorkspace under the\n // post-2026-05-26 hierarchy: workspace = brand-tenant, location =\n // outlet within a brand. Both can be set on the same SDK instance\n // (e.g. multi-brand agency dashboard navigating between brands +\n // selecting outlets within each).\n private _runtimeLocation: string | null = null;\n\n async init(\n writeKey: string,\n config?: Partial<AegisConfig>\n ): Promise<void> {\n if (this.initPromise) {\n return this.initPromise;\n }\n\n this.initPromise = this._init(writeKey, config);\n return this.initPromise;\n }\n\n private async _init(\n writeKey: string,\n config?: Partial<AegisConfig>\n ): Promise<void> {\n if (this.config?.initialized) {\n logger.warn('SDK already initialized');\n return;\n }\n\n if (this.shouldRespectDNT(config)) {\n logger.info('Do Not Track is enabled, SDK disabled');\n return;\n }\n\n // An editor preview link (dated or not: `?preview_as_of=`,\n // `?section_names=1`, `?preview_store=`, `?campaign_preview=`,\n // `?preview=admin`) is a preview, never a visit: no page view, no event,\n // no identify from it.\n if (isPreviewPage()) {\n logger.info('Editor preview, SDK records nothing');\n return;\n }\n\n if (isBot()) {\n logger.info('Bot detected, SDK disabled');\n return;\n }\n\n this.config = this.buildConfig(writeKey, config);\n\n if (this.config.debug) {\n logger.enable();\n }\n\n logger.info('Initializing Active Reach SDK...', this.config);\n\n this.storage = new Storage({\n cookieDomain: this.config.cookie_domain,\n secureCookie: this.config.secure_cookie,\n crossDomain: this.config.cross_domain_tracking,\n });\n\n this.identity = new Identity(this.storage);\n\n this.consent = new ConsentManager(this.storage, {\n defaultConsent: this.config.default_consent,\n waitForConsent: this.config.wait_for_consent,\n });\n\n if (this.config.integrate_onetrust) {\n this.consent.integrateOneTrust();\n }\n\n if (this.config.integrate_cookiebot) {\n this.consent.integrateCookiebot();\n }\n\n if (this.config.integrate_google_consent_mode) {\n this.consent.integrateGoogleConsentMode();\n }\n\n this.session = new SessionManager(\n this.storage,\n this.config.session_timeout\n );\n\n this.captureAdClickIDsOnInit();\n\n this.transport = new Transport(\n {\n writeKey: this.config.write_key,\n apiHost: this.config.api_host,\n cellEndpoints: this.config.cell_endpoints,\n preferredRegion: this.config.preferred_region,\n autoRegionDetection: this.config.auto_region_detection,\n requestTimeout: this.config.request_timeout,\n retryFailedRequests: this.config.retry_failed_requests,\n maxRetries: this.config.max_retries,\n retryBackoffMultiplier: this.config.retry_backoff_multiplier,\n },\n this.storage\n );\n\n this.config.active_cell = this.transport.getActiveCell();\n\n this.queue = new EventQueue(\n {\n batchSize: this.config.batch_size,\n batchInterval: this.config.batch_interval,\n enableOfflineMode: this.config.enable_offline_mode,\n maxOfflineEvents: this.config.max_offline_events,\n persistNamespace: this.config.write_key,\n },\n this.transport,\n this.storage\n );\n\n this.rateLimiter = new RateLimiter({\n burstCapacity: this.config.rate_limit_burst,\n refillPerSecond: this.config.rate_limit_per_second,\n onDropBatch: (count, sampleName) => this.emitRateLimitMeta(count, sampleName),\n });\n\n await this.initializePlugins();\n\n if (this.config.auto_page_view) {\n this.page();\n this.startSPATracking();\n }\n\n logger.info('Active Reach SDK initialized successfully');\n }\n\n /**\n * SPA navigation tracking — monkey-patches pushState/replaceState and\n * listens for popstate to fire page() on every client-side route change.\n */\n private startSPATracking(): void {\n this._lastPageUrl = window.location.href;\n\n const onRouteChange = () => {\n // Debounce: only fire if URL actually changed\n const currentUrl = window.location.href;\n if (currentUrl === this._lastPageUrl) return;\n this._lastPageUrl = currentUrl;\n\n // Small delay to let the framework update document.title\n setTimeout(() => {\n // A host that mounts one SDK instance per page (Next.js route\n // components) navigates via pushState BEFORE the old page unmounts;\n // the old instance's patched pushState schedules this callback and is\n // then destroyed. It must not emit — the new page's instance fires its\n // own page view on init, so emitting here double-counts the view.\n if (!this._popstateHandler) return;\n this.page();\n }, 50);\n };\n\n // Listen for browser back/forward\n this._popstateHandler = onRouteChange;\n window.addEventListener('popstate', this._popstateHandler);\n\n // Monkey-patch pushState and replaceState\n this._originalPushState = history.pushState.bind(history);\n this._originalReplaceState = history.replaceState.bind(history);\n\n history.pushState = (...args: Parameters<typeof history.pushState>) => {\n this._originalPushState!(...args);\n onRouteChange();\n };\n\n history.replaceState = (...args: Parameters<typeof history.replaceState>) => {\n this._originalReplaceState!(...args);\n onRouteChange();\n };\n }\n\n private stopSPATracking(): void {\n if (this._popstateHandler) {\n window.removeEventListener('popstate', this._popstateHandler);\n this._popstateHandler = null;\n }\n\n if (this._originalPushState) {\n history.pushState = this._originalPushState;\n this._originalPushState = null;\n }\n\n if (this._originalReplaceState) {\n history.replaceState = this._originalReplaceState;\n this._originalReplaceState = null;\n }\n }\n\n private buildConfig(\n writeKey: string,\n config?: Partial<AegisConfig>\n ): AegisConfigInternal {\n return {\n ...DEFAULT_CONFIG,\n ...config,\n write_key: writeKey,\n initialized: true,\n } as AegisConfigInternal;\n }\n\n private shouldRespectDNT(config?: Partial<AegisConfig>): boolean {\n const respectDNT = config?.respect_dnt !== false;\n if (!respectDNT) return false;\n\n const dnt =\n navigator.doNotTrack ||\n (window as any).doNotTrack ||\n (navigator as any).msDoNotTrack;\n\n return dnt === '1' || dnt === 'yes';\n }\n\n private captureAdClickIDsOnInit(): void {\n if (!this.session) return;\n\n const adClickIDs = parseAdClickIDs();\n\n if (hasAdClickIDs(adClickIDs)) {\n // The landing page is persisted and rides every event's context as\n // `landingPage` — redact its credential params before it is stored.\n this.session.setAdClickIDs(adClickIDs, redactUrl(window.location.href));\n logger.info('Ad click IDs captured on page load:', adClickIDs);\n }\n\n // The Aegis short-link redirect stamps `aegis_code` (+ the link row's\n // attribution) on the landing URL. Captured once, here, beside the ad\n // click ids: it is the join key that names the send which brought this\n // visitor, and it has to outlive the landing URL to reach the order.\n const linkAttribution = parseLinkAttribution();\n if (linkAttribution.aegis_code) {\n this.session.setLinkAttribution(linkAttribution);\n }\n }\n\n private async initializePlugins(): Promise<void> {\n if (!this.config) return;\n\n for (const pluginName of this.config.plugins) {\n logger.debug(`Initializing plugin: ${pluginName}`);\n }\n\n await this.plugins.executeHook('init', this.config);\n }\n\n use(plugin: Plugin): void {\n this.plugins.register(plugin);\n\n if (this.config?.initialized && plugin.init) {\n Promise.resolve(plugin.init(this.config)).catch((error: any) => {\n logger.error(`Failed to initialize plugin \"${plugin.name}\":`, error);\n });\n }\n }\n\n /**\n * Symmetric counterpart to `use(plugin)`. Calls the plugin's `destroy()`\n * hook (if defined) and removes it from the registry so its hooks no\n * longer fire on subsequent events. Safe to call with a name that\n * isn't registered — logs a warning and returns.\n *\n * Primary use case: React components that register a plugin in\n * `useEffect` and need to unregister in the cleanup function so HMR /\n * provider remount doesn't leak listeners. See cashier-portal's\n * MetaPixelInjector for an example.\n */\n removePlugin(name: string): void {\n this.plugins.unregister(name);\n }\n\n /**\n * Plugin-handshake P1 — ingest the workspace_code allowlist from the\n * bootstrap response. Pass `result.workspaceCodes` from `bootstrap()`\n * here so the SDK can do path-segment workspace detection on\n * customer-facing pages like `/south/rewards`, `/ghatkopar/feedback`.\n *\n * Empty array is the right answer for single-outlet tenants — SDK\n * will skip the path cascade and fall through to query param /\n * setWorkspace() / gateway origin lookup.\n *\n * Safe to call before init() — the set is consulted at event-fire time.\n */\n ingestWorkspaceCodes(codes: string[] | null | undefined): void {\n this._workspaceCodes = new Set(\n (codes ?? []).filter((c) => typeof c === 'string' && c.length > 0),\n );\n logger.debug('Workspace codes ingested', { count: this._workspaceCodes.size });\n }\n\n /**\n * Plugin-handshake P1 (Track E) — explicitly set the workspace for\n * subsequent events. Used by:\n * - SPAs where workspace context changes via in-app routing\n * - Mobile / RN apps that have no URL\n * - Custom integrations that resolve workspace from their own state\n *\n * Pass null to clear (or call clearWorkspace()).\n *\n * Persisted to sessionStorage so SPA reloads / page transitions on the\n * same outlet inherit it without re-calling.\n */\n setWorkspace(codeOrId: string | null): void {\n this._runtimeWorkspace = codeOrId;\n if (typeof window !== 'undefined' && window.sessionStorage) {\n try {\n if (codeOrId) {\n window.sessionStorage.setItem('aegis_runtime_ws', codeOrId);\n } else {\n window.sessionStorage.removeItem('aegis_runtime_ws');\n }\n } catch {\n // Quota / private mode — non-fatal; in-memory value still applies.\n }\n }\n logger.debug('Runtime workspace set', { value: codeOrId });\n }\n\n /** Symmetric helper to clear the runtime workspace. */\n clearWorkspace(): void {\n this.setWorkspace(null);\n }\n\n // ── P15.1 — location (outlet) facade ─────────────────────────\n //\n // Under the post-2026-05-26 canonical hierarchy:\n // workspace_id = brand-tenant (one per brand)\n // location_id = outlet within a brand\n // The two are distinct dimensions. Both can be stamped on the\n // same event. These methods mirror the workspace facade but\n // resolve the outlet specifically.\n\n /**\n * P15.1 — ingest the outlet-code allowlist from bootstrap. The\n * SDK consults this set when reading the URL path segment to\n * decide whether `location.pathname.split('/')[1]` is a valid\n * outlet code vs a generic route.\n *\n * Empty array = single-outlet tenant; SDK skips the path-segment\n * cascade for location resolution.\n *\n * Safe to call before init(); the set is consulted at event-\n * fire time.\n */\n ingestLocationCodes(codes: string[] | null | undefined): void {\n // Shares the same underlying set as workspace codes — under the\n // new hierarchy the path segment IS the outlet code (was\n // workspace code pre-2026-05-26 when the dimensions collapsed).\n // The set is consulted by both `getPathWorkspaceCode()` and\n // `getPathLocationCode()` to avoid maintaining two copies of\n // the same allowlist.\n this._workspaceCodes = new Set(\n (codes ?? []).filter((c) => typeof c === 'string' && c.length > 0),\n );\n logger.debug('Location codes ingested', { count: this._workspaceCodes.size });\n }\n\n /**\n * P15.1 — explicitly set the active outlet for subsequent events.\n * Used by:\n * - Storefronts where outlet picker fires `aegis.setLocation()`\n * on selection (so events that follow carry that outlet's\n * location_id without the SDK having to re-parse the URL).\n * - SPAs where outlet context changes via in-app routing.\n * - Mobile/RN apps that have no URL.\n *\n * Pass null to clear (or call clearLocation()).\n *\n * Persisted to sessionStorage so SPA reloads + route transitions\n * on the same outlet inherit it without re-calling.\n */\n setLocation(codeOrId: string | null): void {\n this._runtimeLocation = codeOrId;\n if (typeof window !== 'undefined' && window.sessionStorage) {\n try {\n if (codeOrId) {\n window.sessionStorage.setItem('aegis_runtime_location', codeOrId);\n } else {\n window.sessionStorage.removeItem('aegis_runtime_location');\n }\n } catch {\n // Quota / private mode — non-fatal; in-memory value still applies.\n }\n }\n logger.debug('Runtime location set', { value: codeOrId });\n }\n\n /** Symmetric helper to clear the runtime location. */\n clearLocation(): void {\n this.setLocation(null);\n }\n\n /**\n * P15.1 — same logic as `getPathWorkspaceCode()` but expresses\n * the semantic correctly: under the new hierarchy, the first\n * path segment after the brand subdomain IS the outlet code.\n * Returns `undefined` when no outlet code matches the allowlist.\n */\n private getPathLocationCode(): string | undefined {\n // Same allowlist as workspace codes (single set, two names).\n return this.getPathWorkspaceCode();\n }\n\n /**\n * P15.1 — resolve the effective `location_id` for the next event.\n * Independent of `getEffectiveWorkspaceId()`: both run on every\n * event so workspace_id (brand) and location_id (outlet) land\n * on the same event when both are resolvable.\n *\n * Cascade (highest precedence first):\n * 1. `this.config.location_id` — explicit operator config.\n * 2. `?location=` query param (also accepts `?ws=` for back-\n * compat with storefronts that pass outlet via the old\n * param name — the value is the same; param naming only).\n * 3. URL path segment matching the outlet-code allowlist.\n * 4. Runtime `aegis.setLocation()` (in-memory).\n * 5. sessionStorage `aegis_runtime_location`.\n * 6. `undefined` — event-ingress treats as brand-tier\n * (no outlet attribution).\n */\n public getEffectiveLocationId(): string | undefined {\n // 1. Explicit operator config wins\n const configured = (this.config as { location_id?: string } | undefined)\n ?.location_id;\n if (configured) return configured;\n if (typeof window === 'undefined') return undefined;\n\n // 2. ?location= / ?ws= query param (both accepted)\n try {\n const search = new URLSearchParams(window.location.search);\n const loc = search.get('location') || search.get('ws');\n if (loc && loc.length > 0) return loc;\n } catch {\n /* malformed search — fall through */\n }\n\n // 3. URL path segment matching outlet-code allowlist\n const pathLoc = this.getPathLocationCode();\n if (pathLoc) return pathLoc;\n\n // 4. Runtime aegis.setLocation() value (in-memory)\n if (this._runtimeLocation) return this._runtimeLocation;\n\n // 5. sessionStorage fallback (set by prior setLocation() this session)\n try {\n if (window.sessionStorage) {\n const cached = window.sessionStorage.getItem('aegis_runtime_location');\n if (cached && cached.length > 0) return cached;\n }\n } catch {\n /* private mode — fall through */\n }\n\n // 6. No outlet resolvable — event is brand-tier\n return undefined;\n }\n\n /**\n * Inspect the URL's first path segment and return it if it's in the\n * org's workspace_code allowlist. Skips well-known non-workspace prefixes\n * (e.g. `b` for bill short codes; `s` is the storefront app slug).\n *\n * Returns undefined when:\n * - window is undefined (SSR / Node)\n * - path is empty / root\n * - first segment isn't in `_workspaceCodes` (e.g. /products, /cart)\n *\n * The returned value is a workspace CODE (slug like \"south\"), not a\n * UUID. The gateway normalizes code → UUID server-side via\n * workspace_subaccounts lookup with Redis cache.\n */\n private getPathWorkspaceCode(): string | undefined {\n if (typeof window === 'undefined') return undefined;\n if (this._workspaceCodes.size === 0) return undefined;\n try {\n const segments = window.location.pathname.split('/').filter(Boolean);\n if (segments.length === 0) return undefined;\n const first = segments[0].toLowerCase();\n return this._workspaceCodes.has(first) ? first : undefined;\n } catch {\n return undefined;\n }\n }\n\n /**\n * Resolve the effective `workspace_id` for the next event.\n *\n * Cascade (highest precedence first):\n * 1. `this.config.workspace_id` — explicit operator config (headless\n * SDK usage, server-rendered apps, native shells).\n * 2. `?ws=` query param on the current URL — the P3 storefront URL\n * contract. The outlet picker writes this via `router.replace`.\n * 3. URL path segment (P1 Track A) — `/south/rewards` → \"south\" when\n * \"south\" is in the org's workspace_code allowlist.\n * 4. `aegis.setWorkspace()` runtime override (P1 Track E) — SPAs +\n * mobile + custom integrations.\n * 5. sessionStorage `aegis_runtime_ws` — persists setWorkspace across\n * reloads/SPA route changes.\n * 6. `undefined` — gateway falls back to `resolveByOrigin` lookup\n * against the property's allowed_origins.\n *\n * The returned value can be EITHER a UUID (from config / ?ws=) or a\n * workspace CODE slug (from path / setWorkspace). The gateway\n * normalizes slug → UUID server-side; analytics layer never needs to\n * worry about the difference.\n *\n * See docs/architecture/MULTI_OUTLET_URL_STRATEGY.md §2.3 and\n * docs/architecture/PLUGIN_HANDSHAKE_AUTOMATION.md §2.\n */\n /**\n * Public so peer SDK surfaces (AegisMessageRuntime / AegisInAppManager /\n * AegisWidgetManager) can plumb the same\n * resolved workspace into their own gateway POSTs. Each manager calls\n * the gateway on its own endpoint (`/v1/in-app/events`,\n * `/v1/widgets/track-event`); without this,\n * those events arrive at event-ingress with no workspace_id stamped\n * → impressions/clicks fall back to the org's primary workspace and\n * cross-outlet attribution breaks.\n */\n public getEffectiveWorkspaceId(): string | undefined {\n // 1. Explicit operator config wins\n const configured = this.config?.workspace_id;\n if (configured) return configured;\n if (typeof window === 'undefined') return undefined;\n\n // 2. ?ws= query param\n try {\n const ws = new URLSearchParams(window.location.search).get('ws');\n if (ws && ws.length > 0) return ws;\n } catch {\n /* malformed search — fall through */\n }\n\n // 3. URL path segment matching workspace_code allowlist\n const pathWs = this.getPathWorkspaceCode();\n if (pathWs) return pathWs;\n\n // 4. Runtime aegis.setWorkspace() value (in-memory)\n if (this._runtimeWorkspace) return this._runtimeWorkspace;\n\n // 5. sessionStorage fallback (set by prior setWorkspace() this session)\n try {\n if (window.sessionStorage) {\n const cached = window.sessionStorage.getItem('aegis_runtime_ws');\n if (cached && cached.length > 0) return cached;\n }\n } catch {\n /* private mode — fall through */\n }\n\n // 6. Gateway handles via resolveByOrigin\n return undefined;\n }\n\n track(eventName: string, properties?: Record<string, any>): void {\n if (!this.assertInitialized()) return;\n\n const messageId = generateMessageId();\n const event: TrackEvent = {\n type: 'track',\n event: eventName,\n properties: properties || {},\n messageId,\n timestamp: new Date().toISOString(),\n anonymousId: this.identity.getAnonymousId(),\n userId: this.identity.getUserId() || undefined,\n sessionId: this.session!.getSessionId(),\n workspace_id: this.getEffectiveWorkspaceId(),\n location_id: this.getEffectiveLocationId(),\n context: buildContext(this.config!, this.session!),\n };\n\n // Record so tenants who run their own Meta Pixel via GTM can pull the\n // event_id and pass it as `eventID` in fbq('track', ...). See B1.2.\n this._lastEventIds.set(eventName, messageId);\n\n this.captureEvent(event);\n }\n\n identify(userId: string, traits?: Record<string, any>): void {\n if (!this.assertInitialized()) return;\n\n // P10.5 — apply trait governance BEFORE setUserId + send. The BE\n // applies the same guards in `record_attribute_keys`, but doing it\n // client-side lets us warn the developer in console.warn and emit\n // sanitized values so what they see locally matches what gets stored.\n const wsForGovernor = this.getEffectiveWorkspaceId() || null;\n const { sanitized: governedTraits } = this.traitGovernor.process(traits, wsForGovernor);\n\n // C1b: a token is bound to ONE contact — identifying a different one\n // without a fresh `setContactToken()` call must not keep the old proof.\n if (this.identity.getUserId() !== userId) {\n this.contactToken = undefined;\n }\n this.identity.setUserId(userId, governedTraits);\n\n const event: IdentifyEvent = {\n type: 'identify',\n traits: governedTraits,\n messageId: generateMessageId(),\n timestamp: new Date().toISOString(),\n anonymousId: this.identity.getAnonymousId(),\n userId: userId,\n sessionId: this.session!.getSessionId(),\n workspace_id: this.getEffectiveWorkspaceId(),\n location_id: this.getEffectiveLocationId(),\n context: buildContext(this.config!, this.session!),\n };\n\n this.captureEvent(event);\n }\n\n page(name?: string, properties?: Record<string, any>): void {\n if (!this.assertInitialized()) return;\n\n const event: PageEvent = {\n type: 'page',\n name: name || document.title,\n properties: properties || {},\n messageId: generateMessageId(),\n timestamp: new Date().toISOString(),\n anonymousId: this.identity.getAnonymousId(),\n userId: this.identity.getUserId() || undefined,\n sessionId: this.session!.getSessionId(),\n workspace_id: this.getEffectiveWorkspaceId(),\n location_id: this.getEffectiveLocationId(),\n context: buildContext(this.config!, this.session!),\n };\n\n this.captureEvent(event);\n }\n\n group(groupId: string, traits?: Record<string, any>): void {\n if (!this.assertInitialized()) return;\n\n // P10.5 — same trait governance as identify(); group traits ride\n // the same `record_attribute_keys` BE chokepoint.\n const wsForGovernor = this.getEffectiveWorkspaceId() || null;\n const { sanitized: governedTraits } = this.traitGovernor.process(traits, wsForGovernor);\n\n const event: GroupEvent = {\n type: 'group',\n groupId,\n traits: governedTraits,\n messageId: generateMessageId(),\n timestamp: new Date().toISOString(),\n anonymousId: this.identity.getAnonymousId(),\n userId: this.identity.getUserId() || undefined,\n sessionId: this.session!.getSessionId(),\n context: buildContext(this.config!, this.session!),\n };\n\n this.captureEvent(event);\n }\n\n alias(newUserId: string): void {\n if (!this.assertInitialized()) return;\n\n const { previousId } = this.identity.alias(newUserId);\n\n const event: AliasEvent = {\n type: 'alias',\n previousId,\n messageId: generateMessageId(),\n timestamp: new Date().toISOString(),\n anonymousId: this.identity.getAnonymousId(),\n userId: newUserId,\n sessionId: this.session!.getSessionId(),\n context: buildContext(this.config!, this.session!),\n };\n\n this.captureEvent(event);\n }\n\n /**\n * SPA-logical screen view. Distinct from `page()` (URL-bound) — fires\n * when the user enters a logical surface like cart / checkout / drawer\n * without a URL change. Gateway maps `screen` → `engagement.screen_view`.\n */\n screen(name: string, properties?: Record<string, any>): void {\n if (!this.assertInitialized()) return;\n if (typeof name !== 'string' || name.length === 0) {\n logger.warn('aegis.screen: name must be a non-empty string');\n return;\n }\n\n const event: ScreenEvent = {\n type: 'screen',\n name,\n properties: properties || {},\n messageId: generateMessageId(),\n timestamp: new Date().toISOString(),\n anonymousId: this.identity.getAnonymousId(),\n userId: this.identity.getUserId() || undefined,\n sessionId: this.session!.getSessionId(),\n workspace_id: this.getEffectiveWorkspaceId(),\n location_id: this.getEffectiveLocationId(),\n context: buildContext(this.config!, this.session!),\n };\n\n this.captureEvent(event);\n }\n\n private async captureEvent(event: AegisEvent): Promise<void> {\n if (this.config?.enable_consent_mode && this.consent) {\n if (event.type === 'track' || event.type === 'page') {\n if (!this.consent.hasConsent('analytics')) {\n logger.debug('Event blocked: analytics consent not granted');\n return;\n }\n }\n }\n\n // Event-name governance — drops novel names once the org's unique-event\n // cap is exhausted. Meta events (aegis.client.*) bypass the governor so\n // the telemetry channel stays open even under a cap-exhaustion storm.\n // See governance/name-governor.ts.\n if (event.type === 'track') {\n const trackEvent = event as TrackEvent;\n const isMetaEvent =\n typeof trackEvent.event === 'string' &&\n trackEvent.event.startsWith('aegis.client.');\n // A purchase is never dropped (Q13, purchase-events.ts): its names are\n // known canonical spellings, so the novel-name cap never applies.\n if (!isMetaEvent && !isPurchaseEvent(event) && !this.nameGovernor.shouldSend(trackEvent.event)) {\n return;\n }\n }\n\n if (this.rateLimiter) {\n const eventLabel =\n event.type === 'track' && (event as TrackEvent).event\n ? (event as TrackEvent).event\n : event.type;\n // Meta-events bypass the rate limiter to avoid recursion / lost telemetry.\n const isMetaEvent =\n event.type === 'track' &&\n typeof (event as TrackEvent).event === 'string' &&\n (event as TrackEvent).event.startsWith('aegis.client.');\n // Purchases bypass the runaway-loop limiter too (Q13): one is never\n // dropped; the queue bounds them (MAX_PURCHASE_BACKLOG).\n if (!isMetaEvent && !isPurchaseEvent(event) && !this.rateLimiter.tryConsume(eventLabel)) {\n return;\n }\n }\n\n // Auto-inject UTM attribution from the URL context into event properties\n // under the CANONICAL keys (`utm_*`, data_governance.canonical_properties)\n // so downstream consumers receive it without manual mapping.\n //\n // `campaign_id` is NEVER written here. It is ONLY ever an Aegis campaign\n // id; this block used to put `utm.campaign` (free text a tenant or an ad\n // platform chose) into it, which corrupted every reader of that slot\n // (`uniqExact(campaign_id)` on /live among them). History is left as it is\n // — no backfill. The legacy `campaign_source/_medium/_content/_term`\n // spellings are no longer written; readers resolve `utm_*` first and still\n // read the old spelling on historical events.\n const ctx = (event as any).context;\n const props = (event as any).properties;\n if (ctx?.campaign && props) {\n const utm = ctx.campaign;\n if (utm.source && !props.utm_source) props.utm_source = utm.source;\n if (utm.medium && !props.utm_medium) props.utm_medium = utm.medium;\n if (utm.campaign && !props.utm_campaign) props.utm_campaign = utm.campaign;\n if (utm.content && !props.utm_content) props.utm_content = utm.content;\n if (utm.term && !props.utm_term) props.utm_term = utm.term;\n }\n if (ctx?.adClickIDs && props) {\n const clicks = ctx.adClickIDs;\n // The explicit per-platform keys — each its own fact. `gbraid` / `wbraid`\n // are Google's iOS (ATT) click ids and are NOT gclids.\n if (clicks.gclid && !props.gclid) props.gclid = clicks.gclid;\n if (clicks.gbraid && !props.gbraid) props.gbraid = clicks.gbraid;\n if (clicks.wbraid && !props.wbraid) props.wbraid = clicks.wbraid;\n if (clicks.fbclid && !props.fbclid) props.fbclid = clicks.fbclid;\n // `campaign_click_id` is the merged \"some click id\" — kept for its\n // existing readers, and deliberately NOT a spelling of any single id\n // (it can hold an fbclid).\n const clickId = clicks.gclid || clicks.fbclid || clicks.ctwa_clid || clicks.msclkid || clicks.ttclid;\n if (clickId && !props.campaign_click_id) props.campaign_click_id = clickId;\n }\n // Which Aegis send brought this visitor — `aegis_code` (the join key) and\n // the link row's attribution, captured from the landing URL. Never `utm_*`.\n if (props && this.session) {\n const link = this.session.getLinkAttribution();\n if (link.aegis_code) {\n for (const [key, value] of Object.entries(link)) {\n if (value && !props[key]) props[key] = value;\n }\n }\n }\n\n // B1.2 — Auto-inject Meta companion cookies (_fbp, _fbc, fbclid) into\n // event properties so the cell-side CAPI service can pass them as\n // user_data fields to Meta. Lifts EMQ from ~6-7 (PII-only) to ≥8.0\n // without firing fbq() browser-side. fbp is self-generated if absent;\n // fbc only set when an inbound fbclid landed in the URL.\n // See libs/web-sdk/src/utils/meta-cookies.ts for the spec.\n if (props) {\n const meta = captureMetaCookies();\n if (meta.fbp && !props.fbp) props.fbp = meta.fbp;\n if (meta.fbc && !props.fbc) props.fbc = meta.fbc;\n if (meta.fbclid && !props.fbclid) props.fbclid = meta.fbclid;\n }\n\n // `fbc` / `fbp` are Meta cookie values — match keys for CAPI, never log\n // content. The debug line prints the event with them masked.\n logger.debug('Capturing event:', redactMetaCookies(event));\n\n const transformedEvent = await this.plugins.executeHookChain(\n 'beforeEventCapture',\n event\n );\n\n if (!transformedEvent) {\n logger.debug('Event cancelled by plugin');\n return;\n }\n\n this.queue!.push(transformedEvent);\n this.session!.incrementEventCount();\n\n await this.plugins.executeHook('afterEventCapture', transformedEvent);\n }\n\n /**\n * Emit a coalesced meta-event reporting client-side rate-limit drops.\n * Bypasses the limiter (see captureEvent guard).\n */\n private emitRateLimitMeta(count: number, sampleEventName: string | null): void {\n if (!this.config?.initialized || !this.session || !this.identity) return;\n const event: TrackEvent = {\n type: 'track',\n event: 'aegis.client.rate_limited',\n properties: {\n dropped_count: count,\n sample_event_name: sampleEventName,\n burst_capacity: this.config.rate_limit_burst,\n refill_per_second: this.config.rate_limit_per_second,\n },\n messageId: generateMessageId(),\n timestamp: new Date().toISOString(),\n anonymousId: this.identity.getAnonymousId(),\n userId: this.identity.getUserId() || undefined,\n sessionId: this.session.getSessionId(),\n context: buildContext(this.config, this.session),\n };\n this.queue?.push(event);\n }\n\n reset(): void {\n if (!this.assertInitialized()) return;\n\n this.identity.reset();\n // Drop pending pre-login traits buffered on the user namespace —\n // a reset() either through `aegis.reset()` or `aegis.user.logout()`\n // should leave no residual identity state behind.\n this._user = null;\n logger.info('User identity reset');\n }\n\n /**\n * Ingest the event-governance hint returned from `/v1/sdk/bootstrap`.\n *\n * Callers (Shopify pixel, snippet, react integration) run `bootstrap()`\n * themselves and pass the resulting `eventGovernance` field here so the\n * SDK can self-throttle novel event names before they hit the gateway.\n *\n * Passing null/undefined disables governance (Enterprise plan / outage\n * fail-open). Safe to call before `init()` — the hint is stored and\n * applied as soon as init completes.\n */\n ingestGovernanceHint(hint: EventGovernanceHint | null | undefined): void {\n this.nameGovernor.ingestHint(hint ?? null);\n logger.debug('Governance hint ingested', hint ? {\n k: hint.k,\n m: hint.m,\n remaining: hint.remaining_new_names,\n } : 'disabled');\n }\n\n /**\n * Drain the client-side drop counter and emit a meta-event. Called\n * periodically by the queue flush path so ops dashboards see novel-name\n * amplification patterns in near-real-time.\n */\n private emitGovernanceDropMeta(): void {\n if (!this.config?.initialized || !this.session || !this.identity) return;\n const report = this.nameGovernor.drainDropReport();\n if (!report) return;\n\n const event: TrackEvent = {\n type: 'track',\n event: 'aegis.client.name_governor_dropped',\n properties: {\n dropped_count: report.total,\n distinct_names: Object.keys(report.events).length,\n // Cap the payload — a runaway loop could produce thousands of names;\n // we ship the top 10 for diagnostics and the total for counting.\n sample_names: Object.entries(report.events)\n .sort((a, b) => b[1] - a[1])\n .slice(0, 10)\n .map(([name, count]) => ({ name, count })),\n window_start: report.since,\n window_end: Date.now(),\n },\n messageId: generateMessageId(),\n timestamp: new Date().toISOString(),\n anonymousId: this.identity.getAnonymousId(),\n userId: this.identity.getUserId() || undefined,\n sessionId: this.session.getSessionId(),\n context: buildContext(this.config, this.session),\n };\n this.queue?.push(event);\n }\n\n async flush(): Promise<void> {\n if (!this.assertInitialized()) return;\n\n // Emit any coalesced governance-drop telemetry BEFORE flushing so the\n // meta event rides in the same batch as the rest.\n this.emitGovernanceDropMeta();\n await this.queue!.flush();\n }\n\n getAnonymousId(): string | null {\n if (!this.identity) return null;\n return this.identity.getAnonymousId();\n }\n\n getUserId(): string | null {\n if (!this.identity) return null;\n return this.identity.getUserId();\n }\n\n /**\n * C1b: register the server-minted proof for the CURRENT contact (as\n * returned by `getUserId()`). A host wiring `AegisMessageRuntime` calls\n * this alongside `runtime.updateContactId(id, token)` so `getRewards()`\n * can also present `X-Contact-Token`. Pass `undefined` to clear it (e.g.\n * on logout, or when the id changes without a fresh token).\n */\n setContactToken(token?: string): void {\n this.contactToken = token;\n }\n\n /**\n * The Aegis short-link attribution captured from this visitor's landing URL\n * (`aegis_code` + the link row's `aegis_campaign` / `aegis_journey` /\n * `aegis_playbook` / `aegis_button`), or `{}` when they did not arrive\n * through one. Hosts forward `aegis_code` with an order so the order can be\n * joined to the send that brought the shopper. Never contains `utm_*`, `k`,\n * `t` or `u`.\n */\n getLinkAttribution(): LinkAttribution {\n if (!this.session) return {};\n return { ...this.session.getLinkAttribution() };\n }\n\n /**\n * Fetch the identified contact's REDEEMABLE rewards — coupon codes the\n * storefront can auto-apply at checkout + loyalty points balance/tier.\n * Mirrors `GET /api/v1/sdk/entitlements`. Returns `null` when the SDK is\n * uninitialised, the contact is anonymous, the endpoint returns 204 (nothing\n * to show), or on any network/HTTP error — callers degrade gracefully.\n *\n * Scoped to the identified contact (own grants only) and, when an outlet is\n * resolvable (`getEffectiveLocationId()`), to org-wide + that outlet's grants.\n */\n async getRewards(): Promise<RewardsResponse | null> {\n const config = this.config;\n if (!config || !config.api_host || !this.identity) return null;\n const contactId = this.identity.getUserId();\n if (!contactId) return null;\n const apiHost = config.api_host.replace(/\\/$/, '');\n\n const headers: Record<string, string> = {\n 'X-Aegis-Write-Key': config.write_key,\n 'X-Contact-ID': contactId,\n 'X-User-ID': contactId,\n };\n // C1b: only send the token with its own contact.\n if (this.contactToken) headers['X-Contact-Token'] = this.contactToken;\n const orgId = (config as { organization_id?: string }).organization_id;\n if (orgId) headers['X-Organization-ID'] = orgId;\n const location = this.getEffectiveLocationId();\n if (location) headers['X-Location-Id'] = location;\n\n try {\n const resp = await fetch(`${apiHost}/api/v1/sdk/entitlements`, {\n method: 'GET',\n headers,\n credentials: 'include',\n });\n if (resp.status === 204 || !resp.ok) return null;\n return (await resp.json()) as RewardsResponse;\n } catch (err) {\n logger.warn('getRewards() failed', err);\n return null;\n }\n }\n\n getSessionId(): string | null {\n if (!this.session) return null;\n return this.session.getSessionId();\n }\n\n /**\n * B1.2 — Tenant-Pixel coexistence handoff. Returns the messageId of the\n * most recent `track('<eventName>', ...)` call, or null if no event of\n * that name has been tracked since SDK init.\n *\n * Use this from a tenant's own Meta Pixel script (e.g. via GTM) to pass\n * the same event_id to `fbq('track', '<eventName>', payload, {eventID: id})`.\n * Meta dedups on (pixel_id, event_name, event_id) so the browser-fired\n * Pixel event and our server-side CAPI event collapse to one — preventing\n * double-counting.\n *\n * Event names are case-sensitive (\"Purchase\" ≠ \"purchase\") — Meta's dedup\n * is also case-sensitive, so be exact.\n *\n * See docs/integrations/META_PIXEL_COEXISTENCE.md.\n */\n lastEventId(eventName: string): string | null {\n return this._lastEventIds.get(eventName) ?? null;\n }\n\n debug(enable: boolean = true): void {\n if (enable) {\n logger.enable();\n } else {\n logger.disable();\n }\n\n if (this.config) {\n this.config.debug = enable;\n }\n }\n\n setCell(cellEndpoint: CellEndpoint): void {\n if (!this.config) {\n logger.warn('SDK not initialized');\n return;\n }\n\n const existingCell = this.config.cell_endpoints.find(\n (c) => c.region === cellEndpoint.region\n );\n\n if (existingCell) {\n Object.assign(existingCell, cellEndpoint);\n } else {\n this.config.cell_endpoints.push(cellEndpoint);\n }\n\n logger.info('Cell endpoint configured:', cellEndpoint);\n }\n\n getCellInfo() {\n if (!this.transport) return null;\n\n return {\n activeCell: this.transport.getActiveCell(),\n latencies: this.transport.getRegionLatencies(),\n };\n }\n\n setConsent(preferences: Partial<ConsentPreferences>): void {\n if (!this.consent) {\n logger.warn('Consent manager not initialized');\n return;\n }\n\n this.consent.setConsent(preferences);\n logger.info('Consent preferences updated');\n }\n\n grantConsent(category?: ConsentCategory): void {\n if (!this.consent) {\n logger.warn('Consent manager not initialized');\n return;\n }\n\n if (category) {\n this.consent.setConsent({ [category]: true });\n } else {\n this.consent.grantAll();\n }\n }\n\n denyConsent(category?: ConsentCategory): void {\n if (!this.consent) {\n logger.warn('Consent manager not initialized');\n return;\n }\n\n if (category) {\n this.consent.setConsent({ [category]: false });\n } else {\n this.consent.denyAll();\n }\n }\n\n hasConsent(category: ConsentCategory): boolean {\n if (!this.consent) {\n return true;\n }\n\n return this.consent.hasConsent(category);\n }\n\n getConsentPreferences(): ConsentPreferences | null {\n if (!this.consent) {\n return null;\n }\n\n return this.consent.getPreferences();\n }\n\n onConsentChange(callback: (preferences: ConsentPreferences) => void): () => void {\n if (!this.consent) {\n logger.warn('Consent manager not initialized');\n return () => {};\n }\n\n return this.consent.onChange(callback);\n }\n\n private assertInitialized(): boolean {\n if (!this.config?.initialized) {\n logger.warn('SDK not initialized. Call aegis.init() first.');\n return false;\n }\n return true;\n }\n\n get ecommerce(): EcommerceTracker {\n if (!this._ecommerce) {\n this._ecommerce = new EcommerceTracker(this);\n }\n return this._ecommerce;\n }\n\n get user(): UserNamespace {\n if (!this._user) {\n this._user = new UserNamespace(this);\n }\n return this._user;\n }\n\n destroy(): void {\n this.stopSPATracking();\n\n if (this.queue) {\n this.queue.destroy();\n }\n\n if (this.session) {\n this.session.destroy();\n }\n\n if (this.transport) {\n this.transport.destroy();\n }\n\n if (this.rateLimiter) {\n this.rateLimiter.destroy();\n this.rateLimiter = null;\n }\n\n this.plugins.clear();\n\n logger.info('SDK destroyed');\n }\n}\n"],"names":["k1"],"mappings":"AA+GO,MAAM,iBAA+C;AAAA,EAC1D,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,gBAAgB;AAAA,EAChB,aAAa;AAAA,EACb,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,EACjB,OAAO;AAAA,EACP,aAAa;AAAA,EACb,uBAAuB;AAAA,EACvB,eAAe;AAAA,EACf,qBAAqB;AAAA,EACrB,oBAAoB;AAAA,EACpB,uBAAuB;AAAA,EACvB,aAAa;AAAA,EACb,0BAA0B;AAAA,EAC1B,iBAAiB;AAAA,EACjB,kBAAkB;AAAA,EAClB,uBAAuB;AAAA,EACvB,uBAAuB;AAAA,EACvB,kBAAkB;AAAA,EAClB,qBAAqB;AAAA,EACrB,oBAAoB;AAAA,EACpB,qBAAqB;AAAA,EACrB,+BAA+B;AAAA,EAC/B,iBAAiB;AAAA,IACf,WAAW;AAAA,IACX,WAAW;AAAA,IACX,YAAY;AAAA,EAAA;AAAA,EAEd,aAAa;AAAA,EACb,UAAU;AAAA,EACV,gBAAgB,CAAA;AAAA,EAChB,kBAAkB;AAAA,EAClB,eAAe;AAAA,EACf,SAAS,CAAA;AAAA,EACT,aAAa;AACf;ACrJO,SAAS,eAAuB;AACrC,MAA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