{"version":3,"file":"main.w64_ypTi.js","sources":["../../../../../../node_modules/@datadog/browser-core/esm/tools/display.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/catchUserErrors.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/utils/numberUtils.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/utils/timeUtils.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/utils/byteUtils.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/utils/polyfills.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/utils/objectUtils.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/getGlobalObject.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/getZoneJsOriginalValue.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/monitor.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/timer.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/observable.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/utils/functionUtils.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/utils/stringUtils.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/utils/browserDetection.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/experimentalFeatures.js","../../../../../../node_modules/@datadog/browser-core/esm/browser/cookie.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/session/storeStrategies/sessionStoreStrategy.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/utils/typeUtils.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/user/user.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/session/sessionConstants.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/session/sessionStateValidation.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/session/sessionState.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/session/oldCookiesMigration.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/session/storeStrategies/sessionInCookie.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/session/storeStrategies/sessionInLocalStorage.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/session/sessionStoreOperations.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/session/sessionStore.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/trackingConsent.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/serialisation/jsonStringify.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/utils/urlPolyfill.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/configuration/intakeSites.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/configuration/endpointBuilder.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/configuration/tags.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/configuration/transportConfiguration.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/configuration/configuration.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/stackTrace/computeStackTrace.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/stackTrace/handlingStack.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/instrumentMethod.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/serialisation/sanitize.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/error/error.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/error/error.types.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/error/trackRuntimeError.js","../../../../../../node_modules/@datadog/browser-core/esm/boot/init.js","../../../../../../node_modules/@datadog/browser-core/esm/boot/displayAlreadyInitializedError.js","../../../../../../node_modules/@datadog/browser-core/esm/browser/addEventListener.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/report/reportObservable.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/sendToExtension.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/mergeInto.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/connectivity/connectivity.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/utils/arrayUtils.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/boundedBuffer.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/telemetry/rawTelemetryEvent.types.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/telemetry/telemetry.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/valueHistory.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/session/sessionManager.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/utils/responseUtils.js","../../../../../../node_modules/@datadog/browser-core/esm/transport/sendWithRetryStrategy.js","../../../../../../node_modules/@datadog/browser-core/esm/transport/httpRequest.js","../../../../../../node_modules/@datadog/browser-core/esm/transport/eventBridge.js","../../../../../../node_modules/@datadog/browser-core/esm/browser/pageExitObservable.js","../../../../../../node_modules/@datadog/browser-core/esm/transport/batch.js","../../../../../../node_modules/@datadog/browser-core/esm/transport/flushController.js","../../../../../../node_modules/@datadog/browser-core/esm/transport/startBatchWithReplica.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/encoder.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/abstractLifeCycle.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/eventRateLimiter/createEventRateLimiter.js","../../../../../../node_modules/@datadog/browser-core/esm/browser/runOnReadyState.js","../../../../../../node_modules/@datadog/browser-core/esm/browser/xhrObservable.js","../../../../../../node_modules/@datadog/browser-core/esm/browser/fetchObservable.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/requestIdleCallback.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/taskQueue.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/console/consoleObservable.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/context/contextManager.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/context/storeContextManager.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/context/customerDataTracker.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/readBytesFromStream.js","../../../../../../node_modules/@datadog/browser-core/esm/domain/synthetics/syntheticsWorkerValues.js","../../../../../../node_modules/@datadog/browser-core/esm/tools/matchOption.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/contexts/commonContext.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/vital/vitalCollection.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/browser/crypto.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/tracing/identifier.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/tracing/sampler.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/tracing/tracer.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/configuration/configuration.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/configuration/remoteConfiguration.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/plugins.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/boot/preStartRum.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/boot/rumPublicApi.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/browser/domMutationObservable.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/browser/windowOpenObservable.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/contexts/syntheticsContext.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/limitModification.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/assembly.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/contexts/internalContext.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/lifeCycle.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/contexts/viewHistory.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/resource/resourceUtils.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/requestCollection.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/discardNegativeDuration.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/trackEventCounts.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/browser/firstInputPolyfill.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/browser/performanceObservable.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/waitPageActivityEnd.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/browser/polyfills.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/browser/htmlDomUtils.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/privacy.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/action/getActionNameFromElement.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/getSelectorFromElement.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/action/clickChain.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/action/listenActionEvents.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/action/computeFrustration.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/action/interactionSelectorCache.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/action/trackClickActions.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/action/actionCollection.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/error/trackConsoleError.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/error/trackReportError.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/error/errorCollection.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/longTask/longTaskCollection.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/resource/matchRequestResourceEntry.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/tracing/getDocumentTraceId.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/browser/performanceUtils.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/resource/retrieveInitialDocumentResourceTiming.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/resource/resourceCollection.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/view/trackViewEventCounts.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackFirstContentfulPaint.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackFirstInput.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackNavigationTimings.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackLargestContentfulPaint.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackFirstHidden.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackInitialViewMetrics.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackCumulativeLayoutShift.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/interactionCountPolyfill.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackInteractionToNextPaint.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackLoadingTime.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/browser/scroll.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/browser/viewportObservable.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackScrollMetrics.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/view/viewMetrics/trackCommonViewMetrics.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/view/trackViews.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/view/viewCollection.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/rumSessionManager.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/transport/startRumBatch.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/transport/startRumEventBridge.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/contexts/urlContexts.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/browser/locationChangeObservable.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/contexts/featureFlagContext.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/startCustomerDataTelemetry.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/contexts/pageStateHistory.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/contexts/displayContext.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/browser/cookieObservable.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/contexts/ciVisibilityContext.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/longAnimationFrame/longAnimationFrameCollection.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/boot/startRum.js","../../../../../../node_modules/@datadog/browser-rum-core/esm/domain/getSessionReplayUrl.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/replayStats.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/serialization/serializationUtils.js","../../../../../../node_modules/@datadog/browser-rum/esm/types/sessionReplayConstants.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/serialization/serializeStyleSheets.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/serialization/serializeAttribute.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/serialization/serializeAttributes.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/serialization/serializeNode.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/serialization/serializeDocument.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/eventsUtils.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/viewports.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/assembly.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackMove.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackMouseInteraction.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackScroll.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackViewportResize.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackMediaInteraction.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackStyleSheet.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackFocus.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackFrustration.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackViewEnd.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackInput.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/mutationBatch.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/trackers/trackMutation.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/elementsScrollPositions.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/shadowRootsController.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/startFullSnapshots.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/recordIds.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/record/record.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/segmentCollection/buildReplayPayload.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/segmentCollection/segment.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/segmentCollection/segmentCollection.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/startRecordBridge.js","../../../../../../node_modules/@datadog/browser-rum/esm/boot/startRecording.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/deflate/deflateEncoder.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/deflate/deflateWorker.js","../../../../../../node_modules/@datadog/browser-rum/esm/boot/isBrowserSupported.js","../../../../../../node_modules/@datadog/browser-rum/esm/domain/getSessionReplayLink.js","../../../../../../node_modules/@datadog/browser-rum/esm/boot/postStartStrategy.js","../../../../../../node_modules/@datadog/browser-rum/esm/boot/preStartStrategy.js","../../../../../../node_modules/@datadog/browser-rum/esm/boot/recorderApi.js","../../../../../../node_modules/@datadog/browser-rum/esm/entries/main.js"],"sourcesContent":["/* eslint-disable local-rules/disallow-side-effects */\n/**\n * Keep references on console methods to avoid triggering patched behaviors\n *\n * NB: in some setup, console could already be patched by another SDK.\n * In this case, some display messages can be sent by the other SDK\n * but we should be safe from infinite loop nonetheless.\n */\nexport var ConsoleApiName = {\n log: 'log',\n debug: 'debug',\n info: 'info',\n warn: 'warn',\n error: 'error',\n};\n/**\n * When building JS bundles, some users might use a plugin[1] or configuration[2] to remove\n * \"console.*\" references. This causes some issue as we expect `console.*` to be defined.\n * As a workaround, let's use a variable alias, so those expressions won't be taken into account by\n * simple static analysis.\n *\n * [1]: https://babeljs.io/docs/babel-plugin-transform-remove-console/\n * [2]: https://github.com/terser/terser#compress-options (look for drop_console)\n */\nexport var globalConsole = console;\nexport var originalConsoleMethods = {};\nObject.keys(ConsoleApiName).forEach(function (name) {\n originalConsoleMethods[name] = globalConsole[name];\n});\nvar PREFIX = 'Datadog Browser SDK:';\nexport var display = {\n debug: originalConsoleMethods.debug.bind(globalConsole, PREFIX),\n log: originalConsoleMethods.log.bind(globalConsole, PREFIX),\n info: originalConsoleMethods.info.bind(globalConsole, PREFIX),\n warn: originalConsoleMethods.warn.bind(globalConsole, PREFIX),\n error: originalConsoleMethods.error.bind(globalConsole, PREFIX),\n};\nexport var DOCS_ORIGIN = 'https://docs.datadoghq.com';\nexport var DOCS_TROUBLESHOOTING = \"\".concat(DOCS_ORIGIN, \"/real_user_monitoring/browser/troubleshooting\");\nexport var MORE_DETAILS = 'More details:';\n//# sourceMappingURL=display.js.map","import { display } from './display';\nexport function catchUserErrors(fn, errorMsg) {\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n try {\n return fn.apply(void 0, args);\n }\n catch (err) {\n display.error(errorMsg, err);\n }\n };\n}\n//# sourceMappingURL=catchUserErrors.js.map","/**\n * Return true if the draw is successful\n * @param threshold between 0 and 100\n */\nexport function performDraw(threshold) {\n return threshold !== 0 && Math.random() * 100 <= threshold;\n}\nexport function round(num, decimals) {\n return +num.toFixed(decimals);\n}\nexport function isPercentage(value) {\n return isNumber(value) && value >= 0 && value <= 100;\n}\nexport function isNumber(value) {\n return typeof value === 'number';\n}\n//# sourceMappingURL=numberUtils.js.map","import { isNumber, round } from './numberUtils';\nexport var ONE_SECOND = 1000;\nexport var ONE_MINUTE = 60 * ONE_SECOND;\nexport var ONE_HOUR = 60 * ONE_MINUTE;\nexport var ONE_DAY = 24 * ONE_HOUR;\nexport var ONE_YEAR = 365 * ONE_DAY;\nexport function relativeToClocks(relative) {\n return { relative: relative, timeStamp: getCorrectedTimeStamp(relative) };\n}\nexport function timeStampToClocks(timeStamp) {\n return { relative: getRelativeTime(timeStamp), timeStamp: timeStamp };\n}\nfunction getCorrectedTimeStamp(relativeTime) {\n var correctedOrigin = (dateNow() - performance.now());\n // apply correction only for positive drift\n if (correctedOrigin > getNavigationStart()) {\n return Math.round(addDuration(correctedOrigin, relativeTime));\n }\n return getTimeStamp(relativeTime);\n}\nexport function currentDrift() {\n return Math.round(dateNow() - addDuration(getNavigationStart(), performance.now()));\n}\nexport function toServerDuration(duration) {\n if (!isNumber(duration)) {\n return duration;\n }\n return round(duration * 1e6, 0);\n}\nexport function dateNow() {\n // Do not use `Date.now` because sometimes websites are wrongly \"polyfilling\" it. For example, we\n // had some users using a very old version of `datejs`, which patched `Date.now` to return a Date\n // instance instead of a timestamp[1]. Those users are unlikely to fix this, so let's handle this\n // case ourselves.\n // [1]: https://github.com/datejs/Datejs/blob/97f5c7c58c5bc5accdab8aa7602b6ac56462d778/src/core-debug.js#L14-L16\n return new Date().getTime();\n}\nexport function timeStampNow() {\n return dateNow();\n}\nexport function relativeNow() {\n return performance.now();\n}\nexport function clocksNow() {\n return { relative: relativeNow(), timeStamp: timeStampNow() };\n}\nexport function clocksOrigin() {\n return { relative: 0, timeStamp: getNavigationStart() };\n}\nexport function elapsed(start, end) {\n return (end - start);\n}\nexport function addDuration(a, b) {\n return a + b;\n}\n/**\n * Get the time since the navigation was started.\n *\n * Note: this does not use `performance.timeOrigin` because it doesn't seem to reflect the actual\n * time on which the navigation has started: it may be much farther in the past, at least in Firefox 71.\n * Related issue in Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=1429926\n */\nexport function getRelativeTime(timestamp) {\n return (timestamp - getNavigationStart());\n}\nexport function getTimeStamp(relativeTime) {\n return Math.round(addDuration(getNavigationStart(), relativeTime));\n}\nexport function looksLikeRelativeTime(time) {\n return time < ONE_YEAR;\n}\n/**\n * Navigation start slightly change on some rare cases\n */\nvar navigationStart;\nfunction getNavigationStart() {\n if (navigationStart === undefined) {\n navigationStart = performance.timing.navigationStart;\n }\n return navigationStart;\n}\n//# sourceMappingURL=timeUtils.js.map","export var ONE_KIBI_BYTE = 1024;\nexport var ONE_MEBI_BYTE = 1024 * ONE_KIBI_BYTE;\n// eslint-disable-next-line no-control-regex\nvar HAS_MULTI_BYTES_CHARACTERS = /[^\\u0000-\\u007F]/;\nexport function computeBytesCount(candidate) {\n // Accurate bytes count computations can degrade performances when there is a lot of events to process\n if (!HAS_MULTI_BYTES_CHARACTERS.test(candidate)) {\n return candidate.length;\n }\n if (window.TextEncoder !== undefined) {\n return new TextEncoder().encode(candidate).length;\n }\n return new Blob([candidate]).size;\n}\nexport function concatBuffers(buffers) {\n var length = buffers.reduce(function (total, buffer) { return total + buffer.length; }, 0);\n var result = new Uint8Array(length);\n var offset = 0;\n for (var _i = 0, buffers_1 = buffers; _i < buffers_1.length; _i++) {\n var buffer = buffers_1[_i];\n result.set(buffer, offset);\n offset += buffer.length;\n }\n return result;\n}\n//# sourceMappingURL=byteUtils.js.map","export function includes(candidate, search) {\n return candidate.indexOf(search) !== -1;\n}\nexport function arrayFrom(arrayLike) {\n if (Array.from) {\n return Array.from(arrayLike);\n }\n var array = [];\n if (arrayLike instanceof Set) {\n arrayLike.forEach(function (item) { return array.push(item); });\n }\n else {\n for (var i = 0; i < arrayLike.length; i++) {\n array.push(arrayLike[i]);\n }\n }\n return array;\n}\nexport function find(array, predicate) {\n for (var i = 0; i < array.length; i += 1) {\n var item = array[i];\n if (predicate(item, i)) {\n return item;\n }\n }\n return undefined;\n}\nexport function findLast(array, predicate) {\n for (var i = array.length - 1; i >= 0; i -= 1) {\n var item = array[i];\n if (predicate(item, i, array)) {\n return item;\n }\n }\n return undefined;\n}\nexport function forEach(list, callback) {\n Array.prototype.forEach.call(list, callback);\n}\nexport function objectValues(object) {\n return Object.keys(object).map(function (key) { return object[key]; });\n}\nexport function objectEntries(object) {\n return Object.keys(object).map(function (key) { return [key, object[key]]; });\n}\nexport function startsWith(candidate, search) {\n return candidate.slice(0, search.length) === search;\n}\nexport function endsWith(candidate, search) {\n return candidate.slice(-search.length) === search;\n}\nexport function assign(target) {\n var toAssign = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n toAssign[_i - 1] = arguments[_i];\n }\n toAssign.forEach(function (source) {\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n });\n return target;\n}\n//# sourceMappingURL=polyfills.js.map","import { assign } from './polyfills';\nexport function shallowClone(object) {\n return assign({}, object);\n}\nexport function objectHasValue(object, value) {\n return Object.keys(object).some(function (key) { return object[key] === value; });\n}\nexport function isEmptyObject(object) {\n return Object.keys(object).length === 0;\n}\nexport function mapValues(object, fn) {\n var newObject = {};\n for (var _i = 0, _a = Object.keys(object); _i < _a.length; _i++) {\n var key = _a[_i];\n newObject[key] = fn(object[key]);\n }\n return newObject;\n}\n//# sourceMappingURL=objectUtils.js.map","/**\n * inspired by https://mathiasbynens.be/notes/globalthis\n */\nexport function getGlobalObject() {\n if (typeof globalThis === 'object') {\n return globalThis;\n }\n Object.defineProperty(Object.prototype, '_dd_temp_', {\n get: function () {\n return this;\n },\n configurable: true,\n });\n // @ts-ignore _dd_temp is defined using defineProperty\n var globalObject = _dd_temp_;\n // @ts-ignore _dd_temp is defined using defineProperty\n delete Object.prototype._dd_temp_;\n if (typeof globalObject !== 'object') {\n // on safari _dd_temp_ is available on window but not globally\n // fallback on other browser globals check\n if (typeof self === 'object') {\n globalObject = self;\n }\n else if (typeof window === 'object') {\n globalObject = window;\n }\n else {\n globalObject = {};\n }\n }\n return globalObject;\n}\n//# sourceMappingURL=getGlobalObject.js.map","import { getGlobalObject } from './getGlobalObject';\n/**\n * Gets the original value for a DOM API that was potentially patched by Zone.js.\n *\n * Zone.js[1] is a library that patches a bunch of JS and DOM APIs. It usually stores the original\n * value of the patched functions/constructors/methods in a hidden property prefixed by\n * __zone_symbol__.\n *\n * In multiple occasions, we observed that Zone.js is the culprit of important issues leading to\n * browser resource exhaustion (memory leak, high CPU usage). This method is used as a workaround to\n * use the original DOM API instead of the one patched by Zone.js.\n *\n * [1]: https://github.com/angular/angular/tree/main/packages/zone.js\n */\nexport function getZoneJsOriginalValue(target, name) {\n var browserWindow = getGlobalObject();\n var original;\n if (browserWindow.Zone && typeof browserWindow.Zone.__symbol__ === 'function') {\n original = target[browserWindow.Zone.__symbol__(name)];\n }\n if (!original) {\n original = target[name];\n }\n return original;\n}\n//# sourceMappingURL=getZoneJsOriginalValue.js.map","var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { display } from './display';\nvar onMonitorErrorCollected;\nvar debugMode = false;\nexport function startMonitorErrorCollection(newOnMonitorErrorCollected) {\n onMonitorErrorCollected = newOnMonitorErrorCollected;\n}\nexport function setDebugMode(newDebugMode) {\n debugMode = newDebugMode;\n}\nexport function resetMonitor() {\n onMonitorErrorCollected = undefined;\n debugMode = false;\n}\nexport function monitored(_, __, descriptor) {\n var originalMethod = descriptor.value;\n descriptor.value = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var decorated = onMonitorErrorCollected ? monitor(originalMethod) : originalMethod;\n return decorated.apply(this, args);\n };\n}\nexport function monitor(fn) {\n return function () {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return callMonitored(fn, this, arguments);\n }; // consider output type has input type\n}\nexport function callMonitored(fn, context, args) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return fn.apply(context, args);\n }\n catch (e) {\n displayIfDebugEnabled(e);\n if (onMonitorErrorCollected) {\n try {\n onMonitorErrorCollected(e);\n }\n catch (e) {\n displayIfDebugEnabled(e);\n }\n }\n }\n}\nexport function displayIfDebugEnabled() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n if (debugMode) {\n display.error.apply(display, __spreadArray(['[MONITOR]'], args, false));\n }\n}\n//# sourceMappingURL=monitor.js.map","import { getZoneJsOriginalValue } from './getZoneJsOriginalValue';\nimport { monitor } from './monitor';\nimport { getGlobalObject } from './getGlobalObject';\nexport function setTimeout(callback, delay) {\n return getZoneJsOriginalValue(getGlobalObject(), 'setTimeout')(monitor(callback), delay);\n}\nexport function clearTimeout(timeoutId) {\n getZoneJsOriginalValue(getGlobalObject(), 'clearTimeout')(timeoutId);\n}\nexport function setInterval(callback, delay) {\n return getZoneJsOriginalValue(getGlobalObject(), 'setInterval')(monitor(callback), delay);\n}\nexport function clearInterval(timeoutId) {\n getZoneJsOriginalValue(getGlobalObject(), 'clearInterval')(timeoutId);\n}\n//# sourceMappingURL=timer.js.map","// eslint-disable-next-line no-restricted-syntax\nvar Observable = /** @class */ (function () {\n function Observable(onFirstSubscribe) {\n this.onFirstSubscribe = onFirstSubscribe;\n this.observers = [];\n }\n Observable.prototype.subscribe = function (f) {\n var _this = this;\n this.observers.push(f);\n if (this.observers.length === 1 && this.onFirstSubscribe) {\n this.onLastUnsubscribe = this.onFirstSubscribe(this) || undefined;\n }\n return {\n unsubscribe: function () {\n _this.observers = _this.observers.filter(function (other) { return f !== other; });\n if (!_this.observers.length && _this.onLastUnsubscribe) {\n _this.onLastUnsubscribe();\n }\n },\n };\n };\n Observable.prototype.notify = function (data) {\n this.observers.forEach(function (observer) { return observer(data); });\n };\n return Observable;\n}());\nexport { Observable };\nexport function mergeObservables() {\n var observables = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n observables[_i] = arguments[_i];\n }\n return new Observable(function (globalObservable) {\n var subscriptions = observables.map(function (observable) {\n return observable.subscribe(function (data) { return globalObservable.notify(data); });\n });\n return function () { return subscriptions.forEach(function (subscription) { return subscription.unsubscribe(); }); };\n });\n}\n//# sourceMappingURL=observable.js.map","import { setTimeout, clearTimeout } from '../timer';\n// use lodash API\nexport function throttle(fn, wait, options) {\n var needLeadingExecution = options && options.leading !== undefined ? options.leading : true;\n var needTrailingExecution = options && options.trailing !== undefined ? options.trailing : true;\n var inWaitPeriod = false;\n var pendingExecutionWithParameters;\n var pendingTimeoutId;\n return {\n throttled: function () {\n var parameters = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n parameters[_i] = arguments[_i];\n }\n if (inWaitPeriod) {\n pendingExecutionWithParameters = parameters;\n return;\n }\n if (needLeadingExecution) {\n fn.apply(void 0, parameters);\n }\n else {\n pendingExecutionWithParameters = parameters;\n }\n inWaitPeriod = true;\n pendingTimeoutId = setTimeout(function () {\n if (needTrailingExecution && pendingExecutionWithParameters) {\n fn.apply(void 0, pendingExecutionWithParameters);\n }\n inWaitPeriod = false;\n pendingExecutionWithParameters = undefined;\n }, wait);\n },\n cancel: function () {\n clearTimeout(pendingTimeoutId);\n inWaitPeriod = false;\n pendingExecutionWithParameters = undefined;\n },\n };\n}\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nexport function noop() { }\n//# sourceMappingURL=functionUtils.js.map","/**\n * UUID v4\n * from https://gist.github.com/jed/982883\n */\nexport function generateUUID(placeholder) {\n return placeholder\n ? // eslint-disable-next-line no-bitwise\n (parseInt(placeholder, 10) ^ ((Math.random() * 16) >> (parseInt(placeholder, 10) / 4))).toString(16)\n : \"\".concat(1e7, \"-\").concat(1e3, \"-\").concat(4e3, \"-\").concat(8e3, \"-\").concat(1e11).replace(/[018]/g, generateUUID);\n}\nvar COMMA_SEPARATED_KEY_VALUE = /([\\w-]+)\\s*=\\s*([^;]+)/g;\nexport function findCommaSeparatedValue(rawString, name) {\n COMMA_SEPARATED_KEY_VALUE.lastIndex = 0;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n var match = COMMA_SEPARATED_KEY_VALUE.exec(rawString);\n if (match) {\n if (match[1] === name) {\n return match[2];\n }\n }\n else {\n break;\n }\n }\n}\nexport function findCommaSeparatedValues(rawString) {\n var result = new Map();\n COMMA_SEPARATED_KEY_VALUE.lastIndex = 0;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n var match = COMMA_SEPARATED_KEY_VALUE.exec(rawString);\n if (match) {\n result.set(match[1], match[2]);\n }\n else {\n break;\n }\n }\n return result;\n}\nexport function safeTruncate(candidate, length, suffix) {\n if (suffix === void 0) { suffix = ''; }\n var lastChar = candidate.charCodeAt(length - 1);\n var isLastCharSurrogatePair = lastChar >= 0xd800 && lastChar <= 0xdbff;\n var correctedLength = isLastCharSurrogatePair ? length + 1 : length;\n if (candidate.length <= correctedLength) {\n return candidate;\n }\n return \"\".concat(candidate.slice(0, correctedLength)).concat(suffix);\n}\n//# sourceMappingURL=stringUtils.js.map","export function isIE() {\n return detectBrowserCached() === 0 /* Browser.IE */;\n}\nexport function isChromium() {\n return detectBrowserCached() === 1 /* Browser.CHROMIUM */;\n}\nexport function isSafari() {\n return detectBrowserCached() === 2 /* Browser.SAFARI */;\n}\nvar browserCache;\nfunction detectBrowserCached() {\n return browserCache !== null && browserCache !== void 0 ? browserCache : (browserCache = detectBrowser());\n}\n// Exported only for tests\nexport function detectBrowser(browserWindow) {\n var _a;\n if (browserWindow === void 0) { browserWindow = window; }\n var userAgent = browserWindow.navigator.userAgent;\n if (browserWindow.chrome || /HeadlessChrome/.test(userAgent)) {\n return 1 /* Browser.CHROMIUM */;\n }\n if (\n // navigator.vendor is deprecated, but it is the most resilient way we found to detect\n // \"Apple maintained browsers\" (AKA Safari). If one day it gets removed, we still have the\n // useragent test as a semi-working fallback.\n ((_a = browserWindow.navigator.vendor) === null || _a === void 0 ? void 0 : _a.indexOf('Apple')) === 0 ||\n (/safari/i.test(userAgent) && !/chrome|android/i.test(userAgent))) {\n return 2 /* Browser.SAFARI */;\n }\n if (browserWindow.document.documentMode) {\n return 0 /* Browser.IE */;\n }\n return 3 /* Browser.OTHER */;\n}\n//# sourceMappingURL=browserDetection.js.map","/**\n * LIMITATION:\n * For NPM setup, this feature flag singleton is shared between RUM and Logs product.\n * This means that an experimental flag set on the RUM product will be set on the Logs product.\n * So keep in mind that in certain configurations, your experimental feature flag may affect other products.\n *\n * FORMAT:\n * All feature flags should be snake_cased\n */\n// We want to use a real enum (i.e. not a const enum) here, to be able to check whether an arbitrary\n// string is an expected feature flag\nimport { objectHasValue } from './utils/objectUtils';\n// eslint-disable-next-line no-restricted-syntax\nexport var ExperimentalFeature;\n(function (ExperimentalFeature) {\n ExperimentalFeature[\"WRITABLE_RESOURCE_GRAPHQL\"] = \"writable_resource_graphql\";\n ExperimentalFeature[\"REMOTE_CONFIGURATION\"] = \"remote_configuration\";\n ExperimentalFeature[\"LONG_ANIMATION_FRAME\"] = \"long_animation_frame\";\n ExperimentalFeature[\"ANONYMOUS_USER_TRACKING\"] = \"anonymous_user_tracking\";\n ExperimentalFeature[\"ACTION_NAME_MASKING\"] = \"action_name_masking\";\n ExperimentalFeature[\"CONSISTENT_TRACE_SAMPLING\"] = \"consistent_trace_sampling\";\n ExperimentalFeature[\"DELAY_VIEWPORT_COLLECTION\"] = \"delay_viewport_collection\";\n})(ExperimentalFeature || (ExperimentalFeature = {}));\nvar enabledExperimentalFeatures = new Set();\nexport function initFeatureFlags(enableExperimentalFeatures) {\n if (Array.isArray(enableExperimentalFeatures)) {\n addExperimentalFeatures(enableExperimentalFeatures.filter(function (flag) {\n return objectHasValue(ExperimentalFeature, flag);\n }));\n }\n}\nexport function addExperimentalFeatures(enabledFeatures) {\n enabledFeatures.forEach(function (flag) {\n enabledExperimentalFeatures.add(flag);\n });\n}\nexport function isExperimentalFeatureEnabled(featureName) {\n return enabledExperimentalFeatures.has(featureName);\n}\nexport function resetExperimentalFeatures() {\n enabledExperimentalFeatures.clear();\n}\nexport function getExperimentalFeatures() {\n return enabledExperimentalFeatures;\n}\n//# sourceMappingURL=experimentalFeatures.js.map","import { display } from '../tools/display';\nimport { ONE_MINUTE, ONE_SECOND } from '../tools/utils/timeUtils';\nimport { findCommaSeparatedValue, findCommaSeparatedValues, generateUUID } from '../tools/utils/stringUtils';\nexport function setCookie(name, value, expireDelay, options) {\n if (expireDelay === void 0) { expireDelay = 0; }\n var date = new Date();\n date.setTime(date.getTime() + expireDelay);\n var expires = \"expires=\".concat(date.toUTCString());\n var sameSite = options && options.crossSite ? 'none' : 'strict';\n var domain = options && options.domain ? \";domain=\".concat(options.domain) : '';\n var secure = options && options.secure ? ';secure' : '';\n var partitioned = options && options.partitioned ? ';partitioned' : '';\n document.cookie = \"\".concat(name, \"=\").concat(value, \";\").concat(expires, \";path=/;samesite=\").concat(sameSite).concat(domain).concat(secure).concat(partitioned);\n}\nexport function getCookie(name) {\n return findCommaSeparatedValue(document.cookie, name);\n}\nvar initCookieParsed;\n/**\n * Returns a cached value of the cookie. Use this during SDK initialization (and whenever possible)\n * to avoid accessing document.cookie multiple times.\n */\nexport function getInitCookie(name) {\n if (!initCookieParsed) {\n initCookieParsed = findCommaSeparatedValues(document.cookie);\n }\n return initCookieParsed.get(name);\n}\nexport function resetInitCookies() {\n initCookieParsed = undefined;\n}\nexport function deleteCookie(name, options) {\n setCookie(name, '', 0, options);\n}\nexport function areCookiesAuthorized(options) {\n if (document.cookie === undefined || document.cookie === null) {\n return false;\n }\n try {\n // Use a unique cookie name to avoid issues when the SDK is initialized multiple times during\n // the test cookie lifetime\n var testCookieName = \"dd_cookie_test_\".concat(generateUUID());\n var testCookieValue = 'test';\n setCookie(testCookieName, testCookieValue, ONE_MINUTE, options);\n var isCookieCorrectlySet = getCookie(testCookieName) === testCookieValue;\n deleteCookie(testCookieName, options);\n return isCookieCorrectlySet;\n }\n catch (error) {\n display.error(error);\n return false;\n }\n}\n/**\n * No API to retrieve it, number of levels for subdomain and suffix are unknown\n * strategy: find the minimal domain on which cookies are allowed to be set\n * https://web.dev/same-site-same-origin/#site\n */\nvar getCurrentSiteCache;\nexport function getCurrentSite() {\n if (getCurrentSiteCache === undefined) {\n // Use a unique cookie name to avoid issues when the SDK is initialized multiple times during\n // the test cookie lifetime\n var testCookieName = \"dd_site_test_\".concat(generateUUID());\n var testCookieValue = 'test';\n var domainLevels = window.location.hostname.split('.');\n var candidateDomain = domainLevels.pop();\n while (domainLevels.length && !getCookie(testCookieName)) {\n candidateDomain = \"\".concat(domainLevels.pop(), \".\").concat(candidateDomain);\n setCookie(testCookieName, testCookieValue, ONE_SECOND, { domain: candidateDomain });\n }\n deleteCookie(testCookieName, { domain: candidateDomain });\n getCurrentSiteCache = candidateDomain;\n }\n return getCurrentSiteCache;\n}\n//# sourceMappingURL=cookie.js.map","export var SESSION_STORE_KEY = '_dd_s';\n//# sourceMappingURL=sessionStoreStrategy.js.map","/**\n * Similar to `typeof`, but distinguish plain objects from `null` and arrays\n */\nexport function getType(value) {\n if (value === null) {\n return 'null';\n }\n if (Array.isArray(value)) {\n return 'array';\n }\n return typeof value;\n}\n//# sourceMappingURL=typeUtils.js.map","import { display } from '../../tools/display';\nimport { getType } from '../../tools/utils/typeUtils';\nimport { assign } from '../../tools/utils/polyfills';\n/**\n * Clone input data and ensure known user properties (id, name, email)\n * are strings, as defined here:\n * https://docs.datadoghq.com/logs/log_configuration/attributes_naming_convention/#user-related-attributes\n */\nexport function sanitizeUser(newUser) {\n // We shallow clone only to prevent mutation of user data.\n var user = assign({}, newUser);\n var keys = ['id', 'name', 'email'];\n keys.forEach(function (key) {\n if (key in user) {\n /* eslint-disable @typescript-eslint/no-base-to-string */\n user[key] = String(user[key]);\n }\n });\n return user;\n}\n/**\n * Simple check to ensure user is valid\n */\nexport function checkUser(newUser) {\n var isValid = getType(newUser) === 'object';\n if (!isValid) {\n display.error('Unsupported user:', newUser);\n }\n return isValid;\n}\nexport function generateAnonymousId() {\n return Math.floor(Math.random() * Math.pow(2, 53)).toString(36);\n}\n//# sourceMappingURL=user.js.map","import { ONE_HOUR, ONE_MINUTE, ONE_YEAR } from '../../tools/utils/timeUtils';\nexport var SESSION_TIME_OUT_DELAY = 4 * ONE_HOUR;\nexport var SESSION_EXPIRATION_DELAY = 15 * ONE_MINUTE;\nexport var SESSION_COOKIE_EXPIRATION_DELAY = ONE_YEAR;\nexport var SessionPersistence = {\n COOKIE: 'cookie',\n LOCAL_STORAGE: 'local-storage',\n};\n//# sourceMappingURL=sessionConstants.js.map","export var SESSION_ENTRY_REGEXP = /^([a-zA-Z]+)=([a-z0-9-]+)$/;\nexport var SESSION_ENTRY_SEPARATOR = '&';\nexport function isValidSessionString(sessionString) {\n return (!!sessionString &&\n (sessionString.indexOf(SESSION_ENTRY_SEPARATOR) !== -1 || SESSION_ENTRY_REGEXP.test(sessionString)));\n}\n//# sourceMappingURL=sessionStateValidation.js.map","import { ExperimentalFeature, isExperimentalFeatureEnabled } from '../../tools/experimentalFeatures';\nimport { isEmptyObject } from '../../tools/utils/objectUtils';\nimport { objectEntries } from '../../tools/utils/polyfills';\nimport { dateNow } from '../../tools/utils/timeUtils';\nimport { generateAnonymousId } from '../user';\nimport { SESSION_EXPIRATION_DELAY, SESSION_TIME_OUT_DELAY } from './sessionConstants';\nimport { isValidSessionString, SESSION_ENTRY_REGEXP, SESSION_ENTRY_SEPARATOR } from './sessionStateValidation';\nexport var EXPIRED = '1';\nexport function getExpiredSessionState(previousSessionState) {\n var expiredSessionState = {\n isExpired: EXPIRED,\n };\n if (isExperimentalFeatureEnabled(ExperimentalFeature.ANONYMOUS_USER_TRACKING)) {\n if (previousSessionState === null || previousSessionState === void 0 ? void 0 : previousSessionState.anonymousId) {\n expiredSessionState.anonymousId = previousSessionState === null || previousSessionState === void 0 ? void 0 : previousSessionState.anonymousId;\n }\n else {\n expiredSessionState.anonymousId = generateAnonymousId();\n }\n }\n return expiredSessionState;\n}\nexport function isSessionInNotStartedState(session) {\n return isEmptyObject(session);\n}\nexport function isSessionStarted(session) {\n return !isSessionInNotStartedState(session);\n}\nexport function isSessionInExpiredState(session) {\n return session.isExpired !== undefined || !isActiveSession(session);\n}\n// An active session is a session in either `Tracked` or `NotTracked` state\nfunction isActiveSession(sessionState) {\n // created and expire can be undefined for versions which was not storing them\n // these checks could be removed when older versions will not be available/live anymore\n return ((sessionState.created === undefined || dateNow() - Number(sessionState.created) < SESSION_TIME_OUT_DELAY) &&\n (sessionState.expire === undefined || dateNow() < Number(sessionState.expire)));\n}\nexport function expandSessionState(session) {\n session.expire = String(dateNow() + SESSION_EXPIRATION_DELAY);\n}\nexport function toSessionString(session) {\n return (objectEntries(session)\n // we use `aid` as a key for anonymousId\n .map(function (_a) {\n var key = _a[0], value = _a[1];\n return (key === 'anonymousId' ? \"aid=\".concat(value) : \"\".concat(key, \"=\").concat(value));\n })\n .join(SESSION_ENTRY_SEPARATOR));\n}\nexport function toSessionState(sessionString) {\n var session = {};\n if (isValidSessionString(sessionString)) {\n sessionString.split(SESSION_ENTRY_SEPARATOR).forEach(function (entry) {\n var matches = SESSION_ENTRY_REGEXP.exec(entry);\n if (matches !== null) {\n var key = matches[1], value = matches[2];\n if (key === 'aid') {\n // we use `aid` as a key for anonymousId\n session.anonymousId = value;\n }\n else {\n session[key] = value;\n }\n }\n });\n }\n return session;\n}\n//# sourceMappingURL=sessionState.js.map","import { getInitCookie } from '../../browser/cookie';\nimport { SESSION_STORE_KEY } from './storeStrategies/sessionStoreStrategy';\nimport { expandSessionState, isSessionStarted } from './sessionState';\nexport var OLD_SESSION_COOKIE_NAME = '_dd';\nexport var OLD_RUM_COOKIE_NAME = '_dd_r';\nexport var OLD_LOGS_COOKIE_NAME = '_dd_l';\n// duplicate values to avoid dependency issues\nexport var RUM_SESSION_KEY = 'rum';\nexport var LOGS_SESSION_KEY = 'logs';\n/**\n * This migration should remain in the codebase as long as older versions are available/live\n * to allow older sdk versions to be upgraded to newer versions without compatibility issues.\n */\nexport function tryOldCookiesMigration(cookieStoreStrategy) {\n var sessionString = getInitCookie(SESSION_STORE_KEY);\n if (!sessionString) {\n var oldSessionId = getInitCookie(OLD_SESSION_COOKIE_NAME);\n var oldRumType = getInitCookie(OLD_RUM_COOKIE_NAME);\n var oldLogsType = getInitCookie(OLD_LOGS_COOKIE_NAME);\n var session = {};\n if (oldSessionId) {\n session.id = oldSessionId;\n }\n if (oldLogsType && /^[01]$/.test(oldLogsType)) {\n session[LOGS_SESSION_KEY] = oldLogsType;\n }\n if (oldRumType && /^[012]$/.test(oldRumType)) {\n session[RUM_SESSION_KEY] = oldRumType;\n }\n if (isSessionStarted(session)) {\n expandSessionState(session);\n cookieStoreStrategy.persistSession(session);\n }\n }\n}\n//# sourceMappingURL=oldCookiesMigration.js.map","import { isChromium } from '../../../tools/utils/browserDetection';\nimport { ExperimentalFeature, isExperimentalFeatureEnabled } from '../../../tools/experimentalFeatures';\nimport { getCurrentSite, areCookiesAuthorized, getCookie, setCookie } from '../../../browser/cookie';\nimport { tryOldCookiesMigration } from '../oldCookiesMigration';\nimport { SESSION_COOKIE_EXPIRATION_DELAY, SESSION_EXPIRATION_DELAY, SESSION_TIME_OUT_DELAY, SessionPersistence, } from '../sessionConstants';\nimport { toSessionString, toSessionState, getExpiredSessionState } from '../sessionState';\nimport { SESSION_STORE_KEY } from './sessionStoreStrategy';\nexport function selectCookieStrategy(initConfiguration) {\n var cookieOptions = buildCookieOptions(initConfiguration);\n return areCookiesAuthorized(cookieOptions) ? { type: SessionPersistence.COOKIE, cookieOptions: cookieOptions } : undefined;\n}\nexport function initCookieStrategy(cookieOptions) {\n var cookieStore = {\n /**\n * Lock strategy allows mitigating issues due to concurrent access to cookie.\n * This issue concerns only chromium browsers and enabling this on firefox increases cookie write failures.\n */\n isLockEnabled: isChromium(),\n persistSession: persistSessionCookie(cookieOptions),\n retrieveSession: retrieveSessionCookie,\n expireSession: function (sessionState) { return expireSessionCookie(cookieOptions, sessionState); },\n };\n tryOldCookiesMigration(cookieStore);\n return cookieStore;\n}\nfunction persistSessionCookie(options) {\n return function (session) {\n setCookie(SESSION_STORE_KEY, toSessionString(session), SESSION_EXPIRATION_DELAY, options);\n };\n}\nfunction expireSessionCookie(options, sessionState) {\n var expiredSessionState = getExpiredSessionState(sessionState);\n setCookie(SESSION_STORE_KEY, toSessionString(expiredSessionState), isExperimentalFeatureEnabled(ExperimentalFeature.ANONYMOUS_USER_TRACKING)\n ? SESSION_COOKIE_EXPIRATION_DELAY\n : SESSION_TIME_OUT_DELAY, options);\n}\nfunction retrieveSessionCookie() {\n var sessionString = getCookie(SESSION_STORE_KEY);\n var sessionState = toSessionState(sessionString);\n return sessionState;\n}\nexport function buildCookieOptions(initConfiguration) {\n var cookieOptions = {};\n cookieOptions.secure =\n !!initConfiguration.useSecureSessionCookie ||\n !!initConfiguration.usePartitionedCrossSiteSessionCookie ||\n !!initConfiguration.useCrossSiteSessionCookie;\n cookieOptions.crossSite =\n !!initConfiguration.usePartitionedCrossSiteSessionCookie || !!initConfiguration.useCrossSiteSessionCookie;\n cookieOptions.partitioned = !!initConfiguration.usePartitionedCrossSiteSessionCookie;\n if (initConfiguration.trackSessionAcrossSubdomains) {\n cookieOptions.domain = getCurrentSite();\n }\n return cookieOptions;\n}\n//# sourceMappingURL=sessionInCookie.js.map","import { generateUUID } from '../../../tools/utils/stringUtils';\nimport { SessionPersistence } from '../sessionConstants';\nimport { toSessionString, toSessionState, getExpiredSessionState } from '../sessionState';\nimport { SESSION_STORE_KEY } from './sessionStoreStrategy';\nvar LOCAL_STORAGE_TEST_KEY = '_dd_test_';\nexport function selectLocalStorageStrategy() {\n try {\n var id = generateUUID();\n var testKey = \"\".concat(LOCAL_STORAGE_TEST_KEY).concat(id);\n localStorage.setItem(testKey, id);\n var retrievedId = localStorage.getItem(testKey);\n localStorage.removeItem(testKey);\n return id === retrievedId ? { type: SessionPersistence.LOCAL_STORAGE } : undefined;\n }\n catch (_a) {\n return undefined;\n }\n}\nexport function initLocalStorageStrategy() {\n return {\n isLockEnabled: false,\n persistSession: persistInLocalStorage,\n retrieveSession: retrieveSessionFromLocalStorage,\n expireSession: expireSessionFromLocalStorage,\n };\n}\nfunction persistInLocalStorage(sessionState) {\n localStorage.setItem(SESSION_STORE_KEY, toSessionString(sessionState));\n}\nfunction retrieveSessionFromLocalStorage() {\n var sessionString = localStorage.getItem(SESSION_STORE_KEY);\n return toSessionState(sessionString);\n}\nfunction expireSessionFromLocalStorage(previousSessionState) {\n persistInLocalStorage(getExpiredSessionState(previousSessionState));\n}\n//# sourceMappingURL=sessionInLocalStorage.js.map","import { setTimeout } from '../../tools/timer';\nimport { generateUUID } from '../../tools/utils/stringUtils';\nimport { assign } from '../../tools/utils/polyfills';\nimport { expandSessionState, isSessionInExpiredState } from './sessionState';\nexport var LOCK_RETRY_DELAY = 10;\nexport var LOCK_MAX_TRIES = 100;\nvar bufferedOperations = [];\nvar ongoingOperations;\nexport function processSessionStoreOperations(operations, sessionStoreStrategy, numberOfRetries) {\n var _a;\n if (numberOfRetries === void 0) { numberOfRetries = 0; }\n var isLockEnabled = sessionStoreStrategy.isLockEnabled, persistSession = sessionStoreStrategy.persistSession, expireSession = sessionStoreStrategy.expireSession;\n var persistWithLock = function (session) { return persistSession(assign({}, session, { lock: currentLock })); };\n var retrieveStore = function () {\n var session = sessionStoreStrategy.retrieveSession();\n var lock = session.lock;\n if (session.lock) {\n delete session.lock;\n }\n return {\n session: session,\n lock: lock,\n };\n };\n if (!ongoingOperations) {\n ongoingOperations = operations;\n }\n if (operations !== ongoingOperations) {\n bufferedOperations.push(operations);\n return;\n }\n if (isLockEnabled && numberOfRetries >= LOCK_MAX_TRIES) {\n next(sessionStoreStrategy);\n return;\n }\n var currentLock;\n var currentStore = retrieveStore();\n if (isLockEnabled) {\n // if someone has lock, retry later\n if (currentStore.lock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries);\n return;\n }\n // acquire lock\n currentLock = generateUUID();\n persistWithLock(currentStore.session);\n // if lock is not acquired, retry later\n currentStore = retrieveStore();\n if (currentStore.lock !== currentLock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries);\n return;\n }\n }\n var processedSession = operations.process(currentStore.session);\n if (isLockEnabled) {\n // if lock corrupted after process, retry later\n currentStore = retrieveStore();\n if (currentStore.lock !== currentLock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries);\n return;\n }\n }\n if (processedSession) {\n if (isSessionInExpiredState(processedSession)) {\n expireSession(processedSession);\n }\n else {\n expandSessionState(processedSession);\n if (isLockEnabled) {\n persistWithLock(processedSession);\n }\n else {\n persistSession(processedSession);\n }\n }\n }\n if (isLockEnabled) {\n // correctly handle lock around expiration would require to handle this case properly at several levels\n // since we don't have evidence of lock issues around expiration, let's just not do the corruption check for it\n if (!(processedSession && isSessionInExpiredState(processedSession))) {\n // if lock corrupted after persist, retry later\n currentStore = retrieveStore();\n if (currentStore.lock !== currentLock) {\n retryLater(operations, sessionStoreStrategy, numberOfRetries);\n return;\n }\n persistSession(currentStore.session);\n processedSession = currentStore.session;\n }\n }\n // call after even if session is not persisted in order to perform operations on\n // up-to-date session state value => the value could have been modified by another tab\n (_a = operations.after) === null || _a === void 0 ? void 0 : _a.call(operations, processedSession || currentStore.session);\n next(sessionStoreStrategy);\n}\nfunction retryLater(operations, sessionStore, currentNumberOfRetries) {\n setTimeout(function () {\n processSessionStoreOperations(operations, sessionStore, currentNumberOfRetries + 1);\n }, LOCK_RETRY_DELAY);\n}\nfunction next(sessionStore) {\n ongoingOperations = undefined;\n var nextOperations = bufferedOperations.shift();\n if (nextOperations) {\n processSessionStoreOperations(nextOperations, sessionStore);\n }\n}\n//# sourceMappingURL=sessionStoreOperations.js.map","import { clearInterval, setInterval } from '../../tools/timer';\nimport { Observable } from '../../tools/observable';\nimport { ONE_SECOND, dateNow } from '../../tools/utils/timeUtils';\nimport { throttle } from '../../tools/utils/functionUtils';\nimport { generateUUID } from '../../tools/utils/stringUtils';\nimport { assign } from '../../tools/utils/polyfills';\nimport { display } from '../../tools/display';\nimport { selectCookieStrategy, initCookieStrategy } from './storeStrategies/sessionInCookie';\nimport { getExpiredSessionState, isSessionInExpiredState, isSessionInNotStartedState, isSessionStarted, } from './sessionState';\nimport { initLocalStorageStrategy, selectLocalStorageStrategy } from './storeStrategies/sessionInLocalStorage';\nimport { processSessionStoreOperations } from './sessionStoreOperations';\nimport { SessionPersistence } from './sessionConstants';\n/**\n * Every second, the storage will be polled to check for any change that can occur\n * to the session state in another browser tab, or another window.\n * This value has been determined from our previous cookie-only implementation.\n */\nexport var STORAGE_POLL_DELAY = ONE_SECOND;\n/**\n * Selects the correct session store strategy type based on the configuration and storage\n * availability.\n */\nexport function selectSessionStoreStrategyType(initConfiguration) {\n switch (initConfiguration.sessionPersistence) {\n case SessionPersistence.COOKIE:\n return selectCookieStrategy(initConfiguration);\n case SessionPersistence.LOCAL_STORAGE:\n return selectLocalStorageStrategy();\n case undefined: {\n var sessionStoreStrategyType = selectCookieStrategy(initConfiguration);\n if (!sessionStoreStrategyType && initConfiguration.allowFallbackToLocalStorage) {\n sessionStoreStrategyType = selectLocalStorageStrategy();\n }\n return sessionStoreStrategyType;\n }\n default:\n display.error(\"Invalid session persistence '\".concat(String(initConfiguration.sessionPersistence), \"'\"));\n }\n}\n/**\n * Different session concepts:\n * - tracked, the session has an id and is updated along the user navigation\n * - not tracked, the session does not have an id but it is updated along the user navigation\n * - inactive, no session in store or session expired, waiting for a renew session\n */\nexport function startSessionStore(sessionStoreStrategyType, productKey, computeSessionState) {\n var renewObservable = new Observable();\n var expireObservable = new Observable();\n var sessionStateUpdateObservable = new Observable();\n var sessionStoreStrategy = sessionStoreStrategyType.type === SessionPersistence.COOKIE\n ? initCookieStrategy(sessionStoreStrategyType.cookieOptions)\n : initLocalStorageStrategy();\n var expireSession = sessionStoreStrategy.expireSession;\n var watchSessionTimeoutId = setInterval(watchSession, STORAGE_POLL_DELAY);\n var sessionCache;\n startSession();\n var _a = throttle(function () {\n processSessionStoreOperations({\n process: function (sessionState) {\n if (isSessionInNotStartedState(sessionState)) {\n return;\n }\n var synchronizedSession = synchronizeSession(sessionState);\n expandOrRenewSessionState(synchronizedSession);\n return synchronizedSession;\n },\n after: function (sessionState) {\n if (isSessionStarted(sessionState) && !hasSessionInCache()) {\n renewSessionInCache(sessionState);\n }\n sessionCache = sessionState;\n },\n }, sessionStoreStrategy);\n }, STORAGE_POLL_DELAY), throttledExpandOrRenewSession = _a.throttled, cancelExpandOrRenewSession = _a.cancel;\n function expandSession() {\n processSessionStoreOperations({\n process: function (sessionState) { return (hasSessionInCache() ? synchronizeSession(sessionState) : undefined); },\n }, sessionStoreStrategy);\n }\n /**\n * allows two behaviors:\n * - if the session is active, synchronize the session cache without updating the session store\n * - if the session is not active, clear the session store and expire the session cache\n */\n function watchSession() {\n processSessionStoreOperations({\n process: function (sessionState) {\n return isSessionInExpiredState(sessionState) ? getExpiredSessionState(sessionState) : undefined;\n },\n after: synchronizeSession,\n }, sessionStoreStrategy);\n }\n function synchronizeSession(sessionState) {\n if (isSessionInExpiredState(sessionState)) {\n sessionState = getExpiredSessionState(sessionState);\n }\n if (hasSessionInCache()) {\n if (isSessionInCacheOutdated(sessionState)) {\n expireSessionInCache();\n }\n else {\n sessionStateUpdateObservable.notify({ previousState: sessionCache, newState: sessionState });\n sessionCache = sessionState;\n }\n }\n return sessionState;\n }\n function startSession() {\n processSessionStoreOperations({\n process: function (sessionState) {\n if (isSessionInNotStartedState(sessionState)) {\n return getExpiredSessionState(sessionState);\n }\n },\n after: function (sessionState) {\n sessionCache = sessionState;\n },\n }, sessionStoreStrategy);\n }\n function expandOrRenewSessionState(sessionState) {\n if (isSessionInNotStartedState(sessionState)) {\n return false;\n }\n var _a = computeSessionState(sessionState[productKey]), trackingType = _a.trackingType, isTracked = _a.isTracked;\n sessionState[productKey] = trackingType;\n delete sessionState.isExpired;\n if (isTracked && !sessionState.id) {\n sessionState.id = generateUUID();\n sessionState.created = String(dateNow());\n }\n }\n function hasSessionInCache() {\n return sessionCache[productKey] !== undefined;\n }\n function isSessionInCacheOutdated(sessionState) {\n return sessionCache.id !== sessionState.id || sessionCache[productKey] !== sessionState[productKey];\n }\n function expireSessionInCache() {\n sessionCache = getExpiredSessionState(sessionCache);\n expireObservable.notify();\n }\n function renewSessionInCache(sessionState) {\n sessionCache = sessionState;\n renewObservable.notify();\n }\n function updateSessionState(partialSessionState) {\n processSessionStoreOperations({\n process: function (sessionState) { return assign({}, sessionState, partialSessionState); },\n after: synchronizeSession,\n }, sessionStoreStrategy);\n }\n return {\n expandOrRenewSession: throttledExpandOrRenewSession,\n expandSession: expandSession,\n getSession: function () { return sessionCache; },\n renewObservable: renewObservable,\n expireObservable: expireObservable,\n sessionStateUpdateObservable: sessionStateUpdateObservable,\n restartSession: startSession,\n expire: function () {\n cancelExpandOrRenewSession();\n expireSession(sessionCache);\n synchronizeSession(getExpiredSessionState(sessionCache));\n },\n stop: function () {\n clearInterval(watchSessionTimeoutId);\n },\n updateSessionState: updateSessionState,\n };\n}\n//# sourceMappingURL=sessionStore.js.map","import { Observable } from '../tools/observable';\nexport var TrackingConsent = {\n GRANTED: 'granted',\n NOT_GRANTED: 'not-granted',\n};\nexport function createTrackingConsentState(currentConsent) {\n var observable = new Observable();\n return {\n tryToInit: function (trackingConsent) {\n if (!currentConsent) {\n currentConsent = trackingConsent;\n }\n },\n update: function (trackingConsent) {\n currentConsent = trackingConsent;\n observable.notify();\n },\n isGranted: function () {\n return currentConsent === TrackingConsent.GRANTED;\n },\n observable: observable,\n };\n}\n//# sourceMappingURL=trackingConsent.js.map","import { noop } from '../utils/functionUtils';\n/**\n * Custom implementation of JSON.stringify that ignores some toJSON methods. We need to do that\n * because some sites badly override toJSON on certain objects. Removing all toJSON methods from\n * nested values would be too costly, so we just detach them from the root value, and native classes\n * used to build JSON values (Array and Object).\n *\n * Note: this still assumes that JSON.stringify is correct.\n */\nexport function jsonStringify(value, replacer, space) {\n if (typeof value !== 'object' || value === null) {\n return JSON.stringify(value);\n }\n // Note: The order matter here. We need to detach toJSON methods on parent classes before their\n // subclasses.\n var restoreObjectPrototypeToJson = detachToJsonMethod(Object.prototype);\n var restoreArrayPrototypeToJson = detachToJsonMethod(Array.prototype);\n var restoreValuePrototypeToJson = detachToJsonMethod(Object.getPrototypeOf(value));\n var restoreValueToJson = detachToJsonMethod(value);\n try {\n return JSON.stringify(value, replacer, space);\n }\n catch (_a) {\n return '';\n }\n finally {\n restoreObjectPrototypeToJson();\n restoreArrayPrototypeToJson();\n restoreValuePrototypeToJson();\n restoreValueToJson();\n }\n}\nexport function detachToJsonMethod(value) {\n var object = value;\n var objectToJson = object.toJSON;\n if (objectToJson) {\n delete object.toJSON;\n return function () {\n object.toJSON = objectToJson;\n };\n }\n return noop;\n}\n//# sourceMappingURL=jsonStringify.js.map","import { jsonStringify } from '../serialisation/jsonStringify';\nexport function normalizeUrl(url) {\n return buildUrl(url, location.href).href;\n}\nexport function isValidUrl(url) {\n try {\n return !!buildUrl(url);\n }\n catch (_a) {\n return false;\n }\n}\nexport function getPathName(url) {\n var pathname = buildUrl(url).pathname;\n return pathname[0] === '/' ? pathname : \"/\".concat(pathname);\n}\nexport function buildUrl(url, base) {\n var supportedURL = getSupportedUrl();\n if (supportedURL) {\n try {\n return base !== undefined ? new supportedURL(url, base) : new supportedURL(url);\n }\n catch (error) {\n throw new Error(\"Failed to construct URL: \".concat(String(error), \" \").concat(jsonStringify({ url: url, base: base })));\n }\n }\n if (base === undefined && !/:/.test(url)) {\n throw new Error(\"Invalid URL: '\".concat(url, \"'\"));\n }\n var doc = document;\n var anchorElement = doc.createElement('a');\n if (base !== undefined) {\n doc = document.implementation.createHTMLDocument('');\n var baseElement = doc.createElement('base');\n baseElement.href = base;\n doc.head.appendChild(baseElement);\n doc.body.appendChild(anchorElement);\n }\n anchorElement.href = url;\n return anchorElement;\n}\nvar originalURL = URL;\nvar isURLSupported;\nfunction getSupportedUrl() {\n if (isURLSupported === undefined) {\n try {\n var url = new originalURL('http://test/path');\n isURLSupported = url.href === 'http://test/path';\n }\n catch (_a) {\n isURLSupported = false;\n }\n }\n return isURLSupported ? originalURL : undefined;\n}\n//# sourceMappingURL=urlPolyfill.js.map","export var INTAKE_SITE_STAGING = 'datad0g.com';\nexport var INTAKE_SITE_FED_STAGING = 'dd0g-gov.com';\nexport var INTAKE_SITE_US1 = 'datadoghq.com';\nexport var INTAKE_SITE_EU1 = 'datadoghq.eu';\nexport var INTAKE_SITE_US1_FED = 'ddog-gov.com';\nexport var PCI_INTAKE_HOST_US1 = 'pci.browser-intake-datadoghq.com';\nexport var INTAKE_URL_PARAMETERS = ['ddsource', 'ddtags'];\n//# sourceMappingURL=intakeSites.js.map","import { timeStampNow } from '../../tools/utils/timeUtils';\nimport { normalizeUrl } from '../../tools/utils/urlPolyfill';\nimport { generateUUID } from '../../tools/utils/stringUtils';\nimport { INTAKE_SITE_US1, INTAKE_SITE_FED_STAGING, PCI_INTAKE_HOST_US1 } from './intakeSites';\nexport function createEndpointBuilder(initConfiguration, trackType, configurationTags) {\n var buildUrlWithParameters = createEndpointUrlWithParametersBuilder(initConfiguration, trackType);\n return {\n build: function (api, payload) {\n var parameters = buildEndpointParameters(initConfiguration, trackType, configurationTags, api, payload);\n return buildUrlWithParameters(parameters);\n },\n urlPrefix: buildUrlWithParameters(''),\n trackType: trackType,\n };\n}\n/**\n * Create a function used to build a full endpoint url from provided parameters. The goal of this\n * function is to pre-compute some parts of the URL to avoid re-computing everything on every\n * request, as only parameters are changing.\n */\nfunction createEndpointUrlWithParametersBuilder(initConfiguration, trackType) {\n var path = \"/api/v2/\".concat(trackType);\n var proxy = initConfiguration.proxy;\n if (typeof proxy === 'string') {\n var normalizedProxyUrl_1 = normalizeUrl(proxy);\n return function (parameters) { return \"\".concat(normalizedProxyUrl_1, \"?ddforward=\").concat(encodeURIComponent(\"\".concat(path, \"?\").concat(parameters))); };\n }\n if (typeof proxy === 'function') {\n return function (parameters) { return proxy({ path: path, parameters: parameters }); };\n }\n var host = buildEndpointHost(trackType, initConfiguration);\n return function (parameters) { return \"https://\".concat(host).concat(path, \"?\").concat(parameters); };\n}\nfunction buildEndpointHost(trackType, initConfiguration) {\n var _a = initConfiguration.site, site = _a === void 0 ? INTAKE_SITE_US1 : _a, internalAnalyticsSubdomain = initConfiguration.internalAnalyticsSubdomain;\n if (trackType === 'logs' && initConfiguration.usePciIntake && site === INTAKE_SITE_US1) {\n return PCI_INTAKE_HOST_US1;\n }\n if (internalAnalyticsSubdomain && site === INTAKE_SITE_US1) {\n return \"\".concat(internalAnalyticsSubdomain, \".\").concat(INTAKE_SITE_US1);\n }\n if (site === INTAKE_SITE_FED_STAGING) {\n return \"http-intake.logs.\".concat(site);\n }\n var domainParts = site.split('.');\n var extension = domainParts.pop();\n return \"browser-intake-\".concat(domainParts.join('-'), \".\").concat(extension);\n}\n/**\n * Build parameters to be used for an intake request. Parameters should be re-built for each\n * request, as they change randomly.\n */\nfunction buildEndpointParameters(_a, trackType, configurationTags, api, _b) {\n var clientToken = _a.clientToken, internalAnalyticsSubdomain = _a.internalAnalyticsSubdomain;\n var retry = _b.retry, encoding = _b.encoding;\n var tags = [\"sdk_version:\".concat(\"5.35.0\"), \"api:\".concat(api)].concat(configurationTags);\n if (retry) {\n tags.push(\"retry_count:\".concat(retry.count), \"retry_after:\".concat(retry.lastFailureStatus));\n }\n var parameters = [\n 'ddsource=browser',\n \"ddtags=\".concat(encodeURIComponent(tags.join(','))),\n \"dd-api-key=\".concat(clientToken),\n \"dd-evp-origin-version=\".concat(encodeURIComponent(\"5.35.0\")),\n 'dd-evp-origin=browser',\n \"dd-request-id=\".concat(generateUUID()),\n ];\n if (encoding) {\n parameters.push(\"dd-evp-encoding=\".concat(encoding));\n }\n if (trackType === 'rum') {\n parameters.push(\"batch_time=\".concat(timeStampNow()));\n }\n if (internalAnalyticsSubdomain) {\n parameters.reverse();\n }\n return parameters.join('&');\n}\n//# sourceMappingURL=endpointBuilder.js.map","import { DOCS_ORIGIN, MORE_DETAILS, display } from '../../tools/display';\nexport var TAG_SIZE_LIMIT = 200;\nexport function buildTags(configuration) {\n var env = configuration.env, service = configuration.service, version = configuration.version, datacenter = configuration.datacenter;\n var tags = [];\n if (env) {\n tags.push(buildTag('env', env));\n }\n if (service) {\n tags.push(buildTag('service', service));\n }\n if (version) {\n tags.push(buildTag('version', version));\n }\n if (datacenter) {\n tags.push(buildTag('datacenter', datacenter));\n }\n return tags;\n}\nexport function buildTag(key, rawValue) {\n // See https://docs.datadoghq.com/getting_started/tagging/#defining-tags for tags syntax. Note\n // that the backend may not follow the exact same rules, so we only want to display an informal\n // warning.\n var valueSizeLimit = TAG_SIZE_LIMIT - key.length - 1;\n if (rawValue.length > valueSizeLimit || hasForbiddenCharacters(rawValue)) {\n 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\"));\n }\n // Let the backend do most of the sanitization, but still make sure multiple tags can't be crafted\n // by forging a value containing commas.\n var sanitizedValue = rawValue.replace(/,/g, '_');\n return \"\".concat(key, \":\").concat(sanitizedValue);\n}\nfunction hasForbiddenCharacters(rawValue) {\n // Unicode property escapes is not supported in all browsers, so we use a try/catch.\n // Todo: Remove the try/catch when dropping IE11.\n if (!supportUnicodePropertyEscapes()) {\n return false;\n }\n // We use the Unicode property escapes to match any character that is a letter including other languages like Chinese, Japanese, etc.\n // p{Ll} matches a lowercase letter.\n // p{Lo} matches a letter that is neither uppercase nor lowercase (ex: Japanese characters).\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape#unicode_property_escapes_vs._character_classes\n return new RegExp('[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]', 'u').test(rawValue);\n}\nexport function supportUnicodePropertyEscapes() {\n try {\n new RegExp('[\\\\p{Ll}]', 'u');\n return true;\n }\n catch (_a) {\n return false;\n }\n}\n//# sourceMappingURL=tags.js.map","import { assign, includes } from '../../tools/utils/polyfills';\nimport { createEndpointBuilder } from './endpointBuilder';\nimport { buildTags } from './tags';\nimport { INTAKE_SITE_US1, INTAKE_URL_PARAMETERS } from './intakeSites';\nexport function computeTransportConfiguration(initConfiguration) {\n var site = initConfiguration.site || INTAKE_SITE_US1;\n var tags = buildTags(initConfiguration);\n var endpointBuilders = computeEndpointBuilders(initConfiguration, tags);\n var replicaConfiguration = computeReplicaConfiguration(initConfiguration, tags);\n return assign({\n replica: replicaConfiguration,\n site: site,\n }, endpointBuilders);\n}\nfunction computeEndpointBuilders(initConfiguration, tags) {\n return {\n logsEndpointBuilder: createEndpointBuilder(initConfiguration, 'logs', tags),\n rumEndpointBuilder: createEndpointBuilder(initConfiguration, 'rum', tags),\n sessionReplayEndpointBuilder: createEndpointBuilder(initConfiguration, 'replay', tags),\n };\n}\nfunction computeReplicaConfiguration(initConfiguration, tags) {\n if (!initConfiguration.replica) {\n return;\n }\n var replicaConfiguration = assign({}, initConfiguration, {\n site: INTAKE_SITE_US1,\n clientToken: initConfiguration.replica.clientToken,\n });\n var replicaEndpointBuilders = {\n logsEndpointBuilder: createEndpointBuilder(replicaConfiguration, 'logs', tags),\n rumEndpointBuilder: createEndpointBuilder(replicaConfiguration, 'rum', tags),\n };\n return assign({ applicationId: initConfiguration.replica.applicationId }, replicaEndpointBuilders);\n}\nexport function isIntakeUrl(url) {\n // check if tags is present in the query string\n return INTAKE_URL_PARAMETERS.every(function (param) { return includes(url, param); });\n}\n//# sourceMappingURL=transportConfiguration.js.map","import { catchUserErrors } from '../../tools/catchUserErrors';\nimport { DOCS_ORIGIN, MORE_DETAILS, display } from '../../tools/display';\nimport { ONE_SECOND } from '../../tools/utils/timeUtils';\nimport { isPercentage } from '../../tools/utils/numberUtils';\nimport { ONE_KIBI_BYTE } from '../../tools/utils/byteUtils';\nimport { objectHasValue } from '../../tools/utils/objectUtils';\nimport { assign } from '../../tools/utils/polyfills';\nimport { selectSessionStoreStrategyType } from '../session/sessionStore';\nimport { TrackingConsent } from '../trackingConsent';\nimport { computeTransportConfiguration } from './transportConfiguration';\nexport var DefaultPrivacyLevel = {\n ALLOW: 'allow',\n MASK: 'mask',\n MASK_USER_INPUT: 'mask-user-input',\n};\nexport var TraceContextInjection = {\n ALL: 'all',\n SAMPLED: 'sampled',\n};\nfunction isString(tag, tagName) {\n if (tag !== undefined && tag !== null && typeof tag !== 'string') {\n display.error(\"\".concat(tagName, \" must be defined as a string\"));\n return false;\n }\n return true;\n}\nfunction isDatadogSite(site) {\n if (site && typeof site === 'string' && !/(datadog|ddog|datad0g|dd0g)/.test(site)) {\n display.error(\"Site should be a valid Datadog site. \".concat(MORE_DETAILS, \" \").concat(DOCS_ORIGIN, \"/getting_started/site/.\"));\n return false;\n }\n return true;\n}\nexport function isSampleRate(sampleRate, name) {\n if (sampleRate !== undefined && !isPercentage(sampleRate)) {\n display.error(\"\".concat(name, \" Sample Rate should be a number between 0 and 100\"));\n return false;\n }\n return true;\n}\nexport function validateAndBuildConfiguration(initConfiguration) {\n var _a, _b, _c, _d, _e;\n if (!initConfiguration || !initConfiguration.clientToken) {\n display.error('Client Token is not configured, we will not send any data.');\n return;\n }\n if (!isDatadogSite(initConfiguration.site) ||\n !isSampleRate(initConfiguration.sessionSampleRate, 'Session') ||\n !isSampleRate(initConfiguration.telemetrySampleRate, 'Telemetry') ||\n !isSampleRate(initConfiguration.telemetryConfigurationSampleRate, 'Telemetry Configuration') ||\n !isSampleRate(initConfiguration.telemetryUsageSampleRate, 'Telemetry Usage') ||\n !isString(initConfiguration.version, 'Version') ||\n !isString(initConfiguration.env, 'Env') ||\n !isString(initConfiguration.service, 'Service')) {\n return;\n }\n if (initConfiguration.trackingConsent !== undefined &&\n !objectHasValue(TrackingConsent, initConfiguration.trackingConsent)) {\n display.error('Tracking Consent should be either \"granted\" or \"not-granted\"');\n return;\n }\n return assign({\n beforeSend: initConfiguration.beforeSend && catchUserErrors(initConfiguration.beforeSend, 'beforeSend threw an error:'),\n sessionStoreStrategyType: selectSessionStoreStrategyType(initConfiguration),\n sessionSampleRate: (_a = initConfiguration.sessionSampleRate) !== null && _a !== void 0 ? _a : 100,\n telemetrySampleRate: (_b = initConfiguration.telemetrySampleRate) !== null && _b !== void 0 ? _b : 20,\n telemetryConfigurationSampleRate: (_c = initConfiguration.telemetryConfigurationSampleRate) !== null && _c !== void 0 ? _c : 5,\n telemetryUsageSampleRate: (_d = initConfiguration.telemetryUsageSampleRate) !== null && _d !== void 0 ? _d : 5,\n service: initConfiguration.service || undefined,\n silentMultipleInit: !!initConfiguration.silentMultipleInit,\n allowUntrustedEvents: !!initConfiguration.allowUntrustedEvents,\n trackingConsent: (_e = initConfiguration.trackingConsent) !== null && _e !== void 0 ? _e : TrackingConsent.GRANTED,\n storeContextsAcrossPages: !!initConfiguration.storeContextsAcrossPages,\n /**\n * beacon payload max queue size implementation is 64kb\n * ensure that we leave room for logs, rum and potential other users\n */\n batchBytesLimit: 16 * ONE_KIBI_BYTE,\n eventRateLimiterThreshold: 3000,\n maxTelemetryEventsPerPage: 15,\n /**\n * flush automatically, aim to be lower than ALB connection timeout\n * to maximize connection reuse.\n */\n flushTimeout: (30 * ONE_SECOND),\n /**\n * Logs intake limit\n */\n batchMessagesLimit: 50,\n messageBytesLimit: 256 * ONE_KIBI_BYTE,\n }, computeTransportConfiguration(initConfiguration));\n}\nexport function serializeConfiguration(initConfiguration) {\n return {\n session_sample_rate: initConfiguration.sessionSampleRate,\n telemetry_sample_rate: initConfiguration.telemetrySampleRate,\n telemetry_configuration_sample_rate: initConfiguration.telemetryConfigurationSampleRate,\n telemetry_usage_sample_rate: initConfiguration.telemetryUsageSampleRate,\n use_before_send: !!initConfiguration.beforeSend,\n use_cross_site_session_cookie: initConfiguration.useCrossSiteSessionCookie,\n use_partitioned_cross_site_session_cookie: initConfiguration.usePartitionedCrossSiteSessionCookie,\n use_secure_session_cookie: initConfiguration.useSecureSessionCookie,\n use_proxy: !!initConfiguration.proxy,\n silent_multiple_init: initConfiguration.silentMultipleInit,\n track_session_across_subdomains: initConfiguration.trackSessionAcrossSubdomains,\n session_persistence: initConfiguration.sessionPersistence,\n allow_fallback_to_local_storage: !!initConfiguration.allowFallbackToLocalStorage,\n store_contexts_across_pages: !!initConfiguration.storeContextsAcrossPages,\n allow_untrusted_events: !!initConfiguration.allowUntrustedEvents,\n tracking_consent: initConfiguration.trackingConsent,\n };\n}\n//# sourceMappingURL=configuration.js.map","/**\n * Cross-browser stack trace computation.\n *\n * Reference implementation: https://github.com/csnover/TraceKit/blob/04530298073c3823de72deb0b97e7b38ca7bcb59/tracekit.js\n */\nimport { startsWith } from '../utils/polyfills';\nvar UNKNOWN_FUNCTION = '?';\nexport function computeStackTrace(ex) {\n var stack = [];\n var stackProperty = tryToGetString(ex, 'stack');\n var exString = String(ex);\n if (stackProperty && startsWith(stackProperty, exString)) {\n stackProperty = stackProperty.slice(exString.length);\n }\n if (stackProperty) {\n stackProperty.split('\\n').forEach(function (line) {\n var stackFrame = parseChromeLine(line) || parseChromeAnonymousLine(line) || parseWinLine(line) || parseGeckoLine(line);\n if (stackFrame) {\n if (!stackFrame.func && stackFrame.line) {\n stackFrame.func = UNKNOWN_FUNCTION;\n }\n stack.push(stackFrame);\n }\n });\n }\n return {\n message: tryToGetString(ex, 'message'),\n name: tryToGetString(ex, 'name'),\n stack: stack,\n };\n}\nvar fileUrl = '((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet||\\\\w+\\\\.|\\\\/).*?)';\nvar filePosition = '(?::(\\\\d+))';\nvar CHROME_LINE_RE = new RegExp(\"^\\\\s*at (.*?) ?\\\\(\".concat(fileUrl).concat(filePosition, \"?\").concat(filePosition, \"?\\\\)?\\\\s*$\"), 'i');\nvar CHROME_EVAL_RE = new RegExp(\"\\\\((\\\\S*)\".concat(filePosition).concat(filePosition, \"\\\\)\"));\nfunction parseChromeLine(line) {\n var parts = CHROME_LINE_RE.exec(line);\n if (!parts) {\n return;\n }\n var isNative = parts[2] && parts[2].indexOf('native') === 0; // start of line\n var isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n var submatch = CHROME_EVAL_RE.exec(parts[2]);\n if (isEval && submatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = submatch[1]; // url\n parts[3] = submatch[2]; // line\n parts[4] = submatch[3]; // column\n }\n return {\n args: isNative ? [parts[2]] : [],\n column: parts[4] ? +parts[4] : undefined,\n func: parts[1] || UNKNOWN_FUNCTION,\n line: parts[3] ? +parts[3] : undefined,\n url: !isNative ? parts[2] : undefined,\n };\n}\nvar CHROME_ANONYMOUS_FUNCTION_RE = new RegExp(\"^\\\\s*at ?\".concat(fileUrl).concat(filePosition, \"?\").concat(filePosition, \"??\\\\s*$\"), 'i');\nfunction parseChromeAnonymousLine(line) {\n var parts = CHROME_ANONYMOUS_FUNCTION_RE.exec(line);\n if (!parts) {\n return;\n }\n return {\n args: [],\n column: parts[3] ? +parts[3] : undefined,\n func: UNKNOWN_FUNCTION,\n line: parts[2] ? +parts[2] : undefined,\n url: parts[1],\n };\n}\nvar WINJS_LINE_RE = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\nfunction parseWinLine(line) {\n var parts = WINJS_LINE_RE.exec(line);\n if (!parts) {\n return;\n }\n return {\n args: [],\n column: parts[4] ? +parts[4] : undefined,\n func: parts[1] || UNKNOWN_FUNCTION,\n line: +parts[3],\n url: parts[2],\n };\n}\nvar GECKO_LINE_RE = /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nvar GECKO_EVAL_RE = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\nfunction parseGeckoLine(line) {\n var parts = GECKO_LINE_RE.exec(line);\n if (!parts) {\n return;\n }\n var isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n var submatch = GECKO_EVAL_RE.exec(parts[3]);\n if (isEval && submatch) {\n // throw out eval line/column and use top-most line number\n parts[3] = submatch[1];\n parts[4] = submatch[2];\n parts[5] = undefined; // no column when eval\n }\n return {\n args: parts[2] ? parts[2].split(',') : [],\n column: parts[5] ? +parts[5] : undefined,\n func: parts[1] || UNKNOWN_FUNCTION,\n line: parts[4] ? +parts[4] : undefined,\n url: parts[3],\n };\n}\nfunction tryToGetString(candidate, property) {\n if (typeof candidate !== 'object' || !candidate || !(property in candidate)) {\n return undefined;\n }\n var value = candidate[property];\n return typeof value === 'string' ? value : undefined;\n}\nexport function computeStackTraceFromOnErrorMessage(messageObj, url, line, column) {\n var stack = [{ url: url, column: column, line: line }];\n var _a = tryToParseMessage(messageObj), name = _a.name, message = _a.message;\n return {\n name: name,\n message: message,\n stack: stack,\n };\n}\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Error_types\nvar ERROR_TYPES_RE = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/;\nfunction tryToParseMessage(messageObj) {\n var _a;\n var name;\n var message;\n if ({}.toString.call(messageObj) === '[object String]') {\n ;\n _a = ERROR_TYPES_RE.exec(messageObj), name = _a[1], message = _a[2];\n }\n return { name: name, message: message };\n}\n//# sourceMappingURL=computeStackTrace.js.map","import { callMonitored } from '../monitor';\nimport { noop } from '../utils/functionUtils';\nimport { computeStackTrace } from './computeStackTrace';\n/**\n * Creates a stacktrace without SDK internal frames.\n * Constraints:\n * - Has to be called at the utmost position of the call stack.\n * - No monitored function should encapsulate it, that is why we need to use callMonitored inside it.\n */\nexport function createHandlingStack() {\n /**\n * Skip the two internal frames:\n * - SDK API (console.error, ...)\n * - this function\n * in order to keep only the user calls\n */\n var internalFramesToSkip = 2;\n var error = new Error();\n var formattedStack;\n // IE needs to throw the error to fill in the stack trace\n if (!error.stack) {\n try {\n throw error;\n }\n catch (_a) {\n noop();\n }\n }\n callMonitored(function () {\n var stackTrace = computeStackTrace(error);\n stackTrace.stack = stackTrace.stack.slice(internalFramesToSkip);\n formattedStack = toStackTraceString(stackTrace);\n });\n return formattedStack;\n}\nexport function toStackTraceString(stack) {\n var result = formatErrorMessage(stack);\n stack.stack.forEach(function (frame) {\n var func = frame.func === '?' ? '' : frame.func;\n var args = frame.args && frame.args.length > 0 ? \"(\".concat(frame.args.join(', '), \")\") : '';\n var line = frame.line ? \":\".concat(frame.line) : '';\n var column = frame.line && frame.column ? \":\".concat(frame.column) : '';\n result += \"\\n at \".concat(func).concat(args, \" @ \").concat(frame.url).concat(line).concat(column);\n });\n return result;\n}\nexport function formatErrorMessage(stack) {\n return \"\".concat(stack.name || 'Error', \": \").concat(stack.message);\n}\n//# sourceMappingURL=handlingStack.js.map","import { setTimeout } from './timer';\nimport { callMonitored } from './monitor';\nimport { noop } from './utils/functionUtils';\nimport { arrayFrom, startsWith } from './utils/polyfills';\nimport { createHandlingStack } from './stackTrace/handlingStack';\n/**\n * Instruments a method on a object, calling the given callback before the original method is\n * invoked. The callback receives an object with information about the method call.\n *\n * This function makes sure that we are \"good citizens\" regarding third party instrumentations: when\n * removing the instrumentation, the original method is usually restored, but if a third party\n * instrumentation was set after ours, we keep it in place and just replace our instrumentation with\n * a noop.\n *\n * Note: it is generally better to instrument methods that are \"owned\" by the object instead of ones\n * that are inherited from the prototype chain. Example:\n * * do: `instrumentMethod(Array.prototype, 'push', ...)`\n * * don't: `instrumentMethod([], 'push', ...)`\n *\n * This method is also used to set event handler properties (ex: window.onerror = ...), as it has\n * the same requirements as instrumenting a method:\n * * if the event handler is already set by a third party, we need to call it and not just blindly\n * override it.\n * * if the event handler is set by a third party after us, we need to keep it in place when\n * removing ours.\n *\n * @example\n *\n * instrumentMethod(window, 'fetch', ({ target, parameters, onPostCall }) => {\n * console.log('Before calling fetch on', target, 'with parameters', parameters)\n *\n * onPostCall((result) => {\n * console.log('After fetch calling on', target, 'with parameters', parameters, 'and result', result)\n * })\n * })\n */\nexport function instrumentMethod(targetPrototype, method, onPreCall, _a) {\n var _b = _a === void 0 ? {} : _a, computeHandlingStack = _b.computeHandlingStack;\n var original = targetPrototype[method];\n if (typeof original !== 'function') {\n if (method in targetPrototype && startsWith(method, 'on')) {\n original = noop;\n }\n else {\n return { stop: noop };\n }\n }\n var stopped = false;\n var instrumentation = function () {\n if (stopped) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call\n return original.apply(this, arguments);\n }\n var parameters = arrayFrom(arguments);\n var postCallCallback;\n callMonitored(onPreCall, null, [\n {\n target: this,\n parameters: parameters,\n onPostCall: function (callback) {\n postCallCallback = callback;\n },\n handlingStack: computeHandlingStack ? createHandlingStack() : undefined,\n },\n ]);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n var result = original.apply(this, parameters);\n if (postCallCallback) {\n callMonitored(postCallCallback, null, [result]);\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return result;\n };\n targetPrototype[method] = instrumentation;\n return {\n stop: function () {\n stopped = true;\n // If the instrumentation has been removed by a third party, keep the last one\n if (targetPrototype[method] === instrumentation) {\n targetPrototype[method] = original;\n }\n },\n };\n}\nexport function instrumentSetter(targetPrototype, property, after) {\n var originalDescriptor = Object.getOwnPropertyDescriptor(targetPrototype, property);\n if (!originalDescriptor || !originalDescriptor.set || !originalDescriptor.configurable) {\n return { stop: noop };\n }\n var stoppedInstrumentation = noop;\n var instrumentation = function (target, value) {\n // put hooked setter into event loop to avoid of set latency\n setTimeout(function () {\n if (instrumentation !== stoppedInstrumentation) {\n after(target, value);\n }\n }, 0);\n };\n var instrumentationWrapper = function (value) {\n originalDescriptor.set.call(this, value);\n instrumentation(this, value);\n };\n Object.defineProperty(targetPrototype, property, {\n set: instrumentationWrapper,\n });\n return {\n stop: function () {\n var _a;\n if (((_a = Object.getOwnPropertyDescriptor(targetPrototype, property)) === null || _a === void 0 ? void 0 : _a.set) === instrumentationWrapper) {\n Object.defineProperty(targetPrototype, property, originalDescriptor);\n }\n instrumentation = stoppedInstrumentation;\n },\n };\n}\n//# sourceMappingURL=instrumentMethod.js.map","import { display } from '../display';\nimport { ONE_KIBI_BYTE } from '../utils/byteUtils';\nimport { detachToJsonMethod } from './jsonStringify';\n// The maximum size of a single event is 256KiB. By default, we ensure that user-provided data\n// going through sanitize fits inside our events, while leaving room for other contexts, metadata, ...\nvar SANITIZE_DEFAULT_MAX_CHARACTER_COUNT = 220 * ONE_KIBI_BYTE;\n// Symbol for the root element of the JSONPath used for visited objects\nvar JSON_PATH_ROOT_ELEMENT = '$';\n// When serializing (using JSON.stringify) a key of an object, { key: 42 } gets wrapped in quotes as \"key\".\n// With the separator (:), we need to add 3 characters to the count.\nvar KEY_DECORATION_LENGTH = 3;\nexport function sanitize(source, maxCharacterCount) {\n if (maxCharacterCount === void 0) { maxCharacterCount = SANITIZE_DEFAULT_MAX_CHARACTER_COUNT; }\n // Unbind any toJSON function we may have on [] or {} prototypes\n var restoreObjectPrototypeToJson = detachToJsonMethod(Object.prototype);\n var restoreArrayPrototypeToJson = detachToJsonMethod(Array.prototype);\n // Initial call to sanitizeProcessor - will populate containerQueue if source is an Array or a plain Object\n var containerQueue = [];\n var visitedObjectsWithPath = new WeakMap();\n var sanitizedData = sanitizeProcessor(source, JSON_PATH_ROOT_ELEMENT, undefined, containerQueue, visitedObjectsWithPath);\n var serializedSanitizedData = JSON.stringify(sanitizedData);\n var accumulatedCharacterCount = serializedSanitizedData ? serializedSanitizedData.length : 0;\n if (accumulatedCharacterCount > maxCharacterCount) {\n warnOverCharacterLimit(maxCharacterCount, 'discarded', source);\n return undefined;\n }\n while (containerQueue.length > 0 && accumulatedCharacterCount < maxCharacterCount) {\n var containerToProcess = containerQueue.shift();\n var separatorLength = 0; // 0 for the first element, 1 for subsequent elements\n // Arrays and Objects have to be handled distinctly to ensure\n // we do not pick up non-numerical properties from Arrays\n if (Array.isArray(containerToProcess.source)) {\n for (var key = 0; key < containerToProcess.source.length; key++) {\n var targetData = sanitizeProcessor(containerToProcess.source[key], containerToProcess.path, key, containerQueue, visitedObjectsWithPath);\n if (targetData !== undefined) {\n accumulatedCharacterCount += JSON.stringify(targetData).length;\n }\n else {\n // When an element of an Array (targetData) is undefined, it is serialized as null:\n // JSON.stringify([undefined]) => '[null]' - This accounts for 4 characters\n accumulatedCharacterCount += 4;\n }\n accumulatedCharacterCount += separatorLength;\n separatorLength = 1;\n if (accumulatedCharacterCount > maxCharacterCount) {\n warnOverCharacterLimit(maxCharacterCount, 'truncated', source);\n break;\n }\n ;\n containerToProcess.target[key] = targetData;\n }\n }\n else {\n for (var key in containerToProcess.source) {\n if (Object.prototype.hasOwnProperty.call(containerToProcess.source, key)) {\n var targetData = sanitizeProcessor(containerToProcess.source[key], containerToProcess.path, key, containerQueue, visitedObjectsWithPath);\n // When a property of an object has an undefined value, it will be dropped during serialization:\n // JSON.stringify({a:undefined}) => '{}'\n if (targetData !== undefined) {\n accumulatedCharacterCount +=\n JSON.stringify(targetData).length + separatorLength + key.length + KEY_DECORATION_LENGTH;\n separatorLength = 1;\n }\n if (accumulatedCharacterCount > maxCharacterCount) {\n warnOverCharacterLimit(maxCharacterCount, 'truncated', source);\n break;\n }\n ;\n containerToProcess.target[key] = targetData;\n }\n }\n }\n }\n // Rebind detached toJSON functions\n restoreObjectPrototypeToJson();\n restoreArrayPrototypeToJson();\n return sanitizedData;\n}\n/**\n * Internal function to factorize the process common to the\n * initial call to sanitize, and iterations for Arrays and Objects\n *\n */\nfunction sanitizeProcessor(source, parentPath, key, queue, visitedObjectsWithPath) {\n // Start by handling toJSON, as we want to sanitize its output\n var sourceToSanitize = tryToApplyToJSON(source);\n if (!sourceToSanitize || typeof sourceToSanitize !== 'object') {\n return sanitizePrimitivesAndFunctions(sourceToSanitize);\n }\n var sanitizedSource = sanitizeObjects(sourceToSanitize);\n if (sanitizedSource !== '[Object]' && sanitizedSource !== '[Array]' && sanitizedSource !== '[Error]') {\n return sanitizedSource;\n }\n // Handle potential cyclic references\n // We need to use source as sourceToSanitize could be a reference to a new object\n // At this stage, we know the source is an object type\n var sourceAsObject = source;\n if (visitedObjectsWithPath.has(sourceAsObject)) {\n return \"[Reference seen at \".concat(visitedObjectsWithPath.get(sourceAsObject), \"]\");\n }\n // Add processed source to queue\n var currentPath = key !== undefined ? \"\".concat(parentPath, \".\").concat(key) : parentPath;\n var target = Array.isArray(sourceToSanitize) ? [] : {};\n visitedObjectsWithPath.set(sourceAsObject, currentPath);\n queue.push({ source: sourceToSanitize, target: target, path: currentPath });\n return target;\n}\n/**\n * Handles sanitization of simple, non-object types\n *\n */\nfunction sanitizePrimitivesAndFunctions(value) {\n // BigInt cannot be serialized by JSON.stringify(), convert it to a string representation\n if (typeof value === 'bigint') {\n return \"[BigInt] \".concat(value.toString());\n }\n // Functions cannot be serialized by JSON.stringify(). Moreover, if a faulty toJSON is present, it needs to be converted\n // so it won't prevent stringify from serializing later\n if (typeof value === 'function') {\n return \"[Function] \".concat(value.name || 'unknown');\n }\n // JSON.stringify() does not serialize symbols.\n if (typeof value === 'symbol') {\n return \"[Symbol] \".concat(value.description || value.toString());\n }\n return value;\n}\n/**\n * Handles sanitization of object types\n *\n * LIMITATIONS\n * - If a class defines a toStringTag Symbol, it will fall in the catch-all method and prevent enumeration of properties.\n * To avoid this, a toJSON method can be defined.\n * - IE11 does not return a distinct type for objects such as Map, WeakMap, ... These objects will pass through and their\n * properties enumerated if any.\n *\n */\nfunction sanitizeObjects(value) {\n try {\n // Handle events - Keep a simple implementation to avoid breaking changes\n if (value instanceof Event) {\n return {\n isTrusted: value.isTrusted,\n };\n }\n // Handle all remaining object types in a generic way\n var result = Object.prototype.toString.call(value);\n var match = result.match(/\\[object (.*)\\]/);\n if (match && match[1]) {\n return \"[\".concat(match[1], \"]\");\n }\n }\n catch (_a) {\n // If the previous serialization attempts failed, and we cannot convert using\n // Object.prototype.toString, declare the value unserializable\n }\n return '[Unserializable]';\n}\n/**\n * Checks if a toJSON function exists and tries to execute it\n *\n */\nfunction tryToApplyToJSON(value) {\n var object = value;\n if (object && typeof object.toJSON === 'function') {\n try {\n return object.toJSON();\n }\n catch (_a) {\n // If toJSON fails, we continue by trying to serialize the value manually\n }\n }\n return value;\n}\n/**\n * Helper function to display the warning when the accumulated character count is over the limit\n */\nfunction warnOverCharacterLimit(maxCharacterCount, changeType, source) {\n display.warn(\"The data provided has been \".concat(changeType, \" as it is over the limit of \").concat(maxCharacterCount, \" characters:\"), source);\n}\n//# sourceMappingURL=sanitize.js.map","import { sanitize } from '../../tools/serialisation/sanitize';\nimport { jsonStringify } from '../../tools/serialisation/jsonStringify';\nimport { computeStackTrace } from '../../tools/stackTrace/computeStackTrace';\nimport { toStackTraceString } from '../../tools/stackTrace/handlingStack';\nexport var NO_ERROR_STACK_PRESENT_MESSAGE = 'No stack, consider using an instance of Error';\nexport function computeRawError(_a) {\n var stackTrace = _a.stackTrace, originalError = _a.originalError, handlingStack = _a.handlingStack, startClocks = _a.startClocks, nonErrorPrefix = _a.nonErrorPrefix, source = _a.source, handling = _a.handling;\n var isErrorInstance = isError(originalError);\n var message = computeMessage(stackTrace, isErrorInstance, nonErrorPrefix, originalError);\n var stack = hasUsableStack(isErrorInstance, stackTrace)\n ? toStackTraceString(stackTrace)\n : NO_ERROR_STACK_PRESENT_MESSAGE;\n var causes = isErrorInstance ? flattenErrorCauses(originalError, source) : undefined;\n var type = stackTrace ? stackTrace.name : undefined;\n var fingerprint = tryToGetFingerprint(originalError);\n return {\n startClocks: startClocks,\n source: source,\n handling: handling,\n handlingStack: handlingStack,\n originalError: originalError,\n type: type,\n message: message,\n stack: stack,\n causes: causes,\n fingerprint: fingerprint,\n };\n}\nfunction computeMessage(stackTrace, isErrorInstance, nonErrorPrefix, originalError) {\n // Favor stackTrace message only if tracekit has really been able to extract something meaningful (message + name)\n // TODO rework tracekit integration to avoid scattering error building logic\n return (stackTrace === null || stackTrace === void 0 ? void 0 : stackTrace.message) && (stackTrace === null || stackTrace === void 0 ? void 0 : stackTrace.name)\n ? stackTrace.message\n : !isErrorInstance\n ? \"\".concat(nonErrorPrefix, \" \").concat(jsonStringify(sanitize(originalError)))\n : 'Empty message';\n}\nfunction hasUsableStack(isErrorInstance, stackTrace) {\n if (stackTrace === undefined) {\n return false;\n }\n if (isErrorInstance) {\n return true;\n }\n // handle cases where tracekit return stack = [] or stack = [{url: undefined, line: undefined, column: undefined}]\n // TODO rework tracekit integration to avoid generating those unusable stack\n return stackTrace.stack.length > 0 && (stackTrace.stack.length > 1 || stackTrace.stack[0].url !== undefined);\n}\nexport function tryToGetFingerprint(originalError) {\n return isError(originalError) && 'dd_fingerprint' in originalError ? String(originalError.dd_fingerprint) : undefined;\n}\nexport function getFileFromStackTraceString(stack) {\n var _a;\n return (_a = /@ (.+)/.exec(stack)) === null || _a === void 0 ? void 0 : _a[1];\n}\nexport function isError(error) {\n return error instanceof Error || Object.prototype.toString.call(error) === '[object Error]';\n}\nexport function flattenErrorCauses(error, parentSource) {\n var currentError = error;\n var causes = [];\n while (isError(currentError === null || currentError === void 0 ? void 0 : currentError.cause) && causes.length < 10) {\n var stackTrace = computeStackTrace(currentError.cause);\n causes.push({\n message: currentError.cause.message,\n source: parentSource,\n type: stackTrace === null || stackTrace === void 0 ? void 0 : stackTrace.name,\n stack: stackTrace && toStackTraceString(stackTrace),\n });\n currentError = currentError.cause;\n }\n return causes.length ? causes : undefined;\n}\n//# sourceMappingURL=error.js.map","export var ErrorSource = {\n AGENT: 'agent',\n CONSOLE: 'console',\n CUSTOM: 'custom',\n LOGGER: 'logger',\n NETWORK: 'network',\n SOURCE: 'source',\n REPORT: 'report',\n};\n//# sourceMappingURL=error.types.js.map","import { instrumentMethod } from '../../tools/instrumentMethod';\nimport { clocksNow } from '../../tools/utils/timeUtils';\nimport { computeStackTrace, computeStackTraceFromOnErrorMessage } from '../../tools/stackTrace/computeStackTrace';\nimport { computeRawError, isError } from './error';\nimport { ErrorSource } from './error.types';\nexport function trackRuntimeError(errorObservable) {\n var handleRuntimeError = function (stackTrace, originalError) {\n var rawError = computeRawError({\n stackTrace: stackTrace,\n originalError: originalError,\n startClocks: clocksNow(),\n nonErrorPrefix: \"Uncaught\" /* NonErrorPrefix.UNCAUGHT */,\n source: ErrorSource.SOURCE,\n handling: \"unhandled\" /* ErrorHandling.UNHANDLED */,\n });\n errorObservable.notify(rawError);\n };\n var stopInstrumentingOnError = instrumentOnError(handleRuntimeError).stop;\n var stopInstrumentingOnUnhandledRejection = instrumentUnhandledRejection(handleRuntimeError).stop;\n return {\n stop: function () {\n stopInstrumentingOnError();\n stopInstrumentingOnUnhandledRejection();\n },\n };\n}\nexport function instrumentOnError(callback) {\n return instrumentMethod(window, 'onerror', function (_a) {\n var _b = _a.parameters, messageObj = _b[0], url = _b[1], line = _b[2], column = _b[3], errorObj = _b[4];\n var stackTrace;\n if (isError(errorObj)) {\n stackTrace = computeStackTrace(errorObj);\n }\n else {\n stackTrace = computeStackTraceFromOnErrorMessage(messageObj, url, line, column);\n }\n callback(stackTrace, errorObj !== null && errorObj !== void 0 ? errorObj : messageObj);\n });\n}\nexport function instrumentUnhandledRejection(callback) {\n return instrumentMethod(window, 'onunhandledrejection', function (_a) {\n var e = _a.parameters[0];\n var reason = e.reason || 'Empty reason';\n var stack = computeStackTrace(reason);\n callback(stack, reason);\n });\n}\n//# sourceMappingURL=trackRuntimeError.js.map","import { catchUserErrors } from '../tools/catchUserErrors';\nimport { setDebugMode } from '../tools/monitor';\nimport { assign } from '../tools/utils/polyfills';\nimport { display } from '../tools/display';\nexport function makePublicApi(stub) {\n var publicApi = assign({\n version: \"5.35.0\",\n // This API method is intentionally not monitored, since the only thing executed is the\n // user-provided 'callback'. All SDK usages executed in the callback should be monitored, and\n // we don't want to interfere with the user uncaught exceptions.\n onReady: function (callback) {\n callback();\n },\n }, stub);\n // Add a \"hidden\" property to set debug mode. We define it that way to hide it\n // as much as possible but of course it's not a real protection.\n Object.defineProperty(publicApi, '_setDebug', {\n get: function () {\n return setDebugMode;\n },\n enumerable: false,\n });\n return publicApi;\n}\nexport function defineGlobal(global, name, api) {\n var existingGlobalVariable = global[name];\n if (existingGlobalVariable && !existingGlobalVariable.q && existingGlobalVariable.version) {\n display.warn('SDK is loaded more than once. This is unsupported and might have unexpected behavior.');\n }\n global[name] = api;\n if (existingGlobalVariable && existingGlobalVariable.q) {\n existingGlobalVariable.q.forEach(function (fn) { return catchUserErrors(fn, 'onReady callback threw an error:')(); });\n }\n}\n//# sourceMappingURL=init.js.map","import { display } from '../tools/display';\nexport function displayAlreadyInitializedError(sdkName, initConfiguration) {\n if (!initConfiguration.silentMultipleInit) {\n display.error(\"\".concat(sdkName, \" is already initialized.\"));\n }\n}\n//# sourceMappingURL=displayAlreadyInitializedError.js.map","import { monitor } from '../tools/monitor';\nimport { getZoneJsOriginalValue } from '../tools/getZoneJsOriginalValue';\n/**\n * Add an event listener to an event target object (Window, Element, mock object...). This provides\n * a few conveniences compared to using `element.addEventListener` directly:\n *\n * * supports IE11 by: using an option object only if needed and emulating the `once` option\n *\n * * wraps the listener with a `monitor` function\n *\n * * returns a `stop` function to remove the listener\n */\nexport function addEventListener(configuration, eventTarget, eventName, listener, options) {\n return addEventListeners(configuration, eventTarget, [eventName], listener, options);\n}\n/**\n * Add event listeners to an event target object (Window, Element, mock object...). This provides\n * a few conveniences compared to using `element.addEventListener` directly:\n *\n * * supports IE11 by: using an option object only if needed and emulating the `once` option\n *\n * * wraps the listener with a `monitor` function\n *\n * * returns a `stop` function to remove the listener\n *\n * * with `once: true`, the listener will be called at most once, even if different events are listened\n */\nexport function addEventListeners(configuration, eventTarget, eventNames, listener, _a) {\n var _b = _a === void 0 ? {} : _a, once = _b.once, capture = _b.capture, passive = _b.passive;\n var listenerWithMonitor = monitor(function (event) {\n if (!event.isTrusted && !event.__ddIsTrusted && !configuration.allowUntrustedEvents) {\n return;\n }\n if (once) {\n stop();\n }\n listener(event);\n });\n var options = passive ? { capture: capture, passive: passive } : capture;\n // Use the window.EventTarget.prototype when possible to avoid wrong overrides (e.g: https://github.com/salesforce/lwc/issues/1824)\n var listenerTarget = window.EventTarget && eventTarget instanceof EventTarget ? window.EventTarget.prototype : eventTarget;\n var add = getZoneJsOriginalValue(listenerTarget, 'addEventListener');\n eventNames.forEach(function (eventName) { return add.call(eventTarget, eventName, listenerWithMonitor, options); });\n function stop() {\n var remove = getZoneJsOriginalValue(listenerTarget, 'removeEventListener');\n eventNames.forEach(function (eventName) { return remove.call(eventTarget, eventName, listenerWithMonitor, options); });\n }\n return {\n stop: stop,\n };\n}\n//# sourceMappingURL=addEventListener.js.map","import { toStackTraceString } from '../../tools/stackTrace/handlingStack';\nimport { monitor } from '../../tools/monitor';\nimport { mergeObservables, Observable } from '../../tools/observable';\nimport { addEventListener } from '../../browser/addEventListener';\nimport { assign, includes } from '../../tools/utils/polyfills';\nimport { safeTruncate } from '../../tools/utils/stringUtils';\nimport { ErrorSource } from '../error/error.types';\nimport { clocksNow } from '../../tools/utils/timeUtils';\nexport var RawReportType = {\n intervention: 'intervention',\n deprecation: 'deprecation',\n cspViolation: 'csp_violation',\n};\nexport function initReportObservable(configuration, apis) {\n var observables = [];\n if (includes(apis, RawReportType.cspViolation)) {\n observables.push(createCspViolationReportObservable(configuration));\n }\n var reportTypes = apis.filter(function (api) { return api !== RawReportType.cspViolation; });\n if (reportTypes.length) {\n observables.push(createReportObservable(reportTypes));\n }\n return mergeObservables.apply(void 0, observables);\n}\nfunction createReportObservable(reportTypes) {\n return new Observable(function (observable) {\n if (!window.ReportingObserver) {\n return;\n }\n var handleReports = monitor(function (reports, _) {\n return reports.forEach(function (report) { return observable.notify(buildRawReportErrorFromReport(report)); });\n });\n var observer = new window.ReportingObserver(handleReports, {\n types: reportTypes,\n buffered: true,\n });\n observer.observe();\n return function () {\n observer.disconnect();\n };\n });\n}\nfunction createCspViolationReportObservable(configuration) {\n return new Observable(function (observable) {\n var stop = addEventListener(configuration, document, \"securitypolicyviolation\" /* DOM_EVENT.SECURITY_POLICY_VIOLATION */, function (event) {\n observable.notify(buildRawReportErrorFromCspViolation(event));\n }).stop;\n return stop;\n });\n}\nfunction buildRawReportErrorFromReport(report) {\n var type = report.type, body = report.body;\n return buildRawReportError({\n type: body.id,\n message: \"\".concat(type, \": \").concat(body.message),\n originalError: report,\n stack: buildStack(body.id, body.message, body.sourceFile, body.lineNumber, body.columnNumber),\n });\n}\nfunction buildRawReportErrorFromCspViolation(event) {\n var message = \"'\".concat(event.blockedURI, \"' blocked by '\").concat(event.effectiveDirective, \"' directive\");\n return buildRawReportError({\n type: event.effectiveDirective,\n message: \"\".concat(RawReportType.cspViolation, \": \").concat(message),\n originalError: event,\n csp: {\n disposition: event.disposition,\n },\n stack: buildStack(event.effectiveDirective, event.originalPolicy\n ? \"\".concat(message, \" of the policy \\\"\").concat(safeTruncate(event.originalPolicy, 100, '...'), \"\\\"\")\n : 'no policy', event.sourceFile, event.lineNumber, event.columnNumber),\n });\n}\nfunction buildRawReportError(partial) {\n return assign({\n startClocks: clocksNow(),\n source: ErrorSource.REPORT,\n handling: \"unhandled\" /* ErrorHandling.UNHANDLED */,\n }, partial);\n}\nfunction buildStack(name, message, sourceFile, lineNumber, columnNumber) {\n return sourceFile\n ? toStackTraceString({\n name: name,\n message: message,\n stack: [\n {\n func: '?',\n url: sourceFile,\n line: lineNumber !== null && lineNumber !== void 0 ? lineNumber : undefined,\n column: columnNumber !== null && columnNumber !== void 0 ? columnNumber : undefined,\n },\n ],\n })\n : undefined;\n}\n//# sourceMappingURL=reportObservable.js.map","export function sendToExtension(type, payload) {\n var callback = window.__ddBrowserSdkExtensionCallback;\n if (callback) {\n callback({ type: type, payload: payload });\n }\n}\n//# sourceMappingURL=sendToExtension.js.map","import { getType } from './utils/typeUtils';\n/**\n * Iterate over source and affect its sub values into destination, recursively.\n * If the source and destination can't be merged, return source.\n */\nexport function mergeInto(destination, source, circularReferenceChecker) {\n if (circularReferenceChecker === void 0) { circularReferenceChecker = createCircularReferenceChecker(); }\n // ignore the source if it is undefined\n if (source === undefined) {\n return destination;\n }\n if (typeof source !== 'object' || source === null) {\n // primitive values - just return source\n return source;\n }\n else if (source instanceof Date) {\n return new Date(source.getTime());\n }\n else if (source instanceof RegExp) {\n var flags = source.flags ||\n // old browsers compatibility\n [\n source.global ? 'g' : '',\n source.ignoreCase ? 'i' : '',\n source.multiline ? 'm' : '',\n source.sticky ? 'y' : '',\n source.unicode ? 'u' : '',\n ].join('');\n return new RegExp(source.source, flags);\n }\n if (circularReferenceChecker.hasAlreadyBeenSeen(source)) {\n // remove circular references\n return undefined;\n }\n else if (Array.isArray(source)) {\n var merged_1 = Array.isArray(destination) ? destination : [];\n for (var i = 0; i < source.length; ++i) {\n merged_1[i] = mergeInto(merged_1[i], source[i], circularReferenceChecker);\n }\n return merged_1;\n }\n var merged = getType(destination) === 'object' ? destination : {};\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n merged[key] = mergeInto(merged[key], source[key], circularReferenceChecker);\n }\n }\n return merged;\n}\n/**\n * A simplistic implementation of a deep clone algorithm.\n * Caveats:\n * - It doesn't maintain prototype chains - don't use with instances of custom classes.\n * - It doesn't handle Map and Set\n */\nexport function deepClone(value) {\n return mergeInto(undefined, value);\n}\nexport function combine() {\n var sources = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n sources[_i] = arguments[_i];\n }\n var destination;\n for (var _a = 0, sources_1 = sources; _a < sources_1.length; _a++) {\n var source = sources_1[_a];\n // Ignore any undefined or null sources.\n if (source === undefined || source === null) {\n continue;\n }\n destination = mergeInto(destination, source);\n }\n return destination;\n}\nfunction createCircularReferenceChecker() {\n if (typeof WeakSet !== 'undefined') {\n var set_1 = new WeakSet();\n return {\n hasAlreadyBeenSeen: function (value) {\n var has = set_1.has(value);\n if (!has) {\n set_1.add(value);\n }\n return has;\n },\n };\n }\n var array = [];\n return {\n hasAlreadyBeenSeen: function (value) {\n var has = array.indexOf(value) >= 0;\n if (!has) {\n array.push(value);\n }\n return has;\n },\n };\n}\n//# sourceMappingURL=mergeInto.js.map","export function getConnectivity() {\n var _a;\n var navigator = window.navigator;\n return {\n status: navigator.onLine ? 'connected' : 'not_connected',\n interfaces: navigator.connection && navigator.connection.type ? [navigator.connection.type] : undefined,\n effective_type: (_a = navigator.connection) === null || _a === void 0 ? void 0 : _a.effectiveType,\n };\n}\n//# sourceMappingURL=connectivity.js.map","import { arrayFrom } from './polyfills';\nexport function removeDuplicates(array) {\n var set = new Set();\n array.forEach(function (item) { return set.add(item); });\n return arrayFrom(set);\n}\nexport function removeItem(array, item) {\n var index = array.indexOf(item);\n if (index >= 0) {\n array.splice(index, 1);\n }\n}\n//# sourceMappingURL=arrayUtils.js.map","import { removeItem } from './utils/arrayUtils';\nvar BUFFER_LIMIT = 500;\nexport function createBoundedBuffer() {\n var buffer = [];\n var add = function (callback) {\n var length = buffer.push(callback);\n if (length > BUFFER_LIMIT) {\n buffer.splice(0, 1);\n }\n };\n var remove = function (callback) {\n removeItem(buffer, callback);\n };\n var drain = function (arg) {\n buffer.forEach(function (callback) { return callback(arg); });\n buffer.length = 0;\n };\n return {\n add: add,\n remove: remove,\n drain: drain,\n };\n}\n//# sourceMappingURL=boundedBuffer.js.map","export var TelemetryType = {\n log: 'log',\n configuration: 'configuration',\n usage: 'usage',\n};\n//# sourceMappingURL=rawTelemetryEvent.types.js.map","import { ConsoleApiName } from '../../tools/display';\nimport { NO_ERROR_STACK_PRESENT_MESSAGE, isError } from '../error/error';\nimport { toStackTraceString } from '../../tools/stackTrace/handlingStack';\nimport { getExperimentalFeatures } from '../../tools/experimentalFeatures';\nimport { INTAKE_SITE_STAGING, INTAKE_SITE_US1_FED } from '../configuration';\nimport { Observable } from '../../tools/observable';\nimport { timeStampNow } from '../../tools/utils/timeUtils';\nimport { displayIfDebugEnabled, startMonitorErrorCollection } from '../../tools/monitor';\nimport { sendToExtension } from '../../tools/sendToExtension';\nimport { startsWith, arrayFrom, includes, assign } from '../../tools/utils/polyfills';\nimport { performDraw } from '../../tools/utils/numberUtils';\nimport { jsonStringify } from '../../tools/serialisation/jsonStringify';\nimport { combine } from '../../tools/mergeInto';\nimport { computeStackTrace } from '../../tools/stackTrace/computeStackTrace';\nimport { getConnectivity } from '../connectivity';\nimport { createBoundedBuffer } from '../../tools/boundedBuffer';\nimport { TelemetryType } from './rawTelemetryEvent.types';\nvar ALLOWED_FRAME_URLS = [\n 'https://www.datadoghq-browser-agent.com',\n 'https://www.datad0g-browser-agent.com',\n 'https://d3uc069fcn7uxw.cloudfront.net',\n 'https://d20xtzwzcl0ceb.cloudfront.net',\n 'http://localhost',\n '',\n];\nvar TELEMETRY_EXCLUDED_SITES = [INTAKE_SITE_US1_FED];\n// eslint-disable-next-line local-rules/disallow-side-effects\nvar preStartTelemetryBuffer = createBoundedBuffer();\nvar onRawTelemetryEventCollected = function (event) {\n preStartTelemetryBuffer.add(function () { return onRawTelemetryEventCollected(event); });\n};\nexport function startTelemetry(telemetryService, configuration) {\n var _a;\n var contextProvider;\n var observable = new Observable();\n var alreadySentEvents = new Set();\n var telemetryEnabled = !includes(TELEMETRY_EXCLUDED_SITES, configuration.site) && performDraw(configuration.telemetrySampleRate);\n var telemetryEnabledPerType = (_a = {},\n _a[TelemetryType.log] = telemetryEnabled,\n _a[TelemetryType.configuration] = telemetryEnabled && performDraw(configuration.telemetryConfigurationSampleRate),\n _a[TelemetryType.usage] = telemetryEnabled && performDraw(configuration.telemetryUsageSampleRate),\n _a);\n var runtimeEnvInfo = getRuntimeEnvInfo();\n onRawTelemetryEventCollected = function (rawEvent) {\n var stringifiedEvent = jsonStringify(rawEvent);\n if (telemetryEnabledPerType[rawEvent.type] &&\n alreadySentEvents.size < configuration.maxTelemetryEventsPerPage &&\n !alreadySentEvents.has(stringifiedEvent)) {\n var event_1 = toTelemetryEvent(telemetryService, rawEvent, runtimeEnvInfo);\n observable.notify(event_1);\n sendToExtension('telemetry', event_1);\n alreadySentEvents.add(stringifiedEvent);\n }\n };\n startMonitorErrorCollection(addTelemetryError);\n function toTelemetryEvent(telemetryService, event, runtimeEnvInfo) {\n return combine({\n type: 'telemetry',\n date: timeStampNow(),\n service: telemetryService,\n version: \"5.35.0\",\n source: 'browser',\n _dd: {\n format_version: 2,\n },\n telemetry: combine(event, {\n runtime_env: runtimeEnvInfo,\n connectivity: getConnectivity(),\n sdk_setup: \"npm\",\n }),\n experimental_features: arrayFrom(getExperimentalFeatures()),\n }, contextProvider !== undefined ? contextProvider() : {});\n }\n return {\n setContextProvider: function (provider) {\n contextProvider = provider;\n },\n observable: observable,\n enabled: telemetryEnabled,\n };\n}\nfunction getRuntimeEnvInfo() {\n return {\n is_local_file: window.location.protocol === 'file:',\n is_worker: 'WorkerGlobalScope' in self,\n };\n}\nexport function startFakeTelemetry() {\n var events = [];\n onRawTelemetryEventCollected = function (event) {\n events.push(event);\n };\n return events;\n}\n// need to be called after telemetry context is provided and observers are registered\nexport function drainPreStartTelemetry() {\n preStartTelemetryBuffer.drain();\n}\nexport function resetTelemetry() {\n preStartTelemetryBuffer = createBoundedBuffer();\n onRawTelemetryEventCollected = function (event) {\n preStartTelemetryBuffer.add(function () { return onRawTelemetryEventCollected(event); });\n };\n}\n/**\n * Avoid mixing telemetry events from different data centers\n * but keep replicating staging events for reliability\n */\nexport function isTelemetryReplicationAllowed(configuration) {\n return configuration.site === INTAKE_SITE_STAGING;\n}\nexport function addTelemetryDebug(message, context) {\n displayIfDebugEnabled(ConsoleApiName.debug, message, context);\n onRawTelemetryEventCollected(assign({\n type: TelemetryType.log,\n message: message,\n status: \"debug\" /* StatusType.debug */,\n }, context));\n}\nexport function addTelemetryError(e, context) {\n onRawTelemetryEventCollected(assign({\n type: TelemetryType.log,\n status: \"error\" /* StatusType.error */,\n }, formatError(e), context));\n}\nexport function addTelemetryConfiguration(configuration) {\n onRawTelemetryEventCollected({\n type: TelemetryType.configuration,\n configuration: configuration,\n });\n}\nexport function addTelemetryUsage(usage) {\n onRawTelemetryEventCollected({\n type: TelemetryType.usage,\n usage: usage,\n });\n}\nexport function formatError(e) {\n if (isError(e)) {\n var stackTrace = computeStackTrace(e);\n return {\n error: {\n kind: stackTrace.name,\n stack: toStackTraceString(scrubCustomerFrames(stackTrace)),\n },\n message: stackTrace.message,\n };\n }\n return {\n error: {\n stack: NO_ERROR_STACK_PRESENT_MESSAGE,\n },\n message: \"\".concat(\"Uncaught\" /* NonErrorPrefix.UNCAUGHT */, \" \").concat(jsonStringify(e)),\n };\n}\nexport function scrubCustomerFrames(stackTrace) {\n stackTrace.stack = stackTrace.stack.filter(function (frame) { return !frame.url || ALLOWED_FRAME_URLS.some(function (allowedFrameUrl) { return startsWith(frame.url, allowedFrameUrl); }); });\n return stackTrace;\n}\n//# sourceMappingURL=telemetry.js.map","import { setInterval, clearInterval } from './timer';\nimport { removeItem } from './utils/arrayUtils';\nimport { addDuration, relativeNow, ONE_MINUTE } from './utils/timeUtils';\nvar END_OF_TIMES = Infinity;\nexport var CLEAR_OLD_VALUES_INTERVAL = ONE_MINUTE;\nexport function createValueHistory(_a) {\n var expireDelay = _a.expireDelay, maxEntries = _a.maxEntries;\n var entries = [];\n var clearOldValuesInterval = setInterval(function () { return clearOldValues(); }, CLEAR_OLD_VALUES_INTERVAL);\n function clearOldValues() {\n var oldTimeThreshold = relativeNow() - expireDelay;\n while (entries.length > 0 && entries[entries.length - 1].endTime < oldTimeThreshold) {\n entries.pop();\n }\n }\n /**\n * Add a value to the history associated with a start time. Returns a reference to this newly\n * added entry that can be removed or closed.\n */\n function add(value, startTime) {\n var entry = {\n value: value,\n startTime: startTime,\n endTime: END_OF_TIMES,\n remove: function () {\n removeItem(entries, entry);\n },\n close: function (endTime) {\n entry.endTime = endTime;\n },\n };\n if (maxEntries && entries.length >= maxEntries) {\n entries.pop();\n }\n entries.unshift(entry);\n return entry;\n }\n /**\n * Return the latest value that was active during `startTime`, or the currently active value\n * if no `startTime` is provided. This method assumes that entries are not overlapping.\n *\n * If `option.returnInactive` is true, returns the value at `startTime` (active or not).\n */\n function find(startTime, options) {\n if (startTime === void 0) { startTime = END_OF_TIMES; }\n if (options === void 0) { options = { returnInactive: false }; }\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\n var entry = entries_1[_i];\n if (entry.startTime <= startTime) {\n if (options.returnInactive || startTime <= entry.endTime) {\n return entry.value;\n }\n break;\n }\n }\n }\n /**\n * Helper function to close the currently active value, if any. This method assumes that entries\n * are not overlapping.\n */\n function closeActive(endTime) {\n var latestEntry = entries[0];\n if (latestEntry && latestEntry.endTime === END_OF_TIMES) {\n latestEntry.close(endTime);\n }\n }\n /**\n * Return all values with an active period overlapping with the duration,\n * or all values that were active during `startTime` if no duration is provided,\n * or all currently active values if no `startTime` is provided.\n */\n function findAll(startTime, duration) {\n if (startTime === void 0) { startTime = END_OF_TIMES; }\n if (duration === void 0) { duration = 0; }\n var endTime = addDuration(startTime, duration);\n return entries\n .filter(function (entry) { return entry.startTime <= endTime && startTime <= entry.endTime; })\n .map(function (entry) { return entry.value; });\n }\n /**\n * Remove all entries from this collection.\n */\n function reset() {\n entries = [];\n }\n /**\n * Stop internal garbage collection of past entries.\n */\n function stop() {\n clearInterval(clearOldValuesInterval);\n }\n return { add: add, find: find, closeActive: closeActive, findAll: findAll, reset: reset, stop: stop };\n}\n//# sourceMappingURL=valueHistory.js.map","import { Observable } from '../../tools/observable';\nimport { createValueHistory } from '../../tools/valueHistory';\nimport { relativeNow, clocksOrigin, ONE_MINUTE } from '../../tools/utils/timeUtils';\nimport { addEventListener, addEventListeners } from '../../browser/addEventListener';\nimport { clearInterval, setInterval } from '../../tools/timer';\nimport { SESSION_TIME_OUT_DELAY } from './sessionConstants';\nimport { startSessionStore } from './sessionStore';\nexport var VISIBILITY_CHECK_DELAY = ONE_MINUTE;\nvar SESSION_CONTEXT_TIMEOUT_DELAY = SESSION_TIME_OUT_DELAY;\nvar stopCallbacks = [];\nexport function startSessionManager(configuration, productKey, computeSessionState, trackingConsentState) {\n var renewObservable = new Observable();\n var expireObservable = new Observable();\n // TODO - Improve configuration type and remove assertion\n var sessionStore = startSessionStore(configuration.sessionStoreStrategyType, productKey, computeSessionState);\n stopCallbacks.push(function () { return sessionStore.stop(); });\n var sessionContextHistory = createValueHistory({\n expireDelay: SESSION_CONTEXT_TIMEOUT_DELAY,\n });\n stopCallbacks.push(function () { return sessionContextHistory.stop(); });\n sessionStore.renewObservable.subscribe(function () {\n sessionContextHistory.add(buildSessionContext(), relativeNow());\n renewObservable.notify();\n });\n sessionStore.expireObservable.subscribe(function () {\n expireObservable.notify();\n sessionContextHistory.closeActive(relativeNow());\n });\n // We expand/renew session unconditionally as tracking consent is always granted when the session\n // manager is started.\n sessionStore.expandOrRenewSession();\n sessionContextHistory.add(buildSessionContext(), clocksOrigin().relative);\n trackingConsentState.observable.subscribe(function () {\n if (trackingConsentState.isGranted()) {\n sessionStore.expandOrRenewSession();\n }\n else {\n sessionStore.expire();\n }\n });\n trackActivity(configuration, function () {\n if (trackingConsentState.isGranted()) {\n sessionStore.expandOrRenewSession();\n }\n });\n trackVisibility(configuration, function () { return sessionStore.expandSession(); });\n trackResume(configuration, function () { return sessionStore.restartSession(); });\n function buildSessionContext() {\n return {\n id: sessionStore.getSession().id,\n trackingType: sessionStore.getSession()[productKey],\n isReplayForced: !!sessionStore.getSession().forcedReplay,\n anonymousId: sessionStore.getSession().anonymousId,\n };\n }\n return {\n findSession: function (startTime, options) { return sessionContextHistory.find(startTime, options); },\n renewObservable: renewObservable,\n expireObservable: expireObservable,\n sessionStateUpdateObservable: sessionStore.sessionStateUpdateObservable,\n expire: sessionStore.expire,\n updateSessionState: sessionStore.updateSessionState,\n };\n}\nexport function stopSessionManager() {\n stopCallbacks.forEach(function (e) { return e(); });\n stopCallbacks = [];\n}\nfunction trackActivity(configuration, expandOrRenewSession) {\n var stop = addEventListeners(configuration, window, [\"click\" /* DOM_EVENT.CLICK */, \"touchstart\" /* DOM_EVENT.TOUCH_START */, \"keydown\" /* DOM_EVENT.KEY_DOWN */, \"scroll\" /* DOM_EVENT.SCROLL */], expandOrRenewSession, { capture: true, passive: true }).stop;\n stopCallbacks.push(stop);\n}\nfunction trackVisibility(configuration, expandSession) {\n var expandSessionWhenVisible = function () {\n if (document.visibilityState === 'visible') {\n expandSession();\n }\n };\n var stop = addEventListener(configuration, document, \"visibilitychange\" /* DOM_EVENT.VISIBILITY_CHANGE */, expandSessionWhenVisible).stop;\n stopCallbacks.push(stop);\n var visibilityCheckInterval = setInterval(expandSessionWhenVisible, VISIBILITY_CHECK_DELAY);\n stopCallbacks.push(function () {\n clearInterval(visibilityCheckInterval);\n });\n}\nfunction trackResume(configuration, cb) {\n var stop = addEventListener(configuration, window, \"resume\" /* DOM_EVENT.RESUME */, cb, { capture: true }).stop;\n stopCallbacks.push(stop);\n}\n//# sourceMappingURL=sessionManager.js.map","export function isServerError(status) {\n return status >= 500;\n}\nexport function tryToClone(response) {\n try {\n return response.clone();\n }\n catch (_a) {\n // clone can throw if the response has already been used by another instrumentation or is disturbed\n return;\n }\n}\n//# sourceMappingURL=responseUtils.js.map","import { setTimeout } from '../tools/timer';\nimport { clocksNow, ONE_MINUTE, ONE_SECOND } from '../tools/utils/timeUtils';\nimport { ONE_MEBI_BYTE, ONE_KIBI_BYTE } from '../tools/utils/byteUtils';\nimport { isServerError } from '../tools/utils/responseUtils';\nimport { ErrorSource } from '../domain/error/error.types';\nexport var MAX_ONGOING_BYTES_COUNT = 80 * ONE_KIBI_BYTE;\nexport var MAX_ONGOING_REQUESTS = 32;\nexport var MAX_QUEUE_BYTES_COUNT = 3 * ONE_MEBI_BYTE;\nexport var MAX_BACKOFF_TIME = ONE_MINUTE;\nexport var INITIAL_BACKOFF_TIME = ONE_SECOND;\nexport function sendWithRetryStrategy(payload, state, sendStrategy, trackType, reportError) {\n if (state.transportStatus === 0 /* TransportStatus.UP */ &&\n state.queuedPayloads.size() === 0 &&\n state.bandwidthMonitor.canHandle(payload)) {\n send(payload, state, sendStrategy, {\n onSuccess: function () { return retryQueuedPayloads(0 /* RetryReason.AFTER_SUCCESS */, state, sendStrategy, trackType, reportError); },\n onFailure: function () {\n state.queuedPayloads.enqueue(payload);\n scheduleRetry(state, sendStrategy, trackType, reportError);\n },\n });\n }\n else {\n state.queuedPayloads.enqueue(payload);\n }\n}\nfunction scheduleRetry(state, sendStrategy, trackType, reportError) {\n if (state.transportStatus !== 2 /* TransportStatus.DOWN */) {\n return;\n }\n setTimeout(function () {\n var payload = state.queuedPayloads.first();\n send(payload, state, sendStrategy, {\n onSuccess: function () {\n state.queuedPayloads.dequeue();\n state.currentBackoffTime = INITIAL_BACKOFF_TIME;\n retryQueuedPayloads(1 /* RetryReason.AFTER_RESUME */, state, sendStrategy, trackType, reportError);\n },\n onFailure: function () {\n state.currentBackoffTime = Math.min(MAX_BACKOFF_TIME, state.currentBackoffTime * 2);\n scheduleRetry(state, sendStrategy, trackType, reportError);\n },\n });\n }, state.currentBackoffTime);\n}\nfunction send(payload, state, sendStrategy, _a) {\n var onSuccess = _a.onSuccess, onFailure = _a.onFailure;\n state.bandwidthMonitor.add(payload);\n sendStrategy(payload, function (response) {\n state.bandwidthMonitor.remove(payload);\n if (!shouldRetryRequest(response)) {\n state.transportStatus = 0 /* TransportStatus.UP */;\n onSuccess();\n }\n else {\n // do not consider transport down if another ongoing request could succeed\n state.transportStatus =\n state.bandwidthMonitor.ongoingRequestCount > 0 ? 1 /* TransportStatus.FAILURE_DETECTED */ : 2 /* TransportStatus.DOWN */;\n payload.retry = {\n count: payload.retry ? payload.retry.count + 1 : 1,\n lastFailureStatus: response.status,\n };\n onFailure();\n }\n });\n}\nfunction retryQueuedPayloads(reason, state, sendStrategy, trackType, reportError) {\n if (reason === 0 /* RetryReason.AFTER_SUCCESS */ && state.queuedPayloads.isFull() && !state.queueFullReported) {\n reportError({\n message: \"Reached max \".concat(trackType, \" events size queued for upload: \").concat(MAX_QUEUE_BYTES_COUNT / ONE_MEBI_BYTE, \"MiB\"),\n source: ErrorSource.AGENT,\n startClocks: clocksNow(),\n });\n state.queueFullReported = true;\n }\n var previousQueue = state.queuedPayloads;\n state.queuedPayloads = newPayloadQueue();\n while (previousQueue.size() > 0) {\n sendWithRetryStrategy(previousQueue.dequeue(), state, sendStrategy, trackType, reportError);\n }\n}\nfunction shouldRetryRequest(response) {\n return (response.type !== 'opaque' &&\n ((response.status === 0 && !navigator.onLine) ||\n response.status === 408 ||\n response.status === 429 ||\n isServerError(response.status)));\n}\nexport function newRetryState() {\n return {\n transportStatus: 0 /* TransportStatus.UP */,\n currentBackoffTime: INITIAL_BACKOFF_TIME,\n bandwidthMonitor: newBandwidthMonitor(),\n queuedPayloads: newPayloadQueue(),\n queueFullReported: false,\n };\n}\nfunction newPayloadQueue() {\n var queue = [];\n return {\n bytesCount: 0,\n enqueue: function (payload) {\n if (this.isFull()) {\n return;\n }\n queue.push(payload);\n this.bytesCount += payload.bytesCount;\n },\n first: function () {\n return queue[0];\n },\n dequeue: function () {\n var payload = queue.shift();\n if (payload) {\n this.bytesCount -= payload.bytesCount;\n }\n return payload;\n },\n size: function () {\n return queue.length;\n },\n isFull: function () {\n return this.bytesCount >= MAX_QUEUE_BYTES_COUNT;\n },\n };\n}\nfunction newBandwidthMonitor() {\n return {\n ongoingRequestCount: 0,\n ongoingByteCount: 0,\n canHandle: function (payload) {\n return (this.ongoingRequestCount === 0 ||\n (this.ongoingByteCount + payload.bytesCount <= MAX_ONGOING_BYTES_COUNT &&\n this.ongoingRequestCount < MAX_ONGOING_REQUESTS));\n },\n add: function (payload) {\n this.ongoingRequestCount += 1;\n this.ongoingByteCount += payload.bytesCount;\n },\n remove: function (payload) {\n this.ongoingRequestCount -= 1;\n this.ongoingByteCount -= payload.bytesCount;\n },\n };\n}\n//# sourceMappingURL=sendWithRetryStrategy.js.map","import { addTelemetryError } from '../domain/telemetry';\nimport { monitor } from '../tools/monitor';\nimport { addEventListener } from '../browser/addEventListener';\nimport { newRetryState, sendWithRetryStrategy } from './sendWithRetryStrategy';\nexport function createHttpRequest(endpointBuilder, bytesLimit, reportError) {\n var retryState = newRetryState();\n var sendStrategyForRetry = function (payload, onResponse) {\n return fetchKeepAliveStrategy(endpointBuilder, bytesLimit, payload, onResponse);\n };\n return {\n send: function (payload) {\n sendWithRetryStrategy(payload, retryState, sendStrategyForRetry, endpointBuilder.trackType, reportError);\n },\n /**\n * Since fetch keepalive behaves like regular fetch on Firefox,\n * keep using sendBeaconStrategy on exit\n */\n sendOnExit: function (payload) {\n sendBeaconStrategy(endpointBuilder, bytesLimit, payload);\n },\n };\n}\nfunction sendBeaconStrategy(endpointBuilder, bytesLimit, payload) {\n var canUseBeacon = !!navigator.sendBeacon && payload.bytesCount < bytesLimit;\n if (canUseBeacon) {\n try {\n var beaconUrl = endpointBuilder.build('beacon', payload);\n var isQueued = navigator.sendBeacon(beaconUrl, payload.data);\n if (isQueued) {\n return;\n }\n }\n catch (e) {\n reportBeaconError(e);\n }\n }\n var xhrUrl = endpointBuilder.build('xhr', payload);\n sendXHR(xhrUrl, payload.data);\n}\nvar hasReportedBeaconError = false;\nfunction reportBeaconError(e) {\n if (!hasReportedBeaconError) {\n hasReportedBeaconError = true;\n addTelemetryError(e);\n }\n}\nexport function fetchKeepAliveStrategy(endpointBuilder, bytesLimit, payload, onResponse) {\n var canUseKeepAlive = isKeepAliveSupported() && payload.bytesCount < bytesLimit;\n if (canUseKeepAlive) {\n var fetchUrl = endpointBuilder.build('fetch', payload);\n fetch(fetchUrl, { method: 'POST', body: payload.data, keepalive: true, mode: 'cors' }).then(monitor(function (response) { return onResponse === null || onResponse === void 0 ? void 0 : onResponse({ status: response.status, type: response.type }); }), monitor(function () {\n var xhrUrl = endpointBuilder.build('xhr', payload);\n // failed to queue the request\n sendXHR(xhrUrl, payload.data, onResponse);\n }));\n }\n else {\n var xhrUrl = endpointBuilder.build('xhr', payload);\n sendXHR(xhrUrl, payload.data, onResponse);\n }\n}\nfunction isKeepAliveSupported() {\n // Request can throw, cf https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#errors\n try {\n return window.Request && 'keepalive' in new Request('http://a');\n }\n catch (_a) {\n return false;\n }\n}\nexport function sendXHR(url, data, onResponse) {\n var request = new XMLHttpRequest();\n request.open('POST', url, true);\n if (data instanceof Blob) {\n // When using a Blob instance, IE does not use its 'type' to define the 'Content-Type' header\n // automatically, so the intake request ends up being rejected with an HTTP status 415\n // Defining the header manually fixes this issue.\n request.setRequestHeader('Content-Type', data.type);\n }\n addEventListener(\n // allow untrusted event to acount for synthetic event dispatched by third party xhr wrapper\n { allowUntrustedEvents: true }, request, 'loadend', function () {\n onResponse === null || onResponse === void 0 ? void 0 : onResponse({ status: request.status });\n }, {\n // prevent multiple onResponse callbacks\n // if the xhr instance is reused by a third party\n once: true,\n });\n request.send(data);\n}\n//# sourceMappingURL=httpRequest.js.map","import { endsWith, includes } from '../tools/utils/polyfills';\nimport { getGlobalObject } from '../tools/getGlobalObject';\nexport function getEventBridge() {\n var eventBridgeGlobal = getEventBridgeGlobal();\n if (!eventBridgeGlobal) {\n return;\n }\n return {\n getCapabilities: function () {\n var _a;\n return JSON.parse(((_a = eventBridgeGlobal.getCapabilities) === null || _a === void 0 ? void 0 : _a.call(eventBridgeGlobal)) || '[]');\n },\n getPrivacyLevel: function () {\n var _a;\n return (_a = eventBridgeGlobal.getPrivacyLevel) === null || _a === void 0 ? void 0 : _a.call(eventBridgeGlobal);\n },\n getAllowedWebViewHosts: function () {\n return JSON.parse(eventBridgeGlobal.getAllowedWebViewHosts());\n },\n send: function (eventType, event, viewId) {\n var view = viewId ? { id: viewId } : undefined;\n eventBridgeGlobal.send(JSON.stringify({ eventType: eventType, event: event, view: view }));\n },\n };\n}\nexport function bridgeSupports(capability) {\n var bridge = getEventBridge();\n return !!bridge && includes(bridge.getCapabilities(), capability);\n}\nexport function canUseEventBridge(currentHost) {\n var _a;\n if (currentHost === void 0) { currentHost = (_a = getGlobalObject().location) === null || _a === void 0 ? void 0 : _a.hostname; }\n var bridge = getEventBridge();\n return (!!bridge &&\n bridge\n .getAllowedWebViewHosts()\n .some(function (allowedHost) { return currentHost === allowedHost || endsWith(currentHost, \".\".concat(allowedHost)); }));\n}\nfunction getEventBridgeGlobal() {\n return getGlobalObject().DatadogEventBridge;\n}\n//# sourceMappingURL=eventBridge.js.map","import { Observable } from '../tools/observable';\nimport { objectValues, includes } from '../tools/utils/polyfills';\nimport { addEventListeners, addEventListener } from './addEventListener';\nexport var PageExitReason = {\n HIDDEN: 'visibility_hidden',\n UNLOADING: 'before_unload',\n PAGEHIDE: 'page_hide',\n FROZEN: 'page_frozen',\n};\nexport function createPageExitObservable(configuration) {\n return new Observable(function (observable) {\n var stopListeners = addEventListeners(configuration, window, [\"visibilitychange\" /* DOM_EVENT.VISIBILITY_CHANGE */, \"freeze\" /* DOM_EVENT.FREEZE */], function (event) {\n if (event.type === \"visibilitychange\" /* DOM_EVENT.VISIBILITY_CHANGE */ && document.visibilityState === 'hidden') {\n /**\n * Only event that guarantee to fire on mobile devices when the page transitions to background state\n * (e.g. when user switches to a different application, goes to homescreen, etc), or is being unloaded.\n */\n observable.notify({ reason: PageExitReason.HIDDEN });\n }\n else if (event.type === \"freeze\" /* DOM_EVENT.FREEZE */) {\n /**\n * After transitioning in background a tab can be freezed to preserve resources. (cf: https://developer.chrome.com/blog/page-lifecycle-api)\n * Allow to collect events happening between hidden and frozen state.\n */\n observable.notify({ reason: PageExitReason.FROZEN });\n }\n }, { capture: true }).stop;\n var stopBeforeUnloadListener = addEventListener(configuration, window, \"beforeunload\" /* DOM_EVENT.BEFORE_UNLOAD */, function () {\n observable.notify({ reason: PageExitReason.UNLOADING });\n }).stop;\n return function () {\n stopListeners();\n stopBeforeUnloadListener();\n };\n });\n}\nexport function isPageExitReason(reason) {\n return includes(objectValues(PageExitReason), reason);\n}\n//# sourceMappingURL=pageExitObservable.js.map","import { DOCS_TROUBLESHOOTING, MORE_DETAILS, display } from '../tools/display';\nimport { objectValues } from '../tools/utils/polyfills';\nimport { isPageExitReason } from '../browser/pageExitObservable';\nimport { jsonStringify } from '../tools/serialisation/jsonStringify';\nimport { computeBytesCount } from '../tools/utils/byteUtils';\nexport function createBatch(_a) {\n var encoder = _a.encoder, request = _a.request, flushController = _a.flushController, messageBytesLimit = _a.messageBytesLimit;\n var upsertBuffer = {};\n var flushSubscription = flushController.flushObservable.subscribe(function (event) { return flush(event); });\n function push(serializedMessage, estimatedMessageBytesCount, key) {\n flushController.notifyBeforeAddMessage(estimatedMessageBytesCount);\n if (key !== undefined) {\n upsertBuffer[key] = serializedMessage;\n flushController.notifyAfterAddMessage();\n }\n else {\n encoder.write(encoder.isEmpty ? serializedMessage : \"\\n\".concat(serializedMessage), function (realMessageBytesCount) {\n flushController.notifyAfterAddMessage(realMessageBytesCount - estimatedMessageBytesCount);\n });\n }\n }\n function hasMessageFor(key) {\n return key !== undefined && upsertBuffer[key] !== undefined;\n }\n function remove(key) {\n var removedMessage = upsertBuffer[key];\n delete upsertBuffer[key];\n var messageBytesCount = encoder.estimateEncodedBytesCount(removedMessage);\n flushController.notifyAfterRemoveMessage(messageBytesCount);\n }\n function addOrUpdate(message, key) {\n var serializedMessage = jsonStringify(message);\n var estimatedMessageBytesCount = encoder.estimateEncodedBytesCount(serializedMessage);\n if (estimatedMessageBytesCount >= messageBytesLimit) {\n 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\"));\n return;\n }\n if (hasMessageFor(key)) {\n remove(key);\n }\n push(serializedMessage, estimatedMessageBytesCount, key);\n }\n function flush(event) {\n var upsertMessages = objectValues(upsertBuffer).join('\\n');\n upsertBuffer = {};\n var isPageExit = isPageExitReason(event.reason);\n var send = isPageExit ? request.sendOnExit : request.send;\n if (isPageExit &&\n // Note: checking that the encoder is async is not strictly needed, but it's an optimization:\n // if the encoder is async we need to send two requests in some cases (one for encoded data\n // and the other for non-encoded data). But if it's not async, we don't have to worry about\n // it and always send a single request.\n encoder.isAsync) {\n var encoderResult = encoder.finishSync();\n // Send encoded messages\n if (encoderResult.outputBytesCount) {\n send(formatPayloadFromEncoder(encoderResult));\n }\n // Send messages that are not yet encoded at this point\n var pendingMessages = [encoderResult.pendingData, upsertMessages].filter(Boolean).join('\\n');\n if (pendingMessages) {\n send({\n data: pendingMessages,\n bytesCount: computeBytesCount(pendingMessages),\n });\n }\n }\n else {\n if (upsertMessages) {\n encoder.write(encoder.isEmpty ? upsertMessages : \"\\n\".concat(upsertMessages));\n }\n encoder.finish(function (encoderResult) {\n send(formatPayloadFromEncoder(encoderResult));\n });\n }\n }\n return {\n flushController: flushController,\n add: addOrUpdate,\n upsert: addOrUpdate,\n stop: flushSubscription.unsubscribe,\n };\n}\nfunction formatPayloadFromEncoder(encoderResult) {\n var data;\n if (typeof encoderResult.output === 'string') {\n data = encoderResult.output;\n }\n else {\n data = new Blob([encoderResult.output], {\n // This will set the 'Content-Type: text/plain' header. Reasoning:\n // * The intake rejects the request if there is no content type.\n // * The browser will issue CORS preflight requests if we set it to 'application/json', which\n // could induce higher intake load (and maybe has other impacts).\n // * Also it's not quite JSON, since we are concatenating multiple JSON objects separated by\n // new lines.\n type: 'text/plain',\n });\n }\n return {\n data: data,\n bytesCount: encoderResult.outputBytesCount,\n encoding: encoderResult.encoding,\n };\n}\n//# sourceMappingURL=batch.js.map","import { Observable } from '../tools/observable';\nimport { clearTimeout, setTimeout } from '../tools/timer';\n/**\n * Returns a \"flush controller\", responsible of notifying when flushing a pool of pending data needs\n * to happen. The implementation is designed to support both synchronous and asynchronous usages,\n * but relies on invariants described in each method documentation to keep a coherent state.\n */\nexport function createFlushController(_a) {\n var messagesLimit = _a.messagesLimit, bytesLimit = _a.bytesLimit, durationLimit = _a.durationLimit, pageExitObservable = _a.pageExitObservable, sessionExpireObservable = _a.sessionExpireObservable;\n var pageExitSubscription = pageExitObservable.subscribe(function (event) { return flush(event.reason); });\n var sessionExpireSubscription = sessionExpireObservable.subscribe(function () { return flush('session_expire'); });\n var flushObservable = new Observable(function () { return function () {\n pageExitSubscription.unsubscribe();\n sessionExpireSubscription.unsubscribe();\n }; });\n var currentBytesCount = 0;\n var currentMessagesCount = 0;\n function flush(flushReason) {\n if (currentMessagesCount === 0) {\n return;\n }\n var messagesCount = currentMessagesCount;\n var bytesCount = currentBytesCount;\n currentMessagesCount = 0;\n currentBytesCount = 0;\n cancelDurationLimitTimeout();\n flushObservable.notify({\n reason: flushReason,\n messagesCount: messagesCount,\n bytesCount: bytesCount,\n });\n }\n var durationLimitTimeoutId;\n function scheduleDurationLimitTimeout() {\n if (durationLimitTimeoutId === undefined) {\n durationLimitTimeoutId = setTimeout(function () {\n flush('duration_limit');\n }, durationLimit);\n }\n }\n function cancelDurationLimitTimeout() {\n clearTimeout(durationLimitTimeoutId);\n durationLimitTimeoutId = undefined;\n }\n return {\n flushObservable: flushObservable,\n get messagesCount() {\n return currentMessagesCount;\n },\n /**\n * Notifies that a message will be added to a pool of pending messages waiting to be flushed.\n *\n * This function needs to be called synchronously, right before adding the message, so no flush\n * event can happen after `notifyBeforeAddMessage` and before adding the message.\n *\n * @param estimatedMessageBytesCount: an estimation of the message bytes count once it is\n * actually added.\n */\n notifyBeforeAddMessage: function (estimatedMessageBytesCount) {\n if (currentBytesCount + estimatedMessageBytesCount >= bytesLimit) {\n flush('bytes_limit');\n }\n // Consider the message to be added now rather than in `notifyAfterAddMessage`, because if no\n // message was added yet and `notifyAfterAddMessage` is called asynchronously, we still want\n // to notify when a flush is needed (for example on page exit).\n currentMessagesCount += 1;\n currentBytesCount += estimatedMessageBytesCount;\n scheduleDurationLimitTimeout();\n },\n /**\n * Notifies that a message *was* added to a pool of pending messages waiting to be flushed.\n *\n * This function can be called asynchronously after the message was added, but in this case it\n * should not be called if a flush event occurred in between.\n *\n * @param messageBytesCountDiff: the difference between the estimated message bytes count and\n * its actual bytes count once added to the pool.\n */\n notifyAfterAddMessage: function (messageBytesCountDiff) {\n if (messageBytesCountDiff === void 0) { messageBytesCountDiff = 0; }\n currentBytesCount += messageBytesCountDiff;\n if (currentMessagesCount >= messagesLimit) {\n flush('messages_limit');\n }\n else if (currentBytesCount >= bytesLimit) {\n flush('bytes_limit');\n }\n },\n /**\n * Notifies that a message was removed from a pool of pending messages waiting to be flushed.\n *\n * This function needs to be called synchronously, right after removing the message, so no flush\n * event can happen after removing the message and before `notifyAfterRemoveMessage`.\n *\n * @param messageBytesCount: the message bytes count that was added to the pool. Should\n * correspond to the sum of bytes counts passed to `notifyBeforeAddMessage` and\n * `notifyAfterAddMessage`.\n */\n notifyAfterRemoveMessage: function (messageBytesCount) {\n currentBytesCount -= messageBytesCount;\n currentMessagesCount -= 1;\n if (currentMessagesCount === 0) {\n cancelDurationLimitTimeout();\n }\n },\n };\n}\n//# sourceMappingURL=flushController.js.map","import { createBatch } from './batch';\nimport { createHttpRequest } from './httpRequest';\nimport { createFlushController } from './flushController';\nexport function startBatchWithReplica(configuration, primary, replica, reportError, pageExitObservable, sessionExpireObservable, batchFactoryImp) {\n if (batchFactoryImp === void 0) { batchFactoryImp = createBatch; }\n var primaryBatch = createBatchFromConfig(configuration, primary);\n var replicaBatch = replica && createBatchFromConfig(configuration, replica);\n function createBatchFromConfig(configuration, _a) {\n var endpoint = _a.endpoint, encoder = _a.encoder;\n return batchFactoryImp({\n encoder: encoder,\n request: createHttpRequest(endpoint, configuration.batchBytesLimit, reportError),\n flushController: createFlushController({\n messagesLimit: configuration.batchMessagesLimit,\n bytesLimit: configuration.batchBytesLimit,\n durationLimit: configuration.flushTimeout,\n pageExitObservable: pageExitObservable,\n sessionExpireObservable: sessionExpireObservable,\n }),\n messageBytesLimit: configuration.messageBytesLimit,\n });\n }\n return {\n flushObservable: primaryBatch.flushController.flushObservable,\n add: function (message, replicated) {\n if (replicated === void 0) { replicated = true; }\n primaryBatch.add(message);\n if (replicaBatch && replicated) {\n replicaBatch.add(replica.transformMessage ? replica.transformMessage(message) : message);\n }\n },\n upsert: function (message, key) {\n primaryBatch.upsert(message, key);\n if (replicaBatch) {\n replicaBatch.upsert(replica.transformMessage ? replica.transformMessage(message) : message, key);\n }\n },\n stop: function () {\n primaryBatch.stop();\n if (replicaBatch) {\n replicaBatch.stop();\n }\n },\n };\n}\n//# sourceMappingURL=startBatchWithReplica.js.map","import { computeBytesCount } from './utils/byteUtils';\nexport function createIdentityEncoder() {\n var output = '';\n var outputBytesCount = 0;\n return {\n isAsync: false,\n get isEmpty() {\n return !output;\n },\n write: function (data, callback) {\n var additionalEncodedBytesCount = computeBytesCount(data);\n outputBytesCount += additionalEncodedBytesCount;\n output += data;\n if (callback) {\n callback(additionalEncodedBytesCount);\n }\n },\n finish: function (callback) {\n callback(this.finishSync());\n },\n finishSync: function () {\n var result = {\n output: output,\n outputBytesCount: outputBytesCount,\n rawBytesCount: outputBytesCount,\n pendingData: '',\n };\n output = '';\n outputBytesCount = 0;\n return result;\n },\n estimateEncodedBytesCount: function (data) {\n return data.length;\n },\n };\n}\n//# sourceMappingURL=encoder.js.map","// eslint-disable-next-line no-restricted-syntax\nvar AbstractLifeCycle = /** @class */ (function () {\n function AbstractLifeCycle() {\n this.callbacks = {};\n }\n AbstractLifeCycle.prototype.notify = function (eventType, data) {\n var eventCallbacks = this.callbacks[eventType];\n if (eventCallbacks) {\n eventCallbacks.forEach(function (callback) { return callback(data); });\n }\n };\n AbstractLifeCycle.prototype.subscribe = function (eventType, callback) {\n var _this = this;\n if (!this.callbacks[eventType]) {\n this.callbacks[eventType] = [];\n }\n this.callbacks[eventType].push(callback);\n return {\n unsubscribe: function () {\n _this.callbacks[eventType] = _this.callbacks[eventType].filter(function (other) { return callback !== other; });\n },\n };\n };\n return AbstractLifeCycle;\n}());\nexport { AbstractLifeCycle };\n//# sourceMappingURL=abstractLifeCycle.js.map","import { setTimeout } from '../../tools/timer';\nimport { clocksNow, ONE_MINUTE } from '../../tools/utils/timeUtils';\nimport { ErrorSource } from '../error/error.types';\nexport function createEventRateLimiter(eventType, limit, onLimitReached) {\n var eventCount = 0;\n var allowNextEvent = false;\n return {\n isLimitReached: function () {\n if (eventCount === 0) {\n setTimeout(function () {\n eventCount = 0;\n }, ONE_MINUTE);\n }\n eventCount += 1;\n if (eventCount <= limit || allowNextEvent) {\n allowNextEvent = false;\n return false;\n }\n if (eventCount === limit + 1) {\n allowNextEvent = true;\n try {\n onLimitReached({\n message: \"Reached max number of \".concat(eventType, \"s by minute: \").concat(limit),\n source: ErrorSource.AGENT,\n startClocks: clocksNow(),\n });\n }\n finally {\n allowNextEvent = false;\n }\n }\n return true;\n },\n };\n}\n//# sourceMappingURL=createEventRateLimiter.js.map","import { noop } from '../tools/utils/functionUtils';\nimport { addEventListener } from './addEventListener';\nexport function runOnReadyState(configuration, expectedReadyState, callback) {\n if (document.readyState === expectedReadyState || document.readyState === 'complete') {\n callback();\n return { stop: noop };\n }\n var eventName = expectedReadyState === 'complete' ? \"load\" /* DOM_EVENT.LOAD */ : \"DOMContentLoaded\" /* DOM_EVENT.DOM_CONTENT_LOADED */;\n return addEventListener(configuration, window, eventName, callback, { once: true });\n}\n//# sourceMappingURL=runOnReadyState.js.map","import { instrumentMethod } from '../tools/instrumentMethod';\nimport { Observable } from '../tools/observable';\nimport { elapsed, clocksNow, timeStampNow } from '../tools/utils/timeUtils';\nimport { normalizeUrl } from '../tools/utils/urlPolyfill';\nimport { shallowClone } from '../tools/utils/objectUtils';\nimport { addEventListener } from './addEventListener';\nvar xhrObservable;\nvar xhrContexts = new WeakMap();\nexport function initXhrObservable(configuration) {\n if (!xhrObservable) {\n xhrObservable = createXhrObservable(configuration);\n }\n return xhrObservable;\n}\nfunction createXhrObservable(configuration) {\n return new Observable(function (observable) {\n var stopInstrumentingStart = instrumentMethod(XMLHttpRequest.prototype, 'open', openXhr).stop;\n var stopInstrumentingSend = instrumentMethod(XMLHttpRequest.prototype, 'send', function (call) {\n sendXhr(call, configuration, observable);\n }, { computeHandlingStack: true }).stop;\n var stopInstrumentingAbort = instrumentMethod(XMLHttpRequest.prototype, 'abort', abortXhr).stop;\n return function () {\n stopInstrumentingStart();\n stopInstrumentingSend();\n stopInstrumentingAbort();\n };\n });\n}\nfunction openXhr(_a) {\n var xhr = _a.target, _b = _a.parameters, method = _b[0], url = _b[1];\n xhrContexts.set(xhr, {\n state: 'open',\n method: String(method).toUpperCase(),\n url: normalizeUrl(String(url)),\n });\n}\nfunction sendXhr(_a, configuration, observable) {\n var xhr = _a.target, handlingStack = _a.handlingStack;\n var context = xhrContexts.get(xhr);\n if (!context) {\n return;\n }\n var startContext = context;\n startContext.state = 'start';\n startContext.startClocks = clocksNow();\n startContext.isAborted = false;\n startContext.xhr = xhr;\n startContext.handlingStack = handlingStack;\n var hasBeenReported = false;\n var stopInstrumentingOnReadyStateChange = instrumentMethod(xhr, 'onreadystatechange', function () {\n if (xhr.readyState === XMLHttpRequest.DONE) {\n // Try to report the XHR as soon as possible, because the XHR may be mutated by the\n // application during a future event. For example, Angular is calling .abort() on\n // completed requests during an onreadystatechange event, so the status becomes '0'\n // before the request is collected.\n onEnd();\n }\n }).stop;\n var onEnd = function () {\n unsubscribeLoadEndListener();\n stopInstrumentingOnReadyStateChange();\n if (hasBeenReported) {\n return;\n }\n hasBeenReported = true;\n var completeContext = context;\n completeContext.state = 'complete';\n completeContext.duration = elapsed(startContext.startClocks.timeStamp, timeStampNow());\n completeContext.status = xhr.status;\n observable.notify(shallowClone(completeContext));\n };\n var unsubscribeLoadEndListener = addEventListener(configuration, xhr, 'loadend', onEnd).stop;\n observable.notify(startContext);\n}\nfunction abortXhr(_a) {\n var xhr = _a.target;\n var context = xhrContexts.get(xhr);\n if (context) {\n context.isAborted = true;\n }\n}\n//# sourceMappingURL=xhrObservable.js.map","import { instrumentMethod } from '../tools/instrumentMethod';\nimport { monitor } from '../tools/monitor';\nimport { Observable } from '../tools/observable';\nimport { assign } from '../tools/utils/polyfills';\nimport { clocksNow } from '../tools/utils/timeUtils';\nimport { normalizeUrl } from '../tools/utils/urlPolyfill';\nvar fetchObservable;\nexport function initFetchObservable() {\n if (!fetchObservable) {\n fetchObservable = createFetchObservable();\n }\n return fetchObservable;\n}\nexport function resetFetchObservable() {\n fetchObservable = undefined;\n}\nfunction createFetchObservable() {\n return new Observable(function (observable) {\n if (!window.fetch) {\n return;\n }\n var stop = instrumentMethod(window, 'fetch', function (call) { return beforeSend(call, observable); }, {\n computeHandlingStack: true,\n }).stop;\n return stop;\n });\n}\nfunction beforeSend(_a, observable) {\n var parameters = _a.parameters, onPostCall = _a.onPostCall, handlingStack = _a.handlingStack;\n var input = parameters[0], init = parameters[1];\n var methodFromParams = init && init.method;\n if (methodFromParams === undefined && input instanceof Request) {\n methodFromParams = input.method;\n }\n var method = methodFromParams !== undefined ? String(methodFromParams).toUpperCase() : 'GET';\n var url = input instanceof Request ? input.url : normalizeUrl(String(input));\n var startClocks = clocksNow();\n var context = {\n state: 'start',\n init: init,\n input: input,\n method: method,\n startClocks: startClocks,\n url: url,\n handlingStack: handlingStack,\n };\n observable.notify(context);\n // Those properties can be changed by observable subscribers\n parameters[0] = context.input;\n parameters[1] = context.init;\n onPostCall(function (responsePromise) { return afterSend(observable, responsePromise, context); });\n}\nfunction afterSend(observable, responsePromise, startContext) {\n var context = startContext;\n function reportFetch(partialContext) {\n context.state = 'resolve';\n assign(context, partialContext);\n observable.notify(context);\n }\n responsePromise.then(monitor(function (response) {\n reportFetch({\n response: response,\n responseType: response.type,\n status: response.status,\n isAborted: false,\n });\n }), monitor(function (error) {\n var _a, _b;\n reportFetch({\n status: 0,\n isAborted: ((_b = (_a = context.init) === null || _a === void 0 ? void 0 : _a.signal) === null || _b === void 0 ? void 0 : _b.aborted) || (error instanceof DOMException && error.code === DOMException.ABORT_ERR),\n error: error,\n });\n }));\n}\n//# sourceMappingURL=fetchObservable.js.map","import { setTimeout, clearTimeout } from './timer';\nimport { monitor } from './monitor';\nimport { dateNow } from './utils/timeUtils';\n/**\n * 'requestIdleCallback' with a shim.\n */\nexport function requestIdleCallback(callback, opts) {\n // Note: check both 'requestIdleCallback' and 'cancelIdleCallback' existence because some polyfills only implement 'requestIdleCallback'.\n if (window.requestIdleCallback && window.cancelIdleCallback) {\n var id_1 = window.requestIdleCallback(monitor(callback), opts);\n return function () { return window.cancelIdleCallback(id_1); };\n }\n return requestIdleCallbackShim(callback);\n}\nexport var MAX_TASK_TIME = 50;\n/*\n * Shim from https://developer.chrome.com/blog/using-requestidlecallback#checking_for_requestidlecallback\n * Note: there is no simple way to support the \"timeout\" option, so we ignore it.\n */\nexport function requestIdleCallbackShim(callback) {\n var start = dateNow();\n var timeoutId = setTimeout(function () {\n callback({\n didTimeout: false,\n timeRemaining: function () { return Math.max(0, MAX_TASK_TIME - (dateNow() - start)); },\n });\n }, 0);\n return function () { return clearTimeout(timeoutId); };\n}\n//# sourceMappingURL=requestIdleCallback.js.map","import { ONE_SECOND } from './utils/timeUtils';\nimport { requestIdleCallback } from './requestIdleCallback';\n/**\n * Maximum delay before starting to execute tasks in the queue. We don't want to wait too long\n * before running tasks, as it might hurt reliability (ex: if the user navigates away, we might lose\n * the opportunity to send some data). We also don't want to run tasks too often, as it might hurt\n * performance.\n */\nvar IDLE_CALLBACK_TIMEOUT = ONE_SECOND;\n/**\n * Maximum amount of time allocated to running tasks when a timeout (`IDLE_CALLBACK_TIMEOUT`) is\n * reached. We should not run tasks for too long as it will hurt performance, but we should still\n * run some tasks to avoid postponing them forever.\n *\n * Rational: Running tasks for 30ms every second (IDLE_CALLBACK_TIMEOUT) should be acceptable.\n */\nexport var MAX_EXECUTION_TIME_ON_TIMEOUT = 30;\nexport function createTaskQueue() {\n var pendingTasks = [];\n function run(deadline) {\n var executionTimeRemaining;\n if (deadline.didTimeout) {\n var start_1 = performance.now();\n executionTimeRemaining = function () { return MAX_EXECUTION_TIME_ON_TIMEOUT - (performance.now() - start_1); };\n }\n else {\n executionTimeRemaining = deadline.timeRemaining.bind(deadline);\n }\n while (executionTimeRemaining() > 0 && pendingTasks.length) {\n pendingTasks.shift()();\n }\n if (pendingTasks.length) {\n scheduleNextRun();\n }\n }\n function scheduleNextRun() {\n requestIdleCallback(run, { timeout: IDLE_CALLBACK_TIMEOUT });\n }\n return {\n push: function (task) {\n if (pendingTasks.push(task) === 1) {\n scheduleNextRun();\n }\n },\n };\n}\n//# sourceMappingURL=taskQueue.js.map","import { flattenErrorCauses, isError, tryToGetFingerprint } from '../error/error';\nimport { mergeObservables, Observable } from '../../tools/observable';\nimport { ConsoleApiName, globalConsole } from '../../tools/display';\nimport { callMonitored } from '../../tools/monitor';\nimport { sanitize } from '../../tools/serialisation/sanitize';\nimport { find } from '../../tools/utils/polyfills';\nimport { jsonStringify } from '../../tools/serialisation/jsonStringify';\nimport { ErrorSource } from '../error/error.types';\nimport { computeStackTrace } from '../../tools/stackTrace/computeStackTrace';\nimport { createHandlingStack, toStackTraceString, formatErrorMessage } from '../../tools/stackTrace/handlingStack';\nimport { clocksNow } from '../../tools/utils/timeUtils';\nvar consoleObservablesByApi = {};\nexport function initConsoleObservable(apis) {\n var consoleObservables = apis.map(function (api) {\n if (!consoleObservablesByApi[api]) {\n consoleObservablesByApi[api] = createConsoleObservable(api); // we are sure that the observable created for this api will yield the expected ConsoleLog type\n }\n return consoleObservablesByApi[api];\n });\n return mergeObservables.apply(void 0, consoleObservables);\n}\nexport function resetConsoleObservable() {\n consoleObservablesByApi = {};\n}\nfunction createConsoleObservable(api) {\n return new Observable(function (observable) {\n var originalConsoleApi = globalConsole[api];\n globalConsole[api] = function () {\n var params = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n params[_i] = arguments[_i];\n }\n originalConsoleApi.apply(console, params);\n var handlingStack = createHandlingStack();\n callMonitored(function () {\n observable.notify(buildConsoleLog(params, api, handlingStack));\n });\n };\n return function () {\n globalConsole[api] = originalConsoleApi;\n };\n });\n}\nfunction buildConsoleLog(params, api, handlingStack) {\n var message = params.map(function (param) { return formatConsoleParameters(param); }).join(' ');\n var error;\n if (api === ConsoleApiName.error) {\n var firstErrorParam = find(params, isError);\n error = {\n stack: firstErrorParam ? toStackTraceString(computeStackTrace(firstErrorParam)) : undefined,\n fingerprint: tryToGetFingerprint(firstErrorParam),\n causes: firstErrorParam ? flattenErrorCauses(firstErrorParam, 'console') : undefined,\n startClocks: clocksNow(),\n message: message,\n source: ErrorSource.CONSOLE,\n handling: \"handled\" /* ErrorHandling.HANDLED */,\n handlingStack: handlingStack,\n };\n }\n return {\n api: api,\n message: message,\n error: error,\n handlingStack: handlingStack,\n };\n}\nfunction formatConsoleParameters(param) {\n if (typeof param === 'string') {\n return sanitize(param);\n }\n if (isError(param)) {\n return formatErrorMessage(computeStackTrace(param));\n }\n return jsonStringify(sanitize(param), undefined, 2);\n}\n//# sourceMappingURL=consoleObservable.js.map","import { deepClone } from '../../tools/mergeInto';\nimport { getType } from '../../tools/utils/typeUtils';\nimport { sanitize } from '../../tools/serialisation/sanitize';\nimport { Observable } from '../../tools/observable';\nexport function createContextManager(customerDataTracker) {\n var context = {};\n var changeObservable = new Observable();\n var contextManager = {\n getContext: function () { return deepClone(context); },\n setContext: function (newContext) {\n if (getType(newContext) === 'object') {\n context = sanitize(newContext);\n customerDataTracker === null || customerDataTracker === void 0 ? void 0 : customerDataTracker.updateCustomerData(context);\n }\n else {\n contextManager.clearContext();\n }\n changeObservable.notify();\n },\n setContextProperty: function (key, property) {\n context[key] = sanitize(property);\n customerDataTracker === null || customerDataTracker === void 0 ? void 0 : customerDataTracker.updateCustomerData(context);\n changeObservable.notify();\n },\n removeContextProperty: function (key) {\n delete context[key];\n customerDataTracker === null || customerDataTracker === void 0 ? void 0 : customerDataTracker.updateCustomerData(context);\n changeObservable.notify();\n },\n clearContext: function () {\n context = {};\n customerDataTracker === null || customerDataTracker === void 0 ? void 0 : customerDataTracker.resetCustomerData();\n changeObservable.notify();\n },\n changeObservable: changeObservable,\n };\n return contextManager;\n}\n//# sourceMappingURL=contextManager.js.map","import { addEventListener } from '../../browser/addEventListener';\nimport { combine } from '../../tools/mergeInto';\nvar CONTEXT_STORE_KEY_PREFIX = '_dd_c';\nvar storageListeners = [];\nexport function storeContextManager(configuration, contextManager, productKey, customerDataType) {\n var storageKey = buildStorageKey(productKey, customerDataType);\n storageListeners.push(addEventListener(configuration, window, \"storage\" /* DOM_EVENT.STORAGE */, function (_a) {\n var key = _a.key;\n if (storageKey === key) {\n synchronizeWithStorage();\n }\n }));\n contextManager.changeObservable.subscribe(dumpToStorage);\n contextManager.setContext(combine(getFromStorage(), contextManager.getContext()));\n function synchronizeWithStorage() {\n contextManager.setContext(getFromStorage());\n }\n function dumpToStorage() {\n localStorage.setItem(storageKey, JSON.stringify(contextManager.getContext()));\n }\n function getFromStorage() {\n var rawContext = localStorage.getItem(storageKey);\n return rawContext !== null ? JSON.parse(rawContext) : {};\n }\n}\nexport function buildStorageKey(productKey, customerDataType) {\n return \"\".concat(CONTEXT_STORE_KEY_PREFIX, \"_\").concat(productKey, \"_\").concat(customerDataType);\n}\nexport function removeStorageListeners() {\n storageListeners.map(function (listener) { return listener.stop(); });\n}\n//# sourceMappingURL=storeContextManager.js.map","import { ONE_KIBI_BYTE, computeBytesCount } from '../../tools/utils/byteUtils';\nimport { throttle } from '../../tools/utils/functionUtils';\nimport { jsonStringify } from '../../tools/serialisation/jsonStringify';\nimport { DOCS_TROUBLESHOOTING, MORE_DETAILS, display } from '../../tools/display';\nimport { isEmptyObject } from '../../tools/utils/objectUtils';\n// RUM and logs batch bytes limit is 16KB\n// ensure that we leave room for other event attributes and maintain a decent amount of event per batch\n// (3KB (customer data) + 1KB (other attributes)) * 4 (events per batch) = 16KB\nexport var CUSTOMER_DATA_BYTES_LIMIT = 3 * ONE_KIBI_BYTE;\n// We observed that the compression ratio is around 8 in general, but we also want to keep a margin\n// because some data might not be compressed (ex: last view update on page exit). We chose 16KiB\n// because it is also the limit of the 'batchBytesCount' that we use for RUM and Logs data, but this\n// is a bit arbitrary.\nexport var CUSTOMER_COMPRESSED_DATA_BYTES_LIMIT = 16 * ONE_KIBI_BYTE;\nexport var BYTES_COMPUTATION_THROTTLING_DELAY = 200;\nexport function createCustomerDataTrackerManager(compressionStatus) {\n if (compressionStatus === void 0) { compressionStatus = 2 /* CustomerDataCompressionStatus.Disabled */; }\n var customerDataTrackers = new Map();\n var alreadyWarned = false;\n function checkCustomerDataLimit(initialBytesCount) {\n if (initialBytesCount === void 0) { initialBytesCount = 0; }\n if (alreadyWarned || compressionStatus === 0 /* CustomerDataCompressionStatus.Unknown */) {\n return;\n }\n var bytesCountLimit = compressionStatus === 2 /* CustomerDataCompressionStatus.Disabled */\n ? CUSTOMER_DATA_BYTES_LIMIT\n : CUSTOMER_COMPRESSED_DATA_BYTES_LIMIT;\n var bytesCount = initialBytesCount;\n customerDataTrackers.forEach(function (tracker) {\n bytesCount += tracker.getBytesCount();\n });\n if (bytesCount > bytesCountLimit) {\n displayCustomerDataLimitReachedWarning(bytesCountLimit);\n alreadyWarned = true;\n }\n }\n return {\n /**\n * Creates a detached tracker. The manager will not store a reference to that tracker, and the\n * bytes count will be counted independently from other detached trackers.\n *\n * This is particularly useful when we don't know when the tracker will be unused, so we don't\n * leak memory (ex: when used in Logger instances).\n */\n createDetachedTracker: function () {\n var tracker = createCustomerDataTracker(function () { return checkCustomerDataLimit(tracker.getBytesCount()); });\n return tracker;\n },\n /**\n * Creates a tracker if it doesn't exist, and returns it.\n */\n getOrCreateTracker: function (type) {\n if (!customerDataTrackers.has(type)) {\n customerDataTrackers.set(type, createCustomerDataTracker(checkCustomerDataLimit));\n }\n return customerDataTrackers.get(type);\n },\n setCompressionStatus: function (newCompressionStatus) {\n if (compressionStatus === 0 /* CustomerDataCompressionStatus.Unknown */) {\n compressionStatus = newCompressionStatus;\n checkCustomerDataLimit();\n }\n },\n getCompressionStatus: function () { return compressionStatus; },\n stop: function () {\n customerDataTrackers.forEach(function (tracker) { return tracker.stop(); });\n customerDataTrackers.clear();\n },\n };\n}\nexport function createCustomerDataTracker(checkCustomerDataLimit) {\n var bytesCountCache = 0;\n // Throttle the bytes computation to minimize the impact on performance.\n // Especially useful if the user call context APIs synchronously multiple times in a row\n var _a = throttle(function (context) {\n bytesCountCache = computeBytesCount(jsonStringify(context));\n checkCustomerDataLimit();\n }, BYTES_COMPUTATION_THROTTLING_DELAY), computeBytesCountThrottled = _a.throttled, cancelComputeBytesCount = _a.cancel;\n var resetBytesCount = function () {\n cancelComputeBytesCount();\n bytesCountCache = 0;\n };\n return {\n updateCustomerData: function (context) {\n if (isEmptyObject(context)) {\n resetBytesCount();\n }\n else {\n computeBytesCountThrottled(context);\n }\n },\n resetCustomerData: resetBytesCount,\n getBytesCount: function () { return bytesCountCache; },\n stop: function () {\n cancelComputeBytesCount();\n },\n };\n}\nfunction displayCustomerDataLimitReachedWarning(bytesCountLimit) {\n 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\"));\n}\n//# sourceMappingURL=customerDataTracker.js.map","import { monitor } from './monitor';\nimport { noop } from './utils/functionUtils';\n/**\n * Read bytes from a ReadableStream until at least `limit` bytes have been read (or until the end of\n * the stream). The callback is invoked with the at most `limit` bytes, and indicates that the limit\n * has been exceeded if more bytes were available.\n */\nexport function readBytesFromStream(stream, callback, options) {\n var reader = stream.getReader();\n var chunks = [];\n var readBytesCount = 0;\n readMore();\n function readMore() {\n reader.read().then(monitor(function (result) {\n if (result.done) {\n onDone();\n return;\n }\n if (options.collectStreamBody) {\n chunks.push(result.value);\n }\n readBytesCount += result.value.length;\n if (readBytesCount > options.bytesLimit) {\n onDone();\n }\n else {\n readMore();\n }\n }), monitor(function (error) { return callback(error); }));\n }\n function onDone() {\n reader.cancel().catch(\n // we don't care if cancel fails, but we still need to catch the error to avoid reporting it\n // as an unhandled rejection\n noop);\n var bytes;\n var limitExceeded;\n if (options.collectStreamBody) {\n var completeBuffer_1;\n if (chunks.length === 1) {\n // optimization: if the response is small enough to fit in a single buffer (provided by the browser), just\n // use it directly.\n completeBuffer_1 = chunks[0];\n }\n else {\n // else, we need to copy buffers into a larger buffer to concatenate them.\n completeBuffer_1 = new Uint8Array(readBytesCount);\n var offset_1 = 0;\n chunks.forEach(function (chunk) {\n completeBuffer_1.set(chunk, offset_1);\n offset_1 += chunk.length;\n });\n }\n bytes = completeBuffer_1.slice(0, options.bytesLimit);\n limitExceeded = completeBuffer_1.length > options.bytesLimit;\n }\n callback(undefined, bytes, limitExceeded);\n }\n}\n//# sourceMappingURL=readBytesFromStream.js.map","import { getInitCookie } from '../../browser/cookie';\nexport var SYNTHETICS_TEST_ID_COOKIE_NAME = 'datadog-synthetics-public-id';\nexport var SYNTHETICS_RESULT_ID_COOKIE_NAME = 'datadog-synthetics-result-id';\nexport var SYNTHETICS_INJECTS_RUM_COOKIE_NAME = 'datadog-synthetics-injects-rum';\nexport function willSyntheticsInjectRum() {\n return Boolean(window._DATADOG_SYNTHETICS_INJECTS_RUM || getInitCookie(SYNTHETICS_INJECTS_RUM_COOKIE_NAME));\n}\nexport function getSyntheticsTestId() {\n var value = window._DATADOG_SYNTHETICS_PUBLIC_ID || getInitCookie(SYNTHETICS_TEST_ID_COOKIE_NAME);\n return typeof value === 'string' ? value : undefined;\n}\nexport function getSyntheticsResultId() {\n var value = window._DATADOG_SYNTHETICS_RESULT_ID || getInitCookie(SYNTHETICS_RESULT_ID_COOKIE_NAME);\n return typeof value === 'string' ? value : undefined;\n}\n//# sourceMappingURL=syntheticsWorkerValues.js.map","import { startsWith } from './utils/polyfills';\nimport { display } from './display';\nimport { getType } from './utils/typeUtils';\nexport function isMatchOption(item) {\n var itemType = getType(item);\n return itemType === 'string' || itemType === 'function' || item instanceof RegExp;\n}\n/**\n * Returns true if value can be matched by at least one of the provided MatchOptions.\n * When comparing strings, setting useStartsWith to true will compare the value with the start of\n * the option, instead of requiring an exact match.\n */\nexport function matchList(list, value, useStartsWith) {\n if (useStartsWith === void 0) { useStartsWith = false; }\n return list.some(function (item) {\n try {\n if (typeof item === 'function') {\n return item(value);\n }\n else if (item instanceof RegExp) {\n return item.test(value);\n }\n else if (typeof item === 'string') {\n return useStartsWith ? startsWith(value, item) : item === value;\n }\n }\n catch (e) {\n display.error(e);\n }\n return false;\n });\n}\n//# sourceMappingURL=matchOption.js.map","export function buildCommonContext(globalContextManager, userContextManager, recorderApi) {\n return {\n context: globalContextManager.getContext(),\n user: userContextManager.getContext(),\n hasReplay: recorderApi.isRecording() ? true : undefined,\n };\n}\n//# sourceMappingURL=commonContext.js.map","import { clocksNow, combine, elapsed, generateUUID, toServerDuration } from '@datadog/browser-core';\nexport function createCustomVitalsState() {\n var vitalsByName = new Map();\n var vitalsByReference = new WeakMap();\n return { vitalsByName: vitalsByName, vitalsByReference: vitalsByReference };\n}\nexport function startVitalCollection(lifeCycle, pageStateHistory, customVitalsState) {\n function isValid(vital) {\n return !pageStateHistory.wasInPageStateDuringPeriod(\"frozen\" /* PageState.FROZEN */, vital.startClocks.relative, vital.duration);\n }\n function addDurationVital(vital) {\n if (isValid(vital)) {\n lifeCycle.notify(11 /* LifeCycleEventType.RAW_RUM_EVENT_COLLECTED */, processVital(vital, true));\n }\n }\n return {\n addDurationVital: addDurationVital,\n startDurationVital: function (name, options) {\n if (options === void 0) { options = {}; }\n return startDurationVital(customVitalsState, name, options);\n },\n stopDurationVital: function (nameOrRef, options) {\n if (options === void 0) { options = {}; }\n stopDurationVital(addDurationVital, customVitalsState, nameOrRef, options);\n },\n };\n}\nexport function startDurationVital(_a, name, options) {\n var vitalsByName = _a.vitalsByName, vitalsByReference = _a.vitalsByReference;\n if (options === void 0) { options = {}; }\n var vital = {\n name: name,\n startClocks: clocksNow(),\n context: options.context,\n description: options.description,\n };\n // To avoid leaking implementation details of the vital, we return a reference to it.\n var reference = { __dd_vital_reference: true };\n vitalsByName.set(name, vital);\n // To avoid memory leaks caused by the creation of numerous references (e.g., from improper useEffect implementations), we use a WeakMap.\n vitalsByReference.set(reference, vital);\n return reference;\n}\nexport function stopDurationVital(stopCallback, _a, nameOrRef, options) {\n var vitalsByName = _a.vitalsByName, vitalsByReference = _a.vitalsByReference;\n if (options === void 0) { options = {}; }\n var vitalStart = typeof nameOrRef === 'string' ? vitalsByName.get(nameOrRef) : vitalsByReference.get(nameOrRef);\n if (!vitalStart) {\n return;\n }\n stopCallback(buildDurationVital(vitalStart, vitalStart.startClocks, options, clocksNow()));\n if (typeof nameOrRef === 'string') {\n vitalsByName.delete(nameOrRef);\n }\n else {\n vitalsByReference.delete(nameOrRef);\n }\n}\nfunction buildDurationVital(vitalStart, startClocks, stopOptions, stopClocks) {\n var _a;\n return {\n name: vitalStart.name,\n type: \"duration\" /* VitalType.DURATION */,\n startClocks: startClocks,\n duration: elapsed(startClocks.timeStamp, stopClocks.timeStamp),\n context: combine(vitalStart.context, stopOptions.context),\n description: (_a = stopOptions.description) !== null && _a !== void 0 ? _a : vitalStart.description,\n };\n}\nfunction processVital(vital, valueComputedBySdk) {\n var rawRumEvent = {\n date: vital.startClocks.timeStamp,\n vital: {\n id: generateUUID(),\n type: vital.type,\n name: vital.name,\n duration: toServerDuration(vital.duration),\n description: vital.description,\n },\n type: \"vital\" /* RumEventType.VITAL */,\n };\n if (valueComputedBySdk) {\n rawRumEvent._dd = {\n vital: {\n computed_value: true,\n },\n };\n }\n return {\n rawRumEvent: rawRumEvent,\n startTime: vital.startClocks.relative,\n customerContext: vital.context,\n domainContext: {},\n };\n}\n//# sourceMappingURL=vitalCollection.js.map","export function getCrypto() {\n // TODO: remove msCrypto when IE11 support is dropped\n return window.crypto || window.msCrypto;\n}\n//# sourceMappingURL=crypto.js.map","import { ExperimentalFeature, isExperimentalFeatureEnabled } from '@datadog/browser-core';\nimport { getCrypto } from '../../browser/crypto';\nexport function createTraceIdentifier() {\n return createIdentifier(64);\n}\nexport function createSpanIdentifier() {\n return createIdentifier(63);\n}\nvar createIdentifierImplementationCache;\nfunction createIdentifier(bits) {\n if (!createIdentifierImplementationCache) {\n createIdentifierImplementationCache =\n isExperimentalFeatureEnabled(ExperimentalFeature.CONSISTENT_TRACE_SAMPLING) && areBigIntIdentifiersSupported()\n ? createIdentifierUsingBigInt\n : createIdentifierUsingUint32Array;\n }\n return createIdentifierImplementationCache(bits);\n}\nexport function areBigIntIdentifiersSupported() {\n try {\n crypto.getRandomValues(new BigUint64Array(1));\n return true;\n }\n catch (_a) {\n return false;\n }\n}\nfunction createIdentifierUsingBigInt(bits) {\n var id = crypto.getRandomValues(new BigUint64Array(1))[0];\n if (bits === 63) {\n // eslint-disable-next-line no-bitwise\n id >>= BigInt('1');\n }\n return id;\n}\n// TODO: remove this when all browser we support have BigInt support\nfunction createIdentifierUsingUint32Array(bits) {\n var buffer = getCrypto().getRandomValues(new Uint32Array(2));\n if (bits === 63) {\n // eslint-disable-next-line no-bitwise\n buffer[buffer.length - 1] >>>= 1; // force 63-bit\n }\n return {\n toString: function (radix) {\n if (radix === void 0) { radix = 10; }\n var high = buffer[1];\n var low = buffer[0];\n var str = '';\n do {\n var mod = (high % radix) * 4294967296 + low;\n high = Math.floor(high / radix);\n low = Math.floor(mod / radix);\n str = (mod % radix).toString(radix) + str;\n } while (high || low);\n return str;\n },\n };\n}\nexport function toPaddedHexadecimalString(id) {\n var traceId = id.toString(16);\n // TODO: replace with String.prototype.padStart when we drop IE11 support\n return Array(17 - traceId.length).join('0') + traceId;\n}\n//# sourceMappingURL=identifier.js.map","import { performDraw } from '@datadog/browser-core';\nexport function isTraceSampled(identifier, sampleRate) {\n // Shortcuts for common cases. This is not strictly necessary, but it makes the code faster for\n // customers willing to ingest all traces.\n if (sampleRate === 100) {\n return true;\n }\n if (sampleRate === 0) {\n return false;\n }\n // For simplicity, we don't use consistent sampling for browser that don't support BigInt\n // TODO: remove this when all browser we support have BigInt support\n if (typeof identifier !== 'bigint') {\n return performDraw(sampleRate);\n }\n // Offer consistent sampling for the same trace id across different environments. The rule is:\n //\n // (identifier * knuthFactor) % 2^64 < sampleRate * 2^64\n //\n // Because JavaScript numbers are 64-bit floats, we can't represent 64-bit integers, and the\n // modulo would be incorrect. Thus, we are using BigInts here.\n //\n // Implementation in other languages:\n // * Go https://github.com/DataDog/dd-trace-go/blob/ec6fbb1f2d517b7b8e69961052adf7136f3af773/ddtrace/tracer/sampler.go#L86-L91\n // * Python https://github.com/DataDog/dd-trace-py/blob/0cee2f066fb6e79aa15947c1514c0f406dea47c5/ddtrace/sampling_rule.py#L197\n // * Ruby https://github.com/DataDog/dd-trace-rb/blob/1a6e255cdcb7e7e22235ea5955f90f6dfa91045d/lib/datadog/tracing/sampling/rate_sampler.rb#L42\n // * C++ https://github.com/DataDog/dd-trace-cpp/blob/159629edc438ae45f2bb318eb7bd51abd05e94b5/src/datadog/trace_sampler.cpp#L58\n // * Java https://github.com/DataDog/dd-trace-java/blob/896dd6b380533216e0bdee59614606c8272d313e/dd-trace-core/src/main/java/datadog/trace/common/sampling/DeterministicSampler.java#L48\n //\n // Note: All implementations have slight variations. Some of them use '<=' instead of '<', and\n // use `sampleRate * 2^64 - 1` instead of `sampleRate * 2^64`. The following implementation\n // should adhere to the spec and is a bit simpler than using a 2^64-1 limit as there are less\n // BigInt arithmetic to write. In practice this does not matter, as we are using floating point\n // numbers in the end, and Number(2n**64n-1n) === Number(2n**64n).\n var knuthFactor = BigInt('1111111111111111111');\n var twoPow64 = BigInt('0x10000000000000000'); // 2n ** 64n\n var hash = (identifier * knuthFactor) % twoPow64;\n return Number(hash) <= (sampleRate / 100) * Number(twoPow64);\n}\n//# sourceMappingURL=sampler.js.map","import { objectEntries, shallowClone, assign, find, getType, isMatchOption, matchList, TraceContextInjection, } from '@datadog/browser-core';\nimport { getCrypto } from '../../browser/crypto';\nimport { createSpanIdentifier, createTraceIdentifier, toPaddedHexadecimalString } from './identifier';\nimport { isTraceSampled } from './sampler';\nexport function isTracingOption(item) {\n var expectedItem = item;\n return (getType(expectedItem) === 'object' &&\n isMatchOption(expectedItem.match) &&\n Array.isArray(expectedItem.propagatorTypes));\n}\n/**\n * Clear tracing information to avoid incomplete traces. Ideally, we should do it when the\n * request did not reach the server, but the browser does not expose this. So, we clear tracing\n * information if the request ended with status 0 without being aborted by the application.\n *\n * Reasoning:\n *\n * * Applications are usually aborting requests after a bit of time, for example when the user is\n * typing (autocompletion) or navigating away (in a SPA). With a performant device and good\n * network conditions, the request is likely to reach the server before being canceled.\n *\n * * Requests aborted otherwise (ex: lack of internet, CORS issue, blocked by a privacy extension)\n * are likely to finish quickly and without reaching the server.\n *\n * Of course, it might not be the case every time, but it should limit having incomplete traces a\n * bit.\n * */\nexport function clearTracingIfNeeded(context) {\n if (context.status === 0 && !context.isAborted) {\n context.traceId = undefined;\n context.spanId = undefined;\n context.traceSampled = undefined;\n }\n}\nexport function startTracer(configuration, sessionManager) {\n return {\n clearTracingIfNeeded: clearTracingIfNeeded,\n traceFetch: function (context) {\n return injectHeadersIfTracingAllowed(configuration, context, sessionManager, function (tracingHeaders) {\n var _a;\n if (context.input instanceof Request && !((_a = context.init) === null || _a === void 0 ? void 0 : _a.headers)) {\n context.input = new Request(context.input);\n Object.keys(tracingHeaders).forEach(function (key) {\n ;\n context.input.headers.append(key, tracingHeaders[key]);\n });\n }\n else {\n context.init = shallowClone(context.init);\n var headers_1 = [];\n if (context.init.headers instanceof Headers) {\n context.init.headers.forEach(function (value, key) {\n headers_1.push([key, value]);\n });\n }\n else if (Array.isArray(context.init.headers)) {\n context.init.headers.forEach(function (header) {\n headers_1.push(header);\n });\n }\n else if (context.init.headers) {\n Object.keys(context.init.headers).forEach(function (key) {\n headers_1.push([key, context.init.headers[key]]);\n });\n }\n context.init.headers = headers_1.concat(objectEntries(tracingHeaders));\n }\n });\n },\n traceXhr: function (context, xhr) {\n return injectHeadersIfTracingAllowed(configuration, context, sessionManager, function (tracingHeaders) {\n Object.keys(tracingHeaders).forEach(function (name) {\n xhr.setRequestHeader(name, tracingHeaders[name]);\n });\n });\n },\n };\n}\nfunction injectHeadersIfTracingAllowed(configuration, context, sessionManager, inject) {\n if (!isTracingSupported() || !sessionManager.findTrackedSession()) {\n return;\n }\n var tracingOption = find(configuration.allowedTracingUrls, function (tracingOption) {\n return matchList([tracingOption.match], context.url, true);\n });\n if (!tracingOption) {\n return;\n }\n var traceId = createTraceIdentifier();\n context.traceSampled = isTraceSampled(traceId, configuration.traceSampleRate);\n var shouldInjectHeaders = context.traceSampled || configuration.traceContextInjection === TraceContextInjection.ALL;\n if (!shouldInjectHeaders) {\n return;\n }\n context.traceId = traceId;\n context.spanId = createSpanIdentifier();\n inject(makeTracingHeaders(context.traceId, context.spanId, context.traceSampled, tracingOption.propagatorTypes));\n}\nexport function isTracingSupported() {\n return getCrypto() !== undefined;\n}\n/**\n * When trace is not sampled, set priority to '0' instead of not adding the tracing headers\n * to prepare the implementation for sampling delegation.\n */\nfunction makeTracingHeaders(traceId, spanId, traceSampled, propagatorTypes) {\n var tracingHeaders = {};\n propagatorTypes.forEach(function (propagatorType) {\n switch (propagatorType) {\n case 'datadog': {\n assign(tracingHeaders, {\n 'x-datadog-origin': 'rum',\n 'x-datadog-parent-id': spanId.toString(),\n 'x-datadog-sampling-priority': traceSampled ? '1' : '0',\n 'x-datadog-trace-id': traceId.toString(),\n });\n break;\n }\n // https://www.w3.org/TR/trace-context/\n case 'tracecontext': {\n assign(tracingHeaders, {\n traceparent: \"00-0000000000000000\".concat(toPaddedHexadecimalString(traceId), \"-\").concat(toPaddedHexadecimalString(spanId), \"-0\").concat(traceSampled ? '1' : '0'),\n });\n break;\n }\n // https://github.com/openzipkin/b3-propagation\n case 'b3': {\n assign(tracingHeaders, {\n b3: \"\".concat(toPaddedHexadecimalString(traceId), \"-\").concat(toPaddedHexadecimalString(spanId), \"-\").concat(traceSampled ? '1' : '0'),\n });\n break;\n }\n case 'b3multi': {\n assign(tracingHeaders, {\n 'X-B3-TraceId': toPaddedHexadecimalString(traceId),\n 'X-B3-SpanId': toPaddedHexadecimalString(spanId),\n 'X-B3-Sampled': traceSampled ? '1' : '0',\n });\n break;\n }\n }\n });\n return tracingHeaders;\n}\n//# sourceMappingURL=tracer.js.map","import { getType, arrayFrom, isMatchOption, serializeConfiguration, assign, DefaultPrivacyLevel, TraceContextInjection, display, objectHasValue, validateAndBuildConfiguration, isSampleRate, isNumber, } from '@datadog/browser-core';\nimport { isTracingOption } from '../tracing/tracer';\nexport var DEFAULT_PROPAGATOR_TYPES = ['tracecontext', 'datadog'];\nexport function validateAndBuildRumConfiguration(initConfiguration) {\n var _a, _b, _c;\n if (!initConfiguration.applicationId) {\n display.error('Application ID is not configured, no RUM data will be collected.');\n return;\n }\n if (!isSampleRate(initConfiguration.sessionReplaySampleRate, 'Session Replay') ||\n !isSampleRate(initConfiguration.traceSampleRate, 'Trace')) {\n return;\n }\n if (initConfiguration.excludedActivityUrls !== undefined && !Array.isArray(initConfiguration.excludedActivityUrls)) {\n display.error('Excluded Activity Urls should be an array');\n return;\n }\n var allowedTracingUrls = validateAndBuildTracingOptions(initConfiguration);\n if (!allowedTracingUrls) {\n return;\n }\n var baseConfiguration = validateAndBuildConfiguration(initConfiguration);\n if (!baseConfiguration) {\n return;\n }\n var sessionReplaySampleRate = (_a = initConfiguration.sessionReplaySampleRate) !== null && _a !== void 0 ? _a : 0;\n return assign({\n applicationId: initConfiguration.applicationId,\n version: initConfiguration.version || undefined,\n actionNameAttribute: initConfiguration.actionNameAttribute,\n sessionReplaySampleRate: sessionReplaySampleRate,\n startSessionReplayRecordingManually: initConfiguration.startSessionReplayRecordingManually !== undefined\n ? !!initConfiguration.startSessionReplayRecordingManually\n : sessionReplaySampleRate === 0,\n traceSampleRate: (_b = initConfiguration.traceSampleRate) !== null && _b !== void 0 ? _b : 100,\n rulePsr: isNumber(initConfiguration.traceSampleRate) ? initConfiguration.traceSampleRate / 100 : undefined,\n allowedTracingUrls: allowedTracingUrls,\n excludedActivityUrls: (_c = initConfiguration.excludedActivityUrls) !== null && _c !== void 0 ? _c : [],\n workerUrl: initConfiguration.workerUrl,\n compressIntakeRequests: !!initConfiguration.compressIntakeRequests,\n trackUserInteractions: !!initConfiguration.trackUserInteractions,\n trackViewsManually: !!initConfiguration.trackViewsManually,\n trackResources: !!initConfiguration.trackResources,\n trackLongTasks: !!initConfiguration.trackLongTasks,\n subdomain: initConfiguration.subdomain,\n defaultPrivacyLevel: objectHasValue(DefaultPrivacyLevel, initConfiguration.defaultPrivacyLevel)\n ? initConfiguration.defaultPrivacyLevel\n : DefaultPrivacyLevel.MASK,\n enablePrivacyForActionName: !!initConfiguration.enablePrivacyForActionName,\n customerDataTelemetrySampleRate: 1,\n traceContextInjection: objectHasValue(TraceContextInjection, initConfiguration.traceContextInjection)\n ? initConfiguration.traceContextInjection\n : TraceContextInjection.ALL,\n plugins: initConfiguration.plugins || [],\n }, baseConfiguration);\n}\n/**\n * Validates allowedTracingUrls and converts match options to tracing options\n */\nfunction validateAndBuildTracingOptions(initConfiguration) {\n if (initConfiguration.allowedTracingUrls === undefined) {\n return [];\n }\n if (!Array.isArray(initConfiguration.allowedTracingUrls)) {\n display.error('Allowed Tracing URLs should be an array');\n return;\n }\n if (initConfiguration.allowedTracingUrls.length !== 0 && initConfiguration.service === undefined) {\n display.error('Service needs to be configured when tracing is enabled');\n return;\n }\n // Convert from (MatchOption | TracingOption) to TracingOption, remove unknown properties\n var tracingOptions = [];\n initConfiguration.allowedTracingUrls.forEach(function (option) {\n if (isMatchOption(option)) {\n tracingOptions.push({ match: option, propagatorTypes: DEFAULT_PROPAGATOR_TYPES });\n }\n else if (isTracingOption(option)) {\n tracingOptions.push(option);\n }\n else {\n display.warn('Allowed Tracing Urls parameters should be a string, RegExp, function, or an object. Ignoring parameter', option);\n }\n });\n return tracingOptions;\n}\n/**\n * Combines the selected tracing propagators from the different options in allowedTracingUrls\n */\nfunction getSelectedTracingPropagators(configuration) {\n var usedTracingPropagators = new Set();\n if (Array.isArray(configuration.allowedTracingUrls) && configuration.allowedTracingUrls.length > 0) {\n configuration.allowedTracingUrls.forEach(function (option) {\n if (isMatchOption(option)) {\n DEFAULT_PROPAGATOR_TYPES.forEach(function (propagatorType) { return usedTracingPropagators.add(propagatorType); });\n }\n else if (getType(option) === 'object' && Array.isArray(option.propagatorTypes)) {\n // Ensure we have an array, as we cannot rely on types yet (configuration is provided by users)\n option.propagatorTypes.forEach(function (propagatorType) { return usedTracingPropagators.add(propagatorType); });\n }\n });\n }\n return arrayFrom(usedTracingPropagators);\n}\nexport function serializeRumConfiguration(configuration) {\n var _a;\n var baseSerializedConfiguration = serializeConfiguration(configuration);\n return assign({\n session_replay_sample_rate: configuration.sessionReplaySampleRate,\n start_session_replay_recording_manually: configuration.startSessionReplayRecordingManually,\n trace_sample_rate: configuration.traceSampleRate,\n trace_context_injection: configuration.traceContextInjection,\n action_name_attribute: configuration.actionNameAttribute,\n use_allowed_tracing_urls: Array.isArray(configuration.allowedTracingUrls) && configuration.allowedTracingUrls.length > 0,\n selected_tracing_propagators: getSelectedTracingPropagators(configuration),\n default_privacy_level: configuration.defaultPrivacyLevel,\n enable_privacy_for_action_name: configuration.enablePrivacyForActionName,\n use_excluded_activity_urls: Array.isArray(configuration.excludedActivityUrls) && configuration.excludedActivityUrls.length > 0,\n use_worker_url: !!configuration.workerUrl,\n compress_intake_requests: configuration.compressIntakeRequests,\n track_views_manually: configuration.trackViewsManually,\n track_user_interactions: configuration.trackUserInteractions,\n track_resources: configuration.trackResources,\n track_long_task: configuration.trackLongTasks,\n plugins: (_a = configuration.plugins) === null || _a === void 0 ? void 0 : _a.map(function (plugin) { var _a; return assign({ name: plugin.name }, (_a = plugin.getConfigurationTelemetry) === null || _a === void 0 ? void 0 : _a.call(plugin)); }),\n }, baseSerializedConfiguration);\n}\n//# sourceMappingURL=configuration.js.map","import { display, addEventListener, assign } from '@datadog/browser-core';\nexport var REMOTE_CONFIGURATION_URL = 'https://d3uc069fcn7uxw.cloudfront.net/configuration';\nexport function fetchAndApplyRemoteConfiguration(initConfiguration, callback) {\n fetchRemoteConfiguration(initConfiguration, function (remoteInitConfiguration) {\n callback(applyRemoteConfiguration(initConfiguration, remoteInitConfiguration));\n });\n}\nexport function applyRemoteConfiguration(initConfiguration, remoteInitConfiguration) {\n return assign({}, initConfiguration, remoteInitConfiguration);\n}\nexport function fetchRemoteConfiguration(configuration, callback) {\n var xhr = new XMLHttpRequest();\n addEventListener(configuration, xhr, 'load', function () {\n if (xhr.status === 200) {\n callback(JSON.parse(xhr.responseText));\n }\n else {\n displayRemoteConfigurationFetchingError();\n }\n });\n addEventListener(configuration, xhr, 'error', function () {\n displayRemoteConfigurationFetchingError();\n });\n xhr.open('GET', \"\".concat(REMOTE_CONFIGURATION_URL, \"/\").concat(encodeURIComponent(configuration.remoteConfigurationId), \".json\"));\n xhr.send();\n}\nfunction displayRemoteConfigurationFetchingError() {\n display.error('Error fetching the remote configuration.');\n}\n//# sourceMappingURL=remoteConfiguration.js.map","export function callPluginsMethod(plugins, methodName, parameter) {\n if (!plugins) {\n return;\n }\n for (var _i = 0, plugins_1 = plugins; _i < plugins_1.length; _i++) {\n var plugin = plugins_1[_i];\n var method = plugin[methodName];\n if (method) {\n method(parameter);\n }\n }\n}\n//# sourceMappingURL=plugins.js.map","import { createBoundedBuffer, display, canUseEventBridge, displayAlreadyInitializedError, willSyntheticsInjectRum, noop, timeStampNow, clocksNow, assign, getEventBridge, ExperimentalFeature, isExperimentalFeatureEnabled, initFeatureFlags, addTelemetryConfiguration, initFetchObservable, } from '@datadog/browser-core';\nimport { validateAndBuildRumConfiguration, } from '../domain/configuration';\nimport { startDurationVital, stopDurationVital } from '../domain/vital/vitalCollection';\nimport { fetchAndApplyRemoteConfiguration, serializeRumConfiguration } from '../domain/configuration';\nimport { callPluginsMethod } from '../domain/plugins';\nexport function createPreStartStrategy(_a, getCommonContext, trackingConsentState, customVitalsState, doStartRum) {\n var ignoreInitIfSyntheticsWillInjectRum = _a.ignoreInitIfSyntheticsWillInjectRum, startDeflateWorker = _a.startDeflateWorker;\n var bufferApiCalls = createBoundedBuffer();\n var firstStartViewCall;\n var deflateWorker;\n var cachedInitConfiguration;\n var cachedConfiguration;\n var trackingConsentStateSubscription = trackingConsentState.observable.subscribe(tryStartRum);\n function tryStartRum() {\n if (!cachedInitConfiguration || !cachedConfiguration || !trackingConsentState.isGranted()) {\n return;\n }\n trackingConsentStateSubscription.unsubscribe();\n var initialViewOptions;\n if (cachedConfiguration.trackViewsManually) {\n if (!firstStartViewCall) {\n return;\n }\n // An initial view is always created when starting RUM.\n // When tracking views automatically, any startView call before RUM start creates an extra\n // view.\n // When tracking views manually, we use the ViewOptions from the first startView call as the\n // initial view options, and we remove the actual startView call so we don't create an extra\n // view.\n bufferApiCalls.remove(firstStartViewCall.callback);\n initialViewOptions = firstStartViewCall.options;\n }\n var startRumResult = doStartRum(cachedConfiguration, deflateWorker, initialViewOptions);\n bufferApiCalls.drain(startRumResult);\n }\n function doInit(initConfiguration) {\n var eventBridgeAvailable = canUseEventBridge();\n if (eventBridgeAvailable) {\n initConfiguration = overrideInitConfigurationForBridge(initConfiguration);\n }\n // Update the exposed initConfiguration to reflect the bridge and remote configuration overrides\n cachedInitConfiguration = initConfiguration;\n addTelemetryConfiguration(serializeRumConfiguration(initConfiguration));\n if (cachedConfiguration) {\n displayAlreadyInitializedError('DD_RUM', initConfiguration);\n return;\n }\n var configuration = validateAndBuildRumConfiguration(initConfiguration);\n if (!configuration) {\n return;\n }\n if (!eventBridgeAvailable && !configuration.sessionStoreStrategyType) {\n display.warn('No storage available for session. We will not send any data.');\n return;\n }\n if (configuration.compressIntakeRequests && !eventBridgeAvailable && startDeflateWorker) {\n deflateWorker = startDeflateWorker(configuration, 'Datadog RUM', \n // Worker initialization can fail asynchronously, especially in Firefox where even CSP\n // issues are reported asynchronously. For now, the SDK will continue its execution even if\n // data won't be sent to Datadog. We could improve this behavior in the future.\n noop);\n if (!deflateWorker) {\n // `startDeflateWorker` should have logged an error message explaining the issue\n return;\n }\n }\n cachedConfiguration = configuration;\n // Instrumuent fetch to track network requests\n // This is needed in case the consent is not granted and some cutsomer\n // library (Apollo Client) is storing uninstrumented fetch to be used later\n // The subscrption is needed so that the instrumentation process is completed\n initFetchObservable().subscribe(noop);\n trackingConsentState.tryToInit(configuration.trackingConsent);\n tryStartRum();\n }\n var addDurationVital = function (vital) {\n bufferApiCalls.add(function (startRumResult) { return startRumResult.addDurationVital(vital); });\n };\n return {\n init: function (initConfiguration, publicApi) {\n if (!initConfiguration) {\n display.error('Missing configuration');\n return;\n }\n // Set the experimental feature flags as early as possible, so we can use them in most places\n initFeatureFlags(initConfiguration.enableExperimentalFeatures);\n // Expose the initial configuration regardless of initialization success.\n cachedInitConfiguration = initConfiguration;\n // If we are in a Synthetics test configured to automatically inject a RUM instance, we want\n // to completely discard the customer application RUM instance by ignoring their init() call.\n // But, we should not ignore the init() call from the Synthetics-injected RUM instance, so the\n // internal `ignoreInitIfSyntheticsWillInjectRum` option is here to bypass this condition.\n if (ignoreInitIfSyntheticsWillInjectRum && willSyntheticsInjectRum()) {\n return;\n }\n callPluginsMethod(initConfiguration.plugins, 'onInit', { initConfiguration: initConfiguration, publicApi: publicApi });\n if (initConfiguration.remoteConfigurationId &&\n isExperimentalFeatureEnabled(ExperimentalFeature.REMOTE_CONFIGURATION)) {\n fetchAndApplyRemoteConfiguration(initConfiguration, doInit);\n }\n else {\n doInit(initConfiguration);\n }\n },\n get initConfiguration() {\n return cachedInitConfiguration;\n },\n getInternalContext: noop,\n stopSession: noop,\n addTiming: function (name, time) {\n if (time === void 0) { time = timeStampNow(); }\n bufferApiCalls.add(function (startRumResult) { return startRumResult.addTiming(name, time); });\n },\n startView: function (options, startClocks) {\n if (startClocks === void 0) { startClocks = clocksNow(); }\n var callback = function (startRumResult) {\n startRumResult.startView(options, startClocks);\n };\n bufferApiCalls.add(callback);\n if (!firstStartViewCall) {\n firstStartViewCall = { options: options, callback: callback };\n tryStartRum();\n }\n },\n setViewName: function (name) {\n bufferApiCalls.add(function (startRumResult) { return startRumResult.setViewName(name); });\n },\n setViewContext: function (context) {\n bufferApiCalls.add(function (startRumResult) { return startRumResult.setViewContext(context); });\n },\n setViewContextProperty: function (key, value) {\n bufferApiCalls.add(function (startRumResult) { return startRumResult.setViewContextProperty(key, value); });\n },\n addAction: function (action, commonContext) {\n if (commonContext === void 0) { commonContext = getCommonContext(); }\n bufferApiCalls.add(function (startRumResult) { return startRumResult.addAction(action, commonContext); });\n },\n addError: function (providedError, commonContext) {\n if (commonContext === void 0) { commonContext = getCommonContext(); }\n bufferApiCalls.add(function (startRumResult) { return startRumResult.addError(providedError, commonContext); });\n },\n addFeatureFlagEvaluation: function (key, value) {\n bufferApiCalls.add(function (startRumResult) { return startRumResult.addFeatureFlagEvaluation(key, value); });\n },\n startDurationVital: function (name, options) {\n return startDurationVital(customVitalsState, name, options);\n },\n stopDurationVital: function (name, options) {\n stopDurationVital(addDurationVital, customVitalsState, name, options);\n },\n addDurationVital: addDurationVital,\n };\n}\nfunction overrideInitConfigurationForBridge(initConfiguration) {\n var _a, _b;\n return assign({}, initConfiguration, {\n applicationId: '00000000-aaaa-0000-aaaa-000000000000',\n clientToken: 'empty',\n sessionSampleRate: 100,\n defaultPrivacyLevel: (_a = initConfiguration.defaultPrivacyLevel) !== null && _a !== void 0 ? _a : (_b = getEventBridge()) === null || _b === void 0 ? void 0 : _b.getPrivacyLevel(),\n });\n}\n//# sourceMappingURL=preStartRum.js.map","import { addTelemetryUsage, assign, createContextManager, deepClone, makePublicApi, monitor, clocksNow, callMonitored, createHandlingStack, checkUser, sanitizeUser, sanitize, createIdentityEncoder, createCustomerDataTrackerManager, storeContextManager, displayAlreadyInitializedError, createTrackingConsentState, timeStampToClocks, } from '@datadog/browser-core';\nimport { buildCommonContext } from '../domain/contexts/commonContext';\nimport { createCustomVitalsState } from '../domain/vital/vitalCollection';\nimport { createPreStartStrategy } from './preStartRum';\nvar RUM_STORAGE_KEY = 'rum';\nexport function makeRumPublicApi(startRumImpl, recorderApi, options) {\n if (options === void 0) { options = {}; }\n var customerDataTrackerManager = createCustomerDataTrackerManager(0 /* CustomerDataCompressionStatus.Unknown */);\n var globalContextManager = createContextManager(customerDataTrackerManager.getOrCreateTracker(2 /* CustomerDataType.GlobalContext */));\n var userContextManager = createContextManager(customerDataTrackerManager.getOrCreateTracker(1 /* CustomerDataType.User */));\n var trackingConsentState = createTrackingConsentState();\n var customVitalsState = createCustomVitalsState();\n function getCommonContext() {\n return buildCommonContext(globalContextManager, userContextManager, recorderApi);\n }\n var strategy = createPreStartStrategy(options, getCommonContext, trackingConsentState, customVitalsState, function (configuration, deflateWorker, initialViewOptions) {\n if (configuration.storeContextsAcrossPages) {\n storeContextManager(configuration, globalContextManager, RUM_STORAGE_KEY, 2 /* CustomerDataType.GlobalContext */);\n storeContextManager(configuration, userContextManager, RUM_STORAGE_KEY, 1 /* CustomerDataType.User */);\n }\n customerDataTrackerManager.setCompressionStatus(deflateWorker ? 1 /* CustomerDataCompressionStatus.Enabled */ : 2 /* CustomerDataCompressionStatus.Disabled */);\n var startRumResult = startRumImpl(configuration, recorderApi, customerDataTrackerManager, getCommonContext, initialViewOptions, deflateWorker && options.createDeflateEncoder\n ? function (streamId) { return options.createDeflateEncoder(configuration, deflateWorker, streamId); }\n : createIdentityEncoder, trackingConsentState, customVitalsState);\n recorderApi.onRumStart(startRumResult.lifeCycle, configuration, startRumResult.session, startRumResult.viewHistory, deflateWorker);\n strategy = createPostStartStrategy(strategy, startRumResult);\n return startRumResult;\n });\n var startView = monitor(function (options) {\n var sanitizedOptions = typeof options === 'object' ? options : { name: options };\n if (sanitizedOptions.context) {\n customerDataTrackerManager.getOrCreateTracker(3 /* CustomerDataType.View */).updateCustomerData(sanitizedOptions.context);\n }\n strategy.startView(sanitizedOptions);\n addTelemetryUsage({ feature: 'start-view' });\n });\n var rumPublicApi = makePublicApi({\n init: monitor(function (initConfiguration) {\n strategy.init(initConfiguration, rumPublicApi);\n }),\n setTrackingConsent: monitor(function (trackingConsent) {\n trackingConsentState.update(trackingConsent);\n addTelemetryUsage({ feature: 'set-tracking-consent', tracking_consent: trackingConsent });\n }),\n setViewName: monitor(function (name) {\n strategy.setViewName(name);\n }),\n setViewContext: monitor(function (context) {\n strategy.setViewContext(context);\n }),\n setViewContextProperty: monitor(function (key, value) {\n strategy.setViewContextProperty(key, value);\n }),\n setGlobalContext: monitor(function (context) {\n globalContextManager.setContext(context);\n addTelemetryUsage({ feature: 'set-global-context' });\n }),\n getGlobalContext: monitor(function () { return globalContextManager.getContext(); }),\n setGlobalContextProperty: monitor(function (key, value) {\n globalContextManager.setContextProperty(key, value);\n addTelemetryUsage({ feature: 'set-global-context' });\n }),\n removeGlobalContextProperty: monitor(function (key) { return globalContextManager.removeContextProperty(key); }),\n clearGlobalContext: monitor(function () { return globalContextManager.clearContext(); }),\n getInternalContext: monitor(function (startTime) { return strategy.getInternalContext(startTime); }),\n getInitConfiguration: monitor(function () { return deepClone(strategy.initConfiguration); }),\n addAction: function (name, context) {\n var handlingStack = createHandlingStack();\n callMonitored(function () {\n strategy.addAction({\n name: sanitize(name),\n context: sanitize(context),\n startClocks: clocksNow(),\n type: \"custom\" /* ActionType.CUSTOM */,\n handlingStack: handlingStack,\n });\n addTelemetryUsage({ feature: 'add-action' });\n });\n },\n addError: function (error, context) {\n var handlingStack = createHandlingStack();\n callMonitored(function () {\n strategy.addError({\n error: error, // Do not sanitize error here, it is needed unserialized by computeRawError()\n handlingStack: handlingStack,\n context: sanitize(context),\n startClocks: clocksNow(),\n });\n addTelemetryUsage({ feature: 'add-error' });\n });\n },\n addTiming: monitor(function (name, time) {\n // TODO: next major decide to drop relative time support or update its behaviour\n strategy.addTiming(sanitize(name), time);\n }),\n setUser: monitor(function (newUser) {\n if (checkUser(newUser)) {\n userContextManager.setContext(sanitizeUser(newUser));\n }\n addTelemetryUsage({ feature: 'set-user' });\n }),\n getUser: monitor(function () { return userContextManager.getContext(); }),\n setUserProperty: monitor(function (key, property) {\n var _a;\n var sanitizedProperty = sanitizeUser((_a = {}, _a[key] = property, _a))[key];\n userContextManager.setContextProperty(key, sanitizedProperty);\n addTelemetryUsage({ feature: 'set-user' });\n }),\n removeUserProperty: monitor(function (key) { return userContextManager.removeContextProperty(key); }),\n clearUser: monitor(function () { return userContextManager.clearContext(); }),\n startView: startView,\n stopSession: monitor(function () {\n strategy.stopSession();\n addTelemetryUsage({ feature: 'stop-session' });\n }),\n addFeatureFlagEvaluation: monitor(function (key, value) {\n strategy.addFeatureFlagEvaluation(sanitize(key), sanitize(value));\n addTelemetryUsage({ feature: 'add-feature-flag-evaluation' });\n }),\n getSessionReplayLink: monitor(function () { return recorderApi.getSessionReplayLink(); }),\n startSessionReplayRecording: monitor(function (options) {\n recorderApi.start(options);\n addTelemetryUsage({ feature: 'start-session-replay-recording', force: options && options.force });\n }),\n stopSessionReplayRecording: monitor(function () { return recorderApi.stop(); }),\n addDurationVital: monitor(function (name, options) {\n addTelemetryUsage({ feature: 'add-duration-vital' });\n strategy.addDurationVital({\n name: sanitize(name),\n type: \"duration\" /* VitalType.DURATION */,\n startClocks: timeStampToClocks(options.startTime),\n duration: options.duration,\n context: sanitize(options && options.context),\n description: sanitize(options && options.description),\n });\n }),\n startDurationVital: monitor(function (name, options) {\n addTelemetryUsage({ feature: 'start-duration-vital' });\n return strategy.startDurationVital(sanitize(name), {\n context: sanitize(options && options.context),\n description: sanitize(options && options.description),\n });\n }),\n stopDurationVital: monitor(function (nameOrRef, options) {\n addTelemetryUsage({ feature: 'stop-duration-vital' });\n strategy.stopDurationVital(typeof nameOrRef === 'string' ? sanitize(nameOrRef) : nameOrRef, {\n context: sanitize(options && options.context),\n description: sanitize(options && options.description),\n });\n }),\n });\n return rumPublicApi;\n}\nfunction createPostStartStrategy(preStartStrategy, startRumResult) {\n return assign({\n init: function (initConfiguration) {\n displayAlreadyInitializedError('DD_RUM', initConfiguration);\n },\n initConfiguration: preStartStrategy.initConfiguration,\n }, startRumResult);\n}\n//# sourceMappingURL=rumPublicApi.js.map","import { monitor, noop, Observable, getZoneJsOriginalValue } from '@datadog/browser-core';\nexport function createDOMMutationObservable() {\n var MutationObserver = getMutationObserverConstructor();\n return new Observable(function (observable) {\n if (!MutationObserver) {\n return;\n }\n var observer = new MutationObserver(monitor(function () { return observable.notify(); }));\n observer.observe(document, {\n attributes: true,\n characterData: true,\n childList: true,\n subtree: true,\n });\n return function () { return observer.disconnect(); };\n });\n}\nexport function getMutationObserverConstructor() {\n var constructor;\n var browserWindow = window;\n // Angular uses Zone.js to provide a context persisting across async tasks. Zone.js replaces the\n // global MutationObserver constructor with a patched version to support the context propagation.\n // There is an ongoing issue[1][2] with this setup when using a MutationObserver within a Angular\n // component: on some occasions, the callback is being called in an infinite loop, causing the\n // page to freeze (even if the callback is completely empty).\n //\n // To work around this issue, we try to get the original MutationObserver constructor stored by\n // Zone.js.\n //\n // [1] https://github.com/angular/angular/issues/26948\n // [2] https://github.com/angular/angular/issues/31712\n if (browserWindow.Zone) {\n // Zone.js 0.8.6+ is storing original class constructors into the browser 'window' object[3].\n //\n // [3] https://github.com/angular/angular/blob/6375fa79875c0fe7b815efc45940a6e6f5c9c9eb/packages/zone.js/lib/common/utils.ts#L288\n constructor = getZoneJsOriginalValue(browserWindow, 'MutationObserver');\n if (browserWindow.MutationObserver && constructor === browserWindow.MutationObserver) {\n // Anterior Zone.js versions (used in Angular 2) does not expose the original MutationObserver\n // in the 'window' object. Luckily, the patched MutationObserver class is storing an original\n // instance in its properties[4]. Let's get the original MutationObserver constructor from\n // there.\n //\n // [4] https://github.com/angular/zone.js/blob/v0.8.5/lib/common/utils.ts#L412\n var patchedInstance = new browserWindow.MutationObserver(noop);\n var originalInstance = getZoneJsOriginalValue(patchedInstance, 'originalInstance');\n constructor = originalInstance && originalInstance.constructor;\n }\n }\n if (!constructor) {\n constructor = browserWindow.MutationObserver;\n }\n return constructor;\n}\n//# sourceMappingURL=domMutationObservable.js.map","import { instrumentMethod, Observable } from '@datadog/browser-core';\nexport function createWindowOpenObservable() {\n var observable = new Observable();\n var stop = instrumentMethod(window, 'open', function () { return observable.notify(); }).stop;\n return { observable: observable, stop: stop };\n}\n//# sourceMappingURL=windowOpenObservable.js.map","import { getSyntheticsResultId, getSyntheticsTestId, willSyntheticsInjectRum } from '@datadog/browser-core';\nexport function getSyntheticsContext() {\n var testId = getSyntheticsTestId();\n var resultId = getSyntheticsResultId();\n if (testId && resultId) {\n return {\n test_id: testId,\n result_id: resultId,\n injected: willSyntheticsInjectRum(),\n };\n }\n}\n//# sourceMappingURL=syntheticsContext.js.map","import { sanitize, deepClone, getType, objectEntries } from '@datadog/browser-core';\n/**\n * Current limitation:\n * - field path do not support array, 'a.b.c' only\n */\nexport function limitModification(object, modifiableFieldPaths, modifier) {\n var clone = deepClone(object);\n var result = modifier(clone);\n objectEntries(modifiableFieldPaths).forEach(function (_a) {\n var fieldPath = _a[0], fieldType = _a[1];\n var newValue = get(clone, fieldPath);\n var newType = getType(newValue);\n if (newType === fieldType) {\n set(object, fieldPath, sanitize(newValue));\n }\n else if (fieldType === 'object' && (newType === 'undefined' || newType === 'null')) {\n set(object, fieldPath, {});\n }\n });\n return result;\n}\nfunction get(object, path) {\n var current = object;\n for (var _i = 0, _a = path.split('.'); _i < _a.length; _i++) {\n var field = _a[_i];\n if (!isValidObjectContaining(current, field)) {\n return;\n }\n current = current[field];\n }\n return current;\n}\nfunction set(object, path, value) {\n var current = object;\n var fields = path.split('.');\n for (var i = 0; i < fields.length; i += 1) {\n var field = fields[i];\n if (!isValidObject(current)) {\n return;\n }\n if (i !== fields.length - 1) {\n current = current[field];\n }\n else {\n current[field] = value;\n }\n }\n}\nfunction isValidObject(object) {\n return getType(object) === 'object';\n}\nfunction isValidObjectContaining(object, field) {\n return isValidObject(object) && Object.prototype.hasOwnProperty.call(object, field);\n}\n//# sourceMappingURL=limitModification.js.map","import { combine, isEmptyObject, timeStampNow, currentDrift, display, createEventRateLimiter, canUseEventBridge, assign, round, isExperimentalFeatureEnabled, ExperimentalFeature, getConnectivity, } from '@datadog/browser-core';\nimport { getSyntheticsContext } from './contexts/syntheticsContext';\nimport { limitModification } from './limitModification';\nvar VIEW_MODIFIABLE_FIELD_PATHS = {\n 'view.name': 'string',\n 'view.url': 'string',\n 'view.referrer': 'string',\n};\nvar USER_CUSTOMIZABLE_FIELD_PATHS = {\n context: 'object',\n};\nvar ROOT_MODIFIABLE_FIELD_PATHS = {\n service: 'string',\n version: 'string',\n};\nvar modifiableFieldPathsByEvent;\nexport function startRumAssembly(configuration, lifeCycle, sessionManager, viewHistory, urlContexts, actionContexts, displayContext, ciVisibilityContext, getCommonContext, reportError) {\n var _a, _b;\n modifiableFieldPathsByEvent = (_a = {},\n _a[\"view\" /* RumEventType.VIEW */] = assign({}, USER_CUSTOMIZABLE_FIELD_PATHS, VIEW_MODIFIABLE_FIELD_PATHS),\n _a[\"error\" /* RumEventType.ERROR */] = assign({\n 'error.message': 'string',\n 'error.stack': 'string',\n 'error.resource.url': 'string',\n 'error.fingerprint': 'string',\n }, USER_CUSTOMIZABLE_FIELD_PATHS, VIEW_MODIFIABLE_FIELD_PATHS, ROOT_MODIFIABLE_FIELD_PATHS),\n _a[\"resource\" /* RumEventType.RESOURCE */] = assign({\n 'resource.url': 'string',\n }, isExperimentalFeatureEnabled(ExperimentalFeature.WRITABLE_RESOURCE_GRAPHQL)\n ? {\n 'resource.graphql': 'object',\n }\n : {}, USER_CUSTOMIZABLE_FIELD_PATHS, VIEW_MODIFIABLE_FIELD_PATHS, ROOT_MODIFIABLE_FIELD_PATHS),\n _a[\"action\" /* RumEventType.ACTION */] = assign({\n 'action.target.name': 'string',\n }, USER_CUSTOMIZABLE_FIELD_PATHS, VIEW_MODIFIABLE_FIELD_PATHS, ROOT_MODIFIABLE_FIELD_PATHS),\n _a[\"long_task\" /* RumEventType.LONG_TASK */] = assign({}, USER_CUSTOMIZABLE_FIELD_PATHS, VIEW_MODIFIABLE_FIELD_PATHS),\n _a[\"vital\" /* RumEventType.VITAL */] = assign({}, USER_CUSTOMIZABLE_FIELD_PATHS, VIEW_MODIFIABLE_FIELD_PATHS),\n _a);\n var eventRateLimiters = (_b = {},\n _b[\"error\" /* RumEventType.ERROR */] = createEventRateLimiter(\"error\" /* RumEventType.ERROR */, configuration.eventRateLimiterThreshold, reportError),\n _b[\"action\" /* RumEventType.ACTION */] = createEventRateLimiter(\"action\" /* RumEventType.ACTION */, configuration.eventRateLimiterThreshold, reportError),\n _b[\"vital\" /* RumEventType.VITAL */] = createEventRateLimiter(\"vital\" /* RumEventType.VITAL */, configuration.eventRateLimiterThreshold, reportError),\n _b);\n var syntheticsContext = getSyntheticsContext();\n lifeCycle.subscribe(11 /* LifeCycleEventType.RAW_RUM_EVENT_COLLECTED */, function (_a) {\n var startTime = _a.startTime, rawRumEvent = _a.rawRumEvent, domainContext = _a.domainContext, savedCommonContext = _a.savedCommonContext, customerContext = _a.customerContext;\n var viewHistoryEntry = viewHistory.findView(startTime);\n var urlContext = urlContexts.findUrl(startTime);\n var session = sessionManager.findTrackedSession(startTime);\n if (session && viewHistoryEntry && urlContext) {\n var commonContext = savedCommonContext || getCommonContext();\n var actionId = actionContexts.findActionId(startTime);\n var rumContext = {\n _dd: {\n format_version: 2,\n drift: currentDrift(),\n configuration: {\n session_sample_rate: round(configuration.sessionSampleRate, 3),\n session_replay_sample_rate: round(configuration.sessionReplaySampleRate, 3),\n },\n browser_sdk_version: canUseEventBridge() ? \"5.35.0\" : undefined,\n },\n application: {\n id: configuration.applicationId,\n },\n date: timeStampNow(),\n service: viewHistoryEntry.service || configuration.service,\n version: viewHistoryEntry.version || configuration.version,\n source: 'browser',\n session: {\n id: session.id,\n type: syntheticsContext\n ? \"synthetics\" /* SessionType.SYNTHETICS */\n : ciVisibilityContext.get()\n ? \"ci_test\" /* SessionType.CI_TEST */\n : \"user\" /* SessionType.USER */,\n },\n view: {\n id: viewHistoryEntry.id,\n name: viewHistoryEntry.name,\n url: urlContext.url,\n referrer: urlContext.referrer,\n },\n action: needToAssembleWithAction(rawRumEvent) && actionId ? { id: actionId } : undefined,\n synthetics: syntheticsContext,\n ci_test: ciVisibilityContext.get(),\n display: displayContext.get(),\n connectivity: getConnectivity(),\n };\n var serverRumEvent = combine(rumContext, rawRumEvent);\n serverRumEvent.context = combine(commonContext.context, viewHistoryEntry.context, customerContext);\n if (!('has_replay' in serverRumEvent.session)) {\n ;\n serverRumEvent.session.has_replay = commonContext.hasReplay;\n }\n if (serverRumEvent.type === 'view') {\n ;\n serverRumEvent.session.sampled_for_replay =\n session.sessionReplay === 1 /* SessionReplayState.SAMPLED */;\n }\n if (\n // TODO: remove ff and should always add anonymous user id\n isExperimentalFeatureEnabled(ExperimentalFeature.ANONYMOUS_USER_TRACKING) &&\n !commonContext.user.anonymous_id) {\n commonContext.user.anonymous_id = session.anonymousId;\n }\n if (!isEmptyObject(commonContext.user)) {\n ;\n serverRumEvent.usr = commonContext.user;\n }\n if (shouldSend(serverRumEvent, configuration.beforeSend, domainContext, eventRateLimiters)) {\n if (isEmptyObject(serverRumEvent.context)) {\n delete serverRumEvent.context;\n }\n lifeCycle.notify(12 /* LifeCycleEventType.RUM_EVENT_COLLECTED */, serverRumEvent);\n }\n }\n });\n}\nfunction shouldSend(event, beforeSend, domainContext, eventRateLimiters) {\n var _a;\n if (beforeSend) {\n var result = limitModification(event, modifiableFieldPathsByEvent[event.type], function (event) {\n return beforeSend(event, domainContext);\n });\n if (result === false && event.type !== \"view\" /* RumEventType.VIEW */) {\n return false;\n }\n if (result === false) {\n display.warn(\"Can't dismiss view events using beforeSend!\");\n }\n }\n var rateLimitReached = (_a = eventRateLimiters[event.type]) === null || _a === void 0 ? void 0 : _a.isLimitReached();\n return !rateLimitReached;\n}\nfunction needToAssembleWithAction(event) {\n return [\"error\" /* RumEventType.ERROR */, \"resource\" /* RumEventType.RESOURCE */, \"long_task\" /* RumEventType.LONG_TASK */].indexOf(event.type) !== -1;\n}\n//# sourceMappingURL=assembly.js.map","/**\n * Internal context keep returning v1 format\n * to not break compatibility with logs data format\n */\nexport function startInternalContext(applicationId, sessionManager, viewHistory, actionContexts, urlContexts) {\n return {\n get: function (startTime) {\n var viewContext = viewHistory.findView(startTime);\n var urlContext = urlContexts.findUrl(startTime);\n var session = sessionManager.findTrackedSession(startTime);\n if (session && viewContext && urlContext) {\n var actionId = actionContexts.findActionId(startTime);\n return {\n application_id: applicationId,\n session_id: session.id,\n user_action: actionId ? { id: actionId } : undefined,\n view: { id: viewContext.id, name: viewContext.name, referrer: urlContext.referrer, url: urlContext.url },\n };\n }\n },\n };\n}\n//# sourceMappingURL=internalContext.js.map","import { AbstractLifeCycle } from '@datadog/browser-core';\nexport var LifeCycle = (AbstractLifeCycle);\n//# sourceMappingURL=lifeCycle.js.map","import { SESSION_TIME_OUT_DELAY, createValueHistory } from '@datadog/browser-core';\nexport var VIEW_CONTEXT_TIME_OUT_DELAY = SESSION_TIME_OUT_DELAY;\nexport function startViewHistory(lifeCycle) {\n var viewValueHistory = createValueHistory({ expireDelay: VIEW_CONTEXT_TIME_OUT_DELAY });\n lifeCycle.subscribe(1 /* LifeCycleEventType.BEFORE_VIEW_CREATED */, function (view) {\n viewValueHistory.add(buildViewHistoryEntry(view), view.startClocks.relative);\n });\n lifeCycle.subscribe(5 /* LifeCycleEventType.AFTER_VIEW_ENDED */, function (_a) {\n var endClocks = _a.endClocks;\n viewValueHistory.closeActive(endClocks.relative);\n });\n lifeCycle.subscribe(3 /* LifeCycleEventType.VIEW_UPDATED */, function (viewUpdate) {\n var currentView = viewValueHistory.find(viewUpdate.startClocks.relative);\n if (currentView && viewUpdate.name) {\n currentView.name = viewUpdate.name;\n }\n if (currentView && viewUpdate.context) {\n currentView.context = viewUpdate.context;\n }\n });\n lifeCycle.subscribe(9 /* LifeCycleEventType.SESSION_RENEWED */, function () {\n viewValueHistory.reset();\n });\n function buildViewHistoryEntry(view) {\n return {\n service: view.service,\n version: view.version,\n context: view.context,\n id: view.id,\n name: view.name,\n startClocks: view.startClocks,\n };\n }\n return {\n findView: function (startTime) { return viewValueHistory.find(startTime); },\n stop: function () {\n viewValueHistory.stop();\n },\n };\n}\n//# sourceMappingURL=viewHistory.js.map","import { addTelemetryDebug, elapsed, getPathName, includes, isValidUrl, toServerDuration, isIntakeUrl, } from '@datadog/browser-core';\nexport var FAKE_INITIAL_DOCUMENT = 'initial_document';\nvar RESOURCE_TYPES = [\n [\"document\" /* ResourceType.DOCUMENT */, function (initiatorType) { return FAKE_INITIAL_DOCUMENT === initiatorType; }],\n [\"xhr\" /* ResourceType.XHR */, function (initiatorType) { return 'xmlhttprequest' === initiatorType; }],\n [\"fetch\" /* ResourceType.FETCH */, function (initiatorType) { return 'fetch' === initiatorType; }],\n [\"beacon\" /* ResourceType.BEACON */, function (initiatorType) { return 'beacon' === initiatorType; }],\n [\"css\" /* ResourceType.CSS */, function (_, path) { return /\\.css$/i.test(path); }],\n [\"js\" /* ResourceType.JS */, function (_, path) { return /\\.js$/i.test(path); }],\n [\n \"image\" /* ResourceType.IMAGE */,\n function (initiatorType, path) {\n return includes(['image', 'img', 'icon'], initiatorType) || /\\.(gif|jpg|jpeg|tiff|png|svg|ico)$/i.exec(path) !== null;\n },\n ],\n [\"font\" /* ResourceType.FONT */, function (_, path) { return /\\.(woff|eot|woff2|ttf)$/i.exec(path) !== null; }],\n [\n \"media\" /* ResourceType.MEDIA */,\n function (initiatorType, path) {\n return includes(['audio', 'video'], initiatorType) || /\\.(mp3|mp4)$/i.exec(path) !== null;\n },\n ],\n];\nexport function computeResourceEntryType(entry) {\n var url = entry.name;\n if (!isValidUrl(url)) {\n addTelemetryDebug(\"Failed to construct URL for \\\"\".concat(entry.name, \"\\\"\"));\n return \"other\" /* ResourceType.OTHER */;\n }\n var path = getPathName(url);\n for (var _i = 0, RESOURCE_TYPES_1 = RESOURCE_TYPES; _i < RESOURCE_TYPES_1.length; _i++) {\n var _a = RESOURCE_TYPES_1[_i], type = _a[0], isType = _a[1];\n if (isType(entry.initiatorType, path)) {\n return type;\n }\n }\n return \"other\" /* ResourceType.OTHER */;\n}\nfunction areInOrder() {\n var numbers = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n numbers[_i] = arguments[_i];\n }\n for (var i = 1; i < numbers.length; i += 1) {\n if (numbers[i - 1] > numbers[i]) {\n return false;\n }\n }\n return true;\n}\nexport function isResourceEntryRequestType(entry) {\n return entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch';\n}\nexport function computeResourceEntryDuration(entry) {\n var duration = entry.duration, startTime = entry.startTime, responseEnd = entry.responseEnd;\n // Safari duration is always 0 on timings blocked by cross origin policies.\n if (duration === 0 && startTime < responseEnd) {\n return toServerDuration(elapsed(startTime, responseEnd));\n }\n return toServerDuration(duration);\n}\nexport function computeResourceEntryDetails(entry) {\n if (!hasValidResourceEntryTimings(entry)) {\n return undefined;\n }\n var startTime = entry.startTime, fetchStart = entry.fetchStart, workerStart = entry.workerStart, redirectStart = entry.redirectStart, redirectEnd = entry.redirectEnd, domainLookupStart = entry.domainLookupStart, domainLookupEnd = entry.domainLookupEnd, connectStart = entry.connectStart, secureConnectionStart = entry.secureConnectionStart, connectEnd = entry.connectEnd, requestStart = entry.requestStart, responseStart = entry.responseStart, responseEnd = entry.responseEnd;\n var details = {\n download: formatTiming(startTime, responseStart, responseEnd),\n first_byte: formatTiming(startTime, requestStart, responseStart),\n };\n // Make sure a worker processing time is recorded\n if (0 < workerStart && workerStart < fetchStart) {\n details.worker = formatTiming(startTime, workerStart, fetchStart);\n }\n // Make sure a connection occurred\n if (fetchStart < connectEnd) {\n details.connect = formatTiming(startTime, connectStart, connectEnd);\n // Make sure a secure connection occurred\n if (connectStart <= secureConnectionStart && secureConnectionStart <= connectEnd) {\n details.ssl = formatTiming(startTime, secureConnectionStart, connectEnd);\n }\n }\n // Make sure a domain lookup occurred\n if (fetchStart < domainLookupEnd) {\n details.dns = formatTiming(startTime, domainLookupStart, domainLookupEnd);\n }\n // Make sure a redirection occurred\n if (startTime < redirectEnd) {\n details.redirect = formatTiming(startTime, redirectStart, redirectEnd);\n }\n return details;\n}\n/**\n * Entries with negative duration are unexpected and should be dismissed. The intake will ignore RUM\n * Resource events with negative durations anyway.\n * Since Chromium 128, more entries have unexpected negative durations, see\n * https://issues.chromium.org/issues/363031537\n */\nexport function hasValidResourceEntryDuration(entry) {\n return entry.duration >= 0;\n}\nexport function hasValidResourceEntryTimings(entry) {\n // Ensure timings are in the right order. On top of filtering out potential invalid\n // RumPerformanceResourceTiming, it will ignore entries from requests where timings cannot be\n // collected, for example cross origin requests without a \"Timing-Allow-Origin\" header allowing\n // it.\n var areCommonTimingsInOrder = areInOrder(entry.startTime, entry.fetchStart, entry.domainLookupStart, entry.domainLookupEnd, entry.connectStart, entry.connectEnd, entry.requestStart, entry.responseStart, entry.responseEnd);\n var areRedirectionTimingsInOrder = hasRedirection(entry)\n ? areInOrder(entry.startTime, entry.redirectStart, entry.redirectEnd, entry.fetchStart)\n : true;\n return areCommonTimingsInOrder && areRedirectionTimingsInOrder;\n}\nfunction hasRedirection(entry) {\n return entry.redirectEnd > entry.startTime;\n}\nfunction formatTiming(origin, start, end) {\n if (origin <= start && start <= end) {\n return {\n duration: toServerDuration(elapsed(start, end)),\n start: toServerDuration(elapsed(origin, start)),\n };\n }\n}\n/**\n * The 'nextHopProtocol' is an empty string for cross-origin resources without CORS headers,\n * meaning the protocol is unknown, and we shouldn't report it.\n * https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming/nextHopProtocol#cross-origin_resources\n */\nexport function computeResourceEntryProtocol(entry) {\n return entry.nextHopProtocol === '' ? undefined : entry.nextHopProtocol;\n}\n/**\n * Handles the 'deliveryType' property to distinguish between supported values ('cache', 'navigational-prefetch'),\n * undefined (unsupported in some browsers), and other cases ('other' for unknown or unrecognized values).\n * see: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming/deliveryType\n */\nexport function computeResourceEntryDeliveryType(entry) {\n return entry.deliveryType === '' ? 'other' : entry.deliveryType;\n}\nexport function computeResourceEntrySize(entry) {\n // Make sure a request actually occurred\n if (entry.startTime < entry.responseStart) {\n var encodedBodySize = entry.encodedBodySize, decodedBodySize = entry.decodedBodySize, transferSize = entry.transferSize;\n return {\n size: decodedBodySize,\n encoded_body_size: encodedBodySize,\n decoded_body_size: decodedBodySize,\n transfer_size: transferSize,\n };\n }\n return {\n size: undefined,\n encoded_body_size: undefined,\n decoded_body_size: undefined,\n transfer_size: undefined,\n };\n}\nexport function isAllowedRequestUrl(url) {\n return url && !isIntakeUrl(url);\n}\nvar DATA_URL_REGEX = /data:(.+)?(;base64)?,/g;\nexport var MAX_ATTRIBUTE_VALUE_CHAR_LENGTH = 24000;\nexport function isLongDataUrl(url) {\n if (url.length <= MAX_ATTRIBUTE_VALUE_CHAR_LENGTH) {\n return false;\n }\n else if (url.substring(0, 5) === 'data:') {\n // Avoid String.match RangeError: Maximum call stack size exceeded\n url = url.substring(0, MAX_ATTRIBUTE_VALUE_CHAR_LENGTH);\n return true;\n }\n return false;\n}\nexport function sanitizeDataUrl(url) {\n return \"\".concat(url.match(DATA_URL_REGEX)[0], \"[...]\");\n}\n//# sourceMappingURL=resourceUtils.js.map","import { initFetchObservable, initXhrObservable, readBytesFromStream, elapsed, timeStampNow, tryToClone, } from '@datadog/browser-core';\nimport { isAllowedRequestUrl } from './resource/resourceUtils';\nimport { startTracer } from './tracing/tracer';\nvar nextRequestIndex = 1;\nexport function startRequestCollection(lifeCycle, configuration, sessionManager) {\n var tracer = startTracer(configuration, sessionManager);\n trackXhr(lifeCycle, configuration, tracer);\n trackFetch(lifeCycle, tracer);\n}\nexport function trackXhr(lifeCycle, configuration, tracer) {\n var subscription = initXhrObservable(configuration).subscribe(function (rawContext) {\n var context = rawContext;\n if (!isAllowedRequestUrl(context.url)) {\n return;\n }\n switch (context.state) {\n case 'start':\n tracer.traceXhr(context, context.xhr);\n context.requestIndex = getNextRequestIndex();\n lifeCycle.notify(6 /* LifeCycleEventType.REQUEST_STARTED */, {\n requestIndex: context.requestIndex,\n url: context.url,\n });\n break;\n case 'complete':\n tracer.clearTracingIfNeeded(context);\n lifeCycle.notify(7 /* LifeCycleEventType.REQUEST_COMPLETED */, {\n duration: context.duration,\n method: context.method,\n requestIndex: context.requestIndex,\n spanId: context.spanId,\n startClocks: context.startClocks,\n status: context.status,\n traceId: context.traceId,\n traceSampled: context.traceSampled,\n type: \"xhr\" /* RequestType.XHR */,\n url: context.url,\n xhr: context.xhr,\n isAborted: context.isAborted,\n handlingStack: context.handlingStack,\n });\n break;\n }\n });\n return { stop: function () { return subscription.unsubscribe(); } };\n}\nexport function trackFetch(lifeCycle, tracer) {\n var subscription = initFetchObservable().subscribe(function (rawContext) {\n var context = rawContext;\n if (!isAllowedRequestUrl(context.url)) {\n return;\n }\n switch (context.state) {\n case 'start':\n tracer.traceFetch(context);\n context.requestIndex = getNextRequestIndex();\n lifeCycle.notify(6 /* LifeCycleEventType.REQUEST_STARTED */, {\n requestIndex: context.requestIndex,\n url: context.url,\n });\n break;\n case 'resolve':\n waitForResponseToComplete(context, function (duration) {\n tracer.clearTracingIfNeeded(context);\n lifeCycle.notify(7 /* LifeCycleEventType.REQUEST_COMPLETED */, {\n duration: duration,\n method: context.method,\n requestIndex: context.requestIndex,\n responseType: context.responseType,\n spanId: context.spanId,\n startClocks: context.startClocks,\n status: context.status,\n traceId: context.traceId,\n traceSampled: context.traceSampled,\n type: \"fetch\" /* RequestType.FETCH */,\n url: context.url,\n response: context.response,\n init: context.init,\n input: context.input,\n isAborted: context.isAborted,\n handlingStack: context.handlingStack,\n });\n });\n break;\n }\n });\n return { stop: function () { return subscription.unsubscribe(); } };\n}\nfunction getNextRequestIndex() {\n var result = nextRequestIndex;\n nextRequestIndex += 1;\n return result;\n}\nfunction waitForResponseToComplete(context, callback) {\n var clonedResponse = context.response && tryToClone(context.response);\n if (!clonedResponse || !clonedResponse.body) {\n // do not try to wait for the response if the clone failed, fetch error or null body\n callback(elapsed(context.startClocks.timeStamp, timeStampNow()));\n }\n else {\n readBytesFromStream(clonedResponse.body, function () {\n callback(elapsed(context.startClocks.timeStamp, timeStampNow()));\n }, {\n bytesLimit: Number.POSITIVE_INFINITY,\n collectStreamBody: false,\n });\n }\n}\n//# sourceMappingURL=requestCollection.js.map","import { isNumber } from '@datadog/browser-core';\nexport function discardNegativeDuration(duration) {\n return isNumber(duration) && duration < 0 ? undefined : duration;\n}\n//# sourceMappingURL=discardNegativeDuration.js.map","import { noop } from '@datadog/browser-core';\nexport function trackEventCounts(_a) {\n var lifeCycle = _a.lifeCycle, isChildEvent = _a.isChildEvent, _b = _a.onChange, callback = _b === void 0 ? noop : _b;\n var eventCounts = {\n errorCount: 0,\n longTaskCount: 0,\n resourceCount: 0,\n actionCount: 0,\n frustrationCount: 0,\n };\n var subscription = lifeCycle.subscribe(12 /* LifeCycleEventType.RUM_EVENT_COLLECTED */, function (event) {\n var _a;\n if (event.type === 'view' || event.type === 'vital' || !isChildEvent(event)) {\n return;\n }\n switch (event.type) {\n case \"error\" /* RumEventType.ERROR */:\n eventCounts.errorCount += 1;\n callback();\n break;\n case \"action\" /* RumEventType.ACTION */:\n eventCounts.actionCount += 1;\n if (event.action.frustration) {\n eventCounts.frustrationCount += event.action.frustration.type.length;\n }\n callback();\n break;\n case \"long_task\" /* RumEventType.LONG_TASK */:\n eventCounts.longTaskCount += 1;\n callback();\n break;\n case \"resource\" /* RumEventType.RESOURCE */:\n if (!((_a = event._dd) === null || _a === void 0 ? void 0 : _a.discarded)) {\n eventCounts.resourceCount += 1;\n callback();\n }\n break;\n }\n });\n return {\n stop: function () {\n subscription.unsubscribe();\n },\n eventCounts: eventCounts,\n };\n}\n//# sourceMappingURL=trackEventCounts.js.map","import { addEventListeners, dateNow, relativeNow } from '@datadog/browser-core';\n/**\n * first-input timing entry polyfill based on\n * https://github.com/GoogleChrome/web-vitals/blob/master/src/lib/polyfills/firstInputPolyfill.ts\n */\nexport function retrieveFirstInputTiming(configuration, callback) {\n var startTimeStamp = dateNow();\n var timingSent = false;\n var removeEventListeners = addEventListeners(configuration, window, [\"click\" /* DOM_EVENT.CLICK */, \"mousedown\" /* DOM_EVENT.MOUSE_DOWN */, \"keydown\" /* DOM_EVENT.KEY_DOWN */, \"touchstart\" /* DOM_EVENT.TOUCH_START */, \"pointerdown\" /* DOM_EVENT.POINTER_DOWN */], function (evt) {\n // Only count cancelable events, which should trigger behavior important to the user.\n if (!evt.cancelable) {\n return;\n }\n // This timing will be used to compute the \"first Input delay\", which is the delta between\n // when the system received the event (e.g. evt.timeStamp) and when it could run the callback\n // (e.g. performance.now()).\n var timing = {\n entryType: 'first-input',\n processingStart: relativeNow(),\n processingEnd: relativeNow(),\n startTime: evt.timeStamp,\n duration: 0, // arbitrary value to avoid nullable duration and simplify INP logic\n name: '',\n cancelable: false,\n target: null,\n toJSON: function () { return ({}); },\n };\n if (evt.type === \"pointerdown\" /* DOM_EVENT.POINTER_DOWN */) {\n sendTimingIfPointerIsNotCancelled(configuration, timing);\n }\n else {\n sendTiming(timing);\n }\n }, { passive: true, capture: true }).stop;\n return { stop: removeEventListeners };\n /**\n * Pointer events are a special case, because they can trigger main or compositor thread behavior.\n * We differentiate these cases based on whether or not we see a pointercancel event, which are\n * fired when we scroll. If we're scrolling we don't need to report input delay since FID excludes\n * scrolling and pinch/zooming.\n */\n function sendTimingIfPointerIsNotCancelled(configuration, timing) {\n addEventListeners(configuration, window, [\"pointerup\" /* DOM_EVENT.POINTER_UP */, \"pointercancel\" /* DOM_EVENT.POINTER_CANCEL */], function (event) {\n if (event.type === \"pointerup\" /* DOM_EVENT.POINTER_UP */) {\n sendTiming(timing);\n }\n }, { once: true });\n }\n function sendTiming(timing) {\n if (!timingSent) {\n timingSent = true;\n removeEventListeners();\n // In some cases the recorded delay is clearly wrong, e.g. it's negative or it's larger than\n // the time between now and when the page was loaded.\n // - https://github.com/GoogleChromeLabs/first-input-delay/issues/4\n // - https://github.com/GoogleChromeLabs/first-input-delay/issues/6\n // - https://github.com/GoogleChromeLabs/first-input-delay/issues/7\n var delay = timing.processingStart - timing.startTime;\n if (delay >= 0 && delay < dateNow() - startTimeStamp) {\n callback(timing);\n }\n }\n }\n}\n//# sourceMappingURL=firstInputPolyfill.js.map","import { addEventListener, Observable, setTimeout, clearTimeout, monitor, includes } from '@datadog/browser-core';\nimport { hasValidResourceEntryDuration, isAllowedRequestUrl } from '../domain/resource/resourceUtils';\nimport { retrieveFirstInputTiming } from './firstInputPolyfill';\n// We want to use a real enum (i.e. not a const enum) here, to be able to check whether an arbitrary\n// string is an expected performance entry\n// eslint-disable-next-line no-restricted-syntax\nexport var RumPerformanceEntryType;\n(function (RumPerformanceEntryType) {\n RumPerformanceEntryType[\"EVENT\"] = \"event\";\n RumPerformanceEntryType[\"FIRST_INPUT\"] = \"first-input\";\n RumPerformanceEntryType[\"LARGEST_CONTENTFUL_PAINT\"] = \"largest-contentful-paint\";\n RumPerformanceEntryType[\"LAYOUT_SHIFT\"] = \"layout-shift\";\n RumPerformanceEntryType[\"LONG_TASK\"] = \"longtask\";\n RumPerformanceEntryType[\"LONG_ANIMATION_FRAME\"] = \"long-animation-frame\";\n RumPerformanceEntryType[\"NAVIGATION\"] = \"navigation\";\n RumPerformanceEntryType[\"PAINT\"] = \"paint\";\n RumPerformanceEntryType[\"RESOURCE\"] = \"resource\";\n})(RumPerformanceEntryType || (RumPerformanceEntryType = {}));\nexport function createPerformanceObservable(configuration, options) {\n return new Observable(function (observable) {\n if (!window.PerformanceObserver) {\n return;\n }\n var handlePerformanceEntries = function (entries) {\n var rumPerformanceEntries = filterRumPerformanceEntries(entries);\n if (rumPerformanceEntries.length > 0) {\n observable.notify(rumPerformanceEntries);\n }\n };\n var timeoutId;\n var isObserverInitializing = true;\n var observer = new PerformanceObserver(monitor(function (entries) {\n // In Safari the performance observer callback is synchronous.\n // Because the buffered performance entry list can be quite large we delay the computation to prevent the SDK from blocking the main thread on init\n if (isObserverInitializing) {\n timeoutId = setTimeout(function () { return handlePerformanceEntries(entries.getEntries()); });\n }\n else {\n handlePerformanceEntries(entries.getEntries());\n }\n }));\n try {\n observer.observe(options);\n }\n catch (_a) {\n // Some old browser versions (<= chrome 74 ) don't support the PerformanceObserver type and buffered options\n // In these cases, fallback to getEntriesByType and PerformanceObserver with entryTypes\n // TODO: remove this fallback in the next major version\n var fallbackSupportedEntryTypes = [\n RumPerformanceEntryType.RESOURCE,\n RumPerformanceEntryType.NAVIGATION,\n RumPerformanceEntryType.LONG_TASK,\n RumPerformanceEntryType.PAINT,\n ];\n if (includes(fallbackSupportedEntryTypes, options.type)) {\n if (options.buffered) {\n timeoutId = setTimeout(function () { return handlePerformanceEntries(performance.getEntriesByType(options.type)); });\n }\n try {\n observer.observe({ entryTypes: [options.type] });\n }\n catch (_b) {\n // Old versions of Safari are throwing \"entryTypes contained only unsupported types\"\n // errors when observing only unsupported entry types.\n //\n // We could use `supportPerformanceTimingEvent` to make sure we don't invoke\n // `observer.observe` with an unsupported entry type, but Safari 11 and 12 don't support\n // `Performance.supportedEntryTypes`, so doing so would lose support for these versions\n // even if they do support the entry type.\n return;\n }\n }\n }\n isObserverInitializing = false;\n manageResourceTimingBufferFull(configuration);\n var stopFirstInputTiming;\n if (!supportPerformanceTimingEvent(RumPerformanceEntryType.FIRST_INPUT) &&\n options.type === RumPerformanceEntryType.FIRST_INPUT) {\n ;\n (stopFirstInputTiming = retrieveFirstInputTiming(configuration, function (timing) {\n handlePerformanceEntries([timing]);\n }).stop);\n }\n return function () {\n observer.disconnect();\n if (stopFirstInputTiming) {\n stopFirstInputTiming();\n }\n clearTimeout(timeoutId);\n };\n });\n}\nvar resourceTimingBufferFullListener;\nfunction manageResourceTimingBufferFull(configuration) {\n if (!resourceTimingBufferFullListener && supportPerformanceObject() && 'addEventListener' in performance) {\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1559377\n resourceTimingBufferFullListener = addEventListener(configuration, performance, 'resourcetimingbufferfull', function () {\n performance.clearResourceTimings();\n });\n }\n return function () {\n resourceTimingBufferFullListener === null || resourceTimingBufferFullListener === void 0 ? void 0 : resourceTimingBufferFullListener.stop();\n };\n}\nfunction supportPerformanceObject() {\n return window.performance !== undefined && 'getEntries' in performance;\n}\nexport function supportPerformanceTimingEvent(entryType) {\n return (window.PerformanceObserver &&\n PerformanceObserver.supportedEntryTypes !== undefined &&\n PerformanceObserver.supportedEntryTypes.includes(entryType));\n}\nfunction filterRumPerformanceEntries(entries) {\n return entries.filter(function (entry) { return !isForbiddenResource(entry); });\n}\nfunction isForbiddenResource(entry) {\n return (entry.entryType === RumPerformanceEntryType.RESOURCE &&\n (!isAllowedRequestUrl(entry.name) || !hasValidResourceEntryDuration(entry)));\n}\n//# sourceMappingURL=performanceObservable.js.map","import { matchList, monitor, Observable, timeStampNow, setTimeout, clearTimeout } from '@datadog/browser-core';\nimport { createPerformanceObservable, RumPerformanceEntryType } from '../browser/performanceObservable';\n// Delay to wait for a page activity to validate the tracking process\nexport var PAGE_ACTIVITY_VALIDATION_DELAY = 100;\n// Delay to wait after a page activity to end the tracking process\nexport var PAGE_ACTIVITY_END_DELAY = 100;\n/**\n * Wait for the page activity end\n *\n * Detection lifecycle:\n * ```\n * Wait page activity end\n * .-------------------'--------------------.\n * v v\n * [Wait for a page activity ] [Wait for a maximum duration]\n * [timeout: VALIDATION_DELAY] [ timeout: maxDuration ]\n * / \\ |\n * v v |\n * [No page activity] [Page activity] |\n * | |,----------------------. |\n * v v | |\n * (Discard) [Wait for a page activity] | |\n * [ timeout: END_DELAY ] | |\n * / \\ | |\n * v v | |\n * [No page activity] [Page activity] | |\n * | | | |\n * | '------------' |\n * '-----------. ,--------------------'\n * v\n * (End)\n * ```\n *\n * Note: by assuming that maxDuration is greater than VALIDATION_DELAY, we are sure that if the\n * process is still alive after maxDuration, it has been validated.\n */\nexport function waitPageActivityEnd(lifeCycle, domMutationObservable, windowOpenObservable, configuration, pageActivityEndCallback, maxDuration) {\n var pageActivityObservable = createPageActivityObservable(lifeCycle, domMutationObservable, windowOpenObservable, configuration);\n return doWaitPageActivityEnd(pageActivityObservable, pageActivityEndCallback, maxDuration);\n}\nexport function doWaitPageActivityEnd(pageActivityObservable, pageActivityEndCallback, maxDuration) {\n var pageActivityEndTimeoutId;\n var hasCompleted = false;\n var validationTimeoutId = setTimeout(monitor(function () { return complete({ hadActivity: false }); }), PAGE_ACTIVITY_VALIDATION_DELAY);\n var maxDurationTimeoutId = maxDuration !== undefined\n ? setTimeout(monitor(function () { return complete({ hadActivity: true, end: timeStampNow() }); }), maxDuration)\n : undefined;\n var pageActivitySubscription = pageActivityObservable.subscribe(function (_a) {\n var isBusy = _a.isBusy;\n clearTimeout(validationTimeoutId);\n clearTimeout(pageActivityEndTimeoutId);\n var lastChangeTime = timeStampNow();\n if (!isBusy) {\n pageActivityEndTimeoutId = setTimeout(monitor(function () { return complete({ hadActivity: true, end: lastChangeTime }); }), PAGE_ACTIVITY_END_DELAY);\n }\n });\n var stop = function () {\n hasCompleted = true;\n clearTimeout(validationTimeoutId);\n clearTimeout(pageActivityEndTimeoutId);\n clearTimeout(maxDurationTimeoutId);\n pageActivitySubscription.unsubscribe();\n };\n function complete(event) {\n if (hasCompleted) {\n return;\n }\n stop();\n pageActivityEndCallback(event);\n }\n return { stop: stop };\n}\nexport function createPageActivityObservable(lifeCycle, domMutationObservable, windowOpenObservable, configuration) {\n return new Observable(function (observable) {\n var subscriptions = [];\n var firstRequestIndex;\n var pendingRequestsCount = 0;\n subscriptions.push(domMutationObservable.subscribe(notifyPageActivity), windowOpenObservable.subscribe(notifyPageActivity), createPerformanceObservable(configuration, { type: RumPerformanceEntryType.RESOURCE }).subscribe(function (entries) {\n if (entries.some(function (entry) { return !isExcludedUrl(configuration, entry.name); })) {\n notifyPageActivity();\n }\n }), lifeCycle.subscribe(6 /* LifeCycleEventType.REQUEST_STARTED */, function (startEvent) {\n if (isExcludedUrl(configuration, startEvent.url)) {\n return;\n }\n if (firstRequestIndex === undefined) {\n firstRequestIndex = startEvent.requestIndex;\n }\n pendingRequestsCount += 1;\n notifyPageActivity();\n }), lifeCycle.subscribe(7 /* LifeCycleEventType.REQUEST_COMPLETED */, function (request) {\n if (isExcludedUrl(configuration, request.url) ||\n firstRequestIndex === undefined ||\n // If the request started before the tracking start, ignore it\n request.requestIndex < firstRequestIndex) {\n return;\n }\n pendingRequestsCount -= 1;\n notifyPageActivity();\n }));\n return function () {\n subscriptions.forEach(function (s) { return s.unsubscribe(); });\n };\n function notifyPageActivity() {\n observable.notify({ isBusy: pendingRequestsCount > 0 });\n }\n });\n}\nfunction isExcludedUrl(configuration, requestUrl) {\n return matchList(configuration.excludedActivityUrls, requestUrl);\n}\n//# sourceMappingURL=waitPageActivityEnd.js.map","// https://github.com/jquery/jquery/blob/a684e6ba836f7c553968d7d026ed7941e1a612d8/src/selector/escapeSelector.js\nexport function cssEscape(str) {\n if (window.CSS && window.CSS.escape) {\n return window.CSS.escape(str);\n }\n // eslint-disable-next-line no-control-regex\n return str.replace(/([\\0-\\x1f\\x7f]|^-?\\d)|^-$|[^\\x80-\\uFFFF\\w-]/g, function (ch, asCodePoint) {\n if (asCodePoint) {\n // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER\n if (ch === '\\0') {\n return '\\uFFFD';\n }\n // Control characters and (dependent upon position) numbers get escaped as code points\n return \"\".concat(ch.slice(0, -1), \"\\\\\").concat(ch.charCodeAt(ch.length - 1).toString(16), \" \");\n }\n // Other potentially-special ASCII characters get backslash-escaped\n return \"\\\\\".concat(ch);\n });\n}\nexport function elementMatches(element, selector) {\n if (element.matches) {\n return element.matches(selector);\n }\n // IE11 support\n if (element.msMatchesSelector) {\n return element.msMatchesSelector(selector);\n }\n return false;\n}\n/**\n * Return the parentElement of an node\n *\n * In cases where parentElement is not supported, such as in IE11 for SVG nodes, we fallback to parentNode\n */\nexport function getParentElement(node) {\n if (node.parentElement) {\n return node.parentElement;\n }\n while (node.parentNode) {\n if (node.parentNode.nodeType === Node.ELEMENT_NODE) {\n return node.parentNode;\n }\n node = node.parentNode;\n }\n return null;\n}\n/**\n * Return the classList of an element or an array of classes if classList is not supported\n *\n * In cases where classList is not supported, such as in IE11 for SVG and MathML elements,\n * we fallback to using element.getAttribute('class').\n * We opt for element.getAttribute('class') over element.className because className returns an SVGAnimatedString for SVG elements.\n */\nexport function getClassList(element) {\n if (element.classList) {\n return element.classList;\n }\n var classes = (element.getAttribute('class') || '').trim();\n return classes ? classes.split(/\\s+/) : [];\n}\n// ie11 supports WeakMap but not WeakSet\nvar PLACEHOLDER = 1;\n// eslint-disable-next-line no-restricted-syntax\nvar WeakSet = /** @class */ (function () {\n function WeakSet(initialValues) {\n var _this = this;\n this.map = new WeakMap();\n if (initialValues) {\n initialValues.forEach(function (value) { return _this.map.set(value, PLACEHOLDER); });\n }\n }\n WeakSet.prototype.add = function (value) {\n this.map.set(value, PLACEHOLDER);\n return this;\n };\n WeakSet.prototype.delete = function (value) {\n return this.map.delete(value);\n };\n WeakSet.prototype.has = function (value) {\n return this.map.has(value);\n };\n return WeakSet;\n}());\nexport { WeakSet };\n//# sourceMappingURL=polyfills.js.map","export function isTextNode(node) {\n return node.nodeType === Node.TEXT_NODE;\n}\nexport function isCommentNode(node) {\n return node.nodeType === Node.COMMENT_NODE;\n}\nexport function isElementNode(node) {\n return node.nodeType === Node.ELEMENT_NODE;\n}\nexport function isNodeShadowHost(node) {\n return isElementNode(node) && Boolean(node.shadowRoot);\n}\nexport function isNodeShadowRoot(node) {\n var shadowRoot = node;\n return !!shadowRoot.host && shadowRoot.nodeType === Node.DOCUMENT_FRAGMENT_NODE && isElementNode(shadowRoot.host);\n}\nexport function hasChildNodes(node) {\n return node.childNodes.length > 0 || isNodeShadowHost(node);\n}\nexport function forEachChildNodes(node, callback) {\n var child = node.firstChild;\n while (child) {\n callback(child);\n child = child.nextSibling;\n }\n if (isNodeShadowHost(node)) {\n callback(node.shadowRoot);\n }\n}\n/**\n * Return `host` in case if the current node is a shadow root otherwise will return the `parentNode`\n */\nexport function getParentNode(node) {\n return isNodeShadowRoot(node) ? node.host : node.parentNode;\n}\n//# sourceMappingURL=htmlDomUtils.js.map","import { DefaultPrivacyLevel } from '@datadog/browser-core';\nimport { isElementNode, getParentNode, isTextNode } from '../browser/htmlDomUtils';\nimport { elementMatches } from '../browser/polyfills';\nexport var NodePrivacyLevel = {\n IGNORE: 'ignore',\n HIDDEN: 'hidden',\n ALLOW: DefaultPrivacyLevel.ALLOW,\n MASK: DefaultPrivacyLevel.MASK,\n MASK_USER_INPUT: DefaultPrivacyLevel.MASK_USER_INPUT,\n};\nexport var PRIVACY_ATTR_NAME = 'data-dd-privacy';\n// Privacy Attrs\nexport var PRIVACY_ATTR_VALUE_ALLOW = 'allow';\nexport var PRIVACY_ATTR_VALUE_MASK = 'mask';\nexport var PRIVACY_ATTR_VALUE_MASK_USER_INPUT = 'mask-user-input';\nexport var PRIVACY_ATTR_VALUE_HIDDEN = 'hidden';\n// Privacy Classes - not all customers can set plain HTML attributes, so support classes too\nexport var PRIVACY_CLASS_PREFIX = 'dd-privacy-';\n// Private Replacement Templates\nexport var CENSORED_STRING_MARK = '***';\nexport var CENSORED_IMG_MARK = 'data:image/gif;base64,R0lGODlhAQABAIAAAMLCwgAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==';\nexport var FORM_PRIVATE_TAG_NAMES = {\n INPUT: true,\n OUTPUT: true,\n TEXTAREA: true,\n SELECT: true,\n OPTION: true,\n DATALIST: true,\n OPTGROUP: true,\n};\nvar TEXT_MASKING_CHAR = 'x';\n/**\n * Get node privacy level by iterating over its ancestors. When the direct parent privacy level is\n * know, it is best to use something like:\n *\n * derivePrivacyLevelGivenParent(getNodeSelfPrivacyLevel(node), parentNodePrivacyLevel)\n */\nexport function getNodePrivacyLevel(node, defaultPrivacyLevel, cache) {\n if (cache && cache.has(node)) {\n return cache.get(node);\n }\n var parentNode = getParentNode(node);\n var parentNodePrivacyLevel = parentNode\n ? getNodePrivacyLevel(parentNode, defaultPrivacyLevel, cache)\n : defaultPrivacyLevel;\n var selfNodePrivacyLevel = getNodeSelfPrivacyLevel(node);\n var nodePrivacyLevel = reducePrivacyLevel(selfNodePrivacyLevel, parentNodePrivacyLevel);\n if (cache) {\n cache.set(node, nodePrivacyLevel);\n }\n return nodePrivacyLevel;\n}\n/**\n * Reduces the next privacy level based on self + parent privacy levels\n */\nexport function reducePrivacyLevel(childPrivacyLevel, parentNodePrivacyLevel) {\n switch (parentNodePrivacyLevel) {\n // These values cannot be overridden\n case NodePrivacyLevel.HIDDEN:\n case NodePrivacyLevel.IGNORE:\n return parentNodePrivacyLevel;\n }\n switch (childPrivacyLevel) {\n case NodePrivacyLevel.ALLOW:\n case NodePrivacyLevel.MASK:\n case NodePrivacyLevel.MASK_USER_INPUT:\n case NodePrivacyLevel.HIDDEN:\n case NodePrivacyLevel.IGNORE:\n return childPrivacyLevel;\n default:\n return parentNodePrivacyLevel;\n }\n}\n/**\n * Determines the node's own privacy level without checking for ancestors.\n */\nexport function getNodeSelfPrivacyLevel(node) {\n // Only Element types can have a privacy level set\n if (!isElementNode(node)) {\n return;\n }\n // Overrules for replay purpose\n if (node.tagName === 'BASE') {\n return NodePrivacyLevel.ALLOW;\n }\n // Overrules to enforce end-user protection\n if (node.tagName === 'INPUT') {\n var inputElement = node;\n if (inputElement.type === 'password' || inputElement.type === 'email' || inputElement.type === 'tel') {\n return NodePrivacyLevel.MASK;\n }\n if (inputElement.type === 'hidden') {\n return NodePrivacyLevel.MASK;\n }\n var autocomplete = inputElement.getAttribute('autocomplete');\n // Handle input[autocomplete=cc-number/cc-csc/cc-exp/cc-exp-month/cc-exp-year/new-password/current-password]\n if (autocomplete && (autocomplete.startsWith('cc-') || autocomplete.endsWith('-password'))) {\n return NodePrivacyLevel.MASK;\n }\n }\n // Check HTML privacy attributes and classes\n if (elementMatches(node, getPrivacySelector(NodePrivacyLevel.HIDDEN))) {\n return NodePrivacyLevel.HIDDEN;\n }\n if (elementMatches(node, getPrivacySelector(NodePrivacyLevel.MASK))) {\n return NodePrivacyLevel.MASK;\n }\n if (elementMatches(node, getPrivacySelector(NodePrivacyLevel.MASK_USER_INPUT))) {\n return NodePrivacyLevel.MASK_USER_INPUT;\n }\n if (elementMatches(node, getPrivacySelector(NodePrivacyLevel.ALLOW))) {\n return NodePrivacyLevel.ALLOW;\n }\n if (shouldIgnoreElement(node)) {\n return NodePrivacyLevel.IGNORE;\n }\n}\n/**\n * Helper aiming to unify `mask` and `mask-user-input` privacy levels:\n *\n * In the `mask` case, it is trivial: we should mask the element.\n *\n * In the `mask-user-input` case, we should mask the element only if it is a \"form\" element or the\n * direct parent is a form element for text nodes).\n *\n * Other `shouldMaskNode` cases are edge cases that should not matter too much (ex: should we mask a\n * node if it is ignored or hidden? it doesn't matter since it won't be serialized).\n */\nexport function shouldMaskNode(node, privacyLevel) {\n switch (privacyLevel) {\n case NodePrivacyLevel.MASK:\n case NodePrivacyLevel.HIDDEN:\n case NodePrivacyLevel.IGNORE:\n return true;\n case NodePrivacyLevel.MASK_USER_INPUT:\n return isTextNode(node) ? isFormElement(node.parentNode) : isFormElement(node);\n default:\n return false;\n }\n}\nfunction isFormElement(node) {\n if (!node || node.nodeType !== node.ELEMENT_NODE) {\n return false;\n }\n var element = node;\n if (element.tagName === 'INPUT') {\n switch (element.type) {\n case 'button':\n case 'color':\n case 'reset':\n case 'submit':\n return false;\n }\n }\n return !!FORM_PRIVATE_TAG_NAMES[element.tagName];\n}\n/**\n * Text censoring non-destructively maintains whitespace characters in order to preserve text shape\n * during replay.\n */\nexport var censorText = function (text) { return text.replace(/\\S/g, TEXT_MASKING_CHAR); };\nexport function getTextContent(textNode, ignoreWhiteSpace, parentNodePrivacyLevel) {\n var _a;\n // The parent node may not be a html element which has a tagName attribute.\n // So just let it be undefined which is ok in this use case.\n var parentTagName = (_a = textNode.parentElement) === null || _a === void 0 ? void 0 : _a.tagName;\n var textContent = textNode.textContent || '';\n if (ignoreWhiteSpace && !textContent.trim()) {\n return;\n }\n var nodePrivacyLevel = parentNodePrivacyLevel;\n var isScript = parentTagName === 'SCRIPT';\n if (isScript) {\n // For perf reasons, we don't record script (heuristic)\n textContent = CENSORED_STRING_MARK;\n }\n else if (nodePrivacyLevel === NodePrivacyLevel.HIDDEN) {\n // Should never occur, but just in case, we set to CENSORED_MARK.\n textContent = CENSORED_STRING_MARK;\n }\n else if (shouldMaskNode(textNode, nodePrivacyLevel)) {\n if (\n // Scrambling the child list breaks text nodes for DATALIST/SELECT/OPTGROUP\n parentTagName === 'DATALIST' ||\n parentTagName === 'SELECT' ||\n parentTagName === 'OPTGROUP') {\n if (!textContent.trim()) {\n return;\n }\n }\n else if (parentTagName === 'OPTION') {\n //