@faceyoga/analytics 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-J4RHGPNT.js +233 -0
- package/dist/chunk-J4RHGPNT.js.map +1 -0
- package/dist/client.d.ts +99 -0
- package/dist/client.js +320 -0
- package/dist/client.js.map +1 -0
- package/dist/names-CWW29ek_.d.ts +63 -0
- package/dist/server.d.ts +255 -0
- package/dist/server.js +323 -0
- package/dist/server.js.map +1 -0
- package/package.json +43 -3
- package/README.md +0 -3
package/dist/client.js
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
import { uuid, readPreviewState, QA_MAX_AGE_SECONDS, PREVIEW_COOKIE, notFound, EventNames, toExperiment, QA_COOKIE, LIBRARY, toEventName, cleanProps } from './chunk-J4RHGPNT.js';
|
|
2
|
+
export { EventNames } from './chunk-J4RHGPNT.js';
|
|
3
|
+
|
|
4
|
+
// src/client/storage.ts
|
|
5
|
+
function readCookie(name) {
|
|
6
|
+
if (typeof document === "undefined") return void 0;
|
|
7
|
+
try {
|
|
8
|
+
const prefix = `${encodeURIComponent(name)}=`;
|
|
9
|
+
for (const part of document.cookie.split(";")) {
|
|
10
|
+
const trimmed = part.trim();
|
|
11
|
+
if (trimmed.startsWith(prefix)) return decodeURIComponent(trimmed.slice(prefix.length)) || void 0;
|
|
12
|
+
}
|
|
13
|
+
} catch {
|
|
14
|
+
}
|
|
15
|
+
return void 0;
|
|
16
|
+
}
|
|
17
|
+
function writeCookie(name, value, maxAgeSeconds) {
|
|
18
|
+
if (typeof document === "undefined") return;
|
|
19
|
+
try {
|
|
20
|
+
const secure = typeof location !== "undefined" && location.protocol === "https:" ? "; Secure" : "";
|
|
21
|
+
document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}; Path=/; Max-Age=${maxAgeSeconds}; SameSite=Lax${secure}`;
|
|
22
|
+
} catch {
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function readJson(kind, key) {
|
|
26
|
+
try {
|
|
27
|
+
const raw = globalThis[kind]?.getItem(key);
|
|
28
|
+
return raw ? JSON.parse(raw) : void 0;
|
|
29
|
+
} catch {
|
|
30
|
+
return void 0;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function writeJson(kind, key, value) {
|
|
34
|
+
try {
|
|
35
|
+
globalThis[kind]?.setItem(key, JSON.stringify(value));
|
|
36
|
+
} catch {
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// src/client/index.ts
|
|
41
|
+
var OWN_ANON_COOKIE = "fya_aid";
|
|
42
|
+
var USER_KEY = "fya_uid";
|
|
43
|
+
var SESSION_KEY = "fya_session";
|
|
44
|
+
var EXPOSED_KEY = "fya_exposed";
|
|
45
|
+
var ONE_YEAR = 365 * 24 * 60 * 60;
|
|
46
|
+
function createNoop() {
|
|
47
|
+
const empty = toExperiment(notFound(""));
|
|
48
|
+
return {
|
|
49
|
+
track: () => "",
|
|
50
|
+
page: () => "",
|
|
51
|
+
identify: () => {
|
|
52
|
+
},
|
|
53
|
+
reset: () => {
|
|
54
|
+
},
|
|
55
|
+
getExperiment: (key) => ({ ...empty, key }),
|
|
56
|
+
setAssignments: () => {
|
|
57
|
+
},
|
|
58
|
+
getAnonymousId: () => "",
|
|
59
|
+
getSessionId: () => "",
|
|
60
|
+
isQa: () => false,
|
|
61
|
+
flush: async () => {
|
|
62
|
+
},
|
|
63
|
+
shutdown: () => {
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
function createFetchTransport(endpoint) {
|
|
68
|
+
return {
|
|
69
|
+
async send(body, { beacon }) {
|
|
70
|
+
if (beacon && typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function") {
|
|
71
|
+
try {
|
|
72
|
+
if (navigator.sendBeacon(endpoint, new Blob([body], { type: "text/plain;charset=UTF-8" }))) return "ok";
|
|
73
|
+
} catch {
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
try {
|
|
77
|
+
const response = await fetch(endpoint, {
|
|
78
|
+
method: "POST",
|
|
79
|
+
body,
|
|
80
|
+
headers: { "Content-Type": "text/plain;charset=UTF-8" },
|
|
81
|
+
// keepalive bodies are capped at 64 KB per page.
|
|
82
|
+
keepalive: body.length < 6e4,
|
|
83
|
+
credentials: "omit"
|
|
84
|
+
});
|
|
85
|
+
if (response.ok) return "ok";
|
|
86
|
+
return response.status === 429 || response.status >= 500 ? "retry" : "drop";
|
|
87
|
+
} catch {
|
|
88
|
+
return "retry";
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function createAnalytics(options) {
|
|
94
|
+
if (typeof window === "undefined" || options.disabled) return createNoop();
|
|
95
|
+
if ((options.ignoreAutomation ?? true) && typeof navigator !== "undefined" && navigator.webdriver) {
|
|
96
|
+
return createNoop();
|
|
97
|
+
}
|
|
98
|
+
const flushIntervalMs = options.flushIntervalMs ?? 3e3;
|
|
99
|
+
const maxBatchSize = Math.min(options.maxBatchSize ?? 20, 100);
|
|
100
|
+
const maxQueueSize = options.maxQueueSize ?? 500;
|
|
101
|
+
const sessionTimeoutMs = options.sessionTimeoutMs ?? 30 * 60 * 1e3;
|
|
102
|
+
const environment = options.environment ?? options.bootstrap?.environment ?? "unknown";
|
|
103
|
+
const transport = options.transport ?? createFetchTransport(options.endpoint);
|
|
104
|
+
const log = (...args) => {
|
|
105
|
+
if (options.debug) console.debug("[analytics]", ...args);
|
|
106
|
+
};
|
|
107
|
+
let anonymousId = options.anonymousId || (options.anonymousIdCookie ? readCookie(options.anonymousIdCookie) : void 0) || readCookie(OWN_ANON_COOKIE) || "";
|
|
108
|
+
if (!anonymousId) {
|
|
109
|
+
anonymousId = uuid();
|
|
110
|
+
writeCookie(OWN_ANON_COOKIE, anonymousId, ONE_YEAR);
|
|
111
|
+
}
|
|
112
|
+
let userId = options.userId || readJson("localStorage", USER_KEY);
|
|
113
|
+
if (options.userId) writeJson("localStorage", USER_KEY, options.userId);
|
|
114
|
+
const preview = readPreviewState(typeof location !== "undefined" ? location.search : "", readCookie);
|
|
115
|
+
if (preview.change?.action === "set") {
|
|
116
|
+
writeCookie(QA_COOKIE, "1", QA_MAX_AGE_SECONDS);
|
|
117
|
+
writeCookie(PREVIEW_COOKIE, preview.change.preview, preview.change.preview ? QA_MAX_AGE_SECONDS : 0);
|
|
118
|
+
} else if (preview.change?.action === "clear") {
|
|
119
|
+
writeCookie(QA_COOKIE, "", 0);
|
|
120
|
+
writeCookie(PREVIEW_COOKIE, "", 0);
|
|
121
|
+
}
|
|
122
|
+
const isQa = () => preview.qa || Boolean(readCookie(QA_COOKIE));
|
|
123
|
+
if (preview.qa) log("QA mode: events from this browser are stored with environment `test`");
|
|
124
|
+
const bootstrapAssignments = options.bootstrap?.assignments ?? {};
|
|
125
|
+
let assignments = { ...options.assignments };
|
|
126
|
+
for (const assignment of Object.values(bootstrapAssignments)) {
|
|
127
|
+
if ((assignment.reason === "assigned" || assignment.reason === "preview") && assignment.variant) {
|
|
128
|
+
assignments[assignment.experiment] = assignment.variant;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
const exposed = new Set(readJson("sessionStorage", EXPOSED_KEY) ?? []);
|
|
132
|
+
let sessionId = "";
|
|
133
|
+
function touchSession(now) {
|
|
134
|
+
const stored = readJson("localStorage", SESSION_KEY);
|
|
135
|
+
const isNew = !stored || now - stored.last > sessionTimeoutMs;
|
|
136
|
+
sessionId = isNew ? uuid() : stored.id;
|
|
137
|
+
writeJson("localStorage", SESSION_KEY, { id: sessionId, last: now });
|
|
138
|
+
return isNew;
|
|
139
|
+
}
|
|
140
|
+
const queue = [];
|
|
141
|
+
let timer;
|
|
142
|
+
let flushing = false;
|
|
143
|
+
let backoffMs = 0;
|
|
144
|
+
const serialize = (events) => JSON.stringify({
|
|
145
|
+
writeKey: options.writeKey,
|
|
146
|
+
sentAt: Date.now(),
|
|
147
|
+
source: "client",
|
|
148
|
+
environment,
|
|
149
|
+
...isQa() && { qa: true },
|
|
150
|
+
library: LIBRARY,
|
|
151
|
+
events
|
|
152
|
+
});
|
|
153
|
+
function trimQueue() {
|
|
154
|
+
if (queue.length > maxQueueSize) queue.splice(0, queue.length - maxQueueSize);
|
|
155
|
+
}
|
|
156
|
+
function schedule() {
|
|
157
|
+
if (timer || queue.length === 0) return;
|
|
158
|
+
timer = setTimeout(() => {
|
|
159
|
+
timer = void 0;
|
|
160
|
+
void flush();
|
|
161
|
+
}, flushIntervalMs + backoffMs);
|
|
162
|
+
}
|
|
163
|
+
async function flush() {
|
|
164
|
+
if (flushing) return;
|
|
165
|
+
flushing = true;
|
|
166
|
+
if (timer) {
|
|
167
|
+
clearTimeout(timer);
|
|
168
|
+
timer = void 0;
|
|
169
|
+
}
|
|
170
|
+
try {
|
|
171
|
+
while (queue.length) {
|
|
172
|
+
const events = queue.splice(0, maxBatchSize);
|
|
173
|
+
const result = await transport.send(serialize(events), { beacon: false });
|
|
174
|
+
log("flush", events.length, result);
|
|
175
|
+
if (result === "retry") {
|
|
176
|
+
queue.unshift(...events);
|
|
177
|
+
trimQueue();
|
|
178
|
+
backoffMs = Math.min(backoffMs ? backoffMs * 2 : 1e3, 3e4);
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
backoffMs = 0;
|
|
182
|
+
}
|
|
183
|
+
} finally {
|
|
184
|
+
flushing = false;
|
|
185
|
+
schedule();
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
function drainWithBeacon() {
|
|
189
|
+
if (timer) {
|
|
190
|
+
clearTimeout(timer);
|
|
191
|
+
timer = void 0;
|
|
192
|
+
}
|
|
193
|
+
while (queue.length) void transport.send(serialize(queue.splice(0, maxBatchSize)), { beacon: true });
|
|
194
|
+
}
|
|
195
|
+
function enqueue(event) {
|
|
196
|
+
queue.push(event);
|
|
197
|
+
trimQueue();
|
|
198
|
+
log("track", event.name, event);
|
|
199
|
+
if (queue.length >= maxBatchSize) void flush();
|
|
200
|
+
else schedule();
|
|
201
|
+
}
|
|
202
|
+
function build(name, props, extra = {}) {
|
|
203
|
+
const event = {
|
|
204
|
+
id: extra.id || uuid(),
|
|
205
|
+
name: toEventName(name),
|
|
206
|
+
ts: Date.now(),
|
|
207
|
+
anonymousId,
|
|
208
|
+
sessionId,
|
|
209
|
+
url: location.href.slice(0, 2048)
|
|
210
|
+
};
|
|
211
|
+
if (userId) event.userId = userId;
|
|
212
|
+
if (extra.value !== void 0 && Number.isFinite(extra.value)) event.value = extra.value;
|
|
213
|
+
if (extra.currency) event.currency = extra.currency;
|
|
214
|
+
if (extra.orderId) event.orderId = extra.orderId;
|
|
215
|
+
if (extra.referrer) event.referrer = extra.referrer.slice(0, 2048);
|
|
216
|
+
if (Object.keys(assignments).length) event.experiments = { ...assignments };
|
|
217
|
+
const cleaned = cleanProps(props);
|
|
218
|
+
if (cleaned) event.props = cleaned;
|
|
219
|
+
return event;
|
|
220
|
+
}
|
|
221
|
+
function track(name, props, extra) {
|
|
222
|
+
if (touchSession(Date.now())) {
|
|
223
|
+
enqueue(build(EventNames.SessionStart, { landing_url: location.href, referrer: document.referrer || null }));
|
|
224
|
+
}
|
|
225
|
+
const event = build(name, props, extra);
|
|
226
|
+
enqueue(event);
|
|
227
|
+
return event.id;
|
|
228
|
+
}
|
|
229
|
+
let lastPageUrl;
|
|
230
|
+
let previousUrl;
|
|
231
|
+
function page(props) {
|
|
232
|
+
const href = location.href;
|
|
233
|
+
const referrer = previousUrl ?? (document.referrer || void 0);
|
|
234
|
+
previousUrl = href;
|
|
235
|
+
lastPageUrl = href;
|
|
236
|
+
return track(
|
|
237
|
+
EventNames.PageView,
|
|
238
|
+
{ path: location.pathname, title: document.title || null, ...props },
|
|
239
|
+
referrer ? { referrer } : void 0
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
const cleanups = [];
|
|
243
|
+
if (options.autocapture?.pageViews ?? true) {
|
|
244
|
+
const onNavigate = () => {
|
|
245
|
+
setTimeout(() => {
|
|
246
|
+
const href = location.href.split("#")[0];
|
|
247
|
+
if (href !== lastPageUrl?.split("#")[0]) page();
|
|
248
|
+
}, 0);
|
|
249
|
+
};
|
|
250
|
+
const { pushState, replaceState } = history;
|
|
251
|
+
history.pushState = function(...args) {
|
|
252
|
+
pushState.apply(this, args);
|
|
253
|
+
onNavigate();
|
|
254
|
+
};
|
|
255
|
+
history.replaceState = function(...args) {
|
|
256
|
+
replaceState.apply(this, args);
|
|
257
|
+
onNavigate();
|
|
258
|
+
};
|
|
259
|
+
window.addEventListener("popstate", onNavigate);
|
|
260
|
+
cleanups.push(() => {
|
|
261
|
+
history.pushState = pushState;
|
|
262
|
+
history.replaceState = replaceState;
|
|
263
|
+
window.removeEventListener("popstate", onNavigate);
|
|
264
|
+
});
|
|
265
|
+
setTimeout(() => {
|
|
266
|
+
if (!lastPageUrl) page();
|
|
267
|
+
}, 0);
|
|
268
|
+
}
|
|
269
|
+
const onHide = () => {
|
|
270
|
+
if (document.visibilityState === "hidden") drainWithBeacon();
|
|
271
|
+
};
|
|
272
|
+
document.addEventListener("visibilitychange", onHide);
|
|
273
|
+
window.addEventListener("pagehide", drainWithBeacon);
|
|
274
|
+
cleanups.push(() => {
|
|
275
|
+
document.removeEventListener("visibilitychange", onHide);
|
|
276
|
+
window.removeEventListener("pagehide", drainWithBeacon);
|
|
277
|
+
});
|
|
278
|
+
return {
|
|
279
|
+
track,
|
|
280
|
+
page,
|
|
281
|
+
identify(id, traits) {
|
|
282
|
+
if (!id) return;
|
|
283
|
+
const changed = id !== userId;
|
|
284
|
+
userId = id;
|
|
285
|
+
writeJson("localStorage", USER_KEY, id);
|
|
286
|
+
if (changed) track(EventNames.Identify, traits);
|
|
287
|
+
},
|
|
288
|
+
reset() {
|
|
289
|
+
userId = void 0;
|
|
290
|
+
try {
|
|
291
|
+
localStorage.removeItem(USER_KEY);
|
|
292
|
+
} catch {
|
|
293
|
+
}
|
|
294
|
+
},
|
|
295
|
+
getExperiment(key) {
|
|
296
|
+
const assignment = bootstrapAssignments[key] ?? notFound(key);
|
|
297
|
+
if (assignment.reason === "assigned" && assignment.variant && !exposed.has(key)) {
|
|
298
|
+
exposed.add(key);
|
|
299
|
+
writeJson("sessionStorage", EXPOSED_KEY, [...exposed]);
|
|
300
|
+
track(EventNames.ExperimentExposure, { experiment: key, variant: assignment.variant });
|
|
301
|
+
}
|
|
302
|
+
return toExperiment(assignment);
|
|
303
|
+
},
|
|
304
|
+
setAssignments(next) {
|
|
305
|
+
assignments = { ...next };
|
|
306
|
+
},
|
|
307
|
+
getAnonymousId: () => anonymousId,
|
|
308
|
+
getSessionId: () => sessionId,
|
|
309
|
+
isQa,
|
|
310
|
+
flush,
|
|
311
|
+
shutdown() {
|
|
312
|
+
for (const cleanup of cleanups) cleanup();
|
|
313
|
+
drainWithBeacon();
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export { createAnalytics, createFetchTransport };
|
|
319
|
+
//# sourceMappingURL=client.js.map
|
|
320
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client/storage.ts","../src/client/index.ts"],"names":[],"mappings":";;;;AAEO,SAAS,WAAW,IAAA,EAAkC;AAC3D,EAAA,IAAI,OAAO,QAAA,KAAa,WAAA,EAAa,OAAO,MAAA;AAC5C,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,CAAA,EAAG,kBAAA,CAAmB,IAAI,CAAC,CAAA,CAAA,CAAA;AAC1C,IAAA,KAAA,MAAW,IAAA,IAAQ,QAAA,CAAS,MAAA,CAAO,KAAA,CAAM,GAAG,CAAA,EAAG;AAC7C,MAAA,MAAM,OAAA,GAAU,KAAK,IAAA,EAAK;AAC1B,MAAA,IAAI,OAAA,CAAQ,UAAA,CAAW,MAAM,CAAA,EAAG,OAAO,kBAAA,CAAmB,OAAA,CAAQ,KAAA,CAAM,MAAA,CAAO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ACF,CAAA;AAAA,IACA,cAAc,GAAA,EAAK;AACjB,MAAA,MAAM,UAAA,GAAa,oBAAA,CAAqB,GAAG,CAAA,IAAK,SAAS,GAAG,CAAA;AAC5D,MAAA,IAAI,UAAA,CAAW,WAAW,UAAA,IAAc,UAAA,CAAW,WAAW,CAAC,OAAA,CAAQ,GAAA,CAAI,GAAG,CAAA,EAAG;AAC/E,QAAA,OAAA,CAAQ,IAAI,GAAG,CAAA;AACf,QAAA,SAAA,CAAU,gBAAA,EAAkB,WAAA,EAAa,CAAC,GAAG,OAAO,CAAC,CAAA;AACrD,QAAA,KAAA,CAAM,UAAA,CAAW,oBAAoB,EAAE,UAAA,EAAY,KAAK,OAAA,EAAS,UAAA,CAAW,SAAS,CAAA;AAAA,MACvF;AAEA,MAAA,OAAO,aAAa,UAAU,CAAA;AAAA,IAChC,CAAA;AAAA,IACA,eAAe,IAAA,EAAM;AACnB,MAAA,WAAA,GAAc,EAAE,GAAG,IAAA,EAAK;AAAA,IAC1B,CAAA;AAAA,IACA,gBAAgB,MAAM,WAAA;AAAA,IACtB,cAAc,MAAM,SAAA;AAAA,IACpB,IAAA;AAAA,IACA,KAAA;AAAA,IACA,QAAA,GAAW;AACT,MAAA,KAAA,MAAW,OAAA,IAAW,UAAU,OAAA,EAAQ;AACxC,MAAA,eAAA,EAAgB;AAAA,IAClB;AAAA,GACF;AACF","file":"client.js","sourcesContent":["/** Storage helpers that never throw: private mode, blocked cookies and quota errors are all \"no value\". */\n\nexport function readCookie(name: string): string | undefined {\n if (typeof document === \"undefined\") return undefined;\n try {\n const prefix = `${encodeURIComponent(name)}=`;\n for (const part of document.cookie.split(\";\")) {\n const trimmed = part.trim();\n if (trimmed.startsWith(prefix)) return decodeURIComponent(trimmed.slice(prefix.length)) || undefined;\n }\n } catch {\n // Cookies disabled.\n }\n\n return undefined;\n}\n\nexport function writeCookie(name: string, value: string, maxAgeSeconds: number) {\n if (typeof document === \"undefined\") return;\n try {\n const secure = typeof location !== \"undefined\" && location.protocol === \"https:\" ? \"; Secure\" : \"\";\n document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}; Path=/; Max-Age=${maxAgeSeconds}; SameSite=Lax${secure}`;\n } catch {\n // Cookies disabled.\n }\n}\n\ntype StorageKind = \"localStorage\" | \"sessionStorage\";\n\nexport function readJson<T>(kind: StorageKind, key: string): T | undefined {\n try {\n const raw = globalThis[kind]?.getItem(key);\n\n return raw ? (JSON.parse(raw) as T) : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function writeJson(kind: StorageKind, key: string, value: unknown) {\n try {\n globalThis[kind]?.setItem(key, JSON.stringify(value));\n } catch {\n // Private mode or quota.\n }\n}\n","import type { AnalyticsEvent, EventProps } from \"@faceyoga/analytics-schema/events\";\nimport { notFound, type Assignment } from \"@faceyoga/analytics-schema/assign\";\nimport { EventNames } from \"@faceyoga/analytics-schema/names\";\nimport {\n PREVIEW_COOKIE,\n QA_COOKIE,\n QA_MAX_AGE_SECONDS,\n readPreviewState,\n} from \"@faceyoga/analytics-schema/preview\";\nimport { toExperiment, type Experiment } from \"../shared/experiment\";\nimport { cleanProps, LIBRARY, toEventName, uuid } from \"../shared/util\";\nimport { readCookie, readJson, writeCookie, writeJson } from \"./storage\";\n\nexport type { Experiment } from \"../shared/experiment\";\nexport type { Assignment } from \"@faceyoga/analytics-schema/assign\";\nexport { EventNames } from \"@faceyoga/analytics-schema/names\";\n\n/**\n * Browser pixel. One instance per page app, created once (module scope or a root provider).\n *\n * - Events are queued and sent in batches (`maxBatchSize` or every `flushIntervalMs`).\n * - When the tab is hidden or closed, the queue is drained with `navigator.sendBeacon`.\n * - Bodies are `text/plain` JSON so cross-origin sends never need a CORS preflight; better still,\n * send to the app's own `/a/collect` route (`createCollectHandler`) so ad blockers leave it alone.\n */\n\nexport type SendResult = \"ok\" | \"retry\" | \"drop\";\n\nexport interface Transport {\n send(body: string, options: { beacon: boolean }): Promise<SendResult>;\n}\n\nexport interface ClientExperimentBootstrap {\n /** From `experiments.getClientBootstrap(unit)` on the server. */\n assignments: Record<string, Assignment>;\n /** The server's deployment environment; used when `environment` is not passed. */\n environment?: string;\n}\n\nexport interface AnalyticsOptions {\n /**\n * Where batches go. Preferred: `/a/collect`, a same-origin route built with\n * `createCollectHandler` from `@faceyoga/analytics/server`; no `writeKey` is needed then.\n * Alternatively the collector itself, `https://analytics.example.com/api/collect`, with a `writeKey`.\n */\n endpoint: string;\n /** Public per-product key. Only for sending straight to the collector, not through `/a/collect`. */\n writeKey?: string;\n /**\n * `production` | `preview` | `development`. Default: the server's value from `bootstrap`, else\n * `unknown`. Ignored when sending through `/a/collect`, which stamps the server's own environment.\n */\n environment?: string;\n /**\n * Cookie that already holds the product's anonymous id (pithos `{product}_user_id`,\n * Hoola `hoola-userId`). Reusing it keeps ids identical to Statsig, Meta `external_id` and Axiom.\n * When missing, the SDK mints its own `fya_aid` cookie.\n */\n anonymousIdCookie?: string;\n /** Explicit anonymous id; wins over the cookie. */\n anonymousId?: string;\n /** Logged-in user id, if known at startup. */\n userId?: string;\n /**\n * Experiment assignments to tag onto every event (experiment key -> variant), e.g. from\n * `experiments.getAssignments(unit)`. This is what lets heatmaps and replays be split by variant.\n */\n assignments?: Record<string, string>;\n /** Full client-side experiment values for apps that read params in the browser (Hoola). */\n bootstrap?: ClientExperimentBootstrap;\n flushIntervalMs?: number;\n maxBatchSize?: number;\n maxQueueSize?: number;\n /** Inactivity after which the next event starts a new session. Default 30 minutes. */\n sessionTimeoutMs?: number;\n autocapture?: {\n /** Initial load plus client-side navigations (history API). Default true. */\n pageViews?: boolean;\n };\n /** Skip automated browsers (Playwright smoke tests). Default true. */\n ignoreAutomation?: boolean;\n disabled?: boolean;\n debug?: boolean;\n /** Test seam; defaults to fetch + sendBeacon. */\n transport?: Transport;\n}\n\nexport interface TrackOptions {\n /** Event id. Use the order id for purchases so retries de-duplicate. */\n id?: string;\n value?: number;\n currency?: string;\n orderId?: string;\n}\n\nexport interface Analytics {\n /** Queue an event. Returns its id. */\n track(name: string, props?: Record<string, unknown>, options?: TrackOptions): string;\n page(props?: Record<string, unknown>): string;\n /** Attach a logged-in user id to this device and all following events. */\n identify(userId: string, traits?: Record<string, unknown>): void;\n /** Forget the user id (logout). The anonymous id stays. */\n reset(): void;\n /** Read a client-side experiment; logs one exposure per experiment per session. */\n getExperiment(key: string): Experiment;\n setAssignments(assignments: Record<string, string>): void;\n getAnonymousId(): string;\n getSessionId(): string;\n /** True while this browser is in QA mode (opened a preview link): its events are stored as `test`. */\n isQa(): boolean;\n flush(): Promise<void>;\n shutdown(): void;\n}\n\nconst OWN_ANON_COOKIE = \"fya_aid\";\nconst USER_KEY = \"fya_uid\";\nconst SESSION_KEY = \"fya_session\";\nconst EXPOSED_KEY = \"fya_exposed\";\nconst ONE_YEAR = 365 * 24 * 60 * 60;\n\nfunction createNoop(): Analytics {\n const empty = toExperiment(notFound(\"\"));\n\n return {\n track: () => \"\",\n page: () => \"\",\n identify: () => {},\n reset: () => {},\n getExperiment: (key) => ({ ...empty, key }),\n setAssignments: () => {},\n getAnonymousId: () => \"\",\n getSessionId: () => \"\",\n isQa: () => false,\n flush: async () => {},\n shutdown: () => {},\n };\n}\n\nexport function createFetchTransport(endpoint: string): Transport {\n return {\n async send(body, { beacon }) {\n if (beacon && typeof navigator !== \"undefined\" && typeof navigator.sendBeacon === \"function\") {\n try {\n if (navigator.sendBeacon(endpoint, new Blob([body], { type: \"text/plain;charset=UTF-8\" }))) return \"ok\";\n } catch {\n // Fall through to fetch.\n }\n }\n try {\n const response = await fetch(endpoint, {\n method: \"POST\",\n body,\n headers: { \"Content-Type\": \"text/plain;charset=UTF-8\" },\n // keepalive bodies are capped at 64 KB per page.\n keepalive: body.length < 60_000,\n credentials: \"omit\",\n });\n if (response.ok) return \"ok\";\n\n return response.status === 429 || response.status >= 500 ? \"retry\" : \"drop\";\n } catch {\n return \"retry\";\n }\n },\n };\n}\n\nexport function createAnalytics(options: AnalyticsOptions): Analytics {\n if (typeof window === \"undefined\" || options.disabled) return createNoop();\n if ((options.ignoreAutomation ?? true) && typeof navigator !== \"undefined\" && navigator.webdriver) {\n return createNoop();\n }\n\n const flushIntervalMs = options.flushIntervalMs ?? 3_000;\n const maxBatchSize = Math.min(options.maxBatchSize ?? 20, 100);\n const maxQueueSize = options.maxQueueSize ?? 500;\n const sessionTimeoutMs = options.sessionTimeoutMs ?? 30 * 60 * 1000;\n const environment = options.environment ?? options.bootstrap?.environment ?? \"unknown\";\n const transport = options.transport ?? createFetchTransport(options.endpoint);\n const log = (...args: unknown[]) => {\n if (options.debug) console.debug(\"[analytics]\", ...args);\n };\n\n // --- identity -------------------------------------------------------------\n let anonymousId =\n options.anonymousId ||\n (options.anonymousIdCookie ? readCookie(options.anonymousIdCookie) : undefined) ||\n readCookie(OWN_ANON_COOKIE) ||\n \"\";\n if (!anonymousId) {\n anonymousId = uuid();\n writeCookie(OWN_ANON_COOKIE, anonymousId, ONE_YEAR);\n }\n let userId: string | undefined = options.userId || readJson<string>(\"localStorage\", USER_KEY);\n if (options.userId) writeJson(\"localStorage\", USER_KEY, options.userId);\n\n // --- QA mode (preview links) ------------------------------------------------\n // `?fy_preview=exp:variant` or `?fy_qa=1` turns it on for a day; `?fy_preview=off` turns it off.\n const preview = readPreviewState(typeof location !== \"undefined\" ? location.search : \"\", readCookie);\n if (preview.change?.action === \"set\") {\n writeCookie(QA_COOKIE, \"1\", QA_MAX_AGE_SECONDS);\n writeCookie(PREVIEW_COOKIE, preview.change.preview, preview.change.preview ? QA_MAX_AGE_SECONDS : 0);\n } else if (preview.change?.action === \"clear\") {\n writeCookie(QA_COOKIE, \"\", 0);\n writeCookie(PREVIEW_COOKIE, \"\", 0);\n }\n const isQa = () => preview.qa || Boolean(readCookie(QA_COOKIE));\n if (preview.qa) log(\"QA mode: events from this browser are stored with environment `test`\");\n\n // --- experiments ----------------------------------------------------------\n const bootstrapAssignments = options.bootstrap?.assignments ?? {};\n let assignments: Record<string, string> = { ...options.assignments };\n for (const assignment of Object.values(bootstrapAssignments)) {\n if ((assignment.reason === \"assigned\" || assignment.reason === \"preview\") && assignment.variant) {\n assignments[assignment.experiment] = assignment.variant;\n }\n }\n const exposed = new Set<string>(readJson<string[]>(\"sessionStorage\", EXPOSED_KEY) ?? []);\n\n // --- session --------------------------------------------------------------\n let sessionId = \"\";\n function touchSession(now: number): boolean {\n const stored = readJson<{ id: string; last: number }>(\"localStorage\", SESSION_KEY);\n const isNew = !stored || now - stored.last > sessionTimeoutMs;\n sessionId = isNew ? uuid() : stored.id;\n writeJson(\"localStorage\", SESSION_KEY, { id: sessionId, last: now });\n\n return isNew;\n }\n\n // --- queue + transport ----------------------------------------------------\n const queue: AnalyticsEvent[] = [];\n let timer: ReturnType<typeof setTimeout> | undefined;\n let flushing = false;\n let backoffMs = 0;\n\n const serialize = (events: AnalyticsEvent[]) =>\n JSON.stringify({\n writeKey: options.writeKey,\n sentAt: Date.now(),\n source: \"client\",\n environment,\n ...(isQa() && { qa: true }),\n library: LIBRARY,\n events,\n });\n\n function trimQueue() {\n if (queue.length > maxQueueSize) queue.splice(0, queue.length - maxQueueSize);\n }\n\n function schedule() {\n if (timer || queue.length === 0) return;\n timer = setTimeout(() => {\n timer = undefined;\n void flush();\n }, flushIntervalMs + backoffMs);\n }\n\n async function flush(): Promise<void> {\n if (flushing) return;\n flushing = true;\n if (timer) {\n clearTimeout(timer);\n timer = undefined;\n }\n try {\n while (queue.length) {\n const events = queue.splice(0, maxBatchSize);\n const result = await transport.send(serialize(events), { beacon: false });\n log(\"flush\", events.length, result);\n if (result === \"retry\") {\n queue.unshift(...events);\n trimQueue();\n backoffMs = Math.min(backoffMs ? backoffMs * 2 : 1_000, 30_000);\n break;\n }\n backoffMs = 0;\n }\n } finally {\n flushing = false;\n schedule();\n }\n }\n\n function drainWithBeacon() {\n if (timer) {\n clearTimeout(timer);\n timer = undefined;\n }\n while (queue.length) void transport.send(serialize(queue.splice(0, maxBatchSize)), { beacon: true });\n }\n\n function enqueue(event: AnalyticsEvent) {\n queue.push(event);\n trimQueue();\n log(\"track\", event.name, event);\n if (queue.length >= maxBatchSize) void flush();\n else schedule();\n }\n\n type InternalOptions = TrackOptions & { referrer?: string };\n\n function build(\n name: string,\n props: Record<string, unknown> | undefined,\n extra: InternalOptions = {}\n ): AnalyticsEvent {\n const event: AnalyticsEvent = {\n id: extra.id || uuid(),\n name: toEventName(name),\n ts: Date.now(),\n anonymousId,\n sessionId,\n url: location.href.slice(0, 2048),\n };\n if (userId) event.userId = userId;\n if (extra.value !== undefined && Number.isFinite(extra.value)) event.value = extra.value;\n if (extra.currency) event.currency = extra.currency;\n if (extra.orderId) event.orderId = extra.orderId;\n if (extra.referrer) event.referrer = extra.referrer.slice(0, 2048);\n if (Object.keys(assignments).length) event.experiments = { ...assignments };\n const cleaned = cleanProps(props) as EventProps | undefined;\n if (cleaned) event.props = cleaned;\n\n return event;\n }\n\n function track(name: string, props?: Record<string, unknown>, extra?: InternalOptions): string {\n if (touchSession(Date.now())) {\n enqueue(build(EventNames.SessionStart, { landing_url: location.href, referrer: document.referrer || null }));\n }\n const event = build(name, props, extra);\n enqueue(event);\n\n return event.id;\n }\n\n // --- page views -----------------------------------------------------------\n let lastPageUrl: string | undefined;\n let previousUrl: string | undefined;\n\n function page(props?: Record<string, unknown>): string {\n const href = location.href;\n const referrer = previousUrl ?? (document.referrer || undefined);\n previousUrl = href;\n lastPageUrl = href;\n\n return track(\n EventNames.PageView,\n { path: location.pathname, title: document.title || null, ...props },\n referrer ? { referrer } : undefined\n );\n }\n\n const cleanups: Array<() => void> = [];\n\n if (options.autocapture?.pageViews ?? true) {\n const onNavigate = () => {\n // Next.js updates the URL before rendering; wait a tick so document.title is the new page's.\n setTimeout(() => {\n const href = location.href.split(\"#\")[0];\n if (href !== lastPageUrl?.split(\"#\")[0]) page();\n }, 0);\n };\n const { pushState, replaceState } = history;\n history.pushState = function (...args: Parameters<History[\"pushState\"]>) {\n pushState.apply(this, args);\n onNavigate();\n };\n history.replaceState = function (...args: Parameters<History[\"replaceState\"]>) {\n replaceState.apply(this, args);\n onNavigate();\n };\n window.addEventListener(\"popstate\", onNavigate);\n cleanups.push(() => {\n history.pushState = pushState;\n history.replaceState = replaceState;\n window.removeEventListener(\"popstate\", onNavigate);\n });\n // Initial view on the next tick so callers can set assignments / identify first.\n setTimeout(() => {\n if (!lastPageUrl) page();\n }, 0);\n }\n\n const onHide = () => {\n if (document.visibilityState === \"hidden\") drainWithBeacon();\n };\n document.addEventListener(\"visibilitychange\", onHide);\n window.addEventListener(\"pagehide\", drainWithBeacon);\n cleanups.push(() => {\n document.removeEventListener(\"visibilitychange\", onHide);\n window.removeEventListener(\"pagehide\", drainWithBeacon);\n });\n\n return {\n track,\n page,\n identify(id, traits) {\n if (!id) return;\n const changed = id !== userId;\n userId = id;\n writeJson(\"localStorage\", USER_KEY, id);\n if (changed) track(EventNames.Identify, traits);\n },\n reset() {\n userId = undefined;\n try {\n localStorage.removeItem(USER_KEY);\n } catch {\n // Private mode.\n }\n },\n getExperiment(key) {\n const assignment = bootstrapAssignments[key] ?? notFound(key);\n if (assignment.reason === \"assigned\" && assignment.variant && !exposed.has(key)) {\n exposed.add(key);\n writeJson(\"sessionStorage\", EXPOSED_KEY, [...exposed]);\n track(EventNames.ExperimentExposure, { experiment: key, variant: assignment.variant });\n }\n\n return toExperiment(assignment);\n },\n setAssignments(next) {\n assignments = { ...next };\n },\n getAnonymousId: () => anonymousId,\n getSessionId: () => sessionId,\n isQa,\n flush,\n shutdown() {\n for (const cleanup of cleanups) cleanup();\n drainWithBeacon();\n },\n };\n}\n"]}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
interface AssignmentUnit {
|
|
2
|
+
/** Anonymous id. Experiments are assigned per device/browser, not per login. */
|
|
3
|
+
id: string;
|
|
4
|
+
country?: string;
|
|
5
|
+
locale?: string;
|
|
6
|
+
}
|
|
7
|
+
type AssignmentReason =
|
|
8
|
+
/** In the test; an exposure should be logged when a param is read. */
|
|
9
|
+
"assigned"
|
|
10
|
+
/** Experiment is launched; everyone gets the launched variant and no exposure is logged. */
|
|
11
|
+
| "launched"
|
|
12
|
+
/** Outside the allocation percentage. Gets fallbacks. */
|
|
13
|
+
| "not_allocated"
|
|
14
|
+
/** Country or locale outside the targeting rules. Gets fallbacks. */
|
|
15
|
+
| "targeting"
|
|
16
|
+
/** No running or launched experiment with that key. Gets fallbacks. */
|
|
17
|
+
| "not_found"
|
|
18
|
+
/** Variant forced by a preview link (QA mode). No exposure is logged. */
|
|
19
|
+
| "preview";
|
|
20
|
+
interface Assignment {
|
|
21
|
+
experiment: string;
|
|
22
|
+
/** Variant key, or null when the user gets fallbacks. */
|
|
23
|
+
variant: string | null;
|
|
24
|
+
params: Record<string, unknown>;
|
|
25
|
+
reason: AssignmentReason;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** What `getExperiment` returns on both client and server. Mirrors Statsig's `experiment.get(name, fallback)`. */
|
|
29
|
+
interface Experiment {
|
|
30
|
+
key: string;
|
|
31
|
+
/** Variant key, or null when the user gets fallbacks (not allocated, not targeted, unknown key). */
|
|
32
|
+
variant: string | null;
|
|
33
|
+
reason: AssignmentReason;
|
|
34
|
+
/** Read a variant parameter. Returns `fallback` when the param is missing or of a different type. */
|
|
35
|
+
get<T>(param: string, fallback: T): T;
|
|
36
|
+
/** All params of the assigned variant. */
|
|
37
|
+
params: Record<string, unknown>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Canonical event names. Products may send any snake_case name, but these have fixed meaning
|
|
42
|
+
* in dashboards, funnels and experiment metrics, so map onto them where one fits.
|
|
43
|
+
*/
|
|
44
|
+
declare const EventNames: {
|
|
45
|
+
readonly PageView: "page_view";
|
|
46
|
+
readonly SessionStart: "session_start";
|
|
47
|
+
readonly ExperimentExposure: "experiment_exposure";
|
|
48
|
+
readonly Identify: "identify";
|
|
49
|
+
readonly ViewContent: "view_content";
|
|
50
|
+
readonly AddToCart: "add_to_cart";
|
|
51
|
+
readonly InitiateCheckout: "initiate_checkout";
|
|
52
|
+
readonly CheckoutEmailCaptured: "checkout_email_captured";
|
|
53
|
+
readonly Purchase: "purchase";
|
|
54
|
+
readonly Upsell: "upsell";
|
|
55
|
+
readonly FailedOrder: "failed_order";
|
|
56
|
+
readonly FailedTransaction: "failed_transaction";
|
|
57
|
+
readonly CtaClicked: "cta_clicked";
|
|
58
|
+
readonly QuizStepViewed: "quiz_step_viewed";
|
|
59
|
+
readonly QuizStepCompleted: "quiz_step_completed";
|
|
60
|
+
readonly QuizCompleted: "quiz_completed";
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
export { type Assignment as A, type Experiment as E, EventNames as a, type AssignmentUnit as b };
|