infront-logger 1.1.5 → 1.1.6

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.
@@ -0,0 +1,4176 @@
1
+ var ConsoleApiName = {
2
+ log: "log",
3
+ debug: "debug",
4
+ info: "info",
5
+ warn: "warn",
6
+ error: "error"
7
+ };
8
+ var globalConsole = console;
9
+ var originalConsoleMethods = {};
10
+ Object.keys(ConsoleApiName).forEach(function(name) {
11
+ originalConsoleMethods[name] = globalConsole[name];
12
+ });
13
+ var PREFIX = "Datadog Browser SDK:";
14
+ var display = {
15
+ debug: originalConsoleMethods.debug.bind(globalConsole, PREFIX),
16
+ log: originalConsoleMethods.log.bind(globalConsole, PREFIX),
17
+ info: originalConsoleMethods.info.bind(globalConsole, PREFIX),
18
+ warn: originalConsoleMethods.warn.bind(globalConsole, PREFIX),
19
+ error: originalConsoleMethods.error.bind(globalConsole, PREFIX)
20
+ };
21
+ var DOCS_ORIGIN = "https://docs.datadoghq.com";
22
+ var DOCS_TROUBLESHOOTING = "".concat(DOCS_ORIGIN, "/real_user_monitoring/browser/troubleshooting");
23
+ var MORE_DETAILS = "More details:";
24
+ function catchUserErrors(fn, errorMsg) {
25
+ return function() {
26
+ var args = [];
27
+ for (var _i = 0; _i < arguments.length; _i++) {
28
+ args[_i] = arguments[_i];
29
+ }
30
+ try {
31
+ return fn.apply(void 0, args);
32
+ } catch (err) {
33
+ display.error(errorMsg, err);
34
+ }
35
+ };
36
+ }
37
+ function performDraw(threshold) {
38
+ return threshold !== 0 && Math.random() * 100 <= threshold;
39
+ }
40
+ function isPercentage(value) {
41
+ return isNumber(value) && value >= 0 && value <= 100;
42
+ }
43
+ function isNumber(value) {
44
+ return typeof value === "number";
45
+ }
46
+ var ONE_SECOND = 1e3;
47
+ var ONE_MINUTE = 60 * ONE_SECOND;
48
+ var ONE_HOUR = 60 * ONE_MINUTE;
49
+ function dateNow() {
50
+ return (/* @__PURE__ */ new Date()).getTime();
51
+ }
52
+ function timeStampNow() {
53
+ return dateNow();
54
+ }
55
+ function relativeNow() {
56
+ return performance.now();
57
+ }
58
+ function clocksNow() {
59
+ return { relative: relativeNow(), timeStamp: timeStampNow() };
60
+ }
61
+ function clocksOrigin() {
62
+ return { relative: 0, timeStamp: getNavigationStart() };
63
+ }
64
+ function elapsed(start, end) {
65
+ return end - start;
66
+ }
67
+ function addDuration(a, b) {
68
+ return a + b;
69
+ }
70
+ function getRelativeTime(timestamp) {
71
+ return timestamp - getNavigationStart();
72
+ }
73
+ var navigationStart;
74
+ function getNavigationStart() {
75
+ if (navigationStart === void 0) {
76
+ navigationStart = performance.timing.navigationStart;
77
+ }
78
+ return navigationStart;
79
+ }
80
+ var ONE_KIBI_BYTE = 1024;
81
+ var ONE_MEBI_BYTE = 1024 * ONE_KIBI_BYTE;
82
+ var HAS_MULTI_BYTES_CHARACTERS = /[^\u0000-\u007F]/;
83
+ function computeBytesCount(candidate) {
84
+ if (!HAS_MULTI_BYTES_CHARACTERS.test(candidate)) {
85
+ return candidate.length;
86
+ }
87
+ if (window.TextEncoder !== void 0) {
88
+ return new TextEncoder().encode(candidate).length;
89
+ }
90
+ return new Blob([candidate]).size;
91
+ }
92
+ function includes(candidate, search) {
93
+ return candidate.indexOf(search) !== -1;
94
+ }
95
+ function arrayFrom(arrayLike) {
96
+ if (Array.from) {
97
+ return Array.from(arrayLike);
98
+ }
99
+ var array = [];
100
+ if (arrayLike instanceof Set) {
101
+ arrayLike.forEach(function(item) {
102
+ return array.push(item);
103
+ });
104
+ } else {
105
+ for (var i = 0; i < arrayLike.length; i++) {
106
+ array.push(arrayLike[i]);
107
+ }
108
+ }
109
+ return array;
110
+ }
111
+ function find(array, predicate) {
112
+ for (var i = 0; i < array.length; i += 1) {
113
+ var item = array[i];
114
+ if (predicate(item, i)) {
115
+ return item;
116
+ }
117
+ }
118
+ return void 0;
119
+ }
120
+ function objectValues(object) {
121
+ return Object.keys(object).map(function(key) {
122
+ return object[key];
123
+ });
124
+ }
125
+ function objectEntries(object) {
126
+ return Object.keys(object).map(function(key) {
127
+ return [key, object[key]];
128
+ });
129
+ }
130
+ function startsWith(candidate, search) {
131
+ return candidate.slice(0, search.length) === search;
132
+ }
133
+ function endsWith(candidate, search) {
134
+ return candidate.slice(-search.length) === search;
135
+ }
136
+ function assign(target) {
137
+ var toAssign = [];
138
+ for (var _i = 1; _i < arguments.length; _i++) {
139
+ toAssign[_i - 1] = arguments[_i];
140
+ }
141
+ toAssign.forEach(function(source) {
142
+ for (var key in source) {
143
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
144
+ target[key] = source[key];
145
+ }
146
+ }
147
+ });
148
+ return target;
149
+ }
150
+ function shallowClone(object) {
151
+ return assign({}, object);
152
+ }
153
+ function objectHasValue(object, value) {
154
+ return Object.keys(object).some(function(key) {
155
+ return object[key] === value;
156
+ });
157
+ }
158
+ function isEmptyObject(object) {
159
+ return Object.keys(object).length === 0;
160
+ }
161
+ function getGlobalObject() {
162
+ if (typeof globalThis === "object") {
163
+ return globalThis;
164
+ }
165
+ Object.defineProperty(Object.prototype, "_dd_temp_", {
166
+ get: function() {
167
+ return this;
168
+ },
169
+ configurable: true
170
+ });
171
+ var globalObject = _dd_temp_;
172
+ delete Object.prototype._dd_temp_;
173
+ if (typeof globalObject !== "object") {
174
+ if (typeof self === "object") {
175
+ globalObject = self;
176
+ } else if (typeof window === "object") {
177
+ globalObject = window;
178
+ } else {
179
+ globalObject = {};
180
+ }
181
+ }
182
+ return globalObject;
183
+ }
184
+ function getZoneJsOriginalValue(target, name) {
185
+ var browserWindow = getGlobalObject();
186
+ var original;
187
+ if (browserWindow.Zone && typeof browserWindow.Zone.__symbol__ === "function") {
188
+ original = target[browserWindow.Zone.__symbol__(name)];
189
+ }
190
+ if (!original) {
191
+ original = target[name];
192
+ }
193
+ return original;
194
+ }
195
+ var __spreadArray = function(to, from, pack) {
196
+ if (pack || arguments.length === 2)
197
+ for (var i = 0, l = from.length, ar; i < l; i++) {
198
+ if (ar || !(i in from)) {
199
+ if (!ar)
200
+ ar = Array.prototype.slice.call(from, 0, i);
201
+ ar[i] = from[i];
202
+ }
203
+ }
204
+ return to.concat(ar || Array.prototype.slice.call(from));
205
+ };
206
+ var onMonitorErrorCollected;
207
+ var debugMode = false;
208
+ function startMonitorErrorCollection(newOnMonitorErrorCollected) {
209
+ onMonitorErrorCollected = newOnMonitorErrorCollected;
210
+ }
211
+ function setDebugMode(newDebugMode) {
212
+ debugMode = newDebugMode;
213
+ }
214
+ function monitored(_, __, descriptor) {
215
+ var originalMethod = descriptor.value;
216
+ descriptor.value = function() {
217
+ var args = [];
218
+ for (var _i = 0; _i < arguments.length; _i++) {
219
+ args[_i] = arguments[_i];
220
+ }
221
+ var decorated = onMonitorErrorCollected ? monitor(originalMethod) : originalMethod;
222
+ return decorated.apply(this, args);
223
+ };
224
+ }
225
+ function monitor(fn) {
226
+ return function() {
227
+ return callMonitored(fn, this, arguments);
228
+ };
229
+ }
230
+ function callMonitored(fn, context, args) {
231
+ try {
232
+ return fn.apply(context, args);
233
+ } catch (e) {
234
+ displayIfDebugEnabled(e);
235
+ if (onMonitorErrorCollected) {
236
+ try {
237
+ onMonitorErrorCollected(e);
238
+ } catch (e2) {
239
+ displayIfDebugEnabled(e2);
240
+ }
241
+ }
242
+ }
243
+ }
244
+ function displayIfDebugEnabled() {
245
+ var args = [];
246
+ for (var _i = 0; _i < arguments.length; _i++) {
247
+ args[_i] = arguments[_i];
248
+ }
249
+ if (debugMode) {
250
+ display.error.apply(display, __spreadArray(["[MONITOR]"], args, false));
251
+ }
252
+ }
253
+ function setTimeout(callback, delay) {
254
+ return getZoneJsOriginalValue(getGlobalObject(), "setTimeout")(monitor(callback), delay);
255
+ }
256
+ function clearTimeout(timeoutId) {
257
+ getZoneJsOriginalValue(getGlobalObject(), "clearTimeout")(timeoutId);
258
+ }
259
+ function setInterval(callback, delay) {
260
+ return getZoneJsOriginalValue(getGlobalObject(), "setInterval")(monitor(callback), delay);
261
+ }
262
+ function clearInterval(timeoutId) {
263
+ getZoneJsOriginalValue(getGlobalObject(), "clearInterval")(timeoutId);
264
+ }
265
+ var Observable = (
266
+ /** @class */
267
+ function() {
268
+ function Observable2(onFirstSubscribe) {
269
+ this.onFirstSubscribe = onFirstSubscribe;
270
+ this.observers = [];
271
+ }
272
+ Observable2.prototype.subscribe = function(f) {
273
+ var _this = this;
274
+ this.observers.push(f);
275
+ if (this.observers.length === 1 && this.onFirstSubscribe) {
276
+ this.onLastUnsubscribe = this.onFirstSubscribe(this) || void 0;
277
+ }
278
+ return {
279
+ unsubscribe: function() {
280
+ _this.observers = _this.observers.filter(function(other) {
281
+ return f !== other;
282
+ });
283
+ if (!_this.observers.length && _this.onLastUnsubscribe) {
284
+ _this.onLastUnsubscribe();
285
+ }
286
+ }
287
+ };
288
+ };
289
+ Observable2.prototype.notify = function(data) {
290
+ this.observers.forEach(function(observer) {
291
+ return observer(data);
292
+ });
293
+ };
294
+ return Observable2;
295
+ }()
296
+ );
297
+ function mergeObservables() {
298
+ var observables = [];
299
+ for (var _i = 0; _i < arguments.length; _i++) {
300
+ observables[_i] = arguments[_i];
301
+ }
302
+ return new Observable(function(globalObservable) {
303
+ var subscriptions = observables.map(function(observable) {
304
+ return observable.subscribe(function(data) {
305
+ return globalObservable.notify(data);
306
+ });
307
+ });
308
+ return function() {
309
+ return subscriptions.forEach(function(subscription) {
310
+ return subscription.unsubscribe();
311
+ });
312
+ };
313
+ });
314
+ }
315
+ function throttle(fn, wait, options) {
316
+ var needLeadingExecution = options && options.leading !== void 0 ? options.leading : true;
317
+ var needTrailingExecution = options && options.trailing !== void 0 ? options.trailing : true;
318
+ var inWaitPeriod = false;
319
+ var pendingExecutionWithParameters;
320
+ var pendingTimeoutId;
321
+ return {
322
+ throttled: function() {
323
+ var parameters = [];
324
+ for (var _i = 0; _i < arguments.length; _i++) {
325
+ parameters[_i] = arguments[_i];
326
+ }
327
+ if (inWaitPeriod) {
328
+ pendingExecutionWithParameters = parameters;
329
+ return;
330
+ }
331
+ if (needLeadingExecution) {
332
+ fn.apply(void 0, parameters);
333
+ } else {
334
+ pendingExecutionWithParameters = parameters;
335
+ }
336
+ inWaitPeriod = true;
337
+ pendingTimeoutId = setTimeout(function() {
338
+ if (needTrailingExecution && pendingExecutionWithParameters) {
339
+ fn.apply(void 0, pendingExecutionWithParameters);
340
+ }
341
+ inWaitPeriod = false;
342
+ pendingExecutionWithParameters = void 0;
343
+ }, wait);
344
+ },
345
+ cancel: function() {
346
+ clearTimeout(pendingTimeoutId);
347
+ inWaitPeriod = false;
348
+ pendingExecutionWithParameters = void 0;
349
+ }
350
+ };
351
+ }
352
+ function noop() {
353
+ }
354
+ function generateUUID(placeholder) {
355
+ return placeholder ? (
356
+ // eslint-disable-next-line no-bitwise
357
+ (parseInt(placeholder, 10) ^ Math.random() * 16 >> parseInt(placeholder, 10) / 4).toString(16)
358
+ ) : "".concat(1e7, "-").concat(1e3, "-").concat(4e3, "-").concat(8e3, "-").concat(1e11).replace(/[018]/g, generateUUID);
359
+ }
360
+ var COMMA_SEPARATED_KEY_VALUE = /([\w-]+)\s*=\s*([^;]+)/g;
361
+ function findCommaSeparatedValue(rawString, name) {
362
+ COMMA_SEPARATED_KEY_VALUE.lastIndex = 0;
363
+ while (true) {
364
+ var match = COMMA_SEPARATED_KEY_VALUE.exec(rawString);
365
+ if (match) {
366
+ if (match[1] === name) {
367
+ return match[2];
368
+ }
369
+ } else {
370
+ break;
371
+ }
372
+ }
373
+ }
374
+ function findCommaSeparatedValues(rawString) {
375
+ var result = /* @__PURE__ */ new Map();
376
+ COMMA_SEPARATED_KEY_VALUE.lastIndex = 0;
377
+ while (true) {
378
+ var match = COMMA_SEPARATED_KEY_VALUE.exec(rawString);
379
+ if (match) {
380
+ result.set(match[1], match[2]);
381
+ } else {
382
+ break;
383
+ }
384
+ }
385
+ return result;
386
+ }
387
+ function safeTruncate(candidate, length, suffix) {
388
+ if (suffix === void 0) {
389
+ suffix = "";
390
+ }
391
+ var lastChar = candidate.charCodeAt(length - 1);
392
+ var isLastCharSurrogatePair = lastChar >= 55296 && lastChar <= 56319;
393
+ var correctedLength = isLastCharSurrogatePair ? length + 1 : length;
394
+ if (candidate.length <= correctedLength) {
395
+ return candidate;
396
+ }
397
+ return "".concat(candidate.slice(0, correctedLength)).concat(suffix);
398
+ }
399
+ function isChromium() {
400
+ return detectBrowserCached() === 1;
401
+ }
402
+ var browserCache;
403
+ function detectBrowserCached() {
404
+ return browserCache !== null && browserCache !== void 0 ? browserCache : browserCache = detectBrowser();
405
+ }
406
+ function detectBrowser(browserWindow) {
407
+ var _a2;
408
+ if (browserWindow === void 0) {
409
+ browserWindow = window;
410
+ }
411
+ var userAgent = browserWindow.navigator.userAgent;
412
+ if (browserWindow.chrome || /HeadlessChrome/.test(userAgent)) {
413
+ return 1;
414
+ }
415
+ if (
416
+ // navigator.vendor is deprecated, but it is the most resilient way we found to detect
417
+ // "Apple maintained browsers" (AKA Safari). If one day it gets removed, we still have the
418
+ // useragent test as a semi-working fallback.
419
+ ((_a2 = browserWindow.navigator.vendor) === null || _a2 === void 0 ? void 0 : _a2.indexOf("Apple")) === 0 || /safari/i.test(userAgent) && !/chrome|android/i.test(userAgent)
420
+ ) {
421
+ return 2;
422
+ }
423
+ if (browserWindow.document.documentMode) {
424
+ return 0;
425
+ }
426
+ return 3;
427
+ }
428
+ function setCookie(name, value, expireDelay, options) {
429
+ var date = /* @__PURE__ */ new Date();
430
+ date.setTime(date.getTime() + expireDelay);
431
+ var expires = "expires=".concat(date.toUTCString());
432
+ var sameSite = options && options.crossSite ? "none" : "strict";
433
+ var domain = options && options.domain ? ";domain=".concat(options.domain) : "";
434
+ var secure = options && options.secure ? ";secure" : "";
435
+ var partitioned = options && options.partitioned ? ";partitioned" : "";
436
+ document.cookie = "".concat(name, "=").concat(value, ";").concat(expires, ";path=/;samesite=").concat(sameSite).concat(domain).concat(secure).concat(partitioned);
437
+ }
438
+ function getCookie(name) {
439
+ return findCommaSeparatedValue(document.cookie, name);
440
+ }
441
+ var initCookieParsed;
442
+ function getInitCookie(name) {
443
+ if (!initCookieParsed) {
444
+ initCookieParsed = findCommaSeparatedValues(document.cookie);
445
+ }
446
+ return initCookieParsed.get(name);
447
+ }
448
+ function deleteCookie(name, options) {
449
+ setCookie(name, "", 0, options);
450
+ }
451
+ function areCookiesAuthorized(options) {
452
+ if (document.cookie === void 0 || document.cookie === null) {
453
+ return false;
454
+ }
455
+ try {
456
+ var testCookieName = "dd_cookie_test_".concat(generateUUID());
457
+ var testCookieValue = "test";
458
+ setCookie(testCookieName, testCookieValue, ONE_MINUTE, options);
459
+ var isCookieCorrectlySet = getCookie(testCookieName) === testCookieValue;
460
+ deleteCookie(testCookieName, options);
461
+ return isCookieCorrectlySet;
462
+ } catch (error) {
463
+ display.error(error);
464
+ return false;
465
+ }
466
+ }
467
+ var getCurrentSiteCache;
468
+ function getCurrentSite() {
469
+ if (getCurrentSiteCache === void 0) {
470
+ var testCookieName = "dd_site_test_".concat(generateUUID());
471
+ var testCookieValue = "test";
472
+ var domainLevels = window.location.hostname.split(".");
473
+ var candidateDomain = domainLevels.pop();
474
+ while (domainLevels.length && !getCookie(testCookieName)) {
475
+ candidateDomain = "".concat(domainLevels.pop(), ".").concat(candidateDomain);
476
+ setCookie(testCookieName, testCookieValue, ONE_SECOND, { domain: candidateDomain });
477
+ }
478
+ deleteCookie(testCookieName, { domain: candidateDomain });
479
+ getCurrentSiteCache = candidateDomain;
480
+ }
481
+ return getCurrentSiteCache;
482
+ }
483
+ var SESSION_STORE_KEY = "_dd_s";
484
+ var SESSION_TIME_OUT_DELAY = 4 * ONE_HOUR;
485
+ var SESSION_EXPIRATION_DELAY = 15 * ONE_MINUTE;
486
+ var SESSION_ENTRY_REGEXP = /^([a-zA-Z]+)=([a-z0-9-]+)$/;
487
+ var SESSION_ENTRY_SEPARATOR = "&";
488
+ var EXPIRED = "1";
489
+ function getExpiredSessionState() {
490
+ return {
491
+ isExpired: EXPIRED
492
+ };
493
+ }
494
+ function isSessionInNotStartedState(session) {
495
+ return isEmptyObject(session);
496
+ }
497
+ function isSessionStarted(session) {
498
+ return !isSessionInNotStartedState(session);
499
+ }
500
+ function isSessionInExpiredState(session) {
501
+ return session.isExpired !== void 0 || !isActiveSession(session);
502
+ }
503
+ function isActiveSession(sessionState) {
504
+ return (sessionState.created === void 0 || dateNow() - Number(sessionState.created) < SESSION_TIME_OUT_DELAY) && (sessionState.expire === void 0 || dateNow() < Number(sessionState.expire));
505
+ }
506
+ function expandSessionState(session) {
507
+ session.expire = String(dateNow() + SESSION_EXPIRATION_DELAY);
508
+ }
509
+ function toSessionString(session) {
510
+ return objectEntries(session).map(function(_a2) {
511
+ var key = _a2[0], value = _a2[1];
512
+ return "".concat(key, "=").concat(value);
513
+ }).join(SESSION_ENTRY_SEPARATOR);
514
+ }
515
+ function toSessionState(sessionString) {
516
+ var session = {};
517
+ if (isValidSessionString(sessionString)) {
518
+ sessionString.split(SESSION_ENTRY_SEPARATOR).forEach(function(entry) {
519
+ var matches = SESSION_ENTRY_REGEXP.exec(entry);
520
+ if (matches !== null) {
521
+ var key = matches[1], value = matches[2];
522
+ session[key] = value;
523
+ }
524
+ });
525
+ }
526
+ return session;
527
+ }
528
+ function isValidSessionString(sessionString) {
529
+ return !!sessionString && (sessionString.indexOf(SESSION_ENTRY_SEPARATOR) !== -1 || SESSION_ENTRY_REGEXP.test(sessionString));
530
+ }
531
+ var OLD_SESSION_COOKIE_NAME = "_dd";
532
+ var OLD_RUM_COOKIE_NAME = "_dd_r";
533
+ var OLD_LOGS_COOKIE_NAME = "_dd_l";
534
+ var RUM_SESSION_KEY = "rum";
535
+ var LOGS_SESSION_KEY$1 = "logs";
536
+ function tryOldCookiesMigration(cookieStoreStrategy) {
537
+ var sessionString = getInitCookie(SESSION_STORE_KEY);
538
+ if (!sessionString) {
539
+ var oldSessionId = getInitCookie(OLD_SESSION_COOKIE_NAME);
540
+ var oldRumType = getInitCookie(OLD_RUM_COOKIE_NAME);
541
+ var oldLogsType = getInitCookie(OLD_LOGS_COOKIE_NAME);
542
+ var session = {};
543
+ if (oldSessionId) {
544
+ session.id = oldSessionId;
545
+ }
546
+ if (oldLogsType && /^[01]$/.test(oldLogsType)) {
547
+ session[LOGS_SESSION_KEY$1] = oldLogsType;
548
+ }
549
+ if (oldRumType && /^[012]$/.test(oldRumType)) {
550
+ session[RUM_SESSION_KEY] = oldRumType;
551
+ }
552
+ if (isSessionStarted(session)) {
553
+ expandSessionState(session);
554
+ cookieStoreStrategy.persistSession(session);
555
+ }
556
+ }
557
+ }
558
+ function selectCookieStrategy(initConfiguration) {
559
+ var cookieOptions = buildCookieOptions(initConfiguration);
560
+ return areCookiesAuthorized(cookieOptions) ? { type: "Cookie", cookieOptions } : void 0;
561
+ }
562
+ function initCookieStrategy(cookieOptions) {
563
+ var cookieStore = {
564
+ /**
565
+ * Lock strategy allows mitigating issues due to concurrent access to cookie.
566
+ * This issue concerns only chromium browsers and enabling this on firefox increases cookie write failures.
567
+ */
568
+ isLockEnabled: isChromium(),
569
+ persistSession: persistSessionCookie(cookieOptions),
570
+ retrieveSession: retrieveSessionCookie,
571
+ expireSession: function() {
572
+ return expireSessionCookie(cookieOptions);
573
+ }
574
+ };
575
+ tryOldCookiesMigration(cookieStore);
576
+ return cookieStore;
577
+ }
578
+ function persistSessionCookie(options) {
579
+ return function(session) {
580
+ setCookie(SESSION_STORE_KEY, toSessionString(session), SESSION_EXPIRATION_DELAY, options);
581
+ };
582
+ }
583
+ function expireSessionCookie(options) {
584
+ setCookie(SESSION_STORE_KEY, toSessionString(getExpiredSessionState()), SESSION_TIME_OUT_DELAY, options);
585
+ }
586
+ function retrieveSessionCookie() {
587
+ var sessionString = getCookie(SESSION_STORE_KEY);
588
+ return toSessionState(sessionString);
589
+ }
590
+ function buildCookieOptions(initConfiguration) {
591
+ var cookieOptions = {};
592
+ cookieOptions.secure = !!initConfiguration.useSecureSessionCookie || !!initConfiguration.usePartitionedCrossSiteSessionCookie || !!initConfiguration.useCrossSiteSessionCookie;
593
+ cookieOptions.crossSite = !!initConfiguration.usePartitionedCrossSiteSessionCookie || !!initConfiguration.useCrossSiteSessionCookie;
594
+ cookieOptions.partitioned = !!initConfiguration.usePartitionedCrossSiteSessionCookie;
595
+ if (initConfiguration.trackSessionAcrossSubdomains) {
596
+ cookieOptions.domain = getCurrentSite();
597
+ }
598
+ return cookieOptions;
599
+ }
600
+ var LOCAL_STORAGE_TEST_KEY = "_dd_test_";
601
+ function selectLocalStorageStrategy() {
602
+ try {
603
+ var id = generateUUID();
604
+ var testKey = "".concat(LOCAL_STORAGE_TEST_KEY).concat(id);
605
+ localStorage.setItem(testKey, id);
606
+ var retrievedId = localStorage.getItem(testKey);
607
+ localStorage.removeItem(testKey);
608
+ return id === retrievedId ? { type: "LocalStorage" } : void 0;
609
+ } catch (e) {
610
+ return void 0;
611
+ }
612
+ }
613
+ function initLocalStorageStrategy() {
614
+ return {
615
+ isLockEnabled: false,
616
+ persistSession: persistInLocalStorage,
617
+ retrieveSession: retrieveSessionFromLocalStorage,
618
+ expireSession: expireSessionFromLocalStorage
619
+ };
620
+ }
621
+ function persistInLocalStorage(sessionState) {
622
+ localStorage.setItem(SESSION_STORE_KEY, toSessionString(sessionState));
623
+ }
624
+ function retrieveSessionFromLocalStorage() {
625
+ var sessionString = localStorage.getItem(SESSION_STORE_KEY);
626
+ return toSessionState(sessionString);
627
+ }
628
+ function expireSessionFromLocalStorage() {
629
+ persistInLocalStorage(getExpiredSessionState());
630
+ }
631
+ var LOCK_RETRY_DELAY = 10;
632
+ var LOCK_MAX_TRIES = 100;
633
+ var bufferedOperations = [];
634
+ var ongoingOperations;
635
+ function processSessionStoreOperations(operations, sessionStoreStrategy, numberOfRetries) {
636
+ var _a2;
637
+ if (numberOfRetries === void 0) {
638
+ numberOfRetries = 0;
639
+ }
640
+ var isLockEnabled = sessionStoreStrategy.isLockEnabled, persistSession = sessionStoreStrategy.persistSession, expireSession = sessionStoreStrategy.expireSession;
641
+ var persistWithLock = function(session) {
642
+ return persistSession(assign({}, session, { lock: currentLock }));
643
+ };
644
+ var retrieveStore = function() {
645
+ var session = sessionStoreStrategy.retrieveSession();
646
+ var lock = session.lock;
647
+ if (session.lock) {
648
+ delete session.lock;
649
+ }
650
+ return {
651
+ session,
652
+ lock
653
+ };
654
+ };
655
+ if (!ongoingOperations) {
656
+ ongoingOperations = operations;
657
+ }
658
+ if (operations !== ongoingOperations) {
659
+ bufferedOperations.push(operations);
660
+ return;
661
+ }
662
+ if (isLockEnabled && numberOfRetries >= LOCK_MAX_TRIES) {
663
+ next(sessionStoreStrategy);
664
+ return;
665
+ }
666
+ var currentLock;
667
+ var currentStore = retrieveStore();
668
+ if (isLockEnabled) {
669
+ if (currentStore.lock) {
670
+ retryLater(operations, sessionStoreStrategy, numberOfRetries);
671
+ return;
672
+ }
673
+ currentLock = generateUUID();
674
+ persistWithLock(currentStore.session);
675
+ currentStore = retrieveStore();
676
+ if (currentStore.lock !== currentLock) {
677
+ retryLater(operations, sessionStoreStrategy, numberOfRetries);
678
+ return;
679
+ }
680
+ }
681
+ var processedSession = operations.process(currentStore.session);
682
+ if (isLockEnabled) {
683
+ currentStore = retrieveStore();
684
+ if (currentStore.lock !== currentLock) {
685
+ retryLater(operations, sessionStoreStrategy, numberOfRetries);
686
+ return;
687
+ }
688
+ }
689
+ if (processedSession) {
690
+ if (isSessionInExpiredState(processedSession)) {
691
+ expireSession();
692
+ } else {
693
+ expandSessionState(processedSession);
694
+ isLockEnabled ? persistWithLock(processedSession) : persistSession(processedSession);
695
+ }
696
+ }
697
+ if (isLockEnabled) {
698
+ if (!(processedSession && isSessionInExpiredState(processedSession))) {
699
+ currentStore = retrieveStore();
700
+ if (currentStore.lock !== currentLock) {
701
+ retryLater(operations, sessionStoreStrategy, numberOfRetries);
702
+ return;
703
+ }
704
+ persistSession(currentStore.session);
705
+ processedSession = currentStore.session;
706
+ }
707
+ }
708
+ (_a2 = operations.after) === null || _a2 === void 0 ? void 0 : _a2.call(operations, processedSession || currentStore.session);
709
+ next(sessionStoreStrategy);
710
+ }
711
+ function retryLater(operations, sessionStore, currentNumberOfRetries) {
712
+ setTimeout(function() {
713
+ processSessionStoreOperations(operations, sessionStore, currentNumberOfRetries + 1);
714
+ }, LOCK_RETRY_DELAY);
715
+ }
716
+ function next(sessionStore) {
717
+ ongoingOperations = void 0;
718
+ var nextOperations = bufferedOperations.shift();
719
+ if (nextOperations) {
720
+ processSessionStoreOperations(nextOperations, sessionStore);
721
+ }
722
+ }
723
+ var STORAGE_POLL_DELAY = ONE_SECOND;
724
+ function selectSessionStoreStrategyType(initConfiguration) {
725
+ var sessionStoreStrategyType = selectCookieStrategy(initConfiguration);
726
+ if (!sessionStoreStrategyType && initConfiguration.allowFallbackToLocalStorage) {
727
+ sessionStoreStrategyType = selectLocalStorageStrategy();
728
+ }
729
+ return sessionStoreStrategyType;
730
+ }
731
+ function startSessionStore(sessionStoreStrategyType, productKey, computeSessionState2) {
732
+ var renewObservable = new Observable();
733
+ var expireObservable = new Observable();
734
+ var sessionStateUpdateObservable = new Observable();
735
+ var sessionStoreStrategy = sessionStoreStrategyType.type === "Cookie" ? initCookieStrategy(sessionStoreStrategyType.cookieOptions) : initLocalStorageStrategy();
736
+ var expireSession = sessionStoreStrategy.expireSession;
737
+ var watchSessionTimeoutId = setInterval(watchSession, STORAGE_POLL_DELAY);
738
+ var sessionCache;
739
+ startSession();
740
+ var _a2 = throttle(function() {
741
+ processSessionStoreOperations({
742
+ process: function(sessionState) {
743
+ if (isSessionInNotStartedState(sessionState)) {
744
+ return;
745
+ }
746
+ var synchronizedSession = synchronizeSession(sessionState);
747
+ expandOrRenewSessionState(synchronizedSession);
748
+ return synchronizedSession;
749
+ },
750
+ after: function(sessionState) {
751
+ if (isSessionStarted(sessionState) && !hasSessionInCache()) {
752
+ renewSessionInCache(sessionState);
753
+ }
754
+ sessionCache = sessionState;
755
+ }
756
+ }, sessionStoreStrategy);
757
+ }, STORAGE_POLL_DELAY), throttledExpandOrRenewSession = _a2.throttled, cancelExpandOrRenewSession = _a2.cancel;
758
+ function expandSession() {
759
+ processSessionStoreOperations({
760
+ process: function(sessionState) {
761
+ return hasSessionInCache() ? synchronizeSession(sessionState) : void 0;
762
+ }
763
+ }, sessionStoreStrategy);
764
+ }
765
+ function watchSession() {
766
+ processSessionStoreOperations({
767
+ process: function(sessionState) {
768
+ return isSessionInExpiredState(sessionState) ? getExpiredSessionState() : void 0;
769
+ },
770
+ after: synchronizeSession
771
+ }, sessionStoreStrategy);
772
+ }
773
+ function synchronizeSession(sessionState) {
774
+ if (isSessionInExpiredState(sessionState)) {
775
+ sessionState = getExpiredSessionState();
776
+ }
777
+ if (hasSessionInCache()) {
778
+ if (isSessionInCacheOutdated(sessionState)) {
779
+ expireSessionInCache();
780
+ } else {
781
+ sessionStateUpdateObservable.notify({ previousState: sessionCache, newState: sessionState });
782
+ sessionCache = sessionState;
783
+ }
784
+ }
785
+ return sessionState;
786
+ }
787
+ function startSession() {
788
+ processSessionStoreOperations({
789
+ process: function(sessionState) {
790
+ if (isSessionInNotStartedState(sessionState)) {
791
+ return getExpiredSessionState();
792
+ }
793
+ },
794
+ after: function(sessionState) {
795
+ sessionCache = sessionState;
796
+ }
797
+ }, sessionStoreStrategy);
798
+ }
799
+ function expandOrRenewSessionState(sessionState) {
800
+ if (isSessionInNotStartedState(sessionState)) {
801
+ return false;
802
+ }
803
+ var _a3 = computeSessionState2(sessionState[productKey]), trackingType = _a3.trackingType, isTracked = _a3.isTracked;
804
+ sessionState[productKey] = trackingType;
805
+ delete sessionState.isExpired;
806
+ if (isTracked && !sessionState.id) {
807
+ sessionState.id = generateUUID();
808
+ sessionState.created = String(dateNow());
809
+ }
810
+ }
811
+ function hasSessionInCache() {
812
+ return sessionCache[productKey] !== void 0;
813
+ }
814
+ function isSessionInCacheOutdated(sessionState) {
815
+ return sessionCache.id !== sessionState.id || sessionCache[productKey] !== sessionState[productKey];
816
+ }
817
+ function expireSessionInCache() {
818
+ sessionCache = getExpiredSessionState();
819
+ expireObservable.notify();
820
+ }
821
+ function renewSessionInCache(sessionState) {
822
+ sessionCache = sessionState;
823
+ renewObservable.notify();
824
+ }
825
+ function updateSessionState(partialSessionState) {
826
+ processSessionStoreOperations({
827
+ process: function(sessionState) {
828
+ return assign({}, sessionState, partialSessionState);
829
+ },
830
+ after: synchronizeSession
831
+ }, sessionStoreStrategy);
832
+ }
833
+ return {
834
+ expandOrRenewSession: throttledExpandOrRenewSession,
835
+ expandSession,
836
+ getSession: function() {
837
+ return sessionCache;
838
+ },
839
+ renewObservable,
840
+ expireObservable,
841
+ sessionStateUpdateObservable,
842
+ restartSession: startSession,
843
+ expire: function() {
844
+ cancelExpandOrRenewSession();
845
+ expireSession();
846
+ synchronizeSession(getExpiredSessionState());
847
+ },
848
+ stop: function() {
849
+ clearInterval(watchSessionTimeoutId);
850
+ },
851
+ updateSessionState
852
+ };
853
+ }
854
+ var TrackingConsent = {
855
+ GRANTED: "granted",
856
+ NOT_GRANTED: "not-granted"
857
+ };
858
+ function createTrackingConsentState(currentConsent) {
859
+ var observable = new Observable();
860
+ return {
861
+ tryToInit: function(trackingConsent) {
862
+ if (!currentConsent) {
863
+ currentConsent = trackingConsent;
864
+ }
865
+ },
866
+ update: function(trackingConsent) {
867
+ currentConsent = trackingConsent;
868
+ observable.notify();
869
+ },
870
+ isGranted: function() {
871
+ return currentConsent === TrackingConsent.GRANTED;
872
+ },
873
+ observable
874
+ };
875
+ }
876
+ function jsonStringify(value, replacer, space) {
877
+ if (typeof value !== "object" || value === null) {
878
+ return JSON.stringify(value);
879
+ }
880
+ var restoreObjectPrototypeToJson = detachToJsonMethod(Object.prototype);
881
+ var restoreArrayPrototypeToJson = detachToJsonMethod(Array.prototype);
882
+ var restoreValuePrototypeToJson = detachToJsonMethod(Object.getPrototypeOf(value));
883
+ var restoreValueToJson = detachToJsonMethod(value);
884
+ try {
885
+ return JSON.stringify(value, replacer, space);
886
+ } catch (_a2) {
887
+ return "<error: unable to serialize object>";
888
+ } finally {
889
+ restoreObjectPrototypeToJson();
890
+ restoreArrayPrototypeToJson();
891
+ restoreValuePrototypeToJson();
892
+ restoreValueToJson();
893
+ }
894
+ }
895
+ function detachToJsonMethod(value) {
896
+ var object = value;
897
+ var objectToJson = object.toJSON;
898
+ if (objectToJson) {
899
+ delete object.toJSON;
900
+ return function() {
901
+ object.toJSON = objectToJson;
902
+ };
903
+ }
904
+ return noop;
905
+ }
906
+ function normalizeUrl(url) {
907
+ return buildUrl(url, location.href).href;
908
+ }
909
+ function buildUrl(url, base) {
910
+ var supportedURL = getSupportedUrl();
911
+ if (supportedURL) {
912
+ try {
913
+ return base !== void 0 ? new supportedURL(url, base) : new supportedURL(url);
914
+ } catch (error) {
915
+ throw new Error("Failed to construct URL: ".concat(String(error), " ").concat(jsonStringify({ url, base })));
916
+ }
917
+ }
918
+ if (base === void 0 && !/:/.test(url)) {
919
+ throw new Error("Invalid URL: '".concat(url, "'"));
920
+ }
921
+ var doc = document;
922
+ var anchorElement = doc.createElement("a");
923
+ if (base !== void 0) {
924
+ doc = document.implementation.createHTMLDocument("");
925
+ var baseElement = doc.createElement("base");
926
+ baseElement.href = base;
927
+ doc.head.appendChild(baseElement);
928
+ doc.body.appendChild(anchorElement);
929
+ }
930
+ anchorElement.href = url;
931
+ return anchorElement;
932
+ }
933
+ var originalURL = URL;
934
+ var isURLSupported;
935
+ function getSupportedUrl() {
936
+ if (isURLSupported === void 0) {
937
+ try {
938
+ var url = new originalURL("http://test/path");
939
+ isURLSupported = url.href === "http://test/path";
940
+ } catch (_a2) {
941
+ isURLSupported = false;
942
+ }
943
+ }
944
+ return isURLSupported ? originalURL : void 0;
945
+ }
946
+ var INTAKE_SITE_STAGING = "datad0g.com";
947
+ var INTAKE_SITE_FED_STAGING = "dd0g-gov.com";
948
+ var INTAKE_SITE_US1 = "datadoghq.com";
949
+ var INTAKE_SITE_US1_FED = "ddog-gov.com";
950
+ var PCI_INTAKE_HOST_US1 = "pci.browser-intake-datadoghq.com";
951
+ function createEndpointBuilder(initConfiguration, trackType, configurationTags) {
952
+ var buildUrlWithParameters = createEndpointUrlWithParametersBuilder(initConfiguration, trackType);
953
+ return {
954
+ build: function(api, payload) {
955
+ var parameters = buildEndpointParameters(initConfiguration, trackType, configurationTags, api, payload);
956
+ return buildUrlWithParameters(parameters);
957
+ },
958
+ urlPrefix: buildUrlWithParameters(""),
959
+ trackType
960
+ };
961
+ }
962
+ function createEndpointUrlWithParametersBuilder(initConfiguration, trackType) {
963
+ var path = "/api/v2/".concat(trackType);
964
+ var proxy = initConfiguration.proxy;
965
+ if (typeof proxy === "string") {
966
+ var normalizedProxyUrl_1 = normalizeUrl(proxy);
967
+ return function(parameters) {
968
+ return "".concat(normalizedProxyUrl_1, "?ddforward=").concat(encodeURIComponent("".concat(path, "?").concat(parameters)));
969
+ };
970
+ }
971
+ if (typeof proxy === "function") {
972
+ return function(parameters) {
973
+ return proxy({ path, parameters });
974
+ };
975
+ }
976
+ var host = buildEndpointHost(trackType, initConfiguration);
977
+ return function(parameters) {
978
+ return "https://".concat(host).concat(path, "?").concat(parameters);
979
+ };
980
+ }
981
+ function buildEndpointHost(trackType, initConfiguration) {
982
+ var _a2 = initConfiguration.site, site = _a2 === void 0 ? INTAKE_SITE_US1 : _a2, internalAnalyticsSubdomain = initConfiguration.internalAnalyticsSubdomain;
983
+ if (trackType === "logs" && initConfiguration.usePciIntake && site === INTAKE_SITE_US1) {
984
+ return PCI_INTAKE_HOST_US1;
985
+ }
986
+ if (internalAnalyticsSubdomain && site === INTAKE_SITE_US1) {
987
+ return "".concat(internalAnalyticsSubdomain, ".").concat(INTAKE_SITE_US1);
988
+ }
989
+ if (site === INTAKE_SITE_FED_STAGING) {
990
+ return "http-intake.logs.".concat(site);
991
+ }
992
+ var domainParts = site.split(".");
993
+ var extension = domainParts.pop();
994
+ return "browser-intake-".concat(domainParts.join("-"), ".").concat(extension);
995
+ }
996
+ function buildEndpointParameters(_a2, trackType, configurationTags, api, _b) {
997
+ var clientToken = _a2.clientToken, internalAnalyticsSubdomain = _a2.internalAnalyticsSubdomain;
998
+ var retry = _b.retry, encoding = _b.encoding;
999
+ var tags = ["sdk_version:".concat("5.23.3"), "api:".concat(api)].concat(configurationTags);
1000
+ if (retry) {
1001
+ tags.push("retry_count:".concat(retry.count), "retry_after:".concat(retry.lastFailureStatus));
1002
+ }
1003
+ var parameters = [
1004
+ "ddsource=browser",
1005
+ "ddtags=".concat(encodeURIComponent(tags.join(","))),
1006
+ "dd-api-key=".concat(clientToken),
1007
+ "dd-evp-origin-version=".concat(encodeURIComponent("5.23.3")),
1008
+ "dd-evp-origin=browser",
1009
+ "dd-request-id=".concat(generateUUID())
1010
+ ];
1011
+ if (encoding) {
1012
+ parameters.push("dd-evp-encoding=".concat(encoding));
1013
+ }
1014
+ if (trackType === "rum") {
1015
+ parameters.push("batch_time=".concat(timeStampNow()));
1016
+ }
1017
+ if (internalAnalyticsSubdomain) {
1018
+ parameters.reverse();
1019
+ }
1020
+ return parameters.join("&");
1021
+ }
1022
+ var TAG_SIZE_LIMIT = 200;
1023
+ function buildTags(configuration) {
1024
+ var env = configuration.env, service = configuration.service, version = configuration.version, datacenter = configuration.datacenter;
1025
+ var tags = [];
1026
+ if (env) {
1027
+ tags.push(buildTag("env", env));
1028
+ }
1029
+ if (service) {
1030
+ tags.push(buildTag("service", service));
1031
+ }
1032
+ if (version) {
1033
+ tags.push(buildTag("version", version));
1034
+ }
1035
+ if (datacenter) {
1036
+ tags.push(buildTag("datacenter", datacenter));
1037
+ }
1038
+ return tags;
1039
+ }
1040
+ var FORBIDDEN_CHARACTERS = /[^a-z0-9_:./-]/;
1041
+ function buildTag(key, rawValue) {
1042
+ var valueSizeLimit = TAG_SIZE_LIMIT - key.length - 1;
1043
+ if (rawValue.length > valueSizeLimit || FORBIDDEN_CHARACTERS.test(rawValue)) {
1044
+ display.warn("".concat(key, " value doesn't meet tag requirements and will be sanitized. ").concat(MORE_DETAILS, " ").concat(DOCS_ORIGIN, "/getting_started/tagging/#defining-tags"));
1045
+ }
1046
+ var sanitizedValue = rawValue.replace(/,/g, "_");
1047
+ return "".concat(key, ":").concat(sanitizedValue);
1048
+ }
1049
+ function computeTransportConfiguration(initConfiguration) {
1050
+ var site = initConfiguration.site || INTAKE_SITE_US1;
1051
+ var tags = buildTags(initConfiguration);
1052
+ var endpointBuilders = computeEndpointBuilders(initConfiguration, tags);
1053
+ var intakeUrlPrefixes = computeIntakeUrlPrefixes(endpointBuilders, site);
1054
+ var replicaConfiguration = computeReplicaConfiguration(initConfiguration, intakeUrlPrefixes, tags);
1055
+ return assign({
1056
+ isIntakeUrl: function(url) {
1057
+ return intakeUrlPrefixes.some(function(intakeEndpoint) {
1058
+ return url.indexOf(intakeEndpoint) === 0;
1059
+ });
1060
+ },
1061
+ replica: replicaConfiguration,
1062
+ site
1063
+ }, endpointBuilders);
1064
+ }
1065
+ function computeEndpointBuilders(initConfiguration, tags) {
1066
+ return {
1067
+ logsEndpointBuilder: createEndpointBuilder(initConfiguration, "logs", tags),
1068
+ rumEndpointBuilder: createEndpointBuilder(initConfiguration, "rum", tags),
1069
+ sessionReplayEndpointBuilder: createEndpointBuilder(initConfiguration, "replay", tags)
1070
+ };
1071
+ }
1072
+ function computeReplicaConfiguration(initConfiguration, intakeUrlPrefixes, tags) {
1073
+ if (!initConfiguration.replica) {
1074
+ return;
1075
+ }
1076
+ var replicaConfiguration = assign({}, initConfiguration, {
1077
+ site: INTAKE_SITE_US1,
1078
+ clientToken: initConfiguration.replica.clientToken
1079
+ });
1080
+ var replicaEndpointBuilders = {
1081
+ logsEndpointBuilder: createEndpointBuilder(replicaConfiguration, "logs", tags),
1082
+ rumEndpointBuilder: createEndpointBuilder(replicaConfiguration, "rum", tags)
1083
+ };
1084
+ intakeUrlPrefixes.push.apply(intakeUrlPrefixes, objectValues(replicaEndpointBuilders).map(function(builder) {
1085
+ return builder.urlPrefix;
1086
+ }));
1087
+ return assign({ applicationId: initConfiguration.replica.applicationId }, replicaEndpointBuilders);
1088
+ }
1089
+ function computeIntakeUrlPrefixes(endpointBuilders, site) {
1090
+ var intakeUrlPrefixes = objectValues(endpointBuilders).map(function(builder) {
1091
+ return builder.urlPrefix;
1092
+ });
1093
+ if (site === INTAKE_SITE_US1) {
1094
+ intakeUrlPrefixes.push("https://".concat(PCI_INTAKE_HOST_US1, "/"));
1095
+ }
1096
+ return intakeUrlPrefixes;
1097
+ }
1098
+ function isString(tag, tagName) {
1099
+ if (tag !== void 0 && tag !== null && typeof tag !== "string") {
1100
+ display.error("".concat(tagName, " must be defined as a string"));
1101
+ return false;
1102
+ }
1103
+ return true;
1104
+ }
1105
+ function isDatadogSite(site) {
1106
+ if (site && typeof site === "string" && !/(datadog|ddog|datad0g|dd0g)/.test(site)) {
1107
+ display.error("Site should be a valid Datadog site. ".concat(MORE_DETAILS, " ").concat(DOCS_ORIGIN, "/getting_started/site/."));
1108
+ return false;
1109
+ }
1110
+ return true;
1111
+ }
1112
+ function isSampleRate(sampleRate, name) {
1113
+ if (sampleRate !== void 0 && !isPercentage(sampleRate)) {
1114
+ display.error("".concat(name, " Sample Rate should be a number between 0 and 100"));
1115
+ return false;
1116
+ }
1117
+ return true;
1118
+ }
1119
+ function validateAndBuildConfiguration(initConfiguration) {
1120
+ var _a2, _b, _c, _d, _e;
1121
+ if (!initConfiguration || !initConfiguration.clientToken) {
1122
+ display.error("Client Token is not configured, we will not send any data.");
1123
+ return;
1124
+ }
1125
+ if (!isDatadogSite(initConfiguration.site) || !isSampleRate(initConfiguration.sessionSampleRate, "Session") || !isSampleRate(initConfiguration.telemetrySampleRate, "Telemetry") || !isSampleRate(initConfiguration.telemetryConfigurationSampleRate, "Telemetry Configuration") || !isSampleRate(initConfiguration.telemetryUsageSampleRate, "Telemetry Usage") || !isString(initConfiguration.version, "Version") || !isString(initConfiguration.env, "Env") || !isString(initConfiguration.service, "Service")) {
1126
+ return;
1127
+ }
1128
+ if (initConfiguration.trackingConsent !== void 0 && !objectHasValue(TrackingConsent, initConfiguration.trackingConsent)) {
1129
+ display.error('Tracking Consent should be either "granted" or "not-granted"');
1130
+ return;
1131
+ }
1132
+ return assign({
1133
+ beforeSend: initConfiguration.beforeSend && catchUserErrors(initConfiguration.beforeSend, "beforeSend threw an error:"),
1134
+ sessionStoreStrategyType: selectSessionStoreStrategyType(initConfiguration),
1135
+ sessionSampleRate: (_a2 = initConfiguration.sessionSampleRate) !== null && _a2 !== void 0 ? _a2 : 100,
1136
+ telemetrySampleRate: (_b = initConfiguration.telemetrySampleRate) !== null && _b !== void 0 ? _b : 20,
1137
+ telemetryConfigurationSampleRate: (_c = initConfiguration.telemetryConfigurationSampleRate) !== null && _c !== void 0 ? _c : 5,
1138
+ telemetryUsageSampleRate: (_d = initConfiguration.telemetryUsageSampleRate) !== null && _d !== void 0 ? _d : 5,
1139
+ service: initConfiguration.service || void 0,
1140
+ silentMultipleInit: !!initConfiguration.silentMultipleInit,
1141
+ allowUntrustedEvents: !!initConfiguration.allowUntrustedEvents,
1142
+ trackingConsent: (_e = initConfiguration.trackingConsent) !== null && _e !== void 0 ? _e : TrackingConsent.GRANTED,
1143
+ storeContextsAcrossPages: !!initConfiguration.storeContextsAcrossPages,
1144
+ /**
1145
+ * beacon payload max queue size implementation is 64kb
1146
+ * ensure that we leave room for logs, rum and potential other users
1147
+ */
1148
+ batchBytesLimit: 16 * ONE_KIBI_BYTE,
1149
+ eventRateLimiterThreshold: 3e3,
1150
+ maxTelemetryEventsPerPage: 15,
1151
+ /**
1152
+ * flush automatically, aim to be lower than ALB connection timeout
1153
+ * to maximize connection reuse.
1154
+ */
1155
+ flushTimeout: 30 * ONE_SECOND,
1156
+ /**
1157
+ * Logs intake limit
1158
+ */
1159
+ batchMessagesLimit: 50,
1160
+ messageBytesLimit: 256 * ONE_KIBI_BYTE
1161
+ }, computeTransportConfiguration(initConfiguration));
1162
+ }
1163
+ function serializeConfiguration(initConfiguration) {
1164
+ return {
1165
+ session_sample_rate: initConfiguration.sessionSampleRate,
1166
+ telemetry_sample_rate: initConfiguration.telemetrySampleRate,
1167
+ telemetry_configuration_sample_rate: initConfiguration.telemetryConfigurationSampleRate,
1168
+ telemetry_usage_sample_rate: initConfiguration.telemetryUsageSampleRate,
1169
+ use_before_send: !!initConfiguration.beforeSend,
1170
+ use_cross_site_session_cookie: initConfiguration.useCrossSiteSessionCookie,
1171
+ use_partitioned_cross_site_session_cookie: initConfiguration.usePartitionedCrossSiteSessionCookie,
1172
+ use_secure_session_cookie: initConfiguration.useSecureSessionCookie,
1173
+ use_proxy: !!initConfiguration.proxy,
1174
+ silent_multiple_init: initConfiguration.silentMultipleInit,
1175
+ track_session_across_subdomains: initConfiguration.trackSessionAcrossSubdomains,
1176
+ allow_fallback_to_local_storage: !!initConfiguration.allowFallbackToLocalStorage,
1177
+ store_contexts_across_pages: !!initConfiguration.storeContextsAcrossPages,
1178
+ allow_untrusted_events: !!initConfiguration.allowUntrustedEvents,
1179
+ tracking_consent: initConfiguration.trackingConsent
1180
+ };
1181
+ }
1182
+ var ExperimentalFeature;
1183
+ (function(ExperimentalFeature2) {
1184
+ ExperimentalFeature2["WRITABLE_RESOURCE_GRAPHQL"] = "writable_resource_graphql";
1185
+ ExperimentalFeature2["CUSTOM_VITALS"] = "custom_vitals";
1186
+ ExperimentalFeature2["TOLERANT_RESOURCE_TIMINGS"] = "tolerant_resource_timings";
1187
+ ExperimentalFeature2["REMOTE_CONFIGURATION"] = "remote_configuration";
1188
+ ExperimentalFeature2["UPDATE_VIEW_NAME"] = "update_view_name";
1189
+ })(ExperimentalFeature || (ExperimentalFeature = {}));
1190
+ var enabledExperimentalFeatures = /* @__PURE__ */ new Set();
1191
+ function initFeatureFlags(enableExperimentalFeatures) {
1192
+ if (Array.isArray(enableExperimentalFeatures)) {
1193
+ addExperimentalFeatures(enableExperimentalFeatures.filter(function(flag) {
1194
+ return objectHasValue(ExperimentalFeature, flag);
1195
+ }));
1196
+ }
1197
+ }
1198
+ function addExperimentalFeatures(enabledFeatures) {
1199
+ enabledFeatures.forEach(function(flag) {
1200
+ enabledExperimentalFeatures.add(flag);
1201
+ });
1202
+ }
1203
+ function getExperimentalFeatures() {
1204
+ return enabledExperimentalFeatures;
1205
+ }
1206
+ var UNKNOWN_FUNCTION = "?";
1207
+ function computeStackTrace(ex) {
1208
+ var stack = [];
1209
+ var stackProperty = tryToGetString(ex, "stack");
1210
+ var exString = String(ex);
1211
+ if (stackProperty && startsWith(stackProperty, exString)) {
1212
+ stackProperty = stackProperty.slice(exString.length);
1213
+ }
1214
+ if (stackProperty) {
1215
+ stackProperty.split("\n").forEach(function(line) {
1216
+ var stackFrame = parseChromeLine(line) || parseChromeAnonymousLine(line) || parseWinLine(line) || parseGeckoLine(line);
1217
+ if (stackFrame) {
1218
+ if (!stackFrame.func && stackFrame.line) {
1219
+ stackFrame.func = UNKNOWN_FUNCTION;
1220
+ }
1221
+ stack.push(stackFrame);
1222
+ }
1223
+ });
1224
+ }
1225
+ return {
1226
+ message: tryToGetString(ex, "message"),
1227
+ name: tryToGetString(ex, "name"),
1228
+ stack
1229
+ };
1230
+ }
1231
+ var fileUrl = "((?:file|https?|blob|chrome-extension|native|eval|webpack|snippet|<anonymous>|\\w+\\.|\\/).*?)";
1232
+ var filePosition = "(?::(\\d+))";
1233
+ var CHROME_LINE_RE = new RegExp("^\\s*at (.*?) ?\\(".concat(fileUrl).concat(filePosition, "?").concat(filePosition, "?\\)?\\s*$"), "i");
1234
+ var CHROME_EVAL_RE = new RegExp("\\((\\S*)".concat(filePosition).concat(filePosition, "\\)"));
1235
+ function parseChromeLine(line) {
1236
+ var parts = CHROME_LINE_RE.exec(line);
1237
+ if (!parts) {
1238
+ return;
1239
+ }
1240
+ var isNative = parts[2] && parts[2].indexOf("native") === 0;
1241
+ var isEval = parts[2] && parts[2].indexOf("eval") === 0;
1242
+ var submatch = CHROME_EVAL_RE.exec(parts[2]);
1243
+ if (isEval && submatch) {
1244
+ parts[2] = submatch[1];
1245
+ parts[3] = submatch[2];
1246
+ parts[4] = submatch[3];
1247
+ }
1248
+ return {
1249
+ args: isNative ? [parts[2]] : [],
1250
+ column: parts[4] ? +parts[4] : void 0,
1251
+ func: parts[1] || UNKNOWN_FUNCTION,
1252
+ line: parts[3] ? +parts[3] : void 0,
1253
+ url: !isNative ? parts[2] : void 0
1254
+ };
1255
+ }
1256
+ var CHROME_ANONYMOUS_FUNCTION_RE = new RegExp("^\\s*at ?".concat(fileUrl).concat(filePosition, "?").concat(filePosition, "??\\s*$"), "i");
1257
+ function parseChromeAnonymousLine(line) {
1258
+ var parts = CHROME_ANONYMOUS_FUNCTION_RE.exec(line);
1259
+ if (!parts) {
1260
+ return;
1261
+ }
1262
+ return {
1263
+ args: [],
1264
+ column: parts[3] ? +parts[3] : void 0,
1265
+ func: UNKNOWN_FUNCTION,
1266
+ line: parts[2] ? +parts[2] : void 0,
1267
+ url: parts[1]
1268
+ };
1269
+ }
1270
+ var WINJS_LINE_RE = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1271
+ function parseWinLine(line) {
1272
+ var parts = WINJS_LINE_RE.exec(line);
1273
+ if (!parts) {
1274
+ return;
1275
+ }
1276
+ return {
1277
+ args: [],
1278
+ column: parts[4] ? +parts[4] : void 0,
1279
+ func: parts[1] || UNKNOWN_FUNCTION,
1280
+ line: +parts[3],
1281
+ url: parts[2]
1282
+ };
1283
+ }
1284
+ var GECKO_LINE_RE = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;
1285
+ var GECKO_EVAL_RE = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
1286
+ function parseGeckoLine(line) {
1287
+ var parts = GECKO_LINE_RE.exec(line);
1288
+ if (!parts) {
1289
+ return;
1290
+ }
1291
+ var isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
1292
+ var submatch = GECKO_EVAL_RE.exec(parts[3]);
1293
+ if (isEval && submatch) {
1294
+ parts[3] = submatch[1];
1295
+ parts[4] = submatch[2];
1296
+ parts[5] = void 0;
1297
+ }
1298
+ return {
1299
+ args: parts[2] ? parts[2].split(",") : [],
1300
+ column: parts[5] ? +parts[5] : void 0,
1301
+ func: parts[1] || UNKNOWN_FUNCTION,
1302
+ line: parts[4] ? +parts[4] : void 0,
1303
+ url: parts[3]
1304
+ };
1305
+ }
1306
+ function tryToGetString(candidate, property) {
1307
+ if (typeof candidate !== "object" || !candidate || !(property in candidate)) {
1308
+ return void 0;
1309
+ }
1310
+ var value = candidate[property];
1311
+ return typeof value === "string" ? value : void 0;
1312
+ }
1313
+ function computeStackTraceFromOnErrorMessage(messageObj, url, line, column) {
1314
+ var stack = [{ url, column, line }];
1315
+ var _a2 = tryToParseMessage(messageObj), name = _a2.name, message = _a2.message;
1316
+ return {
1317
+ name,
1318
+ message,
1319
+ stack
1320
+ };
1321
+ }
1322
+ var ERROR_TYPES_RE = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\s\S]*)$/;
1323
+ function tryToParseMessage(messageObj) {
1324
+ var _a2;
1325
+ var name;
1326
+ var message;
1327
+ if ({}.toString.call(messageObj) === "[object String]") {
1328
+ _a2 = ERROR_TYPES_RE.exec(messageObj), name = _a2[1], message = _a2[2];
1329
+ }
1330
+ return { name, message };
1331
+ }
1332
+ function createHandlingStack() {
1333
+ var internalFramesToSkip = 2;
1334
+ var error = new Error();
1335
+ var formattedStack;
1336
+ if (!error.stack) {
1337
+ try {
1338
+ throw error;
1339
+ } catch (e) {
1340
+ }
1341
+ }
1342
+ callMonitored(function() {
1343
+ var stackTrace = computeStackTrace(error);
1344
+ stackTrace.stack = stackTrace.stack.slice(internalFramesToSkip);
1345
+ formattedStack = toStackTraceString(stackTrace);
1346
+ });
1347
+ return formattedStack;
1348
+ }
1349
+ function toStackTraceString(stack) {
1350
+ var result = formatErrorMessage(stack);
1351
+ stack.stack.forEach(function(frame) {
1352
+ var func = frame.func === "?" ? "<anonymous>" : frame.func;
1353
+ var args = frame.args && frame.args.length > 0 ? "(".concat(frame.args.join(", "), ")") : "";
1354
+ var line = frame.line ? ":".concat(frame.line) : "";
1355
+ var column = frame.line && frame.column ? ":".concat(frame.column) : "";
1356
+ result += "\n at ".concat(func).concat(args, " @ ").concat(frame.url).concat(line).concat(column);
1357
+ });
1358
+ return result;
1359
+ }
1360
+ function formatErrorMessage(stack) {
1361
+ return "".concat(stack.name || "Error", ": ").concat(stack.message);
1362
+ }
1363
+ function instrumentMethod(targetPrototype, method, onPreCall, _a2) {
1364
+ var _b = _a2 === void 0 ? {} : _a2, computeHandlingStack = _b.computeHandlingStack;
1365
+ var original = targetPrototype[method];
1366
+ if (typeof original !== "function") {
1367
+ if (startsWith(method, "on")) {
1368
+ original = noop;
1369
+ } else {
1370
+ return { stop: noop };
1371
+ }
1372
+ }
1373
+ var stopped = false;
1374
+ var instrumentation = function() {
1375
+ if (stopped) {
1376
+ return original.apply(this, arguments);
1377
+ }
1378
+ var parameters = arrayFrom(arguments);
1379
+ var postCallCallback;
1380
+ callMonitored(onPreCall, null, [
1381
+ {
1382
+ target: this,
1383
+ parameters,
1384
+ onPostCall: function(callback) {
1385
+ postCallCallback = callback;
1386
+ },
1387
+ handlingStack: computeHandlingStack ? createHandlingStack() : void 0
1388
+ }
1389
+ ]);
1390
+ var result = original.apply(this, parameters);
1391
+ if (postCallCallback) {
1392
+ callMonitored(postCallCallback, null, [result]);
1393
+ }
1394
+ return result;
1395
+ };
1396
+ targetPrototype[method] = instrumentation;
1397
+ return {
1398
+ stop: function() {
1399
+ stopped = true;
1400
+ if (targetPrototype[method] === instrumentation) {
1401
+ targetPrototype[method] = original;
1402
+ }
1403
+ }
1404
+ };
1405
+ }
1406
+ var SANITIZE_DEFAULT_MAX_CHARACTER_COUNT = 220 * ONE_KIBI_BYTE;
1407
+ var JSON_PATH_ROOT_ELEMENT = "$";
1408
+ var KEY_DECORATION_LENGTH = 3;
1409
+ function sanitize(source, maxCharacterCount) {
1410
+ if (maxCharacterCount === void 0) {
1411
+ maxCharacterCount = SANITIZE_DEFAULT_MAX_CHARACTER_COUNT;
1412
+ }
1413
+ var restoreObjectPrototypeToJson = detachToJsonMethod(Object.prototype);
1414
+ var restoreArrayPrototypeToJson = detachToJsonMethod(Array.prototype);
1415
+ var containerQueue = [];
1416
+ var visitedObjectsWithPath = /* @__PURE__ */ new WeakMap();
1417
+ var sanitizedData = sanitizeProcessor(source, JSON_PATH_ROOT_ELEMENT, void 0, containerQueue, visitedObjectsWithPath);
1418
+ var serializedSanitizedData = JSON.stringify(sanitizedData);
1419
+ var accumulatedCharacterCount = serializedSanitizedData ? serializedSanitizedData.length : 0;
1420
+ if (accumulatedCharacterCount > maxCharacterCount) {
1421
+ warnOverCharacterLimit(maxCharacterCount, "discarded", source);
1422
+ return void 0;
1423
+ }
1424
+ while (containerQueue.length > 0 && accumulatedCharacterCount < maxCharacterCount) {
1425
+ var containerToProcess = containerQueue.shift();
1426
+ var separatorLength = 0;
1427
+ if (Array.isArray(containerToProcess.source)) {
1428
+ for (var key = 0; key < containerToProcess.source.length; key++) {
1429
+ var targetData = sanitizeProcessor(containerToProcess.source[key], containerToProcess.path, key, containerQueue, visitedObjectsWithPath);
1430
+ if (targetData !== void 0) {
1431
+ accumulatedCharacterCount += JSON.stringify(targetData).length;
1432
+ } else {
1433
+ accumulatedCharacterCount += 4;
1434
+ }
1435
+ accumulatedCharacterCount += separatorLength;
1436
+ separatorLength = 1;
1437
+ if (accumulatedCharacterCount > maxCharacterCount) {
1438
+ warnOverCharacterLimit(maxCharacterCount, "truncated", source);
1439
+ break;
1440
+ }
1441
+ containerToProcess.target[key] = targetData;
1442
+ }
1443
+ } else {
1444
+ for (var key in containerToProcess.source) {
1445
+ if (Object.prototype.hasOwnProperty.call(containerToProcess.source, key)) {
1446
+ var targetData = sanitizeProcessor(containerToProcess.source[key], containerToProcess.path, key, containerQueue, visitedObjectsWithPath);
1447
+ if (targetData !== void 0) {
1448
+ accumulatedCharacterCount += JSON.stringify(targetData).length + separatorLength + key.length + KEY_DECORATION_LENGTH;
1449
+ separatorLength = 1;
1450
+ }
1451
+ if (accumulatedCharacterCount > maxCharacterCount) {
1452
+ warnOverCharacterLimit(maxCharacterCount, "truncated", source);
1453
+ break;
1454
+ }
1455
+ containerToProcess.target[key] = targetData;
1456
+ }
1457
+ }
1458
+ }
1459
+ }
1460
+ restoreObjectPrototypeToJson();
1461
+ restoreArrayPrototypeToJson();
1462
+ return sanitizedData;
1463
+ }
1464
+ function sanitizeProcessor(source, parentPath, key, queue, visitedObjectsWithPath) {
1465
+ var sourceToSanitize = tryToApplyToJSON(source);
1466
+ if (!sourceToSanitize || typeof sourceToSanitize !== "object") {
1467
+ return sanitizePrimitivesAndFunctions(sourceToSanitize);
1468
+ }
1469
+ var sanitizedSource = sanitizeObjects(sourceToSanitize);
1470
+ if (sanitizedSource !== "[Object]" && sanitizedSource !== "[Array]" && sanitizedSource !== "[Error]") {
1471
+ return sanitizedSource;
1472
+ }
1473
+ var sourceAsObject = source;
1474
+ if (visitedObjectsWithPath.has(sourceAsObject)) {
1475
+ return "[Reference seen at ".concat(visitedObjectsWithPath.get(sourceAsObject), "]");
1476
+ }
1477
+ var currentPath = key !== void 0 ? "".concat(parentPath, ".").concat(key) : parentPath;
1478
+ var target = Array.isArray(sourceToSanitize) ? [] : {};
1479
+ visitedObjectsWithPath.set(sourceAsObject, currentPath);
1480
+ queue.push({ source: sourceToSanitize, target, path: currentPath });
1481
+ return target;
1482
+ }
1483
+ function sanitizePrimitivesAndFunctions(value) {
1484
+ if (typeof value === "bigint") {
1485
+ return "[BigInt] ".concat(value.toString());
1486
+ }
1487
+ if (typeof value === "function") {
1488
+ return "[Function] ".concat(value.name || "unknown");
1489
+ }
1490
+ if (typeof value === "symbol") {
1491
+ return "[Symbol] ".concat(value.description || value.toString());
1492
+ }
1493
+ return value;
1494
+ }
1495
+ function sanitizeObjects(value) {
1496
+ try {
1497
+ if (value instanceof Event) {
1498
+ return {
1499
+ isTrusted: value.isTrusted
1500
+ };
1501
+ }
1502
+ var result = Object.prototype.toString.call(value);
1503
+ var match = result.match(/\[object (.*)\]/);
1504
+ if (match && match[1]) {
1505
+ return "[".concat(match[1], "]");
1506
+ }
1507
+ } catch (_a2) {
1508
+ }
1509
+ return "[Unserializable]";
1510
+ }
1511
+ function tryToApplyToJSON(value) {
1512
+ var object = value;
1513
+ if (object && typeof object.toJSON === "function") {
1514
+ try {
1515
+ return object.toJSON();
1516
+ } catch (_a2) {
1517
+ }
1518
+ }
1519
+ return value;
1520
+ }
1521
+ function warnOverCharacterLimit(maxCharacterCount, changeType, source) {
1522
+ display.warn("The data provided has been ".concat(changeType, " as it is over the limit of ").concat(maxCharacterCount, " characters:"), source);
1523
+ }
1524
+ var NO_ERROR_STACK_PRESENT_MESSAGE = "No stack, consider using an instance of Error";
1525
+ function computeRawError(_a2) {
1526
+ var stackTrace = _a2.stackTrace, originalError = _a2.originalError, handlingStack = _a2.handlingStack, startClocks = _a2.startClocks, nonErrorPrefix = _a2.nonErrorPrefix, source = _a2.source, handling = _a2.handling;
1527
+ var isErrorInstance = originalError instanceof Error;
1528
+ var message = computeMessage(stackTrace, isErrorInstance, nonErrorPrefix, originalError);
1529
+ var stack = hasUsableStack(isErrorInstance, stackTrace) ? toStackTraceString(stackTrace) : NO_ERROR_STACK_PRESENT_MESSAGE;
1530
+ var causes = isErrorInstance ? flattenErrorCauses(originalError, source) : void 0;
1531
+ var type = stackTrace ? stackTrace.name : void 0;
1532
+ var fingerprint = tryToGetFingerprint(originalError);
1533
+ return {
1534
+ startClocks,
1535
+ source,
1536
+ handling,
1537
+ handlingStack,
1538
+ originalError,
1539
+ type,
1540
+ message,
1541
+ stack,
1542
+ causes,
1543
+ fingerprint
1544
+ };
1545
+ }
1546
+ function computeMessage(stackTrace, isErrorInstance, nonErrorPrefix, originalError) {
1547
+ return (stackTrace === null || stackTrace === void 0 ? void 0 : stackTrace.message) && (stackTrace === null || stackTrace === void 0 ? void 0 : stackTrace.name) ? stackTrace.message : !isErrorInstance ? "".concat(nonErrorPrefix, " ").concat(jsonStringify(sanitize(originalError))) : "Empty message";
1548
+ }
1549
+ function hasUsableStack(isErrorInstance, stackTrace) {
1550
+ if (stackTrace === void 0) {
1551
+ return false;
1552
+ }
1553
+ if (isErrorInstance) {
1554
+ return true;
1555
+ }
1556
+ return stackTrace.stack.length > 0 && (stackTrace.stack.length > 1 || stackTrace.stack[0].url !== void 0);
1557
+ }
1558
+ function tryToGetFingerprint(originalError) {
1559
+ return originalError instanceof Error && "dd_fingerprint" in originalError ? String(originalError.dd_fingerprint) : void 0;
1560
+ }
1561
+ function getFileFromStackTraceString(stack) {
1562
+ var _a2;
1563
+ return (_a2 = /@ (.+)/.exec(stack)) === null || _a2 === void 0 ? void 0 : _a2[1];
1564
+ }
1565
+ function flattenErrorCauses(error, parentSource) {
1566
+ var currentError = error;
1567
+ var causes = [];
1568
+ while ((currentError === null || currentError === void 0 ? void 0 : currentError.cause) instanceof Error && causes.length < 10) {
1569
+ var stackTrace = computeStackTrace(currentError.cause);
1570
+ causes.push({
1571
+ message: currentError.cause.message,
1572
+ source: parentSource,
1573
+ type: stackTrace === null || stackTrace === void 0 ? void 0 : stackTrace.name,
1574
+ stack: stackTrace && toStackTraceString(stackTrace)
1575
+ });
1576
+ currentError = currentError.cause;
1577
+ }
1578
+ return causes.length ? causes : void 0;
1579
+ }
1580
+ var ErrorSource = {
1581
+ AGENT: "agent",
1582
+ CONSOLE: "console",
1583
+ CUSTOM: "custom",
1584
+ LOGGER: "logger",
1585
+ NETWORK: "network",
1586
+ SOURCE: "source",
1587
+ REPORT: "report"
1588
+ };
1589
+ function trackRuntimeError(errorObservable) {
1590
+ var handleRuntimeError = function(stackTrace, originalError) {
1591
+ var rawError = computeRawError({
1592
+ stackTrace,
1593
+ originalError,
1594
+ startClocks: clocksNow(),
1595
+ nonErrorPrefix: "Uncaught",
1596
+ source: ErrorSource.SOURCE,
1597
+ handling: "unhandled"
1598
+ });
1599
+ errorObservable.notify(rawError);
1600
+ };
1601
+ var stopInstrumentingOnError = instrumentOnError(handleRuntimeError).stop;
1602
+ var stopInstrumentingOnUnhandledRejection = instrumentUnhandledRejection(handleRuntimeError).stop;
1603
+ return {
1604
+ stop: function() {
1605
+ stopInstrumentingOnError();
1606
+ stopInstrumentingOnUnhandledRejection();
1607
+ }
1608
+ };
1609
+ }
1610
+ function instrumentOnError(callback) {
1611
+ return instrumentMethod(window, "onerror", function(_a2) {
1612
+ var _b = _a2.parameters, messageObj = _b[0], url = _b[1], line = _b[2], column = _b[3], errorObj = _b[4];
1613
+ var stackTrace;
1614
+ if (errorObj instanceof Error) {
1615
+ stackTrace = computeStackTrace(errorObj);
1616
+ } else {
1617
+ stackTrace = computeStackTraceFromOnErrorMessage(messageObj, url, line, column);
1618
+ }
1619
+ callback(stackTrace, errorObj !== null && errorObj !== void 0 ? errorObj : messageObj);
1620
+ });
1621
+ }
1622
+ function instrumentUnhandledRejection(callback) {
1623
+ return instrumentMethod(window, "onunhandledrejection", function(_a2) {
1624
+ var e = _a2.parameters[0];
1625
+ var reason = e.reason || "Empty reason";
1626
+ var stack = computeStackTrace(reason);
1627
+ callback(stack, reason);
1628
+ });
1629
+ }
1630
+ function makePublicApi(stub) {
1631
+ var publicApi = assign({
1632
+ version: "5.23.3",
1633
+ // This API method is intentionally not monitored, since the only thing executed is the
1634
+ // user-provided 'callback'. All SDK usages executed in the callback should be monitored, and
1635
+ // we don't want to interfere with the user uncaught exceptions.
1636
+ onReady: function(callback) {
1637
+ callback();
1638
+ }
1639
+ }, stub);
1640
+ Object.defineProperty(publicApi, "_setDebug", {
1641
+ get: function() {
1642
+ return setDebugMode;
1643
+ },
1644
+ enumerable: false
1645
+ });
1646
+ return publicApi;
1647
+ }
1648
+ function defineGlobal(global, name, api) {
1649
+ var existingGlobalVariable = global[name];
1650
+ if (existingGlobalVariable && !existingGlobalVariable.q && existingGlobalVariable.version) {
1651
+ display.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior.");
1652
+ }
1653
+ global[name] = api;
1654
+ if (existingGlobalVariable && existingGlobalVariable.q) {
1655
+ existingGlobalVariable.q.forEach(function(fn) {
1656
+ return catchUserErrors(fn, "onReady callback threw an error:")();
1657
+ });
1658
+ }
1659
+ }
1660
+ function displayAlreadyInitializedError(sdkName, initConfiguration) {
1661
+ if (!initConfiguration.silentMultipleInit) {
1662
+ display.error("".concat(sdkName, " is already initialized."));
1663
+ }
1664
+ }
1665
+ function addEventListener(configuration, eventTarget, eventName, listener, options) {
1666
+ return addEventListeners(configuration, eventTarget, [eventName], listener, options);
1667
+ }
1668
+ function addEventListeners(configuration, eventTarget, eventNames, listener, _a2) {
1669
+ var _b = _a2 === void 0 ? {} : _a2, once = _b.once, capture = _b.capture, passive = _b.passive;
1670
+ var listenerWithMonitor = monitor(function(event) {
1671
+ if (!event.isTrusted && !event.__ddIsTrusted && !configuration.allowUntrustedEvents) {
1672
+ return;
1673
+ }
1674
+ if (once) {
1675
+ stop();
1676
+ }
1677
+ listener(event);
1678
+ });
1679
+ var options = passive ? { capture, passive } : capture;
1680
+ var add = getZoneJsOriginalValue(eventTarget, "addEventListener");
1681
+ eventNames.forEach(function(eventName) {
1682
+ return add.call(eventTarget, eventName, listenerWithMonitor, options);
1683
+ });
1684
+ function stop() {
1685
+ var remove = getZoneJsOriginalValue(eventTarget, "removeEventListener");
1686
+ eventNames.forEach(function(eventName) {
1687
+ return remove.call(eventTarget, eventName, listenerWithMonitor, options);
1688
+ });
1689
+ }
1690
+ return {
1691
+ stop
1692
+ };
1693
+ }
1694
+ var RawReportType = {
1695
+ intervention: "intervention",
1696
+ deprecation: "deprecation",
1697
+ cspViolation: "csp_violation"
1698
+ };
1699
+ function initReportObservable(configuration, apis) {
1700
+ var observables = [];
1701
+ if (includes(apis, RawReportType.cspViolation)) {
1702
+ observables.push(createCspViolationReportObservable(configuration));
1703
+ }
1704
+ var reportTypes = apis.filter(function(api) {
1705
+ return api !== RawReportType.cspViolation;
1706
+ });
1707
+ if (reportTypes.length) {
1708
+ observables.push(createReportObservable(reportTypes));
1709
+ }
1710
+ return mergeObservables.apply(void 0, observables);
1711
+ }
1712
+ function createReportObservable(reportTypes) {
1713
+ return new Observable(function(observable) {
1714
+ if (!window.ReportingObserver) {
1715
+ return;
1716
+ }
1717
+ var handleReports = monitor(function(reports, _) {
1718
+ return reports.forEach(function(report) {
1719
+ observable.notify(buildRawReportFromReport(report));
1720
+ });
1721
+ });
1722
+ var observer = new window.ReportingObserver(handleReports, {
1723
+ types: reportTypes,
1724
+ buffered: true
1725
+ });
1726
+ observer.observe();
1727
+ return function() {
1728
+ observer.disconnect();
1729
+ };
1730
+ });
1731
+ }
1732
+ function createCspViolationReportObservable(configuration) {
1733
+ return new Observable(function(observable) {
1734
+ var stop = addEventListener(configuration, document, "securitypolicyviolation", function(event) {
1735
+ observable.notify(buildRawReportFromCspViolation(event));
1736
+ }).stop;
1737
+ return stop;
1738
+ });
1739
+ }
1740
+ function buildRawReportFromReport(report) {
1741
+ var type = report.type, body = report.body;
1742
+ return {
1743
+ type,
1744
+ subtype: body.id,
1745
+ message: "".concat(type, ": ").concat(body.message),
1746
+ originalReport: report,
1747
+ stack: buildStack(body.id, body.message, body.sourceFile, body.lineNumber, body.columnNumber)
1748
+ };
1749
+ }
1750
+ function buildRawReportFromCspViolation(event) {
1751
+ var type = RawReportType.cspViolation;
1752
+ var message = "'".concat(event.blockedURI, "' blocked by '").concat(event.effectiveDirective, "' directive");
1753
+ return {
1754
+ type: RawReportType.cspViolation,
1755
+ subtype: event.effectiveDirective,
1756
+ message: "".concat(type, ": ").concat(message),
1757
+ stack: buildStack(event.effectiveDirective, event.originalPolicy ? "".concat(message, ' of the policy "').concat(safeTruncate(event.originalPolicy, 100, "..."), '"') : "no policy", event.sourceFile, event.lineNumber, event.columnNumber),
1758
+ originalReport: event
1759
+ };
1760
+ }
1761
+ function buildStack(name, message, sourceFile, lineNumber, columnNumber) {
1762
+ return sourceFile ? toStackTraceString({
1763
+ name,
1764
+ message,
1765
+ stack: [
1766
+ {
1767
+ func: "?",
1768
+ url: sourceFile,
1769
+ line: lineNumber !== null && lineNumber !== void 0 ? lineNumber : void 0,
1770
+ column: columnNumber !== null && columnNumber !== void 0 ? columnNumber : void 0
1771
+ }
1772
+ ]
1773
+ }) : void 0;
1774
+ }
1775
+ function sendToExtension(type, payload) {
1776
+ var callback = window.__ddBrowserSdkExtensionCallback;
1777
+ if (callback) {
1778
+ callback({ type, payload });
1779
+ }
1780
+ }
1781
+ function getType(value) {
1782
+ if (value === null) {
1783
+ return "null";
1784
+ }
1785
+ if (Array.isArray(value)) {
1786
+ return "array";
1787
+ }
1788
+ return typeof value;
1789
+ }
1790
+ function mergeInto(destination, source, circularReferenceChecker) {
1791
+ if (circularReferenceChecker === void 0) {
1792
+ circularReferenceChecker = createCircularReferenceChecker();
1793
+ }
1794
+ if (source === void 0) {
1795
+ return destination;
1796
+ }
1797
+ if (typeof source !== "object" || source === null) {
1798
+ return source;
1799
+ } else if (source instanceof Date) {
1800
+ return new Date(source.getTime());
1801
+ } else if (source instanceof RegExp) {
1802
+ var flags = source.flags || // old browsers compatibility
1803
+ [
1804
+ source.global ? "g" : "",
1805
+ source.ignoreCase ? "i" : "",
1806
+ source.multiline ? "m" : "",
1807
+ source.sticky ? "y" : "",
1808
+ source.unicode ? "u" : ""
1809
+ ].join("");
1810
+ return new RegExp(source.source, flags);
1811
+ }
1812
+ if (circularReferenceChecker.hasAlreadyBeenSeen(source)) {
1813
+ return void 0;
1814
+ } else if (Array.isArray(source)) {
1815
+ var merged_1 = Array.isArray(destination) ? destination : [];
1816
+ for (var i = 0; i < source.length; ++i) {
1817
+ merged_1[i] = mergeInto(merged_1[i], source[i], circularReferenceChecker);
1818
+ }
1819
+ return merged_1;
1820
+ }
1821
+ var merged = getType(destination) === "object" ? destination : {};
1822
+ for (var key in source) {
1823
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
1824
+ merged[key] = mergeInto(merged[key], source[key], circularReferenceChecker);
1825
+ }
1826
+ }
1827
+ return merged;
1828
+ }
1829
+ function deepClone(value) {
1830
+ return mergeInto(void 0, value);
1831
+ }
1832
+ function combine() {
1833
+ var sources = [];
1834
+ for (var _i = 0; _i < arguments.length; _i++) {
1835
+ sources[_i] = arguments[_i];
1836
+ }
1837
+ var destination;
1838
+ for (var _a2 = 0, sources_1 = sources; _a2 < sources_1.length; _a2++) {
1839
+ var source = sources_1[_a2];
1840
+ if (source === void 0 || source === null) {
1841
+ continue;
1842
+ }
1843
+ destination = mergeInto(destination, source);
1844
+ }
1845
+ return destination;
1846
+ }
1847
+ function createCircularReferenceChecker() {
1848
+ if (typeof WeakSet !== "undefined") {
1849
+ var set_1 = /* @__PURE__ */ new WeakSet();
1850
+ return {
1851
+ hasAlreadyBeenSeen: function(value) {
1852
+ var has = set_1.has(value);
1853
+ if (!has) {
1854
+ set_1.add(value);
1855
+ }
1856
+ return has;
1857
+ }
1858
+ };
1859
+ }
1860
+ var array = [];
1861
+ return {
1862
+ hasAlreadyBeenSeen: function(value) {
1863
+ var has = array.indexOf(value) >= 0;
1864
+ if (!has) {
1865
+ array.push(value);
1866
+ }
1867
+ return has;
1868
+ }
1869
+ };
1870
+ }
1871
+ function getConnectivity() {
1872
+ var _a2;
1873
+ var navigator2 = window.navigator;
1874
+ return {
1875
+ status: navigator2.onLine ? "connected" : "not_connected",
1876
+ interfaces: navigator2.connection && navigator2.connection.type ? [navigator2.connection.type] : void 0,
1877
+ effective_type: (_a2 = navigator2.connection) === null || _a2 === void 0 ? void 0 : _a2.effectiveType
1878
+ };
1879
+ }
1880
+ function removeDuplicates(array) {
1881
+ var set = /* @__PURE__ */ new Set();
1882
+ array.forEach(function(item) {
1883
+ return set.add(item);
1884
+ });
1885
+ return arrayFrom(set);
1886
+ }
1887
+ function removeItem(array, item) {
1888
+ var index = array.indexOf(item);
1889
+ if (index >= 0) {
1890
+ array.splice(index, 1);
1891
+ }
1892
+ }
1893
+ var BUFFER_LIMIT = 500;
1894
+ function createBoundedBuffer() {
1895
+ var buffer = [];
1896
+ var add = function(callback) {
1897
+ var length = buffer.push(callback);
1898
+ if (length > BUFFER_LIMIT) {
1899
+ buffer.splice(0, 1);
1900
+ }
1901
+ };
1902
+ var remove = function(callback) {
1903
+ removeItem(buffer, callback);
1904
+ };
1905
+ var drain = function(arg) {
1906
+ buffer.forEach(function(callback) {
1907
+ return callback(arg);
1908
+ });
1909
+ buffer.length = 0;
1910
+ };
1911
+ return {
1912
+ add,
1913
+ remove,
1914
+ drain
1915
+ };
1916
+ }
1917
+ var TelemetryType = {
1918
+ log: "log",
1919
+ configuration: "configuration",
1920
+ usage: "usage"
1921
+ };
1922
+ var ALLOWED_FRAME_URLS = [
1923
+ "https://www.datadoghq-browser-agent.com",
1924
+ "https://www.datad0g-browser-agent.com",
1925
+ "https://d3uc069fcn7uxw.cloudfront.net",
1926
+ "https://d20xtzwzcl0ceb.cloudfront.net",
1927
+ "http://localhost",
1928
+ "<anonymous>"
1929
+ ];
1930
+ var TELEMETRY_EXCLUDED_SITES = [INTAKE_SITE_US1_FED];
1931
+ var preStartTelemetryBuffer = createBoundedBuffer();
1932
+ var onRawTelemetryEventCollected = function(event) {
1933
+ preStartTelemetryBuffer.add(function() {
1934
+ return onRawTelemetryEventCollected(event);
1935
+ });
1936
+ };
1937
+ function startTelemetry(telemetryService, configuration) {
1938
+ var _a2;
1939
+ var contextProvider;
1940
+ var observable = new Observable();
1941
+ var alreadySentEvents = /* @__PURE__ */ new Set();
1942
+ var telemetryEnabled = !includes(TELEMETRY_EXCLUDED_SITES, configuration.site) && performDraw(configuration.telemetrySampleRate);
1943
+ var telemetryEnabledPerType = (_a2 = {}, _a2[TelemetryType.log] = telemetryEnabled, _a2[TelemetryType.configuration] = telemetryEnabled && performDraw(configuration.telemetryConfigurationSampleRate), _a2[TelemetryType.usage] = telemetryEnabled && performDraw(configuration.telemetryUsageSampleRate), _a2);
1944
+ var runtimeEnvInfo = getRuntimeEnvInfo();
1945
+ onRawTelemetryEventCollected = function(rawEvent) {
1946
+ var stringifiedEvent = jsonStringify(rawEvent);
1947
+ if (telemetryEnabledPerType[rawEvent.type] && alreadySentEvents.size < configuration.maxTelemetryEventsPerPage && !alreadySentEvents.has(stringifiedEvent)) {
1948
+ var event_1 = toTelemetryEvent(telemetryService, rawEvent, runtimeEnvInfo);
1949
+ observable.notify(event_1);
1950
+ sendToExtension("telemetry", event_1);
1951
+ alreadySentEvents.add(stringifiedEvent);
1952
+ }
1953
+ };
1954
+ startMonitorErrorCollection(addTelemetryError);
1955
+ function toTelemetryEvent(telemetryService2, event, runtimeEnvInfo2) {
1956
+ return combine({
1957
+ type: "telemetry",
1958
+ date: timeStampNow(),
1959
+ service: telemetryService2,
1960
+ version: "5.23.3",
1961
+ source: "browser",
1962
+ _dd: {
1963
+ format_version: 2
1964
+ },
1965
+ telemetry: combine(event, {
1966
+ runtime_env: runtimeEnvInfo2,
1967
+ connectivity: getConnectivity()
1968
+ }),
1969
+ experimental_features: arrayFrom(getExperimentalFeatures())
1970
+ }, contextProvider !== void 0 ? contextProvider() : {});
1971
+ }
1972
+ return {
1973
+ setContextProvider: function(provider) {
1974
+ contextProvider = provider;
1975
+ },
1976
+ observable,
1977
+ enabled: telemetryEnabled
1978
+ };
1979
+ }
1980
+ function getRuntimeEnvInfo() {
1981
+ return {
1982
+ is_local_file: window.location.protocol === "file:",
1983
+ is_worker: "WorkerGlobalScope" in self
1984
+ };
1985
+ }
1986
+ function drainPreStartTelemetry() {
1987
+ preStartTelemetryBuffer.drain();
1988
+ }
1989
+ function isTelemetryReplicationAllowed(configuration) {
1990
+ return configuration.site === INTAKE_SITE_STAGING;
1991
+ }
1992
+ function addTelemetryDebug(message, context) {
1993
+ displayIfDebugEnabled(ConsoleApiName.debug, message, context);
1994
+ onRawTelemetryEventCollected(assign({
1995
+ type: TelemetryType.log,
1996
+ message,
1997
+ status: "debug"
1998
+ }, context));
1999
+ }
2000
+ function addTelemetryError(e, context) {
2001
+ onRawTelemetryEventCollected(assign({
2002
+ type: TelemetryType.log,
2003
+ status: "error"
2004
+ }, formatError(e), context));
2005
+ }
2006
+ function addTelemetryConfiguration(configuration) {
2007
+ onRawTelemetryEventCollected({
2008
+ type: TelemetryType.configuration,
2009
+ configuration
2010
+ });
2011
+ }
2012
+ function addTelemetryUsage(usage) {
2013
+ onRawTelemetryEventCollected({
2014
+ type: TelemetryType.usage,
2015
+ usage
2016
+ });
2017
+ }
2018
+ function formatError(e) {
2019
+ if (e instanceof Error) {
2020
+ var stackTrace = computeStackTrace(e);
2021
+ return {
2022
+ error: {
2023
+ kind: stackTrace.name,
2024
+ stack: toStackTraceString(scrubCustomerFrames(stackTrace))
2025
+ },
2026
+ message: stackTrace.message
2027
+ };
2028
+ }
2029
+ return {
2030
+ error: {
2031
+ stack: NO_ERROR_STACK_PRESENT_MESSAGE
2032
+ },
2033
+ message: "".concat("Uncaught", " ").concat(jsonStringify(e))
2034
+ };
2035
+ }
2036
+ function scrubCustomerFrames(stackTrace) {
2037
+ stackTrace.stack = stackTrace.stack.filter(function(frame) {
2038
+ return !frame.url || ALLOWED_FRAME_URLS.some(function(allowedFrameUrl) {
2039
+ return startsWith(frame.url, allowedFrameUrl);
2040
+ });
2041
+ });
2042
+ return stackTrace;
2043
+ }
2044
+ var END_OF_TIMES = Infinity;
2045
+ var CLEAR_OLD_VALUES_INTERVAL = ONE_MINUTE;
2046
+ function createValueHistory(_a2) {
2047
+ var expireDelay = _a2.expireDelay, maxEntries = _a2.maxEntries;
2048
+ var entries = [];
2049
+ var clearOldValuesInterval = setInterval(function() {
2050
+ return clearOldValues();
2051
+ }, CLEAR_OLD_VALUES_INTERVAL);
2052
+ function clearOldValues() {
2053
+ var oldTimeThreshold = relativeNow() - expireDelay;
2054
+ while (entries.length > 0 && entries[entries.length - 1].endTime < oldTimeThreshold) {
2055
+ entries.pop();
2056
+ }
2057
+ }
2058
+ function add(value, startTime) {
2059
+ var entry = {
2060
+ value,
2061
+ startTime,
2062
+ endTime: END_OF_TIMES,
2063
+ remove: function() {
2064
+ removeItem(entries, entry);
2065
+ },
2066
+ close: function(endTime) {
2067
+ entry.endTime = endTime;
2068
+ }
2069
+ };
2070
+ if (maxEntries && entries.length >= maxEntries) {
2071
+ entries.pop();
2072
+ }
2073
+ entries.unshift(entry);
2074
+ return entry;
2075
+ }
2076
+ function find2(startTime, options) {
2077
+ if (startTime === void 0) {
2078
+ startTime = END_OF_TIMES;
2079
+ }
2080
+ if (options === void 0) {
2081
+ options = { returnInactive: false };
2082
+ }
2083
+ for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
2084
+ var entry = entries_1[_i];
2085
+ if (entry.startTime <= startTime) {
2086
+ if (options.returnInactive || startTime <= entry.endTime) {
2087
+ return entry.value;
2088
+ }
2089
+ break;
2090
+ }
2091
+ }
2092
+ }
2093
+ function closeActive(endTime) {
2094
+ var latestEntry = entries[0];
2095
+ if (latestEntry && latestEntry.endTime === END_OF_TIMES) {
2096
+ latestEntry.close(endTime);
2097
+ }
2098
+ }
2099
+ function findAll(startTime, duration) {
2100
+ if (startTime === void 0) {
2101
+ startTime = END_OF_TIMES;
2102
+ }
2103
+ if (duration === void 0) {
2104
+ duration = 0;
2105
+ }
2106
+ var endTime = addDuration(startTime, duration);
2107
+ return entries.filter(function(entry) {
2108
+ return entry.startTime <= endTime && startTime <= entry.endTime;
2109
+ }).map(function(entry) {
2110
+ return entry.value;
2111
+ });
2112
+ }
2113
+ function reset() {
2114
+ entries = [];
2115
+ }
2116
+ function stop() {
2117
+ clearInterval(clearOldValuesInterval);
2118
+ }
2119
+ return { add, find: find2, closeActive, findAll, reset, stop };
2120
+ }
2121
+ var VISIBILITY_CHECK_DELAY = ONE_MINUTE;
2122
+ var SESSION_CONTEXT_TIMEOUT_DELAY = SESSION_TIME_OUT_DELAY;
2123
+ function startSessionManager(configuration, productKey, computeSessionState2, trackingConsentState) {
2124
+ var renewObservable = new Observable();
2125
+ var expireObservable = new Observable();
2126
+ var sessionStore = startSessionStore(configuration.sessionStoreStrategyType, productKey, computeSessionState2);
2127
+ var sessionContextHistory = createValueHistory({
2128
+ expireDelay: SESSION_CONTEXT_TIMEOUT_DELAY
2129
+ });
2130
+ sessionStore.renewObservable.subscribe(function() {
2131
+ sessionContextHistory.add(buildSessionContext(), relativeNow());
2132
+ renewObservable.notify();
2133
+ });
2134
+ sessionStore.expireObservable.subscribe(function() {
2135
+ expireObservable.notify();
2136
+ sessionContextHistory.closeActive(relativeNow());
2137
+ });
2138
+ sessionStore.expandOrRenewSession();
2139
+ sessionContextHistory.add(buildSessionContext(), clocksOrigin().relative);
2140
+ trackingConsentState.observable.subscribe(function() {
2141
+ if (trackingConsentState.isGranted()) {
2142
+ sessionStore.expandOrRenewSession();
2143
+ } else {
2144
+ sessionStore.expire();
2145
+ }
2146
+ });
2147
+ trackActivity(configuration, function() {
2148
+ if (trackingConsentState.isGranted()) {
2149
+ sessionStore.expandOrRenewSession();
2150
+ }
2151
+ });
2152
+ trackVisibility(configuration, function() {
2153
+ return sessionStore.expandSession();
2154
+ });
2155
+ trackResume(configuration, function() {
2156
+ return sessionStore.restartSession();
2157
+ });
2158
+ function buildSessionContext() {
2159
+ return {
2160
+ id: sessionStore.getSession().id,
2161
+ trackingType: sessionStore.getSession()[productKey],
2162
+ isReplayForced: !!sessionStore.getSession().forcedReplay
2163
+ };
2164
+ }
2165
+ return {
2166
+ findSession: function(startTime, options) {
2167
+ return sessionContextHistory.find(startTime, options);
2168
+ },
2169
+ renewObservable,
2170
+ expireObservable,
2171
+ sessionStateUpdateObservable: sessionStore.sessionStateUpdateObservable,
2172
+ expire: sessionStore.expire,
2173
+ updateSessionState: sessionStore.updateSessionState
2174
+ };
2175
+ }
2176
+ function trackActivity(configuration, expandOrRenewSession) {
2177
+ addEventListeners(configuration, window, [
2178
+ "click",
2179
+ "touchstart",
2180
+ "keydown",
2181
+ "scroll"
2182
+ /* DOM_EVENT.SCROLL */
2183
+ ], expandOrRenewSession, { capture: true, passive: true }).stop;
2184
+ }
2185
+ function trackVisibility(configuration, expandSession) {
2186
+ var expandSessionWhenVisible = function() {
2187
+ if (document.visibilityState === "visible") {
2188
+ expandSession();
2189
+ }
2190
+ };
2191
+ addEventListener(configuration, document, "visibilitychange", expandSessionWhenVisible).stop;
2192
+ setInterval(expandSessionWhenVisible, VISIBILITY_CHECK_DELAY);
2193
+ }
2194
+ function trackResume(configuration, cb) {
2195
+ addEventListener(configuration, window, "resume", cb, { capture: true }).stop;
2196
+ }
2197
+ function isServerError(status) {
2198
+ return status >= 500;
2199
+ }
2200
+ function tryToClone(response) {
2201
+ try {
2202
+ return response.clone();
2203
+ } catch (e) {
2204
+ return;
2205
+ }
2206
+ }
2207
+ var MAX_ONGOING_BYTES_COUNT = 80 * ONE_KIBI_BYTE;
2208
+ var MAX_ONGOING_REQUESTS = 32;
2209
+ var MAX_QUEUE_BYTES_COUNT = 3 * ONE_MEBI_BYTE;
2210
+ var MAX_BACKOFF_TIME = ONE_MINUTE;
2211
+ var INITIAL_BACKOFF_TIME = ONE_SECOND;
2212
+ function sendWithRetryStrategy(payload, state, sendStrategy, trackType, reportError) {
2213
+ if (state.transportStatus === 0 && state.queuedPayloads.size() === 0 && state.bandwidthMonitor.canHandle(payload)) {
2214
+ send(payload, state, sendStrategy, {
2215
+ onSuccess: function() {
2216
+ return retryQueuedPayloads(0, state, sendStrategy, trackType, reportError);
2217
+ },
2218
+ onFailure: function() {
2219
+ state.queuedPayloads.enqueue(payload);
2220
+ scheduleRetry(state, sendStrategy, trackType, reportError);
2221
+ }
2222
+ });
2223
+ } else {
2224
+ state.queuedPayloads.enqueue(payload);
2225
+ }
2226
+ }
2227
+ function scheduleRetry(state, sendStrategy, trackType, reportError) {
2228
+ if (state.transportStatus !== 2) {
2229
+ return;
2230
+ }
2231
+ setTimeout(function() {
2232
+ var payload = state.queuedPayloads.first();
2233
+ send(payload, state, sendStrategy, {
2234
+ onSuccess: function() {
2235
+ state.queuedPayloads.dequeue();
2236
+ state.currentBackoffTime = INITIAL_BACKOFF_TIME;
2237
+ retryQueuedPayloads(1, state, sendStrategy, trackType, reportError);
2238
+ },
2239
+ onFailure: function() {
2240
+ state.currentBackoffTime = Math.min(MAX_BACKOFF_TIME, state.currentBackoffTime * 2);
2241
+ scheduleRetry(state, sendStrategy, trackType, reportError);
2242
+ }
2243
+ });
2244
+ }, state.currentBackoffTime);
2245
+ }
2246
+ function send(payload, state, sendStrategy, _a2) {
2247
+ var onSuccess = _a2.onSuccess, onFailure = _a2.onFailure;
2248
+ state.bandwidthMonitor.add(payload);
2249
+ sendStrategy(payload, function(response) {
2250
+ state.bandwidthMonitor.remove(payload);
2251
+ if (!shouldRetryRequest(response)) {
2252
+ state.transportStatus = 0;
2253
+ onSuccess();
2254
+ } else {
2255
+ state.transportStatus = state.bandwidthMonitor.ongoingRequestCount > 0 ? 1 : 2;
2256
+ payload.retry = {
2257
+ count: payload.retry ? payload.retry.count + 1 : 1,
2258
+ lastFailureStatus: response.status
2259
+ };
2260
+ onFailure();
2261
+ }
2262
+ });
2263
+ }
2264
+ function retryQueuedPayloads(reason, state, sendStrategy, trackType, reportError) {
2265
+ if (reason === 0 && state.queuedPayloads.isFull() && !state.queueFullReported) {
2266
+ reportError({
2267
+ message: "Reached max ".concat(trackType, " events size queued for upload: ").concat(MAX_QUEUE_BYTES_COUNT / ONE_MEBI_BYTE, "MiB"),
2268
+ source: ErrorSource.AGENT,
2269
+ startClocks: clocksNow()
2270
+ });
2271
+ state.queueFullReported = true;
2272
+ }
2273
+ var previousQueue = state.queuedPayloads;
2274
+ state.queuedPayloads = newPayloadQueue();
2275
+ while (previousQueue.size() > 0) {
2276
+ sendWithRetryStrategy(previousQueue.dequeue(), state, sendStrategy, trackType, reportError);
2277
+ }
2278
+ }
2279
+ function shouldRetryRequest(response) {
2280
+ return response.type !== "opaque" && (response.status === 0 && !navigator.onLine || response.status === 408 || response.status === 429 || isServerError(response.status));
2281
+ }
2282
+ function newRetryState() {
2283
+ return {
2284
+ transportStatus: 0,
2285
+ currentBackoffTime: INITIAL_BACKOFF_TIME,
2286
+ bandwidthMonitor: newBandwidthMonitor(),
2287
+ queuedPayloads: newPayloadQueue(),
2288
+ queueFullReported: false
2289
+ };
2290
+ }
2291
+ function newPayloadQueue() {
2292
+ var queue = [];
2293
+ return {
2294
+ bytesCount: 0,
2295
+ enqueue: function(payload) {
2296
+ if (this.isFull()) {
2297
+ return;
2298
+ }
2299
+ queue.push(payload);
2300
+ this.bytesCount += payload.bytesCount;
2301
+ },
2302
+ first: function() {
2303
+ return queue[0];
2304
+ },
2305
+ dequeue: function() {
2306
+ var payload = queue.shift();
2307
+ if (payload) {
2308
+ this.bytesCount -= payload.bytesCount;
2309
+ }
2310
+ return payload;
2311
+ },
2312
+ size: function() {
2313
+ return queue.length;
2314
+ },
2315
+ isFull: function() {
2316
+ return this.bytesCount >= MAX_QUEUE_BYTES_COUNT;
2317
+ }
2318
+ };
2319
+ }
2320
+ function newBandwidthMonitor() {
2321
+ return {
2322
+ ongoingRequestCount: 0,
2323
+ ongoingByteCount: 0,
2324
+ canHandle: function(payload) {
2325
+ return this.ongoingRequestCount === 0 || this.ongoingByteCount + payload.bytesCount <= MAX_ONGOING_BYTES_COUNT && this.ongoingRequestCount < MAX_ONGOING_REQUESTS;
2326
+ },
2327
+ add: function(payload) {
2328
+ this.ongoingRequestCount += 1;
2329
+ this.ongoingByteCount += payload.bytesCount;
2330
+ },
2331
+ remove: function(payload) {
2332
+ this.ongoingRequestCount -= 1;
2333
+ this.ongoingByteCount -= payload.bytesCount;
2334
+ }
2335
+ };
2336
+ }
2337
+ function createHttpRequest(configuration, endpointBuilder, bytesLimit, reportError) {
2338
+ var retryState = newRetryState();
2339
+ var sendStrategyForRetry = function(payload, onResponse) {
2340
+ return fetchKeepAliveStrategy(configuration, endpointBuilder, bytesLimit, payload, onResponse);
2341
+ };
2342
+ return {
2343
+ send: function(payload) {
2344
+ sendWithRetryStrategy(payload, retryState, sendStrategyForRetry, endpointBuilder.trackType, reportError);
2345
+ },
2346
+ /**
2347
+ * Since fetch keepalive behaves like regular fetch on Firefox,
2348
+ * keep using sendBeaconStrategy on exit
2349
+ */
2350
+ sendOnExit: function(payload) {
2351
+ sendBeaconStrategy(configuration, endpointBuilder, bytesLimit, payload);
2352
+ }
2353
+ };
2354
+ }
2355
+ function sendBeaconStrategy(configuration, endpointBuilder, bytesLimit, payload) {
2356
+ var canUseBeacon = !!navigator.sendBeacon && payload.bytesCount < bytesLimit;
2357
+ if (canUseBeacon) {
2358
+ try {
2359
+ var beaconUrl = endpointBuilder.build("beacon", payload);
2360
+ var isQueued = navigator.sendBeacon(beaconUrl, payload.data);
2361
+ if (isQueued) {
2362
+ return;
2363
+ }
2364
+ } catch (e) {
2365
+ reportBeaconError(e);
2366
+ }
2367
+ }
2368
+ var xhrUrl = endpointBuilder.build("xhr", payload);
2369
+ sendXHR(configuration, xhrUrl, payload.data);
2370
+ }
2371
+ var hasReportedBeaconError = false;
2372
+ function reportBeaconError(e) {
2373
+ if (!hasReportedBeaconError) {
2374
+ hasReportedBeaconError = true;
2375
+ addTelemetryError(e);
2376
+ }
2377
+ }
2378
+ function fetchKeepAliveStrategy(configuration, endpointBuilder, bytesLimit, payload, onResponse) {
2379
+ var canUseKeepAlive = isKeepAliveSupported() && payload.bytesCount < bytesLimit;
2380
+ if (canUseKeepAlive) {
2381
+ var fetchUrl = endpointBuilder.build("fetch", payload);
2382
+ fetch(fetchUrl, { method: "POST", body: payload.data, keepalive: true, mode: "cors" }).then(monitor(function(response) {
2383
+ return onResponse === null || onResponse === void 0 ? void 0 : onResponse({ status: response.status, type: response.type });
2384
+ }), monitor(function() {
2385
+ var xhrUrl2 = endpointBuilder.build("xhr", payload);
2386
+ sendXHR(configuration, xhrUrl2, payload.data, onResponse);
2387
+ }));
2388
+ } else {
2389
+ var xhrUrl = endpointBuilder.build("xhr", payload);
2390
+ sendXHR(configuration, xhrUrl, payload.data, onResponse);
2391
+ }
2392
+ }
2393
+ function isKeepAliveSupported() {
2394
+ try {
2395
+ return window.Request && "keepalive" in new Request("http://a");
2396
+ } catch (_a2) {
2397
+ return false;
2398
+ }
2399
+ }
2400
+ function sendXHR(configuration, url, data, onResponse) {
2401
+ var request = new XMLHttpRequest();
2402
+ request.open("POST", url, true);
2403
+ if (data instanceof Blob) {
2404
+ request.setRequestHeader("Content-Type", data.type);
2405
+ }
2406
+ addEventListener(configuration, request, "loadend", function() {
2407
+ onResponse === null || onResponse === void 0 ? void 0 : onResponse({ status: request.status });
2408
+ }, {
2409
+ // prevent multiple onResponse callbacks
2410
+ // if the xhr instance is reused by a third party
2411
+ once: true
2412
+ });
2413
+ request.send(data);
2414
+ }
2415
+ function getEventBridge() {
2416
+ var eventBridgeGlobal = getEventBridgeGlobal();
2417
+ if (!eventBridgeGlobal) {
2418
+ return;
2419
+ }
2420
+ return {
2421
+ getCapabilities: function() {
2422
+ var _a2;
2423
+ return JSON.parse(((_a2 = eventBridgeGlobal.getCapabilities) === null || _a2 === void 0 ? void 0 : _a2.call(eventBridgeGlobal)) || "[]");
2424
+ },
2425
+ getPrivacyLevel: function() {
2426
+ var _a2;
2427
+ return (_a2 = eventBridgeGlobal.getPrivacyLevel) === null || _a2 === void 0 ? void 0 : _a2.call(eventBridgeGlobal);
2428
+ },
2429
+ getAllowedWebViewHosts: function() {
2430
+ return JSON.parse(eventBridgeGlobal.getAllowedWebViewHosts());
2431
+ },
2432
+ send: function(eventType, event, viewId) {
2433
+ var view = viewId ? { id: viewId } : void 0;
2434
+ eventBridgeGlobal.send(JSON.stringify({ eventType, event, view }));
2435
+ }
2436
+ };
2437
+ }
2438
+ function canUseEventBridge(currentHost) {
2439
+ var _a2;
2440
+ if (currentHost === void 0) {
2441
+ currentHost = (_a2 = getGlobalObject().location) === null || _a2 === void 0 ? void 0 : _a2.hostname;
2442
+ }
2443
+ var bridge = getEventBridge();
2444
+ return !!bridge && bridge.getAllowedWebViewHosts().some(function(allowedHost) {
2445
+ return currentHost === allowedHost || endsWith(currentHost, ".".concat(allowedHost));
2446
+ });
2447
+ }
2448
+ function getEventBridgeGlobal() {
2449
+ return getGlobalObject().DatadogEventBridge;
2450
+ }
2451
+ var PageExitReason = {
2452
+ HIDDEN: "visibility_hidden",
2453
+ UNLOADING: "before_unload",
2454
+ PAGEHIDE: "page_hide",
2455
+ FROZEN: "page_frozen"
2456
+ };
2457
+ function createPageExitObservable(configuration) {
2458
+ return new Observable(function(observable) {
2459
+ var stopListeners = addEventListeners(configuration, window, [
2460
+ "visibilitychange",
2461
+ "freeze"
2462
+ /* DOM_EVENT.FREEZE */
2463
+ ], function(event) {
2464
+ if (event.type === "visibilitychange" && document.visibilityState === "hidden") {
2465
+ observable.notify({ reason: PageExitReason.HIDDEN });
2466
+ } else if (event.type === "freeze") {
2467
+ observable.notify({ reason: PageExitReason.FROZEN });
2468
+ }
2469
+ }, { capture: true }).stop;
2470
+ var stopBeforeUnloadListener = addEventListener(configuration, window, "beforeunload", function() {
2471
+ observable.notify({ reason: PageExitReason.UNLOADING });
2472
+ }).stop;
2473
+ return function() {
2474
+ stopListeners();
2475
+ stopBeforeUnloadListener();
2476
+ };
2477
+ });
2478
+ }
2479
+ function isPageExitReason(reason) {
2480
+ return includes(objectValues(PageExitReason), reason);
2481
+ }
2482
+ function createBatch(_a2) {
2483
+ var encoder = _a2.encoder, request = _a2.request, flushController = _a2.flushController, messageBytesLimit = _a2.messageBytesLimit;
2484
+ var upsertBuffer = {};
2485
+ var flushSubscription = flushController.flushObservable.subscribe(function(event) {
2486
+ return flush(event);
2487
+ });
2488
+ function push(serializedMessage, estimatedMessageBytesCount, key) {
2489
+ flushController.notifyBeforeAddMessage(estimatedMessageBytesCount);
2490
+ if (key !== void 0) {
2491
+ upsertBuffer[key] = serializedMessage;
2492
+ flushController.notifyAfterAddMessage();
2493
+ } else {
2494
+ encoder.write(encoder.isEmpty ? serializedMessage : "\n".concat(serializedMessage), function(realMessageBytesCount) {
2495
+ flushController.notifyAfterAddMessage(realMessageBytesCount - estimatedMessageBytesCount);
2496
+ });
2497
+ }
2498
+ }
2499
+ function hasMessageFor(key) {
2500
+ return key !== void 0 && upsertBuffer[key] !== void 0;
2501
+ }
2502
+ function remove(key) {
2503
+ var removedMessage = upsertBuffer[key];
2504
+ delete upsertBuffer[key];
2505
+ var messageBytesCount = encoder.estimateEncodedBytesCount(removedMessage);
2506
+ flushController.notifyAfterRemoveMessage(messageBytesCount);
2507
+ }
2508
+ function addOrUpdate(message, key) {
2509
+ var serializedMessage = jsonStringify(message);
2510
+ var estimatedMessageBytesCount = encoder.estimateEncodedBytesCount(serializedMessage);
2511
+ if (estimatedMessageBytesCount >= messageBytesLimit) {
2512
+ display.warn("Discarded a message whose size was bigger than the maximum allowed size ".concat(messageBytesLimit, "KB. ").concat(MORE_DETAILS, " ").concat(DOCS_TROUBLESHOOTING, "/#technical-limitations"));
2513
+ return;
2514
+ }
2515
+ if (hasMessageFor(key)) {
2516
+ remove(key);
2517
+ }
2518
+ push(serializedMessage, estimatedMessageBytesCount, key);
2519
+ }
2520
+ function flush(event) {
2521
+ var upsertMessages = objectValues(upsertBuffer).join("\n");
2522
+ upsertBuffer = {};
2523
+ var isPageExit = isPageExitReason(event.reason);
2524
+ var send2 = isPageExit ? request.sendOnExit : request.send;
2525
+ if (isPageExit && // Note: checking that the encoder is async is not strictly needed, but it's an optimization:
2526
+ // if the encoder is async we need to send two requests in some cases (one for encoded data
2527
+ // and the other for non-encoded data). But if it's not async, we don't have to worry about
2528
+ // it and always send a single request.
2529
+ encoder.isAsync) {
2530
+ var encoderResult = encoder.finishSync();
2531
+ if (encoderResult.outputBytesCount) {
2532
+ send2(formatPayloadFromEncoder(encoderResult));
2533
+ }
2534
+ var pendingMessages = [encoderResult.pendingData, upsertMessages].filter(Boolean).join("\n");
2535
+ if (pendingMessages) {
2536
+ send2({
2537
+ data: pendingMessages,
2538
+ bytesCount: computeBytesCount(pendingMessages)
2539
+ });
2540
+ }
2541
+ } else {
2542
+ if (upsertMessages) {
2543
+ encoder.write(encoder.isEmpty ? upsertMessages : "\n".concat(upsertMessages));
2544
+ }
2545
+ encoder.finish(function(encoderResult2) {
2546
+ send2(formatPayloadFromEncoder(encoderResult2));
2547
+ });
2548
+ }
2549
+ }
2550
+ return {
2551
+ flushController,
2552
+ add: addOrUpdate,
2553
+ upsert: addOrUpdate,
2554
+ stop: flushSubscription.unsubscribe
2555
+ };
2556
+ }
2557
+ function formatPayloadFromEncoder(encoderResult) {
2558
+ var data;
2559
+ if (typeof encoderResult.output === "string") {
2560
+ data = encoderResult.output;
2561
+ } else {
2562
+ data = new Blob([encoderResult.output], {
2563
+ // This will set the 'Content-Type: text/plain' header. Reasoning:
2564
+ // * The intake rejects the request if there is no content type.
2565
+ // * The browser will issue CORS preflight requests if we set it to 'application/json', which
2566
+ // could induce higher intake load (and maybe has other impacts).
2567
+ // * Also it's not quite JSON, since we are concatenating multiple JSON objects separated by
2568
+ // new lines.
2569
+ type: "text/plain"
2570
+ });
2571
+ }
2572
+ return {
2573
+ data,
2574
+ bytesCount: encoderResult.outputBytesCount,
2575
+ encoding: encoderResult.encoding
2576
+ };
2577
+ }
2578
+ function createFlushController(_a2) {
2579
+ var messagesLimit = _a2.messagesLimit, bytesLimit = _a2.bytesLimit, durationLimit = _a2.durationLimit, pageExitObservable = _a2.pageExitObservable, sessionExpireObservable = _a2.sessionExpireObservable;
2580
+ var pageExitSubscription = pageExitObservable.subscribe(function(event) {
2581
+ return flush(event.reason);
2582
+ });
2583
+ var sessionExpireSubscription = sessionExpireObservable.subscribe(function() {
2584
+ return flush("session_expire");
2585
+ });
2586
+ var flushObservable = new Observable(function() {
2587
+ return function() {
2588
+ pageExitSubscription.unsubscribe();
2589
+ sessionExpireSubscription.unsubscribe();
2590
+ };
2591
+ });
2592
+ var currentBytesCount = 0;
2593
+ var currentMessagesCount = 0;
2594
+ function flush(flushReason) {
2595
+ if (currentMessagesCount === 0) {
2596
+ return;
2597
+ }
2598
+ var messagesCount = currentMessagesCount;
2599
+ var bytesCount = currentBytesCount;
2600
+ currentMessagesCount = 0;
2601
+ currentBytesCount = 0;
2602
+ cancelDurationLimitTimeout();
2603
+ flushObservable.notify({
2604
+ reason: flushReason,
2605
+ messagesCount,
2606
+ bytesCount
2607
+ });
2608
+ }
2609
+ var durationLimitTimeoutId;
2610
+ function scheduleDurationLimitTimeout() {
2611
+ if (durationLimitTimeoutId === void 0) {
2612
+ durationLimitTimeoutId = setTimeout(function() {
2613
+ flush("duration_limit");
2614
+ }, durationLimit);
2615
+ }
2616
+ }
2617
+ function cancelDurationLimitTimeout() {
2618
+ clearTimeout(durationLimitTimeoutId);
2619
+ durationLimitTimeoutId = void 0;
2620
+ }
2621
+ return {
2622
+ flushObservable,
2623
+ get messagesCount() {
2624
+ return currentMessagesCount;
2625
+ },
2626
+ /**
2627
+ * Notifies that a message will be added to a pool of pending messages waiting to be flushed.
2628
+ *
2629
+ * This function needs to be called synchronously, right before adding the message, so no flush
2630
+ * event can happen after `notifyBeforeAddMessage` and before adding the message.
2631
+ *
2632
+ * @param estimatedMessageBytesCount: an estimation of the message bytes count once it is
2633
+ * actually added.
2634
+ */
2635
+ notifyBeforeAddMessage: function(estimatedMessageBytesCount) {
2636
+ if (currentBytesCount + estimatedMessageBytesCount >= bytesLimit) {
2637
+ flush("bytes_limit");
2638
+ }
2639
+ currentMessagesCount += 1;
2640
+ currentBytesCount += estimatedMessageBytesCount;
2641
+ scheduleDurationLimitTimeout();
2642
+ },
2643
+ /**
2644
+ * Notifies that a message *was* added to a pool of pending messages waiting to be flushed.
2645
+ *
2646
+ * This function can be called asynchronously after the message was added, but in this case it
2647
+ * should not be called if a flush event occurred in between.
2648
+ *
2649
+ * @param messageBytesCountDiff: the difference between the estimated message bytes count and
2650
+ * its actual bytes count once added to the pool.
2651
+ */
2652
+ notifyAfterAddMessage: function(messageBytesCountDiff) {
2653
+ if (messageBytesCountDiff === void 0) {
2654
+ messageBytesCountDiff = 0;
2655
+ }
2656
+ currentBytesCount += messageBytesCountDiff;
2657
+ if (currentMessagesCount >= messagesLimit) {
2658
+ flush("messages_limit");
2659
+ } else if (currentBytesCount >= bytesLimit) {
2660
+ flush("bytes_limit");
2661
+ }
2662
+ },
2663
+ /**
2664
+ * Notifies that a message was removed from a pool of pending messages waiting to be flushed.
2665
+ *
2666
+ * This function needs to be called synchronously, right after removing the message, so no flush
2667
+ * event can happen after removing the message and before `notifyAfterRemoveMessage`.
2668
+ *
2669
+ * @param messageBytesCount: the message bytes count that was added to the pool. Should
2670
+ * correspond to the sum of bytes counts passed to `notifyBeforeAddMessage` and
2671
+ * `notifyAfterAddMessage`.
2672
+ */
2673
+ notifyAfterRemoveMessage: function(messageBytesCount) {
2674
+ currentBytesCount -= messageBytesCount;
2675
+ currentMessagesCount -= 1;
2676
+ if (currentMessagesCount === 0) {
2677
+ cancelDurationLimitTimeout();
2678
+ }
2679
+ }
2680
+ };
2681
+ }
2682
+ function startBatchWithReplica(configuration, primary, replica, reportError, pageExitObservable, sessionExpireObservable, batchFactoryImp) {
2683
+ if (batchFactoryImp === void 0) {
2684
+ batchFactoryImp = createBatch;
2685
+ }
2686
+ var primaryBatch = createBatchFromConfig(configuration, primary);
2687
+ var replicaBatch = replica && createBatchFromConfig(configuration, replica);
2688
+ function createBatchFromConfig(configuration2, _a2) {
2689
+ var endpoint = _a2.endpoint, encoder = _a2.encoder;
2690
+ return batchFactoryImp({
2691
+ encoder,
2692
+ request: createHttpRequest(configuration2, endpoint, configuration2.batchBytesLimit, reportError),
2693
+ flushController: createFlushController({
2694
+ messagesLimit: configuration2.batchMessagesLimit,
2695
+ bytesLimit: configuration2.batchBytesLimit,
2696
+ durationLimit: configuration2.flushTimeout,
2697
+ pageExitObservable,
2698
+ sessionExpireObservable
2699
+ }),
2700
+ messageBytesLimit: configuration2.messageBytesLimit
2701
+ });
2702
+ }
2703
+ return {
2704
+ flushObservable: primaryBatch.flushController.flushObservable,
2705
+ add: function(message, replicated) {
2706
+ if (replicated === void 0) {
2707
+ replicated = true;
2708
+ }
2709
+ primaryBatch.add(message);
2710
+ if (replicaBatch && replicated) {
2711
+ replicaBatch.add(replica.transformMessage ? replica.transformMessage(message) : message);
2712
+ }
2713
+ },
2714
+ upsert: function(message, key) {
2715
+ primaryBatch.upsert(message, key);
2716
+ if (replicaBatch) {
2717
+ replicaBatch.upsert(replica.transformMessage ? replica.transformMessage(message) : message, key);
2718
+ }
2719
+ },
2720
+ stop: function() {
2721
+ primaryBatch.stop();
2722
+ if (replicaBatch) {
2723
+ replicaBatch.stop();
2724
+ }
2725
+ }
2726
+ };
2727
+ }
2728
+ function createIdentityEncoder() {
2729
+ var output = "";
2730
+ var outputBytesCount = 0;
2731
+ return {
2732
+ isAsync: false,
2733
+ get isEmpty() {
2734
+ return !output;
2735
+ },
2736
+ write: function(data, callback) {
2737
+ var additionalEncodedBytesCount = computeBytesCount(data);
2738
+ outputBytesCount += additionalEncodedBytesCount;
2739
+ output += data;
2740
+ if (callback) {
2741
+ callback(additionalEncodedBytesCount);
2742
+ }
2743
+ },
2744
+ finish: function(callback) {
2745
+ callback(this.finishSync());
2746
+ },
2747
+ finishSync: function() {
2748
+ var result = {
2749
+ output,
2750
+ outputBytesCount,
2751
+ rawBytesCount: outputBytesCount,
2752
+ pendingData: ""
2753
+ };
2754
+ output = "";
2755
+ outputBytesCount = 0;
2756
+ return result;
2757
+ },
2758
+ estimateEncodedBytesCount: function(data) {
2759
+ return data.length;
2760
+ }
2761
+ };
2762
+ }
2763
+ var AbstractLifeCycle = (
2764
+ /** @class */
2765
+ function() {
2766
+ function AbstractLifeCycle2() {
2767
+ this.callbacks = {};
2768
+ }
2769
+ AbstractLifeCycle2.prototype.notify = function(eventType, data) {
2770
+ var eventCallbacks = this.callbacks[eventType];
2771
+ if (eventCallbacks) {
2772
+ eventCallbacks.forEach(function(callback) {
2773
+ return callback(data);
2774
+ });
2775
+ }
2776
+ };
2777
+ AbstractLifeCycle2.prototype.subscribe = function(eventType, callback) {
2778
+ var _this = this;
2779
+ if (!this.callbacks[eventType]) {
2780
+ this.callbacks[eventType] = [];
2781
+ }
2782
+ this.callbacks[eventType].push(callback);
2783
+ return {
2784
+ unsubscribe: function() {
2785
+ _this.callbacks[eventType] = _this.callbacks[eventType].filter(function(other) {
2786
+ return callback !== other;
2787
+ });
2788
+ }
2789
+ };
2790
+ };
2791
+ return AbstractLifeCycle2;
2792
+ }()
2793
+ );
2794
+ function createEventRateLimiter(eventType, limit, onLimitReached) {
2795
+ var eventCount = 0;
2796
+ var allowNextEvent = false;
2797
+ return {
2798
+ isLimitReached: function() {
2799
+ if (eventCount === 0) {
2800
+ setTimeout(function() {
2801
+ eventCount = 0;
2802
+ }, ONE_MINUTE);
2803
+ }
2804
+ eventCount += 1;
2805
+ if (eventCount <= limit || allowNextEvent) {
2806
+ allowNextEvent = false;
2807
+ return false;
2808
+ }
2809
+ if (eventCount === limit + 1) {
2810
+ allowNextEvent = true;
2811
+ try {
2812
+ onLimitReached({
2813
+ message: "Reached max number of ".concat(eventType, "s by minute: ").concat(limit),
2814
+ source: ErrorSource.AGENT,
2815
+ startClocks: clocksNow()
2816
+ });
2817
+ } finally {
2818
+ allowNextEvent = false;
2819
+ }
2820
+ }
2821
+ return true;
2822
+ }
2823
+ };
2824
+ }
2825
+ var xhrObservable;
2826
+ var xhrContexts = /* @__PURE__ */ new WeakMap();
2827
+ function initXhrObservable(configuration) {
2828
+ if (!xhrObservable) {
2829
+ xhrObservable = createXhrObservable(configuration);
2830
+ }
2831
+ return xhrObservable;
2832
+ }
2833
+ function createXhrObservable(configuration) {
2834
+ return new Observable(function(observable) {
2835
+ var stopInstrumentingStart = instrumentMethod(XMLHttpRequest.prototype, "open", openXhr).stop;
2836
+ var stopInstrumentingSend = instrumentMethod(XMLHttpRequest.prototype, "send", function(call) {
2837
+ sendXhr(call, configuration, observable);
2838
+ }, { computeHandlingStack: true }).stop;
2839
+ var stopInstrumentingAbort = instrumentMethod(XMLHttpRequest.prototype, "abort", abortXhr).stop;
2840
+ return function() {
2841
+ stopInstrumentingStart();
2842
+ stopInstrumentingSend();
2843
+ stopInstrumentingAbort();
2844
+ };
2845
+ });
2846
+ }
2847
+ function openXhr(_a2) {
2848
+ var xhr = _a2.target, _b = _a2.parameters, method = _b[0], url = _b[1];
2849
+ xhrContexts.set(xhr, {
2850
+ state: "open",
2851
+ method: String(method).toUpperCase(),
2852
+ url: normalizeUrl(String(url))
2853
+ });
2854
+ }
2855
+ function sendXhr(_a2, configuration, observable) {
2856
+ var xhr = _a2.target, handlingStack = _a2.handlingStack;
2857
+ var context = xhrContexts.get(xhr);
2858
+ if (!context) {
2859
+ return;
2860
+ }
2861
+ var startContext = context;
2862
+ startContext.state = "start";
2863
+ startContext.startClocks = clocksNow();
2864
+ startContext.isAborted = false;
2865
+ startContext.xhr = xhr;
2866
+ startContext.handlingStack = handlingStack;
2867
+ var hasBeenReported = false;
2868
+ var stopInstrumentingOnReadyStateChange = instrumentMethod(xhr, "onreadystatechange", function() {
2869
+ if (xhr.readyState === XMLHttpRequest.DONE) {
2870
+ onEnd();
2871
+ }
2872
+ }).stop;
2873
+ var onEnd = function() {
2874
+ unsubscribeLoadEndListener();
2875
+ stopInstrumentingOnReadyStateChange();
2876
+ if (hasBeenReported) {
2877
+ return;
2878
+ }
2879
+ hasBeenReported = true;
2880
+ var completeContext = context;
2881
+ completeContext.state = "complete";
2882
+ completeContext.duration = elapsed(startContext.startClocks.timeStamp, timeStampNow());
2883
+ completeContext.status = xhr.status;
2884
+ observable.notify(shallowClone(completeContext));
2885
+ };
2886
+ var unsubscribeLoadEndListener = addEventListener(configuration, xhr, "loadend", onEnd).stop;
2887
+ observable.notify(startContext);
2888
+ }
2889
+ function abortXhr(_a2) {
2890
+ var xhr = _a2.target;
2891
+ var context = xhrContexts.get(xhr);
2892
+ if (context) {
2893
+ context.isAborted = true;
2894
+ }
2895
+ }
2896
+ var fetchObservable;
2897
+ function initFetchObservable() {
2898
+ if (!fetchObservable) {
2899
+ fetchObservable = createFetchObservable();
2900
+ }
2901
+ return fetchObservable;
2902
+ }
2903
+ function createFetchObservable() {
2904
+ return new Observable(function(observable) {
2905
+ if (!window.fetch) {
2906
+ return;
2907
+ }
2908
+ var stop = instrumentMethod(window, "fetch", function(call) {
2909
+ return beforeSend(call, observable);
2910
+ }, {
2911
+ computeHandlingStack: true
2912
+ }).stop;
2913
+ return stop;
2914
+ });
2915
+ }
2916
+ function beforeSend(_a2, observable) {
2917
+ var parameters = _a2.parameters, onPostCall = _a2.onPostCall, handlingStack = _a2.handlingStack;
2918
+ var input = parameters[0], init = parameters[1];
2919
+ var methodFromParams = init && init.method;
2920
+ if (methodFromParams === void 0 && input instanceof Request) {
2921
+ methodFromParams = input.method;
2922
+ }
2923
+ var method = methodFromParams !== void 0 ? String(methodFromParams).toUpperCase() : "GET";
2924
+ var url = input instanceof Request ? input.url : normalizeUrl(String(input));
2925
+ var startClocks = clocksNow();
2926
+ var context = {
2927
+ state: "start",
2928
+ init,
2929
+ input,
2930
+ method,
2931
+ startClocks,
2932
+ url,
2933
+ handlingStack
2934
+ };
2935
+ observable.notify(context);
2936
+ parameters[0] = context.input;
2937
+ parameters[1] = context.init;
2938
+ onPostCall(function(responsePromise) {
2939
+ return afterSend(observable, responsePromise, context);
2940
+ });
2941
+ }
2942
+ function afterSend(observable, responsePromise, startContext) {
2943
+ var context = startContext;
2944
+ function reportFetch(partialContext) {
2945
+ context.state = "resolve";
2946
+ assign(context, partialContext);
2947
+ observable.notify(context);
2948
+ }
2949
+ responsePromise.then(monitor(function(response) {
2950
+ reportFetch({
2951
+ response,
2952
+ responseType: response.type,
2953
+ status: response.status,
2954
+ isAborted: false
2955
+ });
2956
+ }), monitor(function(error) {
2957
+ var _a2, _b;
2958
+ reportFetch({
2959
+ status: 0,
2960
+ isAborted: ((_b = (_a2 = context.init) === null || _a2 === void 0 ? void 0 : _a2.signal) === null || _b === void 0 ? void 0 : _b.aborted) || error instanceof DOMException && error.code === DOMException.ABORT_ERR,
2961
+ error
2962
+ });
2963
+ }));
2964
+ }
2965
+ var consoleObservablesByApi = {};
2966
+ function initConsoleObservable(apis) {
2967
+ var consoleObservables = apis.map(function(api) {
2968
+ if (!consoleObservablesByApi[api]) {
2969
+ consoleObservablesByApi[api] = createConsoleObservable(api);
2970
+ }
2971
+ return consoleObservablesByApi[api];
2972
+ });
2973
+ return mergeObservables.apply(void 0, consoleObservables);
2974
+ }
2975
+ function createConsoleObservable(api) {
2976
+ return new Observable(function(observable) {
2977
+ var originalConsoleApi = globalConsole[api];
2978
+ globalConsole[api] = function() {
2979
+ var params = [];
2980
+ for (var _i = 0; _i < arguments.length; _i++) {
2981
+ params[_i] = arguments[_i];
2982
+ }
2983
+ originalConsoleApi.apply(console, params);
2984
+ var handlingStack = createHandlingStack();
2985
+ callMonitored(function() {
2986
+ observable.notify(buildConsoleLog(params, api, handlingStack));
2987
+ });
2988
+ };
2989
+ return function() {
2990
+ globalConsole[api] = originalConsoleApi;
2991
+ };
2992
+ });
2993
+ }
2994
+ function buildConsoleLog(params, api, handlingStack) {
2995
+ var message = params.map(function(param) {
2996
+ return formatConsoleParameters(param);
2997
+ }).join(" ");
2998
+ var stack;
2999
+ var fingerprint;
3000
+ var causes;
3001
+ if (api === ConsoleApiName.error) {
3002
+ var firstErrorParam = find(params, function(param) {
3003
+ return param instanceof Error;
3004
+ });
3005
+ stack = firstErrorParam ? toStackTraceString(computeStackTrace(firstErrorParam)) : void 0;
3006
+ fingerprint = tryToGetFingerprint(firstErrorParam);
3007
+ causes = firstErrorParam ? flattenErrorCauses(firstErrorParam, "console") : void 0;
3008
+ }
3009
+ return {
3010
+ api,
3011
+ message,
3012
+ stack,
3013
+ handlingStack,
3014
+ fingerprint,
3015
+ causes
3016
+ };
3017
+ }
3018
+ function formatConsoleParameters(param) {
3019
+ if (typeof param === "string") {
3020
+ return sanitize(param);
3021
+ }
3022
+ if (param instanceof Error) {
3023
+ return formatErrorMessage(computeStackTrace(param));
3024
+ }
3025
+ return jsonStringify(sanitize(param), void 0, 2);
3026
+ }
3027
+ function createContextManager(customerDataTracker) {
3028
+ var context = {};
3029
+ var changeObservable = new Observable();
3030
+ var contextManager = {
3031
+ getContext: function() {
3032
+ return deepClone(context);
3033
+ },
3034
+ setContext: function(newContext) {
3035
+ if (getType(newContext) === "object") {
3036
+ context = sanitize(newContext);
3037
+ customerDataTracker.updateCustomerData(context);
3038
+ } else {
3039
+ contextManager.clearContext();
3040
+ }
3041
+ changeObservable.notify();
3042
+ },
3043
+ setContextProperty: function(key, property) {
3044
+ context[key] = sanitize(property);
3045
+ customerDataTracker.updateCustomerData(context);
3046
+ changeObservable.notify();
3047
+ },
3048
+ removeContextProperty: function(key) {
3049
+ delete context[key];
3050
+ customerDataTracker.updateCustomerData(context);
3051
+ changeObservable.notify();
3052
+ },
3053
+ clearContext: function() {
3054
+ context = {};
3055
+ customerDataTracker.resetCustomerData();
3056
+ changeObservable.notify();
3057
+ },
3058
+ changeObservable
3059
+ };
3060
+ return contextManager;
3061
+ }
3062
+ var CONTEXT_STORE_KEY_PREFIX = "_dd_c";
3063
+ var storageListeners = [];
3064
+ function storeContextManager(configuration, contextManager, productKey, customerDataType) {
3065
+ var storageKey = buildStorageKey(productKey, customerDataType);
3066
+ storageListeners.push(addEventListener(configuration, window, "storage", function(_a2) {
3067
+ var key = _a2.key;
3068
+ if (storageKey === key) {
3069
+ synchronizeWithStorage();
3070
+ }
3071
+ }));
3072
+ contextManager.changeObservable.subscribe(dumpToStorage);
3073
+ contextManager.setContext(combine(getFromStorage(), contextManager.getContext()));
3074
+ function synchronizeWithStorage() {
3075
+ contextManager.setContext(getFromStorage());
3076
+ }
3077
+ function dumpToStorage() {
3078
+ localStorage.setItem(storageKey, JSON.stringify(contextManager.getContext()));
3079
+ }
3080
+ function getFromStorage() {
3081
+ var rawContext = localStorage.getItem(storageKey);
3082
+ return rawContext !== null ? JSON.parse(rawContext) : {};
3083
+ }
3084
+ }
3085
+ function buildStorageKey(productKey, customerDataType) {
3086
+ return "".concat(CONTEXT_STORE_KEY_PREFIX, "_").concat(productKey, "_").concat(customerDataType);
3087
+ }
3088
+ var CUSTOMER_DATA_BYTES_LIMIT = 3 * ONE_KIBI_BYTE;
3089
+ var CUSTOMER_COMPRESSED_DATA_BYTES_LIMIT = 16 * ONE_KIBI_BYTE;
3090
+ var BYTES_COMPUTATION_THROTTLING_DELAY = 200;
3091
+ function createCustomerDataTrackerManager(compressionStatus) {
3092
+ if (compressionStatus === void 0) {
3093
+ compressionStatus = 2;
3094
+ }
3095
+ var customerDataTrackers = /* @__PURE__ */ new Map();
3096
+ var alreadyWarned = false;
3097
+ function checkCustomerDataLimit(initialBytesCount) {
3098
+ if (initialBytesCount === void 0) {
3099
+ initialBytesCount = 0;
3100
+ }
3101
+ if (alreadyWarned || compressionStatus === 0) {
3102
+ return;
3103
+ }
3104
+ var bytesCountLimit = compressionStatus === 2 ? CUSTOMER_DATA_BYTES_LIMIT : CUSTOMER_COMPRESSED_DATA_BYTES_LIMIT;
3105
+ var bytesCount = initialBytesCount;
3106
+ customerDataTrackers.forEach(function(tracker) {
3107
+ bytesCount += tracker.getBytesCount();
3108
+ });
3109
+ if (bytesCount > bytesCountLimit) {
3110
+ displayCustomerDataLimitReachedWarning(bytesCountLimit);
3111
+ alreadyWarned = true;
3112
+ }
3113
+ }
3114
+ return {
3115
+ /**
3116
+ * Creates a detached tracker. The manager will not store a reference to that tracker, and the
3117
+ * bytes count will be counted independently from other detached trackers.
3118
+ *
3119
+ * This is particularly useful when we don't know when the tracker will be unused, so we don't
3120
+ * leak memory (ex: when used in Logger instances).
3121
+ */
3122
+ createDetachedTracker: function() {
3123
+ var tracker = createCustomerDataTracker(function() {
3124
+ return checkCustomerDataLimit(tracker.getBytesCount());
3125
+ });
3126
+ return tracker;
3127
+ },
3128
+ /**
3129
+ * Creates a tracker if it doesn't exist, and returns it.
3130
+ */
3131
+ getOrCreateTracker: function(type) {
3132
+ if (!customerDataTrackers.has(type)) {
3133
+ customerDataTrackers.set(type, createCustomerDataTracker(checkCustomerDataLimit));
3134
+ }
3135
+ return customerDataTrackers.get(type);
3136
+ },
3137
+ setCompressionStatus: function(newCompressionStatus) {
3138
+ if (compressionStatus === 0) {
3139
+ compressionStatus = newCompressionStatus;
3140
+ checkCustomerDataLimit();
3141
+ }
3142
+ },
3143
+ getCompressionStatus: function() {
3144
+ return compressionStatus;
3145
+ },
3146
+ stop: function() {
3147
+ customerDataTrackers.forEach(function(tracker) {
3148
+ return tracker.stop();
3149
+ });
3150
+ customerDataTrackers.clear();
3151
+ }
3152
+ };
3153
+ }
3154
+ function createCustomerDataTracker(checkCustomerDataLimit) {
3155
+ var bytesCountCache = 0;
3156
+ var _a2 = throttle(function(context) {
3157
+ bytesCountCache = computeBytesCount(jsonStringify(context));
3158
+ checkCustomerDataLimit();
3159
+ }, BYTES_COMPUTATION_THROTTLING_DELAY), computeBytesCountThrottled = _a2.throttled, cancelComputeBytesCount = _a2.cancel;
3160
+ var resetBytesCount = function() {
3161
+ cancelComputeBytesCount();
3162
+ bytesCountCache = 0;
3163
+ };
3164
+ return {
3165
+ updateCustomerData: function(context) {
3166
+ if (isEmptyObject(context)) {
3167
+ resetBytesCount();
3168
+ } else {
3169
+ computeBytesCountThrottled(context);
3170
+ }
3171
+ },
3172
+ resetCustomerData: resetBytesCount,
3173
+ getBytesCount: function() {
3174
+ return bytesCountCache;
3175
+ },
3176
+ stop: function() {
3177
+ cancelComputeBytesCount();
3178
+ }
3179
+ };
3180
+ }
3181
+ function displayCustomerDataLimitReachedWarning(bytesCountLimit) {
3182
+ display.warn("Customer data exceeds the recommended ".concat(bytesCountLimit / ONE_KIBI_BYTE, "KiB threshold. ").concat(MORE_DETAILS, " ").concat(DOCS_TROUBLESHOOTING, "/#customer-data-exceeds-the-recommended-threshold-warning"));
3183
+ }
3184
+ function readBytesFromStream(stream, callback, options) {
3185
+ var reader = stream.getReader();
3186
+ var chunks = [];
3187
+ var readBytesCount = 0;
3188
+ readMore();
3189
+ function readMore() {
3190
+ reader.read().then(monitor(function(result) {
3191
+ if (result.done) {
3192
+ onDone();
3193
+ return;
3194
+ }
3195
+ if (options.collectStreamBody) {
3196
+ chunks.push(result.value);
3197
+ }
3198
+ readBytesCount += result.value.length;
3199
+ if (readBytesCount > options.bytesLimit) {
3200
+ onDone();
3201
+ } else {
3202
+ readMore();
3203
+ }
3204
+ }), monitor(function(error) {
3205
+ return callback(error);
3206
+ }));
3207
+ }
3208
+ function onDone() {
3209
+ reader.cancel().catch(
3210
+ // we don't care if cancel fails, but we still need to catch the error to avoid reporting it
3211
+ // as an unhandled rejection
3212
+ noop
3213
+ );
3214
+ var bytes;
3215
+ var limitExceeded;
3216
+ if (options.collectStreamBody) {
3217
+ var completeBuffer_1;
3218
+ if (chunks.length === 1) {
3219
+ completeBuffer_1 = chunks[0];
3220
+ } else {
3221
+ completeBuffer_1 = new Uint8Array(readBytesCount);
3222
+ var offset_1 = 0;
3223
+ chunks.forEach(function(chunk) {
3224
+ completeBuffer_1.set(chunk, offset_1);
3225
+ offset_1 += chunk.length;
3226
+ });
3227
+ }
3228
+ bytes = completeBuffer_1.slice(0, options.bytesLimit);
3229
+ limitExceeded = completeBuffer_1.length > options.bytesLimit;
3230
+ }
3231
+ callback(void 0, bytes, limitExceeded);
3232
+ }
3233
+ }
3234
+ var SYNTHETICS_TEST_ID_COOKIE_NAME = "datadog-synthetics-public-id";
3235
+ var SYNTHETICS_RESULT_ID_COOKIE_NAME = "datadog-synthetics-result-id";
3236
+ var SYNTHETICS_INJECTS_RUM_COOKIE_NAME = "datadog-synthetics-injects-rum";
3237
+ function willSyntheticsInjectRum() {
3238
+ return Boolean(window._DATADOG_SYNTHETICS_INJECTS_RUM || getInitCookie(SYNTHETICS_INJECTS_RUM_COOKIE_NAME));
3239
+ }
3240
+ function getSyntheticsTestId() {
3241
+ var value = window._DATADOG_SYNTHETICS_PUBLIC_ID || getInitCookie(SYNTHETICS_TEST_ID_COOKIE_NAME);
3242
+ return typeof value === "string" ? value : void 0;
3243
+ }
3244
+ function getSyntheticsResultId() {
3245
+ var value = window._DATADOG_SYNTHETICS_RESULT_ID || getInitCookie(SYNTHETICS_RESULT_ID_COOKIE_NAME);
3246
+ return typeof value === "string" ? value : void 0;
3247
+ }
3248
+ function sanitizeUser(newUser) {
3249
+ var user = assign({}, newUser);
3250
+ var keys = ["id", "name", "email"];
3251
+ keys.forEach(function(key) {
3252
+ if (key in user) {
3253
+ user[key] = String(user[key]);
3254
+ }
3255
+ });
3256
+ return user;
3257
+ }
3258
+ function checkUser(newUser) {
3259
+ var isValid = getType(newUser) === "object";
3260
+ if (!isValid) {
3261
+ display.error("Unsupported user:", newUser);
3262
+ }
3263
+ return isValid;
3264
+ }
3265
+ var _a$3;
3266
+ function isAuthorized(status, handlerType, logger) {
3267
+ var loggerHandler = logger.getHandler();
3268
+ var sanitizedHandlerType = Array.isArray(loggerHandler) ? loggerHandler : [loggerHandler];
3269
+ return STATUS_PRIORITIES[status] >= STATUS_PRIORITIES[logger.getLevel()] && includes(sanitizedHandlerType, handlerType);
3270
+ }
3271
+ var StatusType = {
3272
+ ok: "ok",
3273
+ debug: "debug",
3274
+ info: "info",
3275
+ notice: "notice",
3276
+ warn: "warn",
3277
+ error: "error",
3278
+ critical: "critical",
3279
+ alert: "alert",
3280
+ emerg: "emerg"
3281
+ };
3282
+ var STATUS_PRIORITIES = (_a$3 = {}, _a$3[StatusType.ok] = 0, _a$3[StatusType.debug] = 1, _a$3[StatusType.info] = 2, _a$3[StatusType.notice] = 4, _a$3[StatusType.warn] = 5, _a$3[StatusType.error] = 6, _a$3[StatusType.critical] = 7, _a$3[StatusType.alert] = 8, _a$3[StatusType.emerg] = 9, _a$3);
3283
+ var __decorate = function(decorators, target, key, desc) {
3284
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3285
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3286
+ r = Reflect.decorate(decorators, target, key, desc);
3287
+ else
3288
+ for (var i = decorators.length - 1; i >= 0; i--)
3289
+ if (d = decorators[i])
3290
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3291
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3292
+ };
3293
+ var HandlerType = {
3294
+ console: "console",
3295
+ http: "http",
3296
+ silent: "silent"
3297
+ };
3298
+ var STATUSES = Object.keys(StatusType);
3299
+ var Logger = (
3300
+ /** @class */
3301
+ function() {
3302
+ function Logger2(handleLogStrategy, customerDataTracker, name, handlerType, level, loggerContext) {
3303
+ if (handlerType === void 0) {
3304
+ handlerType = HandlerType.http;
3305
+ }
3306
+ if (level === void 0) {
3307
+ level = StatusType.debug;
3308
+ }
3309
+ if (loggerContext === void 0) {
3310
+ loggerContext = {};
3311
+ }
3312
+ this.handleLogStrategy = handleLogStrategy;
3313
+ this.handlerType = handlerType;
3314
+ this.level = level;
3315
+ this.contextManager = createContextManager(customerDataTracker);
3316
+ this.contextManager.setContext(loggerContext);
3317
+ if (name) {
3318
+ this.contextManager.setContextProperty("logger", { name });
3319
+ }
3320
+ }
3321
+ Logger2.prototype.logImplementation = function(message, messageContext, status, error, handlingStack) {
3322
+ if (status === void 0) {
3323
+ status = StatusType.info;
3324
+ }
3325
+ var errorContext;
3326
+ if (error !== void 0 && error !== null) {
3327
+ var stackTrace = error instanceof Error ? computeStackTrace(error) : void 0;
3328
+ var rawError = computeRawError({
3329
+ stackTrace,
3330
+ originalError: error,
3331
+ nonErrorPrefix: "Provided",
3332
+ source: ErrorSource.LOGGER,
3333
+ handling: "handled",
3334
+ startClocks: clocksNow()
3335
+ });
3336
+ errorContext = {
3337
+ stack: rawError.stack,
3338
+ kind: rawError.type,
3339
+ message: rawError.message,
3340
+ causes: rawError.causes
3341
+ };
3342
+ }
3343
+ var sanitizedMessageContext = sanitize(messageContext);
3344
+ var context = errorContext ? combine({ error: errorContext }, sanitizedMessageContext) : sanitizedMessageContext;
3345
+ this.handleLogStrategy({
3346
+ message: sanitize(message),
3347
+ context,
3348
+ status
3349
+ }, this, handlingStack);
3350
+ };
3351
+ Logger2.prototype.log = function(message, messageContext, status, error) {
3352
+ if (status === void 0) {
3353
+ status = StatusType.info;
3354
+ }
3355
+ var handlingStack;
3356
+ if (isAuthorized(status, HandlerType.http, this)) {
3357
+ handlingStack = createHandlingStack();
3358
+ }
3359
+ this.logImplementation(message, messageContext, status, error, handlingStack);
3360
+ };
3361
+ Logger2.prototype.setContext = function(context) {
3362
+ this.contextManager.setContext(context);
3363
+ };
3364
+ Logger2.prototype.getContext = function() {
3365
+ return this.contextManager.getContext();
3366
+ };
3367
+ Logger2.prototype.setContextProperty = function(key, value) {
3368
+ this.contextManager.setContextProperty(key, value);
3369
+ };
3370
+ Logger2.prototype.removeContextProperty = function(key) {
3371
+ this.contextManager.removeContextProperty(key);
3372
+ };
3373
+ Logger2.prototype.clearContext = function() {
3374
+ this.contextManager.clearContext();
3375
+ };
3376
+ Logger2.prototype.setHandler = function(handler) {
3377
+ this.handlerType = handler;
3378
+ };
3379
+ Logger2.prototype.getHandler = function() {
3380
+ return this.handlerType;
3381
+ };
3382
+ Logger2.prototype.setLevel = function(level) {
3383
+ this.level = level;
3384
+ };
3385
+ Logger2.prototype.getLevel = function() {
3386
+ return this.level;
3387
+ };
3388
+ __decorate([
3389
+ monitored
3390
+ ], Logger2.prototype, "logImplementation", null);
3391
+ return Logger2;
3392
+ }()
3393
+ );
3394
+ Logger.prototype.ok = createLoggerMethod(StatusType.ok);
3395
+ Logger.prototype.debug = createLoggerMethod(StatusType.debug);
3396
+ Logger.prototype.info = createLoggerMethod(StatusType.info);
3397
+ Logger.prototype.notice = createLoggerMethod(StatusType.notice);
3398
+ Logger.prototype.warn = createLoggerMethod(StatusType.warn);
3399
+ Logger.prototype.error = createLoggerMethod(StatusType.error);
3400
+ Logger.prototype.critical = createLoggerMethod(StatusType.critical);
3401
+ Logger.prototype.alert = createLoggerMethod(StatusType.alert);
3402
+ Logger.prototype.emerg = createLoggerMethod(StatusType.emerg);
3403
+ function createLoggerMethod(status) {
3404
+ return function(message, messageContext, error) {
3405
+ var handlingStack;
3406
+ if (isAuthorized(status, HandlerType.http, this)) {
3407
+ handlingStack = createHandlingStack();
3408
+ }
3409
+ this.logImplementation(message, messageContext, status, error, handlingStack);
3410
+ };
3411
+ }
3412
+ function buildCommonContext(globalContextManager, userContextManager) {
3413
+ return {
3414
+ view: {
3415
+ referrer: document.referrer,
3416
+ url: window.location.href
3417
+ },
3418
+ context: globalContextManager.getContext(),
3419
+ user: userContextManager.getContext()
3420
+ };
3421
+ }
3422
+ var DEFAULT_REQUEST_ERROR_RESPONSE_LENGTH_LIMIT = 32 * ONE_KIBI_BYTE;
3423
+ function validateAndBuildLogsConfiguration(initConfiguration) {
3424
+ if (initConfiguration.usePciIntake === true && initConfiguration.site && initConfiguration.site !== "datadoghq.com") {
3425
+ display.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");
3426
+ }
3427
+ var baseConfiguration = validateAndBuildConfiguration(initConfiguration);
3428
+ var forwardConsoleLogs = validateAndBuildForwardOption(initConfiguration.forwardConsoleLogs, objectValues(ConsoleApiName), "Forward Console Logs");
3429
+ var forwardReports = validateAndBuildForwardOption(initConfiguration.forwardReports, objectValues(RawReportType), "Forward Reports");
3430
+ if (!baseConfiguration || !forwardConsoleLogs || !forwardReports) {
3431
+ return;
3432
+ }
3433
+ if (initConfiguration.forwardErrorsToLogs && !includes(forwardConsoleLogs, ConsoleApiName.error)) {
3434
+ forwardConsoleLogs.push(ConsoleApiName.error);
3435
+ }
3436
+ return assign({
3437
+ forwardErrorsToLogs: initConfiguration.forwardErrorsToLogs !== false,
3438
+ forwardConsoleLogs,
3439
+ forwardReports,
3440
+ requestErrorResponseLengthLimit: DEFAULT_REQUEST_ERROR_RESPONSE_LENGTH_LIMIT,
3441
+ sendLogsAfterSessionExpiration: !!initConfiguration.sendLogsAfterSessionExpiration
3442
+ }, baseConfiguration);
3443
+ }
3444
+ function validateAndBuildForwardOption(option, allowedValues, label) {
3445
+ if (option === void 0) {
3446
+ return [];
3447
+ }
3448
+ if (!(option === "all" || Array.isArray(option) && option.every(function(api) {
3449
+ return includes(allowedValues, api);
3450
+ }))) {
3451
+ display.error("".concat(label, ' should be "all" or an array with allowed values "').concat(allowedValues.join('", "'), '"'));
3452
+ return;
3453
+ }
3454
+ return option === "all" ? allowedValues : removeDuplicates(option);
3455
+ }
3456
+ function serializeLogsConfiguration(configuration) {
3457
+ var baseSerializedInitConfiguration = serializeConfiguration(configuration);
3458
+ return assign({
3459
+ forward_errors_to_logs: configuration.forwardErrorsToLogs,
3460
+ forward_console_logs: configuration.forwardConsoleLogs,
3461
+ forward_reports: configuration.forwardReports,
3462
+ use_pci_intake: configuration.usePciIntake,
3463
+ send_logs_after_session_expiration: configuration.sendLogsAfterSessionExpiration
3464
+ }, baseSerializedInitConfiguration);
3465
+ }
3466
+ function createPreStartStrategy(getCommonContext, trackingConsentState, doStartLogs) {
3467
+ var bufferApiCalls = createBoundedBuffer();
3468
+ var cachedInitConfiguration;
3469
+ var cachedConfiguration;
3470
+ var trackingConsentStateSubscription = trackingConsentState.observable.subscribe(tryStartLogs);
3471
+ function tryStartLogs() {
3472
+ if (!cachedConfiguration || !cachedInitConfiguration || !trackingConsentState.isGranted()) {
3473
+ return;
3474
+ }
3475
+ trackingConsentStateSubscription.unsubscribe();
3476
+ var startLogsResult = doStartLogs(cachedInitConfiguration, cachedConfiguration);
3477
+ bufferApiCalls.drain(startLogsResult);
3478
+ }
3479
+ return {
3480
+ init: function(initConfiguration) {
3481
+ if (!initConfiguration) {
3482
+ display.error("Missing configuration");
3483
+ return;
3484
+ }
3485
+ initFeatureFlags(initConfiguration.enableExperimentalFeatures);
3486
+ if (canUseEventBridge()) {
3487
+ initConfiguration = overrideInitConfigurationForBridge(initConfiguration);
3488
+ }
3489
+ cachedInitConfiguration = initConfiguration;
3490
+ if (cachedConfiguration) {
3491
+ displayAlreadyInitializedError("DD_LOGS", initConfiguration);
3492
+ return;
3493
+ }
3494
+ var configuration = validateAndBuildLogsConfiguration(initConfiguration);
3495
+ if (!configuration) {
3496
+ return;
3497
+ }
3498
+ cachedConfiguration = configuration;
3499
+ initFetchObservable().subscribe(noop);
3500
+ trackingConsentState.tryToInit(configuration.trackingConsent);
3501
+ tryStartLogs();
3502
+ },
3503
+ get initConfiguration() {
3504
+ return cachedInitConfiguration;
3505
+ },
3506
+ getInternalContext: noop,
3507
+ handleLog: function(message, statusType, handlingStack, context, date) {
3508
+ if (context === void 0) {
3509
+ context = getCommonContext();
3510
+ }
3511
+ if (date === void 0) {
3512
+ date = timeStampNow();
3513
+ }
3514
+ bufferApiCalls.add(function(startLogsResult) {
3515
+ return startLogsResult.handleLog(message, statusType, handlingStack, context, date);
3516
+ });
3517
+ }
3518
+ };
3519
+ }
3520
+ function overrideInitConfigurationForBridge(initConfiguration) {
3521
+ return assign({}, initConfiguration, { clientToken: "empty" });
3522
+ }
3523
+ var LOGS_STORAGE_KEY = "logs";
3524
+ function makeLogsPublicApi(startLogsImpl) {
3525
+ var customerDataTrackerManager = createCustomerDataTrackerManager();
3526
+ var globalContextManager = createContextManager(customerDataTrackerManager.getOrCreateTracker(
3527
+ 2
3528
+ /* CustomerDataType.GlobalContext */
3529
+ ));
3530
+ var userContextManager = createContextManager(customerDataTrackerManager.getOrCreateTracker(
3531
+ 1
3532
+ /* CustomerDataType.User */
3533
+ ));
3534
+ var trackingConsentState = createTrackingConsentState();
3535
+ function getCommonContext() {
3536
+ return buildCommonContext(globalContextManager, userContextManager);
3537
+ }
3538
+ var strategy = createPreStartStrategy(getCommonContext, trackingConsentState, function(initConfiguration, configuration) {
3539
+ if (initConfiguration.storeContextsAcrossPages) {
3540
+ storeContextManager(
3541
+ configuration,
3542
+ globalContextManager,
3543
+ LOGS_STORAGE_KEY,
3544
+ 2
3545
+ /* CustomerDataType.GlobalContext */
3546
+ );
3547
+ storeContextManager(
3548
+ configuration,
3549
+ userContextManager,
3550
+ LOGS_STORAGE_KEY,
3551
+ 1
3552
+ /* CustomerDataType.User */
3553
+ );
3554
+ }
3555
+ var startLogsResult = startLogsImpl(initConfiguration, configuration, getCommonContext, trackingConsentState);
3556
+ strategy = createPostStartStrategy(initConfiguration, startLogsResult);
3557
+ return startLogsResult;
3558
+ });
3559
+ var customLoggers = {};
3560
+ var mainLogger = new Logger(function() {
3561
+ var params = [];
3562
+ for (var _i = 0; _i < arguments.length; _i++) {
3563
+ params[_i] = arguments[_i];
3564
+ }
3565
+ return strategy.handleLog.apply(strategy, params);
3566
+ }, customerDataTrackerManager.createDetachedTracker());
3567
+ return makePublicApi({
3568
+ logger: mainLogger,
3569
+ init: monitor(function(initConfiguration) {
3570
+ return strategy.init(initConfiguration);
3571
+ }),
3572
+ setTrackingConsent: monitor(function(trackingConsent) {
3573
+ trackingConsentState.update(trackingConsent);
3574
+ addTelemetryUsage({ feature: "set-tracking-consent", tracking_consent: trackingConsent });
3575
+ }),
3576
+ getGlobalContext: monitor(function() {
3577
+ return globalContextManager.getContext();
3578
+ }),
3579
+ setGlobalContext: monitor(function(context) {
3580
+ return globalContextManager.setContext(context);
3581
+ }),
3582
+ setGlobalContextProperty: monitor(function(key, value) {
3583
+ return globalContextManager.setContextProperty(key, value);
3584
+ }),
3585
+ removeGlobalContextProperty: monitor(function(key) {
3586
+ return globalContextManager.removeContextProperty(key);
3587
+ }),
3588
+ clearGlobalContext: monitor(function() {
3589
+ return globalContextManager.clearContext();
3590
+ }),
3591
+ createLogger: monitor(function(name, conf) {
3592
+ if (conf === void 0) {
3593
+ conf = {};
3594
+ }
3595
+ customLoggers[name] = new Logger(function() {
3596
+ var params = [];
3597
+ for (var _i = 0; _i < arguments.length; _i++) {
3598
+ params[_i] = arguments[_i];
3599
+ }
3600
+ return strategy.handleLog.apply(strategy, params);
3601
+ }, customerDataTrackerManager.createDetachedTracker(), sanitize(name), conf.handler, conf.level, sanitize(conf.context));
3602
+ return customLoggers[name];
3603
+ }),
3604
+ getLogger: monitor(function(name) {
3605
+ return customLoggers[name];
3606
+ }),
3607
+ getInitConfiguration: monitor(function() {
3608
+ return deepClone(strategy.initConfiguration);
3609
+ }),
3610
+ getInternalContext: monitor(function(startTime) {
3611
+ return strategy.getInternalContext(startTime);
3612
+ }),
3613
+ setUser: monitor(function(newUser) {
3614
+ if (checkUser(newUser)) {
3615
+ userContextManager.setContext(sanitizeUser(newUser));
3616
+ }
3617
+ }),
3618
+ getUser: monitor(function() {
3619
+ return userContextManager.getContext();
3620
+ }),
3621
+ setUserProperty: monitor(function(key, property) {
3622
+ var _a2;
3623
+ var sanitizedProperty = sanitizeUser((_a2 = {}, _a2[key] = property, _a2))[key];
3624
+ userContextManager.setContextProperty(key, sanitizedProperty);
3625
+ }),
3626
+ removeUserProperty: monitor(function(key) {
3627
+ return userContextManager.removeContextProperty(key);
3628
+ }),
3629
+ clearUser: monitor(function() {
3630
+ return userContextManager.clearContext();
3631
+ })
3632
+ });
3633
+ }
3634
+ function createPostStartStrategy(initConfiguration, startLogsResult) {
3635
+ return assign({
3636
+ init: function(initConfiguration2) {
3637
+ displayAlreadyInitializedError("DD_LOGS", initConfiguration2);
3638
+ },
3639
+ initConfiguration
3640
+ }, startLogsResult);
3641
+ }
3642
+ var LOGS_SESSION_KEY = "logs";
3643
+ function startLogsSessionManager(configuration, trackingConsentState) {
3644
+ var sessionManager = startSessionManager(configuration, LOGS_SESSION_KEY, function(rawTrackingType) {
3645
+ return computeSessionState(configuration, rawTrackingType);
3646
+ }, trackingConsentState);
3647
+ return {
3648
+ findTrackedSession: function(startTime, options) {
3649
+ if (options === void 0) {
3650
+ options = { returnInactive: false };
3651
+ }
3652
+ var session = sessionManager.findSession(startTime, options);
3653
+ return session && session.trackingType === "1" ? {
3654
+ id: session.id
3655
+ } : void 0;
3656
+ },
3657
+ expireObservable: sessionManager.expireObservable
3658
+ };
3659
+ }
3660
+ function startLogsSessionManagerStub(configuration) {
3661
+ var isTracked = computeTrackingType(configuration) === "1";
3662
+ var session = isTracked ? {} : void 0;
3663
+ return {
3664
+ findTrackedSession: function() {
3665
+ return session;
3666
+ },
3667
+ expireObservable: new Observable()
3668
+ };
3669
+ }
3670
+ function computeTrackingType(configuration) {
3671
+ if (!performDraw(configuration.sessionSampleRate)) {
3672
+ return "0";
3673
+ }
3674
+ return "1";
3675
+ }
3676
+ function computeSessionState(configuration, rawSessionType) {
3677
+ var trackingType = hasValidLoggerSession(rawSessionType) ? rawSessionType : computeTrackingType(configuration);
3678
+ return {
3679
+ trackingType,
3680
+ isTracked: trackingType === "1"
3681
+ };
3682
+ }
3683
+ function hasValidLoggerSession(trackingType) {
3684
+ return trackingType === "0" || trackingType === "1";
3685
+ }
3686
+ var logsSentBeforeRumInjectionTelemetryAdded = false;
3687
+ function getRUMInternalContext(startTime) {
3688
+ var browserWindow = window;
3689
+ if (willSyntheticsInjectRum()) {
3690
+ var context = getInternalContextFromRumGlobal(browserWindow.DD_RUM_SYNTHETICS);
3691
+ if (!context && !logsSentBeforeRumInjectionTelemetryAdded) {
3692
+ logsSentBeforeRumInjectionTelemetryAdded = true;
3693
+ addTelemetryDebug("Logs sent before RUM is injected by the synthetics worker", {
3694
+ testId: getSyntheticsTestId(),
3695
+ resultId: getSyntheticsResultId()
3696
+ });
3697
+ }
3698
+ return context;
3699
+ }
3700
+ return getInternalContextFromRumGlobal(browserWindow.DD_RUM);
3701
+ function getInternalContextFromRumGlobal(rumGlobal) {
3702
+ if (rumGlobal && rumGlobal.getInternalContext) {
3703
+ return rumGlobal.getInternalContext(startTime);
3704
+ }
3705
+ }
3706
+ }
3707
+ function startLogsAssembly(sessionManager, configuration, lifeCycle, getCommonContext, reportError) {
3708
+ var statusWithCustom = STATUSES.concat(["custom"]);
3709
+ var logRateLimiters = {};
3710
+ statusWithCustom.forEach(function(status) {
3711
+ logRateLimiters[status] = createEventRateLimiter(status, configuration.eventRateLimiterThreshold, reportError);
3712
+ });
3713
+ lifeCycle.subscribe(0, function(_a2) {
3714
+ var _b, _c;
3715
+ var rawLogsEvent = _a2.rawLogsEvent, _d = _a2.messageContext, messageContext = _d === void 0 ? void 0 : _d, _e = _a2.savedCommonContext, savedCommonContext = _e === void 0 ? void 0 : _e, domainContext = _a2.domainContext;
3716
+ var startTime = getRelativeTime(rawLogsEvent.date);
3717
+ var session = sessionManager.findTrackedSession(startTime);
3718
+ if (!session && (!configuration.sendLogsAfterSessionExpiration || !sessionManager.findTrackedSession(startTime, { returnInactive: true }))) {
3719
+ return;
3720
+ }
3721
+ var commonContext = savedCommonContext || getCommonContext();
3722
+ var log = combine({
3723
+ service: configuration.service,
3724
+ session_id: session ? session.id : void 0,
3725
+ // Insert user first to allow overrides from global context
3726
+ usr: !isEmptyObject(commonContext.user) ? commonContext.user : void 0,
3727
+ view: commonContext.view
3728
+ }, commonContext.context, getRUMInternalContext(startTime), rawLogsEvent, messageContext);
3729
+ if (((_b = configuration.beforeSend) === null || _b === void 0 ? void 0 : _b.call(configuration, log, domainContext)) === false || log.origin !== ErrorSource.AGENT && ((_c = logRateLimiters[log.status]) !== null && _c !== void 0 ? _c : logRateLimiters["custom"]).isLimitReached()) {
3730
+ return;
3731
+ }
3732
+ lifeCycle.notify(1, log);
3733
+ });
3734
+ }
3735
+ var _a$2;
3736
+ var LogStatusForApi = (_a$2 = {}, _a$2[ConsoleApiName.log] = StatusType.info, _a$2[ConsoleApiName.debug] = StatusType.debug, _a$2[ConsoleApiName.info] = StatusType.info, _a$2[ConsoleApiName.warn] = StatusType.warn, _a$2[ConsoleApiName.error] = StatusType.error, _a$2);
3737
+ function startConsoleCollection(configuration, lifeCycle) {
3738
+ var consoleSubscription = initConsoleObservable(configuration.forwardConsoleLogs).subscribe(function(log) {
3739
+ var collectedData = {
3740
+ rawLogsEvent: {
3741
+ date: timeStampNow(),
3742
+ message: log.message,
3743
+ origin: ErrorSource.CONSOLE,
3744
+ error: log.api === ConsoleApiName.error ? {
3745
+ stack: log.stack,
3746
+ fingerprint: log.fingerprint,
3747
+ causes: log.causes
3748
+ } : void 0,
3749
+ status: LogStatusForApi[log.api]
3750
+ },
3751
+ domainContext: {
3752
+ handlingStack: log.handlingStack
3753
+ }
3754
+ };
3755
+ lifeCycle.notify(0, collectedData);
3756
+ });
3757
+ return {
3758
+ stop: function() {
3759
+ consoleSubscription.unsubscribe();
3760
+ }
3761
+ };
3762
+ }
3763
+ var _a$1;
3764
+ var LogStatusForReport = (_a$1 = {}, _a$1[RawReportType.cspViolation] = StatusType.error, _a$1[RawReportType.intervention] = StatusType.error, _a$1[RawReportType.deprecation] = StatusType.warn, _a$1);
3765
+ function startReportCollection(configuration, lifeCycle) {
3766
+ var reportSubscription = initReportObservable(configuration, configuration.forwardReports).subscribe(function(report) {
3767
+ var message = report.message;
3768
+ var status = LogStatusForReport[report.type];
3769
+ var error;
3770
+ if (status === StatusType.error) {
3771
+ error = {
3772
+ kind: report.subtype,
3773
+ stack: report.stack
3774
+ };
3775
+ } else if (report.stack) {
3776
+ message += " Found in ".concat(getFileFromStackTraceString(report.stack));
3777
+ }
3778
+ lifeCycle.notify(0, {
3779
+ rawLogsEvent: {
3780
+ date: timeStampNow(),
3781
+ message,
3782
+ origin: ErrorSource.REPORT,
3783
+ error,
3784
+ status
3785
+ }
3786
+ });
3787
+ });
3788
+ return {
3789
+ stop: function() {
3790
+ reportSubscription.unsubscribe();
3791
+ }
3792
+ };
3793
+ }
3794
+ function startNetworkErrorCollection(configuration, lifeCycle) {
3795
+ if (!configuration.forwardErrorsToLogs) {
3796
+ return { stop: noop };
3797
+ }
3798
+ var xhrSubscription = initXhrObservable(configuration).subscribe(function(context) {
3799
+ if (context.state === "complete") {
3800
+ handleResponse("xhr", context);
3801
+ }
3802
+ });
3803
+ var fetchSubscription = initFetchObservable().subscribe(function(context) {
3804
+ if (context.state === "resolve") {
3805
+ handleResponse("fetch", context);
3806
+ }
3807
+ });
3808
+ function handleResponse(type, request) {
3809
+ if (!configuration.isIntakeUrl(request.url) && (isRejected(request) || isServerError(request.status))) {
3810
+ if ("xhr" in request) {
3811
+ computeXhrResponseData(request.xhr, configuration, onResponseDataAvailable);
3812
+ } else if (request.response) {
3813
+ computeFetchResponseText(request.response, configuration, onResponseDataAvailable);
3814
+ } else if (request.error) {
3815
+ computeFetchErrorText(request.error, configuration, onResponseDataAvailable);
3816
+ }
3817
+ }
3818
+ function onResponseDataAvailable(responseData) {
3819
+ var domainContext = {
3820
+ isAborted: request.isAborted,
3821
+ handlingStack: request.handlingStack
3822
+ };
3823
+ lifeCycle.notify(0, {
3824
+ rawLogsEvent: {
3825
+ message: "".concat(format(type), " error ").concat(request.method, " ").concat(request.url),
3826
+ date: request.startClocks.timeStamp,
3827
+ error: {
3828
+ stack: responseData || "Failed to load"
3829
+ },
3830
+ http: {
3831
+ method: request.method,
3832
+ // Cast resource method because of case mismatch cf issue RUMF-1152
3833
+ status_code: request.status,
3834
+ url: request.url
3835
+ },
3836
+ status: StatusType.error,
3837
+ origin: ErrorSource.NETWORK
3838
+ },
3839
+ domainContext
3840
+ });
3841
+ }
3842
+ }
3843
+ return {
3844
+ stop: function() {
3845
+ xhrSubscription.unsubscribe();
3846
+ fetchSubscription.unsubscribe();
3847
+ }
3848
+ };
3849
+ }
3850
+ function computeXhrResponseData(xhr, configuration, callback) {
3851
+ if (typeof xhr.response === "string") {
3852
+ callback(truncateResponseText(xhr.response, configuration));
3853
+ } else {
3854
+ callback(xhr.response);
3855
+ }
3856
+ }
3857
+ function computeFetchErrorText(error, configuration, callback) {
3858
+ callback(truncateResponseText(toStackTraceString(computeStackTrace(error)), configuration));
3859
+ }
3860
+ function computeFetchResponseText(response, configuration, callback) {
3861
+ var clonedResponse = tryToClone(response);
3862
+ if (!clonedResponse || !clonedResponse.body) {
3863
+ callback();
3864
+ } else if (!window.TextDecoder) {
3865
+ clonedResponse.text().then(monitor(function(text) {
3866
+ return callback(truncateResponseText(text, configuration));
3867
+ }), monitor(function(error) {
3868
+ return callback("Unable to retrieve response: ".concat(error));
3869
+ }));
3870
+ } else {
3871
+ truncateResponseStream(clonedResponse.body, configuration.requestErrorResponseLengthLimit, function(error, responseText) {
3872
+ if (error) {
3873
+ callback("Unable to retrieve response: ".concat(error));
3874
+ } else {
3875
+ callback(responseText);
3876
+ }
3877
+ });
3878
+ }
3879
+ }
3880
+ function isRejected(request) {
3881
+ return request.status === 0 && request.responseType !== "opaque";
3882
+ }
3883
+ function truncateResponseText(responseText, configuration) {
3884
+ if (responseText.length > configuration.requestErrorResponseLengthLimit) {
3885
+ return "".concat(responseText.substring(0, configuration.requestErrorResponseLengthLimit), "...");
3886
+ }
3887
+ return responseText;
3888
+ }
3889
+ function format(type) {
3890
+ if ("xhr" === type) {
3891
+ return "XHR";
3892
+ }
3893
+ return "Fetch";
3894
+ }
3895
+ function truncateResponseStream(stream, bytesLimit, callback) {
3896
+ readBytesFromStream(stream, function(error, bytes, limitExceeded) {
3897
+ if (error) {
3898
+ callback(error);
3899
+ } else {
3900
+ var responseText = new TextDecoder().decode(bytes);
3901
+ if (limitExceeded) {
3902
+ responseText += "...";
3903
+ }
3904
+ callback(void 0, responseText);
3905
+ }
3906
+ }, {
3907
+ bytesLimit,
3908
+ collectStreamBody: true
3909
+ });
3910
+ }
3911
+ function startRuntimeErrorCollection(configuration, lifeCycle) {
3912
+ if (!configuration.forwardErrorsToLogs) {
3913
+ return { stop: noop };
3914
+ }
3915
+ var rawErrorObservable = new Observable();
3916
+ var stopRuntimeErrorTracking = trackRuntimeError(rawErrorObservable).stop;
3917
+ var rawErrorSubscription = rawErrorObservable.subscribe(function(rawError) {
3918
+ lifeCycle.notify(0, {
3919
+ rawLogsEvent: {
3920
+ message: rawError.message,
3921
+ date: rawError.startClocks.timeStamp,
3922
+ error: {
3923
+ kind: rawError.type,
3924
+ stack: rawError.stack,
3925
+ causes: rawError.causes
3926
+ },
3927
+ origin: ErrorSource.SOURCE,
3928
+ status: StatusType.error
3929
+ }
3930
+ });
3931
+ });
3932
+ return {
3933
+ stop: function() {
3934
+ stopRuntimeErrorTracking();
3935
+ rawErrorSubscription.unsubscribe();
3936
+ }
3937
+ };
3938
+ }
3939
+ var LifeCycle = AbstractLifeCycle;
3940
+ var _a;
3941
+ function startLoggerCollection(lifeCycle) {
3942
+ function handleLog(logsMessage, logger, handlingStack, savedCommonContext, savedDate) {
3943
+ var messageContext = combine(logger.getContext(), logsMessage.context);
3944
+ if (isAuthorized(logsMessage.status, HandlerType.console, logger)) {
3945
+ displayInConsole(logsMessage, messageContext);
3946
+ }
3947
+ if (isAuthorized(logsMessage.status, HandlerType.http, logger)) {
3948
+ var rawLogEventData = {
3949
+ rawLogsEvent: {
3950
+ date: savedDate || timeStampNow(),
3951
+ message: logsMessage.message,
3952
+ status: logsMessage.status,
3953
+ origin: ErrorSource.LOGGER
3954
+ },
3955
+ messageContext,
3956
+ savedCommonContext
3957
+ };
3958
+ if (handlingStack) {
3959
+ rawLogEventData.domainContext = { handlingStack };
3960
+ }
3961
+ lifeCycle.notify(0, rawLogEventData);
3962
+ }
3963
+ }
3964
+ return {
3965
+ handleLog
3966
+ };
3967
+ }
3968
+ var loggerToConsoleApiName = (_a = {}, _a[StatusType.ok] = ConsoleApiName.debug, _a[StatusType.debug] = ConsoleApiName.debug, _a[StatusType.info] = ConsoleApiName.info, _a[StatusType.notice] = ConsoleApiName.info, _a[StatusType.warn] = ConsoleApiName.warn, _a[StatusType.error] = ConsoleApiName.error, _a[StatusType.critical] = ConsoleApiName.error, _a[StatusType.alert] = ConsoleApiName.error, _a[StatusType.emerg] = ConsoleApiName.error, _a);
3969
+ function displayInConsole(_a2, messageContext) {
3970
+ var status = _a2.status, message = _a2.message;
3971
+ originalConsoleMethods[loggerToConsoleApiName[status]].call(globalConsole, message, messageContext);
3972
+ }
3973
+ function startLogsBatch(configuration, lifeCycle, reportError, pageExitObservable, session) {
3974
+ var batch = startBatchWithReplica(configuration, {
3975
+ endpoint: configuration.logsEndpointBuilder,
3976
+ encoder: createIdentityEncoder()
3977
+ }, configuration.replica && {
3978
+ endpoint: configuration.replica.logsEndpointBuilder,
3979
+ encoder: createIdentityEncoder()
3980
+ }, reportError, pageExitObservable, session.expireObservable);
3981
+ lifeCycle.subscribe(1, function(serverLogsEvent) {
3982
+ batch.add(serverLogsEvent);
3983
+ });
3984
+ return batch;
3985
+ }
3986
+ function startLogsBridge(lifeCycle) {
3987
+ var bridge = getEventBridge();
3988
+ lifeCycle.subscribe(1, function(serverLogsEvent) {
3989
+ bridge.send("log", serverLogsEvent);
3990
+ });
3991
+ }
3992
+ function startInternalContext(sessionManager) {
3993
+ return {
3994
+ get: function(startTime) {
3995
+ var trackedSession = sessionManager.findTrackedSession(startTime);
3996
+ if (trackedSession) {
3997
+ return {
3998
+ session_id: trackedSession.id
3999
+ };
4000
+ }
4001
+ }
4002
+ };
4003
+ }
4004
+ function startReportError(lifeCycle) {
4005
+ return function(error) {
4006
+ lifeCycle.notify(0, {
4007
+ rawLogsEvent: {
4008
+ message: error.message,
4009
+ date: error.startClocks.timeStamp,
4010
+ origin: ErrorSource.AGENT,
4011
+ status: StatusType.error
4012
+ }
4013
+ });
4014
+ addTelemetryDebug("Error reported to customer", { "error.message": error.message });
4015
+ };
4016
+ }
4017
+ function startLogsTelemetry(initConfiguration, configuration, reportError, pageExitObservable, session) {
4018
+ var telemetry = startTelemetry("browser-logs-sdk", configuration);
4019
+ telemetry.setContextProvider(function() {
4020
+ var _a2, _b, _c, _d, _e, _f;
4021
+ return {
4022
+ application: {
4023
+ id: (_a2 = getRUMInternalContext()) === null || _a2 === void 0 ? void 0 : _a2.application_id
4024
+ },
4025
+ session: {
4026
+ id: (_b = session.findTrackedSession()) === null || _b === void 0 ? void 0 : _b.id
4027
+ },
4028
+ view: {
4029
+ id: (_d = (_c = getRUMInternalContext()) === null || _c === void 0 ? void 0 : _c.view) === null || _d === void 0 ? void 0 : _d.id
4030
+ },
4031
+ action: {
4032
+ id: (_f = (_e = getRUMInternalContext()) === null || _e === void 0 ? void 0 : _e.user_action) === null || _f === void 0 ? void 0 : _f.id
4033
+ }
4034
+ };
4035
+ });
4036
+ var cleanupTasks = [];
4037
+ if (canUseEventBridge()) {
4038
+ var bridge_1 = getEventBridge();
4039
+ var telemetrySubscription_1 = telemetry.observable.subscribe(function(event) {
4040
+ return bridge_1.send("internal_telemetry", event);
4041
+ });
4042
+ cleanupTasks.push(function() {
4043
+ return telemetrySubscription_1.unsubscribe();
4044
+ });
4045
+ } else {
4046
+ var telemetryBatch_1 = startBatchWithReplica(configuration, {
4047
+ endpoint: configuration.rumEndpointBuilder,
4048
+ encoder: createIdentityEncoder()
4049
+ }, configuration.replica && {
4050
+ endpoint: configuration.replica.rumEndpointBuilder,
4051
+ encoder: createIdentityEncoder()
4052
+ }, reportError, pageExitObservable, session.expireObservable);
4053
+ cleanupTasks.push(function() {
4054
+ return telemetryBatch_1.stop();
4055
+ });
4056
+ var telemetrySubscription_2 = telemetry.observable.subscribe(function(event) {
4057
+ return telemetryBatch_1.add(event, isTelemetryReplicationAllowed(configuration));
4058
+ });
4059
+ cleanupTasks.push(function() {
4060
+ return telemetrySubscription_2.unsubscribe();
4061
+ });
4062
+ }
4063
+ drainPreStartTelemetry();
4064
+ addTelemetryConfiguration(serializeLogsConfiguration(initConfiguration));
4065
+ return {
4066
+ telemetry,
4067
+ stop: function() {
4068
+ cleanupTasks.forEach(function(task) {
4069
+ return task();
4070
+ });
4071
+ }
4072
+ };
4073
+ }
4074
+ function startLogs(initConfiguration, configuration, getCommonContext, trackingConsentState) {
4075
+ var lifeCycle = new LifeCycle();
4076
+ var cleanupTasks = [];
4077
+ lifeCycle.subscribe(1, function(log) {
4078
+ return sendToExtension("logs", log);
4079
+ });
4080
+ var reportError = startReportError(lifeCycle);
4081
+ var pageExitObservable = createPageExitObservable(configuration);
4082
+ var session = configuration.sessionStoreStrategyType && !canUseEventBridge() && !willSyntheticsInjectRum() ? startLogsSessionManager(configuration, trackingConsentState) : startLogsSessionManagerStub(configuration);
4083
+ var stopLogsTelemetry = startLogsTelemetry(initConfiguration, configuration, reportError, pageExitObservable, session).stop;
4084
+ cleanupTasks.push(function() {
4085
+ return stopLogsTelemetry();
4086
+ });
4087
+ startNetworkErrorCollection(configuration, lifeCycle);
4088
+ startRuntimeErrorCollection(configuration, lifeCycle);
4089
+ startConsoleCollection(configuration, lifeCycle);
4090
+ startReportCollection(configuration, lifeCycle);
4091
+ var handleLog = startLoggerCollection(lifeCycle).handleLog;
4092
+ startLogsAssembly(session, configuration, lifeCycle, getCommonContext, reportError);
4093
+ if (!canUseEventBridge()) {
4094
+ var stopLogsBatch_1 = startLogsBatch(configuration, lifeCycle, reportError, pageExitObservable, session).stop;
4095
+ cleanupTasks.push(function() {
4096
+ return stopLogsBatch_1();
4097
+ });
4098
+ } else {
4099
+ startLogsBridge(lifeCycle);
4100
+ }
4101
+ var internalContext = startInternalContext(session);
4102
+ return {
4103
+ handleLog,
4104
+ getInternalContext: internalContext.get,
4105
+ stop: function() {
4106
+ cleanupTasks.forEach(function(task) {
4107
+ return task();
4108
+ });
4109
+ }
4110
+ };
4111
+ }
4112
+ var datadogLogs = makeLogsPublicApi(startLogs);
4113
+ defineGlobal(getGlobalObject(), "DD_LOGS", datadogLogs);
4114
+ function normalizeArgs(args) {
4115
+ let msg = "";
4116
+ let obj = {};
4117
+ let error;
4118
+ let arrCount = 1;
4119
+ Array.from(arguments).forEach((arg) => {
4120
+ if (typeof arg === "string") {
4121
+ msg += ` ${arg}`;
4122
+ } else if (arg instanceof Error) {
4123
+ error = arg;
4124
+ } else if (Array.isArray(arg)) {
4125
+ obj[`array${arrCount++}`] = arg;
4126
+ } else if (typeof arg === "object") {
4127
+ Object.assign(obj, arg);
4128
+ }
4129
+ });
4130
+ return {
4131
+ message: msg.trim(),
4132
+ properties: obj,
4133
+ error
4134
+ };
4135
+ }
4136
+ const DEFAULTS = {
4137
+ silentMultipleInit: true,
4138
+ service: "BROWSER_LOG",
4139
+ site: "datadoghq.com",
4140
+ forwardErrorsToLogs: false,
4141
+ sessionSampleRate: 100
4142
+ };
4143
+ class DatadogLogger {
4144
+ constructor(options = {}) {
4145
+ if (!options.clientToken) {
4146
+ throw new Error('Please provide "clientToken" for your Datadog account');
4147
+ }
4148
+ datadogLogs.init({ ...DEFAULTS, ...options });
4149
+ this.options = options;
4150
+ this.logger = datadogLogs.logger;
4151
+ this.ctx = {};
4152
+ }
4153
+ log() {
4154
+ let normalized = normalizeArgs(...arguments);
4155
+ this.logger.log(normalized.message, Object.assign(normalized.properties, this.ctx));
4156
+ }
4157
+ info() {
4158
+ let normalized = normalizeArgs(...arguments);
4159
+ this.logger.info(normalized.message, Object.assign(normalized.properties, this.ctx));
4160
+ }
4161
+ error() {
4162
+ let normalized = normalizeArgs(...arguments);
4163
+ this.logger.error(normalized.message, Object.assign(normalized.properties, this.ctx), normalized.error);
4164
+ }
4165
+ context(key, value) {
4166
+ if (typeof key === "string") {
4167
+ this.ctx[key] = value;
4168
+ } else if (typeof key === "object") {
4169
+ Object.assign(this.ctx, key);
4170
+ }
4171
+ return this;
4172
+ }
4173
+ }
4174
+ export {
4175
+ DatadogLogger
4176
+ };