@intlayer/analytics 9.0.0-canary.16 → 9.0.0-canary.18

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.
Files changed (45) hide show
  1. package/dist/cjs/core/AnalyticsClient.cjs.map +1 -1
  2. package/dist/cjs/core/abTesting.cjs.map +1 -1
  3. package/dist/cjs/core/eventBuffer.cjs.map +1 -1
  4. package/dist/cjs/core/globalManager.cjs.map +1 -1
  5. package/dist/cjs/core/initAnalyticsClient.cjs.map +1 -1
  6. package/dist/cjs/core/sampling.cjs.map +1 -1
  7. package/dist/cjs/core/session.cjs.map +1 -1
  8. package/dist/cjs/core/transport.cjs.map +1 -1
  9. package/dist/cjs/events/contentExposure.cjs.map +1 -1
  10. package/dist/cjs/isEnabled.cjs.map +1 -1
  11. package/dist/cjs/utils/hash.cjs.map +1 -1
  12. package/dist/cjs/utils/idle.cjs.map +1 -1
  13. package/dist/esm/core/AnalyticsClient.mjs.map +1 -1
  14. package/dist/esm/core/abTesting.mjs.map +1 -1
  15. package/dist/esm/core/eventBuffer.mjs.map +1 -1
  16. package/dist/esm/core/globalManager.mjs.map +1 -1
  17. package/dist/esm/core/initAnalyticsClient.mjs.map +1 -1
  18. package/dist/esm/core/sampling.mjs.map +1 -1
  19. package/dist/esm/core/session.mjs.map +1 -1
  20. package/dist/esm/core/transport.mjs.map +1 -1
  21. package/dist/esm/events/contentExposure.mjs.map +1 -1
  22. package/dist/esm/isEnabled.mjs.map +1 -1
  23. package/dist/esm/utils/hash.mjs.map +1 -1
  24. package/dist/esm/utils/idle.mjs.map +1 -1
  25. package/dist/types/core/AnalyticsClient.d.ts +26 -13
  26. package/dist/types/core/AnalyticsClient.d.ts.map +1 -1
  27. package/dist/types/core/abTesting.d.ts.map +1 -1
  28. package/dist/types/core/eventBuffer.d.ts +6 -6
  29. package/dist/types/core/eventBuffer.d.ts.map +1 -1
  30. package/dist/types/core/globalManager.d.ts +0 -1
  31. package/dist/types/core/globalManager.d.ts.map +1 -1
  32. package/dist/types/core/initAnalyticsClient.d.ts +0 -1
  33. package/dist/types/core/initAnalyticsClient.d.ts.map +1 -1
  34. package/dist/types/core/sampling.d.ts.map +1 -1
  35. package/dist/types/core/session.d.ts.map +1 -1
  36. package/dist/types/core/transport.d.ts +1 -4
  37. package/dist/types/core/transport.d.ts.map +1 -1
  38. package/dist/types/core/types.d.ts +51 -24
  39. package/dist/types/core/types.d.ts.map +1 -1
  40. package/dist/types/events/contentExposure.d.ts +1 -2
  41. package/dist/types/events/contentExposure.d.ts.map +1 -1
  42. package/dist/types/isEnabled.d.ts.map +1 -1
  43. package/dist/types/utils/hash.d.ts.map +1 -1
  44. package/dist/types/utils/idle.d.ts.map +1 -1
  45. package/package.json +7 -7
@@ -1 +1 @@
1
- {"version":3,"file":"AnalyticsClient.cjs","names":["getSessionId","isSampledIn","createEventBuffer","assignVariant"],"sources":["../../../src/core/AnalyticsClient.ts"],"sourcesContent":["import { onIdle } from '../utils/idle';\nimport { assignVariant } from './abTesting';\nimport { createEventBuffer, type EventBuffer } from './eventBuffer';\nimport { isSampledIn } from './sampling';\nimport { getSessionId } from './session';\nimport { sendEvents } from './transport';\nimport type {\n AnalyticsClientConfig,\n AnalyticsEvent,\n ContentExposureEvent,\n ConversionEvent,\n PageViewEvent,\n TrackableEvent,\n} from './types';\n\n/**\n * Caller-supplied fields for a page view. Everything is optional — the client\n * fills `url`, `locale`, viewport, and referrer from the environment when omitted.\n */\nexport type PageViewInput = {\n /** Explicit pathname / screen name (native runtimes have no `location`). */\n url?: string;\n /** Explicit locale; falls back to the client's ambient locale. */\n locale?: string;\n /** Referrer host override. */\n ref?: string;\n /** Viewport width override. */\n vw?: number;\n /** Viewport height override. */\n vh?: number;\n /** Why the view was recorded. */\n reason?: PageViewEvent['reason'];\n};\n\n/** Default flush cadence — one network request per 20 seconds. */\nexport const DEFAULT_FLUSH_INTERVAL = 20_000;\n/** Default cap on distinct buffered events before an early flush. */\nexport const DEFAULT_MAX_BUFFER_SIZE = 500;\n/** Default sampling — keep every session. */\nexport const DEFAULT_SAMPLE_RATE = 1;\n/**\n * Maximum events per network request. `sendBeacon` and `fetch(keepalive)`\n * reject bodies over ~64KB, so large batches are split into multiple sends.\n */\nexport const MAX_EVENTS_PER_SEND = 200;\n/** Identifies the producing SDK in the ingest envelope. */\nconst SDK_VERSION = 'intlayer-analytics/1';\n\n/**\n * The public surface of the analytics client singleton. Framework bindings hold\n * a reference to this and forward provider/node/conversion signals into it.\n */\nexport type AnalyticsClient = {\n /** Sets the ambient locale stamped onto subsequent events. */\n setLocale: (locale: string) => void;\n /** Records a page/locale view (provider level). */\n trackPageView: (event?: PageViewInput) => void;\n /** Records a content exposure (node level). Sampled + deduped per page view. */\n trackContentExposure: (\n event: Omit<TrackableEvent<ContentExposureEvent>, 'type'>\n ) => void;\n /** Records a conversion tied to an experiment variant. */\n trackConversion: (\n event: Omit<TrackableEvent<ConversionEvent>, 'type'>\n ) => void;\n /** Deterministically resolves this session's variant for an experiment. */\n getVariant: (\n experimentKey: string,\n variants: string[],\n weights?: number[]\n ) => string;\n /** Sends the buffered batch now. */\n flush: (useBeacon?: boolean) => void;\n /** Starts the flush loop and lifecycle listeners (idempotent). */\n start: () => void;\n /** Stops timers/listeners and flushes any remaining events. */\n stop: () => void;\n};\n\n/**\n * Reads the current page pathname. Search params are intentionally excluded to\n * avoid capturing anything sensitive.\n */\nconst currentUrl = (): string => {\n if (typeof window === 'undefined' || !window.location) return '';\n return window.location.pathname;\n};\n\n/**\n * Reduces the referrer to its host — never the full URL — for privacy.\n */\nconst referrerHost = (): string | undefined => {\n if (typeof document === 'undefined' || !document.referrer) return undefined;\n try {\n return new URL(document.referrer).host;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Creates an analytics client. Prefer {@link initAnalyticsClient} in application\n * code — it manages a shared singleton so there is only ever one flush timer.\n *\n * @param config - Resolved client configuration.\n * @returns A started-on-demand {@link AnalyticsClient}.\n */\nexport const createAnalyticsClient = (\n config: AnalyticsClientConfig\n): AnalyticsClient => {\n const sessionId = getSessionId();\n const sampledIn = isSampledIn(sessionId, config.sampleRate);\n const buffer: EventBuffer = createEventBuffer({ max: config.maxBufferSize });\n const endpoint = `${config.backendURL.replace(/\\/$/, '')}/api/analytics/events`;\n\n let ambientLocale = '';\n let flushTimer: ReturnType<typeof setInterval> | null = null;\n let started = false;\n let detachListeners: (() => void) | null = null;\n\n // Exposure keys already recorded for the current page view. React (and other\n // frameworks) resolve content nodes on every re-render; without this gate a\n // component re-rendering 60×/s would count 60 exposures per second. The set\n // is cleared on each page view so the recorded semantic is \"shown at least\n // once during this page view\".\n let seenExposureKeys = new Set<string>();\n\n const flush = (useBeacon = false): void => {\n const events = buffer.drain();\n\n // Split into bounded chunks so no single request exceeds transport limits.\n for (let start = 0; start < events.length; start += MAX_EVENTS_PER_SEND) {\n sendEvents(\n endpoint,\n {\n clientId: config.clientId,\n sessionId,\n sdkVersion: SDK_VERSION,\n events: events.slice(start, start + MAX_EVENTS_PER_SEND),\n },\n { useBeacon }\n );\n }\n };\n\n /** Pushes an event and triggers an early flush if the buffer is full. */\n const enqueue = (event: AnalyticsEvent): void => {\n const size = buffer.push(event);\n if (size >= config.maxBufferSize) flush();\n };\n\n const setLocale = (locale: string): void => {\n ambientLocale = locale;\n };\n\n const trackPageView: AnalyticsClient['trackPageView'] = (event = {}) => {\n if (!sampledIn) return;\n\n // A new page view starts a fresh exposure window.\n seenExposureKeys = new Set<string>();\n\n enqueue({\n type: 'page_view',\n t: Date.now(),\n url: event.url ?? currentUrl(),\n locale: event.locale ?? ambientLocale,\n ref: event.ref ?? referrerHost(),\n vw:\n event.vw ??\n (typeof window !== 'undefined' ? window.innerWidth : undefined),\n vh:\n event.vh ??\n (typeof window !== 'undefined' ? window.innerHeight : undefined),\n reason: event.reason ?? 'initial',\n });\n };\n\n const trackContentExposure: AnalyticsClient['trackContentExposure'] = (\n event\n ) => {\n if (!sampledIn) return;\n\n const locale = event.locale ?? ambientLocale;\n // Joined with \\x01 (never present in content keys) so parts cannot collide.\n const exposureKey = [\n event.dictionaryKey,\n event.keyPath,\n locale,\n event.experimentKey ?? '',\n event.variant ?? '',\n ].join('\u0001');\n\n // Deduplicate within the current page view (see `seenExposureKeys`).\n if (seenExposureKeys.has(exposureKey)) return;\n seenExposureKeys.add(exposureKey);\n\n enqueue({\n ...event,\n type: 'content_exposure',\n t: Date.now(),\n url: currentUrl(),\n locale,\n });\n };\n\n const trackConversion: AnalyticsClient['trackConversion'] = (event) => {\n // Conversions are never sampled out — they are rare and decisive for A/B.\n enqueue({\n ...event,\n type: 'conversion',\n t: Date.now(),\n url: currentUrl(),\n locale: event.locale ?? ambientLocale,\n });\n // Flush conversions promptly so they are not lost on immediate navigation.\n flush();\n };\n\n const getVariant: AnalyticsClient['getVariant'] = (\n experimentKey,\n variants,\n weights\n ) => assignVariant(sessionId, experimentKey, variants, weights);\n\n /** Attaches lifecycle + SPA-navigation listeners without blocking render. */\n const attachListeners = (): void => {\n if (typeof window === 'undefined') return;\n\n const onHidden = (): void => {\n if (document.visibilityState === 'hidden') flush(true);\n };\n const onPageHide = (): void => flush(true);\n const onPopState = (): void => trackPageView({ reason: 'route_change' });\n\n document.addEventListener('visibilitychange', onHidden);\n window.addEventListener('pagehide', onPageHide, { capture: true });\n window.addEventListener('popstate', onPopState);\n\n // Patch history.pushState so client-side route changes emit a page view.\n // `replaceState` is intentionally left untouched: routers use it for\n // same-page URL sync (scroll, params), which is not a navigation.\n const history = window.history;\n const originalPush = history.pushState;\n\n const patchedPushState = function patchedPush(\n this: History,\n ...args: Parameters<History['pushState']>\n ) {\n const result = originalPush.apply(this, args);\n trackPageView({ reason: 'route_change' });\n return result;\n };\n history.pushState = patchedPushState;\n\n detachListeners = (): void => {\n document.removeEventListener('visibilitychange', onHidden);\n window.removeEventListener('pagehide', onPageHide, { capture: true });\n window.removeEventListener('popstate', onPopState);\n // Only restore if nothing else re-patched pushState after us; restoring\n // blindly would clobber another library's wrapper.\n if (history.pushState === patchedPushState) {\n history.pushState = originalPush;\n }\n };\n };\n\n const start = (): void => {\n if (started) return;\n started = true;\n\n flushTimer = setInterval(flush, config.flushInterval);\n // Some runtimes (Node during SSR) keep the process alive on timers.\n (flushTimer as { unref?: () => void })?.unref?.();\n\n onIdle(attachListeners);\n };\n\n const stop = (): void => {\n if (!started) return;\n started = false;\n\n if (flushTimer) {\n clearInterval(flushTimer);\n flushTimer = null;\n }\n detachListeners?.();\n detachListeners = null;\n flush(true);\n };\n\n return {\n setLocale,\n trackPageView,\n trackContentExposure,\n trackConversion,\n getVariant,\n flush,\n start,\n stop,\n };\n};\n"],"mappings":"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"}
1
+ {"version":3,"file":"AnalyticsClient.cjs","names":["getSessionId","isSampledIn","createEventBuffer","assignVariant"],"sources":["../../../src/core/AnalyticsClient.ts"],"sourcesContent":["import { onIdle } from '../utils/idle';\nimport { assignVariant } from './abTesting';\nimport { createEventBuffer, type EventBuffer } from './eventBuffer';\nimport { isSampledIn } from './sampling';\nimport { getSessionId } from './session';\nimport { sendEvents } from './transport';\nimport type {\n AnalyticsClientConfig,\n AnalyticsEvent,\n ContentExposureEvent,\n ConversionEvent,\n PageViewEvent,\n TrackableEvent,\n} from './types';\n\n/**\n * Caller-supplied fields for a page view. Everything is optional — the client\n * fills `url`, `locale`, viewport, and referrer from the environment when omitted.\n */\nexport type PageViewInput = {\n /** Explicit pathname / screen name (native runtimes have no `location`). */\n url?: string;\n /** Explicit locale; falls back to the client's ambient locale. */\n locale?: string;\n /** Referrer host override. */\n ref?: string;\n /** Viewport width override. */\n vw?: number;\n /** Viewport height override. */\n vh?: number;\n /** Why the view was recorded. */\n reason?: PageViewEvent['reason'];\n};\n\n/** Default flush cadence — one network request per 20 seconds. */\nexport const DEFAULT_FLUSH_INTERVAL = 20_000;\n/** Default cap on distinct buffered events before an early flush. */\nexport const DEFAULT_MAX_BUFFER_SIZE = 500;\n/** Default sampling — keep every session. */\nexport const DEFAULT_SAMPLE_RATE = 1;\n/**\n * Maximum events per network request. `sendBeacon` and `fetch(keepalive)`\n * reject bodies over ~64KB, so large batches are split into multiple sends.\n */\nexport const MAX_EVENTS_PER_SEND = 200;\n/** Identifies the producing SDK in the ingest envelope. */\nconst SDK_VERSION = 'intlayer-analytics/1';\n\n/**\n * The public surface of the analytics client singleton. Framework bindings hold\n * a reference to this and forward provider/node/conversion signals into it.\n */\nexport type AnalyticsClient = {\n /** Sets the ambient locale stamped onto subsequent events. */\n setLocale: (locale: string) => void;\n /** Records a page/locale view (provider level). */\n trackPageView: (event?: PageViewInput) => void;\n /** Records a content exposure (node level). Sampled + deduped per page view. */\n trackContentExposure: (\n event: Omit<TrackableEvent<ContentExposureEvent>, 'type'>\n ) => void;\n /** Records a conversion tied to an experiment variant. */\n trackConversion: (\n event: Omit<TrackableEvent<ConversionEvent>, 'type'>\n ) => void;\n /** Deterministically resolves this session's variant for an experiment. */\n getVariant: (\n experimentKey: string,\n variants: string[],\n weights?: number[]\n ) => string;\n /** Sends the buffered batch now. */\n flush: (useBeacon?: boolean) => void;\n /** Starts the flush loop and lifecycle listeners (idempotent). */\n start: () => void;\n /** Stops timers/listeners and flushes any remaining events. */\n stop: () => void;\n};\n\n/**\n * Reads the current page pathname. Search params are intentionally excluded to\n * avoid capturing anything sensitive.\n */\nconst currentUrl = (): string => {\n if (typeof window === 'undefined' || !window.location) return '';\n return window.location.pathname;\n};\n\n/**\n * Reduces the referrer to its host — never the full URL — for privacy.\n */\nconst referrerHost = (): string | undefined => {\n if (typeof document === 'undefined' || !document.referrer) return undefined;\n try {\n return new URL(document.referrer).host;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Creates an analytics client. Prefer {@link initAnalyticsClient} in application\n * code — it manages a shared singleton so there is only ever one flush timer.\n *\n * @param config - Resolved client configuration.\n * @returns A started-on-demand {@link AnalyticsClient}.\n */\nexport const createAnalyticsClient = (\n config: AnalyticsClientConfig\n): AnalyticsClient => {\n const sessionId = getSessionId();\n const sampledIn = isSampledIn(sessionId, config.sampleRate);\n const buffer: EventBuffer = createEventBuffer({ max: config.maxBufferSize });\n const endpoint = `${config.backendURL.replace(/\\/$/, '')}/api/analytics/events`;\n\n let ambientLocale = '';\n let flushTimer: ReturnType<typeof setInterval> | null = null;\n let started = false;\n let detachListeners: (() => void) | null = null;\n\n // Exposure keys already recorded for the current page view. React (and other\n // frameworks) resolve content nodes on every re-render; without this gate a\n // component re-rendering 60×/s would count 60 exposures per second. The set\n // is cleared on each page view so the recorded semantic is \"shown at least\n // once during this page view\".\n let seenExposureKeys = new Set<string>();\n\n const flush = (useBeacon = false): void => {\n const events = buffer.drain();\n\n // Split into bounded chunks so no single request exceeds transport limits.\n for (let start = 0; start < events.length; start += MAX_EVENTS_PER_SEND) {\n sendEvents(\n endpoint,\n {\n clientId: config.clientId,\n sessionId,\n sdkVersion: SDK_VERSION,\n events: events.slice(start, start + MAX_EVENTS_PER_SEND),\n },\n { useBeacon }\n );\n }\n };\n\n /** Pushes an event and triggers an early flush if the buffer is full. */\n const enqueue = (event: AnalyticsEvent): void => {\n const size = buffer.push(event);\n if (size >= config.maxBufferSize) flush();\n };\n\n const setLocale = (locale: string): void => {\n ambientLocale = locale;\n };\n\n const trackPageView: AnalyticsClient['trackPageView'] = (event = {}) => {\n if (!sampledIn) return;\n\n // A new page view starts a fresh exposure window.\n seenExposureKeys = new Set<string>();\n\n enqueue({\n type: 'page_view',\n t: Date.now(),\n url: event.url ?? currentUrl(),\n locale: event.locale ?? ambientLocale,\n ref: event.ref ?? referrerHost(),\n vw:\n event.vw ??\n (typeof window !== 'undefined' ? window.innerWidth : undefined),\n vh:\n event.vh ??\n (typeof window !== 'undefined' ? window.innerHeight : undefined),\n reason: event.reason ?? 'initial',\n });\n };\n\n const trackContentExposure: AnalyticsClient['trackContentExposure'] = (\n event\n ) => {\n if (!sampledIn) return;\n\n const locale = event.locale ?? ambientLocale;\n // Joined with \\x01 (never present in content keys) so parts cannot collide.\n const exposureKey = [\n event.dictionaryKey,\n event.keyPath,\n locale,\n event.experimentKey ?? '',\n event.variant ?? '',\n ].join('\u0001');\n\n // Deduplicate within the current page view (see `seenExposureKeys`).\n if (seenExposureKeys.has(exposureKey)) return;\n seenExposureKeys.add(exposureKey);\n\n enqueue({\n ...event,\n type: 'content_exposure',\n t: Date.now(),\n url: currentUrl(),\n locale,\n });\n };\n\n const trackConversion: AnalyticsClient['trackConversion'] = (event) => {\n // Conversions are never sampled out — they are rare and decisive for A/B.\n enqueue({\n ...event,\n type: 'conversion',\n t: Date.now(),\n url: currentUrl(),\n locale: event.locale ?? ambientLocale,\n });\n // Flush conversions promptly so they are not lost on immediate navigation.\n flush();\n };\n\n const getVariant: AnalyticsClient['getVariant'] = (\n experimentKey,\n variants,\n weights\n ) => assignVariant(sessionId, experimentKey, variants, weights);\n\n /** Attaches lifecycle + SPA-navigation listeners without blocking render. */\n const attachListeners = (): void => {\n if (typeof window === 'undefined') return;\n\n const onHidden = (): void => {\n if (document.visibilityState === 'hidden') flush(true);\n };\n const onPageHide = (): void => flush(true);\n const onPopState = (): void => trackPageView({ reason: 'route_change' });\n\n document.addEventListener('visibilitychange', onHidden);\n window.addEventListener('pagehide', onPageHide, { capture: true });\n window.addEventListener('popstate', onPopState);\n\n // Patch history.pushState so client-side route changes emit a page view.\n // `replaceState` is intentionally left untouched: routers use it for\n // same-page URL sync (scroll, params), which is not a navigation.\n const history = window.history;\n const originalPush = history.pushState;\n\n const patchedPushState = function patchedPush(\n this: History,\n ...args: Parameters<History['pushState']>\n ) {\n const result = originalPush.apply(this, args);\n trackPageView({ reason: 'route_change' });\n return result;\n };\n history.pushState = patchedPushState;\n\n detachListeners = (): void => {\n document.removeEventListener('visibilitychange', onHidden);\n window.removeEventListener('pagehide', onPageHide, { capture: true });\n window.removeEventListener('popstate', onPopState);\n // Only restore if nothing else re-patched pushState after us; restoring\n // blindly would clobber another library's wrapper.\n if (history.pushState === patchedPushState) {\n history.pushState = originalPush;\n }\n };\n };\n\n const start = (): void => {\n if (started) return;\n started = true;\n\n flushTimer = setInterval(flush, config.flushInterval);\n // Some runtimes (Node during SSR) keep the process alive on timers.\n (flushTimer as { unref?: () => void })?.unref?.();\n\n onIdle(attachListeners);\n };\n\n const stop = (): void => {\n if (!started) return;\n started = false;\n\n if (flushTimer) {\n clearInterval(flushTimer);\n flushTimer = null;\n }\n detachListeners?.();\n detachListeners = null;\n flush(true);\n };\n\n return {\n setLocale,\n trackPageView,\n trackContentExposure,\n trackConversion,\n getVariant,\n flush,\n start,\n stop,\n };\n};\n"],"mappings":"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"}
@@ -1 +1 @@
1
- {"version":3,"file":"abTesting.cjs","names":["hashString"],"sources":["../../../src/core/abTesting.ts"],"sourcesContent":["import { hashString } from '../utils/hash';\n\n/**\n * Deterministically assigns a variant to a session for a given experiment.\n *\n * The assignment is a pure function of `sessionId` + `experimentKey`, so it is\n * stable for the whole session and requires **no** server round-trip before the\n * first render — avoiding layout shift / content flicker. Optional `weights`\n * bias the split (e.g. `[0.9, 0.1]` for a 90/10 rollout).\n *\n * @param sessionId - The current anonymous session id.\n * @param experimentKey - Unique key identifying the experiment.\n * @param variants - The candidate variant names (at least one).\n * @param weights - Optional relative weights, one per variant.\n * @returns The variant assigned to this session.\n *\n * @example\n * assignVariant('sid-1', 'homepage-hero', ['a', 'b']); // stable 'a' | 'b'\n * assignVariant('sid-1', 'homepage-hero', ['a', 'b'], [9, 1]); // ~90% 'a'\n */\nexport const assignVariant = (\n sessionId: string,\n experimentKey: string,\n variants: string[],\n weights?: number[]\n): string => {\n if (variants.length === 0) {\n throw new Error('assignVariant requires at least one variant');\n }\n if (variants.length === 1) return variants[0]!;\n\n // Uniform bucket in [0, 1) derived from the session + experiment.\n const bucket = hashString(`${sessionId}:${experimentKey}`) / 0x100000000;\n\n if (!weights || weights.length !== variants.length) {\n const index = Math.floor(bucket * variants.length);\n return variants[Math.min(index, variants.length - 1)];\n }\n\n const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);\n if (totalWeight <= 0) {\n return variants[Math.floor(bucket * variants.length)];\n }\n\n let cumulative = 0;\n const target = bucket * totalWeight;\n for (let index = 0; index < variants.length; index++) {\n cumulative += weights[index];\n if (target < cumulative) return variants[index];\n }\n\n return variants[variants.length - 1];\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoBA,MAAa,iBACX,WACA,eACA,UACA,YACW;AACX,KAAI,SAAS,WAAW,EACtB,OAAM,IAAI,MAAM,8CAA8C;AAEhE,KAAI,SAAS,WAAW,EAAG,QAAO,SAAS;CAG3C,MAAM,SAASA,8BAAW,GAAG,UAAU,GAAG,gBAAgB,GAAG;AAE7D,KAAI,CAAC,WAAW,QAAQ,WAAW,SAAS,QAAQ;EAClD,MAAM,QAAQ,KAAK,MAAM,SAAS,SAAS,OAAO;AAClD,SAAO,SAAS,KAAK,IAAI,OAAO,SAAS,SAAS,EAAE;;CAGtD,MAAM,cAAc,QAAQ,QAAQ,KAAK,WAAW,MAAM,QAAQ,EAAE;AACpE,KAAI,eAAe,EACjB,QAAO,SAAS,KAAK,MAAM,SAAS,SAAS,OAAO;CAGtD,IAAI,aAAa;CACjB,MAAM,SAAS,SAAS;AACxB,MAAK,IAAI,QAAQ,GAAG,QAAQ,SAAS,QAAQ,SAAS;AACpD,gBAAc,QAAQ;AACtB,MAAI,SAAS,WAAY,QAAO,SAAS;;AAG3C,QAAO,SAAS,SAAS,SAAS"}
1
+ {"version":3,"file":"abTesting.cjs","names":["hashString"],"sources":["../../../src/core/abTesting.ts"],"sourcesContent":["import { hashString } from '../utils/hash';\n\n/**\n * Deterministically assigns a variant to a session for a given experiment.\n *\n * The assignment is a pure function of `sessionId` + `experimentKey`, so it is\n * stable for the whole session and requires **no** server round-trip before the\n * first render — avoiding layout shift / content flicker. Optional `weights`\n * bias the split (e.g. `[0.9, 0.1]` for a 90/10 rollout).\n *\n * @param sessionId - The current anonymous session id.\n * @param experimentKey - Unique key identifying the experiment.\n * @param variants - The candidate variant names (at least one).\n * @param weights - Optional relative weights, one per variant.\n * @returns The variant assigned to this session.\n *\n * @example\n * assignVariant('sid-1', 'homepage-hero', ['a', 'b']); // stable 'a' | 'b'\n * assignVariant('sid-1', 'homepage-hero', ['a', 'b'], [9, 1]); // ~90% 'a'\n */\nexport const assignVariant = (\n sessionId: string,\n experimentKey: string,\n variants: string[],\n weights?: number[]\n): string => {\n if (variants.length === 0) {\n throw new Error('assignVariant requires at least one variant');\n }\n if (variants.length === 1) return variants[0]!;\n\n // Uniform bucket in [0, 1) derived from the session + experiment.\n const bucket = hashString(`${sessionId}:${experimentKey}`) / 0x100000000;\n\n if (!weights || weights.length !== variants.length) {\n const index = Math.floor(bucket * variants.length);\n return variants[Math.min(index, variants.length - 1)];\n }\n\n const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);\n if (totalWeight <= 0) {\n return variants[Math.floor(bucket * variants.length)];\n }\n\n let cumulative = 0;\n const target = bucket * totalWeight;\n for (let index = 0; index < variants.length; index++) {\n cumulative += weights[index];\n if (target < cumulative) return variants[index];\n }\n\n return variants[variants.length - 1];\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoBA,MAAa,iBACX,WACA,eACA,UACA,YACW;CACX,IAAI,SAAS,WAAW,GACtB,MAAM,IAAI,MAAM,6CAA6C;CAE/D,IAAI,SAAS,WAAW,GAAG,OAAO,SAAS;CAG3C,MAAM,SAASA,8BAAW,GAAG,UAAU,GAAG,eAAe,IAAI;CAE7D,IAAI,CAAC,WAAW,QAAQ,WAAW,SAAS,QAAQ;EAClD,MAAM,QAAQ,KAAK,MAAM,SAAS,SAAS,MAAM;EACjD,OAAO,SAAS,KAAK,IAAI,OAAO,SAAS,SAAS,CAAC;CACrD;CAEA,MAAM,cAAc,QAAQ,QAAQ,KAAK,WAAW,MAAM,QAAQ,CAAC;CACnE,IAAI,eAAe,GACjB,OAAO,SAAS,KAAK,MAAM,SAAS,SAAS,MAAM;CAGrD,IAAI,aAAa;CACjB,MAAM,SAAS,SAAS;CACxB,KAAK,IAAI,QAAQ,GAAG,QAAQ,SAAS,QAAQ,SAAS;EACpD,cAAc,QAAQ;EACtB,IAAI,SAAS,YAAY,OAAO,SAAS;CAC3C;CAEA,OAAO,SAAS,SAAS,SAAS;AACpC"}
@@ -1 +1 @@
1
- {"version":3,"file":"eventBuffer.cjs","names":[],"sources":["../../../src/core/eventBuffer.ts"],"sourcesContent":["import type { AnalyticsEvent, ContentExposureEvent } from './types';\n\n/** Field separator for coalescing keys — never present in content keys. */\nconst KEY_SEPARATOR = '\u0001';\n\n/**\n * Builds the coalescing key for a content-exposure event. Two exposures of the\n * same node, page, locale, experiment, and variant collapse into one event with\n * an incremented `count`.\n */\nconst exposureKey = (event: ContentExposureEvent): string =>\n [\n event.url,\n event.dictionaryKey,\n event.keyPath,\n event.locale,\n event.experimentKey ?? '',\n event.variant ?? '',\n ].join(KEY_SEPARATOR);\n\n/**\n * A bounded, coalescing in-memory buffer for analytics events.\n *\n * - `page_view` and `conversion` events are appended verbatim (they are rare\n * and valuable — they are never evicted while exposures remain).\n * - `content_exposure` events are deduplicated by page/node/locale/variant with\n * a running `count`, keeping the highest-volume signal cheap.\n * - When the total number of stored events exceeds `max`, the **oldest\n * exposures** are evicted first (analytics is lossy by design; exposures are\n * the expendable signal). Discrete events are only dropped once no exposures\n * remain.\n */\nexport type EventBuffer = {\n /** Adds an event, coalescing content exposures. Returns the current size. */\n push: (event: AnalyticsEvent) => number;\n /** Removes and returns every buffered event. */\n drain: () => AnalyticsEvent[];\n /** Current number of distinct buffered events. */\n size: () => number;\n};\n\n/**\n * Creates an {@link EventBuffer}.\n *\n * @param options - Buffer options.\n * @param options.max - Maximum number of distinct events to retain.\n * @returns A new buffer instance.\n */\nexport const createEventBuffer = ({ max }: { max: number }): EventBuffer => {\n // Insertion-ordered list of non-coalesced events (page views, conversions).\n let discreteEvents: AnalyticsEvent[] = [];\n // Coalesced content exposures keyed by page/node/locale/variant.\n const exposures = new Map<string, ContentExposureEvent>();\n\n const size = (): number => discreteEvents.length + exposures.size;\n\n /** Evicts oldest exposures first, then oldest discrete events. */\n const enforceCap = (): void => {\n while (size() > max && exposures.size > 0) {\n // Map iteration follows insertion order — the first key is the oldest.\n const oldestKey = exposures.keys().next().value as string;\n exposures.delete(oldestKey);\n }\n if (size() > max) {\n discreteEvents = discreteEvents.slice(size() - max);\n }\n };\n\n const push = (event: AnalyticsEvent): number => {\n if (event.type === 'content_exposure') {\n const key = exposureKey(event);\n const existing = exposures.get(key);\n\n if (existing) {\n existing.count = (existing.count ?? 1) + (event.count ?? 1);\n existing.t = event.t; // keep the most recent timestamp\n } else {\n exposures.set(key, { ...event, count: event.count ?? 1 });\n }\n } else {\n discreteEvents.push(event);\n }\n\n enforceCap();\n\n return size();\n };\n\n const drain = (): AnalyticsEvent[] => {\n const drained: AnalyticsEvent[] = [\n ...discreteEvents,\n ...exposures.values(),\n ];\n discreteEvents = [];\n exposures.clear();\n return drained;\n };\n\n return { push, drain, size };\n};\n"],"mappings":";;;;AAGA,MAAM,gBAAgB;;;;;;AAOtB,MAAM,eAAe,UACnB;CACE,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM,iBAAiB;CACvB,MAAM,WAAW;CAClB,CAAC,KAAK,cAAc;;;;;;;;AA8BvB,MAAa,qBAAqB,EAAE,UAAwC;CAE1E,IAAI,iBAAmC,EAAE;CAEzC,MAAM,4BAAY,IAAI,KAAmC;CAEzD,MAAM,aAAqB,eAAe,SAAS,UAAU;;CAG7D,MAAM,mBAAyB;AAC7B,SAAO,MAAM,GAAG,OAAO,UAAU,OAAO,GAAG;GAEzC,MAAM,YAAY,UAAU,MAAM,CAAC,MAAM,CAAC;AAC1C,aAAU,OAAO,UAAU;;AAE7B,MAAI,MAAM,GAAG,IACX,kBAAiB,eAAe,MAAM,MAAM,GAAG,IAAI;;CAIvD,MAAM,QAAQ,UAAkC;AAC9C,MAAI,MAAM,SAAS,oBAAoB;GACrC,MAAM,MAAM,YAAY,MAAM;GAC9B,MAAM,WAAW,UAAU,IAAI,IAAI;AAEnC,OAAI,UAAU;AACZ,aAAS,SAAS,SAAS,SAAS,MAAM,MAAM,SAAS;AACzD,aAAS,IAAI,MAAM;SAEnB,WAAU,IAAI,KAAK;IAAE,GAAG;IAAO,OAAO,MAAM,SAAS;IAAG,CAAC;QAG3D,gBAAe,KAAK,MAAM;AAG5B,cAAY;AAEZ,SAAO,MAAM;;CAGf,MAAM,cAAgC;EACpC,MAAM,UAA4B,CAChC,GAAG,gBACH,GAAG,UAAU,QAAQ,CACtB;AACD,mBAAiB,EAAE;AACnB,YAAU,OAAO;AACjB,SAAO;;AAGT,QAAO;EAAE;EAAM;EAAO;EAAM"}
1
+ {"version":3,"file":"eventBuffer.cjs","names":[],"sources":["../../../src/core/eventBuffer.ts"],"sourcesContent":["import type { AnalyticsEvent, ContentExposureEvent } from './types';\n\n/** Field separator for coalescing keys — never present in content keys. */\nconst KEY_SEPARATOR = '\u0001';\n\n/**\n * Builds the coalescing key for a content-exposure event. Two exposures of the\n * same node, page, locale, experiment, and variant collapse into one event with\n * an incremented `count`.\n */\nconst exposureKey = (event: ContentExposureEvent): string =>\n [\n event.url,\n event.dictionaryKey,\n event.keyPath,\n event.locale,\n event.experimentKey ?? '',\n event.variant ?? '',\n ].join(KEY_SEPARATOR);\n\n/**\n * A bounded, coalescing in-memory buffer for analytics events.\n *\n * - `page_view` and `conversion` events are appended verbatim (they are rare\n * and valuable — they are never evicted while exposures remain).\n * - `content_exposure` events are deduplicated by page/node/locale/variant with\n * a running `count`, keeping the highest-volume signal cheap.\n * - When the total number of stored events exceeds `max`, the **oldest\n * exposures** are evicted first (analytics is lossy by design; exposures are\n * the expendable signal). Discrete events are only dropped once no exposures\n * remain.\n */\nexport type EventBuffer = {\n /** Adds an event, coalescing content exposures. Returns the current size. */\n push: (event: AnalyticsEvent) => number;\n /** Removes and returns every buffered event. */\n drain: () => AnalyticsEvent[];\n /** Current number of distinct buffered events. */\n size: () => number;\n};\n\n/**\n * Creates an {@link EventBuffer}.\n *\n * @param options - Buffer options.\n * @param options.max - Maximum number of distinct events to retain.\n * @returns A new buffer instance.\n */\nexport const createEventBuffer = ({ max }: { max: number }): EventBuffer => {\n // Insertion-ordered list of non-coalesced events (page views, conversions).\n let discreteEvents: AnalyticsEvent[] = [];\n // Coalesced content exposures keyed by page/node/locale/variant.\n const exposures = new Map<string, ContentExposureEvent>();\n\n const size = (): number => discreteEvents.length + exposures.size;\n\n /** Evicts oldest exposures first, then oldest discrete events. */\n const enforceCap = (): void => {\n while (size() > max && exposures.size > 0) {\n // Map iteration follows insertion order — the first key is the oldest.\n const oldestKey = exposures.keys().next().value as string;\n exposures.delete(oldestKey);\n }\n if (size() > max) {\n discreteEvents = discreteEvents.slice(size() - max);\n }\n };\n\n const push = (event: AnalyticsEvent): number => {\n if (event.type === 'content_exposure') {\n const key = exposureKey(event);\n const existing = exposures.get(key);\n\n if (existing) {\n existing.count = (existing.count ?? 1) + (event.count ?? 1);\n existing.t = event.t; // keep the most recent timestamp\n } else {\n exposures.set(key, { ...event, count: event.count ?? 1 });\n }\n } else {\n discreteEvents.push(event);\n }\n\n enforceCap();\n\n return size();\n };\n\n const drain = (): AnalyticsEvent[] => {\n const drained: AnalyticsEvent[] = [\n ...discreteEvents,\n ...exposures.values(),\n ];\n discreteEvents = [];\n exposures.clear();\n return drained;\n };\n\n return { push, drain, size };\n};\n"],"mappings":";;;;AAGA,MAAM,gBAAgB;;;;;;AAOtB,MAAM,eAAe,UACnB;CACE,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM,iBAAiB;CACvB,MAAM,WAAW;AACnB,CAAC,CAAC,KAAK,aAAa;;;;;;;;AA8BtB,MAAa,qBAAqB,EAAE,UAAwC;CAE1E,IAAI,iBAAmC,CAAC;CAExC,MAAM,4BAAY,IAAI,IAAkC;CAExD,MAAM,aAAqB,eAAe,SAAS,UAAU;;CAG7D,MAAM,mBAAyB;EAC7B,OAAO,KAAK,IAAI,OAAO,UAAU,OAAO,GAAG;GAEzC,MAAM,YAAY,UAAU,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;GAC1C,UAAU,OAAO,SAAS;EAC5B;EACA,IAAI,KAAK,IAAI,KACX,iBAAiB,eAAe,MAAM,KAAK,IAAI,GAAG;CAEtD;CAEA,MAAM,QAAQ,UAAkC;EAC9C,IAAI,MAAM,SAAS,oBAAoB;GACrC,MAAM,MAAM,YAAY,KAAK;GAC7B,MAAM,WAAW,UAAU,IAAI,GAAG;GAElC,IAAI,UAAU;IACZ,SAAS,SAAS,SAAS,SAAS,MAAM,MAAM,SAAS;IACzD,SAAS,IAAI,MAAM;GACrB,OACE,UAAU,IAAI,KAAK;IAAE,GAAG;IAAO,OAAO,MAAM,SAAS;GAAE,CAAC;EAE5D,OACE,eAAe,KAAK,KAAK;EAG3B,WAAW;EAEX,OAAO,KAAK;CACd;CAEA,MAAM,cAAgC;EACpC,MAAM,UAA4B,CAChC,GAAG,gBACH,GAAG,UAAU,OAAO,CACtB;EACA,iBAAiB,CAAC;EAClB,UAAU,MAAM;EAChB,OAAO;CACT;CAEA,OAAO;EAAE;EAAM;EAAO;CAAK;AAC7B"}
@@ -1 +1 @@
1
- {"version":3,"file":"globalManager.cjs","names":[],"sources":["../../../src/core/globalManager.ts"],"sourcesContent":["import type { AnalyticsClient } from './AnalyticsClient';\n\n/**\n * Key on `window` used to share the client singleton across multiple module\n * instances. When bundlers include `@intlayer/analytics` more than once (e.g.\n * a framework package plus the app), each copy has its own module-level\n * variables; storing the client on `window` ensures they all share one buffer\n * and one flush timer.\n */\nconst CLIENT_KEY = '__intlayer_analytics_client__';\n\n/**\n * Key on `window` holding the provider reference count. It lives next to the\n * client (rather than in module scope) for the same reason the client does:\n * duplicated module instances must share one count, otherwise one copy's\n * `stopAnalyticsClient` could stop a client another copy still uses.\n */\nconst REF_COUNT_KEY = '__intlayer_analytics_ref_count__';\n\ntype WindowWithAnalyticsGlobals = typeof window & {\n [CLIENT_KEY]?: AnalyticsClient | null;\n [REF_COUNT_KEY]?: number;\n};\n\n/**\n * Returns the global analytics client, or `null` in SSR or before init.\n */\nexport const getGlobalAnalyticsClient = (): AnalyticsClient | null => {\n if (typeof window === 'undefined') return null;\n return (window as WindowWithAnalyticsGlobals)[CLIENT_KEY] ?? null;\n};\n\n/**\n * Sets (or clears) the global analytics client singleton.\n *\n * @param client - The client to store globally, or `null` to clear it.\n */\nexport const setGlobalAnalyticsClient = (\n client: AnalyticsClient | null\n): void => {\n if (typeof window === 'undefined') return;\n (window as WindowWithAnalyticsGlobals)[CLIENT_KEY] = client;\n};\n\n/**\n * Increments the shared provider reference count.\n *\n * @returns The count after incrementing (`0` in SSR, where nothing is stored).\n */\nexport const incrementAnalyticsClientRefCount = (): number => {\n if (typeof window === 'undefined') return 0;\n const globals = window as WindowWithAnalyticsGlobals;\n globals[REF_COUNT_KEY] = (globals[REF_COUNT_KEY] ?? 0) + 1;\n return globals[REF_COUNT_KEY];\n};\n\n/**\n * Decrements the shared provider reference count, clamping at zero.\n *\n * @returns The count after decrementing (`0` in SSR, where nothing is stored).\n */\nexport const decrementAnalyticsClientRefCount = (): number => {\n if (typeof window === 'undefined') return 0;\n const globals = window as WindowWithAnalyticsGlobals;\n globals[REF_COUNT_KEY] = Math.max(0, (globals[REF_COUNT_KEY] ?? 0) - 1);\n return globals[REF_COUNT_KEY];\n};\n"],"mappings":";;;;;;;;;;AASA,MAAM,aAAa;;;;;;;AAQnB,MAAM,gBAAgB;;;;AAUtB,MAAa,iCAAyD;AACpE,KAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,QAAQ,OAAsC,eAAe;;;;;;;AAQ/D,MAAa,4BACX,WACS;AACT,KAAI,OAAO,WAAW,YAAa;AACnC,CAAC,OAAsC,cAAc;;;;;;;AAQvD,MAAa,yCAAiD;AAC5D,KAAI,OAAO,WAAW,YAAa,QAAO;CAC1C,MAAM,UAAU;AAChB,SAAQ,kBAAkB,QAAQ,kBAAkB,KAAK;AACzD,QAAO,QAAQ;;;;;;;AAQjB,MAAa,yCAAiD;AAC5D,KAAI,OAAO,WAAW,YAAa,QAAO;CAC1C,MAAM,UAAU;AAChB,SAAQ,iBAAiB,KAAK,IAAI,IAAI,QAAQ,kBAAkB,KAAK,EAAE;AACvE,QAAO,QAAQ"}
1
+ {"version":3,"file":"globalManager.cjs","names":[],"sources":["../../../src/core/globalManager.ts"],"sourcesContent":["import type { AnalyticsClient } from './AnalyticsClient';\n\n/**\n * Key on `window` used to share the client singleton across multiple module\n * instances. When bundlers include `@intlayer/analytics` more than once (e.g.\n * a framework package plus the app), each copy has its own module-level\n * variables; storing the client on `window` ensures they all share one buffer\n * and one flush timer.\n */\nconst CLIENT_KEY = '__intlayer_analytics_client__';\n\n/**\n * Key on `window` holding the provider reference count. It lives next to the\n * client (rather than in module scope) for the same reason the client does:\n * duplicated module instances must share one count, otherwise one copy's\n * `stopAnalyticsClient` could stop a client another copy still uses.\n */\nconst REF_COUNT_KEY = '__intlayer_analytics_ref_count__';\n\ntype WindowWithAnalyticsGlobals = typeof window & {\n [CLIENT_KEY]?: AnalyticsClient | null;\n [REF_COUNT_KEY]?: number;\n};\n\n/**\n * Returns the global analytics client, or `null` in SSR or before init.\n */\nexport const getGlobalAnalyticsClient = (): AnalyticsClient | null => {\n if (typeof window === 'undefined') return null;\n return (window as WindowWithAnalyticsGlobals)[CLIENT_KEY] ?? null;\n};\n\n/**\n * Sets (or clears) the global analytics client singleton.\n *\n * @param client - The client to store globally, or `null` to clear it.\n */\nexport const setGlobalAnalyticsClient = (\n client: AnalyticsClient | null\n): void => {\n if (typeof window === 'undefined') return;\n (window as WindowWithAnalyticsGlobals)[CLIENT_KEY] = client;\n};\n\n/**\n * Increments the shared provider reference count.\n *\n * @returns The count after incrementing (`0` in SSR, where nothing is stored).\n */\nexport const incrementAnalyticsClientRefCount = (): number => {\n if (typeof window === 'undefined') return 0;\n const globals = window as WindowWithAnalyticsGlobals;\n globals[REF_COUNT_KEY] = (globals[REF_COUNT_KEY] ?? 0) + 1;\n return globals[REF_COUNT_KEY];\n};\n\n/**\n * Decrements the shared provider reference count, clamping at zero.\n *\n * @returns The count after decrementing (`0` in SSR, where nothing is stored).\n */\nexport const decrementAnalyticsClientRefCount = (): number => {\n if (typeof window === 'undefined') return 0;\n const globals = window as WindowWithAnalyticsGlobals;\n globals[REF_COUNT_KEY] = Math.max(0, (globals[REF_COUNT_KEY] ?? 0) - 1);\n return globals[REF_COUNT_KEY];\n};\n"],"mappings":";;;;;;;;;;AASA,MAAM,aAAa;;;;;;;AAQnB,MAAM,gBAAgB;;;;AAUtB,MAAa,iCAAyD;CACpE,IAAI,OAAO,WAAW,aAAa,OAAO;CAC1C,OAAQ,OAAsC,eAAe;AAC/D;;;;;;AAOA,MAAa,4BACX,WACS;CACT,IAAI,OAAO,WAAW,aAAa;CACnC,AAAC,OAAsC,cAAc;AACvD;;;;;;AAOA,MAAa,yCAAiD;CAC5D,IAAI,OAAO,WAAW,aAAa,OAAO;CAC1C,MAAM,UAAU;CAChB,QAAQ,kBAAkB,QAAQ,kBAAkB,KAAK;CACzD,OAAO,QAAQ;AACjB;;;;;;AAOA,MAAa,yCAAiD;CAC5D,IAAI,OAAO,WAAW,aAAa,OAAO;CAC1C,MAAM,UAAU;CAChB,QAAQ,iBAAiB,KAAK,IAAI,IAAI,QAAQ,kBAAkB,KAAK,CAAC;CACtE,OAAO,QAAQ;AACjB"}
@@ -1 +1 @@
1
- {"version":3,"file":"initAnalyticsClient.cjs","names":["getGlobalAnalyticsClient","createAnalyticsClient","editor","analytics","decrementAnalyticsClientRefCount"],"sources":["../../../src/core/initAnalyticsClient.ts"],"sourcesContent":["import { analytics, editor } from '@intlayer/config/built';\nimport {\n type AnalyticsClient,\n createAnalyticsClient,\n DEFAULT_FLUSH_INTERVAL,\n DEFAULT_MAX_BUFFER_SIZE,\n DEFAULT_SAMPLE_RATE,\n} from './AnalyticsClient';\nimport {\n decrementAnalyticsClientRefCount,\n getGlobalAnalyticsClient,\n incrementAnalyticsClientRefCount,\n setGlobalAnalyticsClient,\n} from './globalManager';\n\n/**\n * Initializes the Intlayer analytics client singleton.\n *\n * Behavior comes from the `analytics` config block (`flushInterval`,\n * `sampleRate`); attribution reuses the existing `editor` config\n * (`editor.backendURL` for the endpoint, `editor.clientId` for the project).\n *\n * Safe to call multiple times: returns the existing client and increments a\n * `window`-shared reference count so nested providers (or duplicated module\n * instances) don't stop the client prematurely.\n *\n * @returns The started analytics client singleton.\n */\nexport const initAnalyticsClient = (): AnalyticsClient => {\n incrementAnalyticsClientRefCount();\n\n const existing = getGlobalAnalyticsClient();\n if (existing) return existing;\n\n const client = createAnalyticsClient({\n backendURL: editor?.backendURL ?? '',\n clientId: editor?.clientId,\n flushInterval: analytics?.flushInterval ?? DEFAULT_FLUSH_INTERVAL,\n maxBufferSize: DEFAULT_MAX_BUFFER_SIZE,\n sampleRate: analytics?.sampleRate ?? DEFAULT_SAMPLE_RATE,\n });\n\n setGlobalAnalyticsClient(client);\n client.start();\n\n return client;\n};\n\n/**\n * Decrements the shared reference count and stops the global analytics client\n * only when the last provider unmounts (flushing any remaining events).\n *\n * Callers must pair each `stopAnalyticsClient` with a prior\n * `initAnalyticsClient` — never call it when init was skipped or cancelled.\n */\nexport const stopAnalyticsClient = (): void => {\n if (decrementAnalyticsClientRefCount() > 0) return;\n\n const client = getGlobalAnalyticsClient();\n client?.stop();\n setGlobalAnalyticsClient(null);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA4BA,MAAa,4BAA6C;AACxD,8DAAkC;CAElC,MAAM,WAAWA,qDAA0B;AAC3C,KAAI,SAAU,QAAO;CAErB,MAAM,SAASC,mDAAsB;EACnC,YAAYC,+BAAQ,cAAc;EAClC,UAAUA,+BAAQ;EAClB,eAAeC,kCAAW;EAC1B;EACA,YAAYA,kCAAW;EACxB,CAAC;AAEF,qDAAyB,OAAO;AAChC,QAAO,OAAO;AAEd,QAAO;;;;;;;;;AAUT,MAAa,4BAAkC;AAC7C,KAAIC,6DAAkC,GAAG,EAAG;AAG5C,CADeJ,qDACT,EAAE,MAAM;AACd,qDAAyB,KAAK"}
1
+ {"version":3,"file":"initAnalyticsClient.cjs","names":["getGlobalAnalyticsClient","createAnalyticsClient","editor","analytics","decrementAnalyticsClientRefCount"],"sources":["../../../src/core/initAnalyticsClient.ts"],"sourcesContent":["import { analytics, editor } from '@intlayer/config/built';\nimport {\n type AnalyticsClient,\n createAnalyticsClient,\n DEFAULT_FLUSH_INTERVAL,\n DEFAULT_MAX_BUFFER_SIZE,\n DEFAULT_SAMPLE_RATE,\n} from './AnalyticsClient';\nimport {\n decrementAnalyticsClientRefCount,\n getGlobalAnalyticsClient,\n incrementAnalyticsClientRefCount,\n setGlobalAnalyticsClient,\n} from './globalManager';\n\n/**\n * Initializes the Intlayer analytics client singleton.\n *\n * Behavior comes from the `analytics` config block (`flushInterval`,\n * `sampleRate`); attribution reuses the existing `editor` config\n * (`editor.backendURL` for the endpoint, `editor.clientId` for the project).\n *\n * Safe to call multiple times: returns the existing client and increments a\n * `window`-shared reference count so nested providers (or duplicated module\n * instances) don't stop the client prematurely.\n *\n * @returns The started analytics client singleton.\n */\nexport const initAnalyticsClient = (): AnalyticsClient => {\n incrementAnalyticsClientRefCount();\n\n const existing = getGlobalAnalyticsClient();\n if (existing) return existing;\n\n const client = createAnalyticsClient({\n backendURL: editor?.backendURL ?? '',\n clientId: editor?.clientId,\n flushInterval: analytics?.flushInterval ?? DEFAULT_FLUSH_INTERVAL,\n maxBufferSize: DEFAULT_MAX_BUFFER_SIZE,\n sampleRate: analytics?.sampleRate ?? DEFAULT_SAMPLE_RATE,\n });\n\n setGlobalAnalyticsClient(client);\n client.start();\n\n return client;\n};\n\n/**\n * Decrements the shared reference count and stops the global analytics client\n * only when the last provider unmounts (flushing any remaining events).\n *\n * Callers must pair each `stopAnalyticsClient` with a prior\n * `initAnalyticsClient` — never call it when init was skipped or cancelled.\n */\nexport const stopAnalyticsClient = (): void => {\n if (decrementAnalyticsClientRefCount() > 0) return;\n\n const client = getGlobalAnalyticsClient();\n client?.stop();\n setGlobalAnalyticsClient(null);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA4BA,MAAa,4BAA6C;CACxD,4DAAiC;CAEjC,MAAM,WAAWA,oDAAyB;CAC1C,IAAI,UAAU,OAAO;CAErB,MAAM,SAASC,mDAAsB;EACnC,YAAYC,+BAAQ,cAAc;EAClC,UAAUA,+BAAQ;EAClB,eAAeC,kCAAW;EAC1B;EACA,YAAYA,kCAAW;CACzB,CAAC;CAED,oDAAyB,MAAM;CAC/B,OAAO,MAAM;CAEb,OAAO;AACT;;;;;;;;AASA,MAAa,4BAAkC;CAC7C,IAAIC,4DAAiC,IAAI,GAAG;CAG5C,AADeJ,oDACV,CAAC,EAAE,KAAK;CACb,oDAAyB,IAAI;AAC/B"}
@@ -1 +1 @@
1
- {"version":3,"file":"sampling.cjs","names":["hashString"],"sources":["../../../src/core/sampling.ts"],"sourcesContent":["import { hashString } from '../utils/hash';\n\n/**\n * Deterministic per-session sampling gate. Using the session id (rather than a\n * fresh random draw per event) means a sampled-in session reports *all* of its\n * content exposures, keeping per-session funnels consistent instead of leaving\n * holes.\n *\n * @param sessionId - The current anonymous session id.\n * @param sampleRate - Fraction of sessions to keep, from 0 (none) to 1 (all).\n * @returns `true` when this session's events should be recorded.\n *\n * @example\n * isSampledIn('abc', 1); // always true\n * isSampledIn('abc', 0); // always false\n * isSampledIn('abc', 0.5); // stable per session\n */\nexport const isSampledIn = (sessionId: string, sampleRate: number): boolean => {\n if (sampleRate >= 1) return true;\n if (sampleRate <= 0) return false;\n\n const bucket = hashString(sessionId) / 0xffffffff;\n return bucket < sampleRate;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiBA,MAAa,eAAe,WAAmB,eAAgC;AAC7E,KAAI,cAAc,EAAG,QAAO;AAC5B,KAAI,cAAc,EAAG,QAAO;AAG5B,QADeA,8BAAW,UAAU,GAAG,aACvB"}
1
+ {"version":3,"file":"sampling.cjs","names":["hashString"],"sources":["../../../src/core/sampling.ts"],"sourcesContent":["import { hashString } from '../utils/hash';\n\n/**\n * Deterministic per-session sampling gate. Using the session id (rather than a\n * fresh random draw per event) means a sampled-in session reports *all* of its\n * content exposures, keeping per-session funnels consistent instead of leaving\n * holes.\n *\n * @param sessionId - The current anonymous session id.\n * @param sampleRate - Fraction of sessions to keep, from 0 (none) to 1 (all).\n * @returns `true` when this session's events should be recorded.\n *\n * @example\n * isSampledIn('abc', 1); // always true\n * isSampledIn('abc', 0); // always false\n * isSampledIn('abc', 0.5); // stable per session\n */\nexport const isSampledIn = (sessionId: string, sampleRate: number): boolean => {\n if (sampleRate >= 1) return true;\n if (sampleRate <= 0) return false;\n\n const bucket = hashString(sessionId) / 0xffffffff;\n return bucket < sampleRate;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiBA,MAAa,eAAe,WAAmB,eAAgC;CAC7E,IAAI,cAAc,GAAG,OAAO;CAC5B,IAAI,cAAc,GAAG,OAAO;CAG5B,OADeA,8BAAW,SAAS,IAAI,aACvB;AAClB"}
@@ -1 +1 @@
1
- {"version":3,"file":"session.cjs","names":[],"sources":["../../../src/core/session.ts"],"sourcesContent":["/**\n * Anonymous, per-tab session identity. Stored in `sessionStorage` so it is\n * cleared when the tab closes and is never shared across sites — no durable\n * cookie, no cross-site tracking, no PII.\n */\n\nconst SESSION_STORAGE_KEY = '__intlayer_analytics_sid__';\n\n/**\n * Generates a random, opaque session identifier.\n *\n * @returns A URL-safe random string.\n */\nconst generateSessionId = (): string => {\n const cryptoObj =\n typeof globalThis !== 'undefined'\n ? (globalThis.crypto as Crypto | undefined)\n : undefined;\n\n if (cryptoObj?.randomUUID) {\n return cryptoObj.randomUUID();\n }\n\n // Fallback for environments without crypto.randomUUID (older RN/Lynx)\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n};\n\n/**\n * Returns the current session id, creating and persisting one on first access.\n * Degrades gracefully to an in-memory id when `sessionStorage` is unavailable\n * (private mode, native runtimes).\n *\n * @returns The stable session id for the lifetime of the tab.\n */\nexport const getSessionId = (): string => {\n if (typeof window === 'undefined' || !window.sessionStorage) {\n return generateSessionId();\n }\n\n try {\n const existing = window.sessionStorage.getItem(SESSION_STORAGE_KEY);\n if (existing) return existing;\n\n const created = generateSessionId();\n window.sessionStorage.setItem(SESSION_STORAGE_KEY, created);\n return created;\n } catch {\n // sessionStorage can throw (Safari private mode, quota) — never break the app\n return generateSessionId();\n }\n};\n"],"mappings":";;;;;;;;AAMA,MAAM,sBAAsB;;;;;;AAO5B,MAAM,0BAAkC;CACtC,MAAM,YACJ,OAAO,eAAe,cACjB,WAAW,SACZ;AAEN,KAAI,WAAW,WACb,QAAO,UAAU,YAAY;AAI/B,QAAO,GAAG,KAAK,KAAK,CAAC,SAAS,GAAG,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,GAAG,GAAG;;;;;;;;;AAU9E,MAAa,qBAA6B;AACxC,KAAI,OAAO,WAAW,eAAe,CAAC,OAAO,eAC3C,QAAO,mBAAmB;AAG5B,KAAI;EACF,MAAM,WAAW,OAAO,eAAe,QAAQ,oBAAoB;AACnE,MAAI,SAAU,QAAO;EAErB,MAAM,UAAU,mBAAmB;AACnC,SAAO,eAAe,QAAQ,qBAAqB,QAAQ;AAC3D,SAAO;SACD;AAEN,SAAO,mBAAmB"}
1
+ {"version":3,"file":"session.cjs","names":[],"sources":["../../../src/core/session.ts"],"sourcesContent":["/**\n * Anonymous, per-tab session identity. Stored in `sessionStorage` so it is\n * cleared when the tab closes and is never shared across sites — no durable\n * cookie, no cross-site tracking, no PII.\n */\n\nconst SESSION_STORAGE_KEY = '__intlayer_analytics_sid__';\n\n/**\n * Generates a random, opaque session identifier.\n *\n * @returns A URL-safe random string.\n */\nconst generateSessionId = (): string => {\n const cryptoObj =\n typeof globalThis !== 'undefined'\n ? (globalThis.crypto as Crypto | undefined)\n : undefined;\n\n if (cryptoObj?.randomUUID) {\n return cryptoObj.randomUUID();\n }\n\n // Fallback for environments without crypto.randomUUID (older RN/Lynx)\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n};\n\n/**\n * Returns the current session id, creating and persisting one on first access.\n * Degrades gracefully to an in-memory id when `sessionStorage` is unavailable\n * (private mode, native runtimes).\n *\n * @returns The stable session id for the lifetime of the tab.\n */\nexport const getSessionId = (): string => {\n if (typeof window === 'undefined' || !window.sessionStorage) {\n return generateSessionId();\n }\n\n try {\n const existing = window.sessionStorage.getItem(SESSION_STORAGE_KEY);\n if (existing) return existing;\n\n const created = generateSessionId();\n window.sessionStorage.setItem(SESSION_STORAGE_KEY, created);\n return created;\n } catch {\n // sessionStorage can throw (Safari private mode, quota) — never break the app\n return generateSessionId();\n }\n};\n"],"mappings":";;;;;;;;AAMA,MAAM,sBAAsB;;;;;;AAO5B,MAAM,0BAAkC;CACtC,MAAM,YACJ,OAAO,eAAe,cACjB,WAAW,SACZ;CAEN,IAAI,WAAW,YACb,OAAO,UAAU,WAAW;CAI9B,OAAO,GAAG,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,GAAG,EAAE;AAC7E;;;;;;;;AASA,MAAa,qBAA6B;CACxC,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,gBAC3C,OAAO,kBAAkB;CAG3B,IAAI;EACF,MAAM,WAAW,OAAO,eAAe,QAAQ,mBAAmB;EAClE,IAAI,UAAU,OAAO;EAErB,MAAM,UAAU,kBAAkB;EAClC,OAAO,eAAe,QAAQ,qBAAqB,OAAO;EAC1D,OAAO;CACT,QAAQ;EAEN,OAAO,kBAAkB;CAC3B;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"transport.cjs","names":[],"sources":["../../../src/core/transport.ts"],"sourcesContent":["import type { AnalyticsIngestBody } from './types';\n\n/**\n * Sends a batch of events to the backend. Every path is non-blocking and\n * no-throw — analytics must never break, slow, or delay the host application.\n *\n * Strategy:\n * 1. `navigator.sendBeacon` for the flush-on-hide path — survives page unload\n * and never blocks navigation. The payload is sent as `text/plain` (a\n * CORS-safelisted content type): a JSON `Blob` would require a CORS\n * preflight that browsers handle inconsistently during unload, silently\n * dropping the beacon. The backend parses `text/plain` bodies as JSON.\n * 2. `fetch(..., { keepalive: true })` for interval flushes — survives short\n * navigations without holding the main thread.\n * 3. Plain `fetch` fallback for runtimes without `keepalive` (older RN/Lynx).\n *\n * @param endpoint - Fully-qualified ingestion URL.\n * @param body - The batched payload.\n * @param options - Transport options.\n * @param options.useBeacon - Prefer `sendBeacon` (used when the page is hiding).\n * @returns `true` when a send was dispatched, `false` otherwise.\n */\nexport const sendEvents = (\n endpoint: string,\n body: AnalyticsIngestBody,\n { useBeacon = false }: { useBeacon?: boolean } = {}\n): boolean => {\n try {\n const payload = JSON.stringify(body);\n\n if (\n useBeacon &&\n typeof navigator !== 'undefined' &&\n typeof navigator.sendBeacon === 'function'\n ) {\n // Note: unlike the fetch path below, sendBeacon always includes\n // credentials; the ingest endpoint ignores them.\n return navigator.sendBeacon(endpoint, payload);\n }\n\n if (typeof fetch === 'function') {\n // keepalive lets the request outlive a same-tab navigation.\n void fetch(endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: payload,\n keepalive: true,\n // Analytics is best-effort; never send credentials.\n credentials: 'omit',\n mode: 'cors',\n }).catch(() => {\n /* swallow — best-effort delivery */\n });\n return true;\n }\n\n return false;\n } catch {\n // JSON serialization failed — drop the batch silently.\n return false;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAsBA,MAAa,cACX,UACA,MACA,EAAE,YAAY,UAAmC,EAAE,KACvC;AACZ,KAAI;EACF,MAAM,UAAU,KAAK,UAAU,KAAK;AAEpC,MACE,aACA,OAAO,cAAc,eACrB,OAAO,UAAU,eAAe,WAIhC,QAAO,UAAU,WAAW,UAAU,QAAQ;AAGhD,MAAI,OAAO,UAAU,YAAY;AAE/B,GAAK,MAAM,UAAU;IACnB,QAAQ;IACR,SAAS,EAAE,gBAAgB,oBAAoB;IAC/C,MAAM;IACN,WAAW;IAEX,aAAa;IACb,MAAM;IACP,CAAC,CAAC,YAAY,GAEb;AACF,UAAO;;AAGT,SAAO;SACD;AAEN,SAAO"}
1
+ {"version":3,"file":"transport.cjs","names":[],"sources":["../../../src/core/transport.ts"],"sourcesContent":["import type { AnalyticsIngestBody } from './types';\n\n/**\n * Sends a batch of events to the backend. Every path is non-blocking and\n * no-throw — analytics must never break, slow, or delay the host application.\n *\n * Strategy:\n * 1. `navigator.sendBeacon` for the flush-on-hide path — survives page unload\n * and never blocks navigation. The payload is sent as `text/plain` (a\n * CORS-safelisted content type): a JSON `Blob` would require a CORS\n * preflight that browsers handle inconsistently during unload, silently\n * dropping the beacon. The backend parses `text/plain` bodies as JSON.\n * 2. `fetch(..., { keepalive: true })` for interval flushes — survives short\n * navigations without holding the main thread.\n * 3. Plain `fetch` fallback for runtimes without `keepalive` (older RN/Lynx).\n *\n * @param endpoint - Fully-qualified ingestion URL.\n * @param body - The batched payload.\n * @param options - Transport options.\n * @param options.useBeacon - Prefer `sendBeacon` (used when the page is hiding).\n * @returns `true` when a send was dispatched, `false` otherwise.\n */\nexport const sendEvents = (\n endpoint: string,\n body: AnalyticsIngestBody,\n { useBeacon = false }: { useBeacon?: boolean } = {}\n): boolean => {\n try {\n const payload = JSON.stringify(body);\n\n if (\n useBeacon &&\n typeof navigator !== 'undefined' &&\n typeof navigator.sendBeacon === 'function'\n ) {\n // Note: unlike the fetch path below, sendBeacon always includes\n // credentials; the ingest endpoint ignores them.\n return navigator.sendBeacon(endpoint, payload);\n }\n\n if (typeof fetch === 'function') {\n // keepalive lets the request outlive a same-tab navigation.\n void fetch(endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: payload,\n keepalive: true,\n // Analytics is best-effort; never send credentials.\n credentials: 'omit',\n mode: 'cors',\n }).catch(() => {\n /* swallow — best-effort delivery */\n });\n return true;\n }\n\n return false;\n } catch {\n // JSON serialization failed — drop the batch silently.\n return false;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAsBA,MAAa,cACX,UACA,MACA,EAAE,YAAY,UAAmC,CAAC,MACtC;CACZ,IAAI;EACF,MAAM,UAAU,KAAK,UAAU,IAAI;EAEnC,IACE,aACA,OAAO,cAAc,eACrB,OAAO,UAAU,eAAe,YAIhC,OAAO,UAAU,WAAW,UAAU,OAAO;EAG/C,IAAI,OAAO,UAAU,YAAY;GAE/B,AAAK,MAAM,UAAU;IACnB,QAAQ;IACR,SAAS,EAAE,gBAAgB,mBAAmB;IAC9C,MAAM;IACN,WAAW;IAEX,aAAa;IACb,MAAM;GACR,CAAC,CAAC,CAAC,YAAY,CAEf,CAAC;GACD,OAAO;EACT;EAEA,OAAO;CACT,QAAQ;EAEN,OAAO;CACT;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"contentExposure.cjs","names":[],"sources":["../../../src/events/contentExposure.ts"],"sourcesContent":["import type { KeyPath } from '@intlayer/types/keyPath';\nimport type { ContentExposureEvent, TrackableEvent } from '../core/types';\n\n/**\n * Serializes a `KeyPath[]` into a compact, stable string used both as the\n * coalescing key in the buffer and as the stored `keyPath` on the wire.\n *\n * Only the `key` of each segment is kept (types are implied by the dictionary\n * shape), producing paths like `\"faq.items.2.answer\"`.\n *\n * @param keyPath - The interpreter key path locating a node.\n * @returns A dot-joined, stable path string.\n *\n * @example\n * serializeKeyPath([{ type: 'object', key: 'faq' }, { type: 'array', key: 2 }]);\n * // \"faq.2\"\n */\nexport const serializeKeyPath = (keyPath: KeyPath[]): string =>\n keyPath\n .map((segment) => (segment.key === undefined ? '*' : String(segment.key)))\n .join('.');\n\n/**\n * Builds a content-exposure payload from interpreter node metadata. Shared by\n * every framework binding's analytics node plugin so the wire shape stays\n * identical across React, Vue, Svelte, Angular, etc.\n *\n * @param params - Node metadata available on `NodeProps`.\n * @returns A trackable content-exposure event (minus buffer-stamped fields).\n */\nexport const buildContentExposure = (params: {\n dictionaryKey: string;\n keyPath: KeyPath[];\n locale?: string;\n nodeType?: string;\n experimentKey?: string;\n variant?: string;\n}): Omit<TrackableEvent<ContentExposureEvent>, 'type'> => ({\n dictionaryKey: params.dictionaryKey,\n keyPath: serializeKeyPath(params.keyPath),\n // Left undefined when unknown so the client stamps its ambient locale.\n locale: params.locale,\n nodeType: params.nodeType,\n experimentKey: params.experimentKey,\n variant: params.variant,\n});\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,MAAa,oBAAoB,YAC/B,QACG,KAAK,YAAa,QAAQ,QAAQ,SAAY,MAAM,OAAO,QAAQ,IAAI,CAAE,CACzE,KAAK,IAAI;;;;;;;;;AAUd,MAAa,wBAAwB,YAOsB;CACzD,eAAe,OAAO;CACtB,SAAS,iBAAiB,OAAO,QAAQ;CAEzC,QAAQ,OAAO;CACf,UAAU,OAAO;CACjB,eAAe,OAAO;CACtB,SAAS,OAAO;CACjB"}
1
+ {"version":3,"file":"contentExposure.cjs","names":[],"sources":["../../../src/events/contentExposure.ts"],"sourcesContent":["import type { KeyPath } from '@intlayer/types/keyPath';\nimport type { ContentExposureEvent, TrackableEvent } from '../core/types';\n\n/**\n * Serializes a `KeyPath[]` into a compact, stable string used both as the\n * coalescing key in the buffer and as the stored `keyPath` on the wire.\n *\n * Only the `key` of each segment is kept (types are implied by the dictionary\n * shape), producing paths like `\"faq.items.2.answer\"`.\n *\n * @param keyPath - The interpreter key path locating a node.\n * @returns A dot-joined, stable path string.\n *\n * @example\n * serializeKeyPath([{ type: 'object', key: 'faq' }, { type: 'array', key: 2 }]);\n * // \"faq.2\"\n */\nexport const serializeKeyPath = (keyPath: KeyPath[]): string =>\n keyPath\n .map((segment) => (segment.key === undefined ? '*' : String(segment.key)))\n .join('.');\n\n/**\n * Builds a content-exposure payload from interpreter node metadata. Shared by\n * every framework binding's analytics node plugin so the wire shape stays\n * identical across React, Vue, Svelte, Angular, etc.\n *\n * @param params - Node metadata available on `NodeProps`.\n * @returns A trackable content-exposure event (minus buffer-stamped fields).\n */\nexport const buildContentExposure = (params: {\n dictionaryKey: string;\n keyPath: KeyPath[];\n locale?: string;\n nodeType?: string;\n experimentKey?: string;\n variant?: string;\n}): Omit<TrackableEvent<ContentExposureEvent>, 'type'> => ({\n dictionaryKey: params.dictionaryKey,\n keyPath: serializeKeyPath(params.keyPath),\n // Left undefined when unknown so the client stamps its ambient locale.\n locale: params.locale,\n nodeType: params.nodeType,\n experimentKey: params.experimentKey,\n variant: params.variant,\n});\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,MAAa,oBAAoB,YAC/B,QACG,KAAK,YAAa,QAAQ,QAAQ,SAAY,MAAM,OAAO,QAAQ,GAAG,CAAE,CAAC,CACzE,KAAK,GAAG;;;;;;;;;AAUb,MAAa,wBAAwB,YAOsB;CACzD,eAAe,OAAO;CACtB,SAAS,iBAAiB,OAAO,OAAO;CAExC,QAAQ,OAAO;CACf,UAAU,OAAO;CACjB,eAAe,OAAO;CACtB,SAAS,OAAO;AAClB"}
@@ -1 +1 @@
1
- {"version":3,"file":"isEnabled.cjs","names":["analytics","editor"],"sources":["../../src/isEnabled.ts"],"sourcesContent":["import { analytics, editor } from '@intlayer/config/built';\n\n/**\n * Compile-time kill switch. Bundlers replace `process.env.INTLAYER_ANALYTICS_ENABLED`\n * (set to `'false'` by `@intlayer/config` unless `analytics.enabled` is `true`\n * AND an `editor.clientId` is configured) so the whole analytics integration is\n * dead-code-eliminated for apps that don't opt in.\n */\nconst TREE_SHAKE_ANALYTICS = process.env.INTLAYER_ANALYTICS_ENABLED === 'false';\n\n/**\n * Runtime guard mirroring `@intlayer/editor`'s `isEnabled`, but inverted with\n * respect to the iframe: analytics runs for real end users on the **top**\n * window and stays off inside the editor/CMS preview iframe so editor sessions\n * are never counted as traffic.\n *\n * Enabled when:\n * - the bundler did not tree-shake analytics away, and\n * - the user opted in (`analytics.enabled === true`), and\n * - a project key is configured (`editor.clientId`), and\n * - we are on the client, and\n * - we are the top window (not embedded in the editor).\n */\nexport const isEnabled =\n !TREE_SHAKE_ANALYTICS &&\n analytics?.enabled === true &&\n Boolean(editor?.clientId) &&\n typeof window !== 'undefined' &&\n window.self === window.top;\n"],"mappings":";;;;;;;;;;AAQA,MAAM,uBAAuB,QAAQ,IAAI,+BAA+B;;;;;;;;;;;;;;AAexE,MAAa,YACX,CAAC,wBACDA,kCAAW,YAAY,QACvB,QAAQC,+BAAQ,SAAS,IACzB,OAAO,WAAW,eAClB,OAAO,SAAS,OAAO"}
1
+ {"version":3,"file":"isEnabled.cjs","names":["analytics","editor"],"sources":["../../src/isEnabled.ts"],"sourcesContent":["import { analytics, editor } from '@intlayer/config/built';\n\n/**\n * Compile-time kill switch. Bundlers replace `process.env.INTLAYER_ANALYTICS_ENABLED`\n * (set to `'false'` by `@intlayer/config` unless `analytics.enabled` is `true`\n * AND an `editor.clientId` is configured) so the whole analytics integration is\n * dead-code-eliminated for apps that don't opt in.\n */\nconst TREE_SHAKE_ANALYTICS = process.env.INTLAYER_ANALYTICS_ENABLED === 'false';\n\n/**\n * Runtime guard mirroring `@intlayer/editor`'s `isEnabled`, but inverted with\n * respect to the iframe: analytics runs for real end users on the **top**\n * window and stays off inside the editor/CMS preview iframe so editor sessions\n * are never counted as traffic.\n *\n * Enabled when:\n * - the bundler did not tree-shake analytics away, and\n * - the user opted in (`analytics.enabled === true`), and\n * - a project key is configured (`editor.clientId`), and\n * - we are on the client, and\n * - we are the top window (not embedded in the editor).\n */\nexport const isEnabled =\n !TREE_SHAKE_ANALYTICS &&\n analytics?.enabled === true &&\n Boolean(editor?.clientId) &&\n typeof window !== 'undefined' &&\n window.self === window.top;\n"],"mappings":";;;;;;;;;;AAQA,MAAM,uBAAuB,QAAQ,IAAI,+BAA+B;;;;;;;;;;;;;;AAexE,MAAa,YACX,CAAC,wBACDA,kCAAW,YAAY,QACvB,QAAQC,+BAAQ,QAAQ,KACxB,OAAO,WAAW,eAClB,OAAO,SAAS,OAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"hash.cjs","names":[],"sources":["../../../src/utils/hash.ts"],"sourcesContent":["/**\n * FNV-1a 32-bit string hash. Small, fast, dependency-free, and stable across\n * runtimes — good enough for deterministic A/B bucketing and session seeding\n * (not for cryptographic use).\n *\n * @param input - The string to hash.\n * @returns An unsigned 32-bit integer hash.\n *\n * @example\n * hashString('session-1:homepage-hero'); // 3039336720\n */\nexport const hashString = (input: string): number => {\n let hash = 0x811c9dc5; // FNV offset basis\n\n for (let index = 0; index < input.length; index++) {\n hash ^= input.charCodeAt(index);\n // 32-bit FNV prime multiplication via shifts to stay within Number safe range\n hash = Math.imul(hash, 0x01000193);\n }\n\n // Coerce to unsigned 32-bit\n return hash >>> 0;\n};\n"],"mappings":";;;;;;;;;;;;;;AAWA,MAAa,cAAc,UAA0B;CACnD,IAAI,OAAO;AAEX,MAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS;AACjD,UAAQ,MAAM,WAAW,MAAM;AAE/B,SAAO,KAAK,KAAK,MAAM,SAAW;;AAIpC,QAAO,SAAS"}
1
+ {"version":3,"file":"hash.cjs","names":[],"sources":["../../../src/utils/hash.ts"],"sourcesContent":["/**\n * FNV-1a 32-bit string hash. Small, fast, dependency-free, and stable across\n * runtimes — good enough for deterministic A/B bucketing and session seeding\n * (not for cryptographic use).\n *\n * @param input - The string to hash.\n * @returns An unsigned 32-bit integer hash.\n *\n * @example\n * hashString('session-1:homepage-hero'); // 3039336720\n */\nexport const hashString = (input: string): number => {\n let hash = 0x811c9dc5; // FNV offset basis\n\n for (let index = 0; index < input.length; index++) {\n hash ^= input.charCodeAt(index);\n // 32-bit FNV prime multiplication via shifts to stay within Number safe range\n hash = Math.imul(hash, 0x01000193);\n }\n\n // Coerce to unsigned 32-bit\n return hash >>> 0;\n};\n"],"mappings":";;;;;;;;;;;;;;AAWA,MAAa,cAAc,UAA0B;CACnD,IAAI,OAAO;CAEX,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS;EACjD,QAAQ,MAAM,WAAW,KAAK;EAE9B,OAAO,KAAK,KAAK,MAAM,QAAU;CACnC;CAGA,OAAO,SAAS;AAClB"}
@@ -1 +1 @@
1
- {"version":3,"file":"idle.cjs","names":[],"sources":["../../../src/utils/idle.ts"],"sourcesContent":["/**\n * Runs a callback when the browser is idle, without blocking first render.\n * Falls back to a short `setTimeout` where `requestIdleCallback` is unavailable\n * (Safari, React Native, Lynx).\n *\n * @param callback - Work to run once the main thread is free.\n *\n * @example\n * onIdle(() => attachVisibilityListeners());\n */\nexport const onIdle = (callback: () => void): void => {\n if (typeof window === 'undefined') return;\n\n const requestIdle = (\n window as Window & {\n requestIdleCallback?: (cb: () => void) => number;\n }\n ).requestIdleCallback;\n\n if (typeof requestIdle === 'function') {\n requestIdle(() => callback());\n return;\n }\n\n setTimeout(callback, 1);\n};\n"],"mappings":";;;;;;;;;;;;;AAUA,MAAa,UAAU,aAA+B;AACpD,KAAI,OAAO,WAAW,YAAa;CAEnC,MAAM,cACJ,OAGA;AAEF,KAAI,OAAO,gBAAgB,YAAY;AACrC,oBAAkB,UAAU,CAAC;AAC7B;;AAGF,YAAW,UAAU,EAAE"}
1
+ {"version":3,"file":"idle.cjs","names":[],"sources":["../../../src/utils/idle.ts"],"sourcesContent":["/**\n * Runs a callback when the browser is idle, without blocking first render.\n * Falls back to a short `setTimeout` where `requestIdleCallback` is unavailable\n * (Safari, React Native, Lynx).\n *\n * @param callback - Work to run once the main thread is free.\n *\n * @example\n * onIdle(() => attachVisibilityListeners());\n */\nexport const onIdle = (callback: () => void): void => {\n if (typeof window === 'undefined') return;\n\n const requestIdle = (\n window as Window & {\n requestIdleCallback?: (cb: () => void) => number;\n }\n ).requestIdleCallback;\n\n if (typeof requestIdle === 'function') {\n requestIdle(() => callback());\n return;\n }\n\n setTimeout(callback, 1);\n};\n"],"mappings":";;;;;;;;;;;;;AAUA,MAAa,UAAU,aAA+B;CACpD,IAAI,OAAO,WAAW,aAAa;CAEnC,MAAM,cACJ,OAGA;CAEF,IAAI,OAAO,gBAAgB,YAAY;EACrC,kBAAkB,SAAS,CAAC;EAC5B;CACF;CAEA,WAAW,UAAU,CAAC;AACxB"}
@@ -1 +1 @@
1
- {"version":3,"file":"AnalyticsClient.mjs","names":[],"sources":["../../../src/core/AnalyticsClient.ts"],"sourcesContent":["import { onIdle } from '../utils/idle';\nimport { assignVariant } from './abTesting';\nimport { createEventBuffer, type EventBuffer } from './eventBuffer';\nimport { isSampledIn } from './sampling';\nimport { getSessionId } from './session';\nimport { sendEvents } from './transport';\nimport type {\n AnalyticsClientConfig,\n AnalyticsEvent,\n ContentExposureEvent,\n ConversionEvent,\n PageViewEvent,\n TrackableEvent,\n} from './types';\n\n/**\n * Caller-supplied fields for a page view. Everything is optional — the client\n * fills `url`, `locale`, viewport, and referrer from the environment when omitted.\n */\nexport type PageViewInput = {\n /** Explicit pathname / screen name (native runtimes have no `location`). */\n url?: string;\n /** Explicit locale; falls back to the client's ambient locale. */\n locale?: string;\n /** Referrer host override. */\n ref?: string;\n /** Viewport width override. */\n vw?: number;\n /** Viewport height override. */\n vh?: number;\n /** Why the view was recorded. */\n reason?: PageViewEvent['reason'];\n};\n\n/** Default flush cadence — one network request per 20 seconds. */\nexport const DEFAULT_FLUSH_INTERVAL = 20_000;\n/** Default cap on distinct buffered events before an early flush. */\nexport const DEFAULT_MAX_BUFFER_SIZE = 500;\n/** Default sampling — keep every session. */\nexport const DEFAULT_SAMPLE_RATE = 1;\n/**\n * Maximum events per network request. `sendBeacon` and `fetch(keepalive)`\n * reject bodies over ~64KB, so large batches are split into multiple sends.\n */\nexport const MAX_EVENTS_PER_SEND = 200;\n/** Identifies the producing SDK in the ingest envelope. */\nconst SDK_VERSION = 'intlayer-analytics/1';\n\n/**\n * The public surface of the analytics client singleton. Framework bindings hold\n * a reference to this and forward provider/node/conversion signals into it.\n */\nexport type AnalyticsClient = {\n /** Sets the ambient locale stamped onto subsequent events. */\n setLocale: (locale: string) => void;\n /** Records a page/locale view (provider level). */\n trackPageView: (event?: PageViewInput) => void;\n /** Records a content exposure (node level). Sampled + deduped per page view. */\n trackContentExposure: (\n event: Omit<TrackableEvent<ContentExposureEvent>, 'type'>\n ) => void;\n /** Records a conversion tied to an experiment variant. */\n trackConversion: (\n event: Omit<TrackableEvent<ConversionEvent>, 'type'>\n ) => void;\n /** Deterministically resolves this session's variant for an experiment. */\n getVariant: (\n experimentKey: string,\n variants: string[],\n weights?: number[]\n ) => string;\n /** Sends the buffered batch now. */\n flush: (useBeacon?: boolean) => void;\n /** Starts the flush loop and lifecycle listeners (idempotent). */\n start: () => void;\n /** Stops timers/listeners and flushes any remaining events. */\n stop: () => void;\n};\n\n/**\n * Reads the current page pathname. Search params are intentionally excluded to\n * avoid capturing anything sensitive.\n */\nconst currentUrl = (): string => {\n if (typeof window === 'undefined' || !window.location) return '';\n return window.location.pathname;\n};\n\n/**\n * Reduces the referrer to its host — never the full URL — for privacy.\n */\nconst referrerHost = (): string | undefined => {\n if (typeof document === 'undefined' || !document.referrer) return undefined;\n try {\n return new URL(document.referrer).host;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Creates an analytics client. Prefer {@link initAnalyticsClient} in application\n * code — it manages a shared singleton so there is only ever one flush timer.\n *\n * @param config - Resolved client configuration.\n * @returns A started-on-demand {@link AnalyticsClient}.\n */\nexport const createAnalyticsClient = (\n config: AnalyticsClientConfig\n): AnalyticsClient => {\n const sessionId = getSessionId();\n const sampledIn = isSampledIn(sessionId, config.sampleRate);\n const buffer: EventBuffer = createEventBuffer({ max: config.maxBufferSize });\n const endpoint = `${config.backendURL.replace(/\\/$/, '')}/api/analytics/events`;\n\n let ambientLocale = '';\n let flushTimer: ReturnType<typeof setInterval> | null = null;\n let started = false;\n let detachListeners: (() => void) | null = null;\n\n // Exposure keys already recorded for the current page view. React (and other\n // frameworks) resolve content nodes on every re-render; without this gate a\n // component re-rendering 60×/s would count 60 exposures per second. The set\n // is cleared on each page view so the recorded semantic is \"shown at least\n // once during this page view\".\n let seenExposureKeys = new Set<string>();\n\n const flush = (useBeacon = false): void => {\n const events = buffer.drain();\n\n // Split into bounded chunks so no single request exceeds transport limits.\n for (let start = 0; start < events.length; start += MAX_EVENTS_PER_SEND) {\n sendEvents(\n endpoint,\n {\n clientId: config.clientId,\n sessionId,\n sdkVersion: SDK_VERSION,\n events: events.slice(start, start + MAX_EVENTS_PER_SEND),\n },\n { useBeacon }\n );\n }\n };\n\n /** Pushes an event and triggers an early flush if the buffer is full. */\n const enqueue = (event: AnalyticsEvent): void => {\n const size = buffer.push(event);\n if (size >= config.maxBufferSize) flush();\n };\n\n const setLocale = (locale: string): void => {\n ambientLocale = locale;\n };\n\n const trackPageView: AnalyticsClient['trackPageView'] = (event = {}) => {\n if (!sampledIn) return;\n\n // A new page view starts a fresh exposure window.\n seenExposureKeys = new Set<string>();\n\n enqueue({\n type: 'page_view',\n t: Date.now(),\n url: event.url ?? currentUrl(),\n locale: event.locale ?? ambientLocale,\n ref: event.ref ?? referrerHost(),\n vw:\n event.vw ??\n (typeof window !== 'undefined' ? window.innerWidth : undefined),\n vh:\n event.vh ??\n (typeof window !== 'undefined' ? window.innerHeight : undefined),\n reason: event.reason ?? 'initial',\n });\n };\n\n const trackContentExposure: AnalyticsClient['trackContentExposure'] = (\n event\n ) => {\n if (!sampledIn) return;\n\n const locale = event.locale ?? ambientLocale;\n // Joined with \\x01 (never present in content keys) so parts cannot collide.\n const exposureKey = [\n event.dictionaryKey,\n event.keyPath,\n locale,\n event.experimentKey ?? '',\n event.variant ?? '',\n ].join('\u0001');\n\n // Deduplicate within the current page view (see `seenExposureKeys`).\n if (seenExposureKeys.has(exposureKey)) return;\n seenExposureKeys.add(exposureKey);\n\n enqueue({\n ...event,\n type: 'content_exposure',\n t: Date.now(),\n url: currentUrl(),\n locale,\n });\n };\n\n const trackConversion: AnalyticsClient['trackConversion'] = (event) => {\n // Conversions are never sampled out — they are rare and decisive for A/B.\n enqueue({\n ...event,\n type: 'conversion',\n t: Date.now(),\n url: currentUrl(),\n locale: event.locale ?? ambientLocale,\n });\n // Flush conversions promptly so they are not lost on immediate navigation.\n flush();\n };\n\n const getVariant: AnalyticsClient['getVariant'] = (\n experimentKey,\n variants,\n weights\n ) => assignVariant(sessionId, experimentKey, variants, weights);\n\n /** Attaches lifecycle + SPA-navigation listeners without blocking render. */\n const attachListeners = (): void => {\n if (typeof window === 'undefined') return;\n\n const onHidden = (): void => {\n if (document.visibilityState === 'hidden') flush(true);\n };\n const onPageHide = (): void => flush(true);\n const onPopState = (): void => trackPageView({ reason: 'route_change' });\n\n document.addEventListener('visibilitychange', onHidden);\n window.addEventListener('pagehide', onPageHide, { capture: true });\n window.addEventListener('popstate', onPopState);\n\n // Patch history.pushState so client-side route changes emit a page view.\n // `replaceState` is intentionally left untouched: routers use it for\n // same-page URL sync (scroll, params), which is not a navigation.\n const history = window.history;\n const originalPush = history.pushState;\n\n const patchedPushState = function patchedPush(\n this: History,\n ...args: Parameters<History['pushState']>\n ) {\n const result = originalPush.apply(this, args);\n trackPageView({ reason: 'route_change' });\n return result;\n };\n history.pushState = patchedPushState;\n\n detachListeners = (): void => {\n document.removeEventListener('visibilitychange', onHidden);\n window.removeEventListener('pagehide', onPageHide, { capture: true });\n window.removeEventListener('popstate', onPopState);\n // Only restore if nothing else re-patched pushState after us; restoring\n // blindly would clobber another library's wrapper.\n if (history.pushState === patchedPushState) {\n history.pushState = originalPush;\n }\n };\n };\n\n const start = (): void => {\n if (started) return;\n started = true;\n\n flushTimer = setInterval(flush, config.flushInterval);\n // Some runtimes (Node during SSR) keep the process alive on timers.\n (flushTimer as { unref?: () => void })?.unref?.();\n\n onIdle(attachListeners);\n };\n\n const stop = (): void => {\n if (!started) return;\n started = false;\n\n if (flushTimer) {\n clearInterval(flushTimer);\n flushTimer = null;\n }\n detachListeners?.();\n detachListeners = null;\n flush(true);\n };\n\n return {\n setLocale,\n trackPageView,\n trackContentExposure,\n trackConversion,\n getVariant,\n flush,\n start,\n stop,\n };\n};\n"],"mappings":"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"}
1
+ {"version":3,"file":"AnalyticsClient.mjs","names":[],"sources":["../../../src/core/AnalyticsClient.ts"],"sourcesContent":["import { onIdle } from '../utils/idle';\nimport { assignVariant } from './abTesting';\nimport { createEventBuffer, type EventBuffer } from './eventBuffer';\nimport { isSampledIn } from './sampling';\nimport { getSessionId } from './session';\nimport { sendEvents } from './transport';\nimport type {\n AnalyticsClientConfig,\n AnalyticsEvent,\n ContentExposureEvent,\n ConversionEvent,\n PageViewEvent,\n TrackableEvent,\n} from './types';\n\n/**\n * Caller-supplied fields for a page view. Everything is optional — the client\n * fills `url`, `locale`, viewport, and referrer from the environment when omitted.\n */\nexport type PageViewInput = {\n /** Explicit pathname / screen name (native runtimes have no `location`). */\n url?: string;\n /** Explicit locale; falls back to the client's ambient locale. */\n locale?: string;\n /** Referrer host override. */\n ref?: string;\n /** Viewport width override. */\n vw?: number;\n /** Viewport height override. */\n vh?: number;\n /** Why the view was recorded. */\n reason?: PageViewEvent['reason'];\n};\n\n/** Default flush cadence — one network request per 20 seconds. */\nexport const DEFAULT_FLUSH_INTERVAL = 20_000;\n/** Default cap on distinct buffered events before an early flush. */\nexport const DEFAULT_MAX_BUFFER_SIZE = 500;\n/** Default sampling — keep every session. */\nexport const DEFAULT_SAMPLE_RATE = 1;\n/**\n * Maximum events per network request. `sendBeacon` and `fetch(keepalive)`\n * reject bodies over ~64KB, so large batches are split into multiple sends.\n */\nexport const MAX_EVENTS_PER_SEND = 200;\n/** Identifies the producing SDK in the ingest envelope. */\nconst SDK_VERSION = 'intlayer-analytics/1';\n\n/**\n * The public surface of the analytics client singleton. Framework bindings hold\n * a reference to this and forward provider/node/conversion signals into it.\n */\nexport type AnalyticsClient = {\n /** Sets the ambient locale stamped onto subsequent events. */\n setLocale: (locale: string) => void;\n /** Records a page/locale view (provider level). */\n trackPageView: (event?: PageViewInput) => void;\n /** Records a content exposure (node level). Sampled + deduped per page view. */\n trackContentExposure: (\n event: Omit<TrackableEvent<ContentExposureEvent>, 'type'>\n ) => void;\n /** Records a conversion tied to an experiment variant. */\n trackConversion: (\n event: Omit<TrackableEvent<ConversionEvent>, 'type'>\n ) => void;\n /** Deterministically resolves this session's variant for an experiment. */\n getVariant: (\n experimentKey: string,\n variants: string[],\n weights?: number[]\n ) => string;\n /** Sends the buffered batch now. */\n flush: (useBeacon?: boolean) => void;\n /** Starts the flush loop and lifecycle listeners (idempotent). */\n start: () => void;\n /** Stops timers/listeners and flushes any remaining events. */\n stop: () => void;\n};\n\n/**\n * Reads the current page pathname. Search params are intentionally excluded to\n * avoid capturing anything sensitive.\n */\nconst currentUrl = (): string => {\n if (typeof window === 'undefined' || !window.location) return '';\n return window.location.pathname;\n};\n\n/**\n * Reduces the referrer to its host — never the full URL — for privacy.\n */\nconst referrerHost = (): string | undefined => {\n if (typeof document === 'undefined' || !document.referrer) return undefined;\n try {\n return new URL(document.referrer).host;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Creates an analytics client. Prefer {@link initAnalyticsClient} in application\n * code — it manages a shared singleton so there is only ever one flush timer.\n *\n * @param config - Resolved client configuration.\n * @returns A started-on-demand {@link AnalyticsClient}.\n */\nexport const createAnalyticsClient = (\n config: AnalyticsClientConfig\n): AnalyticsClient => {\n const sessionId = getSessionId();\n const sampledIn = isSampledIn(sessionId, config.sampleRate);\n const buffer: EventBuffer = createEventBuffer({ max: config.maxBufferSize });\n const endpoint = `${config.backendURL.replace(/\\/$/, '')}/api/analytics/events`;\n\n let ambientLocale = '';\n let flushTimer: ReturnType<typeof setInterval> | null = null;\n let started = false;\n let detachListeners: (() => void) | null = null;\n\n // Exposure keys already recorded for the current page view. React (and other\n // frameworks) resolve content nodes on every re-render; without this gate a\n // component re-rendering 60×/s would count 60 exposures per second. The set\n // is cleared on each page view so the recorded semantic is \"shown at least\n // once during this page view\".\n let seenExposureKeys = new Set<string>();\n\n const flush = (useBeacon = false): void => {\n const events = buffer.drain();\n\n // Split into bounded chunks so no single request exceeds transport limits.\n for (let start = 0; start < events.length; start += MAX_EVENTS_PER_SEND) {\n sendEvents(\n endpoint,\n {\n clientId: config.clientId,\n sessionId,\n sdkVersion: SDK_VERSION,\n events: events.slice(start, start + MAX_EVENTS_PER_SEND),\n },\n { useBeacon }\n );\n }\n };\n\n /** Pushes an event and triggers an early flush if the buffer is full. */\n const enqueue = (event: AnalyticsEvent): void => {\n const size = buffer.push(event);\n if (size >= config.maxBufferSize) flush();\n };\n\n const setLocale = (locale: string): void => {\n ambientLocale = locale;\n };\n\n const trackPageView: AnalyticsClient['trackPageView'] = (event = {}) => {\n if (!sampledIn) return;\n\n // A new page view starts a fresh exposure window.\n seenExposureKeys = new Set<string>();\n\n enqueue({\n type: 'page_view',\n t: Date.now(),\n url: event.url ?? currentUrl(),\n locale: event.locale ?? ambientLocale,\n ref: event.ref ?? referrerHost(),\n vw:\n event.vw ??\n (typeof window !== 'undefined' ? window.innerWidth : undefined),\n vh:\n event.vh ??\n (typeof window !== 'undefined' ? window.innerHeight : undefined),\n reason: event.reason ?? 'initial',\n });\n };\n\n const trackContentExposure: AnalyticsClient['trackContentExposure'] = (\n event\n ) => {\n if (!sampledIn) return;\n\n const locale = event.locale ?? ambientLocale;\n // Joined with \\x01 (never present in content keys) so parts cannot collide.\n const exposureKey = [\n event.dictionaryKey,\n event.keyPath,\n locale,\n event.experimentKey ?? '',\n event.variant ?? '',\n ].join('\u0001');\n\n // Deduplicate within the current page view (see `seenExposureKeys`).\n if (seenExposureKeys.has(exposureKey)) return;\n seenExposureKeys.add(exposureKey);\n\n enqueue({\n ...event,\n type: 'content_exposure',\n t: Date.now(),\n url: currentUrl(),\n locale,\n });\n };\n\n const trackConversion: AnalyticsClient['trackConversion'] = (event) => {\n // Conversions are never sampled out — they are rare and decisive for A/B.\n enqueue({\n ...event,\n type: 'conversion',\n t: Date.now(),\n url: currentUrl(),\n locale: event.locale ?? ambientLocale,\n });\n // Flush conversions promptly so they are not lost on immediate navigation.\n flush();\n };\n\n const getVariant: AnalyticsClient['getVariant'] = (\n experimentKey,\n variants,\n weights\n ) => assignVariant(sessionId, experimentKey, variants, weights);\n\n /** Attaches lifecycle + SPA-navigation listeners without blocking render. */\n const attachListeners = (): void => {\n if (typeof window === 'undefined') return;\n\n const onHidden = (): void => {\n if (document.visibilityState === 'hidden') flush(true);\n };\n const onPageHide = (): void => flush(true);\n const onPopState = (): void => trackPageView({ reason: 'route_change' });\n\n document.addEventListener('visibilitychange', onHidden);\n window.addEventListener('pagehide', onPageHide, { capture: true });\n window.addEventListener('popstate', onPopState);\n\n // Patch history.pushState so client-side route changes emit a page view.\n // `replaceState` is intentionally left untouched: routers use it for\n // same-page URL sync (scroll, params), which is not a navigation.\n const history = window.history;\n const originalPush = history.pushState;\n\n const patchedPushState = function patchedPush(\n this: History,\n ...args: Parameters<History['pushState']>\n ) {\n const result = originalPush.apply(this, args);\n trackPageView({ reason: 'route_change' });\n return result;\n };\n history.pushState = patchedPushState;\n\n detachListeners = (): void => {\n document.removeEventListener('visibilitychange', onHidden);\n window.removeEventListener('pagehide', onPageHide, { capture: true });\n window.removeEventListener('popstate', onPopState);\n // Only restore if nothing else re-patched pushState after us; restoring\n // blindly would clobber another library's wrapper.\n if (history.pushState === patchedPushState) {\n history.pushState = originalPush;\n }\n };\n };\n\n const start = (): void => {\n if (started) return;\n started = true;\n\n flushTimer = setInterval(flush, config.flushInterval);\n // Some runtimes (Node during SSR) keep the process alive on timers.\n (flushTimer as { unref?: () => void })?.unref?.();\n\n onIdle(attachListeners);\n };\n\n const stop = (): void => {\n if (!started) return;\n started = false;\n\n if (flushTimer) {\n clearInterval(flushTimer);\n flushTimer = null;\n }\n detachListeners?.();\n detachListeners = null;\n flush(true);\n };\n\n return {\n setLocale,\n trackPageView,\n trackContentExposure,\n trackConversion,\n getVariant,\n flush,\n start,\n stop,\n };\n};\n"],"mappings":"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"}
@@ -1 +1 @@
1
- {"version":3,"file":"abTesting.mjs","names":[],"sources":["../../../src/core/abTesting.ts"],"sourcesContent":["import { hashString } from '../utils/hash';\n\n/**\n * Deterministically assigns a variant to a session for a given experiment.\n *\n * The assignment is a pure function of `sessionId` + `experimentKey`, so it is\n * stable for the whole session and requires **no** server round-trip before the\n * first render — avoiding layout shift / content flicker. Optional `weights`\n * bias the split (e.g. `[0.9, 0.1]` for a 90/10 rollout).\n *\n * @param sessionId - The current anonymous session id.\n * @param experimentKey - Unique key identifying the experiment.\n * @param variants - The candidate variant names (at least one).\n * @param weights - Optional relative weights, one per variant.\n * @returns The variant assigned to this session.\n *\n * @example\n * assignVariant('sid-1', 'homepage-hero', ['a', 'b']); // stable 'a' | 'b'\n * assignVariant('sid-1', 'homepage-hero', ['a', 'b'], [9, 1]); // ~90% 'a'\n */\nexport const assignVariant = (\n sessionId: string,\n experimentKey: string,\n variants: string[],\n weights?: number[]\n): string => {\n if (variants.length === 0) {\n throw new Error('assignVariant requires at least one variant');\n }\n if (variants.length === 1) return variants[0]!;\n\n // Uniform bucket in [0, 1) derived from the session + experiment.\n const bucket = hashString(`${sessionId}:${experimentKey}`) / 0x100000000;\n\n if (!weights || weights.length !== variants.length) {\n const index = Math.floor(bucket * variants.length);\n return variants[Math.min(index, variants.length - 1)];\n }\n\n const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);\n if (totalWeight <= 0) {\n return variants[Math.floor(bucket * variants.length)];\n }\n\n let cumulative = 0;\n const target = bucket * totalWeight;\n for (let index = 0; index < variants.length; index++) {\n cumulative += weights[index];\n if (target < cumulative) return variants[index];\n }\n\n return variants[variants.length - 1];\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoBA,MAAa,iBACX,WACA,eACA,UACA,YACW;AACX,KAAI,SAAS,WAAW,EACtB,OAAM,IAAI,MAAM,8CAA8C;AAEhE,KAAI,SAAS,WAAW,EAAG,QAAO,SAAS;CAG3C,MAAM,SAAS,WAAW,GAAG,UAAU,GAAG,gBAAgB,GAAG;AAE7D,KAAI,CAAC,WAAW,QAAQ,WAAW,SAAS,QAAQ;EAClD,MAAM,QAAQ,KAAK,MAAM,SAAS,SAAS,OAAO;AAClD,SAAO,SAAS,KAAK,IAAI,OAAO,SAAS,SAAS,EAAE;;CAGtD,MAAM,cAAc,QAAQ,QAAQ,KAAK,WAAW,MAAM,QAAQ,EAAE;AACpE,KAAI,eAAe,EACjB,QAAO,SAAS,KAAK,MAAM,SAAS,SAAS,OAAO;CAGtD,IAAI,aAAa;CACjB,MAAM,SAAS,SAAS;AACxB,MAAK,IAAI,QAAQ,GAAG,QAAQ,SAAS,QAAQ,SAAS;AACpD,gBAAc,QAAQ;AACtB,MAAI,SAAS,WAAY,QAAO,SAAS;;AAG3C,QAAO,SAAS,SAAS,SAAS"}
1
+ {"version":3,"file":"abTesting.mjs","names":[],"sources":["../../../src/core/abTesting.ts"],"sourcesContent":["import { hashString } from '../utils/hash';\n\n/**\n * Deterministically assigns a variant to a session for a given experiment.\n *\n * The assignment is a pure function of `sessionId` + `experimentKey`, so it is\n * stable for the whole session and requires **no** server round-trip before the\n * first render — avoiding layout shift / content flicker. Optional `weights`\n * bias the split (e.g. `[0.9, 0.1]` for a 90/10 rollout).\n *\n * @param sessionId - The current anonymous session id.\n * @param experimentKey - Unique key identifying the experiment.\n * @param variants - The candidate variant names (at least one).\n * @param weights - Optional relative weights, one per variant.\n * @returns The variant assigned to this session.\n *\n * @example\n * assignVariant('sid-1', 'homepage-hero', ['a', 'b']); // stable 'a' | 'b'\n * assignVariant('sid-1', 'homepage-hero', ['a', 'b'], [9, 1]); // ~90% 'a'\n */\nexport const assignVariant = (\n sessionId: string,\n experimentKey: string,\n variants: string[],\n weights?: number[]\n): string => {\n if (variants.length === 0) {\n throw new Error('assignVariant requires at least one variant');\n }\n if (variants.length === 1) return variants[0]!;\n\n // Uniform bucket in [0, 1) derived from the session + experiment.\n const bucket = hashString(`${sessionId}:${experimentKey}`) / 0x100000000;\n\n if (!weights || weights.length !== variants.length) {\n const index = Math.floor(bucket * variants.length);\n return variants[Math.min(index, variants.length - 1)];\n }\n\n const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);\n if (totalWeight <= 0) {\n return variants[Math.floor(bucket * variants.length)];\n }\n\n let cumulative = 0;\n const target = bucket * totalWeight;\n for (let index = 0; index < variants.length; index++) {\n cumulative += weights[index];\n if (target < cumulative) return variants[index];\n }\n\n return variants[variants.length - 1];\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoBA,MAAa,iBACX,WACA,eACA,UACA,YACW;CACX,IAAI,SAAS,WAAW,GACtB,MAAM,IAAI,MAAM,6CAA6C;CAE/D,IAAI,SAAS,WAAW,GAAG,OAAO,SAAS;CAG3C,MAAM,SAAS,WAAW,GAAG,UAAU,GAAG,eAAe,IAAI;CAE7D,IAAI,CAAC,WAAW,QAAQ,WAAW,SAAS,QAAQ;EAClD,MAAM,QAAQ,KAAK,MAAM,SAAS,SAAS,MAAM;EACjD,OAAO,SAAS,KAAK,IAAI,OAAO,SAAS,SAAS,CAAC;CACrD;CAEA,MAAM,cAAc,QAAQ,QAAQ,KAAK,WAAW,MAAM,QAAQ,CAAC;CACnE,IAAI,eAAe,GACjB,OAAO,SAAS,KAAK,MAAM,SAAS,SAAS,MAAM;CAGrD,IAAI,aAAa;CACjB,MAAM,SAAS,SAAS;CACxB,KAAK,IAAI,QAAQ,GAAG,QAAQ,SAAS,QAAQ,SAAS;EACpD,cAAc,QAAQ;EACtB,IAAI,SAAS,YAAY,OAAO,SAAS;CAC3C;CAEA,OAAO,SAAS,SAAS,SAAS;AACpC"}
@@ -1 +1 @@
1
- {"version":3,"file":"eventBuffer.mjs","names":[],"sources":["../../../src/core/eventBuffer.ts"],"sourcesContent":["import type { AnalyticsEvent, ContentExposureEvent } from './types';\n\n/** Field separator for coalescing keys — never present in content keys. */\nconst KEY_SEPARATOR = '\u0001';\n\n/**\n * Builds the coalescing key for a content-exposure event. Two exposures of the\n * same node, page, locale, experiment, and variant collapse into one event with\n * an incremented `count`.\n */\nconst exposureKey = (event: ContentExposureEvent): string =>\n [\n event.url,\n event.dictionaryKey,\n event.keyPath,\n event.locale,\n event.experimentKey ?? '',\n event.variant ?? '',\n ].join(KEY_SEPARATOR);\n\n/**\n * A bounded, coalescing in-memory buffer for analytics events.\n *\n * - `page_view` and `conversion` events are appended verbatim (they are rare\n * and valuable — they are never evicted while exposures remain).\n * - `content_exposure` events are deduplicated by page/node/locale/variant with\n * a running `count`, keeping the highest-volume signal cheap.\n * - When the total number of stored events exceeds `max`, the **oldest\n * exposures** are evicted first (analytics is lossy by design; exposures are\n * the expendable signal). Discrete events are only dropped once no exposures\n * remain.\n */\nexport type EventBuffer = {\n /** Adds an event, coalescing content exposures. Returns the current size. */\n push: (event: AnalyticsEvent) => number;\n /** Removes and returns every buffered event. */\n drain: () => AnalyticsEvent[];\n /** Current number of distinct buffered events. */\n size: () => number;\n};\n\n/**\n * Creates an {@link EventBuffer}.\n *\n * @param options - Buffer options.\n * @param options.max - Maximum number of distinct events to retain.\n * @returns A new buffer instance.\n */\nexport const createEventBuffer = ({ max }: { max: number }): EventBuffer => {\n // Insertion-ordered list of non-coalesced events (page views, conversions).\n let discreteEvents: AnalyticsEvent[] = [];\n // Coalesced content exposures keyed by page/node/locale/variant.\n const exposures = new Map<string, ContentExposureEvent>();\n\n const size = (): number => discreteEvents.length + exposures.size;\n\n /** Evicts oldest exposures first, then oldest discrete events. */\n const enforceCap = (): void => {\n while (size() > max && exposures.size > 0) {\n // Map iteration follows insertion order — the first key is the oldest.\n const oldestKey = exposures.keys().next().value as string;\n exposures.delete(oldestKey);\n }\n if (size() > max) {\n discreteEvents = discreteEvents.slice(size() - max);\n }\n };\n\n const push = (event: AnalyticsEvent): number => {\n if (event.type === 'content_exposure') {\n const key = exposureKey(event);\n const existing = exposures.get(key);\n\n if (existing) {\n existing.count = (existing.count ?? 1) + (event.count ?? 1);\n existing.t = event.t; // keep the most recent timestamp\n } else {\n exposures.set(key, { ...event, count: event.count ?? 1 });\n }\n } else {\n discreteEvents.push(event);\n }\n\n enforceCap();\n\n return size();\n };\n\n const drain = (): AnalyticsEvent[] => {\n const drained: AnalyticsEvent[] = [\n ...discreteEvents,\n ...exposures.values(),\n ];\n discreteEvents = [];\n exposures.clear();\n return drained;\n };\n\n return { push, drain, size };\n};\n"],"mappings":";;AAGA,MAAM,gBAAgB;;;;;;AAOtB,MAAM,eAAe,UACnB;CACE,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM,iBAAiB;CACvB,MAAM,WAAW;CAClB,CAAC,KAAK,cAAc;;;;;;;;AA8BvB,MAAa,qBAAqB,EAAE,UAAwC;CAE1E,IAAI,iBAAmC,EAAE;CAEzC,MAAM,4BAAY,IAAI,KAAmC;CAEzD,MAAM,aAAqB,eAAe,SAAS,UAAU;;CAG7D,MAAM,mBAAyB;AAC7B,SAAO,MAAM,GAAG,OAAO,UAAU,OAAO,GAAG;GAEzC,MAAM,YAAY,UAAU,MAAM,CAAC,MAAM,CAAC;AAC1C,aAAU,OAAO,UAAU;;AAE7B,MAAI,MAAM,GAAG,IACX,kBAAiB,eAAe,MAAM,MAAM,GAAG,IAAI;;CAIvD,MAAM,QAAQ,UAAkC;AAC9C,MAAI,MAAM,SAAS,oBAAoB;GACrC,MAAM,MAAM,YAAY,MAAM;GAC9B,MAAM,WAAW,UAAU,IAAI,IAAI;AAEnC,OAAI,UAAU;AACZ,aAAS,SAAS,SAAS,SAAS,MAAM,MAAM,SAAS;AACzD,aAAS,IAAI,MAAM;SAEnB,WAAU,IAAI,KAAK;IAAE,GAAG;IAAO,OAAO,MAAM,SAAS;IAAG,CAAC;QAG3D,gBAAe,KAAK,MAAM;AAG5B,cAAY;AAEZ,SAAO,MAAM;;CAGf,MAAM,cAAgC;EACpC,MAAM,UAA4B,CAChC,GAAG,gBACH,GAAG,UAAU,QAAQ,CACtB;AACD,mBAAiB,EAAE;AACnB,YAAU,OAAO;AACjB,SAAO;;AAGT,QAAO;EAAE;EAAM;EAAO;EAAM"}
1
+ {"version":3,"file":"eventBuffer.mjs","names":[],"sources":["../../../src/core/eventBuffer.ts"],"sourcesContent":["import type { AnalyticsEvent, ContentExposureEvent } from './types';\n\n/** Field separator for coalescing keys — never present in content keys. */\nconst KEY_SEPARATOR = '\u0001';\n\n/**\n * Builds the coalescing key for a content-exposure event. Two exposures of the\n * same node, page, locale, experiment, and variant collapse into one event with\n * an incremented `count`.\n */\nconst exposureKey = (event: ContentExposureEvent): string =>\n [\n event.url,\n event.dictionaryKey,\n event.keyPath,\n event.locale,\n event.experimentKey ?? '',\n event.variant ?? '',\n ].join(KEY_SEPARATOR);\n\n/**\n * A bounded, coalescing in-memory buffer for analytics events.\n *\n * - `page_view` and `conversion` events are appended verbatim (they are rare\n * and valuable — they are never evicted while exposures remain).\n * - `content_exposure` events are deduplicated by page/node/locale/variant with\n * a running `count`, keeping the highest-volume signal cheap.\n * - When the total number of stored events exceeds `max`, the **oldest\n * exposures** are evicted first (analytics is lossy by design; exposures are\n * the expendable signal). Discrete events are only dropped once no exposures\n * remain.\n */\nexport type EventBuffer = {\n /** Adds an event, coalescing content exposures. Returns the current size. */\n push: (event: AnalyticsEvent) => number;\n /** Removes and returns every buffered event. */\n drain: () => AnalyticsEvent[];\n /** Current number of distinct buffered events. */\n size: () => number;\n};\n\n/**\n * Creates an {@link EventBuffer}.\n *\n * @param options - Buffer options.\n * @param options.max - Maximum number of distinct events to retain.\n * @returns A new buffer instance.\n */\nexport const createEventBuffer = ({ max }: { max: number }): EventBuffer => {\n // Insertion-ordered list of non-coalesced events (page views, conversions).\n let discreteEvents: AnalyticsEvent[] = [];\n // Coalesced content exposures keyed by page/node/locale/variant.\n const exposures = new Map<string, ContentExposureEvent>();\n\n const size = (): number => discreteEvents.length + exposures.size;\n\n /** Evicts oldest exposures first, then oldest discrete events. */\n const enforceCap = (): void => {\n while (size() > max && exposures.size > 0) {\n // Map iteration follows insertion order — the first key is the oldest.\n const oldestKey = exposures.keys().next().value as string;\n exposures.delete(oldestKey);\n }\n if (size() > max) {\n discreteEvents = discreteEvents.slice(size() - max);\n }\n };\n\n const push = (event: AnalyticsEvent): number => {\n if (event.type === 'content_exposure') {\n const key = exposureKey(event);\n const existing = exposures.get(key);\n\n if (existing) {\n existing.count = (existing.count ?? 1) + (event.count ?? 1);\n existing.t = event.t; // keep the most recent timestamp\n } else {\n exposures.set(key, { ...event, count: event.count ?? 1 });\n }\n } else {\n discreteEvents.push(event);\n }\n\n enforceCap();\n\n return size();\n };\n\n const drain = (): AnalyticsEvent[] => {\n const drained: AnalyticsEvent[] = [\n ...discreteEvents,\n ...exposures.values(),\n ];\n discreteEvents = [];\n exposures.clear();\n return drained;\n };\n\n return { push, drain, size };\n};\n"],"mappings":";;AAGA,MAAM,gBAAgB;;;;;;AAOtB,MAAM,eAAe,UACnB;CACE,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM,iBAAiB;CACvB,MAAM,WAAW;AACnB,CAAC,CAAC,KAAK,aAAa;;;;;;;;AA8BtB,MAAa,qBAAqB,EAAE,UAAwC;CAE1E,IAAI,iBAAmC,CAAC;CAExC,MAAM,4BAAY,IAAI,IAAkC;CAExD,MAAM,aAAqB,eAAe,SAAS,UAAU;;CAG7D,MAAM,mBAAyB;EAC7B,OAAO,KAAK,IAAI,OAAO,UAAU,OAAO,GAAG;GAEzC,MAAM,YAAY,UAAU,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;GAC1C,UAAU,OAAO,SAAS;EAC5B;EACA,IAAI,KAAK,IAAI,KACX,iBAAiB,eAAe,MAAM,KAAK,IAAI,GAAG;CAEtD;CAEA,MAAM,QAAQ,UAAkC;EAC9C,IAAI,MAAM,SAAS,oBAAoB;GACrC,MAAM,MAAM,YAAY,KAAK;GAC7B,MAAM,WAAW,UAAU,IAAI,GAAG;GAElC,IAAI,UAAU;IACZ,SAAS,SAAS,SAAS,SAAS,MAAM,MAAM,SAAS;IACzD,SAAS,IAAI,MAAM;GACrB,OACE,UAAU,IAAI,KAAK;IAAE,GAAG;IAAO,OAAO,MAAM,SAAS;GAAE,CAAC;EAE5D,OACE,eAAe,KAAK,KAAK;EAG3B,WAAW;EAEX,OAAO,KAAK;CACd;CAEA,MAAM,cAAgC;EACpC,MAAM,UAA4B,CAChC,GAAG,gBACH,GAAG,UAAU,OAAO,CACtB;EACA,iBAAiB,CAAC;EAClB,UAAU,MAAM;EAChB,OAAO;CACT;CAEA,OAAO;EAAE;EAAM;EAAO;CAAK;AAC7B"}
@@ -1 +1 @@
1
- {"version":3,"file":"globalManager.mjs","names":[],"sources":["../../../src/core/globalManager.ts"],"sourcesContent":["import type { AnalyticsClient } from './AnalyticsClient';\n\n/**\n * Key on `window` used to share the client singleton across multiple module\n * instances. When bundlers include `@intlayer/analytics` more than once (e.g.\n * a framework package plus the app), each copy has its own module-level\n * variables; storing the client on `window` ensures they all share one buffer\n * and one flush timer.\n */\nconst CLIENT_KEY = '__intlayer_analytics_client__';\n\n/**\n * Key on `window` holding the provider reference count. It lives next to the\n * client (rather than in module scope) for the same reason the client does:\n * duplicated module instances must share one count, otherwise one copy's\n * `stopAnalyticsClient` could stop a client another copy still uses.\n */\nconst REF_COUNT_KEY = '__intlayer_analytics_ref_count__';\n\ntype WindowWithAnalyticsGlobals = typeof window & {\n [CLIENT_KEY]?: AnalyticsClient | null;\n [REF_COUNT_KEY]?: number;\n};\n\n/**\n * Returns the global analytics client, or `null` in SSR or before init.\n */\nexport const getGlobalAnalyticsClient = (): AnalyticsClient | null => {\n if (typeof window === 'undefined') return null;\n return (window as WindowWithAnalyticsGlobals)[CLIENT_KEY] ?? null;\n};\n\n/**\n * Sets (or clears) the global analytics client singleton.\n *\n * @param client - The client to store globally, or `null` to clear it.\n */\nexport const setGlobalAnalyticsClient = (\n client: AnalyticsClient | null\n): void => {\n if (typeof window === 'undefined') return;\n (window as WindowWithAnalyticsGlobals)[CLIENT_KEY] = client;\n};\n\n/**\n * Increments the shared provider reference count.\n *\n * @returns The count after incrementing (`0` in SSR, where nothing is stored).\n */\nexport const incrementAnalyticsClientRefCount = (): number => {\n if (typeof window === 'undefined') return 0;\n const globals = window as WindowWithAnalyticsGlobals;\n globals[REF_COUNT_KEY] = (globals[REF_COUNT_KEY] ?? 0) + 1;\n return globals[REF_COUNT_KEY];\n};\n\n/**\n * Decrements the shared provider reference count, clamping at zero.\n *\n * @returns The count after decrementing (`0` in SSR, where nothing is stored).\n */\nexport const decrementAnalyticsClientRefCount = (): number => {\n if (typeof window === 'undefined') return 0;\n const globals = window as WindowWithAnalyticsGlobals;\n globals[REF_COUNT_KEY] = Math.max(0, (globals[REF_COUNT_KEY] ?? 0) - 1);\n return globals[REF_COUNT_KEY];\n};\n"],"mappings":";;;;;;;;AASA,MAAM,aAAa;;;;;;;AAQnB,MAAM,gBAAgB;;;;AAUtB,MAAa,iCAAyD;AACpE,KAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,QAAQ,OAAsC,eAAe;;;;;;;AAQ/D,MAAa,4BACX,WACS;AACT,KAAI,OAAO,WAAW,YAAa;AACnC,CAAC,OAAsC,cAAc;;;;;;;AAQvD,MAAa,yCAAiD;AAC5D,KAAI,OAAO,WAAW,YAAa,QAAO;CAC1C,MAAM,UAAU;AAChB,SAAQ,kBAAkB,QAAQ,kBAAkB,KAAK;AACzD,QAAO,QAAQ;;;;;;;AAQjB,MAAa,yCAAiD;AAC5D,KAAI,OAAO,WAAW,YAAa,QAAO;CAC1C,MAAM,UAAU;AAChB,SAAQ,iBAAiB,KAAK,IAAI,IAAI,QAAQ,kBAAkB,KAAK,EAAE;AACvE,QAAO,QAAQ"}
1
+ {"version":3,"file":"globalManager.mjs","names":[],"sources":["../../../src/core/globalManager.ts"],"sourcesContent":["import type { AnalyticsClient } from './AnalyticsClient';\n\n/**\n * Key on `window` used to share the client singleton across multiple module\n * instances. When bundlers include `@intlayer/analytics` more than once (e.g.\n * a framework package plus the app), each copy has its own module-level\n * variables; storing the client on `window` ensures they all share one buffer\n * and one flush timer.\n */\nconst CLIENT_KEY = '__intlayer_analytics_client__';\n\n/**\n * Key on `window` holding the provider reference count. It lives next to the\n * client (rather than in module scope) for the same reason the client does:\n * duplicated module instances must share one count, otherwise one copy's\n * `stopAnalyticsClient` could stop a client another copy still uses.\n */\nconst REF_COUNT_KEY = '__intlayer_analytics_ref_count__';\n\ntype WindowWithAnalyticsGlobals = typeof window & {\n [CLIENT_KEY]?: AnalyticsClient | null;\n [REF_COUNT_KEY]?: number;\n};\n\n/**\n * Returns the global analytics client, or `null` in SSR or before init.\n */\nexport const getGlobalAnalyticsClient = (): AnalyticsClient | null => {\n if (typeof window === 'undefined') return null;\n return (window as WindowWithAnalyticsGlobals)[CLIENT_KEY] ?? null;\n};\n\n/**\n * Sets (or clears) the global analytics client singleton.\n *\n * @param client - The client to store globally, or `null` to clear it.\n */\nexport const setGlobalAnalyticsClient = (\n client: AnalyticsClient | null\n): void => {\n if (typeof window === 'undefined') return;\n (window as WindowWithAnalyticsGlobals)[CLIENT_KEY] = client;\n};\n\n/**\n * Increments the shared provider reference count.\n *\n * @returns The count after incrementing (`0` in SSR, where nothing is stored).\n */\nexport const incrementAnalyticsClientRefCount = (): number => {\n if (typeof window === 'undefined') return 0;\n const globals = window as WindowWithAnalyticsGlobals;\n globals[REF_COUNT_KEY] = (globals[REF_COUNT_KEY] ?? 0) + 1;\n return globals[REF_COUNT_KEY];\n};\n\n/**\n * Decrements the shared provider reference count, clamping at zero.\n *\n * @returns The count after decrementing (`0` in SSR, where nothing is stored).\n */\nexport const decrementAnalyticsClientRefCount = (): number => {\n if (typeof window === 'undefined') return 0;\n const globals = window as WindowWithAnalyticsGlobals;\n globals[REF_COUNT_KEY] = Math.max(0, (globals[REF_COUNT_KEY] ?? 0) - 1);\n return globals[REF_COUNT_KEY];\n};\n"],"mappings":";;;;;;;;AASA,MAAM,aAAa;;;;;;;AAQnB,MAAM,gBAAgB;;;;AAUtB,MAAa,iCAAyD;CACpE,IAAI,OAAO,WAAW,aAAa,OAAO;CAC1C,OAAQ,OAAsC,eAAe;AAC/D;;;;;;AAOA,MAAa,4BACX,WACS;CACT,IAAI,OAAO,WAAW,aAAa;CACnC,AAAC,OAAsC,cAAc;AACvD;;;;;;AAOA,MAAa,yCAAiD;CAC5D,IAAI,OAAO,WAAW,aAAa,OAAO;CAC1C,MAAM,UAAU;CAChB,QAAQ,kBAAkB,QAAQ,kBAAkB,KAAK;CACzD,OAAO,QAAQ;AACjB;;;;;;AAOA,MAAa,yCAAiD;CAC5D,IAAI,OAAO,WAAW,aAAa,OAAO;CAC1C,MAAM,UAAU;CAChB,QAAQ,iBAAiB,KAAK,IAAI,IAAI,QAAQ,kBAAkB,KAAK,CAAC;CACtE,OAAO,QAAQ;AACjB"}
@@ -1 +1 @@
1
- {"version":3,"file":"initAnalyticsClient.mjs","names":[],"sources":["../../../src/core/initAnalyticsClient.ts"],"sourcesContent":["import { analytics, editor } from '@intlayer/config/built';\nimport {\n type AnalyticsClient,\n createAnalyticsClient,\n DEFAULT_FLUSH_INTERVAL,\n DEFAULT_MAX_BUFFER_SIZE,\n DEFAULT_SAMPLE_RATE,\n} from './AnalyticsClient';\nimport {\n decrementAnalyticsClientRefCount,\n getGlobalAnalyticsClient,\n incrementAnalyticsClientRefCount,\n setGlobalAnalyticsClient,\n} from './globalManager';\n\n/**\n * Initializes the Intlayer analytics client singleton.\n *\n * Behavior comes from the `analytics` config block (`flushInterval`,\n * `sampleRate`); attribution reuses the existing `editor` config\n * (`editor.backendURL` for the endpoint, `editor.clientId` for the project).\n *\n * Safe to call multiple times: returns the existing client and increments a\n * `window`-shared reference count so nested providers (or duplicated module\n * instances) don't stop the client prematurely.\n *\n * @returns The started analytics client singleton.\n */\nexport const initAnalyticsClient = (): AnalyticsClient => {\n incrementAnalyticsClientRefCount();\n\n const existing = getGlobalAnalyticsClient();\n if (existing) return existing;\n\n const client = createAnalyticsClient({\n backendURL: editor?.backendURL ?? '',\n clientId: editor?.clientId,\n flushInterval: analytics?.flushInterval ?? DEFAULT_FLUSH_INTERVAL,\n maxBufferSize: DEFAULT_MAX_BUFFER_SIZE,\n sampleRate: analytics?.sampleRate ?? DEFAULT_SAMPLE_RATE,\n });\n\n setGlobalAnalyticsClient(client);\n client.start();\n\n return client;\n};\n\n/**\n * Decrements the shared reference count and stops the global analytics client\n * only when the last provider unmounts (flushing any remaining events).\n *\n * Callers must pair each `stopAnalyticsClient` with a prior\n * `initAnalyticsClient` — never call it when init was skipped or cancelled.\n */\nexport const stopAnalyticsClient = (): void => {\n if (decrementAnalyticsClientRefCount() > 0) return;\n\n const client = getGlobalAnalyticsClient();\n client?.stop();\n setGlobalAnalyticsClient(null);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4BA,MAAa,4BAA6C;AACxD,mCAAkC;CAElC,MAAM,WAAW,0BAA0B;AAC3C,KAAI,SAAU,QAAO;CAErB,MAAM,SAAS,sBAAsB;EACnC,YAAY,QAAQ,cAAc;EAClC,UAAU,QAAQ;EAClB,eAAe,WAAW;EAC1B;EACA,YAAY,WAAW;EACxB,CAAC;AAEF,0BAAyB,OAAO;AAChC,QAAO,OAAO;AAEd,QAAO;;;;;;;;;AAUT,MAAa,4BAAkC;AAC7C,KAAI,kCAAkC,GAAG,EAAG;AAG5C,CADe,0BACT,EAAE,MAAM;AACd,0BAAyB,KAAK"}
1
+ {"version":3,"file":"initAnalyticsClient.mjs","names":[],"sources":["../../../src/core/initAnalyticsClient.ts"],"sourcesContent":["import { analytics, editor } from '@intlayer/config/built';\nimport {\n type AnalyticsClient,\n createAnalyticsClient,\n DEFAULT_FLUSH_INTERVAL,\n DEFAULT_MAX_BUFFER_SIZE,\n DEFAULT_SAMPLE_RATE,\n} from './AnalyticsClient';\nimport {\n decrementAnalyticsClientRefCount,\n getGlobalAnalyticsClient,\n incrementAnalyticsClientRefCount,\n setGlobalAnalyticsClient,\n} from './globalManager';\n\n/**\n * Initializes the Intlayer analytics client singleton.\n *\n * Behavior comes from the `analytics` config block (`flushInterval`,\n * `sampleRate`); attribution reuses the existing `editor` config\n * (`editor.backendURL` for the endpoint, `editor.clientId` for the project).\n *\n * Safe to call multiple times: returns the existing client and increments a\n * `window`-shared reference count so nested providers (or duplicated module\n * instances) don't stop the client prematurely.\n *\n * @returns The started analytics client singleton.\n */\nexport const initAnalyticsClient = (): AnalyticsClient => {\n incrementAnalyticsClientRefCount();\n\n const existing = getGlobalAnalyticsClient();\n if (existing) return existing;\n\n const client = createAnalyticsClient({\n backendURL: editor?.backendURL ?? '',\n clientId: editor?.clientId,\n flushInterval: analytics?.flushInterval ?? DEFAULT_FLUSH_INTERVAL,\n maxBufferSize: DEFAULT_MAX_BUFFER_SIZE,\n sampleRate: analytics?.sampleRate ?? DEFAULT_SAMPLE_RATE,\n });\n\n setGlobalAnalyticsClient(client);\n client.start();\n\n return client;\n};\n\n/**\n * Decrements the shared reference count and stops the global analytics client\n * only when the last provider unmounts (flushing any remaining events).\n *\n * Callers must pair each `stopAnalyticsClient` with a prior\n * `initAnalyticsClient` — never call it when init was skipped or cancelled.\n */\nexport const stopAnalyticsClient = (): void => {\n if (decrementAnalyticsClientRefCount() > 0) return;\n\n const client = getGlobalAnalyticsClient();\n client?.stop();\n setGlobalAnalyticsClient(null);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4BA,MAAa,4BAA6C;CACxD,iCAAiC;CAEjC,MAAM,WAAW,yBAAyB;CAC1C,IAAI,UAAU,OAAO;CAErB,MAAM,SAAS,sBAAsB;EACnC,YAAY,QAAQ,cAAc;EAClC,UAAU,QAAQ;EAClB,eAAe,WAAW;EAC1B;EACA,YAAY,WAAW;CACzB,CAAC;CAED,yBAAyB,MAAM;CAC/B,OAAO,MAAM;CAEb,OAAO;AACT;;;;;;;;AASA,MAAa,4BAAkC;CAC7C,IAAI,iCAAiC,IAAI,GAAG;CAG5C,AADe,yBACV,CAAC,EAAE,KAAK;CACb,yBAAyB,IAAI;AAC/B"}
@@ -1 +1 @@
1
- {"version":3,"file":"sampling.mjs","names":[],"sources":["../../../src/core/sampling.ts"],"sourcesContent":["import { hashString } from '../utils/hash';\n\n/**\n * Deterministic per-session sampling gate. Using the session id (rather than a\n * fresh random draw per event) means a sampled-in session reports *all* of its\n * content exposures, keeping per-session funnels consistent instead of leaving\n * holes.\n *\n * @param sessionId - The current anonymous session id.\n * @param sampleRate - Fraction of sessions to keep, from 0 (none) to 1 (all).\n * @returns `true` when this session's events should be recorded.\n *\n * @example\n * isSampledIn('abc', 1); // always true\n * isSampledIn('abc', 0); // always false\n * isSampledIn('abc', 0.5); // stable per session\n */\nexport const isSampledIn = (sessionId: string, sampleRate: number): boolean => {\n if (sampleRate >= 1) return true;\n if (sampleRate <= 0) return false;\n\n const bucket = hashString(sessionId) / 0xffffffff;\n return bucket < sampleRate;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,MAAa,eAAe,WAAmB,eAAgC;AAC7E,KAAI,cAAc,EAAG,QAAO;AAC5B,KAAI,cAAc,EAAG,QAAO;AAG5B,QADe,WAAW,UAAU,GAAG,aACvB"}
1
+ {"version":3,"file":"sampling.mjs","names":[],"sources":["../../../src/core/sampling.ts"],"sourcesContent":["import { hashString } from '../utils/hash';\n\n/**\n * Deterministic per-session sampling gate. Using the session id (rather than a\n * fresh random draw per event) means a sampled-in session reports *all* of its\n * content exposures, keeping per-session funnels consistent instead of leaving\n * holes.\n *\n * @param sessionId - The current anonymous session id.\n * @param sampleRate - Fraction of sessions to keep, from 0 (none) to 1 (all).\n * @returns `true` when this session's events should be recorded.\n *\n * @example\n * isSampledIn('abc', 1); // always true\n * isSampledIn('abc', 0); // always false\n * isSampledIn('abc', 0.5); // stable per session\n */\nexport const isSampledIn = (sessionId: string, sampleRate: number): boolean => {\n if (sampleRate >= 1) return true;\n if (sampleRate <= 0) return false;\n\n const bucket = hashString(sessionId) / 0xffffffff;\n return bucket < sampleRate;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,MAAa,eAAe,WAAmB,eAAgC;CAC7E,IAAI,cAAc,GAAG,OAAO;CAC5B,IAAI,cAAc,GAAG,OAAO;CAG5B,OADe,WAAW,SAAS,IAAI,aACvB;AAClB"}
@@ -1 +1 @@
1
- {"version":3,"file":"session.mjs","names":[],"sources":["../../../src/core/session.ts"],"sourcesContent":["/**\n * Anonymous, per-tab session identity. Stored in `sessionStorage` so it is\n * cleared when the tab closes and is never shared across sites — no durable\n * cookie, no cross-site tracking, no PII.\n */\n\nconst SESSION_STORAGE_KEY = '__intlayer_analytics_sid__';\n\n/**\n * Generates a random, opaque session identifier.\n *\n * @returns A URL-safe random string.\n */\nconst generateSessionId = (): string => {\n const cryptoObj =\n typeof globalThis !== 'undefined'\n ? (globalThis.crypto as Crypto | undefined)\n : undefined;\n\n if (cryptoObj?.randomUUID) {\n return cryptoObj.randomUUID();\n }\n\n // Fallback for environments without crypto.randomUUID (older RN/Lynx)\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n};\n\n/**\n * Returns the current session id, creating and persisting one on first access.\n * Degrades gracefully to an in-memory id when `sessionStorage` is unavailable\n * (private mode, native runtimes).\n *\n * @returns The stable session id for the lifetime of the tab.\n */\nexport const getSessionId = (): string => {\n if (typeof window === 'undefined' || !window.sessionStorage) {\n return generateSessionId();\n }\n\n try {\n const existing = window.sessionStorage.getItem(SESSION_STORAGE_KEY);\n if (existing) return existing;\n\n const created = generateSessionId();\n window.sessionStorage.setItem(SESSION_STORAGE_KEY, created);\n return created;\n } catch {\n // sessionStorage can throw (Safari private mode, quota) — never break the app\n return generateSessionId();\n }\n};\n"],"mappings":";;;;;;AAMA,MAAM,sBAAsB;;;;;;AAO5B,MAAM,0BAAkC;CACtC,MAAM,YACJ,OAAO,eAAe,cACjB,WAAW,SACZ;AAEN,KAAI,WAAW,WACb,QAAO,UAAU,YAAY;AAI/B,QAAO,GAAG,KAAK,KAAK,CAAC,SAAS,GAAG,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,GAAG,GAAG;;;;;;;;;AAU9E,MAAa,qBAA6B;AACxC,KAAI,OAAO,WAAW,eAAe,CAAC,OAAO,eAC3C,QAAO,mBAAmB;AAG5B,KAAI;EACF,MAAM,WAAW,OAAO,eAAe,QAAQ,oBAAoB;AACnE,MAAI,SAAU,QAAO;EAErB,MAAM,UAAU,mBAAmB;AACnC,SAAO,eAAe,QAAQ,qBAAqB,QAAQ;AAC3D,SAAO;SACD;AAEN,SAAO,mBAAmB"}
1
+ {"version":3,"file":"session.mjs","names":[],"sources":["../../../src/core/session.ts"],"sourcesContent":["/**\n * Anonymous, per-tab session identity. Stored in `sessionStorage` so it is\n * cleared when the tab closes and is never shared across sites — no durable\n * cookie, no cross-site tracking, no PII.\n */\n\nconst SESSION_STORAGE_KEY = '__intlayer_analytics_sid__';\n\n/**\n * Generates a random, opaque session identifier.\n *\n * @returns A URL-safe random string.\n */\nconst generateSessionId = (): string => {\n const cryptoObj =\n typeof globalThis !== 'undefined'\n ? (globalThis.crypto as Crypto | undefined)\n : undefined;\n\n if (cryptoObj?.randomUUID) {\n return cryptoObj.randomUUID();\n }\n\n // Fallback for environments without crypto.randomUUID (older RN/Lynx)\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n};\n\n/**\n * Returns the current session id, creating and persisting one on first access.\n * Degrades gracefully to an in-memory id when `sessionStorage` is unavailable\n * (private mode, native runtimes).\n *\n * @returns The stable session id for the lifetime of the tab.\n */\nexport const getSessionId = (): string => {\n if (typeof window === 'undefined' || !window.sessionStorage) {\n return generateSessionId();\n }\n\n try {\n const existing = window.sessionStorage.getItem(SESSION_STORAGE_KEY);\n if (existing) return existing;\n\n const created = generateSessionId();\n window.sessionStorage.setItem(SESSION_STORAGE_KEY, created);\n return created;\n } catch {\n // sessionStorage can throw (Safari private mode, quota) — never break the app\n return generateSessionId();\n }\n};\n"],"mappings":";;;;;;AAMA,MAAM,sBAAsB;;;;;;AAO5B,MAAM,0BAAkC;CACtC,MAAM,YACJ,OAAO,eAAe,cACjB,WAAW,SACZ;CAEN,IAAI,WAAW,YACb,OAAO,UAAU,WAAW;CAI9B,OAAO,GAAG,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,GAAG,EAAE;AAC7E;;;;;;;;AASA,MAAa,qBAA6B;CACxC,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,gBAC3C,OAAO,kBAAkB;CAG3B,IAAI;EACF,MAAM,WAAW,OAAO,eAAe,QAAQ,mBAAmB;EAClE,IAAI,UAAU,OAAO;EAErB,MAAM,UAAU,kBAAkB;EAClC,OAAO,eAAe,QAAQ,qBAAqB,OAAO;EAC1D,OAAO;CACT,QAAQ;EAEN,OAAO,kBAAkB;CAC3B;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"transport.mjs","names":[],"sources":["../../../src/core/transport.ts"],"sourcesContent":["import type { AnalyticsIngestBody } from './types';\n\n/**\n * Sends a batch of events to the backend. Every path is non-blocking and\n * no-throw — analytics must never break, slow, or delay the host application.\n *\n * Strategy:\n * 1. `navigator.sendBeacon` for the flush-on-hide path — survives page unload\n * and never blocks navigation. The payload is sent as `text/plain` (a\n * CORS-safelisted content type): a JSON `Blob` would require a CORS\n * preflight that browsers handle inconsistently during unload, silently\n * dropping the beacon. The backend parses `text/plain` bodies as JSON.\n * 2. `fetch(..., { keepalive: true })` for interval flushes — survives short\n * navigations without holding the main thread.\n * 3. Plain `fetch` fallback for runtimes without `keepalive` (older RN/Lynx).\n *\n * @param endpoint - Fully-qualified ingestion URL.\n * @param body - The batched payload.\n * @param options - Transport options.\n * @param options.useBeacon - Prefer `sendBeacon` (used when the page is hiding).\n * @returns `true` when a send was dispatched, `false` otherwise.\n */\nexport const sendEvents = (\n endpoint: string,\n body: AnalyticsIngestBody,\n { useBeacon = false }: { useBeacon?: boolean } = {}\n): boolean => {\n try {\n const payload = JSON.stringify(body);\n\n if (\n useBeacon &&\n typeof navigator !== 'undefined' &&\n typeof navigator.sendBeacon === 'function'\n ) {\n // Note: unlike the fetch path below, sendBeacon always includes\n // credentials; the ingest endpoint ignores them.\n return navigator.sendBeacon(endpoint, payload);\n }\n\n if (typeof fetch === 'function') {\n // keepalive lets the request outlive a same-tab navigation.\n void fetch(endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: payload,\n keepalive: true,\n // Analytics is best-effort; never send credentials.\n credentials: 'omit',\n mode: 'cors',\n }).catch(() => {\n /* swallow — best-effort delivery */\n });\n return true;\n }\n\n return false;\n } catch {\n // JSON serialization failed — drop the batch silently.\n return false;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAsBA,MAAa,cACX,UACA,MACA,EAAE,YAAY,UAAmC,EAAE,KACvC;AACZ,KAAI;EACF,MAAM,UAAU,KAAK,UAAU,KAAK;AAEpC,MACE,aACA,OAAO,cAAc,eACrB,OAAO,UAAU,eAAe,WAIhC,QAAO,UAAU,WAAW,UAAU,QAAQ;AAGhD,MAAI,OAAO,UAAU,YAAY;AAE/B,GAAK,MAAM,UAAU;IACnB,QAAQ;IACR,SAAS,EAAE,gBAAgB,oBAAoB;IAC/C,MAAM;IACN,WAAW;IAEX,aAAa;IACb,MAAM;IACP,CAAC,CAAC,YAAY,GAEb;AACF,UAAO;;AAGT,SAAO;SACD;AAEN,SAAO"}
1
+ {"version":3,"file":"transport.mjs","names":[],"sources":["../../../src/core/transport.ts"],"sourcesContent":["import type { AnalyticsIngestBody } from './types';\n\n/**\n * Sends a batch of events to the backend. Every path is non-blocking and\n * no-throw — analytics must never break, slow, or delay the host application.\n *\n * Strategy:\n * 1. `navigator.sendBeacon` for the flush-on-hide path — survives page unload\n * and never blocks navigation. The payload is sent as `text/plain` (a\n * CORS-safelisted content type): a JSON `Blob` would require a CORS\n * preflight that browsers handle inconsistently during unload, silently\n * dropping the beacon. The backend parses `text/plain` bodies as JSON.\n * 2. `fetch(..., { keepalive: true })` for interval flushes — survives short\n * navigations without holding the main thread.\n * 3. Plain `fetch` fallback for runtimes without `keepalive` (older RN/Lynx).\n *\n * @param endpoint - Fully-qualified ingestion URL.\n * @param body - The batched payload.\n * @param options - Transport options.\n * @param options.useBeacon - Prefer `sendBeacon` (used when the page is hiding).\n * @returns `true` when a send was dispatched, `false` otherwise.\n */\nexport const sendEvents = (\n endpoint: string,\n body: AnalyticsIngestBody,\n { useBeacon = false }: { useBeacon?: boolean } = {}\n): boolean => {\n try {\n const payload = JSON.stringify(body);\n\n if (\n useBeacon &&\n typeof navigator !== 'undefined' &&\n typeof navigator.sendBeacon === 'function'\n ) {\n // Note: unlike the fetch path below, sendBeacon always includes\n // credentials; the ingest endpoint ignores them.\n return navigator.sendBeacon(endpoint, payload);\n }\n\n if (typeof fetch === 'function') {\n // keepalive lets the request outlive a same-tab navigation.\n void fetch(endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: payload,\n keepalive: true,\n // Analytics is best-effort; never send credentials.\n credentials: 'omit',\n mode: 'cors',\n }).catch(() => {\n /* swallow — best-effort delivery */\n });\n return true;\n }\n\n return false;\n } catch {\n // JSON serialization failed — drop the batch silently.\n return false;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAsBA,MAAa,cACX,UACA,MACA,EAAE,YAAY,UAAmC,CAAC,MACtC;CACZ,IAAI;EACF,MAAM,UAAU,KAAK,UAAU,IAAI;EAEnC,IACE,aACA,OAAO,cAAc,eACrB,OAAO,UAAU,eAAe,YAIhC,OAAO,UAAU,WAAW,UAAU,OAAO;EAG/C,IAAI,OAAO,UAAU,YAAY;GAE/B,AAAK,MAAM,UAAU;IACnB,QAAQ;IACR,SAAS,EAAE,gBAAgB,mBAAmB;IAC9C,MAAM;IACN,WAAW;IAEX,aAAa;IACb,MAAM;GACR,CAAC,CAAC,CAAC,YAAY,CAEf,CAAC;GACD,OAAO;EACT;EAEA,OAAO;CACT,QAAQ;EAEN,OAAO;CACT;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"contentExposure.mjs","names":[],"sources":["../../../src/events/contentExposure.ts"],"sourcesContent":["import type { KeyPath } from '@intlayer/types/keyPath';\nimport type { ContentExposureEvent, TrackableEvent } from '../core/types';\n\n/**\n * Serializes a `KeyPath[]` into a compact, stable string used both as the\n * coalescing key in the buffer and as the stored `keyPath` on the wire.\n *\n * Only the `key` of each segment is kept (types are implied by the dictionary\n * shape), producing paths like `\"faq.items.2.answer\"`.\n *\n * @param keyPath - The interpreter key path locating a node.\n * @returns A dot-joined, stable path string.\n *\n * @example\n * serializeKeyPath([{ type: 'object', key: 'faq' }, { type: 'array', key: 2 }]);\n * // \"faq.2\"\n */\nexport const serializeKeyPath = (keyPath: KeyPath[]): string =>\n keyPath\n .map((segment) => (segment.key === undefined ? '*' : String(segment.key)))\n .join('.');\n\n/**\n * Builds a content-exposure payload from interpreter node metadata. Shared by\n * every framework binding's analytics node plugin so the wire shape stays\n * identical across React, Vue, Svelte, Angular, etc.\n *\n * @param params - Node metadata available on `NodeProps`.\n * @returns A trackable content-exposure event (minus buffer-stamped fields).\n */\nexport const buildContentExposure = (params: {\n dictionaryKey: string;\n keyPath: KeyPath[];\n locale?: string;\n nodeType?: string;\n experimentKey?: string;\n variant?: string;\n}): Omit<TrackableEvent<ContentExposureEvent>, 'type'> => ({\n dictionaryKey: params.dictionaryKey,\n keyPath: serializeKeyPath(params.keyPath),\n // Left undefined when unknown so the client stamps its ambient locale.\n locale: params.locale,\n nodeType: params.nodeType,\n experimentKey: params.experimentKey,\n variant: params.variant,\n});\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,MAAa,oBAAoB,YAC/B,QACG,KAAK,YAAa,QAAQ,QAAQ,SAAY,MAAM,OAAO,QAAQ,IAAI,CAAE,CACzE,KAAK,IAAI;;;;;;;;;AAUd,MAAa,wBAAwB,YAOsB;CACzD,eAAe,OAAO;CACtB,SAAS,iBAAiB,OAAO,QAAQ;CAEzC,QAAQ,OAAO;CACf,UAAU,OAAO;CACjB,eAAe,OAAO;CACtB,SAAS,OAAO;CACjB"}
1
+ {"version":3,"file":"contentExposure.mjs","names":[],"sources":["../../../src/events/contentExposure.ts"],"sourcesContent":["import type { KeyPath } from '@intlayer/types/keyPath';\nimport type { ContentExposureEvent, TrackableEvent } from '../core/types';\n\n/**\n * Serializes a `KeyPath[]` into a compact, stable string used both as the\n * coalescing key in the buffer and as the stored `keyPath` on the wire.\n *\n * Only the `key` of each segment is kept (types are implied by the dictionary\n * shape), producing paths like `\"faq.items.2.answer\"`.\n *\n * @param keyPath - The interpreter key path locating a node.\n * @returns A dot-joined, stable path string.\n *\n * @example\n * serializeKeyPath([{ type: 'object', key: 'faq' }, { type: 'array', key: 2 }]);\n * // \"faq.2\"\n */\nexport const serializeKeyPath = (keyPath: KeyPath[]): string =>\n keyPath\n .map((segment) => (segment.key === undefined ? '*' : String(segment.key)))\n .join('.');\n\n/**\n * Builds a content-exposure payload from interpreter node metadata. Shared by\n * every framework binding's analytics node plugin so the wire shape stays\n * identical across React, Vue, Svelte, Angular, etc.\n *\n * @param params - Node metadata available on `NodeProps`.\n * @returns A trackable content-exposure event (minus buffer-stamped fields).\n */\nexport const buildContentExposure = (params: {\n dictionaryKey: string;\n keyPath: KeyPath[];\n locale?: string;\n nodeType?: string;\n experimentKey?: string;\n variant?: string;\n}): Omit<TrackableEvent<ContentExposureEvent>, 'type'> => ({\n dictionaryKey: params.dictionaryKey,\n keyPath: serializeKeyPath(params.keyPath),\n // Left undefined when unknown so the client stamps its ambient locale.\n locale: params.locale,\n nodeType: params.nodeType,\n experimentKey: params.experimentKey,\n variant: params.variant,\n});\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,MAAa,oBAAoB,YAC/B,QACG,KAAK,YAAa,QAAQ,QAAQ,SAAY,MAAM,OAAO,QAAQ,GAAG,CAAE,CAAC,CACzE,KAAK,GAAG;;;;;;;;;AAUb,MAAa,wBAAwB,YAOsB;CACzD,eAAe,OAAO;CACtB,SAAS,iBAAiB,OAAO,OAAO;CAExC,QAAQ,OAAO;CACf,UAAU,OAAO;CACjB,eAAe,OAAO;CACtB,SAAS,OAAO;AAClB"}
@@ -1 +1 @@
1
- {"version":3,"file":"isEnabled.mjs","names":[],"sources":["../../src/isEnabled.ts"],"sourcesContent":["import { analytics, editor } from '@intlayer/config/built';\n\n/**\n * Compile-time kill switch. Bundlers replace `process.env.INTLAYER_ANALYTICS_ENABLED`\n * (set to `'false'` by `@intlayer/config` unless `analytics.enabled` is `true`\n * AND an `editor.clientId` is configured) so the whole analytics integration is\n * dead-code-eliminated for apps that don't opt in.\n */\nconst TREE_SHAKE_ANALYTICS = process.env.INTLAYER_ANALYTICS_ENABLED === 'false';\n\n/**\n * Runtime guard mirroring `@intlayer/editor`'s `isEnabled`, but inverted with\n * respect to the iframe: analytics runs for real end users on the **top**\n * window and stays off inside the editor/CMS preview iframe so editor sessions\n * are never counted as traffic.\n *\n * Enabled when:\n * - the bundler did not tree-shake analytics away, and\n * - the user opted in (`analytics.enabled === true`), and\n * - a project key is configured (`editor.clientId`), and\n * - we are on the client, and\n * - we are the top window (not embedded in the editor).\n */\nexport const isEnabled =\n !TREE_SHAKE_ANALYTICS &&\n analytics?.enabled === true &&\n Boolean(editor?.clientId) &&\n typeof window !== 'undefined' &&\n window.self === window.top;\n"],"mappings":";;;;;;;;;AAQA,MAAM,uBAAuB,QAAQ,IAAI,+BAA+B;;;;;;;;;;;;;;AAexE,MAAa,YACX,CAAC,wBACD,WAAW,YAAY,QACvB,QAAQ,QAAQ,SAAS,IACzB,OAAO,WAAW,eAClB,OAAO,SAAS,OAAO"}
1
+ {"version":3,"file":"isEnabled.mjs","names":[],"sources":["../../src/isEnabled.ts"],"sourcesContent":["import { analytics, editor } from '@intlayer/config/built';\n\n/**\n * Compile-time kill switch. Bundlers replace `process.env.INTLAYER_ANALYTICS_ENABLED`\n * (set to `'false'` by `@intlayer/config` unless `analytics.enabled` is `true`\n * AND an `editor.clientId` is configured) so the whole analytics integration is\n * dead-code-eliminated for apps that don't opt in.\n */\nconst TREE_SHAKE_ANALYTICS = process.env.INTLAYER_ANALYTICS_ENABLED === 'false';\n\n/**\n * Runtime guard mirroring `@intlayer/editor`'s `isEnabled`, but inverted with\n * respect to the iframe: analytics runs for real end users on the **top**\n * window and stays off inside the editor/CMS preview iframe so editor sessions\n * are never counted as traffic.\n *\n * Enabled when:\n * - the bundler did not tree-shake analytics away, and\n * - the user opted in (`analytics.enabled === true`), and\n * - a project key is configured (`editor.clientId`), and\n * - we are on the client, and\n * - we are the top window (not embedded in the editor).\n */\nexport const isEnabled =\n !TREE_SHAKE_ANALYTICS &&\n analytics?.enabled === true &&\n Boolean(editor?.clientId) &&\n typeof window !== 'undefined' &&\n window.self === window.top;\n"],"mappings":";;;;;;;;;AAQA,MAAM,uBAAuB,QAAQ,IAAI,+BAA+B;;;;;;;;;;;;;;AAexE,MAAa,YACX,CAAC,wBACD,WAAW,YAAY,QACvB,QAAQ,QAAQ,QAAQ,KACxB,OAAO,WAAW,eAClB,OAAO,SAAS,OAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"hash.mjs","names":[],"sources":["../../../src/utils/hash.ts"],"sourcesContent":["/**\n * FNV-1a 32-bit string hash. Small, fast, dependency-free, and stable across\n * runtimes — good enough for deterministic A/B bucketing and session seeding\n * (not for cryptographic use).\n *\n * @param input - The string to hash.\n * @returns An unsigned 32-bit integer hash.\n *\n * @example\n * hashString('session-1:homepage-hero'); // 3039336720\n */\nexport const hashString = (input: string): number => {\n let hash = 0x811c9dc5; // FNV offset basis\n\n for (let index = 0; index < input.length; index++) {\n hash ^= input.charCodeAt(index);\n // 32-bit FNV prime multiplication via shifts to stay within Number safe range\n hash = Math.imul(hash, 0x01000193);\n }\n\n // Coerce to unsigned 32-bit\n return hash >>> 0;\n};\n"],"mappings":";;;;;;;;;;;;AAWA,MAAa,cAAc,UAA0B;CACnD,IAAI,OAAO;AAEX,MAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS;AACjD,UAAQ,MAAM,WAAW,MAAM;AAE/B,SAAO,KAAK,KAAK,MAAM,SAAW;;AAIpC,QAAO,SAAS"}
1
+ {"version":3,"file":"hash.mjs","names":[],"sources":["../../../src/utils/hash.ts"],"sourcesContent":["/**\n * FNV-1a 32-bit string hash. Small, fast, dependency-free, and stable across\n * runtimes — good enough for deterministic A/B bucketing and session seeding\n * (not for cryptographic use).\n *\n * @param input - The string to hash.\n * @returns An unsigned 32-bit integer hash.\n *\n * @example\n * hashString('session-1:homepage-hero'); // 3039336720\n */\nexport const hashString = (input: string): number => {\n let hash = 0x811c9dc5; // FNV offset basis\n\n for (let index = 0; index < input.length; index++) {\n hash ^= input.charCodeAt(index);\n // 32-bit FNV prime multiplication via shifts to stay within Number safe range\n hash = Math.imul(hash, 0x01000193);\n }\n\n // Coerce to unsigned 32-bit\n return hash >>> 0;\n};\n"],"mappings":";;;;;;;;;;;;AAWA,MAAa,cAAc,UAA0B;CACnD,IAAI,OAAO;CAEX,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS;EACjD,QAAQ,MAAM,WAAW,KAAK;EAE9B,OAAO,KAAK,KAAK,MAAM,QAAU;CACnC;CAGA,OAAO,SAAS;AAClB"}
@@ -1 +1 @@
1
- {"version":3,"file":"idle.mjs","names":[],"sources":["../../../src/utils/idle.ts"],"sourcesContent":["/**\n * Runs a callback when the browser is idle, without blocking first render.\n * Falls back to a short `setTimeout` where `requestIdleCallback` is unavailable\n * (Safari, React Native, Lynx).\n *\n * @param callback - Work to run once the main thread is free.\n *\n * @example\n * onIdle(() => attachVisibilityListeners());\n */\nexport const onIdle = (callback: () => void): void => {\n if (typeof window === 'undefined') return;\n\n const requestIdle = (\n window as Window & {\n requestIdleCallback?: (cb: () => void) => number;\n }\n ).requestIdleCallback;\n\n if (typeof requestIdle === 'function') {\n requestIdle(() => callback());\n return;\n }\n\n setTimeout(callback, 1);\n};\n"],"mappings":";;;;;;;;;;;AAUA,MAAa,UAAU,aAA+B;AACpD,KAAI,OAAO,WAAW,YAAa;CAEnC,MAAM,cACJ,OAGA;AAEF,KAAI,OAAO,gBAAgB,YAAY;AACrC,oBAAkB,UAAU,CAAC;AAC7B;;AAGF,YAAW,UAAU,EAAE"}
1
+ {"version":3,"file":"idle.mjs","names":[],"sources":["../../../src/utils/idle.ts"],"sourcesContent":["/**\n * Runs a callback when the browser is idle, without blocking first render.\n * Falls back to a short `setTimeout` where `requestIdleCallback` is unavailable\n * (Safari, React Native, Lynx).\n *\n * @param callback - Work to run once the main thread is free.\n *\n * @example\n * onIdle(() => attachVisibilityListeners());\n */\nexport const onIdle = (callback: () => void): void => {\n if (typeof window === 'undefined') return;\n\n const requestIdle = (\n window as Window & {\n requestIdleCallback?: (cb: () => void) => number;\n }\n ).requestIdleCallback;\n\n if (typeof requestIdle === 'function') {\n requestIdle(() => callback());\n return;\n }\n\n setTimeout(callback, 1);\n};\n"],"mappings":";;;;;;;;;;;AAUA,MAAa,UAAU,aAA+B;CACpD,IAAI,OAAO,WAAW,aAAa;CAEnC,MAAM,cACJ,OAGA;CAEF,IAAI,OAAO,gBAAgB,YAAY;EACrC,kBAAkB,SAAS,CAAC;EAC5B;CACF;CAEA,WAAW,UAAU,CAAC;AACxB"}
@@ -1,16 +1,21 @@
1
1
  import { AnalyticsClientConfig, ContentExposureEvent, ConversionEvent, PageViewEvent, TrackableEvent } from "./types.js";
2
-
3
2
  //#region src/core/AnalyticsClient.d.ts
4
3
  /**
5
4
  * Caller-supplied fields for a page view. Everything is optional — the client
6
5
  * fills `url`, `locale`, viewport, and referrer from the environment when omitted.
7
6
  */
8
7
  type PageViewInput = {
9
- /** Explicit pathname / screen name (native runtimes have no `location`). */url?: string; /** Explicit locale; falls back to the client's ambient locale. */
10
- locale?: string; /** Referrer host override. */
11
- ref?: string; /** Viewport width override. */
12
- vw?: number; /** Viewport height override. */
13
- vh?: number; /** Why the view was recorded. */
8
+ /** Explicit pathname / screen name (native runtimes have no `location`). */
9
+ url?: string;
10
+ /** Explicit locale; falls back to the client's ambient locale. */
11
+ locale?: string;
12
+ /** Referrer host override. */
13
+ ref?: string;
14
+ /** Viewport width override. */
15
+ vw?: number;
16
+ /** Viewport height override. */
17
+ vh?: number;
18
+ /** Why the view was recorded. */
14
19
  reason?: PageViewEvent['reason'];
15
20
  };
16
21
  /** Default flush cadence — one network request per 20 seconds. */
@@ -29,13 +34,21 @@ declare const MAX_EVENTS_PER_SEND = 200;
29
34
  * a reference to this and forward provider/node/conversion signals into it.
30
35
  */
31
36
  type AnalyticsClient = {
32
- /** Sets the ambient locale stamped onto subsequent events. */setLocale: (locale: string) => void; /** Records a page/locale view (provider level). */
33
- trackPageView: (event?: PageViewInput) => void; /** Records a content exposure (node level). Sampled + deduped per page view. */
34
- trackContentExposure: (event: Omit<TrackableEvent<ContentExposureEvent>, 'type'>) => void; /** Records a conversion tied to an experiment variant. */
35
- trackConversion: (event: Omit<TrackableEvent<ConversionEvent>, 'type'>) => void; /** Deterministically resolves this session's variant for an experiment. */
36
- getVariant: (experimentKey: string, variants: string[], weights?: number[]) => string; /** Sends the buffered batch now. */
37
- flush: (useBeacon?: boolean) => void; /** Starts the flush loop and lifecycle listeners (idempotent). */
38
- start: () => void; /** Stops timers/listeners and flushes any remaining events. */
37
+ /** Sets the ambient locale stamped onto subsequent events. */
38
+ setLocale: (locale: string) => void;
39
+ /** Records a page/locale view (provider level). */
40
+ trackPageView: (event?: PageViewInput) => void;
41
+ /** Records a content exposure (node level). Sampled + deduped per page view. */
42
+ trackContentExposure: (event: Omit<TrackableEvent<ContentExposureEvent>, 'type'>) => void;
43
+ /** Records a conversion tied to an experiment variant. */
44
+ trackConversion: (event: Omit<TrackableEvent<ConversionEvent>, 'type'>) => void;
45
+ /** Deterministically resolves this session's variant for an experiment. */
46
+ getVariant: (experimentKey: string, variants: string[], weights?: number[]) => string;
47
+ /** Sends the buffered batch now. */
48
+ flush: (useBeacon?: boolean) => void;
49
+ /** Starts the flush loop and lifecycle listeners (idempotent). */
50
+ start: () => void;
51
+ /** Stops timers/listeners and flushes any remaining events. */
39
52
  stop: () => void;
40
53
  };
41
54
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"AnalyticsClient.d.ts","names":[],"sources":["../../../src/core/AnalyticsClient.ts"],"mappings":";;;;;AAmBA;;KAAY,aAAA;EAYY,4EAVtB,GAAA,WAEA;EAAA,MAAA,WAIA;EAFA,GAAA,WAMA;EAJA,EAAA,WAIsB;EAFtB,EAAA,WAMW;EAJX,MAAA,GAAS,aAAA;AAAA;;cAIE,sBAAA;AAEb;AAAA,cAAa,uBAAA;;cAEA,mBAAA;;AAAb;;;cAKa,mBAAA;;AAAb;;;KAQY,eAAA;EARoB,8DAU9B,SAAA,GAAY,MAAA,mBAFa;EAIzB,aAAA,GAAgB,KAAA,GAAQ,aAAA,WAAA;EAExB,oBAAA,GACE,KAAA,EAAO,IAAA,CAAK,cAAA,CAAe,oBAAA,qBAAf;EAGd,eAAA,GACE,KAAA,EAAO,IAAA,CAAK,cAAA,CAAe,eAAA,qBAAA;EAG7B,UAAA,GACE,aAAA,UACA,QAAA,YACA,OAAA,wBANO;EAST,KAAA,GAAQ,SAAA,qBATK;EAWb,KAAA,cApBY;EAsBZ,IAAA;AAAA;;;;;;;;cA+BW,qBAAA,GACX,MAAA,EAAQ,qBAAA,KACP,eAAA"}
1
+ {"version":3,"file":"AnalyticsClient.d.ts","names":[],"sources":["../../../src/core/AnalyticsClient.ts"],"mappings":";;;;;;KAmBY;;EAEV;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,SAAS;;;cAIE;;cAEA;;cAEA;;;;;cAKA;;;;;KAQD;;EAEV,YAAY;;EAEZ,gBAAgB,QAAQ;;EAExB,uBACE,OAAO,KAAK,eAAe;;EAG7B,kBACE,OAAO,KAAK,eAAe;;EAG7B,aACE,uBACA,oBACA;;EAGF,QAAQ;;EAER;;EAEA;;;;;;;;;cA+BW,wBAAqB,QACxB,0BACP"}
@@ -1 +1 @@
1
- {"version":3,"file":"abTesting.d.ts","names":[],"sources":["../../../src/core/abTesting.ts"],"mappings":";;AAoBA;;;;;;;;;;;;;;;;;cAAa,aAAA,GACX,SAAA,UACA,aAAA,UACA,QAAA,YACA,OAAA"}
1
+ {"version":3,"file":"abTesting.d.ts","names":[],"sources":["../../../src/core/abTesting.ts"],"mappings":";;;;;;;;;;;;;;;;;;;cAoBa,gBAAa,mBACP,uBACI,oBACH"}
@@ -1,5 +1,4 @@
1
1
  import { AnalyticsEvent } from "./types.js";
2
-
3
2
  //#region src/core/eventBuffer.d.ts
4
3
  /**
5
4
  * A bounded, coalescing in-memory buffer for analytics events.
@@ -14,8 +13,11 @@ import { AnalyticsEvent } from "./types.js";
14
13
  * remain.
15
14
  */
16
15
  type EventBuffer = {
17
- /** Adds an event, coalescing content exposures. Returns the current size. */push: (event: AnalyticsEvent) => number; /** Removes and returns every buffered event. */
18
- drain: () => AnalyticsEvent[]; /** Current number of distinct buffered events. */
16
+ /** Adds an event, coalescing content exposures. Returns the current size. */
17
+ push: (event: AnalyticsEvent) => number;
18
+ /** Removes and returns every buffered event. */
19
+ drain: () => AnalyticsEvent[];
20
+ /** Current number of distinct buffered events. */
19
21
  size: () => number;
20
22
  };
21
23
  /**
@@ -25,9 +27,7 @@ type EventBuffer = {
25
27
  * @param options.max - Maximum number of distinct events to retain.
26
28
  * @returns A new buffer instance.
27
29
  */
28
- declare const createEventBuffer: ({
29
- max
30
- }: {
30
+ declare const createEventBuffer: ({ max }: {
31
31
  max: number;
32
32
  }) => EventBuffer;
33
33
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"eventBuffer.d.ts","names":[],"sources":["../../../src/core/eventBuffer.ts"],"mappings":";;;;;AAgCA;;;;;;;;;;KAAY,WAAA;EAMN,6EAJJ,IAAA,GAAO,KAAA,EAAO,cAAA,aAiEf;EA/DC,KAAA,QAAa,cAAA,IA+Dd;EA7DC,IAAA;AAAA;;;;;;;;cAUW,iBAAA;EAAqB;AAAA;EAAW,GAAA;AAAA,MAAgB,WAAA"}
1
+ {"version":3,"file":"eventBuffer.d.ts","names":[],"sources":["../../../src/core/eventBuffer.ts"],"mappings":";;;;;;;;;;;;;;KAgCY;;EAEV,OAAO,OAAO;;EAEd,aAAa;;EAEb;;;;;;;;;cAUW,sBAAiB;EAAe;MAAgB"}
@@ -1,5 +1,4 @@
1
1
  import { AnalyticsClient } from "./AnalyticsClient.js";
2
-
3
2
  //#region src/core/globalManager.d.ts
4
3
  /**
5
4
  * Returns the global analytics client, or `null` in SSR or before init.
@@ -1 +1 @@
1
- {"version":3,"file":"globalManager.d.ts","names":[],"sources":["../../../src/core/globalManager.ts"],"mappings":";;;;;AA2BA;cAAa,wBAAA,QAA+B,eAAA;;;;AAU5C;;cAAa,wBAAA,GACX,MAAA,EAAQ,eAAA;;;AAWV;;;cAAa,gCAAA;;AAYb;;;;cAAa,gCAAA"}
1
+ {"version":3,"file":"globalManager.d.ts","names":[],"sources":["../../../src/core/globalManager.ts"],"mappings":";;;;;cA2Ba,gCAA+B;;;;;;cAU/B,2BAAwB,QAC3B;;;;;;cAWG;;;;;;cAYA"}
@@ -1,5 +1,4 @@
1
1
  import { AnalyticsClient } from "./AnalyticsClient.js";
2
-
3
2
  //#region src/core/initAnalyticsClient.d.ts
4
3
  /**
5
4
  * Initializes the Intlayer analytics client singleton.
@@ -1 +1 @@
1
- {"version":3,"file":"initAnalyticsClient.d.ts","names":[],"sources":["../../../src/core/initAnalyticsClient.ts"],"mappings":";;;;;AA4BA;;;;;AA2BA;;;;;;cA3Ba,mBAAA,QAA0B,eAAA;;;;;;;;cA2B1B,mBAAA"}
1
+ {"version":3,"file":"initAnalyticsClient.d.ts","names":[],"sources":["../../../src/core/initAnalyticsClient.ts"],"mappings":";;;;;;;;;;;;;;;cA4Ba,2BAA0B;;;;;;;;cA2B1B"}
@@ -1 +1 @@
1
- {"version":3,"file":"sampling.d.ts","names":[],"sources":["../../../src/core/sampling.ts"],"mappings":";;AAiBA;;;;;;;;;;;;;;cAAa,WAAA,GAAe,SAAA,UAAmB,UAAA"}
1
+ {"version":3,"file":"sampling.d.ts","names":[],"sources":["../../../src/core/sampling.ts"],"mappings":";;;;;;;;;;;;;;;;cAiBa,cAAW,mBAAqB"}
@@ -1 +1 @@
1
- {"version":3,"file":"session.d.ts","names":[],"sources":["../../../src/core/session.ts"],"mappings":";;AAkCA;;;;;;;;;;;cAAa,YAAA"}
1
+ {"version":3,"file":"session.d.ts","names":[],"sources":["../../../src/core/session.ts"],"mappings":";;;;;;;;;;;;;cAkCa"}
@@ -1,5 +1,4 @@
1
1
  import { AnalyticsIngestBody } from "./types.js";
2
-
3
2
  //#region src/core/transport.d.ts
4
3
  /**
5
4
  * Sends a batch of events to the backend. Every path is non-blocking and
@@ -21,9 +20,7 @@ import { AnalyticsIngestBody } from "./types.js";
21
20
  * @param options.useBeacon - Prefer `sendBeacon` (used when the page is hiding).
22
21
  * @returns `true` when a send was dispatched, `false` otherwise.
23
22
  */
24
- declare const sendEvents: (endpoint: string, body: AnalyticsIngestBody, {
25
- useBeacon
26
- }?: {
23
+ declare const sendEvents: (endpoint: string, body: AnalyticsIngestBody, { useBeacon }?: {
27
24
  useBeacon?: boolean;
28
25
  }) => boolean;
29
26
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"transport.d.ts","names":[],"sources":["../../../src/core/transport.ts"],"mappings":";;;;;AAsBA;;;;;;;;;;;;;;;;;;cAAa,UAAA,GACX,QAAA,UACA,IAAA,EAAM,mBAAA;EACN;AAAA;EAAyB,SAAA;AAAA"}
1
+ {"version":3,"file":"transport.d.ts","names":[],"sources":["../../../src/core/transport.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;cAsBa,aAAU,kBACL,MACV,uBAAmB;EACA"}
@@ -12,8 +12,11 @@ type AnalyticsEventType = 'page_view' | 'content_exposure' | 'conversion';
12
12
  * Fields present on every event regardless of its type.
13
13
  */
14
14
  type BaseAnalyticsEvent = {
15
- /** Client timestamp in milliseconds since epoch. */t: number; /** Current locale being displayed when the event was captured. */
16
- locale: string; /** Pathname of the page (search params excluded by default for privacy). */
15
+ /** Client timestamp in milliseconds since epoch. */
16
+ t: number;
17
+ /** Current locale being displayed when the event was captured. */
18
+ locale: string;
19
+ /** Pathname of the page (search params excluded by default for privacy). */
17
20
  url: string;
18
21
  };
19
22
  /**
@@ -21,10 +24,14 @@ type BaseAnalyticsEvent = {
21
24
  * on client-side navigation, and on locale change.
22
25
  */
23
26
  type PageViewEvent = BaseAnalyticsEvent & {
24
- type: 'page_view'; /** Referrer host only (never the full URL) — omitted when unavailable. */
25
- ref?: string; /** Viewport width in CSS pixels. */
26
- vw?: number; /** Viewport height in CSS pixels. */
27
- vh?: number; /** Why the view was recorded (initial load vs. locale switch vs. route change). */
27
+ type: 'page_view';
28
+ /** Referrer host only (never the full URL) — omitted when unavailable. */
29
+ ref?: string;
30
+ /** Viewport width in CSS pixels. */
31
+ vw?: number;
32
+ /** Viewport height in CSS pixels. */
33
+ vh?: number;
34
+ /** Why the view was recorded (initial load vs. locale switch vs. route change). */
28
35
  reason?: 'initial' | 'locale_change' | 'route_change';
29
36
  };
30
37
  /**
@@ -33,22 +40,32 @@ type PageViewEvent = BaseAnalyticsEvent & {
33
40
  * same node within a flush window collapse into a single event with a `count`.
34
41
  */
35
42
  type ContentExposureEvent = BaseAnalyticsEvent & {
36
- type: 'content_exposure'; /** The dictionary the resolved node belongs to. */
37
- dictionaryKey: string; /** Stable-serialized `KeyPath[]` locating the node inside the dictionary. */
38
- keyPath: string; /** The interpreter node type (translation, enumeration, markdown, …). */
39
- nodeType?: string; /** The experiment this exposure belongs to, when part of an experiment. */
40
- experimentKey?: string; /** A/B variant that produced this exposure, when part of an experiment. */
41
- variant?: string; /** Number of coalesced exposures represented by this event. */
43
+ type: 'content_exposure';
44
+ /** The dictionary the resolved node belongs to. */
45
+ dictionaryKey: string;
46
+ /** Stable-serialized `KeyPath[]` locating the node inside the dictionary. */
47
+ keyPath: string;
48
+ /** The interpreter node type (translation, enumeration, markdown, …). */
49
+ nodeType?: string;
50
+ /** The experiment this exposure belongs to, when part of an experiment. */
51
+ experimentKey?: string;
52
+ /** A/B variant that produced this exposure, when part of an experiment. */
53
+ variant?: string;
54
+ /** Number of coalesced exposures represented by this event. */
42
55
  count?: number;
43
56
  };
44
57
  /**
45
58
  * A conversion event tying a goal to the A/B variant the session was exposed to.
46
59
  */
47
60
  type ConversionEvent = BaseAnalyticsEvent & {
48
- type: 'conversion'; /** The experiment this conversion is attributed to. */
49
- experimentKey: string; /** The variant the session was assigned. */
50
- variant: string; /** The goal that was reached (e.g. `"signup"`, `"cta_click"`). */
51
- goal: string; /** Optional numeric value associated with the conversion (e.g. revenue). */
61
+ type: 'conversion';
62
+ /** The experiment this conversion is attributed to. */
63
+ experimentKey: string;
64
+ /** The variant the session was assigned. */
65
+ variant: string;
66
+ /** The goal that was reached (e.g. `"signup"`, `"cta_click"`). */
67
+ goal: string;
68
+ /** Optional numeric value associated with the conversion (e.g. revenue). */
52
69
  value?: number;
53
70
  };
54
71
  /**
@@ -60,15 +77,20 @@ type AnalyticsEvent = PageViewEvent | ContentExposureEvent | ConversionEvent;
60
77
  * shared `BaseAnalyticsEvent` fields (`t`, `url`, and the ambient `locale`).
61
78
  */
62
79
  type TrackableEvent<E extends AnalyticsEvent = AnalyticsEvent> = Omit<E, 't' | 'url' | 'locale'> & {
63
- /** Optional explicit locale; falls back to the client's ambient locale. */locale?: string;
80
+ /** Optional explicit locale; falls back to the client's ambient locale. */
81
+ locale?: string;
64
82
  };
65
83
  /**
66
84
  * The batched request body sent to `POST /api/analytics/events`.
67
85
  */
68
86
  type AnalyticsIngestBody = {
69
- /** Public project key — reused from `editor.clientId`. */clientId?: string; /** Anonymous per-tab session identifier (new tab ⇒ new id; never durable). */
70
- sessionId: string; /** Version of the analytics SDK that produced the batch. */
71
- sdkVersion: string; /** The events collected during the flush window. */
87
+ /** Public project key — reused from `editor.clientId`. */
88
+ clientId?: string;
89
+ /** Anonymous per-tab session identifier (new tab ⇒ new id; never durable). */
90
+ sessionId: string;
91
+ /** Version of the analytics SDK that produced the batch. */
92
+ sdkVersion: string;
93
+ /** The events collected during the flush window. */
72
94
  events: AnalyticsEvent[];
73
95
  };
74
96
  /**
@@ -76,10 +98,15 @@ type AnalyticsIngestBody = {
76
98
  * defaults so the client can run with only a `backendURL`.
77
99
  */
78
100
  type AnalyticsClientConfig = {
79
- /** Base URL of the Intlayer backend — reused from `editor.backendURL`. */backendURL: string; /** Public project key — reused from `editor.clientId`. */
80
- clientId?: string; /** Milliseconds between automatic flushes. Defaults to 20000. */
81
- flushInterval: number; /** Maximum number of buffered events before an early flush. Defaults to 500. */
82
- maxBufferSize: number; /** Fraction of content-exposure events to keep, 0..1. Defaults to 1. */
101
+ /** Base URL of the Intlayer backend — reused from `editor.backendURL`. */
102
+ backendURL: string;
103
+ /** Public project key — reused from `editor.clientId`. */
104
+ clientId?: string;
105
+ /** Milliseconds between automatic flushes. Defaults to 20000. */
106
+ flushInterval: number;
107
+ /** Maximum number of buffered events before an early flush. Defaults to 500. */
108
+ maxBufferSize: number;
109
+ /** Fraction of content-exposure events to keep, 0..1. Defaults to 1. */
83
110
  sampleRate: number;
84
111
  };
85
112
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/core/types.ts"],"mappings":";;AASA;;;;;AAQA;;KARY,kBAAA;;;;KAQA,kBAAA;EAMP,oDAJH,CAAA,UAWU;EATV,MAAA;EAEA,GAAA;AAAA;;;;;KAOU,aAAA,GAAgB,kBAAA;EAC1B,IAAA,eAQM;EANN,GAAA,WAc8B;EAZ9B,EAAA,WAYmD;EAVnD,EAAA,WAWA;EATA,MAAA;AAAA;;;;;;KAQU,oBAAA,GAAuB,kBAAA;EACjC,IAAA,sBAkByB;EAhBzB,aAAA,UAgB8C;EAd9C,OAAA,UAeA;EAbA,QAAA,WAiBA;EAfA,aAAA,WAmBA;EAjBA,OAAA,WAiBK;EAfL,KAAA;AAAA;;;;KAMU,eAAA,GAAkB,kBAAA;EAC5B,IAAA,gBAiBiB;EAfjB,aAAA,UAcE;EAZF,OAAA,UAaiB;EAXjB,IAAA,UAiBU;EAfV,KAAA;AAAA;;;;KAMU,cAAA,GACR,aAAA,GACA,oBAAA,GACA,eAAA;;;;;KAMQ,cAAA,WAAyB,cAAA,GAAiB,cAAA,IAAkB,IAAA,CACtE,CAAA;EADsE,2EAKtE,MAAA;AAAA;;;AAMF;KAAY,mBAAA;4DAEV,QAAA;EAEA,SAAA,UAEA;EAAA,UAAA,UAEQ;EAAR,MAAA,EAAQ,cAAA;AAAA;AAOV;;;;AAAA,KAAY,qBAAA;EAIV,0EAFA,UAAA,UAMA;EAJA,QAAA,WAMU;EAJV,aAAA;EAEA,aAAA;EAEA,UAAA;AAAA"}
1
+ {"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/core/types.ts"],"mappings":";;;;;;;;;KASY;;;;KAQA;;EAEV;;EAEA;;EAEA;;;;;;KAOU,gBAAgB;EAC1B;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;KAQU,uBAAuB;EACjC;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;;;;KAMU,kBAAkB;EAC5B;;EAEA;;EAEA;;EAEA;;EAEA;;;;;KAMU,iBACR,gBACA,uBACA;;;;;KAMQ,eAAe,UAAU,iBAAiB,kBAAkB,KACtE;;EAIA;;;;;KAMU;;EAEV;;EAEA;;EAEA;;EAEA,QAAQ;;;;;;KAOE;;EAEV;;EAEA;;EAEA;;EAEA;;EAEA"}
@@ -1,6 +1,5 @@
1
1
  import { ContentExposureEvent, TrackableEvent } from "../core/types.js";
2
2
  import { KeyPath } from "@intlayer/types/keyPath";
3
-
4
3
  //#region src/events/contentExposure.d.ts
5
4
  /**
6
5
  * Serializes a `KeyPath[]` into a compact, stable string used both as the
@@ -32,7 +31,7 @@ declare const buildContentExposure: (params: {
32
31
  nodeType?: string;
33
32
  experimentKey?: string;
34
33
  variant?: string;
35
- }) => Omit<TrackableEvent<ContentExposureEvent>, "type">;
34
+ }) => Omit<TrackableEvent<ContentExposureEvent>, 'type'>;
36
35
  //#endregion
37
36
  export { buildContentExposure, serializeKeyPath };
38
37
  //# sourceMappingURL=contentExposure.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"contentExposure.d.ts","names":[],"sources":["../../../src/events/contentExposure.ts"],"mappings":";;;;;;AAiBA;;;;;AAaA;;;;;;;cAba,gBAAA,GAAoB,OAAA,EAAS,OAAA;;;;;;;;;cAa7B,oBAAA,GAAwB,MAAA;EACnC,aAAA;EACA,OAAA,EAAS,OAAA;EACT,MAAA;EACA,QAAA;EACA,aAAA;EACA,OAAA;AAAA,MACE,IAAA,CAAK,cAAA,CAAe,oBAAA"}
1
+ {"version":3,"file":"contentExposure.d.ts","names":[],"sources":["../../../src/events/contentExposure.ts"],"mappings":";;;;;;;;;;;;;;;;;cAiBa,mBAAgB,SAAa;;;;;;;;;cAa7B,uBAAoB;EAC/B;EACA,SAAS;EACT;EACA;EACA;EACA;MACE,KAAK,eAAe"}
@@ -1 +1 @@
1
- {"version":3,"file":"isEnabled.d.ts","names":[],"sources":["../../src/isEnabled.ts"],"mappings":";;AAuBA;;;;;;;;;;;;cAAa,SAAA"}
1
+ {"version":3,"file":"isEnabled.d.ts","names":[],"sources":["../../src/isEnabled.ts"],"mappings":";;;;;;;;;;;;;;cAuBa"}
@@ -1 +1 @@
1
- {"version":3,"file":"hash.d.ts","names":[],"sources":["../../../src/utils/hash.ts"],"mappings":";;AAWA;;;;;;;;;;cAAa,UAAA,GAAc,KAAA"}
1
+ {"version":3,"file":"hash.d.ts","names":[],"sources":["../../../src/utils/hash.ts"],"mappings":";;;;;;;;;;;;cAWa,aAAU"}
@@ -1 +1 @@
1
- {"version":3,"file":"idle.d.ts","names":[],"sources":["../../../src/utils/idle.ts"],"mappings":";;AAUA;;;;;;;;;cAAa,MAAA,GAAU,QAAA"}
1
+ {"version":3,"file":"idle.d.ts","names":[],"sources":["../../../src/utils/idle.ts"],"mappings":";;;;;;;;;;;cAUa,SAAM"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intlayer/analytics",
3
- "version": "9.0.0-canary.16",
3
+ "version": "9.0.0-canary.18",
4
4
  "private": false,
5
5
  "description": "Collects which Intlayer content is shown (page/locale + node-level) and powers content A/B testing. Optional, lazily-imported companion to @intlayer/editor.",
6
6
  "keywords": [
@@ -80,18 +80,18 @@
80
80
  "typecheck": "tsc --noEmit --project tsconfig.types.json"
81
81
  },
82
82
  "dependencies": {
83
- "@intlayer/config": "9.0.0-canary.16",
84
- "@intlayer/core": "9.0.0-canary.16",
85
- "@intlayer/types": "9.0.0-canary.16"
83
+ "@intlayer/config": "9.0.0-canary.18",
84
+ "@intlayer/core": "9.0.0-canary.18",
85
+ "@intlayer/types": "9.0.0-canary.18"
86
86
  },
87
87
  "devDependencies": {
88
- "@types/node": "25.9.4",
88
+ "@types/node": "26.1.1",
89
89
  "@utils/ts-config": "1.0.4",
90
90
  "@utils/ts-config-types": "1.0.4",
91
91
  "@utils/tsdown-config": "1.0.4",
92
92
  "rimraf": "6.1.3",
93
- "tsdown": "0.21.10",
94
- "typescript": "6.0.3",
93
+ "tsdown": "0.22.12",
94
+ "typescript": "7.0.2",
95
95
  "vitest": "4.1.10"
96
96
  },
97
97
  "engines": {