@naturalcycles/internal-web-lib 1.0.2 → 1.1.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/bundle/analyticsClient.js +19 -19
- package/bundle/analyticsClient.js.map +1 -1
- package/bundle/cookieMonster.js +863 -0
- package/bundle/cookieMonster.js.map +1 -0
- package/dist/analytics/analyticsClient.js +674 -804
- package/dist/analytics/index.js +2 -1
- package/dist/cookie-monster/components/setting-dropdown/setting-dropdown.component.d.ts +17 -0
- package/dist/cookie-monster/components/setting-dropdown/setting-dropdown.component.js +4 -0
- package/dist/cookie-monster/components/setting-dropdown/setting-dropdown2.component.js +129 -0
- package/dist/cookie-monster/components/themed-button/themed-button.component.d.ts +7 -0
- package/dist/cookie-monster/components/themed-button/themed-button.component.js +4 -0
- package/dist/cookie-monster/components/themed-button/themed-button2.component.js +30 -0
- package/dist/cookie-monster/consent/consent.service.d.ts +24 -0
- package/dist/cookie-monster/consent/consent.service.js +68 -0
- package/dist/cookie-monster/consent/consentLogStorage.service.d.ts +9 -0
- package/dist/cookie-monster/consent/consentLogStorage.service.js +38 -0
- package/dist/cookie-monster/const/cookieMonster.const.d.ts +4 -0
- package/dist/cookie-monster/const/cookieMonster.const.js +11 -0
- package/dist/cookie-monster/cookie-monster-element.d.ts +33 -0
- package/dist/cookie-monster/cookie-monster-element.js +121 -0
- package/dist/cookie-monster/cookieMonsterService.d.ts +19 -0
- package/dist/cookie-monster/cookieMonsterService.js +59 -0
- package/dist/cookie-monster/css/fonts.js +4 -0
- package/dist/cookie-monster/css/general.js +4 -0
- package/dist/cookie-monster/css/shared-sheets.d.ts +4 -0
- package/dist/cookie-monster/css/shared-sheets.js +14 -0
- package/dist/cookie-monster/icons/back.js +4 -0
- package/dist/cookie-monster/icons/chevron.js +4 -0
- package/dist/cookie-monster/index.d.ts +2 -0
- package/dist/cookie-monster/index.js +3 -0
- package/dist/cookie-monster/lang/da-DK.js +22 -0
- package/dist/cookie-monster/lang/de-DE.js +22 -0
- package/dist/cookie-monster/lang/en-GB.js +22 -0
- package/dist/cookie-monster/lang/en-US.js +22 -0
- package/dist/cookie-monster/lang/es-US.js +22 -0
- package/dist/cookie-monster/lang/fi-FI.js +22 -0
- package/dist/cookie-monster/lang/fr-FR.js +22 -0
- package/dist/cookie-monster/lang/it-IT.js +22 -0
- package/dist/cookie-monster/lang/no-NO.js +22 -0
- package/dist/cookie-monster/lang/pt-BR.js +22 -0
- package/dist/cookie-monster/lang/sv-SE.js +22 -0
- package/dist/cookie-monster/types/CookieMonster.types.d.ts +56 -0
- package/dist/cookie-monster/types/CookieMonster.types.js +34 -0
- package/dist/cookie-monster/utils/createButton.d.ts +1 -0
- package/dist/cookie-monster/utils/createButton.js +11 -0
- package/dist/cookie-monster/utils/getCookieMonsterEvent.d.ts +2 -0
- package/dist/cookie-monster/utils/getCookieMonsterEvent.js +10 -0
- package/dist/cookie-monster/utils/handleRootClick.d.ts +1 -0
- package/dist/cookie-monster/utils/handleRootClick.js +16 -0
- package/dist/cookie-monster/utils/linkify.d.ts +1 -0
- package/dist/cookie-monster/utils/linkify.js +9 -0
- package/dist/cookie-monster/utils/translationsService.d.ts +7 -0
- package/dist/cookie-monster/utils/translationsService.js +56 -0
- package/dist/cookie-monster/views/main.view.d.ts +24 -0
- package/dist/cookie-monster/views/main.view.js +115 -0
- package/dist/cookie-monster/views/settings.view.d.ts +18 -0
- package/dist/cookie-monster/views/settings.view.js +96 -0
- package/dist/cookie-monster/views/views.js +4 -0
- package/dist/index.js +2 -1
- package/dist/node_modules/.pnpm/@naturalcycles_ncuikit@1.14.0_react@19.3.0_undici@8.11.2/node_modules/@naturalcycles/ncuikit/dist/styles/_palette.js +4 -0
- package/package.json +14 -4
|
@@ -1,828 +1,698 @@
|
|
|
1
|
-
import { _isEmptyObject, isServerSide } from
|
|
2
|
-
import {
|
|
3
|
-
import { _mapToObject } from
|
|
4
|
-
import {
|
|
5
|
-
import { getFetcher } from
|
|
6
|
-
import { nanoidBrowser, nanoidBrowserCustomAlphabet } from
|
|
7
|
-
import { _filterNullishValues, _filterObject } from
|
|
8
|
-
import { _safeJsonStringify } from
|
|
9
|
-
import { _noop } from
|
|
1
|
+
import { _isEmptyObject, isServerSide } from "@naturalcycles/js-lib";
|
|
2
|
+
import { ANALYTICS_IDENTIFY_EVENT_NAME, CANONICAL_UTM_PARAMS, truncateAnalyticsProperty } from "@naturalcycles/js-lib/analytics";
|
|
3
|
+
import { _mapToObject } from "@naturalcycles/js-lib/array";
|
|
4
|
+
import { AppError, _errorDataAppend } from "@naturalcycles/js-lib/error";
|
|
5
|
+
import { getFetcher } from "@naturalcycles/js-lib/http";
|
|
6
|
+
import { nanoidBrowser, nanoidBrowserCustomAlphabet } from "@naturalcycles/js-lib/nanoid";
|
|
7
|
+
import { _filterNullishValues, _filterObject } from "@naturalcycles/js-lib/object";
|
|
8
|
+
import { _safeJsonStringify } from "@naturalcycles/js-lib/string";
|
|
9
|
+
import { _noop } from "@naturalcycles/js-lib/types";
|
|
10
|
+
//#region src/analytics/analyticsClient.ts
|
|
10
11
|
/**
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
12
|
+
* Browsers drop a cookie over 4096 bytes, and the identity goes with it. The 3800 budget also
|
|
13
|
+
* has to cover the `; expires=`, `; path=`, `; domain=` and `; secure` attributes that setCookie
|
|
14
|
+
* appends (roughly 75 bytes), which cookieLength below does not measure. Keep that in mind
|
|
15
|
+
* before raising this toward 4096.
|
|
16
|
+
*/
|
|
17
|
+
var MAX_COOKIE_LENGTH = 3800;
|
|
18
|
+
var UTM_QUERY_PARAM_PREFIX = "utm_";
|
|
19
|
+
var CLICK_QUERY_PARAMS = [
|
|
20
|
+
"dclid",
|
|
21
|
+
"fbclid",
|
|
22
|
+
"gclid",
|
|
23
|
+
"ko_click_id",
|
|
24
|
+
"li_fat_id",
|
|
25
|
+
"msclkid",
|
|
26
|
+
"sccid",
|
|
27
|
+
"ttclid",
|
|
28
|
+
"twclid",
|
|
29
|
+
"wbraid"
|
|
29
30
|
];
|
|
30
|
-
|
|
31
|
+
var generateEventId = nanoidBrowserCustomAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 16);
|
|
31
32
|
/**
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
return {
|
|
464
|
-
events: batch.events,
|
|
465
|
-
body: _safeJsonStringify(input),
|
|
466
|
-
};
|
|
467
|
-
}
|
|
468
|
-
/**
|
|
469
|
-
* Adopts queue snapshots persisted by previous pageloads (crashed/killed tabs) and re-sends them.
|
|
470
|
-
* A snapshot of a still-alive tab may be adopted too - the resulting duplicate delivery
|
|
471
|
-
* is deduped by the Backend via event ids.
|
|
472
|
-
*/
|
|
473
|
-
restoreOrphanedQueues() {
|
|
474
|
-
if (!this.cfg.persistQueue)
|
|
475
|
-
return;
|
|
476
|
-
try {
|
|
477
|
-
const prefix = `${this.cfg.localStorageKeyPrefix}.q.`;
|
|
478
|
-
const keys = [];
|
|
479
|
-
for (let i = 0; i < localStorage.length; i++) {
|
|
480
|
-
const key = localStorage.key(i);
|
|
481
|
-
if (key?.startsWith(prefix))
|
|
482
|
-
keys.push(key);
|
|
483
|
-
}
|
|
484
|
-
if (!keys.length)
|
|
485
|
-
return;
|
|
486
|
-
const minTs = Date.now() - this.cfg.maxPersistedAge;
|
|
487
|
-
for (const key of keys) {
|
|
488
|
-
try {
|
|
489
|
-
const events = JSON.parse(localStorage.getItem(key) || '[]');
|
|
490
|
-
localStorage.removeItem(key);
|
|
491
|
-
this.queue.push(...events.filter(event => event.ts >= minTs));
|
|
492
|
-
}
|
|
493
|
-
catch {
|
|
494
|
-
// Corrupted snapshot - discard only this key and continue restoring the others.
|
|
495
|
-
localStorage.removeItem(key);
|
|
496
|
-
}
|
|
497
|
-
}
|
|
498
|
-
if (this.queue.length > this.cfg.maxQueueSize) {
|
|
499
|
-
this.queue.splice(0, this.queue.length - this.cfg.maxQueueSize);
|
|
500
|
-
}
|
|
501
|
-
if (this.queue.length) {
|
|
502
|
-
this.persistQueue();
|
|
503
|
-
this.scheduleFlush();
|
|
504
|
-
}
|
|
505
|
-
}
|
|
506
|
-
catch {
|
|
507
|
-
// localStorage unavailable - pending in-memory events continue normally
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
scheduleFlush() {
|
|
511
|
-
if (this.flushTimer || isServerSide())
|
|
512
|
-
return;
|
|
513
|
-
let delayMs = this.cfg.flushInterval;
|
|
514
|
-
if (this.consecutiveFailures) {
|
|
515
|
-
delayMs = Math.min(this.cfg.flushInterval * 2 ** this.consecutiveFailures, this.cfg.maxRetryBackoff);
|
|
516
|
-
delayMs = Math.max(delayMs, this.retryAfter);
|
|
517
|
-
}
|
|
518
|
-
this.flushTimer = setTimeout(() => {
|
|
519
|
-
this.flushTimer = undefined;
|
|
520
|
-
void this.flush();
|
|
521
|
-
}, delayMs);
|
|
522
|
-
}
|
|
523
|
-
clearFlushTimer() {
|
|
524
|
-
if (!this.flushTimer)
|
|
525
|
-
return;
|
|
526
|
-
clearTimeout(this.flushTimer);
|
|
527
|
-
this.flushTimer = undefined;
|
|
528
|
-
}
|
|
529
|
-
removeFromQueue(batch) {
|
|
530
|
-
const ids = new Set(batch.map(event => event.id));
|
|
531
|
-
this.queue = this.queue.filter(event => !ids.has(event.id));
|
|
532
|
-
this.persistQueue();
|
|
533
|
-
}
|
|
534
|
-
persistQueue() {
|
|
535
|
-
if (!this.cfg.persistQueue)
|
|
536
|
-
return;
|
|
537
|
-
try {
|
|
538
|
-
if (this.queue.length) {
|
|
539
|
-
localStorage.setItem(this.queueKey, _safeJsonStringify(this.queue));
|
|
540
|
-
}
|
|
541
|
-
else {
|
|
542
|
-
localStorage.removeItem(this.queueKey);
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
catch {
|
|
546
|
-
// localStorage unavailable/full - analytics must never break the app
|
|
547
|
-
}
|
|
548
|
-
}
|
|
549
|
-
get queueKey() {
|
|
550
|
-
return `${this.cfg.localStorageKeyPrefix}.q.${this.tabId}`;
|
|
551
|
-
}
|
|
552
|
-
}
|
|
33
|
+
* Self-hosted analytics event client.
|
|
34
|
+
*
|
|
35
|
+
* Captures client-side analytics events, adds browser page properties, batches them, retries
|
|
36
|
+
* transient failures and delivers them to our own Backend via a single REST endpoint.
|
|
37
|
+
*/
|
|
38
|
+
var AnalyticsClient = class {
|
|
39
|
+
constructor(cfg) {
|
|
40
|
+
const localStorageKeyPrefix = cfg.localStorageKeyPrefix || "nca";
|
|
41
|
+
this.cfg = {
|
|
42
|
+
onError: _noop,
|
|
43
|
+
firstTouchUrl: "",
|
|
44
|
+
isEnabled: () => true,
|
|
45
|
+
getCommonProps: () => ({}),
|
|
46
|
+
flushInterval: 5e3,
|
|
47
|
+
maxBatchSize: 50,
|
|
48
|
+
maxBatchBytes: 6e4,
|
|
49
|
+
maxQueueSize: 1e3,
|
|
50
|
+
maxRetryBackoff: 6e5,
|
|
51
|
+
requestTimeout: 3e4,
|
|
52
|
+
persistQueue: true,
|
|
53
|
+
maxPersistedAge: 864e5,
|
|
54
|
+
localStorageKeyPrefix,
|
|
55
|
+
logger: console,
|
|
56
|
+
debug: false,
|
|
57
|
+
...cfg
|
|
58
|
+
};
|
|
59
|
+
this.identity = new AnalyticsIdentity(this.cfg.identity);
|
|
60
|
+
this.firstTouchFetcher = getFetcher({
|
|
61
|
+
logger: this.cfg.logger,
|
|
62
|
+
retryPost: true,
|
|
63
|
+
timeoutSeconds: 10
|
|
64
|
+
});
|
|
65
|
+
if (isServerSide()) return;
|
|
66
|
+
this.restoreOrphanedQueues();
|
|
67
|
+
globalThis.addEventListener("pagehide", this.handlePageHide);
|
|
68
|
+
document.addEventListener("visibilitychange", this.handleVisibilityChange);
|
|
69
|
+
}
|
|
70
|
+
cfg;
|
|
71
|
+
firstTouchFetcher;
|
|
72
|
+
/**
|
|
73
|
+
* The built-in identity, constructed from `cfg.identity`. Also readable by application code,
|
|
74
|
+
* e.g to feed the distinctId or acquisition props to other integrations.
|
|
75
|
+
*/
|
|
76
|
+
identity;
|
|
77
|
+
/**
|
|
78
|
+
* Random id of this AnalyticsClient instance (in practice - of this tab/pageload),
|
|
79
|
+
* used to namespace the localStorage queue snapshot.
|
|
80
|
+
*/
|
|
81
|
+
tabId = nanoidBrowser(10);
|
|
82
|
+
queue = [];
|
|
83
|
+
flushTimer;
|
|
84
|
+
isFlushing = false;
|
|
85
|
+
consecutiveFailures = 0;
|
|
86
|
+
/**
|
|
87
|
+
* Requested by the server via `Retry-After` header (already converted to ms).
|
|
88
|
+
*/
|
|
89
|
+
retryAfter = 0;
|
|
90
|
+
hasUpdatedAcquisitionProps = false;
|
|
91
|
+
eventListeners = /* @__PURE__ */ new Set();
|
|
92
|
+
handlePageHide = () => {
|
|
93
|
+
this.flushNow();
|
|
94
|
+
};
|
|
95
|
+
handleVisibilityChange = () => {
|
|
96
|
+
if (document.visibilityState === "hidden") this.flushNow();
|
|
97
|
+
};
|
|
98
|
+
/**
|
|
99
|
+
* Optional eager bootstrapping, to call once at app boot: registers the acquisition props
|
|
100
|
+
* into the identity entry while the landing url/referrer are still current - the moment
|
|
101
|
+
* an SPA navigation can strip the utm params off the url before the first event fires. Gated by cfg.isEnabled, like the events themselves.
|
|
102
|
+
* Without it the registration happens lazily before the first enabled event.
|
|
103
|
+
*/
|
|
104
|
+
init() {
|
|
105
|
+
if (!this.canTrack()) return;
|
|
106
|
+
this.ensureAcquisitionProps();
|
|
107
|
+
this.replayFromStub();
|
|
108
|
+
}
|
|
109
|
+
track(name, props) {
|
|
110
|
+
const event = this.enqueue(name, props);
|
|
111
|
+
if (event) this.notifyEventListeners(event);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Replays the calls a stub recorded on the page before this client loaded, under the timestamps
|
|
115
|
+
* they were made at. Tracked in order, so calls made before the stub's `identify()` keep the
|
|
116
|
+
* anonymous identity.
|
|
117
|
+
*/
|
|
118
|
+
replayFromStub() {
|
|
119
|
+
const stub = globalThis.analyticsClient;
|
|
120
|
+
if (!stub || !("q" in stub)) return;
|
|
121
|
+
for (const call of stub.q) try {
|
|
122
|
+
if (call.method === "identify") this.identify(call.args[0]);
|
|
123
|
+
else {
|
|
124
|
+
const event = this.enqueue(call.args[0], call.args[1], call.ts);
|
|
125
|
+
if (event) this.notifyEventListeners(event);
|
|
126
|
+
}
|
|
127
|
+
} catch (err) {
|
|
128
|
+
this.cfg.logger.warn("[analytics] could not replay a stubbed call", err);
|
|
129
|
+
}
|
|
130
|
+
stub.q.length = 0;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Registers a listener called synchronously for every delivered event, past the gates in
|
|
134
|
+
* `track()`. Returns an unsubscribe function. Listeners receive a snapshot and cannot affect
|
|
135
|
+
* delivery, and a throwing listener never breaks tracking.
|
|
136
|
+
*/
|
|
137
|
+
onEvent(listener) {
|
|
138
|
+
this.eventListeners.add(listener);
|
|
139
|
+
return () => this.eventListeners.delete(listener);
|
|
140
|
+
}
|
|
141
|
+
notifyEventListeners(event) {
|
|
142
|
+
if (!this.eventListeners.size) return;
|
|
143
|
+
const distinctId = event.userId || this.identity.getDistinctId();
|
|
144
|
+
const snapshot = {
|
|
145
|
+
...event,
|
|
146
|
+
props: { ...event.props }
|
|
147
|
+
};
|
|
148
|
+
for (const listener of this.eventListeners) try {
|
|
149
|
+
listener(snapshot, distinctId);
|
|
150
|
+
} catch (err) {
|
|
151
|
+
this.cfg.logger.warn("[analytics] onEvent listener threw", err);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Sets the distinctId going forward (persisted), e.g after a successful signup.
|
|
156
|
+
* Pending events are kept, each under the identity it was tracked with.
|
|
157
|
+
*/
|
|
158
|
+
identify(userId) {
|
|
159
|
+
if (!this.canTrack()) return;
|
|
160
|
+
const previousDistinctId = this.identity.getDistinctId();
|
|
161
|
+
this.identity.identify(userId);
|
|
162
|
+
if (previousDistinctId === userId) return;
|
|
163
|
+
this.enqueue(ANALYTICS_IDENTIFY_EVENT_NAME, { anon_distinct_id: previousDistinctId });
|
|
164
|
+
this.flush();
|
|
165
|
+
this.sendFirstTouch();
|
|
166
|
+
}
|
|
167
|
+
enqueue(name, props, ts) {
|
|
168
|
+
if (!this.canTrack()) return;
|
|
169
|
+
this.ensureAcquisitionProps();
|
|
170
|
+
const event = {
|
|
171
|
+
id: generateEventId(),
|
|
172
|
+
name,
|
|
173
|
+
ts: ts || Date.now(),
|
|
174
|
+
props: {
|
|
175
|
+
...this.getDefaultProps(),
|
|
176
|
+
...this.cfg.getCommonProps(),
|
|
177
|
+
...props
|
|
178
|
+
},
|
|
179
|
+
userId: this.identity.getDistinctId()
|
|
180
|
+
};
|
|
181
|
+
if (this.cfg.debug) this.cfg.logger.log(`[analytics] ${event.name}`, event.props);
|
|
182
|
+
this.queue.push(event);
|
|
183
|
+
if (this.queue.length > this.cfg.maxQueueSize) {
|
|
184
|
+
this.queue.shift();
|
|
185
|
+
this.cfg.logger.warn("[analytics] queue overflow, dropped the oldest event");
|
|
186
|
+
}
|
|
187
|
+
this.persistQueue();
|
|
188
|
+
if (this.queue.length >= this.cfg.maxBatchSize && !this.consecutiveFailures) this.flush();
|
|
189
|
+
else this.scheduleFlush();
|
|
190
|
+
return event;
|
|
191
|
+
}
|
|
192
|
+
canTrack() {
|
|
193
|
+
return !isServerSide() && this.cfg.isEnabled();
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Clears pending events and the persisted identity entry, including its acquisition
|
|
197
|
+
* properties. A new identity is generated on next use.
|
|
198
|
+
*/
|
|
199
|
+
reset() {
|
|
200
|
+
this.clearPendingEvents();
|
|
201
|
+
this.identity.reset();
|
|
202
|
+
this.hasUpdatedAcquisitionProps = false;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Drains the queue, one batch per request.
|
|
206
|
+
* Called automatically (flush interval / batch size / pagehide) - public for manual flushing.
|
|
207
|
+
*/
|
|
208
|
+
async flush() {
|
|
209
|
+
if (isServerSide() || this.isFlushing) return;
|
|
210
|
+
this.isFlushing = true;
|
|
211
|
+
this.clearFlushTimer();
|
|
212
|
+
try {
|
|
213
|
+
while (this.queue.length) for (const batch of this.prepareBatches()) {
|
|
214
|
+
if (await this.sendBatch(batch) === "retry") {
|
|
215
|
+
this.consecutiveFailures++;
|
|
216
|
+
this.scheduleFlush();
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
this.removeFromQueue(batch.events);
|
|
220
|
+
this.consecutiveFailures = 0;
|
|
221
|
+
this.retryAfter = 0;
|
|
222
|
+
}
|
|
223
|
+
} finally {
|
|
224
|
+
this.isFlushing = false;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Immediate flush: hands queued events over to the browser via keepalive fetch.
|
|
229
|
+
* Runs automatically on pagehide / visibilitychange:hidden. Public so that app code can
|
|
230
|
+
* hand events over right away: events tracked in its own page-lifecycle handlers (which
|
|
231
|
+
* run after this client's own), and events tracked right before a navigation (e.g a
|
|
232
|
+
* cta click) - unload-time delivery is best-effort and can be lost, while a
|
|
233
|
+
* keepalive request from a still-alive page survives the navigation.
|
|
234
|
+
* The persisted queue remains untouched because keepalive requests cannot reliably process
|
|
235
|
+
* their response; a later regular flush re-sends and deduplicates the events.
|
|
236
|
+
*/
|
|
237
|
+
flushNow() {
|
|
238
|
+
if (!this.queue.length) return;
|
|
239
|
+
this.clearFlushTimer();
|
|
240
|
+
for (const batch of this.prepareBatches()) this.postBatch(batch, true).catch((err) => {
|
|
241
|
+
this.cfg.logger.warn("[analytics] lifecycle batch failed to send; retained for retry", err);
|
|
242
|
+
});
|
|
243
|
+
this.scheduleFlush();
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Removes listeners and pending timers. Only needed when an instance is discarded
|
|
247
|
+
* (e.g in tests or HMR) - the app-wide singleton never needs it.
|
|
248
|
+
*/
|
|
249
|
+
destroy() {
|
|
250
|
+
this.clearFlushTimer();
|
|
251
|
+
if (isServerSide()) return;
|
|
252
|
+
globalThis.removeEventListener("pagehide", this.handlePageHide);
|
|
253
|
+
document.removeEventListener("visibilitychange", this.handleVisibilityChange);
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Registers the acquisition props into the identity entry once per pageload, like
|
|
257
|
+
* eagerly from init(), or lazily before the first
|
|
258
|
+
* enabled event. Either path is gated by cfg.isEnabled, so bot/e2e/consent gating
|
|
259
|
+
* applies to the persistence write too.
|
|
260
|
+
*/
|
|
261
|
+
ensureAcquisitionProps() {
|
|
262
|
+
if (this.hasUpdatedAcquisitionProps) return;
|
|
263
|
+
this.hasUpdatedAcquisitionProps = true;
|
|
264
|
+
this.identity.updateAcquisitionProps();
|
|
265
|
+
this.sendFirstTouch();
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Posts the first-touch props to their own endpoint, once per pageload. Fire-and-forget:
|
|
269
|
+
* `$set_once` ignores every write after the first, so a lost or repeated call costs nothing.
|
|
270
|
+
*/
|
|
271
|
+
async sendFirstTouch() {
|
|
272
|
+
const { firstTouchUrl } = this.cfg;
|
|
273
|
+
if (!firstTouchUrl) return;
|
|
274
|
+
const props = this.identity.getFirstTouchProps();
|
|
275
|
+
if (!props) return;
|
|
276
|
+
const input = {
|
|
277
|
+
clientId: this.cfg.clientId,
|
|
278
|
+
userId: this.identity.getDistinctId(),
|
|
279
|
+
props
|
|
280
|
+
};
|
|
281
|
+
const res = await this.firstTouchFetcher.doFetch({
|
|
282
|
+
url: firstTouchUrl,
|
|
283
|
+
method: "POST",
|
|
284
|
+
text: _safeJsonStringify(input),
|
|
285
|
+
responseType: "void"
|
|
286
|
+
});
|
|
287
|
+
if (!res.err) return;
|
|
288
|
+
try {
|
|
289
|
+
this.cfg.onError(_errorDataAppend(res.err, { firstTouch: true }));
|
|
290
|
+
} catch (err) {
|
|
291
|
+
this.cfg.logger.warn("[analytics] onError hook threw", err);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
getDefaultProps() {
|
|
295
|
+
const referrer = document.referrer;
|
|
296
|
+
const url = new URL(globalThis.location.href);
|
|
297
|
+
return {
|
|
298
|
+
...referrer && { referrer },
|
|
299
|
+
current_url: globalThis.location.href,
|
|
300
|
+
screen_height: globalThis.screen.height,
|
|
301
|
+
screen_width: globalThis.screen.width,
|
|
302
|
+
...this.identity.getAcquisitionProps(),
|
|
303
|
+
...getLastTouchUtms(url),
|
|
304
|
+
...getQueryProperties(url, CLICK_QUERY_PARAMS)
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
clearPendingEvents() {
|
|
308
|
+
this.clearFlushTimer();
|
|
309
|
+
this.queue = [];
|
|
310
|
+
this.consecutiveFailures = 0;
|
|
311
|
+
this.retryAfter = 0;
|
|
312
|
+
this.persistQueue();
|
|
313
|
+
}
|
|
314
|
+
async sendBatch(batch) {
|
|
315
|
+
let res;
|
|
316
|
+
try {
|
|
317
|
+
res = await this.postBatch(batch, false, AbortSignal.timeout?.(this.cfg.requestTimeout));
|
|
318
|
+
} catch (err) {
|
|
319
|
+
this.cfg.logger.warn("[analytics] batch failed to send, will retry", err);
|
|
320
|
+
return "retry";
|
|
321
|
+
}
|
|
322
|
+
if (res.ok) return "ok";
|
|
323
|
+
if (res.status === 429 || res.status >= 500) {
|
|
324
|
+
const retryAfter = Number(res.headers.get("retry-after"));
|
|
325
|
+
if (retryAfter) this.retryAfter = retryAfter * 1e3;
|
|
326
|
+
this.cfg.logger.warn(`[analytics] batch rejected with ${res.status}, will retry`);
|
|
327
|
+
return "retry";
|
|
328
|
+
}
|
|
329
|
+
this.cfg.logger.error(`[analytics] batch rejected with ${res.status}, dropping ${batch.events.length} event(s)`);
|
|
330
|
+
try {
|
|
331
|
+
this.cfg.onError(new AppError("batch dropped on a non-retryable status", {
|
|
332
|
+
status: res.status,
|
|
333
|
+
eventCount: batch.events.length
|
|
334
|
+
}));
|
|
335
|
+
} catch (err) {
|
|
336
|
+
this.cfg.logger.warn("[analytics] onError hook threw", err);
|
|
337
|
+
}
|
|
338
|
+
return "drop";
|
|
339
|
+
}
|
|
340
|
+
async postBatch(batch, isLifecycleFlush, signal) {
|
|
341
|
+
return fetch(this.cfg.url, {
|
|
342
|
+
method: "POST",
|
|
343
|
+
headers: { "content-type": "text/plain" },
|
|
344
|
+
body: batch.body,
|
|
345
|
+
...isLifecycleFlush && { keepalive: true },
|
|
346
|
+
signal
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Splits the whole queue into request-ready batches of at most maxBatchSize events
|
|
351
|
+
* and maxBatchBytes serialized bytes each.
|
|
352
|
+
*/
|
|
353
|
+
prepareBatches() {
|
|
354
|
+
const batches = [];
|
|
355
|
+
let current;
|
|
356
|
+
const userId = this.identity.getDistinctId();
|
|
357
|
+
for (const event of this.queue) {
|
|
358
|
+
const eventBytes = getUtf8ByteLength(_safeJsonStringify(event));
|
|
359
|
+
const hasReachedCount = current?.events.length === this.cfg.maxBatchSize;
|
|
360
|
+
const separatorBytes = current?.events.length ? 1 : 0;
|
|
361
|
+
const hasReachedBytes = !!current && current.bodyBytes + separatorBytes + eventBytes > this.cfg.maxBatchBytes;
|
|
362
|
+
if (current && (hasReachedCount || hasReachedBytes)) {
|
|
363
|
+
batches.push(this.finalizeBatch(current));
|
|
364
|
+
current = void 0;
|
|
365
|
+
}
|
|
366
|
+
current ||= this.createPendingBatch(userId);
|
|
367
|
+
const nextSeparatorBytes = current.events.length ? 1 : 0;
|
|
368
|
+
current.events.push(event);
|
|
369
|
+
current.bodyBytes += nextSeparatorBytes + eventBytes;
|
|
370
|
+
}
|
|
371
|
+
if (current?.events.length) batches.push(this.finalizeBatch(current));
|
|
372
|
+
return batches;
|
|
373
|
+
}
|
|
374
|
+
createPendingBatch(userId) {
|
|
375
|
+
const sentAt = Date.now();
|
|
376
|
+
const emptyBody = {
|
|
377
|
+
sentAt,
|
|
378
|
+
clientId: this.cfg.clientId,
|
|
379
|
+
userId,
|
|
380
|
+
events: []
|
|
381
|
+
};
|
|
382
|
+
return {
|
|
383
|
+
sentAt,
|
|
384
|
+
userId,
|
|
385
|
+
events: [],
|
|
386
|
+
bodyBytes: getUtf8ByteLength(JSON.stringify(emptyBody))
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
finalizeBatch(batch) {
|
|
390
|
+
const input = {
|
|
391
|
+
sentAt: batch.sentAt,
|
|
392
|
+
clientId: this.cfg.clientId,
|
|
393
|
+
userId: batch.userId,
|
|
394
|
+
events: batch.events
|
|
395
|
+
};
|
|
396
|
+
return {
|
|
397
|
+
events: batch.events,
|
|
398
|
+
body: _safeJsonStringify(input)
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Adopts queue snapshots persisted by previous pageloads (crashed/killed tabs) and re-sends them.
|
|
403
|
+
* A snapshot of a still-alive tab may be adopted too - the resulting duplicate delivery
|
|
404
|
+
* is deduped by the Backend via event ids.
|
|
405
|
+
*/
|
|
406
|
+
restoreOrphanedQueues() {
|
|
407
|
+
if (!this.cfg.persistQueue) return;
|
|
408
|
+
try {
|
|
409
|
+
const prefix = `${this.cfg.localStorageKeyPrefix}.q.`;
|
|
410
|
+
const keys = [];
|
|
411
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
412
|
+
const key = localStorage.key(i);
|
|
413
|
+
if (key?.startsWith(prefix)) keys.push(key);
|
|
414
|
+
}
|
|
415
|
+
if (!keys.length) return;
|
|
416
|
+
const minTs = Date.now() - this.cfg.maxPersistedAge;
|
|
417
|
+
for (const key of keys) try {
|
|
418
|
+
const events = JSON.parse(localStorage.getItem(key) || "[]");
|
|
419
|
+
localStorage.removeItem(key);
|
|
420
|
+
this.queue.push(...events.filter((event) => event.ts >= minTs));
|
|
421
|
+
} catch {
|
|
422
|
+
localStorage.removeItem(key);
|
|
423
|
+
}
|
|
424
|
+
if (this.queue.length > this.cfg.maxQueueSize) this.queue.splice(0, this.queue.length - this.cfg.maxQueueSize);
|
|
425
|
+
if (this.queue.length) {
|
|
426
|
+
this.persistQueue();
|
|
427
|
+
this.scheduleFlush();
|
|
428
|
+
}
|
|
429
|
+
} catch {}
|
|
430
|
+
}
|
|
431
|
+
scheduleFlush() {
|
|
432
|
+
if (this.flushTimer || isServerSide()) return;
|
|
433
|
+
let delayMs = this.cfg.flushInterval;
|
|
434
|
+
if (this.consecutiveFailures) {
|
|
435
|
+
delayMs = Math.min(this.cfg.flushInterval * 2 ** this.consecutiveFailures, this.cfg.maxRetryBackoff);
|
|
436
|
+
delayMs = Math.max(delayMs, this.retryAfter);
|
|
437
|
+
}
|
|
438
|
+
this.flushTimer = setTimeout(() => {
|
|
439
|
+
this.flushTimer = void 0;
|
|
440
|
+
this.flush();
|
|
441
|
+
}, delayMs);
|
|
442
|
+
}
|
|
443
|
+
clearFlushTimer() {
|
|
444
|
+
if (!this.flushTimer) return;
|
|
445
|
+
clearTimeout(this.flushTimer);
|
|
446
|
+
this.flushTimer = void 0;
|
|
447
|
+
}
|
|
448
|
+
removeFromQueue(batch) {
|
|
449
|
+
const ids = new Set(batch.map((event) => event.id));
|
|
450
|
+
this.queue = this.queue.filter((event) => !ids.has(event.id));
|
|
451
|
+
this.persistQueue();
|
|
452
|
+
}
|
|
453
|
+
persistQueue() {
|
|
454
|
+
if (!this.cfg.persistQueue) return;
|
|
455
|
+
try {
|
|
456
|
+
if (this.queue.length) localStorage.setItem(this.queueKey, _safeJsonStringify(this.queue));
|
|
457
|
+
else localStorage.removeItem(this.queueKey);
|
|
458
|
+
} catch {}
|
|
459
|
+
}
|
|
460
|
+
get queueKey() {
|
|
461
|
+
return `${this.cfg.localStorageKeyPrefix}.q.${this.tabId}`;
|
|
462
|
+
}
|
|
463
|
+
};
|
|
553
464
|
/**
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
const persisted = getCookieValues(this.cfg.persistenceKey);
|
|
717
|
-
if (!persisted.includes(value)) {
|
|
718
|
-
this.reportError(new AnalyticsClientError('cookie write did not persist', {
|
|
719
|
-
bytes,
|
|
720
|
-
hadPreviousCookie: persisted.length > 0,
|
|
721
|
-
}));
|
|
722
|
-
}
|
|
723
|
-
}
|
|
724
|
-
else {
|
|
725
|
-
localStorage.setItem(this.cfg.persistenceKey, value);
|
|
726
|
-
}
|
|
727
|
-
}
|
|
728
|
-
catch (err) {
|
|
729
|
-
// The identity stays session-scoped in memory
|
|
730
|
-
this.reportError(_errorDataAppend(err, { bytes }));
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
cookieLength(entry) {
|
|
734
|
-
return this.cfg.persistenceKey.length + encodeURIComponent(JSON.stringify(entry)).length;
|
|
735
|
-
}
|
|
736
|
-
reportError(err) {
|
|
737
|
-
try {
|
|
738
|
-
this.cfg.onError(err);
|
|
739
|
-
}
|
|
740
|
-
catch {
|
|
741
|
-
// A consumer hook must not break identity updates
|
|
742
|
-
}
|
|
743
|
-
}
|
|
744
|
-
}
|
|
465
|
+
* Distinct-id generation and persistence:
|
|
466
|
+
*
|
|
467
|
+
* - a new identity is a UUID v4 device id, stored as `$device_id`,
|
|
468
|
+
* with `distinct_id` derived from it by `generateDistinctId`
|
|
469
|
+
* - `identify(userId)` sets `distinct_id` and `user_id`, keeping `$device_id` (same person)
|
|
470
|
+
* - `reset()` clears the whole entry and generates a fresh anonymous identity (unrelated person)
|
|
471
|
+
* - the identity is stored as a JSON object under a single cookie / localStorage name
|
|
472
|
+
*
|
|
473
|
+
* Apps sharing a persistenceName and cookie domain read and write the same identity:
|
|
474
|
+
* whichever writes first, the others adopt it. Properties they keep in the same entry
|
|
475
|
+
* are preserved on write, never interpreted.
|
|
476
|
+
*
|
|
477
|
+
* Storage failures (SSR, blocked cookies/localStorage) degrade to an in-memory session-scoped
|
|
478
|
+
* identity - analytics must never break the app.
|
|
479
|
+
*/
|
|
480
|
+
var AnalyticsIdentity = class {
|
|
481
|
+
constructor(cfg) {
|
|
482
|
+
this.cfg = {
|
|
483
|
+
onError: _noop,
|
|
484
|
+
cookieDomain: "",
|
|
485
|
+
expireDays: 365,
|
|
486
|
+
secureCookie: false,
|
|
487
|
+
generateDistinctId: (deviceId) => `$device:${deviceId}`,
|
|
488
|
+
...cfg
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
cfg;
|
|
492
|
+
/**
|
|
493
|
+
* Fallback identity for when storage is unavailable, and the last-known-good copy
|
|
494
|
+
* if storage becomes unreadable later.
|
|
495
|
+
*/
|
|
496
|
+
memoryEntry = {};
|
|
497
|
+
hasRefreshedExpiry = false;
|
|
498
|
+
getDistinctId() {
|
|
499
|
+
return this.ensureIdentity().distinct_id;
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* The bare (unprefixed) device UUID. Undefined for legacy identities persisted before
|
|
503
|
+
* a device id was stored (their `distinct_id` has no device prefix either).
|
|
504
|
+
*/
|
|
505
|
+
getDeviceId() {
|
|
506
|
+
return this.ensureIdentity().$device_id;
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* Reads any property of the persisted entry: the acquisition props maintained by
|
|
510
|
+
* updateAcquisitionProps(), or props written by another app sharing the entry.
|
|
511
|
+
*/
|
|
512
|
+
getProperty(key) {
|
|
513
|
+
return this.loadEntry()[key];
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* The acquisition props that can't be derived from event payloads, and are stored separately.
|
|
517
|
+
*/
|
|
518
|
+
getAcquisitionProps() {
|
|
519
|
+
const entry = this.loadEntry();
|
|
520
|
+
const props = _filterObject(entry, (k) => String(k).startsWith(UTM_QUERY_PARAM_PREFIX));
|
|
521
|
+
const { firstTouch } = entry;
|
|
522
|
+
if (firstTouch) props["initial_referrer"] = firstTouch.referrer;
|
|
523
|
+
return props;
|
|
524
|
+
}
|
|
525
|
+
/** The captured first touch, as the props to `$set_once` on the profile. */
|
|
526
|
+
getFirstTouchProps() {
|
|
527
|
+
const { firstTouch } = this.loadEntry();
|
|
528
|
+
if (!firstTouch) return;
|
|
529
|
+
return {
|
|
530
|
+
...firstTouch.utms,
|
|
531
|
+
initial_referrer: firstTouch.referrer
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* Sets the identity going forward, e.g after a successful signup/login.
|
|
536
|
+
* `$device_id` is kept, so the destination can merge the pre-identify
|
|
537
|
+
* anonymous events into the same user.
|
|
538
|
+
*/
|
|
539
|
+
identify(userId) {
|
|
540
|
+
const entry = this.ensureIdentity();
|
|
541
|
+
entry.$device_id ||= entry.distinct_id;
|
|
542
|
+
entry.user_id = userId;
|
|
543
|
+
entry.distinct_id = entry.user_id;
|
|
544
|
+
this.saveEntry(entry);
|
|
545
|
+
}
|
|
546
|
+
/**
|
|
547
|
+
* Clears the whole persisted entry and generates a fresh anonymous identity.
|
|
548
|
+
* Call only when switching to an UNRELATED identity (e.g logout): everything else stored
|
|
549
|
+
* in the entry may belong to the previous user, so it goes too.
|
|
550
|
+
*/
|
|
551
|
+
reset() {
|
|
552
|
+
const deviceId = crypto.randomUUID();
|
|
553
|
+
this.saveEntry({
|
|
554
|
+
distinct_id: this.cfg.generateDistinctId(deviceId),
|
|
555
|
+
$device_id: deviceId
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
/** Collects properties of the user that can be used to attribute traffic. */
|
|
559
|
+
updateAcquisitionProps() {
|
|
560
|
+
if (isServerSide()) return;
|
|
561
|
+
const entry = this.loadEntry();
|
|
562
|
+
const url = new URL(globalThis.location.href);
|
|
563
|
+
Object.assign(entry, getLastTouchUtms(url));
|
|
564
|
+
entry.firstTouch ||= { referrer: getReferrer() };
|
|
565
|
+
entry.firstTouch.utms ||= getFirstTouchUtms(url);
|
|
566
|
+
this.saveEntry(entry);
|
|
567
|
+
}
|
|
568
|
+
ensureIdentity() {
|
|
569
|
+
const entry = this.loadEntry();
|
|
570
|
+
if (entry.distinct_id) this.refreshExpiry(entry);
|
|
571
|
+
else {
|
|
572
|
+
const deviceId = crypto.randomUUID();
|
|
573
|
+
entry.distinct_id = this.cfg.generateDistinctId(deviceId);
|
|
574
|
+
entry.$device_id = deviceId;
|
|
575
|
+
this.saveEntry(entry);
|
|
576
|
+
}
|
|
577
|
+
return entry;
|
|
578
|
+
}
|
|
579
|
+
/**
|
|
580
|
+
* The cookie expiration window slides: expireDays counts from the LAST visit, not the
|
|
581
|
+
* first. Re-saved once per instance (in practice - once per pageload).
|
|
582
|
+
*/
|
|
583
|
+
refreshExpiry(entry) {
|
|
584
|
+
if (this.hasRefreshedExpiry || this.cfg.persistence !== "cookie") return;
|
|
585
|
+
this.saveEntry(entry);
|
|
586
|
+
}
|
|
587
|
+
loadEntry() {
|
|
588
|
+
try {
|
|
589
|
+
const raw = this.cfg.persistence === "cookie" ? getCookie(this.cfg.persistenceKey) : localStorage.getItem(this.cfg.persistenceKey);
|
|
590
|
+
if (raw) this.memoryEntry = JSON.parse(raw);
|
|
591
|
+
} catch {}
|
|
592
|
+
return this.memoryEntry;
|
|
593
|
+
}
|
|
594
|
+
saveEntry(entry) {
|
|
595
|
+
this.memoryEntry = entry;
|
|
596
|
+
this.hasRefreshedExpiry = true;
|
|
597
|
+
let bytes = 0;
|
|
598
|
+
try {
|
|
599
|
+
const value = JSON.stringify(entry);
|
|
600
|
+
bytes = value.length;
|
|
601
|
+
if (this.cfg.persistence === "cookie") {
|
|
602
|
+
bytes = this.cookieLength(entry);
|
|
603
|
+
if (bytes > MAX_COOKIE_LENGTH) {
|
|
604
|
+
this.reportError(new AnalyticsClientError("cookie exceeded the length limit", { bytes }));
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
setCookie(this.cfg.persistenceKey, value, this.cfg.expireDays, this.cfg.cookieDomain, this.cfg.secureCookie);
|
|
608
|
+
const persisted = getCookieValues(this.cfg.persistenceKey);
|
|
609
|
+
if (!persisted.includes(value)) this.reportError(new AnalyticsClientError("cookie write did not persist", {
|
|
610
|
+
bytes,
|
|
611
|
+
hadPreviousCookie: persisted.length > 0
|
|
612
|
+
}));
|
|
613
|
+
} else localStorage.setItem(this.cfg.persistenceKey, value);
|
|
614
|
+
} catch (err) {
|
|
615
|
+
this.reportError(_errorDataAppend(err, { bytes }));
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
cookieLength(entry) {
|
|
619
|
+
return this.cfg.persistenceKey.length + encodeURIComponent(JSON.stringify(entry)).length;
|
|
620
|
+
}
|
|
621
|
+
reportError(err) {
|
|
622
|
+
try {
|
|
623
|
+
this.cfg.onError(err);
|
|
624
|
+
} catch {}
|
|
625
|
+
}
|
|
626
|
+
};
|
|
745
627
|
/** The non-empty canonical `utm_*` params of the given url. */
|
|
746
628
|
function getLastTouchUtms(url) {
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
return props;
|
|
629
|
+
const props = {};
|
|
630
|
+
for (const param of CANONICAL_UTM_PARAMS) {
|
|
631
|
+
const value = url.searchParams.get(param);
|
|
632
|
+
if (value) props[param] = truncateAnalyticsProperty(value);
|
|
633
|
+
}
|
|
634
|
+
return props;
|
|
754
635
|
}
|
|
755
636
|
/** The referrer of this pageload, or null when it has none (a direct visit). */
|
|
756
637
|
function getReferrer() {
|
|
757
|
-
|
|
638
|
+
return truncateAnalyticsProperty(document.referrer) || null;
|
|
758
639
|
}
|
|
759
640
|
/** Captures all utms if any are set, otherwise none */
|
|
760
641
|
function getFirstTouchUtms(url) {
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
return;
|
|
768
|
-
return utms;
|
|
642
|
+
const utms = _mapToObject(CANONICAL_UTM_PARAMS, (param) => {
|
|
643
|
+
const value = url.searchParams.get(param);
|
|
644
|
+
return [`initial_${param}`, value ? truncateAnalyticsProperty(value) : null];
|
|
645
|
+
});
|
|
646
|
+
if (_isEmptyObject(_filterNullishValues(utms))) return;
|
|
647
|
+
return utms;
|
|
769
648
|
}
|
|
770
649
|
function getQueryProperties(url, keys) {
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
650
|
+
return Object.fromEntries(keys.flatMap((key) => {
|
|
651
|
+
const value = url.searchParams.get(key);
|
|
652
|
+
return value ? [[key, value]] : [];
|
|
653
|
+
}));
|
|
775
654
|
}
|
|
776
|
-
|
|
777
|
-
// we measure to stay under the fetch keepalive body quota.
|
|
778
|
-
const textEncoder = new TextEncoder();
|
|
655
|
+
var textEncoder = new TextEncoder();
|
|
779
656
|
function getUtf8ByteLength(value) {
|
|
780
|
-
|
|
657
|
+
return textEncoder.encode(value).byteLength;
|
|
781
658
|
}
|
|
782
659
|
/** The first visible value under this name, or null. */
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
return getCookieValues(name)[0] ?? null;
|
|
660
|
+
function getCookie(name) {
|
|
661
|
+
if (!name) return null;
|
|
662
|
+
return getCookieValues(name)[0] ?? null;
|
|
787
663
|
}
|
|
788
664
|
/**
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
665
|
+
* Every visible value under this name, in `document.cookie` order. A host-only and a
|
|
666
|
+
* parent-domain cookie with the same name and path coexist as separate cookies.
|
|
667
|
+
*/
|
|
792
668
|
function getCookieValues(name) {
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
}
|
|
802
|
-
return values;
|
|
669
|
+
const nameEq = `${name}=`;
|
|
670
|
+
const values = [];
|
|
671
|
+
for (let c of document.cookie.split(";")) {
|
|
672
|
+
while (c.startsWith(" ")) c = c.slice(1);
|
|
673
|
+
if (!c.startsWith(nameEq)) continue;
|
|
674
|
+
values.push(decodeURIComponent(c.slice(nameEq.length)));
|
|
675
|
+
}
|
|
676
|
+
return values;
|
|
803
677
|
}
|
|
804
678
|
/**
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
attrs.push('secure');
|
|
818
|
-
const cookie = attrs.join('; ');
|
|
819
|
-
// The Cookie Store API is async and missing in Safari, so this stays synchronous
|
|
820
|
-
// oxlint-disable-next-line unicorn/no-document-cookie
|
|
821
|
-
document.cookie = cookie;
|
|
822
|
-
return cookie;
|
|
823
|
-
}
|
|
824
|
-
export class AnalyticsClientError extends AppError {
|
|
825
|
-
constructor(message, data) {
|
|
826
|
-
super(message, data, { name: 'AnalyticsClientError' });
|
|
827
|
-
}
|
|
679
|
+
* Writes the cookie and returns what was written, which the tests assert on.
|
|
680
|
+
* `domain` is explicit, e.g `.example.com` to share it across subdomains.
|
|
681
|
+
*/
|
|
682
|
+
function setCookie(name, value, days, domain, isSecure) {
|
|
683
|
+
const attrs = [`${name}=${encodeURIComponent(value)}`];
|
|
684
|
+
if (days) attrs.push(`expires=${new Date(Date.now() + days * 24 * 3600 * 1e3).toUTCString()}`);
|
|
685
|
+
attrs.push("path=/");
|
|
686
|
+
if (domain) attrs.push(`domain=${domain}`);
|
|
687
|
+
if (isSecure) attrs.push("secure");
|
|
688
|
+
const cookie = attrs.join("; ");
|
|
689
|
+
document.cookie = cookie;
|
|
690
|
+
return cookie;
|
|
828
691
|
}
|
|
692
|
+
var AnalyticsClientError = class extends AppError {
|
|
693
|
+
constructor(message, data) {
|
|
694
|
+
super(message, data, { name: "AnalyticsClientError" });
|
|
695
|
+
}
|
|
696
|
+
};
|
|
697
|
+
//#endregion
|
|
698
|
+
export { AnalyticsClient, AnalyticsClientError, AnalyticsIdentity, getCookie, setCookie };
|