-
Notifications
You must be signed in to change notification settings - Fork 20
/
lux-reporter.js
2218 lines (2193 loc) · 80.6 KB
/
lux-reporter.js
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
/* eslint-disable */
/*
* Part of Speedcurve's LUX script, which allows us to run real user metrics on
* pages using the public layout template.
*
* See docs/real-user-metrics.md for more information.
*/
/* ! Remember to keep these settings at the end of this file when updating LUX:
*
* * `LUX.customerid = 47044334` to let LUX know who this is
* * `LUX.debug = false` turns debugging on and off. Left set to false - and
* kept in the file so it's easier to remember that this can be turned on.
*
* ! And the sample rate needs to be set inside the main function that's
* assigned to `LUX`:
* * `LUX.samplerate = 1` to set sample rate to 1% of users.
*/
(function () {
'use strict';
/**
* Fit an array of user timing delimited strings into a URL and return both the entries that fit and
* the remaining entries that didn't fit.
*/
function fitUserTimingEntries(utValues, config, url) {
// Start with the maximum allowed UT entries per beacon
var beaconUtValues = utValues.slice(0, config.maxBeaconUTEntries);
var remainingUtValues = utValues.slice(config.maxBeaconUTEntries);
// Trim UT entries until they fit within the maximum URL length, ensuring at least one UT entry
// is included.
while ((url + "&UT=" + beaconUtValues.join(",")).length > config.maxBeaconUrlLength && beaconUtValues.length > 1) {
remainingUtValues.unshift(beaconUtValues.pop());
}
return [beaconUtValues, remainingUtValues];
}
var luxOrigin = "https://lux.speedcurve.com";
function fromObject(obj) {
var autoMode = getProperty(obj, "auto", true);
return {
auto: autoMode,
beaconUrl: getProperty(obj, "beaconUrl", luxOrigin + "/lux/"),
conversions: getProperty(obj, "conversions"),
customerid: getProperty(obj, "customerid"),
errorBeaconUrl: getProperty(obj, "errorBeaconUrl", luxOrigin + "/error/"),
jspagelabel: getProperty(obj, "jspagelabel"),
label: getProperty(obj, "label"),
maxBeaconUrlLength: getProperty(obj, "maxBeaconUrlLength", 8190),
maxBeaconUTEntries: getProperty(obj, "maxBeaconUTEntries", 20),
maxErrors: getProperty(obj, "maxErrors", 5),
maxMeasureTime: getProperty(obj, "maxMeasureTime", 60000),
minMeasureTime: getProperty(obj, "minMeasureTime", 0),
newBeaconOnPageShow: getProperty(obj, "newBeaconOnPageShow", false),
samplerate: getProperty(obj, "samplerate", 100),
sendBeaconOnPageHidden: getProperty(obj, "sendBeaconOnPageHidden", autoMode),
serverTiming: getProperty(obj, "serverTiming"),
trackErrors: getProperty(obj, "trackErrors", true),
trackHiddenPages: getProperty(obj, "trackHiddenPages", false),
pagegroups: getProperty(obj, "pagegroups"),
};
}
function getProperty(obj, key, defaultValue) {
if (typeof obj[key] !== "undefined") {
return obj[key];
}
return defaultValue;
}
var START_MARK = "LUX_start";
var END_MARK = "LUX_end";
var BOOLEAN_TRUE = "true";
var customDataValues = {};
var updatedCustomData = {};
function addCustomDataValue(name, value) {
var typeV = typeof value;
if (customDataValues[name] !== value) {
// If the value is new or different to the previous value, record it so that later we can send
// only the values that have changed.
updatedCustomData[name] = value;
}
if (typeV === "string" || typeV === "number" || typeV === "boolean") {
customDataValues[name] = value;
}
if (typeV === "undefined" || value === null) {
delete customDataValues[name];
}
}
function getAllCustomData() {
return customDataValues;
}
function getUpdatedCustomData() {
return updatedCustomData;
}
function clearUpdateCustomData() {
updatedCustomData = {};
}
/**
* Convert a set of custom data values to the string format expected by the backend.
*/
function valuesToString(values) {
var strings = [];
for (var key in values) {
// Convert all values to strings
var value = "" + values[key];
// Strip out reserved characters (, and | are used as delimiters)
key = key.replace(/,/g, "").replace(/\|/g, "");
value = value.replace(/,/g, "").replace(/\|/g, "");
strings.push(key + "|" + value);
}
return encodeURIComponent(strings.join(","));
}
function floor(x) {
return Math.floor(x);
}
var max = Math.max;
/**
* Clamp a number so that it is never less than 0
*/
function clamp(x) {
return max(0, x);
}
function sortNumeric(a, b) {
return a - b;
}
function now() {
return Date.now ? Date.now() : +new Date();
}
var scriptStartTime = now();
var _a;
// If the various performance APIs aren't available, we export an empty object to
// prevent having to make regular typeof checks.
var performance = window.performance || {};
var timing = performance.timing || {
// If performance.timing isn't available, we attempt to polyfill the navigationStart value.
// Our first attempt is from LUX.ns, which is the time that the snippet execution began. If this
// is not available, we fall back to the time that the current script execution began.
navigationStart: ((_a = window.LUX) === null || _a === void 0 ? void 0 : _a.ns) || scriptStartTime,
};
function msSinceNavigationStart() {
if (performance.now) {
return floor(performance.now());
}
return now() - timing.navigationStart;
}
function navigationType() {
if (performance.navigation && typeof performance.navigation.type !== "undefined") {
return performance.navigation.type;
}
return "";
}
function getNavigationEntry() {
var navEntries = getEntriesByType("navigation");
if (navEntries.length) {
var nativeEntry = navEntries[0];
var entry_1 = {
navigationStart: 0,
activationStart: 0,
};
for (var key in nativeEntry) {
entry_1[key] = nativeEntry[key];
}
return entry_1;
}
var navType = navigationType();
var entry = {
navigationStart: 0,
activationStart: 0,
startTime: 0,
type: navType == 2 ? "back_forward" : navType === 1 ? "reload" : "navigate",
};
{
for (var key in timing) {
if (typeof timing[key] === "number" && key !== "navigationStart") {
entry[key] = floor(timing[key] - timing.navigationStart);
}
}
}
return entry;
}
/**
* Simple wrapper around performance.getEntriesByType to provide fallbacks for
* legacy browsers, and work around edge cases where undefined is returned instead
* of an empty PerformanceEntryList.
*/
function getEntriesByType(type) {
if (typeof performance.getEntriesByType === "function") {
var entries = performance.getEntriesByType(type);
if (entries && entries.length) {
return entries;
}
}
return [];
}
function isVisible() {
if (document.visibilityState) {
return document.visibilityState === "visible";
}
// For browsers that don't support document.visibilityState, we assume the page is visible.
return true;
}
function onVisible(cb) {
afterPrerender(function () {
if (isVisible()) {
cb();
}
else {
var onVisibleCallback_1 = function () {
if (isVisible()) {
cb();
removeEventListener("visibilitychange", onVisibleCallback_1);
}
};
addEventListener("visibilitychange", onVisibleCallback_1, true);
}
});
}
function afterPrerender(cb) {
if (document.prerendering) {
document.addEventListener("prerenderingchange", cb, true);
}
else {
cb();
}
}
function wasPrerendered() {
return document.prerendering || getNavigationEntry().activationStart > 0;
}
function wasRedirected() {
return getNavigationEntry().redirectCount > 0 || timing.redirectEnd > 0;
}
var Flags = {
InitCalled: 1 << 0,
NavTimingNotSupported: 1 << 1,
UserTimingNotSupported: 1 << 2,
VisibilityStateNotVisible: 1 << 3,
BeaconSentFromUnloadHandler: 1 << 4,
BeaconSentAfterTimeout: 1 << 5,
PageLabelFromDocumentTitle: 1 << 6,
PageLabelFromLabelProp: 1 << 7,
PageLabelFromGlobalVariable: 1 << 8,
PageLabelFromUrlPattern: 1 << 9,
PageWasPrerendered: 1 << 10,
PageWasBfCacheRestored: 1 << 11,
};
function addFlag(flags, flag) {
return flags | flag;
}
function hasParentNode(el) {
if (el.parentNode && el.parentNode.tagName) {
return true;
}
return false;
}
/**
* Get the interaction attribution name for an element
*/
function interactionAttributionForElement(el) {
// Our first preference is to use the data-sctrack attribute from anywhere in the tree
var trackId = getClosestScTrackAttribute(el);
if (trackId) {
return trackId;
}
// The second preference is to use the element's ID
if (el.id) {
return el.id;
}
// The third preference is to use the text content of a button or link
var isSubmitInput = el.tagName === "INPUT" && el.type === "submit";
var isButton = el.tagName === "BUTTON";
var isLink = el.tagName === "A";
if (isSubmitInput && el.value) {
return el.value;
}
if ((isButton || isLink) && el.innerText) {
return el.innerText;
}
if (hasParentNode(el)) {
return interactionAttributionForElement(el.parentNode);
}
// No suitable attribute was found
return "";
}
function getClosestScTrackAttribute(el) {
var _a;
if (el.hasAttribute("data-sctrack")) {
var trackId = (_a = el.getAttribute("data-sctrack")) === null || _a === void 0 ? void 0 : _a.trim();
if (trackId) {
return trackId;
}
}
if (hasParentNode(el)) {
return getClosestScTrackAttribute(el.parentNode);
}
return null;
}
var LogEvent = {
// Internal events
EvaluationStart: 1,
EvaluationEnd: 2,
InitCalled: 3,
MarkCalled: 4,
MeasureCalled: 5,
AddDataCalled: 6,
SendCalled: 7,
ForceSampleCalled: 8,
DataCollectionStart: 9,
UnloadHandlerTriggered: 10,
OnloadHandlerTriggered: 11,
MarkLoadTimeCalled: 12,
SendCancelledPageHidden: 13,
// Data collection events
SessionIsSampled: 21,
SessionIsNotSampled: 22,
MainBeaconSent: 23,
UserTimingBeaconSent: 24,
InteractionBeaconSent: 25,
CustomDataBeaconSent: 26,
// Metric information
NavigationStart: 41,
PerformanceEntryReceived: 42,
PerformanceEntryProcessed: 43,
// Errors
PerformanceObserverError: 51,
InputEventPermissionError: 52,
InnerHtmlAccessError: 53,
EventTargetAccessError: 54,
CookieReadError: 55,
CookieSetError: 56,
PageLabelEvaluationError: 57,
// Browser support messages
NavTimingNotSupported: 71,
PaintTimingNotSupported: 72,
};
var Logger = /** @class */ (function () {
function Logger() {
this.events = [];
}
Logger.prototype.logEvent = function (event, args) {
if (args === void 0) { args = []; }
this.events.push([now(), event, args]);
};
Logger.prototype.getEvents = function () {
return this.events;
};
return Logger;
}());
var sessionValue = 0;
var sessionEntries = [];
var maximumSessionValue = 0;
function addEntry$2(entry) {
if (!entry.hadRecentInput) {
var firstEntry = sessionEntries[0];
var latestEntry = sessionEntries[sessionEntries.length - 1];
if (sessionEntries.length &&
(entry.startTime - latestEntry.startTime >= 1000 ||
entry.startTime - firstEntry.startTime >= 5000)) {
sessionValue = entry.value;
sessionEntries = [entry];
}
else {
sessionValue += entry.value;
sessionEntries.push(entry);
}
maximumSessionValue = max(maximumSessionValue, sessionValue);
}
}
function reset$1() {
sessionValue = 0;
sessionEntries = [];
maximumSessionValue = 0;
}
function getCLS() {
return maximumSessionValue;
}
/**
* This implementation is based on the web-vitals implementation, however it is stripped back to the
* bare minimum required to measure just the INP value and does not store the actual event entries.
*/
// The maximum number of interactions to store
var MAX_INTERACTIONS = 10;
// A list of the slowest interactions
var slowestEntries = [];
// A map of the slowest interactions by ID
var slowestEntriesMap = {};
// The total number of interactions recorded on the page
var interactionCountEstimate = 0;
function reset() {
interactionCountEstimate = 0;
slowestEntries = [];
slowestEntriesMap = {};
}
function addEntry$1(entry) {
if (entry.interactionId || (entry.entryType === "first-input" && !entryExists(entry))) {
var duration = entry.duration, startTime = entry.startTime, interactionId = entry.interactionId;
var existingEntry = slowestEntriesMap[interactionId];
if (existingEntry) {
existingEntry.duration = max(duration, existingEntry.duration);
}
else {
interactionCountEstimate++;
slowestEntriesMap[interactionId] = { duration: duration, interactionId: interactionId, startTime: startTime };
slowestEntries.push(slowestEntriesMap[interactionId]);
}
// Only store the longest <MAX_INTERACTIONS> interactions
slowestEntries.sort(function (a, b) { return b.duration - a.duration; });
slowestEntries.splice(MAX_INTERACTIONS).forEach(function (entry) {
delete slowestEntriesMap[entry.interactionId];
});
}
}
function entryExists(e1) {
return slowestEntries.some(function (e2) { return e1.startTime === e2.startTime && e1.duration === e2.duration; });
}
/**
* Returns an estimated high percentile INP value based on the total number of interactions on the
* current page.
*/
function getHighPercentileINP() {
var _a;
var index = Math.min(slowestEntries.length - 1, Math.floor(getInteractionCount() / 50));
return (_a = slowestEntries[index]) === null || _a === void 0 ? void 0 : _a.duration;
}
function getInteractionCount() {
if ("interactionCount" in performance) {
return performance.interactionCount;
}
return interactionCountEstimate;
}
var ALL_ENTRIES = [];
function observe(type, callback, options) {
if (typeof PerformanceObserver === "function" && PerformanceObserver.supportedEntryTypes.includes(type)) {
var po = new PerformanceObserver(function (list) {
list.getEntries().forEach(function (entry) { return callback(entry); });
});
po.observe(Object.assign({ type: type, buffered: true }, { options: options }));
return po;
}
return undefined;
}
function getEntries(type) {
return ALL_ENTRIES.filter(function (entry) { return entry.entryType === type; });
}
function addEntry(entry) {
ALL_ENTRIES.push(entry);
}
/**
* A server timing metric that has its value set to the duration field
*/
var TYPE_DURATION = "r";
/**
* When a description metric has no value, we consider it to be a boolean and set it to this value.
*/
var BOOLEAN_TRUE_VALUE = "true";
function getKeyValuePairs(config, serverTiming) {
var pairs = {};
serverTiming.forEach(function (stEntry) {
var name = stEntry.name;
var description = stEntry.description;
if (name in config) {
var spec = config[name];
var multiplier = spec[1];
if (spec[0] === TYPE_DURATION) {
pairs[name] = stEntry.duration * (multiplier || 1);
}
else if (description && multiplier) {
var numericValue = parseFloat(description);
if (!isNaN(numericValue)) {
pairs[name] = numericValue * multiplier;
}
}
else {
pairs[name] = description || BOOLEAN_TRUE_VALUE;
}
}
});
return pairs;
}
function getMatchesFromPatternMap(patternMap, hostname, pathname, firstOnly) {
var matches = [];
for (var key in patternMap) {
var patterns = patternMap[key];
if (Array.isArray(patterns)) {
for (var i in patterns) {
var pattern = patterns[i];
if (typeof pattern === "string" && patternMatchesUrl(pattern, hostname, pathname)) {
if (firstOnly) {
return key;
}
matches.push(key);
}
}
}
}
if (firstOnly) {
return undefined;
}
return matches;
}
function patternMatchesUrl(pattern, hostname, pathname) {
var regex = createRegExpFromPattern(pattern);
if (pattern.charAt(0) === "/") {
// Rule is a pathname only
return regex.test(pathname);
}
// Rule is a hostname and pathname
return regex.test(hostname + pathname);
}
function createRegExpFromPattern(pattern) {
return new RegExp("^" + escapeStringForRegExp(pattern).replace(/\*/g, ".*") + "$", "i");
}
function escapeStringForRegExp(str) {
// Note: we don't escape * because it's our own special symbol!
return str.replace(/[-/\\^$+?.()|[\]{}]/g, "\\$&");
}
var LUX = window.LUX || {};
var scriptEndTime = scriptStartTime;
LUX = (function () {
// -------------------------------------------------------------------------
// Settings
// -------------------------------------------------------------------------
// This ID usually appended to the end of the lux.js as a query string when
// using the SpeedCurve hosted version - but we have to include it here as
// this is self hosted.
LUX.customerid = 47044334;
// Set the sample rate to 1% to avoid all events being sent.
LUX.samplerate = 1;
// -------------------------------------------------------------------------
/// End
// -------------------------------------------------------------------------
var SCRIPT_VERSION = "311";
var logger = new Logger();
var globalConfig = fromObject(LUX);
logger.logEvent(LogEvent.EvaluationStart, [SCRIPT_VERSION]);
// Variable aliases that allow the minifier to reduce file size.
var document = window.document;
var addEventListener = window.addEventListener;
var removeEventListener = window.removeEventListener;
var setTimeout = window.setTimeout;
var clearTimeout = window.clearTimeout;
var encodeURIComponent = window.encodeURIComponent;
var thisScript = document.currentScript || {};
// Log JS errors.
var nErrors = 0;
function errorHandler(e) {
if (!globalConfig.trackErrors) {
return;
}
nErrors++;
if (e && typeof e.filename !== "undefined" && typeof e.message !== "undefined") {
// Always send LUX errors
var isLuxError = e.filename.indexOf("/lux.js?") > -1 || e.message.indexOf("LUX") > -1;
if (isLuxError || (nErrors <= globalConfig.maxErrors && _sample())) {
// Sample & limit other errors.
// Send the error beacon.
new Image().src =
globalConfig.errorBeaconUrl +
"?v=" +
SCRIPT_VERSION +
"&id=" +
getCustomerId() +
"&fn=" +
encodeURIComponent(e.filename) +
"&ln=" +
e.lineno +
"&cn=" +
e.colno +
"&msg=" +
encodeURIComponent(e.message) +
"&l=" +
encodeURIComponent(_getPageLabel()) +
(connectionType() ? "&ct=" + connectionType() : "") +
"&HN=" +
encodeURIComponent(document.location.hostname) +
"&PN=" +
encodeURIComponent(document.location.pathname);
}
}
}
addEventListener("error", errorHandler);
var logEntry = function (entry) {
logger.logEvent(LogEvent.PerformanceEntryReceived, [entry]);
};
// Most PerformanceEntry types we log an event for and add it to the global entry store.
var processAndLogEntry = function (entry) {
addEntry(entry);
logEntry(entry);
};
// Before long tasks were buffered, we added a PerformanceObserver to the lux.js snippet to capture
// any long tasks that occurred before the full script was loaded. To deal with this, we process
// all of the snippet long tasks, and we check for double-ups in the new PerformanceObserver.
var snippetLongTasks = typeof window.LUX_al === "object" ? window.LUX_al : [];
snippetLongTasks.forEach(processAndLogEntry);
try {
observe("longtask", function (entry) {
if (ALL_ENTRIES.indexOf(entry) === -1) {
processAndLogEntry(entry);
}
});
observe("largest-contentful-paint", processAndLogEntry);
observe("element", processAndLogEntry);
observe("paint", processAndLogEntry);
observe("layout-shift", function (entry) {
addEntry$2(entry);
logEntry(entry);
});
observe("first-input", function (entry) {
var entryTime = entry.processingStart - entry.startTime;
if (!gFirstInputDelay || gFirstInputDelay < entryTime) {
gFirstInputDelay = floor(entryTime);
}
// Allow first-input events to be considered for INP
addEntry$1(entry);
});
// TODO: Add { durationThreshold: 40 } once performance.interactionCount is widely supported.
// Right now we have to count every event to get the total interaction count so that we can
// estimate a high percentile value for INP.
observe("event", addEntry$1);
}
catch (e) {
logger.logEvent(LogEvent.PerformanceObserverError, [e]);
}
// Bitmask of flags for this session & page
var gFlags = 0;
var gaMarks = [];
var gaMeasures = [];
var ghIx = {}; // hash for Interaction Metrics (scroll, click, keyboard)
var gbLuxSent = 0; // have we sent the LUX data? (avoid sending twice in unload)
var gbNavSent = 0; // have we sent the Nav Timing beacon yet? (avoid sending twice for SPA)
var gbIxSent = 0; // have we sent the IX data? (avoid sending twice for SPA)
var gbFirstPV = 1; // this is the first page view (vs. a SPA "soft nav")
var gSessionTimeout = 30 * 60; // number of seconds after which we consider a session to have "timed out" (used for calculating bouncerate)
var gSyncId = createSyncId(); // if we send multiple beacons, use this to sync them (eg, LUX & IX) (also called "luxid")
var gUid = refreshUniqueId(gSyncId); // cookie for this session ("Unique ID")
var gCustomerDataTimeout; // setTimeout timer for sending a Customer Data beacon after onload
var gMaxMeasureTimeout; // setTimeout timer for sending the beacon after a maximum measurement time
var pageRestoreTime; // ms since navigationStart representing when the page was restored from the bfcache
/**
* To measure the way a user experienced a metric, we measure metrics relative to the time the user
* started viewing the page. On prerendered pages, this is activationStart. On bfcache restores, this
* is the page restore time. On all other pages this value will be zero.
*/
var getZeroTime = function () {
var _a;
return Math.max(pageRestoreTime || 0, getNavigationEntry().activationStart, ((_a = _getMark(START_MARK)) === null || _a === void 0 ? void 0 : _a.startTime) || 0);
};
/**
* Most time-based metrics that LUX reports should be relative to the "zero" marker, rounded down
* to the nearest unit so as not to report times in the future, and clamped to zero.
*/
var processTimeMetric = function (value) { return clamp(floor(value - getZeroTime())); };
/**
* Some values should only be reported if they are non-zero. The exception to this is when the page
* was prerendered or restored from BF cache
*/
var shouldReportValue = function (value) { return value > 0 || pageRestoreTime || wasPrerendered(); };
if (_sample()) {
logger.logEvent(LogEvent.SessionIsSampled, [globalConfig.samplerate]);
}
else {
logger.logEvent(LogEvent.SessionIsNotSampled, [globalConfig.samplerate]);
}
var gLuxSnippetStart = LUX.ns ? LUX.ns - timing.navigationStart : 0;
if (!performance.timing) {
logger.logEvent(LogEvent.NavTimingNotSupported);
gFlags = addFlag(gFlags, Flags.NavTimingNotSupported);
}
logger.logEvent(LogEvent.NavigationStart, [timing.navigationStart]);
////////////////////// FID BEGIN
// FIRST INPUT DELAY (FID)
// The basic idea behind FID is to attach various input event listeners and measure the time
// between when the event happens and when the handler executes. That is FID.
var gFirstInputDelay;
var gaEventTypes = ["click", "mousedown", "keydown", "touchstart", "pointerdown"]; // NOTE: does NOT include scroll!
var ghListenerOptions = { passive: true, capture: true };
// Record the FIRST input delay.
function recordDelay(delay) {
if (!gFirstInputDelay) {
gFirstInputDelay = delay;
// remove event listeners
gaEventTypes.forEach(function (eventType) {
removeEventListener(eventType, onInput, ghListenerOptions);
});
}
}
// Pointer events are special. Ignore scrolling by looking for pointercancel
// events because FID does not include scrolling nor pinch/zooming.
function onPointerDown(delay) {
function onPointerUp() {
recordDelay(delay);
removeListeners();
}
// Do NOT record FID - this is a scroll.
function onPointerCancel() {
removeListeners();
}
function removeListeners() {
removeEventListener("pointerup", onPointerUp, ghListenerOptions);
removeEventListener("pointercancel", onPointerCancel, ghListenerOptions);
}
addEventListener("pointerup", onPointerUp, ghListenerOptions);
addEventListener("pointercancel", onPointerCancel, ghListenerOptions);
}
// Record FID as the delta between when the event happened and when the
// listener was able to execute.
function onInput(evt) {
var bCancelable = false;
try {
// Seeing "Permission denied" errors, so do a simple try-catch.
bCancelable = evt.cancelable;
}
catch (e) {
// bail - no need to return anything
logger.logEvent(LogEvent.InputEventPermissionError);
return;
}
if (bCancelable) {
var now_1 = _now(true);
var eventTimeStamp = evt.timeStamp;
if (eventTimeStamp > 1520000000) {
// If the event timeStamp is an epoch time instead of a time relative to NavigationStart,
// then compare it to Date.now() instead of performance.now().
now_1 = Number(new Date());
}
if (eventTimeStamp > now_1) {
// If there is a race condition and eventTimeStamp happened after
// this code was executed, something is wrong. Bail.
return;
}
var delay = now_1 - eventTimeStamp;
if (evt.type === "pointerdown") {
// special case
onPointerDown(delay);
}
else {
recordDelay(delay);
}
}
}
// Attach event listener to input events.
gaEventTypes.forEach(function (eventType) {
addEventListener(eventType, onInput, ghListenerOptions);
});
////////////////////// FID END
/**
* Returns the time elapsed (in ms) since navigationStart. For SPAs, returns
* the time elapsed since the last LUX.init call.
*
* When `absolute = true` the time is always relative to navigationStart, even
* in SPAs.
*/
function _now(absolute) {
var sinceNavigationStart = msSinceNavigationStart();
var startMark = _getMark(START_MARK);
// For SPA page views, we use our internal mark as a reference point
if (startMark && !absolute) {
return floor(sinceNavigationStart - startMark.startTime);
}
// For "regular" page views, we can use performance.now() if it's available...
return sinceNavigationStart;
}
// This is a wrapper around performance.mark that falls back to a polyfill when the User Timing
// API isn't supported.
function _mark() {
var _a, _b;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
logger.logEvent(LogEvent.MarkCalled, args);
if (performance.mark) {
// Use the native performance.mark where possible...
return performance.mark.apply(performance, args);
}
// ...Otherwise provide a polyfill
{
var name_1 = args[0];
var detail = ((_a = args[1]) === null || _a === void 0 ? void 0 : _a.detail) || null;
var startTime = ((_b = args[1]) === null || _b === void 0 ? void 0 : _b.startTime) || _now();
var entry = {
entryType: "mark",
duration: 0,
name: name_1,
detail: detail,
startTime: startTime,
};
gaMarks.push(entry);
gFlags = addFlag(gFlags, Flags.UserTimingNotSupported);
return entry;
}
}
// This is a wrapper around performance.measure that falls back to a polyfill when the User Timing
// API isn't supported.
function _measure() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
logger.logEvent(LogEvent.MeasureCalled, args);
var name = args[0];
var startMarkName = args[1];
var endMarkName = args[2];
var options;
if (typeof startMarkName === "object") {
options = args[1];
startMarkName = options.start;
endMarkName = options.end;
}
if (typeof startMarkName === "undefined") {
// Without a start mark specified, performance.measure defaults to using navigationStart
if (_getMark(START_MARK)) {
// For SPAs that have already called LUX.init(), we use our internal start mark instead of
// navigationStart
startMarkName = START_MARK;
}
else {
// For regular page views, we need to patch the navigationStart behaviour because IE11 throws
// a SyntaxError without a start mark
startMarkName = "navigationStart";
}
// Since we've potentially modified the start mark, we need to shove it back into whichever
// argument it belongs in.
if (options) {
// If options were provided, we need to avoid specifying a start mark if an end mark and
// duration were already specified.
if (!options.end || !options.duration) {
args[1].start = startMarkName;
}
}
else {
args[1] = startMarkName;
}
}
if (performance.measure) {
// Use the native performance.measure where possible...
return performance.measure.apply(performance, args);
}
// ...Otherwise provide a polyfill
{
var navEntry = getNavigationEntry();
var startTime = typeof startMarkName === "number" ? startMarkName : 0;
var endTime = typeof endMarkName === "number" ? endMarkName : _now();
var throwError = function (missingMark) {
throw new DOMException("Failed to execute 'measure' on 'Performance': The mark '" +
missingMark +
"' does not exist");
};
if (typeof startMarkName === "string") {
var startMark = _getMark(startMarkName);
if (startMark) {
startTime = startMark.startTime;
}
else if (typeof navEntry[startMarkName] === "number") {
// the mark name can also be a property from Navigation Timing
startTime = navEntry[startMarkName];
}
else {
throwError(startMarkName);
}
}
if (typeof endMarkName === "string") {
var endMark = _getMark(endMarkName);
if (endMark) {
endTime = endMark.startTime;
}
else if (typeof navEntry[endMarkName] === "number") {
// the mark name can also be a property from Navigation Timing
endTime = navEntry[endMarkName];
}
else {
throwError(endMarkName);
}
}
var duration = endTime - startTime;
var detail = null;
if (options) {
if (options.duration) {
duration = options.duration;
}
detail = options.detail;
}
var entry = {
entryType: "measure",
name: name,
detail: detail,
startTime: startTime,
duration: duration,
};
gaMeasures.push(entry);
gFlags = addFlag(gFlags, Flags.UserTimingNotSupported);
return entry;
}
}
// Return THE LAST mark that matches the name.
function _getMark(name) {
return _getM(name, _getMarks());
}
function _getM(name, aItems) {
if (aItems) {
for (var i = aItems.length - 1; i >= 0; i--) {
var m = aItems[i];
if (name === m.name) {
return m;
}
}
}
return undefined;
}
// Return an array of marks.
function _getMarks() {
var marks = getEntriesByType("mark");
if (marks.length) {
return marks;
}
return gaMarks;
}
// Return an array of measures.
function _getMeasures() {
var measures = getEntriesByType("measure");
if (measures.length) {
return measures;
}
return gaMeasures;
}
// Return a string of User Timing Metrics formatted for beacon querystring.
function userTimingValues() {
// The User Timing spec allows for there to be multiple marks with the same name,
// and multiple measures with the same name. But we can only send back one value
// for a name, so we always take the maximum value.
var hUT = {};
var startMark = _getMark(START_MARK);
// For user timing values taken in a SPA page load, we need to adjust them
// so that they're zeroed against the last LUX.init() call.
var tZero = getZeroTime();
// marks
_getMarks().forEach(function (mark) {
var name = mark.name;
if (name === START_MARK || name === END_MARK) {
// Don't include the internal marks in the beacon
return;
}
var startTime = floor(mark.startTime - tZero);
if (startTime < 0) {
// Exclude marks that were taken before the current SPA page view
return;
}
if (typeof hUT[name] === "undefined") {
hUT[name] = { startTime: startTime };
}
else {
hUT[name].startTime = max(startTime, hUT[name].startTime);
}
});
// measures
_getMeasures().forEach(function (measure) {
if (startMark && measure.startTime < startMark.startTime) {
// Exclude measures that were taken before the current SPA page view
return;
}
var name = measure.name;
var startTime = floor(measure.startTime - tZero);
var duration = floor(measure.duration);
if (typeof hUT[name] === "undefined" || startTime > hUT[name].startTime) {
hUT[name] = { startTime: startTime, duration: duration };
}
});
// Convert the user timing values into a delimited string. This string takes the format
// markName|startTime,measureName|startTime|duration,[markName...]
var aUT = [];
for (var utName in hUT) {
var _a = hUT[utName], startTime = _a.startTime, duration = _a.duration;
var utParts = [utName, startTime];
if (typeof duration !== "undefined") {
utParts.push(duration);
}
aUT.push(utParts.join("|"));
}
return aUT;
}
// Return a string of Element Timing Metrics formatted for beacon querystring.
function elementTimingValues() {