@intlayer/analytics 9.0.0-canary.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +330 -0
- package/dist/cjs/core/AnalyticsClient.cjs +182 -0
- package/dist/cjs/core/AnalyticsClient.cjs.map +1 -0
- package/dist/cjs/core/abTesting.cjs +44 -0
- package/dist/cjs/core/abTesting.cjs.map +1 -0
- package/dist/cjs/core/eventBuffer.cjs +68 -0
- package/dist/cjs/core/eventBuffer.cjs.map +1 -0
- package/dist/cjs/core/globalManager.cjs +63 -0
- package/dist/cjs/core/globalManager.cjs.map +1 -0
- package/dist/cjs/core/index.cjs +26 -0
- package/dist/cjs/core/initAnalyticsClient.cjs +51 -0
- package/dist/cjs/core/initAnalyticsClient.cjs.map +1 -0
- package/dist/cjs/core/sampling.cjs +28 -0
- package/dist/cjs/core/sampling.cjs.map +1 -0
- package/dist/cjs/core/session.cjs +42 -0
- package/dist/cjs/core/session.cjs.map +1 -0
- package/dist/cjs/core/transport.cjs +47 -0
- package/dist/cjs/core/transport.cjs.map +1 -0
- package/dist/cjs/core/types.cjs +0 -0
- package/dist/cjs/events/contentExposure.cjs +39 -0
- package/dist/cjs/events/contentExposure.cjs.map +1 -0
- package/dist/cjs/index.cjs +29 -0
- package/dist/cjs/isEnabled.cjs +29 -0
- package/dist/cjs/isEnabled.cjs.map +1 -0
- package/dist/cjs/utils/hash.cjs +26 -0
- package/dist/cjs/utils/hash.cjs.map +1 -0
- package/dist/cjs/utils/idle.cjs +26 -0
- package/dist/cjs/utils/idle.cjs.map +1 -0
- package/dist/esm/core/AnalyticsClient.mjs +177 -0
- package/dist/esm/core/AnalyticsClient.mjs.map +1 -0
- package/dist/esm/core/abTesting.mjs +43 -0
- package/dist/esm/core/abTesting.mjs.map +1 -0
- package/dist/esm/core/eventBuffer.mjs +66 -0
- package/dist/esm/core/eventBuffer.mjs.map +1 -0
- package/dist/esm/core/globalManager.mjs +58 -0
- package/dist/esm/core/globalManager.mjs.map +1 -0
- package/dist/esm/core/index.mjs +10 -0
- package/dist/esm/core/initAnalyticsClient.mjs +49 -0
- package/dist/esm/core/initAnalyticsClient.mjs.map +1 -0
- package/dist/esm/core/sampling.mjs +27 -0
- package/dist/esm/core/sampling.mjs.map +1 -0
- package/dist/esm/core/session.mjs +40 -0
- package/dist/esm/core/session.mjs.map +1 -0
- package/dist/esm/core/transport.mjs +45 -0
- package/dist/esm/core/transport.mjs.map +1 -0
- package/dist/esm/core/types.mjs +0 -0
- package/dist/esm/events/contentExposure.mjs +36 -0
- package/dist/esm/events/contentExposure.mjs.map +1 -0
- package/dist/esm/index.mjs +11 -0
- package/dist/esm/isEnabled.mjs +28 -0
- package/dist/esm/isEnabled.mjs.map +1 -0
- package/dist/esm/utils/hash.mjs +24 -0
- package/dist/esm/utils/hash.mjs.map +1 -0
- package/dist/esm/utils/idle.mjs +24 -0
- package/dist/esm/utils/idle.mjs.map +1 -0
- package/dist/types/core/AnalyticsClient.d.ts +51 -0
- package/dist/types/core/AnalyticsClient.d.ts.map +1 -0
- package/dist/types/core/abTesting.d.ts +23 -0
- package/dist/types/core/abTesting.d.ts.map +1 -0
- package/dist/types/core/eventBuffer.d.ts +35 -0
- package/dist/types/core/eventBuffer.d.ts.map +1 -0
- package/dist/types/core/globalManager.d.ts +28 -0
- package/dist/types/core/globalManager.d.ts.map +1 -0
- package/dist/types/core/index.d.ts +10 -0
- package/dist/types/core/initAnalyticsClient.d.ts +28 -0
- package/dist/types/core/initAnalyticsClient.d.ts.map +1 -0
- package/dist/types/core/sampling.d.ts +20 -0
- package/dist/types/core/sampling.d.ts.map +1 -0
- package/dist/types/core/session.d.ts +17 -0
- package/dist/types/core/session.d.ts.map +1 -0
- package/dist/types/core/transport.d.ts +31 -0
- package/dist/types/core/transport.d.ts.map +1 -0
- package/dist/types/core/types.d.ts +87 -0
- package/dist/types/core/types.d.ts.map +1 -0
- package/dist/types/events/contentExposure.d.ts +38 -0
- package/dist/types/events/contentExposure.d.ts.map +1 -0
- package/dist/types/index.d.ts +11 -0
- package/dist/types/isEnabled.d.ts +18 -0
- package/dist/types/isEnabled.d.ts.map +1 -0
- package/dist/types/utils/hash.d.ts +16 -0
- package/dist/types/utils/hash.d.ts.map +1 -0
- package/dist/types/utils/idle.d.ts +15 -0
- package/dist/types/utils/idle.d.ts.map +1 -0
- package/package.json +100 -0
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { onIdle } from "../utils/idle.mjs";
|
|
2
|
+
import { assignVariant } from "./abTesting.mjs";
|
|
3
|
+
import { createEventBuffer } from "./eventBuffer.mjs";
|
|
4
|
+
import { isSampledIn } from "./sampling.mjs";
|
|
5
|
+
import { getSessionId } from "./session.mjs";
|
|
6
|
+
import { sendEvents } from "./transport.mjs";
|
|
7
|
+
|
|
8
|
+
//#region src/core/AnalyticsClient.ts
|
|
9
|
+
/** Default flush cadence — one network request per 20 seconds. */
|
|
10
|
+
const DEFAULT_FLUSH_INTERVAL = 2e4;
|
|
11
|
+
/** Default cap on distinct buffered events before an early flush. */
|
|
12
|
+
const DEFAULT_MAX_BUFFER_SIZE = 500;
|
|
13
|
+
/** Default sampling — keep every session. */
|
|
14
|
+
const DEFAULT_SAMPLE_RATE = 1;
|
|
15
|
+
/**
|
|
16
|
+
* Maximum events per network request. `sendBeacon` and `fetch(keepalive)`
|
|
17
|
+
* reject bodies over ~64KB, so large batches are split into multiple sends.
|
|
18
|
+
*/
|
|
19
|
+
const MAX_EVENTS_PER_SEND = 200;
|
|
20
|
+
/** Identifies the producing SDK in the ingest envelope. */
|
|
21
|
+
const SDK_VERSION = "intlayer-analytics/1";
|
|
22
|
+
/**
|
|
23
|
+
* Reads the current page pathname. Search params are intentionally excluded to
|
|
24
|
+
* avoid capturing anything sensitive.
|
|
25
|
+
*/
|
|
26
|
+
const currentUrl = () => {
|
|
27
|
+
if (typeof window === "undefined" || !window.location) return "";
|
|
28
|
+
return window.location.pathname;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Reduces the referrer to its host — never the full URL — for privacy.
|
|
32
|
+
*/
|
|
33
|
+
const referrerHost = () => {
|
|
34
|
+
if (typeof document === "undefined" || !document.referrer) return void 0;
|
|
35
|
+
try {
|
|
36
|
+
return new URL(document.referrer).host;
|
|
37
|
+
} catch {
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Creates an analytics client. Prefer {@link initAnalyticsClient} in application
|
|
43
|
+
* code — it manages a shared singleton so there is only ever one flush timer.
|
|
44
|
+
*
|
|
45
|
+
* @param config - Resolved client configuration.
|
|
46
|
+
* @returns A started-on-demand {@link AnalyticsClient}.
|
|
47
|
+
*/
|
|
48
|
+
const createAnalyticsClient = (config) => {
|
|
49
|
+
const sessionId = getSessionId();
|
|
50
|
+
const sampledIn = isSampledIn(sessionId, config.sampleRate);
|
|
51
|
+
const buffer = createEventBuffer({ max: config.maxBufferSize });
|
|
52
|
+
const endpoint = `${config.backendURL.replace(/\/$/, "")}/api/analytics/events`;
|
|
53
|
+
let ambientLocale = "";
|
|
54
|
+
let flushTimer = null;
|
|
55
|
+
let started = false;
|
|
56
|
+
let detachListeners = null;
|
|
57
|
+
let seenExposureKeys = /* @__PURE__ */ new Set();
|
|
58
|
+
const flush = (useBeacon = false) => {
|
|
59
|
+
const events = buffer.drain();
|
|
60
|
+
for (let start = 0; start < events.length; start += 200) sendEvents(endpoint, {
|
|
61
|
+
clientId: config.clientId,
|
|
62
|
+
sessionId,
|
|
63
|
+
sdkVersion: SDK_VERSION,
|
|
64
|
+
events: events.slice(start, start + 200)
|
|
65
|
+
}, { useBeacon });
|
|
66
|
+
};
|
|
67
|
+
/** Pushes an event and triggers an early flush if the buffer is full. */
|
|
68
|
+
const enqueue = (event) => {
|
|
69
|
+
if (buffer.push(event) >= config.maxBufferSize) flush();
|
|
70
|
+
};
|
|
71
|
+
const setLocale = (locale) => {
|
|
72
|
+
ambientLocale = locale;
|
|
73
|
+
};
|
|
74
|
+
const trackPageView = (event = {}) => {
|
|
75
|
+
if (!sampledIn) return;
|
|
76
|
+
seenExposureKeys = /* @__PURE__ */ new Set();
|
|
77
|
+
enqueue({
|
|
78
|
+
type: "page_view",
|
|
79
|
+
t: Date.now(),
|
|
80
|
+
url: event.url ?? currentUrl(),
|
|
81
|
+
locale: event.locale ?? ambientLocale,
|
|
82
|
+
ref: event.ref ?? referrerHost(),
|
|
83
|
+
vw: event.vw ?? (typeof window !== "undefined" ? window.innerWidth : void 0),
|
|
84
|
+
vh: event.vh ?? (typeof window !== "undefined" ? window.innerHeight : void 0),
|
|
85
|
+
reason: event.reason ?? "initial"
|
|
86
|
+
});
|
|
87
|
+
};
|
|
88
|
+
const trackContentExposure = (event) => {
|
|
89
|
+
if (!sampledIn) return;
|
|
90
|
+
const locale = event.locale ?? ambientLocale;
|
|
91
|
+
const exposureKey = [
|
|
92
|
+
event.dictionaryKey,
|
|
93
|
+
event.keyPath,
|
|
94
|
+
locale,
|
|
95
|
+
event.experimentKey ?? "",
|
|
96
|
+
event.variant ?? ""
|
|
97
|
+
].join("");
|
|
98
|
+
if (seenExposureKeys.has(exposureKey)) return;
|
|
99
|
+
seenExposureKeys.add(exposureKey);
|
|
100
|
+
enqueue({
|
|
101
|
+
...event,
|
|
102
|
+
type: "content_exposure",
|
|
103
|
+
t: Date.now(),
|
|
104
|
+
url: currentUrl(),
|
|
105
|
+
locale
|
|
106
|
+
});
|
|
107
|
+
};
|
|
108
|
+
const trackConversion = (event) => {
|
|
109
|
+
enqueue({
|
|
110
|
+
...event,
|
|
111
|
+
type: "conversion",
|
|
112
|
+
t: Date.now(),
|
|
113
|
+
url: currentUrl(),
|
|
114
|
+
locale: event.locale ?? ambientLocale
|
|
115
|
+
});
|
|
116
|
+
flush();
|
|
117
|
+
};
|
|
118
|
+
const getVariant = (experimentKey, variants, weights) => assignVariant(sessionId, experimentKey, variants, weights);
|
|
119
|
+
/** Attaches lifecycle + SPA-navigation listeners without blocking render. */
|
|
120
|
+
const attachListeners = () => {
|
|
121
|
+
if (typeof window === "undefined") return;
|
|
122
|
+
const onHidden = () => {
|
|
123
|
+
if (document.visibilityState === "hidden") flush(true);
|
|
124
|
+
};
|
|
125
|
+
const onPageHide = () => flush(true);
|
|
126
|
+
const onPopState = () => trackPageView({ reason: "route_change" });
|
|
127
|
+
document.addEventListener("visibilitychange", onHidden);
|
|
128
|
+
window.addEventListener("pagehide", onPageHide, { capture: true });
|
|
129
|
+
window.addEventListener("popstate", onPopState);
|
|
130
|
+
const history = window.history;
|
|
131
|
+
const originalPush = history.pushState;
|
|
132
|
+
const patchedPushState = function patchedPush(...args) {
|
|
133
|
+
const result = originalPush.apply(this, args);
|
|
134
|
+
trackPageView({ reason: "route_change" });
|
|
135
|
+
return result;
|
|
136
|
+
};
|
|
137
|
+
history.pushState = patchedPushState;
|
|
138
|
+
detachListeners = () => {
|
|
139
|
+
document.removeEventListener("visibilitychange", onHidden);
|
|
140
|
+
window.removeEventListener("pagehide", onPageHide, { capture: true });
|
|
141
|
+
window.removeEventListener("popstate", onPopState);
|
|
142
|
+
if (history.pushState === patchedPushState) history.pushState = originalPush;
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
const start = () => {
|
|
146
|
+
if (started) return;
|
|
147
|
+
started = true;
|
|
148
|
+
flushTimer = setInterval(flush, config.flushInterval);
|
|
149
|
+
flushTimer?.unref?.();
|
|
150
|
+
onIdle(attachListeners);
|
|
151
|
+
};
|
|
152
|
+
const stop = () => {
|
|
153
|
+
if (!started) return;
|
|
154
|
+
started = false;
|
|
155
|
+
if (flushTimer) {
|
|
156
|
+
clearInterval(flushTimer);
|
|
157
|
+
flushTimer = null;
|
|
158
|
+
}
|
|
159
|
+
detachListeners?.();
|
|
160
|
+
detachListeners = null;
|
|
161
|
+
flush(true);
|
|
162
|
+
};
|
|
163
|
+
return {
|
|
164
|
+
setLocale,
|
|
165
|
+
trackPageView,
|
|
166
|
+
trackContentExposure,
|
|
167
|
+
trackConversion,
|
|
168
|
+
getVariant,
|
|
169
|
+
flush,
|
|
170
|
+
start,
|
|
171
|
+
stop
|
|
172
|
+
};
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
//#endregion
|
|
176
|
+
export { DEFAULT_FLUSH_INTERVAL, DEFAULT_MAX_BUFFER_SIZE, DEFAULT_SAMPLE_RATE, MAX_EVENTS_PER_SEND, createAnalyticsClient };
|
|
177
|
+
//# sourceMappingURL=AnalyticsClient.mjs.map
|
|
@@ -0,0 +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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"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { hashString } from "../utils/hash.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/core/abTesting.ts
|
|
4
|
+
/**
|
|
5
|
+
* Deterministically assigns a variant to a session for a given experiment.
|
|
6
|
+
*
|
|
7
|
+
* The assignment is a pure function of `sessionId` + `experimentKey`, so it is
|
|
8
|
+
* stable for the whole session and requires **no** server round-trip before the
|
|
9
|
+
* first render — avoiding layout shift / content flicker. Optional `weights`
|
|
10
|
+
* bias the split (e.g. `[0.9, 0.1]` for a 90/10 rollout).
|
|
11
|
+
*
|
|
12
|
+
* @param sessionId - The current anonymous session id.
|
|
13
|
+
* @param experimentKey - Unique key identifying the experiment.
|
|
14
|
+
* @param variants - The candidate variant names (at least one).
|
|
15
|
+
* @param weights - Optional relative weights, one per variant.
|
|
16
|
+
* @returns The variant assigned to this session.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* assignVariant('sid-1', 'homepage-hero', ['a', 'b']); // stable 'a' | 'b'
|
|
20
|
+
* assignVariant('sid-1', 'homepage-hero', ['a', 'b'], [9, 1]); // ~90% 'a'
|
|
21
|
+
*/
|
|
22
|
+
const assignVariant = (sessionId, experimentKey, variants, weights) => {
|
|
23
|
+
if (variants.length === 0) throw new Error("assignVariant requires at least one variant");
|
|
24
|
+
if (variants.length === 1) return variants[0];
|
|
25
|
+
const bucket = hashString(`${sessionId}:${experimentKey}`) / 4294967296;
|
|
26
|
+
if (!weights || weights.length !== variants.length) {
|
|
27
|
+
const index = Math.floor(bucket * variants.length);
|
|
28
|
+
return variants[Math.min(index, variants.length - 1)];
|
|
29
|
+
}
|
|
30
|
+
const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);
|
|
31
|
+
if (totalWeight <= 0) return variants[Math.floor(bucket * variants.length)];
|
|
32
|
+
let cumulative = 0;
|
|
33
|
+
const target = bucket * totalWeight;
|
|
34
|
+
for (let index = 0; index < variants.length; index++) {
|
|
35
|
+
cumulative += weights[index];
|
|
36
|
+
if (target < cumulative) return variants[index];
|
|
37
|
+
}
|
|
38
|
+
return variants[variants.length - 1];
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
//#endregion
|
|
42
|
+
export { assignVariant };
|
|
43
|
+
//# sourceMappingURL=abTesting.mjs.map
|
|
@@ -0,0 +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"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
//#region src/core/eventBuffer.ts
|
|
2
|
+
/** Field separator for coalescing keys — never present in content keys. */
|
|
3
|
+
const KEY_SEPARATOR = "";
|
|
4
|
+
/**
|
|
5
|
+
* Builds the coalescing key for a content-exposure event. Two exposures of the
|
|
6
|
+
* same node, page, locale, experiment, and variant collapse into one event with
|
|
7
|
+
* an incremented `count`.
|
|
8
|
+
*/
|
|
9
|
+
const exposureKey = (event) => [
|
|
10
|
+
event.url,
|
|
11
|
+
event.dictionaryKey,
|
|
12
|
+
event.keyPath,
|
|
13
|
+
event.locale,
|
|
14
|
+
event.experimentKey ?? "",
|
|
15
|
+
event.variant ?? ""
|
|
16
|
+
].join(KEY_SEPARATOR);
|
|
17
|
+
/**
|
|
18
|
+
* Creates an {@link EventBuffer}.
|
|
19
|
+
*
|
|
20
|
+
* @param options - Buffer options.
|
|
21
|
+
* @param options.max - Maximum number of distinct events to retain.
|
|
22
|
+
* @returns A new buffer instance.
|
|
23
|
+
*/
|
|
24
|
+
const createEventBuffer = ({ max }) => {
|
|
25
|
+
let discreteEvents = [];
|
|
26
|
+
const exposures = /* @__PURE__ */ new Map();
|
|
27
|
+
const size = () => discreteEvents.length + exposures.size;
|
|
28
|
+
/** Evicts oldest exposures first, then oldest discrete events. */
|
|
29
|
+
const enforceCap = () => {
|
|
30
|
+
while (size() > max && exposures.size > 0) {
|
|
31
|
+
const oldestKey = exposures.keys().next().value;
|
|
32
|
+
exposures.delete(oldestKey);
|
|
33
|
+
}
|
|
34
|
+
if (size() > max) discreteEvents = discreteEvents.slice(size() - max);
|
|
35
|
+
};
|
|
36
|
+
const push = (event) => {
|
|
37
|
+
if (event.type === "content_exposure") {
|
|
38
|
+
const key = exposureKey(event);
|
|
39
|
+
const existing = exposures.get(key);
|
|
40
|
+
if (existing) {
|
|
41
|
+
existing.count = (existing.count ?? 1) + (event.count ?? 1);
|
|
42
|
+
existing.t = event.t;
|
|
43
|
+
} else exposures.set(key, {
|
|
44
|
+
...event,
|
|
45
|
+
count: event.count ?? 1
|
|
46
|
+
});
|
|
47
|
+
} else discreteEvents.push(event);
|
|
48
|
+
enforceCap();
|
|
49
|
+
return size();
|
|
50
|
+
};
|
|
51
|
+
const drain = () => {
|
|
52
|
+
const drained = [...discreteEvents, ...exposures.values()];
|
|
53
|
+
discreteEvents = [];
|
|
54
|
+
exposures.clear();
|
|
55
|
+
return drained;
|
|
56
|
+
};
|
|
57
|
+
return {
|
|
58
|
+
push,
|
|
59
|
+
drain,
|
|
60
|
+
size
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
//#endregion
|
|
65
|
+
export { createEventBuffer };
|
|
66
|
+
//# sourceMappingURL=eventBuffer.mjs.map
|
|
@@ -0,0 +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"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
//#region src/core/globalManager.ts
|
|
2
|
+
/**
|
|
3
|
+
* Key on `window` used to share the client singleton across multiple module
|
|
4
|
+
* instances. When bundlers include `@intlayer/analytics` more than once (e.g.
|
|
5
|
+
* a framework package plus the app), each copy has its own module-level
|
|
6
|
+
* variables; storing the client on `window` ensures they all share one buffer
|
|
7
|
+
* and one flush timer.
|
|
8
|
+
*/
|
|
9
|
+
const CLIENT_KEY = "__intlayer_analytics_client__";
|
|
10
|
+
/**
|
|
11
|
+
* Key on `window` holding the provider reference count. It lives next to the
|
|
12
|
+
* client (rather than in module scope) for the same reason the client does:
|
|
13
|
+
* duplicated module instances must share one count, otherwise one copy's
|
|
14
|
+
* `stopAnalyticsClient` could stop a client another copy still uses.
|
|
15
|
+
*/
|
|
16
|
+
const REF_COUNT_KEY = "__intlayer_analytics_ref_count__";
|
|
17
|
+
/**
|
|
18
|
+
* Returns the global analytics client, or `null` in SSR or before init.
|
|
19
|
+
*/
|
|
20
|
+
const getGlobalAnalyticsClient = () => {
|
|
21
|
+
if (typeof window === "undefined") return null;
|
|
22
|
+
return window[CLIENT_KEY] ?? null;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Sets (or clears) the global analytics client singleton.
|
|
26
|
+
*
|
|
27
|
+
* @param client - The client to store globally, or `null` to clear it.
|
|
28
|
+
*/
|
|
29
|
+
const setGlobalAnalyticsClient = (client) => {
|
|
30
|
+
if (typeof window === "undefined") return;
|
|
31
|
+
window[CLIENT_KEY] = client;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Increments the shared provider reference count.
|
|
35
|
+
*
|
|
36
|
+
* @returns The count after incrementing (`0` in SSR, where nothing is stored).
|
|
37
|
+
*/
|
|
38
|
+
const incrementAnalyticsClientRefCount = () => {
|
|
39
|
+
if (typeof window === "undefined") return 0;
|
|
40
|
+
const globals = window;
|
|
41
|
+
globals[REF_COUNT_KEY] = (globals[REF_COUNT_KEY] ?? 0) + 1;
|
|
42
|
+
return globals[REF_COUNT_KEY];
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Decrements the shared provider reference count, clamping at zero.
|
|
46
|
+
*
|
|
47
|
+
* @returns The count after decrementing (`0` in SSR, where nothing is stored).
|
|
48
|
+
*/
|
|
49
|
+
const decrementAnalyticsClientRefCount = () => {
|
|
50
|
+
if (typeof window === "undefined") return 0;
|
|
51
|
+
const globals = window;
|
|
52
|
+
globals[REF_COUNT_KEY] = Math.max(0, (globals[REF_COUNT_KEY] ?? 0) - 1);
|
|
53
|
+
return globals[REF_COUNT_KEY];
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
//#endregion
|
|
57
|
+
export { decrementAnalyticsClientRefCount, getGlobalAnalyticsClient, incrementAnalyticsClientRefCount, setGlobalAnalyticsClient };
|
|
58
|
+
//# sourceMappingURL=globalManager.mjs.map
|
|
@@ -0,0 +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"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { assignVariant } from "./abTesting.mjs";
|
|
2
|
+
import { createEventBuffer } from "./eventBuffer.mjs";
|
|
3
|
+
import { isSampledIn } from "./sampling.mjs";
|
|
4
|
+
import { getSessionId } from "./session.mjs";
|
|
5
|
+
import { sendEvents } from "./transport.mjs";
|
|
6
|
+
import { DEFAULT_FLUSH_INTERVAL, DEFAULT_MAX_BUFFER_SIZE, DEFAULT_SAMPLE_RATE, MAX_EVENTS_PER_SEND, createAnalyticsClient } from "./AnalyticsClient.mjs";
|
|
7
|
+
import { decrementAnalyticsClientRefCount, getGlobalAnalyticsClient, incrementAnalyticsClientRefCount, setGlobalAnalyticsClient } from "./globalManager.mjs";
|
|
8
|
+
import { initAnalyticsClient, stopAnalyticsClient } from "./initAnalyticsClient.mjs";
|
|
9
|
+
|
|
10
|
+
export { DEFAULT_FLUSH_INTERVAL, DEFAULT_MAX_BUFFER_SIZE, DEFAULT_SAMPLE_RATE, MAX_EVENTS_PER_SEND, assignVariant, createAnalyticsClient, createEventBuffer, decrementAnalyticsClientRefCount, getGlobalAnalyticsClient, getSessionId, incrementAnalyticsClientRefCount, initAnalyticsClient, isSampledIn, sendEvents, setGlobalAnalyticsClient, stopAnalyticsClient };
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { DEFAULT_FLUSH_INTERVAL, DEFAULT_MAX_BUFFER_SIZE, DEFAULT_SAMPLE_RATE, createAnalyticsClient } from "./AnalyticsClient.mjs";
|
|
2
|
+
import { decrementAnalyticsClientRefCount, getGlobalAnalyticsClient, incrementAnalyticsClientRefCount, setGlobalAnalyticsClient } from "./globalManager.mjs";
|
|
3
|
+
import { analytics, editor } from "@intlayer/config/built";
|
|
4
|
+
|
|
5
|
+
//#region src/core/initAnalyticsClient.ts
|
|
6
|
+
/**
|
|
7
|
+
* Initializes the Intlayer analytics client singleton.
|
|
8
|
+
*
|
|
9
|
+
* Behavior comes from the `analytics` config block (`flushInterval`,
|
|
10
|
+
* `sampleRate`); attribution reuses the existing `editor` config
|
|
11
|
+
* (`editor.backendURL` for the endpoint, `editor.clientId` for the project).
|
|
12
|
+
*
|
|
13
|
+
* Safe to call multiple times: returns the existing client and increments a
|
|
14
|
+
* `window`-shared reference count so nested providers (or duplicated module
|
|
15
|
+
* instances) don't stop the client prematurely.
|
|
16
|
+
*
|
|
17
|
+
* @returns The started analytics client singleton.
|
|
18
|
+
*/
|
|
19
|
+
const initAnalyticsClient = () => {
|
|
20
|
+
incrementAnalyticsClientRefCount();
|
|
21
|
+
const existing = getGlobalAnalyticsClient();
|
|
22
|
+
if (existing) return existing;
|
|
23
|
+
const client = createAnalyticsClient({
|
|
24
|
+
backendURL: editor?.backendURL ?? "",
|
|
25
|
+
clientId: editor?.clientId,
|
|
26
|
+
flushInterval: analytics?.flushInterval ?? 2e4,
|
|
27
|
+
maxBufferSize: 500,
|
|
28
|
+
sampleRate: analytics?.sampleRate ?? 1
|
|
29
|
+
});
|
|
30
|
+
setGlobalAnalyticsClient(client);
|
|
31
|
+
client.start();
|
|
32
|
+
return client;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Decrements the shared reference count and stops the global analytics client
|
|
36
|
+
* only when the last provider unmounts (flushing any remaining events).
|
|
37
|
+
*
|
|
38
|
+
* Callers must pair each `stopAnalyticsClient` with a prior
|
|
39
|
+
* `initAnalyticsClient` — never call it when init was skipped or cancelled.
|
|
40
|
+
*/
|
|
41
|
+
const stopAnalyticsClient = () => {
|
|
42
|
+
if (decrementAnalyticsClientRefCount() > 0) return;
|
|
43
|
+
getGlobalAnalyticsClient()?.stop();
|
|
44
|
+
setGlobalAnalyticsClient(null);
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
//#endregion
|
|
48
|
+
export { initAnalyticsClient, stopAnalyticsClient };
|
|
49
|
+
//# sourceMappingURL=initAnalyticsClient.mjs.map
|
|
@@ -0,0 +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"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { hashString } from "../utils/hash.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/core/sampling.ts
|
|
4
|
+
/**
|
|
5
|
+
* Deterministic per-session sampling gate. Using the session id (rather than a
|
|
6
|
+
* fresh random draw per event) means a sampled-in session reports *all* of its
|
|
7
|
+
* content exposures, keeping per-session funnels consistent instead of leaving
|
|
8
|
+
* holes.
|
|
9
|
+
*
|
|
10
|
+
* @param sessionId - The current anonymous session id.
|
|
11
|
+
* @param sampleRate - Fraction of sessions to keep, from 0 (none) to 1 (all).
|
|
12
|
+
* @returns `true` when this session's events should be recorded.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* isSampledIn('abc', 1); // always true
|
|
16
|
+
* isSampledIn('abc', 0); // always false
|
|
17
|
+
* isSampledIn('abc', 0.5); // stable per session
|
|
18
|
+
*/
|
|
19
|
+
const isSampledIn = (sessionId, sampleRate) => {
|
|
20
|
+
if (sampleRate >= 1) return true;
|
|
21
|
+
if (sampleRate <= 0) return false;
|
|
22
|
+
return hashString(sessionId) / 4294967295 < sampleRate;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
//#endregion
|
|
26
|
+
export { isSampledIn };
|
|
27
|
+
//# sourceMappingURL=sampling.mjs.map
|
|
@@ -0,0 +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"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
//#region src/core/session.ts
|
|
2
|
+
/**
|
|
3
|
+
* Anonymous, per-tab session identity. Stored in `sessionStorage` so it is
|
|
4
|
+
* cleared when the tab closes and is never shared across sites — no durable
|
|
5
|
+
* cookie, no cross-site tracking, no PII.
|
|
6
|
+
*/
|
|
7
|
+
const SESSION_STORAGE_KEY = "__intlayer_analytics_sid__";
|
|
8
|
+
/**
|
|
9
|
+
* Generates a random, opaque session identifier.
|
|
10
|
+
*
|
|
11
|
+
* @returns A URL-safe random string.
|
|
12
|
+
*/
|
|
13
|
+
const generateSessionId = () => {
|
|
14
|
+
const cryptoObj = typeof globalThis !== "undefined" ? globalThis.crypto : void 0;
|
|
15
|
+
if (cryptoObj?.randomUUID) return cryptoObj.randomUUID();
|
|
16
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Returns the current session id, creating and persisting one on first access.
|
|
20
|
+
* Degrades gracefully to an in-memory id when `sessionStorage` is unavailable
|
|
21
|
+
* (private mode, native runtimes).
|
|
22
|
+
*
|
|
23
|
+
* @returns The stable session id for the lifetime of the tab.
|
|
24
|
+
*/
|
|
25
|
+
const getSessionId = () => {
|
|
26
|
+
if (typeof window === "undefined" || !window.sessionStorage) return generateSessionId();
|
|
27
|
+
try {
|
|
28
|
+
const existing = window.sessionStorage.getItem(SESSION_STORAGE_KEY);
|
|
29
|
+
if (existing) return existing;
|
|
30
|
+
const created = generateSessionId();
|
|
31
|
+
window.sessionStorage.setItem(SESSION_STORAGE_KEY, created);
|
|
32
|
+
return created;
|
|
33
|
+
} catch {
|
|
34
|
+
return generateSessionId();
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
//#endregion
|
|
39
|
+
export { getSessionId };
|
|
40
|
+
//# sourceMappingURL=session.mjs.map
|
|
@@ -0,0 +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"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
//#region src/core/transport.ts
|
|
2
|
+
/**
|
|
3
|
+
* Sends a batch of events to the backend. Every path is non-blocking and
|
|
4
|
+
* no-throw — analytics must never break, slow, or delay the host application.
|
|
5
|
+
*
|
|
6
|
+
* Strategy:
|
|
7
|
+
* 1. `navigator.sendBeacon` for the flush-on-hide path — survives page unload
|
|
8
|
+
* and never blocks navigation. The payload is sent as `text/plain` (a
|
|
9
|
+
* CORS-safelisted content type): a JSON `Blob` would require a CORS
|
|
10
|
+
* preflight that browsers handle inconsistently during unload, silently
|
|
11
|
+
* dropping the beacon. The backend parses `text/plain` bodies as JSON.
|
|
12
|
+
* 2. `fetch(..., { keepalive: true })` for interval flushes — survives short
|
|
13
|
+
* navigations without holding the main thread.
|
|
14
|
+
* 3. Plain `fetch` fallback for runtimes without `keepalive` (older RN/Lynx).
|
|
15
|
+
*
|
|
16
|
+
* @param endpoint - Fully-qualified ingestion URL.
|
|
17
|
+
* @param body - The batched payload.
|
|
18
|
+
* @param options - Transport options.
|
|
19
|
+
* @param options.useBeacon - Prefer `sendBeacon` (used when the page is hiding).
|
|
20
|
+
* @returns `true` when a send was dispatched, `false` otherwise.
|
|
21
|
+
*/
|
|
22
|
+
const sendEvents = (endpoint, body, { useBeacon = false } = {}) => {
|
|
23
|
+
try {
|
|
24
|
+
const payload = JSON.stringify(body);
|
|
25
|
+
if (useBeacon && typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function") return navigator.sendBeacon(endpoint, payload);
|
|
26
|
+
if (typeof fetch === "function") {
|
|
27
|
+
fetch(endpoint, {
|
|
28
|
+
method: "POST",
|
|
29
|
+
headers: { "Content-Type": "application/json" },
|
|
30
|
+
body: payload,
|
|
31
|
+
keepalive: true,
|
|
32
|
+
credentials: "omit",
|
|
33
|
+
mode: "cors"
|
|
34
|
+
}).catch(() => {});
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
37
|
+
return false;
|
|
38
|
+
} catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
//#endregion
|
|
44
|
+
export { sendEvents };
|
|
45
|
+
//# sourceMappingURL=transport.mjs.map
|
|
@@ -0,0 +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"}
|
|
File without changes
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
//#region src/events/contentExposure.ts
|
|
2
|
+
/**
|
|
3
|
+
* Serializes a `KeyPath[]` into a compact, stable string used both as the
|
|
4
|
+
* coalescing key in the buffer and as the stored `keyPath` on the wire.
|
|
5
|
+
*
|
|
6
|
+
* Only the `key` of each segment is kept (types are implied by the dictionary
|
|
7
|
+
* shape), producing paths like `"faq.items.2.answer"`.
|
|
8
|
+
*
|
|
9
|
+
* @param keyPath - The interpreter key path locating a node.
|
|
10
|
+
* @returns A dot-joined, stable path string.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* serializeKeyPath([{ type: 'object', key: 'faq' }, { type: 'array', key: 2 }]);
|
|
14
|
+
* // "faq.2"
|
|
15
|
+
*/
|
|
16
|
+
const serializeKeyPath = (keyPath) => keyPath.map((segment) => segment.key === void 0 ? "*" : String(segment.key)).join(".");
|
|
17
|
+
/**
|
|
18
|
+
* Builds a content-exposure payload from interpreter node metadata. Shared by
|
|
19
|
+
* every framework binding's analytics node plugin so the wire shape stays
|
|
20
|
+
* identical across React, Vue, Svelte, Angular, etc.
|
|
21
|
+
*
|
|
22
|
+
* @param params - Node metadata available on `NodeProps`.
|
|
23
|
+
* @returns A trackable content-exposure event (minus buffer-stamped fields).
|
|
24
|
+
*/
|
|
25
|
+
const buildContentExposure = (params) => ({
|
|
26
|
+
dictionaryKey: params.dictionaryKey,
|
|
27
|
+
keyPath: serializeKeyPath(params.keyPath),
|
|
28
|
+
locale: params.locale,
|
|
29
|
+
nodeType: params.nodeType,
|
|
30
|
+
experimentKey: params.experimentKey,
|
|
31
|
+
variant: params.variant
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
//#endregion
|
|
35
|
+
export { buildContentExposure, serializeKeyPath };
|
|
36
|
+
//# sourceMappingURL=contentExposure.mjs.map
|