-
Notifications
You must be signed in to change notification settings - Fork 222
/
index.ts
executable file
·1341 lines (1177 loc) · 46.4 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2022 Snowplow Analytics Ltd, 2010 Anthon Pang
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import {
trackerCore,
buildPagePing,
buildPageView,
CommonEventProperties,
PayloadBuilder,
SelfDescribingJson,
LOG,
} from '@snowplow/tracker-core';
import hash from 'sha1';
import { v4 as uuid } from 'uuid';
import {
decorateQuerystring,
findRootDomain,
fixupDomain,
getReferrer,
addEventListener,
getHostName,
cookie,
attemptGetLocalStorage,
attemptWriteLocalStorage,
attemptDeleteLocalStorage,
deleteCookie,
fixupTitle,
fromQuerystring,
isInteger,
attemptGetSessionStorage,
attemptWriteSessionStorage,
} from '../helpers';
import { BrowserPlugin } from '../plugins';
import { OutQueueManager } from './out_queue';
import { fixupUrl } from '../proxies';
import { SharedState } from '../state';
import {
PageViewEvent,
ActivityCallback,
ActivityCallbackData,
TrackerConfiguration,
BrowserTracker,
ActivityTrackingConfiguration,
ActivityTrackingConfigurationCallback,
DisableAnonymousTrackingConfiguration,
EnableAnonymousTrackingConfiguration,
FlushBufferConfiguration,
BrowserPluginConfiguration,
ClearUserDataConfiguration,
ClientSession,
} from './types';
import {
parseIdCookie,
initializeDomainUserId,
startNewIdCookieSession,
updateNowTsInIdCookie,
serializeIdCookie,
sessionIdFromIdCookie,
domainUserIdFromIdCookie,
updateFirstEventInIdCookie,
visitCountFromIdCookie,
cookiesEnabledInIdCookie,
ParsedIdCookie,
clientSessionFromIdCookie,
incrementEventIndexInIdCookie,
emptyIdCookie,
eventIndexFromIdCookie,
} from './id_cookie';
import { CLIENT_SESSION_SCHEMA, WEB_PAGE_SCHEMA, BROWSER_CONTEXT_SCHEMA } from './schemata';
import { getBrowserProperties } from '../helpers/browser_props';
declare global {
interface Navigator {
msDoNotTrack: boolean;
}
interface Window {
doNotTrack: boolean;
}
}
/** Represents an instance of an activity tracking configuration */
type ActivityConfig = {
/** The callback to fire based on heart beat */
callback: ActivityCallback;
/** The minimum time that must have elapsed before first heartbeat */
configMinimumVisitLength: number;
/** The interval at which the callback will be fired */
configHeartBeatTimer: number;
/** The setInterval identifier */
activityInterval?: number;
};
/** The configurations for the two types of Activity Tracking */
type ActivityConfigurations = {
/** The configuration for enableActivityTrackingCallback */
callback?: ActivityConfig;
/** The configuration for enableActivityTracking */
pagePing?: ActivityConfig;
};
/** The configuration for if either activity tracking system is enable */
type ActivityTrackingConfig = {
/** Tracks if activity tracking is enabled */
enabled: boolean;
/** Tracks if activity tracking hooks have been installed */
installed: boolean;
/** Stores the configuration for each type of activity tracking */
configurations: ActivityConfigurations;
};
/**
* The Snowplow Tracker
*
* @param trackerId - The unique identifier of the tracker
* @param namespace - The namespace of the tracker object
* @param version - The current version of the JavaScript Tracker
* @param endpoint - The collector endpoint to send events to, with or without protocol
* @param sharedState - An object containing state which is shared across tracker instances
* @param trackerConfiguration - Dictionary of configuration options
*/
export function Tracker(
trackerId: string,
namespace: string,
version: string,
endpoint: string,
sharedState: SharedState,
trackerConfiguration: TrackerConfiguration = {}
): BrowserTracker {
const browserPlugins: Array<BrowserPlugin> = [];
const newTracker = (
trackerId: string,
namespace: string,
version: string,
endpoint: string,
state: SharedState,
trackerConfiguration: TrackerConfiguration
) => {
/************************************************************
* Private members
************************************************************/
//use POST if eventMethod isn't present on the newTrackerConfiguration
trackerConfiguration.eventMethod = trackerConfiguration.eventMethod ?? 'post';
const getStateStorageStrategy = (config: TrackerConfiguration) =>
config.stateStorageStrategy ?? 'cookieAndLocalStorage',
getAnonymousSessionTracking = (config: TrackerConfiguration) => {
if (typeof config.anonymousTracking === 'boolean') {
return false;
}
return config.anonymousTracking?.withSessionTracking === true ?? false;
},
getAnonymousServerTracking = (config: TrackerConfiguration) => {
if (typeof config.anonymousTracking === 'boolean') {
return false;
}
return config.anonymousTracking?.withServerAnonymisation === true ?? false;
},
getAnonymousTracking = (config: TrackerConfiguration) => !!config.anonymousTracking,
isBrowserContextAvailable = trackerConfiguration?.contexts?.browser ?? false,
isWebPageContextAvailable = trackerConfiguration?.contexts?.webPage ?? true;
// Get all injected plugins
browserPlugins.push(getBrowserDataPlugin());
/* When including the Web Page context, we add the relevant internal plugins */
if (isWebPageContextAvailable) {
browserPlugins.push(getWebPagePlugin());
}
if (isBrowserContextAvailable) {
browserPlugins.push(getBrowserContextPlugin());
}
browserPlugins.push(...(trackerConfiguration.plugins ?? []));
let // Tracker core
core = trackerCore({
base64: trackerConfiguration.encodeBase64,
corePlugins: browserPlugins,
callback: sendRequest,
}),
// Aliases
documentCharset = document.characterSet || document.charset,
// Current URL and Referrer URL
locationArray = fixupUrl(window.location.hostname, window.location.href, getReferrer()),
domainAlias = fixupDomain(locationArray[0]),
locationHrefAlias = locationArray[1],
configReferrerUrl = locationArray[2],
customReferrer: string,
// Platform defaults to web for this tracker
configPlatform = trackerConfiguration.platform ?? 'web',
// Snowplow collector URL
configCollectorUrl = asCollectorUrl(endpoint),
// Custom path for post requests (to get around adblockers)
configPostPath = trackerConfiguration.postPath ?? '/com.snowplowanalytics.snowplow/tp2',
// Site ID
configTrackerSiteId = trackerConfiguration.appId ?? '',
// Document URL
configCustomUrl: string,
// Document title
lastDocumentTitle = document.title,
// Custom title
lastConfigTitle: string | null | undefined,
// Controls whether activity tracking page ping event timers are reset on page view events
resetActivityTrackingOnPageView = trackerConfiguration.resetActivityTrackingOnPageView ?? true,
// Disallow hash tags in URL. TODO: Should this be set to true by default?
configDiscardHashTag: boolean,
// Disallow brace in URL.
configDiscardBrace: boolean,
// First-party cookie name prefix
configCookieNamePrefix = trackerConfiguration.cookieName ?? '_sp_',
// First-party cookie domain
// User agent defaults to origin hostname
configCookieDomain = trackerConfiguration.cookieDomain ?? undefined,
// First-party cookie path
// Default is user agent defined.
configCookiePath = '/',
// First-party cookie samesite attribute
configCookieSameSite = trackerConfiguration.cookieSameSite ?? 'None',
// First-party cookie secure attribute
configCookieSecure = trackerConfiguration.cookieSecure ?? true,
// Do Not Track browser feature
dnt = navigator.doNotTrack || navigator.msDoNotTrack || window.doNotTrack,
// Do Not Track
configDoNotTrack =
typeof trackerConfiguration.respectDoNotTrack !== 'undefined'
? trackerConfiguration.respectDoNotTrack && (dnt === 'yes' || dnt === '1')
: false,
// Opt out of cookie tracking
configOptOutCookie: string | null | undefined,
// Life of the visitor cookie (in seconds)
configVisitorCookieTimeout = trackerConfiguration.cookieLifetime ?? 63072000, // 2 years
// Life of the session cookie (in seconds)
configSessionCookieTimeout = trackerConfiguration.sessionCookieTimeout ?? 1800, // 30 minutes
// Allows tracking user session (using cookies or local storage), can only be used with anonymousTracking
configAnonymousSessionTracking = getAnonymousSessionTracking(trackerConfiguration),
// Will send a header to server to prevent returning cookie and capturing IP
configAnonymousServerTracking = getAnonymousServerTracking(trackerConfiguration),
// Sets tracker to work in anonymous mode without accessing client storage
configAnonymousTracking = getAnonymousTracking(trackerConfiguration),
// Strategy defining how to store the state: cookie, localStorage, cookieAndLocalStorage or none
configStateStorageStrategy = getStateStorageStrategy(trackerConfiguration),
// Last activity timestamp
lastActivityTime: number,
// The last time an event was fired on the page - used to invalidate session if cookies are disabled
lastEventTime = new Date().getTime(),
// How are we scrolling?
minXOffset: number,
maxXOffset: number,
minYOffset: number,
maxYOffset: number,
// Domain hash value
domainHash: string,
// Domain unique user ID
domainUserId: string,
// ID for the current session
memorizedSessionId: string,
// Index for the current session - kept in memory in case cookies are disabled
memorizedVisitCount = 1,
// Business-defined unique user ID
businessUserId: string | null | undefined,
// Manager for local storage queue
outQueue = OutQueueManager(
trackerId,
state,
configStateStorageStrategy == 'localStorage' || configStateStorageStrategy == 'cookieAndLocalStorage',
trackerConfiguration.eventMethod,
configPostPath,
trackerConfiguration.bufferSize ?? 1,
trackerConfiguration.maxPostBytes ?? 40000,
trackerConfiguration.maxGetBytes ?? 0,
trackerConfiguration.useStm ?? true,
trackerConfiguration.maxLocalStorageQueueSize ?? 1000,
trackerConfiguration.connectionTimeout ?? 5000,
configAnonymousServerTracking,
trackerConfiguration.customHeaders ?? {},
trackerConfiguration.withCredentials ?? true,
trackerConfiguration.retryStatusCodes ?? [],
(trackerConfiguration.dontRetryStatusCodes ?? []).concat([400, 401, 403, 410, 422]),
trackerConfiguration.idService
),
// Whether pageViewId should be regenerated after each trackPageView. Affect web_page context
preservePageViewId = false,
// Whether first trackPageView was fired and pageViewId should not be changed anymore until reload
pageViewSent = false,
// Activity tracking config for callback and page ping variants
activityTrackingConfig: ActivityTrackingConfig = {
enabled: false,
installed: false, // Guard against installing the activity tracker more than once per Tracker instance
configurations: {},
},
configSessionContext = trackerConfiguration.contexts?.session ?? false,
toOptoutByCookie: string | boolean,
onSessionUpdateCallback = trackerConfiguration.onSessionUpdateCallback,
manualSessionUpdateCalled = false;
if (trackerConfiguration.hasOwnProperty('discoverRootDomain') && trackerConfiguration.discoverRootDomain) {
configCookieDomain = findRootDomain(configCookieSameSite, configCookieSecure);
}
const { browserLanguage, resolution, colorDepth, cookiesEnabled } = getBrowserProperties();
// Set up unchanging name-value pairs
core.setTrackerVersion(version);
core.setTrackerNamespace(namespace);
core.setAppId(configTrackerSiteId);
core.setPlatform(configPlatform);
core.addPayloadPair('cookie', cookiesEnabled ? '1' : '0');
core.addPayloadPair('cs', documentCharset);
core.addPayloadPair('lang', browserLanguage);
core.addPayloadPair('res', resolution);
core.addPayloadPair('cd', colorDepth);
/*
* Initialize tracker
*/
updateDomainHash();
initializeIdsAndCookies();
if (trackerConfiguration.crossDomainLinker) {
decorateLinks(trackerConfiguration.crossDomainLinker);
}
/**
* Recalculate the domain, URL, and referrer
*/
function refreshUrl() {
locationArray = fixupUrl(window.location.hostname, window.location.href, getReferrer());
// If this is a single-page app and the page URL has changed, then:
// - if the new URL's querystring contains a "refer(r)er" parameter, use it as the referrer
// - otherwise use the old URL as the referer
if (locationArray[1] !== locationHrefAlias) {
configReferrerUrl = getReferrer(locationHrefAlias);
}
domainAlias = fixupDomain(locationArray[0]);
locationHrefAlias = locationArray[1];
}
/**
* Decorate the querystring of a single link
*
* @param event - e The event targeting the link
*/
function linkDecorationHandler(evt: Event) {
const timestamp = new Date().getTime();
const elt = evt.currentTarget as HTMLAnchorElement | HTMLAreaElement | null;
if (elt?.href) {
elt.href = decorateQuerystring(elt.href, '_sp', domainUserId + '.' + timestamp);
}
}
/**
* Enable querystring decoration for links pasing a filter
* Whenever such a link is clicked on or navigated to via the keyboard,
* add "_sp={{duid}}.{{timestamp}}" to its querystring
*
* @param crossDomainLinker - Function used to determine which links to decorate
*/
function decorateLinks(crossDomainLinker: (elt: HTMLAnchorElement | HTMLAreaElement) => boolean) {
for (let i = 0; i < document.links.length; i++) {
const elt = document.links[i];
if (!(elt as any).spDecorationEnabled && crossDomainLinker(elt)) {
addEventListener(elt, 'click', linkDecorationHandler, true);
addEventListener(elt, 'mousedown', linkDecorationHandler, true);
// Don't add event listeners more than once
(elt as any).spDecorationEnabled = true;
}
}
}
/*
* Removes hash tag from the URL
*
* URLs are purified before being recorded in the cookie,
* or before being sent as GET parameters
*/
function purify(url: string) {
let targetPattern;
if (configDiscardHashTag) {
targetPattern = new RegExp('#.*');
url = url.replace(targetPattern, '');
}
if (configDiscardBrace) {
targetPattern = new RegExp('[{}]', 'g');
url = url.replace(targetPattern, '');
}
return url;
}
/*
* Extract scheme/protocol from URL
*/
function getProtocolScheme(url: string) {
const e = new RegExp('^([a-z]+):'),
matches = e.exec(url);
return matches ? matches[1] : null;
}
/*
* Resolve relative reference
*
* Note: not as described in rfc3986 section 5.2
*/
function resolveRelativeReference(baseUrl: string, url: string) {
let protocol = getProtocolScheme(url),
i;
if (protocol) {
return url;
}
if (url.slice(0, 1) === '/') {
return getProtocolScheme(baseUrl) + '://' + getHostName(baseUrl) + url;
}
baseUrl = purify(baseUrl);
if ((i = baseUrl.indexOf('?')) >= 0) {
baseUrl = baseUrl.slice(0, i);
}
if ((i = baseUrl.lastIndexOf('/')) !== baseUrl.length - 1) {
baseUrl = baseUrl.slice(0, i + 1);
}
return baseUrl + url;
}
/*
* Send request
*/
function sendRequest(request: PayloadBuilder) {
if (!(configDoNotTrack || toOptoutByCookie)) {
outQueue.enqueueRequest(request.build(), configCollectorUrl);
}
}
/*
* Get cookie name with prefix and domain hash
*/
function getSnowplowCookieName(baseName: string) {
return configCookieNamePrefix + baseName + '.' + domainHash;
}
/*
* Cookie getter.
*/
function getSnowplowCookieValue(cookieName: string) {
const fullName = getSnowplowCookieName(cookieName);
if (configStateStorageStrategy == 'localStorage') {
return attemptGetLocalStorage(fullName);
} else if (configStateStorageStrategy == 'cookie' || configStateStorageStrategy == 'cookieAndLocalStorage') {
return cookie(fullName);
}
return undefined;
}
/*
* Update domain hash
*/
function updateDomainHash() {
refreshUrl();
domainHash = hash((configCookieDomain || domainAlias) + (configCookiePath || '/')).slice(0, 4); // 4 hexits = 16 bits
}
/*
* Process all "activity" events.
* For performance, this function must have low overhead.
*/
function activityHandler() {
const now = new Date();
lastActivityTime = now.getTime();
}
/*
* Process all "scroll" events.
*/
function scrollHandler() {
updateMaxScrolls();
activityHandler();
}
/*
* Returns [pageXOffset, pageYOffset]
*/
function getPageOffsets() {
const documentElement = document.documentElement;
if (documentElement) {
return [documentElement.scrollLeft || window.pageXOffset, documentElement.scrollTop || window.pageYOffset];
}
return [0, 0];
}
/*
* Quick initialization/reset of max scroll levels
*/
function resetMaxScrolls() {
const offsets = getPageOffsets();
const x = offsets[0];
minXOffset = x;
maxXOffset = x;
const y = offsets[1];
minYOffset = y;
maxYOffset = y;
}
/*
* Check the max scroll levels, updating as necessary
*/
function updateMaxScrolls() {
const offsets = getPageOffsets();
const x = offsets[0];
if (x < minXOffset) {
minXOffset = x;
} else if (x > maxXOffset) {
maxXOffset = x;
}
const y = offsets[1];
if (y < minYOffset) {
minYOffset = y;
} else if (y > maxYOffset) {
maxYOffset = y;
}
}
/*
* Prevents offsets from being decimal or NaN
* See https://github.com/snowplow/snowplow-javascript-tracker/issues/324
*/
function cleanOffset(offset: number) {
return Math.round(offset);
}
/**
* Sets or renews the session cookie.
* Responsible for calling the `onSessionUpdateCallback` callback.
* @returns {boolean} If the value persisted in cookies or LocalStorage
*/
function setSessionCookie() {
const cookieName = getSnowplowCookieName('ses');
const cookieValue = '*';
return persistValue(cookieName, cookieValue, configSessionCookieTimeout);
}
/**
* @mutates idCookie
* @param {ParsedIdCookie} idCookie
* @returns {boolean} If the value persisted in cookies or LocalStorage
*/
function setDomainUserIdCookie(idCookie: ParsedIdCookie) {
const cookieName = getSnowplowCookieName('id');
const cookieValue = serializeIdCookie(idCookie);
return persistValue(cookieName, cookieValue, configVisitorCookieTimeout);
}
/**
* no-op if anonymousTracking enabled, will still set cookies if anonymousSessionTracking is enabled
* Sets a cookie based on the storage strategy:
* - if 'localStorage': attempts to write to local storage
* - if 'cookie' or 'cookieAndLocalStorage': writes to cookies
* - otherwise: no-op
* @param {string} name Name/key of the value to persist
* @param {string} value
* @param {number} timeout Used as the expiration date for cookies or as a TTL to be checked on LocalStorage
* @returns {boolean} If the operation was successful or not
*/
function persistValue(name: string, value: string, timeout: number): boolean {
if (configAnonymousTracking && !configAnonymousSessionTracking) {
return false;
}
if (configStateStorageStrategy == 'localStorage') {
return attemptWriteLocalStorage(name, value, timeout);
} else if (configStateStorageStrategy == 'cookie' || configStateStorageStrategy == 'cookieAndLocalStorage') {
cookie(name, value, timeout, configCookiePath, configCookieDomain, configCookieSameSite, configCookieSecure);
return document.cookie.indexOf(`${name}=`) !== -1 ? true : false;
}
return false;
}
/**
* Clears all cookie and local storage for id and ses values
*/
function clearUserDataAndCookies(configuration?: ClearUserDataConfiguration) {
const idname = getSnowplowCookieName('id');
const sesname = getSnowplowCookieName('ses');
attemptDeleteLocalStorage(idname);
attemptDeleteLocalStorage(sesname);
deleteCookie(idname, configCookieDomain, configCookieSameSite, configCookieSecure);
deleteCookie(sesname, configCookieDomain, configCookieSameSite, configCookieSecure);
if (!configuration?.preserveSession) {
memorizedSessionId = uuid();
memorizedVisitCount = 1;
}
if (!configuration?.preserveUser) {
domainUserId = configAnonymousTracking ? '' : uuid();
businessUserId = null;
}
}
/**
* Toggle Anonymous Tracking
*/
function toggleAnonymousTracking(
configuration?: EnableAnonymousTrackingConfiguration | DisableAnonymousTrackingConfiguration
) {
if (configuration && configuration.stateStorageStrategy) {
trackerConfiguration.stateStorageStrategy = configuration.stateStorageStrategy;
configStateStorageStrategy = getStateStorageStrategy(trackerConfiguration);
}
configAnonymousTracking = getAnonymousTracking(trackerConfiguration);
configAnonymousSessionTracking = getAnonymousSessionTracking(trackerConfiguration);
configAnonymousServerTracking = getAnonymousServerTracking(trackerConfiguration);
outQueue.setUseLocalStorage(
configStateStorageStrategy == 'localStorage' || configStateStorageStrategy == 'cookieAndLocalStorage'
);
outQueue.setAnonymousTracking(configAnonymousServerTracking);
}
/*
* Load the domain user ID and the session ID
* Set the cookies (if cookies are enabled)
*/
function initializeIdsAndCookies() {
if (configAnonymousTracking && !configAnonymousSessionTracking) {
return;
}
const sesCookieSet = configStateStorageStrategy != 'none' && !!getSnowplowCookieValue('ses');
const idCookie = loadDomainUserIdCookie();
domainUserId = initializeDomainUserId(idCookie, configAnonymousTracking);
if (!sesCookieSet) {
memorizedSessionId = startNewIdCookieSession(idCookie);
} else {
memorizedSessionId = sessionIdFromIdCookie(idCookie);
}
memorizedVisitCount = visitCountFromIdCookie(idCookie);
if (configStateStorageStrategy != 'none') {
setSessionCookie();
// Update currentVisitTs
updateNowTsInIdCookie(idCookie);
setDomainUserIdCookie(idCookie);
}
}
/*
* Load visitor ID cookie
*/
function loadDomainUserIdCookie() {
if (configStateStorageStrategy == 'none') {
return emptyIdCookie();
}
const id = getSnowplowCookieValue('id') || undefined;
return parseIdCookie(id, domainUserId, memorizedSessionId, memorizedVisitCount);
}
/**
* Adds the protocol in front of our collector URL
*
* @param string - collectorUrl The collector URL with or without protocol
* @returns string collectorUrl The tracker URL with protocol
*/
function asCollectorUrl(collectorUrl: string) {
if (collectorUrl.indexOf('http') === 0) {
return collectorUrl;
}
return ('https:' === document.location.protocol ? 'https' : 'http') + '://' + collectorUrl;
}
/**
* Initialize new `pageViewId` if it shouldn't be preserved.
* Should be called when `trackPageView` is invoked
*/
function resetPageView() {
if (!preservePageViewId || state.pageViewId == null) {
state.pageViewId = uuid();
}
}
/**
* Safe function to get `pageViewId`.
* Generates it if it wasn't initialized by other tracker
*/
function getPageViewId() {
if (state.pageViewId == null) {
state.pageViewId = uuid();
}
return state.pageViewId;
}
/**
* Safe function to get `tabId`.
* Generates it if it is not yet initialized. Shared between trackers.
*/
function getTabId() {
if (configStateStorageStrategy === 'none' || configAnonymousTracking || !isWebPageContextAvailable) {
return null;
}
const SESSION_STORAGE_TAB_ID = '_sp_tab_id';
let tabId = attemptGetSessionStorage(SESSION_STORAGE_TAB_ID);
if (!tabId) {
attemptWriteSessionStorage(SESSION_STORAGE_TAB_ID, uuid());
tabId = attemptGetSessionStorage(SESSION_STORAGE_TAB_ID);
}
return tabId || null;
}
/**
* Put together a web page context with a unique UUID for the page view
*
* @returns web_page context
*/
function getWebPagePlugin() {
return {
contexts: () => {
return [
{
schema: WEB_PAGE_SCHEMA,
data: {
id: getPageViewId(),
},
},
];
},
};
}
function getBrowserContextPlugin() {
return {
contexts: () => {
return [
{
schema: BROWSER_CONTEXT_SCHEMA,
data: {
...getBrowserProperties(),
tabId: getTabId(),
},
},
];
},
};
}
/*
* Attaches common web fields to every request (resolution, url, referrer, etc.)
* Also sets the required cookies.
*/
function getBrowserDataPlugin() {
const anonymizeOr = (value?: string | number | null) => (configAnonymousTracking ? null : value);
const anonymizeSessionOr = (value?: string | number | null) =>
configAnonymousSessionTracking ? value : anonymizeOr(value);
return {
beforeTrack: (payloadBuilder: PayloadBuilder) => {
const existingSession = getSnowplowCookieValue('ses'),
idCookie = loadDomainUserIdCookie();
const isFirstEventInSession = eventIndexFromIdCookie(idCookie) === 0;
if (configOptOutCookie) {
toOptoutByCookie = !!cookie(configOptOutCookie);
} else {
toOptoutByCookie = false;
}
if (configDoNotTrack || toOptoutByCookie) {
clearUserDataAndCookies();
return;
}
// If cookies are enabled, base visit count and session ID on the cookies
if (cookiesEnabledInIdCookie(idCookie)) {
// New session?
if (!existingSession && configStateStorageStrategy != 'none') {
memorizedSessionId = startNewIdCookieSession(idCookie);
} else {
memorizedSessionId = sessionIdFromIdCookie(idCookie);
}
memorizedVisitCount = visitCountFromIdCookie(idCookie);
} else if (new Date().getTime() - lastEventTime > configSessionCookieTimeout * 1000) {
memorizedVisitCount++;
memorizedSessionId = startNewIdCookieSession(idCookie, {
memorizedVisitCount,
});
}
// Update cookie
updateNowTsInIdCookie(idCookie);
updateFirstEventInIdCookie(idCookie, payloadBuilder);
incrementEventIndexInIdCookie(idCookie);
const { viewport, documentSize } = getBrowserProperties();
payloadBuilder.add('vp', viewport);
payloadBuilder.add('ds', documentSize);
payloadBuilder.add('vid', anonymizeSessionOr(memorizedVisitCount));
payloadBuilder.add('sid', anonymizeSessionOr(memorizedSessionId));
payloadBuilder.add('duid', anonymizeOr(domainUserIdFromIdCookie(idCookie))); // Always load from cookie as this is better etiquette than in-memory values
payloadBuilder.add('uid', anonymizeOr(businessUserId));
refreshUrl();
payloadBuilder.add('refr', purify(customReferrer || configReferrerUrl));
// Add the page URL last as it may take us over the IE limit (and we don't always need it)
payloadBuilder.add('url', purify(configCustomUrl || locationHrefAlias));
const clientSession = clientSessionFromIdCookie(
idCookie,
configStateStorageStrategy,
configAnonymousTracking
);
if (configSessionContext && (!configAnonymousTracking || configAnonymousSessionTracking)) {
addSessionContextToPayload(payloadBuilder, clientSession);
}
// Update cookies
if (configStateStorageStrategy != 'none') {
setDomainUserIdCookie(idCookie);
const sessionIdentifierPersisted = setSessionCookie();
if (
(!existingSession || isFirstEventInSession) &&
sessionIdentifierPersisted &&
onSessionUpdateCallback &&
!manualSessionUpdateCalled
) {
onSessionUpdateCallback(clientSession);
manualSessionUpdateCalled = false;
}
}
lastEventTime = new Date().getTime();
},
};
}
function addSessionContextToPayload(payloadBuilder: PayloadBuilder, clientSession: ClientSession) {
let sessionContext: SelfDescribingJson<ClientSession> = {
schema: CLIENT_SESSION_SCHEMA,
data: clientSession,
};
payloadBuilder.addContextEntity(sessionContext);
}
/**
* Expires current session and starts a new session.
*/
function newSession() {
// If cookies are enabled, base visit count and session ID on the cookies
let idCookie = loadDomainUserIdCookie();
// When cookies are enabled
if (cookiesEnabledInIdCookie(idCookie)) {
// When cookie/local storage is enabled - make a new session
if (configStateStorageStrategy != 'none') {
memorizedSessionId = startNewIdCookieSession(idCookie);
} else {
memorizedSessionId = sessionIdFromIdCookie(idCookie);
}
memorizedVisitCount = visitCountFromIdCookie(idCookie);
} else {
memorizedVisitCount++;
memorizedSessionId = startNewIdCookieSession(idCookie, {
memorizedVisitCount,
});
}
updateNowTsInIdCookie(idCookie);
// Update cookies
if (configStateStorageStrategy != 'none') {
const clientSession = clientSessionFromIdCookie(idCookie, configStateStorageStrategy, configAnonymousTracking);
setDomainUserIdCookie(idCookie);
const sessionIdentifierPersisted = setSessionCookie();
if (sessionIdentifierPersisted && onSessionUpdateCallback) {
manualSessionUpdateCalled = true;
onSessionUpdateCallback(clientSession);
}
}
lastEventTime = new Date().getTime();
}
/**
* Combine an array of unchanging contexts with the result of a context-creating function
*
* @param staticContexts - Array of custom contexts
* @param contextCallback - Function returning an array of contexts
*/
function finalizeContexts(
staticContexts?: Array<SelfDescribingJson> | null,
contextCallback?: (() => Array<SelfDescribingJson>) | null
) {
return (staticContexts || []).concat(contextCallback ? contextCallback() : []);
}
function logPageView({ title, context, timestamp, contextCallback }: PageViewEvent & CommonEventProperties) {
refreshUrl();
if (pageViewSent) {
// Do not reset pageViewId if previous events were not page_view
resetPageView();
}
pageViewSent = true;
// So we know what document.title was at the time of trackPageView
lastDocumentTitle = document.title;
lastConfigTitle = title;
// Fixup page title
const pageTitle = fixupTitle(lastConfigTitle || lastDocumentTitle);
// Log page view
core.track(
buildPageView({
pageUrl: purify(configCustomUrl || locationHrefAlias),
pageTitle,
referrer: purify(customReferrer || configReferrerUrl),
}),
finalizeContexts(context, contextCallback),
timestamp
);
// Send ping (to log that user has stayed on page)
const now = new Date();
let installingActivityTracking = false;
if (activityTrackingConfig.enabled && !activityTrackingConfig.installed) {
activityTrackingConfig.installed = true;
installingActivityTracking = true;
// Add mousewheel event handler, detect passive event listeners for performance
const detectPassiveEvents: { update: () => void; hasSupport?: boolean } = {
update: function update() {
if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
let passive = false;
const options = Object.defineProperty({}, 'passive', {
get: function get() {
passive = true;
},
set: function set() {},
});
// note: have to set and remove a no-op listener instead of null
// (which was used previously), because Edge v15 throws an error
// when providing a null callback.
// https://github.com/rafrex/detect-passive-events/pull/3
const noop = function noop() {};
window.addEventListener('testPassiveEventSupport', noop, options);
window.removeEventListener('testPassiveEventSupport', noop, options);
detectPassiveEvents.hasSupport = passive;
}
},
};
detectPassiveEvents.update();
// Detect available wheel event