{"version":3,"sources":["node_modules/hammerjs/hammer.js","node_modules/@angular/router/fesm2022/router-LSBBtrLI.mjs","node_modules/@angular/router/fesm2022/router_module-C0FJ-J6L.mjs","node_modules/@angular/animations/fesm2022/private_export-DBN_2NMM.mjs","node_modules/@angular/animations/fesm2022/util-DIamNgWY.mjs","node_modules/@angular/animations/fesm2022/browser.mjs","node_modules/@angular/platform-browser/fesm2022/animations.mjs","src/main.ts","node_modules/@nevware21/ts-utils/dist/es5/mod/ts-utils.js","node_modules/@microsoft/dynamicproto-js/dist-es5/DynamicProto.js","node_modules/@microsoft/applicationinsights-shims/dist-es5/Constants.js","node_modules/@microsoft/applicationinsights-shims/dist-es5/TsLibShims.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK.Enums/EnumHelperFuncs.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK.Enums/InitActiveStatusEnum.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/__DynamicConstants.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/AggregationError.js","node_modules/@nevware21/ts-async/dist/es5/mod/ts-async.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/InternalConstants.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/HelperFuncs.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/EnvUtils.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/RandomHelper.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/DataCacheHelper.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/Config/ConfigDefaults.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/Config/DynamicSupport.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/Config/DynamicProperty.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/Config/DynamicState.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/Config/DynamicConfig.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/AsyncUtils.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/Constants.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/Config/ConfigDefaultHelpers.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/DbgExtensionUtils.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/DiagnosticLogger.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/CookieMgr.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/NotificationManager.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/PerfManager.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/CoreUtils.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/W3cTraceParent.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/TelemetryHelpers.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/ProcessTelemetryContext.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/UnloadHandlerContainer.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/UnloadHookContainer.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/BaseTelemetryPlugin.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/TelemetryInitializerPlugin.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/AppInsightsCore.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/ResponseHelpers.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/SenderPostManager.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/EventHelpers.js","node_modules/@microsoft/applicationinsights-core-js/dist-es5/JavaScriptSDK/InstrumentHooks.js","node_modules/@microsoft/applicationinsights-common/dist-es5/Constants.js","node_modules/@microsoft/applicationinsights-common/dist-es5/RequestResponseHeaders.js","node_modules/@microsoft/applicationinsights-common/dist-es5/__DynamicConstants.js","node_modules/@microsoft/applicationinsights-common/dist-es5/Telemetry/Common/DataSanitizer.js","node_modules/@microsoft/applicationinsights-common/dist-es5/UrlHelperFuncs.js","node_modules/@microsoft/applicationinsights-common/dist-es5/Util.js","node_modules/@microsoft/applicationinsights-common/dist-es5/Enums.js","node_modules/@microsoft/applicationinsights-common/dist-es5/StorageHelperFuncs.js","node_modules/@microsoft/applicationinsights-common/dist-es5/ThrottleMgr.js","node_modules/@microsoft/applicationinsights-common/dist-es5/ConnectionStringParser.js","node_modules/@microsoft/applicationinsights-common/dist-es5/Telemetry/Common/Envelope.js","node_modules/@microsoft/applicationinsights-common/dist-es5/Telemetry/Event.js","node_modules/@microsoft/applicationinsights-common/dist-es5/Telemetry/Exception.js","node_modules/@microsoft/applicationinsights-common/dist-es5/Telemetry/Common/DataPoint.js","node_modules/@microsoft/applicationinsights-common/dist-es5/Telemetry/Metric.js","node_modules/@microsoft/applicationinsights-common/dist-es5/HelperFuncs.js","node_modules/@microsoft/applicationinsights-common/dist-es5/Telemetry/PageView.js","node_modules/@microsoft/applicationinsights-common/dist-es5/Telemetry/RemoteDependencyData.js","node_modules/@microsoft/applicationinsights-common/dist-es5/Telemetry/Trace.js","node_modules/@microsoft/applicationinsights-common/dist-es5/Telemetry/PageViewPerformance.js","node_modules/@microsoft/applicationinsights-common/dist-es5/Telemetry/Common/Data.js","node_modules/@microsoft/applicationinsights-common/dist-es5/Interfaces/Contracts/ContextTagKeys.js","node_modules/@microsoft/applicationinsights-common/dist-es5/TelemetryItemCreator.js","node_modules/@microsoft/applicationinsights-common/dist-es5/Interfaces/PartAExtensions.js","node_modules/@microsoft/applicationinsights-common/dist-es5/DomHelperFuncs.js","node_modules/@microsoft/applicationinsights-common/dist-es5/Offline.js","node_modules/@microsoft/applicationinsights-common/dist-es5/applicationinsights-common.js","node_modules/@microsoft/applicationinsights-analytics-js/dist-es5/__DynamicConstants.js","node_modules/@microsoft/applicationinsights-analytics-js/dist-es5/JavaScriptSDK/Telemetry/PageViewManager.js","node_modules/@microsoft/applicationinsights-analytics-js/dist-es5/JavaScriptSDK/Telemetry/PageViewPerformanceManager.js","node_modules/@microsoft/applicationinsights-analytics-js/dist-es5/JavaScriptSDK/Telemetry/PageVisitTimeManager.js","node_modules/@microsoft/applicationinsights-analytics-js/dist-es5/JavaScriptSDK/Timing.js","node_modules/@microsoft/applicationinsights-analytics-js/dist-es5/JavaScriptSDK/AnalyticsPlugin.js","node_modules/@microsoft/applicationinsights-cfgsync-js/dist-es5/__DynamicConstants.js","node_modules/@microsoft/applicationinsights-cfgsync-js/dist-es5/CfgSyncHelperFuncs.js","node_modules/@microsoft/applicationinsights-cfgsync-js/dist-es5/CfgSyncPlugin.js","node_modules/@microsoft/applicationinsights-channel-js/dist-es5/InternalConstants.js","node_modules/@microsoft/applicationinsights-channel-js/dist-es5/__DynamicConstants.js","node_modules/@microsoft/applicationinsights-channel-js/dist-es5/EnvelopeCreator.js","node_modules/@microsoft/applicationinsights-channel-js/dist-es5/SendBuffer.js","node_modules/@microsoft/applicationinsights-channel-js/dist-es5/Serializer.js","node_modules/@microsoft/applicationinsights-channel-js/dist-es5/TelemetryProcessors/SamplingScoreGenerators/HashCodeScoreGenerator.js","node_modules/@microsoft/applicationinsights-channel-js/dist-es5/TelemetryProcessors/SamplingScoreGenerators/SamplingScoreGenerator.js","node_modules/@microsoft/applicationinsights-channel-js/dist-es5/TelemetryProcessors/Sample.js","node_modules/@microsoft/applicationinsights-channel-js/dist-es5/Sender.js","node_modules/@microsoft/applicationinsights-dependencies-js/dist-es5/InternalConstants.js","node_modules/@microsoft/applicationinsights-dependencies-js/dist-es5/__DynamicConstants.js","node_modules/@microsoft/applicationinsights-dependencies-js/dist-es5/ajaxRecord.js","node_modules/@microsoft/applicationinsights-dependencies-js/dist-es5/ajax.js","node_modules/@microsoft/applicationinsights-properties-js/dist-es5/Context/Application.js","node_modules/@microsoft/applicationinsights-properties-js/dist-es5/Context/Device.js","node_modules/@microsoft/applicationinsights-properties-js/dist-es5/Context/Internal.js","node_modules/@microsoft/applicationinsights-properties-js/dist-es5/Context/Location.js","node_modules/@microsoft/applicationinsights-properties-js/dist-es5/__DynamicConstants.js","node_modules/@microsoft/applicationinsights-properties-js/dist-es5/Context/Session.js","node_modules/@microsoft/applicationinsights-properties-js/dist-es5/Context/TelemetryTrace.js","node_modules/@microsoft/applicationinsights-properties-js/dist-es5/Context/User.js","node_modules/@microsoft/applicationinsights-properties-js/dist-es5/TelemetryContext.js","node_modules/@microsoft/applicationinsights-properties-js/dist-es5/PropertiesPlugin.js","node_modules/@microsoft/applicationinsights-web/dist-es5/InternalConstants.js","node_modules/@microsoft/applicationinsights-web/dist-es5/__DynamicConstants.js","node_modules/@microsoft/applicationinsights-web/dist-es5/AISku.js","src/app/core/services/logging.service.ts","src/app/app.component.ts","src/app/app.component.html","node_modules/perfect-scrollbar/dist/perfect-scrollbar.esm.js","src/app/components/footer/footer.component.ts","src/app/components/footer/footer.component.html","src/app/components/sidebar/sidebar.component.ts","src/app/components/sidebar/sidebar.component.html","src/app/components/navbar/navbar.component.ts","src/app/components/navbar/navbar.component.html","src/app/layouts/admin-layout/admin-layout.component.ts","src/app/layouts/admin-layout/admin-layout.component.html","src/app/app-routes.ts","src/app/core/services/error-handler.service.ts","node_modules/@fortawesome/free-solid-svg-icons/index.mjs","node_modules/@fortawesome/free-brands-svg-icons/index.mjs","src/app/shared/shared.module.ts"],"sourcesContent":["/*! Hammer.JS - v2.0.7 - 2016-04-22\n * http://hammerjs.github.io/\n *\n * Copyright (c) 2016 Jorik Tangelder;\n * Licensed under the MIT license */\n(function (window, document, exportName, undefined) {\n 'use strict';\n\n var VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'];\n var TEST_ELEMENT = document.createElement('div');\n var TYPE_FUNCTION = 'function';\n var round = Math.round;\n var abs = Math.abs;\n var now = Date.now;\n\n /**\n * set a timeout with a given scope\n * @param {Function} fn\n * @param {Number} timeout\n * @param {Object} context\n * @returns {number}\n */\n function setTimeoutContext(fn, timeout, context) {\n return setTimeout(bindFn(fn, context), timeout);\n }\n\n /**\n * if the argument is an array, we want to execute the fn on each entry\n * if it aint an array we don't want to do a thing.\n * this is used by all the methods that accept a single and array argument.\n * @param {*|Array} arg\n * @param {String} fn\n * @param {Object} [context]\n * @returns {Boolean}\n */\n function invokeArrayArg(arg, fn, context) {\n if (Array.isArray(arg)) {\n each(arg, context[fn], context);\n return true;\n }\n return false;\n }\n\n /**\n * walk objects and arrays\n * @param {Object} obj\n * @param {Function} iterator\n * @param {Object} context\n */\n function each(obj, iterator, context) {\n var i;\n if (!obj) {\n return;\n }\n if (obj.forEach) {\n obj.forEach(iterator, context);\n } else if (obj.length !== undefined) {\n i = 0;\n while (i < obj.length) {\n iterator.call(context, obj[i], i, obj);\n i++;\n }\n } else {\n for (i in obj) {\n obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);\n }\n }\n }\n\n /**\n * wrap a method with a deprecation warning and stack trace\n * @param {Function} method\n * @param {String} name\n * @param {String} message\n * @returns {Function} A new function wrapping the supplied method.\n */\n function deprecate(method, name, message) {\n var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\\n' + message + ' AT \\n';\n return function () {\n var e = new Error('get-stack-trace');\n var stack = e && e.stack ? e.stack.replace(/^[^\\(]+?[\\n$]/gm, '').replace(/^\\s+at\\s+/gm, '').replace(/^Object.\\s*\\(/gm, '{anonymous}()@') : 'Unknown Stack Trace';\n var log = window.console && (window.console.warn || window.console.log);\n if (log) {\n log.call(window.console, deprecationMessage, stack);\n }\n return method.apply(this, arguments);\n };\n }\n\n /**\n * extend object.\n * means that properties in dest will be overwritten by the ones in src.\n * @param {Object} target\n * @param {...Object} objects_to_assign\n * @returns {Object} target\n */\n var assign;\n if (typeof Object.assign !== 'function') {\n assign = function assign(target) {\n if (target === undefined || target === null) {\n throw new TypeError('Cannot convert undefined or null to object');\n }\n var output = Object(target);\n for (var index = 1; index < arguments.length; index++) {\n var source = arguments[index];\n if (source !== undefined && source !== null) {\n for (var nextKey in source) {\n if (source.hasOwnProperty(nextKey)) {\n output[nextKey] = source[nextKey];\n }\n }\n }\n }\n return output;\n };\n } else {\n assign = Object.assign;\n }\n\n /**\n * extend object.\n * means that properties in dest will be overwritten by the ones in src.\n * @param {Object} dest\n * @param {Object} src\n * @param {Boolean} [merge=false]\n * @returns {Object} dest\n */\n var extend = deprecate(function extend(dest, src, merge) {\n var keys = Object.keys(src);\n var i = 0;\n while (i < keys.length) {\n if (!merge || merge && dest[keys[i]] === undefined) {\n dest[keys[i]] = src[keys[i]];\n }\n i++;\n }\n return dest;\n }, 'extend', 'Use `assign`.');\n\n /**\n * merge the values from src in the dest.\n * means that properties that exist in dest will not be overwritten by src\n * @param {Object} dest\n * @param {Object} src\n * @returns {Object} dest\n */\n var merge = deprecate(function merge(dest, src) {\n return extend(dest, src, true);\n }, 'merge', 'Use `assign`.');\n\n /**\n * simple class inheritance\n * @param {Function} child\n * @param {Function} base\n * @param {Object} [properties]\n */\n function inherit(child, base, properties) {\n var baseP = base.prototype,\n childP;\n childP = child.prototype = Object.create(baseP);\n childP.constructor = child;\n childP._super = baseP;\n if (properties) {\n assign(childP, properties);\n }\n }\n\n /**\n * simple function bind\n * @param {Function} fn\n * @param {Object} context\n * @returns {Function}\n */\n function bindFn(fn, context) {\n return function boundFn() {\n return fn.apply(context, arguments);\n };\n }\n\n /**\n * let a boolean value also be a function that must return a boolean\n * this first item in args will be used as the context\n * @param {Boolean|Function} val\n * @param {Array} [args]\n * @returns {Boolean}\n */\n function boolOrFn(val, args) {\n if (typeof val == TYPE_FUNCTION) {\n return val.apply(args ? args[0] || undefined : undefined, args);\n }\n return val;\n }\n\n /**\n * use the val2 when val1 is undefined\n * @param {*} val1\n * @param {*} val2\n * @returns {*}\n */\n function ifUndefined(val1, val2) {\n return val1 === undefined ? val2 : val1;\n }\n\n /**\n * addEventListener with multiple events at once\n * @param {EventTarget} target\n * @param {String} types\n * @param {Function} handler\n */\n function addEventListeners(target, types, handler) {\n each(splitStr(types), function (type) {\n target.addEventListener(type, handler, false);\n });\n }\n\n /**\n * removeEventListener with multiple events at once\n * @param {EventTarget} target\n * @param {String} types\n * @param {Function} handler\n */\n function removeEventListeners(target, types, handler) {\n each(splitStr(types), function (type) {\n target.removeEventListener(type, handler, false);\n });\n }\n\n /**\n * find if a node is in the given parent\n * @method hasParent\n * @param {HTMLElement} node\n * @param {HTMLElement} parent\n * @return {Boolean} found\n */\n function hasParent(node, parent) {\n while (node) {\n if (node == parent) {\n return true;\n }\n node = node.parentNode;\n }\n return false;\n }\n\n /**\n * small indexOf wrapper\n * @param {String} str\n * @param {String} find\n * @returns {Boolean} found\n */\n function inStr(str, find) {\n return str.indexOf(find) > -1;\n }\n\n /**\n * split string on whitespace\n * @param {String} str\n * @returns {Array} words\n */\n function splitStr(str) {\n return str.trim().split(/\\s+/g);\n }\n\n /**\n * find if a array contains the object using indexOf or a simple polyFill\n * @param {Array} src\n * @param {String} find\n * @param {String} [findByKey]\n * @return {Boolean|Number} false when not found, or the index\n */\n function inArray(src, find, findByKey) {\n if (src.indexOf && !findByKey) {\n return src.indexOf(find);\n } else {\n var i = 0;\n while (i < src.length) {\n if (findByKey && src[i][findByKey] == find || !findByKey && src[i] === find) {\n return i;\n }\n i++;\n }\n return -1;\n }\n }\n\n /**\n * convert array-like objects to real arrays\n * @param {Object} obj\n * @returns {Array}\n */\n function toArray(obj) {\n return Array.prototype.slice.call(obj, 0);\n }\n\n /**\n * unique array with objects based on a key (like 'id') or just by the array's value\n * @param {Array} src [{id:1},{id:2},{id:1}]\n * @param {String} [key]\n * @param {Boolean} [sort=False]\n * @returns {Array} [{id:1},{id:2}]\n */\n function uniqueArray(src, key, sort) {\n var results = [];\n var values = [];\n var i = 0;\n while (i < src.length) {\n var val = key ? src[i][key] : src[i];\n if (inArray(values, val) < 0) {\n results.push(src[i]);\n }\n values[i] = val;\n i++;\n }\n if (sort) {\n if (!key) {\n results = results.sort();\n } else {\n results = results.sort(function sortUniqueArray(a, b) {\n return a[key] > b[key];\n });\n }\n }\n return results;\n }\n\n /**\n * get the prefixed property\n * @param {Object} obj\n * @param {String} property\n * @returns {String|Undefined} prefixed\n */\n function prefixed(obj, property) {\n var prefix, prop;\n var camelProp = property[0].toUpperCase() + property.slice(1);\n var i = 0;\n while (i < VENDOR_PREFIXES.length) {\n prefix = VENDOR_PREFIXES[i];\n prop = prefix ? prefix + camelProp : property;\n if (prop in obj) {\n return prop;\n }\n i++;\n }\n return undefined;\n }\n\n /**\n * get a unique id\n * @returns {number} uniqueId\n */\n var _uniqueId = 1;\n function uniqueId() {\n return _uniqueId++;\n }\n\n /**\n * get the window object of an element\n * @param {HTMLElement} element\n * @returns {DocumentView|Window}\n */\n function getWindowForElement(element) {\n var doc = element.ownerDocument || element;\n return doc.defaultView || doc.parentWindow || window;\n }\n var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;\n var SUPPORT_TOUCH = 'ontouchstart' in window;\n var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined;\n var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent);\n var INPUT_TYPE_TOUCH = 'touch';\n var INPUT_TYPE_PEN = 'pen';\n var INPUT_TYPE_MOUSE = 'mouse';\n var INPUT_TYPE_KINECT = 'kinect';\n var COMPUTE_INTERVAL = 25;\n var INPUT_START = 1;\n var INPUT_MOVE = 2;\n var INPUT_END = 4;\n var INPUT_CANCEL = 8;\n var DIRECTION_NONE = 1;\n var DIRECTION_LEFT = 2;\n var DIRECTION_RIGHT = 4;\n var DIRECTION_UP = 8;\n var DIRECTION_DOWN = 16;\n var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;\n var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;\n var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;\n var PROPS_XY = ['x', 'y'];\n var PROPS_CLIENT_XY = ['clientX', 'clientY'];\n\n /**\n * create new input type manager\n * @param {Manager} manager\n * @param {Function} callback\n * @returns {Input}\n * @constructor\n */\n function Input(manager, callback) {\n var self = this;\n this.manager = manager;\n this.callback = callback;\n this.element = manager.element;\n this.target = manager.options.inputTarget;\n\n // smaller wrapper around the handler, for the scope and the enabled state of the manager,\n // so when disabled the input events are completely bypassed.\n this.domHandler = function (ev) {\n if (boolOrFn(manager.options.enable, [manager])) {\n self.handler(ev);\n }\n };\n this.init();\n }\n Input.prototype = {\n /**\n * should handle the inputEvent data and trigger the callback\n * @virtual\n */\n handler: function () {},\n /**\n * bind the events\n */\n init: function () {\n this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);\n this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler);\n this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);\n },\n /**\n * unbind the events\n */\n destroy: function () {\n this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler);\n this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler);\n this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);\n }\n };\n\n /**\n * create new input type manager\n * called by the Manager constructor\n * @param {Hammer} manager\n * @returns {Input}\n */\n function createInputInstance(manager) {\n var Type;\n var inputClass = manager.options.inputClass;\n if (inputClass) {\n Type = inputClass;\n } else if (SUPPORT_POINTER_EVENTS) {\n Type = PointerEventInput;\n } else if (SUPPORT_ONLY_TOUCH) {\n Type = TouchInput;\n } else if (!SUPPORT_TOUCH) {\n Type = MouseInput;\n } else {\n Type = TouchMouseInput;\n }\n return new Type(manager, inputHandler);\n }\n\n /**\n * handle input events\n * @param {Manager} manager\n * @param {String} eventType\n * @param {Object} input\n */\n function inputHandler(manager, eventType, input) {\n var pointersLen = input.pointers.length;\n var changedPointersLen = input.changedPointers.length;\n var isFirst = eventType & INPUT_START && pointersLen - changedPointersLen === 0;\n var isFinal = eventType & (INPUT_END | INPUT_CANCEL) && pointersLen - changedPointersLen === 0;\n input.isFirst = !!isFirst;\n input.isFinal = !!isFinal;\n if (isFirst) {\n manager.session = {};\n }\n\n // source event is the normalized value of the domEvents\n // like 'touchstart, mouseup, pointerdown'\n input.eventType = eventType;\n\n // compute scale, rotation etc\n computeInputData(manager, input);\n\n // emit secret event\n manager.emit('hammer.input', input);\n manager.recognize(input);\n manager.session.prevInput = input;\n }\n\n /**\n * extend the data with some usable properties like scale, rotate, velocity etc\n * @param {Object} manager\n * @param {Object} input\n */\n function computeInputData(manager, input) {\n var session = manager.session;\n var pointers = input.pointers;\n var pointersLength = pointers.length;\n\n // store the first input to calculate the distance and direction\n if (!session.firstInput) {\n session.firstInput = simpleCloneInputData(input);\n }\n\n // to compute scale and rotation we need to store the multiple touches\n if (pointersLength > 1 && !session.firstMultiple) {\n session.firstMultiple = simpleCloneInputData(input);\n } else if (pointersLength === 1) {\n session.firstMultiple = false;\n }\n var firstInput = session.firstInput;\n var firstMultiple = session.firstMultiple;\n var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;\n var center = input.center = getCenter(pointers);\n input.timeStamp = now();\n input.deltaTime = input.timeStamp - firstInput.timeStamp;\n input.angle = getAngle(offsetCenter, center);\n input.distance = getDistance(offsetCenter, center);\n computeDeltaXY(session, input);\n input.offsetDirection = getDirection(input.deltaX, input.deltaY);\n var overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY);\n input.overallVelocityX = overallVelocity.x;\n input.overallVelocityY = overallVelocity.y;\n input.overallVelocity = abs(overallVelocity.x) > abs(overallVelocity.y) ? overallVelocity.x : overallVelocity.y;\n input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;\n input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;\n input.maxPointers = !session.prevInput ? input.pointers.length : input.pointers.length > session.prevInput.maxPointers ? input.pointers.length : session.prevInput.maxPointers;\n computeIntervalInputData(session, input);\n\n // find the correct target\n var target = manager.element;\n if (hasParent(input.srcEvent.target, target)) {\n target = input.srcEvent.target;\n }\n input.target = target;\n }\n function computeDeltaXY(session, input) {\n var center = input.center;\n var offset = session.offsetDelta || {};\n var prevDelta = session.prevDelta || {};\n var prevInput = session.prevInput || {};\n if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) {\n prevDelta = session.prevDelta = {\n x: prevInput.deltaX || 0,\n y: prevInput.deltaY || 0\n };\n offset = session.offsetDelta = {\n x: center.x,\n y: center.y\n };\n }\n input.deltaX = prevDelta.x + (center.x - offset.x);\n input.deltaY = prevDelta.y + (center.y - offset.y);\n }\n\n /**\n * velocity is calculated every x ms\n * @param {Object} session\n * @param {Object} input\n */\n function computeIntervalInputData(session, input) {\n var last = session.lastInterval || input,\n deltaTime = input.timeStamp - last.timeStamp,\n velocity,\n velocityX,\n velocityY,\n direction;\n if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {\n var deltaX = input.deltaX - last.deltaX;\n var deltaY = input.deltaY - last.deltaY;\n var v = getVelocity(deltaTime, deltaX, deltaY);\n velocityX = v.x;\n velocityY = v.y;\n velocity = abs(v.x) > abs(v.y) ? v.x : v.y;\n direction = getDirection(deltaX, deltaY);\n session.lastInterval = input;\n } else {\n // use latest velocity info if it doesn't overtake a minimum period\n velocity = last.velocity;\n velocityX = last.velocityX;\n velocityY = last.velocityY;\n direction = last.direction;\n }\n input.velocity = velocity;\n input.velocityX = velocityX;\n input.velocityY = velocityY;\n input.direction = direction;\n }\n\n /**\n * create a simple clone from the input used for storage of firstInput and firstMultiple\n * @param {Object} input\n * @returns {Object} clonedInputData\n */\n function simpleCloneInputData(input) {\n // make a simple copy of the pointers because we will get a reference if we don't\n // we only need clientXY for the calculations\n var pointers = [];\n var i = 0;\n while (i < input.pointers.length) {\n pointers[i] = {\n clientX: round(input.pointers[i].clientX),\n clientY: round(input.pointers[i].clientY)\n };\n i++;\n }\n return {\n timeStamp: now(),\n pointers: pointers,\n center: getCenter(pointers),\n deltaX: input.deltaX,\n deltaY: input.deltaY\n };\n }\n\n /**\n * get the center of all the pointers\n * @param {Array} pointers\n * @return {Object} center contains `x` and `y` properties\n */\n function getCenter(pointers) {\n var pointersLength = pointers.length;\n\n // no need to loop when only one touch\n if (pointersLength === 1) {\n return {\n x: round(pointers[0].clientX),\n y: round(pointers[0].clientY)\n };\n }\n var x = 0,\n y = 0,\n i = 0;\n while (i < pointersLength) {\n x += pointers[i].clientX;\n y += pointers[i].clientY;\n i++;\n }\n return {\n x: round(x / pointersLength),\n y: round(y / pointersLength)\n };\n }\n\n /**\n * calculate the velocity between two points. unit is in px per ms.\n * @param {Number} deltaTime\n * @param {Number} x\n * @param {Number} y\n * @return {Object} velocity `x` and `y`\n */\n function getVelocity(deltaTime, x, y) {\n return {\n x: x / deltaTime || 0,\n y: y / deltaTime || 0\n };\n }\n\n /**\n * get the direction between two points\n * @param {Number} x\n * @param {Number} y\n * @return {Number} direction\n */\n function getDirection(x, y) {\n if (x === y) {\n return DIRECTION_NONE;\n }\n if (abs(x) >= abs(y)) {\n return x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;\n }\n return y < 0 ? DIRECTION_UP : DIRECTION_DOWN;\n }\n\n /**\n * calculate the absolute distance between two points\n * @param {Object} p1 {x, y}\n * @param {Object} p2 {x, y}\n * @param {Array} [props] containing x and y keys\n * @return {Number} distance\n */\n function getDistance(p1, p2, props) {\n if (!props) {\n props = PROPS_XY;\n }\n var x = p2[props[0]] - p1[props[0]],\n y = p2[props[1]] - p1[props[1]];\n return Math.sqrt(x * x + y * y);\n }\n\n /**\n * calculate the angle between two coordinates\n * @param {Object} p1\n * @param {Object} p2\n * @param {Array} [props] containing x and y keys\n * @return {Number} angle\n */\n function getAngle(p1, p2, props) {\n if (!props) {\n props = PROPS_XY;\n }\n var x = p2[props[0]] - p1[props[0]],\n y = p2[props[1]] - p1[props[1]];\n return Math.atan2(y, x) * 180 / Math.PI;\n }\n\n /**\n * calculate the rotation degrees between two pointersets\n * @param {Array} start array of pointers\n * @param {Array} end array of pointers\n * @return {Number} rotation\n */\n function getRotation(start, end) {\n return getAngle(end[1], end[0], PROPS_CLIENT_XY) + getAngle(start[1], start[0], PROPS_CLIENT_XY);\n }\n\n /**\n * calculate the scale factor between two pointersets\n * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out\n * @param {Array} start array of pointers\n * @param {Array} end array of pointers\n * @return {Number} scale\n */\n function getScale(start, end) {\n return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);\n }\n var MOUSE_INPUT_MAP = {\n mousedown: INPUT_START,\n mousemove: INPUT_MOVE,\n mouseup: INPUT_END\n };\n var MOUSE_ELEMENT_EVENTS = 'mousedown';\n var MOUSE_WINDOW_EVENTS = 'mousemove mouseup';\n\n /**\n * Mouse events input\n * @constructor\n * @extends Input\n */\n function MouseInput() {\n this.evEl = MOUSE_ELEMENT_EVENTS;\n this.evWin = MOUSE_WINDOW_EVENTS;\n this.pressed = false; // mousedown state\n\n Input.apply(this, arguments);\n }\n inherit(MouseInput, Input, {\n /**\n * handle mouse events\n * @param {Object} ev\n */\n handler: function MEhandler(ev) {\n var eventType = MOUSE_INPUT_MAP[ev.type];\n\n // on start we want to have the left mouse button down\n if (eventType & INPUT_START && ev.button === 0) {\n this.pressed = true;\n }\n if (eventType & INPUT_MOVE && ev.which !== 1) {\n eventType = INPUT_END;\n }\n\n // mouse must be down\n if (!this.pressed) {\n return;\n }\n if (eventType & INPUT_END) {\n this.pressed = false;\n }\n this.callback(this.manager, eventType, {\n pointers: [ev],\n changedPointers: [ev],\n pointerType: INPUT_TYPE_MOUSE,\n srcEvent: ev\n });\n }\n });\n var POINTER_INPUT_MAP = {\n pointerdown: INPUT_START,\n pointermove: INPUT_MOVE,\n pointerup: INPUT_END,\n pointercancel: INPUT_CANCEL,\n pointerout: INPUT_CANCEL\n };\n\n // in IE10 the pointer types is defined as an enum\n var IE10_POINTER_TYPE_ENUM = {\n 2: INPUT_TYPE_TOUCH,\n 3: INPUT_TYPE_PEN,\n 4: INPUT_TYPE_MOUSE,\n 5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816\n };\n var POINTER_ELEMENT_EVENTS = 'pointerdown';\n var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel';\n\n // IE10 has prefixed support, and case-sensitive\n if (window.MSPointerEvent && !window.PointerEvent) {\n POINTER_ELEMENT_EVENTS = 'MSPointerDown';\n POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel';\n }\n\n /**\n * Pointer events input\n * @constructor\n * @extends Input\n */\n function PointerEventInput() {\n this.evEl = POINTER_ELEMENT_EVENTS;\n this.evWin = POINTER_WINDOW_EVENTS;\n Input.apply(this, arguments);\n this.store = this.manager.session.pointerEvents = [];\n }\n inherit(PointerEventInput, Input, {\n /**\n * handle mouse events\n * @param {Object} ev\n */\n handler: function PEhandler(ev) {\n var store = this.store;\n var removePointer = false;\n var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');\n var eventType = POINTER_INPUT_MAP[eventTypeNormalized];\n var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;\n var isTouch = pointerType == INPUT_TYPE_TOUCH;\n\n // get index of the event in the store\n var storeIndex = inArray(store, ev.pointerId, 'pointerId');\n\n // start and mouse must be down\n if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {\n if (storeIndex < 0) {\n store.push(ev);\n storeIndex = store.length - 1;\n }\n } else if (eventType & (INPUT_END | INPUT_CANCEL)) {\n removePointer = true;\n }\n\n // it not found, so the pointer hasn't been down (so it's probably a hover)\n if (storeIndex < 0) {\n return;\n }\n\n // update the event in the store\n store[storeIndex] = ev;\n this.callback(this.manager, eventType, {\n pointers: store,\n changedPointers: [ev],\n pointerType: pointerType,\n srcEvent: ev\n });\n if (removePointer) {\n // remove from the store\n store.splice(storeIndex, 1);\n }\n }\n });\n var SINGLE_TOUCH_INPUT_MAP = {\n touchstart: INPUT_START,\n touchmove: INPUT_MOVE,\n touchend: INPUT_END,\n touchcancel: INPUT_CANCEL\n };\n var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart';\n var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel';\n\n /**\n * Touch events input\n * @constructor\n * @extends Input\n */\n function SingleTouchInput() {\n this.evTarget = SINGLE_TOUCH_TARGET_EVENTS;\n this.evWin = SINGLE_TOUCH_WINDOW_EVENTS;\n this.started = false;\n Input.apply(this, arguments);\n }\n inherit(SingleTouchInput, Input, {\n handler: function TEhandler(ev) {\n var type = SINGLE_TOUCH_INPUT_MAP[ev.type];\n\n // should we handle the touch events?\n if (type === INPUT_START) {\n this.started = true;\n }\n if (!this.started) {\n return;\n }\n var touches = normalizeSingleTouches.call(this, ev, type);\n\n // when done, reset the started state\n if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) {\n this.started = false;\n }\n this.callback(this.manager, type, {\n pointers: touches[0],\n changedPointers: touches[1],\n pointerType: INPUT_TYPE_TOUCH,\n srcEvent: ev\n });\n }\n });\n\n /**\n * @this {TouchInput}\n * @param {Object} ev\n * @param {Number} type flag\n * @returns {undefined|Array} [all, changed]\n */\n function normalizeSingleTouches(ev, type) {\n var all = toArray(ev.touches);\n var changed = toArray(ev.changedTouches);\n if (type & (INPUT_END | INPUT_CANCEL)) {\n all = uniqueArray(all.concat(changed), 'identifier', true);\n }\n return [all, changed];\n }\n var TOUCH_INPUT_MAP = {\n touchstart: INPUT_START,\n touchmove: INPUT_MOVE,\n touchend: INPUT_END,\n touchcancel: INPUT_CANCEL\n };\n var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel';\n\n /**\n * Multi-user touch events input\n * @constructor\n * @extends Input\n */\n function TouchInput() {\n this.evTarget = TOUCH_TARGET_EVENTS;\n this.targetIds = {};\n Input.apply(this, arguments);\n }\n inherit(TouchInput, Input, {\n handler: function MTEhandler(ev) {\n var type = TOUCH_INPUT_MAP[ev.type];\n var touches = getTouches.call(this, ev, type);\n if (!touches) {\n return;\n }\n this.callback(this.manager, type, {\n pointers: touches[0],\n changedPointers: touches[1],\n pointerType: INPUT_TYPE_TOUCH,\n srcEvent: ev\n });\n }\n });\n\n /**\n * @this {TouchInput}\n * @param {Object} ev\n * @param {Number} type flag\n * @returns {undefined|Array} [all, changed]\n */\n function getTouches(ev, type) {\n var allTouches = toArray(ev.touches);\n var targetIds = this.targetIds;\n\n // when there is only one touch, the process can be simplified\n if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {\n targetIds[allTouches[0].identifier] = true;\n return [allTouches, allTouches];\n }\n var i,\n targetTouches,\n changedTouches = toArray(ev.changedTouches),\n changedTargetTouches = [],\n target = this.target;\n\n // get target touches from touches\n targetTouches = allTouches.filter(function (touch) {\n return hasParent(touch.target, target);\n });\n\n // collect touches\n if (type === INPUT_START) {\n i = 0;\n while (i < targetTouches.length) {\n targetIds[targetTouches[i].identifier] = true;\n i++;\n }\n }\n\n // filter changed touches to only contain touches that exist in the collected target ids\n i = 0;\n while (i < changedTouches.length) {\n if (targetIds[changedTouches[i].identifier]) {\n changedTargetTouches.push(changedTouches[i]);\n }\n\n // cleanup removed touches\n if (type & (INPUT_END | INPUT_CANCEL)) {\n delete targetIds[changedTouches[i].identifier];\n }\n i++;\n }\n if (!changedTargetTouches.length) {\n return;\n }\n return [\n // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'\n uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true), changedTargetTouches];\n }\n\n /**\n * Combined touch and mouse input\n *\n * Touch has a higher priority then mouse, and while touching no mouse events are allowed.\n * This because touch devices also emit mouse events while doing a touch.\n *\n * @constructor\n * @extends Input\n */\n\n var DEDUP_TIMEOUT = 2500;\n var DEDUP_DISTANCE = 25;\n function TouchMouseInput() {\n Input.apply(this, arguments);\n var handler = bindFn(this.handler, this);\n this.touch = new TouchInput(this.manager, handler);\n this.mouse = new MouseInput(this.manager, handler);\n this.primaryTouch = null;\n this.lastTouches = [];\n }\n inherit(TouchMouseInput, Input, {\n /**\n * handle mouse and touch events\n * @param {Hammer} manager\n * @param {String} inputEvent\n * @param {Object} inputData\n */\n handler: function TMEhandler(manager, inputEvent, inputData) {\n var isTouch = inputData.pointerType == INPUT_TYPE_TOUCH,\n isMouse = inputData.pointerType == INPUT_TYPE_MOUSE;\n if (isMouse && inputData.sourceCapabilities && inputData.sourceCapabilities.firesTouchEvents) {\n return;\n }\n\n // when we're in a touch event, record touches to de-dupe synthetic mouse event\n if (isTouch) {\n recordTouches.call(this, inputEvent, inputData);\n } else if (isMouse && isSyntheticEvent.call(this, inputData)) {\n return;\n }\n this.callback(manager, inputEvent, inputData);\n },\n /**\n * remove the event listeners\n */\n destroy: function destroy() {\n this.touch.destroy();\n this.mouse.destroy();\n }\n });\n function recordTouches(eventType, eventData) {\n if (eventType & INPUT_START) {\n this.primaryTouch = eventData.changedPointers[0].identifier;\n setLastTouch.call(this, eventData);\n } else if (eventType & (INPUT_END | INPUT_CANCEL)) {\n setLastTouch.call(this, eventData);\n }\n }\n function setLastTouch(eventData) {\n var touch = eventData.changedPointers[0];\n if (touch.identifier === this.primaryTouch) {\n var lastTouch = {\n x: touch.clientX,\n y: touch.clientY\n };\n this.lastTouches.push(lastTouch);\n var lts = this.lastTouches;\n var removeLastTouch = function () {\n var i = lts.indexOf(lastTouch);\n if (i > -1) {\n lts.splice(i, 1);\n }\n };\n setTimeout(removeLastTouch, DEDUP_TIMEOUT);\n }\n }\n function isSyntheticEvent(eventData) {\n var x = eventData.srcEvent.clientX,\n y = eventData.srcEvent.clientY;\n for (var i = 0; i < this.lastTouches.length; i++) {\n var t = this.lastTouches[i];\n var dx = Math.abs(x - t.x),\n dy = Math.abs(y - t.y);\n if (dx <= DEDUP_DISTANCE && dy <= DEDUP_DISTANCE) {\n return true;\n }\n }\n return false;\n }\n var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction');\n var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined;\n\n // magical touchAction value\n var TOUCH_ACTION_COMPUTE = 'compute';\n var TOUCH_ACTION_AUTO = 'auto';\n var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented\n var TOUCH_ACTION_NONE = 'none';\n var TOUCH_ACTION_PAN_X = 'pan-x';\n var TOUCH_ACTION_PAN_Y = 'pan-y';\n var TOUCH_ACTION_MAP = getTouchActionProps();\n\n /**\n * Touch Action\n * sets the touchAction property or uses the js alternative\n * @param {Manager} manager\n * @param {String} value\n * @constructor\n */\n function TouchAction(manager, value) {\n this.manager = manager;\n this.set(value);\n }\n TouchAction.prototype = {\n /**\n * set the touchAction value on the element or enable the polyfill\n * @param {String} value\n */\n set: function (value) {\n // find out the touch-action by the event handlers\n if (value == TOUCH_ACTION_COMPUTE) {\n value = this.compute();\n }\n if (NATIVE_TOUCH_ACTION && this.manager.element.style && TOUCH_ACTION_MAP[value]) {\n this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;\n }\n this.actions = value.toLowerCase().trim();\n },\n /**\n * just re-set the touchAction value\n */\n update: function () {\n this.set(this.manager.options.touchAction);\n },\n /**\n * compute the value for the touchAction property based on the recognizer's settings\n * @returns {String} value\n */\n compute: function () {\n var actions = [];\n each(this.manager.recognizers, function (recognizer) {\n if (boolOrFn(recognizer.options.enable, [recognizer])) {\n actions = actions.concat(recognizer.getTouchAction());\n }\n });\n return cleanTouchActions(actions.join(' '));\n },\n /**\n * this method is called on each input cycle and provides the preventing of the browser behavior\n * @param {Object} input\n */\n preventDefaults: function (input) {\n var srcEvent = input.srcEvent;\n var direction = input.offsetDirection;\n\n // if the touch action did prevented once this session\n if (this.manager.session.prevented) {\n srcEvent.preventDefault();\n return;\n }\n var actions = this.actions;\n var hasNone = inStr(actions, TOUCH_ACTION_NONE) && !TOUCH_ACTION_MAP[TOUCH_ACTION_NONE];\n var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_Y];\n var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_X];\n if (hasNone) {\n //do not prevent defaults if this is a tap gesture\n\n var isTapPointer = input.pointers.length === 1;\n var isTapMovement = input.distance < 2;\n var isTapTouchTime = input.deltaTime < 250;\n if (isTapPointer && isTapMovement && isTapTouchTime) {\n return;\n }\n }\n if (hasPanX && hasPanY) {\n // `pan-x pan-y` means browser handles all scrolling/panning, do not prevent\n return;\n }\n if (hasNone || hasPanY && direction & DIRECTION_HORIZONTAL || hasPanX && direction & DIRECTION_VERTICAL) {\n return this.preventSrc(srcEvent);\n }\n },\n /**\n * call preventDefault to prevent the browser's default behavior (scrolling in most cases)\n * @param {Object} srcEvent\n */\n preventSrc: function (srcEvent) {\n this.manager.session.prevented = true;\n srcEvent.preventDefault();\n }\n };\n\n /**\n * when the touchActions are collected they are not a valid value, so we need to clean things up. *\n * @param {String} actions\n * @returns {*}\n */\n function cleanTouchActions(actions) {\n // none\n if (inStr(actions, TOUCH_ACTION_NONE)) {\n return TOUCH_ACTION_NONE;\n }\n var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);\n var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);\n\n // if both pan-x and pan-y are set (different recognizers\n // for different directions, e.g. horizontal pan but vertical swipe?)\n // we need none (as otherwise with pan-x pan-y combined none of these\n // recognizers will work, since the browser would handle all panning\n if (hasPanX && hasPanY) {\n return TOUCH_ACTION_NONE;\n }\n\n // pan-x OR pan-y\n if (hasPanX || hasPanY) {\n return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;\n }\n\n // manipulation\n if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {\n return TOUCH_ACTION_MANIPULATION;\n }\n return TOUCH_ACTION_AUTO;\n }\n function getTouchActionProps() {\n if (!NATIVE_TOUCH_ACTION) {\n return false;\n }\n var touchMap = {};\n var cssSupports = window.CSS && window.CSS.supports;\n ['auto', 'manipulation', 'pan-y', 'pan-x', 'pan-x pan-y', 'none'].forEach(function (val) {\n // If css.supports is not supported but there is native touch-action assume it supports\n // all values. This is the case for IE 10 and 11.\n touchMap[val] = cssSupports ? window.CSS.supports('touch-action', val) : true;\n });\n return touchMap;\n }\n\n /**\n * Recognizer flow explained; *\n * All recognizers have the initial state of POSSIBLE when a input session starts.\n * The definition of a input session is from the first input until the last input, with all it's movement in it. *\n * Example session for mouse-input: mousedown -> mousemove -> mouseup\n *\n * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed\n * which determines with state it should be.\n *\n * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to\n * POSSIBLE to give it another change on the next cycle.\n *\n * Possible\n * |\n * +-----+---------------+\n * | |\n * +-----+-----+ |\n * | | |\n * Failed Cancelled |\n * +-------+------+\n * | |\n * Recognized Began\n * |\n * Changed\n * |\n * Ended/Recognized\n */\n var STATE_POSSIBLE = 1;\n var STATE_BEGAN = 2;\n var STATE_CHANGED = 4;\n var STATE_ENDED = 8;\n var STATE_RECOGNIZED = STATE_ENDED;\n var STATE_CANCELLED = 16;\n var STATE_FAILED = 32;\n\n /**\n * Recognizer\n * Every recognizer needs to extend from this class.\n * @constructor\n * @param {Object} options\n */\n function Recognizer(options) {\n this.options = assign({}, this.defaults, options || {});\n this.id = uniqueId();\n this.manager = null;\n\n // default is enable true\n this.options.enable = ifUndefined(this.options.enable, true);\n this.state = STATE_POSSIBLE;\n this.simultaneous = {};\n this.requireFail = [];\n }\n Recognizer.prototype = {\n /**\n * @virtual\n * @type {Object}\n */\n defaults: {},\n /**\n * set options\n * @param {Object} options\n * @return {Recognizer}\n */\n set: function (options) {\n assign(this.options, options);\n\n // also update the touchAction, in case something changed about the directions/enabled state\n this.manager && this.manager.touchAction.update();\n return this;\n },\n /**\n * recognize simultaneous with an other recognizer.\n * @param {Recognizer} otherRecognizer\n * @returns {Recognizer} this\n */\n recognizeWith: function (otherRecognizer) {\n if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {\n return this;\n }\n var simultaneous = this.simultaneous;\n otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);\n if (!simultaneous[otherRecognizer.id]) {\n simultaneous[otherRecognizer.id] = otherRecognizer;\n otherRecognizer.recognizeWith(this);\n }\n return this;\n },\n /**\n * drop the simultaneous link. it doesnt remove the link on the other recognizer.\n * @param {Recognizer} otherRecognizer\n * @returns {Recognizer} this\n */\n dropRecognizeWith: function (otherRecognizer) {\n if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) {\n return this;\n }\n otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);\n delete this.simultaneous[otherRecognizer.id];\n return this;\n },\n /**\n * recognizer can only run when an other is failing\n * @param {Recognizer} otherRecognizer\n * @returns {Recognizer} this\n */\n requireFailure: function (otherRecognizer) {\n if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) {\n return this;\n }\n var requireFail = this.requireFail;\n otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);\n if (inArray(requireFail, otherRecognizer) === -1) {\n requireFail.push(otherRecognizer);\n otherRecognizer.requireFailure(this);\n }\n return this;\n },\n /**\n * drop the requireFailure link. it does not remove the link on the other recognizer.\n * @param {Recognizer} otherRecognizer\n * @returns {Recognizer} this\n */\n dropRequireFailure: function (otherRecognizer) {\n if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) {\n return this;\n }\n otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);\n var index = inArray(this.requireFail, otherRecognizer);\n if (index > -1) {\n this.requireFail.splice(index, 1);\n }\n return this;\n },\n /**\n * has require failures boolean\n * @returns {boolean}\n */\n hasRequireFailures: function () {\n return this.requireFail.length > 0;\n },\n /**\n * if the recognizer can recognize simultaneous with an other recognizer\n * @param {Recognizer} otherRecognizer\n * @returns {Boolean}\n */\n canRecognizeWith: function (otherRecognizer) {\n return !!this.simultaneous[otherRecognizer.id];\n },\n /**\n * You should use `tryEmit` instead of `emit` directly to check\n * that all the needed recognizers has failed before emitting.\n * @param {Object} input\n */\n emit: function (input) {\n var self = this;\n var state = this.state;\n function emit(event) {\n self.manager.emit(event, input);\n }\n\n // 'panstart' and 'panmove'\n if (state < STATE_ENDED) {\n emit(self.options.event + stateStr(state));\n }\n emit(self.options.event); // simple 'eventName' events\n\n if (input.additionalEvent) {\n // additional event(panleft, panright, pinchin, pinchout...)\n emit(input.additionalEvent);\n }\n\n // panend and pancancel\n if (state >= STATE_ENDED) {\n emit(self.options.event + stateStr(state));\n }\n },\n /**\n * Check that all the require failure recognizers has failed,\n * if true, it emits a gesture event,\n * otherwise, setup the state to FAILED.\n * @param {Object} input\n */\n tryEmit: function (input) {\n if (this.canEmit()) {\n return this.emit(input);\n }\n // it's failing anyway\n this.state = STATE_FAILED;\n },\n /**\n * can we emit?\n * @returns {boolean}\n */\n canEmit: function () {\n var i = 0;\n while (i < this.requireFail.length) {\n if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {\n return false;\n }\n i++;\n }\n return true;\n },\n /**\n * update the recognizer\n * @param {Object} inputData\n */\n recognize: function (inputData) {\n // make a new copy of the inputData\n // so we can change the inputData without messing up the other recognizers\n var inputDataClone = assign({}, inputData);\n\n // is is enabled and allow recognizing?\n if (!boolOrFn(this.options.enable, [this, inputDataClone])) {\n this.reset();\n this.state = STATE_FAILED;\n return;\n }\n\n // reset when we've reached the end\n if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {\n this.state = STATE_POSSIBLE;\n }\n this.state = this.process(inputDataClone);\n\n // the recognizer has recognized a gesture\n // so trigger an event\n if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {\n this.tryEmit(inputDataClone);\n }\n },\n /**\n * return the state of the recognizer\n * the actual recognizing happens in this method\n * @virtual\n * @param {Object} inputData\n * @returns {Const} STATE\n */\n process: function (inputData) {},\n // jshint ignore:line\n\n /**\n * return the preferred touch-action\n * @virtual\n * @returns {Array}\n */\n getTouchAction: function () {},\n /**\n * called when the gesture isn't allowed to recognize\n * like when another is being recognized or it is disabled\n * @virtual\n */\n reset: function () {}\n };\n\n /**\n * get a usable string, used as event postfix\n * @param {Const} state\n * @returns {String} state\n */\n function stateStr(state) {\n if (state & STATE_CANCELLED) {\n return 'cancel';\n } else if (state & STATE_ENDED) {\n return 'end';\n } else if (state & STATE_CHANGED) {\n return 'move';\n } else if (state & STATE_BEGAN) {\n return 'start';\n }\n return '';\n }\n\n /**\n * direction cons to string\n * @param {Const} direction\n * @returns {String}\n */\n function directionStr(direction) {\n if (direction == DIRECTION_DOWN) {\n return 'down';\n } else if (direction == DIRECTION_UP) {\n return 'up';\n } else if (direction == DIRECTION_LEFT) {\n return 'left';\n } else if (direction == DIRECTION_RIGHT) {\n return 'right';\n }\n return '';\n }\n\n /**\n * get a recognizer by name if it is bound to a manager\n * @param {Recognizer|String} otherRecognizer\n * @param {Recognizer} recognizer\n * @returns {Recognizer}\n */\n function getRecognizerByNameIfManager(otherRecognizer, recognizer) {\n var manager = recognizer.manager;\n if (manager) {\n return manager.get(otherRecognizer);\n }\n return otherRecognizer;\n }\n\n /**\n * This recognizer is just used as a base for the simple attribute recognizers.\n * @constructor\n * @extends Recognizer\n */\n function AttrRecognizer() {\n Recognizer.apply(this, arguments);\n }\n inherit(AttrRecognizer, Recognizer, {\n /**\n * @namespace\n * @memberof AttrRecognizer\n */\n defaults: {\n /**\n * @type {Number}\n * @default 1\n */\n pointers: 1\n },\n /**\n * Used to check if it the recognizer receives valid input, like input.distance > 10.\n * @memberof AttrRecognizer\n * @param {Object} input\n * @returns {Boolean} recognized\n */\n attrTest: function (input) {\n var optionPointers = this.options.pointers;\n return optionPointers === 0 || input.pointers.length === optionPointers;\n },\n /**\n * Process the input and return the state for the recognizer\n * @memberof AttrRecognizer\n * @param {Object} input\n * @returns {*} State\n */\n process: function (input) {\n var state = this.state;\n var eventType = input.eventType;\n var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);\n var isValid = this.attrTest(input);\n\n // on cancel input and we've recognized before, return STATE_CANCELLED\n if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {\n return state | STATE_CANCELLED;\n } else if (isRecognized || isValid) {\n if (eventType & INPUT_END) {\n return state | STATE_ENDED;\n } else if (!(state & STATE_BEGAN)) {\n return STATE_BEGAN;\n }\n return state | STATE_CHANGED;\n }\n return STATE_FAILED;\n }\n });\n\n /**\n * Pan\n * Recognized when the pointer is down and moved in the allowed direction.\n * @constructor\n * @extends AttrRecognizer\n */\n function PanRecognizer() {\n AttrRecognizer.apply(this, arguments);\n this.pX = null;\n this.pY = null;\n }\n inherit(PanRecognizer, AttrRecognizer, {\n /**\n * @namespace\n * @memberof PanRecognizer\n */\n defaults: {\n event: 'pan',\n threshold: 10,\n pointers: 1,\n direction: DIRECTION_ALL\n },\n getTouchAction: function () {\n var direction = this.options.direction;\n var actions = [];\n if (direction & DIRECTION_HORIZONTAL) {\n actions.push(TOUCH_ACTION_PAN_Y);\n }\n if (direction & DIRECTION_VERTICAL) {\n actions.push(TOUCH_ACTION_PAN_X);\n }\n return actions;\n },\n directionTest: function (input) {\n var options = this.options;\n var hasMoved = true;\n var distance = input.distance;\n var direction = input.direction;\n var x = input.deltaX;\n var y = input.deltaY;\n\n // lock to axis?\n if (!(direction & options.direction)) {\n if (options.direction & DIRECTION_HORIZONTAL) {\n direction = x === 0 ? DIRECTION_NONE : x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;\n hasMoved = x != this.pX;\n distance = Math.abs(input.deltaX);\n } else {\n direction = y === 0 ? DIRECTION_NONE : y < 0 ? DIRECTION_UP : DIRECTION_DOWN;\n hasMoved = y != this.pY;\n distance = Math.abs(input.deltaY);\n }\n }\n input.direction = direction;\n return hasMoved && distance > options.threshold && direction & options.direction;\n },\n attrTest: function (input) {\n return AttrRecognizer.prototype.attrTest.call(this, input) && (this.state & STATE_BEGAN || !(this.state & STATE_BEGAN) && this.directionTest(input));\n },\n emit: function (input) {\n this.pX = input.deltaX;\n this.pY = input.deltaY;\n var direction = directionStr(input.direction);\n if (direction) {\n input.additionalEvent = this.options.event + direction;\n }\n this._super.emit.call(this, input);\n }\n });\n\n /**\n * Pinch\n * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).\n * @constructor\n * @extends AttrRecognizer\n */\n function PinchRecognizer() {\n AttrRecognizer.apply(this, arguments);\n }\n inherit(PinchRecognizer, AttrRecognizer, {\n /**\n * @namespace\n * @memberof PinchRecognizer\n */\n defaults: {\n event: 'pinch',\n threshold: 0,\n pointers: 2\n },\n getTouchAction: function () {\n return [TOUCH_ACTION_NONE];\n },\n attrTest: function (input) {\n return this._super.attrTest.call(this, input) && (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN);\n },\n emit: function (input) {\n if (input.scale !== 1) {\n var inOut = input.scale < 1 ? 'in' : 'out';\n input.additionalEvent = this.options.event + inOut;\n }\n this._super.emit.call(this, input);\n }\n });\n\n /**\n * Press\n * Recognized when the pointer is down for x ms without any movement.\n * @constructor\n * @extends Recognizer\n */\n function PressRecognizer() {\n Recognizer.apply(this, arguments);\n this._timer = null;\n this._input = null;\n }\n inherit(PressRecognizer, Recognizer, {\n /**\n * @namespace\n * @memberof PressRecognizer\n */\n defaults: {\n event: 'press',\n pointers: 1,\n time: 251,\n // minimal time of the pointer to be pressed\n threshold: 9 // a minimal movement is ok, but keep it low\n },\n getTouchAction: function () {\n return [TOUCH_ACTION_AUTO];\n },\n process: function (input) {\n var options = this.options;\n var validPointers = input.pointers.length === options.pointers;\n var validMovement = input.distance < options.threshold;\n var validTime = input.deltaTime > options.time;\n this._input = input;\n\n // we only allow little movement\n // and we've reached an end event, so a tap is possible\n if (!validMovement || !validPointers || input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime) {\n this.reset();\n } else if (input.eventType & INPUT_START) {\n this.reset();\n this._timer = setTimeoutContext(function () {\n this.state = STATE_RECOGNIZED;\n this.tryEmit();\n }, options.time, this);\n } else if (input.eventType & INPUT_END) {\n return STATE_RECOGNIZED;\n }\n return STATE_FAILED;\n },\n reset: function () {\n clearTimeout(this._timer);\n },\n emit: function (input) {\n if (this.state !== STATE_RECOGNIZED) {\n return;\n }\n if (input && input.eventType & INPUT_END) {\n this.manager.emit(this.options.event + 'up', input);\n } else {\n this._input.timeStamp = now();\n this.manager.emit(this.options.event, this._input);\n }\n }\n });\n\n /**\n * Rotate\n * Recognized when two or more pointer are moving in a circular motion.\n * @constructor\n * @extends AttrRecognizer\n */\n function RotateRecognizer() {\n AttrRecognizer.apply(this, arguments);\n }\n inherit(RotateRecognizer, AttrRecognizer, {\n /**\n * @namespace\n * @memberof RotateRecognizer\n */\n defaults: {\n event: 'rotate',\n threshold: 0,\n pointers: 2\n },\n getTouchAction: function () {\n return [TOUCH_ACTION_NONE];\n },\n attrTest: function (input) {\n return this._super.attrTest.call(this, input) && (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN);\n }\n });\n\n /**\n * Swipe\n * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.\n * @constructor\n * @extends AttrRecognizer\n */\n function SwipeRecognizer() {\n AttrRecognizer.apply(this, arguments);\n }\n inherit(SwipeRecognizer, AttrRecognizer, {\n /**\n * @namespace\n * @memberof SwipeRecognizer\n */\n defaults: {\n event: 'swipe',\n threshold: 10,\n velocity: 0.3,\n direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,\n pointers: 1\n },\n getTouchAction: function () {\n return PanRecognizer.prototype.getTouchAction.call(this);\n },\n attrTest: function (input) {\n var direction = this.options.direction;\n var velocity;\n if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {\n velocity = input.overallVelocity;\n } else if (direction & DIRECTION_HORIZONTAL) {\n velocity = input.overallVelocityX;\n } else if (direction & DIRECTION_VERTICAL) {\n velocity = input.overallVelocityY;\n }\n return this._super.attrTest.call(this, input) && direction & input.offsetDirection && input.distance > this.options.threshold && input.maxPointers == this.options.pointers && abs(velocity) > this.options.velocity && input.eventType & INPUT_END;\n },\n emit: function (input) {\n var direction = directionStr(input.offsetDirection);\n if (direction) {\n this.manager.emit(this.options.event + direction, input);\n }\n this.manager.emit(this.options.event, input);\n }\n });\n\n /**\n * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur\n * between the given interval and position. The delay option can be used to recognize multi-taps without firing\n * a single tap.\n *\n * The eventData from the emitted event contains the property `tapCount`, which contains the amount of\n * multi-taps being recognized.\n * @constructor\n * @extends Recognizer\n */\n function TapRecognizer() {\n Recognizer.apply(this, arguments);\n\n // previous time and center,\n // used for tap counting\n this.pTime = false;\n this.pCenter = false;\n this._timer = null;\n this._input = null;\n this.count = 0;\n }\n inherit(TapRecognizer, Recognizer, {\n /**\n * @namespace\n * @memberof PinchRecognizer\n */\n defaults: {\n event: 'tap',\n pointers: 1,\n taps: 1,\n interval: 300,\n // max time between the multi-tap taps\n time: 250,\n // max time of the pointer to be down (like finger on the screen)\n threshold: 9,\n // a minimal movement is ok, but keep it low\n posThreshold: 10 // a multi-tap can be a bit off the initial position\n },\n getTouchAction: function () {\n return [TOUCH_ACTION_MANIPULATION];\n },\n process: function (input) {\n var options = this.options;\n var validPointers = input.pointers.length === options.pointers;\n var validMovement = input.distance < options.threshold;\n var validTouchTime = input.deltaTime < options.time;\n this.reset();\n if (input.eventType & INPUT_START && this.count === 0) {\n return this.failTimeout();\n }\n\n // we only allow little movement\n // and we've reached an end event, so a tap is possible\n if (validMovement && validTouchTime && validPointers) {\n if (input.eventType != INPUT_END) {\n return this.failTimeout();\n }\n var validInterval = this.pTime ? input.timeStamp - this.pTime < options.interval : true;\n var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold;\n this.pTime = input.timeStamp;\n this.pCenter = input.center;\n if (!validMultiTap || !validInterval) {\n this.count = 1;\n } else {\n this.count += 1;\n }\n this._input = input;\n\n // if tap count matches we have recognized it,\n // else it has began recognizing...\n var tapCount = this.count % options.taps;\n if (tapCount === 0) {\n // no failing requirements, immediately trigger the tap event\n // or wait as long as the multitap interval to trigger\n if (!this.hasRequireFailures()) {\n return STATE_RECOGNIZED;\n } else {\n this._timer = setTimeoutContext(function () {\n this.state = STATE_RECOGNIZED;\n this.tryEmit();\n }, options.interval, this);\n return STATE_BEGAN;\n }\n }\n }\n return STATE_FAILED;\n },\n failTimeout: function () {\n this._timer = setTimeoutContext(function () {\n this.state = STATE_FAILED;\n }, this.options.interval, this);\n return STATE_FAILED;\n },\n reset: function () {\n clearTimeout(this._timer);\n },\n emit: function () {\n if (this.state == STATE_RECOGNIZED) {\n this._input.tapCount = this.count;\n this.manager.emit(this.options.event, this._input);\n }\n }\n });\n\n /**\n * Simple way to create a manager with a default set of recognizers.\n * @param {HTMLElement} element\n * @param {Object} [options]\n * @constructor\n */\n function Hammer(element, options) {\n options = options || {};\n options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset);\n return new Manager(element, options);\n }\n\n /**\n * @const {string}\n */\n Hammer.VERSION = '2.0.7';\n\n /**\n * default settings\n * @namespace\n */\n Hammer.defaults = {\n /**\n * set if DOM events are being triggered.\n * But this is slower and unused by simple implementations, so disabled by default.\n * @type {Boolean}\n * @default false\n */\n domEvents: false,\n /**\n * The value for the touchAction property/fallback.\n * When set to `compute` it will magically set the correct value based on the added recognizers.\n * @type {String}\n * @default compute\n */\n touchAction: TOUCH_ACTION_COMPUTE,\n /**\n * @type {Boolean}\n * @default true\n */\n enable: true,\n /**\n * EXPERIMENTAL FEATURE -- can be removed/changed\n * Change the parent input target element.\n * If Null, then it is being set the to main element.\n * @type {Null|EventTarget}\n * @default null\n */\n inputTarget: null,\n /**\n * force an input class\n * @type {Null|Function}\n * @default null\n */\n inputClass: null,\n /**\n * Default recognizer setup when calling `Hammer()`\n * When creating a new Manager these will be skipped.\n * @type {Array}\n */\n preset: [\n // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]\n [RotateRecognizer, {\n enable: false\n }], [PinchRecognizer, {\n enable: false\n }, ['rotate']], [SwipeRecognizer, {\n direction: DIRECTION_HORIZONTAL\n }], [PanRecognizer, {\n direction: DIRECTION_HORIZONTAL\n }, ['swipe']], [TapRecognizer], [TapRecognizer, {\n event: 'doubletap',\n taps: 2\n }, ['tap']], [PressRecognizer]],\n /**\n * Some CSS properties can be used to improve the working of Hammer.\n * Add them to this method and they will be set when creating a new Manager.\n * @namespace\n */\n cssProps: {\n /**\n * Disables text selection to improve the dragging gesture. Mainly for desktop browsers.\n * @type {String}\n * @default 'none'\n */\n userSelect: 'none',\n /**\n * Disable the Windows Phone grippers when pressing an element.\n * @type {String}\n * @default 'none'\n */\n touchSelect: 'none',\n /**\n * Disables the default callout shown when you touch and hold a touch target.\n * On iOS, when you touch and hold a touch target such as a link, Safari displays\n * a callout containing information about the link. This property allows you to disable that callout.\n * @type {String}\n * @default 'none'\n */\n touchCallout: 'none',\n /**\n * Specifies whether zooming is enabled. Used by IE10>\n * @type {String}\n * @default 'none'\n */\n contentZooming: 'none',\n /**\n * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.\n * @type {String}\n * @default 'none'\n */\n userDrag: 'none',\n /**\n * Overrides the highlight color shown when the user taps a link or a JavaScript\n * clickable element in iOS. This property obeys the alpha value, if specified.\n * @type {String}\n * @default 'rgba(0,0,0,0)'\n */\n tapHighlightColor: 'rgba(0,0,0,0)'\n }\n };\n var STOP = 1;\n var FORCED_STOP = 2;\n\n /**\n * Manager\n * @param {HTMLElement} element\n * @param {Object} [options]\n * @constructor\n */\n function Manager(element, options) {\n this.options = assign({}, Hammer.defaults, options || {});\n this.options.inputTarget = this.options.inputTarget || element;\n this.handlers = {};\n this.session = {};\n this.recognizers = [];\n this.oldCssProps = {};\n this.element = element;\n this.input = createInputInstance(this);\n this.touchAction = new TouchAction(this, this.options.touchAction);\n toggleCssProps(this, true);\n each(this.options.recognizers, function (item) {\n var recognizer = this.add(new item[0](item[1]));\n item[2] && recognizer.recognizeWith(item[2]);\n item[3] && recognizer.requireFailure(item[3]);\n }, this);\n }\n Manager.prototype = {\n /**\n * set options\n * @param {Object} options\n * @returns {Manager}\n */\n set: function (options) {\n assign(this.options, options);\n\n // Options that need a little more setup\n if (options.touchAction) {\n this.touchAction.update();\n }\n if (options.inputTarget) {\n // Clean up existing event listeners and reinitialize\n this.input.destroy();\n this.input.target = options.inputTarget;\n this.input.init();\n }\n return this;\n },\n /**\n * stop recognizing for this session.\n * This session will be discarded, when a new [input]start event is fired.\n * When forced, the recognizer cycle is stopped immediately.\n * @param {Boolean} [force]\n */\n stop: function (force) {\n this.session.stopped = force ? FORCED_STOP : STOP;\n },\n /**\n * run the recognizers!\n * called by the inputHandler function on every movement of the pointers (touches)\n * it walks through all the recognizers and tries to detect the gesture that is being made\n * @param {Object} inputData\n */\n recognize: function (inputData) {\n var session = this.session;\n if (session.stopped) {\n return;\n }\n\n // run the touch-action polyfill\n this.touchAction.preventDefaults(inputData);\n var recognizer;\n var recognizers = this.recognizers;\n\n // this holds the recognizer that is being recognized.\n // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED\n // if no recognizer is detecting a thing, it is set to `null`\n var curRecognizer = session.curRecognizer;\n\n // reset when the last recognizer is recognized\n // or when we're in a new session\n if (!curRecognizer || curRecognizer && curRecognizer.state & STATE_RECOGNIZED) {\n curRecognizer = session.curRecognizer = null;\n }\n var i = 0;\n while (i < recognizers.length) {\n recognizer = recognizers[i];\n\n // find out if we are allowed try to recognize the input for this one.\n // 1. allow if the session is NOT forced stopped (see the .stop() method)\n // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one\n // that is being recognized.\n // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.\n // this can be setup with the `recognizeWith()` method on the recognizer.\n if (session.stopped !== FORCED_STOP && (\n // 1\n !curRecognizer || recognizer == curRecognizer ||\n // 2\n recognizer.canRecognizeWith(curRecognizer))) {\n // 3\n recognizer.recognize(inputData);\n } else {\n recognizer.reset();\n }\n\n // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the\n // current active recognizer. but only if we don't already have an active recognizer\n if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {\n curRecognizer = session.curRecognizer = recognizer;\n }\n i++;\n }\n },\n /**\n * get a recognizer by its event name.\n * @param {Recognizer|String} recognizer\n * @returns {Recognizer|Null}\n */\n get: function (recognizer) {\n if (recognizer instanceof Recognizer) {\n return recognizer;\n }\n var recognizers = this.recognizers;\n for (var i = 0; i < recognizers.length; i++) {\n if (recognizers[i].options.event == recognizer) {\n return recognizers[i];\n }\n }\n return null;\n },\n /**\n * add a recognizer to the manager\n * existing recognizers with the same event name will be removed\n * @param {Recognizer} recognizer\n * @returns {Recognizer|Manager}\n */\n add: function (recognizer) {\n if (invokeArrayArg(recognizer, 'add', this)) {\n return this;\n }\n\n // remove existing\n var existing = this.get(recognizer.options.event);\n if (existing) {\n this.remove(existing);\n }\n this.recognizers.push(recognizer);\n recognizer.manager = this;\n this.touchAction.update();\n return recognizer;\n },\n /**\n * remove a recognizer by name or instance\n * @param {Recognizer|String} recognizer\n * @returns {Manager}\n */\n remove: function (recognizer) {\n if (invokeArrayArg(recognizer, 'remove', this)) {\n return this;\n }\n recognizer = this.get(recognizer);\n\n // let's make sure this recognizer exists\n if (recognizer) {\n var recognizers = this.recognizers;\n var index = inArray(recognizers, recognizer);\n if (index !== -1) {\n recognizers.splice(index, 1);\n this.touchAction.update();\n }\n }\n return this;\n },\n /**\n * bind event\n * @param {String} events\n * @param {Function} handler\n * @returns {EventEmitter} this\n */\n on: function (events, handler) {\n if (events === undefined) {\n return;\n }\n if (handler === undefined) {\n return;\n }\n var handlers = this.handlers;\n each(splitStr(events), function (event) {\n handlers[event] = handlers[event] || [];\n handlers[event].push(handler);\n });\n return this;\n },\n /**\n * unbind event, leave emit blank to remove all handlers\n * @param {String} events\n * @param {Function} [handler]\n * @returns {EventEmitter} this\n */\n off: function (events, handler) {\n if (events === undefined) {\n return;\n }\n var handlers = this.handlers;\n each(splitStr(events), function (event) {\n if (!handler) {\n delete handlers[event];\n } else {\n handlers[event] && handlers[event].splice(inArray(handlers[event], handler), 1);\n }\n });\n return this;\n },\n /**\n * emit event to the listeners\n * @param {String} event\n * @param {Object} data\n */\n emit: function (event, data) {\n // we also want to trigger dom events\n if (this.options.domEvents) {\n triggerDomEvent(event, data);\n }\n\n // no handlers, so skip it all\n var handlers = this.handlers[event] && this.handlers[event].slice();\n if (!handlers || !handlers.length) {\n return;\n }\n data.type = event;\n data.preventDefault = function () {\n data.srcEvent.preventDefault();\n };\n var i = 0;\n while (i < handlers.length) {\n handlers[i](data);\n i++;\n }\n },\n /**\n * destroy the manager and unbinds all events\n * it doesn't unbind dom events, that is the user own responsibility\n */\n destroy: function () {\n this.element && toggleCssProps(this, false);\n this.handlers = {};\n this.session = {};\n this.input.destroy();\n this.element = null;\n }\n };\n\n /**\n * add/remove the css properties as defined in manager.options.cssProps\n * @param {Manager} manager\n * @param {Boolean} add\n */\n function toggleCssProps(manager, add) {\n var element = manager.element;\n if (!element.style) {\n return;\n }\n var prop;\n each(manager.options.cssProps, function (value, name) {\n prop = prefixed(element.style, name);\n if (add) {\n manager.oldCssProps[prop] = element.style[prop];\n element.style[prop] = value;\n } else {\n element.style[prop] = manager.oldCssProps[prop] || '';\n }\n });\n if (!add) {\n manager.oldCssProps = {};\n }\n }\n\n /**\n * trigger dom event\n * @param {String} event\n * @param {Object} data\n */\n function triggerDomEvent(event, data) {\n var gestureEvent = document.createEvent('Event');\n gestureEvent.initEvent(event, true, true);\n gestureEvent.gesture = data;\n data.target.dispatchEvent(gestureEvent);\n }\n assign(Hammer, {\n INPUT_START: INPUT_START,\n INPUT_MOVE: INPUT_MOVE,\n INPUT_END: INPUT_END,\n INPUT_CANCEL: INPUT_CANCEL,\n STATE_POSSIBLE: STATE_POSSIBLE,\n STATE_BEGAN: STATE_BEGAN,\n STATE_CHANGED: STATE_CHANGED,\n STATE_ENDED: STATE_ENDED,\n STATE_RECOGNIZED: STATE_RECOGNIZED,\n STATE_CANCELLED: STATE_CANCELLED,\n STATE_FAILED: STATE_FAILED,\n DIRECTION_NONE: DIRECTION_NONE,\n DIRECTION_LEFT: DIRECTION_LEFT,\n DIRECTION_RIGHT: DIRECTION_RIGHT,\n DIRECTION_UP: DIRECTION_UP,\n DIRECTION_DOWN: DIRECTION_DOWN,\n DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL,\n DIRECTION_VERTICAL: DIRECTION_VERTICAL,\n DIRECTION_ALL: DIRECTION_ALL,\n Manager: Manager,\n Input: Input,\n TouchAction: TouchAction,\n TouchInput: TouchInput,\n MouseInput: MouseInput,\n PointerEventInput: PointerEventInput,\n TouchMouseInput: TouchMouseInput,\n SingleTouchInput: SingleTouchInput,\n Recognizer: Recognizer,\n AttrRecognizer: AttrRecognizer,\n Tap: TapRecognizer,\n Pan: PanRecognizer,\n Swipe: SwipeRecognizer,\n Pinch: PinchRecognizer,\n Rotate: RotateRecognizer,\n Press: PressRecognizer,\n on: addEventListeners,\n off: removeEventListeners,\n each: each,\n merge: merge,\n extend: extend,\n assign: assign,\n inherit: inherit,\n bindFn: bindFn,\n prefixed: prefixed\n });\n\n // this prevents errors when Hammer is loaded in the presence of an AMD\n // style loader but by script tag, not by the loader.\n var freeGlobal = typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}; // jshint ignore:line\n freeGlobal.Hammer = Hammer;\n if (typeof define === 'function' && define.amd) {\n define(function () {\n return Hammer;\n });\n } else if (typeof module != 'undefined' && module.exports) {\n module.exports = Hammer;\n } else {\n window[exportName] = Hammer;\n }\n})(window, document, 'Hammer');","/**\n * @license Angular v19.2.5\n * (c) 2010-2025 Google LLC. https://angular.io/\n * License: MIT\n */\n\nimport { DOCUMENT, Location } from '@angular/common';\nimport * as i0 from '@angular/core';\nimport { ɵisPromise as _isPromise, ɵRuntimeError as _RuntimeError, Injectable, ɵisNgModule as _isNgModule, isStandalone, createEnvironmentInjector, InjectionToken, EventEmitter, input, inject, ViewContainerRef, ChangeDetectorRef, Output, Input, Directive, reflectComponentType, ɵisInjectable as _isInjectable, runInInjectionContext, Component, NgModuleFactory, Compiler, NgZone, afterNextRender, EnvironmentInjector, DestroyRef, ɵConsole as _Console, ɵPendingTasksInternal as _PendingTasksInternal } from '@angular/core';\nimport { isObservable, from, of, BehaviorSubject, combineLatest, EmptyError, concat, defer, pipe, throwError, EMPTY, ConnectableObservable, Subject, Subscription } from 'rxjs';\nimport { map, switchMap, take, startWith, filter, mergeMap, first, concatMap, tap, catchError, scan, defaultIfEmpty, last as last$1, takeLast, finalize, refCount, takeUntil } from 'rxjs/operators';\nimport * as i1 from '@angular/platform-browser';\n\n/**\n * The primary routing outlet.\n *\n * @publicApi\n */\nconst PRIMARY_OUTLET = 'primary';\n/**\n * A private symbol used to store the value of `Route.title` inside the `Route.data` if it is a\n * static string or `Route.resolve` if anything else. This allows us to reuse the existing route\n * data/resolvers to support the title feature without new instrumentation in the `Router` pipeline.\n */\nconst RouteTitleKey = /* @__PURE__ */Symbol('RouteTitle');\nclass ParamsAsMap {\n params;\n constructor(params) {\n this.params = params || {};\n }\n has(name) {\n return Object.prototype.hasOwnProperty.call(this.params, name);\n }\n get(name) {\n if (this.has(name)) {\n const v = this.params[name];\n return Array.isArray(v) ? v[0] : v;\n }\n return null;\n }\n getAll(name) {\n if (this.has(name)) {\n const v = this.params[name];\n return Array.isArray(v) ? v : [v];\n }\n return [];\n }\n get keys() {\n return Object.keys(this.params);\n }\n}\n/**\n * Converts a `Params` instance to a `ParamMap`.\n * @param params The instance to convert.\n * @returns The new map instance.\n *\n * @publicApi\n */\nfunction convertToParamMap(params) {\n return new ParamsAsMap(params);\n}\n/**\n * Matches the route configuration (`route`) against the actual URL (`segments`).\n *\n * When no matcher is defined on a `Route`, this is the matcher used by the Router by default.\n *\n * @param segments The remaining unmatched segments in the current navigation\n * @param segmentGroup The current segment group being matched\n * @param route The `Route` to match against.\n *\n * @see {@link UrlMatchResult}\n * @see {@link Route}\n *\n * @returns The resulting match information or `null` if the `route` should not match.\n * @publicApi\n */\nfunction defaultUrlMatcher(segments, segmentGroup, route) {\n const parts = route.path.split('/');\n if (parts.length > segments.length) {\n // The actual URL is shorter than the config, no match\n return null;\n }\n if (route.pathMatch === 'full' && (segmentGroup.hasChildren() || parts.length < segments.length)) {\n // The config is longer than the actual URL but we are looking for a full match, return null\n return null;\n }\n const posParams = {};\n // Check each config part against the actual URL\n for (let index = 0; index < parts.length; index++) {\n const part = parts[index];\n const segment = segments[index];\n const isParameter = part[0] === ':';\n if (isParameter) {\n posParams[part.substring(1)] = segment;\n } else if (part !== segment.path) {\n // The actual URL part does not match the config, no match\n return null;\n }\n }\n return {\n consumed: segments.slice(0, parts.length),\n posParams\n };\n}\nfunction shallowEqualArrays(a, b) {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; ++i) {\n if (!shallowEqual(a[i], b[i])) return false;\n }\n return true;\n}\nfunction shallowEqual(a, b) {\n // While `undefined` should never be possible, it would sometimes be the case in IE 11\n // and pre-chromium Edge. The check below accounts for this edge case.\n const k1 = a ? getDataKeys(a) : undefined;\n const k2 = b ? getDataKeys(b) : undefined;\n if (!k1 || !k2 || k1.length != k2.length) {\n return false;\n }\n let key;\n for (let i = 0; i < k1.length; i++) {\n key = k1[i];\n if (!equalArraysOrString(a[key], b[key])) {\n return false;\n }\n }\n return true;\n}\n/**\n * Gets the keys of an object, including `symbol` keys.\n */\nfunction getDataKeys(obj) {\n return [...Object.keys(obj), ...Object.getOwnPropertySymbols(obj)];\n}\n/**\n * Test equality for arrays of strings or a string.\n */\nfunction equalArraysOrString(a, b) {\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n const aSorted = [...a].sort();\n const bSorted = [...b].sort();\n return aSorted.every((val, index) => bSorted[index] === val);\n } else {\n return a === b;\n }\n}\n/**\n * Return the last element of an array.\n */\nfunction last(a) {\n return a.length > 0 ? a[a.length - 1] : null;\n}\nfunction wrapIntoObservable(value) {\n if (isObservable(value)) {\n return value;\n }\n if (_isPromise(value)) {\n // Use `Promise.resolve()` to wrap promise-like instances.\n // Required ie when a Resolver returns a AngularJS `$q` promise to correctly trigger the\n // change detection.\n return from(Promise.resolve(value));\n }\n return of(value);\n}\nconst pathCompareMap = {\n 'exact': equalSegmentGroups,\n 'subset': containsSegmentGroup\n};\nconst paramCompareMap = {\n 'exact': equalParams,\n 'subset': containsParams,\n 'ignored': () => true\n};\nfunction containsTree(container, containee, options) {\n return pathCompareMap[options.paths](container.root, containee.root, options.matrixParams) && paramCompareMap[options.queryParams](container.queryParams, containee.queryParams) && !(options.fragment === 'exact' && container.fragment !== containee.fragment);\n}\nfunction equalParams(container, containee) {\n // TODO: This does not handle array params correctly.\n return shallowEqual(container, containee);\n}\nfunction equalSegmentGroups(container, containee, matrixParams) {\n if (!equalPath(container.segments, containee.segments)) return false;\n if (!matrixParamsMatch(container.segments, containee.segments, matrixParams)) {\n return false;\n }\n if (container.numberOfChildren !== containee.numberOfChildren) return false;\n for (const c in containee.children) {\n if (!container.children[c]) return false;\n if (!equalSegmentGroups(container.children[c], containee.children[c], matrixParams)) return false;\n }\n return true;\n}\nfunction containsParams(container, containee) {\n return Object.keys(containee).length <= Object.keys(container).length && Object.keys(containee).every(key => equalArraysOrString(container[key], containee[key]));\n}\nfunction containsSegmentGroup(container, containee, matrixParams) {\n return containsSegmentGroupHelper(container, containee, containee.segments, matrixParams);\n}\nfunction containsSegmentGroupHelper(container, containee, containeePaths, matrixParams) {\n if (container.segments.length > containeePaths.length) {\n const current = container.segments.slice(0, containeePaths.length);\n if (!equalPath(current, containeePaths)) return false;\n if (containee.hasChildren()) return false;\n if (!matrixParamsMatch(current, containeePaths, matrixParams)) return false;\n return true;\n } else if (container.segments.length === containeePaths.length) {\n if (!equalPath(container.segments, containeePaths)) return false;\n if (!matrixParamsMatch(container.segments, containeePaths, matrixParams)) return false;\n for (const c in containee.children) {\n if (!container.children[c]) return false;\n if (!containsSegmentGroup(container.children[c], containee.children[c], matrixParams)) {\n return false;\n }\n }\n return true;\n } else {\n const current = containeePaths.slice(0, container.segments.length);\n const next = containeePaths.slice(container.segments.length);\n if (!equalPath(container.segments, current)) return false;\n if (!matrixParamsMatch(container.segments, current, matrixParams)) return false;\n if (!container.children[PRIMARY_OUTLET]) return false;\n return containsSegmentGroupHelper(container.children[PRIMARY_OUTLET], containee, next, matrixParams);\n }\n}\nfunction matrixParamsMatch(containerPaths, containeePaths, options) {\n return containeePaths.every((containeeSegment, i) => {\n return paramCompareMap[options](containerPaths[i].parameters, containeeSegment.parameters);\n });\n}\n/**\n * @description\n *\n * Represents the parsed URL.\n *\n * Since a router state is a tree, and the URL is nothing but a serialized state, the URL is a\n * serialized tree.\n * UrlTree is a data structure that provides a lot of affordances in dealing with URLs\n *\n * @usageNotes\n * ### Example\n *\n * ```ts\n * @Component({templateUrl:'template.html'})\n * class MyComponent {\n * constructor(router: Router) {\n * const tree: UrlTree =\n * router.parseUrl('/team/33/(user/victor//support:help)?debug=true#fragment');\n * const f = tree.fragment; // return 'fragment'\n * const q = tree.queryParams; // returns {debug: 'true'}\n * const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];\n * const s: UrlSegment[] = g.segments; // returns 2 segments 'team' and '33'\n * g.children[PRIMARY_OUTLET].segments; // returns 2 segments 'user' and 'victor'\n * g.children['support'].segments; // return 1 segment 'help'\n * }\n * }\n * ```\n *\n * @publicApi\n */\nclass UrlTree {\n root;\n queryParams;\n fragment;\n /** @internal */\n _queryParamMap;\n constructor(/** The root segment group of the URL tree */\n root = new UrlSegmentGroup([], {}), /** The query params of the URL */\n queryParams = {}, /** The fragment of the URL */\n fragment = null) {\n this.root = root;\n this.queryParams = queryParams;\n this.fragment = fragment;\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n if (root.segments.length > 0) {\n throw new _RuntimeError(4015 /* RuntimeErrorCode.INVALID_ROOT_URL_SEGMENT */, 'The root `UrlSegmentGroup` should not contain `segments`. ' + 'Instead, these segments belong in the `children` so they can be associated with a named outlet.');\n }\n }\n }\n get queryParamMap() {\n this._queryParamMap ??= convertToParamMap(this.queryParams);\n return this._queryParamMap;\n }\n /** @docsNotRequired */\n toString() {\n return DEFAULT_SERIALIZER.serialize(this);\n }\n}\n/**\n * @description\n *\n * Represents the parsed URL segment group.\n *\n * See `UrlTree` for more information.\n *\n * @publicApi\n */\nclass UrlSegmentGroup {\n segments;\n children;\n /** The parent node in the url tree */\n parent = null;\n constructor(/** The URL segments of this group. See `UrlSegment` for more information */\n segments, /** The list of children of this group */\n children) {\n this.segments = segments;\n this.children = children;\n Object.values(children).forEach(v => v.parent = this);\n }\n /** Whether the segment has child segments */\n hasChildren() {\n return this.numberOfChildren > 0;\n }\n /** Number of child segments */\n get numberOfChildren() {\n return Object.keys(this.children).length;\n }\n /** @docsNotRequired */\n toString() {\n return serializePaths(this);\n }\n}\n/**\n * @description\n *\n * Represents a single URL segment.\n *\n * A UrlSegment is a part of a URL between the two slashes. It contains a path and the matrix\n * parameters associated with the segment.\n *\n * @usageNotes\n * ### Example\n *\n * ```ts\n * @Component({templateUrl:'template.html'})\n * class MyComponent {\n * constructor(router: Router) {\n * const tree: UrlTree = router.parseUrl('/team;id=33');\n * const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];\n * const s: UrlSegment[] = g.segments;\n * s[0].path; // returns 'team'\n * s[0].parameters; // returns {id: 33}\n * }\n * }\n * ```\n *\n * @publicApi\n */\nclass UrlSegment {\n path;\n parameters;\n /** @internal */\n _parameterMap;\n constructor(/** The path part of a URL segment */\n path, /** The matrix parameters associated with a segment */\n parameters) {\n this.path = path;\n this.parameters = parameters;\n }\n get parameterMap() {\n this._parameterMap ??= convertToParamMap(this.parameters);\n return this._parameterMap;\n }\n /** @docsNotRequired */\n toString() {\n return serializePath(this);\n }\n}\nfunction equalSegments(as, bs) {\n return equalPath(as, bs) && as.every((a, i) => shallowEqual(a.parameters, bs[i].parameters));\n}\nfunction equalPath(as, bs) {\n if (as.length !== bs.length) return false;\n return as.every((a, i) => a.path === bs[i].path);\n}\nfunction mapChildrenIntoArray(segment, fn) {\n let res = [];\n Object.entries(segment.children).forEach(([childOutlet, child]) => {\n if (childOutlet === PRIMARY_OUTLET) {\n res = res.concat(fn(child, childOutlet));\n }\n });\n Object.entries(segment.children).forEach(([childOutlet, child]) => {\n if (childOutlet !== PRIMARY_OUTLET) {\n res = res.concat(fn(child, childOutlet));\n }\n });\n return res;\n}\n/**\n * @description\n *\n * Serializes and deserializes a URL string into a URL tree.\n *\n * The url serialization strategy is customizable. You can\n * make all URLs case insensitive by providing a custom UrlSerializer.\n *\n * See `DefaultUrlSerializer` for an example of a URL serializer.\n *\n * @publicApi\n */\nlet UrlSerializer = /*#__PURE__*/(() => {\n class UrlSerializer {\n static ɵfac = function UrlSerializer_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || UrlSerializer)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: UrlSerializer,\n factory: () => (() => new DefaultUrlSerializer())(),\n providedIn: 'root'\n });\n }\n return UrlSerializer;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * @description\n *\n * A default implementation of the `UrlSerializer`.\n *\n * Example URLs:\n *\n * ```\n * /inbox/33(popup:compose)\n * /inbox/33;open=true/messages/44\n * ```\n *\n * DefaultUrlSerializer uses parentheses to serialize secondary segments (e.g., popup:compose), the\n * colon syntax to specify the outlet, and the ';parameter=value' syntax (e.g., open=true) to\n * specify route specific parameters.\n *\n * @publicApi\n */\nclass DefaultUrlSerializer {\n /** Parses a url into a `UrlTree` */\n parse(url) {\n const p = new UrlParser(url);\n return new UrlTree(p.parseRootSegment(), p.parseQueryParams(), p.parseFragment());\n }\n /** Converts a `UrlTree` into a url */\n serialize(tree) {\n const segment = `/${serializeSegment(tree.root, true)}`;\n const query = serializeQueryParams(tree.queryParams);\n const fragment = typeof tree.fragment === `string` ? `#${encodeUriFragment(tree.fragment)}` : '';\n return `${segment}${query}${fragment}`;\n }\n}\nconst DEFAULT_SERIALIZER = /*#__PURE__*/new DefaultUrlSerializer();\nfunction serializePaths(segment) {\n return segment.segments.map(p => serializePath(p)).join('/');\n}\nfunction serializeSegment(segment, root) {\n if (!segment.hasChildren()) {\n return serializePaths(segment);\n }\n if (root) {\n const primary = segment.children[PRIMARY_OUTLET] ? serializeSegment(segment.children[PRIMARY_OUTLET], false) : '';\n const children = [];\n Object.entries(segment.children).forEach(([k, v]) => {\n if (k !== PRIMARY_OUTLET) {\n children.push(`${k}:${serializeSegment(v, false)}`);\n }\n });\n return children.length > 0 ? `${primary}(${children.join('//')})` : primary;\n } else {\n const children = mapChildrenIntoArray(segment, (v, k) => {\n if (k === PRIMARY_OUTLET) {\n return [serializeSegment(segment.children[PRIMARY_OUTLET], false)];\n }\n return [`${k}:${serializeSegment(v, false)}`];\n });\n // use no parenthesis if the only child is a primary outlet route\n if (Object.keys(segment.children).length === 1 && segment.children[PRIMARY_OUTLET] != null) {\n return `${serializePaths(segment)}/${children[0]}`;\n }\n return `${serializePaths(segment)}/(${children.join('//')})`;\n }\n}\n/**\n * Encodes a URI string with the default encoding. This function will only ever be called from\n * `encodeUriQuery` or `encodeUriSegment` as it's the base set of encodings to be used. We need\n * a custom encoding because encodeURIComponent is too aggressive and encodes stuff that doesn't\n * have to be encoded per https://url.spec.whatwg.org.\n */\nfunction encodeUriString(s) {\n return encodeURIComponent(s).replace(/%40/g, '@').replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',');\n}\n/**\n * This function should be used to encode both keys and values in a query string key/value. In\n * the following URL, you need to call encodeUriQuery on \"k\" and \"v\":\n *\n * http://www.site.org/html;mk=mv?k=v#f\n */\nfunction encodeUriQuery(s) {\n return encodeUriString(s).replace(/%3B/gi, ';');\n}\n/**\n * This function should be used to encode a URL fragment. In the following URL, you need to call\n * encodeUriFragment on \"f\":\n *\n * http://www.site.org/html;mk=mv?k=v#f\n */\nfunction encodeUriFragment(s) {\n return encodeURI(s);\n}\n/**\n * This function should be run on any URI segment as well as the key and value in a key/value\n * pair for matrix params. In the following URL, you need to call encodeUriSegment on \"html\",\n * \"mk\", and \"mv\":\n *\n * http://www.site.org/html;mk=mv?k=v#f\n */\nfunction encodeUriSegment(s) {\n return encodeUriString(s).replace(/\\(/g, '%28').replace(/\\)/g, '%29').replace(/%26/gi, '&');\n}\nfunction decode(s) {\n return decodeURIComponent(s);\n}\n// Query keys/values should have the \"+\" replaced first, as \"+\" in a query string is \" \".\n// decodeURIComponent function will not decode \"+\" as a space.\nfunction decodeQuery(s) {\n return decode(s.replace(/\\+/g, '%20'));\n}\nfunction serializePath(path) {\n return `${encodeUriSegment(path.path)}${serializeMatrixParams(path.parameters)}`;\n}\nfunction serializeMatrixParams(params) {\n return Object.entries(params).map(([key, value]) => `;${encodeUriSegment(key)}=${encodeUriSegment(value)}`).join('');\n}\nfunction serializeQueryParams(params) {\n const strParams = Object.entries(params).map(([name, value]) => {\n return Array.isArray(value) ? value.map(v => `${encodeUriQuery(name)}=${encodeUriQuery(v)}`).join('&') : `${encodeUriQuery(name)}=${encodeUriQuery(value)}`;\n }).filter(s => s);\n return strParams.length ? `?${strParams.join('&')}` : '';\n}\nconst SEGMENT_RE = /^[^\\/()?;#]+/;\nfunction matchSegments(str) {\n const match = str.match(SEGMENT_RE);\n return match ? match[0] : '';\n}\nconst MATRIX_PARAM_SEGMENT_RE = /^[^\\/()?;=#]+/;\nfunction matchMatrixKeySegments(str) {\n const match = str.match(MATRIX_PARAM_SEGMENT_RE);\n return match ? match[0] : '';\n}\nconst QUERY_PARAM_RE = /^[^=?&#]+/;\n// Return the name of the query param at the start of the string or an empty string\nfunction matchQueryParams(str) {\n const match = str.match(QUERY_PARAM_RE);\n return match ? match[0] : '';\n}\nconst QUERY_PARAM_VALUE_RE = /^[^&#]+/;\n// Return the value of the query param at the start of the string or an empty string\nfunction matchUrlQueryParamValue(str) {\n const match = str.match(QUERY_PARAM_VALUE_RE);\n return match ? match[0] : '';\n}\nclass UrlParser {\n url;\n remaining;\n constructor(url) {\n this.url = url;\n this.remaining = url;\n }\n parseRootSegment() {\n this.consumeOptional('/');\n if (this.remaining === '' || this.peekStartsWith('?') || this.peekStartsWith('#')) {\n return new UrlSegmentGroup([], {});\n }\n // The root segment group never has segments\n return new UrlSegmentGroup([], this.parseChildren());\n }\n parseQueryParams() {\n const params = {};\n if (this.consumeOptional('?')) {\n do {\n this.parseQueryParam(params);\n } while (this.consumeOptional('&'));\n }\n return params;\n }\n parseFragment() {\n return this.consumeOptional('#') ? decodeURIComponent(this.remaining) : null;\n }\n parseChildren() {\n if (this.remaining === '') {\n return {};\n }\n this.consumeOptional('/');\n const segments = [];\n if (!this.peekStartsWith('(')) {\n segments.push(this.parseSegment());\n }\n while (this.peekStartsWith('/') && !this.peekStartsWith('//') && !this.peekStartsWith('/(')) {\n this.capture('/');\n segments.push(this.parseSegment());\n }\n let children = {};\n if (this.peekStartsWith('/(')) {\n this.capture('/');\n children = this.parseParens(true);\n }\n let res = {};\n if (this.peekStartsWith('(')) {\n res = this.parseParens(false);\n }\n if (segments.length > 0 || Object.keys(children).length > 0) {\n res[PRIMARY_OUTLET] = new UrlSegmentGroup(segments, children);\n }\n return res;\n }\n // parse a segment with its matrix parameters\n // ie `name;k1=v1;k2`\n parseSegment() {\n const path = matchSegments(this.remaining);\n if (path === '' && this.peekStartsWith(';')) {\n throw new _RuntimeError(4009 /* RuntimeErrorCode.EMPTY_PATH_WITH_PARAMS */, (typeof ngDevMode === 'undefined' || ngDevMode) && `Empty path url segment cannot have parameters: '${this.remaining}'.`);\n }\n this.capture(path);\n return new UrlSegment(decode(path), this.parseMatrixParams());\n }\n parseMatrixParams() {\n const params = {};\n while (this.consumeOptional(';')) {\n this.parseParam(params);\n }\n return params;\n }\n parseParam(params) {\n const key = matchMatrixKeySegments(this.remaining);\n if (!key) {\n return;\n }\n this.capture(key);\n let value = '';\n if (this.consumeOptional('=')) {\n const valueMatch = matchSegments(this.remaining);\n if (valueMatch) {\n value = valueMatch;\n this.capture(value);\n }\n }\n params[decode(key)] = decode(value);\n }\n // Parse a single query parameter `name[=value]`\n parseQueryParam(params) {\n const key = matchQueryParams(this.remaining);\n if (!key) {\n return;\n }\n this.capture(key);\n let value = '';\n if (this.consumeOptional('=')) {\n const valueMatch = matchUrlQueryParamValue(this.remaining);\n if (valueMatch) {\n value = valueMatch;\n this.capture(value);\n }\n }\n const decodedKey = decodeQuery(key);\n const decodedVal = decodeQuery(value);\n if (params.hasOwnProperty(decodedKey)) {\n // Append to existing values\n let currentVal = params[decodedKey];\n if (!Array.isArray(currentVal)) {\n currentVal = [currentVal];\n params[decodedKey] = currentVal;\n }\n currentVal.push(decodedVal);\n } else {\n // Create a new value\n params[decodedKey] = decodedVal;\n }\n }\n // parse `(a/b//outlet_name:c/d)`\n parseParens(allowPrimary) {\n const segments = {};\n this.capture('(');\n while (!this.consumeOptional(')') && this.remaining.length > 0) {\n const path = matchSegments(this.remaining);\n const next = this.remaining[path.length];\n // if is is not one of these characters, then the segment was unescaped\n // or the group was not closed\n if (next !== '/' && next !== ')' && next !== ';') {\n throw new _RuntimeError(4010 /* RuntimeErrorCode.UNPARSABLE_URL */, (typeof ngDevMode === 'undefined' || ngDevMode) && `Cannot parse url '${this.url}'`);\n }\n let outletName = undefined;\n if (path.indexOf(':') > -1) {\n outletName = path.slice(0, path.indexOf(':'));\n this.capture(outletName);\n this.capture(':');\n } else if (allowPrimary) {\n outletName = PRIMARY_OUTLET;\n }\n const children = this.parseChildren();\n segments[outletName] = Object.keys(children).length === 1 ? children[PRIMARY_OUTLET] : new UrlSegmentGroup([], children);\n this.consumeOptional('//');\n }\n return segments;\n }\n peekStartsWith(str) {\n return this.remaining.startsWith(str);\n }\n // Consumes the prefix when it is present and returns whether it has been consumed\n consumeOptional(str) {\n if (this.peekStartsWith(str)) {\n this.remaining = this.remaining.substring(str.length);\n return true;\n }\n return false;\n }\n capture(str) {\n if (!this.consumeOptional(str)) {\n throw new _RuntimeError(4011 /* RuntimeErrorCode.UNEXPECTED_VALUE_IN_URL */, (typeof ngDevMode === 'undefined' || ngDevMode) && `Expected \"${str}\".`);\n }\n }\n}\nfunction createRoot(rootCandidate) {\n return rootCandidate.segments.length > 0 ? new UrlSegmentGroup([], {\n [PRIMARY_OUTLET]: rootCandidate\n }) : rootCandidate;\n}\n/**\n * Recursively\n * - merges primary segment children into their parents\n * - drops empty children (those which have no segments and no children themselves). This latter\n * prevents serializing a group into something like `/a(aux:)`, where `aux` is an empty child\n * segment.\n * - merges named outlets without a primary segment sibling into the children. This prevents\n * serializing a URL like `//(a:a)(b:b) instead of `/(a:a//b:b)` when the aux b route lives on the\n * root but the `a` route lives under an empty path primary route.\n */\nfunction squashSegmentGroup(segmentGroup) {\n const newChildren = {};\n for (const [childOutlet, child] of Object.entries(segmentGroup.children)) {\n const childCandidate = squashSegmentGroup(child);\n // moves named children in an empty path primary child into this group\n if (childOutlet === PRIMARY_OUTLET && childCandidate.segments.length === 0 && childCandidate.hasChildren()) {\n for (const [grandChildOutlet, grandChild] of Object.entries(childCandidate.children)) {\n newChildren[grandChildOutlet] = grandChild;\n }\n } // don't add empty children\n else if (childCandidate.segments.length > 0 || childCandidate.hasChildren()) {\n newChildren[childOutlet] = childCandidate;\n }\n }\n const s = new UrlSegmentGroup(segmentGroup.segments, newChildren);\n return mergeTrivialChildren(s);\n}\n/**\n * When possible, merges the primary outlet child into the parent `UrlSegmentGroup`.\n *\n * When a segment group has only one child which is a primary outlet, merges that child into the\n * parent. That is, the child segment group's segments are merged into the `s` and the child's\n * children become the children of `s`. Think of this like a 'squash', merging the child segment\n * group into the parent.\n */\nfunction mergeTrivialChildren(s) {\n if (s.numberOfChildren === 1 && s.children[PRIMARY_OUTLET]) {\n const c = s.children[PRIMARY_OUTLET];\n return new UrlSegmentGroup(s.segments.concat(c.segments), c.children);\n }\n return s;\n}\nfunction isUrlTree(v) {\n return v instanceof UrlTree;\n}\n\n/**\n * Creates a `UrlTree` relative to an `ActivatedRouteSnapshot`.\n *\n * @publicApi\n *\n *\n * @param relativeTo The `ActivatedRouteSnapshot` to apply the commands to\n * @param commands An array of URL fragments with which to construct the new URL tree.\n * If the path is static, can be the literal URL string. For a dynamic path, pass an array of path\n * segments, followed by the parameters for each segment.\n * The fragments are applied to the one provided in the `relativeTo` parameter.\n * @param queryParams The query parameters for the `UrlTree`. `null` if the `UrlTree` does not have\n * any query parameters.\n * @param fragment The fragment for the `UrlTree`. `null` if the `UrlTree` does not have a fragment.\n *\n * @usageNotes\n *\n * ```ts\n * // create /team/33/user/11\n * createUrlTreeFromSnapshot(snapshot, ['/team', 33, 'user', 11]);\n *\n * // create /team/33;expand=true/user/11\n * createUrlTreeFromSnapshot(snapshot, ['/team', 33, {expand: true}, 'user', 11]);\n *\n * // you can collapse static segments like this (this works only with the first passed-in value):\n * createUrlTreeFromSnapshot(snapshot, ['/team/33/user', userId]);\n *\n * // If the first segment can contain slashes, and you do not want the router to split it,\n * // you can do the following:\n * createUrlTreeFromSnapshot(snapshot, [{segmentPath: '/one/two'}]);\n *\n * // create /team/33/(user/11//right:chat)\n * createUrlTreeFromSnapshot(snapshot, ['/team', 33, {outlets: {primary: 'user/11', right:\n * 'chat'}}], null, null);\n *\n * // remove the right secondary node\n * createUrlTreeFromSnapshot(snapshot, ['/team', 33, {outlets: {primary: 'user/11', right: null}}]);\n *\n * // For the examples below, assume the current URL is for the `/team/33/user/11` and the\n * `ActivatedRouteSnapshot` points to `user/11`:\n *\n * // navigate to /team/33/user/11/details\n * createUrlTreeFromSnapshot(snapshot, ['details']);\n *\n * // navigate to /team/33/user/22\n * createUrlTreeFromSnapshot(snapshot, ['../22']);\n *\n * // navigate to /team/44/user/22\n * createUrlTreeFromSnapshot(snapshot, ['../../team/44/user/22']);\n * ```\n */\nfunction createUrlTreeFromSnapshot(relativeTo, commands, queryParams = null, fragment = null) {\n const relativeToUrlSegmentGroup = createSegmentGroupFromRoute(relativeTo);\n return createUrlTreeFromSegmentGroup(relativeToUrlSegmentGroup, commands, queryParams, fragment);\n}\nfunction createSegmentGroupFromRoute(route) {\n let targetGroup;\n function createSegmentGroupFromRouteRecursive(currentRoute) {\n const childOutlets = {};\n for (const childSnapshot of currentRoute.children) {\n const root = createSegmentGroupFromRouteRecursive(childSnapshot);\n childOutlets[childSnapshot.outlet] = root;\n }\n const segmentGroup = new UrlSegmentGroup(currentRoute.url, childOutlets);\n if (currentRoute === route) {\n targetGroup = segmentGroup;\n }\n return segmentGroup;\n }\n const rootCandidate = createSegmentGroupFromRouteRecursive(route.root);\n const rootSegmentGroup = createRoot(rootCandidate);\n return targetGroup ?? rootSegmentGroup;\n}\nfunction createUrlTreeFromSegmentGroup(relativeTo, commands, queryParams, fragment) {\n let root = relativeTo;\n while (root.parent) {\n root = root.parent;\n }\n // There are no commands so the `UrlTree` goes to the same path as the one created from the\n // `UrlSegmentGroup`. All we need to do is update the `queryParams` and `fragment` without\n // applying any other logic.\n if (commands.length === 0) {\n return tree(root, root, root, queryParams, fragment);\n }\n const nav = computeNavigation(commands);\n if (nav.toRoot()) {\n return tree(root, root, new UrlSegmentGroup([], {}), queryParams, fragment);\n }\n const position = findStartingPositionForTargetGroup(nav, root, relativeTo);\n const newSegmentGroup = position.processChildren ? updateSegmentGroupChildren(position.segmentGroup, position.index, nav.commands) : updateSegmentGroup(position.segmentGroup, position.index, nav.commands);\n return tree(root, position.segmentGroup, newSegmentGroup, queryParams, fragment);\n}\nfunction isMatrixParams(command) {\n return typeof command === 'object' && command != null && !command.outlets && !command.segmentPath;\n}\n/**\n * Determines if a given command has an `outlets` map. When we encounter a command\n * with an outlets k/v map, we need to apply each outlet individually to the existing segment.\n */\nfunction isCommandWithOutlets(command) {\n return typeof command === 'object' && command != null && command.outlets;\n}\nfunction tree(oldRoot, oldSegmentGroup, newSegmentGroup, queryParams, fragment) {\n let qp = {};\n if (queryParams) {\n Object.entries(queryParams).forEach(([name, value]) => {\n qp[name] = Array.isArray(value) ? value.map(v => `${v}`) : `${value}`;\n });\n }\n let rootCandidate;\n if (oldRoot === oldSegmentGroup) {\n rootCandidate = newSegmentGroup;\n } else {\n rootCandidate = replaceSegment(oldRoot, oldSegmentGroup, newSegmentGroup);\n }\n const newRoot = createRoot(squashSegmentGroup(rootCandidate));\n return new UrlTree(newRoot, qp, fragment);\n}\n/**\n * Replaces the `oldSegment` which is located in some child of the `current` with the `newSegment`.\n * This also has the effect of creating new `UrlSegmentGroup` copies to update references. This\n * shouldn't be necessary but the fallback logic for an invalid ActivatedRoute in the creation uses\n * the Router's current url tree. If we don't create new segment groups, we end up modifying that\n * value.\n */\nfunction replaceSegment(current, oldSegment, newSegment) {\n const children = {};\n Object.entries(current.children).forEach(([outletName, c]) => {\n if (c === oldSegment) {\n children[outletName] = newSegment;\n } else {\n children[outletName] = replaceSegment(c, oldSegment, newSegment);\n }\n });\n return new UrlSegmentGroup(current.segments, children);\n}\nclass Navigation {\n isAbsolute;\n numberOfDoubleDots;\n commands;\n constructor(isAbsolute, numberOfDoubleDots, commands) {\n this.isAbsolute = isAbsolute;\n this.numberOfDoubleDots = numberOfDoubleDots;\n this.commands = commands;\n if (isAbsolute && commands.length > 0 && isMatrixParams(commands[0])) {\n throw new _RuntimeError(4003 /* RuntimeErrorCode.ROOT_SEGMENT_MATRIX_PARAMS */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Root segment cannot have matrix parameters');\n }\n const cmdWithOutlet = commands.find(isCommandWithOutlets);\n if (cmdWithOutlet && cmdWithOutlet !== last(commands)) {\n throw new _RuntimeError(4004 /* RuntimeErrorCode.MISPLACED_OUTLETS_COMMAND */, (typeof ngDevMode === 'undefined' || ngDevMode) && '{outlets:{}} has to be the last command');\n }\n }\n toRoot() {\n return this.isAbsolute && this.commands.length === 1 && this.commands[0] == '/';\n }\n}\n/** Transforms commands to a normalized `Navigation` */\nfunction computeNavigation(commands) {\n if (typeof commands[0] === 'string' && commands.length === 1 && commands[0] === '/') {\n return new Navigation(true, 0, commands);\n }\n let numberOfDoubleDots = 0;\n let isAbsolute = false;\n const res = commands.reduce((res, cmd, cmdIdx) => {\n if (typeof cmd === 'object' && cmd != null) {\n if (cmd.outlets) {\n const outlets = {};\n Object.entries(cmd.outlets).forEach(([name, commands]) => {\n outlets[name] = typeof commands === 'string' ? commands.split('/') : commands;\n });\n return [...res, {\n outlets\n }];\n }\n if (cmd.segmentPath) {\n return [...res, cmd.segmentPath];\n }\n }\n if (!(typeof cmd === 'string')) {\n return [...res, cmd];\n }\n if (cmdIdx === 0) {\n cmd.split('/').forEach((urlPart, partIndex) => {\n if (partIndex == 0 && urlPart === '.') ;else if (partIndex == 0 && urlPart === '') {\n // '/a'\n isAbsolute = true;\n } else if (urlPart === '..') {\n // '../a'\n numberOfDoubleDots++;\n } else if (urlPart != '') {\n res.push(urlPart);\n }\n });\n return res;\n }\n return [...res, cmd];\n }, []);\n return new Navigation(isAbsolute, numberOfDoubleDots, res);\n}\nclass Position {\n segmentGroup;\n processChildren;\n index;\n constructor(segmentGroup, processChildren, index) {\n this.segmentGroup = segmentGroup;\n this.processChildren = processChildren;\n this.index = index;\n }\n}\nfunction findStartingPositionForTargetGroup(nav, root, target) {\n if (nav.isAbsolute) {\n return new Position(root, true, 0);\n }\n if (!target) {\n // `NaN` is used only to maintain backwards compatibility with incorrectly mocked\n // `ActivatedRouteSnapshot` in tests. In prior versions of this code, the position here was\n // determined based on an internal property that was rarely mocked, resulting in `NaN`. In\n // reality, this code path should _never_ be touched since `target` is not allowed to be falsey.\n return new Position(root, false, NaN);\n }\n if (target.parent === null) {\n return new Position(target, true, 0);\n }\n const modifier = isMatrixParams(nav.commands[0]) ? 0 : 1;\n const index = target.segments.length - 1 + modifier;\n return createPositionApplyingDoubleDots(target, index, nav.numberOfDoubleDots);\n}\nfunction createPositionApplyingDoubleDots(group, index, numberOfDoubleDots) {\n let g = group;\n let ci = index;\n let dd = numberOfDoubleDots;\n while (dd > ci) {\n dd -= ci;\n g = g.parent;\n if (!g) {\n throw new _RuntimeError(4005 /* RuntimeErrorCode.INVALID_DOUBLE_DOTS */, (typeof ngDevMode === 'undefined' || ngDevMode) && \"Invalid number of '../'\");\n }\n ci = g.segments.length;\n }\n return new Position(g, false, ci - dd);\n}\nfunction getOutlets(commands) {\n if (isCommandWithOutlets(commands[0])) {\n return commands[0].outlets;\n }\n return {\n [PRIMARY_OUTLET]: commands\n };\n}\nfunction updateSegmentGroup(segmentGroup, startIndex, commands) {\n segmentGroup ??= new UrlSegmentGroup([], {});\n if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {\n return updateSegmentGroupChildren(segmentGroup, startIndex, commands);\n }\n const m = prefixedWith(segmentGroup, startIndex, commands);\n const slicedCommands = commands.slice(m.commandIndex);\n if (m.match && m.pathIndex < segmentGroup.segments.length) {\n const g = new UrlSegmentGroup(segmentGroup.segments.slice(0, m.pathIndex), {});\n g.children[PRIMARY_OUTLET] = new UrlSegmentGroup(segmentGroup.segments.slice(m.pathIndex), segmentGroup.children);\n return updateSegmentGroupChildren(g, 0, slicedCommands);\n } else if (m.match && slicedCommands.length === 0) {\n return new UrlSegmentGroup(segmentGroup.segments, {});\n } else if (m.match && !segmentGroup.hasChildren()) {\n return createNewSegmentGroup(segmentGroup, startIndex, commands);\n } else if (m.match) {\n return updateSegmentGroupChildren(segmentGroup, 0, slicedCommands);\n } else {\n return createNewSegmentGroup(segmentGroup, startIndex, commands);\n }\n}\nfunction updateSegmentGroupChildren(segmentGroup, startIndex, commands) {\n if (commands.length === 0) {\n return new UrlSegmentGroup(segmentGroup.segments, {});\n } else {\n const outlets = getOutlets(commands);\n const children = {};\n // If the set of commands applies to anything other than the primary outlet and the child\n // segment is an empty path primary segment on its own, we want to apply the commands to the\n // empty child path rather than here. The outcome is that the empty primary child is effectively\n // removed from the final output UrlTree. Imagine the following config:\n //\n // {path: '', children: [{path: '**', outlet: 'popup'}]}.\n //\n // Navigation to /(popup:a) will activate the child outlet correctly Given a follow-up\n // navigation with commands\n // ['/', {outlets: {'popup': 'b'}}], we _would not_ want to apply the outlet commands to the\n // root segment because that would result in\n // //(popup:a)(popup:b) since the outlet command got applied one level above where it appears in\n // the `ActivatedRoute` rather than updating the existing one.\n //\n // Because empty paths do not appear in the URL segments and the fact that the segments used in\n // the output `UrlTree` are squashed to eliminate these empty paths where possible\n // https://github.com/angular/angular/blob/13f10de40e25c6900ca55bd83b36bd533dacfa9e/packages/router/src/url_tree.ts#L755\n // it can be hard to determine what is the right thing to do when applying commands to a\n // `UrlSegmentGroup` that is created from an \"unsquashed\"/expanded `ActivatedRoute` tree.\n // This code effectively \"squashes\" empty path primary routes when they have no siblings on\n // the same level of the tree.\n if (Object.keys(outlets).some(o => o !== PRIMARY_OUTLET) && segmentGroup.children[PRIMARY_OUTLET] && segmentGroup.numberOfChildren === 1 && segmentGroup.children[PRIMARY_OUTLET].segments.length === 0) {\n const childrenOfEmptyChild = updateSegmentGroupChildren(segmentGroup.children[PRIMARY_OUTLET], startIndex, commands);\n return new UrlSegmentGroup(segmentGroup.segments, childrenOfEmptyChild.children);\n }\n Object.entries(outlets).forEach(([outlet, commands]) => {\n if (typeof commands === 'string') {\n commands = [commands];\n }\n if (commands !== null) {\n children[outlet] = updateSegmentGroup(segmentGroup.children[outlet], startIndex, commands);\n }\n });\n Object.entries(segmentGroup.children).forEach(([childOutlet, child]) => {\n if (outlets[childOutlet] === undefined) {\n children[childOutlet] = child;\n }\n });\n return new UrlSegmentGroup(segmentGroup.segments, children);\n }\n}\nfunction prefixedWith(segmentGroup, startIndex, commands) {\n let currentCommandIndex = 0;\n let currentPathIndex = startIndex;\n const noMatch = {\n match: false,\n pathIndex: 0,\n commandIndex: 0\n };\n while (currentPathIndex < segmentGroup.segments.length) {\n if (currentCommandIndex >= commands.length) return noMatch;\n const path = segmentGroup.segments[currentPathIndex];\n const command = commands[currentCommandIndex];\n // Do not try to consume command as part of the prefixing if it has outlets because it can\n // contain outlets other than the one being processed. Consuming the outlets command would\n // result in other outlets being ignored.\n if (isCommandWithOutlets(command)) {\n break;\n }\n const curr = `${command}`;\n const next = currentCommandIndex < commands.length - 1 ? commands[currentCommandIndex + 1] : null;\n if (currentPathIndex > 0 && curr === undefined) break;\n if (curr && next && typeof next === 'object' && next.outlets === undefined) {\n if (!compare(curr, next, path)) return noMatch;\n currentCommandIndex += 2;\n } else {\n if (!compare(curr, {}, path)) return noMatch;\n currentCommandIndex++;\n }\n currentPathIndex++;\n }\n return {\n match: true,\n pathIndex: currentPathIndex,\n commandIndex: currentCommandIndex\n };\n}\nfunction createNewSegmentGroup(segmentGroup, startIndex, commands) {\n const paths = segmentGroup.segments.slice(0, startIndex);\n let i = 0;\n while (i < commands.length) {\n const command = commands[i];\n if (isCommandWithOutlets(command)) {\n const children = createNewSegmentChildren(command.outlets);\n return new UrlSegmentGroup(paths, children);\n }\n // if we start with an object literal, we need to reuse the path part from the segment\n if (i === 0 && isMatrixParams(commands[0])) {\n const p = segmentGroup.segments[startIndex];\n paths.push(new UrlSegment(p.path, stringify(commands[0])));\n i++;\n continue;\n }\n const curr = isCommandWithOutlets(command) ? command.outlets[PRIMARY_OUTLET] : `${command}`;\n const next = i < commands.length - 1 ? commands[i + 1] : null;\n if (curr && next && isMatrixParams(next)) {\n paths.push(new UrlSegment(curr, stringify(next)));\n i += 2;\n } else {\n paths.push(new UrlSegment(curr, {}));\n i++;\n }\n }\n return new UrlSegmentGroup(paths, {});\n}\nfunction createNewSegmentChildren(outlets) {\n const children = {};\n Object.entries(outlets).forEach(([outlet, commands]) => {\n if (typeof commands === 'string') {\n commands = [commands];\n }\n if (commands !== null) {\n children[outlet] = createNewSegmentGroup(new UrlSegmentGroup([], {}), 0, commands);\n }\n });\n return children;\n}\nfunction stringify(params) {\n const res = {};\n Object.entries(params).forEach(([k, v]) => res[k] = `${v}`);\n return res;\n}\nfunction compare(path, params, segment) {\n return path == segment.path && shallowEqual(params, segment.parameters);\n}\nconst IMPERATIVE_NAVIGATION = 'imperative';\n/**\n * Identifies the type of a router event.\n *\n * @publicApi\n */\nvar EventType = /*#__PURE__*/function (EventType) {\n EventType[EventType[\"NavigationStart\"] = 0] = \"NavigationStart\";\n EventType[EventType[\"NavigationEnd\"] = 1] = \"NavigationEnd\";\n EventType[EventType[\"NavigationCancel\"] = 2] = \"NavigationCancel\";\n EventType[EventType[\"NavigationError\"] = 3] = \"NavigationError\";\n EventType[EventType[\"RoutesRecognized\"] = 4] = \"RoutesRecognized\";\n EventType[EventType[\"ResolveStart\"] = 5] = \"ResolveStart\";\n EventType[EventType[\"ResolveEnd\"] = 6] = \"ResolveEnd\";\n EventType[EventType[\"GuardsCheckStart\"] = 7] = \"GuardsCheckStart\";\n EventType[EventType[\"GuardsCheckEnd\"] = 8] = \"GuardsCheckEnd\";\n EventType[EventType[\"RouteConfigLoadStart\"] = 9] = \"RouteConfigLoadStart\";\n EventType[EventType[\"RouteConfigLoadEnd\"] = 10] = \"RouteConfigLoadEnd\";\n EventType[EventType[\"ChildActivationStart\"] = 11] = \"ChildActivationStart\";\n EventType[EventType[\"ChildActivationEnd\"] = 12] = \"ChildActivationEnd\";\n EventType[EventType[\"ActivationStart\"] = 13] = \"ActivationStart\";\n EventType[EventType[\"ActivationEnd\"] = 14] = \"ActivationEnd\";\n EventType[EventType[\"Scroll\"] = 15] = \"Scroll\";\n EventType[EventType[\"NavigationSkipped\"] = 16] = \"NavigationSkipped\";\n return EventType;\n}(EventType || {});\n/**\n * Base for events the router goes through, as opposed to events tied to a specific\n * route. Fired one time for any given navigation.\n *\n * The following code shows how a class subscribes to router events.\n *\n * ```ts\n * import {Event, RouterEvent, Router} from '@angular/router';\n *\n * class MyService {\n * constructor(public router: Router) {\n * router.events.pipe(\n * filter((e: Event | RouterEvent): e is RouterEvent => e instanceof RouterEvent)\n * ).subscribe((e: RouterEvent) => {\n * // Do something\n * });\n * }\n * }\n * ```\n *\n * @see {@link Event}\n * @see [Router events summary](guide/routing/router-reference#router-events)\n * @publicApi\n */\nclass RouterEvent {\n id;\n url;\n constructor(/** A unique ID that the router assigns to every router navigation. */\n id, /** The URL that is the destination for this navigation. */\n url) {\n this.id = id;\n this.url = url;\n }\n}\n/**\n * An event triggered when a navigation starts.\n *\n * @publicApi\n */\nclass NavigationStart extends RouterEvent {\n type = EventType.NavigationStart;\n /**\n * Identifies the call or event that triggered the navigation.\n * An `imperative` trigger is a call to `router.navigateByUrl()` or `router.navigate()`.\n *\n * @see {@link NavigationEnd}\n * @see {@link NavigationCancel}\n * @see {@link NavigationError}\n */\n navigationTrigger;\n /**\n * The navigation state that was previously supplied to the `pushState` call,\n * when the navigation is triggered by a `popstate` event. Otherwise null.\n *\n * The state object is defined by `NavigationExtras`, and contains any\n * developer-defined state value, as well as a unique ID that\n * the router assigns to every router transition/navigation.\n *\n * From the perspective of the router, the router never \"goes back\".\n * When the user clicks on the back button in the browser,\n * a new navigation ID is created.\n *\n * Use the ID in this previous-state object to differentiate between a newly created\n * state and one returned to by a `popstate` event, so that you can restore some\n * remembered state, such as scroll position.\n *\n */\n restoredState;\n constructor(/** @docsNotRequired */\n id, /** @docsNotRequired */\n url, /** @docsNotRequired */\n navigationTrigger = 'imperative', /** @docsNotRequired */\n restoredState = null) {\n super(id, url);\n this.navigationTrigger = navigationTrigger;\n this.restoredState = restoredState;\n }\n /** @docsNotRequired */\n toString() {\n return `NavigationStart(id: ${this.id}, url: '${this.url}')`;\n }\n}\n/**\n * An event triggered when a navigation ends successfully.\n *\n * @see {@link NavigationStart}\n * @see {@link NavigationCancel}\n * @see {@link NavigationError}\n *\n * @publicApi\n */\nclass NavigationEnd extends RouterEvent {\n urlAfterRedirects;\n type = EventType.NavigationEnd;\n constructor(/** @docsNotRequired */\n id, /** @docsNotRequired */\n url, /** @docsNotRequired */\n urlAfterRedirects) {\n super(id, url);\n this.urlAfterRedirects = urlAfterRedirects;\n }\n /** @docsNotRequired */\n toString() {\n return `NavigationEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}')`;\n }\n}\n/**\n * A code for the `NavigationCancel` event of the `Router` to indicate the\n * reason a navigation failed.\n *\n * @publicApi\n */\nvar NavigationCancellationCode = /*#__PURE__*/function (NavigationCancellationCode) {\n /**\n * A navigation failed because a guard returned a `UrlTree` to redirect.\n */\n NavigationCancellationCode[NavigationCancellationCode[\"Redirect\"] = 0] = \"Redirect\";\n /**\n * A navigation failed because a more recent navigation started.\n */\n NavigationCancellationCode[NavigationCancellationCode[\"SupersededByNewNavigation\"] = 1] = \"SupersededByNewNavigation\";\n /**\n * A navigation failed because one of the resolvers completed without emitting a value.\n */\n NavigationCancellationCode[NavigationCancellationCode[\"NoDataFromResolver\"] = 2] = \"NoDataFromResolver\";\n /**\n * A navigation failed because a guard returned `false`.\n */\n NavigationCancellationCode[NavigationCancellationCode[\"GuardRejected\"] = 3] = \"GuardRejected\";\n return NavigationCancellationCode;\n}(NavigationCancellationCode || {});\n/**\n * A code for the `NavigationSkipped` event of the `Router` to indicate the\n * reason a navigation was skipped.\n *\n * @publicApi\n */\nvar NavigationSkippedCode = /*#__PURE__*/function (NavigationSkippedCode) {\n /**\n * A navigation was skipped because the navigation URL was the same as the current Router URL.\n */\n NavigationSkippedCode[NavigationSkippedCode[\"IgnoredSameUrlNavigation\"] = 0] = \"IgnoredSameUrlNavigation\";\n /**\n * A navigation was skipped because the configured `UrlHandlingStrategy` return `false` for both\n * the current Router URL and the target of the navigation.\n *\n * @see {@link UrlHandlingStrategy}\n */\n NavigationSkippedCode[NavigationSkippedCode[\"IgnoredByUrlHandlingStrategy\"] = 1] = \"IgnoredByUrlHandlingStrategy\";\n return NavigationSkippedCode;\n}(NavigationSkippedCode || {});\n/**\n * An event triggered when a navigation is canceled, directly or indirectly.\n * This can happen for several reasons including when a route guard\n * returns `false` or initiates a redirect by returning a `UrlTree`.\n *\n * @see {@link NavigationStart}\n * @see {@link NavigationEnd}\n * @see {@link NavigationError}\n *\n * @publicApi\n */\nclass NavigationCancel extends RouterEvent {\n reason;\n code;\n type = EventType.NavigationCancel;\n constructor(/** @docsNotRequired */\n id, /** @docsNotRequired */\n url,\n /**\n * A description of why the navigation was cancelled. For debug purposes only. Use `code`\n * instead for a stable cancellation reason that can be used in production.\n */\n reason,\n /**\n * A code to indicate why the navigation was canceled. This cancellation code is stable for\n * the reason and can be relied on whereas the `reason` string could change and should not be\n * used in production.\n */\n code) {\n super(id, url);\n this.reason = reason;\n this.code = code;\n }\n /** @docsNotRequired */\n toString() {\n return `NavigationCancel(id: ${this.id}, url: '${this.url}')`;\n }\n}\n/**\n * An event triggered when a navigation is skipped.\n * This can happen for a couple reasons including onSameUrlHandling\n * is set to `ignore` and the navigation URL is not different than the\n * current state.\n *\n * @publicApi\n */\nclass NavigationSkipped extends RouterEvent {\n reason;\n code;\n type = EventType.NavigationSkipped;\n constructor(/** @docsNotRequired */\n id, /** @docsNotRequired */\n url,\n /**\n * A description of why the navigation was skipped. For debug purposes only. Use `code`\n * instead for a stable skipped reason that can be used in production.\n */\n reason,\n /**\n * A code to indicate why the navigation was skipped. This code is stable for\n * the reason and can be relied on whereas the `reason` string could change and should not be\n * used in production.\n */\n code) {\n super(id, url);\n this.reason = reason;\n this.code = code;\n }\n}\n/**\n * An event triggered when a navigation fails due to an unexpected error.\n *\n * @see {@link NavigationStart}\n * @see {@link NavigationEnd}\n * @see {@link NavigationCancel}\n *\n * @publicApi\n */\nclass NavigationError extends RouterEvent {\n error;\n target;\n type = EventType.NavigationError;\n constructor(/** @docsNotRequired */\n id, /** @docsNotRequired */\n url, /** @docsNotRequired */\n error,\n /**\n * The target of the navigation when the error occurred.\n *\n * Note that this can be `undefined` because an error could have occurred before the\n * `RouterStateSnapshot` was created for the navigation.\n */\n target) {\n super(id, url);\n this.error = error;\n this.target = target;\n }\n /** @docsNotRequired */\n toString() {\n return `NavigationError(id: ${this.id}, url: '${this.url}', error: ${this.error})`;\n }\n}\n/**\n * An event triggered when routes are recognized.\n *\n * @publicApi\n */\nclass RoutesRecognized extends RouterEvent {\n urlAfterRedirects;\n state;\n type = EventType.RoutesRecognized;\n constructor(/** @docsNotRequired */\n id, /** @docsNotRequired */\n url, /** @docsNotRequired */\n urlAfterRedirects, /** @docsNotRequired */\n state) {\n super(id, url);\n this.urlAfterRedirects = urlAfterRedirects;\n this.state = state;\n }\n /** @docsNotRequired */\n toString() {\n return `RoutesRecognized(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;\n }\n}\n/**\n * An event triggered at the start of the Guard phase of routing.\n *\n * @see {@link GuardsCheckEnd}\n *\n * @publicApi\n */\nclass GuardsCheckStart extends RouterEvent {\n urlAfterRedirects;\n state;\n type = EventType.GuardsCheckStart;\n constructor(/** @docsNotRequired */\n id, /** @docsNotRequired */\n url, /** @docsNotRequired */\n urlAfterRedirects, /** @docsNotRequired */\n state) {\n super(id, url);\n this.urlAfterRedirects = urlAfterRedirects;\n this.state = state;\n }\n toString() {\n return `GuardsCheckStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;\n }\n}\n/**\n * An event triggered at the end of the Guard phase of routing.\n *\n * @see {@link GuardsCheckStart}\n *\n * @publicApi\n */\nclass GuardsCheckEnd extends RouterEvent {\n urlAfterRedirects;\n state;\n shouldActivate;\n type = EventType.GuardsCheckEnd;\n constructor(/** @docsNotRequired */\n id, /** @docsNotRequired */\n url, /** @docsNotRequired */\n urlAfterRedirects, /** @docsNotRequired */\n state, /** @docsNotRequired */\n shouldActivate) {\n super(id, url);\n this.urlAfterRedirects = urlAfterRedirects;\n this.state = state;\n this.shouldActivate = shouldActivate;\n }\n toString() {\n return `GuardsCheckEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state}, shouldActivate: ${this.shouldActivate})`;\n }\n}\n/**\n * An event triggered at the start of the Resolve phase of routing.\n *\n * Runs in the \"resolve\" phase whether or not there is anything to resolve.\n * In future, may change to only run when there are things to be resolved.\n *\n * @see {@link ResolveEnd}\n *\n * @publicApi\n */\nclass ResolveStart extends RouterEvent {\n urlAfterRedirects;\n state;\n type = EventType.ResolveStart;\n constructor(/** @docsNotRequired */\n id, /** @docsNotRequired */\n url, /** @docsNotRequired */\n urlAfterRedirects, /** @docsNotRequired */\n state) {\n super(id, url);\n this.urlAfterRedirects = urlAfterRedirects;\n this.state = state;\n }\n toString() {\n return `ResolveStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;\n }\n}\n/**\n * An event triggered at the end of the Resolve phase of routing.\n * @see {@link ResolveStart}\n *\n * @publicApi\n */\nclass ResolveEnd extends RouterEvent {\n urlAfterRedirects;\n state;\n type = EventType.ResolveEnd;\n constructor(/** @docsNotRequired */\n id, /** @docsNotRequired */\n url, /** @docsNotRequired */\n urlAfterRedirects, /** @docsNotRequired */\n state) {\n super(id, url);\n this.urlAfterRedirects = urlAfterRedirects;\n this.state = state;\n }\n toString() {\n return `ResolveEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;\n }\n}\n/**\n * An event triggered before lazy loading a route configuration.\n *\n * @see {@link RouteConfigLoadEnd}\n *\n * @publicApi\n */\nclass RouteConfigLoadStart {\n route;\n type = EventType.RouteConfigLoadStart;\n constructor(/** @docsNotRequired */\n route) {\n this.route = route;\n }\n toString() {\n return `RouteConfigLoadStart(path: ${this.route.path})`;\n }\n}\n/**\n * An event triggered when a route has been lazy loaded.\n *\n * @see {@link RouteConfigLoadStart}\n *\n * @publicApi\n */\nclass RouteConfigLoadEnd {\n route;\n type = EventType.RouteConfigLoadEnd;\n constructor(/** @docsNotRequired */\n route) {\n this.route = route;\n }\n toString() {\n return `RouteConfigLoadEnd(path: ${this.route.path})`;\n }\n}\n/**\n * An event triggered at the start of the child-activation\n * part of the Resolve phase of routing.\n * @see {@link ChildActivationEnd}\n * @see {@link ResolveStart}\n *\n * @publicApi\n */\nclass ChildActivationStart {\n snapshot;\n type = EventType.ChildActivationStart;\n constructor(/** @docsNotRequired */\n snapshot) {\n this.snapshot = snapshot;\n }\n toString() {\n const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';\n return `ChildActivationStart(path: '${path}')`;\n }\n}\n/**\n * An event triggered at the end of the child-activation part\n * of the Resolve phase of routing.\n * @see {@link ChildActivationStart}\n * @see {@link ResolveStart}\n * @publicApi\n */\nclass ChildActivationEnd {\n snapshot;\n type = EventType.ChildActivationEnd;\n constructor(/** @docsNotRequired */\n snapshot) {\n this.snapshot = snapshot;\n }\n toString() {\n const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';\n return `ChildActivationEnd(path: '${path}')`;\n }\n}\n/**\n * An event triggered at the start of the activation part\n * of the Resolve phase of routing.\n * @see {@link ActivationEnd}\n * @see {@link ResolveStart}\n *\n * @publicApi\n */\nclass ActivationStart {\n snapshot;\n type = EventType.ActivationStart;\n constructor(/** @docsNotRequired */\n snapshot) {\n this.snapshot = snapshot;\n }\n toString() {\n const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';\n return `ActivationStart(path: '${path}')`;\n }\n}\n/**\n * An event triggered at the end of the activation part\n * of the Resolve phase of routing.\n * @see {@link ActivationStart}\n * @see {@link ResolveStart}\n *\n * @publicApi\n */\nclass ActivationEnd {\n snapshot;\n type = EventType.ActivationEnd;\n constructor(/** @docsNotRequired */\n snapshot) {\n this.snapshot = snapshot;\n }\n toString() {\n const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';\n return `ActivationEnd(path: '${path}')`;\n }\n}\n/**\n * An event triggered by scrolling.\n *\n * @publicApi\n */\nclass Scroll {\n routerEvent;\n position;\n anchor;\n type = EventType.Scroll;\n constructor(/** @docsNotRequired */\n routerEvent, /** @docsNotRequired */\n position, /** @docsNotRequired */\n anchor) {\n this.routerEvent = routerEvent;\n this.position = position;\n this.anchor = anchor;\n }\n toString() {\n const pos = this.position ? `${this.position[0]}, ${this.position[1]}` : null;\n return `Scroll(anchor: '${this.anchor}', position: '${pos}')`;\n }\n}\nclass BeforeActivateRoutes {}\nclass RedirectRequest {\n url;\n navigationBehaviorOptions;\n constructor(url, navigationBehaviorOptions) {\n this.url = url;\n this.navigationBehaviorOptions = navigationBehaviorOptions;\n }\n}\nfunction stringifyEvent(routerEvent) {\n switch (routerEvent.type) {\n case EventType.ActivationEnd:\n return `ActivationEnd(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;\n case EventType.ActivationStart:\n return `ActivationStart(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;\n case EventType.ChildActivationEnd:\n return `ChildActivationEnd(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;\n case EventType.ChildActivationStart:\n return `ChildActivationStart(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;\n case EventType.GuardsCheckEnd:\n return `GuardsCheckEnd(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state}, shouldActivate: ${routerEvent.shouldActivate})`;\n case EventType.GuardsCheckStart:\n return `GuardsCheckStart(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;\n case EventType.NavigationCancel:\n return `NavigationCancel(id: ${routerEvent.id}, url: '${routerEvent.url}')`;\n case EventType.NavigationSkipped:\n return `NavigationSkipped(id: ${routerEvent.id}, url: '${routerEvent.url}')`;\n case EventType.NavigationEnd:\n return `NavigationEnd(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}')`;\n case EventType.NavigationError:\n return `NavigationError(id: ${routerEvent.id}, url: '${routerEvent.url}', error: ${routerEvent.error})`;\n case EventType.NavigationStart:\n return `NavigationStart(id: ${routerEvent.id}, url: '${routerEvent.url}')`;\n case EventType.ResolveEnd:\n return `ResolveEnd(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;\n case EventType.ResolveStart:\n return `ResolveStart(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;\n case EventType.RouteConfigLoadEnd:\n return `RouteConfigLoadEnd(path: ${routerEvent.route.path})`;\n case EventType.RouteConfigLoadStart:\n return `RouteConfigLoadStart(path: ${routerEvent.route.path})`;\n case EventType.RoutesRecognized:\n return `RoutesRecognized(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;\n case EventType.Scroll:\n const pos = routerEvent.position ? `${routerEvent.position[0]}, ${routerEvent.position[1]}` : null;\n return `Scroll(anchor: '${routerEvent.anchor}', position: '${pos}')`;\n }\n}\n\n/**\n * Creates an `EnvironmentInjector` if the `Route` has providers and one does not already exist\n * and returns the injector. Otherwise, if the `Route` does not have `providers`, returns the\n * `currentInjector`.\n *\n * @param route The route that might have providers\n * @param currentInjector The parent injector of the `Route`\n */\nfunction getOrCreateRouteInjectorIfNeeded(route, currentInjector) {\n if (route.providers && !route._injector) {\n route._injector = createEnvironmentInjector(route.providers, currentInjector, `Route: ${route.path}`);\n }\n return route._injector ?? currentInjector;\n}\nfunction validateConfig(config, parentPath = '', requireStandaloneComponents = false) {\n // forEach doesn't iterate undefined values\n for (let i = 0; i < config.length; i++) {\n const route = config[i];\n const fullPath = getFullPath(parentPath, route);\n validateNode(route, fullPath, requireStandaloneComponents);\n }\n}\nfunction assertStandalone(fullPath, component) {\n if (component && _isNgModule(component)) {\n throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}'. You are using 'loadComponent' with a module, ` + `but it must be used with standalone components. Use 'loadChildren' instead.`);\n } else if (component && !isStandalone(component)) {\n throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}'. The component must be standalone.`);\n }\n}\nfunction validateNode(route, fullPath, requireStandaloneComponents) {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n if (!route) {\n throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `\n Invalid configuration of route '${fullPath}': Encountered undefined route.\n The reason might be an extra comma.\n\n Example:\n const routes: Routes = [\n { path: '', redirectTo: '/dashboard', pathMatch: 'full' },\n { path: 'dashboard', component: DashboardComponent },, << two commas\n { path: 'detail/:id', component: HeroDetailComponent }\n ];\n `);\n }\n if (Array.isArray(route)) {\n throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': Array cannot be specified`);\n }\n if (!route.redirectTo && !route.component && !route.loadComponent && !route.children && !route.loadChildren && route.outlet && route.outlet !== PRIMARY_OUTLET) {\n throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': a componentless route without children or loadChildren cannot have a named outlet set`);\n }\n if (route.redirectTo && route.children) {\n throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': redirectTo and children cannot be used together`);\n }\n if (route.redirectTo && route.loadChildren) {\n throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': redirectTo and loadChildren cannot be used together`);\n }\n if (route.children && route.loadChildren) {\n throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': children and loadChildren cannot be used together`);\n }\n if (route.redirectTo && (route.component || route.loadComponent)) {\n throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': redirectTo and component/loadComponent cannot be used together`);\n }\n if (route.component && route.loadComponent) {\n throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': component and loadComponent cannot be used together`);\n }\n if (route.redirectTo && route.canActivate) {\n throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': redirectTo and canActivate cannot be used together. Redirects happen before activation ` + `so canActivate will never be executed.`);\n }\n if (route.path && route.matcher) {\n throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': path and matcher cannot be used together`);\n }\n if (route.redirectTo === void 0 && !route.component && !route.loadComponent && !route.children && !route.loadChildren) {\n throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}'. One of the following must be provided: component, loadComponent, redirectTo, children or loadChildren`);\n }\n if (route.path === void 0 && route.matcher === void 0) {\n throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': routes must have either a path or a matcher specified`);\n }\n if (typeof route.path === 'string' && route.path.charAt(0) === '/') {\n throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': path cannot start with a slash`);\n }\n if (route.path === '' && route.redirectTo !== void 0 && route.pathMatch === void 0) {\n const exp = `The default value of 'pathMatch' is 'prefix', but often the intent is to use 'full'.`;\n throw new _RuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '{path: \"${fullPath}\", redirectTo: \"${route.redirectTo}\"}': please provide 'pathMatch'. ${exp}`);\n }\n if (requireStandaloneComponents) {\n assertStandalone(fullPath, route.component);\n }\n }\n if (route.children) {\n validateConfig(route.children, fullPath, requireStandaloneComponents);\n }\n}\nfunction getFullPath(parentPath, currentRoute) {\n if (!currentRoute) {\n return parentPath;\n }\n if (!parentPath && !currentRoute.path) {\n return '';\n } else if (parentPath && !currentRoute.path) {\n return `${parentPath}/`;\n } else if (!parentPath && currentRoute.path) {\n return currentRoute.path;\n } else {\n return `${parentPath}/${currentRoute.path}`;\n }\n}\n/** Returns the `route.outlet` or PRIMARY_OUTLET if none exists. */\nfunction getOutlet(route) {\n return route.outlet || PRIMARY_OUTLET;\n}\n/**\n * Sorts the `routes` such that the ones with an outlet matching `outletName` come first.\n * The order of the configs is otherwise preserved.\n */\nfunction sortByMatchingOutlets(routes, outletName) {\n const sortedConfig = routes.filter(r => getOutlet(r) === outletName);\n sortedConfig.push(...routes.filter(r => getOutlet(r) !== outletName));\n return sortedConfig;\n}\n/**\n * Gets the first injector in the snapshot's parent tree.\n *\n * If the `Route` has a static list of providers, the returned injector will be the one created from\n * those. If it does not exist, the returned injector may come from the parents, which may be from a\n * loaded config or their static providers.\n *\n * Returns `null` if there is neither this nor any parents have a stored injector.\n *\n * Generally used for retrieving the injector to use for getting tokens for guards/resolvers and\n * also used for getting the correct injector to use for creating components.\n */\nfunction getClosestRouteInjector(snapshot) {\n if (!snapshot) return null;\n // If the current route has its own injector, which is created from the static providers on the\n // route itself, we should use that. Otherwise, we start at the parent since we do not want to\n // include the lazy loaded injector from this route.\n if (snapshot.routeConfig?._injector) {\n return snapshot.routeConfig._injector;\n }\n for (let s = snapshot.parent; s; s = s.parent) {\n const route = s.routeConfig;\n // Note that the order here is important. `_loadedInjector` stored on the route with\n // `loadChildren: () => NgModule` so it applies to child routes with priority. The `_injector`\n // is created from the static providers on that parent route, so it applies to the children as\n // well, but only if there is no lazy loaded NgModuleRef injector.\n if (route?._loadedInjector) return route._loadedInjector;\n if (route?._injector) return route._injector;\n }\n return null;\n}\n\n/**\n * Store contextual information about a `RouterOutlet`\n *\n * @publicApi\n */\nclass OutletContext {\n rootInjector;\n outlet = null;\n route = null;\n children;\n attachRef = null;\n get injector() {\n return getClosestRouteInjector(this.route?.snapshot) ?? this.rootInjector;\n }\n constructor(rootInjector) {\n this.rootInjector = rootInjector;\n this.children = new ChildrenOutletContexts(this.rootInjector);\n }\n}\n/**\n * Store contextual information about the children (= nested) `RouterOutlet`\n *\n * @publicApi\n */\nlet ChildrenOutletContexts = /*#__PURE__*/(() => {\n class ChildrenOutletContexts {\n rootInjector;\n // contexts for child outlets, by name.\n contexts = new Map();\n /** @nodoc */\n constructor(rootInjector) {\n this.rootInjector = rootInjector;\n }\n /** Called when a `RouterOutlet` directive is instantiated */\n onChildOutletCreated(childName, outlet) {\n const context = this.getOrCreateContext(childName);\n context.outlet = outlet;\n this.contexts.set(childName, context);\n }\n /**\n * Called when a `RouterOutlet` directive is destroyed.\n * We need to keep the context as the outlet could be destroyed inside a NgIf and might be\n * re-created later.\n */\n onChildOutletDestroyed(childName) {\n const context = this.getContext(childName);\n if (context) {\n context.outlet = null;\n context.attachRef = null;\n }\n }\n /**\n * Called when the corresponding route is deactivated during navigation.\n * Because the component get destroyed, all children outlet are destroyed.\n */\n onOutletDeactivated() {\n const contexts = this.contexts;\n this.contexts = new Map();\n return contexts;\n }\n onOutletReAttached(contexts) {\n this.contexts = contexts;\n }\n getOrCreateContext(childName) {\n let context = this.getContext(childName);\n if (!context) {\n context = new OutletContext(this.rootInjector);\n this.contexts.set(childName, context);\n }\n return context;\n }\n getContext(childName) {\n return this.contexts.get(childName) || null;\n }\n static ɵfac = function ChildrenOutletContexts_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || ChildrenOutletContexts)(i0.ɵɵinject(i0.EnvironmentInjector));\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: ChildrenOutletContexts,\n factory: ChildrenOutletContexts.ɵfac,\n providedIn: 'root'\n });\n }\n return ChildrenOutletContexts;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nclass Tree {\n /** @internal */\n _root;\n constructor(root) {\n this._root = root;\n }\n get root() {\n return this._root.value;\n }\n /**\n * @internal\n */\n parent(t) {\n const p = this.pathFromRoot(t);\n return p.length > 1 ? p[p.length - 2] : null;\n }\n /**\n * @internal\n */\n children(t) {\n const n = findNode(t, this._root);\n return n ? n.children.map(t => t.value) : [];\n }\n /**\n * @internal\n */\n firstChild(t) {\n const n = findNode(t, this._root);\n return n && n.children.length > 0 ? n.children[0].value : null;\n }\n /**\n * @internal\n */\n siblings(t) {\n const p = findPath(t, this._root);\n if (p.length < 2) return [];\n const c = p[p.length - 2].children.map(c => c.value);\n return c.filter(cc => cc !== t);\n }\n /**\n * @internal\n */\n pathFromRoot(t) {\n return findPath(t, this._root).map(s => s.value);\n }\n}\n// DFS for the node matching the value\nfunction findNode(value, node) {\n if (value === node.value) return node;\n for (const child of node.children) {\n const node = findNode(value, child);\n if (node) return node;\n }\n return null;\n}\n// Return the path to the node with the given value using DFS\nfunction findPath(value, node) {\n if (value === node.value) return [node];\n for (const child of node.children) {\n const path = findPath(value, child);\n if (path.length) {\n path.unshift(node);\n return path;\n }\n }\n return [];\n}\nclass TreeNode {\n value;\n children;\n constructor(value, children) {\n this.value = value;\n this.children = children;\n }\n toString() {\n return `TreeNode(${this.value})`;\n }\n}\n// Return the list of T indexed by outlet name\nfunction nodeChildrenAsMap(node) {\n const map = {};\n if (node) {\n node.children.forEach(child => map[child.value.outlet] = child);\n }\n return map;\n}\n\n/**\n * Represents the state of the router as a tree of activated routes.\n *\n * @usageNotes\n *\n * Every node in the route tree is an `ActivatedRoute` instance\n * that knows about the \"consumed\" URL segments, the extracted parameters,\n * and the resolved data.\n * Use the `ActivatedRoute` properties to traverse the tree from any node.\n *\n * The following fragment shows how a component gets the root node\n * of the current state to establish its own route tree:\n *\n * ```ts\n * @Component({templateUrl:'template.html'})\n * class MyComponent {\n * constructor(router: Router) {\n * const state: RouterState = router.routerState;\n * const root: ActivatedRoute = state.root;\n * const child = root.firstChild;\n * const id: Observable = child.params.map(p => p.id);\n * //...\n * }\n * }\n * ```\n *\n * @see {@link ActivatedRoute}\n * @see [Getting route information](guide/routing/common-router-tasks#getting-route-information)\n *\n * @publicApi\n */\nclass RouterState extends Tree {\n snapshot;\n /** @internal */\n constructor(root, /** The current snapshot of the router state */\n snapshot) {\n super(root);\n this.snapshot = snapshot;\n setRouterState(this, root);\n }\n toString() {\n return this.snapshot.toString();\n }\n}\nfunction createEmptyState(rootComponent) {\n const snapshot = createEmptyStateSnapshot(rootComponent);\n const emptyUrl = new BehaviorSubject([new UrlSegment('', {})]);\n const emptyParams = new BehaviorSubject({});\n const emptyData = new BehaviorSubject({});\n const emptyQueryParams = new BehaviorSubject({});\n const fragment = new BehaviorSubject('');\n const activated = new ActivatedRoute(emptyUrl, emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, snapshot.root);\n activated.snapshot = snapshot.root;\n return new RouterState(new TreeNode(activated, []), snapshot);\n}\nfunction createEmptyStateSnapshot(rootComponent) {\n const emptyParams = {};\n const emptyData = {};\n const emptyQueryParams = {};\n const fragment = '';\n const activated = new ActivatedRouteSnapshot([], emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, null, {});\n return new RouterStateSnapshot('', new TreeNode(activated, []));\n}\n/**\n * Provides access to information about a route associated with a component\n * that is loaded in an outlet.\n * Use to traverse the `RouterState` tree and extract information from nodes.\n *\n * The following example shows how to construct a component using information from a\n * currently activated route.\n *\n * Note: the observables in this class only emit when the current and previous values differ based\n * on shallow equality. For example, changing deeply nested properties in resolved `data` will not\n * cause the `ActivatedRoute.data` `Observable` to emit a new value.\n *\n * {@example router/activated-route/module.ts region=\"activated-route\"\n * header=\"activated-route.component.ts\"}\n *\n * @see [Getting route information](guide/routing/common-router-tasks#getting-route-information)\n *\n * @publicApi\n */\nclass ActivatedRoute {\n urlSubject;\n paramsSubject;\n queryParamsSubject;\n fragmentSubject;\n dataSubject;\n outlet;\n component;\n /** The current snapshot of this route */\n snapshot;\n /** @internal */\n _futureSnapshot;\n /** @internal */\n _routerState;\n /** @internal */\n _paramMap;\n /** @internal */\n _queryParamMap;\n /** An Observable of the resolved route title */\n title;\n /** An observable of the URL segments matched by this route. */\n url;\n /** An observable of the matrix parameters scoped to this route. */\n params;\n /** An observable of the query parameters shared by all the routes. */\n queryParams;\n /** An observable of the URL fragment shared by all the routes. */\n fragment;\n /** An observable of the static and resolved data of this route. */\n data;\n /** @internal */\n constructor(/** @internal */\n urlSubject, /** @internal */\n paramsSubject, /** @internal */\n queryParamsSubject, /** @internal */\n fragmentSubject, /** @internal */\n dataSubject, /** The outlet name of the route, a constant. */\n outlet, /** The component of the route, a constant. */\n component, futureSnapshot) {\n this.urlSubject = urlSubject;\n this.paramsSubject = paramsSubject;\n this.queryParamsSubject = queryParamsSubject;\n this.fragmentSubject = fragmentSubject;\n this.dataSubject = dataSubject;\n this.outlet = outlet;\n this.component = component;\n this._futureSnapshot = futureSnapshot;\n this.title = this.dataSubject?.pipe(map(d => d[RouteTitleKey])) ?? of(undefined);\n // TODO(atscott): Verify that these can be changed to `.asObservable()` with TGP.\n this.url = urlSubject;\n this.params = paramsSubject;\n this.queryParams = queryParamsSubject;\n this.fragment = fragmentSubject;\n this.data = dataSubject;\n }\n /** The configuration used to match this route. */\n get routeConfig() {\n return this._futureSnapshot.routeConfig;\n }\n /** The root of the router state. */\n get root() {\n return this._routerState.root;\n }\n /** The parent of this route in the router state tree. */\n get parent() {\n return this._routerState.parent(this);\n }\n /** The first child of this route in the router state tree. */\n get firstChild() {\n return this._routerState.firstChild(this);\n }\n /** The children of this route in the router state tree. */\n get children() {\n return this._routerState.children(this);\n }\n /** The path from the root of the router state tree to this route. */\n get pathFromRoot() {\n return this._routerState.pathFromRoot(this);\n }\n /**\n * An Observable that contains a map of the required and optional parameters\n * specific to the route.\n * The map supports retrieving single and multiple values from the same parameter.\n */\n get paramMap() {\n this._paramMap ??= this.params.pipe(map(p => convertToParamMap(p)));\n return this._paramMap;\n }\n /**\n * An Observable that contains a map of the query parameters available to all routes.\n * The map supports retrieving single and multiple values from the query parameter.\n */\n get queryParamMap() {\n this._queryParamMap ??= this.queryParams.pipe(map(p => convertToParamMap(p)));\n return this._queryParamMap;\n }\n toString() {\n return this.snapshot ? this.snapshot.toString() : `Future(${this._futureSnapshot})`;\n }\n}\n/**\n * Returns the inherited params, data, and resolve for a given route.\n *\n * By default, we do not inherit parent data unless the current route is path-less or the parent\n * route is component-less.\n */\nfunction getInherited(route, parent, paramsInheritanceStrategy = 'emptyOnly') {\n let inherited;\n const {\n routeConfig\n } = route;\n if (parent !== null && (paramsInheritanceStrategy === 'always' ||\n // inherit parent data if route is empty path\n routeConfig?.path === '' ||\n // inherit parent data if parent was componentless\n !parent.component && !parent.routeConfig?.loadComponent)) {\n inherited = {\n params: {\n ...parent.params,\n ...route.params\n },\n data: {\n ...parent.data,\n ...route.data\n },\n resolve: {\n // Snapshots are created with data inherited from parent and guards (i.e. canActivate) can\n // change data because it's not frozen...\n // This first line could be deleted chose to break/disallow mutating the `data` object in\n // guards.\n // Note that data from parents still override this mutated data so anyone relying on this\n // might be surprised that it doesn't work if parent data is inherited but otherwise does.\n ...route.data,\n // Ensure inherited resolved data overrides inherited static data\n ...parent.data,\n // static data from the current route overrides any inherited data\n ...routeConfig?.data,\n // resolved data from current route overrides everything\n ...route._resolvedData\n }\n };\n } else {\n inherited = {\n params: {\n ...route.params\n },\n data: {\n ...route.data\n },\n resolve: {\n ...route.data,\n ...(route._resolvedData ?? {})\n }\n };\n }\n if (routeConfig && hasStaticTitle(routeConfig)) {\n inherited.resolve[RouteTitleKey] = routeConfig.title;\n }\n return inherited;\n}\n/**\n * @description\n *\n * Contains the information about a route associated with a component loaded in an\n * outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to\n * traverse the router state tree.\n *\n * The following example initializes a component with route information extracted\n * from the snapshot of the root node at the time of creation.\n *\n * ```ts\n * @Component({templateUrl:'./my-component.html'})\n * class MyComponent {\n * constructor(route: ActivatedRoute) {\n * const id: string = route.snapshot.params.id;\n * const url: string = route.snapshot.url.join('');\n * const user = route.snapshot.data.user;\n * }\n * }\n * ```\n *\n * @publicApi\n */\nclass ActivatedRouteSnapshot {\n url;\n params;\n queryParams;\n fragment;\n data;\n outlet;\n component;\n /** The configuration used to match this route **/\n routeConfig;\n /** @internal */\n _resolve;\n /** @internal */\n _resolvedData;\n /** @internal */\n _routerState;\n /** @internal */\n _paramMap;\n /** @internal */\n _queryParamMap;\n /** The resolved route title */\n get title() {\n // Note: This _must_ be a getter because the data is mutated in the resolvers. Title will not be\n // available at the time of class instantiation.\n return this.data?.[RouteTitleKey];\n }\n /** @internal */\n constructor(/** The URL segments matched by this route */\n url,\n /**\n * The matrix parameters scoped to this route.\n *\n * You can compute all params (or data) in the router state or to get params outside\n * of an activated component by traversing the `RouterState` tree as in the following\n * example:\n * ```ts\n * collectRouteParams(router: Router) {\n * let params = {};\n * let stack: ActivatedRouteSnapshot[] = [router.routerState.snapshot.root];\n * while (stack.length > 0) {\n * const route = stack.pop()!;\n * params = {...params, ...route.params};\n * stack.push(...route.children);\n * }\n * return params;\n * }\n * ```\n */\n params, /** The query parameters shared by all the routes */\n queryParams, /** The URL fragment shared by all the routes */\n fragment, /** The static and resolved data of this route */\n data, /** The outlet name of the route */\n outlet, /** The component of the route */\n component, routeConfig, resolve) {\n this.url = url;\n this.params = params;\n this.queryParams = queryParams;\n this.fragment = fragment;\n this.data = data;\n this.outlet = outlet;\n this.component = component;\n this.routeConfig = routeConfig;\n this._resolve = resolve;\n }\n /** The root of the router state */\n get root() {\n return this._routerState.root;\n }\n /** The parent of this route in the router state tree */\n get parent() {\n return this._routerState.parent(this);\n }\n /** The first child of this route in the router state tree */\n get firstChild() {\n return this._routerState.firstChild(this);\n }\n /** The children of this route in the router state tree */\n get children() {\n return this._routerState.children(this);\n }\n /** The path from the root of the router state tree to this route */\n get pathFromRoot() {\n return this._routerState.pathFromRoot(this);\n }\n get paramMap() {\n this._paramMap ??= convertToParamMap(this.params);\n return this._paramMap;\n }\n get queryParamMap() {\n this._queryParamMap ??= convertToParamMap(this.queryParams);\n return this._queryParamMap;\n }\n toString() {\n const url = this.url.map(segment => segment.toString()).join('/');\n const matched = this.routeConfig ? this.routeConfig.path : '';\n return `Route(url:'${url}', path:'${matched}')`;\n }\n}\n/**\n * @description\n *\n * Represents the state of the router at a moment in time.\n *\n * This is a tree of activated route snapshots. Every node in this tree knows about\n * the \"consumed\" URL segments, the extracted parameters, and the resolved data.\n *\n * The following example shows how a component is initialized with information\n * from the snapshot of the root node's state at the time of creation.\n *\n * ```ts\n * @Component({templateUrl:'template.html'})\n * class MyComponent {\n * constructor(router: Router) {\n * const state: RouterState = router.routerState;\n * const snapshot: RouterStateSnapshot = state.snapshot;\n * const root: ActivatedRouteSnapshot = snapshot.root;\n * const child = root.firstChild;\n * const id: Observable = child.params.map(p => p.id);\n * //...\n * }\n * }\n * ```\n *\n * @publicApi\n */\nclass RouterStateSnapshot extends Tree {\n url;\n /** @internal */\n constructor(/** The url from which this snapshot was created */\n url, root) {\n super(root);\n this.url = url;\n setRouterState(this, root);\n }\n toString() {\n return serializeNode(this._root);\n }\n}\nfunction setRouterState(state, node) {\n node.value._routerState = state;\n node.children.forEach(c => setRouterState(state, c));\n}\nfunction serializeNode(node) {\n const c = node.children.length > 0 ? ` { ${node.children.map(serializeNode).join(', ')} } ` : '';\n return `${node.value}${c}`;\n}\n/**\n * The expectation is that the activate route is created with the right set of parameters.\n * So we push new values into the observables only when they are not the initial values.\n * And we detect that by checking if the snapshot field is set.\n */\nfunction advanceActivatedRoute(route) {\n if (route.snapshot) {\n const currentSnapshot = route.snapshot;\n const nextSnapshot = route._futureSnapshot;\n route.snapshot = nextSnapshot;\n if (!shallowEqual(currentSnapshot.queryParams, nextSnapshot.queryParams)) {\n route.queryParamsSubject.next(nextSnapshot.queryParams);\n }\n if (currentSnapshot.fragment !== nextSnapshot.fragment) {\n route.fragmentSubject.next(nextSnapshot.fragment);\n }\n if (!shallowEqual(currentSnapshot.params, nextSnapshot.params)) {\n route.paramsSubject.next(nextSnapshot.params);\n }\n if (!shallowEqualArrays(currentSnapshot.url, nextSnapshot.url)) {\n route.urlSubject.next(nextSnapshot.url);\n }\n if (!shallowEqual(currentSnapshot.data, nextSnapshot.data)) {\n route.dataSubject.next(nextSnapshot.data);\n }\n } else {\n route.snapshot = route._futureSnapshot;\n // this is for resolved data\n route.dataSubject.next(route._futureSnapshot.data);\n }\n}\nfunction equalParamsAndUrlSegments(a, b) {\n const equalUrlParams = shallowEqual(a.params, b.params) && equalSegments(a.url, b.url);\n const parentsMismatch = !a.parent !== !b.parent;\n return equalUrlParams && !parentsMismatch && (!a.parent || equalParamsAndUrlSegments(a.parent, b.parent));\n}\nfunction hasStaticTitle(config) {\n return typeof config.title === 'string' || config.title === null;\n}\n\n/**\n * An `InjectionToken` provided by the `RouterOutlet` and can be set using the `routerOutletData`\n * input.\n *\n * When unset, this value is `null` by default.\n *\n * @usageNotes\n *\n * To set the data from the template of the component with `router-outlet`:\n * ```html\n * \n * ```\n *\n * To read the data in the routed component:\n * ```ts\n * data = inject(ROUTER_OUTLET_DATA) as Signal<{name: string}>;\n * ```\n *\n * @publicApi\n */\nconst ROUTER_OUTLET_DATA = /*#__PURE__*/new InjectionToken(ngDevMode ? 'RouterOutlet data' : '');\n/**\n * @description\n *\n * Acts as a placeholder that Angular dynamically fills based on the current router state.\n *\n * Each outlet can have a unique name, determined by the optional `name` attribute.\n * The name cannot be set or changed dynamically. If not set, default value is \"primary\".\n *\n * ```html\n * \n * \n * \n * ```\n *\n * Named outlets can be the targets of secondary routes.\n * The `Route` object for a secondary route has an `outlet` property to identify the target outlet:\n *\n * `{path: , component: , outlet: }`\n *\n * Using named outlets and secondary routes, you can target multiple outlets in\n * the same `RouterLink` directive.\n *\n * The router keeps track of separate branches in a navigation tree for each named outlet and\n * generates a representation of that tree in the URL.\n * The URL for a secondary route uses the following syntax to specify both the primary and secondary\n * routes at the same time:\n *\n * `http://base-path/primary-route-path(outlet-name:route-path)`\n *\n * A router outlet emits an activate event when a new component is instantiated,\n * deactivate event when a component is destroyed.\n * An attached event emits when the `RouteReuseStrategy` instructs the outlet to reattach the\n * subtree, and the detached event emits when the `RouteReuseStrategy` instructs the outlet to\n * detach the subtree.\n *\n * ```html\n * \n * ```\n *\n * @see {@link RouterLink}\n * @see {@link Route}\n * @ngModule RouterModule\n *\n * @publicApi\n */\nlet RouterOutlet = /*#__PURE__*/(() => {\n class RouterOutlet {\n activated = null;\n /** @internal */\n get activatedComponentRef() {\n return this.activated;\n }\n _activatedRoute = null;\n /**\n * The name of the outlet\n *\n */\n name = PRIMARY_OUTLET;\n activateEvents = new EventEmitter();\n deactivateEvents = new EventEmitter();\n /**\n * Emits an attached component instance when the `RouteReuseStrategy` instructs to re-attach a\n * previously detached subtree.\n **/\n attachEvents = new EventEmitter();\n /**\n * Emits a detached component instance when the `RouteReuseStrategy` instructs to detach the\n * subtree.\n */\n detachEvents = new EventEmitter();\n /**\n * Data that will be provided to the child injector through the `ROUTER_OUTLET_DATA` token.\n *\n * When unset, the value of the token is `undefined` by default.\n */\n routerOutletData = input(undefined);\n parentContexts = inject(ChildrenOutletContexts);\n location = inject(ViewContainerRef);\n changeDetector = inject(ChangeDetectorRef);\n inputBinder = inject(INPUT_BINDER, {\n optional: true\n });\n /** @nodoc */\n supportsBindingToComponentInputs = true;\n /** @nodoc */\n ngOnChanges(changes) {\n if (changes['name']) {\n const {\n firstChange,\n previousValue\n } = changes['name'];\n if (firstChange) {\n // The first change is handled by ngOnInit. Because ngOnChanges doesn't get called when no\n // input is set at all, we need to centrally handle the first change there.\n return;\n }\n // unregister with the old name\n if (this.isTrackedInParentContexts(previousValue)) {\n this.deactivate();\n this.parentContexts.onChildOutletDestroyed(previousValue);\n }\n // register the new name\n this.initializeOutletWithName();\n }\n }\n /** @nodoc */\n ngOnDestroy() {\n // Ensure that the registered outlet is this one before removing it on the context.\n if (this.isTrackedInParentContexts(this.name)) {\n this.parentContexts.onChildOutletDestroyed(this.name);\n }\n this.inputBinder?.unsubscribeFromRouteData(this);\n }\n isTrackedInParentContexts(outletName) {\n return this.parentContexts.getContext(outletName)?.outlet === this;\n }\n /** @nodoc */\n ngOnInit() {\n this.initializeOutletWithName();\n }\n initializeOutletWithName() {\n this.parentContexts.onChildOutletCreated(this.name, this);\n if (this.activated) {\n return;\n }\n // If the outlet was not instantiated at the time the route got activated we need to populate\n // the outlet when it is initialized (ie inside a NgIf)\n const context = this.parentContexts.getContext(this.name);\n if (context?.route) {\n if (context.attachRef) {\n // `attachRef` is populated when there is an existing component to mount\n this.attach(context.attachRef, context.route);\n } else {\n // otherwise the component defined in the configuration is created\n this.activateWith(context.route, context.injector);\n }\n }\n }\n get isActivated() {\n return !!this.activated;\n }\n /**\n * @returns The currently activated component instance.\n * @throws An error if the outlet is not activated.\n */\n get component() {\n if (!this.activated) throw new _RuntimeError(4012 /* RuntimeErrorCode.OUTLET_NOT_ACTIVATED */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated');\n return this.activated.instance;\n }\n get activatedRoute() {\n if (!this.activated) throw new _RuntimeError(4012 /* RuntimeErrorCode.OUTLET_NOT_ACTIVATED */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated');\n return this._activatedRoute;\n }\n get activatedRouteData() {\n if (this._activatedRoute) {\n return this._activatedRoute.snapshot.data;\n }\n return {};\n }\n /**\n * Called when the `RouteReuseStrategy` instructs to detach the subtree\n */\n detach() {\n if (!this.activated) throw new _RuntimeError(4012 /* RuntimeErrorCode.OUTLET_NOT_ACTIVATED */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated');\n this.location.detach();\n const cmp = this.activated;\n this.activated = null;\n this._activatedRoute = null;\n this.detachEvents.emit(cmp.instance);\n return cmp;\n }\n /**\n * Called when the `RouteReuseStrategy` instructs to re-attach a previously detached subtree\n */\n attach(ref, activatedRoute) {\n this.activated = ref;\n this._activatedRoute = activatedRoute;\n this.location.insert(ref.hostView);\n this.inputBinder?.bindActivatedRouteToOutletComponent(this);\n this.attachEvents.emit(ref.instance);\n }\n deactivate() {\n if (this.activated) {\n const c = this.component;\n this.activated.destroy();\n this.activated = null;\n this._activatedRoute = null;\n this.deactivateEvents.emit(c);\n }\n }\n activateWith(activatedRoute, environmentInjector) {\n if (this.isActivated) {\n throw new _RuntimeError(4013 /* RuntimeErrorCode.OUTLET_ALREADY_ACTIVATED */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Cannot activate an already activated outlet');\n }\n this._activatedRoute = activatedRoute;\n const location = this.location;\n const snapshot = activatedRoute.snapshot;\n const component = snapshot.component;\n const childContexts = this.parentContexts.getOrCreateContext(this.name).children;\n const injector = new OutletInjector(activatedRoute, childContexts, location.injector, this.routerOutletData);\n this.activated = location.createComponent(component, {\n index: location.length,\n injector,\n environmentInjector: environmentInjector\n });\n // Calling `markForCheck` to make sure we will run the change detection when the\n // `RouterOutlet` is inside a `ChangeDetectionStrategy.OnPush` component.\n this.changeDetector.markForCheck();\n this.inputBinder?.bindActivatedRouteToOutletComponent(this);\n this.activateEvents.emit(this.activated.instance);\n }\n static ɵfac = function RouterOutlet_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || RouterOutlet)();\n };\n static ɵdir = /* @__PURE__ */i0.ɵɵdefineDirective({\n type: RouterOutlet,\n selectors: [[\"router-outlet\"]],\n inputs: {\n name: \"name\",\n routerOutletData: [1, \"routerOutletData\"]\n },\n outputs: {\n activateEvents: \"activate\",\n deactivateEvents: \"deactivate\",\n attachEvents: \"attach\",\n detachEvents: \"detach\"\n },\n exportAs: [\"outlet\"],\n features: [i0.ɵɵNgOnChangesFeature]\n });\n }\n return RouterOutlet;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nclass OutletInjector {\n route;\n childContexts;\n parent;\n outletData;\n constructor(route, childContexts, parent, outletData) {\n this.route = route;\n this.childContexts = childContexts;\n this.parent = parent;\n this.outletData = outletData;\n }\n get(token, notFoundValue) {\n if (token === ActivatedRoute) {\n return this.route;\n }\n if (token === ChildrenOutletContexts) {\n return this.childContexts;\n }\n if (token === ROUTER_OUTLET_DATA) {\n return this.outletData;\n }\n return this.parent.get(token, notFoundValue);\n }\n}\nconst INPUT_BINDER = /*#__PURE__*/new InjectionToken('');\n/**\n * Injectable used as a tree-shakable provider for opting in to binding router data to component\n * inputs.\n *\n * The RouterOutlet registers itself with this service when an `ActivatedRoute` is attached or\n * activated. When this happens, the service subscribes to the `ActivatedRoute` observables (params,\n * queryParams, data) and sets the inputs of the component using `ComponentRef.setInput`.\n * Importantly, when an input does not have an item in the route data with a matching key, this\n * input is set to `undefined`. If it were not done this way, the previous information would be\n * retained if the data got removed from the route (i.e. if a query parameter is removed).\n *\n * The `RouterOutlet` should unregister itself when destroyed via `unsubscribeFromRouteData` so that\n * the subscriptions are cleaned up.\n */\nlet RoutedComponentInputBinder = /*#__PURE__*/(() => {\n class RoutedComponentInputBinder {\n outletDataSubscriptions = new Map();\n bindActivatedRouteToOutletComponent(outlet) {\n this.unsubscribeFromRouteData(outlet);\n this.subscribeToRouteData(outlet);\n }\n unsubscribeFromRouteData(outlet) {\n this.outletDataSubscriptions.get(outlet)?.unsubscribe();\n this.outletDataSubscriptions.delete(outlet);\n }\n subscribeToRouteData(outlet) {\n const {\n activatedRoute\n } = outlet;\n const dataSubscription = combineLatest([activatedRoute.queryParams, activatedRoute.params, activatedRoute.data]).pipe(switchMap(([queryParams, params, data], index) => {\n data = {\n ...queryParams,\n ...params,\n ...data\n };\n // Get the first result from the data subscription synchronously so it's available to\n // the component as soon as possible (and doesn't require a second change detection).\n if (index === 0) {\n return of(data);\n }\n // Promise.resolve is used to avoid synchronously writing the wrong data when\n // two of the Observables in the `combineLatest` stream emit one after\n // another.\n return Promise.resolve(data);\n })).subscribe(data => {\n // Outlet may have been deactivated or changed names to be associated with a different\n // route\n if (!outlet.isActivated || !outlet.activatedComponentRef || outlet.activatedRoute !== activatedRoute || activatedRoute.component === null) {\n this.unsubscribeFromRouteData(outlet);\n return;\n }\n const mirror = reflectComponentType(activatedRoute.component);\n if (!mirror) {\n this.unsubscribeFromRouteData(outlet);\n return;\n }\n for (const {\n templateName\n } of mirror.inputs) {\n outlet.activatedComponentRef.setInput(templateName, data[templateName]);\n }\n });\n this.outletDataSubscriptions.set(outlet, dataSubscription);\n }\n static ɵfac = function RoutedComponentInputBinder_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || RoutedComponentInputBinder)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: RoutedComponentInputBinder,\n factory: RoutedComponentInputBinder.ɵfac\n });\n }\n return RoutedComponentInputBinder;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nfunction createRouterState(routeReuseStrategy, curr, prevState) {\n const root = createNode(routeReuseStrategy, curr._root, prevState ? prevState._root : undefined);\n return new RouterState(root, curr);\n}\nfunction createNode(routeReuseStrategy, curr, prevState) {\n // reuse an activated route that is currently displayed on the screen\n if (prevState && routeReuseStrategy.shouldReuseRoute(curr.value, prevState.value.snapshot)) {\n const value = prevState.value;\n value._futureSnapshot = curr.value;\n const children = createOrReuseChildren(routeReuseStrategy, curr, prevState);\n return new TreeNode(value, children);\n } else {\n if (routeReuseStrategy.shouldAttach(curr.value)) {\n // retrieve an activated route that is used to be displayed, but is not currently displayed\n const detachedRouteHandle = routeReuseStrategy.retrieve(curr.value);\n if (detachedRouteHandle !== null) {\n const tree = detachedRouteHandle.route;\n tree.value._futureSnapshot = curr.value;\n tree.children = curr.children.map(c => createNode(routeReuseStrategy, c));\n return tree;\n }\n }\n const value = createActivatedRoute(curr.value);\n const children = curr.children.map(c => createNode(routeReuseStrategy, c));\n return new TreeNode(value, children);\n }\n}\nfunction createOrReuseChildren(routeReuseStrategy, curr, prevState) {\n return curr.children.map(child => {\n for (const p of prevState.children) {\n if (routeReuseStrategy.shouldReuseRoute(child.value, p.value.snapshot)) {\n return createNode(routeReuseStrategy, child, p);\n }\n }\n return createNode(routeReuseStrategy, child);\n });\n}\nfunction createActivatedRoute(c) {\n return new ActivatedRoute(new BehaviorSubject(c.url), new BehaviorSubject(c.params), new BehaviorSubject(c.queryParams), new BehaviorSubject(c.fragment), new BehaviorSubject(c.data), c.outlet, c.component, c);\n}\n\n/**\n * Can be returned by a `Router` guard to instruct the `Router` to redirect rather than continue\n * processing the path of the in-flight navigation. The `redirectTo` indicates _where_ the new\n * navigation should go to and the optional `navigationBehaviorOptions` can provide more information\n * about _how_ to perform the navigation.\n *\n * ```ts\n * const route: Route = {\n * path: \"user/:userId\",\n * component: User,\n * canActivate: [\n * () => {\n * const router = inject(Router);\n * const authService = inject(AuthenticationService);\n *\n * if (!authService.isLoggedIn()) {\n * const loginPath = router.parseUrl(\"/login\");\n * return new RedirectCommand(loginPath, {\n * skipLocationChange: \"true\",\n * });\n * }\n *\n * return true;\n * },\n * ],\n * };\n * ```\n * @see [Routing guide](guide/routing/common-router-tasks#preventing-unauthorized-access)\n *\n * @publicApi\n */\nclass RedirectCommand {\n redirectTo;\n navigationBehaviorOptions;\n constructor(redirectTo, navigationBehaviorOptions) {\n this.redirectTo = redirectTo;\n this.navigationBehaviorOptions = navigationBehaviorOptions;\n }\n}\nconst NAVIGATION_CANCELING_ERROR = 'ngNavigationCancelingError';\nfunction redirectingNavigationError(urlSerializer, redirect) {\n const {\n redirectTo,\n navigationBehaviorOptions\n } = isUrlTree(redirect) ? {\n redirectTo: redirect,\n navigationBehaviorOptions: undefined\n } : redirect;\n const error = navigationCancelingError(ngDevMode && `Redirecting to \"${urlSerializer.serialize(redirectTo)}\"`, NavigationCancellationCode.Redirect);\n error.url = redirectTo;\n error.navigationBehaviorOptions = navigationBehaviorOptions;\n return error;\n}\nfunction navigationCancelingError(message, code) {\n const error = new Error(`NavigationCancelingError: ${message || ''}`);\n error[NAVIGATION_CANCELING_ERROR] = true;\n error.cancellationCode = code;\n return error;\n}\nfunction isRedirectingNavigationCancelingError(error) {\n return isNavigationCancelingError(error) && isUrlTree(error.url);\n}\nfunction isNavigationCancelingError(error) {\n return !!error && error[NAVIGATION_CANCELING_ERROR];\n}\nlet warnedAboutUnsupportedInputBinding = false;\nconst activateRoutes = (rootContexts, routeReuseStrategy, forwardEvent, inputBindingEnabled) => map(t => {\n new ActivateRoutes(routeReuseStrategy, t.targetRouterState, t.currentRouterState, forwardEvent, inputBindingEnabled).activate(rootContexts);\n return t;\n});\nclass ActivateRoutes {\n routeReuseStrategy;\n futureState;\n currState;\n forwardEvent;\n inputBindingEnabled;\n constructor(routeReuseStrategy, futureState, currState, forwardEvent, inputBindingEnabled) {\n this.routeReuseStrategy = routeReuseStrategy;\n this.futureState = futureState;\n this.currState = currState;\n this.forwardEvent = forwardEvent;\n this.inputBindingEnabled = inputBindingEnabled;\n }\n activate(parentContexts) {\n const futureRoot = this.futureState._root;\n const currRoot = this.currState ? this.currState._root : null;\n this.deactivateChildRoutes(futureRoot, currRoot, parentContexts);\n advanceActivatedRoute(this.futureState.root);\n this.activateChildRoutes(futureRoot, currRoot, parentContexts);\n }\n // De-activate the child route that are not re-used for the future state\n deactivateChildRoutes(futureNode, currNode, contexts) {\n const children = nodeChildrenAsMap(currNode);\n // Recurse on the routes active in the future state to de-activate deeper children\n futureNode.children.forEach(futureChild => {\n const childOutletName = futureChild.value.outlet;\n this.deactivateRoutes(futureChild, children[childOutletName], contexts);\n delete children[childOutletName];\n });\n // De-activate the routes that will not be re-used\n Object.values(children).forEach(v => {\n this.deactivateRouteAndItsChildren(v, contexts);\n });\n }\n deactivateRoutes(futureNode, currNode, parentContext) {\n const future = futureNode.value;\n const curr = currNode ? currNode.value : null;\n if (future === curr) {\n // Reusing the node, check to see if the children need to be de-activated\n if (future.component) {\n // If we have a normal route, we need to go through an outlet.\n const context = parentContext.getContext(future.outlet);\n if (context) {\n this.deactivateChildRoutes(futureNode, currNode, context.children);\n }\n } else {\n // if we have a componentless route, we recurse but keep the same outlet map.\n this.deactivateChildRoutes(futureNode, currNode, parentContext);\n }\n } else {\n if (curr) {\n // Deactivate the current route which will not be re-used\n this.deactivateRouteAndItsChildren(currNode, parentContext);\n }\n }\n }\n deactivateRouteAndItsChildren(route, parentContexts) {\n // If there is no component, the Route is never attached to an outlet (because there is no\n // component to attach).\n if (route.value.component && this.routeReuseStrategy.shouldDetach(route.value.snapshot)) {\n this.detachAndStoreRouteSubtree(route, parentContexts);\n } else {\n this.deactivateRouteAndOutlet(route, parentContexts);\n }\n }\n detachAndStoreRouteSubtree(route, parentContexts) {\n const context = parentContexts.getContext(route.value.outlet);\n const contexts = context && route.value.component ? context.children : parentContexts;\n const children = nodeChildrenAsMap(route);\n for (const treeNode of Object.values(children)) {\n this.deactivateRouteAndItsChildren(treeNode, contexts);\n }\n if (context && context.outlet) {\n const componentRef = context.outlet.detach();\n const contexts = context.children.onOutletDeactivated();\n this.routeReuseStrategy.store(route.value.snapshot, {\n componentRef,\n route,\n contexts\n });\n }\n }\n deactivateRouteAndOutlet(route, parentContexts) {\n const context = parentContexts.getContext(route.value.outlet);\n // The context could be `null` if we are on a componentless route but there may still be\n // children that need deactivating.\n const contexts = context && route.value.component ? context.children : parentContexts;\n const children = nodeChildrenAsMap(route);\n for (const treeNode of Object.values(children)) {\n this.deactivateRouteAndItsChildren(treeNode, contexts);\n }\n if (context) {\n if (context.outlet) {\n // Destroy the component\n context.outlet.deactivate();\n // Destroy the contexts for all the outlets that were in the component\n context.children.onOutletDeactivated();\n }\n // Clear the information about the attached component on the context but keep the reference to\n // the outlet. Clear even if outlet was not yet activated to avoid activating later with old\n // info\n context.attachRef = null;\n context.route = null;\n }\n }\n activateChildRoutes(futureNode, currNode, contexts) {\n const children = nodeChildrenAsMap(currNode);\n futureNode.children.forEach(c => {\n this.activateRoutes(c, children[c.value.outlet], contexts);\n this.forwardEvent(new ActivationEnd(c.value.snapshot));\n });\n if (futureNode.children.length) {\n this.forwardEvent(new ChildActivationEnd(futureNode.value.snapshot));\n }\n }\n activateRoutes(futureNode, currNode, parentContexts) {\n const future = futureNode.value;\n const curr = currNode ? currNode.value : null;\n advanceActivatedRoute(future);\n // reusing the node\n if (future === curr) {\n if (future.component) {\n // If we have a normal route, we need to go through an outlet.\n const context = parentContexts.getOrCreateContext(future.outlet);\n this.activateChildRoutes(futureNode, currNode, context.children);\n } else {\n // if we have a componentless route, we recurse but keep the same outlet map.\n this.activateChildRoutes(futureNode, currNode, parentContexts);\n }\n } else {\n if (future.component) {\n // if we have a normal route, we need to place the component into the outlet and recurse.\n const context = parentContexts.getOrCreateContext(future.outlet);\n if (this.routeReuseStrategy.shouldAttach(future.snapshot)) {\n const stored = this.routeReuseStrategy.retrieve(future.snapshot);\n this.routeReuseStrategy.store(future.snapshot, null);\n context.children.onOutletReAttached(stored.contexts);\n context.attachRef = stored.componentRef;\n context.route = stored.route.value;\n if (context.outlet) {\n // Attach right away when the outlet has already been instantiated\n // Otherwise attach from `RouterOutlet.ngOnInit` when it is instantiated\n context.outlet.attach(stored.componentRef, stored.route.value);\n }\n advanceActivatedRoute(stored.route.value);\n this.activateChildRoutes(futureNode, null, context.children);\n } else {\n context.attachRef = null;\n context.route = future;\n if (context.outlet) {\n // Activate the outlet when it has already been instantiated\n // Otherwise it will get activated from its `ngOnInit` when instantiated\n context.outlet.activateWith(future, context.injector);\n }\n this.activateChildRoutes(futureNode, null, context.children);\n }\n } else {\n // if we have a componentless route, we recurse but keep the same outlet map.\n this.activateChildRoutes(futureNode, null, parentContexts);\n }\n }\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n const context = parentContexts.getOrCreateContext(future.outlet);\n const outlet = context.outlet;\n if (outlet && this.inputBindingEnabled && !outlet.supportsBindingToComponentInputs && !warnedAboutUnsupportedInputBinding) {\n console.warn(`'withComponentInputBinding' feature is enabled but ` + `this application is using an outlet that may not support binding to component inputs.`);\n warnedAboutUnsupportedInputBinding = true;\n }\n }\n }\n}\nclass CanActivate {\n path;\n route;\n constructor(path) {\n this.path = path;\n this.route = this.path[this.path.length - 1];\n }\n}\nclass CanDeactivate {\n component;\n route;\n constructor(component, route) {\n this.component = component;\n this.route = route;\n }\n}\nfunction getAllRouteGuards(future, curr, parentContexts) {\n const futureRoot = future._root;\n const currRoot = curr ? curr._root : null;\n return getChildRouteGuards(futureRoot, currRoot, parentContexts, [futureRoot.value]);\n}\nfunction getCanActivateChild(p) {\n const canActivateChild = p.routeConfig ? p.routeConfig.canActivateChild : null;\n if (!canActivateChild || canActivateChild.length === 0) return null;\n return {\n node: p,\n guards: canActivateChild\n };\n}\nfunction getTokenOrFunctionIdentity(tokenOrFunction, injector) {\n const NOT_FOUND = Symbol();\n const result = injector.get(tokenOrFunction, NOT_FOUND);\n if (result === NOT_FOUND) {\n if (typeof tokenOrFunction === 'function' && !_isInjectable(tokenOrFunction)) {\n // We think the token is just a function so return it as-is\n return tokenOrFunction;\n } else {\n // This will throw the not found error\n return injector.get(tokenOrFunction);\n }\n }\n return result;\n}\nfunction getChildRouteGuards(futureNode, currNode, contexts, futurePath, checks = {\n canDeactivateChecks: [],\n canActivateChecks: []\n}) {\n const prevChildren = nodeChildrenAsMap(currNode);\n // Process the children of the future route\n futureNode.children.forEach(c => {\n getRouteGuards(c, prevChildren[c.value.outlet], contexts, futurePath.concat([c.value]), checks);\n delete prevChildren[c.value.outlet];\n });\n // Process any children left from the current route (not active for the future route)\n Object.entries(prevChildren).forEach(([k, v]) => deactivateRouteAndItsChildren(v, contexts.getContext(k), checks));\n return checks;\n}\nfunction getRouteGuards(futureNode, currNode, parentContexts, futurePath, checks = {\n canDeactivateChecks: [],\n canActivateChecks: []\n}) {\n const future = futureNode.value;\n const curr = currNode ? currNode.value : null;\n const context = parentContexts ? parentContexts.getContext(futureNode.value.outlet) : null;\n // reusing the node\n if (curr && future.routeConfig === curr.routeConfig) {\n const shouldRun = shouldRunGuardsAndResolvers(curr, future, future.routeConfig.runGuardsAndResolvers);\n if (shouldRun) {\n checks.canActivateChecks.push(new CanActivate(futurePath));\n } else {\n // we need to set the data\n future.data = curr.data;\n future._resolvedData = curr._resolvedData;\n }\n // If we have a component, we need to go through an outlet.\n if (future.component) {\n getChildRouteGuards(futureNode, currNode, context ? context.children : null, futurePath, checks);\n // if we have a componentless route, we recurse but keep the same outlet map.\n } else {\n getChildRouteGuards(futureNode, currNode, parentContexts, futurePath, checks);\n }\n if (shouldRun && context && context.outlet && context.outlet.isActivated) {\n checks.canDeactivateChecks.push(new CanDeactivate(context.outlet.component, curr));\n }\n } else {\n if (curr) {\n deactivateRouteAndItsChildren(currNode, context, checks);\n }\n checks.canActivateChecks.push(new CanActivate(futurePath));\n // If we have a component, we need to go through an outlet.\n if (future.component) {\n getChildRouteGuards(futureNode, null, context ? context.children : null, futurePath, checks);\n // if we have a componentless route, we recurse but keep the same outlet map.\n } else {\n getChildRouteGuards(futureNode, null, parentContexts, futurePath, checks);\n }\n }\n return checks;\n}\nfunction shouldRunGuardsAndResolvers(curr, future, mode) {\n if (typeof mode === 'function') {\n return mode(curr, future);\n }\n switch (mode) {\n case 'pathParamsChange':\n return !equalPath(curr.url, future.url);\n case 'pathParamsOrQueryParamsChange':\n return !equalPath(curr.url, future.url) || !shallowEqual(curr.queryParams, future.queryParams);\n case 'always':\n return true;\n case 'paramsOrQueryParamsChange':\n return !equalParamsAndUrlSegments(curr, future) || !shallowEqual(curr.queryParams, future.queryParams);\n case 'paramsChange':\n default:\n return !equalParamsAndUrlSegments(curr, future);\n }\n}\nfunction deactivateRouteAndItsChildren(route, context, checks) {\n const children = nodeChildrenAsMap(route);\n const r = route.value;\n Object.entries(children).forEach(([childName, node]) => {\n if (!r.component) {\n deactivateRouteAndItsChildren(node, context, checks);\n } else if (context) {\n deactivateRouteAndItsChildren(node, context.children.getContext(childName), checks);\n } else {\n deactivateRouteAndItsChildren(node, null, checks);\n }\n });\n if (!r.component) {\n checks.canDeactivateChecks.push(new CanDeactivate(null, r));\n } else if (context && context.outlet && context.outlet.isActivated) {\n checks.canDeactivateChecks.push(new CanDeactivate(context.outlet.component, r));\n } else {\n checks.canDeactivateChecks.push(new CanDeactivate(null, r));\n }\n}\n\n/**\n * Simple function check, but generic so type inference will flow. Example:\n *\n * function product(a: number, b: number) {\n * return a * b;\n * }\n *\n * if (isFunction(fn)) {\n * return fn(1, 2);\n * } else {\n * throw \"Must provide the `product` function\";\n * }\n */\nfunction isFunction(v) {\n return typeof v === 'function';\n}\nfunction isBoolean(v) {\n return typeof v === 'boolean';\n}\nfunction isCanLoad(guard) {\n return guard && isFunction(guard.canLoad);\n}\nfunction isCanActivate(guard) {\n return guard && isFunction(guard.canActivate);\n}\nfunction isCanActivateChild(guard) {\n return guard && isFunction(guard.canActivateChild);\n}\nfunction isCanDeactivate(guard) {\n return guard && isFunction(guard.canDeactivate);\n}\nfunction isCanMatch(guard) {\n return guard && isFunction(guard.canMatch);\n}\nfunction isEmptyError(e) {\n return e instanceof EmptyError || e?.name === 'EmptyError';\n}\nconst INITIAL_VALUE = /* @__PURE__ */Symbol('INITIAL_VALUE');\nfunction prioritizedGuardValue() {\n return switchMap(obs => {\n return combineLatest(obs.map(o => o.pipe(take(1), startWith(INITIAL_VALUE)))).pipe(map(results => {\n for (const result of results) {\n if (result === true) {\n // If result is true, check the next one\n continue;\n } else if (result === INITIAL_VALUE) {\n // If guard has not finished, we need to stop processing.\n return INITIAL_VALUE;\n } else if (result === false || isRedirect(result)) {\n // Result finished and was not true. Return the result.\n // Note that we only allow false/UrlTree/RedirectCommand. Other values are considered invalid and\n // ignored.\n return result;\n }\n }\n // Everything resolved to true. Return true.\n return true;\n }), filter(item => item !== INITIAL_VALUE), take(1));\n });\n}\nfunction isRedirect(val) {\n return isUrlTree(val) || val instanceof RedirectCommand;\n}\nfunction checkGuards(injector, forwardEvent) {\n return mergeMap(t => {\n const {\n targetSnapshot,\n currentSnapshot,\n guards: {\n canActivateChecks,\n canDeactivateChecks\n }\n } = t;\n if (canDeactivateChecks.length === 0 && canActivateChecks.length === 0) {\n return of({\n ...t,\n guardsResult: true\n });\n }\n return runCanDeactivateChecks(canDeactivateChecks, targetSnapshot, currentSnapshot, injector).pipe(mergeMap(canDeactivate => {\n return canDeactivate && isBoolean(canDeactivate) ? runCanActivateChecks(targetSnapshot, canActivateChecks, injector, forwardEvent) : of(canDeactivate);\n }), map(guardsResult => ({\n ...t,\n guardsResult\n })));\n });\n}\nfunction runCanDeactivateChecks(checks, futureRSS, currRSS, injector) {\n return from(checks).pipe(mergeMap(check => runCanDeactivate(check.component, check.route, currRSS, futureRSS, injector)), first(result => {\n return result !== true;\n }, true));\n}\nfunction runCanActivateChecks(futureSnapshot, checks, injector, forwardEvent) {\n return from(checks).pipe(concatMap(check => {\n return concat(fireChildActivationStart(check.route.parent, forwardEvent), fireActivationStart(check.route, forwardEvent), runCanActivateChild(futureSnapshot, check.path, injector), runCanActivate(futureSnapshot, check.route, injector));\n }), first(result => {\n return result !== true;\n }, true));\n}\n/**\n * This should fire off `ActivationStart` events for each route being activated at this\n * level.\n * In other words, if you're activating `a` and `b` below, `path` will contain the\n * `ActivatedRouteSnapshot`s for both and we will fire `ActivationStart` for both. Always\n * return\n * `true` so checks continue to run.\n */\nfunction fireActivationStart(snapshot, forwardEvent) {\n if (snapshot !== null && forwardEvent) {\n forwardEvent(new ActivationStart(snapshot));\n }\n return of(true);\n}\n/**\n * This should fire off `ChildActivationStart` events for each route being activated at this\n * level.\n * In other words, if you're activating `a` and `b` below, `path` will contain the\n * `ActivatedRouteSnapshot`s for both and we will fire `ChildActivationStart` for both. Always\n * return\n * `true` so checks continue to run.\n */\nfunction fireChildActivationStart(snapshot, forwardEvent) {\n if (snapshot !== null && forwardEvent) {\n forwardEvent(new ChildActivationStart(snapshot));\n }\n return of(true);\n}\nfunction runCanActivate(futureRSS, futureARS, injector) {\n const canActivate = futureARS.routeConfig ? futureARS.routeConfig.canActivate : null;\n if (!canActivate || canActivate.length === 0) return of(true);\n const canActivateObservables = canActivate.map(canActivate => {\n return defer(() => {\n const closestInjector = getClosestRouteInjector(futureARS) ?? injector;\n const guard = getTokenOrFunctionIdentity(canActivate, closestInjector);\n const guardVal = isCanActivate(guard) ? guard.canActivate(futureARS, futureRSS) : runInInjectionContext(closestInjector, () => guard(futureARS, futureRSS));\n return wrapIntoObservable(guardVal).pipe(first());\n });\n });\n return of(canActivateObservables).pipe(prioritizedGuardValue());\n}\nfunction runCanActivateChild(futureRSS, path, injector) {\n const futureARS = path[path.length - 1];\n const canActivateChildGuards = path.slice(0, path.length - 1).reverse().map(p => getCanActivateChild(p)).filter(_ => _ !== null);\n const canActivateChildGuardsMapped = canActivateChildGuards.map(d => {\n return defer(() => {\n const guardsMapped = d.guards.map(canActivateChild => {\n const closestInjector = getClosestRouteInjector(d.node) ?? injector;\n const guard = getTokenOrFunctionIdentity(canActivateChild, closestInjector);\n const guardVal = isCanActivateChild(guard) ? guard.canActivateChild(futureARS, futureRSS) : runInInjectionContext(closestInjector, () => guard(futureARS, futureRSS));\n return wrapIntoObservable(guardVal).pipe(first());\n });\n return of(guardsMapped).pipe(prioritizedGuardValue());\n });\n });\n return of(canActivateChildGuardsMapped).pipe(prioritizedGuardValue());\n}\nfunction runCanDeactivate(component, currARS, currRSS, futureRSS, injector) {\n const canDeactivate = currARS && currARS.routeConfig ? currARS.routeConfig.canDeactivate : null;\n if (!canDeactivate || canDeactivate.length === 0) return of(true);\n const canDeactivateObservables = canDeactivate.map(c => {\n const closestInjector = getClosestRouteInjector(currARS) ?? injector;\n const guard = getTokenOrFunctionIdentity(c, closestInjector);\n const guardVal = isCanDeactivate(guard) ? guard.canDeactivate(component, currARS, currRSS, futureRSS) : runInInjectionContext(closestInjector, () => guard(component, currARS, currRSS, futureRSS));\n return wrapIntoObservable(guardVal).pipe(first());\n });\n return of(canDeactivateObservables).pipe(prioritizedGuardValue());\n}\nfunction runCanLoadGuards(injector, route, segments, urlSerializer) {\n const canLoad = route.canLoad;\n if (canLoad === undefined || canLoad.length === 0) {\n return of(true);\n }\n const canLoadObservables = canLoad.map(injectionToken => {\n const guard = getTokenOrFunctionIdentity(injectionToken, injector);\n const guardVal = isCanLoad(guard) ? guard.canLoad(route, segments) : runInInjectionContext(injector, () => guard(route, segments));\n return wrapIntoObservable(guardVal);\n });\n return of(canLoadObservables).pipe(prioritizedGuardValue(), redirectIfUrlTree(urlSerializer));\n}\nfunction redirectIfUrlTree(urlSerializer) {\n return pipe(tap(result => {\n if (typeof result === 'boolean') return;\n throw redirectingNavigationError(urlSerializer, result);\n }), map(result => result === true));\n}\nfunction runCanMatchGuards(injector, route, segments, urlSerializer) {\n const canMatch = route.canMatch;\n if (!canMatch || canMatch.length === 0) return of(true);\n const canMatchObservables = canMatch.map(injectionToken => {\n const guard = getTokenOrFunctionIdentity(injectionToken, injector);\n const guardVal = isCanMatch(guard) ? guard.canMatch(route, segments) : runInInjectionContext(injector, () => guard(route, segments));\n return wrapIntoObservable(guardVal);\n });\n return of(canMatchObservables).pipe(prioritizedGuardValue(), redirectIfUrlTree(urlSerializer));\n}\nclass NoMatch {\n segmentGroup;\n constructor(segmentGroup) {\n this.segmentGroup = segmentGroup || null;\n }\n}\nclass AbsoluteRedirect extends Error {\n urlTree;\n constructor(urlTree) {\n super();\n this.urlTree = urlTree;\n }\n}\nfunction noMatch$1(segmentGroup) {\n return throwError(new NoMatch(segmentGroup));\n}\nfunction namedOutletsRedirect(redirectTo) {\n return throwError(new _RuntimeError(4000 /* RuntimeErrorCode.NAMED_OUTLET_REDIRECT */, (typeof ngDevMode === 'undefined' || ngDevMode) && `Only absolute redirects can have named outlets. redirectTo: '${redirectTo}'`));\n}\nfunction canLoadFails(route) {\n return throwError(navigationCancelingError((typeof ngDevMode === 'undefined' || ngDevMode) && `Cannot load children because the guard of the route \"path: '${route.path}'\" returned false`, NavigationCancellationCode.GuardRejected));\n}\nclass ApplyRedirects {\n urlSerializer;\n urlTree;\n constructor(urlSerializer, urlTree) {\n this.urlSerializer = urlSerializer;\n this.urlTree = urlTree;\n }\n lineralizeSegments(route, urlTree) {\n let res = [];\n let c = urlTree.root;\n while (true) {\n res = res.concat(c.segments);\n if (c.numberOfChildren === 0) {\n return of(res);\n }\n if (c.numberOfChildren > 1 || !c.children[PRIMARY_OUTLET]) {\n return namedOutletsRedirect(`${route.redirectTo}`);\n }\n c = c.children[PRIMARY_OUTLET];\n }\n }\n applyRedirectCommands(segments, redirectTo, posParams, currentSnapshot, injector) {\n if (typeof redirectTo !== 'string') {\n const redirectToFn = redirectTo;\n const {\n queryParams,\n fragment,\n routeConfig,\n url,\n outlet,\n params,\n data,\n title\n } = currentSnapshot;\n const newRedirect = runInInjectionContext(injector, () => redirectToFn({\n params,\n data,\n queryParams,\n fragment,\n routeConfig,\n url,\n outlet,\n title\n }));\n if (newRedirect instanceof UrlTree) {\n throw new AbsoluteRedirect(newRedirect);\n }\n redirectTo = newRedirect;\n }\n const newTree = this.applyRedirectCreateUrlTree(redirectTo, this.urlSerializer.parse(redirectTo), segments, posParams);\n if (redirectTo[0] === '/') {\n throw new AbsoluteRedirect(newTree);\n }\n return newTree;\n }\n applyRedirectCreateUrlTree(redirectTo, urlTree, segments, posParams) {\n const newRoot = this.createSegmentGroup(redirectTo, urlTree.root, segments, posParams);\n return new UrlTree(newRoot, this.createQueryParams(urlTree.queryParams, this.urlTree.queryParams), urlTree.fragment);\n }\n createQueryParams(redirectToParams, actualParams) {\n const res = {};\n Object.entries(redirectToParams).forEach(([k, v]) => {\n const copySourceValue = typeof v === 'string' && v[0] === ':';\n if (copySourceValue) {\n const sourceName = v.substring(1);\n res[k] = actualParams[sourceName];\n } else {\n res[k] = v;\n }\n });\n return res;\n }\n createSegmentGroup(redirectTo, group, segments, posParams) {\n const updatedSegments = this.createSegments(redirectTo, group.segments, segments, posParams);\n let children = {};\n Object.entries(group.children).forEach(([name, child]) => {\n children[name] = this.createSegmentGroup(redirectTo, child, segments, posParams);\n });\n return new UrlSegmentGroup(updatedSegments, children);\n }\n createSegments(redirectTo, redirectToSegments, actualSegments, posParams) {\n return redirectToSegments.map(s => s.path[0] === ':' ? this.findPosParam(redirectTo, s, posParams) : this.findOrReturn(s, actualSegments));\n }\n findPosParam(redirectTo, redirectToUrlSegment, posParams) {\n const pos = posParams[redirectToUrlSegment.path.substring(1)];\n if (!pos) throw new _RuntimeError(4001 /* RuntimeErrorCode.MISSING_REDIRECT */, (typeof ngDevMode === 'undefined' || ngDevMode) && `Cannot redirect to '${redirectTo}'. Cannot find '${redirectToUrlSegment.path}'.`);\n return pos;\n }\n findOrReturn(redirectToUrlSegment, actualSegments) {\n let idx = 0;\n for (const s of actualSegments) {\n if (s.path === redirectToUrlSegment.path) {\n actualSegments.splice(idx);\n return s;\n }\n idx++;\n }\n return redirectToUrlSegment;\n }\n}\nconst noMatch = {\n matched: false,\n consumedSegments: [],\n remainingSegments: [],\n parameters: {},\n positionalParamSegments: {}\n};\nfunction matchWithChecks(segmentGroup, route, segments, injector, urlSerializer) {\n const result = match(segmentGroup, route, segments);\n if (!result.matched) {\n return of(result);\n }\n // Only create the Route's `EnvironmentInjector` if it matches the attempted\n // navigation\n injector = getOrCreateRouteInjectorIfNeeded(route, injector);\n return runCanMatchGuards(injector, route, segments, urlSerializer).pipe(map(v => v === true ? result : {\n ...noMatch\n }));\n}\nfunction match(segmentGroup, route, segments) {\n if (route.path === '**') {\n return createWildcardMatchResult(segments);\n }\n if (route.path === '') {\n if (route.pathMatch === 'full' && (segmentGroup.hasChildren() || segments.length > 0)) {\n return {\n ...noMatch\n };\n }\n return {\n matched: true,\n consumedSegments: [],\n remainingSegments: segments,\n parameters: {},\n positionalParamSegments: {}\n };\n }\n const matcher = route.matcher || defaultUrlMatcher;\n const res = matcher(segments, segmentGroup, route);\n if (!res) return {\n ...noMatch\n };\n const posParams = {};\n Object.entries(res.posParams ?? {}).forEach(([k, v]) => {\n posParams[k] = v.path;\n });\n const parameters = res.consumed.length > 0 ? {\n ...posParams,\n ...res.consumed[res.consumed.length - 1].parameters\n } : posParams;\n return {\n matched: true,\n consumedSegments: res.consumed,\n remainingSegments: segments.slice(res.consumed.length),\n // TODO(atscott): investigate combining parameters and positionalParamSegments\n parameters,\n positionalParamSegments: res.posParams ?? {}\n };\n}\nfunction createWildcardMatchResult(segments) {\n return {\n matched: true,\n parameters: segments.length > 0 ? last(segments).parameters : {},\n consumedSegments: segments,\n remainingSegments: [],\n positionalParamSegments: {}\n };\n}\nfunction split(segmentGroup, consumedSegments, slicedSegments, config) {\n if (slicedSegments.length > 0 && containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, config)) {\n const s = new UrlSegmentGroup(consumedSegments, createChildrenForEmptyPaths(config, new UrlSegmentGroup(slicedSegments, segmentGroup.children)));\n return {\n segmentGroup: s,\n slicedSegments: []\n };\n }\n if (slicedSegments.length === 0 && containsEmptyPathMatches(segmentGroup, slicedSegments, config)) {\n const s = new UrlSegmentGroup(segmentGroup.segments, addEmptyPathsToChildrenIfNeeded(segmentGroup, slicedSegments, config, segmentGroup.children));\n return {\n segmentGroup: s,\n slicedSegments\n };\n }\n const s = new UrlSegmentGroup(segmentGroup.segments, segmentGroup.children);\n return {\n segmentGroup: s,\n slicedSegments\n };\n}\nfunction addEmptyPathsToChildrenIfNeeded(segmentGroup, slicedSegments, routes, children) {\n const res = {};\n for (const r of routes) {\n if (emptyPathMatch(segmentGroup, slicedSegments, r) && !children[getOutlet(r)]) {\n const s = new UrlSegmentGroup([], {});\n res[getOutlet(r)] = s;\n }\n }\n return {\n ...children,\n ...res\n };\n}\nfunction createChildrenForEmptyPaths(routes, primarySegment) {\n const res = {};\n res[PRIMARY_OUTLET] = primarySegment;\n for (const r of routes) {\n if (r.path === '' && getOutlet(r) !== PRIMARY_OUTLET) {\n const s = new UrlSegmentGroup([], {});\n res[getOutlet(r)] = s;\n }\n }\n return res;\n}\nfunction containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, routes) {\n return routes.some(r => emptyPathMatch(segmentGroup, slicedSegments, r) && getOutlet(r) !== PRIMARY_OUTLET);\n}\nfunction containsEmptyPathMatches(segmentGroup, slicedSegments, routes) {\n return routes.some(r => emptyPathMatch(segmentGroup, slicedSegments, r));\n}\nfunction emptyPathMatch(segmentGroup, slicedSegments, r) {\n if ((segmentGroup.hasChildren() || slicedSegments.length > 0) && r.pathMatch === 'full') {\n return false;\n }\n return r.path === '';\n}\nfunction noLeftoversInUrl(segmentGroup, segments, outlet) {\n return segments.length === 0 && !segmentGroup.children[outlet];\n}\n\n/**\n * Class used to indicate there were no additional route config matches but that all segments of\n * the URL were consumed during matching so the route was URL matched. When this happens, we still\n * try to match child configs in case there are empty path children.\n */\nclass NoLeftoversInUrl {}\nfunction recognize$1(injector, configLoader, rootComponentType, config, urlTree, urlSerializer, paramsInheritanceStrategy = 'emptyOnly') {\n return new Recognizer(injector, configLoader, rootComponentType, config, urlTree, paramsInheritanceStrategy, urlSerializer).recognize();\n}\nconst MAX_ALLOWED_REDIRECTS = 31;\nclass Recognizer {\n injector;\n configLoader;\n rootComponentType;\n config;\n urlTree;\n paramsInheritanceStrategy;\n urlSerializer;\n applyRedirects;\n absoluteRedirectCount = 0;\n allowRedirects = true;\n constructor(injector, configLoader, rootComponentType, config, urlTree, paramsInheritanceStrategy, urlSerializer) {\n this.injector = injector;\n this.configLoader = configLoader;\n this.rootComponentType = rootComponentType;\n this.config = config;\n this.urlTree = urlTree;\n this.paramsInheritanceStrategy = paramsInheritanceStrategy;\n this.urlSerializer = urlSerializer;\n this.applyRedirects = new ApplyRedirects(this.urlSerializer, this.urlTree);\n }\n noMatchError(e) {\n return new _RuntimeError(4002 /* RuntimeErrorCode.NO_MATCH */, typeof ngDevMode === 'undefined' || ngDevMode ? `Cannot match any routes. URL Segment: '${e.segmentGroup}'` : `'${e.segmentGroup}'`);\n }\n recognize() {\n const rootSegmentGroup = split(this.urlTree.root, [], [], this.config).segmentGroup;\n return this.match(rootSegmentGroup).pipe(map(({\n children,\n rootSnapshot\n }) => {\n const rootNode = new TreeNode(rootSnapshot, children);\n const routeState = new RouterStateSnapshot('', rootNode);\n const tree = createUrlTreeFromSnapshot(rootSnapshot, [], this.urlTree.queryParams, this.urlTree.fragment);\n // https://github.com/angular/angular/issues/47307\n // Creating the tree stringifies the query params\n // We don't want to do this here so reassign them to the original.\n tree.queryParams = this.urlTree.queryParams;\n routeState.url = this.urlSerializer.serialize(tree);\n return {\n state: routeState,\n tree\n };\n }));\n }\n match(rootSegmentGroup) {\n // Use Object.freeze to prevent readers of the Router state from modifying it outside\n // of a navigation, resulting in the router being out of sync with the browser.\n const rootSnapshot = new ActivatedRouteSnapshot([], Object.freeze({}), Object.freeze({\n ...this.urlTree.queryParams\n }), this.urlTree.fragment, Object.freeze({}), PRIMARY_OUTLET, this.rootComponentType, null, {});\n return this.processSegmentGroup(this.injector, this.config, rootSegmentGroup, PRIMARY_OUTLET, rootSnapshot).pipe(map(children => {\n return {\n children,\n rootSnapshot\n };\n }), catchError(e => {\n if (e instanceof AbsoluteRedirect) {\n this.urlTree = e.urlTree;\n return this.match(e.urlTree.root);\n }\n if (e instanceof NoMatch) {\n throw this.noMatchError(e);\n }\n throw e;\n }));\n }\n processSegmentGroup(injector, config, segmentGroup, outlet, parentRoute) {\n if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {\n return this.processChildren(injector, config, segmentGroup, parentRoute);\n }\n return this.processSegment(injector, config, segmentGroup, segmentGroup.segments, outlet, true, parentRoute).pipe(map(child => child instanceof TreeNode ? [child] : []));\n }\n /**\n * Matches every child outlet in the `segmentGroup` to a `Route` in the config. Returns `null` if\n * we cannot find a match for _any_ of the children.\n *\n * @param config - The `Routes` to match against\n * @param segmentGroup - The `UrlSegmentGroup` whose children need to be matched against the\n * config.\n */\n processChildren(injector, config, segmentGroup, parentRoute) {\n // Expand outlets one at a time, starting with the primary outlet. We need to do it this way\n // because an absolute redirect from the primary outlet takes precedence.\n const childOutlets = [];\n for (const child of Object.keys(segmentGroup.children)) {\n if (child === 'primary') {\n childOutlets.unshift(child);\n } else {\n childOutlets.push(child);\n }\n }\n return from(childOutlets).pipe(concatMap(childOutlet => {\n const child = segmentGroup.children[childOutlet];\n // Sort the config so that routes with outlets that match the one being activated\n // appear first, followed by routes for other outlets, which might match if they have\n // an empty path.\n const sortedConfig = sortByMatchingOutlets(config, childOutlet);\n return this.processSegmentGroup(injector, sortedConfig, child, childOutlet, parentRoute);\n }), scan((children, outletChildren) => {\n children.push(...outletChildren);\n return children;\n }), defaultIfEmpty(null), last$1(), mergeMap(children => {\n if (children === null) return noMatch$1(segmentGroup);\n // Because we may have matched two outlets to the same empty path segment, we can have\n // multiple activated results for the same outlet. We should merge the children of\n // these results so the final return value is only one `TreeNode` per outlet.\n const mergedChildren = mergeEmptyPathMatches(children);\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n // This should really never happen - we are only taking the first match for each\n // outlet and merge the empty path matches.\n checkOutletNameUniqueness(mergedChildren);\n }\n sortActivatedRouteSnapshots(mergedChildren);\n return of(mergedChildren);\n }));\n }\n processSegment(injector, routes, segmentGroup, segments, outlet, allowRedirects, parentRoute) {\n return from(routes).pipe(concatMap(r => {\n return this.processSegmentAgainstRoute(r._injector ?? injector, routes, r, segmentGroup, segments, outlet, allowRedirects, parentRoute).pipe(catchError(e => {\n if (e instanceof NoMatch) {\n return of(null);\n }\n throw e;\n }));\n }), first(x => !!x), catchError(e => {\n if (isEmptyError(e)) {\n if (noLeftoversInUrl(segmentGroup, segments, outlet)) {\n return of(new NoLeftoversInUrl());\n }\n return noMatch$1(segmentGroup);\n }\n throw e;\n }));\n }\n processSegmentAgainstRoute(injector, routes, route, rawSegment, segments, outlet, allowRedirects, parentRoute) {\n // We allow matches to empty paths when the outlets differ so we can match a url like `/(b:b)` to\n // a config like\n // * `{path: '', children: [{path: 'b', outlet: 'b'}]}`\n // or even\n // * `{path: '', outlet: 'a', children: [{path: 'b', outlet: 'b'}]`\n //\n // The exception here is when the segment outlet is for the primary outlet. This would\n // result in a match inside the named outlet because all children there are written as primary\n // outlets. So we need to prevent child named outlet matches in a url like `/b` in a config like\n // * `{path: '', outlet: 'x' children: [{path: 'b'}]}`\n // This should only match if the url is `/(x:b)`.\n if (getOutlet(route) !== outlet && (outlet === PRIMARY_OUTLET || !emptyPathMatch(rawSegment, segments, route))) {\n return noMatch$1(rawSegment);\n }\n if (route.redirectTo === undefined) {\n return this.matchSegmentAgainstRoute(injector, rawSegment, route, segments, outlet, parentRoute);\n }\n if (this.allowRedirects && allowRedirects) {\n return this.expandSegmentAgainstRouteUsingRedirect(injector, rawSegment, routes, route, segments, outlet, parentRoute);\n }\n return noMatch$1(rawSegment);\n }\n expandSegmentAgainstRouteUsingRedirect(injector, segmentGroup, routes, route, segments, outlet, parentRoute) {\n const {\n matched,\n parameters,\n consumedSegments,\n positionalParamSegments,\n remainingSegments\n } = match(segmentGroup, route, segments);\n if (!matched) return noMatch$1(segmentGroup);\n // TODO(atscott): Move all of this under an if(ngDevMode) as a breaking change and allow stack\n // size exceeded in production\n if (typeof route.redirectTo === 'string' && route.redirectTo[0] === '/') {\n this.absoluteRedirectCount++;\n if (this.absoluteRedirectCount > MAX_ALLOWED_REDIRECTS) {\n if (ngDevMode) {\n throw new _RuntimeError(4016 /* RuntimeErrorCode.INFINITE_REDIRECT */, `Detected possible infinite redirect when redirecting from '${this.urlTree}' to '${route.redirectTo}'.\\n` + `This is currently a dev mode only error but will become a` + ` call stack size exceeded error in production in a future major version.`);\n }\n this.allowRedirects = false;\n }\n }\n const currentSnapshot = new ActivatedRouteSnapshot(segments, parameters, Object.freeze({\n ...this.urlTree.queryParams\n }), this.urlTree.fragment, getData(route), getOutlet(route), route.component ?? route._loadedComponent ?? null, route, getResolve(route));\n const inherited = getInherited(currentSnapshot, parentRoute, this.paramsInheritanceStrategy);\n currentSnapshot.params = Object.freeze(inherited.params);\n currentSnapshot.data = Object.freeze(inherited.data);\n const newTree = this.applyRedirects.applyRedirectCommands(consumedSegments, route.redirectTo, positionalParamSegments, currentSnapshot, injector);\n return this.applyRedirects.lineralizeSegments(route, newTree).pipe(mergeMap(newSegments => {\n return this.processSegment(injector, routes, segmentGroup, newSegments.concat(remainingSegments), outlet, false, parentRoute);\n }));\n }\n matchSegmentAgainstRoute(injector, rawSegment, route, segments, outlet, parentRoute) {\n const matchResult = matchWithChecks(rawSegment, route, segments, injector, this.urlSerializer);\n if (route.path === '**') {\n // Prior versions of the route matching algorithm would stop matching at the wildcard route.\n // We should investigate a better strategy for any existing children. Otherwise, these\n // child segments are silently dropped from the navigation.\n // https://github.com/angular/angular/issues/40089\n rawSegment.children = {};\n }\n return matchResult.pipe(switchMap(result => {\n if (!result.matched) {\n return noMatch$1(rawSegment);\n }\n // If the route has an injector created from providers, we should start using that.\n injector = route._injector ?? injector;\n return this.getChildConfig(injector, route, segments).pipe(switchMap(({\n routes: childConfig\n }) => {\n const childInjector = route._loadedInjector ?? injector;\n const {\n parameters,\n consumedSegments,\n remainingSegments\n } = result;\n const snapshot = new ActivatedRouteSnapshot(consumedSegments, parameters, Object.freeze({\n ...this.urlTree.queryParams\n }), this.urlTree.fragment, getData(route), getOutlet(route), route.component ?? route._loadedComponent ?? null, route, getResolve(route));\n const inherited = getInherited(snapshot, parentRoute, this.paramsInheritanceStrategy);\n snapshot.params = Object.freeze(inherited.params);\n snapshot.data = Object.freeze(inherited.data);\n const {\n segmentGroup,\n slicedSegments\n } = split(rawSegment, consumedSegments, remainingSegments, childConfig);\n if (slicedSegments.length === 0 && segmentGroup.hasChildren()) {\n return this.processChildren(childInjector, childConfig, segmentGroup, snapshot).pipe(map(children => {\n return new TreeNode(snapshot, children);\n }));\n }\n if (childConfig.length === 0 && slicedSegments.length === 0) {\n return of(new TreeNode(snapshot, []));\n }\n const matchedOnOutlet = getOutlet(route) === outlet;\n // If we matched a config due to empty path match on a different outlet, we need to\n // continue passing the current outlet for the segment rather than switch to PRIMARY.\n // Note that we switch to primary when we have a match because outlet configs look like\n // this: {path: 'a', outlet: 'a', children: [\n // {path: 'b', component: B},\n // {path: 'c', component: C},\n // ]}\n // Notice that the children of the named outlet are configured with the primary outlet\n return this.processSegment(childInjector, childConfig, segmentGroup, slicedSegments, matchedOnOutlet ? PRIMARY_OUTLET : outlet, true, snapshot).pipe(map(child => {\n return new TreeNode(snapshot, child instanceof TreeNode ? [child] : []);\n }));\n }));\n }));\n }\n getChildConfig(injector, route, segments) {\n if (route.children) {\n // The children belong to the same module\n return of({\n routes: route.children,\n injector\n });\n }\n if (route.loadChildren) {\n // lazy children belong to the loaded module\n if (route._loadedRoutes !== undefined) {\n return of({\n routes: route._loadedRoutes,\n injector: route._loadedInjector\n });\n }\n return runCanLoadGuards(injector, route, segments, this.urlSerializer).pipe(mergeMap(shouldLoadResult => {\n if (shouldLoadResult) {\n return this.configLoader.loadChildren(injector, route).pipe(tap(cfg => {\n route._loadedRoutes = cfg.routes;\n route._loadedInjector = cfg.injector;\n }));\n }\n return canLoadFails(route);\n }));\n }\n return of({\n routes: [],\n injector\n });\n }\n}\nfunction sortActivatedRouteSnapshots(nodes) {\n nodes.sort((a, b) => {\n if (a.value.outlet === PRIMARY_OUTLET) return -1;\n if (b.value.outlet === PRIMARY_OUTLET) return 1;\n return a.value.outlet.localeCompare(b.value.outlet);\n });\n}\nfunction hasEmptyPathConfig(node) {\n const config = node.value.routeConfig;\n return config && config.path === '';\n}\n/**\n * Finds `TreeNode`s with matching empty path route configs and merges them into `TreeNode` with\n * the children from each duplicate. This is necessary because different outlets can match a\n * single empty path route config and the results need to then be merged.\n */\nfunction mergeEmptyPathMatches(nodes) {\n const result = [];\n // The set of nodes which contain children that were merged from two duplicate empty path nodes.\n const mergedNodes = new Set();\n for (const node of nodes) {\n if (!hasEmptyPathConfig(node)) {\n result.push(node);\n continue;\n }\n const duplicateEmptyPathNode = result.find(resultNode => node.value.routeConfig === resultNode.value.routeConfig);\n if (duplicateEmptyPathNode !== undefined) {\n duplicateEmptyPathNode.children.push(...node.children);\n mergedNodes.add(duplicateEmptyPathNode);\n } else {\n result.push(node);\n }\n }\n // For each node which has children from multiple sources, we need to recompute a new `TreeNode`\n // by also merging those children. This is necessary when there are multiple empty path configs\n // in a row. Put another way: whenever we combine children of two nodes, we need to also check\n // if any of those children can be combined into a single node as well.\n for (const mergedNode of mergedNodes) {\n const mergedChildren = mergeEmptyPathMatches(mergedNode.children);\n result.push(new TreeNode(mergedNode.value, mergedChildren));\n }\n return result.filter(n => !mergedNodes.has(n));\n}\nfunction checkOutletNameUniqueness(nodes) {\n const names = {};\n nodes.forEach(n => {\n const routeWithSameOutletName = names[n.value.outlet];\n if (routeWithSameOutletName) {\n const p = routeWithSameOutletName.url.map(s => s.toString()).join('/');\n const c = n.value.url.map(s => s.toString()).join('/');\n throw new _RuntimeError(4006 /* RuntimeErrorCode.TWO_SEGMENTS_WITH_SAME_OUTLET */, (typeof ngDevMode === 'undefined' || ngDevMode) && `Two segments cannot have the same outlet name: '${p}' and '${c}'.`);\n }\n names[n.value.outlet] = n.value;\n });\n}\nfunction getData(route) {\n return route.data || {};\n}\nfunction getResolve(route) {\n return route.resolve || {};\n}\nfunction recognize(injector, configLoader, rootComponentType, config, serializer, paramsInheritanceStrategy) {\n return mergeMap(t => recognize$1(injector, configLoader, rootComponentType, config, t.extractedUrl, serializer, paramsInheritanceStrategy).pipe(map(({\n state: targetSnapshot,\n tree: urlAfterRedirects\n }) => {\n return {\n ...t,\n targetSnapshot,\n urlAfterRedirects\n };\n })));\n}\nfunction resolveData(paramsInheritanceStrategy, injector) {\n return mergeMap(t => {\n const {\n targetSnapshot,\n guards: {\n canActivateChecks\n }\n } = t;\n if (!canActivateChecks.length) {\n return of(t);\n }\n // Iterating a Set in javascript happens in insertion order so it is safe to use a `Set` to\n // preserve the correct order that the resolvers should run in.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#description\n const routesWithResolversToRun = new Set(canActivateChecks.map(check => check.route));\n const routesNeedingDataUpdates = new Set();\n for (const route of routesWithResolversToRun) {\n if (routesNeedingDataUpdates.has(route)) {\n continue;\n }\n // All children under the route with a resolver to run need to recompute inherited data.\n for (const newRoute of flattenRouteTree(route)) {\n routesNeedingDataUpdates.add(newRoute);\n }\n }\n let routesProcessed = 0;\n return from(routesNeedingDataUpdates).pipe(concatMap(route => {\n if (routesWithResolversToRun.has(route)) {\n return runResolve(route, targetSnapshot, paramsInheritanceStrategy, injector);\n } else {\n route.data = getInherited(route, route.parent, paramsInheritanceStrategy).resolve;\n return of(void 0);\n }\n }), tap(() => routesProcessed++), takeLast(1), mergeMap(_ => routesProcessed === routesNeedingDataUpdates.size ? of(t) : EMPTY));\n });\n}\n/**\n * Returns the `ActivatedRouteSnapshot` tree as an array, using DFS to traverse the route tree.\n */\nfunction flattenRouteTree(route) {\n const descendants = route.children.map(child => flattenRouteTree(child)).flat();\n return [route, ...descendants];\n}\nfunction runResolve(futureARS, futureRSS, paramsInheritanceStrategy, injector) {\n const config = futureARS.routeConfig;\n const resolve = futureARS._resolve;\n if (config?.title !== undefined && !hasStaticTitle(config)) {\n resolve[RouteTitleKey] = config.title;\n }\n return resolveNode(resolve, futureARS, futureRSS, injector).pipe(map(resolvedData => {\n futureARS._resolvedData = resolvedData;\n futureARS.data = getInherited(futureARS, futureARS.parent, paramsInheritanceStrategy).resolve;\n return null;\n }));\n}\nfunction resolveNode(resolve, futureARS, futureRSS, injector) {\n const keys = getDataKeys(resolve);\n if (keys.length === 0) {\n return of({});\n }\n const data = {};\n return from(keys).pipe(mergeMap(key => getResolver(resolve[key], futureARS, futureRSS, injector).pipe(first(), tap(value => {\n if (value instanceof RedirectCommand) {\n throw redirectingNavigationError(new DefaultUrlSerializer(), value);\n }\n data[key] = value;\n }))), takeLast(1), map(() => data), catchError(e => isEmptyError(e) ? EMPTY : throwError(e)));\n}\nfunction getResolver(injectionToken, futureARS, futureRSS, injector) {\n const closestInjector = getClosestRouteInjector(futureARS) ?? injector;\n const resolver = getTokenOrFunctionIdentity(injectionToken, closestInjector);\n const resolverValue = resolver.resolve ? resolver.resolve(futureARS, futureRSS) : runInInjectionContext(closestInjector, () => resolver(futureARS, futureRSS));\n return wrapIntoObservable(resolverValue);\n}\n\n/**\n * Perform a side effect through a switchMap for every emission on the source Observable,\n * but return an Observable that is identical to the source. It's essentially the same as\n * the `tap` operator, but if the side effectful `next` function returns an ObservableInput,\n * it will wait before continuing with the original value.\n */\nfunction switchTap(next) {\n return switchMap(v => {\n const nextResult = next(v);\n if (nextResult) {\n return from(nextResult).pipe(map(() => v));\n }\n return of(v);\n });\n}\n\n/**\n * Provides a strategy for setting the page title after a router navigation.\n *\n * The built-in implementation traverses the router state snapshot and finds the deepest primary\n * outlet with `title` property. Given the `Routes` below, navigating to\n * `/base/child(popup:aux)` would result in the document title being set to \"child\".\n * ```ts\n * [\n * {path: 'base', title: 'base', children: [\n * {path: 'child', title: 'child'},\n * ],\n * {path: 'aux', outlet: 'popup', title: 'popupTitle'}\n * ]\n * ```\n *\n * This class can be used as a base class for custom title strategies. That is, you can create your\n * own class that extends the `TitleStrategy`. Note that in the above example, the `title`\n * from the named outlet is never used. However, a custom strategy might be implemented to\n * incorporate titles in named outlets.\n *\n * @publicApi\n * @see [Page title guide](guide/routing/common-router-tasks#setting-the-page-title)\n */\nlet TitleStrategy = /*#__PURE__*/(() => {\n class TitleStrategy {\n /**\n * @returns The `title` of the deepest primary route.\n */\n buildTitle(snapshot) {\n let pageTitle;\n let route = snapshot.root;\n while (route !== undefined) {\n pageTitle = this.getResolvedTitleForRoute(route) ?? pageTitle;\n route = route.children.find(child => child.outlet === PRIMARY_OUTLET);\n }\n return pageTitle;\n }\n /**\n * Given an `ActivatedRouteSnapshot`, returns the final value of the\n * `Route.title` property, which can either be a static string or a resolved value.\n */\n getResolvedTitleForRoute(snapshot) {\n return snapshot.data[RouteTitleKey];\n }\n static ɵfac = function TitleStrategy_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || TitleStrategy)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: TitleStrategy,\n factory: () => (() => inject(DefaultTitleStrategy))(),\n providedIn: 'root'\n });\n }\n return TitleStrategy;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * The default `TitleStrategy` used by the router that updates the title using the `Title` service.\n */\nlet DefaultTitleStrategy = /*#__PURE__*/(() => {\n class DefaultTitleStrategy extends TitleStrategy {\n title;\n constructor(title) {\n super();\n this.title = title;\n }\n /**\n * Sets the title of the browser to the given value.\n *\n * @param title The `pageTitle` from the deepest primary route.\n */\n updateTitle(snapshot) {\n const title = this.buildTitle(snapshot);\n if (title !== undefined) {\n this.title.setTitle(title);\n }\n }\n static ɵfac = function DefaultTitleStrategy_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || DefaultTitleStrategy)(i0.ɵɵinject(i1.Title));\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: DefaultTitleStrategy,\n factory: DefaultTitleStrategy.ɵfac,\n providedIn: 'root'\n });\n }\n return DefaultTitleStrategy;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/**\n * A DI token for the router service.\n *\n * @publicApi\n */\nconst ROUTER_CONFIGURATION = /*#__PURE__*/new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'router config' : '', {\n providedIn: 'root',\n factory: () => ({})\n});\n\n/**\n * This component is used internally within the router to be a placeholder when an empty\n * router-outlet is needed. For example, with a config such as:\n *\n * `{path: 'parent', outlet: 'nav', children: [...]}`\n *\n * In order to render, there needs to be a component on this config, which will default\n * to this `EmptyOutletComponent`.\n */\nlet ɵEmptyOutletComponent = /*#__PURE__*/(() => {\n class ɵEmptyOutletComponent {\n static ɵfac = function ɵEmptyOutletComponent_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || ɵEmptyOutletComponent)();\n };\n static ɵcmp = /* @__PURE__ */i0.ɵɵdefineComponent({\n type: ɵEmptyOutletComponent,\n selectors: [[\"ng-component\"]],\n exportAs: [\"emptyRouterOutlet\"],\n decls: 1,\n vars: 0,\n template: function _EmptyOutletComponent_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelement(0, \"router-outlet\");\n }\n },\n dependencies: [RouterOutlet],\n encapsulation: 2\n });\n }\n return ɵEmptyOutletComponent;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * Makes a copy of the config and adds any default required properties.\n */\nfunction standardizeConfig(r) {\n const children = r.children && r.children.map(standardizeConfig);\n const c = children ? {\n ...r,\n children\n } : {\n ...r\n };\n if (!c.component && !c.loadComponent && (children || c.loadChildren) && c.outlet && c.outlet !== PRIMARY_OUTLET) {\n c.component = ɵEmptyOutletComponent;\n }\n return c;\n}\n\n/**\n * The DI token for a router configuration.\n *\n * `ROUTES` is a low level API for router configuration via dependency injection.\n *\n * We recommend that in almost all cases to use higher level APIs such as `RouterModule.forRoot()`,\n * `provideRouter`, or `Router.resetConfig()`.\n *\n * @publicApi\n */\nconst ROUTES = /*#__PURE__*/new InjectionToken(ngDevMode ? 'ROUTES' : '');\nlet RouterConfigLoader = /*#__PURE__*/(() => {\n class RouterConfigLoader {\n componentLoaders = new WeakMap();\n childrenLoaders = new WeakMap();\n onLoadStartListener;\n onLoadEndListener;\n compiler = inject(Compiler);\n loadComponent(route) {\n if (this.componentLoaders.get(route)) {\n return this.componentLoaders.get(route);\n } else if (route._loadedComponent) {\n return of(route._loadedComponent);\n }\n if (this.onLoadStartListener) {\n this.onLoadStartListener(route);\n }\n const loadRunner = wrapIntoObservable(route.loadComponent()).pipe(map(maybeUnwrapDefaultExport), tap(component => {\n if (this.onLoadEndListener) {\n this.onLoadEndListener(route);\n }\n (typeof ngDevMode === 'undefined' || ngDevMode) && assertStandalone(route.path ?? '', component);\n route._loadedComponent = component;\n }), finalize(() => {\n this.componentLoaders.delete(route);\n }));\n // Use custom ConnectableObservable as share in runners pipe increasing the bundle size too much\n const loader = new ConnectableObservable(loadRunner, () => new Subject()).pipe(refCount());\n this.componentLoaders.set(route, loader);\n return loader;\n }\n loadChildren(parentInjector, route) {\n if (this.childrenLoaders.get(route)) {\n return this.childrenLoaders.get(route);\n } else if (route._loadedRoutes) {\n return of({\n routes: route._loadedRoutes,\n injector: route._loadedInjector\n });\n }\n if (this.onLoadStartListener) {\n this.onLoadStartListener(route);\n }\n const moduleFactoryOrRoutes$ = loadChildren(route, this.compiler, parentInjector, this.onLoadEndListener);\n const loadRunner = moduleFactoryOrRoutes$.pipe(finalize(() => {\n this.childrenLoaders.delete(route);\n }));\n // Use custom ConnectableObservable as share in runners pipe increasing the bundle size too much\n const loader = new ConnectableObservable(loadRunner, () => new Subject()).pipe(refCount());\n this.childrenLoaders.set(route, loader);\n return loader;\n }\n static ɵfac = function RouterConfigLoader_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || RouterConfigLoader)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: RouterConfigLoader,\n factory: RouterConfigLoader.ɵfac,\n providedIn: 'root'\n });\n }\n return RouterConfigLoader;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * Executes a `route.loadChildren` callback and converts the result to an array of child routes and\n * an injector if that callback returned a module.\n *\n * This function is used for the route discovery during prerendering\n * in @angular-devkit/build-angular. If there are any updates to the contract here, it will require\n * an update to the extractor.\n */\nfunction loadChildren(route, compiler, parentInjector, onLoadEndListener) {\n return wrapIntoObservable(route.loadChildren()).pipe(map(maybeUnwrapDefaultExport), mergeMap(t => {\n if (t instanceof NgModuleFactory || Array.isArray(t)) {\n return of(t);\n } else {\n return from(compiler.compileModuleAsync(t));\n }\n }), map(factoryOrRoutes => {\n if (onLoadEndListener) {\n onLoadEndListener(route);\n }\n // This injector comes from the `NgModuleRef` when lazy loading an `NgModule`. There is\n // no injector associated with lazy loading a `Route` array.\n let injector;\n let rawRoutes;\n let requireStandaloneComponents = false;\n if (Array.isArray(factoryOrRoutes)) {\n rawRoutes = factoryOrRoutes;\n requireStandaloneComponents = true;\n } else {\n injector = factoryOrRoutes.create(parentInjector).injector;\n // When loading a module that doesn't provide `RouterModule.forChild()` preloader\n // will get stuck in an infinite loop. The child module's Injector will look to\n // its parent `Injector` when it doesn't find any ROUTES so it will return routes\n // for it's parent module instead.\n rawRoutes = injector.get(ROUTES, [], {\n optional: true,\n self: true\n }).flat();\n }\n const routes = rawRoutes.map(standardizeConfig);\n (typeof ngDevMode === 'undefined' || ngDevMode) && validateConfig(routes, route.path, requireStandaloneComponents);\n return {\n routes,\n injector\n };\n }));\n}\nfunction isWrappedDefaultExport(value) {\n // We use `in` here with a string key `'default'`, because we expect `DefaultExport` objects to be\n // dynamically imported ES modules with a spec-mandated `default` key. Thus we don't expect that\n // `default` will be a renamed property.\n return value && typeof value === 'object' && 'default' in value;\n}\nfunction maybeUnwrapDefaultExport(input) {\n // As per `isWrappedDefaultExport`, the `default` key here is generated by the browser and not\n // subject to property renaming, so we reference it with bracket access.\n return isWrappedDefaultExport(input) ? input['default'] : input;\n}\n\n/**\n * @description\n *\n * Provides a way to migrate AngularJS applications to Angular.\n *\n * @publicApi\n */\nlet UrlHandlingStrategy = /*#__PURE__*/(() => {\n class UrlHandlingStrategy {\n static ɵfac = function UrlHandlingStrategy_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || UrlHandlingStrategy)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: UrlHandlingStrategy,\n factory: () => (() => inject(DefaultUrlHandlingStrategy))(),\n providedIn: 'root'\n });\n }\n return UrlHandlingStrategy;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * @publicApi\n */\nlet DefaultUrlHandlingStrategy = /*#__PURE__*/(() => {\n class DefaultUrlHandlingStrategy {\n shouldProcessUrl(url) {\n return true;\n }\n extract(url) {\n return url;\n }\n merge(newUrlPart, wholeUrl) {\n return newUrlPart;\n }\n static ɵfac = function DefaultUrlHandlingStrategy_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || DefaultUrlHandlingStrategy)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: DefaultUrlHandlingStrategy,\n factory: DefaultUrlHandlingStrategy.ɵfac,\n providedIn: 'root'\n });\n }\n return DefaultUrlHandlingStrategy;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/// \nconst CREATE_VIEW_TRANSITION = /*#__PURE__*/new InjectionToken(ngDevMode ? 'view transition helper' : '');\nconst VIEW_TRANSITION_OPTIONS = /*#__PURE__*/new InjectionToken(ngDevMode ? 'view transition options' : '');\n/**\n * A helper function for using browser view transitions. This function skips the call to\n * `startViewTransition` if the browser does not support it.\n *\n * @returns A Promise that resolves when the view transition callback begins.\n */\nfunction createViewTransition(injector, from, to) {\n const transitionOptions = injector.get(VIEW_TRANSITION_OPTIONS);\n const document = injector.get(DOCUMENT);\n // Create promises outside the Angular zone to avoid causing extra change detections\n return injector.get(NgZone).runOutsideAngular(() => {\n if (!document.startViewTransition || transitionOptions.skipNextTransition) {\n transitionOptions.skipNextTransition = false;\n // The timing of `startViewTransition` is closer to a macrotask. It won't be called\n // until the current event loop exits so we use a promise resolved in a timeout instead\n // of Promise.resolve().\n return new Promise(resolve => setTimeout(resolve));\n }\n let resolveViewTransitionStarted;\n const viewTransitionStarted = new Promise(resolve => {\n resolveViewTransitionStarted = resolve;\n });\n const transition = document.startViewTransition(() => {\n resolveViewTransitionStarted();\n // We don't actually update dom within the transition callback. The resolving of the above\n // promise unblocks the Router navigation, which synchronously activates and deactivates\n // routes (the DOM update). This view transition waits for the next change detection to\n // complete (below), which includes the update phase of the routed components.\n return createRenderPromise(injector);\n // TODO(atscott): Types in DefinitelyTyped are not up-to-date\n });\n const {\n onViewTransitionCreated\n } = transitionOptions;\n if (onViewTransitionCreated) {\n runInInjectionContext(injector, () => onViewTransitionCreated({\n transition,\n from,\n to\n }));\n }\n return viewTransitionStarted;\n });\n}\n/**\n * Creates a promise that resolves after next render.\n */\nfunction createRenderPromise(injector) {\n return new Promise(resolve => {\n // Wait for the microtask queue to empty after the next render happens (by waiting a macrotask).\n // This ensures any follow-up renders in the microtask queue are completed before the\n // view transition starts animating.\n afterNextRender({\n read: () => setTimeout(resolve)\n }, {\n injector\n });\n });\n}\nconst NAVIGATION_ERROR_HANDLER = /*#__PURE__*/new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'navigation error handler' : '');\nlet NavigationTransitions = /*#__PURE__*/(() => {\n class NavigationTransitions {\n currentNavigation = null;\n currentTransition = null;\n lastSuccessfulNavigation = null;\n /**\n * These events are used to communicate back to the Router about the state of the transition. The\n * Router wants to respond to these events in various ways. Because the `NavigationTransition`\n * class is not public, this event subject is not publicly exposed.\n */\n events = new Subject();\n /**\n * Used to abort the current transition with an error.\n */\n transitionAbortSubject = new Subject();\n configLoader = inject(RouterConfigLoader);\n environmentInjector = inject(EnvironmentInjector);\n destroyRef = inject(DestroyRef);\n urlSerializer = inject(UrlSerializer);\n rootContexts = inject(ChildrenOutletContexts);\n location = inject(Location);\n inputBindingEnabled = inject(INPUT_BINDER, {\n optional: true\n }) !== null;\n titleStrategy = inject(TitleStrategy);\n options = inject(ROUTER_CONFIGURATION, {\n optional: true\n }) || {};\n paramsInheritanceStrategy = this.options.paramsInheritanceStrategy || 'emptyOnly';\n urlHandlingStrategy = inject(UrlHandlingStrategy);\n createViewTransition = inject(CREATE_VIEW_TRANSITION, {\n optional: true\n });\n navigationErrorHandler = inject(NAVIGATION_ERROR_HANDLER, {\n optional: true\n });\n navigationId = 0;\n get hasRequestedNavigation() {\n return this.navigationId !== 0;\n }\n transitions;\n /**\n * Hook that enables you to pause navigation after the preactivation phase.\n * Used by `RouterModule`.\n *\n * @internal\n */\n afterPreactivation = () => of(void 0);\n /** @internal */\n rootComponentType = null;\n destroyed = false;\n constructor() {\n const onLoadStart = r => this.events.next(new RouteConfigLoadStart(r));\n const onLoadEnd = r => this.events.next(new RouteConfigLoadEnd(r));\n this.configLoader.onLoadEndListener = onLoadEnd;\n this.configLoader.onLoadStartListener = onLoadStart;\n this.destroyRef.onDestroy(() => {\n this.destroyed = true;\n });\n }\n complete() {\n this.transitions?.complete();\n }\n handleNavigationRequest(request) {\n const id = ++this.navigationId;\n this.transitions?.next({\n ...request,\n extractedUrl: this.urlHandlingStrategy.extract(request.rawUrl),\n targetSnapshot: null,\n targetRouterState: null,\n guards: {\n canActivateChecks: [],\n canDeactivateChecks: []\n },\n guardsResult: null,\n id\n });\n }\n setupNavigations(router) {\n this.transitions = new BehaviorSubject(null);\n return this.transitions.pipe(filter(t => t !== null),\n // Using switchMap so we cancel executing navigations when a new one comes in\n switchMap(overallTransitionState => {\n let completed = false;\n let errored = false;\n return of(overallTransitionState).pipe(switchMap(t => {\n // It is possible that `switchMap` fails to cancel previous navigations if a new one happens synchronously while the operator\n // is processing the `next` notification of that previous navigation. This can happen when a new navigation (say 2) cancels a\n // previous one (1) and yet another navigation (3) happens synchronously in response to the `NavigationCancel` event for (1).\n // https://github.com/ReactiveX/rxjs/issues/7455\n if (this.navigationId > overallTransitionState.id) {\n const cancellationReason = typeof ngDevMode === 'undefined' || ngDevMode ? `Navigation ID ${overallTransitionState.id} is not equal to the current navigation id ${this.navigationId}` : '';\n this.cancelNavigationTransition(overallTransitionState, cancellationReason, NavigationCancellationCode.SupersededByNewNavigation);\n return EMPTY;\n }\n this.currentTransition = overallTransitionState;\n // Store the Navigation object\n this.currentNavigation = {\n id: t.id,\n initialUrl: t.rawUrl,\n extractedUrl: t.extractedUrl,\n targetBrowserUrl: typeof t.extras.browserUrl === 'string' ? this.urlSerializer.parse(t.extras.browserUrl) : t.extras.browserUrl,\n trigger: t.source,\n extras: t.extras,\n previousNavigation: !this.lastSuccessfulNavigation ? null : {\n ...this.lastSuccessfulNavigation,\n previousNavigation: null\n }\n };\n const urlTransition = !router.navigated || this.isUpdatingInternalState() || this.isUpdatedBrowserUrl();\n const onSameUrlNavigation = t.extras.onSameUrlNavigation ?? router.onSameUrlNavigation;\n if (!urlTransition && onSameUrlNavigation !== 'reload') {\n const reason = typeof ngDevMode === 'undefined' || ngDevMode ? `Navigation to ${t.rawUrl} was ignored because it is the same as the current Router URL.` : '';\n this.events.next(new NavigationSkipped(t.id, this.urlSerializer.serialize(t.rawUrl), reason, NavigationSkippedCode.IgnoredSameUrlNavigation));\n t.resolve(false);\n return EMPTY;\n }\n if (this.urlHandlingStrategy.shouldProcessUrl(t.rawUrl)) {\n return of(t).pipe(\n // Fire NavigationStart event\n switchMap(t => {\n this.events.next(new NavigationStart(t.id, this.urlSerializer.serialize(t.extractedUrl), t.source, t.restoredState));\n if (t.id !== this.navigationId) {\n return EMPTY;\n }\n // This delay is required to match old behavior that forced\n // navigation to always be async\n return Promise.resolve(t);\n }),\n // Recognize\n recognize(this.environmentInjector, this.configLoader, this.rootComponentType, router.config, this.urlSerializer, this.paramsInheritanceStrategy),\n // Update URL if in `eager` update mode\n tap(t => {\n overallTransitionState.targetSnapshot = t.targetSnapshot;\n overallTransitionState.urlAfterRedirects = t.urlAfterRedirects;\n this.currentNavigation = {\n ...this.currentNavigation,\n finalUrl: t.urlAfterRedirects\n };\n // Fire RoutesRecognized\n const routesRecognized = new RoutesRecognized(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot);\n this.events.next(routesRecognized);\n }));\n } else if (urlTransition && this.urlHandlingStrategy.shouldProcessUrl(t.currentRawUrl)) {\n /* When the current URL shouldn't be processed, but the previous one\n * was, we handle this \"error condition\" by navigating to the\n * previously successful URL, but leaving the URL intact.*/\n const {\n id,\n extractedUrl,\n source,\n restoredState,\n extras\n } = t;\n const navStart = new NavigationStart(id, this.urlSerializer.serialize(extractedUrl), source, restoredState);\n this.events.next(navStart);\n const targetSnapshot = createEmptyState(this.rootComponentType).snapshot;\n this.currentTransition = overallTransitionState = {\n ...t,\n targetSnapshot,\n urlAfterRedirects: extractedUrl,\n extras: {\n ...extras,\n skipLocationChange: false,\n replaceUrl: false\n }\n };\n this.currentNavigation.finalUrl = extractedUrl;\n return of(overallTransitionState);\n } else {\n /* When neither the current or previous URL can be processed, do\n * nothing other than update router's internal reference to the\n * current \"settled\" URL. This way the next navigation will be coming\n * from the current URL in the browser.\n */\n const reason = typeof ngDevMode === 'undefined' || ngDevMode ? `Navigation was ignored because the UrlHandlingStrategy` + ` indicated neither the current URL ${t.currentRawUrl} nor target URL ${t.rawUrl} should be processed.` : '';\n this.events.next(new NavigationSkipped(t.id, this.urlSerializer.serialize(t.extractedUrl), reason, NavigationSkippedCode.IgnoredByUrlHandlingStrategy));\n t.resolve(false);\n return EMPTY;\n }\n }),\n // --- GUARDS ---\n tap(t => {\n const guardsStart = new GuardsCheckStart(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot);\n this.events.next(guardsStart);\n }), map(t => {\n this.currentTransition = overallTransitionState = {\n ...t,\n guards: getAllRouteGuards(t.targetSnapshot, t.currentSnapshot, this.rootContexts)\n };\n return overallTransitionState;\n }), checkGuards(this.environmentInjector, evt => this.events.next(evt)), tap(t => {\n overallTransitionState.guardsResult = t.guardsResult;\n if (t.guardsResult && typeof t.guardsResult !== 'boolean') {\n throw redirectingNavigationError(this.urlSerializer, t.guardsResult);\n }\n const guardsEnd = new GuardsCheckEnd(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot, !!t.guardsResult);\n this.events.next(guardsEnd);\n }), filter(t => {\n if (!t.guardsResult) {\n this.cancelNavigationTransition(t, '', NavigationCancellationCode.GuardRejected);\n return false;\n }\n return true;\n }),\n // --- RESOLVE ---\n switchTap(t => {\n if (t.guards.canActivateChecks.length === 0) {\n return undefined;\n }\n return of(t).pipe(tap(t => {\n const resolveStart = new ResolveStart(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot);\n this.events.next(resolveStart);\n }), switchMap(t => {\n let dataResolved = false;\n return of(t).pipe(resolveData(this.paramsInheritanceStrategy, this.environmentInjector), tap({\n next: () => dataResolved = true,\n complete: () => {\n if (!dataResolved) {\n this.cancelNavigationTransition(t, typeof ngDevMode === 'undefined' || ngDevMode ? `At least one route resolver didn't emit any value.` : '', NavigationCancellationCode.NoDataFromResolver);\n }\n }\n }));\n }), tap(t => {\n const resolveEnd = new ResolveEnd(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot);\n this.events.next(resolveEnd);\n }));\n }),\n // --- LOAD COMPONENTS ---\n switchTap(t => {\n const loadComponents = route => {\n const loaders = [];\n if (route.routeConfig?.loadComponent && !route.routeConfig._loadedComponent) {\n loaders.push(this.configLoader.loadComponent(route.routeConfig).pipe(tap(loadedComponent => {\n route.component = loadedComponent;\n }), map(() => void 0)));\n }\n for (const child of route.children) {\n loaders.push(...loadComponents(child));\n }\n return loaders;\n };\n return combineLatest(loadComponents(t.targetSnapshot.root)).pipe(defaultIfEmpty(null), take(1));\n }), switchTap(() => this.afterPreactivation()), switchMap(() => {\n const {\n currentSnapshot,\n targetSnapshot\n } = overallTransitionState;\n const viewTransitionStarted = this.createViewTransition?.(this.environmentInjector, currentSnapshot.root, targetSnapshot.root);\n // If view transitions are enabled, block the navigation until the view\n // transition callback starts. Otherwise, continue immediately.\n return viewTransitionStarted ? from(viewTransitionStarted).pipe(map(() => overallTransitionState)) : of(overallTransitionState);\n }), map(t => {\n const targetRouterState = createRouterState(router.routeReuseStrategy, t.targetSnapshot, t.currentRouterState);\n this.currentTransition = overallTransitionState = {\n ...t,\n targetRouterState\n };\n this.currentNavigation.targetRouterState = targetRouterState;\n return overallTransitionState;\n }), tap(() => {\n this.events.next(new BeforeActivateRoutes());\n }), activateRoutes(this.rootContexts, router.routeReuseStrategy, evt => this.events.next(evt), this.inputBindingEnabled),\n // Ensure that if some observable used to drive the transition doesn't\n // complete, the navigation still finalizes This should never happen, but\n // this is done as a safety measure to avoid surfacing this error (#49567).\n take(1), tap({\n next: t => {\n completed = true;\n this.lastSuccessfulNavigation = this.currentNavigation;\n this.events.next(new NavigationEnd(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects)));\n this.titleStrategy?.updateTitle(t.targetRouterState.snapshot);\n t.resolve(true);\n },\n complete: () => {\n completed = true;\n }\n }),\n // There used to be a lot more logic happening directly within the\n // transition Observable. Some of this logic has been refactored out to\n // other places but there may still be errors that happen there. This gives\n // us a way to cancel the transition from the outside. This may also be\n // required in the future to support something like the abort signal of the\n // Navigation API where the navigation gets aborted from outside the\n // transition.\n takeUntil(this.transitionAbortSubject.pipe(tap(err => {\n throw err;\n }))), finalize(() => {\n /* When the navigation stream finishes either through error or success,\n * we set the `completed` or `errored` flag. However, there are some\n * situations where we could get here without either of those being set.\n * For instance, a redirect during NavigationStart. Therefore, this is a\n * catch-all to make sure the NavigationCancel event is fired when a\n * navigation gets cancelled but not caught by other means. */\n if (!completed && !errored) {\n const cancelationReason = typeof ngDevMode === 'undefined' || ngDevMode ? `Navigation ID ${overallTransitionState.id} is not equal to the current navigation id ${this.navigationId}` : '';\n this.cancelNavigationTransition(overallTransitionState, cancelationReason, NavigationCancellationCode.SupersededByNewNavigation);\n }\n // Only clear current navigation if it is still set to the one that\n // finalized.\n if (this.currentTransition?.id === overallTransitionState.id) {\n this.currentNavigation = null;\n this.currentTransition = null;\n }\n }), catchError(e => {\n // If the application is already destroyed, the catch block should not\n // execute anything in practice because other resources have already\n // been released and destroyed.\n if (this.destroyed) {\n overallTransitionState.resolve(false);\n return EMPTY;\n }\n errored = true;\n /* This error type is issued during Redirect, and is handled as a\n * cancellation rather than an error. */\n if (isNavigationCancelingError(e)) {\n this.events.next(new NavigationCancel(overallTransitionState.id, this.urlSerializer.serialize(overallTransitionState.extractedUrl), e.message, e.cancellationCode));\n // When redirecting, we need to delay resolving the navigation\n // promise and push it to the redirect navigation\n if (!isRedirectingNavigationCancelingError(e)) {\n overallTransitionState.resolve(false);\n } else {\n this.events.next(new RedirectRequest(e.url, e.navigationBehaviorOptions));\n }\n /* All other errors should reset to the router's internal URL reference\n * to the pre-error state. */\n } else {\n const navigationError = new NavigationError(overallTransitionState.id, this.urlSerializer.serialize(overallTransitionState.extractedUrl), e, overallTransitionState.targetSnapshot ?? undefined);\n try {\n const navigationErrorHandlerResult = runInInjectionContext(this.environmentInjector, () => this.navigationErrorHandler?.(navigationError));\n if (navigationErrorHandlerResult instanceof RedirectCommand) {\n const {\n message,\n cancellationCode\n } = redirectingNavigationError(this.urlSerializer, navigationErrorHandlerResult);\n this.events.next(new NavigationCancel(overallTransitionState.id, this.urlSerializer.serialize(overallTransitionState.extractedUrl), message, cancellationCode));\n this.events.next(new RedirectRequest(navigationErrorHandlerResult.redirectTo, navigationErrorHandlerResult.navigationBehaviorOptions));\n } else {\n this.events.next(navigationError);\n throw e;\n }\n } catch (ee) {\n // TODO(atscott): consider flipping the default behavior of\n // resolveNavigationPromiseOnError to be `resolve(false)` when\n // undefined. This is the most sane thing to do given that\n // applications very rarely handle the promise rejection and, as a\n // result, would get \"unhandled promise rejection\" console logs.\n // The vast majority of applications would not be affected by this\n // change so omitting a migration seems reasonable. Instead,\n // applications that rely on rejection can specifically opt-in to the\n // old behavior.\n if (this.options.resolveNavigationPromiseOnError) {\n overallTransitionState.resolve(false);\n } else {\n overallTransitionState.reject(ee);\n }\n }\n }\n return EMPTY;\n }));\n // casting because `pipe` returns observable({}) when called with 8+ arguments\n }));\n }\n cancelNavigationTransition(t, reason, code) {\n const navCancel = new NavigationCancel(t.id, this.urlSerializer.serialize(t.extractedUrl), reason, code);\n this.events.next(navCancel);\n t.resolve(false);\n }\n /**\n * @returns Whether we're navigating to somewhere that is not what the Router is\n * currently set to.\n */\n isUpdatingInternalState() {\n // TODO(atscott): The serializer should likely be used instead of\n // `UrlTree.toString()`. Custom serializers are often written to handle\n // things better than the default one (objects, for example will be\n // [Object object] with the custom serializer and be \"the same\" when they\n // aren't).\n // (Same for isUpdatedBrowserUrl)\n return this.currentTransition?.extractedUrl.toString() !== this.currentTransition?.currentUrlTree.toString();\n }\n /**\n * @returns Whether we're updating the browser URL to something new (navigation is going\n * to somewhere not displayed in the URL bar and we will update the URL\n * bar if navigation succeeds).\n */\n isUpdatedBrowserUrl() {\n // The extracted URL is the part of the URL that this application cares about. `extract` may\n // return only part of the browser URL and that part may have not changed even if some other\n // portion of the URL did.\n const currentBrowserUrl = this.urlHandlingStrategy.extract(this.urlSerializer.parse(this.location.path(true)));\n const targetBrowserUrl = this.currentNavigation?.targetBrowserUrl ?? this.currentNavigation?.extractedUrl;\n return currentBrowserUrl.toString() !== targetBrowserUrl?.toString() && !this.currentNavigation?.extras.skipLocationChange;\n }\n static ɵfac = function NavigationTransitions_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || NavigationTransitions)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: NavigationTransitions,\n factory: NavigationTransitions.ɵfac,\n providedIn: 'root'\n });\n }\n return NavigationTransitions;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nfunction isBrowserTriggeredNavigation(source) {\n return source !== IMPERATIVE_NAVIGATION;\n}\n\n/**\n * @description\n *\n * Provides a way to customize when activated routes get reused.\n *\n * @publicApi\n */\nlet RouteReuseStrategy = /*#__PURE__*/(() => {\n class RouteReuseStrategy {\n static ɵfac = function RouteReuseStrategy_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || RouteReuseStrategy)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: RouteReuseStrategy,\n factory: () => (() => inject(DefaultRouteReuseStrategy))(),\n providedIn: 'root'\n });\n }\n return RouteReuseStrategy;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * @description\n *\n * This base route reuse strategy only reuses routes when the matched router configs are\n * identical. This prevents components from being destroyed and recreated\n * when just the route parameters, query parameters or fragment change\n * (that is, the existing component is _reused_).\n *\n * This strategy does not store any routes for later reuse.\n *\n * Angular uses this strategy by default.\n *\n *\n * It can be used as a base class for custom route reuse strategies, i.e. you can create your own\n * class that extends the `BaseRouteReuseStrategy` one.\n * @publicApi\n */\nclass BaseRouteReuseStrategy {\n /**\n * Whether the given route should detach for later reuse.\n * Always returns false for `BaseRouteReuseStrategy`.\n * */\n shouldDetach(route) {\n return false;\n }\n /**\n * A no-op; the route is never stored since this strategy never detaches routes for later re-use.\n */\n store(route, detachedTree) {}\n /** Returns `false`, meaning the route (and its subtree) is never reattached */\n shouldAttach(route) {\n return false;\n }\n /** Returns `null` because this strategy does not store routes for later re-use. */\n retrieve(route) {\n return null;\n }\n /**\n * Determines if a route should be reused.\n * This strategy returns `true` when the future route config and current route config are\n * identical.\n */\n shouldReuseRoute(future, curr) {\n return future.routeConfig === curr.routeConfig;\n }\n}\nlet DefaultRouteReuseStrategy = /*#__PURE__*/(() => {\n class DefaultRouteReuseStrategy extends BaseRouteReuseStrategy {\n static ɵfac = /* @__PURE__ */(() => {\n let ɵDefaultRouteReuseStrategy_BaseFactory;\n return function DefaultRouteReuseStrategy_Factory(__ngFactoryType__) {\n return (ɵDefaultRouteReuseStrategy_BaseFactory || (ɵDefaultRouteReuseStrategy_BaseFactory = i0.ɵɵgetInheritedFactory(DefaultRouteReuseStrategy)))(__ngFactoryType__ || DefaultRouteReuseStrategy);\n };\n })();\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: DefaultRouteReuseStrategy,\n factory: DefaultRouteReuseStrategy.ɵfac,\n providedIn: 'root'\n });\n }\n return DefaultRouteReuseStrategy;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nlet StateManager = /*#__PURE__*/(() => {\n class StateManager {\n urlSerializer = inject(UrlSerializer);\n options = inject(ROUTER_CONFIGURATION, {\n optional: true\n }) || {};\n canceledNavigationResolution = this.options.canceledNavigationResolution || 'replace';\n location = inject(Location);\n urlHandlingStrategy = inject(UrlHandlingStrategy);\n urlUpdateStrategy = this.options.urlUpdateStrategy || 'deferred';\n currentUrlTree = new UrlTree();\n /**\n * Returns the currently activated `UrlTree`.\n *\n * This `UrlTree` shows only URLs that the `Router` is configured to handle (through\n * `UrlHandlingStrategy`).\n *\n * The value is set after finding the route config tree to activate but before activating the\n * route.\n */\n getCurrentUrlTree() {\n return this.currentUrlTree;\n }\n rawUrlTree = this.currentUrlTree;\n /**\n * Returns a `UrlTree` that is represents what the browser is actually showing.\n *\n * In the life of a navigation transition:\n * 1. When a navigation begins, the raw `UrlTree` is updated to the full URL that's being\n * navigated to.\n * 2. During a navigation, redirects are applied, which might only apply to _part_ of the URL (due\n * to `UrlHandlingStrategy`).\n * 3. Just before activation, the raw `UrlTree` is updated to include the redirects on top of the\n * original raw URL.\n *\n * Note that this is _only_ here to support `UrlHandlingStrategy.extract` and\n * `UrlHandlingStrategy.shouldProcessUrl`. Without those APIs, the current `UrlTree` would not\n * deviated from the raw `UrlTree`.\n *\n * For `extract`, a raw `UrlTree` is needed because `extract` may only return part\n * of the navigation URL. Thus, the current `UrlTree` may only represent _part_ of the browser\n * URL. When a navigation gets cancelled and the router needs to reset the URL or a new navigation\n * occurs, it needs to know the _whole_ browser URL, not just the part handled by\n * `UrlHandlingStrategy`.\n * For `shouldProcessUrl`, when the return is `false`, the router ignores the navigation but\n * still updates the raw `UrlTree` with the assumption that the navigation was caused by the\n * location change listener due to a URL update by the AngularJS router. In this case, the router\n * still need to know what the browser's URL is for future navigations.\n */\n getRawUrlTree() {\n return this.rawUrlTree;\n }\n createBrowserPath({\n finalUrl,\n initialUrl,\n targetBrowserUrl\n }) {\n const rawUrl = finalUrl !== undefined ? this.urlHandlingStrategy.merge(finalUrl, initialUrl) : initialUrl;\n const url = targetBrowserUrl ?? rawUrl;\n const path = url instanceof UrlTree ? this.urlSerializer.serialize(url) : url;\n return path;\n }\n commitTransition({\n targetRouterState,\n finalUrl,\n initialUrl\n }) {\n // If we are committing the transition after having a final URL and target state, we're updating\n // all pieces of the state. Otherwise, we likely skipped the transition (due to URL handling strategy)\n // and only want to update the rawUrlTree, which represents the browser URL (and doesn't necessarily match router state).\n if (finalUrl && targetRouterState) {\n this.currentUrlTree = finalUrl;\n this.rawUrlTree = this.urlHandlingStrategy.merge(finalUrl, initialUrl);\n this.routerState = targetRouterState;\n } else {\n this.rawUrlTree = initialUrl;\n }\n }\n routerState = createEmptyState(null);\n /** Returns the current RouterState. */\n getRouterState() {\n return this.routerState;\n }\n stateMemento = this.createStateMemento();\n updateStateMemento() {\n this.stateMemento = this.createStateMemento();\n }\n createStateMemento() {\n return {\n rawUrlTree: this.rawUrlTree,\n currentUrlTree: this.currentUrlTree,\n routerState: this.routerState\n };\n }\n resetInternalState({\n finalUrl\n }) {\n this.routerState = this.stateMemento.routerState;\n this.currentUrlTree = this.stateMemento.currentUrlTree;\n // Note here that we use the urlHandlingStrategy to get the reset `rawUrlTree` because it may be\n // configured to handle only part of the navigation URL. This means we would only want to reset\n // the part of the navigation handled by the Angular router rather than the whole URL. In\n // addition, the URLHandlingStrategy may be configured to specifically preserve parts of the URL\n // when merging, such as the query params so they are not lost on a refresh.\n this.rawUrlTree = this.urlHandlingStrategy.merge(this.currentUrlTree, finalUrl ?? this.rawUrlTree);\n }\n static ɵfac = function StateManager_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || StateManager)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: StateManager,\n factory: () => (() => inject(HistoryStateManager))(),\n providedIn: 'root'\n });\n }\n return StateManager;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nlet HistoryStateManager = /*#__PURE__*/(() => {\n class HistoryStateManager extends StateManager {\n /**\n * The id of the currently active page in the router.\n * Updated to the transition's target id on a successful navigation.\n *\n * This is used to track what page the router last activated. When an attempted navigation fails,\n * the router can then use this to compute how to restore the state back to the previously active\n * page.\n */\n currentPageId = 0;\n lastSuccessfulId = -1;\n restoredState() {\n return this.location.getState();\n }\n /**\n * The ɵrouterPageId of whatever page is currently active in the browser history. This is\n * important for computing the target page id for new navigations because we need to ensure each\n * page id in the browser history is 1 more than the previous entry.\n */\n get browserPageId() {\n if (this.canceledNavigationResolution !== 'computed') {\n return this.currentPageId;\n }\n return this.restoredState()?.ɵrouterPageId ?? this.currentPageId;\n }\n registerNonRouterCurrentEntryChangeListener(listener) {\n return this.location.subscribe(event => {\n if (event['type'] === 'popstate') {\n // The `setTimeout` was added in #12160 and is likely to support Angular/AngularJS\n // hybrid apps.\n setTimeout(() => {\n listener(event['url'], event.state, 'popstate');\n });\n }\n });\n }\n handleRouterEvent(e, currentTransition) {\n if (e instanceof NavigationStart) {\n this.updateStateMemento();\n } else if (e instanceof NavigationSkipped) {\n this.commitTransition(currentTransition);\n } else if (e instanceof RoutesRecognized) {\n if (this.urlUpdateStrategy === 'eager') {\n if (!currentTransition.extras.skipLocationChange) {\n this.setBrowserUrl(this.createBrowserPath(currentTransition), currentTransition);\n }\n }\n } else if (e instanceof BeforeActivateRoutes) {\n this.commitTransition(currentTransition);\n if (this.urlUpdateStrategy === 'deferred' && !currentTransition.extras.skipLocationChange) {\n this.setBrowserUrl(this.createBrowserPath(currentTransition), currentTransition);\n }\n } else if (e instanceof NavigationCancel && (e.code === NavigationCancellationCode.GuardRejected || e.code === NavigationCancellationCode.NoDataFromResolver)) {\n this.restoreHistory(currentTransition);\n } else if (e instanceof NavigationError) {\n this.restoreHistory(currentTransition, true);\n } else if (e instanceof NavigationEnd) {\n this.lastSuccessfulId = e.id;\n this.currentPageId = this.browserPageId;\n }\n }\n setBrowserUrl(path, {\n extras,\n id\n }) {\n const {\n replaceUrl,\n state\n } = extras;\n if (this.location.isCurrentPathEqualTo(path) || !!replaceUrl) {\n // replacements do not update the target page\n const currentBrowserPageId = this.browserPageId;\n const newState = {\n ...state,\n ...this.generateNgRouterState(id, currentBrowserPageId)\n };\n this.location.replaceState(path, '', newState);\n } else {\n const newState = {\n ...state,\n ...this.generateNgRouterState(id, this.browserPageId + 1)\n };\n this.location.go(path, '', newState);\n }\n }\n /**\n * Performs the necessary rollback action to restore the browser URL to the\n * state before the transition.\n */\n restoreHistory(navigation, restoringFromCaughtError = false) {\n if (this.canceledNavigationResolution === 'computed') {\n const currentBrowserPageId = this.browserPageId;\n const targetPagePosition = this.currentPageId - currentBrowserPageId;\n if (targetPagePosition !== 0) {\n this.location.historyGo(targetPagePosition);\n } else if (this.getCurrentUrlTree() === navigation.finalUrl && targetPagePosition === 0) {\n // We got to the activation stage (where currentUrlTree is set to the navigation's\n // finalUrl), but we weren't moving anywhere in history (skipLocationChange or replaceUrl).\n // We still need to reset the router state back to what it was when the navigation started.\n this.resetInternalState(navigation);\n this.resetUrlToCurrentUrlTree();\n } else ;\n } else if (this.canceledNavigationResolution === 'replace') {\n // TODO(atscott): It seems like we should _always_ reset the state here. It would be a no-op\n // for `deferred` navigations that haven't change the internal state yet because guards\n // reject. For 'eager' navigations, it seems like we also really should reset the state\n // because the navigation was cancelled. Investigate if this can be done by running TGP.\n if (restoringFromCaughtError) {\n this.resetInternalState(navigation);\n }\n this.resetUrlToCurrentUrlTree();\n }\n }\n resetUrlToCurrentUrlTree() {\n this.location.replaceState(this.urlSerializer.serialize(this.getRawUrlTree()), '', this.generateNgRouterState(this.lastSuccessfulId, this.currentPageId));\n }\n generateNgRouterState(navigationId, routerPageId) {\n if (this.canceledNavigationResolution === 'computed') {\n return {\n navigationId,\n ɵrouterPageId: routerPageId\n };\n }\n return {\n navigationId\n };\n }\n static ɵfac = /* @__PURE__ */(() => {\n let ɵHistoryStateManager_BaseFactory;\n return function HistoryStateManager_Factory(__ngFactoryType__) {\n return (ɵHistoryStateManager_BaseFactory || (ɵHistoryStateManager_BaseFactory = i0.ɵɵgetInheritedFactory(HistoryStateManager)))(__ngFactoryType__ || HistoryStateManager);\n };\n })();\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: HistoryStateManager,\n factory: HistoryStateManager.ɵfac,\n providedIn: 'root'\n });\n }\n return HistoryStateManager;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/**\n * Performs the given action once the router finishes its next/current navigation.\n *\n * The navigation is considered complete under the following conditions:\n * - `NavigationCancel` event emits and the code is not `NavigationCancellationCode.Redirect` or\n * `NavigationCancellationCode.SupersededByNewNavigation`. In these cases, the\n * redirecting/superseding navigation must finish.\n * - `NavigationError`, `NavigationEnd`, or `NavigationSkipped` event emits\n */\nfunction afterNextNavigation(router, action) {\n router.events.pipe(filter(e => e instanceof NavigationEnd || e instanceof NavigationCancel || e instanceof NavigationError || e instanceof NavigationSkipped), map(e => {\n if (e instanceof NavigationEnd || e instanceof NavigationSkipped) {\n return 0 /* NavigationResult.COMPLETE */;\n }\n const redirecting = e instanceof NavigationCancel ? e.code === NavigationCancellationCode.Redirect || e.code === NavigationCancellationCode.SupersededByNewNavigation : false;\n return redirecting ? 2 /* NavigationResult.REDIRECTING */ : 1 /* NavigationResult.FAILED */;\n }), filter(result => result !== 2 /* NavigationResult.REDIRECTING */), take(1)).subscribe(() => {\n action();\n });\n}\n\n/**\n * The equivalent `IsActiveMatchOptions` options for `Router.isActive` is called with `true`\n * (exact = true).\n */\nconst exactMatchOptions = {\n paths: 'exact',\n fragment: 'ignored',\n matrixParams: 'ignored',\n queryParams: 'exact'\n};\n/**\n * The equivalent `IsActiveMatchOptions` options for `Router.isActive` is called with `false`\n * (exact = false).\n */\nconst subsetMatchOptions = {\n paths: 'subset',\n fragment: 'ignored',\n matrixParams: 'ignored',\n queryParams: 'subset'\n};\n/**\n * @description\n *\n * A service that facilitates navigation among views and URL manipulation capabilities.\n * This service is provided in the root scope and configured with [provideRouter](api/router/provideRouter).\n *\n * @see {@link Route}\n * @see {@link provideRouter}\n * @see [Routing and Navigation Guide](guide/routing/common-router-tasks).\n *\n * @ngModule RouterModule\n *\n * @publicApi\n */\nlet Router = /*#__PURE__*/(() => {\n class Router {\n get currentUrlTree() {\n return this.stateManager.getCurrentUrlTree();\n }\n get rawUrlTree() {\n return this.stateManager.getRawUrlTree();\n }\n disposed = false;\n nonRouterCurrentEntryChangeSubscription;\n console = inject(_Console);\n stateManager = inject(StateManager);\n options = inject(ROUTER_CONFIGURATION, {\n optional: true\n }) || {};\n pendingTasks = inject(_PendingTasksInternal);\n urlUpdateStrategy = this.options.urlUpdateStrategy || 'deferred';\n navigationTransitions = inject(NavigationTransitions);\n urlSerializer = inject(UrlSerializer);\n location = inject(Location);\n urlHandlingStrategy = inject(UrlHandlingStrategy);\n /**\n * The private `Subject` type for the public events exposed in the getter. This is used internally\n * to push events to. The separate field allows us to expose separate types in the public API\n * (i.e., an Observable rather than the Subject).\n */\n _events = new Subject();\n /**\n * An event stream for routing events.\n */\n get events() {\n // TODO(atscott): This _should_ be events.asObservable(). However, this change requires internal\n // cleanup: tests are doing `(route.events as Subject).next(...)`. This isn't\n // allowed/supported but we still have to fix these or file bugs against the teams before making\n // the change.\n return this._events;\n }\n /**\n * The current state of routing in this NgModule.\n */\n get routerState() {\n return this.stateManager.getRouterState();\n }\n /**\n * True if at least one navigation event has occurred,\n * false otherwise.\n */\n navigated = false;\n /**\n * A strategy for re-using routes.\n *\n * @deprecated Configure using `providers` instead:\n * `{provide: RouteReuseStrategy, useClass: MyStrategy}`.\n */\n routeReuseStrategy = inject(RouteReuseStrategy);\n /**\n * How to handle a navigation request to the current URL.\n *\n *\n * @deprecated Configure this through `provideRouter` or `RouterModule.forRoot` instead.\n * @see {@link withRouterConfig}\n * @see {@link provideRouter}\n * @see {@link RouterModule}\n */\n onSameUrlNavigation = this.options.onSameUrlNavigation || 'ignore';\n config = inject(ROUTES, {\n optional: true\n })?.flat() ?? [];\n /**\n * Indicates whether the application has opted in to binding Router data to component inputs.\n *\n * This option is enabled by the `withComponentInputBinding` feature of `provideRouter` or\n * `bindToComponentInputs` in the `ExtraOptions` of `RouterModule.forRoot`.\n */\n componentInputBindingEnabled = !!inject(INPUT_BINDER, {\n optional: true\n });\n constructor() {\n this.resetConfig(this.config);\n this.navigationTransitions.setupNavigations(this).subscribe({\n error: e => {\n this.console.warn(ngDevMode ? `Unhandled Navigation Error: ${e}` : e);\n }\n });\n this.subscribeToNavigationEvents();\n }\n eventsSubscription = new Subscription();\n subscribeToNavigationEvents() {\n const subscription = this.navigationTransitions.events.subscribe(e => {\n try {\n const currentTransition = this.navigationTransitions.currentTransition;\n const currentNavigation = this.navigationTransitions.currentNavigation;\n if (currentTransition !== null && currentNavigation !== null) {\n this.stateManager.handleRouterEvent(e, currentNavigation);\n if (e instanceof NavigationCancel && e.code !== NavigationCancellationCode.Redirect && e.code !== NavigationCancellationCode.SupersededByNewNavigation) {\n // It seems weird that `navigated` is set to `true` when the navigation is rejected,\n // however it's how things were written initially. Investigation would need to be done\n // to determine if this can be removed.\n this.navigated = true;\n } else if (e instanceof NavigationEnd) {\n this.navigated = true;\n } else if (e instanceof RedirectRequest) {\n const opts = e.navigationBehaviorOptions;\n const mergedTree = this.urlHandlingStrategy.merge(e.url, currentTransition.currentRawUrl);\n const extras = {\n browserUrl: currentTransition.extras.browserUrl,\n info: currentTransition.extras.info,\n skipLocationChange: currentTransition.extras.skipLocationChange,\n // The URL is already updated at this point if we have 'eager' URL\n // updates or if the navigation was triggered by the browser (back\n // button, URL bar, etc). We want to replace that item in history\n // if the navigation is rejected.\n replaceUrl: currentTransition.extras.replaceUrl || this.urlUpdateStrategy === 'eager' || isBrowserTriggeredNavigation(currentTransition.source),\n // allow developer to override default options with RedirectCommand\n ...opts\n };\n this.scheduleNavigation(mergedTree, IMPERATIVE_NAVIGATION, null, extras, {\n resolve: currentTransition.resolve,\n reject: currentTransition.reject,\n promise: currentTransition.promise\n });\n }\n }\n // Note that it's important to have the Router process the events _before_ the event is\n // pushed through the public observable. This ensures the correct router state is in place\n // before applications observe the events.\n if (isPublicRouterEvent(e)) {\n this._events.next(e);\n }\n } catch (e) {\n this.navigationTransitions.transitionAbortSubject.next(e);\n }\n });\n this.eventsSubscription.add(subscription);\n }\n /** @internal */\n resetRootComponentType(rootComponentType) {\n // TODO: vsavkin router 4.0 should make the root component set to null\n // this will simplify the lifecycle of the router.\n this.routerState.root.component = rootComponentType;\n this.navigationTransitions.rootComponentType = rootComponentType;\n }\n /**\n * Sets up the location change listener and performs the initial navigation.\n */\n initialNavigation() {\n this.setUpLocationChangeListener();\n if (!this.navigationTransitions.hasRequestedNavigation) {\n this.navigateToSyncWithBrowser(this.location.path(true), IMPERATIVE_NAVIGATION, this.stateManager.restoredState());\n }\n }\n /**\n * Sets up the location change listener. This listener detects navigations triggered from outside\n * the Router (the browser back/forward buttons, for example) and schedules a corresponding Router\n * navigation so that the correct events, guards, etc. are triggered.\n */\n setUpLocationChangeListener() {\n // Don't need to use Zone.wrap any more, because zone.js\n // already patch onPopState, so location change callback will\n // run into ngZone\n this.nonRouterCurrentEntryChangeSubscription ??= this.stateManager.registerNonRouterCurrentEntryChangeListener((url, state, source) => {\n this.navigateToSyncWithBrowser(url, source, state);\n });\n }\n /**\n * Schedules a router navigation to synchronize Router state with the browser state.\n *\n * This is done as a response to a popstate event and the initial navigation. These\n * two scenarios represent times when the browser URL/state has been updated and\n * the Router needs to respond to ensure its internal state matches.\n */\n navigateToSyncWithBrowser(url, source, state) {\n const extras = {\n replaceUrl: true\n };\n // TODO: restoredState should always include the entire state, regardless\n // of navigationId. This requires a breaking change to update the type on\n // NavigationStart’s restoredState, which currently requires navigationId\n // to always be present. The Router used to only restore history state if\n // a navigationId was present.\n // The stored navigationId is used by the RouterScroller to retrieve the scroll\n // position for the page.\n const restoredState = state?.navigationId ? state : null;\n // Separate to NavigationStart.restoredState, we must also restore the state to\n // history.state and generate a new navigationId, since it will be overwritten\n if (state) {\n const stateCopy = {\n ...state\n };\n delete stateCopy.navigationId;\n delete stateCopy.ɵrouterPageId;\n if (Object.keys(stateCopy).length !== 0) {\n extras.state = stateCopy;\n }\n }\n const urlTree = this.parseUrl(url);\n this.scheduleNavigation(urlTree, source, restoredState, extras);\n }\n /** The current URL. */\n get url() {\n return this.serializeUrl(this.currentUrlTree);\n }\n /**\n * Returns the current `Navigation` object when the router is navigating,\n * and `null` when idle.\n */\n getCurrentNavigation() {\n return this.navigationTransitions.currentNavigation;\n }\n /**\n * The `Navigation` object of the most recent navigation to succeed and `null` if there\n * has not been a successful navigation yet.\n */\n get lastSuccessfulNavigation() {\n return this.navigationTransitions.lastSuccessfulNavigation;\n }\n /**\n * Resets the route configuration used for navigation and generating links.\n *\n * @param config The route array for the new configuration.\n *\n * @usageNotes\n *\n * ```ts\n * router.resetConfig([\n * { path: 'team/:id', component: TeamCmp, children: [\n * { path: 'simple', component: SimpleCmp },\n * { path: 'user/:name', component: UserCmp }\n * ]}\n * ]);\n * ```\n */\n resetConfig(config) {\n (typeof ngDevMode === 'undefined' || ngDevMode) && validateConfig(config);\n this.config = config.map(standardizeConfig);\n this.navigated = false;\n }\n /** @nodoc */\n ngOnDestroy() {\n this.dispose();\n }\n /** Disposes of the router. */\n dispose() {\n // We call `unsubscribe()` to release observers, as users may forget to\n // unsubscribe manually when subscribing to `router.events`. We do not call\n // `complete()` because it is unsafe; if someone subscribes using the `first`\n // operator and the observable completes before emitting a value,\n // RxJS will throw an error.\n this._events.unsubscribe();\n this.navigationTransitions.complete();\n if (this.nonRouterCurrentEntryChangeSubscription) {\n this.nonRouterCurrentEntryChangeSubscription.unsubscribe();\n this.nonRouterCurrentEntryChangeSubscription = undefined;\n }\n this.disposed = true;\n this.eventsSubscription.unsubscribe();\n }\n /**\n * Appends URL segments to the current URL tree to create a new URL tree.\n *\n * @param commands An array of URL fragments with which to construct the new URL tree.\n * If the path is static, can be the literal URL string. For a dynamic path, pass an array of path\n * segments, followed by the parameters for each segment.\n * The fragments are applied to the current URL tree or the one provided in the `relativeTo`\n * property of the options object, if supplied.\n * @param navigationExtras Options that control the navigation strategy.\n * @returns The new URL tree.\n *\n * @usageNotes\n *\n * ```\n * // create /team/33/user/11\n * router.createUrlTree(['/team', 33, 'user', 11]);\n *\n * // create /team/33;expand=true/user/11\n * router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]);\n *\n * // you can collapse static segments like this (this works only with the first passed-in value):\n * router.createUrlTree(['/team/33/user', userId]);\n *\n * // If the first segment can contain slashes, and you do not want the router to split it,\n * // you can do the following:\n * router.createUrlTree([{segmentPath: '/one/two'}]);\n *\n * // create /team/33/(user/11//right:chat)\n * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]);\n *\n * // remove the right secondary node\n * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]);\n *\n * // assuming the current url is `/team/33/user/11` and the route points to `user/11`\n *\n * // navigate to /team/33/user/11/details\n * router.createUrlTree(['details'], {relativeTo: route});\n *\n * // navigate to /team/33/user/22\n * router.createUrlTree(['../22'], {relativeTo: route});\n *\n * // navigate to /team/44/user/22\n * router.createUrlTree(['../../team/44/user/22'], {relativeTo: route});\n *\n * Note that a value of `null` or `undefined` for `relativeTo` indicates that the\n * tree should be created relative to the root.\n * ```\n */\n createUrlTree(commands, navigationExtras = {}) {\n const {\n relativeTo,\n queryParams,\n fragment,\n queryParamsHandling,\n preserveFragment\n } = navigationExtras;\n const f = preserveFragment ? this.currentUrlTree.fragment : fragment;\n let q = null;\n switch (queryParamsHandling ?? this.options.defaultQueryParamsHandling) {\n case 'merge':\n q = {\n ...this.currentUrlTree.queryParams,\n ...queryParams\n };\n break;\n case 'preserve':\n q = this.currentUrlTree.queryParams;\n break;\n default:\n q = queryParams || null;\n }\n if (q !== null) {\n q = this.removeEmptyProps(q);\n }\n let relativeToUrlSegmentGroup;\n try {\n const relativeToSnapshot = relativeTo ? relativeTo.snapshot : this.routerState.snapshot.root;\n relativeToUrlSegmentGroup = createSegmentGroupFromRoute(relativeToSnapshot);\n } catch (e) {\n // This is strictly for backwards compatibility with tests that create\n // invalid `ActivatedRoute` mocks.\n // Note: the difference between having this fallback for invalid `ActivatedRoute` setups and\n // just throwing is ~500 test failures. Fixing all of those tests by hand is not feasible at\n // the moment.\n if (typeof commands[0] !== 'string' || commands[0][0] !== '/') {\n // Navigations that were absolute in the old way of creating UrlTrees\n // would still work because they wouldn't attempt to match the\n // segments in the `ActivatedRoute` to the `currentUrlTree` but\n // instead just replace the root segment with the navigation result.\n // Non-absolute navigations would fail to apply the commands because\n // the logic could not find the segment to replace (so they'd act like there were no\n // commands).\n commands = [];\n }\n relativeToUrlSegmentGroup = this.currentUrlTree.root;\n }\n return createUrlTreeFromSegmentGroup(relativeToUrlSegmentGroup, commands, q, f ?? null);\n }\n /**\n * Navigates to a view using an absolute route path.\n *\n * @param url An absolute path for a defined route. The function does not apply any delta to the\n * current URL.\n * @param extras An object containing properties that modify the navigation strategy.\n *\n * @returns A Promise that resolves to 'true' when navigation succeeds,\n * to 'false' when navigation fails, or is rejected on error.\n *\n * @usageNotes\n *\n * The following calls request navigation to an absolute path.\n *\n * ```ts\n * router.navigateByUrl(\"/team/33/user/11\");\n *\n * // Navigate without updating the URL\n * router.navigateByUrl(\"/team/33/user/11\", { skipLocationChange: true });\n * ```\n *\n * @see [Routing and Navigation guide](guide/routing/common-router-tasks)\n *\n */\n navigateByUrl(url, extras = {\n skipLocationChange: false\n }) {\n const urlTree = isUrlTree(url) ? url : this.parseUrl(url);\n const mergedTree = this.urlHandlingStrategy.merge(urlTree, this.rawUrlTree);\n return this.scheduleNavigation(mergedTree, IMPERATIVE_NAVIGATION, null, extras);\n }\n /**\n * Navigate based on the provided array of commands and a starting point.\n * If no starting route is provided, the navigation is absolute.\n *\n * @param commands An array of URL fragments with which to construct the target URL.\n * If the path is static, can be the literal URL string. For a dynamic path, pass an array of path\n * segments, followed by the parameters for each segment.\n * The fragments are applied to the current URL or the one provided in the `relativeTo` property\n * of the options object, if supplied.\n * @param extras An options object that determines how the URL should be constructed or\n * interpreted.\n *\n * @returns A Promise that resolves to `true` when navigation succeeds, or `false` when navigation\n * fails. The Promise is rejected when an error occurs if `resolveNavigationPromiseOnError` is\n * not `true`.\n *\n * @usageNotes\n *\n * The following calls request navigation to a dynamic route path relative to the current URL.\n *\n * ```ts\n * router.navigate(['team', 33, 'user', 11], {relativeTo: route});\n *\n * // Navigate without updating the URL, overriding the default behavior\n * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});\n * ```\n *\n * @see [Routing and Navigation guide](guide/routing/common-router-tasks)\n *\n */\n navigate(commands, extras = {\n skipLocationChange: false\n }) {\n validateCommands(commands);\n return this.navigateByUrl(this.createUrlTree(commands, extras), extras);\n }\n /** Serializes a `UrlTree` into a string */\n serializeUrl(url) {\n return this.urlSerializer.serialize(url);\n }\n /** Parses a string into a `UrlTree` */\n parseUrl(url) {\n try {\n return this.urlSerializer.parse(url);\n } catch {\n return this.urlSerializer.parse('/');\n }\n }\n isActive(url, matchOptions) {\n let options;\n if (matchOptions === true) {\n options = {\n ...exactMatchOptions\n };\n } else if (matchOptions === false) {\n options = {\n ...subsetMatchOptions\n };\n } else {\n options = matchOptions;\n }\n if (isUrlTree(url)) {\n return containsTree(this.currentUrlTree, url, options);\n }\n const urlTree = this.parseUrl(url);\n return containsTree(this.currentUrlTree, urlTree, options);\n }\n removeEmptyProps(params) {\n return Object.entries(params).reduce((result, [key, value]) => {\n if (value !== null && value !== undefined) {\n result[key] = value;\n }\n return result;\n }, {});\n }\n scheduleNavigation(rawUrl, source, restoredState, extras, priorPromise) {\n if (this.disposed) {\n return Promise.resolve(false);\n }\n let resolve;\n let reject;\n let promise;\n if (priorPromise) {\n resolve = priorPromise.resolve;\n reject = priorPromise.reject;\n promise = priorPromise.promise;\n } else {\n promise = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n }\n // Indicate that the navigation is happening.\n const taskId = this.pendingTasks.add();\n afterNextNavigation(this, () => {\n // Remove pending task in a microtask to allow for cancelled\n // initial navigations and redirects within the same task.\n queueMicrotask(() => this.pendingTasks.remove(taskId));\n });\n this.navigationTransitions.handleNavigationRequest({\n source,\n restoredState,\n currentUrlTree: this.currentUrlTree,\n currentRawUrl: this.currentUrlTree,\n rawUrl,\n extras,\n resolve: resolve,\n reject: reject,\n promise,\n currentSnapshot: this.routerState.snapshot,\n currentRouterState: this.routerState\n });\n // Make sure that the error is propagated even though `processNavigations` catch\n // handler does not rethrow\n return promise.catch(e => {\n return Promise.reject(e);\n });\n }\n static ɵfac = function Router_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || Router)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: Router,\n factory: Router.ɵfac,\n providedIn: 'root'\n });\n }\n return Router;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nfunction validateCommands(commands) {\n for (let i = 0; i < commands.length; i++) {\n const cmd = commands[i];\n if (cmd == null) {\n throw new _RuntimeError(4008 /* RuntimeErrorCode.NULLISH_COMMAND */, (typeof ngDevMode === 'undefined' || ngDevMode) && `The requested path contains ${cmd} segment at index ${i}`);\n }\n }\n}\nfunction isPublicRouterEvent(e) {\n return !(e instanceof BeforeActivateRoutes) && !(e instanceof RedirectRequest);\n}\nexport { RoutedComponentInputBinder as $, ActivationEnd as A, BaseRouteReuseStrategy as B, ChildActivationEnd as C, DefaultTitleStrategy as D, EventType as E, RouterStateSnapshot as F, GuardsCheckEnd as G, convertToParamMap as H, defaultUrlMatcher as I, DefaultUrlSerializer as J, UrlSegment as K, UrlSegmentGroup as L, UrlSerializer as M, NavigationCancel as N, OutletContext as O, PRIMARY_OUTLET as P, UrlTree as Q, RouterOutlet as R, Scroll as S, TitleStrategy as T, UrlHandlingStrategy as U, loadChildren as V, afterNextNavigation as W, isUrlTree as X, RouterConfigLoader as Y, NavigationTransitions as Z, NAVIGATION_ERROR_HANDLER as _, ROUTER_OUTLET_DATA as a, INPUT_BINDER as a0, createViewTransition as a1, CREATE_VIEW_TRANSITION as a2, VIEW_TRANSITION_OPTIONS as a3, stringifyEvent as a4, ActivationStart as b, createUrlTreeFromSnapshot as c, ChildActivationStart as d, GuardsCheckStart as e, NavigationCancellationCode as f, NavigationEnd as g, NavigationError as h, NavigationSkipped as i, NavigationSkippedCode as j, NavigationStart as k, ResolveEnd as l, ResolveStart as m, RouteConfigLoadEnd as n, RouteConfigLoadStart as o, RouterEvent as p, RoutesRecognized as q, RedirectCommand as r, RouteReuseStrategy as s, Router as t, ROUTER_CONFIGURATION as u, ROUTES as v, ChildrenOutletContexts as w, ActivatedRoute as x, ActivatedRouteSnapshot as y, RouterState as z, ɵEmptyOutletComponent as ɵ };\n","/**\n * @license Angular v19.2.5\n * (c) 2010-2025 Google LLC. https://angular.io/\n * License: MIT\n */\n\nimport * as i3 from '@angular/common';\nimport { HashLocationStrategy, LocationStrategy, ViewportScroller, LOCATION_INITIALIZED, Location, PathLocationStrategy } from '@angular/common';\nimport * as i0 from '@angular/core';\nimport { ɵRuntimeError as _RuntimeError, ɵɵsanitizeUrlOrResourceUrl as __sanitizeUrlOrResourceUrl, booleanAttribute, HostListener, Input, HostBinding, Attribute, Directive, EventEmitter, Output, ContentChildren, Optional, createEnvironmentInjector, Injectable, InjectionToken, makeEnvironmentProviders, APP_BOOTSTRAP_LISTENER, ENVIRONMENT_INITIALIZER, inject, Injector, ApplicationRef, InjectFlags, APP_INITIALIZER, NgZone, SkipSelf, NgModule } from '@angular/core';\nimport { g as NavigationEnd, X as isUrlTree, t as Router, x as ActivatedRoute, Y as RouterConfigLoader, k as NavigationStart, i as NavigationSkipped, j as NavigationSkippedCode, S as Scroll, M as UrlSerializer, Z as NavigationTransitions, v as ROUTES, u as ROUTER_CONFIGURATION, _ as NAVIGATION_ERROR_HANDLER, $ as RoutedComponentInputBinder, a0 as INPUT_BINDER, a1 as createViewTransition, a2 as CREATE_VIEW_TRANSITION, a3 as VIEW_TRANSITION_OPTIONS, W as afterNextNavigation, a4 as stringifyEvent, J as DefaultUrlSerializer, w as ChildrenOutletContexts, R as RouterOutlet, ɵ as _EmptyOutletComponent } from './router-LSBBtrLI.mjs';\nimport { Subject, of, from } from 'rxjs';\nimport { mergeAll, catchError, filter, concatMap, mergeMap } from 'rxjs/operators';\n\n/**\n * @description\n *\n * When applied to an element in a template, makes that element a link\n * that initiates navigation to a route. Navigation opens one or more routed components\n * in one or more `` locations on the page.\n *\n * Given a route configuration `[{ path: 'user/:name', component: UserCmp }]`,\n * the following creates a static link to the route:\n * `link to user component`\n *\n * You can use dynamic values to generate the link.\n * For a dynamic link, pass an array of path segments,\n * followed by the params for each segment.\n * For example, `['/team', teamId, 'user', userName, {details: true}]`\n * generates a link to `/team/11/user/bob;details=true`.\n *\n * Multiple static segments can be merged into one term and combined with dynamic segments.\n * For example, `['/team/11/user', userName, {details: true}]`\n *\n * The input that you provide to the link is treated as a delta to the current URL.\n * For instance, suppose the current URL is `/user/(box//aux:team)`.\n * The link `Jim` creates the URL\n * `/user/(jim//aux:team)`.\n * See {@link Router#createUrlTree} for more information.\n *\n * @usageNotes\n *\n * You can use absolute or relative paths in a link, set query parameters,\n * control how parameters are handled, and keep a history of navigation states.\n *\n * ### Relative link paths\n *\n * The first segment name can be prepended with `/`, `./`, or `../`.\n * * If the first segment begins with `/`, the router looks up the route from the root of the\n * app.\n * * If the first segment begins with `./`, or doesn't begin with a slash, the router\n * looks in the children of the current activated route.\n * * If the first segment begins with `../`, the router goes up one level in the route tree.\n *\n * ### Setting and handling query params and fragments\n *\n * The following link adds a query parameter and a fragment to the generated URL:\n *\n * ```html\n * \n * link to user component\n * \n * ```\n * By default, the directive constructs the new URL using the given query parameters.\n * The example generates the link: `/user/bob?debug=true#education`.\n *\n * You can instruct the directive to handle query parameters differently\n * by specifying the `queryParamsHandling` option in the link.\n * Allowed values are:\n *\n * - `'merge'`: Merge the given `queryParams` into the current query params.\n * - `'preserve'`: Preserve the current query params.\n *\n * For example:\n *\n * ```html\n * \n * link to user component\n * \n * ```\n *\n * `queryParams`, `fragment`, `queryParamsHandling`, `preserveFragment`, and `relativeTo`\n * cannot be used when the `routerLink` input is a `UrlTree`.\n *\n * See {@link UrlCreationOptions#queryParamsHandling}.\n *\n * ### Preserving navigation history\n *\n * You can provide a `state` value to be persisted to the browser's\n * [`History.state` property](https://developer.mozilla.org/en-US/docs/Web/API/History#Properties).\n * For example:\n *\n * ```html\n * \n * link to user component\n * \n * ```\n *\n * Use {@link Router#getCurrentNavigation} to retrieve a saved\n * navigation-state value. For example, to capture the `tracingId` during the `NavigationStart`\n * event:\n *\n * ```ts\n * // Get NavigationStart events\n * router.events.pipe(filter(e => e instanceof NavigationStart)).subscribe(e => {\n * const navigation = router.getCurrentNavigation();\n * tracingService.trace({id: navigation.extras.state.tracingId});\n * });\n * ```\n *\n * @ngModule RouterModule\n *\n * @publicApi\n */\nlet RouterLink = /*#__PURE__*/(() => {\n class RouterLink {\n router;\n route;\n tabIndexAttribute;\n renderer;\n el;\n locationStrategy;\n /**\n * Represents an `href` attribute value applied to a host element,\n * when a host element is ``. For other tags, the value is `null`.\n */\n href = null;\n /**\n * Represents the `target` attribute on a host element.\n * This is only used when the host element is an `` tag.\n */\n target;\n /**\n * Passed to {@link Router#createUrlTree} as part of the\n * `UrlCreationOptions`.\n * @see {@link UrlCreationOptions#queryParams}\n * @see {@link Router#createUrlTree}\n */\n queryParams;\n /**\n * Passed to {@link Router#createUrlTree} as part of the\n * `UrlCreationOptions`.\n * @see {@link UrlCreationOptions#fragment}\n * @see {@link Router#createUrlTree}\n */\n fragment;\n /**\n * Passed to {@link Router#createUrlTree} as part of the\n * `UrlCreationOptions`.\n * @see {@link UrlCreationOptions#queryParamsHandling}\n * @see {@link Router#createUrlTree}\n */\n queryParamsHandling;\n /**\n * Passed to {@link Router#navigateByUrl} as part of the\n * `NavigationBehaviorOptions`.\n * @see {@link NavigationBehaviorOptions#state}\n * @see {@link Router#navigateByUrl}\n */\n state;\n /**\n * Passed to {@link Router#navigateByUrl} as part of the\n * `NavigationBehaviorOptions`.\n * @see {@link NavigationBehaviorOptions#info}\n * @see {@link Router#navigateByUrl}\n */\n info;\n /**\n * Passed to {@link Router#createUrlTree} as part of the\n * `UrlCreationOptions`.\n * Specify a value here when you do not want to use the default value\n * for `routerLink`, which is the current activated route.\n * Note that a value of `undefined` here will use the `routerLink` default.\n * @see {@link UrlCreationOptions#relativeTo}\n * @see {@link Router#createUrlTree}\n */\n relativeTo;\n /** Whether a host element is an `` tag. */\n isAnchorElement;\n subscription;\n /** @internal */\n onChanges = new Subject();\n constructor(router, route, tabIndexAttribute, renderer, el, locationStrategy) {\n this.router = router;\n this.route = route;\n this.tabIndexAttribute = tabIndexAttribute;\n this.renderer = renderer;\n this.el = el;\n this.locationStrategy = locationStrategy;\n const tagName = el.nativeElement.tagName?.toLowerCase();\n this.isAnchorElement = tagName === 'a' || tagName === 'area';\n if (this.isAnchorElement) {\n this.subscription = router.events.subscribe(s => {\n if (s instanceof NavigationEnd) {\n this.updateHref();\n }\n });\n } else {\n this.setTabIndexIfNotOnNativeEl('0');\n }\n }\n /**\n * Passed to {@link Router#createUrlTree} as part of the\n * `UrlCreationOptions`.\n * @see {@link UrlCreationOptions#preserveFragment}\n * @see {@link Router#createUrlTree}\n */\n preserveFragment = false;\n /**\n * Passed to {@link Router#navigateByUrl} as part of the\n * `NavigationBehaviorOptions`.\n * @see {@link NavigationBehaviorOptions#skipLocationChange}\n * @see {@link Router#navigateByUrl}\n */\n skipLocationChange = false;\n /**\n * Passed to {@link Router#navigateByUrl} as part of the\n * `NavigationBehaviorOptions`.\n * @see {@link NavigationBehaviorOptions#replaceUrl}\n * @see {@link Router#navigateByUrl}\n */\n replaceUrl = false;\n /**\n * Modifies the tab index if there was not a tabindex attribute on the element during\n * instantiation.\n */\n setTabIndexIfNotOnNativeEl(newTabIndex) {\n if (this.tabIndexAttribute != null /* both `null` and `undefined` */ || this.isAnchorElement) {\n return;\n }\n this.applyAttributeValue('tabindex', newTabIndex);\n }\n /** @nodoc */\n // TODO(atscott): Remove changes parameter in major version as a breaking change.\n ngOnChanges(changes) {\n if (ngDevMode && isUrlTree(this.routerLinkInput) && (this.fragment !== undefined || this.queryParams || this.queryParamsHandling || this.preserveFragment || this.relativeTo)) {\n throw new _RuntimeError(4016 /* RuntimeErrorCode.INVALID_ROUTER_LINK_INPUTS */, 'Cannot configure queryParams or fragment when using a UrlTree as the routerLink input value.');\n }\n if (this.isAnchorElement) {\n this.updateHref();\n }\n // This is subscribed to by `RouterLinkActive` so that it knows to update when there are changes\n // to the RouterLinks it's tracking.\n this.onChanges.next(this);\n }\n routerLinkInput = null;\n /**\n * Commands to pass to {@link Router#createUrlTree} or a `UrlTree`.\n * - **array**: commands to pass to {@link Router#createUrlTree}.\n * - **string**: shorthand for array of commands with just the string, i.e. `['/route']`\n * - **UrlTree**: a `UrlTree` for this link rather than creating one from the commands\n * and other inputs that correspond to properties of `UrlCreationOptions`.\n * - **null|undefined**: effectively disables the `routerLink`\n * @see {@link Router#createUrlTree}\n */\n set routerLink(commandsOrUrlTree) {\n if (commandsOrUrlTree == null) {\n this.routerLinkInput = null;\n this.setTabIndexIfNotOnNativeEl(null);\n } else {\n if (isUrlTree(commandsOrUrlTree)) {\n this.routerLinkInput = commandsOrUrlTree;\n } else {\n this.routerLinkInput = Array.isArray(commandsOrUrlTree) ? commandsOrUrlTree : [commandsOrUrlTree];\n }\n this.setTabIndexIfNotOnNativeEl('0');\n }\n }\n /** @nodoc */\n onClick(button, ctrlKey, shiftKey, altKey, metaKey) {\n const urlTree = this.urlTree;\n if (urlTree === null) {\n return true;\n }\n if (this.isAnchorElement) {\n if (button !== 0 || ctrlKey || shiftKey || altKey || metaKey) {\n return true;\n }\n if (typeof this.target === 'string' && this.target != '_self') {\n return true;\n }\n }\n const extras = {\n skipLocationChange: this.skipLocationChange,\n replaceUrl: this.replaceUrl,\n state: this.state,\n info: this.info\n };\n this.router.navigateByUrl(urlTree, extras);\n // Return `false` for `` elements to prevent default action\n // and cancel the native behavior, since the navigation is handled\n // by the Router.\n return !this.isAnchorElement;\n }\n /** @nodoc */\n ngOnDestroy() {\n this.subscription?.unsubscribe();\n }\n updateHref() {\n const urlTree = this.urlTree;\n this.href = urlTree !== null && this.locationStrategy ? this.locationStrategy?.prepareExternalUrl(this.router.serializeUrl(urlTree)) : null;\n const sanitizedValue = this.href === null ? null :\n // This class represents a directive that can be added to both `` elements,\n // as well as other elements. As a result, we can't define security context at\n // compile time. So the security context is deferred to runtime.\n // The `ɵɵsanitizeUrlOrResourceUrl` selects the necessary sanitizer function\n // based on the tag and property names. The logic mimics the one from\n // `packages/compiler/src/schema/dom_security_schema.ts`, which is used at compile time.\n //\n // Note: we should investigate whether we can switch to using `@HostBinding('attr.href')`\n // instead of applying a value via a renderer, after a final merge of the\n // `RouterLinkWithHref` directive.\n __sanitizeUrlOrResourceUrl(this.href, this.el.nativeElement.tagName.toLowerCase(), 'href');\n this.applyAttributeValue('href', sanitizedValue);\n }\n applyAttributeValue(attrName, attrValue) {\n const renderer = this.renderer;\n const nativeElement = this.el.nativeElement;\n if (attrValue !== null) {\n renderer.setAttribute(nativeElement, attrName, attrValue);\n } else {\n renderer.removeAttribute(nativeElement, attrName);\n }\n }\n get urlTree() {\n if (this.routerLinkInput === null) {\n return null;\n } else if (isUrlTree(this.routerLinkInput)) {\n return this.routerLinkInput;\n }\n return this.router.createUrlTree(this.routerLinkInput, {\n // If the `relativeTo` input is not defined, we want to use `this.route` by default.\n // Otherwise, we should use the value provided by the user in the input.\n relativeTo: this.relativeTo !== undefined ? this.relativeTo : this.route,\n queryParams: this.queryParams,\n fragment: this.fragment,\n queryParamsHandling: this.queryParamsHandling,\n preserveFragment: this.preserveFragment\n });\n }\n static ɵfac = function RouterLink_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || RouterLink)(i0.ɵɵdirectiveInject(Router), i0.ɵɵdirectiveInject(ActivatedRoute), i0.ɵɵinjectAttribute('tabindex'), i0.ɵɵdirectiveInject(i0.Renderer2), i0.ɵɵdirectiveInject(i0.ElementRef), i0.ɵɵdirectiveInject(i3.LocationStrategy));\n };\n static ɵdir = /* @__PURE__ */i0.ɵɵdefineDirective({\n type: RouterLink,\n selectors: [[\"\", \"routerLink\", \"\"]],\n hostVars: 1,\n hostBindings: function RouterLink_HostBindings(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵlistener(\"click\", function RouterLink_click_HostBindingHandler($event) {\n return ctx.onClick($event.button, $event.ctrlKey, $event.shiftKey, $event.altKey, $event.metaKey);\n });\n }\n if (rf & 2) {\n i0.ɵɵattribute(\"target\", ctx.target);\n }\n },\n inputs: {\n target: \"target\",\n queryParams: \"queryParams\",\n fragment: \"fragment\",\n queryParamsHandling: \"queryParamsHandling\",\n state: \"state\",\n info: \"info\",\n relativeTo: \"relativeTo\",\n preserveFragment: [2, \"preserveFragment\", \"preserveFragment\", booleanAttribute],\n skipLocationChange: [2, \"skipLocationChange\", \"skipLocationChange\", booleanAttribute],\n replaceUrl: [2, \"replaceUrl\", \"replaceUrl\", booleanAttribute],\n routerLink: \"routerLink\"\n },\n features: [i0.ɵɵNgOnChangesFeature]\n });\n }\n return RouterLink;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/**\n *\n * @description\n *\n * Tracks whether the linked route of an element is currently active, and allows you\n * to specify one or more CSS classes to add to the element when the linked route\n * is active.\n *\n * Use this directive to create a visual distinction for elements associated with an active route.\n * For example, the following code highlights the word \"Bob\" when the router\n * activates the associated route:\n *\n * ```html\n * Bob\n * ```\n *\n * Whenever the URL is either '/user' or '/user/bob', the \"active-link\" class is\n * added to the anchor tag. If the URL changes, the class is removed.\n *\n * You can set more than one class using a space-separated string or an array.\n * For example:\n *\n * ```html\n * Bob\n * Bob\n * ```\n *\n * To add the classes only when the URL matches the link exactly, add the option `exact: true`:\n *\n * ```html\n * Bob\n * ```\n *\n * To directly check the `isActive` status of the link, assign the `RouterLinkActive`\n * instance to a template variable.\n * For example, the following checks the status without assigning any CSS classes:\n *\n * ```html\n * \n * Bob {{ rla.isActive ? '(already open)' : ''}}\n * \n * ```\n *\n * You can apply the `RouterLinkActive` directive to an ancestor of linked elements.\n * For example, the following sets the active-link class on the `
` parent tag\n * when the URL is either '/user/jim' or '/user/bob'.\n *\n * ```html\n *
\n * Jim\n * Bob\n *
\n * ```\n *\n * The `RouterLinkActive` directive can also be used to set the aria-current attribute\n * to provide an alternative distinction for active elements to visually impaired users.\n *\n * For example, the following code adds the 'active' class to the Home Page link when it is\n * indeed active and in such case also sets its aria-current attribute to 'page':\n *\n * ```html\n * Home Page\n * ```\n *\n * @ngModule RouterModule\n *\n * @publicApi\n */\nlet RouterLinkActive = /*#__PURE__*/(() => {\n class RouterLinkActive {\n router;\n element;\n renderer;\n cdr;\n link;\n links;\n classes = [];\n routerEventsSubscription;\n linkInputChangesSubscription;\n _isActive = false;\n get isActive() {\n return this._isActive;\n }\n /**\n * Options to configure how to determine if the router link is active.\n *\n * These options are passed to the `Router.isActive()` function.\n *\n * @see {@link Router#isActive}\n */\n routerLinkActiveOptions = {\n exact: false\n };\n /**\n * Aria-current attribute to apply when the router link is active.\n *\n * Possible values: `'page'` | `'step'` | `'location'` | `'date'` | `'time'` | `true` | `false`.\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-current}\n */\n ariaCurrentWhenActive;\n /**\n *\n * You can use the output `isActiveChange` to get notified each time the link becomes\n * active or inactive.\n *\n * Emits:\n * true -> Route is active\n * false -> Route is inactive\n *\n * ```html\n * Bob\n * ```\n */\n isActiveChange = new EventEmitter();\n constructor(router, element, renderer, cdr, link) {\n this.router = router;\n this.element = element;\n this.renderer = renderer;\n this.cdr = cdr;\n this.link = link;\n this.routerEventsSubscription = router.events.subscribe(s => {\n if (s instanceof NavigationEnd) {\n this.update();\n }\n });\n }\n /** @nodoc */\n ngAfterContentInit() {\n // `of(null)` is used to force subscribe body to execute once immediately (like `startWith`).\n of(this.links.changes, of(null)).pipe(mergeAll()).subscribe(_ => {\n this.update();\n this.subscribeToEachLinkOnChanges();\n });\n }\n subscribeToEachLinkOnChanges() {\n this.linkInputChangesSubscription?.unsubscribe();\n const allLinkChanges = [...this.links.toArray(), this.link].filter(link => !!link).map(link => link.onChanges);\n this.linkInputChangesSubscription = from(allLinkChanges).pipe(mergeAll()).subscribe(link => {\n if (this._isActive !== this.isLinkActive(this.router)(link)) {\n this.update();\n }\n });\n }\n set routerLinkActive(data) {\n const classes = Array.isArray(data) ? data : data.split(' ');\n this.classes = classes.filter(c => !!c);\n }\n /** @nodoc */\n ngOnChanges(changes) {\n this.update();\n }\n /** @nodoc */\n ngOnDestroy() {\n this.routerEventsSubscription.unsubscribe();\n this.linkInputChangesSubscription?.unsubscribe();\n }\n update() {\n if (!this.links || !this.router.navigated) return;\n queueMicrotask(() => {\n const hasActiveLinks = this.hasActiveLinks();\n this.classes.forEach(c => {\n if (hasActiveLinks) {\n this.renderer.addClass(this.element.nativeElement, c);\n } else {\n this.renderer.removeClass(this.element.nativeElement, c);\n }\n });\n if (hasActiveLinks && this.ariaCurrentWhenActive !== undefined) {\n this.renderer.setAttribute(this.element.nativeElement, 'aria-current', this.ariaCurrentWhenActive.toString());\n } else {\n this.renderer.removeAttribute(this.element.nativeElement, 'aria-current');\n }\n // Only emit change if the active state changed.\n if (this._isActive !== hasActiveLinks) {\n this._isActive = hasActiveLinks;\n this.cdr.markForCheck();\n // Emit on isActiveChange after classes are updated\n this.isActiveChange.emit(hasActiveLinks);\n }\n });\n }\n isLinkActive(router) {\n const options = isActiveMatchOptions(this.routerLinkActiveOptions) ? this.routerLinkActiveOptions :\n // While the types should disallow `undefined` here, it's possible without strict inputs\n this.routerLinkActiveOptions.exact || false;\n return link => {\n const urlTree = link.urlTree;\n return urlTree ? router.isActive(urlTree, options) : false;\n };\n }\n hasActiveLinks() {\n const isActiveCheckFn = this.isLinkActive(this.router);\n return this.link && isActiveCheckFn(this.link) || this.links.some(isActiveCheckFn);\n }\n static ɵfac = function RouterLinkActive_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || RouterLinkActive)(i0.ɵɵdirectiveInject(Router), i0.ɵɵdirectiveInject(i0.ElementRef), i0.ɵɵdirectiveInject(i0.Renderer2), i0.ɵɵdirectiveInject(i0.ChangeDetectorRef), i0.ɵɵdirectiveInject(RouterLink, 8));\n };\n static ɵdir = /* @__PURE__ */i0.ɵɵdefineDirective({\n type: RouterLinkActive,\n selectors: [[\"\", \"routerLinkActive\", \"\"]],\n contentQueries: function RouterLinkActive_ContentQueries(rf, ctx, dirIndex) {\n if (rf & 1) {\n i0.ɵɵcontentQuery(dirIndex, RouterLink, 5);\n }\n if (rf & 2) {\n let _t;\n i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.links = _t);\n }\n },\n inputs: {\n routerLinkActiveOptions: \"routerLinkActiveOptions\",\n ariaCurrentWhenActive: \"ariaCurrentWhenActive\",\n routerLinkActive: \"routerLinkActive\"\n },\n outputs: {\n isActiveChange: \"isActiveChange\"\n },\n exportAs: [\"routerLinkActive\"],\n features: [i0.ɵɵNgOnChangesFeature]\n });\n }\n return RouterLinkActive;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * Use instead of `'paths' in options` to be compatible with property renaming\n */\nfunction isActiveMatchOptions(options) {\n return !!options.paths;\n}\n\n/**\n * @description\n *\n * Provides a preloading strategy.\n *\n * @publicApi\n */\nclass PreloadingStrategy {}\n/**\n * @description\n *\n * Provides a preloading strategy that preloads all modules as quickly as possible.\n *\n * ```ts\n * RouterModule.forRoot(ROUTES, {preloadingStrategy: PreloadAllModules})\n * ```\n *\n * @publicApi\n */\nlet PreloadAllModules = /*#__PURE__*/(() => {\n class PreloadAllModules {\n preload(route, fn) {\n return fn().pipe(catchError(() => of(null)));\n }\n static ɵfac = function PreloadAllModules_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || PreloadAllModules)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: PreloadAllModules,\n factory: PreloadAllModules.ɵfac,\n providedIn: 'root'\n });\n }\n return PreloadAllModules;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * @description\n *\n * Provides a preloading strategy that does not preload any modules.\n *\n * This strategy is enabled by default.\n *\n * @publicApi\n */\nlet NoPreloading = /*#__PURE__*/(() => {\n class NoPreloading {\n preload(route, fn) {\n return of(null);\n }\n static ɵfac = function NoPreloading_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || NoPreloading)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: NoPreloading,\n factory: NoPreloading.ɵfac,\n providedIn: 'root'\n });\n }\n return NoPreloading;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * The preloader optimistically loads all router configurations to\n * make navigations into lazily-loaded sections of the application faster.\n *\n * The preloader runs in the background. When the router bootstraps, the preloader\n * starts listening to all navigation events. After every such event, the preloader\n * will check if any configurations can be loaded lazily.\n *\n * If a route is protected by `canLoad` guards, the preloaded will not load it.\n *\n * @publicApi\n */\nlet RouterPreloader = /*#__PURE__*/(() => {\n class RouterPreloader {\n router;\n injector;\n preloadingStrategy;\n loader;\n subscription;\n constructor(router, compiler, injector, preloadingStrategy, loader) {\n this.router = router;\n this.injector = injector;\n this.preloadingStrategy = preloadingStrategy;\n this.loader = loader;\n }\n setUpPreloading() {\n this.subscription = this.router.events.pipe(filter(e => e instanceof NavigationEnd), concatMap(() => this.preload())).subscribe(() => {});\n }\n preload() {\n return this.processRoutes(this.injector, this.router.config);\n }\n /** @nodoc */\n ngOnDestroy() {\n if (this.subscription) {\n this.subscription.unsubscribe();\n }\n }\n processRoutes(injector, routes) {\n const res = [];\n for (const route of routes) {\n if (route.providers && !route._injector) {\n route._injector = createEnvironmentInjector(route.providers, injector, `Route: ${route.path}`);\n }\n const injectorForCurrentRoute = route._injector ?? injector;\n const injectorForChildren = route._loadedInjector ?? injectorForCurrentRoute;\n // Note that `canLoad` is only checked as a condition that prevents `loadChildren` and not\n // `loadComponent`. `canLoad` guards only block loading of child routes by design. This\n // happens as a consequence of needing to descend into children for route matching immediately\n // while component loading is deferred until route activation. Because `canLoad` guards can\n // have side effects, we cannot execute them here so we instead skip preloading altogether\n // when present. Lastly, it remains to be decided whether `canLoad` should behave this way\n // at all. Code splitting and lazy loading is separate from client-side authorization checks\n // and should not be used as a security measure to prevent loading of code.\n if (route.loadChildren && !route._loadedRoutes && route.canLoad === undefined || route.loadComponent && !route._loadedComponent) {\n res.push(this.preloadConfig(injectorForCurrentRoute, route));\n }\n if (route.children || route._loadedRoutes) {\n res.push(this.processRoutes(injectorForChildren, route.children ?? route._loadedRoutes));\n }\n }\n return from(res).pipe(mergeAll());\n }\n preloadConfig(injector, route) {\n return this.preloadingStrategy.preload(route, () => {\n let loadedChildren$;\n if (route.loadChildren && route.canLoad === undefined) {\n loadedChildren$ = this.loader.loadChildren(injector, route);\n } else {\n loadedChildren$ = of(null);\n }\n const recursiveLoadChildren$ = loadedChildren$.pipe(mergeMap(config => {\n if (config === null) {\n return of(void 0);\n }\n route._loadedRoutes = config.routes;\n route._loadedInjector = config.injector;\n // If the loaded config was a module, use that as the module/module injector going\n // forward. Otherwise, continue using the current module/module injector.\n return this.processRoutes(config.injector ?? injector, config.routes);\n }));\n if (route.loadComponent && !route._loadedComponent) {\n const loadComponent$ = this.loader.loadComponent(route);\n return from([recursiveLoadChildren$, loadComponent$]).pipe(mergeAll());\n } else {\n return recursiveLoadChildren$;\n }\n });\n }\n static ɵfac = function RouterPreloader_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || RouterPreloader)(i0.ɵɵinject(Router), i0.ɵɵinject(i0.Compiler), i0.ɵɵinject(i0.EnvironmentInjector), i0.ɵɵinject(PreloadingStrategy), i0.ɵɵinject(RouterConfigLoader));\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: RouterPreloader,\n factory: RouterPreloader.ɵfac,\n providedIn: 'root'\n });\n }\n return RouterPreloader;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nconst ROUTER_SCROLLER = /*#__PURE__*/new InjectionToken('');\nlet RouterScroller = /*#__PURE__*/(() => {\n class RouterScroller {\n urlSerializer;\n transitions;\n viewportScroller;\n zone;\n options;\n routerEventsSubscription;\n scrollEventsSubscription;\n lastId = 0;\n lastSource = 'imperative';\n restoredId = 0;\n store = {};\n /** @nodoc */\n constructor(urlSerializer, transitions, viewportScroller, zone, options = {}) {\n this.urlSerializer = urlSerializer;\n this.transitions = transitions;\n this.viewportScroller = viewportScroller;\n this.zone = zone;\n this.options = options;\n // Default both options to 'disabled'\n options.scrollPositionRestoration ||= 'disabled';\n options.anchorScrolling ||= 'disabled';\n }\n init() {\n // we want to disable the automatic scrolling because having two places\n // responsible for scrolling results race conditions, especially given\n // that browser don't implement this behavior consistently\n if (this.options.scrollPositionRestoration !== 'disabled') {\n this.viewportScroller.setHistoryScrollRestoration('manual');\n }\n this.routerEventsSubscription = this.createScrollEvents();\n this.scrollEventsSubscription = this.consumeScrollEvents();\n }\n createScrollEvents() {\n return this.transitions.events.subscribe(e => {\n if (e instanceof NavigationStart) {\n // store the scroll position of the current stable navigations.\n this.store[this.lastId] = this.viewportScroller.getScrollPosition();\n this.lastSource = e.navigationTrigger;\n this.restoredId = e.restoredState ? e.restoredState.navigationId : 0;\n } else if (e instanceof NavigationEnd) {\n this.lastId = e.id;\n this.scheduleScrollEvent(e, this.urlSerializer.parse(e.urlAfterRedirects).fragment);\n } else if (e instanceof NavigationSkipped && e.code === NavigationSkippedCode.IgnoredSameUrlNavigation) {\n this.lastSource = undefined;\n this.restoredId = 0;\n this.scheduleScrollEvent(e, this.urlSerializer.parse(e.url).fragment);\n }\n });\n }\n consumeScrollEvents() {\n return this.transitions.events.subscribe(e => {\n if (!(e instanceof Scroll)) return;\n // a popstate event. The pop state event will always ignore anchor scrolling.\n if (e.position) {\n if (this.options.scrollPositionRestoration === 'top') {\n this.viewportScroller.scrollToPosition([0, 0]);\n } else if (this.options.scrollPositionRestoration === 'enabled') {\n this.viewportScroller.scrollToPosition(e.position);\n }\n // imperative navigation \"forward\"\n } else {\n if (e.anchor && this.options.anchorScrolling === 'enabled') {\n this.viewportScroller.scrollToAnchor(e.anchor);\n } else if (this.options.scrollPositionRestoration !== 'disabled') {\n this.viewportScroller.scrollToPosition([0, 0]);\n }\n }\n });\n }\n scheduleScrollEvent(routerEvent, anchor) {\n this.zone.runOutsideAngular(() => {\n // The scroll event needs to be delayed until after change detection. Otherwise, we may\n // attempt to restore the scroll position before the router outlet has fully rendered the\n // component by executing its update block of the template function.\n setTimeout(() => {\n this.zone.run(() => {\n this.transitions.events.next(new Scroll(routerEvent, this.lastSource === 'popstate' ? this.store[this.restoredId] : null, anchor));\n });\n }, 0);\n });\n }\n /** @nodoc */\n ngOnDestroy() {\n this.routerEventsSubscription?.unsubscribe();\n this.scrollEventsSubscription?.unsubscribe();\n }\n static ɵfac = function RouterScroller_Factory(__ngFactoryType__) {\n i0.ɵɵinvalidFactory();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: RouterScroller,\n factory: RouterScroller.ɵfac\n });\n }\n return RouterScroller;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n/**\n * Sets up providers necessary to enable `Router` functionality for the application.\n * Allows to configure a set of routes as well as extra features that should be enabled.\n *\n * @usageNotes\n *\n * Basic example of how you can add a Router to your application:\n * ```ts\n * const appRoutes: Routes = [];\n * bootstrapApplication(AppComponent, {\n * providers: [provideRouter(appRoutes)]\n * });\n * ```\n *\n * You can also enable optional features in the Router by adding functions from the `RouterFeatures`\n * type:\n * ```ts\n * const appRoutes: Routes = [];\n * bootstrapApplication(AppComponent,\n * {\n * providers: [\n * provideRouter(appRoutes,\n * withDebugTracing(),\n * withRouterConfig({paramsInheritanceStrategy: 'always'}))\n * ]\n * }\n * );\n * ```\n *\n * @see {@link RouterFeatures}\n *\n * @publicApi\n * @param routes A set of `Route`s to use for the application routing table.\n * @param features Optional features to configure additional router behaviors.\n * @returns A set of providers to setup a Router.\n */\nfunction provideRouter(routes, ...features) {\n return makeEnvironmentProviders([{\n provide: ROUTES,\n multi: true,\n useValue: routes\n }, typeof ngDevMode === 'undefined' || ngDevMode ? {\n provide: ROUTER_IS_PROVIDED,\n useValue: true\n } : [], {\n provide: ActivatedRoute,\n useFactory: rootRoute,\n deps: [Router]\n }, {\n provide: APP_BOOTSTRAP_LISTENER,\n multi: true,\n useFactory: getBootstrapListener\n }, features.map(feature => feature.ɵproviders)]);\n}\nfunction rootRoute(router) {\n return router.routerState.root;\n}\n/**\n * Helper function to create an object that represents a Router feature.\n */\nfunction routerFeature(kind, providers) {\n return {\n ɵkind: kind,\n ɵproviders: providers\n };\n}\n/**\n * An Injection token used to indicate whether `provideRouter` or `RouterModule.forRoot` was ever\n * called.\n */\nconst ROUTER_IS_PROVIDED = /*#__PURE__*/new InjectionToken('', {\n providedIn: 'root',\n factory: () => false\n});\nconst routerIsProvidedDevModeCheck = {\n provide: ENVIRONMENT_INITIALIZER,\n multi: true,\n useFactory() {\n return () => {\n if (!inject(ROUTER_IS_PROVIDED)) {\n console.warn('`provideRoutes` was called without `provideRouter` or `RouterModule.forRoot`. ' + 'This is likely a mistake.');\n }\n };\n }\n};\n/**\n * Registers a DI provider for a set of routes.\n * @param routes The route configuration to provide.\n *\n * @usageNotes\n *\n * ```ts\n * @NgModule({\n * providers: [provideRoutes(ROUTES)]\n * })\n * class LazyLoadedChildModule {}\n * ```\n *\n * @deprecated If necessary, provide routes using the `ROUTES` `InjectionToken`.\n * @see {@link ROUTES}\n * @publicApi\n */\nfunction provideRoutes(routes) {\n return [{\n provide: ROUTES,\n multi: true,\n useValue: routes\n }, typeof ngDevMode === 'undefined' || ngDevMode ? routerIsProvidedDevModeCheck : []];\n}\n/**\n * Enables customizable scrolling behavior for router navigations.\n *\n * @usageNotes\n *\n * Basic example of how you can enable scrolling feature:\n * ```ts\n * const appRoutes: Routes = [];\n * bootstrapApplication(AppComponent,\n * {\n * providers: [\n * provideRouter(appRoutes, withInMemoryScrolling())\n * ]\n * }\n * );\n * ```\n *\n * @see {@link provideRouter}\n * @see {@link ViewportScroller}\n *\n * @publicApi\n * @param options Set of configuration parameters to customize scrolling behavior, see\n * `InMemoryScrollingOptions` for additional information.\n * @returns A set of providers for use with `provideRouter`.\n */\nfunction withInMemoryScrolling(options = {}) {\n const providers = [{\n provide: ROUTER_SCROLLER,\n useFactory: () => {\n const viewportScroller = inject(ViewportScroller);\n const zone = inject(NgZone);\n const transitions = inject(NavigationTransitions);\n const urlSerializer = inject(UrlSerializer);\n return new RouterScroller(urlSerializer, transitions, viewportScroller, zone, options);\n }\n }];\n return routerFeature(4 /* RouterFeatureKind.InMemoryScrollingFeature */, providers);\n}\nfunction getBootstrapListener() {\n const injector = inject(Injector);\n return bootstrappedComponentRef => {\n const ref = injector.get(ApplicationRef);\n if (bootstrappedComponentRef !== ref.components[0]) {\n return;\n }\n const router = injector.get(Router);\n const bootstrapDone = injector.get(BOOTSTRAP_DONE);\n if (injector.get(INITIAL_NAVIGATION) === 1 /* InitialNavigation.EnabledNonBlocking */) {\n router.initialNavigation();\n }\n injector.get(ROUTER_PRELOADER, null, InjectFlags.Optional)?.setUpPreloading();\n injector.get(ROUTER_SCROLLER, null, InjectFlags.Optional)?.init();\n router.resetRootComponentType(ref.componentTypes[0]);\n if (!bootstrapDone.closed) {\n bootstrapDone.next();\n bootstrapDone.complete();\n bootstrapDone.unsubscribe();\n }\n };\n}\n/**\n * A subject used to indicate that the bootstrapping phase is done. When initial navigation is\n * `enabledBlocking`, the first navigation waits until bootstrapping is finished before continuing\n * to the activation phase.\n */\nconst BOOTSTRAP_DONE = /*#__PURE__*/new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'bootstrap done indicator' : '', {\n factory: () => {\n return new Subject();\n }\n});\nconst INITIAL_NAVIGATION = /*#__PURE__*/new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'initial navigation' : '', {\n providedIn: 'root',\n factory: () => 1 /* InitialNavigation.EnabledNonBlocking */\n});\n/**\n * Configures initial navigation to start before the root component is created.\n *\n * The bootstrap is blocked until the initial navigation is complete. This should be set in case\n * you use [server-side rendering](guide/ssr), but do not enable [hydration](guide/hydration) for\n * your application.\n *\n * @usageNotes\n *\n * Basic example of how you can enable this navigation behavior:\n * ```ts\n * const appRoutes: Routes = [];\n * bootstrapApplication(AppComponent,\n * {\n * providers: [\n * provideRouter(appRoutes, withEnabledBlockingInitialNavigation())\n * ]\n * }\n * );\n * ```\n *\n * @see {@link provideRouter}\n *\n * @publicApi\n * @returns A set of providers for use with `provideRouter`.\n */\nfunction withEnabledBlockingInitialNavigation() {\n const providers = [{\n provide: INITIAL_NAVIGATION,\n useValue: 0 /* InitialNavigation.EnabledBlocking */\n }, {\n provide: APP_INITIALIZER,\n multi: true,\n deps: [Injector],\n useFactory: injector => {\n const locationInitialized = injector.get(LOCATION_INITIALIZED, Promise.resolve());\n return () => {\n return locationInitialized.then(() => {\n return new Promise(resolve => {\n const router = injector.get(Router);\n const bootstrapDone = injector.get(BOOTSTRAP_DONE);\n afterNextNavigation(router, () => {\n // Unblock APP_INITIALIZER in case the initial navigation was canceled or errored\n // without a redirect.\n resolve(true);\n });\n injector.get(NavigationTransitions).afterPreactivation = () => {\n // Unblock APP_INITIALIZER once we get to `afterPreactivation`. At this point, we\n // assume activation will complete successfully (even though this is not\n // guaranteed).\n resolve(true);\n return bootstrapDone.closed ? of(void 0) : bootstrapDone;\n };\n router.initialNavigation();\n });\n });\n };\n }\n }];\n return routerFeature(2 /* RouterFeatureKind.EnabledBlockingInitialNavigationFeature */, providers);\n}\n/**\n * Disables initial navigation.\n *\n * Use if there is a reason to have more control over when the router starts its initial navigation\n * due to some complex initialization logic.\n *\n * @usageNotes\n *\n * Basic example of how you can disable initial navigation:\n * ```ts\n * const appRoutes: Routes = [];\n * bootstrapApplication(AppComponent,\n * {\n * providers: [\n * provideRouter(appRoutes, withDisabledInitialNavigation())\n * ]\n * }\n * );\n * ```\n *\n * @see {@link provideRouter}\n *\n * @returns A set of providers for use with `provideRouter`.\n *\n * @publicApi\n */\nfunction withDisabledInitialNavigation() {\n const providers = [{\n provide: APP_INITIALIZER,\n multi: true,\n useFactory: () => {\n const router = inject(Router);\n return () => {\n router.setUpLocationChangeListener();\n };\n }\n }, {\n provide: INITIAL_NAVIGATION,\n useValue: 2 /* InitialNavigation.Disabled */\n }];\n return routerFeature(3 /* RouterFeatureKind.DisabledInitialNavigationFeature */, providers);\n}\n/**\n * Enables logging of all internal navigation events to the console.\n * Extra logging might be useful for debugging purposes to inspect Router event sequence.\n *\n * @usageNotes\n *\n * Basic example of how you can enable debug tracing:\n * ```ts\n * const appRoutes: Routes = [];\n * bootstrapApplication(AppComponent,\n * {\n * providers: [\n * provideRouter(appRoutes, withDebugTracing())\n * ]\n * }\n * );\n * ```\n *\n * @see {@link provideRouter}\n *\n * @returns A set of providers for use with `provideRouter`.\n *\n * @publicApi\n */\nfunction withDebugTracing() {\n let providers = [];\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n providers = [{\n provide: ENVIRONMENT_INITIALIZER,\n multi: true,\n useFactory: () => {\n const router = inject(Router);\n return () => router.events.subscribe(e => {\n // tslint:disable:no-console\n console.group?.(`Router Event: ${e.constructor.name}`);\n console.log(stringifyEvent(e));\n console.log(e);\n console.groupEnd?.();\n // tslint:enable:no-console\n });\n }\n }];\n } else {\n providers = [];\n }\n return routerFeature(1 /* RouterFeatureKind.DebugTracingFeature */, providers);\n}\nconst ROUTER_PRELOADER = /*#__PURE__*/new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'router preloader' : '');\n/**\n * Allows to configure a preloading strategy to use. The strategy is configured by providing a\n * reference to a class that implements a `PreloadingStrategy`.\n *\n * @usageNotes\n *\n * Basic example of how you can configure preloading:\n * ```ts\n * const appRoutes: Routes = [];\n * bootstrapApplication(AppComponent,\n * {\n * providers: [\n * provideRouter(appRoutes, withPreloading(PreloadAllModules))\n * ]\n * }\n * );\n * ```\n *\n * @see {@link provideRouter}\n *\n * @param preloadingStrategy A reference to a class that implements a `PreloadingStrategy` that\n * should be used.\n * @returns A set of providers for use with `provideRouter`.\n *\n * @publicApi\n */\nfunction withPreloading(preloadingStrategy) {\n const providers = [{\n provide: ROUTER_PRELOADER,\n useExisting: RouterPreloader\n }, {\n provide: PreloadingStrategy,\n useExisting: preloadingStrategy\n }];\n return routerFeature(0 /* RouterFeatureKind.PreloadingFeature */, providers);\n}\n/**\n * Allows to provide extra parameters to configure Router.\n *\n * @usageNotes\n *\n * Basic example of how you can provide extra configuration options:\n * ```ts\n * const appRoutes: Routes = [];\n * bootstrapApplication(AppComponent,\n * {\n * providers: [\n * provideRouter(appRoutes, withRouterConfig({\n * onSameUrlNavigation: 'reload'\n * }))\n * ]\n * }\n * );\n * ```\n *\n * @see {@link provideRouter}\n *\n * @param options A set of parameters to configure Router, see `RouterConfigOptions` for\n * additional information.\n * @returns A set of providers for use with `provideRouter`.\n *\n * @publicApi\n */\nfunction withRouterConfig(options) {\n const providers = [{\n provide: ROUTER_CONFIGURATION,\n useValue: options\n }];\n return routerFeature(5 /* RouterFeatureKind.RouterConfigurationFeature */, providers);\n}\n/**\n * Provides the location strategy that uses the URL fragment instead of the history API.\n *\n * @usageNotes\n *\n * Basic example of how you can use the hash location option:\n * ```ts\n * const appRoutes: Routes = [];\n * bootstrapApplication(AppComponent,\n * {\n * providers: [\n * provideRouter(appRoutes, withHashLocation())\n * ]\n * }\n * );\n * ```\n *\n * @see {@link provideRouter}\n * @see {@link /api/common/HashLocationStrategy HashLocationStrategy}\n *\n * @returns A set of providers for use with `provideRouter`.\n *\n * @publicApi\n */\nfunction withHashLocation() {\n const providers = [{\n provide: LocationStrategy,\n useClass: HashLocationStrategy\n }];\n return routerFeature(6 /* RouterFeatureKind.RouterHashLocationFeature */, providers);\n}\n/**\n * Provides a function which is called when a navigation error occurs.\n *\n * This function is run inside application's [injection context](guide/di/dependency-injection-context)\n * so you can use the [`inject`](api/core/inject) function.\n *\n * This function can return a `RedirectCommand` to convert the error to a redirect, similar to returning\n * a `UrlTree` or `RedirectCommand` from a guard. This will also prevent the `Router` from emitting\n * `NavigationError`; it will instead emit `NavigationCancel` with code NavigationCancellationCode.Redirect.\n * Return values other than `RedirectCommand` are ignored and do not change any behavior with respect to\n * how the `Router` handles the error.\n *\n * @usageNotes\n *\n * Basic example of how you can use the error handler option:\n * ```ts\n * const appRoutes: Routes = [];\n * bootstrapApplication(AppComponent,\n * {\n * providers: [\n * provideRouter(appRoutes, withNavigationErrorHandler((e: NavigationError) =>\n * inject(MyErrorTracker).trackError(e)))\n * ]\n * }\n * );\n * ```\n *\n * @see {@link NavigationError}\n * @see {@link /api/core/inject inject}\n * @see {@link runInInjectionContext}\n *\n * @returns A set of providers for use with `provideRouter`.\n *\n * @publicApi\n */\nfunction withNavigationErrorHandler(handler) {\n const providers = [{\n provide: NAVIGATION_ERROR_HANDLER,\n useValue: handler\n }];\n return routerFeature(7 /* RouterFeatureKind.NavigationErrorHandlerFeature */, providers);\n}\n/**\n * Enables binding information from the `Router` state directly to the inputs of the component in\n * `Route` configurations.\n *\n * @usageNotes\n *\n * Basic example of how you can enable the feature:\n * ```ts\n * const appRoutes: Routes = [];\n * bootstrapApplication(AppComponent,\n * {\n * providers: [\n * provideRouter(appRoutes, withComponentInputBinding())\n * ]\n * }\n * );\n * ```\n *\n * The router bindings information from any of the following sources:\n *\n * - query parameters\n * - path and matrix parameters\n * - static route data\n * - data from resolvers\n *\n * Duplicate keys are resolved in the same order from above, from least to greatest,\n * meaning that resolvers have the highest precedence and override any of the other information\n * from the route.\n *\n * Importantly, when an input does not have an item in the route data with a matching key, this\n * input is set to `undefined`. This prevents previous information from being\n * retained if the data got removed from the route (i.e. if a query parameter is removed).\n * Default values can be provided with a resolver on the route to ensure the value is always present\n * or an input and use an input transform in the component.\n *\n * @see {@link /guide/components/inputs#input-transforms Input Transforms}\n * @returns A set of providers for use with `provideRouter`.\n */\nfunction withComponentInputBinding() {\n const providers = [RoutedComponentInputBinder, {\n provide: INPUT_BINDER,\n useExisting: RoutedComponentInputBinder\n }];\n return routerFeature(8 /* RouterFeatureKind.ComponentInputBindingFeature */, providers);\n}\n/**\n * Enables view transitions in the Router by running the route activation and deactivation inside of\n * `document.startViewTransition`.\n *\n * Note: The View Transitions API is not available in all browsers. If the browser does not support\n * view transitions, the Router will not attempt to start a view transition and continue processing\n * the navigation as usual.\n *\n * @usageNotes\n *\n * Basic example of how you can enable the feature:\n * ```ts\n * const appRoutes: Routes = [];\n * bootstrapApplication(AppComponent,\n * {\n * providers: [\n * provideRouter(appRoutes, withViewTransitions())\n * ]\n * }\n * );\n * ```\n *\n * @returns A set of providers for use with `provideRouter`.\n * @see https://developer.chrome.com/docs/web-platform/view-transitions/\n * @see https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API\n * @developerPreview\n */\nfunction withViewTransitions(options) {\n const providers = [{\n provide: CREATE_VIEW_TRANSITION,\n useValue: createViewTransition\n }, {\n provide: VIEW_TRANSITION_OPTIONS,\n useValue: {\n skipNextTransition: !!options?.skipInitialTransition,\n ...options\n }\n }];\n return routerFeature(9 /* RouterFeatureKind.ViewTransitionsFeature */, providers);\n}\n\n/**\n * The directives defined in the `RouterModule`.\n */\nconst ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkActive, _EmptyOutletComponent];\n/**\n * @docsNotRequired\n */\nconst ROUTER_FORROOT_GUARD = /*#__PURE__*/new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'router duplicate forRoot guard' : '');\n// TODO(atscott): All of these except `ActivatedRoute` are `providedIn: 'root'`. They are only kept\n// here to avoid a breaking change whereby the provider order matters based on where the\n// `RouterModule`/`RouterTestingModule` is imported. These can/should be removed as a \"breaking\"\n// change in a major version.\nconst ROUTER_PROVIDERS = [Location, {\n provide: UrlSerializer,\n useClass: DefaultUrlSerializer\n}, Router, ChildrenOutletContexts, {\n provide: ActivatedRoute,\n useFactory: rootRoute,\n deps: [Router]\n}, RouterConfigLoader,\n// Only used to warn when `provideRoutes` is used without `RouterModule` or `provideRouter`. Can\n// be removed when `provideRoutes` is removed.\ntypeof ngDevMode === 'undefined' || ngDevMode ? {\n provide: ROUTER_IS_PROVIDED,\n useValue: true\n} : []];\n/**\n * @description\n *\n * Adds directives and providers for in-app navigation among views defined in an application.\n * Use the Angular `Router` service to declaratively specify application states and manage state\n * transitions.\n *\n * You can import this NgModule multiple times, once for each lazy-loaded bundle.\n * However, only one `Router` service can be active.\n * To ensure this, there are two ways to register routes when importing this module:\n *\n * * The `forRoot()` method creates an `NgModule` that contains all the directives, the given\n * routes, and the `Router` service itself.\n * * The `forChild()` method creates an `NgModule` that contains all the directives and the given\n * routes, but does not include the `Router` service.\n *\n * @see [Routing and Navigation guide](guide/routing/common-router-tasks) for an\n * overview of how the `Router` service should be used.\n *\n * @publicApi\n */\nlet RouterModule = /*#__PURE__*/(() => {\n class RouterModule {\n constructor() {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n inject(ROUTER_FORROOT_GUARD, {\n optional: true\n });\n }\n }\n /**\n * Creates and configures a module with all the router providers and directives.\n * Optionally sets up an application listener to perform an initial navigation.\n *\n * When registering the NgModule at the root, import as follows:\n *\n * ```ts\n * @NgModule({\n * imports: [RouterModule.forRoot(ROUTES)]\n * })\n * class MyNgModule {}\n * ```\n *\n * @param routes An array of `Route` objects that define the navigation paths for the application.\n * @param config An `ExtraOptions` configuration object that controls how navigation is performed.\n * @return The new `NgModule`.\n *\n */\n static forRoot(routes, config) {\n return {\n ngModule: RouterModule,\n providers: [ROUTER_PROVIDERS, typeof ngDevMode === 'undefined' || ngDevMode ? config?.enableTracing ? withDebugTracing().ɵproviders : [] : [], {\n provide: ROUTES,\n multi: true,\n useValue: routes\n }, typeof ngDevMode === 'undefined' || ngDevMode ? {\n provide: ROUTER_FORROOT_GUARD,\n useFactory: provideForRootGuard,\n deps: [[Router, new Optional(), new SkipSelf()]]\n } : [], config?.errorHandler ? {\n provide: NAVIGATION_ERROR_HANDLER,\n useValue: config.errorHandler\n } : [], {\n provide: ROUTER_CONFIGURATION,\n useValue: config ? config : {}\n }, config?.useHash ? provideHashLocationStrategy() : providePathLocationStrategy(), provideRouterScroller(), config?.preloadingStrategy ? withPreloading(config.preloadingStrategy).ɵproviders : [], config?.initialNavigation ? provideInitialNavigation(config) : [], config?.bindToComponentInputs ? withComponentInputBinding().ɵproviders : [], config?.enableViewTransitions ? withViewTransitions().ɵproviders : [], provideRouterInitializer()]\n };\n }\n /**\n * Creates a module with all the router directives and a provider registering routes,\n * without creating a new Router service.\n * When registering for submodules and lazy-loaded submodules, create the NgModule as follows:\n *\n * ```ts\n * @NgModule({\n * imports: [RouterModule.forChild(ROUTES)]\n * })\n * class MyNgModule {}\n * ```\n *\n * @param routes An array of `Route` objects that define the navigation paths for the submodule.\n * @return The new NgModule.\n *\n */\n static forChild(routes) {\n return {\n ngModule: RouterModule,\n providers: [{\n provide: ROUTES,\n multi: true,\n useValue: routes\n }]\n };\n }\n static ɵfac = function RouterModule_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || RouterModule)();\n };\n static ɵmod = /* @__PURE__ */i0.ɵɵdefineNgModule({\n type: RouterModule\n });\n static ɵinj = /* @__PURE__ */i0.ɵɵdefineInjector({});\n }\n return RouterModule;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * For internal use by `RouterModule` only. Note that this differs from `withInMemoryRouterScroller`\n * because it reads from the `ExtraOptions` which should not be used in the standalone world.\n */\nfunction provideRouterScroller() {\n return {\n provide: ROUTER_SCROLLER,\n useFactory: () => {\n const viewportScroller = inject(ViewportScroller);\n const zone = inject(NgZone);\n const config = inject(ROUTER_CONFIGURATION);\n const transitions = inject(NavigationTransitions);\n const urlSerializer = inject(UrlSerializer);\n if (config.scrollOffset) {\n viewportScroller.setOffset(config.scrollOffset);\n }\n return new RouterScroller(urlSerializer, transitions, viewportScroller, zone, config);\n }\n };\n}\n// Note: For internal use only with `RouterModule`. Standalone setup via `provideRouter` should\n// provide hash location directly via `{provide: LocationStrategy, useClass: HashLocationStrategy}`.\nfunction provideHashLocationStrategy() {\n return {\n provide: LocationStrategy,\n useClass: HashLocationStrategy\n };\n}\n// Note: For internal use only with `RouterModule`. Standalone setup via `provideRouter` does not\n// need this at all because `PathLocationStrategy` is the default factory for `LocationStrategy`.\nfunction providePathLocationStrategy() {\n return {\n provide: LocationStrategy,\n useClass: PathLocationStrategy\n };\n}\nfunction provideForRootGuard(router) {\n if (router) {\n throw new _RuntimeError(4007 /* RuntimeErrorCode.FOR_ROOT_CALLED_TWICE */, `The Router was provided more than once. This can happen if 'forRoot' is used outside of the root injector.` + ` Lazy loaded modules should use RouterModule.forChild() instead.`);\n }\n return 'guarded';\n}\n// Note: For internal use only with `RouterModule`. Standalone router setup with `provideRouter`\n// users call `withXInitialNavigation` directly.\nfunction provideInitialNavigation(config) {\n return [config.initialNavigation === 'disabled' ? withDisabledInitialNavigation().ɵproviders : [], config.initialNavigation === 'enabledBlocking' ? withEnabledBlockingInitialNavigation().ɵproviders : []];\n}\n// TODO(atscott): This should not be in the public API\n/**\n * A DI token for the router initializer that\n * is called after the app is bootstrapped.\n *\n * @publicApi\n */\nconst ROUTER_INITIALIZER = /*#__PURE__*/new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'Router Initializer' : '');\nfunction provideRouterInitializer() {\n return [\n // ROUTER_INITIALIZER token should be removed. It's public API but shouldn't be. We can just\n // have `getBootstrapListener` directly attached to APP_BOOTSTRAP_LISTENER.\n {\n provide: ROUTER_INITIALIZER,\n useFactory: getBootstrapListener\n }, {\n provide: APP_BOOTSTRAP_LISTENER,\n multi: true,\n useExisting: ROUTER_INITIALIZER\n }];\n}\nexport { NoPreloading as N, PreloadAllModules as P, RouterLink as R, RouterLinkActive as a, provideRoutes as b, withComponentInputBinding as c, withDebugTracing as d, withDisabledInitialNavigation as e, withEnabledBlockingInitialNavigation as f, withHashLocation as g, withInMemoryScrolling as h, withNavigationErrorHandler as i, withPreloading as j, withRouterConfig as k, ROUTER_INITIALIZER as l, RouterModule as m, PreloadingStrategy as n, RouterPreloader as o, provideRouter as p, ROUTER_PROVIDERS as q, withViewTransitions as w };\n","/**\n * @license Angular v19.2.5\n * (c) 2010-2025 Google LLC. https://angular.io/\n * License: MIT\n */\n\n/**\n * @description Constants for the categories of parameters that can be defined for animations.\n *\n * A corresponding function defines a set of parameters for each category, and\n * collects them into a corresponding `AnimationMetadata` object.\n *\n * @publicApi\n */\nvar AnimationMetadataType = /*#__PURE__*/function (AnimationMetadataType) {\n /**\n * Associates a named animation state with a set of CSS styles.\n * See [`state()`](api/animations/state)\n */\n AnimationMetadataType[AnimationMetadataType[\"State\"] = 0] = \"State\";\n /**\n * Data for a transition from one animation state to another.\n * See `transition()`\n */\n AnimationMetadataType[AnimationMetadataType[\"Transition\"] = 1] = \"Transition\";\n /**\n * Contains a set of animation steps.\n * See `sequence()`\n */\n AnimationMetadataType[AnimationMetadataType[\"Sequence\"] = 2] = \"Sequence\";\n /**\n * Contains a set of animation steps.\n * See `{@link /api/animations/group group()}`\n */\n AnimationMetadataType[AnimationMetadataType[\"Group\"] = 3] = \"Group\";\n /**\n * Contains an animation step.\n * See `animate()`\n */\n AnimationMetadataType[AnimationMetadataType[\"Animate\"] = 4] = \"Animate\";\n /**\n * Contains a set of animation steps.\n * See `keyframes()`\n */\n AnimationMetadataType[AnimationMetadataType[\"Keyframes\"] = 5] = \"Keyframes\";\n /**\n * Contains a set of CSS property-value pairs into a named style.\n * See `style()`\n */\n AnimationMetadataType[AnimationMetadataType[\"Style\"] = 6] = \"Style\";\n /**\n * Associates an animation with an entry trigger that can be attached to an element.\n * See `trigger()`\n */\n AnimationMetadataType[AnimationMetadataType[\"Trigger\"] = 7] = \"Trigger\";\n /**\n * Contains a re-usable animation.\n * See `animation()`\n */\n AnimationMetadataType[AnimationMetadataType[\"Reference\"] = 8] = \"Reference\";\n /**\n * Contains data to use in executing child animations returned by a query.\n * See `animateChild()`\n */\n AnimationMetadataType[AnimationMetadataType[\"AnimateChild\"] = 9] = \"AnimateChild\";\n /**\n * Contains animation parameters for a re-usable animation.\n * See `useAnimation()`\n */\n AnimationMetadataType[AnimationMetadataType[\"AnimateRef\"] = 10] = \"AnimateRef\";\n /**\n * Contains child-animation query data.\n * See `query()`\n */\n AnimationMetadataType[AnimationMetadataType[\"Query\"] = 11] = \"Query\";\n /**\n * Contains data for staggering an animation sequence.\n * See `stagger()`\n */\n AnimationMetadataType[AnimationMetadataType[\"Stagger\"] = 12] = \"Stagger\";\n return AnimationMetadataType;\n}(AnimationMetadataType || {});\n/**\n * Specifies automatic styling.\n *\n * @publicApi\n */\nconst AUTO_STYLE = '*';\n/**\n * Creates a named animation trigger, containing a list of [`state()`](api/animations/state)\n * and `transition()` entries to be evaluated when the expression\n * bound to the trigger changes.\n *\n * @param name An identifying string.\n * @param definitions An animation definition object, containing an array of\n * [`state()`](api/animations/state) and `transition()` declarations.\n *\n * @return An object that encapsulates the trigger data.\n *\n * @usageNotes\n * Define an animation trigger in the `animations` section of `@Component` metadata.\n * In the template, reference the trigger by name and bind it to a trigger expression that\n * evaluates to a defined animation state, using the following format:\n *\n * `[@triggerName]=\"expression\"`\n *\n * Animation trigger bindings convert all values to strings, and then match the\n * previous and current values against any linked transitions.\n * Booleans can be specified as `1` or `true` and `0` or `false`.\n *\n * ### Usage Example\n *\n * The following example creates an animation trigger reference based on the provided\n * name value.\n * The provided animation value is expected to be an array consisting of state and\n * transition declarations.\n *\n * ```ts\n * @Component({\n * selector: \"my-component\",\n * templateUrl: \"my-component-tpl.html\",\n * animations: [\n * trigger(\"myAnimationTrigger\", [\n * state(...),\n * state(...),\n * transition(...),\n * transition(...)\n * ])\n * ]\n * })\n * class MyComponent {\n * myStatusExp = \"something\";\n * }\n * ```\n *\n * The template associated with this component makes use of the defined trigger\n * by binding to an element within its template code.\n *\n * ```html\n * \n *
...
\n * ```\n *\n * ### Using an inline function\n * The `transition` animation method also supports reading an inline function which can decide\n * if its associated animation should be run.\n *\n * ```ts\n * // this method is run each time the `myAnimationTrigger` trigger value changes.\n * function myInlineMatcherFn(fromState: string, toState: string, element: any, params: {[key:\n string]: any}): boolean {\n * // notice that `element` and `params` are also available here\n * return toState == 'yes-please-animate';\n * }\n *\n * @Component({\n * selector: 'my-component',\n * templateUrl: 'my-component-tpl.html',\n * animations: [\n * trigger('myAnimationTrigger', [\n * transition(myInlineMatcherFn, [\n * // the animation sequence code\n * ]),\n * ])\n * ]\n * })\n * class MyComponent {\n * myStatusExp = \"yes-please-animate\";\n * }\n * ```\n *\n * ### Disabling Animations\n * When true, the special animation control binding `@.disabled` binding prevents\n * all animations from rendering.\n * Place the `@.disabled` binding on an element to disable\n * animations on the element itself, as well as any inner animation triggers\n * within the element.\n *\n * The following example shows how to use this feature:\n *\n * ```angular-ts\n * @Component({\n * selector: 'my-component',\n * template: `\n *
\n *
\n *
\n * `,\n * animations: [\n * trigger(\"childAnimation\", [\n * // ...\n * ])\n * ]\n * })\n * class MyComponent {\n * isDisabled = true;\n * exp = '...';\n * }\n * ```\n *\n * When `@.disabled` is true, it prevents the `@childAnimation` trigger from animating,\n * along with any inner animations.\n *\n * ### Disable animations application-wide\n * When an area of the template is set to have animations disabled,\n * **all** inner components have their animations disabled as well.\n * This means that you can disable all animations for an app\n * by placing a host binding set on `@.disabled` on the topmost Angular component.\n *\n * ```ts\n * import {Component, HostBinding} from '@angular/core';\n *\n * @Component({\n * selector: 'app-component',\n * templateUrl: 'app.component.html',\n * })\n * class AppComponent {\n * @HostBinding('@.disabled')\n * public animationsDisabled = true;\n * }\n * ```\n *\n * ### Overriding disablement of inner animations\n * Despite inner animations being disabled, a parent animation can `query()`\n * for inner elements located in disabled areas of the template and still animate\n * them if needed. This is also the case for when a sub animation is\n * queried by a parent and then later animated using `animateChild()`.\n *\n * ### Detecting when an animation is disabled\n * If a region of the DOM (or the entire application) has its animations disabled, the animation\n * trigger callbacks still fire, but for zero seconds. When the callback fires, it provides\n * an instance of an `AnimationEvent`. If animations are disabled,\n * the `.disabled` flag on the event is true.\n *\n * @publicApi\n */\nfunction trigger(name, definitions) {\n return {\n type: AnimationMetadataType.Trigger,\n name,\n definitions,\n options: {}\n };\n}\n/**\n * Defines an animation step that combines styling information with timing information.\n *\n * @param timings Sets `AnimateTimings` for the parent animation.\n * A string in the format \"duration [delay] [easing]\".\n * - Duration and delay are expressed as a number and optional time unit,\n * such as \"1s\" or \"10ms\" for one second and 10 milliseconds, respectively.\n * The default unit is milliseconds.\n * - The easing value controls how the animation accelerates and decelerates\n * during its runtime. Value is one of `ease`, `ease-in`, `ease-out`,\n * `ease-in-out`, or a `cubic-bezier()` function call.\n * If not supplied, no easing is applied.\n *\n * For example, the string \"1s 100ms ease-out\" specifies a duration of\n * 1000 milliseconds, and delay of 100 ms, and the \"ease-out\" easing style,\n * which decelerates near the end of the duration.\n * @param styles Sets AnimationStyles for the parent animation.\n * A function call to either `style()` or `keyframes()`\n * that returns a collection of CSS style entries to be applied to the parent animation.\n * When null, uses the styles from the destination state.\n * This is useful when describing an animation step that will complete an animation;\n * see \"Animating to the final state\" in `transitions()`.\n * @returns An object that encapsulates the animation step.\n *\n * @usageNotes\n * Call within an animation `sequence()`, {@link /api/animations/group group()}, or\n * `transition()` call to specify an animation step\n * that applies given style data to the parent animation for a given amount of time.\n *\n * ### Syntax Examples\n * **Timing examples**\n *\n * The following examples show various `timings` specifications.\n * - `animate(500)` : Duration is 500 milliseconds.\n * - `animate(\"1s\")` : Duration is 1000 milliseconds.\n * - `animate(\"100ms 0.5s\")` : Duration is 100 milliseconds, delay is 500 milliseconds.\n * - `animate(\"5s ease-in\")` : Duration is 5000 milliseconds, easing in.\n * - `animate(\"5s 10ms cubic-bezier(.17,.67,.88,.1)\")` : Duration is 5000 milliseconds, delay is 10\n * milliseconds, easing according to a bezier curve.\n *\n * **Style examples**\n *\n * The following example calls `style()` to set a single CSS style.\n * ```ts\n * animate(500, style({ background: \"red\" }))\n * ```\n * The following example calls `keyframes()` to set a CSS style\n * to different values for successive keyframes.\n * ```ts\n * animate(500, keyframes(\n * [\n * style({ background: \"blue\" }),\n * style({ background: \"red\" })\n * ])\n * ```\n *\n * @publicApi\n */\nfunction animate(timings, styles = null) {\n return {\n type: AnimationMetadataType.Animate,\n styles,\n timings\n };\n}\n/**\n * @description Defines a list of animation steps to be run in parallel.\n *\n * @param steps An array of animation step objects.\n * - When steps are defined by `style()` or `animate()`\n * function calls, each call within the group is executed instantly.\n * - To specify offset styles to be applied at a later time, define steps with\n * `keyframes()`, or use `animate()` calls with a delay value.\n * For example:\n *\n * ```ts\n * group([\n * animate(\"1s\", style({ background: \"black\" })),\n * animate(\"2s\", style({ color: \"white\" }))\n * ])\n * ```\n *\n * @param options An options object containing a delay and\n * developer-defined parameters that provide styling defaults and\n * can be overridden on invocation.\n *\n * @return An object that encapsulates the group data.\n *\n * @usageNotes\n * Grouped animations are useful when a series of styles must be\n * animated at different starting times and closed off at different ending times.\n *\n * When called within a `sequence()` or a\n * `transition()` call, does not continue to the next\n * instruction until all of the inner animation steps have completed.\n *\n * @publicApi\n */\nfunction group(steps, options = null) {\n return {\n type: AnimationMetadataType.Group,\n steps,\n options\n };\n}\n/**\n * Defines a list of animation steps to be run sequentially, one by one.\n *\n * @param steps An array of animation step objects.\n * - Steps defined by `style()` calls apply the styling data immediately.\n * - Steps defined by `animate()` calls apply the styling data over time\n * as specified by the timing data.\n *\n * ```ts\n * sequence([\n * style({ opacity: 0 }),\n * animate(\"1s\", style({ opacity: 1 }))\n * ])\n * ```\n *\n * @param options An options object containing a delay and\n * developer-defined parameters that provide styling defaults and\n * can be overridden on invocation.\n *\n * @return An object that encapsulates the sequence data.\n *\n * @usageNotes\n * When you pass an array of steps to a\n * `transition()` call, the steps run sequentially by default.\n * Compare this to the {@link /api/animations/group group()} call, which runs animation steps in\n *parallel.\n *\n * When a sequence is used within a {@link /api/animations/group group()} or a `transition()` call,\n * execution continues to the next instruction only after each of the inner animation\n * steps have completed.\n *\n * @publicApi\n **/\nfunction sequence(steps, options = null) {\n return {\n type: AnimationMetadataType.Sequence,\n steps,\n options\n };\n}\n/**\n * Declares a key/value object containing CSS properties/styles that\n * can then be used for an animation [`state`](api/animations/state), within an animation\n *`sequence`, or as styling data for calls to `animate()` and `keyframes()`.\n *\n * @param tokens A set of CSS styles or HTML styles associated with an animation state.\n * The value can be any of the following:\n * - A key-value style pair associating a CSS property with a value.\n * - An array of key-value style pairs.\n * - An asterisk (*), to use auto-styling, where styles are derived from the element\n * being animated and applied to the animation when it starts.\n *\n * Auto-styling can be used to define a state that depends on layout or other\n * environmental factors.\n *\n * @return An object that encapsulates the style data.\n *\n * @usageNotes\n * The following examples create animation styles that collect a set of\n * CSS property values:\n *\n * ```ts\n * // string values for CSS properties\n * style({ background: \"red\", color: \"blue\" })\n *\n * // numerical pixel values\n * style({ width: 100, height: 0 })\n * ```\n *\n * The following example uses auto-styling to allow an element to animate from\n * a height of 0 up to its full height:\n *\n * ```ts\n * style({ height: 0 }),\n * animate(\"1s\", style({ height: \"*\" }))\n * ```\n *\n * @publicApi\n **/\nfunction style(tokens) {\n return {\n type: AnimationMetadataType.Style,\n styles: tokens,\n offset: null\n };\n}\n/**\n * Declares an animation state within a trigger attached to an element.\n *\n * @param name One or more names for the defined state in a comma-separated string.\n * The following reserved state names can be supplied to define a style for specific use\n * cases:\n *\n * - `void` You can associate styles with this name to be used when\n * the element is detached from the application. For example, when an `ngIf` evaluates\n * to false, the state of the associated element is void.\n * - `*` (asterisk) Indicates the default state. You can associate styles with this name\n * to be used as the fallback when the state that is being animated is not declared\n * within the trigger.\n *\n * @param styles A set of CSS styles associated with this state, created using the\n * `style()` function.\n * This set of styles persists on the element once the state has been reached.\n * @param options Parameters that can be passed to the state when it is invoked.\n * 0 or more key-value pairs.\n * @return An object that encapsulates the new state data.\n *\n * @usageNotes\n * Use the `trigger()` function to register states to an animation trigger.\n * Use the `transition()` function to animate between states.\n * When a state is active within a component, its associated styles persist on the element,\n * even when the animation ends.\n *\n * @publicApi\n **/\nfunction state(name, styles, options) {\n return {\n type: AnimationMetadataType.State,\n name,\n styles,\n options\n };\n}\n/**\n * Defines a set of animation styles, associating each style with an optional `offset` value.\n *\n * @param steps A set of animation styles with optional offset data.\n * The optional `offset` value for a style specifies a percentage of the total animation\n * time at which that style is applied.\n * @returns An object that encapsulates the keyframes data.\n *\n * @usageNotes\n * Use with the `animate()` call. Instead of applying animations\n * from the current state\n * to the destination state, keyframes describe how each style entry is applied and at what point\n * within the animation arc.\n * Compare [CSS Keyframe Animations](https://www.w3schools.com/css/css3_animations.asp).\n *\n * ### Usage\n *\n * In the following example, the offset values describe\n * when each `backgroundColor` value is applied. The color is red at the start, and changes to\n * blue when 20% of the total time has elapsed.\n *\n * ```ts\n * // the provided offset values\n * animate(\"5s\", keyframes([\n * style({ backgroundColor: \"red\", offset: 0 }),\n * style({ backgroundColor: \"blue\", offset: 0.2 }),\n * style({ backgroundColor: \"orange\", offset: 0.3 }),\n * style({ backgroundColor: \"black\", offset: 1 })\n * ]))\n * ```\n *\n * If there are no `offset` values specified in the style entries, the offsets\n * are calculated automatically.\n *\n * ```ts\n * animate(\"5s\", keyframes([\n * style({ backgroundColor: \"red\" }) // offset = 0\n * style({ backgroundColor: \"blue\" }) // offset = 0.33\n * style({ backgroundColor: \"orange\" }) // offset = 0.66\n * style({ backgroundColor: \"black\" }) // offset = 1\n * ]))\n *```\n\n * @publicApi\n */\nfunction keyframes(steps) {\n return {\n type: AnimationMetadataType.Keyframes,\n steps\n };\n}\n/**\n * Declares an animation transition which is played when a certain specified condition is met.\n *\n * @param stateChangeExpr A string with a specific format or a function that specifies when the\n * animation transition should occur (see [State Change Expression](#state-change-expression)).\n *\n * @param steps One or more animation objects that represent the animation's instructions.\n *\n * @param options An options object that can be used to specify a delay for the animation or provide\n * custom parameters for it.\n *\n * @returns An object that encapsulates the transition data.\n *\n * @usageNotes\n *\n * ### State Change Expression\n *\n * The State Change Expression instructs Angular when to run the transition's animations, it can\n *either be\n * - a string with a specific syntax\n * - or a function that compares the previous and current state (value of the expression bound to\n * the element's trigger) and returns `true` if the transition should occur or `false` otherwise\n *\n * The string format can be:\n * - `fromState => toState`, which indicates that the transition's animations should occur then the\n * expression bound to the trigger's element goes from `fromState` to `toState`\n *\n * _Example:_\n * ```ts\n * transition('open => closed', animate('.5s ease-out', style({ height: 0 }) ))\n * ```\n *\n * - `fromState <=> toState`, which indicates that the transition's animations should occur then\n * the expression bound to the trigger's element goes from `fromState` to `toState` or vice versa\n *\n * _Example:_\n * ```ts\n * transition('enabled <=> disabled', animate('1s cubic-bezier(0.8,0.3,0,1)'))\n * ```\n *\n * - `:enter`/`:leave`, which indicates that the transition's animations should occur when the\n * element enters or exists the DOM\n *\n * _Example:_\n * ```ts\n * transition(':enter', [\n * style({ opacity: 0 }),\n * animate('500ms', style({ opacity: 1 }))\n * ])\n * ```\n *\n * - `:increment`/`:decrement`, which indicates that the transition's animations should occur when\n * the numerical expression bound to the trigger's element has increased in value or decreased\n *\n * _Example:_\n * ```ts\n * transition(':increment', query('@counter', animateChild()))\n * ```\n *\n * - a sequence of any of the above divided by commas, which indicates that transition's animations\n * should occur whenever one of the state change expressions matches\n *\n * _Example:_\n * ```ts\n * transition(':increment, * => enabled, :enter', animate('1s ease', keyframes([\n * style({ transform: 'scale(1)', offset: 0}),\n * style({ transform: 'scale(1.1)', offset: 0.7}),\n * style({ transform: 'scale(1)', offset: 1})\n * ]))),\n * ```\n *\n * Also note that in such context:\n * - `void` can be used to indicate the absence of the element\n * - asterisks can be used as wildcards that match any state\n * - (as a consequence of the above, `void => *` is equivalent to `:enter` and `* => void` is\n * equivalent to `:leave`)\n * - `true` and `false` also match expression values of `1` and `0` respectively (but do not match\n * _truthy_ and _falsy_ values)\n *\n *
\n *\n * Be careful about entering end leaving elements as their transitions present a common\n * pitfall for developers.\n *\n * Note that when an element with a trigger enters the DOM its `:enter` transition always\n * gets executed, but its `:leave` transition will not be executed if the element is removed\n * alongside its parent (as it will be removed \"without warning\" before its transition has\n * a chance to be executed, the only way that such transition can occur is if the element\n * is exiting the DOM on its own).\n *\n *\n *
\n *\n * ### Animating to a Final State\n *\n * If the final step in a transition is a call to `animate()` that uses a timing value\n * with no `style` data, that step is automatically considered the final animation arc,\n * for the element to reach the final state, in such case Angular automatically adds or removes\n * CSS styles to ensure that the element is in the correct final state.\n *\n *\n * ### Usage Examples\n *\n * - Transition animations applied based on\n * the trigger's expression value\n *\n * ```html\n *
\n * ...\n *
\n * ```\n *\n * ```ts\n * trigger(\"myAnimationTrigger\", [\n * ..., // states\n * transition(\"on => off, open => closed\", animate(500)),\n * transition(\"* <=> error\", query('.indicator', animateChild()))\n * ])\n * ```\n *\n * - Transition animations applied based on custom logic dependent\n * on the trigger's expression value and provided parameters\n *\n * ```html\n *
\n * ...\n *
\n * ```\n *\n * ```ts\n * trigger(\"myAnimationTrigger\", [\n * ..., // states\n * transition(\n * (fromState, toState, _element, params) =>\n * ['firststep', 'laststep'].includes(fromState.toLowerCase())\n * && toState === params?.['target'],\n * animate('1s')\n * )\n * ])\n * ```\n *\n * @publicApi\n **/\nfunction transition(stateChangeExpr, steps, options = null) {\n return {\n type: AnimationMetadataType.Transition,\n expr: stateChangeExpr,\n animation: steps,\n options\n };\n}\n/**\n * Produces a reusable animation that can be invoked in another animation or sequence,\n * by calling the `useAnimation()` function.\n *\n * @param steps One or more animation objects, as returned by the `animate()`\n * or `sequence()` function, that form a transformation from one state to another.\n * A sequence is used by default when you pass an array.\n * @param options An options object that can contain a delay value for the start of the\n * animation, and additional developer-defined parameters.\n * Provided values for additional parameters are used as defaults,\n * and override values can be passed to the caller on invocation.\n * @returns An object that encapsulates the animation data.\n *\n * @usageNotes\n * The following example defines a reusable animation, providing some default parameter\n * values.\n *\n * ```ts\n * var fadeAnimation = animation([\n * style({ opacity: '{{ start }}' }),\n * animate('{{ time }}',\n * style({ opacity: '{{ end }}'}))\n * ],\n * { params: { time: '1000ms', start: 0, end: 1 }});\n * ```\n *\n * The following invokes the defined animation with a call to `useAnimation()`,\n * passing in override parameter values.\n *\n * ```js\n * useAnimation(fadeAnimation, {\n * params: {\n * time: '2s',\n * start: 1,\n * end: 0\n * }\n * })\n * ```\n *\n * If any of the passed-in parameter values are missing from this call,\n * the default values are used. If one or more parameter values are missing before a step is\n * animated, `useAnimation()` throws an error.\n *\n * @publicApi\n */\nfunction animation(steps, options = null) {\n return {\n type: AnimationMetadataType.Reference,\n animation: steps,\n options\n };\n}\n/**\n * Executes a queried inner animation element within an animation sequence.\n *\n * @param options An options object that can contain a delay value for the start of the\n * animation, and additional override values for developer-defined parameters.\n * @return An object that encapsulates the child animation data.\n *\n * @usageNotes\n * Each time an animation is triggered in Angular, the parent animation\n * has priority and any child animations are blocked. In order\n * for a child animation to run, the parent animation must query each of the elements\n * containing child animations, and run them using this function.\n *\n * Note that this feature is designed to be used with `query()` and it will only work\n * with animations that are assigned using the Angular animation library. CSS keyframes\n * and transitions are not handled by this API.\n *\n * @publicApi\n */\nfunction animateChild(options = null) {\n return {\n type: AnimationMetadataType.AnimateChild,\n options\n };\n}\n/**\n * Starts a reusable animation that is created using the `animation()` function.\n *\n * @param animation The reusable animation to start.\n * @param options An options object that can contain a delay value for the start of\n * the animation, and additional override values for developer-defined parameters.\n * @return An object that contains the animation parameters.\n *\n * @publicApi\n */\nfunction useAnimation(animation, options = null) {\n return {\n type: AnimationMetadataType.AnimateRef,\n animation,\n options\n };\n}\n/**\n * Finds one or more inner elements within the current element that is\n * being animated within a sequence. Use with `animate()`.\n *\n * @param selector The element to query, or a set of elements that contain Angular-specific\n * characteristics, specified with one or more of the following tokens.\n * - `query(\":enter\")` or `query(\":leave\")` : Query for newly inserted/removed elements (not\n * all elements can be queried via these tokens, see\n * [Entering and Leaving Elements](#entering-and-leaving-elements))\n * - `query(\":animating\")` : Query all currently animating elements.\n * - `query(\"@triggerName\")` : Query elements that contain an animation trigger.\n * - `query(\"@*\")` : Query all elements that contain an animation triggers.\n * - `query(\":self\")` : Include the current element into the animation sequence.\n *\n * @param animation One or more animation steps to apply to the queried element or elements.\n * An array is treated as an animation sequence.\n * @param options An options object. Use the 'limit' field to limit the total number of\n * items to collect.\n * @return An object that encapsulates the query data.\n *\n * @usageNotes\n *\n * ### Multiple Tokens\n *\n * Tokens can be merged into a combined query selector string. For example:\n *\n * ```ts\n * query(':self, .record:enter, .record:leave, @subTrigger', [...])\n * ```\n *\n * The `query()` function collects multiple elements and works internally by using\n * `element.querySelectorAll`. Use the `limit` field of an options object to limit\n * the total number of items to be collected. For example:\n *\n * ```js\n * query('div', [\n * animate(...),\n * animate(...)\n * ], { limit: 1 })\n * ```\n *\n * By default, throws an error when zero items are found. Set the\n * `optional` flag to ignore this error. For example:\n *\n * ```js\n * query('.some-element-that-may-not-be-there', [\n * animate(...),\n * animate(...)\n * ], { optional: true })\n * ```\n *\n * ### Entering and Leaving Elements\n *\n * Not all elements can be queried via the `:enter` and `:leave` tokens, the only ones\n * that can are those that Angular assumes can enter/leave based on their own logic\n * (if their insertion/removal is simply a consequence of that of their parent they\n * should be queried via a different token in their parent's `:enter`/`:leave` transitions).\n *\n * The only elements Angular assumes can enter/leave based on their own logic (thus the only\n * ones that can be queried via the `:enter` and `:leave` tokens) are:\n * - Those inserted dynamically (via `ViewContainerRef`)\n * - Those that have a structural directive (which, under the hood, are a subset of the above ones)\n *\n *
\n *\n * Note that elements will be successfully queried via `:enter`/`:leave` even if their\n * insertion/removal is not done manually via `ViewContainerRef`or caused by their structural\n * directive (e.g. they enter/exit alongside their parent).\n *\n *
\n *\n *
\n *\n * There is an exception to what previously mentioned, besides elements entering/leaving based on\n * their own logic, elements with an animation trigger can always be queried via `:leave` when\n * their parent is also leaving.\n *\n *
\n *\n * ### Usage Example\n *\n * The following example queries for inner elements and animates them\n * individually using `animate()`.\n *\n * ```angular-ts\n * @Component({\n * selector: 'inner',\n * template: `\n *
\n *

Title

\n *
\n * Blah blah blah\n *
\n *
\n * `,\n * animations: [\n * trigger('queryAnimation', [\n * transition('* => goAnimate', [\n * // hide the inner elements\n * query('h1', style({ opacity: 0 })),\n * query('.content', style({ opacity: 0 })),\n *\n * // animate the inner elements in, one by one\n * query('h1', animate(1000, style({ opacity: 1 }))),\n * query('.content', animate(1000, style({ opacity: 1 }))),\n * ])\n * ])\n * ]\n * })\n * class Cmp {\n * exp = '';\n *\n * goAnimate() {\n * this.exp = 'goAnimate';\n * }\n * }\n * ```\n *\n * @publicApi\n */\nfunction query(selector, animation, options = null) {\n return {\n type: AnimationMetadataType.Query,\n selector,\n animation,\n options\n };\n}\n/**\n * Use within an animation `query()` call to issue a timing gap after\n * each queried item is animated.\n *\n * @param timings A delay value.\n * @param animation One ore more animation steps.\n * @returns An object that encapsulates the stagger data.\n *\n * @usageNotes\n * In the following example, a container element wraps a list of items stamped out\n * by an `ngFor`. The container element contains an animation trigger that will later be set\n * to query for each of the inner items.\n *\n * Each time items are added, the opacity fade-in animation runs,\n * and each removed item is faded out.\n * When either of these animations occur, the stagger effect is\n * applied after each item's animation is started.\n *\n * ```html\n * \n * \n *
\n *
\n *
\n * {{ item }}\n *
\n *
\n * ```\n *\n * Here is the component code:\n *\n * ```ts\n * import {trigger, transition, style, animate, query, stagger} from '@angular/animations';\n * @Component({\n * templateUrl: 'list.component.html',\n * animations: [\n * trigger('listAnimation', [\n * ...\n * ])\n * ]\n * })\n * class ListComponent {\n * items = [];\n *\n * showItems() {\n * this.items = [0,1,2,3,4];\n * }\n *\n * hideItems() {\n * this.items = [];\n * }\n *\n * toggle() {\n * this.items.length ? this.hideItems() : this.showItems();\n * }\n * }\n * ```\n *\n * Here is the animation trigger code:\n *\n * ```ts\n * trigger('listAnimation', [\n * transition('* => *', [ // each time the binding value changes\n * query(':leave', [\n * stagger(100, [\n * animate('0.5s', style({ opacity: 0 }))\n * ])\n * ]),\n * query(':enter', [\n * style({ opacity: 0 }),\n * stagger(100, [\n * animate('0.5s', style({ opacity: 1 }))\n * ])\n * ])\n * ])\n * ])\n * ```\n *\n * @publicApi\n */\nfunction stagger(timings, animation) {\n return {\n type: AnimationMetadataType.Stagger,\n timings,\n animation\n };\n}\n\n/**\n * An empty programmatic controller for reusable animations.\n * Used internally when animations are disabled, to avoid\n * checking for the null case when an animation player is expected.\n *\n * @see {@link animate}\n * @see {@link AnimationPlayer}\n *\n * @publicApi\n */\nclass NoopAnimationPlayer {\n _onDoneFns = [];\n _onStartFns = [];\n _onDestroyFns = [];\n _originalOnDoneFns = [];\n _originalOnStartFns = [];\n _started = false;\n _destroyed = false;\n _finished = false;\n _position = 0;\n parentPlayer = null;\n totalTime;\n constructor(duration = 0, delay = 0) {\n this.totalTime = duration + delay;\n }\n _onFinish() {\n if (!this._finished) {\n this._finished = true;\n this._onDoneFns.forEach(fn => fn());\n this._onDoneFns = [];\n }\n }\n onStart(fn) {\n this._originalOnStartFns.push(fn);\n this._onStartFns.push(fn);\n }\n onDone(fn) {\n this._originalOnDoneFns.push(fn);\n this._onDoneFns.push(fn);\n }\n onDestroy(fn) {\n this._onDestroyFns.push(fn);\n }\n hasStarted() {\n return this._started;\n }\n init() {}\n play() {\n if (!this.hasStarted()) {\n this._onStart();\n this.triggerMicrotask();\n }\n this._started = true;\n }\n /** @internal */\n triggerMicrotask() {\n queueMicrotask(() => this._onFinish());\n }\n _onStart() {\n this._onStartFns.forEach(fn => fn());\n this._onStartFns = [];\n }\n pause() {}\n restart() {}\n finish() {\n this._onFinish();\n }\n destroy() {\n if (!this._destroyed) {\n this._destroyed = true;\n if (!this.hasStarted()) {\n this._onStart();\n }\n this.finish();\n this._onDestroyFns.forEach(fn => fn());\n this._onDestroyFns = [];\n }\n }\n reset() {\n this._started = false;\n this._finished = false;\n this._onStartFns = this._originalOnStartFns;\n this._onDoneFns = this._originalOnDoneFns;\n }\n setPosition(position) {\n this._position = this.totalTime ? position * this.totalTime : 1;\n }\n getPosition() {\n return this.totalTime ? this._position / this.totalTime : 1;\n }\n /** @internal */\n triggerCallback(phaseName) {\n const methods = phaseName == 'start' ? this._onStartFns : this._onDoneFns;\n methods.forEach(fn => fn());\n methods.length = 0;\n }\n}\n\n/**\n * A programmatic controller for a group of reusable animations.\n * Used internally to control animations.\n *\n * @see {@link AnimationPlayer}\n * @see {@link animations/group group}\n *\n */\nclass AnimationGroupPlayer {\n _onDoneFns = [];\n _onStartFns = [];\n _finished = false;\n _started = false;\n _destroyed = false;\n _onDestroyFns = [];\n parentPlayer = null;\n totalTime = 0;\n players;\n constructor(_players) {\n this.players = _players;\n let doneCount = 0;\n let destroyCount = 0;\n let startCount = 0;\n const total = this.players.length;\n if (total == 0) {\n queueMicrotask(() => this._onFinish());\n } else {\n this.players.forEach(player => {\n player.onDone(() => {\n if (++doneCount == total) {\n this._onFinish();\n }\n });\n player.onDestroy(() => {\n if (++destroyCount == total) {\n this._onDestroy();\n }\n });\n player.onStart(() => {\n if (++startCount == total) {\n this._onStart();\n }\n });\n });\n }\n this.totalTime = this.players.reduce((time, player) => Math.max(time, player.totalTime), 0);\n }\n _onFinish() {\n if (!this._finished) {\n this._finished = true;\n this._onDoneFns.forEach(fn => fn());\n this._onDoneFns = [];\n }\n }\n init() {\n this.players.forEach(player => player.init());\n }\n onStart(fn) {\n this._onStartFns.push(fn);\n }\n _onStart() {\n if (!this.hasStarted()) {\n this._started = true;\n this._onStartFns.forEach(fn => fn());\n this._onStartFns = [];\n }\n }\n onDone(fn) {\n this._onDoneFns.push(fn);\n }\n onDestroy(fn) {\n this._onDestroyFns.push(fn);\n }\n hasStarted() {\n return this._started;\n }\n play() {\n if (!this.parentPlayer) {\n this.init();\n }\n this._onStart();\n this.players.forEach(player => player.play());\n }\n pause() {\n this.players.forEach(player => player.pause());\n }\n restart() {\n this.players.forEach(player => player.restart());\n }\n finish() {\n this._onFinish();\n this.players.forEach(player => player.finish());\n }\n destroy() {\n this._onDestroy();\n }\n _onDestroy() {\n if (!this._destroyed) {\n this._destroyed = true;\n this._onFinish();\n this.players.forEach(player => player.destroy());\n this._onDestroyFns.forEach(fn => fn());\n this._onDestroyFns = [];\n }\n }\n reset() {\n this.players.forEach(player => player.reset());\n this._destroyed = false;\n this._finished = false;\n this._started = false;\n }\n setPosition(p) {\n const timeAtPosition = p * this.totalTime;\n this.players.forEach(player => {\n const position = player.totalTime ? Math.min(1, timeAtPosition / player.totalTime) : 1;\n player.setPosition(position);\n });\n }\n getPosition() {\n const longestPlayer = this.players.reduce((longestSoFar, player) => {\n const newPlayerIsLongest = longestSoFar === null || player.totalTime > longestSoFar.totalTime;\n return newPlayerIsLongest ? player : longestSoFar;\n }, null);\n return longestPlayer != null ? longestPlayer.getPosition() : 0;\n }\n beforeDestroy() {\n this.players.forEach(player => {\n if (player.beforeDestroy) {\n player.beforeDestroy();\n }\n });\n }\n /** @internal */\n triggerCallback(phaseName) {\n const methods = phaseName == 'start' ? this._onStartFns : this._onDoneFns;\n methods.forEach(fn => fn());\n methods.length = 0;\n }\n}\nconst ɵPRE_STYLE = '!';\nexport { AnimationMetadataType as A, NoopAnimationPlayer as N, animate as a, animateChild as b, animation as c, AUTO_STYLE as d, stagger as e, state as f, group as g, style as h, trigger as i, AnimationGroupPlayer as j, keyframes as k, query as q, sequence as s, transition as t, useAnimation as u, ɵPRE_STYLE as ɵ };\n","/**\n * @license Angular v19.2.5\n * (c) 2010-2025 Google LLC. https://angular.io/\n * License: MIT\n */\n\nimport { j as AnimationGroupPlayer, N as NoopAnimationPlayer, d as AUTO_STYLE, ɵ as _PRE_STYLE, A as AnimationMetadataType, s as sequence } from './private_export-DBN_2NMM.mjs';\nimport { ɵRuntimeError as _RuntimeError } from '@angular/core';\nconst LINE_START = '\\n - ';\nfunction invalidTimingValue(exp) {\n return new _RuntimeError(3000 /* RuntimeErrorCode.INVALID_TIMING_VALUE */, ngDevMode && `The provided timing value \"${exp}\" is invalid.`);\n}\nfunction negativeStepValue() {\n return new _RuntimeError(3100 /* RuntimeErrorCode.NEGATIVE_STEP_VALUE */, ngDevMode && 'Duration values below 0 are not allowed for this animation step.');\n}\nfunction negativeDelayValue() {\n return new _RuntimeError(3101 /* RuntimeErrorCode.NEGATIVE_DELAY_VALUE */, ngDevMode && 'Delay values below 0 are not allowed for this animation step.');\n}\nfunction invalidStyleParams(varName) {\n return new _RuntimeError(3001 /* RuntimeErrorCode.INVALID_STYLE_PARAMS */, ngDevMode && `Unable to resolve the local animation param ${varName} in the given list of values`);\n}\nfunction invalidParamValue(varName) {\n return new _RuntimeError(3003 /* RuntimeErrorCode.INVALID_PARAM_VALUE */, ngDevMode && `Please provide a value for the animation param ${varName}`);\n}\nfunction invalidNodeType(nodeType) {\n return new _RuntimeError(3004 /* RuntimeErrorCode.INVALID_NODE_TYPE */, ngDevMode && `Unable to resolve animation metadata node #${nodeType}`);\n}\nfunction invalidCssUnitValue(userProvidedProperty, value) {\n return new _RuntimeError(3005 /* RuntimeErrorCode.INVALID_CSS_UNIT_VALUE */, ngDevMode && `Please provide a CSS unit value for ${userProvidedProperty}:${value}`);\n}\nfunction invalidTrigger() {\n return new _RuntimeError(3006 /* RuntimeErrorCode.INVALID_TRIGGER */, ngDevMode && \"animation triggers cannot be prefixed with an `@` sign (e.g. trigger('@foo', [...]))\");\n}\nfunction invalidDefinition() {\n return new _RuntimeError(3007 /* RuntimeErrorCode.INVALID_DEFINITION */, ngDevMode && 'only state() and transition() definitions can sit inside of a trigger()');\n}\nfunction invalidState(metadataName, missingSubs) {\n return new _RuntimeError(3008 /* RuntimeErrorCode.INVALID_STATE */, ngDevMode && `state(\"${metadataName}\", ...) must define default values for all the following style substitutions: ${missingSubs.join(', ')}`);\n}\nfunction invalidStyleValue(value) {\n return new _RuntimeError(3002 /* RuntimeErrorCode.INVALID_STYLE_VALUE */, ngDevMode && `The provided style string value ${value} is not allowed.`);\n}\nfunction invalidParallelAnimation(prop, firstStart, firstEnd, secondStart, secondEnd) {\n return new _RuntimeError(3010 /* RuntimeErrorCode.INVALID_PARALLEL_ANIMATION */, ngDevMode && `The CSS property \"${prop}\" that exists between the times of \"${firstStart}ms\" and \"${firstEnd}ms\" is also being animated in a parallel animation between the times of \"${secondStart}ms\" and \"${secondEnd}ms\"`);\n}\nfunction invalidKeyframes() {\n return new _RuntimeError(3011 /* RuntimeErrorCode.INVALID_KEYFRAMES */, ngDevMode && `keyframes() must be placed inside of a call to animate()`);\n}\nfunction invalidOffset() {\n return new _RuntimeError(3012 /* RuntimeErrorCode.INVALID_OFFSET */, ngDevMode && `Please ensure that all keyframe offsets are between 0 and 1`);\n}\nfunction keyframeOffsetsOutOfOrder() {\n return new _RuntimeError(3200 /* RuntimeErrorCode.KEYFRAME_OFFSETS_OUT_OF_ORDER */, ngDevMode && `Please ensure that all keyframe offsets are in order`);\n}\nfunction keyframesMissingOffsets() {\n return new _RuntimeError(3202 /* RuntimeErrorCode.KEYFRAMES_MISSING_OFFSETS */, ngDevMode && `Not all style() steps within the declared keyframes() contain offsets`);\n}\nfunction invalidStagger() {\n return new _RuntimeError(3013 /* RuntimeErrorCode.INVALID_STAGGER */, ngDevMode && `stagger() can only be used inside of query()`);\n}\nfunction invalidQuery(selector) {\n return new _RuntimeError(3014 /* RuntimeErrorCode.INVALID_QUERY */, ngDevMode && `\\`query(\"${selector}\")\\` returned zero elements. (Use \\`query(\"${selector}\", { optional: true })\\` if you wish to allow this.)`);\n}\nfunction invalidExpression(expr) {\n return new _RuntimeError(3015 /* RuntimeErrorCode.INVALID_EXPRESSION */, ngDevMode && `The provided transition expression \"${expr}\" is not supported`);\n}\nfunction invalidTransitionAlias(alias) {\n return new _RuntimeError(3016 /* RuntimeErrorCode.INVALID_TRANSITION_ALIAS */, ngDevMode && `The transition alias value \"${alias}\" is not supported`);\n}\nfunction validationFailed(errors) {\n return new _RuntimeError(3500 /* RuntimeErrorCode.VALIDATION_FAILED */, ngDevMode && `animation validation failed:\\n${errors.map(err => err.message).join('\\n')}`);\n}\nfunction buildingFailed(errors) {\n return new _RuntimeError(3501 /* RuntimeErrorCode.BUILDING_FAILED */, ngDevMode && `animation building failed:\\n${errors.map(err => err.message).join('\\n')}`);\n}\nfunction triggerBuildFailed(name, errors) {\n return new _RuntimeError(3404 /* RuntimeErrorCode.TRIGGER_BUILD_FAILED */, ngDevMode && `The animation trigger \"${name}\" has failed to build due to the following errors:\\n - ${errors.map(err => err.message).join('\\n - ')}`);\n}\nfunction animationFailed(errors) {\n return new _RuntimeError(3502 /* RuntimeErrorCode.ANIMATION_FAILED */, ngDevMode && `Unable to animate due to the following errors:${LINE_START}${errors.map(err => err.message).join(LINE_START)}`);\n}\nfunction registerFailed(errors) {\n return new _RuntimeError(3503 /* RuntimeErrorCode.REGISTRATION_FAILED */, ngDevMode && `Unable to build the animation due to the following errors: ${errors.map(err => err.message).join('\\n')}`);\n}\nfunction missingOrDestroyedAnimation() {\n return new _RuntimeError(3300 /* RuntimeErrorCode.MISSING_OR_DESTROYED_ANIMATION */, ngDevMode && \"The requested animation doesn't exist or has already been destroyed\");\n}\nfunction createAnimationFailed(errors) {\n return new _RuntimeError(3504 /* RuntimeErrorCode.CREATE_ANIMATION_FAILED */, ngDevMode && `Unable to create the animation due to the following errors:${errors.map(err => err.message).join('\\n')}`);\n}\nfunction missingPlayer(id) {\n return new _RuntimeError(3301 /* RuntimeErrorCode.MISSING_PLAYER */, ngDevMode && `Unable to find the timeline player referenced by ${id}`);\n}\nfunction missingTrigger(phase, name) {\n return new _RuntimeError(3302 /* RuntimeErrorCode.MISSING_TRIGGER */, ngDevMode && `Unable to listen on the animation trigger event \"${phase}\" because the animation trigger \"${name}\" doesn\\'t exist!`);\n}\nfunction missingEvent(name) {\n return new _RuntimeError(3303 /* RuntimeErrorCode.MISSING_EVENT */, ngDevMode && `Unable to listen on the animation trigger \"${name}\" because the provided event is undefined!`);\n}\nfunction unsupportedTriggerEvent(phase, name) {\n return new _RuntimeError(3400 /* RuntimeErrorCode.UNSUPPORTED_TRIGGER_EVENT */, ngDevMode && `The provided animation trigger event \"${phase}\" for the animation trigger \"${name}\" is not supported!`);\n}\nfunction unregisteredTrigger(name) {\n return new _RuntimeError(3401 /* RuntimeErrorCode.UNREGISTERED_TRIGGER */, ngDevMode && `The provided animation trigger \"${name}\" has not been registered!`);\n}\nfunction triggerTransitionsFailed(errors) {\n return new _RuntimeError(3402 /* RuntimeErrorCode.TRIGGER_TRANSITIONS_FAILED */, ngDevMode && `Unable to process animations due to the following failed trigger transitions\\n ${errors.map(err => err.message).join('\\n')}`);\n}\nfunction transitionFailed(name, errors) {\n return new _RuntimeError(3505 /* RuntimeErrorCode.TRANSITION_FAILED */, ngDevMode && `@${name} has failed due to:\\n ${errors.map(err => err.message).join('\\n- ')}`);\n}\n\n/**\n * Set of all animatable CSS properties\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties\n */\nconst ANIMATABLE_PROP_SET = /*#__PURE__*/new Set(['-moz-outline-radius', '-moz-outline-radius-bottomleft', '-moz-outline-radius-bottomright', '-moz-outline-radius-topleft', '-moz-outline-radius-topright', '-ms-grid-columns', '-ms-grid-rows', '-webkit-line-clamp', '-webkit-text-fill-color', '-webkit-text-stroke', '-webkit-text-stroke-color', 'accent-color', 'all', 'backdrop-filter', 'background', 'background-color', 'background-position', 'background-size', 'block-size', 'border', 'border-block-end', 'border-block-end-color', 'border-block-end-width', 'border-block-start', 'border-block-start-color', 'border-block-start-width', 'border-bottom', 'border-bottom-color', 'border-bottom-left-radius', 'border-bottom-right-radius', 'border-bottom-width', 'border-color', 'border-end-end-radius', 'border-end-start-radius', 'border-image-outset', 'border-image-slice', 'border-image-width', 'border-inline-end', 'border-inline-end-color', 'border-inline-end-width', 'border-inline-start', 'border-inline-start-color', 'border-inline-start-width', 'border-left', 'border-left-color', 'border-left-width', 'border-radius', 'border-right', 'border-right-color', 'border-right-width', 'border-start-end-radius', 'border-start-start-radius', 'border-top', 'border-top-color', 'border-top-left-radius', 'border-top-right-radius', 'border-top-width', 'border-width', 'bottom', 'box-shadow', 'caret-color', 'clip', 'clip-path', 'color', 'column-count', 'column-gap', 'column-rule', 'column-rule-color', 'column-rule-width', 'column-width', 'columns', 'filter', 'flex', 'flex-basis', 'flex-grow', 'flex-shrink', 'font', 'font-size', 'font-size-adjust', 'font-stretch', 'font-variation-settings', 'font-weight', 'gap', 'grid-column-gap', 'grid-gap', 'grid-row-gap', 'grid-template-columns', 'grid-template-rows', 'height', 'inline-size', 'input-security', 'inset', 'inset-block', 'inset-block-end', 'inset-block-start', 'inset-inline', 'inset-inline-end', 'inset-inline-start', 'left', 'letter-spacing', 'line-clamp', 'line-height', 'margin', 'margin-block-end', 'margin-block-start', 'margin-bottom', 'margin-inline-end', 'margin-inline-start', 'margin-left', 'margin-right', 'margin-top', 'mask', 'mask-border', 'mask-position', 'mask-size', 'max-block-size', 'max-height', 'max-inline-size', 'max-lines', 'max-width', 'min-block-size', 'min-height', 'min-inline-size', 'min-width', 'object-position', 'offset', 'offset-anchor', 'offset-distance', 'offset-path', 'offset-position', 'offset-rotate', 'opacity', 'order', 'outline', 'outline-color', 'outline-offset', 'outline-width', 'padding', 'padding-block-end', 'padding-block-start', 'padding-bottom', 'padding-inline-end', 'padding-inline-start', 'padding-left', 'padding-right', 'padding-top', 'perspective', 'perspective-origin', 'right', 'rotate', 'row-gap', 'scale', 'scroll-margin', 'scroll-margin-block', 'scroll-margin-block-end', 'scroll-margin-block-start', 'scroll-margin-bottom', 'scroll-margin-inline', 'scroll-margin-inline-end', 'scroll-margin-inline-start', 'scroll-margin-left', 'scroll-margin-right', 'scroll-margin-top', 'scroll-padding', 'scroll-padding-block', 'scroll-padding-block-end', 'scroll-padding-block-start', 'scroll-padding-bottom', 'scroll-padding-inline', 'scroll-padding-inline-end', 'scroll-padding-inline-start', 'scroll-padding-left', 'scroll-padding-right', 'scroll-padding-top', 'scroll-snap-coordinate', 'scroll-snap-destination', 'scrollbar-color', 'shape-image-threshold', 'shape-margin', 'shape-outside', 'tab-size', 'text-decoration', 'text-decoration-color', 'text-decoration-thickness', 'text-emphasis', 'text-emphasis-color', 'text-indent', 'text-shadow', 'text-underline-offset', 'top', 'transform', 'transform-origin', 'translate', 'vertical-align', 'visibility', 'width', 'word-spacing', 'z-index', 'zoom']);\nfunction optimizeGroupPlayer(players) {\n switch (players.length) {\n case 0:\n return new NoopAnimationPlayer();\n case 1:\n return players[0];\n default:\n return new AnimationGroupPlayer(players);\n }\n}\nfunction normalizeKeyframes$1(normalizer, keyframes, preStyles = new Map(), postStyles = new Map()) {\n const errors = [];\n const normalizedKeyframes = [];\n let previousOffset = -1;\n let previousKeyframe = null;\n keyframes.forEach(kf => {\n const offset = kf.get('offset');\n const isSameOffset = offset == previousOffset;\n const normalizedKeyframe = isSameOffset && previousKeyframe || new Map();\n kf.forEach((val, prop) => {\n let normalizedProp = prop;\n let normalizedValue = val;\n if (prop !== 'offset') {\n normalizedProp = normalizer.normalizePropertyName(normalizedProp, errors);\n switch (normalizedValue) {\n case _PRE_STYLE:\n normalizedValue = preStyles.get(prop);\n break;\n case AUTO_STYLE:\n normalizedValue = postStyles.get(prop);\n break;\n default:\n normalizedValue = normalizer.normalizeStyleValue(prop, normalizedProp, normalizedValue, errors);\n break;\n }\n }\n normalizedKeyframe.set(normalizedProp, normalizedValue);\n });\n if (!isSameOffset) {\n normalizedKeyframes.push(normalizedKeyframe);\n }\n previousKeyframe = normalizedKeyframe;\n previousOffset = offset;\n });\n if (errors.length) {\n throw animationFailed(errors);\n }\n return normalizedKeyframes;\n}\nfunction listenOnPlayer(player, eventName, event, callback) {\n switch (eventName) {\n case 'start':\n player.onStart(() => callback(event && copyAnimationEvent(event, 'start', player)));\n break;\n case 'done':\n player.onDone(() => callback(event && copyAnimationEvent(event, 'done', player)));\n break;\n case 'destroy':\n player.onDestroy(() => callback(event && copyAnimationEvent(event, 'destroy', player)));\n break;\n }\n}\nfunction copyAnimationEvent(e, phaseName, player) {\n const totalTime = player.totalTime;\n const disabled = player.disabled ? true : false;\n const event = makeAnimationEvent(e.element, e.triggerName, e.fromState, e.toState, phaseName || e.phaseName, totalTime == undefined ? e.totalTime : totalTime, disabled);\n const data = e['_data'];\n if (data != null) {\n event['_data'] = data;\n }\n return event;\n}\nfunction makeAnimationEvent(element, triggerName, fromState, toState, phaseName = '', totalTime = 0, disabled) {\n return {\n element,\n triggerName,\n fromState,\n toState,\n phaseName,\n totalTime,\n disabled: !!disabled\n };\n}\nfunction getOrSetDefaultValue(map, key, defaultValue) {\n let value = map.get(key);\n if (!value) {\n map.set(key, value = defaultValue);\n }\n return value;\n}\nfunction parseTimelineCommand(command) {\n const separatorPos = command.indexOf(':');\n const id = command.substring(1, separatorPos);\n const action = command.slice(separatorPos + 1);\n return [id, action];\n}\nconst documentElement = /* @__PURE__ */(() => typeof document === 'undefined' ? null : document.documentElement)();\nfunction getParentElement(element) {\n const parent = element.parentNode || element.host || null; // consider host to support shadow DOM\n if (parent === documentElement) {\n return null;\n }\n return parent;\n}\nfunction containsVendorPrefix(prop) {\n // Webkit is the only real popular vendor prefix nowadays\n // cc: http://shouldiprefix.com/\n return prop.substring(1, 6) == 'ebkit'; // webkit or Webkit\n}\nlet _CACHED_BODY = null;\nlet _IS_WEBKIT = false;\nfunction validateStyleProperty(prop) {\n if (!_CACHED_BODY) {\n _CACHED_BODY = getBodyNode() || {};\n _IS_WEBKIT = _CACHED_BODY.style ? 'WebkitAppearance' in _CACHED_BODY.style : false;\n }\n let result = true;\n if (_CACHED_BODY.style && !containsVendorPrefix(prop)) {\n result = prop in _CACHED_BODY.style;\n if (!result && _IS_WEBKIT) {\n const camelProp = 'Webkit' + prop.charAt(0).toUpperCase() + prop.slice(1);\n result = camelProp in _CACHED_BODY.style;\n }\n }\n return result;\n}\nfunction validateWebAnimatableStyleProperty(prop) {\n return ANIMATABLE_PROP_SET.has(prop);\n}\nfunction getBodyNode() {\n if (typeof document != 'undefined') {\n return document.body;\n }\n return null;\n}\nfunction containsElement(elm1, elm2) {\n while (elm2) {\n if (elm2 === elm1) {\n return true;\n }\n elm2 = getParentElement(elm2);\n }\n return false;\n}\nfunction invokeQuery(element, selector, multi) {\n if (multi) {\n return Array.from(element.querySelectorAll(selector));\n }\n const elem = element.querySelector(selector);\n return elem ? [elem] : [];\n}\nconst ONE_SECOND = 1000;\nconst SUBSTITUTION_EXPR_START = '{{';\nconst SUBSTITUTION_EXPR_END = '}}';\nconst ENTER_CLASSNAME = 'ng-enter';\nconst LEAVE_CLASSNAME = 'ng-leave';\nconst NG_TRIGGER_CLASSNAME = 'ng-trigger';\nconst NG_TRIGGER_SELECTOR = '.ng-trigger';\nconst NG_ANIMATING_CLASSNAME = 'ng-animating';\nconst NG_ANIMATING_SELECTOR = '.ng-animating';\nfunction resolveTimingValue(value) {\n if (typeof value == 'number') return value;\n const matches = value.match(/^(-?[\\.\\d]+)(m?s)/);\n if (!matches || matches.length < 2) return 0;\n return _convertTimeValueToMS(parseFloat(matches[1]), matches[2]);\n}\nfunction _convertTimeValueToMS(value, unit) {\n switch (unit) {\n case 's':\n return value * ONE_SECOND;\n default:\n // ms or something else\n return value;\n }\n}\nfunction resolveTiming(timings, errors, allowNegativeValues) {\n return timings.hasOwnProperty('duration') ? timings : parseTimeExpression(timings, errors, allowNegativeValues);\n}\nfunction parseTimeExpression(exp, errors, allowNegativeValues) {\n const regex = /^(-?[\\.\\d]+)(m?s)(?:\\s+(-?[\\.\\d]+)(m?s))?(?:\\s+([-a-z]+(?:\\(.+?\\))?))?$/i;\n let duration;\n let delay = 0;\n let easing = '';\n if (typeof exp === 'string') {\n const matches = exp.match(regex);\n if (matches === null) {\n errors.push(invalidTimingValue(exp));\n return {\n duration: 0,\n delay: 0,\n easing: ''\n };\n }\n duration = _convertTimeValueToMS(parseFloat(matches[1]), matches[2]);\n const delayMatch = matches[3];\n if (delayMatch != null) {\n delay = _convertTimeValueToMS(parseFloat(delayMatch), matches[4]);\n }\n const easingVal = matches[5];\n if (easingVal) {\n easing = easingVal;\n }\n } else {\n duration = exp;\n }\n if (!allowNegativeValues) {\n let containsErrors = false;\n let startIndex = errors.length;\n if (duration < 0) {\n errors.push(negativeStepValue());\n containsErrors = true;\n }\n if (delay < 0) {\n errors.push(negativeDelayValue());\n containsErrors = true;\n }\n if (containsErrors) {\n errors.splice(startIndex, 0, invalidTimingValue(exp));\n }\n }\n return {\n duration,\n delay,\n easing\n };\n}\nfunction normalizeKeyframes(keyframes) {\n if (!keyframes.length) {\n return [];\n }\n if (keyframes[0] instanceof Map) {\n return keyframes;\n }\n return keyframes.map(kf => new Map(Object.entries(kf)));\n}\nfunction normalizeStyles(styles) {\n return Array.isArray(styles) ? new Map(...styles) : new Map(styles);\n}\nfunction setStyles(element, styles, formerStyles) {\n styles.forEach((val, prop) => {\n const camelProp = dashCaseToCamelCase(prop);\n if (formerStyles && !formerStyles.has(prop)) {\n formerStyles.set(prop, element.style[camelProp]);\n }\n element.style[camelProp] = val;\n });\n}\nfunction eraseStyles(element, styles) {\n styles.forEach((_, prop) => {\n const camelProp = dashCaseToCamelCase(prop);\n element.style[camelProp] = '';\n });\n}\nfunction normalizeAnimationEntry(steps) {\n if (Array.isArray(steps)) {\n if (steps.length == 1) return steps[0];\n return sequence(steps);\n }\n return steps;\n}\nfunction validateStyleParams(value, options, errors) {\n const params = options.params || {};\n const matches = extractStyleParams(value);\n if (matches.length) {\n matches.forEach(varName => {\n if (!params.hasOwnProperty(varName)) {\n errors.push(invalidStyleParams(varName));\n }\n });\n }\n}\nconst PARAM_REGEX = /* @__PURE__ */new RegExp(`${SUBSTITUTION_EXPR_START}\\\\s*(.+?)\\\\s*${SUBSTITUTION_EXPR_END}`, 'g');\nfunction extractStyleParams(value) {\n let params = [];\n if (typeof value === 'string') {\n let match;\n while (match = PARAM_REGEX.exec(value)) {\n params.push(match[1]);\n }\n PARAM_REGEX.lastIndex = 0;\n }\n return params;\n}\nfunction interpolateParams(value, params, errors) {\n const original = `${value}`;\n const str = original.replace(PARAM_REGEX, (_, varName) => {\n let localVal = params[varName];\n // this means that the value was never overridden by the data passed in by the user\n if (localVal == null) {\n errors.push(invalidParamValue(varName));\n localVal = '';\n }\n return localVal.toString();\n });\n // we do this to assert that numeric values stay as they are\n return str == original ? value : str;\n}\nconst DASH_CASE_REGEXP = /-+([a-z0-9])/g;\nfunction dashCaseToCamelCase(input) {\n return input.replace(DASH_CASE_REGEXP, (...m) => m[1].toUpperCase());\n}\nfunction camelCaseToDashCase(input) {\n return input.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n}\nfunction allowPreviousPlayerStylesMerge(duration, delay) {\n return duration === 0 || delay === 0;\n}\nfunction balancePreviousStylesIntoKeyframes(element, keyframes, previousStyles) {\n if (previousStyles.size && keyframes.length) {\n let startingKeyframe = keyframes[0];\n let missingStyleProps = [];\n previousStyles.forEach((val, prop) => {\n if (!startingKeyframe.has(prop)) {\n missingStyleProps.push(prop);\n }\n startingKeyframe.set(prop, val);\n });\n if (missingStyleProps.length) {\n for (let i = 1; i < keyframes.length; i++) {\n let kf = keyframes[i];\n missingStyleProps.forEach(prop => kf.set(prop, computeStyle(element, prop)));\n }\n }\n }\n return keyframes;\n}\nfunction visitDslNode(visitor, node, context) {\n switch (node.type) {\n case AnimationMetadataType.Trigger:\n return visitor.visitTrigger(node, context);\n case AnimationMetadataType.State:\n return visitor.visitState(node, context);\n case AnimationMetadataType.Transition:\n return visitor.visitTransition(node, context);\n case AnimationMetadataType.Sequence:\n return visitor.visitSequence(node, context);\n case AnimationMetadataType.Group:\n return visitor.visitGroup(node, context);\n case AnimationMetadataType.Animate:\n return visitor.visitAnimate(node, context);\n case AnimationMetadataType.Keyframes:\n return visitor.visitKeyframes(node, context);\n case AnimationMetadataType.Style:\n return visitor.visitStyle(node, context);\n case AnimationMetadataType.Reference:\n return visitor.visitReference(node, context);\n case AnimationMetadataType.AnimateChild:\n return visitor.visitAnimateChild(node, context);\n case AnimationMetadataType.AnimateRef:\n return visitor.visitAnimateRef(node, context);\n case AnimationMetadataType.Query:\n return visitor.visitQuery(node, context);\n case AnimationMetadataType.Stagger:\n return visitor.visitStagger(node, context);\n default:\n throw invalidNodeType(node.type);\n }\n}\nfunction computeStyle(element, prop) {\n return window.getComputedStyle(element)[prop];\n}\nexport { camelCaseToDashCase as $, interpolateParams as A, invalidQuery as B, registerFailed as C, normalizeKeyframes$1 as D, ENTER_CLASSNAME as E, missingOrDestroyedAnimation as F, createAnimationFailed as G, optimizeGroupPlayer as H, missingPlayer as I, listenOnPlayer as J, makeAnimationEvent as K, LEAVE_CLASSNAME as L, triggerTransitionsFailed as M, NG_TRIGGER_SELECTOR as N, eraseStyles as O, setStyles as P, transitionFailed as Q, missingTrigger as R, SUBSTITUTION_EXPR_START as S, missingEvent as T, unsupportedTriggerEvent as U, unregisteredTrigger as V, NG_TRIGGER_CLASSNAME as W, NG_ANIMATING_CLASSNAME as X, triggerBuildFailed as Y, parseTimelineCommand as Z, computeStyle as _, invalidCssUnitValue as a, validateWebAnimatableStyleProperty as a0, allowPreviousPlayerStylesMerge as a1, normalizeKeyframes as a2, balancePreviousStylesIntoKeyframes as a3, validationFailed as a4, normalizeStyles as a5, buildingFailed as a6, invalidExpression as b, containsElement as c, dashCaseToCamelCase as d, invalidTransitionAlias as e, visitDslNode as f, getParentElement as g, invalidTrigger as h, invokeQuery as i, invalidDefinition as j, extractStyleParams as k, invalidState as l, invalidStyleValue as m, invalidParallelAnimation as n, validateStyleParams as o, invalidKeyframes as p, invalidOffset as q, keyframeOffsetsOutOfOrder as r, keyframesMissingOffsets as s, getOrSetDefaultValue as t, invalidStagger as u, validateStyleProperty as v, resolveTiming as w, normalizeAnimationEntry as x, NG_ANIMATING_SELECTOR as y, resolveTimingValue as z };\n","/**\n * @license Angular v19.2.5\n * (c) 2010-2025 Google LLC. https://angular.io/\n * License: MIT\n */\n\nimport * as i0 from '@angular/core';\nimport { Injectable } from '@angular/core';\nimport { v as validateStyleProperty, c as containsElement, g as getParentElement, i as invokeQuery, d as dashCaseToCamelCase, a as invalidCssUnitValue, b as invalidExpression, e as invalidTransitionAlias, f as visitDslNode, h as invalidTrigger, j as invalidDefinition, k as extractStyleParams, l as invalidState, m as invalidStyleValue, S as SUBSTITUTION_EXPR_START, n as invalidParallelAnimation, o as validateStyleParams, p as invalidKeyframes, q as invalidOffset, r as keyframeOffsetsOutOfOrder, s as keyframesMissingOffsets, t as getOrSetDefaultValue, u as invalidStagger, w as resolveTiming, x as normalizeAnimationEntry, N as NG_TRIGGER_SELECTOR, y as NG_ANIMATING_SELECTOR, z as resolveTimingValue, A as interpolateParams, B as invalidQuery, C as registerFailed, D as normalizeKeyframes, L as LEAVE_CLASSNAME, E as ENTER_CLASSNAME, F as missingOrDestroyedAnimation, G as createAnimationFailed, H as optimizeGroupPlayer, I as missingPlayer, J as listenOnPlayer, K as makeAnimationEvent, M as triggerTransitionsFailed, O as eraseStyles, P as setStyles, Q as transitionFailed, R as missingTrigger, T as missingEvent, U as unsupportedTriggerEvent, V as unregisteredTrigger, W as NG_TRIGGER_CLASSNAME, X as NG_ANIMATING_CLASSNAME, Y as triggerBuildFailed, Z as parseTimelineCommand, _ as computeStyle, $ as camelCaseToDashCase, a0 as validateWebAnimatableStyleProperty, a1 as allowPreviousPlayerStylesMerge, a2 as normalizeKeyframes$1, a3 as balancePreviousStylesIntoKeyframes, a4 as validationFailed, a5 as normalizeStyles, a6 as buildingFailed } from './util-DIamNgWY.mjs';\nimport { N as NoopAnimationPlayer, A as AnimationMetadataType, h as style, d as AUTO_STYLE, ɵ as _PRE_STYLE, j as AnimationGroupPlayer } from './private_export-DBN_2NMM.mjs';\n\n/**\n * @publicApi\n *\n * `AnimationDriver` implentation for Noop animations\n */\nlet NoopAnimationDriver = /*#__PURE__*/(() => {\n class NoopAnimationDriver {\n /**\n * @returns Whether `prop` is a valid CSS property\n */\n validateStyleProperty(prop) {\n return validateStyleProperty(prop);\n }\n /**\n *\n * @returns Whether elm1 contains elm2.\n */\n containsElement(elm1, elm2) {\n return containsElement(elm1, elm2);\n }\n /**\n * @returns Rhe parent of the given element or `null` if the element is the `document`\n */\n getParentElement(element) {\n return getParentElement(element);\n }\n /**\n * @returns The result of the query selector on the element. The array will contain up to 1 item\n * if `multi` is `false`.\n */\n query(element, selector, multi) {\n return invokeQuery(element, selector, multi);\n }\n /**\n * @returns The `defaultValue` or empty string\n */\n computeStyle(element, prop, defaultValue) {\n return defaultValue || '';\n }\n /**\n * @returns An `NoopAnimationPlayer`\n */\n animate(element, keyframes, duration, delay, easing, previousPlayers = [], scrubberAccessRequested) {\n return new NoopAnimationPlayer(duration, delay);\n }\n static ɵfac = function NoopAnimationDriver_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || NoopAnimationDriver)();\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: NoopAnimationDriver,\n factory: NoopAnimationDriver.ɵfac\n });\n }\n return NoopAnimationDriver;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * @publicApi\n */\nclass AnimationDriver {\n /**\n * @deprecated Use the NoopAnimationDriver class.\n */\n static NOOP = /*#__PURE__*/new NoopAnimationDriver();\n}\nclass AnimationStyleNormalizer {}\nclass NoopAnimationStyleNormalizer {\n normalizePropertyName(propertyName, errors) {\n return propertyName;\n }\n normalizeStyleValue(userProvidedProperty, normalizedProperty, value, errors) {\n return value;\n }\n}\nconst DIMENSIONAL_PROP_SET = /*#__PURE__*/new Set(['width', 'height', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight', 'left', 'top', 'bottom', 'right', 'fontSize', 'outlineWidth', 'outlineOffset', 'paddingTop', 'paddingLeft', 'paddingBottom', 'paddingRight', 'marginTop', 'marginLeft', 'marginBottom', 'marginRight', 'borderRadius', 'borderWidth', 'borderTopWidth', 'borderLeftWidth', 'borderRightWidth', 'borderBottomWidth', 'textIndent', 'perspective']);\nclass WebAnimationsStyleNormalizer extends AnimationStyleNormalizer {\n normalizePropertyName(propertyName, errors) {\n return dashCaseToCamelCase(propertyName);\n }\n normalizeStyleValue(userProvidedProperty, normalizedProperty, value, errors) {\n let unit = '';\n const strVal = value.toString().trim();\n if (DIMENSIONAL_PROP_SET.has(normalizedProperty) && value !== 0 && value !== '0') {\n if (typeof value === 'number') {\n unit = 'px';\n } else {\n const valAndSuffixMatch = value.match(/^[+-]?[\\d\\.]+([a-z]*)$/);\n if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) {\n errors.push(invalidCssUnitValue(userProvidedProperty, value));\n }\n }\n }\n return strVal + unit;\n }\n}\nfunction createListOfWarnings(warnings) {\n const LINE_START = '\\n - ';\n return `${LINE_START}${warnings.filter(Boolean).map(warning => warning).join(LINE_START)}`;\n}\nfunction warnValidation(warnings) {\n console.warn(`animation validation warnings:${createListOfWarnings(warnings)}`);\n}\nfunction warnTriggerBuild(name, warnings) {\n console.warn(`The animation trigger \"${name}\" has built with the following warnings:${createListOfWarnings(warnings)}`);\n}\nfunction warnRegister(warnings) {\n console.warn(`Animation built with the following warnings:${createListOfWarnings(warnings)}`);\n}\nfunction pushUnrecognizedPropertiesWarning(warnings, props) {\n if (props.length) {\n warnings.push(`The following provided properties are not recognized: ${props.join(', ')}`);\n }\n}\nconst ANY_STATE = '*';\nfunction parseTransitionExpr(transitionValue, errors) {\n const expressions = [];\n if (typeof transitionValue == 'string') {\n transitionValue.split(/\\s*,\\s*/).forEach(str => parseInnerTransitionStr(str, expressions, errors));\n } else {\n expressions.push(transitionValue);\n }\n return expressions;\n}\nfunction parseInnerTransitionStr(eventStr, expressions, errors) {\n if (eventStr[0] == ':') {\n const result = parseAnimationAlias(eventStr, errors);\n if (typeof result == 'function') {\n expressions.push(result);\n return;\n }\n eventStr = result;\n }\n const match = eventStr.match(/^(\\*|[-\\w]+)\\s*()\\s*(\\*|[-\\w]+)$/);\n if (match == null || match.length < 4) {\n errors.push(invalidExpression(eventStr));\n return expressions;\n }\n const fromState = match[1];\n const separator = match[2];\n const toState = match[3];\n expressions.push(makeLambdaFromStates(fromState, toState));\n const isFullAnyStateExpr = fromState == ANY_STATE && toState == ANY_STATE;\n if (separator[0] == '<' && !isFullAnyStateExpr) {\n expressions.push(makeLambdaFromStates(toState, fromState));\n }\n return;\n}\nfunction parseAnimationAlias(alias, errors) {\n switch (alias) {\n case ':enter':\n return 'void => *';\n case ':leave':\n return '* => void';\n case ':increment':\n return (fromState, toState) => parseFloat(toState) > parseFloat(fromState);\n case ':decrement':\n return (fromState, toState) => parseFloat(toState) < parseFloat(fromState);\n default:\n errors.push(invalidTransitionAlias(alias));\n return '* => *';\n }\n}\n// DO NOT REFACTOR ... keep the follow set instantiations\n// with the values intact (closure compiler for some reason\n// removes follow-up lines that add the values outside of\n// the constructor...\nconst TRUE_BOOLEAN_VALUES = /*#__PURE__*/new Set(['true', '1']);\nconst FALSE_BOOLEAN_VALUES = /*#__PURE__*/new Set(['false', '0']);\nfunction makeLambdaFromStates(lhs, rhs) {\n const LHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(lhs) || FALSE_BOOLEAN_VALUES.has(lhs);\n const RHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(rhs) || FALSE_BOOLEAN_VALUES.has(rhs);\n return (fromState, toState) => {\n let lhsMatch = lhs == ANY_STATE || lhs == fromState;\n let rhsMatch = rhs == ANY_STATE || rhs == toState;\n if (!lhsMatch && LHS_MATCH_BOOLEAN && typeof fromState === 'boolean') {\n lhsMatch = fromState ? TRUE_BOOLEAN_VALUES.has(lhs) : FALSE_BOOLEAN_VALUES.has(lhs);\n }\n if (!rhsMatch && RHS_MATCH_BOOLEAN && typeof toState === 'boolean') {\n rhsMatch = toState ? TRUE_BOOLEAN_VALUES.has(rhs) : FALSE_BOOLEAN_VALUES.has(rhs);\n }\n return lhsMatch && rhsMatch;\n };\n}\nconst SELF_TOKEN = ':self';\nconst SELF_TOKEN_REGEX = /* @__PURE__ */new RegExp(`s*${SELF_TOKEN}s*,?`, 'g');\n/*\n * [Validation]\n * The visitor code below will traverse the animation AST generated by the animation verb functions\n * (the output is a tree of objects) and attempt to perform a series of validations on the data. The\n * following corner-cases will be validated:\n *\n * 1. Overlap of animations\n * Given that a CSS property cannot be animated in more than one place at the same time, it's\n * important that this behavior is detected and validated. The way in which this occurs is that\n * each time a style property is examined, a string-map containing the property will be updated with\n * the start and end times for when the property is used within an animation step.\n *\n * If there are two or more parallel animations that are currently running (these are invoked by the\n * group()) on the same element then the validator will throw an error. Since the start/end timing\n * values are collected for each property then if the current animation step is animating the same\n * property and its timing values fall anywhere into the window of time that the property is\n * currently being animated within then this is what causes an error.\n *\n * 2. Timing values\n * The validator will validate to see if a timing value of `duration delay easing` or\n * `durationNumber` is valid or not.\n *\n * (note that upon validation the code below will replace the timing data with an object containing\n * {duration,delay,easing}.\n *\n * 3. Offset Validation\n * Each of the style() calls are allowed to have an offset value when placed inside of keyframes().\n * Offsets within keyframes() are considered valid when:\n *\n * - No offsets are used at all\n * - Each style() entry contains an offset value\n * - Each offset is between 0 and 1\n * - Each offset is greater to or equal than the previous one\n *\n * Otherwise an error will be thrown.\n */\nfunction buildAnimationAst(driver, metadata, errors, warnings) {\n return new AnimationAstBuilderVisitor(driver).build(metadata, errors, warnings);\n}\nconst ROOT_SELECTOR = '';\nclass AnimationAstBuilderVisitor {\n _driver;\n constructor(_driver) {\n this._driver = _driver;\n }\n build(metadata, errors, warnings) {\n const context = new AnimationAstBuilderContext(errors);\n this._resetContextStyleTimingState(context);\n const ast = visitDslNode(this, normalizeAnimationEntry(metadata), context);\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n if (context.unsupportedCSSPropertiesFound.size) {\n pushUnrecognizedPropertiesWarning(warnings, [...context.unsupportedCSSPropertiesFound.keys()]);\n }\n }\n return ast;\n }\n _resetContextStyleTimingState(context) {\n context.currentQuerySelector = ROOT_SELECTOR;\n context.collectedStyles = new Map();\n context.collectedStyles.set(ROOT_SELECTOR, new Map());\n context.currentTime = 0;\n }\n visitTrigger(metadata, context) {\n let queryCount = context.queryCount = 0;\n let depCount = context.depCount = 0;\n const states = [];\n const transitions = [];\n if (metadata.name.charAt(0) == '@') {\n context.errors.push(invalidTrigger());\n }\n metadata.definitions.forEach(def => {\n this._resetContextStyleTimingState(context);\n if (def.type == AnimationMetadataType.State) {\n const stateDef = def;\n const name = stateDef.name;\n name.toString().split(/\\s*,\\s*/).forEach(n => {\n stateDef.name = n;\n states.push(this.visitState(stateDef, context));\n });\n stateDef.name = name;\n } else if (def.type == AnimationMetadataType.Transition) {\n const transition = this.visitTransition(def, context);\n queryCount += transition.queryCount;\n depCount += transition.depCount;\n transitions.push(transition);\n } else {\n context.errors.push(invalidDefinition());\n }\n });\n return {\n type: AnimationMetadataType.Trigger,\n name: metadata.name,\n states,\n transitions,\n queryCount,\n depCount,\n options: null\n };\n }\n visitState(metadata, context) {\n const styleAst = this.visitStyle(metadata.styles, context);\n const astParams = metadata.options && metadata.options.params || null;\n if (styleAst.containsDynamicStyles) {\n const missingSubs = new Set();\n const params = astParams || {};\n styleAst.styles.forEach(style => {\n if (style instanceof Map) {\n style.forEach(value => {\n extractStyleParams(value).forEach(sub => {\n if (!params.hasOwnProperty(sub)) {\n missingSubs.add(sub);\n }\n });\n });\n }\n });\n if (missingSubs.size) {\n context.errors.push(invalidState(metadata.name, [...missingSubs.values()]));\n }\n }\n return {\n type: AnimationMetadataType.State,\n name: metadata.name,\n style: styleAst,\n options: astParams ? {\n params: astParams\n } : null\n };\n }\n visitTransition(metadata, context) {\n context.queryCount = 0;\n context.depCount = 0;\n const animation = visitDslNode(this, normalizeAnimationEntry(metadata.animation), context);\n const matchers = parseTransitionExpr(metadata.expr, context.errors);\n return {\n type: AnimationMetadataType.Transition,\n matchers,\n animation,\n queryCount: context.queryCount,\n depCount: context.depCount,\n options: normalizeAnimationOptions(metadata.options)\n };\n }\n visitSequence(metadata, context) {\n return {\n type: AnimationMetadataType.Sequence,\n steps: metadata.steps.map(s => visitDslNode(this, s, context)),\n options: normalizeAnimationOptions(metadata.options)\n };\n }\n visitGroup(metadata, context) {\n const currentTime = context.currentTime;\n let furthestTime = 0;\n const steps = metadata.steps.map(step => {\n context.currentTime = currentTime;\n const innerAst = visitDslNode(this, step, context);\n furthestTime = Math.max(furthestTime, context.currentTime);\n return innerAst;\n });\n context.currentTime = furthestTime;\n return {\n type: AnimationMetadataType.Group,\n steps,\n options: normalizeAnimationOptions(metadata.options)\n };\n }\n visitAnimate(metadata, context) {\n const timingAst = constructTimingAst(metadata.timings, context.errors);\n context.currentAnimateTimings = timingAst;\n let styleAst;\n let styleMetadata = metadata.styles ? metadata.styles : style({});\n if (styleMetadata.type == AnimationMetadataType.Keyframes) {\n styleAst = this.visitKeyframes(styleMetadata, context);\n } else {\n let styleMetadata = metadata.styles;\n let isEmpty = false;\n if (!styleMetadata) {\n isEmpty = true;\n const newStyleData = {};\n if (timingAst.easing) {\n newStyleData['easing'] = timingAst.easing;\n }\n styleMetadata = style(newStyleData);\n }\n context.currentTime += timingAst.duration + timingAst.delay;\n const _styleAst = this.visitStyle(styleMetadata, context);\n _styleAst.isEmptyStep = isEmpty;\n styleAst = _styleAst;\n }\n context.currentAnimateTimings = null;\n return {\n type: AnimationMetadataType.Animate,\n timings: timingAst,\n style: styleAst,\n options: null\n };\n }\n visitStyle(metadata, context) {\n const ast = this._makeStyleAst(metadata, context);\n this._validateStyleAst(ast, context);\n return ast;\n }\n _makeStyleAst(metadata, context) {\n const styles = [];\n const metadataStyles = Array.isArray(metadata.styles) ? metadata.styles : [metadata.styles];\n for (let styleTuple of metadataStyles) {\n if (typeof styleTuple === 'string') {\n if (styleTuple === AUTO_STYLE) {\n styles.push(styleTuple);\n } else {\n context.errors.push(invalidStyleValue(styleTuple));\n }\n } else {\n styles.push(new Map(Object.entries(styleTuple)));\n }\n }\n let containsDynamicStyles = false;\n let collectedEasing = null;\n styles.forEach(styleData => {\n if (styleData instanceof Map) {\n if (styleData.has('easing')) {\n collectedEasing = styleData.get('easing');\n styleData.delete('easing');\n }\n if (!containsDynamicStyles) {\n for (let value of styleData.values()) {\n if (value.toString().indexOf(SUBSTITUTION_EXPR_START) >= 0) {\n containsDynamicStyles = true;\n break;\n }\n }\n }\n }\n });\n return {\n type: AnimationMetadataType.Style,\n styles,\n easing: collectedEasing,\n offset: metadata.offset,\n containsDynamicStyles,\n options: null\n };\n }\n _validateStyleAst(ast, context) {\n const timings = context.currentAnimateTimings;\n let endTime = context.currentTime;\n let startTime = context.currentTime;\n if (timings && startTime > 0) {\n startTime -= timings.duration + timings.delay;\n }\n ast.styles.forEach(tuple => {\n if (typeof tuple === 'string') return;\n tuple.forEach((value, prop) => {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n if (!this._driver.validateStyleProperty(prop)) {\n tuple.delete(prop);\n context.unsupportedCSSPropertiesFound.add(prop);\n return;\n }\n }\n // This is guaranteed to have a defined Map at this querySelector location making it\n // safe to add the assertion here. It is set as a default empty map in prior methods.\n const collectedStyles = context.collectedStyles.get(context.currentQuerySelector);\n const collectedEntry = collectedStyles.get(prop);\n let updateCollectedStyle = true;\n if (collectedEntry) {\n if (startTime != endTime && startTime >= collectedEntry.startTime && endTime <= collectedEntry.endTime) {\n context.errors.push(invalidParallelAnimation(prop, collectedEntry.startTime, collectedEntry.endTime, startTime, endTime));\n updateCollectedStyle = false;\n }\n // we always choose the smaller start time value since we\n // want to have a record of the entire animation window where\n // the style property is being animated in between\n startTime = collectedEntry.startTime;\n }\n if (updateCollectedStyle) {\n collectedStyles.set(prop, {\n startTime,\n endTime\n });\n }\n if (context.options) {\n validateStyleParams(value, context.options, context.errors);\n }\n });\n });\n }\n visitKeyframes(metadata, context) {\n const ast = {\n type: AnimationMetadataType.Keyframes,\n styles: [],\n options: null\n };\n if (!context.currentAnimateTimings) {\n context.errors.push(invalidKeyframes());\n return ast;\n }\n const MAX_KEYFRAME_OFFSET = 1;\n let totalKeyframesWithOffsets = 0;\n const offsets = [];\n let offsetsOutOfOrder = false;\n let keyframesOutOfRange = false;\n let previousOffset = 0;\n const keyframes = metadata.steps.map(styles => {\n const style = this._makeStyleAst(styles, context);\n let offsetVal = style.offset != null ? style.offset : consumeOffset(style.styles);\n let offset = 0;\n if (offsetVal != null) {\n totalKeyframesWithOffsets++;\n offset = style.offset = offsetVal;\n }\n keyframesOutOfRange = keyframesOutOfRange || offset < 0 || offset > 1;\n offsetsOutOfOrder = offsetsOutOfOrder || offset < previousOffset;\n previousOffset = offset;\n offsets.push(offset);\n return style;\n });\n if (keyframesOutOfRange) {\n context.errors.push(invalidOffset());\n }\n if (offsetsOutOfOrder) {\n context.errors.push(keyframeOffsetsOutOfOrder());\n }\n const length = metadata.steps.length;\n let generatedOffset = 0;\n if (totalKeyframesWithOffsets > 0 && totalKeyframesWithOffsets < length) {\n context.errors.push(keyframesMissingOffsets());\n } else if (totalKeyframesWithOffsets == 0) {\n generatedOffset = MAX_KEYFRAME_OFFSET / (length - 1);\n }\n const limit = length - 1;\n const currentTime = context.currentTime;\n const currentAnimateTimings = context.currentAnimateTimings;\n const animateDuration = currentAnimateTimings.duration;\n keyframes.forEach((kf, i) => {\n const offset = generatedOffset > 0 ? i == limit ? 1 : generatedOffset * i : offsets[i];\n const durationUpToThisFrame = offset * animateDuration;\n context.currentTime = currentTime + currentAnimateTimings.delay + durationUpToThisFrame;\n currentAnimateTimings.duration = durationUpToThisFrame;\n this._validateStyleAst(kf, context);\n kf.offset = offset;\n ast.styles.push(kf);\n });\n return ast;\n }\n visitReference(metadata, context) {\n return {\n type: AnimationMetadataType.Reference,\n animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context),\n options: normalizeAnimationOptions(metadata.options)\n };\n }\n visitAnimateChild(metadata, context) {\n context.depCount++;\n return {\n type: AnimationMetadataType.AnimateChild,\n options: normalizeAnimationOptions(metadata.options)\n };\n }\n visitAnimateRef(metadata, context) {\n return {\n type: AnimationMetadataType.AnimateRef,\n animation: this.visitReference(metadata.animation, context),\n options: normalizeAnimationOptions(metadata.options)\n };\n }\n visitQuery(metadata, context) {\n const parentSelector = context.currentQuerySelector;\n const options = metadata.options || {};\n context.queryCount++;\n context.currentQuery = metadata;\n const [selector, includeSelf] = normalizeSelector(metadata.selector);\n context.currentQuerySelector = parentSelector.length ? parentSelector + ' ' + selector : selector;\n getOrSetDefaultValue(context.collectedStyles, context.currentQuerySelector, new Map());\n const animation = visitDslNode(this, normalizeAnimationEntry(metadata.animation), context);\n context.currentQuery = null;\n context.currentQuerySelector = parentSelector;\n return {\n type: AnimationMetadataType.Query,\n selector,\n limit: options.limit || 0,\n optional: !!options.optional,\n includeSelf,\n animation,\n originalSelector: metadata.selector,\n options: normalizeAnimationOptions(metadata.options)\n };\n }\n visitStagger(metadata, context) {\n if (!context.currentQuery) {\n context.errors.push(invalidStagger());\n }\n const timings = metadata.timings === 'full' ? {\n duration: 0,\n delay: 0,\n easing: 'full'\n } : resolveTiming(metadata.timings, context.errors, true);\n return {\n type: AnimationMetadataType.Stagger,\n animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context),\n timings,\n options: null\n };\n }\n}\nfunction normalizeSelector(selector) {\n const hasAmpersand = selector.split(/\\s*,\\s*/).find(token => token == SELF_TOKEN) ? true : false;\n if (hasAmpersand) {\n selector = selector.replace(SELF_TOKEN_REGEX, '');\n }\n // Note: the :enter and :leave aren't normalized here since those\n // selectors are filled in at runtime during timeline building\n selector = selector.replace(/@\\*/g, NG_TRIGGER_SELECTOR).replace(/@\\w+/g, match => NG_TRIGGER_SELECTOR + '-' + match.slice(1)).replace(/:animating/g, NG_ANIMATING_SELECTOR);\n return [selector, hasAmpersand];\n}\nfunction normalizeParams(obj) {\n return obj ? {\n ...obj\n } : null;\n}\nclass AnimationAstBuilderContext {\n errors;\n queryCount = 0;\n depCount = 0;\n currentTransition = null;\n currentQuery = null;\n currentQuerySelector = null;\n currentAnimateTimings = null;\n currentTime = 0;\n collectedStyles = /*#__PURE__*/new Map();\n options = null;\n unsupportedCSSPropertiesFound = /*#__PURE__*/new Set();\n constructor(errors) {\n this.errors = errors;\n }\n}\nfunction consumeOffset(styles) {\n if (typeof styles == 'string') return null;\n let offset = null;\n if (Array.isArray(styles)) {\n styles.forEach(styleTuple => {\n if (styleTuple instanceof Map && styleTuple.has('offset')) {\n const obj = styleTuple;\n offset = parseFloat(obj.get('offset'));\n obj.delete('offset');\n }\n });\n } else if (styles instanceof Map && styles.has('offset')) {\n const obj = styles;\n offset = parseFloat(obj.get('offset'));\n obj.delete('offset');\n }\n return offset;\n}\nfunction constructTimingAst(value, errors) {\n if (value.hasOwnProperty('duration')) {\n return value;\n }\n if (typeof value == 'number') {\n const duration = resolveTiming(value, errors).duration;\n return makeTimingAst(duration, 0, '');\n }\n const strValue = value;\n const isDynamic = strValue.split(/\\s+/).some(v => v.charAt(0) == '{' && v.charAt(1) == '{');\n if (isDynamic) {\n const ast = makeTimingAst(0, 0, '');\n ast.dynamic = true;\n ast.strValue = strValue;\n return ast;\n }\n const timings = resolveTiming(strValue, errors);\n return makeTimingAst(timings.duration, timings.delay, timings.easing);\n}\nfunction normalizeAnimationOptions(options) {\n if (options) {\n options = {\n ...options\n };\n if (options['params']) {\n options['params'] = normalizeParams(options['params']);\n }\n } else {\n options = {};\n }\n return options;\n}\nfunction makeTimingAst(duration, delay, easing) {\n return {\n duration,\n delay,\n easing\n };\n}\nfunction createTimelineInstruction(element, keyframes, preStyleProps, postStyleProps, duration, delay, easing = null, subTimeline = false) {\n return {\n type: 1 /* AnimationTransitionInstructionType.TimelineAnimation */,\n element,\n keyframes,\n preStyleProps,\n postStyleProps,\n duration,\n delay,\n totalTime: duration + delay,\n easing,\n subTimeline\n };\n}\nclass ElementInstructionMap {\n _map = /*#__PURE__*/new Map();\n get(element) {\n return this._map.get(element) || [];\n }\n append(element, instructions) {\n let existingInstructions = this._map.get(element);\n if (!existingInstructions) {\n this._map.set(element, existingInstructions = []);\n }\n existingInstructions.push(...instructions);\n }\n has(element) {\n return this._map.has(element);\n }\n clear() {\n this._map.clear();\n }\n}\nconst ONE_FRAME_IN_MILLISECONDS = 1;\nconst ENTER_TOKEN = ':enter';\nconst ENTER_TOKEN_REGEX = /* @__PURE__ */new RegExp(ENTER_TOKEN, 'g');\nconst LEAVE_TOKEN = ':leave';\nconst LEAVE_TOKEN_REGEX = /* @__PURE__ */new RegExp(LEAVE_TOKEN, 'g');\n/*\n * The code within this file aims to generate web-animations-compatible keyframes from Angular's\n * animation DSL code.\n *\n * The code below will be converted from:\n *\n * ```ts\n * sequence([\n * style({ opacity: 0 }),\n * animate(1000, style({ opacity: 0 }))\n * ])\n * ```\n *\n * To:\n * ```ts\n * keyframes = [{ opacity: 0, offset: 0 }, { opacity: 1, offset: 1 }]\n * duration = 1000\n * delay = 0\n * easing = ''\n * ```\n *\n * For this operation to cover the combination of animation verbs (style, animate, group, etc...) a\n * combination of AST traversal and merge-sort-like algorithms are used.\n *\n * [AST Traversal]\n * Each of the animation verbs, when executed, will return an string-map object representing what\n * type of action it is (style, animate, group, etc...) and the data associated with it. This means\n * that when functional composition mix of these functions is evaluated (like in the example above)\n * then it will end up producing a tree of objects representing the animation itself.\n *\n * When this animation object tree is processed by the visitor code below it will visit each of the\n * verb statements within the visitor. And during each visit it will build the context of the\n * animation keyframes by interacting with the `TimelineBuilder`.\n *\n * [TimelineBuilder]\n * This class is responsible for tracking the styles and building a series of keyframe objects for a\n * timeline between a start and end time. The builder starts off with an initial timeline and each\n * time the AST comes across a `group()`, `keyframes()` or a combination of the two within a\n * `sequence()` then it will generate a sub timeline for each step as well as a new one after\n * they are complete.\n *\n * As the AST is traversed, the timing state on each of the timelines will be incremented. If a sub\n * timeline was created (based on one of the cases above) then the parent timeline will attempt to\n * merge the styles used within the sub timelines into itself (only with group() this will happen).\n * This happens with a merge operation (much like how the merge works in mergeSort) and it will only\n * copy the most recently used styles from the sub timelines into the parent timeline. This ensures\n * that if the styles are used later on in another phase of the animation then they will be the most\n * up-to-date values.\n *\n * [How Missing Styles Are Updated]\n * Each timeline has a `backFill` property which is responsible for filling in new styles into\n * already processed keyframes if a new style shows up later within the animation sequence.\n *\n * ```ts\n * sequence([\n * style({ width: 0 }),\n * animate(1000, style({ width: 100 })),\n * animate(1000, style({ width: 200 })),\n * animate(1000, style({ width: 300 }))\n * animate(1000, style({ width: 400, height: 400 })) // notice how `height` doesn't exist anywhere\n * else\n * ])\n * ```\n *\n * What is happening here is that the `height` value is added later in the sequence, but is missing\n * from all previous animation steps. Therefore when a keyframe is created it would also be missing\n * from all previous keyframes up until where it is first used. For the timeline keyframe generation\n * to properly fill in the style it will place the previous value (the value from the parent\n * timeline) or a default value of `*` into the backFill map.\n *\n * When a sub-timeline is created it will have its own backFill property. This is done so that\n * styles present within the sub-timeline do not accidentally seep into the previous/future timeline\n * keyframes\n *\n * [Validation]\n * The code in this file is not responsible for validation. That functionality happens with within\n * the `AnimationValidatorVisitor` code.\n */\nfunction buildAnimationTimelines(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles = new Map(), finalStyles = new Map(), options, subInstructions, errors = []) {\n return new AnimationTimelineBuilderVisitor().buildKeyframes(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles, finalStyles, options, subInstructions, errors);\n}\nclass AnimationTimelineBuilderVisitor {\n buildKeyframes(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles, finalStyles, options, subInstructions, errors = []) {\n subInstructions = subInstructions || new ElementInstructionMap();\n const context = new AnimationTimelineContext(driver, rootElement, subInstructions, enterClassName, leaveClassName, errors, []);\n context.options = options;\n const delay = options.delay ? resolveTimingValue(options.delay) : 0;\n context.currentTimeline.delayNextStep(delay);\n context.currentTimeline.setStyles([startingStyles], null, context.errors, options);\n visitDslNode(this, ast, context);\n // this checks to see if an actual animation happened\n const timelines = context.timelines.filter(timeline => timeline.containsAnimation());\n // note: we just want to apply the final styles for the rootElement, so we do not\n // just apply the styles to the last timeline but the last timeline which\n // element is the root one (basically `*`-styles are replaced with the actual\n // state style values only for the root element)\n if (timelines.length && finalStyles.size) {\n let lastRootTimeline;\n for (let i = timelines.length - 1; i >= 0; i--) {\n const timeline = timelines[i];\n if (timeline.element === rootElement) {\n lastRootTimeline = timeline;\n break;\n }\n }\n if (lastRootTimeline && !lastRootTimeline.allowOnlyTimelineStyles()) {\n lastRootTimeline.setStyles([finalStyles], null, context.errors, options);\n }\n }\n return timelines.length ? timelines.map(timeline => timeline.buildKeyframes()) : [createTimelineInstruction(rootElement, [], [], [], 0, delay, '', false)];\n }\n visitTrigger(ast, context) {\n // these values are not visited in this AST\n }\n visitState(ast, context) {\n // these values are not visited in this AST\n }\n visitTransition(ast, context) {\n // these values are not visited in this AST\n }\n visitAnimateChild(ast, context) {\n const elementInstructions = context.subInstructions.get(context.element);\n if (elementInstructions) {\n const innerContext = context.createSubContext(ast.options);\n const startTime = context.currentTimeline.currentTime;\n const endTime = this._visitSubInstructions(elementInstructions, innerContext, innerContext.options);\n if (startTime != endTime) {\n // we do this on the upper context because we created a sub context for\n // the sub child animations\n context.transformIntoNewTimeline(endTime);\n }\n }\n context.previousNode = ast;\n }\n visitAnimateRef(ast, context) {\n const innerContext = context.createSubContext(ast.options);\n innerContext.transformIntoNewTimeline();\n this._applyAnimationRefDelays([ast.options, ast.animation.options], context, innerContext);\n this.visitReference(ast.animation, innerContext);\n context.transformIntoNewTimeline(innerContext.currentTimeline.currentTime);\n context.previousNode = ast;\n }\n _applyAnimationRefDelays(animationsRefsOptions, context, innerContext) {\n for (const animationRefOptions of animationsRefsOptions) {\n const animationDelay = animationRefOptions?.delay;\n if (animationDelay) {\n const animationDelayValue = typeof animationDelay === 'number' ? animationDelay : resolveTimingValue(interpolateParams(animationDelay, animationRefOptions?.params ?? {}, context.errors));\n innerContext.delayNextStep(animationDelayValue);\n }\n }\n }\n _visitSubInstructions(instructions, context, options) {\n const startTime = context.currentTimeline.currentTime;\n let furthestTime = startTime;\n // this is a special-case for when a user wants to skip a sub\n // animation from being fired entirely.\n const duration = options.duration != null ? resolveTimingValue(options.duration) : null;\n const delay = options.delay != null ? resolveTimingValue(options.delay) : null;\n if (duration !== 0) {\n instructions.forEach(instruction => {\n const instructionTimings = context.appendInstructionToTimeline(instruction, duration, delay);\n furthestTime = Math.max(furthestTime, instructionTimings.duration + instructionTimings.delay);\n });\n }\n return furthestTime;\n }\n visitReference(ast, context) {\n context.updateOptions(ast.options, true);\n visitDslNode(this, ast.animation, context);\n context.previousNode = ast;\n }\n visitSequence(ast, context) {\n const subContextCount = context.subContextCount;\n let ctx = context;\n const options = ast.options;\n if (options && (options.params || options.delay)) {\n ctx = context.createSubContext(options);\n ctx.transformIntoNewTimeline();\n if (options.delay != null) {\n if (ctx.previousNode.type == AnimationMetadataType.Style) {\n ctx.currentTimeline.snapshotCurrentStyles();\n ctx.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;\n }\n const delay = resolveTimingValue(options.delay);\n ctx.delayNextStep(delay);\n }\n }\n if (ast.steps.length) {\n ast.steps.forEach(s => visitDslNode(this, s, ctx));\n // this is here just in case the inner steps only contain or end with a style() call\n ctx.currentTimeline.applyStylesToKeyframe();\n // this means that some animation function within the sequence\n // ended up creating a sub timeline (which means the current\n // timeline cannot overlap with the contents of the sequence)\n if (ctx.subContextCount > subContextCount) {\n ctx.transformIntoNewTimeline();\n }\n }\n context.previousNode = ast;\n }\n visitGroup(ast, context) {\n const innerTimelines = [];\n let furthestTime = context.currentTimeline.currentTime;\n const delay = ast.options && ast.options.delay ? resolveTimingValue(ast.options.delay) : 0;\n ast.steps.forEach(s => {\n const innerContext = context.createSubContext(ast.options);\n if (delay) {\n innerContext.delayNextStep(delay);\n }\n visitDslNode(this, s, innerContext);\n furthestTime = Math.max(furthestTime, innerContext.currentTimeline.currentTime);\n innerTimelines.push(innerContext.currentTimeline);\n });\n // this operation is run after the AST loop because otherwise\n // if the parent timeline's collected styles were updated then\n // it would pass in invalid data into the new-to-be forked items\n innerTimelines.forEach(timeline => context.currentTimeline.mergeTimelineCollectedStyles(timeline));\n context.transformIntoNewTimeline(furthestTime);\n context.previousNode = ast;\n }\n _visitTiming(ast, context) {\n if (ast.dynamic) {\n const strValue = ast.strValue;\n const timingValue = context.params ? interpolateParams(strValue, context.params, context.errors) : strValue;\n return resolveTiming(timingValue, context.errors);\n } else {\n return {\n duration: ast.duration,\n delay: ast.delay,\n easing: ast.easing\n };\n }\n }\n visitAnimate(ast, context) {\n const timings = context.currentAnimateTimings = this._visitTiming(ast.timings, context);\n const timeline = context.currentTimeline;\n if (timings.delay) {\n context.incrementTime(timings.delay);\n timeline.snapshotCurrentStyles();\n }\n const style = ast.style;\n if (style.type == AnimationMetadataType.Keyframes) {\n this.visitKeyframes(style, context);\n } else {\n context.incrementTime(timings.duration);\n this.visitStyle(style, context);\n timeline.applyStylesToKeyframe();\n }\n context.currentAnimateTimings = null;\n context.previousNode = ast;\n }\n visitStyle(ast, context) {\n const timeline = context.currentTimeline;\n const timings = context.currentAnimateTimings;\n // this is a special case for when a style() call\n // directly follows an animate() call (but not inside of an animate() call)\n if (!timings && timeline.hasCurrentStyleProperties()) {\n timeline.forwardFrame();\n }\n const easing = timings && timings.easing || ast.easing;\n if (ast.isEmptyStep) {\n timeline.applyEmptyStep(easing);\n } else {\n timeline.setStyles(ast.styles, easing, context.errors, context.options);\n }\n context.previousNode = ast;\n }\n visitKeyframes(ast, context) {\n const currentAnimateTimings = context.currentAnimateTimings;\n const startTime = context.currentTimeline.duration;\n const duration = currentAnimateTimings.duration;\n const innerContext = context.createSubContext();\n const innerTimeline = innerContext.currentTimeline;\n innerTimeline.easing = currentAnimateTimings.easing;\n ast.styles.forEach(step => {\n const offset = step.offset || 0;\n innerTimeline.forwardTime(offset * duration);\n innerTimeline.setStyles(step.styles, step.easing, context.errors, context.options);\n innerTimeline.applyStylesToKeyframe();\n });\n // this will ensure that the parent timeline gets all the styles from\n // the child even if the new timeline below is not used\n context.currentTimeline.mergeTimelineCollectedStyles(innerTimeline);\n // we do this because the window between this timeline and the sub timeline\n // should ensure that the styles within are exactly the same as they were before\n context.transformIntoNewTimeline(startTime + duration);\n context.previousNode = ast;\n }\n visitQuery(ast, context) {\n // in the event that the first step before this is a style step we need\n // to ensure the styles are applied before the children are animated\n const startTime = context.currentTimeline.currentTime;\n const options = ast.options || {};\n const delay = options.delay ? resolveTimingValue(options.delay) : 0;\n if (delay && (context.previousNode.type === AnimationMetadataType.Style || startTime == 0 && context.currentTimeline.hasCurrentStyleProperties())) {\n context.currentTimeline.snapshotCurrentStyles();\n context.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;\n }\n let furthestTime = startTime;\n const elms = context.invokeQuery(ast.selector, ast.originalSelector, ast.limit, ast.includeSelf, options.optional ? true : false, context.errors);\n context.currentQueryTotal = elms.length;\n let sameElementTimeline = null;\n elms.forEach((element, i) => {\n context.currentQueryIndex = i;\n const innerContext = context.createSubContext(ast.options, element);\n if (delay) {\n innerContext.delayNextStep(delay);\n }\n if (element === context.element) {\n sameElementTimeline = innerContext.currentTimeline;\n }\n visitDslNode(this, ast.animation, innerContext);\n // this is here just incase the inner steps only contain or end\n // with a style() call (which is here to signal that this is a preparatory\n // call to style an element before it is animated again)\n innerContext.currentTimeline.applyStylesToKeyframe();\n const endTime = innerContext.currentTimeline.currentTime;\n furthestTime = Math.max(furthestTime, endTime);\n });\n context.currentQueryIndex = 0;\n context.currentQueryTotal = 0;\n context.transformIntoNewTimeline(furthestTime);\n if (sameElementTimeline) {\n context.currentTimeline.mergeTimelineCollectedStyles(sameElementTimeline);\n context.currentTimeline.snapshotCurrentStyles();\n }\n context.previousNode = ast;\n }\n visitStagger(ast, context) {\n const parentContext = context.parentContext;\n const tl = context.currentTimeline;\n const timings = ast.timings;\n const duration = Math.abs(timings.duration);\n const maxTime = duration * (context.currentQueryTotal - 1);\n let delay = duration * context.currentQueryIndex;\n let staggerTransformer = timings.duration < 0 ? 'reverse' : timings.easing;\n switch (staggerTransformer) {\n case 'reverse':\n delay = maxTime - delay;\n break;\n case 'full':\n delay = parentContext.currentStaggerTime;\n break;\n }\n const timeline = context.currentTimeline;\n if (delay) {\n timeline.delayNextStep(delay);\n }\n const startingTime = timeline.currentTime;\n visitDslNode(this, ast.animation, context);\n context.previousNode = ast;\n // time = duration + delay\n // the reason why this computation is so complex is because\n // the inner timeline may either have a delay value or a stretched\n // keyframe depending on if a subtimeline is not used or is used.\n parentContext.currentStaggerTime = tl.currentTime - startingTime + (tl.startTime - parentContext.currentTimeline.startTime);\n }\n}\nconst DEFAULT_NOOP_PREVIOUS_NODE = {};\nclass AnimationTimelineContext {\n _driver;\n element;\n subInstructions;\n _enterClassName;\n _leaveClassName;\n errors;\n timelines;\n parentContext = null;\n currentTimeline;\n currentAnimateTimings = null;\n previousNode = DEFAULT_NOOP_PREVIOUS_NODE;\n subContextCount = 0;\n options = {};\n currentQueryIndex = 0;\n currentQueryTotal = 0;\n currentStaggerTime = 0;\n constructor(_driver, element, subInstructions, _enterClassName, _leaveClassName, errors, timelines, initialTimeline) {\n this._driver = _driver;\n this.element = element;\n this.subInstructions = subInstructions;\n this._enterClassName = _enterClassName;\n this._leaveClassName = _leaveClassName;\n this.errors = errors;\n this.timelines = timelines;\n this.currentTimeline = initialTimeline || new TimelineBuilder(this._driver, element, 0);\n timelines.push(this.currentTimeline);\n }\n get params() {\n return this.options.params;\n }\n updateOptions(options, skipIfExists) {\n if (!options) return;\n const newOptions = options;\n let optionsToUpdate = this.options;\n // NOTE: this will get patched up when other animation methods support duration overrides\n if (newOptions.duration != null) {\n optionsToUpdate.duration = resolveTimingValue(newOptions.duration);\n }\n if (newOptions.delay != null) {\n optionsToUpdate.delay = resolveTimingValue(newOptions.delay);\n }\n const newParams = newOptions.params;\n if (newParams) {\n let paramsToUpdate = optionsToUpdate.params;\n if (!paramsToUpdate) {\n paramsToUpdate = this.options.params = {};\n }\n Object.keys(newParams).forEach(name => {\n if (!skipIfExists || !paramsToUpdate.hasOwnProperty(name)) {\n paramsToUpdate[name] = interpolateParams(newParams[name], paramsToUpdate, this.errors);\n }\n });\n }\n }\n _copyOptions() {\n const options = {};\n if (this.options) {\n const oldParams = this.options.params;\n if (oldParams) {\n const params = options['params'] = {};\n Object.keys(oldParams).forEach(name => {\n params[name] = oldParams[name];\n });\n }\n }\n return options;\n }\n createSubContext(options = null, element, newTime) {\n const target = element || this.element;\n const context = new AnimationTimelineContext(this._driver, target, this.subInstructions, this._enterClassName, this._leaveClassName, this.errors, this.timelines, this.currentTimeline.fork(target, newTime || 0));\n context.previousNode = this.previousNode;\n context.currentAnimateTimings = this.currentAnimateTimings;\n context.options = this._copyOptions();\n context.updateOptions(options);\n context.currentQueryIndex = this.currentQueryIndex;\n context.currentQueryTotal = this.currentQueryTotal;\n context.parentContext = this;\n this.subContextCount++;\n return context;\n }\n transformIntoNewTimeline(newTime) {\n this.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;\n this.currentTimeline = this.currentTimeline.fork(this.element, newTime);\n this.timelines.push(this.currentTimeline);\n return this.currentTimeline;\n }\n appendInstructionToTimeline(instruction, duration, delay) {\n const updatedTimings = {\n duration: duration != null ? duration : instruction.duration,\n delay: this.currentTimeline.currentTime + (delay != null ? delay : 0) + instruction.delay,\n easing: ''\n };\n const builder = new SubTimelineBuilder(this._driver, instruction.element, instruction.keyframes, instruction.preStyleProps, instruction.postStyleProps, updatedTimings, instruction.stretchStartingKeyframe);\n this.timelines.push(builder);\n return updatedTimings;\n }\n incrementTime(time) {\n this.currentTimeline.forwardTime(this.currentTimeline.duration + time);\n }\n delayNextStep(delay) {\n // negative delays are not yet supported\n if (delay > 0) {\n this.currentTimeline.delayNextStep(delay);\n }\n }\n invokeQuery(selector, originalSelector, limit, includeSelf, optional, errors) {\n let results = [];\n if (includeSelf) {\n results.push(this.element);\n }\n if (selector.length > 0) {\n // only if :self is used then the selector can be empty\n selector = selector.replace(ENTER_TOKEN_REGEX, '.' + this._enterClassName);\n selector = selector.replace(LEAVE_TOKEN_REGEX, '.' + this._leaveClassName);\n const multi = limit != 1;\n let elements = this._driver.query(this.element, selector, multi);\n if (limit !== 0) {\n elements = limit < 0 ? elements.slice(elements.length + limit, elements.length) : elements.slice(0, limit);\n }\n results.push(...elements);\n }\n if (!optional && results.length == 0) {\n errors.push(invalidQuery(originalSelector));\n }\n return results;\n }\n}\nclass TimelineBuilder {\n _driver;\n element;\n startTime;\n _elementTimelineStylesLookup;\n duration = 0;\n easing = null;\n _previousKeyframe = /*#__PURE__*/new Map();\n _currentKeyframe = /*#__PURE__*/new Map();\n _keyframes = /*#__PURE__*/new Map();\n _styleSummary = /*#__PURE__*/new Map();\n _localTimelineStyles = /*#__PURE__*/new Map();\n _globalTimelineStyles;\n _pendingStyles = /*#__PURE__*/new Map();\n _backFill = /*#__PURE__*/new Map();\n _currentEmptyStepKeyframe = null;\n constructor(_driver, element, startTime, _elementTimelineStylesLookup) {\n this._driver = _driver;\n this.element = element;\n this.startTime = startTime;\n this._elementTimelineStylesLookup = _elementTimelineStylesLookup;\n if (!this._elementTimelineStylesLookup) {\n this._elementTimelineStylesLookup = new Map();\n }\n this._globalTimelineStyles = this._elementTimelineStylesLookup.get(element);\n if (!this._globalTimelineStyles) {\n this._globalTimelineStyles = this._localTimelineStyles;\n this._elementTimelineStylesLookup.set(element, this._localTimelineStyles);\n }\n this._loadKeyframe();\n }\n containsAnimation() {\n switch (this._keyframes.size) {\n case 0:\n return false;\n case 1:\n return this.hasCurrentStyleProperties();\n default:\n return true;\n }\n }\n hasCurrentStyleProperties() {\n return this._currentKeyframe.size > 0;\n }\n get currentTime() {\n return this.startTime + this.duration;\n }\n delayNextStep(delay) {\n // in the event that a style() step is placed right before a stagger()\n // and that style() step is the very first style() value in the animation\n // then we need to make a copy of the keyframe [0, copy, 1] so that the delay\n // properly applies the style() values to work with the stagger...\n const hasPreStyleStep = this._keyframes.size === 1 && this._pendingStyles.size;\n if (this.duration || hasPreStyleStep) {\n this.forwardTime(this.currentTime + delay);\n if (hasPreStyleStep) {\n this.snapshotCurrentStyles();\n }\n } else {\n this.startTime += delay;\n }\n }\n fork(element, currentTime) {\n this.applyStylesToKeyframe();\n return new TimelineBuilder(this._driver, element, currentTime || this.currentTime, this._elementTimelineStylesLookup);\n }\n _loadKeyframe() {\n if (this._currentKeyframe) {\n this._previousKeyframe = this._currentKeyframe;\n }\n this._currentKeyframe = this._keyframes.get(this.duration);\n if (!this._currentKeyframe) {\n this._currentKeyframe = new Map();\n this._keyframes.set(this.duration, this._currentKeyframe);\n }\n }\n forwardFrame() {\n this.duration += ONE_FRAME_IN_MILLISECONDS;\n this._loadKeyframe();\n }\n forwardTime(time) {\n this.applyStylesToKeyframe();\n this.duration = time;\n this._loadKeyframe();\n }\n _updateStyle(prop, value) {\n this._localTimelineStyles.set(prop, value);\n this._globalTimelineStyles.set(prop, value);\n this._styleSummary.set(prop, {\n time: this.currentTime,\n value\n });\n }\n allowOnlyTimelineStyles() {\n return this._currentEmptyStepKeyframe !== this._currentKeyframe;\n }\n applyEmptyStep(easing) {\n if (easing) {\n this._previousKeyframe.set('easing', easing);\n }\n // special case for animate(duration):\n // all missing styles are filled with a `*` value then\n // if any destination styles are filled in later on the same\n // keyframe then they will override the overridden styles\n // We use `_globalTimelineStyles` here because there may be\n // styles in previous keyframes that are not present in this timeline\n for (let [prop, value] of this._globalTimelineStyles) {\n this._backFill.set(prop, value || AUTO_STYLE);\n this._currentKeyframe.set(prop, AUTO_STYLE);\n }\n this._currentEmptyStepKeyframe = this._currentKeyframe;\n }\n setStyles(input, easing, errors, options) {\n if (easing) {\n this._previousKeyframe.set('easing', easing);\n }\n const params = options && options.params || {};\n const styles = flattenStyles(input, this._globalTimelineStyles);\n for (let [prop, value] of styles) {\n const val = interpolateParams(value, params, errors);\n this._pendingStyles.set(prop, val);\n if (!this._localTimelineStyles.has(prop)) {\n this._backFill.set(prop, this._globalTimelineStyles.get(prop) ?? AUTO_STYLE);\n }\n this._updateStyle(prop, val);\n }\n }\n applyStylesToKeyframe() {\n if (this._pendingStyles.size == 0) return;\n this._pendingStyles.forEach((val, prop) => {\n this._currentKeyframe.set(prop, val);\n });\n this._pendingStyles.clear();\n this._localTimelineStyles.forEach((val, prop) => {\n if (!this._currentKeyframe.has(prop)) {\n this._currentKeyframe.set(prop, val);\n }\n });\n }\n snapshotCurrentStyles() {\n for (let [prop, val] of this._localTimelineStyles) {\n this._pendingStyles.set(prop, val);\n this._updateStyle(prop, val);\n }\n }\n getFinalKeyframe() {\n return this._keyframes.get(this.duration);\n }\n get properties() {\n const properties = [];\n for (let prop in this._currentKeyframe) {\n properties.push(prop);\n }\n return properties;\n }\n mergeTimelineCollectedStyles(timeline) {\n timeline._styleSummary.forEach((details1, prop) => {\n const details0 = this._styleSummary.get(prop);\n if (!details0 || details1.time > details0.time) {\n this._updateStyle(prop, details1.value);\n }\n });\n }\n buildKeyframes() {\n this.applyStylesToKeyframe();\n const preStyleProps = new Set();\n const postStyleProps = new Set();\n const isEmpty = this._keyframes.size === 1 && this.duration === 0;\n let finalKeyframes = [];\n this._keyframes.forEach((keyframe, time) => {\n const finalKeyframe = new Map([...this._backFill, ...keyframe]);\n finalKeyframe.forEach((value, prop) => {\n if (value === _PRE_STYLE) {\n preStyleProps.add(prop);\n } else if (value === AUTO_STYLE) {\n postStyleProps.add(prop);\n }\n });\n if (!isEmpty) {\n finalKeyframe.set('offset', time / this.duration);\n }\n finalKeyframes.push(finalKeyframe);\n });\n const preProps = [...preStyleProps.values()];\n const postProps = [...postStyleProps.values()];\n // special case for a 0-second animation (which is designed just to place styles onscreen)\n if (isEmpty) {\n const kf0 = finalKeyframes[0];\n const kf1 = new Map(kf0);\n kf0.set('offset', 0);\n kf1.set('offset', 1);\n finalKeyframes = [kf0, kf1];\n }\n return createTimelineInstruction(this.element, finalKeyframes, preProps, postProps, this.duration, this.startTime, this.easing, false);\n }\n}\nclass SubTimelineBuilder extends TimelineBuilder {\n keyframes;\n preStyleProps;\n postStyleProps;\n _stretchStartingKeyframe;\n timings;\n constructor(driver, element, keyframes, preStyleProps, postStyleProps, timings, _stretchStartingKeyframe = false) {\n super(driver, element, timings.delay);\n this.keyframes = keyframes;\n this.preStyleProps = preStyleProps;\n this.postStyleProps = postStyleProps;\n this._stretchStartingKeyframe = _stretchStartingKeyframe;\n this.timings = {\n duration: timings.duration,\n delay: timings.delay,\n easing: timings.easing\n };\n }\n containsAnimation() {\n return this.keyframes.length > 1;\n }\n buildKeyframes() {\n let keyframes = this.keyframes;\n let {\n delay,\n duration,\n easing\n } = this.timings;\n if (this._stretchStartingKeyframe && delay) {\n const newKeyframes = [];\n const totalTime = duration + delay;\n const startingGap = delay / totalTime;\n // the original starting keyframe now starts once the delay is done\n const newFirstKeyframe = new Map(keyframes[0]);\n newFirstKeyframe.set('offset', 0);\n newKeyframes.push(newFirstKeyframe);\n const oldFirstKeyframe = new Map(keyframes[0]);\n oldFirstKeyframe.set('offset', roundOffset(startingGap));\n newKeyframes.push(oldFirstKeyframe);\n /*\n When the keyframe is stretched then it means that the delay before the animation\n starts is gone. Instead the first keyframe is placed at the start of the animation\n and it is then copied to where it starts when the original delay is over. This basically\n means nothing animates during that delay, but the styles are still rendered. For this\n to work the original offset values that exist in the original keyframes must be \"warped\"\n so that they can take the new keyframe + delay into account.\n delay=1000, duration=1000, keyframes = 0 .5 1\n turns into\n delay=0, duration=2000, keyframes = 0 .33 .66 1\n */\n // offsets between 1 ... n -1 are all warped by the keyframe stretch\n const limit = keyframes.length - 1;\n for (let i = 1; i <= limit; i++) {\n let kf = new Map(keyframes[i]);\n const oldOffset = kf.get('offset');\n const timeAtKeyframe = delay + oldOffset * duration;\n kf.set('offset', roundOffset(timeAtKeyframe / totalTime));\n newKeyframes.push(kf);\n }\n // the new starting keyframe should be added at the start\n duration = totalTime;\n delay = 0;\n easing = '';\n keyframes = newKeyframes;\n }\n return createTimelineInstruction(this.element, keyframes, this.preStyleProps, this.postStyleProps, duration, delay, easing, true);\n }\n}\nfunction roundOffset(offset, decimalPoints = 3) {\n const mult = Math.pow(10, decimalPoints - 1);\n return Math.round(offset * mult) / mult;\n}\nfunction flattenStyles(input, allStyles) {\n const styles = new Map();\n let allProperties;\n input.forEach(token => {\n if (token === '*') {\n allProperties ??= allStyles.keys();\n for (let prop of allProperties) {\n styles.set(prop, AUTO_STYLE);\n }\n } else {\n for (let [prop, val] of token) {\n styles.set(prop, val);\n }\n }\n });\n return styles;\n}\nfunction createTransitionInstruction(element, triggerName, fromState, toState, isRemovalTransition, fromStyles, toStyles, timelines, queriedElements, preStyleProps, postStyleProps, totalTime, errors) {\n return {\n type: 0 /* AnimationTransitionInstructionType.TransitionAnimation */,\n element,\n triggerName,\n isRemovalTransition,\n fromState,\n fromStyles,\n toState,\n toStyles,\n timelines,\n queriedElements,\n preStyleProps,\n postStyleProps,\n totalTime,\n errors\n };\n}\nconst EMPTY_OBJECT = {};\nclass AnimationTransitionFactory {\n _triggerName;\n ast;\n _stateStyles;\n constructor(_triggerName, ast, _stateStyles) {\n this._triggerName = _triggerName;\n this.ast = ast;\n this._stateStyles = _stateStyles;\n }\n match(currentState, nextState, element, params) {\n return oneOrMoreTransitionsMatch(this.ast.matchers, currentState, nextState, element, params);\n }\n buildStyles(stateName, params, errors) {\n let styler = this._stateStyles.get('*');\n if (stateName !== undefined) {\n styler = this._stateStyles.get(stateName?.toString()) || styler;\n }\n return styler ? styler.buildStyles(params, errors) : new Map();\n }\n build(driver, element, currentState, nextState, enterClassName, leaveClassName, currentOptions, nextOptions, subInstructions, skipAstBuild) {\n const errors = [];\n const transitionAnimationParams = this.ast.options && this.ast.options.params || EMPTY_OBJECT;\n const currentAnimationParams = currentOptions && currentOptions.params || EMPTY_OBJECT;\n const currentStateStyles = this.buildStyles(currentState, currentAnimationParams, errors);\n const nextAnimationParams = nextOptions && nextOptions.params || EMPTY_OBJECT;\n const nextStateStyles = this.buildStyles(nextState, nextAnimationParams, errors);\n const queriedElements = new Set();\n const preStyleMap = new Map();\n const postStyleMap = new Map();\n const isRemoval = nextState === 'void';\n const animationOptions = {\n params: applyParamDefaults(nextAnimationParams, transitionAnimationParams),\n delay: this.ast.options?.delay\n };\n const timelines = skipAstBuild ? [] : buildAnimationTimelines(driver, element, this.ast.animation, enterClassName, leaveClassName, currentStateStyles, nextStateStyles, animationOptions, subInstructions, errors);\n let totalTime = 0;\n timelines.forEach(tl => {\n totalTime = Math.max(tl.duration + tl.delay, totalTime);\n });\n if (errors.length) {\n return createTransitionInstruction(element, this._triggerName, currentState, nextState, isRemoval, currentStateStyles, nextStateStyles, [], [], preStyleMap, postStyleMap, totalTime, errors);\n }\n timelines.forEach(tl => {\n const elm = tl.element;\n const preProps = getOrSetDefaultValue(preStyleMap, elm, new Set());\n tl.preStyleProps.forEach(prop => preProps.add(prop));\n const postProps = getOrSetDefaultValue(postStyleMap, elm, new Set());\n tl.postStyleProps.forEach(prop => postProps.add(prop));\n if (elm !== element) {\n queriedElements.add(elm);\n }\n });\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n checkNonAnimatableInTimelines(timelines, this._triggerName, driver);\n }\n return createTransitionInstruction(element, this._triggerName, currentState, nextState, isRemoval, currentStateStyles, nextStateStyles, timelines, [...queriedElements.values()], preStyleMap, postStyleMap, totalTime);\n }\n}\n/**\n * Checks inside a set of timelines if they try to animate a css property which is not considered\n * animatable, in that case it prints a warning on the console.\n * Besides that the function doesn't have any other effect.\n *\n * Note: this check is done here after the timelines are built instead of doing on a lower level so\n * that we can make sure that the warning appears only once per instruction (we can aggregate here\n * all the issues instead of finding them separately).\n *\n * @param timelines The built timelines for the current instruction.\n * @param triggerName The name of the trigger for the current instruction.\n * @param driver Animation driver used to perform the check.\n *\n */\nfunction checkNonAnimatableInTimelines(timelines, triggerName, driver) {\n if (!driver.validateAnimatableStyleProperty) {\n return;\n }\n const allowedNonAnimatableProps = new Set([\n // 'easing' is a utility/synthetic prop we use to represent\n // easing functions, it represents a property of the animation\n // which is not animatable but different values can be used\n // in different steps\n 'easing']);\n const invalidNonAnimatableProps = new Set();\n timelines.forEach(({\n keyframes\n }) => {\n const nonAnimatablePropsInitialValues = new Map();\n keyframes.forEach(keyframe => {\n const entriesToCheck = Array.from(keyframe.entries()).filter(([prop]) => !allowedNonAnimatableProps.has(prop));\n for (const [prop, value] of entriesToCheck) {\n if (!driver.validateAnimatableStyleProperty(prop)) {\n if (nonAnimatablePropsInitialValues.has(prop) && !invalidNonAnimatableProps.has(prop)) {\n const propInitialValue = nonAnimatablePropsInitialValues.get(prop);\n if (propInitialValue !== value) {\n invalidNonAnimatableProps.add(prop);\n }\n } else {\n nonAnimatablePropsInitialValues.set(prop, value);\n }\n }\n }\n });\n });\n if (invalidNonAnimatableProps.size > 0) {\n console.warn(`Warning: The animation trigger \"${triggerName}\" is attempting to animate the following` + ' not animatable properties: ' + Array.from(invalidNonAnimatableProps).join(', ') + '\\n' + '(to check the list of all animatable properties visit https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties)');\n }\n}\nfunction oneOrMoreTransitionsMatch(matchFns, currentState, nextState, element, params) {\n return matchFns.some(fn => fn(currentState, nextState, element, params));\n}\nfunction applyParamDefaults(userParams, defaults) {\n const result = {\n ...defaults\n };\n Object.entries(userParams).forEach(([key, value]) => {\n if (value != null) {\n result[key] = value;\n }\n });\n return result;\n}\nclass AnimationStateStyles {\n styles;\n defaultParams;\n normalizer;\n constructor(styles, defaultParams, normalizer) {\n this.styles = styles;\n this.defaultParams = defaultParams;\n this.normalizer = normalizer;\n }\n buildStyles(params, errors) {\n const finalStyles = new Map();\n const combinedParams = applyParamDefaults(params, this.defaultParams);\n this.styles.styles.forEach(value => {\n if (typeof value !== 'string') {\n value.forEach((val, prop) => {\n if (val) {\n val = interpolateParams(val, combinedParams, errors);\n }\n const normalizedProp = this.normalizer.normalizePropertyName(prop, errors);\n val = this.normalizer.normalizeStyleValue(prop, normalizedProp, val, errors);\n finalStyles.set(prop, val);\n });\n }\n });\n return finalStyles;\n }\n}\nfunction buildTrigger(name, ast, normalizer) {\n return new AnimationTrigger(name, ast, normalizer);\n}\nclass AnimationTrigger {\n name;\n ast;\n _normalizer;\n transitionFactories = [];\n fallbackTransition;\n states = /*#__PURE__*/new Map();\n constructor(name, ast, _normalizer) {\n this.name = name;\n this.ast = ast;\n this._normalizer = _normalizer;\n ast.states.forEach(ast => {\n const defaultParams = ast.options && ast.options.params || {};\n this.states.set(ast.name, new AnimationStateStyles(ast.style, defaultParams, _normalizer));\n });\n balanceProperties(this.states, 'true', '1');\n balanceProperties(this.states, 'false', '0');\n ast.transitions.forEach(ast => {\n this.transitionFactories.push(new AnimationTransitionFactory(name, ast, this.states));\n });\n this.fallbackTransition = createFallbackTransition(name, this.states);\n }\n get containsQueries() {\n return this.ast.queryCount > 0;\n }\n matchTransition(currentState, nextState, element, params) {\n const entry = this.transitionFactories.find(f => f.match(currentState, nextState, element, params));\n return entry || null;\n }\n matchStyles(currentState, params, errors) {\n return this.fallbackTransition.buildStyles(currentState, params, errors);\n }\n}\nfunction createFallbackTransition(triggerName, states, normalizer) {\n const matchers = [(fromState, toState) => true];\n const animation = {\n type: AnimationMetadataType.Sequence,\n steps: [],\n options: null\n };\n const transition = {\n type: AnimationMetadataType.Transition,\n animation,\n matchers,\n options: null,\n queryCount: 0,\n depCount: 0\n };\n return new AnimationTransitionFactory(triggerName, transition, states);\n}\nfunction balanceProperties(stateMap, key1, key2) {\n if (stateMap.has(key1)) {\n if (!stateMap.has(key2)) {\n stateMap.set(key2, stateMap.get(key1));\n }\n } else if (stateMap.has(key2)) {\n stateMap.set(key1, stateMap.get(key2));\n }\n}\nconst EMPTY_INSTRUCTION_MAP = /*#__PURE__*/new ElementInstructionMap();\nclass TimelineAnimationEngine {\n bodyNode;\n _driver;\n _normalizer;\n _animations = /*#__PURE__*/new Map();\n _playersById = /*#__PURE__*/new Map();\n players = [];\n constructor(bodyNode, _driver, _normalizer) {\n this.bodyNode = bodyNode;\n this._driver = _driver;\n this._normalizer = _normalizer;\n }\n register(id, metadata) {\n const errors = [];\n const warnings = [];\n const ast = buildAnimationAst(this._driver, metadata, errors, warnings);\n if (errors.length) {\n throw registerFailed(errors);\n } else {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n if (warnings.length) {\n warnRegister(warnings);\n }\n }\n this._animations.set(id, ast);\n }\n }\n _buildPlayer(i, preStyles, postStyles) {\n const element = i.element;\n const keyframes = normalizeKeyframes(this._normalizer, i.keyframes, preStyles, postStyles);\n return this._driver.animate(element, keyframes, i.duration, i.delay, i.easing, [], true);\n }\n create(id, element, options = {}) {\n const errors = [];\n const ast = this._animations.get(id);\n let instructions;\n const autoStylesMap = new Map();\n if (ast) {\n instructions = buildAnimationTimelines(this._driver, element, ast, ENTER_CLASSNAME, LEAVE_CLASSNAME, new Map(), new Map(), options, EMPTY_INSTRUCTION_MAP, errors);\n instructions.forEach(inst => {\n const styles = getOrSetDefaultValue(autoStylesMap, inst.element, new Map());\n inst.postStyleProps.forEach(prop => styles.set(prop, null));\n });\n } else {\n errors.push(missingOrDestroyedAnimation());\n instructions = [];\n }\n if (errors.length) {\n throw createAnimationFailed(errors);\n }\n autoStylesMap.forEach((styles, element) => {\n styles.forEach((_, prop) => {\n styles.set(prop, this._driver.computeStyle(element, prop, AUTO_STYLE));\n });\n });\n const players = instructions.map(i => {\n const styles = autoStylesMap.get(i.element);\n return this._buildPlayer(i, new Map(), styles);\n });\n const player = optimizeGroupPlayer(players);\n this._playersById.set(id, player);\n player.onDestroy(() => this.destroy(id));\n this.players.push(player);\n return player;\n }\n destroy(id) {\n const player = this._getPlayer(id);\n player.destroy();\n this._playersById.delete(id);\n const index = this.players.indexOf(player);\n if (index >= 0) {\n this.players.splice(index, 1);\n }\n }\n _getPlayer(id) {\n const player = this._playersById.get(id);\n if (!player) {\n throw missingPlayer(id);\n }\n return player;\n }\n listen(id, element, eventName, callback) {\n // triggerName, fromState, toState are all ignored for timeline animations\n const baseEvent = makeAnimationEvent(element, '', '', '');\n listenOnPlayer(this._getPlayer(id), eventName, baseEvent, callback);\n return () => {};\n }\n command(id, element, command, args) {\n if (command == 'register') {\n this.register(id, args[0]);\n return;\n }\n if (command == 'create') {\n const options = args[0] || {};\n this.create(id, element, options);\n return;\n }\n const player = this._getPlayer(id);\n switch (command) {\n case 'play':\n player.play();\n break;\n case 'pause':\n player.pause();\n break;\n case 'reset':\n player.reset();\n break;\n case 'restart':\n player.restart();\n break;\n case 'finish':\n player.finish();\n break;\n case 'init':\n player.init();\n break;\n case 'setPosition':\n player.setPosition(parseFloat(args[0]));\n break;\n case 'destroy':\n this.destroy(id);\n break;\n }\n }\n}\nconst QUEUED_CLASSNAME = 'ng-animate-queued';\nconst QUEUED_SELECTOR = '.ng-animate-queued';\nconst DISABLED_CLASSNAME = 'ng-animate-disabled';\nconst DISABLED_SELECTOR = '.ng-animate-disabled';\nconst STAR_CLASSNAME = 'ng-star-inserted';\nconst STAR_SELECTOR = '.ng-star-inserted';\nconst EMPTY_PLAYER_ARRAY = [];\nconst NULL_REMOVAL_STATE = {\n namespaceId: '',\n setForRemoval: false,\n setForMove: false,\n hasAnimation: false,\n removedBeforeQueried: false\n};\nconst NULL_REMOVED_QUERIED_STATE = {\n namespaceId: '',\n setForMove: false,\n setForRemoval: false,\n hasAnimation: false,\n removedBeforeQueried: true\n};\nconst REMOVAL_FLAG = '__ng_removed';\nclass StateValue {\n namespaceId;\n value;\n options;\n get params() {\n return this.options.params;\n }\n constructor(input, namespaceId = '') {\n this.namespaceId = namespaceId;\n const isObj = input && input.hasOwnProperty('value');\n const value = isObj ? input['value'] : input;\n this.value = normalizeTriggerValue(value);\n if (isObj) {\n // we drop the value property from options.\n const {\n value,\n ...options\n } = input;\n this.options = options;\n } else {\n this.options = {};\n }\n if (!this.options.params) {\n this.options.params = {};\n }\n }\n absorbOptions(options) {\n const newParams = options.params;\n if (newParams) {\n const oldParams = this.options.params;\n Object.keys(newParams).forEach(prop => {\n if (oldParams[prop] == null) {\n oldParams[prop] = newParams[prop];\n }\n });\n }\n }\n}\nconst VOID_VALUE = 'void';\nconst DEFAULT_STATE_VALUE = /*#__PURE__*/new StateValue(VOID_VALUE);\nclass AnimationTransitionNamespace {\n id;\n hostElement;\n _engine;\n players = [];\n _triggers = /*#__PURE__*/new Map();\n _queue = [];\n _elementListeners = /*#__PURE__*/new Map();\n _hostClassName;\n constructor(id, hostElement, _engine) {\n this.id = id;\n this.hostElement = hostElement;\n this._engine = _engine;\n this._hostClassName = 'ng-tns-' + id;\n addClass(hostElement, this._hostClassName);\n }\n listen(element, name, phase, callback) {\n if (!this._triggers.has(name)) {\n throw missingTrigger(phase, name);\n }\n if (phase == null || phase.length == 0) {\n throw missingEvent(name);\n }\n if (!isTriggerEventValid(phase)) {\n throw unsupportedTriggerEvent(phase, name);\n }\n const listeners = getOrSetDefaultValue(this._elementListeners, element, []);\n const data = {\n name,\n phase,\n callback\n };\n listeners.push(data);\n const triggersWithStates = getOrSetDefaultValue(this._engine.statesByElement, element, new Map());\n if (!triggersWithStates.has(name)) {\n addClass(element, NG_TRIGGER_CLASSNAME);\n addClass(element, NG_TRIGGER_CLASSNAME + '-' + name);\n triggersWithStates.set(name, DEFAULT_STATE_VALUE);\n }\n return () => {\n // the event listener is removed AFTER the flush has occurred such\n // that leave animations callbacks can fire (otherwise if the node\n // is removed in between then the listeners would be deregistered)\n this._engine.afterFlush(() => {\n const index = listeners.indexOf(data);\n if (index >= 0) {\n listeners.splice(index, 1);\n }\n if (!this._triggers.has(name)) {\n triggersWithStates.delete(name);\n }\n });\n };\n }\n register(name, ast) {\n if (this._triggers.has(name)) {\n // throw\n return false;\n } else {\n this._triggers.set(name, ast);\n return true;\n }\n }\n _getTrigger(name) {\n const trigger = this._triggers.get(name);\n if (!trigger) {\n throw unregisteredTrigger(name);\n }\n return trigger;\n }\n trigger(element, triggerName, value, defaultToFallback = true) {\n const trigger = this._getTrigger(triggerName);\n const player = new TransitionAnimationPlayer(this.id, triggerName, element);\n let triggersWithStates = this._engine.statesByElement.get(element);\n if (!triggersWithStates) {\n addClass(element, NG_TRIGGER_CLASSNAME);\n addClass(element, NG_TRIGGER_CLASSNAME + '-' + triggerName);\n this._engine.statesByElement.set(element, triggersWithStates = new Map());\n }\n let fromState = triggersWithStates.get(triggerName);\n const toState = new StateValue(value, this.id);\n const isObj = value && value.hasOwnProperty('value');\n if (!isObj && fromState) {\n toState.absorbOptions(fromState.options);\n }\n triggersWithStates.set(triggerName, toState);\n if (!fromState) {\n fromState = DEFAULT_STATE_VALUE;\n }\n const isRemoval = toState.value === VOID_VALUE;\n // normally this isn't reached by here, however, if an object expression\n // is passed in then it may be a new object each time. Comparing the value\n // is important since that will stay the same despite there being a new object.\n // The removal arc here is special cased because the same element is triggered\n // twice in the event that it contains animations on the outer/inner portions\n // of the host container\n if (!isRemoval && fromState.value === toState.value) {\n // this means that despite the value not changing, some inner params\n // have changed which means that the animation final styles need to be applied\n if (!objEquals(fromState.params, toState.params)) {\n const errors = [];\n const fromStyles = trigger.matchStyles(fromState.value, fromState.params, errors);\n const toStyles = trigger.matchStyles(toState.value, toState.params, errors);\n if (errors.length) {\n this._engine.reportError(errors);\n } else {\n this._engine.afterFlush(() => {\n eraseStyles(element, fromStyles);\n setStyles(element, toStyles);\n });\n }\n }\n return;\n }\n const playersOnElement = getOrSetDefaultValue(this._engine.playersByElement, element, []);\n playersOnElement.forEach(player => {\n // only remove the player if it is queued on the EXACT same trigger/namespace\n // we only also deal with queued players here because if the animation has\n // started then we want to keep the player alive until the flush happens\n // (which is where the previousPlayers are passed into the new player)\n if (player.namespaceId == this.id && player.triggerName == triggerName && player.queued) {\n player.destroy();\n }\n });\n let transition = trigger.matchTransition(fromState.value, toState.value, element, toState.params);\n let isFallbackTransition = false;\n if (!transition) {\n if (!defaultToFallback) return;\n transition = trigger.fallbackTransition;\n isFallbackTransition = true;\n }\n this._engine.totalQueuedPlayers++;\n this._queue.push({\n element,\n triggerName,\n transition,\n fromState,\n toState,\n player,\n isFallbackTransition\n });\n if (!isFallbackTransition) {\n addClass(element, QUEUED_CLASSNAME);\n player.onStart(() => {\n removeClass(element, QUEUED_CLASSNAME);\n });\n }\n player.onDone(() => {\n let index = this.players.indexOf(player);\n if (index >= 0) {\n this.players.splice(index, 1);\n }\n const players = this._engine.playersByElement.get(element);\n if (players) {\n let index = players.indexOf(player);\n if (index >= 0) {\n players.splice(index, 1);\n }\n }\n });\n this.players.push(player);\n playersOnElement.push(player);\n return player;\n }\n deregister(name) {\n this._triggers.delete(name);\n this._engine.statesByElement.forEach(stateMap => stateMap.delete(name));\n this._elementListeners.forEach((listeners, element) => {\n this._elementListeners.set(element, listeners.filter(entry => {\n return entry.name != name;\n }));\n });\n }\n clearElementCache(element) {\n this._engine.statesByElement.delete(element);\n this._elementListeners.delete(element);\n const elementPlayers = this._engine.playersByElement.get(element);\n if (elementPlayers) {\n elementPlayers.forEach(player => player.destroy());\n this._engine.playersByElement.delete(element);\n }\n }\n _signalRemovalForInnerTriggers(rootElement, context) {\n const elements = this._engine.driver.query(rootElement, NG_TRIGGER_SELECTOR, true);\n // emulate a leave animation for all inner nodes within this node.\n // If there are no animations found for any of the nodes then clear the cache\n // for the element.\n elements.forEach(elm => {\n // this means that an inner remove() operation has already kicked off\n // the animation on this element...\n if (elm[REMOVAL_FLAG]) return;\n const namespaces = this._engine.fetchNamespacesByElement(elm);\n if (namespaces.size) {\n namespaces.forEach(ns => ns.triggerLeaveAnimation(elm, context, false, true));\n } else {\n this.clearElementCache(elm);\n }\n });\n // If the child elements were removed along with the parent, their animations might not\n // have completed. Clear all the elements from the cache so we don't end up with a memory leak.\n this._engine.afterFlushAnimationsDone(() => elements.forEach(elm => this.clearElementCache(elm)));\n }\n triggerLeaveAnimation(element, context, destroyAfterComplete, defaultToFallback) {\n const triggerStates = this._engine.statesByElement.get(element);\n const previousTriggersValues = new Map();\n if (triggerStates) {\n const players = [];\n triggerStates.forEach((state, triggerName) => {\n previousTriggersValues.set(triggerName, state.value);\n // this check is here in the event that an element is removed\n // twice (both on the host level and the component level)\n if (this._triggers.has(triggerName)) {\n const player = this.trigger(element, triggerName, VOID_VALUE, defaultToFallback);\n if (player) {\n players.push(player);\n }\n }\n });\n if (players.length) {\n this._engine.markElementAsRemoved(this.id, element, true, context, previousTriggersValues);\n if (destroyAfterComplete) {\n optimizeGroupPlayer(players).onDone(() => this._engine.processLeaveNode(element));\n }\n return true;\n }\n }\n return false;\n }\n prepareLeaveAnimationListeners(element) {\n const listeners = this._elementListeners.get(element);\n const elementStates = this._engine.statesByElement.get(element);\n // if this statement fails then it means that the element was picked up\n // by an earlier flush (or there are no listeners at all to track the leave).\n if (listeners && elementStates) {\n const visitedTriggers = new Set();\n listeners.forEach(listener => {\n const triggerName = listener.name;\n if (visitedTriggers.has(triggerName)) return;\n visitedTriggers.add(triggerName);\n const trigger = this._triggers.get(triggerName);\n const transition = trigger.fallbackTransition;\n const fromState = elementStates.get(triggerName) || DEFAULT_STATE_VALUE;\n const toState = new StateValue(VOID_VALUE);\n const player = new TransitionAnimationPlayer(this.id, triggerName, element);\n this._engine.totalQueuedPlayers++;\n this._queue.push({\n element,\n triggerName,\n transition,\n fromState,\n toState,\n player,\n isFallbackTransition: true\n });\n });\n }\n }\n removeNode(element, context) {\n const engine = this._engine;\n if (element.childElementCount) {\n this._signalRemovalForInnerTriggers(element, context);\n }\n // this means that a * => VOID animation was detected and kicked off\n if (this.triggerLeaveAnimation(element, context, true)) return;\n // find the player that is animating and make sure that the\n // removal is delayed until that player has completed\n let containsPotentialParentTransition = false;\n if (engine.totalAnimations) {\n const currentPlayers = engine.players.length ? engine.playersByQueriedElement.get(element) : [];\n // when this `if statement` does not continue forward it means that\n // a previous animation query has selected the current element and\n // is animating it. In this situation want to continue forwards and\n // allow the element to be queued up for animation later.\n if (currentPlayers && currentPlayers.length) {\n containsPotentialParentTransition = true;\n } else {\n let parent = element;\n while (parent = parent.parentNode) {\n const triggers = engine.statesByElement.get(parent);\n if (triggers) {\n containsPotentialParentTransition = true;\n break;\n }\n }\n }\n }\n // at this stage we know that the element will either get removed\n // during flush or will be picked up by a parent query. Either way\n // we need to fire the listeners for this element when it DOES get\n // removed (once the query parent animation is done or after flush)\n this.prepareLeaveAnimationListeners(element);\n // whether or not a parent has an animation we need to delay the deferral of the leave\n // operation until we have more information (which we do after flush() has been called)\n if (containsPotentialParentTransition) {\n engine.markElementAsRemoved(this.id, element, false, context);\n } else {\n const removalFlag = element[REMOVAL_FLAG];\n if (!removalFlag || removalFlag === NULL_REMOVAL_STATE) {\n // we do this after the flush has occurred such\n // that the callbacks can be fired\n engine.afterFlush(() => this.clearElementCache(element));\n engine.destroyInnerAnimations(element);\n engine._onRemovalComplete(element, context);\n }\n }\n }\n insertNode(element, parent) {\n addClass(element, this._hostClassName);\n }\n drainQueuedTransitions(microtaskId) {\n const instructions = [];\n this._queue.forEach(entry => {\n const player = entry.player;\n if (player.destroyed) return;\n const element = entry.element;\n const listeners = this._elementListeners.get(element);\n if (listeners) {\n listeners.forEach(listener => {\n if (listener.name == entry.triggerName) {\n const baseEvent = makeAnimationEvent(element, entry.triggerName, entry.fromState.value, entry.toState.value);\n baseEvent['_data'] = microtaskId;\n listenOnPlayer(entry.player, listener.phase, baseEvent, listener.callback);\n }\n });\n }\n if (player.markedForDestroy) {\n this._engine.afterFlush(() => {\n // now we can destroy the element properly since the event listeners have\n // been bound to the player\n player.destroy();\n });\n } else {\n instructions.push(entry);\n }\n });\n this._queue = [];\n return instructions.sort((a, b) => {\n // if depCount == 0 them move to front\n // otherwise if a contains b then move back\n const d0 = a.transition.ast.depCount;\n const d1 = b.transition.ast.depCount;\n if (d0 == 0 || d1 == 0) {\n return d0 - d1;\n }\n return this._engine.driver.containsElement(a.element, b.element) ? 1 : -1;\n });\n }\n destroy(context) {\n this.players.forEach(p => p.destroy());\n this._signalRemovalForInnerTriggers(this.hostElement, context);\n }\n}\nclass TransitionAnimationEngine {\n bodyNode;\n driver;\n _normalizer;\n players = [];\n newHostElements = /*#__PURE__*/new Map();\n playersByElement = /*#__PURE__*/new Map();\n playersByQueriedElement = /*#__PURE__*/new Map();\n statesByElement = /*#__PURE__*/new Map();\n disabledNodes = /*#__PURE__*/new Set();\n totalAnimations = 0;\n totalQueuedPlayers = 0;\n _namespaceLookup = {};\n _namespaceList = [];\n _flushFns = [];\n _whenQuietFns = [];\n namespacesByHostElement = /*#__PURE__*/new Map();\n collectedEnterElements = [];\n collectedLeaveElements = [];\n // this method is designed to be overridden by the code that uses this engine\n onRemovalComplete = (element, context) => {};\n /** @internal */\n _onRemovalComplete(element, context) {\n this.onRemovalComplete(element, context);\n }\n constructor(bodyNode, driver, _normalizer) {\n this.bodyNode = bodyNode;\n this.driver = driver;\n this._normalizer = _normalizer;\n }\n get queuedPlayers() {\n const players = [];\n this._namespaceList.forEach(ns => {\n ns.players.forEach(player => {\n if (player.queued) {\n players.push(player);\n }\n });\n });\n return players;\n }\n createNamespace(namespaceId, hostElement) {\n const ns = new AnimationTransitionNamespace(namespaceId, hostElement, this);\n if (this.bodyNode && this.driver.containsElement(this.bodyNode, hostElement)) {\n this._balanceNamespaceList(ns, hostElement);\n } else {\n // defer this later until flush during when the host element has\n // been inserted so that we know exactly where to place it in\n // the namespace list\n this.newHostElements.set(hostElement, ns);\n // given that this host element is a part of the animation code, it\n // may or may not be inserted by a parent node that is of an\n // animation renderer type. If this happens then we can still have\n // access to this item when we query for :enter nodes. If the parent\n // is a renderer then the set data-structure will normalize the entry\n this.collectEnterElement(hostElement);\n }\n return this._namespaceLookup[namespaceId] = ns;\n }\n _balanceNamespaceList(ns, hostElement) {\n const namespaceList = this._namespaceList;\n const namespacesByHostElement = this.namespacesByHostElement;\n const limit = namespaceList.length - 1;\n if (limit >= 0) {\n let found = false;\n // Find the closest ancestor with an existing namespace so we can then insert `ns` after it,\n // establishing a top-down ordering of namespaces in `this._namespaceList`.\n let ancestor = this.driver.getParentElement(hostElement);\n while (ancestor) {\n const ancestorNs = namespacesByHostElement.get(ancestor);\n if (ancestorNs) {\n // An animation namespace has been registered for this ancestor, so we insert `ns`\n // right after it to establish top-down ordering of animation namespaces.\n const index = namespaceList.indexOf(ancestorNs);\n namespaceList.splice(index + 1, 0, ns);\n found = true;\n break;\n }\n ancestor = this.driver.getParentElement(ancestor);\n }\n if (!found) {\n // No namespace exists that is an ancestor of `ns`, so `ns` is inserted at the front to\n // ensure that any existing descendants are ordered after `ns`, retaining the desired\n // top-down ordering.\n namespaceList.unshift(ns);\n }\n } else {\n namespaceList.push(ns);\n }\n namespacesByHostElement.set(hostElement, ns);\n return ns;\n }\n register(namespaceId, hostElement) {\n let ns = this._namespaceLookup[namespaceId];\n if (!ns) {\n ns = this.createNamespace(namespaceId, hostElement);\n }\n return ns;\n }\n registerTrigger(namespaceId, name, trigger) {\n let ns = this._namespaceLookup[namespaceId];\n if (ns && ns.register(name, trigger)) {\n this.totalAnimations++;\n }\n }\n destroy(namespaceId, context) {\n if (!namespaceId) return;\n this.afterFlush(() => {});\n this.afterFlushAnimationsDone(() => {\n const ns = this._fetchNamespace(namespaceId);\n this.namespacesByHostElement.delete(ns.hostElement);\n const index = this._namespaceList.indexOf(ns);\n if (index >= 0) {\n this._namespaceList.splice(index, 1);\n }\n ns.destroy(context);\n delete this._namespaceLookup[namespaceId];\n });\n }\n _fetchNamespace(id) {\n return this._namespaceLookup[id];\n }\n fetchNamespacesByElement(element) {\n // normally there should only be one namespace per element, however\n // if @triggers are placed on both the component element and then\n // its host element (within the component code) then there will be\n // two namespaces returned. We use a set here to simply deduplicate\n // the namespaces in case (for the reason described above) there are multiple triggers\n const namespaces = new Set();\n const elementStates = this.statesByElement.get(element);\n if (elementStates) {\n for (let stateValue of elementStates.values()) {\n if (stateValue.namespaceId) {\n const ns = this._fetchNamespace(stateValue.namespaceId);\n if (ns) {\n namespaces.add(ns);\n }\n }\n }\n }\n return namespaces;\n }\n trigger(namespaceId, element, name, value) {\n if (isElementNode(element)) {\n const ns = this._fetchNamespace(namespaceId);\n if (ns) {\n ns.trigger(element, name, value);\n return true;\n }\n }\n return false;\n }\n insertNode(namespaceId, element, parent, insertBefore) {\n if (!isElementNode(element)) return;\n // special case for when an element is removed and reinserted (move operation)\n // when this occurs we do not want to use the element for deletion later\n const details = element[REMOVAL_FLAG];\n if (details && details.setForRemoval) {\n details.setForRemoval = false;\n details.setForMove = true;\n const index = this.collectedLeaveElements.indexOf(element);\n if (index >= 0) {\n this.collectedLeaveElements.splice(index, 1);\n }\n }\n // in the event that the namespaceId is blank then the caller\n // code does not contain any animation code in it, but it is\n // just being called so that the node is marked as being inserted\n if (namespaceId) {\n const ns = this._fetchNamespace(namespaceId);\n // This if-statement is a workaround for router issue #21947.\n // The router sometimes hits a race condition where while a route\n // is being instantiated a new navigation arrives, triggering leave\n // animation of DOM that has not been fully initialized, until this\n // is resolved, we need to handle the scenario when DOM is not in a\n // consistent state during the animation.\n if (ns) {\n ns.insertNode(element, parent);\n }\n }\n // only *directives and host elements are inserted before\n if (insertBefore) {\n this.collectEnterElement(element);\n }\n }\n collectEnterElement(element) {\n this.collectedEnterElements.push(element);\n }\n markElementAsDisabled(element, value) {\n if (value) {\n if (!this.disabledNodes.has(element)) {\n this.disabledNodes.add(element);\n addClass(element, DISABLED_CLASSNAME);\n }\n } else if (this.disabledNodes.has(element)) {\n this.disabledNodes.delete(element);\n removeClass(element, DISABLED_CLASSNAME);\n }\n }\n removeNode(namespaceId, element, context) {\n if (isElementNode(element)) {\n const ns = namespaceId ? this._fetchNamespace(namespaceId) : null;\n if (ns) {\n ns.removeNode(element, context);\n } else {\n this.markElementAsRemoved(namespaceId, element, false, context);\n }\n const hostNS = this.namespacesByHostElement.get(element);\n if (hostNS && hostNS.id !== namespaceId) {\n hostNS.removeNode(element, context);\n }\n } else {\n this._onRemovalComplete(element, context);\n }\n }\n markElementAsRemoved(namespaceId, element, hasAnimation, context, previousTriggersValues) {\n this.collectedLeaveElements.push(element);\n element[REMOVAL_FLAG] = {\n namespaceId,\n setForRemoval: context,\n hasAnimation,\n removedBeforeQueried: false,\n previousTriggersValues\n };\n }\n listen(namespaceId, element, name, phase, callback) {\n if (isElementNode(element)) {\n return this._fetchNamespace(namespaceId).listen(element, name, phase, callback);\n }\n return () => {};\n }\n _buildInstruction(entry, subTimelines, enterClassName, leaveClassName, skipBuildAst) {\n return entry.transition.build(this.driver, entry.element, entry.fromState.value, entry.toState.value, enterClassName, leaveClassName, entry.fromState.options, entry.toState.options, subTimelines, skipBuildAst);\n }\n destroyInnerAnimations(containerElement) {\n let elements = this.driver.query(containerElement, NG_TRIGGER_SELECTOR, true);\n elements.forEach(element => this.destroyActiveAnimationsForElement(element));\n if (this.playersByQueriedElement.size == 0) return;\n elements = this.driver.query(containerElement, NG_ANIMATING_SELECTOR, true);\n elements.forEach(element => this.finishActiveQueriedAnimationOnElement(element));\n }\n destroyActiveAnimationsForElement(element) {\n const players = this.playersByElement.get(element);\n if (players) {\n players.forEach(player => {\n // special case for when an element is set for destruction, but hasn't started.\n // in this situation we want to delay the destruction until the flush occurs\n // so that any event listeners attached to the player are triggered.\n if (player.queued) {\n player.markedForDestroy = true;\n } else {\n player.destroy();\n }\n });\n }\n }\n finishActiveQueriedAnimationOnElement(element) {\n const players = this.playersByQueriedElement.get(element);\n if (players) {\n players.forEach(player => player.finish());\n }\n }\n whenRenderingDone() {\n return new Promise(resolve => {\n if (this.players.length) {\n return optimizeGroupPlayer(this.players).onDone(() => resolve());\n } else {\n resolve();\n }\n });\n }\n processLeaveNode(element) {\n const details = element[REMOVAL_FLAG];\n if (details && details.setForRemoval) {\n // this will prevent it from removing it twice\n element[REMOVAL_FLAG] = NULL_REMOVAL_STATE;\n if (details.namespaceId) {\n this.destroyInnerAnimations(element);\n const ns = this._fetchNamespace(details.namespaceId);\n if (ns) {\n ns.clearElementCache(element);\n }\n }\n this._onRemovalComplete(element, details.setForRemoval);\n }\n if (element.classList?.contains(DISABLED_CLASSNAME)) {\n this.markElementAsDisabled(element, false);\n }\n this.driver.query(element, DISABLED_SELECTOR, true).forEach(node => {\n this.markElementAsDisabled(node, false);\n });\n }\n flush(microtaskId = -1) {\n let players = [];\n if (this.newHostElements.size) {\n this.newHostElements.forEach((ns, element) => this._balanceNamespaceList(ns, element));\n this.newHostElements.clear();\n }\n if (this.totalAnimations && this.collectedEnterElements.length) {\n for (let i = 0; i < this.collectedEnterElements.length; i++) {\n const elm = this.collectedEnterElements[i];\n addClass(elm, STAR_CLASSNAME);\n }\n }\n if (this._namespaceList.length && (this.totalQueuedPlayers || this.collectedLeaveElements.length)) {\n const cleanupFns = [];\n try {\n players = this._flushAnimations(cleanupFns, microtaskId);\n } finally {\n for (let i = 0; i < cleanupFns.length; i++) {\n cleanupFns[i]();\n }\n }\n } else {\n for (let i = 0; i < this.collectedLeaveElements.length; i++) {\n const element = this.collectedLeaveElements[i];\n this.processLeaveNode(element);\n }\n }\n this.totalQueuedPlayers = 0;\n this.collectedEnterElements.length = 0;\n this.collectedLeaveElements.length = 0;\n this._flushFns.forEach(fn => fn());\n this._flushFns = [];\n if (this._whenQuietFns.length) {\n // we move these over to a variable so that\n // if any new callbacks are registered in another\n // flush they do not populate the existing set\n const quietFns = this._whenQuietFns;\n this._whenQuietFns = [];\n if (players.length) {\n optimizeGroupPlayer(players).onDone(() => {\n quietFns.forEach(fn => fn());\n });\n } else {\n quietFns.forEach(fn => fn());\n }\n }\n }\n reportError(errors) {\n throw triggerTransitionsFailed(errors);\n }\n _flushAnimations(cleanupFns, microtaskId) {\n const subTimelines = new ElementInstructionMap();\n const skippedPlayers = [];\n const skippedPlayersMap = new Map();\n const queuedInstructions = [];\n const queriedElements = new Map();\n const allPreStyleElements = new Map();\n const allPostStyleElements = new Map();\n const disabledElementsSet = new Set();\n this.disabledNodes.forEach(node => {\n disabledElementsSet.add(node);\n const nodesThatAreDisabled = this.driver.query(node, QUEUED_SELECTOR, true);\n for (let i = 0; i < nodesThatAreDisabled.length; i++) {\n disabledElementsSet.add(nodesThatAreDisabled[i]);\n }\n });\n const bodyNode = this.bodyNode;\n const allTriggerElements = Array.from(this.statesByElement.keys());\n const enterNodeMap = buildRootMap(allTriggerElements, this.collectedEnterElements);\n // this must occur before the instructions are built below such that\n // the :enter queries match the elements (since the timeline queries\n // are fired during instruction building).\n const enterNodeMapIds = new Map();\n let i = 0;\n enterNodeMap.forEach((nodes, root) => {\n const className = ENTER_CLASSNAME + i++;\n enterNodeMapIds.set(root, className);\n nodes.forEach(node => addClass(node, className));\n });\n const allLeaveNodes = [];\n const mergedLeaveNodes = new Set();\n const leaveNodesWithoutAnimations = new Set();\n for (let i = 0; i < this.collectedLeaveElements.length; i++) {\n const element = this.collectedLeaveElements[i];\n const details = element[REMOVAL_FLAG];\n if (details && details.setForRemoval) {\n allLeaveNodes.push(element);\n mergedLeaveNodes.add(element);\n if (details.hasAnimation) {\n this.driver.query(element, STAR_SELECTOR, true).forEach(elm => mergedLeaveNodes.add(elm));\n } else {\n leaveNodesWithoutAnimations.add(element);\n }\n }\n }\n const leaveNodeMapIds = new Map();\n const leaveNodeMap = buildRootMap(allTriggerElements, Array.from(mergedLeaveNodes));\n leaveNodeMap.forEach((nodes, root) => {\n const className = LEAVE_CLASSNAME + i++;\n leaveNodeMapIds.set(root, className);\n nodes.forEach(node => addClass(node, className));\n });\n cleanupFns.push(() => {\n enterNodeMap.forEach((nodes, root) => {\n const className = enterNodeMapIds.get(root);\n nodes.forEach(node => removeClass(node, className));\n });\n leaveNodeMap.forEach((nodes, root) => {\n const className = leaveNodeMapIds.get(root);\n nodes.forEach(node => removeClass(node, className));\n });\n allLeaveNodes.forEach(element => {\n this.processLeaveNode(element);\n });\n });\n const allPlayers = [];\n const erroneousTransitions = [];\n for (let i = this._namespaceList.length - 1; i >= 0; i--) {\n const ns = this._namespaceList[i];\n ns.drainQueuedTransitions(microtaskId).forEach(entry => {\n const player = entry.player;\n const element = entry.element;\n allPlayers.push(player);\n if (this.collectedEnterElements.length) {\n const details = element[REMOVAL_FLAG];\n // animations for move operations (elements being removed and reinserted,\n // e.g. when the order of an *ngFor list changes) are currently not supported\n if (details && details.setForMove) {\n if (details.previousTriggersValues && details.previousTriggersValues.has(entry.triggerName)) {\n const previousValue = details.previousTriggersValues.get(entry.triggerName);\n // we need to restore the previous trigger value since the element has\n // only been moved and hasn't actually left the DOM\n const triggersWithStates = this.statesByElement.get(entry.element);\n if (triggersWithStates && triggersWithStates.has(entry.triggerName)) {\n const state = triggersWithStates.get(entry.triggerName);\n state.value = previousValue;\n triggersWithStates.set(entry.triggerName, state);\n }\n }\n player.destroy();\n return;\n }\n }\n const nodeIsOrphaned = !bodyNode || !this.driver.containsElement(bodyNode, element);\n const leaveClassName = leaveNodeMapIds.get(element);\n const enterClassName = enterNodeMapIds.get(element);\n const instruction = this._buildInstruction(entry, subTimelines, enterClassName, leaveClassName, nodeIsOrphaned);\n if (instruction.errors && instruction.errors.length) {\n erroneousTransitions.push(instruction);\n return;\n }\n // even though the element may not be in the DOM, it may still\n // be added at a later point (due to the mechanics of content\n // projection and/or dynamic component insertion) therefore it's\n // important to still style the element.\n if (nodeIsOrphaned) {\n player.onStart(() => eraseStyles(element, instruction.fromStyles));\n player.onDestroy(() => setStyles(element, instruction.toStyles));\n skippedPlayers.push(player);\n return;\n }\n // if an unmatched transition is queued and ready to go\n // then it SHOULD NOT render an animation and cancel the\n // previously running animations.\n if (entry.isFallbackTransition) {\n player.onStart(() => eraseStyles(element, instruction.fromStyles));\n player.onDestroy(() => setStyles(element, instruction.toStyles));\n skippedPlayers.push(player);\n return;\n }\n // this means that if a parent animation uses this animation as a sub-trigger\n // then it will instruct the timeline builder not to add a player delay, but\n // instead stretch the first keyframe gap until the animation starts. This is\n // important in order to prevent extra initialization styles from being\n // required by the user for the animation.\n const timelines = [];\n instruction.timelines.forEach(tl => {\n tl.stretchStartingKeyframe = true;\n if (!this.disabledNodes.has(tl.element)) {\n timelines.push(tl);\n }\n });\n instruction.timelines = timelines;\n subTimelines.append(element, instruction.timelines);\n const tuple = {\n instruction,\n player,\n element\n };\n queuedInstructions.push(tuple);\n instruction.queriedElements.forEach(element => getOrSetDefaultValue(queriedElements, element, []).push(player));\n instruction.preStyleProps.forEach((stringMap, element) => {\n if (stringMap.size) {\n let setVal = allPreStyleElements.get(element);\n if (!setVal) {\n allPreStyleElements.set(element, setVal = new Set());\n }\n stringMap.forEach((_, prop) => setVal.add(prop));\n }\n });\n instruction.postStyleProps.forEach((stringMap, element) => {\n let setVal = allPostStyleElements.get(element);\n if (!setVal) {\n allPostStyleElements.set(element, setVal = new Set());\n }\n stringMap.forEach((_, prop) => setVal.add(prop));\n });\n });\n }\n if (erroneousTransitions.length) {\n const errors = [];\n erroneousTransitions.forEach(instruction => {\n errors.push(transitionFailed(instruction.triggerName, instruction.errors));\n });\n allPlayers.forEach(player => player.destroy());\n this.reportError(errors);\n }\n const allPreviousPlayersMap = new Map();\n // this map tells us which element in the DOM tree is contained by\n // which animation. Further down this map will get populated once\n // the players are built and in doing so we can use it to efficiently\n // figure out if a sub player is skipped due to a parent player having priority.\n const animationElementMap = new Map();\n queuedInstructions.forEach(entry => {\n const element = entry.element;\n if (subTimelines.has(element)) {\n animationElementMap.set(element, element);\n this._beforeAnimationBuild(entry.player.namespaceId, entry.instruction, allPreviousPlayersMap);\n }\n });\n skippedPlayers.forEach(player => {\n const element = player.element;\n const previousPlayers = this._getPreviousPlayers(element, false, player.namespaceId, player.triggerName, null);\n previousPlayers.forEach(prevPlayer => {\n getOrSetDefaultValue(allPreviousPlayersMap, element, []).push(prevPlayer);\n prevPlayer.destroy();\n });\n });\n // this is a special case for nodes that will be removed either by\n // having their own leave animations or by being queried in a container\n // that will be removed once a parent animation is complete. The idea\n // here is that * styles must be identical to ! styles because of\n // backwards compatibility (* is also filled in by default in many places).\n // Otherwise * styles will return an empty value or \"auto\" since the element\n // passed to getComputedStyle will not be visible (since * === destination)\n const replaceNodes = allLeaveNodes.filter(node => {\n return replacePostStylesAsPre(node, allPreStyleElements, allPostStyleElements);\n });\n // POST STAGE: fill the * styles\n const postStylesMap = new Map();\n const allLeaveQueriedNodes = cloakAndComputeStyles(postStylesMap, this.driver, leaveNodesWithoutAnimations, allPostStyleElements, AUTO_STYLE);\n allLeaveQueriedNodes.forEach(node => {\n if (replacePostStylesAsPre(node, allPreStyleElements, allPostStyleElements)) {\n replaceNodes.push(node);\n }\n });\n // PRE STAGE: fill the ! styles\n const preStylesMap = new Map();\n enterNodeMap.forEach((nodes, root) => {\n cloakAndComputeStyles(preStylesMap, this.driver, new Set(nodes), allPreStyleElements, _PRE_STYLE);\n });\n replaceNodes.forEach(node => {\n const post = postStylesMap.get(node);\n const pre = preStylesMap.get(node);\n postStylesMap.set(node, new Map([...(post?.entries() ?? []), ...(pre?.entries() ?? [])]));\n });\n const rootPlayers = [];\n const subPlayers = [];\n const NO_PARENT_ANIMATION_ELEMENT_DETECTED = {};\n queuedInstructions.forEach(entry => {\n const {\n element,\n player,\n instruction\n } = entry;\n // this means that it was never consumed by a parent animation which\n // means that it is independent and therefore should be set for animation\n if (subTimelines.has(element)) {\n if (disabledElementsSet.has(element)) {\n player.onDestroy(() => setStyles(element, instruction.toStyles));\n player.disabled = true;\n player.overrideTotalTime(instruction.totalTime);\n skippedPlayers.push(player);\n return;\n }\n // this will flow up the DOM and query the map to figure out\n // if a parent animation has priority over it. In the situation\n // that a parent is detected then it will cancel the loop. If\n // nothing is detected, or it takes a few hops to find a parent,\n // then it will fill in the missing nodes and signal them as having\n // a detected parent (or a NO_PARENT value via a special constant).\n let parentWithAnimation = NO_PARENT_ANIMATION_ELEMENT_DETECTED;\n if (animationElementMap.size > 1) {\n let elm = element;\n const parentsToAdd = [];\n while (elm = elm.parentNode) {\n const detectedParent = animationElementMap.get(elm);\n if (detectedParent) {\n parentWithAnimation = detectedParent;\n break;\n }\n parentsToAdd.push(elm);\n }\n parentsToAdd.forEach(parent => animationElementMap.set(parent, parentWithAnimation));\n }\n const innerPlayer = this._buildAnimation(player.namespaceId, instruction, allPreviousPlayersMap, skippedPlayersMap, preStylesMap, postStylesMap);\n player.setRealPlayer(innerPlayer);\n if (parentWithAnimation === NO_PARENT_ANIMATION_ELEMENT_DETECTED) {\n rootPlayers.push(player);\n } else {\n const parentPlayers = this.playersByElement.get(parentWithAnimation);\n if (parentPlayers && parentPlayers.length) {\n player.parentPlayer = optimizeGroupPlayer(parentPlayers);\n }\n skippedPlayers.push(player);\n }\n } else {\n eraseStyles(element, instruction.fromStyles);\n player.onDestroy(() => setStyles(element, instruction.toStyles));\n // there still might be a ancestor player animating this\n // element therefore we will still add it as a sub player\n // even if its animation may be disabled\n subPlayers.push(player);\n if (disabledElementsSet.has(element)) {\n skippedPlayers.push(player);\n }\n }\n });\n // find all of the sub players' corresponding inner animation players\n subPlayers.forEach(player => {\n // even if no players are found for a sub animation it\n // will still complete itself after the next tick since it's Noop\n const playersForElement = skippedPlayersMap.get(player.element);\n if (playersForElement && playersForElement.length) {\n const innerPlayer = optimizeGroupPlayer(playersForElement);\n player.setRealPlayer(innerPlayer);\n }\n });\n // the reason why we don't actually play the animation is\n // because all that a skipped player is designed to do is to\n // fire the start/done transition callback events\n skippedPlayers.forEach(player => {\n if (player.parentPlayer) {\n player.syncPlayerEvents(player.parentPlayer);\n } else {\n player.destroy();\n }\n });\n // run through all of the queued removals and see if they\n // were picked up by a query. If not then perform the removal\n // operation right away unless a parent animation is ongoing.\n for (let i = 0; i < allLeaveNodes.length; i++) {\n const element = allLeaveNodes[i];\n const details = element[REMOVAL_FLAG];\n removeClass(element, LEAVE_CLASSNAME);\n // this means the element has a removal animation that is being\n // taken care of and therefore the inner elements will hang around\n // until that animation is over (or the parent queried animation)\n if (details && details.hasAnimation) continue;\n let players = [];\n // if this element is queried or if it contains queried children\n // then we want for the element not to be removed from the page\n // until the queried animations have finished\n if (queriedElements.size) {\n let queriedPlayerResults = queriedElements.get(element);\n if (queriedPlayerResults && queriedPlayerResults.length) {\n players.push(...queriedPlayerResults);\n }\n let queriedInnerElements = this.driver.query(element, NG_ANIMATING_SELECTOR, true);\n for (let j = 0; j < queriedInnerElements.length; j++) {\n let queriedPlayers = queriedElements.get(queriedInnerElements[j]);\n if (queriedPlayers && queriedPlayers.length) {\n players.push(...queriedPlayers);\n }\n }\n }\n const activePlayers = players.filter(p => !p.destroyed);\n if (activePlayers.length) {\n removeNodesAfterAnimationDone(this, element, activePlayers);\n } else {\n this.processLeaveNode(element);\n }\n }\n // this is required so the cleanup method doesn't remove them\n allLeaveNodes.length = 0;\n rootPlayers.forEach(player => {\n this.players.push(player);\n player.onDone(() => {\n player.destroy();\n const index = this.players.indexOf(player);\n this.players.splice(index, 1);\n });\n player.play();\n });\n return rootPlayers;\n }\n afterFlush(callback) {\n this._flushFns.push(callback);\n }\n afterFlushAnimationsDone(callback) {\n this._whenQuietFns.push(callback);\n }\n _getPreviousPlayers(element, isQueriedElement, namespaceId, triggerName, toStateValue) {\n let players = [];\n if (isQueriedElement) {\n const queriedElementPlayers = this.playersByQueriedElement.get(element);\n if (queriedElementPlayers) {\n players = queriedElementPlayers;\n }\n } else {\n const elementPlayers = this.playersByElement.get(element);\n if (elementPlayers) {\n const isRemovalAnimation = !toStateValue || toStateValue == VOID_VALUE;\n elementPlayers.forEach(player => {\n if (player.queued) return;\n if (!isRemovalAnimation && player.triggerName != triggerName) return;\n players.push(player);\n });\n }\n }\n if (namespaceId || triggerName) {\n players = players.filter(player => {\n if (namespaceId && namespaceId != player.namespaceId) return false;\n if (triggerName && triggerName != player.triggerName) return false;\n return true;\n });\n }\n return players;\n }\n _beforeAnimationBuild(namespaceId, instruction, allPreviousPlayersMap) {\n const triggerName = instruction.triggerName;\n const rootElement = instruction.element;\n // when a removal animation occurs, ALL previous players are collected\n // and destroyed (even if they are outside of the current namespace)\n const targetNameSpaceId = instruction.isRemovalTransition ? undefined : namespaceId;\n const targetTriggerName = instruction.isRemovalTransition ? undefined : triggerName;\n for (const timelineInstruction of instruction.timelines) {\n const element = timelineInstruction.element;\n const isQueriedElement = element !== rootElement;\n const players = getOrSetDefaultValue(allPreviousPlayersMap, element, []);\n const previousPlayers = this._getPreviousPlayers(element, isQueriedElement, targetNameSpaceId, targetTriggerName, instruction.toState);\n previousPlayers.forEach(player => {\n const realPlayer = player.getRealPlayer();\n if (realPlayer.beforeDestroy) {\n realPlayer.beforeDestroy();\n }\n player.destroy();\n players.push(player);\n });\n }\n // this needs to be done so that the PRE/POST styles can be\n // computed properly without interfering with the previous animation\n eraseStyles(rootElement, instruction.fromStyles);\n }\n _buildAnimation(namespaceId, instruction, allPreviousPlayersMap, skippedPlayersMap, preStylesMap, postStylesMap) {\n const triggerName = instruction.triggerName;\n const rootElement = instruction.element;\n // we first run this so that the previous animation player\n // data can be passed into the successive animation players\n const allQueriedPlayers = [];\n const allConsumedElements = new Set();\n const allSubElements = new Set();\n const allNewPlayers = instruction.timelines.map(timelineInstruction => {\n const element = timelineInstruction.element;\n allConsumedElements.add(element);\n // FIXME (matsko): make sure to-be-removed animations are removed properly\n const details = element[REMOVAL_FLAG];\n if (details && details.removedBeforeQueried) return new NoopAnimationPlayer(timelineInstruction.duration, timelineInstruction.delay);\n const isQueriedElement = element !== rootElement;\n const previousPlayers = flattenGroupPlayers((allPreviousPlayersMap.get(element) || EMPTY_PLAYER_ARRAY).map(p => p.getRealPlayer())).filter(p => {\n // the `element` is not apart of the AnimationPlayer definition, but\n // Mock/WebAnimations\n // use the element within their implementation. This will be added in Angular5 to\n // AnimationPlayer\n const pp = p;\n return pp.element ? pp.element === element : false;\n });\n const preStyles = preStylesMap.get(element);\n const postStyles = postStylesMap.get(element);\n const keyframes = normalizeKeyframes(this._normalizer, timelineInstruction.keyframes, preStyles, postStyles);\n const player = this._buildPlayer(timelineInstruction, keyframes, previousPlayers);\n // this means that this particular player belongs to a sub trigger. It is\n // important that we match this player up with the corresponding (@trigger.listener)\n if (timelineInstruction.subTimeline && skippedPlayersMap) {\n allSubElements.add(element);\n }\n if (isQueriedElement) {\n const wrappedPlayer = new TransitionAnimationPlayer(namespaceId, triggerName, element);\n wrappedPlayer.setRealPlayer(player);\n allQueriedPlayers.push(wrappedPlayer);\n }\n return player;\n });\n allQueriedPlayers.forEach(player => {\n getOrSetDefaultValue(this.playersByQueriedElement, player.element, []).push(player);\n player.onDone(() => deleteOrUnsetInMap(this.playersByQueriedElement, player.element, player));\n });\n allConsumedElements.forEach(element => addClass(element, NG_ANIMATING_CLASSNAME));\n const player = optimizeGroupPlayer(allNewPlayers);\n player.onDestroy(() => {\n allConsumedElements.forEach(element => removeClass(element, NG_ANIMATING_CLASSNAME));\n setStyles(rootElement, instruction.toStyles);\n });\n // this basically makes all of the callbacks for sub element animations\n // be dependent on the upper players for when they finish\n allSubElements.forEach(element => {\n getOrSetDefaultValue(skippedPlayersMap, element, []).push(player);\n });\n return player;\n }\n _buildPlayer(instruction, keyframes, previousPlayers) {\n if (keyframes.length > 0) {\n return this.driver.animate(instruction.element, keyframes, instruction.duration, instruction.delay, instruction.easing, previousPlayers);\n }\n // special case for when an empty transition|definition is provided\n // ... there is no point in rendering an empty animation\n return new NoopAnimationPlayer(instruction.duration, instruction.delay);\n }\n}\nclass TransitionAnimationPlayer {\n namespaceId;\n triggerName;\n element;\n _player = /*#__PURE__*/new NoopAnimationPlayer();\n _containsRealPlayer = false;\n _queuedCallbacks = /*#__PURE__*/new Map();\n destroyed = false;\n parentPlayer = null;\n markedForDestroy = false;\n disabled = false;\n queued = true;\n totalTime = 0;\n constructor(namespaceId, triggerName, element) {\n this.namespaceId = namespaceId;\n this.triggerName = triggerName;\n this.element = element;\n }\n setRealPlayer(player) {\n if (this._containsRealPlayer) return;\n this._player = player;\n this._queuedCallbacks.forEach((callbacks, phase) => {\n callbacks.forEach(callback => listenOnPlayer(player, phase, undefined, callback));\n });\n this._queuedCallbacks.clear();\n this._containsRealPlayer = true;\n this.overrideTotalTime(player.totalTime);\n this.queued = false;\n }\n getRealPlayer() {\n return this._player;\n }\n overrideTotalTime(totalTime) {\n this.totalTime = totalTime;\n }\n syncPlayerEvents(player) {\n const p = this._player;\n if (p.triggerCallback) {\n player.onStart(() => p.triggerCallback('start'));\n }\n player.onDone(() => this.finish());\n player.onDestroy(() => this.destroy());\n }\n _queueEvent(name, callback) {\n getOrSetDefaultValue(this._queuedCallbacks, name, []).push(callback);\n }\n onDone(fn) {\n if (this.queued) {\n this._queueEvent('done', fn);\n }\n this._player.onDone(fn);\n }\n onStart(fn) {\n if (this.queued) {\n this._queueEvent('start', fn);\n }\n this._player.onStart(fn);\n }\n onDestroy(fn) {\n if (this.queued) {\n this._queueEvent('destroy', fn);\n }\n this._player.onDestroy(fn);\n }\n init() {\n this._player.init();\n }\n hasStarted() {\n return this.queued ? false : this._player.hasStarted();\n }\n play() {\n !this.queued && this._player.play();\n }\n pause() {\n !this.queued && this._player.pause();\n }\n restart() {\n !this.queued && this._player.restart();\n }\n finish() {\n this._player.finish();\n }\n destroy() {\n this.destroyed = true;\n this._player.destroy();\n }\n reset() {\n !this.queued && this._player.reset();\n }\n setPosition(p) {\n if (!this.queued) {\n this._player.setPosition(p);\n }\n }\n getPosition() {\n return this.queued ? 0 : this._player.getPosition();\n }\n /** @internal */\n triggerCallback(phaseName) {\n const p = this._player;\n if (p.triggerCallback) {\n p.triggerCallback(phaseName);\n }\n }\n}\nfunction deleteOrUnsetInMap(map, key, value) {\n let currentValues = map.get(key);\n if (currentValues) {\n if (currentValues.length) {\n const index = currentValues.indexOf(value);\n currentValues.splice(index, 1);\n }\n if (currentValues.length == 0) {\n map.delete(key);\n }\n }\n return currentValues;\n}\nfunction normalizeTriggerValue(value) {\n // we use `!= null` here because it's the most simple\n // way to test against a \"falsy\" value without mixing\n // in empty strings or a zero value. DO NOT OPTIMIZE.\n return value != null ? value : null;\n}\nfunction isElementNode(node) {\n return node && node['nodeType'] === 1;\n}\nfunction isTriggerEventValid(eventName) {\n return eventName == 'start' || eventName == 'done';\n}\nfunction cloakElement(element, value) {\n const oldValue = element.style.display;\n element.style.display = value != null ? value : 'none';\n return oldValue;\n}\nfunction cloakAndComputeStyles(valuesMap, driver, elements, elementPropsMap, defaultStyle) {\n const cloakVals = [];\n elements.forEach(element => cloakVals.push(cloakElement(element)));\n const failedElements = [];\n elementPropsMap.forEach((props, element) => {\n const styles = new Map();\n props.forEach(prop => {\n const value = driver.computeStyle(element, prop, defaultStyle);\n styles.set(prop, value);\n // there is no easy way to detect this because a sub element could be removed\n // by a parent animation element being detached.\n if (!value || value.length == 0) {\n element[REMOVAL_FLAG] = NULL_REMOVED_QUERIED_STATE;\n failedElements.push(element);\n }\n });\n valuesMap.set(element, styles);\n });\n // we use a index variable here since Set.forEach(a, i) does not return\n // an index value for the closure (but instead just the value)\n let i = 0;\n elements.forEach(element => cloakElement(element, cloakVals[i++]));\n return failedElements;\n}\n/*\nSince the Angular renderer code will return a collection of inserted\nnodes in all areas of a DOM tree, it's up to this algorithm to figure\nout which nodes are roots for each animation @trigger.\n\nBy placing each inserted node into a Set and traversing upwards, it\nis possible to find the @trigger elements and well any direct *star\ninsertion nodes, if a @trigger root is found then the enter element\nis placed into the Map[@trigger] spot.\n */\nfunction buildRootMap(roots, nodes) {\n const rootMap = new Map();\n roots.forEach(root => rootMap.set(root, []));\n if (nodes.length == 0) return rootMap;\n const NULL_NODE = 1;\n const nodeSet = new Set(nodes);\n const localRootMap = new Map();\n function getRoot(node) {\n if (!node) return NULL_NODE;\n let root = localRootMap.get(node);\n if (root) return root;\n const parent = node.parentNode;\n if (rootMap.has(parent)) {\n // ngIf inside @trigger\n root = parent;\n } else if (nodeSet.has(parent)) {\n // ngIf inside ngIf\n root = NULL_NODE;\n } else {\n // recurse upwards\n root = getRoot(parent);\n }\n localRootMap.set(node, root);\n return root;\n }\n nodes.forEach(node => {\n const root = getRoot(node);\n if (root !== NULL_NODE) {\n rootMap.get(root).push(node);\n }\n });\n return rootMap;\n}\nfunction addClass(element, className) {\n element.classList?.add(className);\n}\nfunction removeClass(element, className) {\n element.classList?.remove(className);\n}\nfunction removeNodesAfterAnimationDone(engine, element, players) {\n optimizeGroupPlayer(players).onDone(() => engine.processLeaveNode(element));\n}\nfunction flattenGroupPlayers(players) {\n const finalPlayers = [];\n _flattenGroupPlayersRecur(players, finalPlayers);\n return finalPlayers;\n}\nfunction _flattenGroupPlayersRecur(players, finalPlayers) {\n for (let i = 0; i < players.length; i++) {\n const player = players[i];\n if (player instanceof AnimationGroupPlayer) {\n _flattenGroupPlayersRecur(player.players, finalPlayers);\n } else {\n finalPlayers.push(player);\n }\n }\n}\nfunction objEquals(a, b) {\n const k1 = Object.keys(a);\n const k2 = Object.keys(b);\n if (k1.length != k2.length) return false;\n for (let i = 0; i < k1.length; i++) {\n const prop = k1[i];\n if (!b.hasOwnProperty(prop) || a[prop] !== b[prop]) return false;\n }\n return true;\n}\nfunction replacePostStylesAsPre(element, allPreStyleElements, allPostStyleElements) {\n const postEntry = allPostStyleElements.get(element);\n if (!postEntry) return false;\n let preEntry = allPreStyleElements.get(element);\n if (preEntry) {\n postEntry.forEach(data => preEntry.add(data));\n } else {\n allPreStyleElements.set(element, postEntry);\n }\n allPostStyleElements.delete(element);\n return true;\n}\nclass AnimationEngine {\n _driver;\n _normalizer;\n _transitionEngine;\n _timelineEngine;\n _triggerCache = {};\n // this method is designed to be overridden by the code that uses this engine\n onRemovalComplete = (element, context) => {};\n constructor(doc, _driver, _normalizer) {\n this._driver = _driver;\n this._normalizer = _normalizer;\n this._transitionEngine = new TransitionAnimationEngine(doc.body, _driver, _normalizer);\n this._timelineEngine = new TimelineAnimationEngine(doc.body, _driver, _normalizer);\n this._transitionEngine.onRemovalComplete = (element, context) => this.onRemovalComplete(element, context);\n }\n registerTrigger(componentId, namespaceId, hostElement, name, metadata) {\n const cacheKey = componentId + '-' + name;\n let trigger = this._triggerCache[cacheKey];\n if (!trigger) {\n const errors = [];\n const warnings = [];\n const ast = buildAnimationAst(this._driver, metadata, errors, warnings);\n if (errors.length) {\n throw triggerBuildFailed(name, errors);\n }\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n if (warnings.length) {\n warnTriggerBuild(name, warnings);\n }\n }\n trigger = buildTrigger(name, ast, this._normalizer);\n this._triggerCache[cacheKey] = trigger;\n }\n this._transitionEngine.registerTrigger(namespaceId, name, trigger);\n }\n register(namespaceId, hostElement) {\n this._transitionEngine.register(namespaceId, hostElement);\n }\n destroy(namespaceId, context) {\n this._transitionEngine.destroy(namespaceId, context);\n }\n onInsert(namespaceId, element, parent, insertBefore) {\n this._transitionEngine.insertNode(namespaceId, element, parent, insertBefore);\n }\n onRemove(namespaceId, element, context) {\n this._transitionEngine.removeNode(namespaceId, element, context);\n }\n disableAnimations(element, disable) {\n this._transitionEngine.markElementAsDisabled(element, disable);\n }\n process(namespaceId, element, property, value) {\n if (property.charAt(0) == '@') {\n const [id, action] = parseTimelineCommand(property);\n const args = value;\n this._timelineEngine.command(id, element, action, args);\n } else {\n this._transitionEngine.trigger(namespaceId, element, property, value);\n }\n }\n listen(namespaceId, element, eventName, eventPhase, callback) {\n // @@listen\n if (eventName.charAt(0) == '@') {\n const [id, action] = parseTimelineCommand(eventName);\n return this._timelineEngine.listen(id, element, action, callback);\n }\n return this._transitionEngine.listen(namespaceId, element, eventName, eventPhase, callback);\n }\n flush(microtaskId = -1) {\n this._transitionEngine.flush(microtaskId);\n }\n get players() {\n return [...this._transitionEngine.players, ...this._timelineEngine.players];\n }\n whenRenderingDone() {\n return this._transitionEngine.whenRenderingDone();\n }\n afterFlushAnimationsDone(cb) {\n this._transitionEngine.afterFlushAnimationsDone(cb);\n }\n}\n\n/**\n * Returns an instance of `SpecialCasedStyles` if and when any special (non animateable) styles are\n * detected.\n *\n * In CSS there exist properties that cannot be animated within a keyframe animation\n * (whether it be via CSS keyframes or web-animations) and the animation implementation\n * will ignore them. This function is designed to detect those special cased styles and\n * return a container that will be executed at the start and end of the animation.\n *\n * @returns an instance of `SpecialCasedStyles` if any special styles are detected otherwise `null`\n */\nfunction packageNonAnimatableStyles(element, styles) {\n let startStyles = null;\n let endStyles = null;\n if (Array.isArray(styles) && styles.length) {\n startStyles = filterNonAnimatableStyles(styles[0]);\n if (styles.length > 1) {\n endStyles = filterNonAnimatableStyles(styles[styles.length - 1]);\n }\n } else if (styles instanceof Map) {\n startStyles = filterNonAnimatableStyles(styles);\n }\n return startStyles || endStyles ? new SpecialCasedStyles(element, startStyles, endStyles) : null;\n}\n/**\n * Designed to be executed during a keyframe-based animation to apply any special-cased styles.\n *\n * When started (when the `start()` method is run) then the provided `startStyles`\n * will be applied. When finished (when the `finish()` method is called) the\n * `endStyles` will be applied as well any any starting styles. Finally when\n * `destroy()` is called then all styles will be removed.\n */\nlet SpecialCasedStyles = /*#__PURE__*/(() => {\n class SpecialCasedStyles {\n _element;\n _startStyles;\n _endStyles;\n static initialStylesByElement = /* @__PURE__ */new WeakMap();\n _state = 0 /* SpecialCasedStylesState.Pending */;\n _initialStyles;\n constructor(_element, _startStyles, _endStyles) {\n this._element = _element;\n this._startStyles = _startStyles;\n this._endStyles = _endStyles;\n let initialStyles = SpecialCasedStyles.initialStylesByElement.get(_element);\n if (!initialStyles) {\n SpecialCasedStyles.initialStylesByElement.set(_element, initialStyles = new Map());\n }\n this._initialStyles = initialStyles;\n }\n start() {\n if (this._state < 1 /* SpecialCasedStylesState.Started */) {\n if (this._startStyles) {\n setStyles(this._element, this._startStyles, this._initialStyles);\n }\n this._state = 1 /* SpecialCasedStylesState.Started */;\n }\n }\n finish() {\n this.start();\n if (this._state < 2 /* SpecialCasedStylesState.Finished */) {\n setStyles(this._element, this._initialStyles);\n if (this._endStyles) {\n setStyles(this._element, this._endStyles);\n this._endStyles = null;\n }\n this._state = 1 /* SpecialCasedStylesState.Started */;\n }\n }\n destroy() {\n this.finish();\n if (this._state < 3 /* SpecialCasedStylesState.Destroyed */) {\n SpecialCasedStyles.initialStylesByElement.delete(this._element);\n if (this._startStyles) {\n eraseStyles(this._element, this._startStyles);\n this._endStyles = null;\n }\n if (this._endStyles) {\n eraseStyles(this._element, this._endStyles);\n this._endStyles = null;\n }\n setStyles(this._element, this._initialStyles);\n this._state = 3 /* SpecialCasedStylesState.Destroyed */;\n }\n }\n }\n return SpecialCasedStyles;\n})();\nfunction filterNonAnimatableStyles(styles) {\n let result = null;\n styles.forEach((val, prop) => {\n if (isNonAnimatableStyle(prop)) {\n result = result || new Map();\n result.set(prop, val);\n }\n });\n return result;\n}\nfunction isNonAnimatableStyle(prop) {\n return prop === 'display' || prop === 'position';\n}\nclass WebAnimationsPlayer {\n element;\n keyframes;\n options;\n _specialStyles;\n _onDoneFns = [];\n _onStartFns = [];\n _onDestroyFns = [];\n _duration;\n _delay;\n _initialized = false;\n _finished = false;\n _started = false;\n _destroyed = false;\n _finalKeyframe;\n // the following original fns are persistent copies of the _onStartFns and _onDoneFns\n // and are used to reset the fns to their original values upon reset()\n // (since the _onStartFns and _onDoneFns get deleted after they are called)\n _originalOnDoneFns = [];\n _originalOnStartFns = [];\n // using non-null assertion because it's re(set) by init();\n domPlayer;\n time = 0;\n parentPlayer = null;\n currentSnapshot = /*#__PURE__*/new Map();\n constructor(element, keyframes, options, _specialStyles) {\n this.element = element;\n this.keyframes = keyframes;\n this.options = options;\n this._specialStyles = _specialStyles;\n this._duration = options['duration'];\n this._delay = options['delay'] || 0;\n this.time = this._duration + this._delay;\n }\n _onFinish() {\n if (!this._finished) {\n this._finished = true;\n this._onDoneFns.forEach(fn => fn());\n this._onDoneFns = [];\n }\n }\n init() {\n this._buildPlayer();\n this._preparePlayerBeforeStart();\n }\n _buildPlayer() {\n if (this._initialized) return;\n this._initialized = true;\n const keyframes = this.keyframes;\n // @ts-expect-error overwriting a readonly property\n this.domPlayer = this._triggerWebAnimation(this.element, keyframes, this.options);\n this._finalKeyframe = keyframes.length ? keyframes[keyframes.length - 1] : new Map();\n const onFinish = () => this._onFinish();\n this.domPlayer.addEventListener('finish', onFinish);\n this.onDestroy(() => {\n // We must remove the `finish` event listener once an animation has completed all its\n // iterations. This action is necessary to prevent a memory leak since the listener captures\n // `this`, creating a closure that prevents `this` from being garbage collected.\n this.domPlayer.removeEventListener('finish', onFinish);\n });\n }\n _preparePlayerBeforeStart() {\n // this is required so that the player doesn't start to animate right away\n if (this._delay) {\n this._resetDomPlayerState();\n } else {\n this.domPlayer.pause();\n }\n }\n _convertKeyframesToObject(keyframes) {\n const kfs = [];\n keyframes.forEach(frame => {\n kfs.push(Object.fromEntries(frame));\n });\n return kfs;\n }\n /** @internal */\n _triggerWebAnimation(element, keyframes, options) {\n return element.animate(this._convertKeyframesToObject(keyframes), options);\n }\n onStart(fn) {\n this._originalOnStartFns.push(fn);\n this._onStartFns.push(fn);\n }\n onDone(fn) {\n this._originalOnDoneFns.push(fn);\n this._onDoneFns.push(fn);\n }\n onDestroy(fn) {\n this._onDestroyFns.push(fn);\n }\n play() {\n this._buildPlayer();\n if (!this.hasStarted()) {\n this._onStartFns.forEach(fn => fn());\n this._onStartFns = [];\n this._started = true;\n if (this._specialStyles) {\n this._specialStyles.start();\n }\n }\n this.domPlayer.play();\n }\n pause() {\n this.init();\n this.domPlayer.pause();\n }\n finish() {\n this.init();\n if (this._specialStyles) {\n this._specialStyles.finish();\n }\n this._onFinish();\n this.domPlayer.finish();\n }\n reset() {\n this._resetDomPlayerState();\n this._destroyed = false;\n this._finished = false;\n this._started = false;\n this._onStartFns = this._originalOnStartFns;\n this._onDoneFns = this._originalOnDoneFns;\n }\n _resetDomPlayerState() {\n if (this.domPlayer) {\n this.domPlayer.cancel();\n }\n }\n restart() {\n this.reset();\n this.play();\n }\n hasStarted() {\n return this._started;\n }\n destroy() {\n if (!this._destroyed) {\n this._destroyed = true;\n this._resetDomPlayerState();\n this._onFinish();\n if (this._specialStyles) {\n this._specialStyles.destroy();\n }\n this._onDestroyFns.forEach(fn => fn());\n this._onDestroyFns = [];\n }\n }\n setPosition(p) {\n if (this.domPlayer === undefined) {\n this.init();\n }\n this.domPlayer.currentTime = p * this.time;\n }\n getPosition() {\n // tsc is complaining with TS2362 without the conversion to number\n return +(this.domPlayer.currentTime ?? 0) / this.time;\n }\n get totalTime() {\n return this._delay + this._duration;\n }\n beforeDestroy() {\n const styles = new Map();\n if (this.hasStarted()) {\n // note: this code is invoked only when the `play` function was called prior to this\n // (thus `hasStarted` returns true), this implies that the code that initializes\n // `_finalKeyframe` has also been executed and the non-null assertion can be safely used here\n const finalKeyframe = this._finalKeyframe;\n finalKeyframe.forEach((val, prop) => {\n if (prop !== 'offset') {\n styles.set(prop, this._finished ? val : computeStyle(this.element, prop));\n }\n });\n }\n this.currentSnapshot = styles;\n }\n /** @internal */\n triggerCallback(phaseName) {\n const methods = phaseName === 'start' ? this._onStartFns : this._onDoneFns;\n methods.forEach(fn => fn());\n methods.length = 0;\n }\n}\nclass WebAnimationsDriver {\n validateStyleProperty(prop) {\n // Perform actual validation in dev mode only, in prod mode this check is a noop.\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n return validateStyleProperty(prop);\n }\n return true;\n }\n validateAnimatableStyleProperty(prop) {\n // Perform actual validation in dev mode only, in prod mode this check is a noop.\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n const cssProp = camelCaseToDashCase(prop);\n return validateWebAnimatableStyleProperty(cssProp);\n }\n return true;\n }\n containsElement(elm1, elm2) {\n return containsElement(elm1, elm2);\n }\n getParentElement(element) {\n return getParentElement(element);\n }\n query(element, selector, multi) {\n return invokeQuery(element, selector, multi);\n }\n computeStyle(element, prop, defaultValue) {\n return computeStyle(element, prop);\n }\n animate(element, keyframes, duration, delay, easing, previousPlayers = []) {\n const fill = delay == 0 ? 'both' : 'forwards';\n const playerOptions = {\n duration,\n delay,\n fill\n };\n // we check for this to avoid having a null|undefined value be present\n // for the easing (which results in an error for certain browsers #9752)\n if (easing) {\n playerOptions['easing'] = easing;\n }\n const previousStyles = new Map();\n const previousWebAnimationPlayers = previousPlayers.filter(player => player instanceof WebAnimationsPlayer);\n if (allowPreviousPlayerStylesMerge(duration, delay)) {\n previousWebAnimationPlayers.forEach(player => {\n player.currentSnapshot.forEach((val, prop) => previousStyles.set(prop, val));\n });\n }\n let _keyframes = normalizeKeyframes$1(keyframes).map(styles => new Map(styles));\n _keyframes = balancePreviousStylesIntoKeyframes(element, _keyframes, previousStyles);\n const specialStyles = packageNonAnimatableStyles(element, _keyframes);\n return new WebAnimationsPlayer(element, _keyframes, playerOptions, specialStyles);\n }\n}\nfunction createEngine(type, doc) {\n // TODO: find a way to make this tree shakable.\n if (type === 'noop') {\n return new AnimationEngine(doc, new NoopAnimationDriver(), new NoopAnimationStyleNormalizer());\n }\n return new AnimationEngine(doc, new WebAnimationsDriver(), new WebAnimationsStyleNormalizer());\n}\nclass Animation {\n _driver;\n _animationAst;\n constructor(_driver, input) {\n this._driver = _driver;\n const errors = [];\n const warnings = [];\n const ast = buildAnimationAst(_driver, input, errors, warnings);\n if (errors.length) {\n throw validationFailed(errors);\n }\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n if (warnings.length) {\n warnValidation(warnings);\n }\n }\n this._animationAst = ast;\n }\n buildTimelines(element, startingStyles, destinationStyles, options, subInstructions) {\n const start = Array.isArray(startingStyles) ? normalizeStyles(startingStyles) : startingStyles;\n const dest = Array.isArray(destinationStyles) ? normalizeStyles(destinationStyles) : destinationStyles;\n const errors = [];\n subInstructions = subInstructions || new ElementInstructionMap();\n const result = buildAnimationTimelines(this._driver, element, this._animationAst, ENTER_CLASSNAME, LEAVE_CLASSNAME, start, dest, options, subInstructions, errors);\n if (errors.length) {\n throw buildingFailed(errors);\n }\n return result;\n }\n}\nconst ANIMATION_PREFIX = '@';\nconst DISABLE_ANIMATIONS_FLAG = '@.disabled';\nclass BaseAnimationRenderer {\n namespaceId;\n delegate;\n engine;\n _onDestroy;\n // We need to explicitly type this property because of an api-extractor bug\n // See https://github.com/microsoft/rushstack/issues/4390\n ɵtype = 0 /* AnimationRendererType.Regular */;\n constructor(namespaceId, delegate, engine, _onDestroy) {\n this.namespaceId = namespaceId;\n this.delegate = delegate;\n this.engine = engine;\n this._onDestroy = _onDestroy;\n }\n get data() {\n return this.delegate.data;\n }\n destroyNode(node) {\n this.delegate.destroyNode?.(node);\n }\n destroy() {\n this.engine.destroy(this.namespaceId, this.delegate);\n this.engine.afterFlushAnimationsDone(() => {\n // Call the renderer destroy method after the animations has finished as otherwise\n // styles will be removed too early which will cause an unstyled animation.\n queueMicrotask(() => {\n this.delegate.destroy();\n });\n });\n this._onDestroy?.();\n }\n createElement(name, namespace) {\n return this.delegate.createElement(name, namespace);\n }\n createComment(value) {\n return this.delegate.createComment(value);\n }\n createText(value) {\n return this.delegate.createText(value);\n }\n appendChild(parent, newChild) {\n this.delegate.appendChild(parent, newChild);\n this.engine.onInsert(this.namespaceId, newChild, parent, false);\n }\n insertBefore(parent, newChild, refChild, isMove = true) {\n this.delegate.insertBefore(parent, newChild, refChild);\n // If `isMove` true than we should animate this insert.\n this.engine.onInsert(this.namespaceId, newChild, parent, isMove);\n }\n removeChild(parent, oldChild, isHostElement) {\n // Prior to the changes in #57203, this method wasn't being called at all by `core` if the child\n // doesn't have a parent. There appears to be some animation-specific downstream logic that\n // depends on the null check happening before the animation engine. This check keeps the old\n // behavior while allowing `core` to not have to check for the parent element anymore.\n if (this.parentNode(oldChild)) {\n this.engine.onRemove(this.namespaceId, oldChild, this.delegate);\n }\n }\n selectRootElement(selectorOrNode, preserveContent) {\n return this.delegate.selectRootElement(selectorOrNode, preserveContent);\n }\n parentNode(node) {\n return this.delegate.parentNode(node);\n }\n nextSibling(node) {\n return this.delegate.nextSibling(node);\n }\n setAttribute(el, name, value, namespace) {\n this.delegate.setAttribute(el, name, value, namespace);\n }\n removeAttribute(el, name, namespace) {\n this.delegate.removeAttribute(el, name, namespace);\n }\n addClass(el, name) {\n this.delegate.addClass(el, name);\n }\n removeClass(el, name) {\n this.delegate.removeClass(el, name);\n }\n setStyle(el, style, value, flags) {\n this.delegate.setStyle(el, style, value, flags);\n }\n removeStyle(el, style, flags) {\n this.delegate.removeStyle(el, style, flags);\n }\n setProperty(el, name, value) {\n if (name.charAt(0) == ANIMATION_PREFIX && name == DISABLE_ANIMATIONS_FLAG) {\n this.disableAnimations(el, !!value);\n } else {\n this.delegate.setProperty(el, name, value);\n }\n }\n setValue(node, value) {\n this.delegate.setValue(node, value);\n }\n listen(target, eventName, callback, options) {\n return this.delegate.listen(target, eventName, callback, options);\n }\n disableAnimations(element, value) {\n this.engine.disableAnimations(element, value);\n }\n}\nclass AnimationRenderer extends BaseAnimationRenderer {\n factory;\n constructor(factory, namespaceId, delegate, engine, onDestroy) {\n super(namespaceId, delegate, engine, onDestroy);\n this.factory = factory;\n this.namespaceId = namespaceId;\n }\n setProperty(el, name, value) {\n if (name.charAt(0) == ANIMATION_PREFIX) {\n if (name.charAt(1) == '.' && name == DISABLE_ANIMATIONS_FLAG) {\n value = value === undefined ? true : !!value;\n this.disableAnimations(el, value);\n } else {\n this.engine.process(this.namespaceId, el, name.slice(1), value);\n }\n } else {\n this.delegate.setProperty(el, name, value);\n }\n }\n listen(target, eventName, callback, options) {\n if (eventName.charAt(0) == ANIMATION_PREFIX) {\n const element = resolveElementFromTarget(target);\n let name = eventName.slice(1);\n let phase = '';\n // @listener.phase is for trigger animation callbacks\n // @@listener is for animation builder callbacks\n if (name.charAt(0) != ANIMATION_PREFIX) {\n [name, phase] = parseTriggerCallbackName(name);\n }\n return this.engine.listen(this.namespaceId, element, name, phase, event => {\n const countId = event['_data'] || -1;\n this.factory.scheduleListenerCallback(countId, callback, event);\n });\n }\n return this.delegate.listen(target, eventName, callback, options);\n }\n}\nfunction resolveElementFromTarget(target) {\n switch (target) {\n case 'body':\n return document.body;\n case 'document':\n return document;\n case 'window':\n return window;\n default:\n return target;\n }\n}\nfunction parseTriggerCallbackName(triggerName) {\n const dotIndex = triggerName.indexOf('.');\n const trigger = triggerName.substring(0, dotIndex);\n const phase = triggerName.slice(dotIndex + 1);\n return [trigger, phase];\n}\nclass AnimationRendererFactory {\n delegate;\n engine;\n _zone;\n _currentId = 0;\n _microtaskId = 1;\n _animationCallbacksBuffer = [];\n _rendererCache = /*#__PURE__*/new Map();\n _cdRecurDepth = 0;\n constructor(delegate, engine, _zone) {\n this.delegate = delegate;\n this.engine = engine;\n this._zone = _zone;\n engine.onRemovalComplete = (element, delegate) => {\n delegate?.removeChild(null, element);\n };\n }\n createRenderer(hostElement, type) {\n const EMPTY_NAMESPACE_ID = '';\n // cache the delegates to find out which cached delegate can\n // be used by which cached renderer\n const delegate = this.delegate.createRenderer(hostElement, type);\n if (!hostElement || !type?.data?.['animation']) {\n const cache = this._rendererCache;\n let renderer = cache.get(delegate);\n if (!renderer) {\n // Ensure that the renderer is removed from the cache on destroy\n // since it may contain references to detached DOM nodes.\n const onRendererDestroy = () => cache.delete(delegate);\n renderer = new BaseAnimationRenderer(EMPTY_NAMESPACE_ID, delegate, this.engine, onRendererDestroy);\n // only cache this result when the base renderer is used\n cache.set(delegate, renderer);\n }\n return renderer;\n }\n const componentId = type.id;\n const namespaceId = type.id + '-' + this._currentId;\n this._currentId++;\n this.engine.register(namespaceId, hostElement);\n const registerTrigger = trigger => {\n if (Array.isArray(trigger)) {\n trigger.forEach(registerTrigger);\n } else {\n this.engine.registerTrigger(componentId, namespaceId, hostElement, trigger.name, trigger);\n }\n };\n const animationTriggers = type.data['animation'];\n animationTriggers.forEach(registerTrigger);\n return new AnimationRenderer(this, namespaceId, delegate, this.engine);\n }\n begin() {\n this._cdRecurDepth++;\n if (this.delegate.begin) {\n this.delegate.begin();\n }\n }\n _scheduleCountTask() {\n queueMicrotask(() => {\n this._microtaskId++;\n });\n }\n /** @internal */\n scheduleListenerCallback(count, fn, data) {\n if (count >= 0 && count < this._microtaskId) {\n this._zone.run(() => fn(data));\n return;\n }\n const animationCallbacksBuffer = this._animationCallbacksBuffer;\n if (animationCallbacksBuffer.length == 0) {\n queueMicrotask(() => {\n this._zone.run(() => {\n animationCallbacksBuffer.forEach(tuple => {\n const [fn, data] = tuple;\n fn(data);\n });\n this._animationCallbacksBuffer = [];\n });\n });\n }\n animationCallbacksBuffer.push([fn, data]);\n }\n end() {\n this._cdRecurDepth--;\n // this is to prevent animations from running twice when an inner\n // component does CD when a parent component instead has inserted it\n if (this._cdRecurDepth == 0) {\n this._zone.runOutsideAngular(() => {\n this._scheduleCountTask();\n this.engine.flush(this._microtaskId);\n });\n }\n if (this.delegate.end) {\n this.delegate.end();\n }\n }\n whenRenderingDone() {\n return this.engine.whenRenderingDone();\n }\n /**\n * Used during HMR to clear any cached data about a component.\n * @param componentId ID of the component that is being replaced.\n */\n componentReplaced(componentId) {\n // Flush the engine since the renderer destruction waits for animations to be done.\n this.engine.flush();\n this.delegate.componentReplaced?.(componentId);\n }\n}\nexport { AnimationDriver, NoopAnimationDriver, Animation as ɵAnimation, AnimationEngine as ɵAnimationEngine, AnimationRenderer as ɵAnimationRenderer, AnimationRendererFactory as ɵAnimationRendererFactory, AnimationStyleNormalizer as ɵAnimationStyleNormalizer, BaseAnimationRenderer as ɵBaseAnimationRenderer, NoopAnimationStyleNormalizer as ɵNoopAnimationStyleNormalizer, WebAnimationsDriver as ɵWebAnimationsDriver, WebAnimationsPlayer as ɵWebAnimationsPlayer, WebAnimationsStyleNormalizer as ɵWebAnimationsStyleNormalizer, allowPreviousPlayerStylesMerge as ɵallowPreviousPlayerStylesMerge, camelCaseToDashCase as ɵcamelCaseToDashCase, containsElement as ɵcontainsElement, createEngine as ɵcreateEngine, getParentElement as ɵgetParentElement, invokeQuery as ɵinvokeQuery, normalizeKeyframes$1 as ɵnormalizeKeyframes, validateStyleProperty as ɵvalidateStyleProperty, validateWebAnimatableStyleProperty as ɵvalidateWebAnimatableStyleProperty };\n","/**\n * @license Angular v19.2.5\n * (c) 2010-2025 Google LLC. https://angular.io/\n * License: MIT\n */\n\nimport * as i0 from '@angular/core';\nimport { ANIMATION_MODULE_TYPE, NgZone, RendererFactory2, Inject, Injectable, ɵperformanceMarkFeature as _performanceMarkFeature, NgModule } from '@angular/core';\nexport { ANIMATION_MODULE_TYPE } from '@angular/core';\nimport * as i1 from '@angular/animations/browser';\nimport { NoopAnimationDriver, AnimationDriver, ɵAnimationStyleNormalizer as _AnimationStyleNormalizer, ɵAnimationEngine as _AnimationEngine, ɵWebAnimationsDriver as _WebAnimationsDriver, ɵWebAnimationsStyleNormalizer as _WebAnimationsStyleNormalizer, ɵAnimationRendererFactory as _AnimationRendererFactory } from '@angular/animations/browser';\nimport { DOCUMENT } from '@angular/common';\nimport { D as DomRendererFactory2 } from './dom_renderer-B-2OOwSx.mjs';\nimport { B as BrowserModule } from './browser-6JTYoVGl.mjs';\nlet InjectableAnimationEngine = /*#__PURE__*/(() => {\n class InjectableAnimationEngine extends _AnimationEngine {\n // The `ApplicationRef` is injected here explicitly to force the dependency ordering.\n // Since the `ApplicationRef` should be created earlier before the `AnimationEngine`, they\n // both have `ngOnDestroy` hooks and `flush()` must be called after all views are destroyed.\n constructor(doc, driver, normalizer) {\n super(doc, driver, normalizer);\n }\n ngOnDestroy() {\n this.flush();\n }\n static ɵfac = function InjectableAnimationEngine_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || InjectableAnimationEngine)(i0.ɵɵinject(DOCUMENT), i0.ɵɵinject(i1.AnimationDriver), i0.ɵɵinject(i1.ɵAnimationStyleNormalizer));\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: InjectableAnimationEngine,\n factory: InjectableAnimationEngine.ɵfac\n });\n }\n return InjectableAnimationEngine;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nfunction instantiateDefaultStyleNormalizer() {\n return new _WebAnimationsStyleNormalizer();\n}\nfunction instantiateRendererFactory(renderer, engine, zone) {\n return new _AnimationRendererFactory(renderer, engine, zone);\n}\nconst SHARED_ANIMATION_PROVIDERS = [{\n provide: _AnimationStyleNormalizer,\n useFactory: instantiateDefaultStyleNormalizer\n}, {\n provide: _AnimationEngine,\n useClass: InjectableAnimationEngine\n}, {\n provide: RendererFactory2,\n useFactory: instantiateRendererFactory,\n deps: [DomRendererFactory2, _AnimationEngine, NgZone]\n}];\n/**\n * Separate providers from the actual module so that we can do a local modification in Google3 to\n * include them in the BrowserTestingModule.\n */\nconst BROWSER_NOOP_ANIMATIONS_PROVIDERS = [{\n provide: AnimationDriver,\n useClass: NoopAnimationDriver\n}, {\n provide: ANIMATION_MODULE_TYPE,\n useValue: 'NoopAnimations'\n}, ...SHARED_ANIMATION_PROVIDERS];\n/**\n * Separate providers from the actual module so that we can do a local modification in Google3 to\n * include them in the BrowserModule.\n */\nconst BROWSER_ANIMATIONS_PROVIDERS = [\n// Note: the `ngServerMode` happen inside factories to give the variable time to initialize.\n{\n provide: AnimationDriver,\n useFactory: () => typeof ngServerMode !== 'undefined' && ngServerMode ? new NoopAnimationDriver() : new _WebAnimationsDriver()\n}, {\n provide: ANIMATION_MODULE_TYPE,\n useFactory: () => typeof ngServerMode !== 'undefined' && ngServerMode ? 'NoopAnimations' : 'BrowserAnimations'\n}, ...SHARED_ANIMATION_PROVIDERS];\n\n/**\n * Exports `BrowserModule` with additional dependency-injection providers\n * for use with animations. See [Animations](guide/animations).\n * @publicApi\n */\nlet BrowserAnimationsModule = /*#__PURE__*/(() => {\n class BrowserAnimationsModule {\n /**\n * Configures the module based on the specified object.\n *\n * @param config Object used to configure the behavior of the `BrowserAnimationsModule`.\n * @see {@link BrowserAnimationsModuleConfig}\n *\n * @usageNotes\n * When registering the `BrowserAnimationsModule`, you can use the `withConfig`\n * function as follows:\n * ```ts\n * @NgModule({\n * imports: [BrowserAnimationsModule.withConfig(config)]\n * })\n * class MyNgModule {}\n * ```\n */\n static withConfig(config) {\n return {\n ngModule: BrowserAnimationsModule,\n providers: config.disableAnimations ? BROWSER_NOOP_ANIMATIONS_PROVIDERS : BROWSER_ANIMATIONS_PROVIDERS\n };\n }\n static ɵfac = function BrowserAnimationsModule_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || BrowserAnimationsModule)();\n };\n static ɵmod = /* @__PURE__ */i0.ɵɵdefineNgModule({\n type: BrowserAnimationsModule\n });\n static ɵinj = /* @__PURE__ */i0.ɵɵdefineInjector({\n providers: BROWSER_ANIMATIONS_PROVIDERS,\n imports: [BrowserModule]\n });\n }\n return BrowserAnimationsModule;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * Returns the set of dependency-injection providers\n * to enable animations in an application. See [animations guide](guide/animations)\n * to learn more about animations in Angular.\n *\n * @usageNotes\n *\n * The function is useful when you want to enable animations in an application\n * bootstrapped using the `bootstrapApplication` function. In this scenario there\n * is no need to import the `BrowserAnimationsModule` NgModule at all, just add\n * providers returned by this function to the `providers` list as show below.\n *\n * ```ts\n * bootstrapApplication(RootComponent, {\n * providers: [\n * provideAnimations()\n * ]\n * });\n * ```\n *\n * @publicApi\n */\nfunction provideAnimations() {\n _performanceMarkFeature('NgEagerAnimations');\n // Return a copy to prevent changes to the original array in case any in-place\n // alterations are performed to the `provideAnimations` call results in app code.\n return [...BROWSER_ANIMATIONS_PROVIDERS];\n}\n/**\n * A null player that must be imported to allow disabling of animations.\n * @publicApi\n */\nlet NoopAnimationsModule = /*#__PURE__*/(() => {\n class NoopAnimationsModule {\n static ɵfac = function NoopAnimationsModule_Factory(__ngFactoryType__) {\n return new (__ngFactoryType__ || NoopAnimationsModule)();\n };\n static ɵmod = /* @__PURE__ */i0.ɵɵdefineNgModule({\n type: NoopAnimationsModule\n });\n static ɵinj = /* @__PURE__ */i0.ɵɵdefineInjector({\n providers: BROWSER_NOOP_ANIMATIONS_PROVIDERS,\n imports: [BrowserModule]\n });\n }\n return NoopAnimationsModule;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * Returns the set of dependency-injection providers\n * to disable animations in an application. See [animations guide](guide/animations)\n * to learn more about animations in Angular.\n *\n * @usageNotes\n *\n * The function is useful when you want to bootstrap an application using\n * the `bootstrapApplication` function, but you need to disable animations\n * (for example, when running tests).\n *\n * ```ts\n * bootstrapApplication(RootComponent, {\n * providers: [\n * provideNoopAnimations()\n * ]\n * });\n * ```\n *\n * @publicApi\n */\nfunction provideNoopAnimations() {\n // Return a copy to prevent changes to the original array in case any in-place\n // alterations are performed to the `provideNoopAnimations` call results in app code.\n return [...BROWSER_NOOP_ANIMATIONS_PROVIDERS];\n}\nexport { BrowserAnimationsModule, NoopAnimationsModule, provideAnimations, provideNoopAnimations, InjectableAnimationEngine as ɵInjectableAnimationEngine };\n","import { enableProdMode, ErrorHandler, importProvidersFrom } from '@angular/core';\r\nimport { bootstrapApplication } from '@angular/platform-browser';\r\nimport { PreloadAllModules, provideRouter, withPreloading } from '@angular/router';\r\nimport { withInterceptorsFromDi, provideHttpClient } from '@angular/common/http';\r\nimport { provideAnimations } from '@angular/platform-browser/animations';\r\nimport 'hammerjs';\r\n\r\nimport { environment } from './environments/environment';\r\nimport { AppComponent } from './app/app.component';\r\nimport { APP_ROUTES } from './app/app-routes';\r\nimport { ErrorHandlerService } from './app/core/services/error-handler.service';\r\nimport { LoggingService } from './app/core/services/logging.service';\r\nimport { SharedModule } from './app/shared/shared.module';\r\n\r\nif (environment.production) {\r\n enableProdMode();\r\n}\r\n\r\nbootstrapApplication(AppComponent, {\r\n providers: [\r\n importProvidersFrom(\r\n SharedModule\r\n ),\r\n {\r\n provide: ErrorHandler,\r\n useClass: ErrorHandlerService\r\n },\r\n provideAnimations(),\r\n provideHttpClient(\r\n withInterceptorsFromDi()\r\n ),\r\n provideRouter(\r\n APP_ROUTES,\r\n withPreloading(PreloadAllModules)\r\n ),\r\n LoggingService\r\n ]\r\n});\r\n","/*! https://github.com/nevware21/ts-utils v0.11.8 */\n/*\n * Copyright (c) NevWare21 Solutions LLC and contributors. All rights reserved.\n * Licensed under the MIT license.\n */\n/*#__NO_SIDE_EFFECTS__*/\nfunction _pureAssign(func1, func2) {\n return func1 || func2;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction _pureRef(value, name) {\n return value[name];\n}\nvar UNDEF_VALUE = undefined;\nvar NULL_VALUE = null;\nvar EMPTY = \"\";\nvar FUNCTION = \"function\";\nvar OBJECT = \"object\";\nvar PROTOTYPE = \"prototype\";\nvar __PROTO__ = \"__proto__\";\nvar UNDEFINED = \"undefined\";\nvar CONSTRUCTOR = \"constructor\";\nvar SYMBOL = \"Symbol\";\nvar POLYFILL_TAG = \"_polyfill\";\nvar LENGTH = \"length\";\nvar NAME = \"name\";\nvar CALL = \"call\";\nvar TO_STRING = \"toString\";\nvar ObjClass = /*#__PURE__*/_pureAssign(Object);\nvar ObjProto = /*#__PURE__*/_pureRef(ObjClass, PROTOTYPE);\nvar StrCls = /*#__PURE__*/_pureAssign(String);\nvar StrProto = /*#__PURE__*/_pureRef(StrCls, PROTOTYPE);\nvar MathCls = /*#__PURE__*/_pureAssign(Math);\nvar ArrCls = /*#__PURE__*/_pureAssign(Array);\nvar ArrProto = /*#__PURE__*/_pureRef(ArrCls, PROTOTYPE);\nvar ArrSlice = /*#__PURE__*/_pureRef(ArrProto, \"slice\");\nfunction safe(func, argArray) {\n try {\n return {\n v: func.apply(this, argArray)\n };\n } catch (e) {\n return {\n e: e\n };\n }\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction safeGet(cb, defValue) {\n var result = safe(cb);\n return result.e ? defValue : result.v;\n}\nvar _primitiveTypes;\n/*#__NO_SIDE_EFFECTS__*/\nfunction _createIs(theType) {\n return function (value) {\n return typeof value === theType;\n };\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction _createObjIs(theName) {\n var theType = \"[object \" + theName + \"]\";\n return function (value) {\n return !!(value && objToString(value) === theType);\n };\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction objToString(value) {\n return ObjProto[TO_STRING].call(value);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction isTypeof(value, theType) {\n return typeof value === theType;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction isUndefined(value) {\n return typeof value === UNDEFINED || value === UNDEFINED;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction isStrictUndefined(arg) {\n return !isDefined(arg);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction isNullOrUndefined(value) {\n return value === NULL_VALUE || isUndefined(value);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction isStrictNullOrUndefined(value) {\n return value === NULL_VALUE || !isDefined(value);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction isDefined(arg) {\n return !!arg || arg !== UNDEF_VALUE;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction isPrimitive(value) {\n return value === NULL_VALUE || isPrimitiveType(typeof value);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction isPrimitiveType(theType) {\n !_primitiveTypes && (_primitiveTypes = [\"string\", \"number\", \"boolean\", UNDEFINED, \"symbol\", \"bigint\"]);\n return !!(theType !== OBJECT && _primitiveTypes.indexOf(theType) !== -1);\n}\nvar isString = /*#__PURE__*/_createIs(\"string\");\nvar isFunction = /*#__PURE__*/_createIs(FUNCTION);\n/*#__NO_SIDE_EFFECTS__*/\nfunction isObject(value) {\n if (!value && isNullOrUndefined(value)) {\n return false;\n }\n return !!value && typeof value === OBJECT;\n}\nvar isArray = /* #__PURE__*/_pureRef(ArrCls, \"isArray\");\nvar isDate = /*#__PURE__*/_createObjIs(\"Date\");\nvar isNumber = /*#__PURE__*/_createIs(\"number\");\nvar isBoolean = /*#__PURE__*/_createIs(\"boolean\");\nvar isRegExp = /*#__PURE__*/_createObjIs(\"RegExp\");\nvar isFile = /*#__PURE__*/_createObjIs(\"File\");\nvar isFormData = /*#__PURE__*/_createObjIs(\"FormData\");\nvar isBlob = /*#__PURE__*/_createObjIs(\"Blob\");\nvar isArrayBuffer = /*#__PURE__*/_createObjIs(\"ArrayBuffer\");\nvar isError = /*#__PURE__*/_createObjIs(\"Error\");\n/*#__NO_SIDE_EFFECTS__*/\nfunction isPromiseLike(value) {\n return !!(value && value.then && isFunction(value.then));\n}\nvar isThenable = isPromiseLike;\n/*#__NO_SIDE_EFFECTS__*/\nfunction isPromise(value) {\n return !!(value && value.then && value.catch && isFunction(value.then) && isFunction(value.catch));\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction isNotTruthy(value) {\n return !value || !isTruthy(value);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction isTruthy(value) {\n return !(!value || safeGet(function () {\n return !(value && 0 + value);\n }, !value));\n}\nvar objGetOwnPropertyDescriptor = /* #__PURE__ */_pureRef(ObjClass, \"getOwnPropertyDescriptor\");\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction objHasOwnProperty(obj, prop) {\n return !!obj && ObjProto.hasOwnProperty[CALL](obj, prop);\n}\nvar objHasOwn = /*#__PURE__*/_pureAssign(/* #__PURE__ */_pureRef(ObjClass, \"hasOwn\"), polyObjHasOwn);\n/*#__NO_SIDE_EFFECTS__*/\nfunction polyObjHasOwn(obj, prop) {\n return objHasOwnProperty(obj, prop) || !!objGetOwnPropertyDescriptor(obj, prop);\n}\nfunction objForEachKey(theObject, callbackfn, thisArg) {\n if (theObject && isObject(theObject)) {\n for (var prop in theObject) {\n if (objHasOwn(theObject, prop)) {\n if (callbackfn[CALL](thisArg || theObject, prop, theObject[prop]) === -1) {\n break;\n }\n }\n }\n }\n}\nvar propMap = {\n e: \"enumerable\",\n c: \"configurable\",\n v: \"value\",\n w: \"writable\",\n g: \"get\",\n s: \"set\"\n};\n/*#__NO_SIDE_EFFECTS__*/\nfunction _createProp(value) {\n var prop = {};\n prop[propMap[\"c\"]] = true;\n prop[propMap[\"e\"]] = true;\n if (value.l) {\n prop.get = function () {\n return value.l.v;\n };\n var desc = objGetOwnPropertyDescriptor(value.l, \"v\");\n if (desc && desc.set) {\n prop.set = function (newValue) {\n value.l.v = newValue;\n };\n }\n }\n objForEachKey(value, function (key, value) {\n prop[propMap[key]] = isStrictUndefined(value) ? prop[propMap[key]] : value;\n });\n return prop;\n}\nvar objDefineProp = /*#__PURE__*/_pureRef(ObjClass, \"defineProperty\");\nvar objDefineProperties = /*#__PURE__*/_pureRef(ObjClass, \"defineProperties\");\nfunction objDefineGet(target, key, value, configurable, enumerable) {\n var _a;\n return objDefineProp(target, key, _createProp((_a = {\n e: enumerable,\n c: configurable\n }, _a[isFunction(value) ? \"g\" : \"v\"] = value, _a)));\n}\nfunction objDefineAccessors(target, prop, getProp, setProp, configurable, enumerable) {\n var desc = {\n e: enumerable,\n c: configurable\n };\n if (getProp) {\n desc.g = getProp;\n }\n if (setProp) {\n desc.s = setProp;\n }\n return objDefineProp(target, prop, _createProp(desc));\n}\nfunction objDefine(target, key, propDesc) {\n return objDefineProp(target, key, _createProp(propDesc));\n}\nfunction objDefineProps(target, propDescMap) {\n var props = {};\n objForEachKey(propDescMap, function (key, value) {\n props[key] = _createProp(value);\n });\n return objDefineProperties(target, props);\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction _createKeyValueMap(values, keyType, valueType, completeFn, writable) {\n var theMap = {};\n objForEachKey(values, function (key, value) {\n _assignMapValue(theMap, key, keyType ? value : key);\n _assignMapValue(theMap, value, valueType ? value : key);\n });\n return completeFn ? completeFn(theMap) : theMap;\n}\nfunction _assignMapValue(theMap, key, value, writable) {\n objDefineProp(theMap, key, {\n value: value,\n enumerable: true,\n writable: false\n });\n}\nvar asString = /* #__PURE__ */_pureAssign(StrCls);\nvar ERROR_TYPE = \"[object Error]\";\n/*#__NO_SIDE_EFFECTS__*/\nfunction dumpObj(object, format) {\n var propertyValueDump = EMPTY;\n var objType = ObjProto[TO_STRING][CALL](object);\n if (objType === ERROR_TYPE) {\n object = {\n stack: asString(object.stack),\n message: asString(object.message),\n name: asString(object.name)\n };\n }\n try {\n propertyValueDump = JSON.stringify(object, NULL_VALUE, format ? typeof format === \"number\" ? format : 4 : UNDEF_VALUE);\n propertyValueDump = (propertyValueDump ? propertyValueDump.replace(/\"(\\w+)\"\\s*:\\s{0,1}/g, \"$1: \") : NULL_VALUE) || asString(object);\n } catch (e) {\n propertyValueDump = \" - \" + dumpObj(e, format);\n }\n return objType + \": \" + propertyValueDump;\n}\nfunction throwError(message) {\n throw new Error(message);\n}\nfunction throwTypeError(message) {\n throw new TypeError(message);\n}\nfunction throwRangeError(message) {\n throw new RangeError(message);\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction polyObjKeys(obj) {\n if (!isObject(obj) || obj === NULL_VALUE) {\n throwTypeError(\"non-object \" + dumpObj(obj));\n }\n var result = [];\n for (var prop in obj) {\n if (objHasOwn(obj, prop)) {\n result.push(prop);\n }\n }\n return result;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction polyObjEntries(value) {\n var result = [];\n objForEachKey(value, function (key, value) {\n result.push([key, value]);\n });\n return result;\n}\nvar _objFreeze = /* #__PURE__ */_pureRef(ObjClass, \"freeze\");\nfunction _doNothing(value) {\n return value;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction _getProto(value) {\n return value[__PROTO__] || NULL_VALUE;\n}\nvar objAssign = /*#__PURE__*/_pureRef(ObjClass, \"assign\");\nvar objKeys = /*#__PURE__*/_pureRef(ObjClass, \"keys\");\nfunction objDeepFreeze(value) {\n if (_objFreeze) {\n objForEachKey(value, function (key, value) {\n if (isArray(value) || isObject(value)) {\n objDeepFreeze(value);\n }\n });\n }\n return objFreeze(value);\n}\nvar objFreeze = /* #__PURE__*/_pureAssign(_objFreeze, _doNothing);\nvar objSeal = /* #__PURE__*/_pureAssign(/* #__PURE__*/_pureRef(ObjClass, \"seal\"), _doNothing);\nvar objGetPrototypeOf = /* #__PURE__*/_pureAssign(/* #__PURE__*/_pureRef(ObjClass, \"getPrototypeOf\"), _getProto);\nvar objEntries = /* #__PURE__*/_pureAssign(/* #__PURE__*/_pureRef(ObjClass, \"entries\"), polyObjEntries);\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction createEnum(values) {\n return _createKeyValueMap(values, 1, 0, objFreeze);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction createEnumKeyMap(values) {\n return _createKeyValueMap(values, 0, 0, objFreeze);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction createEnumValueMap(values) {\n return _createKeyValueMap(values, 1, 1, objFreeze);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction createSimpleMap(values) {\n var mapClass = {};\n objForEachKey(values, function (key, value) {\n _assignMapValue(mapClass, key, value[1]);\n _assignMapValue(mapClass, value[0], value[1]);\n });\n return objFreeze(mapClass);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction createTypeMap(values) {\n return createSimpleMap(values);\n}\nvar _wellKnownSymbolMap = /*#__PURE__*/createEnumKeyMap({\n asyncIterator: 0,\n hasInstance: 1,\n isConcatSpreadable: 2,\n iterator: 3,\n match: 4,\n matchAll: 5,\n replace: 6,\n search: 7,\n species: 8,\n split: 9,\n toPrimitive: 10,\n toStringTag: 11,\n unscopables: 12\n});\nvar GLOBAL_CONFIG_KEY = \"__tsUtils$gblCfg\";\nvar _globalCfg;\n/*#__NO_SIDE_EFFECTS__*/\nfunction _getGlobalValue() {\n var result;\n if (typeof globalThis !== UNDEFINED) {\n result = globalThis;\n }\n if (!result && typeof self !== UNDEFINED) {\n result = self;\n }\n if (!result && typeof window !== UNDEFINED) {\n result = window;\n }\n if (!result && typeof global !== UNDEFINED) {\n result = global;\n }\n return result;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction _getGlobalConfig() {\n if (!_globalCfg) {\n var gbl = safe(_getGlobalValue).v || {};\n _globalCfg = gbl[GLOBAL_CONFIG_KEY] = gbl[GLOBAL_CONFIG_KEY] || {};\n }\n return _globalCfg;\n}\nvar _unwrapFunction = _unwrapFunctionWithPoly;\n/*#__NO_SIDE_EFFECTS__*/\nfunction _unwrapFunctionWithPoly(funcName, clsProto, polyFunc) {\n var clsFn = clsProto ? clsProto[funcName] : NULL_VALUE;\n return function (thisArg) {\n var theFunc = (thisArg ? thisArg[funcName] : NULL_VALUE) || clsFn;\n if (theFunc || polyFunc) {\n var theArgs = arguments;\n return (theFunc || polyFunc).apply(thisArg, theFunc ? ArrSlice[CALL](theArgs, 1) : theArgs);\n }\n throwTypeError(\"\\\"\" + asString(funcName) + \"\\\" not defined for \" + dumpObj(thisArg));\n };\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction _unwrapProp(propName) {\n return function (thisArg) {\n return thisArg[propName];\n };\n}\nvar mathMin = /*#__PURE__*/_pureRef(MathCls, \"min\");\nvar mathMax = /*#__PURE__*/_pureRef(MathCls, \"max\");\nvar strSlice = /*#__PURE__*/_unwrapFunction(\"slice\", StrProto);\nvar strSubstring = /*#__PURE__*/_unwrapFunction(\"substring\", StrProto);\nvar strSubstr = /*#__PURE__*/_unwrapFunctionWithPoly(\"substr\", StrProto, polyStrSubstr);\n/*#__NO_SIDE_EFFECTS__*/\nfunction polyStrSubstr(value, start, length) {\n if (isNullOrUndefined(value)) {\n throwTypeError(\"Invalid \" + dumpObj(value));\n }\n if (length < 0) {\n return EMPTY;\n }\n start = start || 0;\n if (start < 0) {\n start = mathMax(start + value[LENGTH], 0);\n }\n if (isUndefined(length)) {\n return strSlice(value, start);\n }\n return strSlice(value, start, start + length);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction strLeft(value, count) {\n return strSubstring(value, 0, count);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction strRight(value, count) {\n return count <= 0 ? EMPTY : value[LENGTH] > count ? strSlice(value, -count) : value;\n}\nvar UNIQUE_REGISTRY_ID = \"_urid\";\nvar _polySymbols;\n/*#__NO_SIDE_EFFECTS__*/\nfunction _globalSymbolRegistry() {\n if (!_polySymbols) {\n var gblCfg = _getGlobalConfig();\n _polySymbols = gblCfg.gblSym = gblCfg.gblSym || {\n k: {},\n s: {}\n };\n }\n return _polySymbols;\n}\nvar _wellKnownSymbolCache;\n/*#__NO_SIDE_EFFECTS__*/\nfunction polyNewSymbol(description) {\n var theSymbol = {\n description: asString(description),\n toString: function () {\n return SYMBOL + \"(\" + description + \")\";\n }\n };\n theSymbol[POLYFILL_TAG] = true;\n return theSymbol;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction polySymbolFor(key) {\n var registry = _globalSymbolRegistry();\n if (!objHasOwn(registry.k, key)) {\n var newSymbol_1 = polyNewSymbol(key);\n var regId_1 = objKeys(registry.s).length;\n newSymbol_1[UNIQUE_REGISTRY_ID] = function () {\n return regId_1 + \"_\" + newSymbol_1[TO_STRING]();\n };\n registry.k[key] = newSymbol_1;\n registry.s[newSymbol_1[UNIQUE_REGISTRY_ID]()] = asString(key);\n }\n return registry.k[key];\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction polySymbolKeyFor(sym) {\n if (!sym || !sym[TO_STRING] || strSubstring(sym[TO_STRING](), 0, 6) != SYMBOL) {\n throwTypeError(sym + \" is not a symbol\");\n }\n var regId = sym[POLYFILL_TAG] && sym[UNIQUE_REGISTRY_ID] && sym[UNIQUE_REGISTRY_ID]();\n return regId ? _globalSymbolRegistry().s[regId] : undefined;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction polyGetKnownSymbol(name) {\n !_wellKnownSymbolCache && (_wellKnownSymbolCache = {});\n var result;\n var knownName = _wellKnownSymbolMap[name];\n if (knownName) {\n result = _wellKnownSymbolCache[knownName] = _wellKnownSymbolCache[knownName] || polyNewSymbol(SYMBOL + \".\" + knownName);\n }\n return result;\n}\nvar _globalLazyTestHooks;\nfunction _initTestHooks() {\n _globalLazyTestHooks = _getGlobalConfig();\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction getLazy(cb) {\n var lazyValue = {};\n !_globalLazyTestHooks && _initTestHooks();\n lazyValue.b = _globalLazyTestHooks.lzy;\n objDefineProp(lazyValue, \"v\", {\n configurable: true,\n get: function () {\n var result = cb();\n if (!_globalLazyTestHooks.lzy) {\n objDefineProp(lazyValue, \"v\", {\n value: result\n });\n }\n lazyValue.b = _globalLazyTestHooks.lzy;\n return result;\n }\n });\n return lazyValue;\n}\nfunction setBypassLazyCache(newValue) {\n !_globalLazyTestHooks && _initTestHooks();\n _globalLazyTestHooks.lzy = newValue;\n}\nfunction getWritableLazy(cb) {\n var lazyValue = {};\n !_globalLazyTestHooks && _initTestHooks();\n lazyValue.b = _globalLazyTestHooks.lzy;\n var _setValue = function (newValue) {\n objDefineProp(lazyValue, \"v\", {\n value: newValue,\n writable: true\n });\n if (lazyValue.b) {\n delete lazyValue.b;\n }\n };\n objDefineProp(lazyValue, \"v\", {\n configurable: true,\n get: function () {\n var result = cb();\n if (!_globalLazyTestHooks.lzy) {\n _setValue(result);\n }\n if (_globalLazyTestHooks.lzy && lazyValue.b !== _globalLazyTestHooks.lzy) {\n lazyValue.b = _globalLazyTestHooks.lzy;\n }\n return result;\n },\n set: _setValue\n });\n return lazyValue;\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction createCachedValue(value) {\n return objDefineProp({\n toJSON: function () {\n return value;\n }\n }, \"v\", {\n value: value\n });\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction createDeferredCachedValue(cb) {\n var theValue = {\n toJSON: function () {\n return theValue.v;\n }\n };\n return objDefineProp(theValue, \"v\", {\n get: function () {\n var result = cb();\n cb = NULL_VALUE;\n objDefineProp(theValue, \"v\", {\n value: result\n });\n return result;\n },\n configurable: true\n });\n}\nvar WINDOW = \"window\";\nvar _cachedGlobal;\nfunction _getGlobalInstFn(getFn, theArgs) {\n var cachedValue;\n return function () {\n !_globalLazyTestHooks && _initTestHooks();\n if (!cachedValue || _globalLazyTestHooks.lzy) {\n cachedValue = createCachedValue(safe(getFn, theArgs).v);\n }\n return cachedValue.v;\n };\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction lazySafeGetInst(name) {\n return getLazy(function () {\n return safe(getInst, [name]).v || UNDEF_VALUE;\n });\n}\nfunction getGlobal(useCached) {\n !_globalLazyTestHooks && _initTestHooks();\n if (!_cachedGlobal || useCached === false || _globalLazyTestHooks.lzy) {\n _cachedGlobal = createCachedValue(safe(_getGlobalValue).v || NULL_VALUE);\n }\n return _cachedGlobal.v;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction getInst(name, useCached) {\n var gbl;\n if (!_cachedGlobal || useCached === false) {\n gbl = getGlobal(useCached);\n } else {\n gbl = _cachedGlobal.v;\n }\n if (gbl && gbl[name]) {\n return gbl[name];\n }\n if (name === WINDOW) {\n try {\n return window;\n } catch (e) {}\n }\n return NULL_VALUE;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction hasDocument() {\n return !!(/*#__PURE__*/getDocument());\n}\nvar getDocument = /*#__PURE__*/_getGlobalInstFn(getInst, [\"document\"]);\n/*#__NO_SIDE_EFFECTS__*/\nfunction hasWindow() {\n return !!(/*#__PURE__*/getWindow());\n}\nvar getWindow = /*#__PURE__*/_getGlobalInstFn(getInst, [WINDOW]);\n/*#__NO_SIDE_EFFECTS__*/\nfunction hasNavigator() {\n return !!(/*#__PURE__*/getNavigator());\n}\nvar getNavigator = /*#__PURE__*/_getGlobalInstFn(getInst, [\"navigator\"]);\n/*#__NO_SIDE_EFFECTS__*/\nfunction hasHistory() {\n return !!(/*#__PURE__*/getHistory());\n}\nvar getHistory = /*#__PURE__*/_getGlobalInstFn(getInst, [\"history\"]);\nvar isNode = /*#__PURE__*/_getGlobalInstFn(function () {\n return !!(/*#__PURE__*/safe(function () {\n return process && (process.versions || {}).node;\n }).v);\n});\nvar isWebWorker = /*#__PURE__*/_getGlobalInstFn(function () {\n return !!(/*#__PURE__*/safe(function () {\n return self && self instanceof WorkerGlobalScope;\n }).v);\n});\nvar _symbol;\nvar _symbolFor;\nvar _symbolKeyFor;\n/*#__NO_SIDE_EFFECTS__*/\nfunction _initSymbol() {\n _symbol = /*#__PURE__*/createCachedValue(safe(getInst, [SYMBOL]).v);\n return _symbol;\n}\nfunction _getSymbolKey(key) {\n var gblSym = (!_globalLazyTestHooks.lzy ? _symbol : 0) || _initSymbol();\n return gblSym.v ? gblSym.v[key] : UNDEF_VALUE;\n}\nvar isSymbol = /*#__PURE__*/_createIs(\"symbol\");\n/*#__NO_SIDE_EFFECTS__*/\nfunction hasSymbol() {\n return !!(/*#__PURE__*/getSymbol());\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction getSymbol() {\n !_globalLazyTestHooks && _initTestHooks();\n return ((!_globalLazyTestHooks.lzy ? _symbol : 0) || _initSymbol()).v;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction getKnownSymbol(name, noPoly) {\n var knownName = _wellKnownSymbolMap[name];\n !_globalLazyTestHooks && _initTestHooks();\n var sym = (!_globalLazyTestHooks.lzy ? _symbol : 0) || _initSymbol();\n return sym.v ? sym.v[knownName || name] : !noPoly ? polyGetKnownSymbol(name) : UNDEF_VALUE;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction newSymbol(description, noPoly) {\n !_globalLazyTestHooks && _initTestHooks();\n var sym = (!_globalLazyTestHooks.lzy ? _symbol : 0) || _initSymbol();\n return sym.v ? sym.v(description) : !noPoly ? polyNewSymbol(description) : NULL_VALUE;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction symbolFor(key) {\n !_globalLazyTestHooks && _initTestHooks();\n _symbolFor = (!_globalLazyTestHooks.lzy ? _symbolFor : 0) || (/*#__PURE__*/createCachedValue(safe(_getSymbolKey, [\"for\"]).v));\n return (_symbolFor.v || polySymbolFor)(key);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction symbolKeyFor(sym) {\n !_globalLazyTestHooks && _initTestHooks();\n _symbolKeyFor = (!_globalLazyTestHooks.lzy ? _symbolKeyFor : 0) || (/*#__PURE__*/createCachedValue(safe(_getSymbolKey, [\"keyFor\"]).v));\n return (_symbolKeyFor.v || polySymbolKeyFor)(sym);\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction isIterator(value) {\n return !!value && isFunction(value.next);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction isIterable(value) {\n return !isStrictNullOrUndefined(value) && isFunction(value[getKnownSymbol(3)]);\n}\nvar _iterSymbol$1;\nfunction iterForOf(iter, callbackfn, thisArg) {\n if (iter) {\n if (!isIterator(iter)) {\n !_iterSymbol$1 && (_iterSymbol$1 = createCachedValue(getKnownSymbol(3)));\n iter = iter[_iterSymbol$1.v] ? iter[_iterSymbol$1.v]() : NULL_VALUE;\n }\n if (isIterator(iter)) {\n var err = UNDEF_VALUE;\n var iterResult = UNDEF_VALUE;\n try {\n var count = 0;\n while (!(iterResult = iter.next()).done) {\n if (callbackfn[CALL](thisArg || iter, iterResult.value, count, iter) === -1) {\n break;\n }\n count++;\n }\n } catch (failed) {\n err = {\n e: failed\n };\n if (iter.throw) {\n iterResult = NULL_VALUE;\n iter.throw(err);\n }\n } finally {\n try {\n if (iterResult && !iterResult.done) {\n iter.return && iter.return(iterResult);\n }\n } finally {\n if (err) {\n // eslint-disable-next-line no-unsafe-finally\n throw err.e;\n }\n }\n }\n }\n }\n}\nfunction fnApply(fn, thisArg, argArray) {\n return fn.apply(thisArg, argArray);\n}\nfunction fnCall(fn, thisArg) {\n return fn.apply(thisArg, ArrSlice[CALL](arguments, 2));\n}\nfunction fnBind(fn, thisArg) {\n return fn.bind.apply(fn, ArrSlice[CALL](arguments, 1));\n}\nfunction arrAppend(target, elms) {\n if (!isUndefined(elms) && target) {\n if (isArray(elms)) {\n fnApply(target.push, target, elms);\n } else if (isIterator(elms) || isIterable(elms)) {\n iterForOf(elms, function (elm) {\n target.push(elm);\n });\n } else {\n target.push(elms);\n }\n }\n return target;\n}\nvar arrEvery = /*#__PURE__*/_unwrapFunction(\"every\", ArrProto);\nvar arrFilter = /*#__PURE__*/_unwrapFunction(\"filter\", ArrProto);\nfunction arrForEach(theArray, callbackfn, thisArg) {\n if (theArray) {\n var len = theArray[LENGTH] >>> 0;\n for (var idx = 0; idx < len; idx++) {\n if (idx in theArray) {\n if (callbackfn[CALL](thisArg || theArray, theArray[idx], idx, theArray) === -1) {\n break;\n }\n }\n }\n }\n}\nvar arrIndexOf = /*#__PURE__*/_unwrapFunction(\"indexOf\", ArrProto);\nvar arrLastIndexOf = /*#__PURE__*/_unwrapFunction(\"lastIndexOf\", ArrProto);\nvar arrMap = /*#__PURE__*/_unwrapFunction(\"map\", ArrProto);\nfunction arrSlice(theArray, start, end) {\n return ((theArray ? theArray[\"slice\"] : NULL_VALUE) || ArrSlice).apply(theArray, ArrSlice[CALL](arguments, 1));\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction polyIsArray(value) {\n if (isNullOrUndefined(value)) {\n return false;\n }\n return objToString(value) === \"[object Array]\";\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction polyArrIncludes(theArray, searchElement, fromIndex) {\n return arrIndexOf(theArray, searchElement, fromIndex) !== -1;\n}\nfunction polyArrFind(theArray, callbackFn, thisArg) {\n var result;\n var idx = polyArrFindIndex(theArray, callbackFn, thisArg);\n return idx !== -1 ? theArray[idx] : result;\n}\nfunction polyArrFindIndex(theArray, callbackFn, thisArg) {\n var result = -1;\n arrForEach(theArray, function (value, index) {\n if (callbackFn[CALL](thisArg | theArray, value, index, theArray)) {\n result = index;\n return -1;\n }\n });\n return result;\n}\nfunction polyArrFindLast(theArray, callbackFn, thisArg) {\n var result;\n var idx = polyArrFindLastIndex(theArray, callbackFn, thisArg);\n return idx !== -1 ? theArray[idx] : result;\n}\nfunction polyArrFindLastIndex(theArray, callbackFn, thisArg) {\n var result = -1;\n var len = theArray[LENGTH] >>> 0;\n for (var idx = len - 1; idx >= 0; idx--) {\n if (idx in theArray && callbackFn[CALL](thisArg | theArray, theArray[idx], idx, theArray)) {\n result = idx;\n break;\n }\n }\n return result;\n}\nfunction polyArrFrom(theValue, mapFn, thisArg) {\n if (isArray(theValue)) {\n var result_1 = arrSlice(theValue);\n return mapFn ? arrMap(result_1, mapFn, thisArg) : result_1;\n }\n var result = [];\n iterForOf(theValue, function (value, cnt) {\n return result.push(mapFn ? mapFn[CALL](thisArg, value, cnt) : value);\n });\n return result;\n}\nvar arrFind = /*#__PURE__*/_unwrapFunctionWithPoly(\"find\", ArrProto, polyArrFind);\nvar arrFindIndex = /*#__PURE__*/_unwrapFunctionWithPoly(\"findIndex\", ArrProto, polyArrFindIndex);\nvar arrFindLast = /*#__PURE__*/_unwrapFunctionWithPoly(\"findLast\", ArrProto, polyArrFindLast);\nvar arrFindLastIndex = /*#__PURE__*/_unwrapFunctionWithPoly(\"findLastIndex\", ArrProto, polyArrFindLastIndex);\nvar arrFrom = /* #__PURE__*/_pureAssign(/* #__PURE__*/_pureRef(ArrCls, \"from\"), polyArrFrom);\nvar arrIncludes = /*#__PURE__*/_unwrapFunctionWithPoly(\"includes\", ArrProto, polyArrIncludes);\nvar arrContains = arrIncludes;\nvar arrReduce = /*#__PURE__*/_unwrapFunction(\"reduce\", ArrProto);\nvar arrSome = /*#__PURE__*/_unwrapFunction(\"some\", ArrProto);\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction createFnDeferredProxy(hostFn, funcName) {\n return function () {\n var theArgs = ArrSlice[CALL](arguments);\n var theHost = hostFn();\n return fnApply(theHost[funcName], theHost, theArgs);\n };\n}\nfunction createProxyFuncs(target, host, funcDefs) {\n if (target && host && isArray(funcDefs)) {\n var isDeferred_1 = isFunction(host);\n arrForEach(funcDefs, function (funcDef) {\n var targetName = funcDef.as || funcDef.n;\n if (funcDef.rp === false && target[targetName]) {\n return;\n }\n target[targetName] = isDeferred_1 ? createFnDeferredProxy(host, funcDef.n) : fnBind(host[funcDef.n], host);\n });\n }\n return target;\n}\nvar _iterSymbol;\n/*#__NO_SIDE_EFFECTS__*/\nfunction readArgs(theArgs, start, end) {\n if (!objHasOwn(theArgs, LENGTH)) {\n !_iterSymbol && (_iterSymbol = createCachedValue(hasSymbol() && getKnownSymbol(3)));\n var iterFn = void 0;\n if (_iterSymbol.v) {\n iterFn = theArgs[_iterSymbol.v];\n }\n if (iterFn) {\n var values_1 = [];\n var from_1 = start === UNDEF_VALUE || start < 0 ? 0 : start;\n var to_1 = end < 0 || start < 0 ? UNDEF_VALUE : end;\n iterForOf(iterFn[CALL](theArgs), function (value, cnt) {\n if (to_1 !== UNDEF_VALUE && cnt >= to_1) {\n return -1;\n }\n if (cnt >= from_1) {\n values_1.push(value);\n }\n });\n if ((start === UNDEF_VALUE || start >= 0) && (end === UNDEF_VALUE || end >= 0)) {\n return values_1;\n }\n theArgs = values_1;\n }\n }\n return arrSlice(theArgs, start, end);\n}\nvar objCreate = /* #__PURE__*/_pureAssign(/* #__PURE__*/_pureRef(ObjClass, \"create\"), polyObjCreate);\n/*#__NO_SIDE_EFFECTS__*/\nfunction polyObjCreate(obj) {\n if (!obj) {\n return {};\n }\n var type = typeof obj;\n if (type !== OBJECT && type !== FUNCTION) {\n throwTypeError(\"Prototype must be an Object or function: \" + dumpObj(obj));\n }\n function tempFunc() {}\n tempFunc[PROTOTYPE] = obj;\n return new tempFunc();\n}\nvar _isProtoArray;\nfunction objSetPrototypeOf(obj, proto) {\n var fn = ObjClass[\"setPrototypeOf\"] || function (d, b) {\n var _a;\n !_isProtoArray && (_isProtoArray = createCachedValue((_a = {}, _a[__PROTO__] = [], _a) instanceof Array));\n _isProtoArray.v ? d[__PROTO__] = b : objForEachKey(b, function (key, value) {\n return d[key] = value;\n });\n };\n return fn(obj, proto);\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction _createCustomError(name, d, b) {\n safe(objDefine, [d, NAME, {\n v: name,\n c: true,\n e: false\n }]);\n d = objSetPrototypeOf(d, b);\n function __() {\n this[CONSTRUCTOR] = d;\n safe(objDefine, [this, NAME, {\n v: name,\n c: true,\n e: false\n }]);\n }\n d[PROTOTYPE] = b === NULL_VALUE ? objCreate(b) : (__[PROTOTYPE] = b[PROTOTYPE], new __());\n return d;\n}\nfunction _setName(baseClass, name) {\n name && (baseClass[NAME] = name);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction createCustomError(name, constructCb, errorBase) {\n var theBaseClass = errorBase || Error;\n var orgName = theBaseClass[PROTOTYPE][NAME];\n var captureFn = Error.captureStackTrace;\n return _createCustomError(name, function () {\n var _this = this;\n var theArgs = arguments;\n try {\n safe(_setName, [theBaseClass, name]);\n var _self = fnApply(theBaseClass, _this, ArrSlice[CALL](theArgs)) || _this;\n if (_self !== _this) {\n var orgProto = objGetPrototypeOf(_this);\n if (orgProto !== objGetPrototypeOf(_self)) {\n objSetPrototypeOf(_self, orgProto);\n }\n }\n captureFn && captureFn(_self, _this[CONSTRUCTOR]);\n constructCb && constructCb(_self, theArgs);\n return _self;\n } finally {\n safe(_setName, [theBaseClass, orgName]);\n }\n }, theBaseClass);\n}\nvar _unsupportedError;\nfunction throwUnsupported(message) {\n if (!_unsupportedError) {\n _unsupportedError = createCustomError(\"UnsupportedError\");\n }\n throw new _unsupportedError(message);\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction utcNow() {\n return (Date.now || polyUtcNow)();\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction polyUtcNow() {\n return new Date().getTime();\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction _createTrimFn(exp) {\n return function _doTrim(value) {\n if (isNullOrUndefined(value)) {\n throwTypeError(\"strTrim called [\" + dumpObj(value) + \"]\");\n }\n if (value && value.replace) {\n value = value.replace(exp, EMPTY);\n }\n return value;\n };\n}\nvar polyStrTrim = /*#__PURE__*/_createTrimFn(/^\\s+|(?=\\s)\\s+$/g);\nvar polyStrTrimStart = /*#__PURE__*/_createTrimFn(/^\\s+/g);\nvar polyStrTrimEnd = /*#__PURE__*/_createTrimFn(/(?=\\s)\\s+$/g);\nvar strTrim = /*#__PURE__*/_unwrapFunctionWithPoly(\"trim\", StrProto, polyStrTrim);\nvar strTrimStart = /*#__PURE__*/_unwrapFunctionWithPoly(\"trimStart\", StrProto, polyStrTrimStart);\nvar strTrimLeft = /*#__PURE__*/_pureAssign(strTrimStart);\nvar strTrimEnd = /*#__PURE__*/_unwrapFunctionWithPoly(\"trimEnd\", StrProto, polyStrTrimEnd);\nvar strTrimRight = /*#__PURE__*/_pureAssign(strTrimEnd);\nvar strUpper = /*#__PURE__*/_unwrapFunction(\"toUpperCase\", StrProto);\nvar strLower = /*#__PURE__*/_unwrapFunction(\"toLowerCase\", StrProto);\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction _convertCase(value, newPrefix, upperWord) {\n return strTrim(asString(value)).replace(/((_|\\W)+(\\w){0,1}|([a-z])([A-Z]))/g, function (_match, _g1, _g2, wordStart, upperPrefix, upperLetter) {\n var convertMatch = wordStart || upperLetter || EMPTY;\n if (upperWord) {\n convertMatch = strUpper(convertMatch);\n }\n return (upperPrefix || EMPTY) + newPrefix + convertMatch;\n });\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction strLetterCase(value) {\n return asString(value).replace(/(_|\\b)\\w/g, strUpper);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction strCamelCase(value, upperFirst) {\n var result = _convertCase(value, \"\", true);\n return result.replace(/^\\w/, upperFirst ? strUpper : strLower);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction strKebabCase(value, scream) {\n var result = _convertCase(value, \"-\");\n return (scream ? strUpper : strLower)(result);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction strSnakeCase(value, scream) {\n var result = _convertCase(value, \"_\");\n return (scream ? strUpper : strLower)(result);\n}\nvar mathFloor = /*#__PURE__*/_pureRef(MathCls, \"floor\");\nvar mathCeil = /*#__PURE__*/_pureRef(MathCls, \"ceil\");\nvar mathTrunc = /* #__PURE__*/_pureAssign(/* #__PURE__*/_pureRef(MathCls, \"trunc\"), polyMathTrunc);\n/*#__NO_SIDE_EFFECTS__*/\nfunction polyMathTrunc(value) {\n var theValue = +value;\n return (theValue > 0 ? mathFloor : mathCeil)(theValue);\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction mathToInt(value, throwInfinity) {\n var result = +value;\n if (result == Infinity && throwInfinity) {\n throwRangeError(\"invalid value [\" + dumpObj(value) + \"]\");\n }\n return result !== result || result === 0 ? 0 : mathTrunc(result);\n}\nvar strRepeat = /*#__PURE__*/_unwrapFunctionWithPoly(\"repeat\", StrProto, polyStrRepeat);\n/*#__NO_SIDE_EFFECTS__*/\nfunction polyStrRepeat(value, count) {\n if (isNullOrUndefined(value)) {\n throwTypeError(\"can't convert [\" + dumpObj(value) + \"]\");\n }\n count = mathToInt(count, true);\n if (count < 0) {\n throwRangeError(\"invalid count must be >= 0 && < Infinity\");\n }\n var pad = isString(value) ? value : asString(value);\n var result = EMPTY;\n for (; count > 0; (count >>>= 1) && (pad += pad)) {\n if (count & 1) {\n result += pad;\n }\n }\n return result;\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction _padValue(value, targetLength, padString) {\n var result = EMPTY;\n targetLength = mathToInt(targetLength, true);\n targetLength >>= 0;\n var len = value[LENGTH];\n if (len < targetLength) {\n result = isNullOrUndefined(padString) ? \" \" : asString(padString);\n targetLength = targetLength - len;\n if (targetLength > result[LENGTH]) {\n result = strRepeat(result, mathCeil(targetLength / result[LENGTH]));\n }\n if (result[LENGTH] > targetLength) {\n result = strSubstring(result, 0, targetLength);\n }\n }\n return result;\n}\nvar strPadStart = /*#__PURE__*/_unwrapFunctionWithPoly(\"padStart\", StrProto, polyStrPadStart);\nvar strPadEnd = /*#__PURE__*/_unwrapFunctionWithPoly(\"padEnd\", StrProto, polyStrPadEnd);\n/*#__NO_SIDE_EFFECTS__*/\nfunction polyStrPadStart(value, targetLength, padString) {\n return _padValue(value, targetLength, padString) + value;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction polyStrPadEnd(value, targetLength, padString) {\n return value + _padValue(value, targetLength, padString);\n}\nvar DBL_QUOTE = \"\\\"\";\nvar INVALID_JS_NAME = /([^\\w\\d_$])/g;\nvar _htmlEntityCache;\n/*#__NO_SIDE_EFFECTS__*/\nfunction normalizeJsName(jsName, camelCase) {\n var result = asString(jsName).replace(INVALID_JS_NAME, \"_\");\n return !isUndefined(camelCase) ? strCamelCase(result, !camelCase) : result;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction encodeAsJson(value, format) {\n var result;\n if (isString(value)) {\n result = DBL_QUOTE + value.replace(/[^\\w .,\\-!@#$%\\^&*\\(\\)_+={}\\[\\]:;|<>?]/g, function (match) {\n if (match === DBL_QUOTE || match === \"\\\\\") {\n return \"\\\\\" + match;\n }\n var hex = match.charCodeAt(0)[TO_STRING](16);\n return \"\\\\u\" + strPadStart(strUpper(hex), 4, \"0\");\n }) + DBL_QUOTE;\n } else {\n try {\n result = JSON.stringify(value, NULL_VALUE, format ? isNumber(format) ? format : 4 : UNDEF_VALUE);\n } catch (e) {\n result = DBL_QUOTE + dumpObj(e) + DBL_QUOTE;\n }\n }\n return result;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction encodeAsHtml(value) {\n !_htmlEntityCache && (_htmlEntityCache = {\n \"&\": \"amp\",\n \"<\": \"lt\",\n \">\": \"gt\",\n \"\\\"\": \"quot\",\n \"'\": \"#39\"\n });\n return asString(value).replace(/[&<>\"']/g, function (match) {\n return \"&\" + _htmlEntityCache[match] + \";\";\n });\n}\nvar _fnToString;\nvar _objCtrFnString;\nvar _gblWindow;\n/*#__NO_SIDE_EFFECTS__*/\nfunction isPlainObject(value) {\n if (!value || typeof value !== OBJECT) {\n return false;\n }\n if (!_gblWindow) {\n _gblWindow = hasWindow() ? getWindow() : true;\n }\n var result = false;\n if (value !== _gblWindow) {\n if (!_objCtrFnString) {\n _fnToString = Function[PROTOTYPE][TO_STRING];\n _objCtrFnString = _fnToString[CALL](ObjClass);\n }\n try {\n var proto = objGetPrototypeOf(value);\n result = !proto;\n if (!result) {\n if (objHasOwnProperty(proto, CONSTRUCTOR)) {\n proto = proto[CONSTRUCTOR];\n }\n result = !!(proto && typeof proto === FUNCTION && _fnToString[CALL](proto) === _objCtrFnString);\n }\n } catch (ex) {}\n }\n return result;\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction _defaultDeepCopyHandler(details) {\n details.value && plainObjDeepCopyHandler(details);\n return true;\n}\nvar defaultDeepCopyHandlers = [arrayDeepCopyHandler, plainObjDeepCopyHandler, functionDeepCopyHandler, dateDeepCopyHandler];\n/*#__NO_SIDE_EFFECTS__*/\nfunction _getSetVisited(visitMap, source, newPath, cb) {\n var theEntry;\n arrForEach(visitMap, function (entry) {\n if (entry.k === source) {\n theEntry = entry;\n return -1;\n }\n });\n if (!theEntry) {\n theEntry = {\n k: source,\n v: source\n };\n visitMap.push(theEntry);\n cb(theEntry);\n }\n return theEntry.v;\n}\nfunction _deepCopy(visitMap, value, ctx, key) {\n var userHandler = ctx.handler;\n var newPath = ctx.path ? key ? ctx.path.concat(key) : ctx.path : [];\n var newCtx = {\n handler: ctx.handler,\n src: ctx.src,\n path: newPath\n };\n var theType = typeof value;\n var isPlain = false;\n var isPrim = value === NULL_VALUE;\n if (!isPrim) {\n if (value && theType === OBJECT) {\n isPlain = isPlainObject(value);\n } else {\n isPrim = isPrimitiveType(theType);\n }\n }\n var details = {\n type: theType,\n isPrim: isPrim,\n isPlain: isPlain,\n value: value,\n result: value,\n path: newPath,\n origin: ctx.src,\n copy: function (source, newKey) {\n return _deepCopy(visitMap, source, newKey ? newCtx : ctx, newKey);\n },\n copyTo: function (target, source) {\n return _copyProps(visitMap, target, source, newCtx);\n }\n };\n if (!details.isPrim) {\n return _getSetVisited(visitMap, value, newPath, function (newEntry) {\n objDefine(details, \"result\", {\n g: function () {\n return newEntry.v;\n },\n s: function (newValue) {\n newEntry.v = newValue;\n }\n });\n var idx = 0;\n var handler = userHandler;\n while (!(handler || (idx < defaultDeepCopyHandlers.length ? defaultDeepCopyHandlers[idx++] : _defaultDeepCopyHandler))[CALL](ctx, details)) {\n handler = NULL_VALUE;\n }\n });\n }\n if (userHandler && userHandler[CALL](ctx, details)) {\n return details.result;\n }\n return value;\n}\nfunction _copyProps(visitMap, target, source, ctx) {\n if (!isNullOrUndefined(source)) {\n for (var key in source) {\n target[key] = _deepCopy(visitMap, source[key], ctx, key);\n }\n }\n return target;\n}\nfunction objCopyProps(target, source, handler) {\n var ctx = {\n handler: handler,\n src: source,\n path: []\n };\n return _copyProps([], target, source, ctx);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction objDeepCopy(source, handler) {\n var ctx = {\n handler: handler,\n src: source\n };\n return _deepCopy([], source, ctx);\n}\nfunction arrayDeepCopyHandler(details) {\n var value = details.value;\n if (isArray(value)) {\n var target = details.result = [];\n target.length = value.length;\n details.copyTo(target, value);\n return true;\n }\n return false;\n}\nfunction dateDeepCopyHandler(details) {\n var value = details.value;\n if (isDate(value)) {\n details.result = new Date(value.getTime());\n return true;\n }\n return false;\n}\nfunction functionDeepCopyHandler(details) {\n if (details.type === FUNCTION) {\n return true;\n }\n return false;\n}\nfunction plainObjDeepCopyHandler(details) {\n var value = details.value;\n if (value && details.isPlain) {\n var target = details.result = {};\n details.copyTo(target, value);\n return true;\n }\n return false;\n}\nfunction _doExtend(target, theArgs) {\n arrForEach(theArgs, function (theArg) {\n objCopyProps(target, theArg);\n });\n return target;\n}\nfunction deepExtend(target, obj1, obj2, obj3, obj4, obj5, obj6) {\n return _doExtend(objDeepCopy(target) || {}, ArrSlice[CALL](arguments));\n}\nfunction objExtend(target, obj1, obj2, obj3, obj4, obj5, obj6) {\n return _doExtend(target || {}, ArrSlice[CALL](arguments));\n}\nvar getLength = /*#__PURE__*/_unwrapProp(LENGTH);\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction getIntValue(value, defValue) {\n if (!isNullOrUndefined(value)) {\n if (isNumber(value)) {\n return value;\n }\n var theValue = parseInt(value, 10);\n return isNaN(theValue) ? defValue : theValue;\n }\n return defValue;\n}\nvar _perf;\n/*#__NO_SIDE_EFFECTS__*/\nfunction hasPerformance() {\n return !!getPerformance();\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction getPerformance() {\n !_globalLazyTestHooks && _initTestHooks();\n if (!_perf || _globalLazyTestHooks.lzy) {\n _perf = createCachedValue(safe(getInst, [\"performance\"]).v);\n }\n return _perf.v;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction perfNow() {\n var perf = getPerformance();\n if (perf && perf.now) {\n return perf.now();\n }\n return utcNow();\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction elapsedTime(startTime) {\n return perfNow() - startTime;\n}\nvar MATCH_ANY = \"(.*)\";\nvar MATCH_SINGLE = \"(.)\";\nfunction _createRegExp(value, escapeRgx, replaceFn, ignoreCase, fullMatch) {\n // eslint-disable-next-line security/detect-non-literal-regexp\n return new RegExp((fullMatch ? \"^\" : EMPTY) + replaceFn(value.replace(escapeRgx, \"\\\\$1\")) + (fullMatch ? \"$\" : EMPTY), ignoreCase ? \"i\" : \"\");\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction createWildcardRegex(value, ignoreCase, fullMatch) {\n return _createRegExp(asString(value), /([-+|^$#.\\?{}()\\[\\]\\\\/\\\"\\'])/g, function (value) {\n return value.replace(/\\*/g, MATCH_ANY);\n }, !!ignoreCase, fullMatch);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction createFilenameRegex(value, ignoreCase, fullMatch) {\n return _createRegExp(asString(value), /([-+|^$#.{}()\\\\\\/\\[\\]\\\"\\'])/g, function (value) {\n return value.replace(/(\\\\\\\\|\\\\\\/|\\*|\\?)/g, function (_all, g1) {\n if (g1 == \"\\\\/\" || g1 == \"\\\\\\\\\") {\n return \"[\\\\\\\\\\\\/]{1}\";\n }\n return g1 == \"*\" ? MATCH_ANY : MATCH_SINGLE;\n });\n }, !!ignoreCase, fullMatch);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction makeGlobRegex(value, ignoreCase, fullMatch) {\n return _createRegExp(asString(value), /([-+|^$#.{}()\\\\\\/\\[\\]\\\"\\'])/g, function (value) {\n return value.replace(/(\\*\\*\\\\[\\\\\\/]|\\\\\\\\|\\\\\\/|\\*\\*|\\*|\\?)/g, function (_all, g1) {\n if (g1 == \"**\\\\/\" || g1 == \"**\\\\\\\\\") {\n return \"(.*[\\\\\\\\\\\\/])*\";\n }\n if (g1 === \"\\\\/\" || g1 == \"\\\\\\\\\") {\n return \"[\\\\\\\\\\\\/]{1}\";\n }\n if (g1 === \"**\") {\n return MATCH_ANY;\n }\n return g1 === \"*\" ? \"([^\\\\\\\\\\\\/]*)\" : \"([^\\\\\\\\\\\\/]{1})\";\n });\n }, !!ignoreCase, fullMatch);\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction safeGetLazy(cb, defValue) {\n return getLazy(function () {\n var result = safe(cb);\n return result.e ? defValue : result.v;\n });\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction safeGetWritableLazy(cb, defValue) {\n return getWritableLazy(function () {\n var result = safe(cb);\n return result.e ? defValue : result.v;\n });\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction _checkLength(value, props) {\n var result;\n arrForEach(props, function (prop) {\n if (prop in value) {\n var propValue = value[prop];\n result = (isFunction(propValue) ? propValue() : propValue) > 0;\n return -1;\n }\n });\n return result;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction _hasValue(value, depth) {\n var result = value === false || value === 0;\n if (!result && !isNullOrUndefined(value)) {\n if (isArray(value)) {\n result = value[LENGTH] > 0;\n } else if (isDate(value)) {\n result = !isNaN(value.getTime());\n } else if (isBoolean(value)) {\n return true;\n } else if (isObject(value)) {\n try {\n var chkValue = _checkLength(value, [LENGTH, \"byteLength\", \"size\", \"count\"]);\n if (isBoolean(chkValue)) {\n return chkValue;\n }\n if (isFunction(value.valueOf) && depth < 5) {\n return _hasValue(value.valueOf(), ++depth);\n }\n } catch (e) {}\n return !!objKeys(value)[LENGTH];\n } else {\n result = isTruthy(value);\n }\n }\n return result;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction hasValue(value) {\n return _hasValue(value, 0);\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction createIterable(ctx) {\n return makeIterable({}, ctx);\n}\nfunction makeIterable(target, ctx) {\n var itSymbol = getKnownSymbol(3);\n function _createIterator() {\n return createIterator(ctx);\n }\n target[itSymbol] = _createIterator;\n return target;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction createIterator(ctx) {\n var isDone = false;\n function _value() {\n return ctx.v;\n }\n function _next() {\n if (!isDone) {\n isDone = ctx.n ? ctx.n(arguments) : true;\n }\n var result = {\n done: isDone\n };\n if (!isDone) {\n objDefine(result, \"value\", {\n g: _value\n });\n }\n return result;\n }\n function _return(value) {\n isDone = true;\n return {\n done: true,\n value: ctx.r && ctx.r(value)\n };\n }\n function _throw(e) {\n isDone = true;\n return {\n done: true,\n value: ctx.t && ctx.t(e)\n };\n }\n var theIterator = {\n next: _next\n };\n if (ctx.r) {\n theIterator.return = _return;\n }\n if (ctx.t) {\n theIterator.throw = _throw;\n }\n return theIterator;\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction createArrayIterator(values) {\n var idx = -1;\n var theValues = values ? values.slice() : [];\n var len = theValues[LENGTH];\n function _value() {\n if (idx >= 0 && idx < len) {\n return theValues[idx];\n }\n }\n function _getNext() {\n idx++;\n return idx >= len;\n }\n var ctx = {\n n: _getNext\n };\n objDefine(ctx, \"v\", {\n g: _value\n });\n return createIterator(ctx);\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction createRangeIterator(start, end, step) {\n var nextValue = start;\n var theValue = UNDEF_VALUE;\n if (isNullOrUndefined(end)) {\n end = start;\n }\n var theStep = step;\n if (!theStep) {\n theStep = start <= end ? 1 : -1;\n }\n function _value() {\n return theValue;\n }\n function _getNext() {\n var isDone = theStep > 0 ? nextValue > end : nextValue < end;\n if (!isDone) {\n theValue = nextValue;\n nextValue += theStep;\n }\n return isDone;\n }\n return createIterator(objDefine({\n n: _getNext\n }, \"v\", {\n g: _value\n }));\n}\nvar mathRound = /*#__PURE__*/_pureRef(MathCls, \"round\");\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction polyStrSymSplit(value, splitter, limit) {\n var splitFn = splitter ? splitter[getKnownSymbol(9)] : UNDEF_VALUE;\n return splitFn ? splitFn(value, limit) : [value];\n}\nvar strSplit = /*#__PURE__*/_unwrapFunction(\"split\", StrProto);\nvar strSymSplit = /*#__PURE__*/_unwrapFunctionWithPoly(\"split\", StrProto, !hasSymbol() ? polyStrSymSplit : NULL_VALUE);\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction getValueByKey(target, path, defValue) {\n if (!path || !target) {\n return defValue;\n }\n var parts = strSplit(path, \".\");\n var cnt = parts.length;\n for (var lp = 0; lp < cnt && !isNullOrUndefined(target); lp++) {\n target = target[parts[lp]];\n }\n return !isNullOrUndefined(target) ? target : defValue;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction getValueByIter(target, iter, defValue) {\n if (!iter || !target) {\n return defValue;\n }\n iterForOf(iter, function (value) {\n if (isNullOrUndefined(target)) {\n return -1;\n }\n target = target[value];\n });\n return !isNullOrUndefined(target) ? target : defValue;\n}\nfunction setValueByKey(target, path, value) {\n if (target && path) {\n var parts = strSplit(path, \".\");\n var lastKey = parts.pop();\n arrForEach(parts, function (key) {\n if (isNullOrUndefined(target[key])) {\n target[key] = {};\n }\n target = target[key];\n });\n target[lastKey] = value;\n }\n}\nfunction setValueByIter(target, iter, value) {\n if (target && iter) {\n var lastKey_1;\n iterForOf(iter, function (key) {\n if (lastKey_1) {\n if (isNullOrUndefined(target[lastKey_1])) {\n target[lastKey_1] = {};\n }\n target = target[lastKey_1];\n }\n lastKey_1 = key;\n });\n target[lastKey_1] = value;\n }\n}\nvar strEndsWith = /*#__PURE__*/_unwrapFunctionWithPoly(\"endsWith\", StrProto, polyStrEndsWith);\n/*#__NO_SIDE_EFFECTS__*/\nfunction polyStrEndsWith(value, searchString, length) {\n if (!isString(value)) {\n throwTypeError(\"'\" + dumpObj(value) + \"' is not a string\");\n }\n var searchValue = isString(searchString) ? searchString : asString(searchString);\n var end = !isUndefined(length) && length < value[LENGTH] ? length : value[LENGTH];\n return strSubstring(value, end - searchValue[LENGTH], end) === searchValue;\n}\nvar strIndexOf = /*#__PURE__*/_unwrapFunction(\"indexOf\", StrProto);\nvar strLastIndexOf = /*#__PURE__*/_unwrapFunction(\"lastIndexOf\", StrProto);\nvar strIncludes = /*#__PURE__*/_unwrapFunctionWithPoly(\"includes\", StrProto, polyStrIncludes);\nvar strContains = /*#__PURE__*/_pureAssign(strIncludes);\n/*#__NO_SIDE_EFFECTS__*/\nfunction polyStrIncludes(value, searchString, position) {\n if (isRegExp(searchString)) {\n throwTypeError(\"'searchString' must not be a regular expression\" + dumpObj(searchString));\n }\n return strIndexOf(value, asString(searchString), position) !== -1;\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction strIsNullOrWhiteSpace(value) {\n if (isString(value)) {\n return value.replace(/[\\s\\t\\r\\n\\f]+/g, EMPTY) === EMPTY;\n }\n return isNullOrUndefined(value);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction strIsNullOrEmpty(value) {\n if (isString(value)) {\n return value === EMPTY;\n }\n return isNullOrUndefined(value);\n}\nvar strStartsWith = /*#__PURE__*/_unwrapFunctionWithPoly(\"startsWith\", StrProto, polyStrStartsWith);\n/*#__NO_SIDE_EFFECTS__*/\nfunction polyStrStartsWith(value, searchString, position) {\n if (!isString(value)) {\n throwTypeError(\"'\" + dumpObj(value) + \"' is not a string\");\n }\n var searchValue = isString(searchString) ? searchString : asString(searchString);\n var pos = position > 0 ? position : 0;\n return strSubstring(value, pos, pos + searchValue[LENGTH]) === searchValue;\n}\nvar REF = \"ref\";\nvar UNREF = \"unref\";\nvar HAS_REF = \"hasRef\";\nvar ENABLED = \"enabled\";\n/*#__NO_SIDE_EFFECTS__*/\nfunction _createTimerHandler(startTimer, refreshFn, cancelFn) {\n var ref = true;\n var timerId = startTimer ? refreshFn(NULL_VALUE) : NULL_VALUE;\n var theTimerHandler;\n function _unref() {\n ref = false;\n timerId && timerId[UNREF] && timerId[UNREF]();\n return theTimerHandler;\n }\n function _cancel() {\n timerId && cancelFn(timerId);\n timerId = NULL_VALUE;\n }\n function _refresh() {\n timerId = refreshFn(timerId);\n if (!ref) {\n _unref();\n }\n return theTimerHandler;\n }\n function _setEnabled(value) {\n !value && timerId && _cancel();\n value && !timerId && _refresh();\n }\n theTimerHandler = {\n cancel: _cancel,\n refresh: _refresh\n };\n theTimerHandler[HAS_REF] = function () {\n if (timerId && timerId[HAS_REF]) {\n return timerId[HAS_REF]();\n }\n return ref;\n };\n theTimerHandler[REF] = function () {\n ref = true;\n timerId && timerId[REF] && timerId[REF]();\n return theTimerHandler;\n };\n theTimerHandler[UNREF] = _unref;\n theTimerHandler = objDefineProp(theTimerHandler, ENABLED, {\n get: function () {\n return !!timerId;\n },\n set: _setEnabled\n });\n return {\n h: theTimerHandler,\n dn: function () {\n timerId = NULL_VALUE;\n }\n };\n}\nfunction _createTimeoutWith(startTimer, overrideFn, theArgs) {\n var isArr = isArray(overrideFn);\n var len = isArr ? overrideFn.length : 0;\n var setFn = (len > 0 ? overrideFn[0] : !isArr ? overrideFn : UNDEF_VALUE) || setTimeout;\n var clearFn = (len > 1 ? overrideFn[1] : UNDEF_VALUE) || clearTimeout;\n var timerFn = theArgs[0];\n theArgs[0] = function () {\n handler.dn();\n fnApply(timerFn, UNDEF_VALUE, ArrSlice[CALL](arguments));\n };\n var handler = _createTimerHandler(startTimer, function (timerId) {\n if (timerId) {\n if (timerId.refresh) {\n timerId.refresh();\n return timerId;\n }\n fnApply(clearFn, UNDEF_VALUE, [timerId]);\n }\n return fnApply(setFn, UNDEF_VALUE, theArgs);\n }, function (timerId) {\n fnApply(clearFn, UNDEF_VALUE, [timerId]);\n });\n return handler.h;\n}\nfunction scheduleTimeout(callback, timeout) {\n return _createTimeoutWith(true, UNDEF_VALUE, ArrSlice[CALL](arguments));\n}\nfunction scheduleTimeoutWith(overrideFn, callback, timeout) {\n return _createTimeoutWith(true, overrideFn, ArrSlice[CALL](arguments, 1));\n}\nfunction createTimeout(callback, timeout) {\n return _createTimeoutWith(false, UNDEF_VALUE, ArrSlice[CALL](arguments));\n}\nfunction createTimeoutWith(overrideFn, callback, timeout) {\n return _createTimeoutWith(false, overrideFn, ArrSlice[CALL](arguments, 1));\n}\nvar _defaultIdleTimeout = 100;\nvar _maxExecutionTime = 50;\n/*#__NO_SIDE_EFFECTS__*/\nfunction hasIdleCallback() {\n return !!(/*#__PURE__*/getIdleCallback());\n}\nvar getIdleCallback = /*#__PURE__*/_getGlobalInstFn(getInst, [\"requestIdleCallback\"]);\nvar getCancelIdleCallback = /*#__PURE__*/_getGlobalInstFn(getInst, [\"cancelIdleCallback\"]);\nfunction setDefaultIdleTimeout(timeout) {\n _defaultIdleTimeout = timeout;\n}\nfunction setDefaultMaxExecutionTime(maxTime) {\n _maxExecutionTime = maxTime;\n}\nfunction scheduleIdleCallback(callback, options) {\n function _createDeadline(timedOut) {\n var startTime = perfNow();\n return {\n didTimeout: timedOut,\n timeRemaining: function () {\n return _maxExecutionTime - elapsedTime(startTime);\n }\n };\n }\n if (hasIdleCallback()) {\n var handler_1 = _createTimerHandler(true, function (idleId) {\n idleId && getCancelIdleCallback()(idleId);\n return getIdleCallback()(function (deadline) {\n handler_1.dn();\n callback(deadline || _createDeadline(false));\n }, options);\n }, function (idleId) {\n getCancelIdleCallback()(idleId);\n });\n return handler_1.h;\n }\n var timeout = (options || {}).timeout;\n if (isUndefined(timeout)) {\n timeout = _defaultIdleTimeout;\n }\n return scheduleTimeout(function () {\n callback(_createDeadline(true));\n }, timeout);\n}\nfunction scheduleInterval(callback, timeout) {\n var theArguments = ArrSlice[CALL](arguments);\n var handler = _createTimerHandler(true, function (intervalId) {\n intervalId && clearInterval(intervalId);\n return fnApply(setInterval, UNDEF_VALUE, theArguments);\n }, function (intervalId) {\n fnApply(clearInterval, UNDEF_VALUE, [intervalId]);\n });\n return handler.h;\n}\nexport { arrAppend, arrContains, arrEvery, arrFilter, arrFind, arrFindIndex, arrFindLast, arrFindLastIndex, arrForEach, arrFrom, arrIncludes, arrIndexOf, arrLastIndexOf, arrMap, arrReduce, arrSlice, arrSome, arrayDeepCopyHandler, asString, createArrayIterator, createCachedValue, createCustomError, createDeferredCachedValue, createEnum, createEnumKeyMap, createEnumValueMap, createFilenameRegex, createFnDeferredProxy, createIterable, createIterator, createProxyFuncs, createRangeIterator, createSimpleMap, createTimeout, createTimeoutWith, createTypeMap, createWildcardRegex, dateDeepCopyHandler, deepExtend, dumpObj, elapsedTime, encodeAsHtml, encodeAsJson, fnApply, fnBind, fnCall, functionDeepCopyHandler, getCancelIdleCallback, getDocument, getGlobal, getHistory, getIdleCallback, getInst, getIntValue, getKnownSymbol, getLazy, getLength, getNavigator, getPerformance, getSymbol, getValueByIter, getValueByKey, getWindow, getWritableLazy, hasDocument, hasHistory, hasIdleCallback, hasNavigator, hasPerformance, hasSymbol, hasValue, hasWindow, isArray, isArrayBuffer, isBlob, isBoolean, isDate, isDefined, isError, isFile, isFormData, isFunction, isIterable, isIterator, isNode, isNotTruthy, isNullOrUndefined, isNumber, isObject, isPlainObject, isPrimitive, isPrimitiveType, isPromise, isPromiseLike, isRegExp, isStrictNullOrUndefined, isStrictUndefined, isString, isSymbol, isThenable, isTruthy, isTypeof, isUndefined, isWebWorker, iterForOf, lazySafeGetInst, makeGlobRegex, makeIterable, mathCeil, mathFloor, mathMax, mathMin, mathRound, mathToInt, mathTrunc, newSymbol, normalizeJsName, objAssign, objCopyProps, objCreate, objDeepCopy, objDeepFreeze, objDefine, objDefineAccessors, objDefineGet, objDefineProp, objDefineProperties, objDefineProps, objEntries, objExtend, objForEachKey, objFreeze, objGetOwnPropertyDescriptor, objGetPrototypeOf, objHasOwn, objHasOwnProperty, objKeys, objSeal, objSetPrototypeOf, objToString, perfNow, plainObjDeepCopyHandler, polyArrFind, polyArrFindIndex, polyArrFindLast, polyArrFindLastIndex, polyArrFrom, polyArrIncludes, polyGetKnownSymbol, polyIsArray, polyNewSymbol, polyObjEntries, polyObjHasOwn, polyObjKeys, polyStrIncludes, polyStrSubstr, polyStrSymSplit, polyStrTrim, polyStrTrimEnd, polyStrTrimStart, polySymbolFor, polySymbolKeyFor, polyUtcNow, readArgs, safe, safeGet, safeGetLazy, safeGetWritableLazy, scheduleIdleCallback, scheduleInterval, scheduleTimeout, scheduleTimeoutWith, setBypassLazyCache, setDefaultIdleTimeout, setDefaultMaxExecutionTime, setValueByIter, setValueByKey, strCamelCase, strContains, strEndsWith, strIncludes, strIndexOf, strIsNullOrEmpty, strIsNullOrWhiteSpace, strKebabCase, strLastIndexOf, strLeft, strLetterCase, strLower, strPadEnd, strPadStart, strRepeat, strRight, strSlice, strSnakeCase, strSplit, strStartsWith, strSubstr, strSubstring, strSymSplit, strTrim, strTrimEnd, strTrimLeft, strTrimRight, strTrimStart, strUpper, symbolFor, symbolKeyFor, throwError, throwRangeError, throwTypeError, throwUnsupported, utcNow };\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nvar _a;\nimport { getGlobal, objCreate, objHasOwnProperty, throwTypeError } from \"@nevware21/ts-utils\";\n;\nvar UNDEFINED = \"undefined\";\n/**\r\n * Constant string defined to support minimization\r\n * @ignore\r\n */\nvar Constructor = 'constructor';\n/**\r\n * Constant string defined to support minimization\r\n * @ignore\r\n */\nvar Prototype = 'prototype';\n/**\r\n * Constant string defined to support minimization\r\n * @ignore\r\n */\nvar strFunction = 'function';\n/**\r\n * Used to define the name of the instance function lookup table\r\n * @ignore\r\n */\nvar DynInstFuncTable = '_dynInstFuncs';\n/**\r\n * Name used to tag the dynamic prototype function\r\n * @ignore\r\n */\nvar DynProxyTag = '_isDynProxy';\n/**\r\n * Name added to a prototype to define the dynamic prototype \"class\" name used to lookup the function table\r\n * @ignore\r\n */\nvar DynClassName = '_dynClass';\n/**\r\n * Prefix added to the classname to avoid any name clashes with other instance level properties\r\n * @ignore\r\n */\nvar DynClassNamePrefix = '_dynCls$';\n/**\r\n * A tag which is used to check if we have already to attempted to set the instance function if one is not present\r\n * @ignore\r\n */\nvar DynInstChkTag = '_dynInstChk';\n/**\r\n * A tag which is used to check if we are allows to try and set an instance function is one is not present. Using the same\r\n * tag name as the function level but a different const name for readability only.\r\n */\nvar DynAllowInstChkTag = DynInstChkTag;\n/**\r\n * The global (imported) instances where the global performance options are stored\r\n */\nvar DynProtoDefaultOptions = '_dfOpts';\n/**\r\n * Value used as the name of a class when it cannot be determined\r\n * @ignore\r\n */\nvar UnknownValue = '_unknown_';\n/**\r\n * Constant string defined to support minimization\r\n * @ignore\r\n */\nvar str__Proto = \"__proto__\";\n/**\r\n * The polyfill version of __proto__ so that it doesn't cause issues for anyone not expecting it to exist\r\n */\nvar DynProtoBaseProto = \"_dyn\" + str__Proto;\n/**\r\n * Runtime Global holder for dynamicProto settings\r\n */\nvar DynProtoGlobalSettings = \"__dynProto$Gbl\";\n/**\r\n * Track the current prototype for IE8 as you can't look back to get the prototype\r\n */\nvar DynProtoCurrent = \"_dynInstProto\";\n/**\r\n * Constant string defined to support minimization\r\n * @ignore\r\n */\nvar strUseBaseInst = 'useBaseInst';\n/**\r\n * Constant string defined to support minimization\r\n * @ignore\r\n */\nvar strSetInstFuncs = 'setInstFuncs';\nvar Obj = Object;\n/**\r\n * Pre-lookup to check if we are running on a modern browser (i.e. not IE8)\r\n * @ignore\r\n */\nvar _objGetPrototypeOf = Obj[\"getPrototypeOf\"];\n/**\r\n * Pre-lookup to check for the existence of this function\r\n */\nvar _objGetOwnProps = Obj[\"getOwnPropertyNames\"];\n// Since 1.1.7 moving these to the runtime global to work around mixed version and module issues\n// See Issue https://github.com/microsoft/DynamicProto-JS/issues/57 for details\nvar _gbl = getGlobal();\nvar _gblInst = _gbl[DynProtoGlobalSettings] || (_gbl[DynProtoGlobalSettings] = {\n o: (_a = {}, _a[strSetInstFuncs] = true, _a[strUseBaseInst] = true, _a),\n n: 1000 // Start new global index @ 1000 so we \"fix\" some cases when mixed with 1.1.6 or earlier\n});\n/**\r\n * Helper used to check whether the target is an Object prototype or Array prototype\r\n * @ignore\r\n */\nfunction _isObjectOrArrayPrototype(target) {\n return target && (target === Obj[Prototype] || target === Array[Prototype]);\n}\n/**\r\n * Helper used to check whether the target is an Object prototype, Array prototype or Function prototype\r\n * @ignore\r\n */\nfunction _isObjectArrayOrFunctionPrototype(target) {\n return _isObjectOrArrayPrototype(target) || target === Function[Prototype];\n}\n/**\r\n * Helper used to get the prototype of the target object as getPrototypeOf is not available in an ES3 environment.\r\n * @ignore\r\n */\nfunction _getObjProto(target) {\n var newProto;\n if (target) {\n // This method doesn't exist in older browsers (e.g. IE8)\n if (_objGetPrototypeOf) {\n return _objGetPrototypeOf(target);\n }\n var curProto = target[str__Proto] || target[Prototype] || (target[Constructor] ? target[Constructor][Prototype] : null);\n // Using the pre-calculated value as IE8 doesn't support looking up the prototype of a prototype and thus fails for more than 1 base class\n newProto = target[DynProtoBaseProto] || curProto;\n if (!objHasOwnProperty(target, DynProtoBaseProto)) {\n // As this prototype doesn't have this property then this is from an inherited class so newProto is the base to return so save it\n // so we can look it up value (which for a multiple hierarchy dynamicProto will be the base class)\n delete target[DynProtoCurrent]; // Delete any current value allocated to this instance so we pick up the value from prototype hierarchy\n newProto = target[DynProtoBaseProto] = target[DynProtoCurrent] || target[DynProtoBaseProto];\n target[DynProtoCurrent] = curProto;\n }\n }\n return newProto;\n}\n/**\r\n * Helper to get the properties of an object, including none enumerable ones as functions on a prototype in ES6\r\n * are not enumerable.\r\n * @param target\r\n */\nfunction _forEachProp(target, func) {\n var props = [];\n if (_objGetOwnProps) {\n props = _objGetOwnProps(target);\n } else {\n for (var name_1 in target) {\n if (typeof name_1 === \"string\" && objHasOwnProperty(target, name_1)) {\n props.push(name_1);\n }\n }\n }\n if (props && props.length > 0) {\n for (var lp = 0; lp < props.length; lp++) {\n func(props[lp]);\n }\n }\n}\n/**\r\n * Helper function to check whether the provided function name is a potential candidate for dynamic\r\n * callback and prototype generation.\r\n * @param target The target object, may be a prototype or class object\r\n * @param funcName The function name\r\n * @param skipOwn Skips the check for own property\r\n * @ignore\r\n */\nfunction _isDynamicCandidate(target, funcName, skipOwn) {\n return funcName !== Constructor && typeof target[funcName] === strFunction && (skipOwn || objHasOwnProperty(target, funcName)) && funcName !== str__Proto && funcName !== Prototype;\n}\n/**\r\n * Helper to throw a TypeError exception\r\n * @param message the message\r\n * @ignore\r\n */\nfunction _throwTypeError(message) {\n throwTypeError(\"DynamicProto: \" + message);\n}\n/**\r\n * Returns a collection of the instance functions that are defined directly on the thisTarget object, it does\r\n * not return any inherited functions\r\n * @param thisTarget The object to get the instance functions from\r\n * @ignore\r\n */\nfunction _getInstanceFuncs(thisTarget) {\n // Get the base proto\n var instFuncs = objCreate(null);\n // Save any existing instance functions\n _forEachProp(thisTarget, function (name) {\n // Don't include any dynamic prototype instances - as we only want the real functions\n if (!instFuncs[name] && _isDynamicCandidate(thisTarget, name, false)) {\n // Create an instance callback for passing the base function to the caller\n instFuncs[name] = thisTarget[name];\n }\n });\n return instFuncs;\n}\n/**\r\n * Returns whether the value is included in the array\r\n * @param values The array of values\r\n * @param value The value\r\n */\nfunction _hasVisited(values, value) {\n for (var lp = values.length - 1; lp >= 0; lp--) {\n if (values[lp] === value) {\n return true;\n }\n }\n return false;\n}\n/**\r\n * Returns an object that contains callback functions for all \"base/super\" functions, this is used to \"save\"\r\n * enabling calling super.xxx() functions without requiring that the base \"class\" has defined a prototype references\r\n * @param target The current instance\r\n * @ignore\r\n */\nfunction _getBaseFuncs(classProto, thisTarget, instFuncs, useBaseInst) {\n function _instFuncProxy(target, funcHost, funcName) {\n var theFunc = funcHost[funcName];\n if (theFunc[DynProxyTag] && useBaseInst) {\n // grab and reuse the hosted looking function (if available) otherwise the original passed function\n var instFuncTable = target[DynInstFuncTable] || {};\n if (instFuncTable[DynAllowInstChkTag] !== false) {\n theFunc = (instFuncTable[funcHost[DynClassName]] || {})[funcName] || theFunc;\n }\n }\n return function () {\n // eslint-disable-next-line prefer-rest-params\n return theFunc.apply(target, arguments);\n };\n }\n // Start creating a new baseFuncs by creating proxies for the instance functions (as they may get replaced)\n var baseFuncs = objCreate(null);\n _forEachProp(instFuncs, function (name) {\n // Create an instance callback for passing the base function to the caller\n baseFuncs[name] = _instFuncProxy(thisTarget, instFuncs, name);\n });\n // Get the base prototype functions\n var baseProto = _getObjProto(classProto);\n var visited = [];\n // Don't include base object functions for Object, Array or Function\n while (baseProto && !_isObjectArrayOrFunctionPrototype(baseProto) && !_hasVisited(visited, baseProto)) {\n // look for prototype functions\n _forEachProp(baseProto, function (name) {\n // Don't include any dynamic prototype instances - as we only want the real functions\n // For IE 7/8 the prototype lookup doesn't provide the full chain so we need to bypass the \n // hasOwnProperty check we get all of the methods, main difference is that IE7/8 doesn't return\n // the Object prototype methods while bypassing the check\n if (!baseFuncs[name] && _isDynamicCandidate(baseProto, name, !_objGetPrototypeOf)) {\n // Create an instance callback for passing the base function to the caller\n baseFuncs[name] = _instFuncProxy(thisTarget, baseProto, name);\n }\n });\n // We need to find all possible functions that might be overloaded by walking the entire prototype chain\n // This avoids the caller from needing to check whether it's direct base class implements the function or not\n // by walking the entire chain it simplifies the usage and issues from upgrading any of the base classes.\n visited.push(baseProto);\n baseProto = _getObjProto(baseProto);\n }\n return baseFuncs;\n}\nfunction _getInstFunc(target, funcName, proto, currentDynProtoProxy) {\n var instFunc = null;\n // We need to check whether the class name is defined directly on this prototype otherwise\n // it will walk the proto chain and return any parent proto classname.\n if (target && objHasOwnProperty(proto, DynClassName)) {\n var instFuncTable = target[DynInstFuncTable] || objCreate(null);\n instFunc = (instFuncTable[proto[DynClassName]] || objCreate(null))[funcName];\n if (!instFunc) {\n // Avoid stack overflow from recursive calling the same function\n _throwTypeError(\"Missing [\" + funcName + \"] \" + strFunction);\n }\n // We have the instance function, lets check it we can speed up further calls\n // by adding the instance function back directly on the instance (avoiding the dynamic func lookup)\n if (!instFunc[DynInstChkTag] && instFuncTable[DynAllowInstChkTag] !== false) {\n // If the instance already has an instance function we can't replace it\n var canAddInst = !objHasOwnProperty(target, funcName);\n // Get current prototype\n var objProto = _getObjProto(target);\n var visited = [];\n // Lookup the function starting at the top (instance level prototype) and traverse down, if the first matching function\n // if nothing is found or if the first hit is a dynamic proto instance then we can safely add an instance shortcut\n while (canAddInst && objProto && !_isObjectArrayOrFunctionPrototype(objProto) && !_hasVisited(visited, objProto)) {\n var protoFunc = objProto[funcName];\n if (protoFunc) {\n canAddInst = protoFunc === currentDynProtoProxy;\n break;\n }\n // We need to find all possible initial functions to ensure that we don't bypass a valid override function\n visited.push(objProto);\n objProto = _getObjProto(objProto);\n }\n try {\n if (canAddInst) {\n // This instance doesn't have an instance func and the class hierarchy does have a higher level prototype version\n // so it's safe to directly assign for any subsequent calls (for better performance)\n target[funcName] = instFunc;\n }\n // Block further attempts to set the instance function for any\n instFunc[DynInstChkTag] = 1;\n } catch (e) {\n // Don't crash if the object is readonly or the runtime doesn't allow changing this\n // And set a flag so we don't try again for any function\n instFuncTable[DynAllowInstChkTag] = false;\n }\n }\n }\n return instFunc;\n}\nfunction _getProtoFunc(funcName, proto, currentDynProtoProxy) {\n var protoFunc = proto[funcName];\n // Check that the prototype function is not a self reference -- try to avoid stack overflow!\n if (protoFunc === currentDynProtoProxy) {\n // It is so lookup the base prototype\n protoFunc = _getObjProto(proto)[funcName];\n }\n if (typeof protoFunc !== strFunction) {\n _throwTypeError(\"[\" + funcName + \"] is not a \" + strFunction);\n }\n return protoFunc;\n}\n/**\r\n * Add the required dynamic prototype methods to the the class prototype\r\n * @param proto - The class prototype\r\n * @param className - The instance classname\r\n * @param target - The target instance\r\n * @param baseInstFuncs - The base instance functions\r\n * @param setInstanceFunc - Flag to allow prototype function to reset the instance function if one does not exist\r\n * @ignore\r\n */\nfunction _populatePrototype(proto, className, target, baseInstFuncs, setInstanceFunc) {\n function _createDynamicPrototype(proto, funcName) {\n var dynProtoProxy = function () {\n // Use the instance or prototype function\n var instFunc = _getInstFunc(this, funcName, proto, dynProtoProxy) || _getProtoFunc(funcName, proto, dynProtoProxy);\n // eslint-disable-next-line prefer-rest-params\n return instFunc.apply(this, arguments);\n };\n // Tag this function as a proxy to support replacing dynamic proxy elements (primary use case is for unit testing\n // via which can dynamically replace the prototype function reference)\n dynProtoProxy[DynProxyTag] = 1;\n return dynProtoProxy;\n }\n if (!_isObjectOrArrayPrototype(proto)) {\n var instFuncTable = target[DynInstFuncTable] = target[DynInstFuncTable] || objCreate(null);\n if (!_isObjectOrArrayPrototype(instFuncTable)) {\n var instFuncs_1 = instFuncTable[className] = instFuncTable[className] || objCreate(null); // fetch and assign if as it may not exist yet\n // Set whether we are allow to lookup instances, if someone has set to false then do not re-enable\n if (instFuncTable[DynAllowInstChkTag] !== false) {\n instFuncTable[DynAllowInstChkTag] = !!setInstanceFunc;\n }\n if (!_isObjectOrArrayPrototype(instFuncs_1)) {\n _forEachProp(target, function (name) {\n // Only add overridden functions\n if (_isDynamicCandidate(target, name, false) && target[name] !== baseInstFuncs[name]) {\n // Save the instance Function to the lookup table and remove it from the instance as it's not a dynamic proto function\n instFuncs_1[name] = target[name];\n delete target[name];\n // Add a dynamic proto if one doesn't exist or if a prototype function exists and it's not a dynamic one\n if (!objHasOwnProperty(proto, name) || proto[name] && !proto[name][DynProxyTag]) {\n proto[name] = _createDynamicPrototype(proto, name);\n }\n }\n });\n }\n }\n }\n}\n/**\r\n * Checks whether the passed prototype object appears to be correct by walking the prototype hierarchy of the instance\r\n * @param classProto The class prototype instance\r\n * @param thisTarget The current instance that will be checked whether the passed prototype instance is in the hierarchy\r\n * @ignore\r\n */\nfunction _checkPrototype(classProto, thisTarget) {\n // This method doesn't existing in older browsers (e.g. IE8)\n if (_objGetPrototypeOf) {\n // As this is primarily a coding time check, don't bother checking if running in IE8 or lower\n var visited = [];\n var thisProto = _getObjProto(thisTarget);\n while (thisProto && !_isObjectArrayOrFunctionPrototype(thisProto) && !_hasVisited(visited, thisProto)) {\n if (thisProto === classProto) {\n return true;\n }\n // This avoids the caller from needing to check whether it's direct base class implements the function or not\n // by walking the entire chain it simplifies the usage and issues from upgrading any of the base classes.\n visited.push(thisProto);\n thisProto = _getObjProto(thisProto);\n }\n return false;\n }\n // If objGetPrototypeOf doesn't exist then just assume everything is ok.\n return true;\n}\n/**\r\n * Gets the current prototype name using the ES6 name if available otherwise falling back to a use unknown as the name.\r\n * It's not critical for this to return a name, it's used to decorate the generated unique name for easier debugging only.\r\n * @param target\r\n * @param unknownValue\r\n * @ignore\r\n */\nfunction _getObjName(target, unknownValue) {\n if (objHasOwnProperty(target, Prototype)) {\n // Look like a prototype\n return target.name || unknownValue || UnknownValue;\n }\n return ((target || {})[Constructor] || {}).name || unknownValue || UnknownValue;\n}\n/**\r\n * Helper function when creating dynamic (inline) functions for classes, this helper performs the following tasks :-\r\n * - Saves references to all defined base class functions\r\n * - Calls the delegateFunc with the current target (this) and a base object reference that can be used to call all \"super\" functions.\r\n * - Will populate the class prototype for all overridden functions to support class extension that call the prototype instance.\r\n * Callers should use this helper when declaring all function within the constructor of a class, as mentioned above the delegateFunc is\r\n * passed both the target \"this\" and an object that can be used to call any base (super) functions, using this based object in place of\r\n * super.XXX() (which gets expanded to _super.prototype.XXX()) provides a better minification outcome and also ensures the correct \"this\"\r\n * context is maintained as TypeScript creates incorrect references using super.XXXX() for dynamically defined functions i.e. Functions\r\n * defined in the constructor or some other function (rather than declared as complete typescript functions).\r\n * ### Usage\r\n * ```typescript\r\n * import dynamicProto from \"@microsoft/dynamicproto-js\";\r\n * class ExampleClass extends BaseClass {\r\n * constructor() {\r\n * dynamicProto(ExampleClass, this, (_self, base) => {\r\n * // This will define a function that will be converted to a prototype function\r\n * _self.newFunc = () => {\r\n * // Access any \"this\" instance property\r\n * if (_self.someProperty) {\r\n * ...\r\n * }\r\n * }\r\n * // This will define a function that will be converted to a prototype function\r\n * _self.myFunction = () => {\r\n * // Access any \"this\" instance property\r\n * if (_self.someProperty) {\r\n * // Call the base version of the function that we are overriding\r\n * base.myFunction();\r\n * }\r\n * ...\r\n * }\r\n * _self.initialize = () => {\r\n * ...\r\n * }\r\n * // Warnings: While the following will work as _self is simply a reference to\r\n * // this, if anyone overrides myFunction() the overridden will be called first\r\n * // as the normal JavaScript method resolution will occur and the defined\r\n * // _self.initialize() function is actually gets removed from the instance and\r\n * // a proxy prototype version is created to reference the created method.\r\n * _self.initialize();\r\n * });\r\n * }\r\n * }\r\n * ```\r\n * @typeparam DPType This is the generic type of the class, used to keep intellisense valid\r\n * @typeparam DPCls The type that contains the prototype of the current class\r\n * @param theClass - This is the current class instance which contains the prototype for the current class\r\n * @param target - The current \"this\" (target) reference, when the class has been extended this.prototype will not be the 'theClass' value.\r\n * @param delegateFunc - The callback function (closure) that will create the dynamic function\r\n * @param options - Additional options to configure how the dynamic prototype operates\r\n */\nexport default function dynamicProto(theClass, target, delegateFunc, options) {\n // Make sure that the passed theClass argument looks correct\n if (!objHasOwnProperty(theClass, Prototype)) {\n _throwTypeError(\"theClass is an invalid class definition.\");\n }\n // Quick check to make sure that the passed theClass argument looks correct (this is a common copy/paste error)\n var classProto = theClass[Prototype];\n if (!_checkPrototype(classProto, target)) {\n _throwTypeError(\"[\" + _getObjName(theClass) + \"] not in hierarchy of [\" + _getObjName(target) + \"]\");\n }\n var className = null;\n if (objHasOwnProperty(classProto, DynClassName)) {\n // Only grab the class name if it's defined on this prototype (i.e. don't walk the prototype chain)\n className = classProto[DynClassName];\n } else {\n // As not all browser support name on the prototype creating a unique dynamic one if we have not already\n // assigned one, so we can use a simple string as the lookup rather than an object for the dynamic instance\n // function table lookup.\n className = DynClassNamePrefix + _getObjName(theClass, \"_\") + \"$\" + _gblInst.n;\n _gblInst.n++;\n classProto[DynClassName] = className;\n }\n var perfOptions = dynamicProto[DynProtoDefaultOptions];\n var useBaseInst = !!perfOptions[strUseBaseInst];\n if (useBaseInst && options && options[strUseBaseInst] !== undefined) {\n useBaseInst = !!options[strUseBaseInst];\n }\n // Get the current instance functions\n var instFuncs = _getInstanceFuncs(target);\n // Get all of the functions for any base instance (before they are potentially overridden)\n var baseFuncs = _getBaseFuncs(classProto, target, instFuncs, useBaseInst);\n // Execute the delegate passing in both the current target \"this\" and \"base\" function references\n // Note casting the same type as we don't actually have the base class here and this will provide some intellisense support\n delegateFunc(target, baseFuncs);\n // Don't allow setting instance functions for older IE instances\n var setInstanceFunc = !!_objGetPrototypeOf && !!perfOptions[strSetInstFuncs];\n if (setInstanceFunc && options) {\n setInstanceFunc = !!options[strSetInstFuncs];\n }\n // Populate the Prototype for any overridden instance functions\n _populatePrototype(classProto, className, target, instFuncs, setInstanceFunc !== false);\n}\n/**\r\n * Exposes the default global options to allow global configuration, if the global values are disabled these will override\r\n * any passed values. This is primarily exposed to support unit-testing without the need for individual classes to expose\r\n * their internal usage of dynamic proto.\r\n */\ndynamicProto[DynProtoDefaultOptions] = _gblInst.o;\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nexport var strShimFunction = \"function\";\nexport var strShimObject = \"object\";\nexport var strShimUndefined = \"undefined\";\nexport var strShimPrototype = \"prototype\";\nexport var strDefault = \"default\";\nexport var ObjClass = Object;\nexport var ObjProto = ObjClass[strShimPrototype];\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { getGlobal, objAssign, objCreate, objDefineProp, objHasOwnProperty, throwTypeError } from \"@nevware21/ts-utils\";\nimport { ObjClass, ObjProto, strDefault, strShimFunction, strShimPrototype } from \"./Constants\";\n// Most of these functions have been directly shamelessly \"lifted\" from the https://github.com/@microsoft/tslib and\n// modified to be ES5 compatible and applying several minification and tree-shaking techniques so that Application Insights\n// can successfully use TypeScript \"importHelpers\" which imports tslib during compilation but it will use these at runtime\n// Which is also why all of the functions have not been included as Application Insights currently doesn't use or require\n// them.\nexport var SymbolObj = (getGlobal() || {})[\"Symbol\"];\nexport var ReflectObj = (getGlobal() || {})[\"Reflect\"];\nexport var __hasReflect = !!ReflectObj;\nvar strDecorate = \"decorate\";\nvar strMetadata = \"metadata\";\nvar strGetOwnPropertySymbols = \"getOwnPropertySymbols\";\nvar strIterator = \"iterator\";\nvar strHasOwnProperty = \"hasOwnProperty\";\nexport var __objAssignFnImpl = function (t) {\n // tslint:disable-next-line: ban-comma-operator\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) {\n if (ObjProto[strHasOwnProperty].call(s, p)) {\n t[p] = s[p];\n }\n }\n }\n return t;\n};\nexport var __assignFn = objAssign || __objAssignFnImpl;\n// tslint:disable-next-line: only-arrow-functions\nvar extendStaticsFn = function (d, b) {\n extendStaticsFn = ObjClass[\"setPrototypeOf\"] ||\n // tslint:disable-next-line: only-arrow-functions\n {\n __proto__: []\n } instanceof Array && function (d, b) {\n d.__proto__ = b;\n } ||\n // tslint:disable-next-line: only-arrow-functions\n function (d, b) {\n for (var p in b) {\n if (b[strHasOwnProperty](p)) {\n d[p] = b[p];\n }\n }\n };\n return extendStaticsFn(d, b);\n};\nexport function __extendsFn(d, b) {\n if (typeof b !== strShimFunction && b !== null) {\n throwTypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n }\n extendStaticsFn(d, b);\n function __() {\n this.constructor = d;\n }\n // tslint:disable-next-line: ban-comma-operator\n d[strShimPrototype] = b === null ? objCreate(b) : (__[strShimPrototype] = b[strShimPrototype], new __());\n}\nexport function __restFn(s, e) {\n var t = {};\n for (var k in s) {\n if (objHasOwnProperty(s, k) && e.indexOf(k) < 0) {\n t[k] = s[k];\n }\n }\n if (s != null && typeof ObjClass[strGetOwnPropertySymbols] === strShimFunction) {\n for (var i = 0, p = ObjClass[strGetOwnPropertySymbols](s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && ObjProto[\"propertyIsEnumerable\"].call(s, p[i])) {\n t[p[i]] = s[p[i]];\n }\n }\n }\n return t;\n}\nexport function __decorateFn(decorators, target, key, desc) {\n var c = arguments.length,\n r = c < 3 ? target : desc === null ? desc = ObjClass[\"getOwnPropertyDescriptor\"](target, key) : desc,\n d;\n if (__hasReflect && typeof ReflectObj[strDecorate] === strShimFunction) {\n r = ReflectObj[strDecorate](decorators, target, key, desc);\n } else {\n for (var i = decorators.length - 1; i >= 0; i--) {\n // eslint-disable-next-line no-cond-assign\n if (d = decorators[i]) {\n r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n }\n }\n }\n // tslint:disable-next-line:ban-comma-operator\n return c > 3 && r && objDefineProp(target, key, r), r;\n}\nexport function __paramFn(paramIndex, decorator) {\n return function (target, key) {\n decorator(target, key, paramIndex);\n };\n}\nexport function __metadataFn(metadataKey, metadataValue) {\n if (__hasReflect && ReflectObj[strMetadata] === strShimFunction) {\n return ReflectObj[strMetadata](metadataKey, metadataValue);\n }\n}\nexport function __exportStarFn(m, o) {\n for (var p in m) {\n if (p !== strDefault && !objHasOwnProperty(o, p)) {\n __createBindingFn(o, m, p);\n }\n }\n}\nexport function __createBindingFn(o, m, k, k2) {\n if (k2 === undefined) {\n k2 = k;\n }\n if (!!objDefineProp) {\n objDefineProp(o, k2, {\n enumerable: true,\n get: function () {\n return m[k];\n }\n });\n } else {\n o[k2] = m[k];\n }\n}\nexport function __valuesFn(o) {\n var s = typeof SymbolObj === strShimFunction && SymbolObj[strIterator],\n m = s && o[s],\n i = 0;\n if (m) {\n return m.call(o);\n }\n if (o && typeof o.length === \"number\") {\n return {\n next: function () {\n if (o && i >= o.length) {\n o = void 0;\n }\n return {\n value: o && o[i++],\n done: !o\n };\n }\n };\n }\n throwTypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\nexport function __readFn(o, n) {\n var m = typeof SymbolObj === strShimFunction && o[SymbolObj[strIterator]];\n if (!m) {\n return o;\n }\n var i = m.call(o),\n r,\n ar = [],\n e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) {\n ar.push(r.value);\n }\n } catch (error) {\n e = {\n error: error\n };\n } finally {\n try {\n // tslint:disable-next-line:no-conditional-assignment\n if (r && !r.done && (m = i[\"return\"])) {\n m.call(i);\n }\n } finally {\n if (e) {\n // eslint-disable-next-line no-unsafe-finally\n throw e.error;\n }\n }\n }\n return ar;\n}\n/** @deprecated */\nexport function __spreadArraysFn() {\n var theArgs = arguments;\n // Calculate new total size\n for (var s = 0, i = 0, il = theArgs.length; i < il; i++) {\n s += theArgs[i].length;\n }\n // Create new full array\n for (var r = Array(s), k = 0, i = 0; i < il; i++) {\n for (var a = theArgs[i], j = 0, jl = a.length; j < jl; j++, k++) {\n r[k] = a[j];\n }\n }\n return r;\n}\nexport function __spreadArrayFn(to, from) {\n for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) {\n to[j] = from[i];\n }\n return to;\n}\nexport function __makeTemplateObjectFn(cooked, raw) {\n if (objDefineProp) {\n objDefineProp(cooked, \"raw\", {\n value: raw\n });\n } else {\n cooked.raw = raw;\n }\n return cooked;\n}\nexport function __importStarFn(mod) {\n if (mod && mod.__esModule) {\n return mod;\n }\n var result = {};\n if (mod != null) {\n for (var k in mod) {\n if (k !== strDefault && Object.prototype.hasOwnProperty.call(mod, k)) {\n __createBindingFn(result, mod, k);\n }\n }\n }\n // Set default module\n if (!!objDefineProp) {\n objDefineProp(result, strDefault, {\n enumerable: true,\n value: mod\n });\n } else {\n result[strDefault] = mod;\n }\n return result;\n}\nexport function __importDefaultFn(mod) {\n return mod && mod.__esModule ? mod : {\n strDefault: mod\n };\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { createEnum, createTypeMap } from \"@nevware21/ts-utils\";\n/**\r\n * Create an enum style object which has both the key \\=\\> value and value \\=\\> key mappings\r\n * @param values - The values to populate on the new object\r\n * @returns\r\n */\nexport var createEnumStyle = createEnum;\n/**\r\n * Create a 2 index map that maps an enum's key and value to the defined map value, X[\"key\"] \\=\\> mapValue and X[0] \\=\\> mapValue.\r\n * Generic values\r\n * - E = the const enum type (typeof eRequestHeaders);\r\n * - V = Identifies the valid values for the keys, this should include both the enum numeric and string key of the type. The\r\n * resulting \"Value\" of each entry identifies the valid values withing the assignments.\r\n * @param values - The values to populate on the new object\r\n * @returns\r\n */\nexport var createValueMap = createTypeMap;\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nimport { createEnumStyle } from \"./EnumHelperFuncs\";\nexport var ActiveStatus = createEnumStyle({\n NONE: 0 /* eActiveStatus.NONE */,\n PENDING: 3 /* eActiveStatus.PENDING */,\n INACTIVE: 1 /* eActiveStatus.INACTIVE */,\n ACTIVE: 2 /* eActiveStatus.ACTIVE */\n});\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n// @skip-file-minify\n// ##############################################################\n// AUTO GENERATED FILE: This file is Auto Generated during build.\n// ##############################################################\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n// Note: DON'T Export these const from the package as we are still targeting ES5 which can result in a mutable variables that someone could change!!!\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nexport var _DYN_TO_LOWER_CASE = \"toLowerCase\"; // Count: 11\nexport var _DYN_LENGTH = \"length\"; // Count: 55\nexport var _DYN_WARN_TO_CONSOLE = \"warnToConsole\"; // Count: 4\nexport var _DYN_THROW_INTERNAL = \"throwInternal\"; // Count: 5\nexport var _DYN_WATCH = \"watch\"; // Count: 7\nexport var _DYN_APPLY = \"apply\"; // Count: 7\nexport var _DYN_PUSH = \"push\"; // Count: 35\nexport var _DYN_SPLICE = \"splice\"; // Count: 8\nexport var _DYN_LOGGER = \"logger\"; // Count: 20\nexport var _DYN_CANCEL = \"cancel\"; // Count: 6\nexport var _DYN_INITIALIZE = \"initialize\"; // Count: 5\nexport var _DYN_IDENTIFIER = \"identifier\"; // Count: 8\nexport var _DYN_REMOVE_NOTIFICATION_0 = \"removeNotificationListener\"; // Count: 4\nexport var _DYN_ADD_NOTIFICATION_LIS1 = \"addNotificationListener\"; // Count: 4\nexport var _DYN_IS_INITIALIZED = \"isInitialized\"; // Count: 10\nexport var _DYN_VALUE = \"value\"; // Count: 5\nexport var _DYN_GET_NOTIFY_MGR = \"getNotifyMgr\"; // Count: 5\nexport var _DYN_GET_PLUGIN = \"getPlugin\"; // Count: 5\nexport var _DYN_NAME = \"name\"; // Count: 9\nexport var _DYN_PROCESS_NEXT = \"processNext\"; // Count: 15\nexport var _DYN_GET_PROCESS_TEL_CONT2 = \"getProcessTelContext\"; // Count: 2\nexport var _DYN_ENABLED = \"enabled\"; // Count: 6\nexport var _DYN_STOP_POLLING_INTERNA3 = \"stopPollingInternalLogs\"; // Count: 2\nexport var _DYN_UNLOAD = \"unload\"; // Count: 7\nexport var _DYN_ON_COMPLETE = \"onComplete\"; // Count: 4\nexport var _DYN_VERSION = \"version\"; // Count: 4\nexport var _DYN_LOGGING_LEVEL_CONSOL4 = \"loggingLevelConsole\"; // Count: 2\nexport var _DYN_CREATE_NEW = \"createNew\"; // Count: 7\nexport var _DYN_TEARDOWN = \"teardown\"; // Count: 9\nexport var _DYN_MESSAGE_ID = \"messageId\"; // Count: 4\nexport var _DYN_MESSAGE = \"message\"; // Count: 7\nexport var _DYN_DIAG_LOG = \"diagLog\"; // Count: 9\nexport var _DYN__DO_TEARDOWN = \"_doTeardown\"; // Count: 5\nexport var _DYN_UPDATE = \"update\"; // Count: 5\nexport var _DYN_GET_NEXT = \"getNext\"; // Count: 10\nexport var _DYN_SET_NEXT_PLUGIN = \"setNextPlugin\"; // Count: 5\nexport var _DYN_USER_AGENT = \"userAgent\"; // Count: 5\nexport var _DYN_SPLIT = \"split\"; // Count: 7\nexport var _DYN_REPLACE = \"replace\"; // Count: 9\nexport var _DYN_TYPE = \"type\"; // Count: 13\nexport var _DYN_EVT_NAME = \"evtName\"; // Count: 4\nexport var _DYN_STATUS = \"status\"; // Count: 5\nexport var _DYN_GET_ALL_RESPONSE_HEA5 = \"getAllResponseHeaders\"; // Count: 2\nexport var _DYN_IS_CHILD_EVT = \"isChildEvt\"; // Count: 3\nexport var _DYN_DATA = \"data\"; // Count: 6\nexport var _DYN_GET_CTX = \"getCtx\"; // Count: 6\nexport var _DYN_SET_CTX = \"setCtx\"; // Count: 10\nexport var _DYN_ITEMS_RECEIVED = \"itemsReceived\"; // Count: 3\nexport var _DYN_URL_STRING = \"urlString\"; // Count: 5\nexport var _DYN_HEADERS = \"headers\"; // Count: 5\nexport var _DYN_TIMEOUT = \"timeout\"; // Count: 6\nexport var _DYN_TRACE_FLAGS = \"traceFlags\"; // Count: 5\nexport var _DYN_GET_ATTRIBUTE = \"getAttribute\"; // Count: 3\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { arrForEach, createCustomError, dumpObj } from \"@nevware21/ts-utils\";\nimport { _DYN_LENGTH } from \"../__DynamicConstants\";\nvar aggregationErrorType;\n/**\r\n * Throws an Aggregation Error which includes all of the errors that led to this error occurring\r\n * @param message - The message describing the aggregation error (the sourceError details are added to this)\r\n * @param sourceErrors - An array of the errors that caused this situation\r\n */\nexport function throwAggregationError(message, sourceErrors) {\n if (!aggregationErrorType) {\n aggregationErrorType = createCustomError(\"AggregationError\", function (self, args) {\n if (args[_DYN_LENGTH /* @min:%2elength */] > 1) {\n // Save the provided errors\n self.errors = args[1];\n }\n });\n }\n var theMessage = message || \"One or more errors occurred.\";\n arrForEach(sourceErrors, function (srcError, idx) {\n theMessage += \"\\n\".concat(idx, \" > \").concat(dumpObj(srcError));\n });\n throw new aggregationErrorType(theMessage, sourceErrors || []);\n}\n","/*!\n * NevWare21 Solutions LLC - ts-async, 0.5.4\n * https://github.com/nevware21/ts-async\n * Copyright (c) NevWare21 Solutions LLC and contributors. All rights reserved.\n * Licensed under the MIT license.\n */\nimport { isPromiseLike, objDefineProperties, getDocument, createCachedValue, safe, getInst, dumpObj, arrSlice, objDefineProp, hasSymbol, getKnownSymbol, isFunction, throwTypeError, iterForOf, scheduleTimeout, isNode, getWindow, getGlobal, objDefine, objToString, isUndefined, isArray, arrForEach, isIterable, createCustomError, isNumber, scheduleIdleCallback, utcNow, getLength, isIterator, fnCall, arrIndexOf } from '@nevware21/ts-utils';\nvar STR_PROMISE = \"Promise\";\nvar DONE = \"done\";\nvar VALUE = \"value\";\nvar RETURN = \"return\";\nvar REJECTED = \"rejected\";\nfunction doAwaitResponse(value, cb) {\n return doAwait(value, function (value) {\n return cb ? cb({\n status: \"fulfilled\",\n rejected: false,\n value: value\n }) : value;\n }, function (reason) {\n return cb ? cb({\n status: REJECTED,\n rejected: true,\n reason: reason\n }) : reason;\n });\n}\nfunction doAwait(value, resolveFn, rejectFn, finallyFn) {\n var result = value;\n try {\n if (isPromiseLike(value)) {\n if (resolveFn || rejectFn) {\n result = value.then(resolveFn, rejectFn);\n }\n } else {\n try {\n if (resolveFn) {\n result = resolveFn(value);\n }\n } catch (err) {\n if (rejectFn) {\n result = rejectFn(err);\n } else {\n throw err;\n }\n }\n }\n } finally {\n if (finallyFn) {\n doFinally(result, finallyFn);\n }\n }\n return result;\n}\nfunction doFinally(value, finallyFn) {\n var result = value;\n if (finallyFn) {\n if (isPromiseLike(value)) {\n if (value.finally) {\n result = value.finally(finallyFn);\n } else {\n result = value.then(function (value) {\n finallyFn();\n return value;\n }, function (reason) {\n finallyFn();\n throw reason;\n });\n }\n } else {\n finallyFn();\n }\n }\n return result;\n}\n\n/*#__NO_SIDE_EFFECTS__*/\nfunction _pureAssign(func1, func2) {\n return func1 || func2;\n}\nvar _debugState;\nvar _debugResult;\nvar _debugHandled;\nvar _promiseDebugEnabled = false;\nfunction _addDebugState$1(thePromise, stateFn, resultFn, handledFn) {\n _debugState = _debugState || {\n toString: function () {\n return \"[[PromiseState]]\";\n }\n };\n _debugResult = _debugResult || {\n toString: function () {\n return \"[[PromiseResult]]\";\n }\n };\n _debugHandled = _debugHandled || {\n toString: function () {\n return \"[[PromiseIsHandled]]\";\n }\n };\n var props = {};\n props[_debugState] = {\n get: stateFn\n };\n props[_debugResult] = {\n get: resultFn\n };\n props[_debugHandled] = {\n get: handledFn\n };\n objDefineProperties(thePromise, props);\n}\nfunction setPromiseDebugState(enabled, logger) {\n _promiseDebugEnabled = enabled;\n}\nvar STRING_STATES = [\"pending\", \"resolving\", \"resolved\", REJECTED];\nvar DISPATCH_EVENT = \"dispatchEvent\";\nvar _hasInitEvent;\nfunction _hasInitEventFn(doc) {\n var evt;\n if (doc && doc.createEvent) {\n evt = doc.createEvent(\"Event\");\n }\n return !!evt && evt.initEvent;\n}\nfunction emitEvent(target, evtName, populateEvent, useNewEvent) {\n var doc = getDocument();\n !_hasInitEvent && (_hasInitEvent = createCachedValue(!!safe(_hasInitEventFn, [doc]).v));\n var theEvt = _hasInitEvent.v ? doc.createEvent(\"Event\") : useNewEvent ? new Event(evtName) : {};\n populateEvent && populateEvent(theEvt);\n if (_hasInitEvent.v) {\n theEvt.initEvent(evtName, false, true);\n }\n if (theEvt && target[DISPATCH_EVENT]) {\n target[DISPATCH_EVENT](theEvt);\n } else {\n var handler = target[\"on\" + evtName];\n if (handler) {\n handler(theEvt);\n } else {\n var theConsole = getInst(\"console\");\n theConsole && (theConsole[\"error\"] || theConsole[\"log\"])(evtName, dumpObj(theEvt));\n }\n }\n}\nvar NODE_UNHANDLED_REJECTION = \"unhandledRejection\";\nvar UNHANDLED_REJECTION = NODE_UNHANDLED_REJECTION.toLowerCase();\nvar _currentPromiseId = [];\nvar _uniquePromiseId = 0;\nvar _unhandledRejectionTimeout = 10;\nvar _aggregationError;\nvar _hasPromiseRejectionEvent;\nfunction dumpFnObj(value) {\n if (isFunction(value)) {\n return value.toString();\n }\n return dumpObj(value);\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction _createAggregationError(values) {\n !_aggregationError && (_aggregationError = createCachedValue(safe(getInst, [\"AggregationError\"]).v || createCustomError(\"AggregationError\", function (self, args) {\n self.errors = args[0];\n })));\n return new _aggregationError.v(values);\n}\nfunction _createPromise(newPromise, processor, executor) {\n var additionalArgs = arrSlice(arguments, 3);\n var _state = 0;\n var _hasResolved = false;\n var _settledValue;\n var _queue = [];\n var _id = _uniquePromiseId++;\n var _parentId = _currentPromiseId.length > 0 ? _currentPromiseId[_currentPromiseId.length - 1] : undefined;\n var _handled = false;\n var _unHandledRejectionHandler = null;\n var _thePromise;\n function _then(onResolved, onRejected) {\n try {\n _currentPromiseId.push(_id);\n _handled = true;\n _unHandledRejectionHandler && _unHandledRejectionHandler.cancel();\n _unHandledRejectionHandler = null;\n var thenPromise = newPromise(function (resolve, reject) {\n _queue.push(function () {\n try {\n var handler = _state === 2 ? onResolved : onRejected;\n var value = isUndefined(handler) ? _settledValue : isFunction(handler) ? handler(_settledValue) : handler;\n if (isPromiseLike(value)) {\n value.then(resolve, reject);\n } else if (handler) {\n resolve(value);\n } else if (_state === 3) {\n reject(value);\n } else {\n resolve(value);\n }\n } catch (e) {\n reject(e);\n }\n });\n if (_hasResolved) {\n _processQueue();\n }\n }, additionalArgs);\n return thenPromise;\n } finally {\n _currentPromiseId.pop();\n }\n }\n function _catch(onRejected) {\n return _then(undefined, onRejected);\n }\n function _finally(onFinally) {\n var thenFinally = onFinally;\n var catchFinally = onFinally;\n if (isFunction(onFinally)) {\n thenFinally = function (value) {\n onFinally && onFinally();\n return value;\n };\n catchFinally = function (reason) {\n onFinally && onFinally();\n throw reason;\n };\n }\n return _then(thenFinally, catchFinally);\n }\n function _strState() {\n return STRING_STATES[_state];\n }\n function _processQueue() {\n if (_queue.length > 0) {\n var pending = _queue.slice();\n _queue = [];\n _handled = true;\n _unHandledRejectionHandler && _unHandledRejectionHandler.cancel();\n _unHandledRejectionHandler = null;\n processor(pending);\n }\n }\n function _createSettleIfFn(newState, allowState) {\n return function (theValue) {\n if (_state === allowState) {\n if (newState === 2 && isPromiseLike(theValue)) {\n _state = 1;\n theValue.then(_createSettleIfFn(2, 1), _createSettleIfFn(3, 1));\n return;\n }\n _state = newState;\n _hasResolved = true;\n _settledValue = theValue;\n _processQueue();\n if (!_handled && newState === 3 && !_unHandledRejectionHandler) {\n _unHandledRejectionHandler = scheduleTimeout(_notifyUnhandledRejection, _unhandledRejectionTimeout);\n }\n }\n };\n }\n function _notifyUnhandledRejection() {\n if (!_handled) {\n _handled = true;\n if (isNode()) {\n process.emit(NODE_UNHANDLED_REJECTION, _settledValue, _thePromise);\n } else {\n var gbl = getWindow() || getGlobal();\n !_hasPromiseRejectionEvent && (_hasPromiseRejectionEvent = createCachedValue(safe(getInst, [STR_PROMISE + \"RejectionEvent\"]).v));\n emitEvent(gbl, UNHANDLED_REJECTION, function (theEvt) {\n objDefine(theEvt, \"promise\", {\n g: function () {\n return _thePromise;\n }\n });\n theEvt.reason = _settledValue;\n return theEvt;\n }, !!_hasPromiseRejectionEvent.v);\n }\n }\n }\n _thePromise = {\n then: _then,\n \"catch\": _catch,\n finally: _finally\n };\n objDefineProp(_thePromise, \"state\", {\n get: _strState\n });\n if (_promiseDebugEnabled) {\n _addDebugState$1(_thePromise, _strState, function () {\n return objToString(_settledValue);\n }, function () {\n return _handled;\n });\n }\n if (hasSymbol()) {\n _thePromise[getKnownSymbol(11)] = \"IPromise\";\n }\n function _toString() {\n return \"IPromise\" + (_promiseDebugEnabled ? \"[\" + _id + (!isUndefined(_parentId) ? \":\" + _parentId : \"\") + \"]\" : \"\") + \" \" + _strState() + (_hasResolved ? \" - \" + dumpFnObj(_settledValue) : \"\") + \"\";\n }\n _thePromise.toString = _toString;\n (function _initialize() {\n if (!isFunction(executor)) {\n throwTypeError(STR_PROMISE + \": executor is not a function - \" + dumpFnObj(executor));\n }\n var _rejectFn = _createSettleIfFn(3, 0);\n try {\n executor.call(_thePromise, _createSettleIfFn(2, 0), _rejectFn);\n } catch (e) {\n _rejectFn(e);\n }\n })();\n return _thePromise;\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction _createAllPromise(newPromise) {\n return function (input) {\n var additionalArgs = arrSlice(arguments, 1);\n return newPromise(function (resolve, reject) {\n try {\n var values_1 = [];\n var pending_1 = 1;\n iterForOf(input, function (item, idx) {\n if (item) {\n pending_1++;\n doAwait(item, function (value) {\n values_1[idx] = value;\n if (--pending_1 === 0) {\n resolve(values_1);\n }\n }, reject);\n }\n });\n pending_1--;\n if (pending_1 === 0) {\n resolve(values_1);\n }\n } catch (e) {\n reject(e);\n }\n }, additionalArgs);\n };\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction _createResolvedPromise(newPromise) {\n return function (value) {\n var additionalArgs = arrSlice(arguments, 1);\n if (isPromiseLike(value)) {\n return value;\n }\n return newPromise(function (resolve) {\n resolve(value);\n }, additionalArgs);\n };\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction _createRejectedPromise(newPromise) {\n return function (reason) {\n var additionalArgs = arrSlice(arguments, 1);\n return newPromise(function (_resolve, reject) {\n reject(reason);\n }, additionalArgs);\n };\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction _createAllSettledPromise(newPromise) {\n return createCachedValue(function (input) {\n var additionalArgs = arrSlice(arguments, 1);\n return newPromise(function (resolve, reject) {\n var values = [];\n var pending = 1;\n function processItem(item, idx) {\n pending++;\n doAwaitResponse(item, function (value) {\n if (value.rejected) {\n values[idx] = {\n status: REJECTED,\n reason: value.reason\n };\n } else {\n values[idx] = {\n status: \"fulfilled\",\n value: value.value\n };\n }\n if (--pending === 0) {\n resolve(values);\n }\n });\n }\n try {\n if (isArray(input)) {\n arrForEach(input, processItem);\n } else if (isIterable(input)) {\n iterForOf(input, processItem);\n } else {\n throwTypeError(\"Input is not an iterable\");\n }\n pending--;\n if (pending === 0) {\n resolve(values);\n }\n } catch (e) {\n reject(e);\n }\n }, additionalArgs);\n });\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction _createRacePromise(newPromise) {\n return createCachedValue(function (input) {\n var additionalArgs = arrSlice(arguments, 1);\n return newPromise(function (resolve, reject) {\n var isDone = false;\n function processItem(item) {\n doAwaitResponse(item, function (value) {\n if (!isDone) {\n isDone = true;\n if (value.rejected) {\n reject(value.reason);\n } else {\n resolve(value.value);\n }\n }\n });\n }\n try {\n if (isArray(input)) {\n arrForEach(input, processItem);\n } else if (isIterable(input)) {\n iterForOf(input, processItem);\n } else {\n throwTypeError(\"Input is not an iterable\");\n }\n } catch (e) {\n reject(e);\n }\n }, additionalArgs);\n });\n}\n/*#__NO_SIDE_EFFECTS__*/\nfunction _createAnyPromise(newPromise) {\n return createCachedValue(function (input) {\n var additionalArgs = arrSlice(arguments, 1);\n return newPromise(function (resolve, reject) {\n var theErros = [];\n var pending = 1;\n var isDone = false;\n function processItem(item, idx) {\n pending++;\n doAwaitResponse(item, function (value) {\n if (!value.rejected) {\n isDone = true;\n resolve(value.value);\n return;\n } else {\n theErros[idx] = value.reason;\n }\n if (--pending === 0 && !isDone) {\n reject(_createAggregationError(theErros));\n }\n });\n }\n try {\n if (isArray(input)) {\n arrForEach(input, processItem);\n } else if (isIterable(input)) {\n iterForOf(input, processItem);\n } else {\n throwTypeError(\"Input is not an iterable\");\n }\n pending--;\n if (pending === 0 && !isDone) {\n reject(_createAggregationError(theErros));\n }\n } catch (e) {\n reject(e);\n }\n }, additionalArgs);\n });\n}\nfunction syncItemProcessor(pending) {\n arrForEach(pending, function (fn) {\n try {\n fn();\n } catch (e) {}\n });\n}\nfunction timeoutItemProcessor(timeout) {\n var callbackTimeout = isNumber(timeout) ? timeout : 0;\n return function (pending) {\n scheduleTimeout(function () {\n syncItemProcessor(pending);\n }, callbackTimeout);\n };\n}\nfunction idleItemProcessor(timeout) {\n var options;\n if (timeout >= 0) {\n options = {\n timeout: +timeout\n };\n }\n return function (pending) {\n scheduleIdleCallback(function (deadline) {\n syncItemProcessor(pending);\n }, options);\n };\n}\nvar _allAsyncSettledCreator;\nvar _raceAsyncCreator;\nvar _anyAsyncCreator;\nfunction createAsyncPromise(executor, timeout) {\n return _createPromise(createAsyncPromise, timeoutItemProcessor(timeout), executor, timeout);\n}\nvar createAsyncAllPromise = /*#__PURE__*/_createAllPromise(createAsyncPromise);\nvar createAsyncResolvedPromise = /*#__PURE__*/_createResolvedPromise(createAsyncPromise);\nvar createAsyncRejectedPromise = /*#__PURE__*/_createRejectedPromise(createAsyncPromise);\nfunction createAsyncAllSettledPromise(input, timeout) {\n !_allAsyncSettledCreator && (_allAsyncSettledCreator = _createAllSettledPromise(createAsyncPromise));\n return _allAsyncSettledCreator.v(input, timeout);\n}\nfunction createAsyncRacePromise(values, timeout) {\n !_raceAsyncCreator && (_raceAsyncCreator = _createRacePromise(createAsyncPromise));\n return _raceAsyncCreator.v(values, timeout);\n}\nfunction createAsyncAnyPromise(values, timeout) {\n !_anyAsyncCreator && (_anyAsyncCreator = _createAnyPromise(createAsyncPromise));\n return _anyAsyncCreator.v(values, timeout);\n}\nvar _promiseCls;\nvar _allCreator;\nvar _allNativeSettledCreator;\nvar _raceNativeCreator;\nvar _anyNativeCreator;\n/*#__NO_SIDE_EFFECTS__*/\nfunction _createNativePromiseHelper(name, func) {\n !_promiseCls && (_promiseCls = createCachedValue(safe(getInst, [STR_PROMISE]).v || null));\n if (_promiseCls.v && _promiseCls.v[name]) {\n return createCachedValue(function (input, timeout) {\n return createNativePromise(function (resolve, reject) {\n _promiseCls.v[name](input).then(resolve, reject);\n });\n });\n }\n return func();\n}\nfunction createNativePromise(executor, timeout) {\n !_promiseCls && (_promiseCls = createCachedValue(safe(getInst, [STR_PROMISE]).v || null));\n var PrmCls = _promiseCls.v;\n if (!PrmCls) {\n return createAsyncPromise(executor);\n }\n if (!isFunction(executor)) {\n throwTypeError(STR_PROMISE + \": executor is not a function - \" + dumpObj(executor));\n }\n var _state = 0;\n function _strState() {\n return STRING_STATES[_state];\n }\n var thePromise = new PrmCls(function (resolve, reject) {\n function _resolve(value) {\n _state = 2;\n resolve(value);\n }\n function _reject(reason) {\n _state = 3;\n reject(reason);\n }\n executor(_resolve, _reject);\n });\n objDefineProp(thePromise, \"state\", {\n get: _strState\n });\n return thePromise;\n}\nfunction createNativeAllPromise(input, timeout) {\n !_allCreator && (_allCreator = _createNativePromiseHelper(\"all\", function () {\n return createCachedValue(_createAllPromise(createNativePromise));\n }));\n return _allCreator.v(input, timeout);\n}\nvar createNativeResolvedPromise = /*#__PURE__*/_createResolvedPromise(createNativePromise);\nvar createNativeRejectedPromise = /*#__PURE__*/_createRejectedPromise(createNativePromise);\nfunction createNativeAllSettledPromise(input, timeout) {\n !_allNativeSettledCreator && (_allNativeSettledCreator = _createNativePromiseHelper(\"allSettled\", function () {\n return _createAllSettledPromise(createNativePromise);\n }));\n return _allNativeSettledCreator.v(input, timeout);\n}\nfunction createNativeRacePromise(values, timeout) {\n !_raceNativeCreator && (_raceNativeCreator = _createNativePromiseHelper(\"race\", function () {\n return _createRacePromise(createNativePromise);\n }));\n return _raceNativeCreator.v(values, timeout);\n}\nfunction createNativeAnyPromise(values, timeout) {\n !_anyNativeCreator && (_anyNativeCreator = _createNativePromiseHelper(\"any\", function () {\n return _createAnyPromise(createNativePromise);\n }));\n return _anyNativeCreator.v(values, timeout);\n}\nvar _allSyncSettledCreator;\nvar _raceSyncCreator;\nvar _anySyncCreator;\nfunction createSyncPromise(executor) {\n return _createPromise(createSyncPromise, syncItemProcessor, executor);\n}\nvar createSyncAllPromise = /*#__PURE__*/_createAllPromise(createSyncPromise);\nvar createSyncResolvedPromise = /*#__PURE__*/_createResolvedPromise(createSyncPromise);\nvar createSyncRejectedPromise = /*#__PURE__*/_createRejectedPromise(createSyncPromise);\nfunction createSyncAllSettledPromise(input, timeout) {\n !_allSyncSettledCreator && (_allSyncSettledCreator = _createAllSettledPromise(createSyncPromise));\n return _allSyncSettledCreator.v(input, timeout);\n}\nfunction createSyncRacePromise(values, timeout) {\n !_raceSyncCreator && (_raceSyncCreator = _createRacePromise(createSyncPromise));\n return _raceSyncCreator.v(values, timeout);\n}\nfunction createSyncAnyPromise(values, timeout) {\n !_anySyncCreator && (_anySyncCreator = _createAnyPromise(createSyncPromise));\n return _anySyncCreator.v(values, timeout);\n}\nvar _defaultIdleTimeout;\nvar _allIdleSettledCreator;\nvar _raceIdleCreator;\nvar _anyIdleCreator;\nfunction setDefaultIdlePromiseTimeout(idleDeadline) {\n _defaultIdleTimeout = idleDeadline;\n}\nvar setDefaultIdleTimeout = /*#__PURE__*/_pureAssign(setDefaultIdlePromiseTimeout);\nfunction createIdlePromise(executor, timeout) {\n var theTimeout = isUndefined(timeout) ? _defaultIdleTimeout : timeout;\n return _createPromise(createIdlePromise, idleItemProcessor(theTimeout), executor, theTimeout);\n}\nvar createIdleAllPromise = /*#__PURE__*/_createAllPromise(createIdlePromise);\nvar createIdleResolvedPromise = /*#__PURE__*/_createResolvedPromise(createIdlePromise);\nvar createIdleRejectedPromise = /*#__PURE__*/_createRejectedPromise(createIdlePromise);\nfunction createIdleAllSettledPromise(input, timeout) {\n !_allIdleSettledCreator && (_allIdleSettledCreator = _createAllSettledPromise(createIdlePromise));\n return _allIdleSettledCreator.v(input, timeout);\n}\nfunction createIdleRacePromise(values, timeout) {\n !_raceIdleCreator && (_raceIdleCreator = _createRacePromise(createIdlePromise));\n return _raceIdleCreator.v(values, timeout);\n}\nfunction createIdleAnyPromise(values, timeout) {\n !_anyIdleCreator && (_anyIdleCreator = _createAnyPromise(createIdlePromise));\n return _anyIdleCreator.v(values, timeout);\n}\nvar _promiseCreator;\nvar _allSettledCreator;\nvar _raceCreator;\nvar _anyCreator;\nfunction setCreatePromiseImpl(creator) {\n _promiseCreator = creator ? createCachedValue(creator) : null;\n}\nfunction createPromise(executor, timeout) {\n !_promiseCreator && (_promiseCreator = createCachedValue(createNativePromise));\n return _promiseCreator.v.call(this, executor, timeout);\n}\nvar createAllPromise = /*#__PURE__*/_createAllPromise(createPromise);\nvar createResolvedPromise = /*#__PURE__*/_createResolvedPromise(createPromise);\nvar createRejectedPromise = /*#__PURE__*/_createRejectedPromise(createPromise);\nfunction createAllSettledPromise(input, timeout) {\n !_allSettledCreator && (_allSettledCreator = _createAllSettledPromise(createPromise));\n return _allSettledCreator.v(input, timeout);\n}\nfunction createRacePromise(values, timeout) {\n !_raceCreator && (_raceCreator = _createRacePromise(createPromise));\n return _raceCreator.v(values, timeout);\n}\nfunction createAnyPromise(values, timeout) {\n !_anyCreator && (_anyCreator = _createAnyPromise(createPromise));\n return _anyCreator.v(values, timeout);\n}\nfunction createTimeoutPromise(timeout, resolveReject, message) {\n return createPromise(function (resolve, reject) {\n scheduleTimeout(function () {\n (resolveReject ? resolve : reject)(!isUndefined(message) ? message : \"Timeout of \" + timeout + \"ms exceeded\");\n }, timeout);\n });\n}\nfunction _doneChk(isDone, state, value, thisArg) {\n var result = isDone;\n state.res = value;\n if (!result) {\n if (state.isDone && isFunction(state.isDone)) {\n return doAwait(state.isDone.call(thisArg, state), function (done) {\n state.iter++;\n return !!done;\n });\n } else {\n result = !!state.isDone;\n }\n }\n state.iter++;\n return result;\n}\nfunction doWhileAsync(callbackFn, isDoneFn, thisArg) {\n var promise;\n var resolve;\n var reject = function (reason) {\n isDone = true;\n throw reason;\n };\n var isDone = false;\n var state = {\n st: utcNow(),\n iter: 0,\n isDone: isDoneFn || false\n };\n if (callbackFn) {\n var _createPromise_1 = function () {\n return createPromise(function (res, rej) {\n resolve = res;\n reject = rej;\n });\n };\n var _handleAsyncDone_1 = function (done) {\n isDone = !!done;\n if (!isDone) {\n _processNext_1();\n } else {\n resolve(state.res);\n }\n };\n var _processNext_1 = function () {\n while (!isDone) {\n try {\n var cbResult = callbackFn.call(thisArg, state);\n if (isPromiseLike(cbResult)) {\n promise = promise || _createPromise_1();\n doAwait(cbResult, function (res) {\n try {\n doAwait(_doneChk(isDone, state, res, thisArg), _handleAsyncDone_1, reject);\n } catch (e) {\n reject(e);\n }\n }, reject);\n return promise;\n } else {\n var dnRes = _doneChk(isDone, state, cbResult, thisArg);\n if (isPromiseLike(dnRes)) {\n promise = promise || _createPromise_1();\n doAwait(dnRes, _handleAsyncDone_1, reject);\n return promise;\n } else {\n isDone = !!dnRes;\n }\n }\n } catch (e) {\n reject(e);\n return promise;\n }\n }\n if (isDone && resolve) {\n resolve(state.res);\n }\n return promise || state.res;\n };\n return _processNext_1();\n }\n}\nfunction arrForEachAsync(theArray, callbackFn, thisArg) {\n if (theArray) {\n var len_1 = getLength(theArray);\n if (len_1) {\n var isDone = function (state) {\n if (state.iter >= len_1 || state.res === -1) {\n return true;\n }\n };\n return doWhileAsync(function (state) {\n var idx = state.iter;\n if (idx in theArray) {\n return callbackFn.call(thisArg || theArray, theArray[idx], idx, theArray);\n }\n }, isDone);\n }\n }\n}\nvar _iterSymbol;\nvar _iterAsyncSymbol;\nfunction iterForOfAsync(iter, callbackFn, thisArg) {\n var err;\n var iterResult;\n var theIter = iter;\n function onFailed(failed) {\n err = {\n e: failed\n };\n if (theIter.throw) {\n iterResult = null;\n theIter.throw(err);\n }\n throw failed;\n }\n function onFinally() {\n try {\n if (iterResult && !iterResult[DONE]) {\n theIter[RETURN] && theIter[RETURN](iterResult);\n }\n } finally {\n if (err) {\n throw err.e;\n }\n }\n }\n if (iter) {\n if (!isIterator(iter)) {\n !_iterAsyncSymbol && (_iterAsyncSymbol = createCachedValue(getKnownSymbol(0)));\n theIter = iter[_iterAsyncSymbol.v] ? iter[_iterAsyncSymbol.v]() : null;\n if (!theIter) {\n !_iterSymbol && (_iterSymbol = createCachedValue(getKnownSymbol(3)));\n theIter = iter[_iterSymbol.v] ? iter[_iterSymbol.v]() : null;\n }\n }\n if (theIter && isIterator(theIter)) {\n var result = void 0;\n try {\n result = doWhileAsync(function (state) {\n return doAwait(theIter.next(), function (res) {\n iterResult = res;\n if (!res[DONE]) {\n return fnCall(callbackFn, thisArg || theIter, iterResult[VALUE], state.iter, theIter);\n }\n }, function (reason) {\n state.isDone = true;\n onFailed(reason);\n });\n }, function (state) {\n if (!iterResult || iterResult[DONE] || state.res === -1) {\n onFinally();\n return true;\n }\n }, thisArg || theIter);\n if (isPromiseLike(result)) {\n result = doFinally(result.catch(onFailed), onFinally);\n }\n return result;\n } catch (failed) {\n onFailed(failed);\n } finally {\n if (result && !isPromiseLike(result)) {\n onFinally();\n }\n }\n }\n }\n}\nvar REJECT = \"reject\";\nvar REJECTED_ERROR = \"Rejected\";\nvar _schedulerId = 0;\nvar _debugName;\nvar _debugIntState;\nvar _customErrors = {};\nfunction _rejectDone() {}\nfunction _createError(type, evt, message) {\n !_customErrors[type] && (_customErrors[type] = createCustomError(type));\n var now = utcNow();\n return new _customErrors[type](\"Task [\".concat(evt.id, \"] \").concat(message || \"\", \"- \").concat(evt.st ? \"Running\" : \"Waiting\", \": \").concat(_calcTime(now, evt.st || evt.cr)));\n}\nfunction _calcTime(now, start) {\n return (now - start || \"0\") + \" ms\";\n}\nfunction _abortStaleTasks(taskQueue, staleTimeoutPeriod) {\n var now = utcNow();\n var expired = now - staleTimeoutPeriod;\n arrForEach(taskQueue, function (evt) {\n if (evt && !evt.rj && evt.st && evt.st < expired || !evt.st && evt.cr && evt.cr < expired) {\n evt && evt[REJECT](evt.rj || _createError(\"Aborted\", evt, \"Stale \"));\n }\n });\n}\nfunction _removeTask(queue, taskDetail) {\n var idx = arrIndexOf(queue, taskDetail);\n if (idx !== -1) {\n queue.splice(idx, 1);\n }\n}\nfunction _addDebugState(theScheduler, nameFn, stateFn) {\n _debugName = _debugName || {\n toString: function () {\n return \"[[SchedulerName]]\";\n }\n };\n _debugIntState = _debugIntState || {\n toString: function () {\n return \"[[SchedulerState]]\";\n }\n };\n objDefineProp(theScheduler, _debugName, {\n get: nameFn\n });\n objDefineProp(theScheduler, _debugIntState, {\n get: stateFn\n });\n}\nfunction createTaskScheduler(newPromise, name) {\n var _theTask;\n var _running = [];\n var _waiting = [];\n var _staleTimeoutPeriod = 600000;\n var _staleTimeoutCheckPeriod = _staleTimeoutPeriod / 10;\n var _taskCount = 0;\n var _schedulerName = (name ? name + \".\" : \"\") + _schedulerId++;\n var _blockedTimer;\n newPromise = newPromise || createPromise;\n var _startBlockedTimer = function () {\n var hasTasks = getLength(_running) + getLength(_waiting) > 0;\n if (_staleTimeoutPeriod > 0) {\n if (!_blockedTimer) {\n _blockedTimer = scheduleTimeout(function () {\n _abortStaleTasks(_running, _staleTimeoutPeriod);\n _abortStaleTasks(_waiting, _staleTimeoutPeriod);\n _blockedTimer && (_blockedTimer.enabled = getLength(_running) + getLength(_waiting) > 0);\n }, _staleTimeoutCheckPeriod);\n _blockedTimer.unref();\n }\n _blockedTimer && (_blockedTimer.enabled = hasTasks);\n }\n };\n var _queueTask = function (startAction, taskName, timeout) {\n var _a;\n var taskId = _schedulerName + \".\" + _taskCount++;\n if (taskName) {\n taskId += \"-(\" + taskName + \")\";\n }\n var newTask = (_a = {\n id: taskId,\n cr: utcNow(),\n to: timeout\n }, _a[REJECT] = function (reason) {\n newTask.rj = reason || _createError(REJECTED_ERROR, newTask);\n newTask[REJECT] = _rejectDone;\n }, _a);\n if (!_theTask) {\n newTask.p = newPromise(_runTask(newTask, startAction));\n } else {\n newTask.p = _waitForPreviousTask(newTask, _theTask, startAction);\n }\n _theTask = newTask;\n return newTask.p;\n };\n var _runTask = function (taskDetail, startAction) {\n taskDetail.st = utcNow();\n _running.push(taskDetail);\n _startBlockedTimer();\n return function (onTaskResolve, onTaskReject) {\n var _promiseReject = function (reason) {\n taskDetail.rj = taskDetail.rj || reason || _createError(REJECTED_ERROR, taskDetail);\n taskDetail[REJECT] = _rejectDone;\n _doCleanup(taskDetail);\n onTaskResolve = null;\n onTaskReject && onTaskReject(reason);\n onTaskReject = null;\n };\n var taskId = taskDetail.id;\n if (taskDetail.rj) {\n _promiseReject(taskDetail.rj);\n } else {\n taskDetail[REJECT] = _promiseReject;\n try {\n var startResult = startAction(taskId);\n if (taskDetail.to && isPromiseLike(startResult)) {\n taskDetail.t = scheduleTimeout(function () {\n _promiseReject(_createError(\"Timeout\", taskDetail));\n }, taskDetail.to);\n }\n doAwait(startResult, function (theResult) {\n _doCleanup(taskDetail);\n try {\n onTaskResolve && onTaskResolve(theResult);\n } catch (e) {\n onTaskReject && onTaskReject(e);\n }\n onTaskReject = null;\n onTaskResolve = null;\n }, _promiseReject);\n } catch (e) {\n _promiseReject(e);\n }\n }\n };\n };\n var _waitForPreviousTask = function (taskDetail, prevTask, startAction) {\n _waiting.push(taskDetail);\n _startBlockedTimer();\n return newPromise(function (onWaitResolve, onWaitReject) {\n doAwaitResponse(prevTask.p, function () {\n _removeTask(_waiting, taskDetail);\n _runTask(taskDetail, startAction)(onWaitResolve, onWaitReject);\n });\n });\n };\n var _doCleanup = function (taskDetail) {\n _removeTask(_running, taskDetail);\n taskDetail.t && taskDetail.t.cancel();\n taskDetail.t = null;\n if (_theTask && _theTask === taskDetail) {\n _theTask = null;\n if (getLength(_running) + getLength(_waiting) === 0) {\n _blockedTimer && _blockedTimer.cancel();\n _blockedTimer = null;\n }\n }\n };\n var theScheduler = {\n idle: true,\n queue: _queueTask,\n setStaleTimeout: function (staleTimeout, staleCheckPeriod) {\n _blockedTimer && _blockedTimer.cancel();\n _blockedTimer = null;\n _staleTimeoutPeriod = staleTimeout;\n _staleTimeoutCheckPeriod = staleCheckPeriod || staleTimeout / 10;\n _startBlockedTimer();\n }\n };\n objDefine(theScheduler, \"idle\", {\n g: function () {\n return getLength(_running) + getLength(_waiting) === 0;\n }\n });\n _addDebugState(theScheduler, function () {\n return _schedulerName;\n }, function () {\n return {\n l: _theTask,\n r: _running,\n w: _waiting\n };\n });\n return theScheduler;\n}\nvar toStringTagSymbol = getKnownSymbol(11);\nvar PolyPromise = /*#__PURE__*/function () {\n function PolyPromiseImpl(executor) {\n this._$ = createAsyncPromise(executor);\n if (toStringTagSymbol) {\n this[toStringTagSymbol] = \"Promise\";\n }\n objDefineProp(this, \"state\", {\n get: function () {\n return this._$.state;\n }\n });\n }\n PolyPromiseImpl.all = createAsyncAllPromise;\n PolyPromiseImpl.race = createAsyncRacePromise;\n PolyPromiseImpl.any = createAsyncAnyPromise;\n PolyPromiseImpl.reject = createAsyncRejectedPromise;\n PolyPromiseImpl.resolve = createAsyncResolvedPromise;\n PolyPromiseImpl.allSettled = createAsyncAllSettledPromise;\n var theProto = PolyPromiseImpl.prototype;\n theProto.then = function (onResolved, onRejected) {\n return this._$.then(onResolved, onRejected);\n };\n theProto.catch = function (onRejected) {\n return this._$.catch(onRejected);\n };\n theProto.finally = function (onfinally) {\n return this._$.finally(onfinally);\n };\n return PolyPromiseImpl;\n}();\nexport { PolyPromise, arrForEachAsync, createAllPromise, createAllSettledPromise, createAnyPromise, createAsyncAllPromise, createAsyncAllSettledPromise, createAsyncAnyPromise, createAsyncPromise, createAsyncRacePromise, createAsyncRejectedPromise, createAsyncResolvedPromise, createIdleAllPromise, createIdleAllSettledPromise, createIdleAnyPromise, createIdlePromise, createIdleRacePromise, createIdleRejectedPromise, createIdleResolvedPromise, createNativeAllPromise, createNativeAllSettledPromise, createNativeAnyPromise, createNativePromise, createNativeRacePromise, createNativeRejectedPromise, createNativeResolvedPromise, createPromise, createRacePromise, createRejectedPromise, createResolvedPromise, createSyncAllPromise, createSyncAllSettledPromise, createSyncAnyPromise, createSyncPromise, createSyncRacePromise, createSyncRejectedPromise, createSyncResolvedPromise, createTaskScheduler, createTimeoutPromise, doAwait, doAwaitResponse, doFinally, doWhileAsync, iterForOfAsync, setCreatePromiseImpl, setDefaultIdlePromiseTimeout, setDefaultIdleTimeout, setPromiseDebugState };\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n// ###################################################################################################################################################\n// Note: DON'T Export these const from the package as we are still targeting IE/ES5 this will export a mutable variables that someone could change ###\n// ###################################################################################################################################################\nexport var UNDEFINED_VALUE = undefined;\nexport var STR_EMPTY = \"\";\nexport var STR_CHANNELS = \"channels\";\nexport var STR_CORE = \"core\";\nexport var STR_CREATE_PERF_MGR = \"createPerfMgr\";\nexport var STR_DISABLED = \"disabled\";\nexport var STR_EXTENSION_CONFIG = \"extensionConfig\";\nexport var STR_EXTENSIONS = \"extensions\";\nexport var STR_PROCESS_TELEMETRY = \"processTelemetry\";\nexport var STR_PRIORITY = \"priority\";\nexport var STR_EVENTS_SENT = \"eventsSent\";\nexport var STR_EVENTS_DISCARDED = \"eventsDiscarded\";\nexport var STR_EVENTS_SEND_REQUEST = \"eventsSendRequest\";\nexport var STR_PERF_EVENT = \"perfEvent\";\nexport var STR_OFFLINE_STORE = \"offlineEventsStored\";\nexport var STR_OFFLINE_SENT = \"offlineBatchSent\";\nexport var STR_OFFLINE_DROP = \"offlineBatchDrop\";\nexport var STR_GET_PERF_MGR = \"getPerfMgr\";\nexport var STR_DOMAIN = \"domain\";\nexport var STR_PATH = \"path\";\nexport var STR_NOT_DYNAMIC_ERROR = \"Not dynamic - \";\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { ObjAssign, ObjClass } from \"@microsoft/applicationinsights-shims\";\nimport { arrForEach, asString as asString21, isArray, isBoolean, isError, isFunction, isNullOrUndefined, isNumber, isObject, isPlainObject, isString, isUndefined, objDeepFreeze, objDefine, objForEachKey, objHasOwn, strIndexOf, strTrim } from \"@nevware21/ts-utils\";\nimport { _DYN_APPLY, _DYN_GET_ALL_RESPONSE_HEA5, _DYN_LENGTH, _DYN_NAME, _DYN_REPLACE, _DYN_SPLIT, _DYN_STATUS, _DYN_TO_LOWER_CASE } from \"../__DynamicConstants\";\nimport { STR_EMPTY } from \"./InternalConstants\";\n// RESTRICT and AVOID circular dependencies you should not import other contained modules or export the contents of this file directly\n// Added to help with minification\nvar strGetPrototypeOf = \"getPrototypeOf\";\nvar rCamelCase = /-([a-z])/g;\nvar rNormalizeInvalid = /([^\\w\\d_$])/g;\nvar rLeadingNumeric = /^(\\d+[\\w\\d_$])/;\nexport var _getObjProto = Object[strGetPrototypeOf];\nexport function isNotUndefined(value) {\n return !isUndefined(value);\n}\nexport function isNotNullOrUndefined(value) {\n return !isNullOrUndefined(value);\n}\n/**\r\n * Validates that the string name conforms to the JS IdentifierName specification and if not\r\n * normalizes the name so that it would. This method does not identify or change any keywords\r\n * meaning that if you pass in a known keyword the same value will be returned.\r\n * This is a simplified version\r\n * @param name - The name to validate\r\n */\nexport function normalizeJsName(name) {\n var value = name;\n if (value && isString(value)) {\n // CamelCase everything after the \"-\" and remove the dash\n value = value[_DYN_REPLACE /* @min:%2ereplace */](rCamelCase, function (_all, letter) {\n return letter.toUpperCase();\n });\n value = value[_DYN_REPLACE /* @min:%2ereplace */](rNormalizeInvalid, \"_\");\n value = value[_DYN_REPLACE /* @min:%2ereplace */](rLeadingNumeric, function (_all, match) {\n return \"_\" + match;\n });\n }\n return value;\n}\n/**\r\n * A simple wrapper (for minification support) to check if the value contains the search string.\r\n * @param value - The string value to check for the existence of the search value\r\n * @param search - The value search within the value\r\n */\nexport function strContains(value, search) {\n if (value && search) {\n return strIndexOf(value, search) !== -1;\n }\n return false;\n}\n/**\r\n * Convert a date to I.S.O. format in IE8\r\n */\nexport function toISOString(date) {\n return date && date.toISOString() || \"\";\n}\nexport var deepFreeze = objDeepFreeze;\n/**\r\n * Returns the name of object if it's an Error. Otherwise, returns empty string.\r\n */\nexport function getExceptionName(object) {\n if (isError(object)) {\n return object[_DYN_NAME /* @min:%2ename */];\n }\n return STR_EMPTY;\n}\n/**\r\n * Sets the provided value on the target instance using the field name when the provided chk function returns true, the chk\r\n * function will only be called if the new value is no equal to the original value.\r\n * @param target - The target object\r\n * @param field - The key of the target\r\n * @param value - The value to set\r\n * @param valChk - [Optional] Callback to check the value that if supplied will be called check if the new value can be set\r\n * @param srcChk - [Optional] Callback to check to original value that if supplied will be called if the new value should be set (if allowed)\r\n * @returns The existing or new value, depending what was set\r\n */\nexport function setValue(target, field, value, valChk, srcChk) {\n var theValue = value;\n if (target) {\n theValue = target[field];\n if (theValue !== value && (!srcChk || srcChk(theValue)) && (!valChk || valChk(value))) {\n theValue = value;\n target[field] = theValue;\n }\n }\n return theValue;\n}\n/**\r\n * Returns the current value from the target object if not null or undefined otherwise sets the new value and returns it\r\n * @param target - The target object to return or set the default value\r\n * @param field - The key for the field to set on the target\r\n * @param defValue - [Optional] The value to set if not already present, when not provided a empty object will be added\r\n */\nexport function getSetValue(target, field, defValue) {\n var theValue;\n if (target) {\n theValue = target[field];\n if (!theValue && isNullOrUndefined(theValue)) {\n // Supports having the default as null\n theValue = !isUndefined(defValue) ? defValue : {};\n target[field] = theValue;\n }\n } else {\n // Expanded for performance so we only check defValue if required\n theValue = !isUndefined(defValue) ? defValue : {};\n }\n return theValue;\n}\nfunction _createProxyFunction(source, funcName) {\n var srcFunc = null;\n var src = null;\n if (isFunction(source)) {\n srcFunc = source;\n } else {\n src = source;\n }\n return function () {\n // Capture the original arguments passed to the method\n var originalArguments = arguments;\n if (srcFunc) {\n src = srcFunc();\n }\n if (src) {\n return src[funcName][_DYN_APPLY /* @min:%2eapply */](src, originalArguments);\n }\n };\n}\n/**\r\n * Effectively assigns all enumerable properties (not just own properties) and functions (including inherited prototype) from\r\n * the source object to the target, it attempts to use proxy getters / setters (if possible) and proxy functions to avoid potential\r\n * implementation issues by assigning prototype functions as instance ones\r\n *\r\n * This method is the primary method used to \"update\" the snippet proxy with the ultimate implementations.\r\n *\r\n * Special ES3 Notes:\r\n * Updates (setting) of direct property values on the target or indirectly on the source object WILL NOT WORK PROPERLY, updates to the\r\n * properties of \"referenced\" object will work (target.context.newValue = 10 =\\> will be reflected in the source.context as it's the\r\n * same object). ES3 Failures: assigning target.myProp = 3 -\\> Won't change source.myProp = 3, likewise the reverse would also fail.\r\n * @param target - The target object to be assigned with the source properties and functions\r\n * @param source - The source object which will be assigned / called by setting / calling the targets proxies\r\n * @param chkSet - An optional callback to determine whether a specific property/function should be proxied\r\n */\nexport function proxyAssign(target, source, chkSet) {\n if (target && source && isObject(target) && isObject(source)) {\n var _loop_1 = function (field) {\n if (isString(field)) {\n var value = source[field];\n if (isFunction(value)) {\n if (!chkSet || chkSet(field, true, source, target)) {\n // Create a proxy function rather than just copying the (possible) prototype to the new object as an instance function\n target[field] = _createProxyFunction(source, field);\n }\n } else if (!chkSet || chkSet(field, false, source, target)) {\n if (objHasOwn(target, field)) {\n // Remove any previous instance property\n delete target[field];\n }\n objDefine(target, field, {\n g: function () {\n return source[field];\n },\n s: function (theValue) {\n source[field] = theValue;\n }\n });\n }\n }\n };\n // effectively apply/proxy full source to the target instance\n for (var field in source) {\n _loop_1(field);\n }\n }\n return target;\n}\n/**\r\n * Creates a proxy function on the target which internally will call the source version with all arguments passed to the target method.\r\n *\r\n * @param target - The target object to be assigned with the source properties and functions\r\n * @param name - The function name that will be added on the target\r\n * @param source - The source object which will be assigned / called by setting / calling the targets proxies\r\n * @param theFunc - The function name on the source that will be proxied on the target\r\n * @param overwriteTarget - If `false` this will not replace any pre-existing name otherwise (the default) it will overwrite any existing name\r\n */\nexport function proxyFunctionAs(target, name, source, theFunc, overwriteTarget) {\n if (target && name && source) {\n if (overwriteTarget !== false || isUndefined(target[name])) {\n target[name] = _createProxyFunction(source, theFunc);\n }\n }\n}\n/**\r\n * Creates proxy functions on the target which internally will call the source version with all arguments passed to the target method.\r\n *\r\n * @param target - The target object to be assigned with the source properties and functions\r\n * @param source - The source object which will be assigned / called by setting / calling the targets proxies\r\n * @param functionsToProxy - An array of function names that will be proxied on the target\r\n * @param overwriteTarget - If false this will not replace any pre-existing name otherwise (the default) it will overwrite any existing name\r\n */\nexport function proxyFunctions(target, source, functionsToProxy, overwriteTarget) {\n if (target && source && isObject(target) && isArray(functionsToProxy)) {\n arrForEach(functionsToProxy, function (theFuncName) {\n if (isString(theFuncName)) {\n proxyFunctionAs(target, theFuncName, source, theFuncName, overwriteTarget);\n }\n });\n }\n return target;\n}\n/**\r\n * Simpler helper to create a dynamic class that implements the interface and populates the values with the defaults.\r\n * Only instance properties (hasOwnProperty) values are copied from the defaults to the new instance\r\n * @param defaults - Simple helper\r\n */\nexport function createClassFromInterface(defaults) {\n return /** @class */function () {\n function class_1() {\n var _this = this;\n if (defaults) {\n objForEachKey(defaults, function (field, value) {\n _this[field] = value;\n });\n }\n }\n return class_1;\n }();\n}\n/**\r\n * A helper function to assist with JIT performance for objects that have properties added / removed dynamically\r\n * this is primarily for chromium based browsers and has limited effects on Firefox and none of IE. Only call this\r\n * function after you have finished \"updating\" the object, calling this within loops reduces or defeats the benefits.\r\n * This helps when iterating using for..in, objKeys() and objForEach()\r\n * @param theObject - The object to be optimized if possible\r\n */\nexport function optimizeObject(theObject) {\n // V8 Optimization to cause the JIT compiler to create a new optimized object for looking up the own properties\n // primarily for object with <= 19 properties for >= 20 the effect is reduced or non-existent\n if (theObject && ObjAssign) {\n theObject = ObjClass(ObjAssign({}, theObject));\n }\n return theObject;\n}\nexport function objExtend(obj1, obj2, obj3, obj4, obj5, obj6) {\n // Variables\n var theArgs = arguments;\n var extended = theArgs[0] || {};\n var argLen = theArgs[_DYN_LENGTH /* @min:%2elength */];\n var deep = false;\n var idx = 1;\n // Check for \"Deep\" flag\n if (argLen > 0 && isBoolean(extended)) {\n deep = extended;\n extended = theArgs[idx] || {};\n idx++;\n }\n // Handle case when target is a string or something (possible in deep copy)\n if (!isObject(extended)) {\n extended = {};\n }\n // Loop through each remaining object and conduct a merge\n for (; idx < argLen; idx++) {\n var arg = theArgs[idx];\n var isArgArray = isArray(arg);\n var isArgObj = isObject(arg);\n for (var prop in arg) {\n var propOk = isArgArray && prop in arg || isArgObj && objHasOwn(arg, prop);\n if (!propOk) {\n continue;\n }\n var newValue = arg[prop];\n var isNewArray = void 0;\n // If deep merge and property is an object, merge properties\n if (deep && newValue && ((isNewArray = isArray(newValue)) || isPlainObject(newValue))) {\n // Grab the current value of the extended object\n var clone = extended[prop];\n if (isNewArray) {\n if (!isArray(clone)) {\n // We can't \"merge\" an array with a non-array so overwrite the original\n clone = [];\n }\n } else if (!isPlainObject(clone)) {\n // We can't \"merge\" an object with a non-object\n clone = {};\n }\n // Never move the original objects always clone them\n newValue = objExtend(deep, clone, newValue);\n }\n // Assign the new (or previous) value (unless undefined)\n if (newValue !== undefined) {\n extended[prop] = newValue;\n }\n }\n }\n return extended;\n}\nexport var asString = asString21;\nexport function isFeatureEnabled(feature, cfg) {\n var rlt = false;\n var ft = cfg && cfg.featureOptIn && cfg.featureOptIn[feature];\n if (feature && ft) {\n var mode = ft.mode;\n // NOTE: None will be considered as true\n rlt = mode == 3 /* FeatureOptInMode.enable */ || mode == 1 /* FeatureOptInMode.none */;\n }\n return rlt;\n}\nexport function getResponseText(xhr) {\n try {\n return xhr.responseText;\n } catch (e) {\n // Best effort, as XHR may throw while XDR wont so just ignore\n }\n return null;\n}\nexport function formatErrorMessageXdr(xdr, message) {\n if (xdr) {\n return \"XDomainRequest,Response:\" + getResponseText(xdr) || \"\";\n }\n return message;\n}\nexport function formatErrorMessageXhr(xhr, message) {\n if (xhr) {\n return \"XMLHttpRequest,Status:\" + xhr[_DYN_STATUS /* @min:%2estatus */] + \",Response:\" + getResponseText(xhr) || xhr.response || \"\";\n }\n return message;\n}\nexport function prependTransports(theTransports, newTransports) {\n if (newTransports) {\n if (isNumber(newTransports)) {\n theTransports = [newTransports].concat(theTransports);\n } else if (isArray(newTransports)) {\n theTransports = newTransports.concat(theTransports);\n }\n }\n return theTransports;\n}\nvar strDisabledPropertyName = \"Microsoft_ApplicationInsights_BypassAjaxInstrumentation\";\nvar strWithCredentials = \"withCredentials\";\nvar strTimeout = \"timeout\";\n/**\r\n * Create and open an XMLHttpRequest object\r\n * @param method - The request method\r\n * @param urlString - The url\r\n * @param withCredentials - Option flag indicating that credentials should be sent\r\n * @param disabled - Optional flag indicating that the XHR object should be marked as disabled and not tracked (default is false)\r\n * @param isSync - Optional flag indicating if the instance should be a synchronous request (defaults to false)\r\n * @param timeout - Optional value identifying the timeout value that should be assigned to the XHR request\r\n * @returns A new opened XHR request\r\n */\nexport function openXhr(method, urlString, withCredentials, disabled, isSync, timeout) {\n if (disabled === void 0) {\n disabled = false;\n }\n if (isSync === void 0) {\n isSync = false;\n }\n function _wrapSetXhrProp(xhr, prop, value) {\n try {\n xhr[prop] = value;\n } catch (e) {\n // - Wrapping as depending on the environment setting the property may fail (non-terminally)\n }\n }\n var xhr = new XMLHttpRequest();\n if (disabled) {\n // Tag the instance so it's not tracked (trackDependency)\n // If the environment has locked down the XMLHttpRequest (preventExtensions and/or freeze), this would\n // cause the request to fail and we no telemetry would be sent\n _wrapSetXhrProp(xhr, strDisabledPropertyName, disabled);\n }\n if (withCredentials) {\n // Some libraries require that the withCredentials flag is set \"before\" open and\n // - Wrapping as IE 10 has started throwing when setting before open\n _wrapSetXhrProp(xhr, strWithCredentials, withCredentials);\n }\n xhr.open(method, urlString, !isSync);\n if (withCredentials) {\n // withCredentials should be set AFTER open (https://xhr.spec.whatwg.org/#the-withcredentials-attribute)\n // And older firefox instances from 11+ will throw for sync events (current versions don't) which happens during unload processing\n _wrapSetXhrProp(xhr, strWithCredentials, withCredentials);\n }\n // Only set the timeout for asynchronous requests as\n // \"Timeout shouldn't be used for synchronous XMLHttpRequests requests used in a document environment or it will throw an InvalidAccessError exception.\"\"\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/timeout\n if (!isSync && timeout) {\n _wrapSetXhrProp(xhr, strTimeout, timeout);\n }\n return xhr;\n}\n/**\r\n* Converts the XHR getAllResponseHeaders to a map containing the header key and value.\r\n* @internal\r\n*/\n// tslint:disable-next-line: align\nexport function convertAllHeadersToMap(headersString) {\n var headers = {};\n if (isString(headersString)) {\n var headersArray = strTrim(headersString)[_DYN_SPLIT /* @min:%2esplit */](/[\\r\\n]+/);\n arrForEach(headersArray, function (headerEntry) {\n if (headerEntry) {\n var idx = headerEntry.indexOf(\": \");\n if (idx !== -1) {\n // The new spec has the headers returning all as lowercase -- but not all browsers do this yet\n var header = strTrim(headerEntry.substring(0, idx))[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\n var value = strTrim(headerEntry.substring(idx + 1));\n headers[header] = value;\n } else {\n headers[strTrim(headerEntry)] = 1;\n }\n }\n });\n }\n return headers;\n}\n/**\r\n* append the XHR headers.\r\n* @internal\r\n*/\nexport function _appendHeader(theHeaders, xhr, name) {\n if (!theHeaders[name] && xhr && xhr.getResponseHeader) {\n var value = xhr.getResponseHeader(name);\n if (value) {\n theHeaders[name] = strTrim(value);\n }\n }\n return theHeaders;\n}\nvar STR_KILL_DURATION_HEADER = \"kill-duration\";\nvar STR_KILL_DURATION_SECONDS_HEADER = \"kill-duration-seconds\";\nvar STR_TIME_DELTA_HEADER = \"time-delta-millis\";\n/**\r\n* get the XHR getAllResponseHeaders.\r\n* @internal\r\n*/\nexport function _getAllResponseHeaders(xhr, isOneDs) {\n var theHeaders = {};\n if (!xhr[_DYN_GET_ALL_RESPONSE_HEA5 /* @min:%2egetAllResponseHeaders */]) {\n // Firefox 2-63 doesn't have getAllResponseHeaders function but it does have getResponseHeader\n // Only call these if getAllResponseHeaders doesn't exist, otherwise we can get invalid response errors\n // as collector is not currently returning the correct header to allow JS to access these headers\n if (!!isOneDs) {\n theHeaders = _appendHeader(theHeaders, xhr, STR_TIME_DELTA_HEADER);\n theHeaders = _appendHeader(theHeaders, xhr, STR_KILL_DURATION_HEADER);\n theHeaders = _appendHeader(theHeaders, xhr, STR_KILL_DURATION_SECONDS_HEADER);\n }\n } else {\n theHeaders = convertAllHeadersToMap(xhr[_DYN_GET_ALL_RESPONSE_HEA5 /* @min:%2egetAllResponseHeaders */]());\n }\n return theHeaders;\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n\"use strict\";\n\nimport { getGlobal, strShimObject, strShimPrototype, strShimUndefined } from \"@microsoft/applicationinsights-shims\";\nimport { getDocument, getInst, getNavigator, getPerformance, hasNavigator, isFunction, isString, isUndefined, mathMax, strIndexOf } from \"@nevware21/ts-utils\";\nimport { _DYN_LENGTH, _DYN_NAME, _DYN_SPLIT, _DYN_TO_LOWER_CASE, _DYN_USER_AGENT } from \"../__DynamicConstants\";\nimport { strContains } from \"./HelperFuncs\";\nimport { STR_EMPTY } from \"./InternalConstants\";\n/**\r\n * This file exists to hold environment utilities that are required to check and\r\n * validate the current operating environment. Unless otherwise required, please\r\n * only use defined methods (functions) in this class so that users of these\r\n * functions/properties only need to include those that are used within their own modules.\r\n */\nvar strDocumentMode = \"documentMode\";\nvar strLocation = \"location\";\nvar strConsole = \"console\";\nvar strJSON = \"JSON\";\nvar strCrypto = \"crypto\";\nvar strMsCrypto = \"msCrypto\";\nvar strReactNative = \"ReactNative\";\nvar strMsie = \"msie\";\nvar strTrident = \"trident/\";\nvar strXMLHttpRequest = \"XMLHttpRequest\";\nvar _isTrident = null;\nvar _navUserAgentCheck = null;\nvar _enableMocks = false;\nvar _useXDomainRequest = null;\nvar _beaconsSupported = null;\nfunction _hasProperty(theClass, property) {\n var supported = false;\n if (theClass) {\n try {\n supported = property in theClass;\n if (!supported) {\n var proto = theClass[strShimPrototype];\n if (proto) {\n supported = property in proto;\n }\n }\n } catch (e) {\n // Do Nothing\n }\n if (!supported) {\n try {\n var tmp = new theClass();\n supported = !isUndefined(tmp[property]);\n } catch (e) {\n // Do Nothing\n }\n }\n }\n return supported;\n}\n/**\r\n * Enable the lookup of test mock objects if requested\r\n * @param enabled - A flag to enable or disable the mock\r\n */\nexport function setEnableEnvMocks(enabled) {\n _enableMocks = enabled;\n}\n/**\r\n * Returns the global location object if it is present otherwise null.\r\n * This helper is used to access the location object without causing an exception\r\n * \"Uncaught ReferenceError: location is not defined\"\r\n */\nexport function getLocation(checkForMock) {\n if (checkForMock && _enableMocks) {\n var mockLocation = getInst(\"__mockLocation\");\n if (mockLocation) {\n return mockLocation;\n }\n }\n if (typeof location === strShimObject && location) {\n return location;\n }\n return getInst(strLocation);\n}\n/**\r\n * Returns the global console object\r\n */\nexport function getConsole() {\n if (typeof console !== strShimUndefined) {\n return console;\n }\n return getInst(strConsole);\n}\n/**\r\n * Checks if JSON object is available, this is required as we support the API running without a\r\n * window /document (eg. Node server, electron webworkers) and if we attempt to assign a history\r\n * object to a local variable or pass as an argument an \"Uncaught ReferenceError: JSON is not defined\"\r\n * exception will be thrown.\r\n * Defined as a function to support lazy / late binding environments.\r\n */\nexport function hasJSON() {\n return Boolean(typeof JSON === strShimObject && JSON || getInst(strJSON) !== null);\n}\n/**\r\n * Returns the global JSON object if it is present otherwise null.\r\n * This helper is used to access the JSON object without causing an exception\r\n * \"Uncaught ReferenceError: JSON is not defined\"\r\n */\nexport function getJSON() {\n if (hasJSON()) {\n return JSON || getInst(strJSON);\n }\n return null;\n}\n/**\r\n * Returns the crypto object if it is present otherwise null.\r\n * This helper is used to access the crypto object from the current\r\n * global instance which could be window or globalThis for a web worker\r\n */\nexport function getCrypto() {\n return getInst(strCrypto);\n}\n/**\r\n * Returns the crypto object if it is present otherwise null.\r\n * This helper is used to access the crypto object from the current\r\n * global instance which could be window or globalThis for a web worker\r\n */\nexport function getMsCrypto() {\n return getInst(strMsCrypto);\n}\n/**\r\n * Returns whether the environment is reporting that we are running in a React Native Environment\r\n */\nexport function isReactNative() {\n // If running in React Native, navigator.product will be populated\n var nav = getNavigator();\n if (nav && nav.product) {\n return nav.product === strReactNative;\n }\n return false;\n}\n/**\r\n * Identifies whether the current environment appears to be IE\r\n */\nexport function isIE() {\n var nav = getNavigator();\n if (nav && (nav[_DYN_USER_AGENT /* @min:%2euserAgent */] !== _navUserAgentCheck || _isTrident === null)) {\n // Added to support test mocking of the user agent\n _navUserAgentCheck = nav[_DYN_USER_AGENT /* @min:%2euserAgent */];\n var userAgent = (_navUserAgentCheck || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\n _isTrident = strContains(userAgent, strMsie) || strContains(userAgent, strTrident);\n }\n return _isTrident;\n}\n/**\r\n * Gets IE version returning the document emulation mode if we are running on IE, or null otherwise\r\n */\nexport function getIEVersion(userAgentStr) {\n if (userAgentStr === void 0) {\n userAgentStr = null;\n }\n if (!userAgentStr) {\n var navigator_1 = getNavigator() || {};\n userAgentStr = navigator_1 ? (navigator_1.userAgent || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]() : STR_EMPTY;\n }\n var ua = (userAgentStr || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\n // Also check for documentMode in case X-UA-Compatible meta tag was included in HTML.\n if (strContains(ua, strMsie)) {\n var doc = getDocument() || {};\n return mathMax(parseInt(ua[_DYN_SPLIT /* @min:%2esplit */](strMsie)[1]), doc[strDocumentMode] || 0);\n } else if (strContains(ua, strTrident)) {\n var tridentVer = parseInt(ua[_DYN_SPLIT /* @min:%2esplit */](strTrident)[1]);\n if (tridentVer) {\n return tridentVer + 4;\n }\n }\n return null;\n}\nexport function isSafari(userAgentStr) {\n if (!userAgentStr || !isString(userAgentStr)) {\n var navigator_2 = getNavigator() || {};\n userAgentStr = navigator_2 ? (navigator_2.userAgent || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]() : STR_EMPTY;\n }\n var ua = (userAgentStr || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\n return strIndexOf(ua, \"safari\") >= 0;\n}\n/**\r\n * Checks if HTML5 Beacons are supported in the current environment.\r\n * @param useCached - [Optional] used for testing to bypass the cached lookup, when `true` this will\r\n * cause the cached global to be reset.\r\n * @returns True if supported, false otherwise.\r\n */\nexport function isBeaconsSupported(useCached) {\n if (_beaconsSupported === null || useCached === false) {\n _beaconsSupported = hasNavigator() && Boolean(getNavigator().sendBeacon);\n }\n return _beaconsSupported;\n}\n/**\r\n * Checks if the Fetch API is supported in the current environment.\r\n * @param withKeepAlive - [Optional] If True, check if fetch is available and it supports the keepalive feature, otherwise only check if fetch is supported\r\n * @returns True if supported, otherwise false\r\n */\nexport function isFetchSupported(withKeepAlive) {\n var isSupported = false;\n try {\n isSupported = !!getInst(\"fetch\");\n var request = getInst(\"Request\");\n if (isSupported && withKeepAlive && request) {\n isSupported = _hasProperty(request, \"keepalive\");\n }\n } catch (e) {\n // Just Swallow any failure during availability checks\n }\n return isSupported;\n}\nexport function useXDomainRequest() {\n if (_useXDomainRequest === null) {\n _useXDomainRequest = typeof XDomainRequest !== strShimUndefined;\n if (_useXDomainRequest && isXhrSupported()) {\n _useXDomainRequest = _useXDomainRequest && !_hasProperty(getInst(strXMLHttpRequest), \"withCredentials\");\n }\n }\n return _useXDomainRequest;\n}\n/**\r\n * Checks if XMLHttpRequest is supported\r\n * @returns True if supported, otherwise false\r\n */\nexport function isXhrSupported() {\n var isSupported = false;\n try {\n var xmlHttpRequest = getInst(strXMLHttpRequest);\n isSupported = !!xmlHttpRequest;\n } catch (e) {\n // Just Swallow any failure during availability checks\n }\n return isSupported;\n}\nfunction _getNamedValue(values, name) {\n if (values) {\n for (var i = 0; i < values[_DYN_LENGTH /* @min:%2elength */]; i++) {\n var value = values[i];\n if (value[_DYN_NAME /* @min:%2ename */]) {\n if (value[_DYN_NAME /* @min:%2ename */] === name) {\n return value;\n }\n }\n }\n }\n return {};\n}\n/**\r\n * Helper function to fetch the named meta-tag from the page.\r\n * @param name - The name of the meta-tag to find.\r\n */\nexport function findMetaTag(name) {\n var doc = getDocument();\n if (doc && name) {\n // Look for a meta-tag\n return _getNamedValue(doc.querySelectorAll(\"meta\"), name).content;\n }\n return null;\n}\n/**\r\n * Helper function to fetch the named server timing value from the page response (first navigation event).\r\n * @param name - The name of the server timing value to find.\r\n */\nexport function findNamedServerTiming(name) {\n var value;\n var perf = getPerformance();\n if (perf) {\n // Try looking for a server-timing header\n var navPerf = perf.getEntriesByType(\"navigation\") || [];\n value = _getNamedValue((navPerf[_DYN_LENGTH /* @min:%2elength */] > 0 ? navPerf[0] : {}).serverTiming, name).description;\n }\n return value;\n}\n// TODO: should reuse this method for analytics plugin\nexport function dispatchEvent(target, evnt) {\n if (target && target.dispatchEvent && evnt) {\n target.dispatchEvent(evnt);\n return true;\n }\n return false;\n}\nexport function createCustomDomEvent(eventName, details) {\n var event = null;\n var detail = {\n detail: details || null\n };\n if (isFunction(CustomEvent)) {\n // Use CustomEvent constructor when available\n event = new CustomEvent(eventName, detail);\n } else {\n // CustomEvent has no constructor in IE\n var doc = getDocument();\n if (doc && doc.createEvent) {\n event = doc.createEvent(\"CustomEvent\");\n event.initCustomEvent(eventName, true, true, detail);\n }\n }\n return event;\n}\nexport function sendCustomEvent(evtName, cfg, customDetails) {\n var global = getGlobal();\n if (global && global.CustomEvent) {\n try {\n var details = {\n cfg: cfg || null,\n customDetails: customDetails || null\n };\n return dispatchEvent(global, createCustomDomEvent(evtName, details));\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n }\n return false;\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { mathFloor, utcNow } from \"@nevware21/ts-utils\";\nimport { _DYN_LENGTH } from \"../__DynamicConstants\";\nimport { getCrypto, getMsCrypto, isIE } from \"./EnvUtils\";\nimport { STR_EMPTY } from \"./InternalConstants\";\nvar UInt32Mask = 0x100000000;\nvar MaxUInt32 = 0xffffffff;\nvar SEED1 = 123456789;\nvar SEED2 = 987654321;\n// MWC based Random generator (for IE)\nvar _mwcSeeded = false;\nvar _mwcW = SEED1;\nvar _mwcZ = SEED2;\n// Takes any integer\nfunction _mwcSeed(seedValue) {\n if (seedValue < 0) {\n // Make sure we end up with a positive number and not -ve one.\n seedValue >>>= 0;\n }\n _mwcW = SEED1 + seedValue & MaxUInt32;\n _mwcZ = SEED2 - seedValue & MaxUInt32;\n _mwcSeeded = true;\n}\nfunction _autoSeedMwc() {\n // Simple initialization using default Math.random() - So we inherit any entropy from the browser\n // and bitwise XOR with the current milliseconds\n try {\n var now = utcNow() & 0x7fffffff;\n _mwcSeed((Math.random() * UInt32Mask ^ now) + now);\n } catch (e) {\n // Don't crash if something goes wrong\n }\n}\n/**\r\n * Generate a random value between 0 and maxValue, max value should be limited to a 32-bit maximum.\r\n * So maxValue(16) will produce a number from 0..16 (range of 17)\r\n * @param maxValue - The max value for the range\r\n */\nexport function randomValue(maxValue) {\n if (maxValue > 0) {\n return mathFloor(random32() / MaxUInt32 * (maxValue + 1)) >>> 0;\n }\n return 0;\n}\n/**\r\n * generate a random 32-bit number (0x000000..0xFFFFFFFF) or (-0x80000000..0x7FFFFFFF), defaults un-unsigned.\r\n * @param signed - True to return a signed 32-bit number (-0x80000000..0x7FFFFFFF) otherwise an unsigned one (0x000000..0xFFFFFFFF)\r\n */\nexport function random32(signed) {\n var value = 0;\n var c = getCrypto() || getMsCrypto();\n if (c && c.getRandomValues) {\n // Make sure the number is converted into the specified range (-0x80000000..0x7FFFFFFF)\n value = c.getRandomValues(new Uint32Array(1))[0] & MaxUInt32;\n }\n if (value === 0 && isIE()) {\n // For IE 6, 7, 8 (especially on XP) Math.random is not very random\n if (!_mwcSeeded) {\n // Set the seed for the Mwc algorithm\n _autoSeedMwc();\n }\n // Don't use Math.random for IE\n // Make sure the number is converted into the specified range (-0x80000000..0x7FFFFFFF)\n value = mwcRandom32() & MaxUInt32;\n }\n if (value === 0) {\n // Make sure the number is converted into the specified range (-0x80000000..0x7FFFFFFF)\n value = mathFloor(UInt32Mask * Math.random() | 0);\n }\n if (!signed) {\n // Make sure we end up with a positive number and not -ve one.\n value >>>= 0;\n }\n return value;\n}\n/**\r\n * Seed the MWC random number generator with the specified seed or a random value\r\n * @param value - optional the number to used as the seed, if undefined, null or zero a random value will be chosen\r\n */\nexport function mwcRandomSeed(value) {\n if (!value) {\n _autoSeedMwc();\n } else {\n _mwcSeed(value);\n }\n}\n/**\r\n * Generate a random 32-bit number between (0x000000..0xFFFFFFFF) or (-0x80000000..0x7FFFFFFF), using MWC (Multiply with carry)\r\n * instead of Math.random() defaults to un-signed.\r\n * Used as a replacement random generator for IE to avoid issues with older IE instances.\r\n * @param signed - True to return a signed 32-bit number (-0x80000000..0x7FFFFFFF) otherwise an unsigned one (0x000000..0xFFFFFFFF)\r\n */\nexport function mwcRandom32(signed) {\n _mwcZ = 36969 * (_mwcZ & 0xFFFF) + (_mwcZ >> 16) & MaxUInt32;\n _mwcW = 18000 * (_mwcW & 0xFFFF) + (_mwcW >> 16) & MaxUInt32;\n var value = (_mwcZ << 16) + (_mwcW & 0xFFFF) >>> 0 & MaxUInt32 | 0;\n if (!signed) {\n // Make sure we end up with a positive number and not -ve one.\n value >>>= 0;\n }\n return value;\n}\n/**\r\n * Generate random base64 id string.\r\n * The default length is 22 which is 132-bits so almost the same as a GUID but as base64 (the previous default was 5)\r\n * @param maxLength - Optional value to specify the length of the id to be generated, defaults to 22\r\n */\nexport function newId(maxLength) {\n if (maxLength === void 0) {\n maxLength = 22;\n }\n var base64chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n // Start with an initial random number, consuming the value in reverse byte order\n var number = random32() >>> 0; // Make sure it's a +ve number\n var chars = 0;\n var result = STR_EMPTY;\n while (result[_DYN_LENGTH /* @min:%2elength */] < maxLength) {\n chars++;\n result += base64chars.charAt(number & 0x3F);\n number >>>= 6; // Zero fill with right shift\n if (chars === 5) {\n // 5 base64 characters === 30 bits so we don't have enough bits for another base64 char\n // So add on another 30 bits and make sure it's +ve\n number = (random32() << 2 & 0xFFFFFFFF | number & 0x03) >>> 0;\n chars = 0; // We need to reset the number every 5 chars (30 bits)\n }\n }\n return result;\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { objDefine } from \"@nevware21/ts-utils\";\nimport { normalizeJsName } from \"./HelperFuncs\";\nimport { STR_EMPTY } from \"./InternalConstants\";\nimport { newId } from \"./RandomHelper\";\nvar version = '3.3.6';\nvar instanceName = \".\" + newId(6);\nvar _dataUid = 0;\n// Accepts only:\n// - Node\n// - Node.ELEMENT_NODE\n// - Node.DOCUMENT_NODE\n// - Object\n// - Any\nfunction _canAcceptData(target) {\n return target.nodeType === 1 || target.nodeType === 9 || !+target.nodeType;\n}\nfunction _getCache(data, target) {\n var theCache = target[data.id];\n if (!theCache) {\n theCache = {};\n try {\n if (_canAcceptData(target)) {\n objDefine(target, data.id, {\n e: false,\n v: theCache\n });\n }\n } catch (e) {\n // Not all environments allow extending all objects, so just ignore the cache in those cases\n }\n }\n return theCache;\n}\nexport function createUniqueNamespace(name, includeVersion) {\n if (includeVersion === void 0) {\n includeVersion = false;\n }\n return normalizeJsName(name + _dataUid++ + (includeVersion ? \".\" + version : STR_EMPTY) + instanceName);\n}\nexport function createElmNodeData(name) {\n var data = {\n id: createUniqueNamespace(\"_aiData-\" + (name || STR_EMPTY) + \".\" + version),\n accept: function (target) {\n return _canAcceptData(target);\n },\n get: function (target, name, defValue, addDefault) {\n var theCache = target[data.id];\n if (!theCache) {\n if (addDefault) {\n // Side effect is adds the cache\n theCache = _getCache(data, target);\n theCache[normalizeJsName(name)] = defValue;\n }\n return defValue;\n }\n return theCache[normalizeJsName(name)];\n },\n kill: function (target, name) {\n if (target && target[name]) {\n try {\n delete target[name];\n } catch (e) {\n // Just cleaning up, so if this fails -- ignore\n }\n }\n }\n };\n return data;\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { asString, isArray, isDefined, isNullOrUndefined, isObject, isPlainObject, isUndefined, objForEachKey, objHasOwn } from \"@nevware21/ts-utils\";\nimport { _DYN_LENGTH } from \"../__DynamicConstants\";\nfunction _isConfigDefaults(value) {\n return value && isObject(value) && (value.isVal || value.fb || objHasOwn(value, \"v\") || objHasOwn(value, \"mrg\") || objHasOwn(value, \"ref\") || value.set);\n}\nfunction _getDefault(dynamicHandler, theConfig, cfgDefaults) {\n var defValue;\n var isDefaultValid = cfgDefaults.dfVal || isDefined;\n // There is a fallback config key so try and grab that first\n if (theConfig && cfgDefaults.fb) {\n var fallbacks = cfgDefaults.fb;\n if (!isArray(fallbacks)) {\n fallbacks = [fallbacks];\n }\n for (var lp = 0; lp < fallbacks[_DYN_LENGTH /* @min:%2elength */]; lp++) {\n var fallback = fallbacks[lp];\n var fbValue = theConfig[fallback];\n if (isDefaultValid(fbValue)) {\n defValue = fbValue;\n } else if (dynamicHandler) {\n // Needed to ensure that the fallback value (and potentially) new field is also dynamic even if null/undefined\n fbValue = dynamicHandler.cfg[fallback];\n if (isDefaultValid(fbValue)) {\n defValue = fbValue;\n }\n // Needed to ensure that the fallback value (and potentially) new field is also dynamic even if null/undefined\n dynamicHandler.set(dynamicHandler.cfg, asString(fallback), fbValue);\n }\n if (isDefaultValid(defValue)) {\n // We have a valid default so break out of the look\n break;\n }\n }\n }\n // If the value is still not defined and we have a default value then use that\n if (!isDefaultValid(defValue) && isDefaultValid(cfgDefaults.v)) {\n defValue = cfgDefaults.v;\n }\n return defValue;\n}\n/**\r\n * Recursively resolve the default value\r\n * @param dynamicHandler\r\n * @param theConfig\r\n * @param cfgDefaults\r\n * @returns\r\n */\nfunction _resolveDefaultValue(dynamicHandler, theConfig, cfgDefaults) {\n var theValue = cfgDefaults;\n if (cfgDefaults && _isConfigDefaults(cfgDefaults)) {\n theValue = _getDefault(dynamicHandler, theConfig, cfgDefaults);\n }\n if (theValue) {\n if (_isConfigDefaults(theValue)) {\n theValue = _resolveDefaultValue(dynamicHandler, theConfig, theValue);\n }\n var newValue_1;\n if (isArray(theValue)) {\n newValue_1 = [];\n newValue_1[_DYN_LENGTH /* @min:%2elength */] = theValue[_DYN_LENGTH /* @min:%2elength */];\n } else if (isPlainObject(theValue)) {\n newValue_1 = {};\n }\n if (newValue_1) {\n objForEachKey(theValue, function (key, value) {\n if (value && _isConfigDefaults(value)) {\n value = _resolveDefaultValue(dynamicHandler, theConfig, value);\n }\n newValue_1[key] = value;\n });\n theValue = newValue_1;\n }\n }\n return theValue;\n}\n/**\r\n * Applies the default value on the config property and makes sure that it's dynamic\r\n * @param theConfig\r\n * @param name\r\n * @param defaultValue\r\n */\nexport function _applyDefaultValue(dynamicHandler, theConfig, name, defaultValue) {\n // Resolve the initial config value from the provided value or use the defined default\n var isValid;\n var setFn;\n var defValue;\n var cfgDefaults = defaultValue;\n var mergeDf;\n var reference;\n var readOnly;\n var blkDynamicValue;\n if (_isConfigDefaults(cfgDefaults)) {\n // looks like a IConfigDefault\n isValid = cfgDefaults.isVal;\n setFn = cfgDefaults.set;\n readOnly = cfgDefaults.rdOnly;\n blkDynamicValue = cfgDefaults.blkVal;\n mergeDf = cfgDefaults.mrg;\n reference = cfgDefaults.ref;\n if (!reference && isUndefined(reference)) {\n reference = !!mergeDf;\n }\n defValue = _getDefault(dynamicHandler, theConfig, cfgDefaults);\n } else {\n defValue = defaultValue;\n }\n if (blkDynamicValue) {\n // Mark the property so that any value assigned will be blocked from conversion, we need to do this\n // before assigning or fetching the value to ensure it's not converted\n dynamicHandler.blkVal(theConfig, name);\n }\n // Set the value to the default value;\n var theValue;\n var usingDefault = true;\n var cfgValue = theConfig[name];\n // try and get and user provided values\n if (cfgValue || !isNullOrUndefined(cfgValue)) {\n // Use the defined theConfig[name] value\n theValue = cfgValue;\n usingDefault = false;\n // The values are different and we have a special default value check, which is used to\n // override config values like empty strings to continue using the default\n if (isValid && theValue !== defValue && !isValid(theValue)) {\n theValue = defValue;\n usingDefault = true;\n }\n if (setFn) {\n theValue = setFn(theValue, defValue, theConfig);\n usingDefault = theValue === defValue;\n }\n }\n if (!usingDefault) {\n if (isPlainObject(theValue) || isArray(defValue)) {\n // we are using the user supplied value and it's an object\n if (mergeDf && defValue && (isPlainObject(defValue) || isArray(defValue))) {\n // Resolve/apply the defaults\n objForEachKey(defValue, function (dfName, dfValue) {\n // Sets the value and makes it dynamic (if it doesn't already exist)\n _applyDefaultValue(dynamicHandler, theValue, dfName, dfValue);\n });\n }\n }\n } else if (defValue) {\n // Just resolve the default\n theValue = _resolveDefaultValue(dynamicHandler, theConfig, defValue);\n } else {\n theValue = defValue;\n }\n // if (theValue && usingDefault && (isPlainObject(theValue) || isArray(theValue))) {\n // theValue = _cfgDeepCopy(theValue);\n // }\n // Needed to ensure that the (potentially) new field is dynamic even if null/undefined\n dynamicHandler.set(theConfig, name, theValue);\n if (reference) {\n dynamicHandler.ref(theConfig, name);\n }\n if (readOnly) {\n dynamicHandler.rdOnly(theConfig, name);\n }\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { isArray, isPlainObject, objForEachKey, symbolFor, throwTypeError } from \"@nevware21/ts-utils\";\nimport { _DYN_LENGTH } from \"../__DynamicConstants\";\n// Using Symbol.for so that if the same symbol was already created it would be returned\n// To handle multiple instances using potentially different versions we are not using\n// createUniqueNamespace()\nexport var CFG_HANDLER_LINK = symbolFor(\"[[ai_dynCfg_1]]\");\n/**\r\n * @internal\r\n * @ignore\r\n * The symbol to tag objects / arrays with if they should not be converted\r\n */\nvar BLOCK_DYNAMIC = symbolFor(\"[[ai_blkDynCfg_1]]\");\n/**\r\n * @internal\r\n * @ignore\r\n * The symbol to tag objects to indicate that when included into the configuration that\r\n * they should be converted into a trackable dynamic object.\r\n */\nvar FORCE_DYNAMIC = symbolFor(\"[[ai_frcDynCfg_1]]\");\nexport function _cfgDeepCopy(source) {\n if (source) {\n var target_1;\n if (isArray(source)) {\n target_1 = [];\n target_1[_DYN_LENGTH /* @min:%2elength */] = source[_DYN_LENGTH /* @min:%2elength */];\n } else if (isPlainObject(source)) {\n target_1 = {};\n }\n if (target_1) {\n // Copying index values by property name as the extensionConfig can be an array or object\n objForEachKey(source, function (key, value) {\n // Perform a deep copy of the object\n target_1[key] = _cfgDeepCopy(value);\n });\n return target_1;\n }\n }\n return source;\n}\n/**\r\n * @internal\r\n * Get the dynamic config handler if the value is already dynamic\r\n * @returns\r\n */\nexport function getDynamicConfigHandler(value) {\n if (value) {\n var handler = value[CFG_HANDLER_LINK] || value;\n if (handler.cfg && (handler.cfg === value || handler.cfg[CFG_HANDLER_LINK] === handler)) {\n return handler;\n }\n }\n return null;\n}\n/**\r\n * Mark the provided value so that if it's included into the configuration it will NOT have\r\n * its properties converted into a dynamic (reactive) object. If the object is not a plain object\r\n * or an array (ie. a class) this function has not affect as only Objects and Arrays are converted\r\n * into dynamic objects in the dynamic configuration.\r\n *\r\n * When you have tagged a value as both {@link forceDynamicConversion} and blocked force will take precedence.\r\n *\r\n * You should only need to use this function, if you are creating dynamic \"classes\" from objects\r\n * which confirm to the require interface. A common case for this is during unit testing where it's\r\n * easier to create mock extensions.\r\n *\r\n * If `value` is falsy (null / undefined / 0 / empty string etc) it will not be tagged and\r\n * if there is an exception adding the property to the value (because its frozen etc) the\r\n * exception will be swallowed\r\n *\r\n * @example\r\n * ```ts\r\n * // This is a valid \"extension\", but it is technically an object\r\n * // So when included in the config.extensions it WILL be cloned and then\r\n * // converted into a dynamic object, where all of its properties will become\r\n * // get/set object properties and will be tracked. While this WILL still\r\n * // function, when attempt to use a mocking framework on top of this the\r\n * // functions are now technically get accessors which return a function\r\n * // and this can cause some mocking frameworks to fail.\r\n * let mockChannel = {\r\n * pause: () => { },\r\n* resume: () => { },\r\n* teardown: () => { },\r\n* flush: (async: any, callBack: any) => { },\r\n* processTelemetry: (env: any) => { },\r\n* setNextPlugin: (next: any) => { },\r\n* initialize: (config: any, core: any, extensions: any) => { },\r\n* identifier: \"testChannel\",\r\n* priority: 1003\r\n* };\r\n * ```\r\n * @param value - The object that you want to block from being converted into a\r\n * trackable dynamic object\r\n * @returns The original value\r\n */\nexport function blockDynamicConversion(value) {\n if (value && (isPlainObject(value) || isArray(value))) {\n try {\n value[BLOCK_DYNAMIC] = true;\n } catch (e) {\n // Don't throw for this case as it's an ask only\n }\n }\n return value;\n}\n/**\r\n * This is the reverse case of {@link blockDynamicConversion} in that this will tag an\r\n * object to indicate that it should always be converted into a dynamic trackable object\r\n * even when not an object or array. So all properties of this object will become\r\n * get / set accessor functions.\r\n *\r\n * When you have tagged a value as both {@link forceDynamicConversion} and blocked force will take precedence.\r\n *\r\n * If `value` is falsy (null / undefined / 0 / empty string etc) it will not be tagged and\r\n * if there is an exception adding the property to the value (because its frozen etc) the\r\n * exception will be swallowed.\r\n * @param value - The object that should be tagged and converted if included into a dynamic\r\n * configuration.\r\n * @returns The original value\r\n */\nexport function forceDynamicConversion(value) {\n if (value) {\n try {\n value[FORCE_DYNAMIC] = true;\n } catch (e) {\n // Don't throw for this case as it's an ask only\n }\n }\n return value;\n}\n/**\r\n * @internal\r\n * @ignore\r\n * Helper function to check whether an object can or should be converted into a dynamic\r\n * object.\r\n * @param value - The object to check whether it should be converted\r\n * @returns `true` if the value should be converted otherwise `false`.\r\n */\nexport function _canMakeDynamic(getFunc, state, value) {\n var result = false;\n // Object must exist and be truthy\n if (value && !getFunc[state.blkVal]) {\n // Tagged as always convert\n result = value[FORCE_DYNAMIC];\n // Check that it's not explicitly tagged as blocked\n if (!result && !value[BLOCK_DYNAMIC]) {\n // Only convert plain objects or arrays by default\n result = isPlainObject(value) || isArray(value);\n }\n }\n return result;\n}\n/**\r\n * Throws an invalid access exception\r\n * @param message - The message to include in the exception\r\n */\nexport function throwInvalidAccess(message) {\n throwTypeError(\"InvalidAccess:\" + message);\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { arrForEach, arrIndexOf, dumpObj, isArray, objDefine, objDefineProp, objForEachKey, objGetOwnPropertyDescriptor } from \"@nevware21/ts-utils\";\nimport { UNDEFINED_VALUE } from \"../JavaScriptSDK/InternalConstants\";\nimport { _DYN_APPLY, _DYN_LOGGER, _DYN_PUSH, _DYN_SPLICE, _DYN_THROW_INTERNAL } from \"../__DynamicConstants\";\nimport { CFG_HANDLER_LINK, _canMakeDynamic, blockDynamicConversion, throwInvalidAccess } from \"./DynamicSupport\";\nvar arrayMethodsToPatch = [\"push\", \"pop\", \"shift\", \"unshift\", \"splice\"];\nexport var _throwDynamicError = function (logger, name, desc, e) {\n logger && logger[_DYN_THROW_INTERNAL /* @min:%2ethrowInternal */](3 /* eLoggingSeverity.DEBUG */, 108 /* _eInternalMessageId.DynamicConfigException */, \"\".concat(desc, \" [\").concat(name, \"] failed - \") + dumpObj(e));\n};\nfunction _patchArray(state, target, name) {\n if (isArray(target)) {\n // Monkey Patch the methods that might change the array\n arrForEach(arrayMethodsToPatch, function (method) {\n var orgMethod = target[method];\n target[method] = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var result = orgMethod[_DYN_APPLY /* @min:%2eapply */](this, args);\n // items may be added, removed or moved so need to make some new dynamic properties\n _makeDynamicObject(state, target, name, \"Patching\");\n return result;\n };\n });\n }\n}\nfunction _getOwnPropGetter(target, name) {\n var propDesc = objGetOwnPropertyDescriptor(target, name);\n return propDesc && propDesc.get;\n}\nfunction _createDynamicProperty(state, theConfig, name, value) {\n // Does not appear to be dynamic so lets make it so\n var detail = {\n n: name,\n h: [],\n trk: function (handler) {\n if (handler && handler.fn) {\n if (arrIndexOf(detail.h, handler) === -1) {\n // Add this handler to the collection that should be notified when the value changes\n detail.h[_DYN_PUSH /* @min:%2epush */](handler);\n }\n state.trk(handler, detail);\n }\n },\n clr: function (handler) {\n var idx = arrIndexOf(detail.h, handler);\n if (idx !== -1) {\n detail.h[_DYN_SPLICE /* @min:%2esplice */](idx, 1);\n }\n }\n };\n // Flag to optimize lookup response time by avoiding additional function calls\n var checkDynamic = true;\n var isObjectOrArray = false;\n function _getProperty() {\n if (checkDynamic) {\n isObjectOrArray = isObjectOrArray || _canMakeDynamic(_getProperty, state, value);\n // Make sure that if it's an object that we make it dynamic\n if (value && !value[CFG_HANDLER_LINK] && isObjectOrArray) {\n // It doesn't look like it's already dynamic so lets make sure it's converted the object into a dynamic Config as well\n value = _makeDynamicObject(state, value, name, \"Converting\");\n }\n // If it needed to be converted it now has been\n checkDynamic = false;\n }\n // If there is an active handler then add it to the tracking set of handlers\n var activeHandler = state.act;\n if (activeHandler) {\n detail.trk(activeHandler);\n }\n return value;\n }\n // Tag this getter as our dynamic property and provide shortcut for notifying a change\n _getProperty[state.prop] = {\n chng: function () {\n state.add(detail);\n }\n };\n function _setProperty(newValue) {\n if (value !== newValue) {\n if (!!_getProperty[state.ro] && !state.upd) {\n // field is marked as readonly so return false\n throwInvalidAccess(\"[\" + name + \"] is read-only:\" + dumpObj(theConfig));\n }\n if (checkDynamic) {\n isObjectOrArray = isObjectOrArray || _canMakeDynamic(_getProperty, state, value);\n checkDynamic = false;\n }\n // The value must be a plain object or an array to enforce the reference (in-place updates)\n var isReferenced = isObjectOrArray && _getProperty[state.rf];\n if (isObjectOrArray) {\n // We are about to replace a plain object or an array\n if (isReferenced) {\n // Reassign the properties from the current value to the same properties from the newValue\n // This will set properties not in the newValue to undefined\n objForEachKey(value, function (key) {\n value[key] = newValue ? newValue[key] : UNDEFINED_VALUE;\n });\n // Now assign / re-assign value with all of the keys from newValue\n try {\n objForEachKey(newValue, function (key, theValue) {\n _setDynamicProperty(state, value, key, theValue);\n });\n // Now drop newValue so when we assign value later it keeps the existing reference\n newValue = value;\n } catch (e) {\n // Unable to convert to dynamic property so just leave as non-dynamic\n _throwDynamicError((state.hdlr || {})[_DYN_LOGGER /* @min:%2elogger */], name, \"Assigning\", e);\n // Mark as not an object or array so we don't try and do this again\n isObjectOrArray = false;\n }\n } else if (value && value[CFG_HANDLER_LINK]) {\n // As we are replacing the value, if it's already dynamic then we need to notify the listeners\n // for every property it has already\n objForEachKey(value, function (key) {\n // Check if the value is dynamic\n var getter = _getOwnPropGetter(value, key);\n if (getter) {\n // And if it is tell it's listeners that the value has changed\n var valueState = getter[state.prop];\n valueState && valueState.chng();\n }\n });\n }\n }\n if (newValue !== value) {\n var newIsObjectOrArray = newValue && _canMakeDynamic(_getProperty, state, newValue);\n if (!isReferenced && newIsObjectOrArray) {\n // As the newValue is an object/array lets preemptively make it dynamic\n newValue = _makeDynamicObject(state, newValue, name, \"Converting\");\n }\n // Now assign the internal \"value\" to the newValue\n value = newValue;\n isObjectOrArray = newIsObjectOrArray;\n }\n // Cause any listeners to be scheduled for notification\n state.add(detail);\n }\n }\n objDefine(theConfig, detail.n, {\n g: _getProperty,\n s: _setProperty\n });\n}\nexport function _setDynamicProperty(state, target, name, value) {\n if (target) {\n // To be a dynamic property it needs to have a get function\n var getter = _getOwnPropGetter(target, name);\n var isDynamic = getter && !!getter[state.prop];\n if (!isDynamic) {\n _createDynamicProperty(state, target, name, value);\n } else {\n // Looks like it's already dynamic just assign the new value\n target[name] = value;\n }\n }\n return target;\n}\nexport function _setDynamicPropertyState(state, target, name, flags) {\n if (target) {\n // To be a dynamic property it needs to have a get function\n var getter = _getOwnPropGetter(target, name);\n var isDynamic = getter && !!getter[state.prop];\n var inPlace = flags && flags[0 /* _eSetDynamicPropertyFlags.inPlace */];\n var rdOnly = flags && flags[1 /* _eSetDynamicPropertyFlags.readOnly */];\n var blkProp = flags && flags[2 /* _eSetDynamicPropertyFlags.blockDynamicProperty */];\n if (!isDynamic) {\n if (blkProp) {\n try {\n // Attempt to mark the target as blocked from conversion\n blockDynamicConversion(target);\n } catch (e) {\n _throwDynamicError((state.hdlr || {})[_DYN_LOGGER /* @min:%2elogger */], name, \"Blocking\", e);\n }\n }\n try {\n // Make sure it's dynamic so that we can tag the property as per the state\n _setDynamicProperty(state, target, name, target[name]);\n getter = _getOwnPropGetter(target, name);\n } catch (e) {\n // Unable to convert to dynamic property so just leave as non-dynamic\n _throwDynamicError((state.hdlr || {})[_DYN_LOGGER /* @min:%2elogger */], name, \"State\", e);\n }\n }\n // Assign the optional flags if true\n if (inPlace) {\n getter[state.rf] = inPlace;\n }\n if (rdOnly) {\n getter[state.ro] = rdOnly;\n }\n if (blkProp) {\n getter[state.blkVal] = true;\n }\n }\n return target;\n}\nexport function _makeDynamicObject(state, target, name, desc) {\n try {\n // Assign target with new value properties (converting into dynamic properties in the process)\n objForEachKey(target, function (key, value) {\n // Assign and/or make the property dynamic\n _setDynamicProperty(state, target, key, value);\n });\n if (!target[CFG_HANDLER_LINK]) {\n // Link the config back to the dynamic config details\n objDefineProp(target, CFG_HANDLER_LINK, {\n get: function () {\n return state.hdlr;\n }\n });\n _patchArray(state, target, name);\n }\n } catch (e) {\n // Unable to convert to dynamic property so just leave as non-dynamic\n _throwDynamicError((state.hdlr || {})[_DYN_LOGGER /* @min:%2elogger */], name, desc, e);\n }\n return target;\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { arrForEach, arrIndexOf, dumpObj, newSymbol, scheduleTimeout } from \"@nevware21/ts-utils\";\nimport { throwAggregationError } from \"../JavaScriptSDK/AggregationError\";\nimport { _DYN_CANCEL, _DYN_LENGTH, _DYN_LOGGER, _DYN_PUSH, _DYN_THROW_INTERNAL } from \"../__DynamicConstants\";\nvar symPrefix = \"[[ai_\";\nvar symPostfix = \"]]\";\nexport function _createState(cfgHandler) {\n var dynamicPropertySymbol = newSymbol(symPrefix + \"get\" + cfgHandler.uid + symPostfix);\n var dynamicPropertyReadOnly = newSymbol(symPrefix + \"ro\" + cfgHandler.uid + symPostfix);\n var dynamicPropertyReferenced = newSymbol(symPrefix + \"rf\" + cfgHandler.uid + symPostfix);\n var dynamicPropertyBlockValue = newSymbol(symPrefix + \"blkVal\" + cfgHandler.uid + symPostfix);\n var dynamicPropertyDetail = newSymbol(symPrefix + \"dtl\" + cfgHandler.uid + symPostfix);\n var _waitingHandlers = null;\n var _watcherTimer = null;\n var theState;\n function _useHandler(activeHandler, callback) {\n var prevWatcher = theState.act;\n try {\n theState.act = activeHandler;\n if (activeHandler && activeHandler[dynamicPropertyDetail]) {\n // Clear out the previously tracked details for this handler, so that access are re-evaluated\n arrForEach(activeHandler[dynamicPropertyDetail], function (detail) {\n detail.clr(activeHandler);\n });\n activeHandler[dynamicPropertyDetail] = [];\n }\n callback({\n cfg: cfgHandler.cfg,\n set: cfgHandler.set.bind(cfgHandler),\n setDf: cfgHandler.setDf.bind(cfgHandler),\n ref: cfgHandler.ref.bind(cfgHandler),\n rdOnly: cfgHandler.rdOnly.bind(cfgHandler)\n });\n } catch (e) {\n var logger = cfgHandler[_DYN_LOGGER /* @min:%2elogger */];\n if (logger) {\n // Don't let one individual failure break everyone\n logger[_DYN_THROW_INTERNAL /* @min:%2ethrowInternal */](1 /* eLoggingSeverity.CRITICAL */, 107 /* _eInternalMessageId.ConfigWatcherException */, dumpObj(e));\n }\n // Re-throw the exception so that any true \"error\" is reported back to the called\n throw e;\n } finally {\n theState.act = prevWatcher || null;\n }\n }\n function _notifyWatchers() {\n if (_waitingHandlers) {\n var notifyHandlers = _waitingHandlers;\n _waitingHandlers = null;\n // Stop any timer as we are running them now anyway\n _watcherTimer && _watcherTimer[_DYN_CANCEL /* @min:%2ecancel */]();\n _watcherTimer = null;\n var watcherFailures_1 = [];\n // Now run the handlers\n arrForEach(notifyHandlers, function (handler) {\n if (handler) {\n if (handler[dynamicPropertyDetail]) {\n arrForEach(handler[dynamicPropertyDetail], function (detail) {\n // Clear out this handler from previously tracked details, so that access are re-evaluated\n detail.clr(handler);\n });\n handler[dynamicPropertyDetail] = null;\n }\n // The handler may have self removed as part of another handler so re-check\n if (handler.fn) {\n try {\n _useHandler(handler, handler.fn);\n } catch (e) {\n // Don't let a single failing watcher cause other watches to fail\n watcherFailures_1[_DYN_PUSH /* @min:%2epush */](e);\n }\n }\n }\n });\n // During notification we may have had additional updates -- so notify those updates as well\n if (_waitingHandlers) {\n try {\n _notifyWatchers();\n } catch (e) {\n watcherFailures_1[_DYN_PUSH /* @min:%2epush */](e);\n }\n }\n if (watcherFailures_1[_DYN_LENGTH /* @min:%2elength */] > 0) {\n throwAggregationError(\"Watcher error(s): \", watcherFailures_1);\n }\n }\n }\n function _addWatcher(detail) {\n if (detail && detail.h[_DYN_LENGTH /* @min:%2elength */] > 0) {\n if (!_waitingHandlers) {\n _waitingHandlers = [];\n }\n if (!_watcherTimer) {\n _watcherTimer = scheduleTimeout(function () {\n _watcherTimer = null;\n _notifyWatchers();\n }, 0);\n }\n // Add all of the handlers for this detail (if not already present) - using normal for-loop for performance\n for (var idx = 0; idx < detail.h[_DYN_LENGTH /* @min:%2elength */]; idx++) {\n var handler = detail.h[idx];\n // Add this handler to the collection of handlers to re-execute\n if (handler && arrIndexOf(_waitingHandlers, handler) === -1) {\n _waitingHandlers[_DYN_PUSH /* @min:%2epush */](handler);\n }\n }\n }\n }\n function _trackHandler(handler, detail) {\n if (handler) {\n var details = handler[dynamicPropertyDetail] = handler[dynamicPropertyDetail] || [];\n if (arrIndexOf(details, detail) === -1) {\n // If this detail is not already listed as tracked then add it so that we re-evaluate it's usage\n details[_DYN_PUSH /* @min:%2epush */](detail);\n }\n }\n }\n theState = {\n prop: dynamicPropertySymbol,\n ro: dynamicPropertyReadOnly,\n rf: dynamicPropertyReferenced,\n blkVal: dynamicPropertyBlockValue,\n hdlr: cfgHandler,\n add: _addWatcher,\n notify: _notifyWatchers,\n use: _useHandler,\n trk: _trackHandler\n };\n return theState;\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { dumpObj, isUndefined, objDefine, objForEachKey } from \"@nevware21/ts-utils\";\nimport { createUniqueNamespace } from \"../JavaScriptSDK/DataCacheHelper\";\nimport { STR_NOT_DYNAMIC_ERROR } from \"../JavaScriptSDK/InternalConstants\";\nimport { _DYN_THROW_INTERNAL, _DYN_WARN_TO_CONSOLE, _DYN_WATCH } from \"../__DynamicConstants\";\nimport { _applyDefaultValue } from \"./ConfigDefaults\";\nimport { _makeDynamicObject, _setDynamicProperty, _setDynamicPropertyState, _throwDynamicError } from \"./DynamicProperty\";\nimport { _createState } from \"./DynamicState\";\nimport { CFG_HANDLER_LINK, _cfgDeepCopy, getDynamicConfigHandler, throwInvalidAccess } from \"./DynamicSupport\";\n/**\r\n * Identifies a function which will be re-called whenever any of it's accessed configuration values\r\n * change.\r\n * @param configHandler - The callback that will be called for the initial request and then whenever any\r\n * accessed configuration changes are identified.\r\n */\nfunction _createAndUseHandler(state, configHandler) {\n var handler = {\n fn: configHandler,\n rm: function () {\n // Clear all references to the handler so it can be garbage collected\n // This will also cause this handler to never get called and eventually removed\n handler.fn = null;\n state = null;\n configHandler = null;\n }\n };\n objDefine(handler, \"toJSON\", {\n v: function () {\n return \"WatcherHandler\" + (handler.fn ? \"\" : \"[X]\");\n }\n });\n state.use(handler, configHandler);\n return handler;\n}\n/**\r\n * Creates the dynamic config handler and associates with the target config as the root object\r\n * @param target - The config that you want to be root of the dynamic config\r\n * @param inPlace - Should the passed config be converted in-place or a new proxy returned\r\n * @returns The existing dynamic handler or a new instance with the provided config values\r\n */\nfunction _createDynamicHandler(logger, target, inPlace) {\n var dynamicHandler = getDynamicConfigHandler(target);\n if (dynamicHandler) {\n // The passed config is already dynamic so return it's tracker\n return dynamicHandler;\n }\n var uid = createUniqueNamespace(\"dyncfg\", true);\n var newTarget = target && inPlace !== false ? target : _cfgDeepCopy(target);\n var theState;\n function _notifyWatchers() {\n theState.notify();\n }\n function _setValue(target, name, value) {\n try {\n target = _setDynamicProperty(theState, target, name, value);\n } catch (e) {\n // Unable to convert to dynamic property so just leave as non-dynamic\n _throwDynamicError(logger, name, \"Setting value\", e);\n }\n return target[name];\n }\n function _watch(configHandler) {\n return _createAndUseHandler(theState, configHandler);\n }\n function _block(configHandler, allowUpdate) {\n theState.use(null, function (details) {\n var prevUpd = theState.upd;\n try {\n if (!isUndefined(allowUpdate)) {\n theState.upd = allowUpdate;\n }\n configHandler(details);\n } finally {\n theState.upd = prevUpd;\n }\n });\n }\n function _ref(target, name) {\n var _a;\n // Make sure it's dynamic and mark as referenced with it's current value\n return _setDynamicPropertyState(theState, target, name, (_a = {}, _a[0 /* _eSetDynamicPropertyFlags.inPlace */] = true, _a))[name];\n }\n function _rdOnly(target, name) {\n var _a;\n // Make sure it's dynamic and mark as readonly with it's current value\n return _setDynamicPropertyState(theState, target, name, (_a = {}, _a[1 /* _eSetDynamicPropertyFlags.readOnly */] = true, _a))[name];\n }\n function _blkPropValue(target, name) {\n var _a;\n // Make sure it's dynamic and mark as readonly with it's current value\n return _setDynamicPropertyState(theState, target, name, (_a = {}, _a[2 /* _eSetDynamicPropertyFlags.blockDynamicProperty */] = true, _a))[name];\n }\n function _applyDefaults(theConfig, defaultValues) {\n if (defaultValues) {\n // Resolve/apply the defaults\n objForEachKey(defaultValues, function (name, value) {\n // Sets the value and makes it dynamic (if it doesn't already exist)\n _applyDefaultValue(cfgHandler, theConfig, name, value);\n });\n }\n return theConfig;\n }\n var cfgHandler = {\n uid: null,\n cfg: newTarget,\n logger: logger,\n notify: _notifyWatchers,\n set: _setValue,\n setDf: _applyDefaults,\n watch: _watch,\n ref: _ref,\n rdOnly: _rdOnly,\n blkVal: _blkPropValue,\n _block: _block\n };\n objDefine(cfgHandler, \"uid\", {\n c: false,\n e: false,\n w: false,\n v: uid\n });\n theState = _createState(cfgHandler);\n // Setup tracking for all defined default keys\n _makeDynamicObject(theState, newTarget, \"config\", \"Creating\");\n return cfgHandler;\n}\n/**\r\n * Log an invalid access message to the console\r\n */\nfunction _logInvalidAccess(logger, message) {\n if (logger) {\n logger[_DYN_WARN_TO_CONSOLE /* @min:%2ewarnToConsole */](message);\n logger[_DYN_THROW_INTERNAL /* @min:%2ethrowInternal */](2 /* eLoggingSeverity.WARNING */, 108 /* _eInternalMessageId.DynamicConfigException */, message);\n } else {\n // We don't have a logger so just throw an exception\n throwInvalidAccess(message);\n }\n}\n/**\r\n * Create or return a dynamic version of the passed config, if it is not already dynamic\r\n * @param config - The config to be converted into a dynamic config\r\n * @param defaultConfig - The default values to apply on the config if the properties don't already exist\r\n * @param inPlace - Should the config be converted in-place into a dynamic config or a new instance returned, defaults to true\r\n * @returns The dynamic config handler for the config (whether new or existing)\r\n */\nexport function createDynamicConfig(config, defaultConfig, logger, inPlace) {\n var dynamicHandler = _createDynamicHandler(logger, config || {}, inPlace);\n if (defaultConfig) {\n dynamicHandler.setDf(dynamicHandler.cfg, defaultConfig);\n }\n return dynamicHandler;\n}\n/**\r\n * Watch and track changes for accesses to the current config, the provided config MUST already be\r\n * a dynamic config or a child accessed via the dynamic config\r\n * @param logger - The logger instance to use if there is no existing handler\r\n * @returns A watcher handler instance that can be used to remove itself when being unloaded\r\n * @throws TypeError if the provided config is not a dynamic config instance\r\n */\nexport function onConfigChange(config, configHandler, logger) {\n var handler = config[CFG_HANDLER_LINK] || config;\n if (handler.cfg && (handler.cfg === config || handler.cfg[CFG_HANDLER_LINK] === handler)) {\n return handler[_DYN_WATCH /* @min:%2ewatch */](configHandler);\n }\n _logInvalidAccess(logger, STR_NOT_DYNAMIC_ERROR + dumpObj(config));\n return createDynamicConfig(config, null, logger)[_DYN_WATCH /* @min:%2ewatch */](configHandler);\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { createPromise, doAwaitResponse } from \"@nevware21/ts-async\";\nimport { arrSlice, getLength } from \"@nevware21/ts-utils\";\nimport { _DYN_UNLOAD } from \"../__DynamicConstants\";\n/**\r\n * Run the unload function of the target object if it exists\r\n * @param target - The target object that contains the unload function\r\n * @param isAsync - The caller identifies whether it is expecting the operation to complete synchronously or asynchronously. Even\r\n * if the caller is not waiting the operation may still be performed asynchronously depending on the component and the reverse is\r\n * also true.\r\n * @returns The result of the target function\r\n */\nexport function runTargetUnload(target, isAsync) {\n if (target && target[_DYN_UNLOAD /* @min:%2eunload */]) {\n return target[_DYN_UNLOAD /* @min:%2eunload */](isAsync);\n }\n}\n/**\r\n * Call the unload function on all targets handling any returned [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * / Promise before calling the next targets unload\r\n * @param targets - An array of the targets to unload\r\n * @param isAsync - The caller identifies whether it is expecting the operations to complete synchronously or asynchronously. Even\r\n * if the caller is not waiting the operation may still be performed asynchronously depending on the component and the reverse is\r\n * also true.\r\n * @param done - Optional callback function to call once all of the unload functions have been called.\r\n */\nexport function doUnloadAll(targets, isAsync, done) {\n var result;\n if (!done) {\n result = createPromise(function (resolved) {\n done = resolved;\n });\n }\n if (targets && getLength(targets) > 0) {\n doAwaitResponse(runTargetUnload(targets[0], isAsync), function () {\n doUnloadAll(arrSlice(targets, 1), isAsync, done);\n });\n } else {\n done();\n }\n return result;\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nexport var ChannelControllerPriority = 500;\nexport var DisabledPropertyName = \"Microsoft_ApplicationInsights_BypassAjaxInstrumentation\";\n// export const SampleRate = \"sampleRate\";\n// export const ProcessLegacy = \"ProcessLegacy\";\n// export const HttpMethod = \"http.method\";\n// export const DEFAULT_BREEZE_ENDPOINT = \"https://dc.services.visualstudio.com\";\n// export const DEFAULT_BREEZE_PATH = \"/v2/track\";\n// export const strNotSpecified = \"not_specified\";\n// export const strIkey = \"iKey\";\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { asString, isBoolean, isFunction, isNullOrUndefined, isString } from \"@nevware21/ts-utils\";\nimport { STR_EMPTY } from \"../JavaScriptSDK/InternalConstants\";\nimport { _DYN_TO_LOWER_CASE } from \"../__DynamicConstants\";\n/**\r\n * @internal\r\n * @ignore\r\n * @param str\r\n * @param defaultValue\r\n * @returns\r\n */\nfunction _stringToBoolOrDefault(theValue, defaultValue, theConfig) {\n if (!theValue && isNullOrUndefined(theValue)) {\n return defaultValue;\n }\n if (isBoolean(theValue)) {\n return theValue;\n }\n return asString(theValue)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]() === \"true\";\n}\n/**\r\n * Helper which returns an IConfigDefaultCheck instance with the field defined as an object\r\n * that should be merged\r\n * @param defaultValue - The default value to apply it not provided or it's not valid\r\n * @returns a new IConfigDefaultCheck structure\r\n */\nexport function cfgDfMerge(defaultValue) {\n return {\n mrg: true,\n v: defaultValue\n };\n}\n/**\r\n * Helper which returns an IConfigDefaultCheck instance with the provided field set function\r\n * @param setter - The IConfigCheckFn function to validate the user provided value\r\n * @param defaultValue - The default value to apply it not provided or it's not valid\r\n * @returns a new IConfigDefaultCheck structure\r\n */\nexport function cfgDfSet(setter, defaultValue) {\n return {\n set: setter,\n v: defaultValue\n };\n}\n/**\r\n * Helper which returns an IConfigDefaultCheck instance with the provided field validator\r\n * @param validator - The IConfigCheckFn function to validate the user provided value\r\n * @param defaultValue - The default value to apply it not provided or it's not valid\r\n * @param fallBackName - The fallback configuration name if the current value is not available\r\n * @returns a new IConfigDefaultCheck structure\r\n */\nexport function cfgDfValidate(validator, defaultValue, fallBackName) {\n return {\n fb: fallBackName,\n isVal: validator,\n v: defaultValue\n };\n}\n/**\r\n * Helper which returns an IConfigDefaultCheck instance that will validate and convert the user\r\n * provided value to a boolean from a string or boolean value\r\n * @param defaultValue - The default value to apply it not provided or it's not valid\r\n * @param fallBackName - The fallback configuration name if the current value is not available\r\n * @returns a new IConfigDefaultCheck structure\r\n */\nexport function cfgDfBoolean(defaultValue, fallBackName) {\n return {\n fb: fallBackName,\n set: _stringToBoolOrDefault,\n v: !!defaultValue\n };\n}\n/**\r\n * Helper which returns an IConfigDefaultCheck instance that will validate that the user\r\n * provided value is a function.\r\n * @param defaultValue - The default value to apply it not provided or it's not valid\r\n * @returns a new IConfigDefaultCheck structure\r\n */\nexport function cfgDfFunc(defaultValue) {\n return {\n isVal: isFunction,\n v: defaultValue || null\n };\n}\n/**\r\n * Helper which returns an IConfigDefaultCheck instance that will validate that the user\r\n * provided value is a function.\r\n * @param defaultValue - The default string value to apply it not provided or it's not valid, defaults to an empty string\r\n * @returns a new IConfigDefaultCheck structure\r\n */\nexport function cfgDfString(defaultValue) {\n return {\n isVal: isString,\n v: asString(defaultValue || STR_EMPTY)\n };\n}\n/**\r\n * Helper which returns an IConfigDefaultCheck instance identifying that value associated with this property\r\n * should not have it's properties converted into a dynamic config properties.\r\n * @param defaultValue - The default value to apply it not provided or it's not valid\r\n * @returns a new IConfigDefaultCheck structure\r\n */\nexport function cfgDfBlockPropValue(defaultValue) {\n return {\n blkVal: true,\n v: defaultValue\n };\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { getInst } from \"@nevware21/ts-utils\";\nimport { _DYN_APPLY, _DYN_LENGTH } from \"../__DynamicConstants\";\nimport { STR_EVENTS_DISCARDED, STR_EVENTS_SEND_REQUEST, STR_EVENTS_SENT, STR_PERF_EVENT } from \"./InternalConstants\";\nvar listenerFuncs = [STR_EVENTS_SENT, STR_EVENTS_DISCARDED, STR_EVENTS_SEND_REQUEST, STR_PERF_EVENT];\nvar _aiNamespace = null;\nvar _debugListener;\nfunction _listenerProxyFunc(name, config) {\n return function () {\n var args = arguments;\n var dbgExt = getDebugExt(config);\n if (dbgExt) {\n var listener = dbgExt.listener;\n if (listener && listener[name]) {\n listener[name][_DYN_APPLY /* @min:%2eapply */](listener, args);\n }\n }\n };\n}\nfunction _getExtensionNamespace() {\n // Cache the lookup of the global namespace object\n var target = getInst(\"Microsoft\");\n if (target) {\n _aiNamespace = target[\"ApplicationInsights\"];\n }\n return _aiNamespace;\n}\nexport function getDebugExt(config) {\n var ns = _aiNamespace;\n if (!ns && config.disableDbgExt !== true) {\n ns = _aiNamespace || _getExtensionNamespace();\n }\n return ns ? ns[\"ChromeDbgExt\"] : null;\n}\nexport function getDebugListener(config) {\n if (!_debugListener) {\n _debugListener = {};\n for (var lp = 0; lp < listenerFuncs[_DYN_LENGTH /* @min:%2elength */]; lp++) {\n _debugListener[listenerFuncs[lp]] = _listenerProxyFunc(listenerFuncs[lp], config);\n }\n }\n return _debugListener;\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n\"use strict\";\n\nvar _a;\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { dumpObj, isFunction, isUndefined } from \"@nevware21/ts-utils\";\nimport { createDynamicConfig, onConfigChange } from \"../Config/DynamicConfig\";\nimport { _DYN_DIAG_LOG, _DYN_LOGGER, _DYN_LOGGING_LEVEL_CONSOL4, _DYN_MESSAGE, _DYN_MESSAGE_ID, _DYN_PUSH, _DYN_REPLACE, _DYN_THROW_INTERNAL, _DYN_UNLOAD, _DYN_WARN_TO_CONSOLE } from \"../__DynamicConstants\";\nimport { getDebugExt } from \"./DbgExtensionUtils\";\nimport { getConsole, getJSON, hasJSON } from \"./EnvUtils\";\nimport { STR_EMPTY } from \"./InternalConstants\";\nvar STR_WARN_TO_CONSOLE = \"warnToConsole\";\n/**\r\n * For user non actionable traces use AI Internal prefix.\r\n */\nvar AiNonUserActionablePrefix = \"AI (Internal): \";\n/**\r\n * Prefix of the traces in portal.\r\n */\nvar AiUserActionablePrefix = \"AI: \";\n/**\r\n * Session storage key for the prefix for the key indicating message type already logged\r\n */\nvar AIInternalMessagePrefix = \"AITR_\";\nvar defaultValues = {\n loggingLevelConsole: 0,\n loggingLevelTelemetry: 1,\n maxMessageLimit: 25,\n enableDebug: false\n};\nvar _logFuncs = (_a = {}, _a[0 /* eLoggingSeverity.DISABLED */] = null, _a[1 /* eLoggingSeverity.CRITICAL */] = \"errorToConsole\", _a[2 /* eLoggingSeverity.WARNING */] = STR_WARN_TO_CONSOLE, _a[3 /* eLoggingSeverity.DEBUG */] = \"debugToConsole\", _a);\nfunction _sanitizeDiagnosticText(text) {\n if (text) {\n return \"\\\"\" + text[_DYN_REPLACE /* @min:%2ereplace */](/\\\"/g, STR_EMPTY) + \"\\\"\";\n }\n return STR_EMPTY;\n}\nfunction _logToConsole(func, message) {\n var theConsole = getConsole();\n if (!!theConsole) {\n var logFunc = \"log\";\n if (theConsole[func]) {\n logFunc = func;\n }\n if (isFunction(theConsole[logFunc])) {\n theConsole[logFunc](message);\n }\n }\n}\nvar _InternalLogMessage = /** @class */function () {\n function _InternalLogMessage(msgId, msg, isUserAct, properties) {\n if (isUserAct === void 0) {\n isUserAct = false;\n }\n var _self = this;\n _self[_DYN_MESSAGE_ID /* @min:%2emessageId */] = msgId;\n _self[_DYN_MESSAGE /* @min:%2emessage */] = (isUserAct ? AiUserActionablePrefix : AiNonUserActionablePrefix) + msgId;\n var strProps = STR_EMPTY;\n if (hasJSON()) {\n strProps = getJSON().stringify(properties);\n }\n var diagnosticText = (msg ? \" message:\" + _sanitizeDiagnosticText(msg) : STR_EMPTY) + (properties ? \" props:\" + _sanitizeDiagnosticText(strProps) : STR_EMPTY);\n _self[_DYN_MESSAGE /* @min:%2emessage */] += diagnosticText;\n }\n _InternalLogMessage.dataType = \"MessageData\";\n return _InternalLogMessage;\n}();\nexport { _InternalLogMessage };\nexport function safeGetLogger(core, config) {\n return (core || {})[_DYN_LOGGER /* @min:%2elogger */] || new DiagnosticLogger(config);\n}\nvar DiagnosticLogger = /** @class */function () {\n function DiagnosticLogger(config) {\n this.identifier = \"DiagnosticLogger\";\n /**\r\n * The internal logging queue\r\n */\n this.queue = [];\n /**\r\n * Count of internal messages sent\r\n */\n var _messageCount = 0;\n /**\r\n * Holds information about what message types were already logged to console or sent to server.\r\n */\n var _messageLogged = {};\n var _loggingLevelConsole;\n var _loggingLevelTelemetry;\n var _maxInternalMessageLimit;\n var _enableDebug;\n var _unloadHandler;\n dynamicProto(DiagnosticLogger, this, function (_self) {\n _unloadHandler = _setDefaultsFromConfig(config || {});\n _self.consoleLoggingLevel = function () {\n return _loggingLevelConsole;\n };\n /**\r\n * This method will throw exceptions in debug mode or attempt to log the error as a console warning.\r\n * @param severity - The severity of the log message\r\n * @param message - The log message.\r\n */\n _self[_DYN_THROW_INTERNAL /* @min:%2ethrowInternal */] = function (severity, msgId, msg, properties, isUserAct) {\n if (isUserAct === void 0) {\n isUserAct = false;\n }\n var message = new _InternalLogMessage(msgId, msg, isUserAct, properties);\n if (_enableDebug) {\n throw dumpObj(message);\n } else {\n // Get the logging function and fallback to warnToConsole of for some reason errorToConsole doesn't exist\n var logFunc = _logFuncs[severity] || STR_WARN_TO_CONSOLE;\n if (!isUndefined(message[_DYN_MESSAGE /* @min:%2emessage */])) {\n if (isUserAct) {\n // check if this message type was already logged to console for this page view and if so, don't log it again\n var messageKey = +message[_DYN_MESSAGE_ID /* @min:%2emessageId */];\n if (!_messageLogged[messageKey] && _loggingLevelConsole >= severity) {\n _self[logFunc](message[_DYN_MESSAGE /* @min:%2emessage */]);\n _messageLogged[messageKey] = true;\n }\n } else {\n // Only log traces if the console Logging Level is >= the throwInternal severity level\n if (_loggingLevelConsole >= severity) {\n _self[logFunc](message[_DYN_MESSAGE /* @min:%2emessage */]);\n }\n }\n _logInternalMessage(severity, message);\n } else {\n _debugExtMsg(\"throw\" + (severity === 1 /* eLoggingSeverity.CRITICAL */ ? \"Critical\" : \"Warning\"), message);\n }\n }\n };\n _self.debugToConsole = function (message) {\n _logToConsole(\"debug\", message);\n _debugExtMsg(\"warning\", message);\n };\n _self[_DYN_WARN_TO_CONSOLE /* @min:%2ewarnToConsole */] = function (message) {\n _logToConsole(\"warn\", message);\n _debugExtMsg(\"warning\", message);\n };\n _self.errorToConsole = function (message) {\n _logToConsole(\"error\", message);\n _debugExtMsg(\"error\", message);\n };\n _self.resetInternalMessageCount = function () {\n _messageCount = 0;\n _messageLogged = {};\n };\n _self.logInternalMessage = _logInternalMessage;\n _self[_DYN_UNLOAD /* @min:%2eunload */] = function (isAsync) {\n _unloadHandler && _unloadHandler.rm();\n _unloadHandler = null;\n };\n function _logInternalMessage(severity, message) {\n if (_areInternalMessagesThrottled()) {\n return;\n }\n // check if this message type was already logged for this session and if so, don't log it again\n var logMessage = true;\n var messageKey = AIInternalMessagePrefix + message[_DYN_MESSAGE_ID /* @min:%2emessageId */];\n // if the session storage is not available, limit to only one message type per page view\n if (_messageLogged[messageKey]) {\n logMessage = false;\n } else {\n _messageLogged[messageKey] = true;\n }\n if (logMessage) {\n // Push the event in the internal queue\n if (severity <= _loggingLevelTelemetry) {\n _self.queue[_DYN_PUSH /* @min:%2epush */](message);\n _messageCount++;\n _debugExtMsg(severity === 1 /* eLoggingSeverity.CRITICAL */ ? \"error\" : \"warn\", message);\n }\n // When throttle limit reached, send a special event\n if (_messageCount === _maxInternalMessageLimit) {\n var throttleLimitMessage = \"Internal events throttle limit per PageView reached for this app.\";\n var throttleMessage = new _InternalLogMessage(23 /* _eInternalMessageId.MessageLimitPerPVExceeded */, throttleLimitMessage, false);\n _self.queue[_DYN_PUSH /* @min:%2epush */](throttleMessage);\n if (severity === 1 /* eLoggingSeverity.CRITICAL */) {\n _self.errorToConsole(throttleLimitMessage);\n } else {\n _self[_DYN_WARN_TO_CONSOLE /* @min:%2ewarnToConsole */](throttleLimitMessage);\n }\n }\n }\n }\n function _setDefaultsFromConfig(config) {\n // make sure the config is dynamic\n return onConfigChange(createDynamicConfig(config, defaultValues, _self).cfg, function (details) {\n var config = details.cfg;\n _loggingLevelConsole = config[_DYN_LOGGING_LEVEL_CONSOL4 /* @min:%2eloggingLevelConsole */];\n _loggingLevelTelemetry = config.loggingLevelTelemetry;\n _maxInternalMessageLimit = config.maxMessageLimit;\n _enableDebug = config.enableDebug;\n });\n }\n function _areInternalMessagesThrottled() {\n return _messageCount >= _maxInternalMessageLimit;\n }\n function _debugExtMsg(name, data) {\n var dbgExt = getDebugExt(config || {});\n if (dbgExt && dbgExt[_DYN_DIAG_LOG /* @min:%2ediagLog */]) {\n dbgExt[_DYN_DIAG_LOG /* @min:%2ediagLog */](name, data);\n }\n }\n });\n }\n // Removed Stub for DiagnosticLogger.prototype.consoleLoggingLevel.\n // Removed Stub for DiagnosticLogger.prototype.throwInternal.\n // Removed Stub for DiagnosticLogger.prototype.debugToConsole.\n // Removed Stub for DiagnosticLogger.prototype.warnToConsole.\n // Removed Stub for DiagnosticLogger.prototype.errorToConsole.\n // Removed Stub for DiagnosticLogger.prototype.resetInternalMessageCount.\n // Removed Stub for DiagnosticLogger.prototype.logInternalMessage.\n // Removed Stub for DiagnosticLogger.prototype.unload.\n // This is a workaround for an IE bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n DiagnosticLogger.__ieDyn = 1;\n return DiagnosticLogger;\n}();\nexport { DiagnosticLogger };\nfunction _getLogger(logger) {\n return logger || new DiagnosticLogger();\n}\n/**\r\n * This is a helper method which will call throwInternal on the passed logger, will throw exceptions in\r\n * debug mode or attempt to log the error as a console warning. This helper is provided mostly to better\r\n * support minification as logger.throwInternal() will not compress the publish \"throwInternal\" used throughout\r\n * the code.\r\n * @param logger - The Diagnostic Logger instance to use.\r\n * @param severity - The severity of the log message\r\n * @param message - The log message.\r\n */\nexport function _throwInternal(logger, severity, msgId, msg, properties, isUserAct) {\n if (isUserAct === void 0) {\n isUserAct = false;\n }\n _getLogger(logger)[_DYN_THROW_INTERNAL /* @min:%2ethrowInternal */](severity, msgId, msg, properties, isUserAct);\n}\n/**\r\n * This is a helper method which will call warnToConsole on the passed logger with the provided message.\r\n * @param logger - The Diagnostic Logger instance to use.\r\n * @param message - The log message.\r\n */\nexport function _warnToConsole(logger, message) {\n _getLogger(logger)[_DYN_WARN_TO_CONSOLE /* @min:%2ewarnToConsole */](message);\n}\n/**\r\n * Logs a message to the internal queue.\r\n * @param logger - The Diagnostic Logger instance to use.\r\n * @param severity - The severity of the log message\r\n * @param message - The message to log.\r\n */\nexport function _logInternalMessage(logger, severity, message) {\n _getLogger(logger).logInternalMessage(severity, message);\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nvar _a, _b;\nimport { arrForEach, arrIndexOf, dumpObj, getDocument, getLazy, getNavigator, isArray, isFunction, isNullOrUndefined, isString, isTruthy, isUndefined, objForEachKey, strEndsWith, strIndexOf, strLeft, strSubstring, strTrim, utcNow } from \"@nevware21/ts-utils\";\nimport { cfgDfMerge } from \"../Config/ConfigDefaultHelpers\";\nimport { createDynamicConfig, onConfigChange } from \"../Config/DynamicConfig\";\nimport { _DYN_ENABLED, _DYN_LENGTH, _DYN_LOGGER, _DYN_SPLIT, _DYN_USER_AGENT } from \"../__DynamicConstants\";\nimport { _throwInternal } from \"./DiagnosticLogger\";\nimport { getLocation, isIE } from \"./EnvUtils\";\nimport { getExceptionName, isNotNullOrUndefined, setValue, strContains } from \"./HelperFuncs\";\nimport { STR_DOMAIN, STR_EMPTY, STR_PATH, UNDEFINED_VALUE } from \"./InternalConstants\";\nvar strToGMTString = \"toGMTString\";\nvar strToUTCString = \"toUTCString\";\nvar strCookie = \"cookie\";\nvar strExpires = \"expires\";\nvar strIsCookieUseDisabled = \"isCookieUseDisabled\";\nvar strDisableCookiesUsage = \"disableCookiesUsage\";\nvar strConfigCookieMgr = \"_ckMgr\";\nvar _supportsCookies = null;\nvar _allowUaSameSite = null;\nvar _parsedCookieValue = null;\nvar _doc;\nvar _cookieCache = {};\nvar _globalCookieConfig = {};\n// // `isCookieUseDisabled` is deprecated, so explicitly casting as a key of IConfiguration to avoid typing error\n// // when both isCookieUseDisabled and disableCookiesUsage are used disableCookiesUsage will take precedent, which is\n// // why its listed first\n/**\r\n * Set the supported dynamic config values as undefined (or an empty object) so that\r\n * any listeners will be informed of any changes.\r\n * Explicitly NOT including the deprecated `isCookieUseDisabled` as we don't want to support\r\n * the v1 deprecated field as dynamic for updates\r\n */\nvar rootDefaultConfig = (_a = {\n cookieCfg: cfgDfMerge((_b = {}, _b[STR_DOMAIN] = {\n fb: \"cookieDomain\",\n dfVal: isNotNullOrUndefined\n }, _b.path = {\n fb: \"cookiePath\",\n dfVal: isNotNullOrUndefined\n }, _b.enabled = UNDEFINED_VALUE, _b.ignoreCookies = UNDEFINED_VALUE, _b.blockedCookies = UNDEFINED_VALUE, _b)),\n cookieDomain: UNDEFINED_VALUE,\n cookiePath: UNDEFINED_VALUE\n}, _a[strDisableCookiesUsage] = UNDEFINED_VALUE, _a);\nfunction _getDoc() {\n !_doc && (_doc = getLazy(function () {\n return getDocument();\n }));\n}\n/**\r\n * @ignore\r\n * DO NOT USE or export from the module, this is exposed as public to support backward compatibility of previous static utility methods only.\r\n * If you want to manager cookies either use the ICookieMgr available from the core instance via getCookieMgr() or create\r\n * your own instance of the CookieMgr and use that.\r\n * Using this directly for enabling / disabling cookie handling will not only affect your usage but EVERY user of cookies.\r\n * Example, if you are using a shared component that is also using Application Insights you will affect their cookie handling.\r\n * @param logger - The DiagnosticLogger to use for reporting errors.\r\n */\nfunction _gblCookieMgr(config, logger) {\n // Stash the global instance against the BaseCookieMgr class\n var inst = createCookieMgr[strConfigCookieMgr] || _globalCookieConfig[strConfigCookieMgr];\n if (!inst) {\n // Note: not using the getSetValue() helper as that would require always creating a temporary cookieMgr\n // that ultimately is never used\n inst = createCookieMgr[strConfigCookieMgr] = createCookieMgr(config, logger);\n _globalCookieConfig[strConfigCookieMgr] = inst;\n }\n return inst;\n}\nfunction _isMgrEnabled(cookieMgr) {\n if (cookieMgr) {\n return cookieMgr.isEnabled();\n }\n return true;\n}\nfunction _isIgnoredCookie(cookieMgrCfg, name) {\n if (name && cookieMgrCfg && isArray(cookieMgrCfg.ignoreCookies)) {\n return arrIndexOf(cookieMgrCfg.ignoreCookies, name) !== -1;\n }\n return false;\n}\nfunction _isBlockedCookie(cookieMgrCfg, name) {\n if (name && cookieMgrCfg && isArray(cookieMgrCfg.blockedCookies)) {\n if (arrIndexOf(cookieMgrCfg.blockedCookies, name) !== -1) {\n return true;\n }\n }\n return _isIgnoredCookie(cookieMgrCfg, name);\n}\nfunction _isCfgEnabled(rootConfig, cookieMgrConfig) {\n var isCfgEnabled = cookieMgrConfig[_DYN_ENABLED /* @min:%2eenabled */];\n if (isNullOrUndefined(isCfgEnabled)) {\n // Set the enabled from the provided setting or the legacy root values\n var cookieEnabled = void 0;\n // This field is deprecated and dynamic updates will not be fully supported\n if (!isUndefined(rootConfig[strIsCookieUseDisabled])) {\n cookieEnabled = !rootConfig[strIsCookieUseDisabled];\n }\n // If this value is defined it takes precedent over the above\n if (!isUndefined(rootConfig[strDisableCookiesUsage])) {\n cookieEnabled = !rootConfig[strDisableCookiesUsage];\n }\n // Not setting the cookieMgrConfig.enabled as that will update (set) the global dynamic config\n // So future \"updates\" then may not be as expected\n isCfgEnabled = cookieEnabled;\n }\n return isCfgEnabled;\n}\n/**\r\n * Helper to return the ICookieMgr from the core (if not null/undefined) or a default implementation\r\n * associated with the configuration or a legacy default.\r\n * @param core - The AppInsightsCore instance to get the cookie manager from\r\n * @param config - The config to use if the core is not available\r\n * @returns\r\n */\nexport function safeGetCookieMgr(core, config) {\n var cookieMgr;\n if (core) {\n // Always returns an instance\n cookieMgr = core.getCookieMgr();\n } else if (config) {\n var cookieCfg = config.cookieCfg;\n if (cookieCfg && cookieCfg[strConfigCookieMgr]) {\n cookieMgr = cookieCfg[strConfigCookieMgr];\n } else {\n cookieMgr = createCookieMgr(config);\n }\n }\n if (!cookieMgr) {\n // Get or initialize the default global (legacy) cookie manager if we couldn't find one\n cookieMgr = _gblCookieMgr(config, (core || {})[_DYN_LOGGER /* @min:%2elogger */]);\n }\n return cookieMgr;\n}\nexport function createCookieMgr(rootConfig, logger) {\n var cookieMgrConfig;\n var _path;\n var _domain;\n var unloadHandler;\n // Explicitly checking against false, so that setting to undefined will === true\n var _enabled;\n var _getCookieFn;\n var _setCookieFn;\n var _delCookieFn;\n // Make sure the root config is dynamic as it may be the global config\n rootConfig = createDynamicConfig(rootConfig || _globalCookieConfig, null, logger).cfg;\n // Will get recalled if the referenced configuration is changed\n unloadHandler = onConfigChange(rootConfig, function (details) {\n // Make sure the root config has all of the the defaults to the root config to ensure they are dynamic\n details.setDf(details.cfg, rootDefaultConfig);\n // Create and apply the defaults to the cookieCfg element\n cookieMgrConfig = details.ref(details.cfg, \"cookieCfg\"); // details.setDf(details.cfg.cookieCfg, defaultConfig);\n _path = cookieMgrConfig[STR_PATH /* @min:%2epath */] || \"/\";\n _domain = cookieMgrConfig[STR_DOMAIN /* @min:%2edomain */];\n // Explicitly checking against false, so that setting to undefined will === true\n _enabled = _isCfgEnabled(rootConfig, cookieMgrConfig) !== false;\n _getCookieFn = cookieMgrConfig.getCookie || _getCookieValue;\n _setCookieFn = cookieMgrConfig.setCookie || _setCookieValue;\n _delCookieFn = cookieMgrConfig.delCookie || _setCookieValue;\n }, logger);\n var cookieMgr = {\n isEnabled: function () {\n var enabled = _isCfgEnabled(rootConfig, cookieMgrConfig) !== false && _enabled && areCookiesSupported(logger);\n // Using an indirect lookup for any global cookie manager to support tree shaking for SDK's\n // that don't use the \"applicationinsights-core\" version of the default cookie function\n var gblManager = _globalCookieConfig[strConfigCookieMgr];\n if (enabled && gblManager && cookieMgr !== gblManager) {\n // Make sure the GlobalCookie Manager instance (if not this instance) is also enabled.\n // As the global (deprecated) functions may have been called (for backward compatibility)\n enabled = _isMgrEnabled(gblManager);\n }\n return enabled;\n },\n setEnabled: function (value) {\n // Explicitly checking against false, so that setting to undefined will === true\n _enabled = value !== false;\n cookieMgrConfig[_DYN_ENABLED /* @min:%2eenabled */] = value;\n },\n set: function (name, value, maxAgeSec, domain, path) {\n var result = false;\n if (_isMgrEnabled(cookieMgr) && !_isBlockedCookie(cookieMgrConfig, name)) {\n var values = {};\n var theValue = strTrim(value || STR_EMPTY);\n var idx = strIndexOf(theValue, \";\");\n if (idx !== -1) {\n theValue = strTrim(strLeft(value, idx));\n values = _extractParts(strSubstring(value, idx + 1));\n }\n // Only update domain if not already present (isUndefined) and the value is truthy (not null, undefined or empty string)\n setValue(values, STR_DOMAIN, domain || _domain, isTruthy, isUndefined);\n if (!isNullOrUndefined(maxAgeSec)) {\n var _isIE = isIE();\n if (isUndefined(values[strExpires])) {\n var nowMs = utcNow();\n // Only add expires if not already present\n var expireMs = nowMs + maxAgeSec * 1000;\n // Sanity check, if zero or -ve then ignore\n if (expireMs > 0) {\n var expiry = new Date();\n expiry.setTime(expireMs);\n setValue(values, strExpires, _formatDate(expiry, !_isIE ? strToUTCString : strToGMTString) || _formatDate(expiry, _isIE ? strToGMTString : strToUTCString) || STR_EMPTY, isTruthy);\n }\n }\n if (!_isIE) {\n // Only replace if not already present\n setValue(values, \"max-age\", STR_EMPTY + maxAgeSec, null, isUndefined);\n }\n }\n var location_1 = getLocation();\n if (location_1 && location_1.protocol === \"https:\") {\n setValue(values, \"secure\", null, null, isUndefined);\n // Only set same site if not also secure\n if (_allowUaSameSite === null) {\n _allowUaSameSite = !uaDisallowsSameSiteNone((getNavigator() || {})[_DYN_USER_AGENT /* @min:%2euserAgent */]);\n }\n if (_allowUaSameSite) {\n setValue(values, \"SameSite\", \"None\", null, isUndefined);\n }\n }\n setValue(values, STR_PATH, path || _path, null, isUndefined);\n //let setCookieFn = cookieMgrConfig.setCookie || _setCookieValue;\n _setCookieFn(name, _formatCookieValue(theValue, values));\n result = true;\n }\n return result;\n },\n get: function (name) {\n var value = STR_EMPTY;\n if (_isMgrEnabled(cookieMgr) && !_isIgnoredCookie(cookieMgrConfig, name)) {\n value = _getCookieFn(name);\n }\n return value;\n },\n del: function (name, path) {\n var result = false;\n if (_isMgrEnabled(cookieMgr)) {\n // Only remove the cookie if the manager and cookie support has not been disabled\n result = cookieMgr.purge(name, path);\n }\n return result;\n },\n purge: function (name, path) {\n var _a;\n var result = false;\n if (areCookiesSupported(logger)) {\n // Setting the expiration date in the past immediately removes the cookie\n var values = (_a = {}, _a[STR_PATH] = path ? path : \"/\", _a[strExpires] = \"Thu, 01 Jan 1970 00:00:01 GMT\", _a);\n if (!isIE()) {\n // Set max age to expire now\n values[\"max-age\"] = \"0\";\n }\n // let delCookie = cookieMgrConfig.delCookie || _setCookieValue;\n _delCookieFn(name, _formatCookieValue(STR_EMPTY, values));\n result = true;\n }\n return result;\n },\n unload: function (isAsync) {\n unloadHandler && unloadHandler.rm();\n unloadHandler = null;\n }\n };\n // Associated this cookie manager with the config\n cookieMgr[strConfigCookieMgr] = cookieMgr;\n return cookieMgr;\n}\n/*\r\n* Helper method to tell if document.cookie object is supported by the runtime\r\n*/\nexport function areCookiesSupported(logger) {\n if (_supportsCookies === null) {\n _supportsCookies = false;\n !_doc && _getDoc();\n try {\n var doc = _doc.v || {};\n _supportsCookies = doc[strCookie] !== undefined;\n } catch (e) {\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 68 /* _eInternalMessageId.CannotAccessCookie */, \"Cannot access document.cookie - \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n }\n return _supportsCookies;\n}\nfunction _extractParts(theValue) {\n var values = {};\n if (theValue && theValue[_DYN_LENGTH /* @min:%2elength */]) {\n var parts = strTrim(theValue)[_DYN_SPLIT /* @min:%2esplit */](\";\");\n arrForEach(parts, function (thePart) {\n thePart = strTrim(thePart || STR_EMPTY);\n if (thePart) {\n var idx = strIndexOf(thePart, \"=\");\n if (idx === -1) {\n values[thePart] = null;\n } else {\n values[strTrim(strLeft(thePart, idx))] = strTrim(strSubstring(thePart, idx + 1));\n }\n }\n });\n }\n return values;\n}\nfunction _formatDate(theDate, func) {\n if (isFunction(theDate[func])) {\n return theDate[func]();\n }\n return null;\n}\nfunction _formatCookieValue(value, values) {\n var cookieValue = value || STR_EMPTY;\n objForEachKey(values, function (name, theValue) {\n cookieValue += \"; \" + name + (!isNullOrUndefined(theValue) ? \"=\" + theValue : STR_EMPTY);\n });\n return cookieValue;\n}\nfunction _getCookieValue(name) {\n var cookieValue = STR_EMPTY;\n !_doc && _getDoc();\n if (_doc.v) {\n var theCookie = _doc.v[strCookie] || STR_EMPTY;\n if (_parsedCookieValue !== theCookie) {\n _cookieCache = _extractParts(theCookie);\n _parsedCookieValue = theCookie;\n }\n cookieValue = strTrim(_cookieCache[name] || STR_EMPTY);\n }\n return cookieValue;\n}\nfunction _setCookieValue(name, cookieValue) {\n !_doc && _getDoc();\n if (_doc.v) {\n _doc.v[strCookie] = name + \"=\" + cookieValue;\n }\n}\nexport function uaDisallowsSameSiteNone(userAgent) {\n if (!isString(userAgent)) {\n return false;\n }\n // Cover all iOS based browsers here. This includes:\n // - Safari on iOS 12 for iPhone, iPod Touch, iPad\n // - WkWebview on iOS 12 for iPhone, iPod Touch, iPad\n // - Chrome on iOS 12 for iPhone, iPod Touch, iPad\n // All of which are broken by SameSite=None, because they use the iOS networking stack\n if (strContains(userAgent, \"CPU iPhone OS 12\") || strContains(userAgent, \"iPad; CPU OS 12\")) {\n return true;\n }\n // Cover Mac OS X based browsers that use the Mac OS networking stack. This includes:\n // - Safari on Mac OS X\n // This does not include:\n // - Internal browser on Mac OS X\n // - Chrome on Mac OS X\n // - Chromium on Mac OS X\n // Because they do not use the Mac OS networking stack.\n if (strContains(userAgent, \"Macintosh; Intel Mac OS X 10_14\") && strContains(userAgent, \"Version/\") && strContains(userAgent, \"Safari\")) {\n return true;\n }\n // Cover Mac OS X internal browsers that use the Mac OS networking stack. This includes:\n // - Internal browser on Mac OS X\n // This does not include:\n // - Safari on Mac OS X\n // - Chrome on Mac OS X\n // - Chromium on Mac OS X\n // Because they do not use the Mac OS networking stack.\n if (strContains(userAgent, \"Macintosh; Intel Mac OS X 10_14\") && strEndsWith(userAgent, \"AppleWebKit/605.1.15 (KHTML, like Gecko)\")) {\n return true;\n }\n // Cover Chrome 50-69, because some versions are broken by SameSite=None, and none in this range require it.\n // Note: this covers some pre-Chromium Edge versions, but pre-Chromim Edge does not require SameSite=None, so this is fine.\n // Note: this regex applies to Windows, Mac OS X, and Linux, deliberately.\n if (strContains(userAgent, \"Chrome/5\") || strContains(userAgent, \"Chrome/6\")) {\n return true;\n }\n // Unreal Engine runs Chromium 59, but does not advertise as Chrome until 4.23. Treat versions of Unreal\n // that don't specify their Chrome version as lacking support for SameSite=None.\n if (strContains(userAgent, \"UnrealEngine\") && !strContains(userAgent, \"Chrome\")) {\n return true;\n }\n // UCBrowser < 12.13.2 ignores Set-Cookie headers with SameSite=None\n // NB: this rule isn't complete - you need regex to make a complete rule.\n // See: https://www.chromium.org/updates/same-site/incompatible-clients\n if (strContains(userAgent, \"UCBrowser/12\") || strContains(userAgent, \"UCBrowser/11\")) {\n return true;\n }\n return false;\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { createAllPromise, createPromise, doAwaitResponse } from \"@nevware21/ts-async\";\nimport { arrForEach, arrIndexOf, objDefine, safe, scheduleTimeout } from \"@nevware21/ts-utils\";\nimport { createDynamicConfig } from \"../Config/DynamicConfig\";\nimport { _DYN_ADD_NOTIFICATION_LIS1, _DYN_CANCEL, _DYN_DATA, _DYN_IS_CHILD_EVT, _DYN_LENGTH, _DYN_PUSH, _DYN_REMOVE_NOTIFICATION_0, _DYN_SPLICE, _DYN_UNLOAD, _DYN_WATCH } from \"../__DynamicConstants\";\nimport { STR_EVENTS_DISCARDED, STR_EVENTS_SEND_REQUEST, STR_EVENTS_SENT, STR_OFFLINE_DROP, STR_OFFLINE_SENT, STR_OFFLINE_STORE, STR_PERF_EVENT } from \"./InternalConstants\";\nvar defaultValues = {\n perfEvtsSendAll: false\n};\nfunction _runScheduledListeners(asyncNotifications) {\n asyncNotifications.h = null;\n var callbacks = asyncNotifications.cb;\n asyncNotifications.cb = [];\n arrForEach(callbacks, function (cb) {\n // Run the listener in a try-catch to ensure that a single listener failing doesn't prevent the others from running\n safe(cb.fn, [cb.arg]);\n });\n}\n// This function is used to combine the logic of running the listeners and handling the async notifications so that they don't\n// create multiple timers if there are multiple async listeners.\nfunction _runListeners(listeners, name, asyncNotifications, callback) {\n arrForEach(listeners, function (listener) {\n if (listener && listener[name]) {\n if (asyncNotifications) {\n // Schedule the callback to be called after the current call stack has cleared.\n asyncNotifications.cb[_DYN_PUSH /* @min:%2epush */]({\n fn: callback,\n arg: listener\n });\n asyncNotifications.h = asyncNotifications.h || scheduleTimeout(_runScheduledListeners, 0, asyncNotifications);\n } else {\n // Run the listener in a try-catch to ensure that a single listener failing doesn't prevent the others from running\n safe(callback, [listener]);\n }\n }\n });\n}\n/**\r\n * Class to manage sending notifications to all the listeners.\r\n */\nvar NotificationManager = /** @class */function () {\n function NotificationManager(config) {\n this.listeners = [];\n var perfEvtsSendAll;\n var unloadHandler;\n var _listeners = [];\n var _asyncNotifications = {\n h: null,\n cb: []\n };\n var cfgHandler = createDynamicConfig(config, defaultValues);\n unloadHandler = cfgHandler[_DYN_WATCH /* @min:%2ewatch */](function (details) {\n perfEvtsSendAll = !!details.cfg.perfEvtsSendAll;\n });\n dynamicProto(NotificationManager, this, function (_self) {\n objDefine(_self, \"listeners\", {\n g: function () {\n return _listeners;\n }\n });\n _self[_DYN_ADD_NOTIFICATION_LIS1 /* @min:%2eaddNotificationListener */] = function (listener) {\n _listeners[_DYN_PUSH /* @min:%2epush */](listener);\n };\n /**\r\n * Removes all instances of the listener.\r\n * @param listener - AWTNotificationListener to remove.\r\n */\n _self[_DYN_REMOVE_NOTIFICATION_0 /* @min:%2eremoveNotificationListener */] = function (listener) {\n var index = arrIndexOf(_listeners, listener);\n while (index > -1) {\n _listeners[_DYN_SPLICE /* @min:%2esplice */](index, 1);\n index = arrIndexOf(_listeners, listener);\n }\n };\n /**\r\n * Notification for events sent.\r\n * @param events - The array of events that have been sent.\r\n */\n _self[STR_EVENTS_SENT /* @min:%2eeventsSent */] = function (events) {\n _runListeners(_listeners, STR_EVENTS_SENT, _asyncNotifications, function (listener) {\n listener[STR_EVENTS_SENT /* @min:%2eeventsSent */](events);\n });\n };\n /**\r\n * Notification for events being discarded.\r\n * @param events - The array of events that have been discarded by the SDK.\r\n * @param reason - The reason for which the SDK discarded the events. The EventsDiscardedReason\r\n * constant should be used to check the different values.\r\n */\n _self[STR_EVENTS_DISCARDED /* @min:%2eeventsDiscarded */] = function (events, reason) {\n _runListeners(_listeners, STR_EVENTS_DISCARDED, _asyncNotifications, function (listener) {\n listener[STR_EVENTS_DISCARDED /* @min:%2eeventsDiscarded */](events, reason);\n });\n };\n /**\r\n * [Optional] A function called when the events have been requested to be sent to the sever.\r\n * @param sendReason - The reason why the event batch is being sent.\r\n * @param isAsync - A flag which identifies whether the requests are being sent in an async or sync manner.\r\n */\n _self[STR_EVENTS_SEND_REQUEST /* @min:%2eeventsSendRequest */] = function (sendReason, isAsync) {\n _runListeners(_listeners, STR_EVENTS_SEND_REQUEST, isAsync ? _asyncNotifications : null, function (listener) {\n listener[STR_EVENTS_SEND_REQUEST /* @min:%2eeventsSendRequest */](sendReason, isAsync);\n });\n };\n _self[STR_PERF_EVENT /* @min:%2eperfEvent */] = function (perfEvent) {\n if (perfEvent) {\n // Send all events or only parent events\n if (perfEvtsSendAll || !perfEvent[_DYN_IS_CHILD_EVT /* @min:%2eisChildEvt */]()) {\n _runListeners(_listeners, STR_PERF_EVENT, null, function (listener) {\n if (perfEvent.isAsync) {\n scheduleTimeout(function () {\n return listener[STR_PERF_EVENT /* @min:%2eperfEvent */](perfEvent);\n }, 0);\n } else {\n listener[STR_PERF_EVENT /* @min:%2eperfEvent */](perfEvent);\n }\n });\n }\n }\n };\n _self[STR_OFFLINE_STORE /* @min:%2eofflineEventsStored */] = function (events) {\n if (events && events[_DYN_LENGTH /* @min:%2elength */]) {\n _runListeners(_listeners, STR_OFFLINE_STORE, _asyncNotifications, function (listener) {\n listener[STR_OFFLINE_STORE /* @min:%2eofflineEventsStored */](events);\n });\n }\n };\n _self[STR_OFFLINE_SENT /* @min:%2eofflineBatchSent */] = function (batch) {\n if (batch && batch[_DYN_DATA /* @min:%2edata */]) {\n _runListeners(_listeners, STR_OFFLINE_SENT, _asyncNotifications, function (listener) {\n listener[STR_OFFLINE_SENT /* @min:%2eofflineBatchSent */](batch);\n });\n }\n };\n _self[STR_OFFLINE_DROP /* @min:%2eofflineBatchDrop */] = function (cnt, reason) {\n if (cnt > 0) {\n var rn_1 = reason || 0; // default is unknown\n _runListeners(_listeners, STR_OFFLINE_DROP, _asyncNotifications, function (listener) {\n listener[STR_OFFLINE_DROP /* @min:%2eofflineBatchDrop */](cnt, rn_1);\n });\n }\n };\n _self[_DYN_UNLOAD /* @min:%2eunload */] = function (isAsync) {\n var _finishUnload = function () {\n unloadHandler && unloadHandler.rm();\n unloadHandler = null;\n _listeners = [];\n // Clear any async listener\n _asyncNotifications.h && _asyncNotifications.h[_DYN_CANCEL /* @min:%2ecancel */]();\n _asyncNotifications.h = null;\n _asyncNotifications.cb = [];\n };\n var waiting;\n _runListeners(_listeners, \"unload\", null, function (listener) {\n var asyncUnload = listener[_DYN_UNLOAD /* @min:%2eunload */](isAsync);\n if (asyncUnload) {\n if (!waiting) {\n waiting = [];\n }\n waiting[_DYN_PUSH /* @min:%2epush */](asyncUnload);\n }\n });\n if (waiting) {\n return createPromise(function (resolve) {\n return doAwaitResponse(createAllPromise(waiting), function () {\n _finishUnload();\n resolve();\n });\n });\n } else {\n _finishUnload();\n }\n };\n });\n }\n // Removed Stub for NotificationManager.prototype.addNotificationListener.\n // Removed Stub for NotificationManager.prototype.removeNotificationListener.\n // Removed Stub for NotificationManager.prototype.eventsSent.\n // Removed Stub for NotificationManager.prototype.eventsDiscarded.\n // Removed Stub for NotificationManager.prototype.eventsSendRequest.\n // Removed Stub for NotificationManager.prototype.perfEvent.\n // Removed Stub for NotificationManager.prototype.unload.\n // Removed Stub for NotificationManager.prototype.offlineEventsStored.\n // Removed Stub for NotificationManager.prototype.offlineBatchSent.\n // Removed Stub for NotificationManager.prototype.offlineBatchDrop.\n // This is a workaround for an IE bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n NotificationManager.__ieDyn = 1;\n return NotificationManager;\n}();\nexport { NotificationManager };\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { isArray, isFunction, objDefine, utcNow } from \"@nevware21/ts-utils\";\nimport { _DYN_GET_CTX, _DYN_IS_CHILD_EVT, _DYN_LENGTH, _DYN_NAME, _DYN_PUSH, _DYN_SET_CTX } from \"../__DynamicConstants\";\nimport { STR_GET_PERF_MGR, STR_PERF_EVENT } from \"./InternalConstants\";\nvar strExecutionContextKey = \"ctx\";\nvar strParentContextKey = \"ParentContextKey\";\nvar strChildrenContextKey = \"ChildrenContextKey\";\nvar _defaultPerfManager = null;\nvar PerfEvent = /** @class */function () {\n function PerfEvent(name, payloadDetails, isAsync) {\n var _self = this;\n _self.start = utcNow();\n _self[_DYN_NAME /* @min:%2ename */] = name;\n _self.isAsync = isAsync;\n _self[_DYN_IS_CHILD_EVT /* @min:%2eisChildEvt */] = function () {\n return false;\n };\n if (isFunction(payloadDetails)) {\n // Create an accessor to minimize the potential performance impact of executing the payloadDetails callback\n var theDetails_1;\n objDefine(_self, \"payload\", {\n g: function () {\n // Delay the execution of the payloadDetails until needed\n if (!theDetails_1 && isFunction(payloadDetails)) {\n theDetails_1 = payloadDetails();\n // clear it out now so the referenced objects can be garbage collected\n payloadDetails = null;\n }\n return theDetails_1;\n }\n });\n }\n _self[_DYN_GET_CTX /* @min:%2egetCtx */] = function (key) {\n if (key) {\n // The parent and child links are located directly on the object (for better viewing in the DebugPlugin)\n if (key === PerfEvent[strParentContextKey] || key === PerfEvent[strChildrenContextKey]) {\n return _self[key];\n }\n return (_self[strExecutionContextKey] || {})[key];\n }\n return null;\n };\n _self[_DYN_SET_CTX /* @min:%2esetCtx */] = function (key, value) {\n if (key) {\n // Put the parent and child links directly on the object (for better viewing in the DebugPlugin)\n if (key === PerfEvent[strParentContextKey]) {\n // Simple assumption, if we are setting a parent then we must be a child\n if (!_self[key]) {\n _self[_DYN_IS_CHILD_EVT /* @min:%2eisChildEvt */] = function () {\n return true;\n };\n }\n _self[key] = value;\n } else if (key === PerfEvent[strChildrenContextKey]) {\n _self[key] = value;\n } else {\n var ctx = _self[strExecutionContextKey] = _self[strExecutionContextKey] || {};\n ctx[key] = value;\n }\n }\n };\n _self.complete = function () {\n var childTime = 0;\n var childEvts = _self[_DYN_GET_CTX /* @min:%2egetCtx */](PerfEvent[strChildrenContextKey]);\n if (isArray(childEvts)) {\n for (var lp = 0; lp < childEvts[_DYN_LENGTH /* @min:%2elength */]; lp++) {\n var childEvt = childEvts[lp];\n if (childEvt) {\n childTime += childEvt.time;\n }\n }\n }\n _self.time = utcNow() - _self.start;\n _self.exTime = _self.time - childTime;\n _self.complete = function () {};\n };\n }\n PerfEvent.ParentContextKey = \"parent\";\n PerfEvent.ChildrenContextKey = \"childEvts\";\n return PerfEvent;\n}();\nexport { PerfEvent };\nvar PerfManager = /** @class */function () {\n function PerfManager(manager) {\n /**\r\n * General bucket used for execution context set and retrieved via setCtx() and getCtx.\r\n * Defined as private so it can be visualized via the DebugPlugin\r\n */\n this.ctx = {};\n dynamicProto(PerfManager, this, function (_self) {\n _self.create = function (src, payloadDetails, isAsync) {\n // TODO (@MSNev): at some point we will want to add additional configuration to \"select\" which events to instrument\n // for now this is just a simple do everything.\n return new PerfEvent(src, payloadDetails, isAsync);\n };\n _self.fire = function (perfEvent) {\n if (perfEvent) {\n perfEvent.complete();\n if (manager && isFunction(manager[STR_PERF_EVENT /* @min:%2eperfEvent */])) {\n manager[STR_PERF_EVENT /* @min:%2eperfEvent */](perfEvent);\n }\n }\n };\n _self[_DYN_SET_CTX /* @min:%2esetCtx */] = function (key, value) {\n if (key) {\n var ctx = _self[strExecutionContextKey] = _self[strExecutionContextKey] || {};\n ctx[key] = value;\n }\n };\n _self[_DYN_GET_CTX /* @min:%2egetCtx */] = function (key) {\n return (_self[strExecutionContextKey] || {})[key];\n };\n });\n }\n // Removed Stub for PerfManager.prototype.create.\n // Removed Stub for PerfManager.prototype.fire.\n // Removed Stub for PerfManager.prototype.setCtx.\n // Removed Stub for PerfManager.prototype.getCtx.\n // This is a workaround for an IE bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n PerfManager.__ieDyn = 1;\n return PerfManager;\n}();\nexport { PerfManager };\nvar doPerfActiveKey = \"CoreUtils.doPerf\";\n/**\r\n * Helper function to wrap a function with a perf event\r\n * @param mgrSource - The Performance Manager or a Performance provider source (may be null)\r\n * @param getSource - The callback to create the source name for the event (if perf monitoring is enabled)\r\n * @param func - The function to call and measure\r\n * @param details - A function to return the payload details\r\n * @param isAsync - Is the event / function being call asynchronously or synchronously\r\n */\nexport function doPerf(mgrSource, getSource, func, details, isAsync) {\n if (mgrSource) {\n var perfMgr = mgrSource;\n if (perfMgr[STR_GET_PERF_MGR]) {\n // Looks like a perf manager provider object\n perfMgr = perfMgr[STR_GET_PERF_MGR]();\n }\n if (perfMgr) {\n var perfEvt = void 0;\n var currentActive = perfMgr[_DYN_GET_CTX /* @min:%2egetCtx */](doPerfActiveKey);\n try {\n perfEvt = perfMgr.create(getSource(), details, isAsync);\n if (perfEvt) {\n if (currentActive && perfEvt[_DYN_SET_CTX /* @min:%2esetCtx */]) {\n perfEvt[_DYN_SET_CTX /* @min:%2esetCtx */](PerfEvent[strParentContextKey], currentActive);\n if (currentActive[_DYN_GET_CTX /* @min:%2egetCtx */] && currentActive[_DYN_SET_CTX /* @min:%2esetCtx */]) {\n var children = currentActive[_DYN_GET_CTX /* @min:%2egetCtx */](PerfEvent[strChildrenContextKey]);\n if (!children) {\n children = [];\n currentActive[_DYN_SET_CTX /* @min:%2esetCtx */](PerfEvent[strChildrenContextKey], children);\n }\n children[_DYN_PUSH /* @min:%2epush */](perfEvt);\n }\n }\n // Set this event as the active event now\n perfMgr[_DYN_SET_CTX /* @min:%2esetCtx */](doPerfActiveKey, perfEvt);\n return func(perfEvt);\n }\n } catch (ex) {\n if (perfEvt && perfEvt[_DYN_SET_CTX /* @min:%2esetCtx */]) {\n perfEvt[_DYN_SET_CTX /* @min:%2esetCtx */](\"exception\", ex);\n }\n } finally {\n // fire the perf event\n if (perfEvt) {\n perfMgr.fire(perfEvt);\n }\n // Reset the active event to the previous value\n perfMgr[_DYN_SET_CTX /* @min:%2esetCtx */](doPerfActiveKey, currentActive);\n }\n }\n }\n return func();\n}\n/**\r\n * Set the global performance manager to use when there is no core instance or it has not been initialized yet.\r\n * @param perfManager - The IPerfManager instance to use when no performance manager is supplied.\r\n */\nexport function setGblPerfMgr(perfManager) {\n _defaultPerfManager = perfManager;\n}\n/**\r\n * Get the current global performance manager that will be used with no performance manager is supplied.\r\n * @returns - The current default manager\r\n */\nexport function getGblPerfMgr() {\n return _defaultPerfManager;\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n\"use strict\";\n\nimport { strShimUndefined } from \"@microsoft/applicationinsights-shims\";\nimport { strSubstr, strSubstring } from \"@nevware21/ts-utils\";\nimport { _DYN_LENGTH } from \"../__DynamicConstants\";\nimport { STR_EMPTY } from \"./InternalConstants\";\nimport { random32 } from \"./RandomHelper\";\n// Added to help with minfication\nexport var Undefined = strShimUndefined;\nexport function newGuid() {\n var uuid = generateW3CId();\n return strSubstring(uuid, 0, 8) + \"-\" + strSubstring(uuid, 8, 12) + \"-\" + strSubstring(uuid, 12, 16) + \"-\" + strSubstring(uuid, 16, 20) + \"-\" + strSubstring(uuid, 20);\n}\n/**\r\n * The strEndsWith() method determines whether a string ends with the characters of a specified string, returning true or false as appropriate.\r\n * @param value - The value to check whether it ends with the search value.\r\n * @param search - The characters to be searched for at the end of the value.\r\n * @returns true if the given search value is found at the end of the string, otherwise false.\r\n */\nexport function strEndsWith(value, search) {\n if (value && search) {\n var len = value[_DYN_LENGTH /* @min:%2elength */];\n var start = len - search[_DYN_LENGTH /* @min:%2elength */];\n return strSubstring(value, start >= 0 ? start : 0, len) === search;\n }\n return false;\n}\n/**\r\n * generate W3C trace id\r\n */\nexport function generateW3CId() {\n var hexValues = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\"];\n // rfc4122 version 4 UUID without dashes and with lowercase letters\n var oct = STR_EMPTY,\n tmp;\n for (var a = 0; a < 4; a++) {\n tmp = random32();\n oct += hexValues[tmp & 0xF] + hexValues[tmp >> 4 & 0xF] + hexValues[tmp >> 8 & 0xF] + hexValues[tmp >> 12 & 0xF] + hexValues[tmp >> 16 & 0xF] + hexValues[tmp >> 20 & 0xF] + hexValues[tmp >> 24 & 0xF] + hexValues[tmp >> 28 & 0xF];\n }\n // \"Set the two most significant bits (bits 6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively\"\n var clockSequenceHi = hexValues[8 + (random32() & 0x03) | 0];\n return strSubstr(oct, 0, 8) + strSubstr(oct, 9, 4) + \"4\" + strSubstr(oct, 13, 3) + clockSequenceHi + strSubstr(oct, 16, 3) + strSubstr(oct, 19, 12);\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nimport { arrForEach, isArray, isString, strLeft, strTrim } from \"@nevware21/ts-utils\";\nimport { _DYN_GET_ATTRIBUTE, _DYN_LENGTH, _DYN_PUSH, _DYN_SPLIT, _DYN_TO_LOWER_CASE, _DYN_TRACE_FLAGS, _DYN_VERSION } from \"../__DynamicConstants\";\nimport { generateW3CId } from \"./CoreUtils\";\nimport { findMetaTag, findNamedServerTiming } from \"./EnvUtils\";\nimport { STR_EMPTY } from \"./InternalConstants\";\n// using {0,16} for leading and trailing whitespace just to constrain the possible runtime of a random string\nvar TRACE_PARENT_REGEX = /^([\\da-f]{2})-([\\da-f]{32})-([\\da-f]{16})-([\\da-f]{2})(-[^\\s]{1,64})?$/i;\nvar DEFAULT_VERSION = \"00\";\nvar INVALID_VERSION = \"ff\";\nvar INVALID_TRACE_ID = \"00000000000000000000000000000000\";\nvar INVALID_SPAN_ID = \"0000000000000000\";\nvar SAMPLED_FLAG = 0x01;\nfunction _isValid(value, len, invalidValue) {\n if (value && value[_DYN_LENGTH /* @min:%2elength */] === len && value !== invalidValue) {\n return !!value.match(/^[\\da-f]*$/i);\n }\n return false;\n}\nfunction _formatValue(value, len, defValue) {\n if (_isValid(value, len)) {\n return value;\n }\n return defValue;\n}\nfunction _formatFlags(value) {\n if (isNaN(value) || value < 0 || value > 255) {\n value = 0x01;\n }\n var result = value.toString(16);\n while (result[_DYN_LENGTH /* @min:%2elength */] < 2) {\n result = \"0\" + result;\n }\n return result;\n}\n/**\r\n * Create a new ITraceParent instance using the provided values.\r\n * @param traceId - The traceId to use, when invalid a new random W3C id will be generated.\r\n * @param spanId - The parent/span id to use, a new random value will be generated if it is invalid.\r\n * @param flags - The traceFlags to use, defaults to zero (0) if not supplied or invalid\r\n * @param version - The version to used, defaults to version \"01\" if not supplied or invalid.\r\n * @returns\r\n */\nexport function createTraceParent(traceId, spanId, flags, version) {\n return {\n version: _isValid(version, 2, INVALID_VERSION) ? version : DEFAULT_VERSION,\n traceId: isValidTraceId(traceId) ? traceId : generateW3CId(),\n spanId: isValidSpanId(spanId) ? spanId : strLeft(generateW3CId(), 16),\n traceFlags: flags >= 0 && flags <= 0xFF ? flags : 1\n };\n}\n/**\r\n * Attempt to parse the provided string as a W3C TraceParent header value (https://www.w3.org/TR/trace-context/#traceparent-header)\r\n *\r\n * @param value - The value to be parsed\r\n * @param selectIdx - If the found value is comma separated which is the preferred entry to select, defaults to the first\r\n * @returns\r\n */\nexport function parseTraceParent(value, selectIdx) {\n if (!value) {\n // Don't pass a null/undefined or empty string\n return null;\n }\n if (isArray(value)) {\n // The value may have been encoded on the page into an array so handle this automatically\n value = value[0] || \"\";\n }\n if (!value || !isString(value) || value[_DYN_LENGTH /* @min:%2elength */] > 8192) {\n // limit potential processing based on total length\n return null;\n }\n if (value.indexOf(\",\") !== -1) {\n var values = value[_DYN_SPLIT /* @min:%2esplit */](\",\");\n value = values[selectIdx > 0 && values[_DYN_LENGTH /* @min:%2elength */] > selectIdx ? selectIdx : 0];\n }\n // See https://www.w3.org/TR/trace-context/#versioning-of-traceparent\n var match = TRACE_PARENT_REGEX.exec(strTrim(value));\n if (!match ||\n // No match\n match[1] === INVALID_VERSION ||\n // version ff is forbidden\n match[2] === INVALID_TRACE_ID ||\n // All zeros is considered to be invalid\n match[3] === INVALID_SPAN_ID) {\n // All zeros is considered to be invalid\n return null;\n }\n return {\n version: (match[1] || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */](),\n traceId: (match[2] || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */](),\n spanId: (match[3] || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */](),\n traceFlags: parseInt(match[4], 16)\n };\n}\n/**\r\n * Is the provided W3c Trace Id a valid string representation, it must be a 32-character string\r\n * of lowercase hexadecimal characters for example, 4bf92f3577b34da6a3ce929d0e0e4736.\r\n * If all characters as zero (00000000000000000000000000000000) it will be considered an invalid value.\r\n * @param value - The W3c trace Id to be validated\r\n * @returns true if valid otherwise false\r\n */\nexport function isValidTraceId(value) {\n return _isValid(value, 32, INVALID_TRACE_ID);\n}\n/**\r\n * Is the provided W3c span id (aka. parent id) a valid string representation, it must be a 16-character\r\n * string of lowercase hexadecimal characters, for example, 00f067aa0ba902b7.\r\n * If all characters are zero (0000000000000000) this is considered an invalid value.\r\n * @param value - The W3c span id to be validated\r\n * @returns true if valid otherwise false\r\n */\nexport function isValidSpanId(value) {\n return _isValid(value, 16, INVALID_SPAN_ID);\n}\n/**\r\n * Validates that the provided ITraceParent instance conforms to the currently supported specifications\r\n * @param value - The parsed traceParent value\r\n * @returns\r\n */\nexport function isValidTraceParent(value) {\n if (!value || !_isValid(value[_DYN_VERSION /* @min:%2eversion */], 2, INVALID_VERSION) || !_isValid(value.traceId, 32, INVALID_TRACE_ID) || !_isValid(value.spanId, 16, INVALID_SPAN_ID) || !_isValid(_formatFlags(value[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */]), 2)) {\n // Each known field must contain a valid value\n return false;\n }\n return true;\n}\n/**\r\n * Is the parsed traceParent indicating that the trace is currently sampled.\r\n * @param value - The parsed traceParent value\r\n * @returns\r\n */\nexport function isSampledFlag(value) {\n if (isValidTraceParent(value)) {\n return (value[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] & SAMPLED_FLAG) === SAMPLED_FLAG;\n }\n return false;\n}\n/**\r\n * Format the ITraceParent value as a string using the supported and know version formats.\r\n * So even if the passed traceParent is a later version the string value returned from this\r\n * function will convert it to only the known version formats.\r\n * This currently only supports version \"00\" and invalid \"ff\"\r\n * @param value - The parsed traceParent value\r\n * @returns\r\n */\nexport function formatTraceParent(value) {\n if (value) {\n // Special Note: This only supports formatting as version 00, future versions should encode any known supported version\n // So parsing a future version will populate the correct version value but reformatting will reduce it to version 00.\n var flags = _formatFlags(value[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */]);\n if (!_isValid(flags, 2)) {\n flags = \"01\";\n }\n var version = value[_DYN_VERSION /* @min:%2eversion */] || DEFAULT_VERSION;\n if (version !== \"00\" && version !== \"ff\") {\n // Reduce version to \"00\"\n version = DEFAULT_VERSION;\n }\n // Format as version 00\n return \"\".concat(version.toLowerCase(), \"-\").concat(_formatValue(value.traceId, 32, INVALID_TRACE_ID).toLowerCase(), \"-\").concat(_formatValue(value.spanId, 16, INVALID_SPAN_ID).toLowerCase(), \"-\").concat(flags.toLowerCase());\n }\n return \"\";\n}\n/**\r\n * Helper function to fetch the passed traceparent from the page, looking for it as a meta-tag or a Server-Timing header.\r\n * @param selectIdx - If the found value is comma separated which is the preferred entry to select, defaults to the first\r\n * @returns\r\n */\nexport function findW3cTraceParent(selectIdx) {\n var name = \"traceparent\";\n var traceParent = parseTraceParent(findMetaTag(name), selectIdx);\n if (!traceParent) {\n traceParent = parseTraceParent(findNamedServerTiming(name), selectIdx);\n }\n return traceParent;\n}\n/**\r\n * Find all script tags in the provided document and return the information about them.\r\n * @param doc - The document to search for script tags\r\n * @returns\r\n */\nexport function findAllScripts(doc) {\n var scripts = doc.getElementsByTagName(\"script\");\n var result = [];\n arrForEach(scripts, function (script) {\n var src = script[_DYN_GET_ATTRIBUTE /* @min:%2egetAttribute */](\"src\");\n if (src) {\n var crossOrigin = script[_DYN_GET_ATTRIBUTE /* @min:%2egetAttribute */](\"crossorigin\");\n var async = script.hasAttribute(\"async\") === true;\n var defer = script.hasAttribute(\"defer\") === true;\n var referrerPolicy = script[_DYN_GET_ATTRIBUTE /* @min:%2egetAttribute */](\"referrerpolicy\");\n var info = {\n url: src\n };\n if (crossOrigin) {\n info.crossOrigin = crossOrigin;\n }\n if (async) {\n info.async = async;\n }\n if (defer) {\n info.defer = defer;\n }\n if (referrerPolicy) {\n info.referrerPolicy = referrerPolicy;\n }\n result[_DYN_PUSH /* @min:%2epush */](info);\n }\n });\n return result;\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n\"use strict\";\n\nimport { arrForEach, isFunction } from \"@nevware21/ts-utils\";\nimport { _DYN_GET_NEXT, _DYN_GET_PLUGIN, _DYN_INITIALIZE, _DYN_IS_INITIALIZED, _DYN_LENGTH, _DYN_NAME, _DYN_PUSH, _DYN_SET_NEXT_PLUGIN, _DYN_TEARDOWN, _DYN_TRACE_FLAGS, _DYN__DO_TEARDOWN } from \"../__DynamicConstants\";\nimport { createElmNodeData } from \"./DataCacheHelper\";\nimport { STR_CORE, STR_PRIORITY, STR_PROCESS_TELEMETRY } from \"./InternalConstants\";\nimport { isValidSpanId, isValidTraceId } from \"./W3cTraceParent\";\nvar pluginStateData = createElmNodeData(\"plugin\");\nexport function _getPluginState(plugin) {\n return pluginStateData.get(plugin, \"state\", {}, true);\n}\n/**\r\n * Initialize the queue of plugins\r\n * @param plugins - The array of plugins to initialize and setting of the next plugin\r\n * @param config - The current config for the instance\r\n * @param core - THe current core instance\r\n * @param extensions - The extensions\r\n */\nexport function initializePlugins(processContext, extensions) {\n // Set the next plugin and identified the uninitialized plugins\n var initPlugins = [];\n var lastPlugin = null;\n var proxy = processContext[_DYN_GET_NEXT /* @min:%2egetNext */]();\n var pluginState;\n while (proxy) {\n var thePlugin = proxy[_DYN_GET_PLUGIN /* @min:%2egetPlugin */]();\n if (thePlugin) {\n if (lastPlugin && lastPlugin[_DYN_SET_NEXT_PLUGIN /* @min:%2esetNextPlugin */] && thePlugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */]) {\n // Set this plugin as the next for the previous one\n lastPlugin[_DYN_SET_NEXT_PLUGIN /* @min:%2esetNextPlugin */](thePlugin);\n }\n pluginState = _getPluginState(thePlugin);\n var isInitialized = !!pluginState[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */];\n if (thePlugin[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */]) {\n isInitialized = thePlugin[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */]();\n }\n if (!isInitialized) {\n initPlugins[_DYN_PUSH /* @min:%2epush */](thePlugin);\n }\n lastPlugin = thePlugin;\n proxy = proxy[_DYN_GET_NEXT /* @min:%2egetNext */]();\n }\n }\n // Now initialize the plugins\n arrForEach(initPlugins, function (thePlugin) {\n var core = processContext[STR_CORE /* @min:%2ecore */]();\n thePlugin[_DYN_INITIALIZE /* @min:%2einitialize */](processContext.getCfg(), core, extensions, processContext[_DYN_GET_NEXT /* @min:%2egetNext */]());\n pluginState = _getPluginState(thePlugin);\n // Only add the core to the state if the plugin didn't set it (doesn't extend from BaseTelemetryPlugin)\n if (!thePlugin[STR_CORE] && !pluginState[STR_CORE]) {\n pluginState[STR_CORE] = core;\n }\n pluginState[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */] = true;\n delete pluginState[_DYN_TEARDOWN /* @min:%2eteardown */];\n });\n}\nexport function sortPlugins(plugins) {\n // Sort by priority\n return plugins.sort(function (extA, extB) {\n var result = 0;\n if (extB) {\n var bHasProcess = extB[STR_PROCESS_TELEMETRY];\n if (extA[STR_PROCESS_TELEMETRY]) {\n result = bHasProcess ? extA[STR_PRIORITY] - extB[STR_PRIORITY] : 1;\n } else if (bHasProcess) {\n result = -1;\n }\n } else {\n result = extA ? 1 : -1;\n }\n return result;\n });\n // sort complete\n}\n/**\r\n * Teardown / Unload helper to perform teardown/unloading operations for the provided components synchronously or asynchronously, this will call any\r\n * _doTeardown() or _doUnload() functions on the provided components to allow them to finish removal.\r\n * @param components - The components you want to unload\r\n * @param unloadCtx - This is the context that should be used during unloading.\r\n * @param unloadState - The details / state of the unload process, it holds details like whether it should be unloaded synchronously or asynchronously and the reason for the unload.\r\n * @param asyncCallback - An optional callback that the plugin must call if it returns true to inform the caller that it has completed any async unload/teardown operations.\r\n * @returns boolean - true if the plugin has or will call asyncCallback, this allows the plugin to perform any asynchronous operations.\r\n */\nexport function unloadComponents(components, unloadCtx, unloadState, asyncCallback) {\n var idx = 0;\n function _doUnload() {\n while (idx < components[_DYN_LENGTH /* @min:%2elength */]) {\n var component = components[idx++];\n if (component) {\n var func = component._doUnload || component[_DYN__DO_TEARDOWN /* @min:%2e_doTeardown */];\n if (isFunction(func)) {\n if (func.call(component, unloadCtx, unloadState, _doUnload) === true) {\n return true;\n }\n }\n }\n }\n }\n return _doUnload();\n}\n/**\r\n * Creates a IDistributedTraceContext which optionally also \"sets\" the value on a parent\r\n * @param parentCtx - An optional parent distributed trace instance\r\n * @returns A new IDistributedTraceContext instance that uses an internal temporary object\r\n */\nexport function createDistributedTraceContext(parentCtx) {\n var trace = {};\n return {\n getName: function () {\n return trace[_DYN_NAME /* @min:%2ename */];\n },\n setName: function (newValue) {\n parentCtx && parentCtx.setName(newValue);\n trace[_DYN_NAME /* @min:%2ename */] = newValue;\n },\n getTraceId: function () {\n return trace.traceId;\n },\n setTraceId: function (newValue) {\n parentCtx && parentCtx.setTraceId(newValue);\n if (isValidTraceId(newValue)) {\n trace.traceId = newValue;\n }\n },\n getSpanId: function () {\n return trace.spanId;\n },\n setSpanId: function (newValue) {\n parentCtx && parentCtx.setSpanId(newValue);\n if (isValidSpanId(newValue)) {\n trace.spanId = newValue;\n }\n },\n getTraceFlags: function () {\n return trace[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */];\n },\n setTraceFlags: function (newTraceFlags) {\n parentCtx && parentCtx.setTraceFlags(newTraceFlags);\n trace[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = newTraceFlags;\n }\n };\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n\"use strict\";\n\nimport { arrForEach, dumpObj, isArray, isFunction, isNullOrUndefined, isUndefined, objForEachKey, objFreeze, objKeys } from \"@nevware21/ts-utils\";\nimport { _applyDefaultValue } from \"../Config/ConfigDefaults\";\nimport { createDynamicConfig } from \"../Config/DynamicConfig\";\nimport { _DYN_CREATE_NEW, _DYN_DIAG_LOG, _DYN_GET_NEXT, _DYN_GET_PLUGIN, _DYN_IDENTIFIER, _DYN_IS_INITIALIZED, _DYN_LENGTH, _DYN_LOGGER, _DYN_PROCESS_NEXT, _DYN_PUSH, _DYN_SET_NEXT_PLUGIN, _DYN_TEARDOWN, _DYN_UNLOAD, _DYN_UPDATE } from \"../__DynamicConstants\";\nimport { _throwInternal, safeGetLogger } from \"./DiagnosticLogger\";\nimport { proxyFunctions } from \"./HelperFuncs\";\nimport { STR_CORE, STR_DISABLED, STR_EMPTY, STR_EXTENSION_CONFIG, STR_PRIORITY, STR_PROCESS_TELEMETRY } from \"./InternalConstants\";\nimport { doPerf } from \"./PerfManager\";\nimport { _getPluginState } from \"./TelemetryHelpers\";\nvar strTelemetryPluginChain = \"TelemetryPluginChain\";\nvar strHasRunFlags = \"_hasRun\";\nvar strGetTelCtx = \"_getTelCtx\";\nvar _chainId = 0;\nfunction _getNextProxyStart(proxy, core, startAt) {\n while (proxy) {\n if (proxy[_DYN_GET_PLUGIN /* @min:%2egetPlugin */]() === startAt) {\n return proxy;\n }\n proxy = proxy[_DYN_GET_NEXT /* @min:%2egetNext */]();\n }\n // This wasn't found in the existing chain so create an isolated one with just this plugin\n return createTelemetryProxyChain([startAt], core.config || {}, core);\n}\n/**\r\n * @ignore\r\n * @param telemetryChain\r\n * @param dynamicHandler\r\n * @param core\r\n * @param startAt - Identifies the next plugin to execute, if null there is no \"next\" plugin and if undefined it should assume the start of the chain\r\n * @returns\r\n */\nfunction _createInternalContext(telemetryChain, dynamicHandler, core, startAt) {\n // We have a special case where we want to start execution from this specific plugin\n // or we simply reuse the existing telemetry plugin chain (normal execution case)\n var _nextProxy = null; // By Default set as no next plugin\n var _onComplete = [];\n if (!dynamicHandler) {\n dynamicHandler = createDynamicConfig({}, null, core[_DYN_LOGGER /* @min:%2elogger */]);\n }\n if (startAt !== null) {\n // There is no next element (null) vs not defined (undefined) so use the full chain\n _nextProxy = startAt ? _getNextProxyStart(telemetryChain, core, startAt) : telemetryChain;\n }\n var context = {\n _next: _moveNext,\n ctx: {\n core: function () {\n return core;\n },\n diagLog: function () {\n return safeGetLogger(core, dynamicHandler.cfg);\n },\n getCfg: function () {\n return dynamicHandler.cfg;\n },\n getExtCfg: _resolveExtCfg,\n getConfig: _getConfig,\n hasNext: function () {\n return !!_nextProxy;\n },\n getNext: function () {\n return _nextProxy;\n },\n setNext: function (nextPlugin) {\n _nextProxy = nextPlugin;\n },\n iterate: _iterateChain,\n onComplete: _addOnComplete\n }\n };\n function _addOnComplete(onComplete, that) {\n var args = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n args[_i - 2] = arguments[_i];\n }\n if (onComplete) {\n _onComplete[_DYN_PUSH /* @min:%2epush */]({\n func: onComplete,\n self: !isUndefined(that) ? that : context.ctx,\n args: args\n });\n }\n }\n function _moveNext() {\n var nextProxy = _nextProxy;\n // Automatically move to the next plugin\n _nextProxy = nextProxy ? nextProxy[_DYN_GET_NEXT /* @min:%2egetNext */]() : null;\n if (!nextProxy) {\n var onComplete = _onComplete;\n if (onComplete && onComplete[_DYN_LENGTH /* @min:%2elength */] > 0) {\n arrForEach(onComplete, function (completeDetails) {\n try {\n completeDetails.func.call(completeDetails.self, completeDetails.args);\n } catch (e) {\n _throwInternal(core[_DYN_LOGGER /* @min:%2elogger */], 2 /* eLoggingSeverity.WARNING */, 73 /* _eInternalMessageId.PluginException */, \"Unexpected Exception during onComplete - \" + dumpObj(e));\n }\n });\n _onComplete = [];\n }\n }\n return nextProxy;\n }\n function _getExtCfg(identifier, createIfMissing) {\n var idCfg = null;\n var cfg = dynamicHandler.cfg;\n if (cfg && identifier) {\n var extCfg = cfg[STR_EXTENSION_CONFIG /* @min:%2eextensionConfig */];\n if (!extCfg && createIfMissing) {\n extCfg = {};\n }\n // Always set the value so that the property always exists\n cfg[STR_EXTENSION_CONFIG] = extCfg; // Note: it is valid for the \"value\" to be undefined\n // Calling `ref()` has a side effect of causing the referenced property to become dynamic (if not already)\n extCfg = dynamicHandler.ref(cfg, STR_EXTENSION_CONFIG);\n if (extCfg) {\n idCfg = extCfg[identifier];\n if (!idCfg && createIfMissing) {\n idCfg = {};\n }\n // Always set the value so that the property always exists\n extCfg[identifier] = idCfg; // Note: it is valid for the \"value\" to be undefined\n // Calling `ref()` has a side effect of causing the referenced property to become dynamic (if not already)\n idCfg = dynamicHandler.ref(extCfg, identifier);\n }\n }\n return idCfg;\n }\n function _resolveExtCfg(identifier, defaultValues) {\n var newConfig = _getExtCfg(identifier, true);\n if (defaultValues) {\n // Enumerate over the defaultValues and if not already populated attempt to\n // find a value from the root config or use the default value\n objForEachKey(defaultValues, function (field, defaultValue) {\n // for each unspecified field, set the default value\n if (isNullOrUndefined(newConfig[field])) {\n var cfgValue = dynamicHandler.cfg[field];\n if (cfgValue || !isNullOrUndefined(cfgValue)) {\n newConfig[field] = cfgValue;\n }\n }\n _applyDefaultValue(dynamicHandler, newConfig, field, defaultValue);\n });\n }\n return dynamicHandler.setDf(newConfig, defaultValues);\n }\n function _getConfig(identifier, field, defaultValue) {\n if (defaultValue === void 0) {\n defaultValue = false;\n }\n var theValue;\n var extConfig = _getExtCfg(identifier, false);\n var rootConfig = dynamicHandler.cfg;\n if (extConfig && (extConfig[field] || !isNullOrUndefined(extConfig[field]))) {\n theValue = extConfig[field];\n } else if (rootConfig[field] || !isNullOrUndefined(rootConfig[field])) {\n theValue = rootConfig[field];\n }\n return theValue || !isNullOrUndefined(theValue) ? theValue : defaultValue;\n }\n function _iterateChain(cb) {\n // Keep processing until we reach the end of the chain\n var nextPlugin;\n while (!!(nextPlugin = context._next())) {\n var plugin = nextPlugin[_DYN_GET_PLUGIN /* @min:%2egetPlugin */]();\n if (plugin) {\n // callback with the current on\n cb(plugin);\n }\n }\n }\n return context;\n}\n/**\r\n * Creates a new Telemetry Item context with the current config, core and plugin execution chain\r\n * @param plugins - The plugin instances that will be executed\r\n * @param config - The current config\r\n * @param core - The current core instance\r\n * @param startAt - Identifies the next plugin to execute, if null there is no \"next\" plugin and if undefined it should assume the start of the chain\r\n */\nexport function createProcessTelemetryContext(telemetryChain, cfg, core, startAt) {\n var config = createDynamicConfig(cfg);\n var internalContext = _createInternalContext(telemetryChain, config, core, startAt);\n var context = internalContext.ctx;\n function _processNext(env) {\n var nextPlugin = internalContext._next();\n if (nextPlugin) {\n // Run the next plugin which will call \"processNext()\"\n nextPlugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */](env, context);\n }\n return !nextPlugin;\n }\n function _createNew(plugins, startAt) {\n if (plugins === void 0) {\n plugins = null;\n }\n if (isArray(plugins)) {\n plugins = createTelemetryProxyChain(plugins, config.cfg, core, startAt);\n }\n return createProcessTelemetryContext(plugins || context[_DYN_GET_NEXT /* @min:%2egetNext */](), config.cfg, core, startAt);\n }\n context[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */] = _processNext;\n context[_DYN_CREATE_NEW /* @min:%2ecreateNew */] = _createNew;\n return context;\n}\n/**\r\n * Creates a new Telemetry Item context with the current config, core and plugin execution chain for handling the unloading of the chain\r\n * @param plugins - The plugin instances that will be executed\r\n * @param config - The current config\r\n * @param core - The current core instance\r\n * @param startAt - Identifies the next plugin to execute, if null there is no \"next\" plugin and if undefined it should assume the start of the chain\r\n */\nexport function createProcessTelemetryUnloadContext(telemetryChain, core, startAt) {\n var config = createDynamicConfig(core.config);\n var internalContext = _createInternalContext(telemetryChain, config, core, startAt);\n var context = internalContext.ctx;\n function _processNext(unloadState) {\n var nextPlugin = internalContext._next();\n nextPlugin && nextPlugin[_DYN_UNLOAD /* @min:%2eunload */](context, unloadState);\n return !nextPlugin;\n }\n function _createNew(plugins, startAt) {\n if (plugins === void 0) {\n plugins = null;\n }\n if (isArray(plugins)) {\n plugins = createTelemetryProxyChain(plugins, config.cfg, core, startAt);\n }\n return createProcessTelemetryUnloadContext(plugins || context[_DYN_GET_NEXT /* @min:%2egetNext */](), core, startAt);\n }\n context[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */] = _processNext;\n context[_DYN_CREATE_NEW /* @min:%2ecreateNew */] = _createNew;\n return context;\n}\n/**\r\n * Creates a new Telemetry Item context with the current config, core and plugin execution chain for updating the configuration\r\n * @param plugins - The plugin instances that will be executed\r\n * @param config - The current config\r\n * @param core - The current core instance\r\n * @param startAt - Identifies the next plugin to execute, if null there is no \"next\" plugin and if undefined it should assume the start of the chain\r\n */\nexport function createProcessTelemetryUpdateContext(telemetryChain, core, startAt) {\n var config = createDynamicConfig(core.config);\n var internalContext = _createInternalContext(telemetryChain, config, core, startAt);\n var context = internalContext.ctx;\n function _processNext(updateState) {\n return context.iterate(function (plugin) {\n if (isFunction(plugin[_DYN_UPDATE /* @min:%2eupdate */])) {\n plugin[_DYN_UPDATE /* @min:%2eupdate */](context, updateState);\n }\n });\n }\n function _createNew(plugins, startAt) {\n if (plugins === void 0) {\n plugins = null;\n }\n if (isArray(plugins)) {\n plugins = createTelemetryProxyChain(plugins, config.cfg, core, startAt);\n }\n return createProcessTelemetryUpdateContext(plugins || context[_DYN_GET_NEXT /* @min:%2egetNext */](), core, startAt);\n }\n context[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */] = _processNext;\n context[_DYN_CREATE_NEW /* @min:%2ecreateNew */] = _createNew;\n return context;\n}\n/**\r\n * Creates an execution chain from the array of plugins\r\n * @param plugins - The array of plugins that will be executed in this order\r\n * @param defItemCtx - The default execution context to use when no telemetry context is passed to processTelemetry(), this\r\n * should be for legacy plugins only. Currently, only used for passing the current core instance and to provide better error\r\n * reporting (hasRun) when errors occur.\r\n */\nexport function createTelemetryProxyChain(plugins, config, core, startAt) {\n var firstProxy = null;\n var add = startAt ? false : true;\n if (isArray(plugins) && plugins[_DYN_LENGTH /* @min:%2elength */] > 0) {\n // Create the proxies and wire up the next plugin chain\n var lastProxy_1 = null;\n arrForEach(plugins, function (thePlugin) {\n if (!add && startAt === thePlugin) {\n add = true;\n }\n if (add && thePlugin && isFunction(thePlugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */])) {\n // Only add plugins that are processors\n var newProxy = createTelemetryPluginProxy(thePlugin, config, core);\n if (!firstProxy) {\n firstProxy = newProxy;\n }\n if (lastProxy_1) {\n // Set this new proxy as the next for the previous one\n lastProxy_1._setNext(newProxy);\n }\n lastProxy_1 = newProxy;\n }\n });\n }\n if (startAt && !firstProxy) {\n // Special case where the \"startAt\" was not in the original list of plugins\n return createTelemetryProxyChain([startAt], config, core);\n }\n return firstProxy;\n}\n/**\r\n * Create the processing telemetry proxy instance, the proxy is used to abstract the current plugin to allow monitoring and\r\n * execution plugins while passing around the dynamic execution state (IProcessTelemetryContext), the proxy instance no longer\r\n * contains any execution state and can be reused between requests (this was not the case for 2.7.2 and earlier with the\r\n * TelemetryPluginChain class).\r\n * @param plugin - The plugin instance to proxy\r\n * @param config - The default execution context to use when no telemetry context is passed to processTelemetry(), this\r\n * should be for legacy plugins only. Currently, only used for passing the current core instance and to provide better error\r\n * reporting (hasRun) when errors occur.\r\n * @returns\r\n */\nexport function createTelemetryPluginProxy(plugin, config, core) {\n var nextProxy = null;\n var hasProcessTelemetry = isFunction(plugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */]);\n var hasSetNext = isFunction(plugin[_DYN_SET_NEXT_PLUGIN /* @min:%2esetNextPlugin */]);\n var chainId;\n if (plugin) {\n chainId = plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */] + \"-\" + plugin[STR_PRIORITY /* @min:%2epriority */] + \"-\" + _chainId++;\n } else {\n chainId = \"Unknown-0-\" + _chainId++;\n }\n var proxyChain = {\n getPlugin: function () {\n return plugin;\n },\n getNext: function () {\n return nextProxy;\n },\n processTelemetry: _processTelemetry,\n unload: _unloadPlugin,\n update: _updatePlugin,\n _id: chainId,\n _setNext: function (nextPlugin) {\n nextProxy = nextPlugin;\n }\n };\n function _getTelCtx() {\n var itemCtx;\n // Looks like a plugin didn't pass the (optional) context, so create a new one\n if (plugin && isFunction(plugin[strGetTelCtx])) {\n // This plugin extends from the BaseTelemetryPlugin so lets use it\n itemCtx = plugin[strGetTelCtx]();\n }\n if (!itemCtx) {\n // Create a temporary one\n itemCtx = createProcessTelemetryContext(proxyChain, config, core);\n }\n return itemCtx;\n }\n function _processChain(itemCtx, processPluginFn, name, details, isAsync) {\n var hasRun = false;\n var identifier = plugin ? plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */] : strTelemetryPluginChain;\n var hasRunContext = itemCtx[strHasRunFlags];\n if (!hasRunContext) {\n // Assign and populate\n hasRunContext = itemCtx[strHasRunFlags] = {};\n }\n // Ensure that we keep the context in sync\n itemCtx.setNext(nextProxy);\n if (plugin) {\n doPerf(itemCtx[STR_CORE /* @min:%2ecore */](), function () {\n return identifier + \":\" + name;\n }, function () {\n // Mark this component as having run\n hasRunContext[chainId] = true;\n try {\n // Set a flag on the next plugin so we know if it was attempted to be executed\n var nextId = nextProxy ? nextProxy._id : STR_EMPTY;\n if (nextId) {\n hasRunContext[nextId] = false;\n }\n hasRun = processPluginFn(itemCtx);\n } catch (error) {\n var hasNextRun = nextProxy ? hasRunContext[nextProxy._id] : true;\n if (hasNextRun) {\n // The next plugin after us has already run so set this one as complete\n hasRun = true;\n }\n if (!nextProxy || !hasNextRun) {\n // Either we have no next plugin or the current one did not attempt to call the next plugin\n // Which means the current one is the root of the failure so log/report this failure\n _throwInternal(itemCtx[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 73 /* _eInternalMessageId.PluginException */, \"Plugin [\" + identifier + \"] failed during \" + name + \" - \" + dumpObj(error) + \", run flags: \" + dumpObj(hasRunContext));\n }\n }\n }, details, isAsync);\n }\n return hasRun;\n }\n function _processTelemetry(env, itemCtx) {\n itemCtx = itemCtx || _getTelCtx();\n function _callProcessTelemetry(itemCtx) {\n if (!plugin || !hasProcessTelemetry) {\n return false;\n }\n var pluginState = _getPluginState(plugin);\n if (pluginState[_DYN_TEARDOWN /* @min:%2eteardown */] || pluginState[STR_DISABLED]) {\n return false;\n }\n // Ensure that we keep the context in sync (for processNext()), just in case a plugin\n // doesn't calls processTelemetry() instead of itemContext.processNext() or some\n // other form of error occurred\n if (hasSetNext) {\n // Backward compatibility setting the next plugin on the instance\n plugin[_DYN_SET_NEXT_PLUGIN /* @min:%2esetNextPlugin */](nextProxy);\n }\n plugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */](env, itemCtx);\n // Process Telemetry is expected to call itemCtx.processNext() or nextPlugin.processTelemetry()\n return true;\n }\n if (!_processChain(itemCtx, _callProcessTelemetry, \"processTelemetry\", function () {\n return {\n item: env\n };\n }, !env.sync)) {\n // The underlying plugin is either not defined, not enabled or does not have a processTelemetry implementation\n // so we still want the next plugin to be executed.\n itemCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](env);\n }\n }\n function _unloadPlugin(unloadCtx, unloadState) {\n function _callTeardown() {\n // Setting default of hasRun as false so the proxyProcessFn() is called as teardown() doesn't have to exist or call unloadNext().\n var hasRun = false;\n if (plugin) {\n var pluginState = _getPluginState(plugin);\n var pluginCore = plugin[STR_CORE] || pluginState[STR_CORE /* @min:%2ecore */];\n // Only teardown the plugin if it was initialized by the current core (i.e. It's not a shared plugin)\n if (plugin && (!pluginCore || pluginCore === unloadCtx.core()) && !pluginState[_DYN_TEARDOWN /* @min:%2eteardown */]) {\n // Handle plugins that don't extend from the BaseTelemetryPlugin\n pluginState[STR_CORE /* @min:%2ecore */] = null;\n pluginState[_DYN_TEARDOWN /* @min:%2eteardown */] = true;\n pluginState[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */] = false;\n if (plugin[_DYN_TEARDOWN /* @min:%2eteardown */] && plugin[_DYN_TEARDOWN /* @min:%2eteardown */](unloadCtx, unloadState) === true) {\n // plugin told us that it was going to (or has) call unloadCtx.processNext()\n hasRun = true;\n }\n }\n }\n return hasRun;\n }\n if (!_processChain(unloadCtx, _callTeardown, \"unload\", function () {}, unloadState.isAsync)) {\n // Only called if we hasRun was not true\n unloadCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](unloadState);\n }\n }\n function _updatePlugin(updateCtx, updateState) {\n function _callUpdate() {\n // Setting default of hasRun as false so the proxyProcessFn() is called as teardown() doesn't have to exist or call unloadNext().\n var hasRun = false;\n if (plugin) {\n var pluginState = _getPluginState(plugin);\n var pluginCore = plugin[STR_CORE] || pluginState[STR_CORE /* @min:%2ecore */];\n // Only update the plugin if it was initialized by the current core (i.e. It's not a shared plugin)\n if (plugin && (!pluginCore || pluginCore === updateCtx.core()) && !pluginState[_DYN_TEARDOWN /* @min:%2eteardown */]) {\n if (plugin[_DYN_UPDATE /* @min:%2eupdate */] && plugin[_DYN_UPDATE /* @min:%2eupdate */](updateCtx, updateState) === true) {\n // plugin told us that it was going to (or has) call unloadCtx.processNext()\n hasRun = true;\n }\n }\n }\n return hasRun;\n }\n if (!_processChain(updateCtx, _callUpdate, \"update\", function () {}, false)) {\n // Only called if we hasRun was not true\n updateCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](updateState);\n }\n }\n return objFreeze(proxyChain);\n}\n/**\r\n * This class will be removed!\r\n * @deprecated use createProcessTelemetryContext() instead\r\n */\nvar ProcessTelemetryContext = /** @class */function () {\n /**\r\n * Creates a new Telemetry Item context with the current config, core and plugin execution chain\r\n * @param plugins - The plugin instances that will be executed\r\n * @param config - The current config\r\n * @param core - The current core instance\r\n */\n function ProcessTelemetryContext(pluginChain, config, core, startAt) {\n var _self = this;\n var context = createProcessTelemetryContext(pluginChain, config, core, startAt);\n // Proxy all functions of the context to this object\n proxyFunctions(_self, context, objKeys(context));\n }\n return ProcessTelemetryContext;\n}();\nexport { ProcessTelemetryContext };\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { arrForEach, dumpObj } from \"@nevware21/ts-utils\";\nimport { _DYN_DIAG_LOG, _DYN_PUSH } from \"../__DynamicConstants\";\nimport { _throwInternal } from \"./DiagnosticLogger\";\nexport function createUnloadHandlerContainer() {\n var handlers = [];\n function _addHandler(handler) {\n if (handler) {\n handlers[_DYN_PUSH /* @min:%2epush */](handler);\n }\n }\n function _runHandlers(unloadCtx, unloadState) {\n arrForEach(handlers, function (handler) {\n try {\n handler(unloadCtx, unloadState);\n } catch (e) {\n _throwInternal(unloadCtx[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 73 /* _eInternalMessageId.PluginException */, \"Unexpected error calling unload handler - \" + dumpObj(e));\n }\n });\n handlers = [];\n }\n return {\n add: _addHandler,\n run: _runHandlers\n };\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { arrAppend, arrForEach, dumpObj } from \"@nevware21/ts-utils\";\nimport { _DYN_LENGTH } from \"../__DynamicConstants\";\nimport { _throwInternal } from \"./DiagnosticLogger\";\nvar _maxHooks;\nvar _hookAddMonitor;\n/**\r\n * Test hook for setting the maximum number of unload hooks and calling a monitor function when the hooks are added or removed\r\n * This allows for automatic test failure when the maximum number of unload hooks is exceeded\r\n * @param maxHooks - The maximum number of unload hooks\r\n * @param addMonitor - The monitor function to call when hooks are added or removed\r\n */\nexport function _testHookMaxUnloadHooksCb(maxHooks, addMonitor) {\n _maxHooks = maxHooks;\n _hookAddMonitor = addMonitor;\n}\n/**\r\n * Create a IUnloadHookContainer which can be used to remember unload hook functions to be executed during the component unloading\r\n * process.\r\n * @returns A new IUnloadHookContainer instance\r\n */\nexport function createUnloadHookContainer() {\n var _hooks = [];\n function _doUnload(logger) {\n var oldHooks = _hooks;\n _hooks = [];\n // Remove all registered unload hooks\n arrForEach(oldHooks, function (fn) {\n // allow either rm or remove callback function\n try {\n (fn.rm || fn.remove).call(fn);\n } catch (e) {\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 73 /* _eInternalMessageId.PluginException */, \"Unloading:\" + dumpObj(e));\n }\n });\n if (_maxHooks && oldHooks[_DYN_LENGTH /* @min:%2elength */] > _maxHooks) {\n _hookAddMonitor ? _hookAddMonitor(\"doUnload\", oldHooks) : _throwInternal(null, 1 /* eLoggingSeverity.CRITICAL */, 48 /* _eInternalMessageId.MaxUnloadHookExceeded */, \"Max unload hooks exceeded. An excessive number of unload hooks has been detected.\");\n }\n }\n function _addHook(hooks) {\n if (hooks) {\n arrAppend(_hooks, hooks);\n if (_maxHooks && _hooks[_DYN_LENGTH /* @min:%2elength */] > _maxHooks) {\n _hookAddMonitor ? _hookAddMonitor(\"Add\", _hooks) : _throwInternal(null, 1 /* eLoggingSeverity.CRITICAL */, 48 /* _eInternalMessageId.MaxUnloadHookExceeded */, \"Max unload hooks exceeded. An excessive number of unload hooks has been detected.\");\n }\n }\n }\n return {\n run: _doUnload,\n add: _addHook\n };\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n\"use strict\";\n\nvar _a;\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { isFunction, objDefine } from \"@nevware21/ts-utils\";\nimport { createDynamicConfig } from \"../Config/DynamicConfig\";\nimport { _DYN_CREATE_NEW, _DYN_DIAG_LOG, _DYN_GET_NEXT, _DYN_GET_PROCESS_TEL_CONT2, _DYN_INITIALIZE, _DYN_IS_INITIALIZED, _DYN_PROCESS_NEXT, _DYN_SET_NEXT_PLUGIN, _DYN_TEARDOWN, _DYN_UPDATE, _DYN__DO_TEARDOWN } from \"../__DynamicConstants\";\nimport { safeGetLogger } from \"./DiagnosticLogger\";\nimport { isNotNullOrUndefined, proxyFunctionAs } from \"./HelperFuncs\";\nimport { STR_CORE, STR_EXTENSION_CONFIG, STR_PROCESS_TELEMETRY } from \"./InternalConstants\";\nimport { createProcessTelemetryContext, createProcessTelemetryUnloadContext, createProcessTelemetryUpdateContext } from \"./ProcessTelemetryContext\";\nimport { createUnloadHandlerContainer } from \"./UnloadHandlerContainer\";\nimport { createUnloadHookContainer } from \"./UnloadHookContainer\";\nvar strGetPlugin = \"getPlugin\";\nvar defaultValues = (_a = {}, _a[STR_EXTENSION_CONFIG] = {\n isVal: isNotNullOrUndefined,\n v: {}\n}, _a);\n/**\r\n * BaseTelemetryPlugin provides a basic implementation of the ITelemetryPlugin interface so that plugins\r\n * can avoid implementation the same set of boiler plate code as well as provide a base\r\n * implementation so that new default implementations can be added without breaking all plugins.\r\n */\nvar BaseTelemetryPlugin = /** @class */function () {\n function BaseTelemetryPlugin() {\n var _self = this; // Setting _self here as it's used outside of the dynamicProto as well\n // NOTE!: DON'T set default values here, instead set them in the _initDefaults() function as it is also called during teardown()\n var _isinitialized;\n var _rootCtx; // Used as the root context, holding the current config and initialized core\n var _nextPlugin; // Used for backward compatibility where plugins don't call the main pipeline\n var _unloadHandlerContainer;\n var _hookContainer;\n _initDefaults();\n dynamicProto(BaseTelemetryPlugin, _self, function (_self) {\n _self[_DYN_INITIALIZE /* @min:%2einitialize */] = function (config, core, extensions, pluginChain) {\n _setDefaults(config, core, pluginChain);\n _isinitialized = true;\n };\n _self[_DYN_TEARDOWN /* @min:%2eteardown */] = function (unloadCtx, unloadState) {\n // If this plugin has already been torn down (not operational) or is not initialized (core is not set)\n // or the core being used for unload was not the same core used for initialization.\n var core = _self[STR_CORE /* @min:%2ecore */];\n if (!core || unloadCtx && core !== unloadCtx[STR_CORE /* @min:%2ecore */]()) {\n // Do Nothing as either the plugin is not initialized or was not initialized by the current core\n return;\n }\n var result;\n var unloadDone = false;\n var theUnloadCtx = unloadCtx || createProcessTelemetryUnloadContext(null, core, _nextPlugin && _nextPlugin[strGetPlugin] ? _nextPlugin[strGetPlugin]() : _nextPlugin);\n var theUnloadState = unloadState || {\n reason: 0 /* TelemetryUnloadReason.ManualTeardown */,\n isAsync: false\n };\n function _unloadCallback() {\n if (!unloadDone) {\n unloadDone = true;\n _unloadHandlerContainer.run(theUnloadCtx, unloadState);\n _hookContainer.run(theUnloadCtx[_DYN_DIAG_LOG /* @min:%2ediagLog */]());\n if (result === true) {\n theUnloadCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](theUnloadState);\n }\n _initDefaults();\n }\n }\n if (!_self[_DYN__DO_TEARDOWN /* @min:%2e_doTeardown */] || _self[_DYN__DO_TEARDOWN /* @min:%2e_doTeardown */](theUnloadCtx, theUnloadState, _unloadCallback) !== true) {\n _unloadCallback();\n } else {\n // Tell the caller that we will be calling processNext()\n result = true;\n }\n return result;\n };\n _self[_DYN_UPDATE /* @min:%2eupdate */] = function (updateCtx, updateState) {\n // If this plugin has already been torn down (not operational) or is not initialized (core is not set)\n // or the core being used for unload was not the same core used for initialization.\n var core = _self[STR_CORE /* @min:%2ecore */];\n if (!core || updateCtx && core !== updateCtx[STR_CORE /* @min:%2ecore */]()) {\n // Do Nothing\n return;\n }\n var result;\n var updateDone = false;\n var theUpdateCtx = updateCtx || createProcessTelemetryUpdateContext(null, core, _nextPlugin && _nextPlugin[strGetPlugin] ? _nextPlugin[strGetPlugin]() : _nextPlugin);\n var theUpdateState = updateState || {\n reason: 0 /* TelemetryUpdateReason.Unknown */\n };\n function _updateCallback() {\n if (!updateDone) {\n updateDone = true;\n _setDefaults(theUpdateCtx.getCfg(), theUpdateCtx.core(), theUpdateCtx[_DYN_GET_NEXT /* @min:%2egetNext */]());\n }\n }\n if (!_self._doUpdate || _self._doUpdate(theUpdateCtx, theUpdateState, _updateCallback) !== true) {\n _updateCallback();\n } else {\n result = true;\n }\n return result;\n };\n proxyFunctionAs(_self, \"_addUnloadCb\", function () {\n return _unloadHandlerContainer;\n }, \"add\");\n proxyFunctionAs(_self, \"_addHook\", function () {\n return _hookContainer;\n }, \"add\");\n objDefine(_self, \"_unloadHooks\", {\n g: function () {\n return _hookContainer;\n }\n });\n });\n // These are added after the dynamicProto so that are not moved to the prototype\n _self[_DYN_DIAG_LOG /* @min:%2ediagLog */] = function (itemCtx) {\n return _getTelCtx(itemCtx)[_DYN_DIAG_LOG /* @min:%2ediagLog */]();\n };\n _self[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */] = function () {\n return _isinitialized;\n };\n _self.setInitialized = function (isInitialized) {\n _isinitialized = isInitialized;\n };\n // _self.getNextPlugin = () => DO NOT IMPLEMENT\n // Sub-classes of this base class *should* not be relying on this value and instead\n // should use processNext() function. If you require access to the plugin use the\n // IProcessTelemetryContext.getNext().getPlugin() while in the pipeline, Note getNext() may return null.\n _self[_DYN_SET_NEXT_PLUGIN /* @min:%2esetNextPlugin */] = function (next) {\n _nextPlugin = next;\n };\n _self[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */] = function (env, itemCtx) {\n if (itemCtx) {\n // Normal core execution sequence\n itemCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](env);\n } else if (_nextPlugin && isFunction(_nextPlugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */])) {\n // Looks like backward compatibility or out of band processing. And as it looks\n // like a ITelemetryPlugin or ITelemetryPluginChain, just call processTelemetry\n _nextPlugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */](env, null);\n }\n };\n _self._getTelCtx = _getTelCtx;\n function _getTelCtx(currentCtx) {\n if (currentCtx === void 0) {\n currentCtx = null;\n }\n var itemCtx = currentCtx;\n if (!itemCtx) {\n var rootCtx = _rootCtx || createProcessTelemetryContext(null, {}, _self[STR_CORE /* @min:%2ecore */]);\n // tslint:disable-next-line: prefer-conditional-expression\n if (_nextPlugin && _nextPlugin[strGetPlugin]) {\n // Looks like a chain object\n itemCtx = rootCtx[_DYN_CREATE_NEW /* @min:%2ecreateNew */](null, _nextPlugin[strGetPlugin]);\n } else {\n itemCtx = rootCtx[_DYN_CREATE_NEW /* @min:%2ecreateNew */](null, _nextPlugin);\n }\n }\n return itemCtx;\n }\n function _setDefaults(config, core, pluginChain) {\n // Make sure the extensionConfig exists and the config is dynamic\n createDynamicConfig(config, defaultValues, safeGetLogger(core));\n if (!pluginChain && core) {\n // Get the first plugin from the core\n pluginChain = core[_DYN_GET_PROCESS_TEL_CONT2 /* @min:%2egetProcessTelContext */]()[_DYN_GET_NEXT /* @min:%2egetNext */]();\n }\n var nextPlugin = _nextPlugin;\n if (_nextPlugin && _nextPlugin[strGetPlugin]) {\n // If it looks like a proxy/chain then get the plugin\n nextPlugin = _nextPlugin[strGetPlugin]();\n }\n // Support legacy plugins where core was defined as a property\n _self[STR_CORE /* @min:%2ecore */] = core;\n _rootCtx = createProcessTelemetryContext(pluginChain, config, core, nextPlugin);\n }\n function _initDefaults() {\n _isinitialized = false;\n _self[STR_CORE /* @min:%2ecore */] = null;\n _rootCtx = null;\n _nextPlugin = null;\n _hookContainer = createUnloadHookContainer();\n _unloadHandlerContainer = createUnloadHandlerContainer();\n }\n }\n // Removed Stub for BaseTelemetryPlugin.prototype.initialize.\n // Removed Stub for BaseTelemetryPlugin.prototype.teardown.\n // Removed Stub for BaseTelemetryPlugin.prototype.update.\n // Removed Stub for BaseTelemetryPlugin.prototype._addUnloadCb.\n // Removed Stub for BaseTelemetryPlugin.prototype._addHook.\n // This is a workaround for an IE bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n BaseTelemetryPlugin.__ieDyn = 1;\n return BaseTelemetryPlugin;\n}();\nexport { BaseTelemetryPlugin };\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n// \n// \nimport { __extendsFn as __extends } from \"@microsoft/applicationinsights-shims\";\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { arrAppend, arrForEach, dumpObj } from \"@nevware21/ts-utils\";\nimport { _DYN_APPLY, _DYN_DIAG_LOG, _DYN_LENGTH, _DYN_PROCESS_NEXT, _DYN_SPLICE, _DYN__DO_TEARDOWN } from \"../__DynamicConstants\";\nimport { BaseTelemetryPlugin } from \"./BaseTelemetryPlugin\";\nimport { _throwInternal } from \"./DiagnosticLogger\";\nimport { getExceptionName } from \"./HelperFuncs\";\nimport { STR_PROCESS_TELEMETRY } from \"./InternalConstants\";\nfunction _addInitializer(_initializers, id, telemetryInitializer) {\n var theInitializer = {\n id: id,\n fn: telemetryInitializer\n };\n arrAppend(_initializers, theInitializer);\n var handler = {\n remove: function () {\n arrForEach(_initializers, function (initializer, idx) {\n if (initializer.id === theInitializer.id) {\n _initializers[_DYN_SPLICE /* @min:%2esplice */](idx, 1);\n return -1;\n }\n });\n }\n };\n return handler;\n}\nfunction _runInitializers(_initializers, item, logger) {\n var doNotSendItem = false;\n var telemetryInitializersCount = _initializers[_DYN_LENGTH /* @min:%2elength */];\n for (var i = 0; i < telemetryInitializersCount; ++i) {\n var telemetryInitializer = _initializers[i];\n if (telemetryInitializer) {\n try {\n if (telemetryInitializer.fn[_DYN_APPLY /* @min:%2eapply */](null, [item]) === false) {\n doNotSendItem = true;\n break;\n }\n } catch (e) {\n // log error but dont stop executing rest of the telemetry initializers\n // doNotSendItem = true;\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 64 /* _eInternalMessageId.TelemetryInitializerFailed */, \"Telemetry initializer failed: \" + getExceptionName(e), {\n exception: dumpObj(e)\n }, true);\n }\n }\n }\n return !doNotSendItem;\n}\nvar TelemetryInitializerPlugin = /** @class */function (_super) {\n __extends(TelemetryInitializerPlugin, _super);\n function TelemetryInitializerPlugin() {\n var _this = _super.call(this) || this;\n _this.identifier = \"TelemetryInitializerPlugin\";\n _this.priority = 199;\n // NOTE!: DON'T set default values here, instead set them in the _initDefaults() function as it is also called during teardown()\n var _id;\n var _initializers;\n _initDefaults();\n dynamicProto(TelemetryInitializerPlugin, _this, function (_self, _base) {\n _self.addTelemetryInitializer = function (telemetryInitializer) {\n return _addInitializer(_initializers, _id++, telemetryInitializer);\n };\n _self[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */] = function (item, itemCtx) {\n if (_runInitializers(_initializers, item, itemCtx ? itemCtx[_DYN_DIAG_LOG /* @min:%2ediagLog */]() : _self[_DYN_DIAG_LOG /* @min:%2ediagLog */]())) {\n _self[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](item, itemCtx);\n }\n };\n _self[_DYN__DO_TEARDOWN /* @min:%2e_doTeardown */] = function () {\n _initDefaults();\n };\n });\n function _initDefaults() {\n _id = 0;\n _initializers = [];\n }\n return _this;\n }\n // Removed Stub for TelemetryInitializerPlugin.prototype.addTelemetryInitializer.\n // Removed Stub for TelemetryInitializerPlugin.prototype.processTelemetry.\n // This is a workaround for an IE bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n TelemetryInitializerPlugin.__ieDyn = 1;\n return TelemetryInitializerPlugin;\n}(BaseTelemetryPlugin);\nexport { TelemetryInitializerPlugin };\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n\"use strict\";\n\nvar _a;\nimport { __spreadArrayFn as __spreadArray } from \"@microsoft/applicationinsights-shims\";\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { createPromise, createSyncAllSettledPromise, doAwaitResponse } from \"@nevware21/ts-async\";\nimport { arrAppend, arrForEach, arrIndexOf, createTimeout, deepExtend, hasDocument, isFunction, isNullOrUndefined, isPlainObject, isPromiseLike, objDeepFreeze, objDefine, objForEachKey, objFreeze, objHasOwn, scheduleTimeout, throwError } from \"@nevware21/ts-utils\";\nimport { createDynamicConfig, onConfigChange } from \"../Config/DynamicConfig\";\nimport { ActiveStatus } from \"../JavaScriptSDK.Enums/InitActiveStatusEnum\";\nimport { _DYN_ADD_NOTIFICATION_LIS1, _DYN_CANCEL, _DYN_CREATE_NEW, _DYN_ENABLED, _DYN_GET_NOTIFY_MGR, _DYN_GET_PLUGIN, _DYN_GET_PROCESS_TEL_CONT2, _DYN_IDENTIFIER, _DYN_INITIALIZE, _DYN_IS_INITIALIZED, _DYN_LENGTH, _DYN_LOGGER, _DYN_LOGGING_LEVEL_CONSOL4, _DYN_MESSAGE, _DYN_MESSAGE_ID, _DYN_NAME, _DYN_ON_COMPLETE, _DYN_PROCESS_NEXT, _DYN_PUSH, _DYN_REMOVE_NOTIFICATION_0, _DYN_SPLICE, _DYN_STOP_POLLING_INTERNA3, _DYN_TEARDOWN, _DYN_UNLOAD, _DYN_VALUE, _DYN_VERSION, _DYN_WATCH } from \"../__DynamicConstants\";\nimport { doUnloadAll, runTargetUnload } from \"./AsyncUtils\";\nimport { ChannelControllerPriority } from \"./Constants\";\nimport { createCookieMgr } from \"./CookieMgr\";\nimport { createUniqueNamespace } from \"./DataCacheHelper\";\nimport { getDebugListener } from \"./DbgExtensionUtils\";\nimport { DiagnosticLogger, _InternalLogMessage, _throwInternal, _warnToConsole } from \"./DiagnosticLogger\";\nimport { getSetValue, isNotNullOrUndefined, proxyFunctionAs, proxyFunctions, toISOString } from \"./HelperFuncs\";\nimport { STR_CHANNELS, STR_CORE, STR_CREATE_PERF_MGR, STR_DISABLED, STR_EMPTY, STR_EVENTS_DISCARDED, STR_EXTENSIONS, STR_EXTENSION_CONFIG, STR_GET_PERF_MGR, STR_PRIORITY, UNDEFINED_VALUE } from \"./InternalConstants\";\nimport { NotificationManager } from \"./NotificationManager\";\nimport { PerfManager, doPerf, getGblPerfMgr } from \"./PerfManager\";\nimport { createProcessTelemetryContext, createProcessTelemetryUnloadContext, createProcessTelemetryUpdateContext, createTelemetryProxyChain } from \"./ProcessTelemetryContext\";\nimport { _getPluginState, createDistributedTraceContext, initializePlugins, sortPlugins } from \"./TelemetryHelpers\";\nimport { TelemetryInitializerPlugin } from \"./TelemetryInitializerPlugin\";\nimport { createUnloadHandlerContainer } from \"./UnloadHandlerContainer\";\nimport { createUnloadHookContainer } from \"./UnloadHookContainer\";\nvar strValidationError = \"Plugins must provide initialize method\";\nvar strNotificationManager = \"_notificationManager\";\nvar strSdkUnloadingError = \"SDK is still unloading...\";\nvar strSdkNotInitialized = \"SDK is not initialized\";\nvar maxInitQueueSize = 100;\nvar maxInitTimeout = 50000;\n// const strPluginUnloadFailed = \"Failed to unload plugin\";\n/**\r\n * The default settings for the config.\r\n * WE MUST include all defaults here to ensure that the config is created with all of the properties\r\n * defined as dynamic.\r\n */\nvar defaultConfig = objDeepFreeze((_a = {\n cookieCfg: {}\n}, _a[STR_EXTENSIONS] = {\n rdOnly: true,\n ref: true,\n v: []\n}, _a[STR_CHANNELS] = {\n rdOnly: true,\n ref: true,\n v: []\n}, _a[STR_EXTENSION_CONFIG] = {\n ref: true,\n v: {}\n}, _a[STR_CREATE_PERF_MGR] = UNDEFINED_VALUE, _a.loggingLevelConsole = 0 /* eLoggingSeverity.DISABLED */, _a.diagnosticLogInterval = UNDEFINED_VALUE, _a));\n/**\r\n * Helper to create the default performance manager\r\n * @param core - The AppInsightsCore instance\r\n * @param notificationMgr - The notification manager\r\n */\nfunction _createPerfManager(core, notificationMgr) {\n return new PerfManager(notificationMgr);\n}\nfunction _validateExtensions(logger, channelPriority, allExtensions) {\n // Concat all available extensions\n var coreExtensions = [];\n var channels = [];\n // Check if any two extensions have the same priority, then warn to console\n // And extract the local extensions from the\n var extPriorities = {};\n // Extension validation\n arrForEach(allExtensions, function (ext) {\n // Check for ext.initialize\n if (isNullOrUndefined(ext) || isNullOrUndefined(ext[_DYN_INITIALIZE /* @min:%2einitialize */])) {\n throwError(strValidationError);\n }\n var extPriority = ext[STR_PRIORITY /* @min:%2epriority */];\n var identifier = ext[_DYN_IDENTIFIER /* @min:%2eidentifier */];\n if (ext && extPriority) {\n if (!isNullOrUndefined(extPriorities[extPriority])) {\n _warnToConsole(logger, \"Two extensions have same priority #\" + extPriority + \" - \" + extPriorities[extPriority] + \", \" + identifier);\n } else {\n // set a value\n extPriorities[extPriority] = identifier;\n }\n }\n // Split extensions to core and channels\n if (!extPriority || extPriority < channelPriority) {\n // Add to core extension that will be managed by AppInsightsCore\n coreExtensions[_DYN_PUSH /* @min:%2epush */](ext);\n } else {\n channels[_DYN_PUSH /* @min:%2epush */](ext);\n }\n });\n return {\n core: coreExtensions,\n channels: channels\n };\n}\nfunction _isPluginPresent(thePlugin, plugins) {\n var exists = false;\n arrForEach(plugins, function (plugin) {\n if (plugin === thePlugin) {\n exists = true;\n return -1;\n }\n });\n return exists;\n}\nfunction _deepMergeConfig(details, target, newValues, merge) {\n // Lets assign the new values to the existing config\n if (newValues) {\n objForEachKey(newValues, function (key, value) {\n if (merge) {\n if (isPlainObject(value) && isPlainObject(target[key])) {\n // The target is an object and it has a value\n _deepMergeConfig(details, target[key], value, merge);\n }\n }\n if (merge && isPlainObject(value) && isPlainObject(target[key])) {\n // The target is an object and it has a value\n _deepMergeConfig(details, target[key], value, merge);\n } else {\n // Just Assign (replace) and/or make the property dynamic\n details.set(target, key, value);\n }\n });\n }\n}\nfunction _findWatcher(listeners, newWatcher) {\n var theListener = null;\n var idx = -1;\n arrForEach(listeners, function (listener, lp) {\n if (listener.w === newWatcher) {\n theListener = listener;\n idx = lp;\n return -1;\n }\n });\n return {\n i: idx,\n l: theListener\n };\n}\nfunction _addDelayedCfgListener(listeners, newWatcher) {\n var theListener = _findWatcher(listeners, newWatcher).l;\n if (!theListener) {\n theListener = {\n w: newWatcher,\n rm: function () {\n var fnd = _findWatcher(listeners, newWatcher);\n if (fnd.i !== -1) {\n listeners[_DYN_SPLICE /* @min:%2esplice */](fnd.i, 1);\n }\n }\n };\n listeners[_DYN_PUSH /* @min:%2epush */](theListener);\n }\n return theListener;\n}\nfunction _registerDelayedCfgListener(config, listeners, logger) {\n arrForEach(listeners, function (listener) {\n var unloadHdl = onConfigChange(config, listener.w, logger);\n delete listener.w; // Clear the listener reference so it will get garbage collected.\n // replace the remove function\n listener.rm = function () {\n unloadHdl.rm();\n };\n });\n}\n// Moved this outside of the closure to reduce the retained memory footprint\nfunction _initDebugListener(configHandler, unloadContainer, notificationManager, debugListener) {\n // Will get recalled if any referenced config values are changed\n unloadContainer.add(configHandler[_DYN_WATCH /* @min:%2ewatch */](function (details) {\n var disableDbgExt = details.cfg.disableDbgExt;\n if (disableDbgExt === true && debugListener) {\n // Remove any previously loaded debug listener\n notificationManager[_DYN_REMOVE_NOTIFICATION_0 /* @min:%2eremoveNotificationListener */](debugListener);\n debugListener = null;\n }\n if (notificationManager && !debugListener && disableDbgExt !== true) {\n debugListener = getDebugListener(details.cfg);\n notificationManager[_DYN_ADD_NOTIFICATION_LIS1 /* @min:%2eaddNotificationListener */](debugListener);\n }\n }));\n return debugListener;\n}\n// Moved this outside of the closure to reduce the retained memory footprint\nfunction _createUnloadHook(unloadHook) {\n return objDefine({\n rm: function () {\n unloadHook.rm();\n }\n }, \"toJSON\", {\n v: function () {\n return \"aicore::onCfgChange<\" + JSON.stringify(unloadHook) + \">\";\n }\n });\n}\n/**\r\n * @group Classes\r\n * @group Entrypoint\r\n */\nvar AppInsightsCore = /** @class */function () {\n function AppInsightsCore() {\n // NOTE!: DON'T set default values here, instead set them in the _initDefaults() function as it is also called during teardown()\n var _configHandler;\n var _isInitialized;\n var _logger;\n var _eventQueue;\n var _notificationManager;\n var _perfManager;\n var _cfgPerfManager;\n var _cookieManager;\n var _pluginChain;\n var _configExtensions;\n var _channelConfig;\n var _channels;\n var _isUnloading;\n var _telemetryInitializerPlugin;\n var _internalLogsEventName;\n var _evtNamespace;\n var _unloadHandlers;\n var _hookContainer;\n var _debugListener;\n var _traceCtx;\n var _instrumentationKey;\n var _cfgListeners;\n var _extensions;\n var _pluginVersionStringArr;\n var _pluginVersionString;\n var _activeStatus; // to indicate if ikey or endpoint url promised is resolved or not\n var _endpoint;\n var _initInMemoMaxSize; // max event count limit during wait for init promises to be resolved\n var _isStatusSet; // track if active status is set in case of init timeout and init promises setting the status twice\n var _initTimer;\n /**\r\n * Internal log poller\r\n */\n var _internalLogPoller;\n var _internalLogPollerListening;\n var _forceStopInternalLogPoller;\n dynamicProto(AppInsightsCore, this, function (_self) {\n // Set the default values (also called during teardown)\n _initDefaults();\n // Special internal method to allow the unit tests and DebugPlugin to hook embedded objects\n _self[\"_getDbgPlgTargets\"] = function () {\n return [_extensions, _eventQueue];\n };\n _self[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */] = function () {\n return _isInitialized;\n };\n // since version 3.3.0\n _self.activeStatus = function () {\n return _activeStatus;\n };\n // since version 3.3.0\n // internal\n _self._setPendingStatus = function () {\n _activeStatus = 3 /* eActiveStatus.PENDING */;\n };\n // Creating the self.initialize = ()\n _self[_DYN_INITIALIZE /* @min:%2einitialize */] = function (config, extensions, logger, notificationManager) {\n if (_isUnloading) {\n throwError(strSdkUnloadingError);\n }\n // Make sure core is only initialized once\n if (_self[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */]()) {\n throwError(\"Core cannot be initialized more than once\");\n }\n _configHandler = createDynamicConfig(config, defaultConfig, logger || _self[_DYN_LOGGER /* @min:%2elogger */], false);\n // Re-assigning the local config property so we don't have any references to the passed value and it can be garbage collected\n config = _configHandler.cfg;\n // This will be \"re-run\" if the referenced config properties are changed\n _addUnloadHook(_configHandler[_DYN_WATCH /* @min:%2ewatch */](function (details) {\n var rootCfg = details.cfg;\n var isPending = _activeStatus === 3 /* eActiveStatus.PENDING */;\n if (isPending) {\n // means waiting for previous promises to be resolved, won't apply new changes\n return;\n }\n _initInMemoMaxSize = rootCfg.initInMemoMaxSize || maxInitQueueSize;\n // app Insights core only handle ikey and endpointurl, aisku will handle cs\n var ikey = rootCfg.instrumentationKey;\n var endpointUrl = rootCfg.endpointUrl; // do not need to validate endpoint url, if it is null, default one will be set by sender\n if (isNullOrUndefined(ikey)) {\n _instrumentationKey = null;\n // if new ikey is null, set status to be inactive, all new events will be saved in memory or dropped\n _activeStatus = ActiveStatus.INACTIVE;\n var msg = \"Please provide instrumentation key\";\n if (!_isInitialized) {\n // only throw error during initialization\n throwError(msg);\n } else {\n _throwInternal(_logger, 1 /* eLoggingSeverity.CRITICAL */, 100 /* _eInternalMessageId.InvalidInstrumentationKey */, msg);\n _releaseQueues();\n }\n return;\n }\n var promises = [];\n if (isPromiseLike(ikey)) {\n promises[_DYN_PUSH /* @min:%2epush */](ikey);\n _instrumentationKey = null; // reset current local ikey variable (otherwise it will always be the previous ikeys if timeout is called before promise cb)\n } else {\n // string\n _instrumentationKey = ikey;\n }\n if (isPromiseLike(endpointUrl)) {\n promises[_DYN_PUSH /* @min:%2epush */](endpointUrl);\n _endpoint = null; // reset current local endpoint variable (otherwise it will always be the previous urls if timeout is called before promise cb)\n } else {\n // string or null\n _endpoint = endpointUrl;\n }\n // at least have one promise\n if (promises[_DYN_LENGTH /* @min:%2elength */]) {\n // reset to false for new dynamic changes\n _isStatusSet = false;\n _activeStatus = 3 /* eActiveStatus.PENDING */;\n var initTimeout = isNotNullOrUndefined(rootCfg.initTimeOut) ? rootCfg.initTimeOut : maxInitTimeout; // rootCfg.initTimeOut could be 0\n var allPromises = createSyncAllSettledPromise(promises);\n _initTimer = scheduleTimeout(function () {\n // set _isStatusSet to true\n // set active status\n // release queues\n _initTimer = null;\n if (!_isStatusSet) {\n _setStatus();\n }\n }, initTimeout);\n doAwaitResponse(allPromises, function (response) {\n try {\n if (_isStatusSet) {\n // promises take too long to resolve, ignore them\n // active status should be set by timeout already\n return;\n }\n if (!response.rejected) {\n var values = response[_DYN_VALUE /* @min:%2evalue */];\n if (values && values[_DYN_LENGTH /* @min:%2elength */]) {\n // ikey\n var ikeyRes = values[0];\n _instrumentationKey = ikeyRes && ikeyRes[_DYN_VALUE /* @min:%2evalue */];\n // endpoint\n if (values[_DYN_LENGTH /* @min:%2elength */] > 1) {\n var endpointRes = values[1];\n _endpoint = endpointRes && endpointRes[_DYN_VALUE /* @min:%2evalue */];\n }\n }\n if (_instrumentationKey) {\n // if ikey is null, no need to trigger extra dynamic changes for extensions\n config.instrumentationKey = _instrumentationKey; // set config.instrumentationKey for extensions to consume\n config.endpointUrl = _endpoint; // set config.endpointUrl for extensions to consume\n }\n }\n // set _isStatusSet to true\n // set active status\n // release queues\n _setStatus();\n } catch (e) {\n if (!_isStatusSet) {\n _setStatus();\n }\n }\n });\n } else {\n // means no promises\n _setStatus();\n }\n //_instrumentationKey = details.cfg.instrumentationKey;\n // Mark the extensionConfig and all first level keys as referenced\n // This is so that calls to getExtCfg() will always return the same object\n // Even when a user may \"re-assign\" the plugin properties (or it's unloaded/reloaded)\n var extCfg = details.ref(details.cfg, STR_EXTENSION_CONFIG);\n objForEachKey(extCfg, function (key) {\n details.ref(extCfg, key);\n });\n }));\n _notificationManager = notificationManager;\n // Initialize the debug listener outside of the closure to reduce the retained memory footprint\n _debugListener = _initDebugListener(_configHandler, _hookContainer, _notificationManager && _self[_DYN_GET_NOTIFY_MGR /* @min:%2egetNotifyMgr */](), _debugListener);\n _initPerfManager();\n _self[_DYN_LOGGER /* @min:%2elogger */] = logger;\n var cfgExtensions = config[STR_EXTENSIONS /* @min:%2eextensions */];\n // Extension validation\n _configExtensions = [];\n _configExtensions[_DYN_PUSH /* @min:%2epush */].apply(_configExtensions, __spreadArray(__spreadArray([], extensions, false), cfgExtensions, false));\n _channelConfig = config[STR_CHANNELS /* @min:%2echannels */];\n _initPluginChain(null);\n if (!_channels || _channels[_DYN_LENGTH /* @min:%2elength */] === 0) {\n throwError(\"No \" + STR_CHANNELS + \" available\");\n }\n if (_channelConfig && _channelConfig[_DYN_LENGTH /* @min:%2elength */] > 1) {\n var teeController = _self[_DYN_GET_PLUGIN /* @min:%2egetPlugin */](\"TeeChannelController\");\n if (!teeController || !teeController.plugin) {\n _throwInternal(_logger, 1 /* eLoggingSeverity.CRITICAL */, 28 /* _eInternalMessageId.SenderNotInitialized */, \"TeeChannel required\");\n }\n }\n _registerDelayedCfgListener(config, _cfgListeners, _logger);\n _cfgListeners = null;\n _isInitialized = true;\n if (_activeStatus === ActiveStatus.ACTIVE) {\n _releaseQueues();\n }\n };\n _self.getChannels = function () {\n var controls = [];\n if (_channels) {\n arrForEach(_channels, function (channel) {\n controls[_DYN_PUSH /* @min:%2epush */](channel);\n });\n }\n return objFreeze(controls);\n };\n _self.track = function (telemetryItem) {\n doPerf(_self[STR_GET_PERF_MGR /* @min:%2egetPerfMgr */](), function () {\n return \"AppInsightsCore:track\";\n }, function () {\n if (telemetryItem === null) {\n _notifyInvalidEvent(telemetryItem);\n // throw error\n throwError(\"Invalid telemetry item\");\n }\n // do basic validation before sending it through the pipeline\n if (!telemetryItem[_DYN_NAME /* @min:%2ename */] && isNullOrUndefined(telemetryItem[_DYN_NAME /* @min:%2ename */])) {\n _notifyInvalidEvent(telemetryItem);\n throwError(\"telemetry name required\");\n }\n // setup default iKey if not passed in\n telemetryItem.iKey = telemetryItem.iKey || _instrumentationKey;\n // add default timestamp if not passed in\n telemetryItem.time = telemetryItem.time || toISOString(new Date());\n // Common Schema 4.0\n telemetryItem.ver = telemetryItem.ver || \"4.0\";\n if (!_isUnloading && _self[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */]() && _activeStatus === ActiveStatus.ACTIVE) {\n // Process the telemetry plugin chain\n _createTelCtx()[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](telemetryItem);\n } else if (_activeStatus !== ActiveStatus.INACTIVE) {\n // Queue events until all extensions are initialized\n if (_eventQueue[_DYN_LENGTH /* @min:%2elength */] <= _initInMemoMaxSize) {\n // set limit, if full, stop adding new events\n _eventQueue[_DYN_PUSH /* @min:%2epush */](telemetryItem);\n }\n }\n }, function () {\n return {\n item: telemetryItem\n };\n }, !telemetryItem.sync);\n };\n _self[_DYN_GET_PROCESS_TEL_CONT2 /* @min:%2egetProcessTelContext */] = _createTelCtx;\n _self[_DYN_GET_NOTIFY_MGR /* @min:%2egetNotifyMgr */] = function () {\n if (!_notificationManager) {\n _notificationManager = new NotificationManager(_configHandler.cfg);\n // For backward compatibility only\n _self[strNotificationManager] = _notificationManager;\n }\n return _notificationManager;\n };\n /**\r\n * Adds a notification listener. The SDK calls methods on the listener when an appropriate notification is raised.\r\n * The added plugins must raise notifications. If the plugins do not implement the notifications, then no methods will be\r\n * called.\r\n * @param listener - An INotificationListener object.\r\n */\n _self[_DYN_ADD_NOTIFICATION_LIS1 /* @min:%2eaddNotificationListener */] = function (listener) {\n _self.getNotifyMgr()[_DYN_ADD_NOTIFICATION_LIS1 /* @min:%2eaddNotificationListener */](listener);\n };\n /**\r\n * Removes all instances of the listener.\r\n * @param listener - INotificationListener to remove.\r\n */\n _self[_DYN_REMOVE_NOTIFICATION_0 /* @min:%2eremoveNotificationListener */] = function (listener) {\n if (_notificationManager) {\n _notificationManager[_DYN_REMOVE_NOTIFICATION_0 /* @min:%2eremoveNotificationListener */](listener);\n }\n };\n _self.getCookieMgr = function () {\n if (!_cookieManager) {\n _cookieManager = createCookieMgr(_configHandler.cfg, _self[_DYN_LOGGER /* @min:%2elogger */]);\n }\n return _cookieManager;\n };\n _self.setCookieMgr = function (cookieMgr) {\n if (_cookieManager !== cookieMgr) {\n runTargetUnload(_cookieManager, false);\n _cookieManager = cookieMgr;\n }\n };\n _self[STR_GET_PERF_MGR /* @min:%2egetPerfMgr */] = function () {\n return _perfManager || _cfgPerfManager || getGblPerfMgr();\n };\n _self.setPerfMgr = function (perfMgr) {\n _perfManager = perfMgr;\n };\n _self.eventCnt = function () {\n return _eventQueue[_DYN_LENGTH /* @min:%2elength */];\n };\n _self.releaseQueue = function () {\n if (_isInitialized && _eventQueue[_DYN_LENGTH /* @min:%2elength */] > 0) {\n var eventQueue = _eventQueue;\n _eventQueue = [];\n if (_activeStatus === 2 /* eActiveStatus.ACTIVE */) {\n arrForEach(eventQueue, function (event) {\n event.iKey = event.iKey || _instrumentationKey;\n _createTelCtx()[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](event);\n });\n } else {\n // new one for msg ikey\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 20 /* _eInternalMessageId.FailedToSendQueuedTelemetry */, \"core init status is not active\");\n }\n }\n };\n _self.pollInternalLogs = function (eventName) {\n _internalLogsEventName = eventName || null;\n _forceStopInternalLogPoller = false;\n _internalLogPoller && _internalLogPoller[_DYN_CANCEL /* @min:%2ecancel */]();\n return _startLogPoller(true);\n };\n function _setStatus() {\n _isStatusSet = true;\n if (isNullOrUndefined(_instrumentationKey)) {\n _activeStatus = ActiveStatus.INACTIVE;\n _throwInternal(_logger, 1 /* eLoggingSeverity.CRITICAL */, 112 /* _eInternalMessageId.InitPromiseException */, \"ikey can't be resolved from promises\");\n } else {\n _activeStatus = ActiveStatus.ACTIVE;\n }\n _releaseQueues();\n }\n function _releaseQueues() {\n if (_isInitialized) {\n _self.releaseQueue();\n _self.pollInternalLogs();\n }\n }\n function _startLogPoller(alwaysStart) {\n if ((!_internalLogPoller || !_internalLogPoller[_DYN_ENABLED /* @min:%2eenabled */]) && !_forceStopInternalLogPoller) {\n var shouldStart = alwaysStart || _logger && _logger.queue[_DYN_LENGTH /* @min:%2elength */] > 0;\n if (shouldStart) {\n if (!_internalLogPollerListening) {\n _internalLogPollerListening = true;\n // listen for any configuration changes so that changes to the\n // interval will cause the timer to be re-initialized\n _addUnloadHook(_configHandler[_DYN_WATCH /* @min:%2ewatch */](function (details) {\n var interval = details.cfg.diagnosticLogInterval;\n if (!interval || !(interval > 0)) {\n interval = 10000;\n }\n var isRunning = false;\n if (_internalLogPoller) {\n // It was already created so remember it's running and cancel\n isRunning = _internalLogPoller[_DYN_ENABLED /* @min:%2eenabled */];\n _internalLogPoller[_DYN_CANCEL /* @min:%2ecancel */]();\n }\n // Create / reconfigure\n _internalLogPoller = createTimeout(_flushInternalLogs, interval);\n _internalLogPoller.unref();\n // Restart if previously running\n _internalLogPoller[_DYN_ENABLED /* @min:%2eenabled */] = isRunning;\n }));\n }\n _internalLogPoller[_DYN_ENABLED /* @min:%2eenabled */] = true;\n }\n }\n return _internalLogPoller;\n }\n _self[_DYN_STOP_POLLING_INTERNA3 /* @min:%2estopPollingInternalLogs */] = function () {\n _forceStopInternalLogPoller = true;\n _internalLogPoller && _internalLogPoller[_DYN_CANCEL /* @min:%2ecancel */]();\n _flushInternalLogs();\n };\n // Add addTelemetryInitializer\n proxyFunctions(_self, function () {\n return _telemetryInitializerPlugin;\n }, [\"addTelemetryInitializer\"]);\n _self[_DYN_UNLOAD /* @min:%2eunload */] = function (isAsync, unloadComplete, cbTimeout) {\n if (isAsync === void 0) {\n isAsync = true;\n }\n if (!_isInitialized) {\n // The SDK is not initialized\n throwError(strSdkNotInitialized);\n }\n // Check if the SDK still unloading so throw\n if (_isUnloading) {\n // The SDK is already unloading\n throwError(strSdkUnloadingError);\n }\n var unloadState = {\n reason: 50 /* TelemetryUnloadReason.SdkUnload */,\n isAsync: isAsync,\n flushComplete: false\n };\n var result;\n if (isAsync && !unloadComplete) {\n result = createPromise(function (resolve) {\n // Set the callback to the promise resolve callback\n unloadComplete = resolve;\n });\n }\n var processUnloadCtx = createProcessTelemetryUnloadContext(_getPluginChain(), _self);\n processUnloadCtx[_DYN_ON_COMPLETE /* @min:%2eonComplete */](function () {\n _hookContainer.run(_self[_DYN_LOGGER /* @min:%2elogger */]);\n // Run any \"unload\" functions for the _cookieManager, _notificationManager and _logger\n doUnloadAll([_cookieManager, _notificationManager, _logger], isAsync, function () {\n _initDefaults();\n unloadComplete && unloadComplete(unloadState);\n });\n }, _self);\n function _doUnload(flushComplete) {\n unloadState.flushComplete = flushComplete;\n _isUnloading = true;\n // Run all of the unload handlers first (before unloading the plugins)\n _unloadHandlers.run(processUnloadCtx, unloadState);\n // Stop polling the internal logs\n _self[_DYN_STOP_POLLING_INTERNA3 /* @min:%2estopPollingInternalLogs */]();\n // Start unloading the components, from this point onwards the SDK should be considered to be in an unstable state\n processUnloadCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](unloadState);\n }\n _flushInternalLogs();\n if (!_flushChannels(isAsync, _doUnload, 6 /* SendRequestReason.SdkUnload */, cbTimeout)) {\n _doUnload(false);\n }\n return result;\n };\n _self[_DYN_GET_PLUGIN /* @min:%2egetPlugin */] = _getPlugin;\n _self.addPlugin = function (plugin, replaceExisting, isAsync, addCb) {\n if (!plugin) {\n addCb && addCb(false);\n _logOrThrowError(strValidationError);\n return;\n }\n var existingPlugin = _getPlugin(plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */]);\n if (existingPlugin && !replaceExisting) {\n addCb && addCb(false);\n _logOrThrowError(\"Plugin [\" + plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */] + \"] is already loaded!\");\n return;\n }\n var updateState = {\n reason: 16 /* TelemetryUpdateReason.PluginAdded */\n };\n function _addPlugin(removed) {\n _configExtensions[_DYN_PUSH /* @min:%2epush */](plugin);\n updateState.added = [plugin];\n // Re-Initialize the plugin chain\n _initPluginChain(updateState);\n addCb && addCb(true);\n }\n if (existingPlugin) {\n var removedPlugins_1 = [existingPlugin.plugin];\n var unloadState = {\n reason: 2 /* TelemetryUnloadReason.PluginReplace */,\n isAsync: !!isAsync\n };\n _removePlugins(removedPlugins_1, unloadState, function (removed) {\n if (!removed) {\n // Previous plugin was successfully removed or was not installed\n addCb && addCb(false);\n } else {\n updateState.removed = removedPlugins_1;\n updateState.reason |= 32 /* TelemetryUpdateReason.PluginRemoved */;\n _addPlugin(true);\n }\n });\n } else {\n _addPlugin(false);\n }\n };\n _self.updateCfg = function (newConfig, mergeExisting) {\n if (mergeExisting === void 0) {\n mergeExisting = true;\n }\n var updateState;\n if (_self[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */]()) {\n updateState = {\n reason: 1 /* TelemetryUpdateReason.ConfigurationChanged */,\n cfg: _configHandler.cfg,\n oldCfg: deepExtend({}, _configHandler.cfg),\n newConfig: deepExtend({}, newConfig),\n merge: mergeExisting\n };\n newConfig = updateState.newConfig;\n var cfg = _configHandler.cfg;\n // replace the immutable (if initialized) values\n // We don't currently allow updating the extensions and channels via the update config\n // So overwriting any user provided values to reuse the existing values\n newConfig[STR_EXTENSIONS /* @min:%2eextensions */] = cfg[STR_EXTENSIONS /* @min:%2eextensions */];\n newConfig[STR_CHANNELS /* @min:%2echannels */] = cfg[STR_CHANNELS /* @min:%2echannels */];\n }\n // Explicitly blocking any previous config watchers so that they don't get called because\n // of this bulk update (Probably not necessary)\n _configHandler._block(function (details) {\n // Lets assign the new values to the existing config either overwriting or re-assigning\n var theConfig = details.cfg;\n _deepMergeConfig(details, theConfig, newConfig, mergeExisting);\n if (!mergeExisting) {\n // Remove (unassign) the values \"missing\" from the newConfig and also not in the default config\n objForEachKey(theConfig, function (key) {\n if (!objHasOwn(newConfig, key)) {\n // Set the value to undefined\n details.set(theConfig, key, UNDEFINED_VALUE);\n }\n });\n }\n // Apply defaults to the new config\n details.setDf(theConfig, defaultConfig);\n }, true);\n // Now execute all of the listeners (synchronously) so they update their values immediately\n _configHandler.notify();\n if (updateState) {\n _doUpdate(updateState);\n }\n };\n _self.evtNamespace = function () {\n return _evtNamespace;\n };\n _self.flush = _flushChannels;\n _self.getTraceCtx = function (createNew) {\n if (!_traceCtx) {\n _traceCtx = createDistributedTraceContext();\n }\n return _traceCtx;\n };\n _self.setTraceCtx = function (traceCtx) {\n _traceCtx = traceCtx || null;\n };\n _self.addUnloadHook = _addUnloadHook;\n // Create the addUnloadCb\n proxyFunctionAs(_self, \"addUnloadCb\", function () {\n return _unloadHandlers;\n }, \"add\");\n _self.onCfgChange = function (handler) {\n var unloadHook;\n if (!_isInitialized) {\n unloadHook = _addDelayedCfgListener(_cfgListeners, handler);\n } else {\n unloadHook = onConfigChange(_configHandler.cfg, handler, _self[_DYN_LOGGER /* @min:%2elogger */]);\n }\n return _createUnloadHook(unloadHook);\n };\n _self.getWParam = function () {\n return hasDocument() || !!_configHandler.cfg.enableWParam ? 0 : -1;\n };\n function _setPluginVersions() {\n var thePlugins = {};\n _pluginVersionStringArr = [];\n var _addPluginVersions = function (plugins) {\n if (plugins) {\n arrForEach(plugins, function (plugin) {\n if (plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */] && plugin[_DYN_VERSION /* @min:%2eversion */] && !thePlugins[plugin.identifier]) {\n var ver = plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */] + \"=\" + plugin[_DYN_VERSION /* @min:%2eversion */];\n _pluginVersionStringArr[_DYN_PUSH /* @min:%2epush */](ver);\n thePlugins[plugin.identifier] = plugin;\n }\n });\n }\n };\n _addPluginVersions(_channels);\n if (_channelConfig) {\n arrForEach(_channelConfig, function (channels) {\n _addPluginVersions(channels);\n });\n }\n _addPluginVersions(_configExtensions);\n }\n function _initDefaults() {\n _isInitialized = false;\n // Use a default logger so initialization errors are not dropped on the floor with full logging\n _configHandler = createDynamicConfig({}, defaultConfig, _self[_DYN_LOGGER /* @min:%2elogger */]);\n // Set the logging level to critical so that any critical initialization failures are displayed on the console\n _configHandler.cfg[_DYN_LOGGING_LEVEL_CONSOL4 /* @min:%2eloggingLevelConsole */] = 1 /* eLoggingSeverity.CRITICAL */;\n // Define _self.config\n objDefine(_self, \"config\", {\n g: function () {\n return _configHandler.cfg;\n },\n s: function (newValue) {\n _self.updateCfg(newValue, false);\n }\n });\n objDefine(_self, \"pluginVersionStringArr\", {\n g: function () {\n if (!_pluginVersionStringArr) {\n _setPluginVersions();\n }\n return _pluginVersionStringArr;\n }\n });\n objDefine(_self, \"pluginVersionString\", {\n g: function () {\n if (!_pluginVersionString) {\n if (!_pluginVersionStringArr) {\n _setPluginVersions();\n }\n _pluginVersionString = _pluginVersionStringArr.join(\";\");\n }\n return _pluginVersionString || STR_EMPTY;\n }\n });\n objDefine(_self, \"logger\", {\n g: function () {\n if (!_logger) {\n _logger = new DiagnosticLogger(_configHandler.cfg);\n _configHandler[_DYN_LOGGER /* @min:%2elogger */] = _logger;\n }\n return _logger;\n },\n s: function (newLogger) {\n _configHandler[_DYN_LOGGER /* @min:%2elogger */] = newLogger;\n if (_logger !== newLogger) {\n runTargetUnload(_logger, false);\n _logger = newLogger;\n }\n }\n });\n _self[_DYN_LOGGER /* @min:%2elogger */] = new DiagnosticLogger(_configHandler.cfg);\n _extensions = [];\n var cfgExtensions = _self.config[STR_EXTENSIONS /* @min:%2eextensions */] || [];\n cfgExtensions.splice(0, cfgExtensions[_DYN_LENGTH /* @min:%2elength */]);\n arrAppend(cfgExtensions, _extensions);\n _telemetryInitializerPlugin = new TelemetryInitializerPlugin();\n _eventQueue = [];\n runTargetUnload(_notificationManager, false);\n _notificationManager = null;\n _perfManager = null;\n _cfgPerfManager = null;\n runTargetUnload(_cookieManager, false);\n _cookieManager = null;\n _pluginChain = null;\n _configExtensions = [];\n _channelConfig = null;\n _channels = null;\n _isUnloading = false;\n _internalLogsEventName = null;\n _evtNamespace = createUniqueNamespace(\"AIBaseCore\", true);\n _unloadHandlers = createUnloadHandlerContainer();\n _traceCtx = null;\n _instrumentationKey = null;\n _hookContainer = createUnloadHookContainer();\n _cfgListeners = [];\n _pluginVersionString = null;\n _pluginVersionStringArr = null;\n _forceStopInternalLogPoller = false;\n _internalLogPoller = null;\n _internalLogPollerListening = false;\n _activeStatus = 0 /* eActiveStatus.NONE */; // default is None\n _endpoint = null;\n _initInMemoMaxSize = null;\n _isStatusSet = false;\n _initTimer = null;\n }\n function _createTelCtx() {\n var theCtx = createProcessTelemetryContext(_getPluginChain(), _configHandler.cfg, _self);\n theCtx[_DYN_ON_COMPLETE /* @min:%2eonComplete */](_startLogPoller);\n return theCtx;\n }\n // Initialize or Re-initialize the plugins\n function _initPluginChain(updateState) {\n // Extension validation\n var theExtensions = _validateExtensions(_self[_DYN_LOGGER /* @min:%2elogger */], ChannelControllerPriority, _configExtensions);\n _pluginChain = null;\n _pluginVersionString = null;\n _pluginVersionStringArr = null;\n // Get the primary channel queue and include as part of the normal extensions\n _channels = (_channelConfig || [])[0] || [];\n // Add any channels provided in the extensions and sort them\n _channels = sortPlugins(arrAppend(_channels, theExtensions[STR_CHANNELS /* @min:%2echannels */]));\n // Create an array of all extensions, including the _channels\n var allExtensions = arrAppend(sortPlugins(theExtensions[STR_CORE /* @min:%2ecore */]), _channels);\n // Required to allow plugins to call core.getPlugin() during their own initialization\n _extensions = objFreeze(allExtensions);\n // This has a side effect of adding the extensions passed during initialization\n // into the config.extensions, so you can see all of the extensions loaded.\n // This will also get updated by the addPlugin() and remove plugin code.\n var cfgExtensions = _self.config[STR_EXTENSIONS /* @min:%2eextensions */] || [];\n cfgExtensions.splice(0, cfgExtensions[_DYN_LENGTH /* @min:%2elength */]);\n arrAppend(cfgExtensions, _extensions);\n var rootCtx = _createTelCtx();\n // Initializing the channels first\n if (_channels && _channels[_DYN_LENGTH /* @min:%2elength */] > 0) {\n initializePlugins(rootCtx[_DYN_CREATE_NEW /* @min:%2ecreateNew */](_channels), allExtensions);\n }\n // Now initialize the normal extensions (explicitly not including the _channels as this can cause duplicate initialization)\n initializePlugins(rootCtx, allExtensions);\n if (updateState) {\n _doUpdate(updateState);\n }\n }\n function _getPlugin(pluginIdentifier) {\n var theExt = null;\n var thePlugin = null;\n var channelHosts = [];\n arrForEach(_extensions, function (ext) {\n if (ext[_DYN_IDENTIFIER /* @min:%2eidentifier */] === pluginIdentifier && ext !== _telemetryInitializerPlugin) {\n thePlugin = ext;\n return -1;\n }\n if (ext.getChannel) {\n channelHosts[_DYN_PUSH /* @min:%2epush */](ext);\n }\n });\n if (!thePlugin && channelHosts[_DYN_LENGTH /* @min:%2elength */] > 0) {\n arrForEach(channelHosts, function (host) {\n thePlugin = host.getChannel(pluginIdentifier);\n if (!thePlugin) {\n return -1;\n }\n });\n }\n if (thePlugin) {\n theExt = {\n plugin: thePlugin,\n setEnabled: function (enabled) {\n _getPluginState(thePlugin)[STR_DISABLED] = !enabled;\n },\n isEnabled: function () {\n var pluginState = _getPluginState(thePlugin);\n return !pluginState[_DYN_TEARDOWN /* @min:%2eteardown */] && !pluginState[STR_DISABLED];\n },\n remove: function (isAsync, removeCb) {\n if (isAsync === void 0) {\n isAsync = true;\n }\n var pluginsToRemove = [thePlugin];\n var unloadState = {\n reason: 1 /* TelemetryUnloadReason.PluginUnload */,\n isAsync: isAsync\n };\n _removePlugins(pluginsToRemove, unloadState, function (removed) {\n if (removed) {\n // Re-Initialize the plugin chain\n _initPluginChain({\n reason: 32 /* TelemetryUpdateReason.PluginRemoved */,\n removed: pluginsToRemove\n });\n }\n removeCb && removeCb(removed);\n });\n }\n };\n }\n return theExt;\n }\n function _getPluginChain() {\n if (!_pluginChain) {\n // copy the collection of extensions\n var extensions = (_extensions || []).slice();\n // During add / remove this may get called again, so don't read if already present\n if (arrIndexOf(extensions, _telemetryInitializerPlugin) === -1) {\n extensions[_DYN_PUSH /* @min:%2epush */](_telemetryInitializerPlugin);\n }\n _pluginChain = createTelemetryProxyChain(sortPlugins(extensions), _configHandler.cfg, _self);\n }\n return _pluginChain;\n }\n function _removePlugins(thePlugins, unloadState, removeComplete) {\n if (thePlugins && thePlugins[_DYN_LENGTH /* @min:%2elength */] > 0) {\n var unloadChain = createTelemetryProxyChain(thePlugins, _configHandler.cfg, _self);\n var unloadCtx = createProcessTelemetryUnloadContext(unloadChain, _self);\n unloadCtx[_DYN_ON_COMPLETE /* @min:%2eonComplete */](function () {\n var removed = false;\n // Remove the listed config extensions\n var newConfigExtensions = [];\n arrForEach(_configExtensions, function (plugin, idx) {\n if (!_isPluginPresent(plugin, thePlugins)) {\n newConfigExtensions[_DYN_PUSH /* @min:%2epush */](plugin);\n } else {\n removed = true;\n }\n });\n _configExtensions = newConfigExtensions;\n _pluginVersionString = null;\n _pluginVersionStringArr = null;\n // Re-Create the channel config\n var newChannelConfig = [];\n if (_channelConfig) {\n arrForEach(_channelConfig, function (queue, idx) {\n var newQueue = [];\n arrForEach(queue, function (channel) {\n if (!_isPluginPresent(channel, thePlugins)) {\n newQueue[_DYN_PUSH /* @min:%2epush */](channel);\n } else {\n removed = true;\n }\n });\n newChannelConfig[_DYN_PUSH /* @min:%2epush */](newQueue);\n });\n _channelConfig = newChannelConfig;\n }\n removeComplete && removeComplete(removed);\n _startLogPoller();\n });\n unloadCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](unloadState);\n } else {\n removeComplete(false);\n }\n }\n function _flushInternalLogs() {\n if (_logger && _logger.queue) {\n var queue = _logger.queue.slice(0);\n _logger.queue[_DYN_LENGTH /* @min:%2elength */] = 0;\n arrForEach(queue, function (logMessage) {\n var item = {\n name: _internalLogsEventName ? _internalLogsEventName : \"InternalMessageId: \" + logMessage[_DYN_MESSAGE_ID /* @min:%2emessageId */],\n iKey: _instrumentationKey,\n time: toISOString(new Date()),\n baseType: _InternalLogMessage.dataType,\n baseData: {\n message: logMessage[_DYN_MESSAGE /* @min:%2emessage */]\n }\n };\n _self.track(item);\n });\n }\n }\n function _flushChannels(isAsync, callBack, sendReason, cbTimeout) {\n // Setting waiting to one so that we don't call the callBack until we finish iterating\n var waiting = 1;\n var doneIterating = false;\n var cbTimer = null;\n cbTimeout = cbTimeout || 5000;\n function doCallback() {\n waiting--;\n if (doneIterating && waiting === 0) {\n cbTimer && cbTimer[_DYN_CANCEL /* @min:%2ecancel */]();\n cbTimer = null;\n callBack && callBack(doneIterating);\n callBack = null;\n }\n }\n if (_channels && _channels[_DYN_LENGTH /* @min:%2elength */] > 0) {\n var flushCtx = _createTelCtx()[_DYN_CREATE_NEW /* @min:%2ecreateNew */](_channels);\n flushCtx.iterate(function (plugin) {\n if (plugin.flush) {\n waiting++;\n var handled_1 = false;\n // Not all channels will call this callback for every scenario\n if (!plugin.flush(isAsync, function () {\n handled_1 = true;\n doCallback();\n }, sendReason)) {\n if (!handled_1) {\n // If any channel doesn't return true and it didn't call the callback, then we should assume that the callback\n // will never be called, so use a timeout to allow the channel(s) some time to \"finish\" before triggering any\n // followup function (such as unloading)\n if (isAsync && cbTimer == null) {\n cbTimer = scheduleTimeout(function () {\n cbTimer = null;\n doCallback();\n }, cbTimeout);\n } else {\n doCallback();\n }\n }\n }\n }\n });\n }\n doneIterating = true;\n doCallback();\n return true;\n }\n function _initPerfManager() {\n // Save the previous config based performance manager creator to avoid creating new perf manager instances if unchanged\n var prevCfgPerfMgr;\n // Will get recalled if any referenced config values are changed\n _addUnloadHook(_configHandler[_DYN_WATCH /* @min:%2ewatch */](function (details) {\n var enablePerfMgr = details.cfg.enablePerfMgr;\n if (enablePerfMgr) {\n var createPerfMgr = details.cfg[STR_CREATE_PERF_MGR /* @min:%2ecreatePerfMgr */];\n // for preCfgPerfMgr = createPerfMgr = null\n // initial createPerfMgr function should be _createPerfManager\n if (prevCfgPerfMgr !== createPerfMgr || !prevCfgPerfMgr) {\n if (!createPerfMgr) {\n createPerfMgr = _createPerfManager;\n }\n // Set the performance manager creation function if not defined\n getSetValue(details.cfg, STR_CREATE_PERF_MGR, createPerfMgr);\n prevCfgPerfMgr = createPerfMgr;\n // Remove any existing config based performance manager\n _cfgPerfManager = null;\n }\n // Only create the performance manager if it's not already created or manually set\n if (!_perfManager && !_cfgPerfManager && isFunction(createPerfMgr)) {\n // Create a new config based performance manager\n _cfgPerfManager = createPerfMgr(_self, _self[_DYN_GET_NOTIFY_MGR /* @min:%2egetNotifyMgr */]());\n }\n } else {\n // Remove any existing config based performance manager\n _cfgPerfManager = null;\n // Clear the previous cached value so it can be GC'd\n prevCfgPerfMgr = null;\n }\n }));\n }\n function _doUpdate(updateState) {\n var updateCtx = createProcessTelemetryUpdateContext(_getPluginChain(), _self);\n updateCtx[_DYN_ON_COMPLETE /* @min:%2eonComplete */](_startLogPoller);\n if (!_self._updateHook || _self._updateHook(updateCtx, updateState) !== true) {\n updateCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](updateState);\n }\n }\n function _logOrThrowError(message) {\n var logger = _self[_DYN_LOGGER /* @min:%2elogger */];\n if (logger) {\n // there should always be a logger\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 73 /* _eInternalMessageId.PluginException */, message);\n _startLogPoller();\n } else {\n throwError(message);\n }\n }\n function _notifyInvalidEvent(telemetryItem) {\n var manager = _self[_DYN_GET_NOTIFY_MGR /* @min:%2egetNotifyMgr */]();\n if (manager) {\n manager[STR_EVENTS_DISCARDED /* @min:%2eeventsDiscarded */]([telemetryItem], 2 /* eEventsDiscardedReason.InvalidEvent */);\n }\n }\n function _addUnloadHook(hooks) {\n _hookContainer.add(hooks);\n }\n });\n }\n // Removed Stub for AppInsightsCore.prototype.initialize.\n // Removed Stub for AppInsightsCore.prototype.getChannels.\n // Removed Stub for AppInsightsCore.prototype.track.\n // Removed Stub for AppInsightsCore.prototype.getProcessTelContext.\n // Removed Stub for AppInsightsCore.prototype.getNotifyMgr.\n // Removed Stub for AppInsightsCore.prototype.addNotificationListener.\n // Removed Stub for AppInsightsCore.prototype.removeNotificationListener.\n // Removed Stub for AppInsightsCore.prototype.getCookieMgr.\n // Removed Stub for AppInsightsCore.prototype.setCookieMgr.\n // Removed Stub for AppInsightsCore.prototype.getPerfMgr.\n // Removed Stub for AppInsightsCore.prototype.setPerfMgr.\n // Removed Stub for AppInsightsCore.prototype.eventCnt.\n // Removed Stub for AppInsightsCore.prototype.pollInternalLogs.\n // Removed Stub for AppInsightsCore.prototype.stopPollingInternalLogs.\n // Removed Stub for AppInsightsCore.prototype.addTelemetryInitializer.\n // Removed Stub for AppInsightsCore.prototype.unload.\n // Removed Stub for AppInsightsCore.prototype.getPlugin.\n // Removed Stub for AppInsightsCore.prototype.addPlugin.\n // Removed Stub for AppInsightsCore.prototype.updateCfg.\n // Removed Stub for AppInsightsCore.prototype.evtNamespace.\n // Removed Stub for AppInsightsCore.prototype.addUnloadCb.\n // Removed Stub for AppInsightsCore.prototype.flush.\n // Removed Stub for AppInsightsCore.prototype.getTraceCtx.\n // Removed Stub for AppInsightsCore.prototype.setTraceCtx.\n // Removed Stub for AppInsightsCore.prototype.addUnloadHook.\n // Removed Stub for AppInsightsCore.prototype.onCfgChange.\n // Removed Stub for AppInsightsCore.prototype.activeStatus.\n // Removed Stub for AppInsightsCore.prototype._setPendingStatus.\n // Removed Stub for AppInsightsCore.prototype.releaseQueue.\n // Removed Stub for AppInsightsCore.prototype._updateHook.\n // This is a workaround for an IE bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n AppInsightsCore.__ieDyn = 1;\n return AppInsightsCore;\n}();\nexport { AppInsightsCore };\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { dumpObj } from \"@nevware21/ts-utils\";\nimport { _DYN_ITEMS_RECEIVED, _DYN_LENGTH, _DYN_NAME } from \"../__DynamicConstants\";\nimport { _throwInternal } from \"./DiagnosticLogger\";\nimport { getJSON } from \"./EnvUtils\";\n/**\r\n * Parses the response from the backend.\r\n * @param response - XMLHttpRequest or XDomainRequest response\r\n */\nexport function parseResponse(response, diagLog) {\n try {\n if (response && response !== \"\") {\n var result = getJSON().parse(response);\n if (result && result[_DYN_ITEMS_RECEIVED /* @min:%2eitemsReceived */] && result[_DYN_ITEMS_RECEIVED /* @min:%2eitemsReceived */] >= result.itemsAccepted && result.itemsReceived - result.itemsAccepted === result.errors[_DYN_LENGTH /* @min:%2elength */]) {\n return result;\n }\n }\n } catch (e) {\n _throwInternal(diagLog, 1 /* eLoggingSeverity.CRITICAL */, 43 /* _eInternalMessageId.InvalidBackendResponse */, \"Cannot parse the response. \" + (e[_DYN_NAME /* @min:%2ename */] || dumpObj(e)), {\n response: response\n });\n }\n return null;\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { createPromise, doAwaitResponse } from \"@nevware21/ts-async\";\nimport { arrForEach, dumpObj, getNavigator, getWindow, isFunction, objKeys } from \"@nevware21/ts-utils\";\nimport { _DYN_DATA, _DYN_HEADERS, _DYN_INITIALIZE, _DYN_LENGTH, _DYN_MESSAGE, _DYN_REPLACE, _DYN_STATUS, _DYN_TIMEOUT, _DYN_TO_LOWER_CASE, _DYN_URL_STRING, _DYN_VALUE, _DYN__DO_TEARDOWN } from \"../__DynamicConstants\";\nimport { DisabledPropertyName } from \"./Constants\";\nimport { _throwInternal, _warnToConsole } from \"./DiagnosticLogger\";\nimport { getLocation, isBeaconsSupported, isFetchSupported, isXhrSupported, useXDomainRequest } from \"./EnvUtils\";\nimport { _getAllResponseHeaders, formatErrorMessageXdr, formatErrorMessageXhr, getResponseText, openXhr } from \"./HelperFuncs\";\nvar STR_EMPTY = \"\";\nvar STR_NO_RESPONSE_BODY = \"NoResponseBody\";\nvar _noResponseQs = \"&\" + STR_NO_RESPONSE_BODY + \"=true\";\nvar STR_POST_METHOD = \"POST\";\n/**\r\n * This Internal component\r\n * Manager SendPost functions\r\n * SendPostManger\r\n * @internal for internal use only\r\n */\nvar SenderPostManager = /** @class */function () {\n function SenderPostManager() {\n var _syncFetchPayload = 0; // Keep track of the outstanding sync fetch payload total (as sync fetch has limits)\n var _enableSendPromise;\n var _isInitialized;\n var _diagLog;\n var _isOneDs;\n var _onCompleteFuncs;\n var _disableCredentials;\n var _fetchCredentials;\n var _fallbackInst;\n var _disableXhr;\n var _disableBeacon;\n var _disableBeaconSync;\n var _disableFetchKeepAlive;\n var _addNoResponse;\n var _timeoutWrapper;\n dynamicProto(SenderPostManager, this, function (_self, _base) {\n var _sendCredentials = true; // for 1ds\n _initDefaults();\n _self[_DYN_INITIALIZE /* @min:%2einitialize */] = function (config, diagLog) {\n _diagLog = diagLog;\n if (_isInitialized) {\n _throwInternal(_diagLog, 1 /* eLoggingSeverity.CRITICAL */, 28 /* _eInternalMessageId.SenderNotInitialized */, \"Sender is already initialized\");\n }\n _self.SetConfig(config);\n _isInitialized = true;\n };\n _self[\"_getDbgPlgTargets\"] = function () {\n return [_isInitialized, _isOneDs, _disableCredentials, _enableSendPromise];\n };\n // This componet might get its config from sender, offline sender, 1ds post\n // so set this function to mock dynamic changes\n _self.SetConfig = function (config) {\n try {\n _onCompleteFuncs = config.senderOnCompleteCallBack || {};\n _disableCredentials = !!config.disableCredentials;\n _fetchCredentials = config.fetchCredentials;\n _isOneDs = !!config.isOneDs;\n _enableSendPromise = !!config.enableSendPromise;\n _disableXhr = !!config.disableXhr;\n _disableBeacon = !!config.disableBeacon;\n _disableBeaconSync = !!config.disableBeaconSync;\n _timeoutWrapper = config.timeWrapper;\n _addNoResponse = !!config.addNoResponse;\n _disableFetchKeepAlive = !!config.disableFetchKeepAlive;\n _fallbackInst = {\n sendPOST: _xhrSender\n };\n if (!_isOneDs) {\n _sendCredentials = false; // for appInsights, set it to false always\n }\n if (_disableCredentials) {\n var location_1 = getLocation();\n if (location_1 && location_1.protocol && location_1.protocol[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]() === \"file:\") {\n // Special case where a local html file fails with a CORS error on Chromium browsers\n _sendCredentials = false;\n }\n }\n return true;\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n return false;\n };\n _self.getSyncFetchPayload = function () {\n return _syncFetchPayload;\n };\n _self.getSenderInst = function (transports, sync) {\n if (transports && transports[_DYN_LENGTH /* @min:%2elength */]) {\n return _getSenderInterface(transports, sync);\n }\n return null;\n };\n _self.getFallbackInst = function () {\n return _fallbackInst;\n };\n _self[_DYN__DO_TEARDOWN /* @min:%2e_doTeardown */] = function (unloadCtx, unloadState) {\n _initDefaults();\n };\n /**\r\n * success handler\r\n */\n function _onSuccess(res, onComplete) {\n _doOnComplete(onComplete, 200, {}, res);\n }\n /**\r\n * error handler\r\n */\n function _onError(message, onComplete) {\n _throwInternal(_diagLog, 2 /* eLoggingSeverity.WARNING */, 26 /* _eInternalMessageId.OnError */, \"Failed to send telemetry.\", {\n message: message\n });\n _doOnComplete(onComplete, 400, {});\n }\n function _onNoPayloadUrl(onComplete) {\n _onError(\"No endpoint url is provided for the batch\", onComplete);\n }\n function _getSenderInterface(transports, syncSupport) {\n var transportType = 0 /* TransportType.NotSet */;\n var sendPostFunc = null;\n var lp = 0;\n while (sendPostFunc == null && lp < transports[_DYN_LENGTH /* @min:%2elength */]) {\n transportType = transports[lp];\n if (!_disableXhr && transportType === 1 /* TransportType.Xhr */) {\n if (useXDomainRequest()) {\n // IE 8 and 9\n sendPostFunc = _xdrSender;\n } else if (isXhrSupported()) {\n sendPostFunc = _xhrSender;\n }\n } else if (transportType === 2 /* TransportType.Fetch */ && isFetchSupported(syncSupport) && (!syncSupport || !_disableFetchKeepAlive)) {\n sendPostFunc = _doFetchSender;\n } else if (transportType === 3 /* TransportType.Beacon */ && isBeaconsSupported() && (syncSupport ? !_disableBeaconSync : !_disableBeacon)) {\n sendPostFunc = _beaconSender;\n }\n lp++;\n }\n if (sendPostFunc) {\n return {\n _transport: transportType,\n _isSync: syncSupport,\n sendPOST: sendPostFunc\n };\n }\n return null;\n }\n function _doOnComplete(oncomplete, status, headers, response) {\n try {\n oncomplete && oncomplete(status, headers, response);\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n }\n function _doBeaconSend(payload, oncomplete) {\n var nav = getNavigator();\n var url = payload[_DYN_URL_STRING /* @min:%2eurlString */];\n if (!url) {\n _onNoPayloadUrl(oncomplete);\n // return true here, because we don't want to retry it with fallback sender\n return true;\n }\n url = payload[_DYN_URL_STRING /* @min:%2eurlString */] + (_addNoResponse ? _noResponseQs : STR_EMPTY);\n var data = payload[_DYN_DATA /* @min:%2edata */];\n // Chrome only allows CORS-safelisted values for the sendBeacon data argument\n // see: https://bugs.chromium.org/p/chromium/issues/detail?id=720283\n // Chrome only allows CORS-safelisted values for the sendBeacon data argument\n // see: https://bugs.chromium.org/p/chromium/issues/detail?id=720283\n var plainTextBatch = _isOneDs ? data : new Blob([data], {\n type: \"text/plain;charset=UTF-8\"\n });\n // The sendBeacon method returns true if the user agent is able to successfully queue the data for transfer. Otherwise it returns false.\n var queued = nav.sendBeacon(url, plainTextBatch);\n return queued;\n }\n /**\r\n * Send Beacon API request\r\n * @param payload - The data payload to be sent.\r\n * @param sync - not used\r\n * Note: Beacon API does not support custom headers and we are not able to get\r\n * appId from the backend for the correct correlation.\r\n */\n function _beaconSender(payload, oncomplete, sync) {\n var data = payload[_DYN_DATA /* @min:%2edata */];\n try {\n if (data) {\n // The sendBeacon method returns true if the user agent is able to successfully queue the data for transfer. Otherwise it returns false.\n if (!_doBeaconSend(payload, oncomplete)) {\n var onRetry = _onCompleteFuncs && _onCompleteFuncs.beaconOnRetry;\n if (onRetry && isFunction(onRetry)) {\n onRetry(payload, oncomplete, _doBeaconSend);\n } else {\n _fallbackInst && _fallbackInst.sendPOST(payload, oncomplete, true);\n _throwInternal(_diagLog, 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". \" + \"Failed to send telemetry with Beacon API, retried with normal sender.\");\n }\n } else {\n // if can send\n _onSuccess(STR_EMPTY, oncomplete);\n }\n }\n } catch (e) {\n _isOneDs && _warnToConsole(_diagLog, \"Failed to send telemetry using sendBeacon API. Ex:\" + dumpObj(e));\n _doOnComplete(oncomplete, _isOneDs ? 0 : 400, {}, STR_EMPTY);\n }\n return;\n }\n /**\r\n * Send XMLHttpRequest\r\n * @param payload - The data payload to be sent.\r\n * @param sync - Indicates if the request should be sent synchronously\r\n */\n function _xhrSender(payload, oncomplete, sync) {\n //let internalPayload = payload as IInternalPayloadData;\n var thePromise;\n var resolveFunc;\n var rejectFunc;\n var headers = payload[_DYN_HEADERS /* @min:%2eheaders */] || {};\n if (!sync && _enableSendPromise) {\n thePromise = createPromise(function (resolve, reject) {\n resolveFunc = resolve;\n rejectFunc = reject;\n });\n }\n if (_isOneDs && sync && payload.disableXhrSync) {\n sync = false;\n }\n //const xhr = new XMLHttpRequest();\n var endPointUrl = payload[_DYN_URL_STRING /* @min:%2eurlString */];\n if (!endPointUrl) {\n _onNoPayloadUrl(oncomplete);\n resolveFunc && resolveFunc(false);\n return;\n }\n var xhr = openXhr(STR_POST_METHOD, endPointUrl, _sendCredentials, true, sync, payload[_DYN_TIMEOUT /* @min:%2etimeout */]);\n if (!_isOneDs) {\n // application/json should NOT add to 1ds post by default\n xhr.setRequestHeader(\"Content-type\", \"application/json\");\n }\n arrForEach(objKeys(headers), function (headerName) {\n xhr.setRequestHeader(headerName, headers[headerName]);\n });\n xhr.onreadystatechange = function () {\n if (!_isOneDs) {\n _doOnReadyFunc(xhr);\n if (xhr.readyState === 4) {\n resolveFunc && resolveFunc(true);\n }\n }\n };\n xhr.onload = function () {\n if (_isOneDs) {\n _doOnReadyFunc(xhr);\n }\n };\n function _doOnReadyFunc(xhr) {\n var onReadyFunc = _onCompleteFuncs && _onCompleteFuncs.xhrOnComplete;\n var onReadyFuncExist = onReadyFunc && isFunction(onReadyFunc);\n if (onReadyFuncExist) {\n onReadyFunc(xhr, oncomplete, payload);\n } else {\n var response = getResponseText(xhr);\n _doOnComplete(oncomplete, xhr[_DYN_STATUS /* @min:%2estatus */], _getAllResponseHeaders(xhr, _isOneDs), response);\n }\n }\n xhr.onerror = function (event) {\n _doOnComplete(oncomplete, _isOneDs ? xhr[_DYN_STATUS /* @min:%2estatus */] : 400, _getAllResponseHeaders(xhr, _isOneDs), _isOneDs ? STR_EMPTY : formatErrorMessageXhr(xhr));\n rejectFunc && rejectFunc(event);\n };\n xhr.ontimeout = function () {\n _doOnComplete(oncomplete, _isOneDs ? xhr[_DYN_STATUS /* @min:%2estatus */] : 500, _getAllResponseHeaders(xhr, _isOneDs), _isOneDs ? STR_EMPTY : formatErrorMessageXhr(xhr));\n resolveFunc && resolveFunc(false);\n };\n xhr.send(payload[_DYN_DATA /* @min:%2edata */]);\n return thePromise;\n }\n /**\r\n * Send fetch API request\r\n * @param payload - The data payload to be sent.\r\n * @param sync - For fetch this identifies whether we are \"unloading\" (false) or a normal request\r\n */\n function _doFetchSender(payload, oncomplete, sync) {\n var _a;\n var endPointUrl = payload[_DYN_URL_STRING /* @min:%2eurlString */];\n var batch = payload[_DYN_DATA /* @min:%2edata */];\n var plainTextBatch = _isOneDs ? batch : new Blob([batch], {\n type: \"application/json\"\n });\n var thePromise;\n var resolveFunc;\n var rejectFunc;\n var requestHeaders = new Headers();\n var batchLength = batch[_DYN_LENGTH /* @min:%2elength */];\n var ignoreResponse = false;\n var responseHandled = false;\n var headers = payload[_DYN_HEADERS /* @min:%2eheaders */] || {};\n //TODO: handle time out for 1ds\n var init = (_a = {\n method: STR_POST_METHOD,\n body: plainTextBatch\n }, _a[DisabledPropertyName] = true // Mark so we don't attempt to track this request\n , _a);\n // Only add headers if there are headers to add, due to issue with some polyfills\n if (payload.headers && objKeys(payload.headers)[_DYN_LENGTH /* @min:%2elength */] > 0) {\n arrForEach(objKeys(headers), function (headerName) {\n requestHeaders.append(headerName, headers[headerName]);\n });\n init[_DYN_HEADERS /* @min:%2eheaders */] = requestHeaders;\n }\n if (_fetchCredentials) {\n // if user passed in this value via post channel (1ds), then use it\n init.credentials = _fetchCredentials;\n } else if (_sendCredentials && _isOneDs) {\n // for 1ds, Don't send credentials when URL is file://\n init.credentials = \"include\";\n }\n if (sync) {\n init.keepalive = true;\n _syncFetchPayload += batchLength;\n if (_isOneDs) {\n if (payload[\"_sendReason\"] === 2 /* SendRequestReason.Unload */) {\n // As a sync request (during unload), it is unlikely that we will get a chance to process the response so\n // just like beacon send assume that the events have been accepted and processed\n ignoreResponse = true;\n if (_addNoResponse) {\n endPointUrl += _noResponseQs;\n }\n }\n } else {\n // for appinsights, set to true for all sync request\n ignoreResponse = true;\n }\n }\n var request = new Request(endPointUrl, init);\n try {\n // Also try and tag the request (just in case the value in init is not copied over)\n request[DisabledPropertyName] = true;\n } catch (e) {\n // If the environment has locked down the XMLHttpRequest (preventExtensions and/or freeze), this would\n // cause the request to fail and we no telemetry would be sent\n }\n if (!sync && _enableSendPromise) {\n thePromise = createPromise(function (resolve, reject) {\n resolveFunc = resolve;\n rejectFunc = reject;\n });\n }\n if (!endPointUrl) {\n _onNoPayloadUrl(oncomplete);\n resolveFunc && resolveFunc(false);\n return;\n }\n function _handleError(res) {\n // In case there is an error in the request. Set the status to 0 for 1ds and 400 for appInsights\n // so that the events can be retried later.\n _doOnComplete(oncomplete, _isOneDs ? 0 : 400, {}, _isOneDs ? STR_EMPTY : res);\n }\n function _onFetchComplete(response, payload, value) {\n var status = response[_DYN_STATUS /* @min:%2estatus */];\n var onCompleteFunc = _onCompleteFuncs.fetchOnComplete;\n if (onCompleteFunc && isFunction(onCompleteFunc)) {\n onCompleteFunc(response, oncomplete, value || STR_EMPTY, payload);\n } else {\n _doOnComplete(oncomplete, status, {}, value || STR_EMPTY);\n }\n }\n try {\n doAwaitResponse(fetch(_isOneDs ? endPointUrl : request, _isOneDs ? init : null), function (result) {\n if (sync) {\n _syncFetchPayload -= batchLength;\n batchLength = 0;\n }\n if (!responseHandled) {\n responseHandled = true;\n if (!result.rejected) {\n var response_1 = result[_DYN_VALUE /* @min:%2evalue */];\n try {\n /**\r\n * The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500.\r\n * Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure\r\n * or if anything prevented the request from completing.\r\n */\n if (!_isOneDs && !response_1.ok) {\n // this is for appInsights only\n _handleError(response_1.statusText);\n resolveFunc && resolveFunc(false);\n } else {\n if (_isOneDs && !response_1.body) {\n _onFetchComplete(response_1, null, STR_EMPTY);\n resolveFunc && resolveFunc(true);\n } else {\n doAwaitResponse(response_1.text(), function (resp) {\n _onFetchComplete(response_1, payload, resp[_DYN_VALUE /* @min:%2evalue */]);\n resolveFunc && resolveFunc(true);\n });\n }\n }\n } catch (e) {\n _handleError(dumpObj(e));\n rejectFunc && rejectFunc(e);\n }\n } else {\n _handleError(result.reason && result.reason[_DYN_MESSAGE /* @min:%2emessage */]);\n rejectFunc && rejectFunc(result.reason);\n }\n }\n });\n } catch (e) {\n if (!responseHandled) {\n _handleError(dumpObj(e));\n rejectFunc && rejectFunc(e);\n }\n }\n if (ignoreResponse && !responseHandled) {\n // Assume success during unload processing as we most likely won't get the response\n responseHandled = true;\n _doOnComplete(oncomplete, 200, {});\n resolveFunc && resolveFunc(true);\n }\n if (_isOneDs && !responseHandled && payload[_DYN_TIMEOUT /* @min:%2etimeout */] > 0) {\n // Simulate timeout\n _timeoutWrapper && _timeoutWrapper.set(function () {\n if (!responseHandled) {\n // Assume a 500 response (which will cause a retry)\n responseHandled = true;\n _doOnComplete(oncomplete, 500, {});\n resolveFunc && resolveFunc(true);\n }\n }, payload[_DYN_TIMEOUT /* @min:%2etimeout */]);\n }\n return thePromise;\n }\n /**\r\n * Send XDomainRequest\r\n * @param payload - The data payload to be sent.\r\n * @param sync - Indicates if the request should be sent synchronously\r\n *\r\n * Note: XDomainRequest does not support sync requests. This 'isAsync' parameter is added\r\n * to maintain consistency with the xhrSender's contract\r\n * Note: XDomainRequest does not support custom headers and we are not able to get\r\n * appId from the backend for the correct correlation.\r\n */\n function _xdrSender(payload, oncomplete, sync) {\n // It doesn't support custom headers, so no action is taken with current requestHeaders\n var _window = getWindow();\n var xdr = new XDomainRequest();\n var data = payload[_DYN_DATA /* @min:%2edata */];\n xdr.onload = function () {\n var response = getResponseText(xdr);\n var onloadFunc = _onCompleteFuncs && _onCompleteFuncs.xdrOnComplete;\n if (onloadFunc && isFunction(onloadFunc)) {\n onloadFunc(xdr, oncomplete, payload);\n } else {\n _doOnComplete(oncomplete, 200, {}, response);\n }\n };\n xdr.onerror = function () {\n _doOnComplete(oncomplete, 400, {}, _isOneDs ? STR_EMPTY : formatErrorMessageXdr(xdr));\n };\n xdr.ontimeout = function () {\n _doOnComplete(oncomplete, 500, {});\n };\n xdr.onprogress = function () {};\n // XDomainRequest requires the same protocol as the hosting page.\n // If the protocol doesn't match, we can't send the telemetry :(.\n var hostingProtocol = _window && _window.location && _window.location.protocol || \"\";\n var endpoint = payload[_DYN_URL_STRING /* @min:%2eurlString */];\n if (!endpoint) {\n _onNoPayloadUrl(oncomplete);\n return;\n }\n if (!_isOneDs && endpoint.lastIndexOf(hostingProtocol, 0) !== 0) {\n var msg = \"Cannot send XDomain request. The endpoint URL protocol doesn't match the hosting page protocol.\";\n _throwInternal(_diagLog, 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". \" + msg);\n _onError(msg, oncomplete);\n return;\n }\n var endpointUrl = _isOneDs ? endpoint : endpoint[_DYN_REPLACE /* @min:%2ereplace */](/^(https?:)/, \"\");\n xdr.open(STR_POST_METHOD, endpointUrl);\n if (payload[_DYN_TIMEOUT /* @min:%2etimeout */]) {\n xdr[_DYN_TIMEOUT /* @min:%2etimeout */] = payload[_DYN_TIMEOUT /* @min:%2etimeout */];\n }\n xdr.send(data);\n if (_isOneDs && sync) {\n _timeoutWrapper && _timeoutWrapper.set(function () {\n xdr.send(data);\n }, 0);\n } else {\n xdr.send(data);\n }\n }\n function _initDefaults() {\n _syncFetchPayload = 0;\n _isInitialized = false;\n _enableSendPromise = false;\n _diagLog = null;\n _isOneDs = null;\n _onCompleteFuncs = null;\n _disableCredentials = null;\n _fetchCredentials = null;\n _fallbackInst = null;\n _disableXhr = false;\n _disableBeacon = false;\n _disableBeaconSync = false;\n _disableFetchKeepAlive = false;\n _addNoResponse = false;\n _timeoutWrapper = null;\n }\n });\n }\n // Removed Stub for SenderPostManager.prototype.initialize.\n // Removed Stub for SenderPostManager.prototype.getSyncFetchPayload.\n // Removed Stub for SenderPostManager.prototype.SetConfig.\n // Removed Stub for SenderPostManager.prototype.getSenderInst.\n // Removed Stub for SenderPostManager.prototype.getFallbackInst.\n // Removed Stub for SenderPostManager.prototype._doTeardown.\n // This is a workaround for an IE bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n SenderPostManager.__ieDyn = 1;\n return SenderPostManager;\n}();\nexport { SenderPostManager };\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { arrForEach, arrIndexOf, getDocument, getWindow, isArray, objForEachKey, objKeys } from \"@nevware21/ts-utils\";\nimport { _DYN_EVT_NAME, _DYN_LENGTH, _DYN_PUSH, _DYN_REPLACE, _DYN_SPLICE, _DYN_SPLIT, _DYN_TYPE } from \"../__DynamicConstants\";\nimport { createElmNodeData, createUniqueNamespace } from \"./DataCacheHelper\";\nimport { STR_EMPTY } from \"./InternalConstants\";\n// Added to help with minfication\nvar strOnPrefix = \"on\";\nvar strAttachEvent = \"attachEvent\";\nvar strAddEventHelper = \"addEventListener\";\nvar strDetachEvent = \"detachEvent\";\nvar strRemoveEventListener = \"removeEventListener\";\nvar strEvents = \"events\";\nvar strVisibilityChangeEvt = \"visibilitychange\";\nvar strPageHide = \"pagehide\";\nvar strPageShow = \"pageshow\";\nvar strUnload = \"unload\";\nvar strBeforeUnload = \"beforeunload\";\nvar strPageHideNamespace = createUniqueNamespace(\"aiEvtPageHide\");\nvar strPageShowNamespace = createUniqueNamespace(\"aiEvtPageShow\");\nvar rRemoveEmptyNs = /\\.[\\.]+/g;\nvar rRemoveTrailingEmptyNs = /[\\.]+$/;\nvar _guid = 1;\nvar elmNodeData = createElmNodeData(\"events\");\nvar eventNamespace = /^([^.]*)(?:\\.(.+)|)/;\nfunction _normalizeNamespace(name) {\n if (name && name[_DYN_REPLACE /* @min:%2ereplace */]) {\n return name[_DYN_REPLACE /* @min:%2ereplace */](/^[\\s\\.]+|(?=[\\s\\.])[\\.\\s]+$/g, STR_EMPTY);\n }\n return name;\n}\nfunction _getEvtNamespace(eventName, evtNamespace) {\n if (evtNamespace) {\n var theNamespace_1 = STR_EMPTY;\n if (isArray(evtNamespace)) {\n theNamespace_1 = STR_EMPTY;\n arrForEach(evtNamespace, function (name) {\n name = _normalizeNamespace(name);\n if (name) {\n if (name[0] !== \".\") {\n name = \".\" + name;\n }\n theNamespace_1 += name;\n }\n });\n } else {\n theNamespace_1 = _normalizeNamespace(evtNamespace);\n }\n if (theNamespace_1) {\n if (theNamespace_1[0] !== \".\") {\n theNamespace_1 = \".\" + theNamespace_1;\n }\n // We may only have the namespace and not an eventName\n eventName = (eventName || STR_EMPTY) + theNamespace_1;\n }\n }\n var parsedEvent = eventNamespace.exec(eventName || STR_EMPTY) || [];\n return {\n type: parsedEvent[1],\n ns: (parsedEvent[2] || STR_EMPTY).replace(rRemoveEmptyNs, \".\").replace(rRemoveTrailingEmptyNs, STR_EMPTY)[_DYN_SPLIT /* @min:%2esplit */](\".\").sort().join(\".\")\n };\n}\n/**\r\n * Get all of the registered events on the target object, this is primarily used for testing cleanup but may also be used by\r\n * applications to remove their own events\r\n * @param target - The EventTarget that has registered events\r\n * @param eventName - [Optional] The name of the event to return the registered handlers and full name (with namespaces)\r\n * @param evtNamespace - [Optional] Additional namespace(s) to append to the event listeners so they can be uniquely identified and removed based on this namespace,\r\n * if the eventName also includes a namespace the namespace(s) are merged into a single namespace\r\n */\nexport function __getRegisteredEvents(target, eventName, evtNamespace) {\n var theEvents = [];\n var eventCache = elmNodeData.get(target, strEvents, {}, false);\n var evtName = _getEvtNamespace(eventName, evtNamespace);\n objForEachKey(eventCache, function (evtType, registeredEvents) {\n arrForEach(registeredEvents, function (value) {\n if (!evtName[_DYN_TYPE /* @min:%2etype */] || evtName[_DYN_TYPE /* @min:%2etype */] === value[_DYN_EVT_NAME /* @min:%2eevtName */][_DYN_TYPE /* @min:%2etype */]) {\n if (!evtName.ns || evtName.ns === evtName.ns) {\n theEvents[_DYN_PUSH /* @min:%2epush */]({\n name: value.evtName[_DYN_TYPE /* @min:%2etype */] + (value[_DYN_EVT_NAME /* @min:%2eevtName */].ns ? \".\" + value[_DYN_EVT_NAME /* @min:%2eevtName */].ns : STR_EMPTY),\n handler: value.handler\n });\n }\n }\n });\n });\n return theEvents;\n}\n// Exported for internal unit testing only\nfunction _getRegisteredEvents(target, evtName, addDefault) {\n if (addDefault === void 0) {\n addDefault = true;\n }\n var aiEvts = elmNodeData.get(target, strEvents, {}, addDefault);\n var registeredEvents = aiEvts[evtName];\n if (!registeredEvents) {\n registeredEvents = aiEvts[evtName] = [];\n }\n return registeredEvents;\n}\nfunction _doDetach(obj, evtName, handlerRef, useCapture) {\n if (obj && evtName && evtName[_DYN_TYPE /* @min:%2etype */]) {\n if (obj[strRemoveEventListener]) {\n obj[strRemoveEventListener](evtName[_DYN_TYPE /* @min:%2etype */], handlerRef, useCapture);\n } else if (obj[strDetachEvent]) {\n obj[strDetachEvent](strOnPrefix + evtName[_DYN_TYPE /* @min:%2etype */], handlerRef);\n }\n }\n}\nfunction _doAttach(obj, evtName, handlerRef, useCapture) {\n var result = false;\n if (obj && evtName && evtName[_DYN_TYPE /* @min:%2etype */] && handlerRef) {\n if (obj[strAddEventHelper]) {\n // all browsers except IE before version 9\n obj[strAddEventHelper](evtName[_DYN_TYPE /* @min:%2etype */], handlerRef, useCapture);\n result = true;\n } else if (obj[strAttachEvent]) {\n // IE before version 9\n obj[strAttachEvent](strOnPrefix + evtName[_DYN_TYPE /* @min:%2etype */], handlerRef);\n result = true;\n }\n }\n return result;\n}\nfunction _doUnregister(target, events, evtName, unRegFn) {\n var idx = events[_DYN_LENGTH /* @min:%2elength */];\n while (idx--) {\n var theEvent = events[idx];\n if (theEvent) {\n if (!evtName.ns || evtName.ns === theEvent[_DYN_EVT_NAME /* @min:%2eevtName */].ns) {\n if (!unRegFn || unRegFn(theEvent)) {\n _doDetach(target, theEvent[_DYN_EVT_NAME /* @min:%2eevtName */], theEvent.handler, theEvent.capture);\n // Remove the registered event\n events[_DYN_SPLICE /* @min:%2esplice */](idx, 1);\n }\n }\n }\n }\n}\nfunction _unregisterEvents(target, evtName, unRegFn) {\n if (evtName[_DYN_TYPE /* @min:%2etype */]) {\n _doUnregister(target, _getRegisteredEvents(target, evtName[_DYN_TYPE /* @min:%2etype */]), evtName, unRegFn);\n } else {\n var eventCache = elmNodeData.get(target, strEvents, {});\n objForEachKey(eventCache, function (evtType, events) {\n _doUnregister(target, events, evtName, unRegFn);\n });\n // Cleanup\n if (objKeys(eventCache)[_DYN_LENGTH /* @min:%2elength */] === 0) {\n elmNodeData.kill(target, strEvents);\n }\n }\n}\nexport function mergeEvtNamespace(theNamespace, namespaces) {\n var newNamespaces;\n if (namespaces) {\n if (isArray(namespaces)) {\n newNamespaces = [theNamespace].concat(namespaces);\n } else {\n newNamespaces = [theNamespace, namespaces];\n }\n // resort the namespaces so they are always in order\n newNamespaces = _getEvtNamespace(\"xx\", newNamespaces).ns[_DYN_SPLIT /* @min:%2esplit */](\".\");\n } else {\n newNamespaces = theNamespace;\n }\n return newNamespaces;\n}\n/**\r\n * Binds the specified function to an event, so that the function gets called whenever the event fires on the object\r\n * @param obj - Object to add the event too.\r\n * @param eventName - String that specifies any of the standard DHTML Events without \"on\" prefix, if may also include an optional (dot \".\" prefixed)\r\n * namespaces \"click\" \"click.mynamespace\" in addition to specific namespaces.\r\n * @param handlerRef - Pointer that specifies the function to call when event fires\r\n * @param evtNamespace - [Optional] Additional namespace(s) to append to the event listeners so they can be uniquely identified and removed based on this namespace,\r\n * if the eventName also includes a namespace the namespace(s) are merged into a single namespace\r\n * @param useCapture - [Optional] Defaults to false\r\n * @returns True if the function was bound successfully to the event, otherwise false\r\n */\nexport function eventOn(target, eventName, handlerRef, evtNamespace, useCapture) {\n if (useCapture === void 0) {\n useCapture = false;\n }\n var result = false;\n if (target) {\n try {\n var evtName = _getEvtNamespace(eventName, evtNamespace);\n result = _doAttach(target, evtName, handlerRef, useCapture);\n if (result && elmNodeData.accept(target)) {\n var registeredEvent = {\n guid: _guid++,\n evtName: evtName,\n handler: handlerRef,\n capture: useCapture\n };\n _getRegisteredEvents(target, evtName.type)[_DYN_PUSH /* @min:%2epush */](registeredEvent);\n }\n } catch (e) {\n // Just Ignore any error so that we don't break any execution path\n }\n }\n return result;\n}\n/**\r\n * Removes an event handler for the specified event\r\n * @param Object - to remove the event from\r\n * @param eventName - The name of the event, with optional namespaces or just the namespaces,\r\n * such as \"click\", \"click.mynamespace\" or \".mynamespace\"\r\n * @param handlerRef - The callback function that needs to be removed from the given event, when using a\r\n * namespace (with or without a qualifying event) this may be null to remove all previously attached event handlers\r\n * otherwise this will only remove events with this specific handler.\r\n * @param evtNamespace - [Optional] Additional namespace(s) to append to the event listeners so they can be uniquely identified and removed based on this namespace,\r\n * if the eventName also includes a namespace the namespace(s) are merged into a single namespace\r\n * @param useCapture - [Optional] Defaults to false\r\n */\nexport function eventOff(target, eventName, handlerRef, evtNamespace, useCapture) {\n if (useCapture === void 0) {\n useCapture = false;\n }\n if (target) {\n try {\n var evtName_1 = _getEvtNamespace(eventName, evtNamespace);\n var found_1 = false;\n _unregisterEvents(target, evtName_1, function (regEvent) {\n if (evtName_1.ns && !handlerRef || regEvent.handler === handlerRef) {\n found_1 = true;\n return true;\n }\n return false;\n });\n if (!found_1) {\n // fallback to try and remove as requested\n _doDetach(target, evtName_1, handlerRef, useCapture);\n }\n } catch (e) {\n // Just Ignore any error so that we don't break any execution path\n }\n }\n}\n/**\r\n * Binds the specified function to an event, so that the function gets called whenever the event fires on the object\r\n * @param obj - Object to add the event too.\r\n * @param eventNameWithoutOn - String that specifies any of the standard DHTML Events without \"on\" prefix and optional (dot \".\" prefixed) namespaces \"click\" \"click.mynamespace\".\r\n * @param handlerRef - Pointer that specifies the function to call when event fires\r\n * @param useCapture - [Optional] Defaults to false\r\n * @returns True if the function was bound successfully to the event, otherwise false\r\n */\nexport function attachEvent(obj, eventNameWithoutOn, handlerRef, useCapture) {\n if (useCapture === void 0) {\n useCapture = false;\n }\n return eventOn(obj, eventNameWithoutOn, handlerRef, null, useCapture);\n}\n/**\r\n * Removes an event handler for the specified event\r\n * @param Object - to remove the event from\r\n * @param eventNameWithoutOn - The name of the event, with optional namespaces or just the namespaces,\r\n * such as \"click\", \"click.mynamespace\" or \".mynamespace\"\r\n * @param handlerRef - The callback function that needs to be removed from the given event, when using a\r\n * namespace (with or without a qualifying event) this may be null to remove all previously attached event handlers\r\n * otherwise this will only remove events with this specific handler.\r\n * @param useCapture - [Optional] Defaults to false\r\n */\nexport function detachEvent(obj, eventNameWithoutOn, handlerRef, useCapture) {\n if (useCapture === void 0) {\n useCapture = false;\n }\n eventOff(obj, eventNameWithoutOn, handlerRef, null, useCapture);\n}\n/**\r\n * Trys to add an event handler for the specified event to the window, body and document\r\n * @param eventName - The name of the event\r\n * @param callback - The callback function that needs to be executed for the given event\r\n * @param evtNamespace - [Optional] Namespace(s) to append to the event listeners so they can be uniquely identified and removed based on this namespace.\r\n * @returns - true if the handler was successfully added\r\n */\nexport function addEventHandler(eventName, callback, evtNamespace) {\n var result = false;\n var w = getWindow();\n if (w) {\n result = eventOn(w, eventName, callback, evtNamespace);\n result = eventOn(w[\"body\"], eventName, callback, evtNamespace) || result;\n }\n var doc = getDocument();\n if (doc) {\n result = eventOn(doc, eventName, callback, evtNamespace) || result;\n }\n return result;\n}\n/**\r\n * Trys to remove event handler(s) for the specified event/namespace to the window, body and document\r\n * @param eventName - The name of the event, with optional namespaces or just the namespaces,\r\n * such as \"click\", \"click.mynamespace\" or \".mynamespace\"\r\n * @param callback - The callback function that needs to be removed from the given event, when using a\r\n * namespace (with or without a qualifying event) this may be null to remove all previously attached event handlers\r\n * otherwise this will only remove events with this specific handler.\r\n * @param evtNamespace - [Optional] Namespace(s) to append to the event listeners so they can be uniquely identified and removed based on this namespace.\r\n */\nexport function removeEventHandler(eventName, callback, evtNamespace) {\n var w = getWindow();\n if (w) {\n eventOff(w, eventName, callback, evtNamespace);\n eventOff(w[\"body\"], eventName, callback, evtNamespace);\n }\n var doc = getDocument();\n if (doc) {\n eventOff(doc, eventName, callback, evtNamespace);\n }\n}\n/**\r\n * Bind the listener to the array of events\r\n * @param events - An string array of event names to bind the listener to\r\n * @param listener - The event callback to call when the event is triggered\r\n * @param excludeEvents - [Optional] An array of events that should not be hooked (if possible), unless no other events can be.\r\n * @param evtNamespace - [Optional] Namespace(s) to append to the event listeners so they can be uniquely identified and removed based on this namespace.\r\n * @returns true - when at least one of the events was registered otherwise false\r\n */\nfunction _addEventListeners(events, listener, excludeEvents, evtNamespace) {\n var added = false;\n if (listener && events && events[_DYN_LENGTH /* @min:%2elength */] > 0) {\n arrForEach(events, function (name) {\n if (name) {\n if (!excludeEvents || arrIndexOf(excludeEvents, name) === -1) {\n added = addEventHandler(name, listener, evtNamespace) || added;\n }\n }\n });\n }\n return added;\n}\n/**\r\n * Bind the listener to the array of events\r\n * @param events - An string array of event names to bind the listener to\r\n * @param listener - The event callback to call when the event is triggered\r\n * @param excludeEvents - [Optional] An array of events that should not be hooked (if possible), unless no other events can be.\r\n * @param evtNamespace - [Optional] Namespace(s) to append to the event listeners so they can be uniquely identified and removed based on this namespace.\r\n * @returns true - when at least one of the events was registered otherwise false\r\n */\nexport function addEventListeners(events, listener, excludeEvents, evtNamespace) {\n var added = false;\n if (listener && events && isArray(events)) {\n added = _addEventListeners(events, listener, excludeEvents, evtNamespace);\n if (!added && excludeEvents && excludeEvents[_DYN_LENGTH /* @min:%2elength */] > 0) {\n // Failed to add any listeners and we excluded some, so just attempt to add the excluded events\n added = _addEventListeners(events, listener, null, evtNamespace);\n }\n }\n return added;\n}\n/**\r\n * Remove the listener from the array of events\r\n * @param events - An string array of event names to bind the listener to\r\n * @param listener - The event callback to call when the event is triggered\r\n * @param evtNamespace - [Optional] Namespace(s) to append to the event listeners so they can be uniquely identified and removed based on this namespace.\r\n */\nexport function removeEventListeners(events, listener, evtNamespace) {\n if (events && isArray(events)) {\n arrForEach(events, function (name) {\n if (name) {\n removeEventHandler(name, listener, evtNamespace);\n }\n });\n }\n}\n/**\r\n * Listen to the 'beforeunload', 'unload' and 'pagehide' events which indicates a page unload is occurring,\r\n * this does NOT listen to the 'visibilitychange' event as while it does indicate that the page is being hidden\r\n * it does not *necessarily* mean that the page is being completely unloaded, it can mean that the user is\r\n * just navigating to a different Tab and may come back (without unloading the page). As such you may also\r\n * need to listen to the 'addPageHideEventListener' and 'addPageShowEventListener' events.\r\n * @param listener - The event callback to call when a page unload event is triggered\r\n * @param excludeEvents - [Optional] An array of events that should not be hooked, unless no other events can be.\r\n * @param evtNamespace - [Optional] Namespace(s) to append to the event listeners so they can be uniquely identified and removed based on this namespace.\r\n * @returns true - when at least one of the events was registered otherwise false\r\n */\nexport function addPageUnloadEventListener(listener, excludeEvents, evtNamespace) {\n // Hook the unload event for the document, window and body to ensure that the client events are flushed to the server\n // As just hooking the window does not always fire (on chrome) for page navigation's.\n return addEventListeners([strBeforeUnload, strUnload, strPageHide], listener, excludeEvents, evtNamespace);\n}\n/**\r\n * Remove any matching 'beforeunload', 'unload' and 'pagehide' events that may have been added via addEventListener,\r\n * addEventListeners, addPageUnloadEventListener or addPageHideEventListener.\r\n * @param listener - The specific event callback to to be removed\r\n * @param evtNamespace - [Optional] Namespace(s) uniquely identified and removed based on this namespace.\r\n * @returns true - when at least one of the events was registered otherwise false\r\n */\nexport function removePageUnloadEventListener(listener, evtNamespace) {\n removeEventListeners([strBeforeUnload, strUnload, strPageHide], listener, evtNamespace);\n}\n/**\r\n * Listen to the pagehide and visibility changing to 'hidden' events, because the 'visibilitychange' uses\r\n * an internal proxy to detect the visibility state you SHOULD use a unique namespace when if you plan to call\r\n * removePageShowEventListener as the remove ignores the listener argument for the 'visibilitychange' event.\r\n * @param listener - The event callback to call when a page hide event is triggered\r\n * @param excludeEvents - [Optional] An array of events that should not be hooked (if possible), unless no other events can be.\r\n * @param evtNamespace - [Optional] A Namespace to append to the event listeners so they can be uniquely identified and removed\r\n * based on this namespace. This call also adds an additional unique \"pageshow\" namespace to the events\r\n * so that only the matching \"removePageHideEventListener\" can remove these events.\r\n * Suggestion: pass as true if you are also calling addPageUnloadEventListener as that also hooks pagehide\r\n * @returns true - when at least one of the events was registered otherwise false\r\n */\nexport function addPageHideEventListener(listener, excludeEvents, evtNamespace) {\n function _handlePageVisibility(evt) {\n var doc = getDocument();\n if (listener && doc && doc.visibilityState === \"hidden\") {\n listener(evt);\n }\n }\n // add the unique page show namespace to any provided namespace so we can only remove the ones added by \"pagehide\"\n var newNamespaces = mergeEvtNamespace(strPageHideNamespace, evtNamespace);\n var pageUnloadAdded = _addEventListeners([strPageHide], listener, excludeEvents, newNamespaces);\n if (!excludeEvents || arrIndexOf(excludeEvents, strVisibilityChangeEvt) === -1) {\n pageUnloadAdded = _addEventListeners([strVisibilityChangeEvt], _handlePageVisibility, excludeEvents, newNamespaces) || pageUnloadAdded;\n }\n if (!pageUnloadAdded && excludeEvents) {\n // Failed to add any listeners and we where requested to exclude some, so just call again without excluding anything\n pageUnloadAdded = addPageHideEventListener(listener, null, evtNamespace);\n }\n return pageUnloadAdded;\n}\n/**\r\n * Removes the pageHide event listeners added by addPageHideEventListener, because the 'visibilitychange' uses\r\n * an internal proxy to detect the visibility state you SHOULD use a unique namespace when calling addPageHideEventListener\r\n * as the remove ignores the listener argument for the 'visibilitychange' event.\r\n * @param listener - The specific listener to remove for the 'pageshow' event only (ignored for 'visibilitychange')\r\n * @param evtNamespace - The unique namespace used when calling addPageShowEventListener\r\n */\nexport function removePageHideEventListener(listener, evtNamespace) {\n // add the unique page show namespace to any provided namespace so we only remove the ones added by \"pagehide\"\n var newNamespaces = mergeEvtNamespace(strPageHideNamespace, evtNamespace);\n removeEventListeners([strPageHide], listener, newNamespaces);\n removeEventListeners([strVisibilityChangeEvt], null, newNamespaces);\n}\n/**\r\n * Listen to the pageshow and visibility changing to 'visible' events, because the 'visibilitychange' uses\r\n * an internal proxy to detect the visibility state you SHOULD use a unique namespace when if you plan to call\r\n * removePageShowEventListener as the remove ignores the listener argument for the 'visibilitychange' event.\r\n * @param listener - The event callback to call when a page is show event is triggered\r\n * @param excludeEvents - [Optional] An array of events that should not be hooked (if possible), unless no other events can be.\r\n * @param evtNamespace - [Optional/Recommended] A Namespace to append to the event listeners so they can be uniquely\r\n * identified and removed based on this namespace. This call also adds an additional unique \"pageshow\" namespace to the events\r\n * so that only the matching \"removePageShowEventListener\" can remove these events.\r\n * @returns true - when at least one of the events was registered otherwise false\r\n */\nexport function addPageShowEventListener(listener, excludeEvents, evtNamespace) {\n function _handlePageVisibility(evt) {\n var doc = getDocument();\n if (listener && doc && doc.visibilityState === \"visible\") {\n listener(evt);\n }\n }\n // add the unique page show namespace to any provided namespace so we can only remove the ones added by \"pageshow\"\n var newNamespaces = mergeEvtNamespace(strPageShowNamespace, evtNamespace);\n var pageShowAdded = _addEventListeners([strPageShow], listener, excludeEvents, newNamespaces);\n pageShowAdded = _addEventListeners([strVisibilityChangeEvt], _handlePageVisibility, excludeEvents, newNamespaces) || pageShowAdded;\n if (!pageShowAdded && excludeEvents) {\n // Failed to add any listeners and we where requested to exclude some, so just call again without excluding anything\n pageShowAdded = addPageShowEventListener(listener, null, evtNamespace);\n }\n return pageShowAdded;\n}\n/**\r\n * Removes the pageShow event listeners added by addPageShowEventListener, because the 'visibilitychange' uses\r\n * an internal proxy to detect the visibility state you SHOULD use a unique namespace when calling addPageShowEventListener\r\n * as the remove ignores the listener argument for the 'visibilitychange' event.\r\n * @param listener - The specific listener to remove for the 'pageshow' event only (ignored for 'visibilitychange')\r\n * @param evtNamespace - The unique namespace used when calling addPageShowEventListener\r\n */\nexport function removePageShowEventListener(listener, evtNamespace) {\n // add the unique page show namespace to any provided namespace so we only remove the ones added by \"pageshow\"\n var newNamespaces = mergeEvtNamespace(strPageShowNamespace, evtNamespace);\n removeEventListeners([strPageShow], listener, newNamespaces);\n removeEventListeners([strVisibilityChangeEvt], null, newNamespaces);\n}\n","/*\n * Application Insights JavaScript SDK - Core, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { strShimFunction, strShimPrototype } from \"@microsoft/applicationinsights-shims\";\nimport { getInst, objHasOwnProperty } from \"@nevware21/ts-utils\";\nimport { _DYN_APPLY, _DYN_LENGTH, _DYN_PUSH, _DYN_SPLICE } from \"../__DynamicConstants\";\nimport { _getObjProto } from \"./HelperFuncs\";\nvar aiInstrumentHooks = \"_aiHooks\";\nvar cbNames = [\"req\", \"rsp\", \"hkErr\", \"fnErr\"];\n/** @ignore */\nfunction _arrLoop(arr, fn) {\n if (arr) {\n for (var lp = 0; lp < arr[_DYN_LENGTH /* @min:%2elength */]; lp++) {\n if (fn(arr[lp], lp)) {\n break;\n }\n }\n }\n}\n/** @ignore */\nfunction _doCallbacks(hooks, callDetails, cbArgs, hookCtx, type) {\n if (type >= 0 /* CallbackType.Request */ && type <= 2 /* CallbackType.HookError */) {\n _arrLoop(hooks, function (hook, idx) {\n var cbks = hook.cbks;\n var cb = cbks[cbNames[type]];\n if (cb) {\n // Set the specific hook context implementation using a lazy creation pattern\n callDetails.ctx = function () {\n var ctx = hookCtx[idx] = hookCtx[idx] || {};\n return ctx;\n };\n try {\n cb[_DYN_APPLY /* @min:%2eapply */](callDetails.inst, cbArgs);\n } catch (err) {\n var orgEx = callDetails.err;\n try {\n // Report Hook error via the callback\n var hookErrorCb = cbks[cbNames[2 /* CallbackType.HookError */]];\n if (hookErrorCb) {\n callDetails.err = err;\n hookErrorCb[_DYN_APPLY /* @min:%2eapply */](callDetails.inst, cbArgs);\n }\n } catch (e) {\n // Not much we can do here -- swallowing the exception to avoid crashing the hosting app\n } finally {\n // restore the original exception (if any)\n callDetails.err = orgEx;\n }\n }\n }\n });\n }\n}\n/** @ignore */\nfunction _createFunctionHook(aiHook) {\n // Define a temporary method that queues-up a the real method call\n return function () {\n var funcThis = this;\n // Capture the original arguments passed to the method\n var orgArgs = arguments;\n var hooks = aiHook.h;\n var funcArgs = {\n name: aiHook.n,\n inst: funcThis,\n ctx: null,\n set: _replaceArg\n };\n var hookCtx = [];\n var cbArgs = _createArgs([funcArgs], orgArgs);\n funcArgs.evt = getInst(\"event\");\n function _createArgs(target, theArgs) {\n _arrLoop(theArgs, function (arg) {\n target[_DYN_PUSH /* @min:%2epush */](arg);\n });\n return target;\n }\n function _replaceArg(idx, value) {\n orgArgs = _createArgs([], orgArgs);\n orgArgs[idx] = value;\n cbArgs = _createArgs([funcArgs], orgArgs);\n }\n // Call the pre-request hooks\n _doCallbacks(hooks, funcArgs, cbArgs, hookCtx, 0 /* CallbackType.Request */);\n // Call the original function was called\n var theFunc = aiHook.f;\n if (theFunc) {\n try {\n funcArgs.rslt = theFunc[_DYN_APPLY /* @min:%2eapply */](funcThis, orgArgs);\n } catch (err) {\n // Report the request callback\n funcArgs.err = err;\n _doCallbacks(hooks, funcArgs, cbArgs, hookCtx, 3 /* CallbackType.FunctionError */);\n // rethrow the original exception so anyone listening for it can catch the exception\n throw err;\n }\n }\n // Call the post-request hooks\n _doCallbacks(hooks, funcArgs, cbArgs, hookCtx, 1 /* CallbackType.Response */);\n return funcArgs.rslt;\n };\n}\n/** @ignore */\nfunction _getOwner(target, name, checkPrototype, checkParentProto) {\n var owner = null;\n if (target) {\n if (objHasOwnProperty(target, name)) {\n owner = target;\n } else if (checkPrototype) {\n owner = _getOwner(_getObjProto(target), name, checkParentProto, false);\n }\n }\n return owner;\n}\n/**\r\n * Intercept the named prototype functions for the target class / object\r\n * @param target - The target object\r\n * @param funcName - The function name\r\n * @param callbacks - The callbacks to configure and call whenever the function is called\r\n */\nexport function InstrumentProto(target, funcName, callbacks) {\n if (target) {\n return InstrumentFunc(target[strShimPrototype], funcName, callbacks, false);\n }\n return null;\n}\n/**\r\n * Intercept the named prototype functions for the target class / object\r\n * @param target - The target object\r\n * @param funcNames - The function names to intercept and call\r\n * @param callbacks - The callbacks to configure and call whenever the function is called\r\n */\nexport function InstrumentProtos(target, funcNames, callbacks) {\n if (target) {\n return InstrumentFuncs(target[strShimPrototype], funcNames, callbacks, false);\n }\n return null;\n}\nfunction _createInstrumentHook(owner, funcName, fn, callbacks) {\n var aiHook = fn && fn[aiInstrumentHooks];\n if (!aiHook) {\n // Only hook the function once\n aiHook = {\n i: 0,\n n: funcName,\n f: fn,\n h: []\n };\n // Override (hook) the original function\n var newFunc = _createFunctionHook(aiHook);\n newFunc[aiInstrumentHooks] = aiHook; // Tag and store the function hooks\n owner[funcName] = newFunc;\n }\n var theHook = {\n // tslint:disable:object-literal-shorthand\n id: aiHook.i,\n cbks: callbacks,\n rm: function () {\n // DO NOT Use () => { shorthand for the function as the this gets replaced\n // with the outer this and not the this for theHook instance.\n var id = this.id;\n _arrLoop(aiHook.h, function (hook, idx) {\n if (hook.id === id) {\n aiHook.h[_DYN_SPLICE /* @min:%2esplice */](idx, 1);\n return 1;\n }\n });\n }\n // tslint:enable:object-literal-shorthand\n };\n aiHook.i++;\n aiHook.h[_DYN_PUSH /* @min:%2epush */](theHook);\n return theHook;\n}\n/**\r\n * Intercept the named prototype functions for the target class / object\r\n * @param target - The target object\r\n * @param funcName - The function name\r\n * @param callbacks - The callbacks to configure and call whenever the function is called\r\n * @param checkPrototype - If the function doesn't exist on the target should it attempt to hook the prototype function\r\n * @param checkParentProto - If the function doesn't exist on the target or it's prototype should it attempt to hook the parent's prototype\r\n */\nexport function InstrumentFunc(target, funcName, callbacks, checkPrototype, checkParentProto) {\n if (checkPrototype === void 0) {\n checkPrototype = true;\n }\n if (target && funcName && callbacks) {\n var owner = _getOwner(target, funcName, checkPrototype, checkParentProto);\n if (owner) {\n var fn = owner[funcName];\n if (typeof fn === strShimFunction) {\n return _createInstrumentHook(owner, funcName, fn, callbacks);\n }\n }\n }\n return null;\n}\n/**\r\n * Intercept the named functions for the target class / object\r\n * @param target - The target object\r\n * @param funcNames - The function names to intercept and call\r\n * @param callbacks - The callbacks to configure and call whenever the function is called\r\n * @param checkPrototype - If the function doesn't exist on the target should it attempt to hook the prototype function\r\n * @param checkParentProto - If the function doesn't exist on the target or it's prototype should it attempt to hook the parent's prototype\r\n */\nexport function InstrumentFuncs(target, funcNames, callbacks, checkPrototype, checkParentProto) {\n if (checkPrototype === void 0) {\n checkPrototype = true;\n }\n var hooks = null;\n _arrLoop(funcNames, function (funcName) {\n var hook = InstrumentFunc(target, funcName, callbacks, checkPrototype, checkParentProto);\n if (hook) {\n if (!hooks) {\n hooks = [];\n }\n hooks[_DYN_PUSH /* @min:%2epush */](hook);\n }\n });\n return hooks;\n}\n/**\r\n * Add an instrumentation hook to the provided named \"event\" for the target class / object, this doesn't check whether the\r\n * named \"event\" is in fact a function and just assigns the instrumentation hook to the target[evtName]\r\n * @param target - The target object\r\n * @param evtName - The name of the event\r\n * @param callbacks - The callbacks to configure and call whenever the function is called\r\n * @param checkPrototype - If the function doesn't exist on the target should it attempt to hook the prototype function\r\n * @param checkParentProto - If the function doesn't exist on the target or it's prototype should it attempt to hook the parent's prototype\r\n */\nexport function InstrumentEvent(target, evtName, callbacks, checkPrototype, checkParentProto) {\n if (target && evtName && callbacks) {\n var owner = _getOwner(target, evtName, checkPrototype, checkParentProto) || target;\n if (owner) {\n return _createInstrumentHook(owner, evtName, owner[evtName], callbacks);\n }\n }\n return null;\n}\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n/**\r\n * This is an internal property used to cause internal (reporting) requests to be ignored from reporting\r\n * additional telemetry, to handle polyfil implementations ALL urls used with a disabled request will\r\n * also be ignored for future requests even when this property is not provided.\r\n * Tagging as Ignore as this is an internal value and is not expected to be used outside of the SDK\r\n * @ignore\r\n */\nexport var DisabledPropertyName = \"Microsoft_ApplicationInsights_BypassAjaxInstrumentation\";\nexport var SampleRate = \"sampleRate\";\nexport var ProcessLegacy = \"ProcessLegacy\";\nexport var HttpMethod = \"http.method\";\nexport var DEFAULT_BREEZE_ENDPOINT = \"https://dc.services.visualstudio.com\";\nexport var DEFAULT_BREEZE_PATH = \"/v2/track\";\nexport var strNotSpecified = \"not_specified\";\nexport var strIkey = \"iKey\";\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { createValueMap } from \"@microsoft/applicationinsights-core-js\";\nexport var RequestHeaders = createValueMap({\n requestContextHeader: [0 /* eRequestHeaders.requestContextHeader */, \"Request-Context\"],\n requestContextTargetKey: [1 /* eRequestHeaders.requestContextTargetKey */, \"appId\"],\n requestContextAppIdFormat: [2 /* eRequestHeaders.requestContextAppIdFormat */, \"appId=cid-v1:\"],\n requestIdHeader: [3 /* eRequestHeaders.requestIdHeader */, \"Request-Id\"],\n traceParentHeader: [4 /* eRequestHeaders.traceParentHeader */, \"traceparent\"],\n traceStateHeader: [5 /* eRequestHeaders.traceStateHeader */, \"tracestate\"],\n sdkContextHeader: [6 /* eRequestHeaders.sdkContextHeader */, \"Sdk-Context\"],\n sdkContextHeaderAppIdRequest: [7 /* eRequestHeaders.sdkContextHeaderAppIdRequest */, \"appId\"],\n requestContextHeaderLowerCase: [8 /* eRequestHeaders.requestContextHeaderLowerCase */, \"request-context\"]\n});\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n// @skip-file-minify\n// ##############################################################\n// AUTO GENERATED FILE: This file is Auto Generated during build.\n// ##############################################################\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n// Note: DON'T Export these const from the package as we are still targeting ES5 which can result in a mutable variables that someone could change!!!\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nexport var _DYN_SPLIT = \"split\"; // Count: 6\nexport var _DYN_LENGTH = \"length\"; // Count: 46\nexport var _DYN_TO_LOWER_CASE = \"toLowerCase\"; // Count: 6\nexport var _DYN_INGESTIONENDPOINT = \"ingestionendpoint\"; // Count: 6\nexport var _DYN_TO_STRING = \"toString\"; // Count: 8\nexport var _DYN_REMOVE_ITEM = \"removeItem\"; // Count: 3\nexport var _DYN_MESSAGE = \"message\"; // Count: 5\nexport var _DYN_COUNT = \"count\"; // Count: 6\nexport var _DYN_PRE_TRIGGER_DATE = \"preTriggerDate\"; // Count: 4\nexport var _DYN_GET_UTCDATE = \"getUTCDate\"; // Count: 3\nexport var _DYN_STRINGIFY = \"stringify\"; // Count: 4\nexport var _DYN_PATHNAME = \"pathname\"; // Count: 4\nexport var _DYN_MATCH = \"match\"; // Count: 5\nexport var _DYN_CORRELATION_HEADER_E0 = \"correlationHeaderExcludePatterns\"; // Count: 2\nexport var _DYN_NAME = \"name\"; // Count: 10\nexport var _DYN_EXTENSION_CONFIG = \"extensionConfig\"; // Count: 4\nexport var _DYN_PROPERTIES = \"properties\"; // Count: 10\nexport var _DYN_MEASUREMENTS = \"measurements\"; // Count: 9\nexport var _DYN_SIZE_IN_BYTES = \"sizeInBytes\"; // Count: 4\nexport var _DYN_TYPE_NAME = \"typeName\"; // Count: 5\nexport var _DYN_EXCEPTIONS = \"exceptions\"; // Count: 5\nexport var _DYN_SEVERITY_LEVEL = \"severityLevel\"; // Count: 5\nexport var _DYN_PROBLEM_GROUP = \"problemGroup\"; // Count: 3\nexport var _DYN_PARSED_STACK = \"parsedStack\"; // Count: 6\nexport var _DYN_HAS_FULL_STACK = \"hasFullStack\"; // Count: 5\nexport var _DYN_ASSEMBLY = \"assembly\"; // Count: 4\nexport var _DYN_FILE_NAME = \"fileName\"; // Count: 9\nexport var _DYN_LINE = \"line\"; // Count: 6\nexport var _DYN_AI_DATA_CONTRACT = \"aiDataContract\"; // Count: 4\nexport var _DYN_DURATION = \"duration\"; // Count: 4\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { _throwInternal, getJSON, hasJSON, isObject, objForEachKey, strTrim } from \"@microsoft/applicationinsights-core-js\";\nimport { asString, strSubstr, strSubstring } from \"@nevware21/ts-utils\";\nimport { _DYN_LENGTH, _DYN_STRINGIFY, _DYN_TO_STRING } from \"../../__DynamicConstants\";\nexport function dataSanitizeKeyAndAddUniqueness(logger, key, map) {\n var origLength = key[_DYN_LENGTH /* @min:%2elength */];\n var field = dataSanitizeKey(logger, key);\n // validation truncated the length. We need to add uniqueness\n if (field[_DYN_LENGTH /* @min:%2elength */] !== origLength) {\n var i = 0;\n var uniqueField = field;\n while (map[uniqueField] !== undefined) {\n i++;\n uniqueField = strSubstring(field, 0, 150 /* DataSanitizerValues.MAX_NAME_LENGTH */ - 3) + dsPadNumber(i);\n }\n field = uniqueField;\n }\n return field;\n}\nexport function dataSanitizeKey(logger, name) {\n var nameTrunc;\n if (name) {\n // Remove any leading or trailing whitespace\n name = strTrim(asString(name));\n // truncate the string to 150 chars\n if (name[_DYN_LENGTH /* @min:%2elength */] > 150 /* DataSanitizerValues.MAX_NAME_LENGTH */) {\n nameTrunc = strSubstring(name, 0, 150 /* DataSanitizerValues.MAX_NAME_LENGTH */);\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 57 /* _eInternalMessageId.NameTooLong */, \"name is too long. It has been truncated to \" + 150 /* DataSanitizerValues.MAX_NAME_LENGTH */ + \" characters.\", {\n name: name\n }, true);\n }\n }\n return nameTrunc || name;\n}\nexport function dataSanitizeString(logger, value, maxLength) {\n if (maxLength === void 0) {\n maxLength = 1024 /* DataSanitizerValues.MAX_STRING_LENGTH */;\n }\n var valueTrunc;\n if (value) {\n maxLength = maxLength ? maxLength : 1024 /* DataSanitizerValues.MAX_STRING_LENGTH */; // in case default parameters dont work\n value = strTrim(asString(value));\n if (value[_DYN_LENGTH /* @min:%2elength */] > maxLength) {\n valueTrunc = strSubstring(value, 0, maxLength);\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 61 /* _eInternalMessageId.StringValueTooLong */, \"string value is too long. It has been truncated to \" + maxLength + \" characters.\", {\n value: value\n }, true);\n }\n }\n return valueTrunc || value;\n}\nexport function dataSanitizeUrl(logger, url) {\n return dataSanitizeInput(logger, url, 2048 /* DataSanitizerValues.MAX_URL_LENGTH */, 66 /* _eInternalMessageId.UrlTooLong */);\n}\nexport function dataSanitizeMessage(logger, message) {\n var messageTrunc;\n if (message) {\n if (message[_DYN_LENGTH /* @min:%2elength */] > 32768 /* DataSanitizerValues.MAX_MESSAGE_LENGTH */) {\n messageTrunc = strSubstring(message, 0, 32768 /* DataSanitizerValues.MAX_MESSAGE_LENGTH */);\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 56 /* _eInternalMessageId.MessageTruncated */, \"message is too long, it has been truncated to \" + 32768 /* DataSanitizerValues.MAX_MESSAGE_LENGTH */ + \" characters.\", {\n message: message\n }, true);\n }\n }\n return messageTrunc || message;\n}\nexport function dataSanitizeException(logger, exception) {\n var exceptionTrunc;\n if (exception) {\n // Make surte its a string\n var value = \"\" + exception;\n if (value[_DYN_LENGTH /* @min:%2elength */] > 32768 /* DataSanitizerValues.MAX_EXCEPTION_LENGTH */) {\n exceptionTrunc = strSubstring(value, 0, 32768 /* DataSanitizerValues.MAX_EXCEPTION_LENGTH */);\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 52 /* _eInternalMessageId.ExceptionTruncated */, \"exception is too long, it has been truncated to \" + 32768 /* DataSanitizerValues.MAX_EXCEPTION_LENGTH */ + \" characters.\", {\n exception: exception\n }, true);\n }\n }\n return exceptionTrunc || exception;\n}\nexport function dataSanitizeProperties(logger, properties) {\n if (properties) {\n var tempProps_1 = {};\n objForEachKey(properties, function (prop, value) {\n if (isObject(value) && hasJSON()) {\n // Stringify any part C properties\n try {\n value = getJSON()[_DYN_STRINGIFY /* @min:%2estringify */](value);\n } catch (e) {\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 49 /* _eInternalMessageId.CannotSerializeObjectNonSerializable */, \"custom property is not valid\", {\n exception: e\n }, true);\n }\n }\n value = dataSanitizeString(logger, value, 8192 /* DataSanitizerValues.MAX_PROPERTY_LENGTH */);\n prop = dataSanitizeKeyAndAddUniqueness(logger, prop, tempProps_1);\n tempProps_1[prop] = value;\n });\n properties = tempProps_1;\n }\n return properties;\n}\nexport function dataSanitizeMeasurements(logger, measurements) {\n if (measurements) {\n var tempMeasurements_1 = {};\n objForEachKey(measurements, function (measure, value) {\n measure = dataSanitizeKeyAndAddUniqueness(logger, measure, tempMeasurements_1);\n tempMeasurements_1[measure] = value;\n });\n measurements = tempMeasurements_1;\n }\n return measurements;\n}\nexport function dataSanitizeId(logger, id) {\n return id ? dataSanitizeInput(logger, id, 128 /* DataSanitizerValues.MAX_ID_LENGTH */, 69 /* _eInternalMessageId.IdTooLong */)[_DYN_TO_STRING /* @min:%2etoString */]() : id;\n}\nexport function dataSanitizeInput(logger, input, maxLength, _msgId) {\n var inputTrunc;\n if (input) {\n input = strTrim(asString(input));\n if (input[_DYN_LENGTH /* @min:%2elength */] > maxLength) {\n inputTrunc = strSubstring(input, 0, maxLength);\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, _msgId, \"input is too long, it has been truncated to \" + maxLength + \" characters.\", {\n data: input\n }, true);\n }\n }\n return inputTrunc || input;\n}\nexport function dsPadNumber(num) {\n var s = \"00\" + num;\n return strSubstr(s, s[_DYN_LENGTH /* @min:%2elength */] - 3);\n}\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { getDocument, isString } from \"@microsoft/applicationinsights-core-js\";\nimport { _DYN_LENGTH, _DYN_MATCH, _DYN_PATHNAME, _DYN_TO_LOWER_CASE } from \"./__DynamicConstants\";\nvar _document = getDocument() || {};\nvar _htmlAnchorIdx = 0;\n// Use an array of temporary values as it's possible for multiple calls to parseUrl() will be called with different URLs\n// Using a cache size of 5 for now as it current depth usage is at least 2, so adding a minor buffer to handle future updates\nvar _htmlAnchorElement = [null, null, null, null, null];\nexport function urlParseUrl(url) {\n var anchorIdx = _htmlAnchorIdx;\n var anchorCache = _htmlAnchorElement;\n var tempAnchor = anchorCache[anchorIdx];\n if (!_document.createElement) {\n // Always create the temp instance if createElement is not available\n tempAnchor = {\n host: urlParseHost(url, true)\n };\n } else if (!anchorCache[anchorIdx]) {\n // Create and cache the unattached anchor instance\n tempAnchor = anchorCache[anchorIdx] = _document.createElement(\"a\");\n }\n tempAnchor.href = url;\n // Move the cache index forward\n anchorIdx++;\n if (anchorIdx >= anchorCache[_DYN_LENGTH /* @min:%2elength */]) {\n anchorIdx = 0;\n }\n _htmlAnchorIdx = anchorIdx;\n return tempAnchor;\n}\nexport function urlGetAbsoluteUrl(url) {\n var result;\n var a = urlParseUrl(url);\n if (a) {\n result = a.href;\n }\n return result;\n}\nexport function urlGetPathName(url) {\n var result;\n var a = urlParseUrl(url);\n if (a) {\n result = a[_DYN_PATHNAME /* @min:%2epathname */];\n }\n return result;\n}\nexport function urlGetCompleteUrl(method, absoluteUrl) {\n if (method) {\n return method.toUpperCase() + \" \" + absoluteUrl;\n }\n return absoluteUrl;\n}\n// Fallback method to grab host from url if document.createElement method is not available\nexport function urlParseHost(url, inclPort) {\n var fullHost = urlParseFullHost(url, inclPort) || \"\";\n if (fullHost) {\n var match = fullHost[_DYN_MATCH /* @min:%2ematch */](/(www\\d{0,5}\\.)?([^\\/:]{1,256})(:\\d{1,20})?/i);\n if (match != null && match[_DYN_LENGTH /* @min:%2elength */] > 3 && isString(match[2]) && match[2][_DYN_LENGTH /* @min:%2elength */] > 0) {\n return match[2] + (match[3] || \"\");\n }\n }\n return fullHost;\n}\nexport function urlParseFullHost(url, inclPort) {\n var result = null;\n if (url) {\n var match = url[_DYN_MATCH /* @min:%2ematch */](/(\\w{1,150}):\\/\\/([^\\/:]{1,256})(:\\d{1,20})?/i);\n if (match != null && match[_DYN_LENGTH /* @min:%2elength */] > 2 && isString(match[2]) && match[2][_DYN_LENGTH /* @min:%2elength */] > 0) {\n result = match[2] || \"\";\n if (inclPort && match[_DYN_LENGTH /* @min:%2elength */] > 2) {\n var protocol = (match[1] || \"\")[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\n var port = match[3] || \"\";\n // IE includes the standard port so pass it off if it's the same as the protocol\n if (protocol === \"http\" && port === \":80\") {\n port = \"\";\n } else if (protocol === \"https\" && port === \":443\") {\n port = \"\";\n }\n result += port;\n }\n }\n }\n return result;\n}\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { arrForEach, arrIndexOf, dateNow, getPerformance, isNullOrUndefined, isValidSpanId, isValidTraceId } from \"@microsoft/applicationinsights-core-js\";\nimport { strIndexOf } from \"@nevware21/ts-utils\";\nimport { DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH } from \"./Constants\";\nimport { RequestHeaders } from \"./RequestResponseHeaders\";\nimport { dataSanitizeString } from \"./Telemetry/Common/DataSanitizer\";\nimport { urlParseFullHost, urlParseUrl } from \"./UrlHelperFuncs\";\nimport { _DYN_CORRELATION_HEADER_E0, _DYN_LENGTH, _DYN_NAME, _DYN_PATHNAME, _DYN_SPLIT, _DYN_TO_LOWER_CASE } from \"./__DynamicConstants\";\n// listing only non-geo specific locations\nvar _internalEndpoints = [DEFAULT_BREEZE_ENDPOINT + DEFAULT_BREEZE_PATH, \"https://breeze.aimon.applicationinsights.io\" + DEFAULT_BREEZE_PATH, \"https://dc-int.services.visualstudio.com\" + DEFAULT_BREEZE_PATH];\nvar _correlationIdPrefix = \"cid-v1:\";\nexport function isInternalApplicationInsightsEndpoint(endpointUrl) {\n return arrIndexOf(_internalEndpoints, endpointUrl[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]()) !== -1;\n}\nexport function correlationIdSetPrefix(prefix) {\n _correlationIdPrefix = prefix;\n}\nexport function correlationIdGetPrefix() {\n return _correlationIdPrefix;\n}\n/**\r\n * Checks if a request url is not on a excluded domain list and if it is safe to add correlation headers.\r\n * Headers are always included if the current domain matches the request domain. If they do not match (CORS),\r\n * they are regex-ed across correlationHeaderDomains and correlationHeaderExcludedDomains to determine if headers are included.\r\n * Some environments don't give information on currentHost via window.location.host (e.g. Cordova). In these cases, the user must\r\n * manually supply domains to include correlation headers on. Else, no headers will be included at all.\r\n */\nexport function correlationIdCanIncludeCorrelationHeader(config, requestUrl, currentHost) {\n if (!requestUrl || config && config.disableCorrelationHeaders) {\n return false;\n }\n if (config && config[_DYN_CORRELATION_HEADER_E0 /* @min:%2ecorrelationHeaderExcludePatterns */]) {\n for (var i = 0; i < config.correlationHeaderExcludePatterns[_DYN_LENGTH /* @min:%2elength */]; i++) {\n if (config[_DYN_CORRELATION_HEADER_E0 /* @min:%2ecorrelationHeaderExcludePatterns */][i].test(requestUrl)) {\n return false;\n }\n }\n }\n var requestHost = urlParseUrl(requestUrl).host[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\n if (requestHost && (strIndexOf(requestHost, \":443\") !== -1 || strIndexOf(requestHost, \":80\") !== -1)) {\n // [Bug #1260] IE can include the port even for http and https URLs so if present\n // try and parse it to remove if it matches the default protocol port\n requestHost = (urlParseFullHost(requestUrl, true) || \"\")[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\n }\n if ((!config || !config.enableCorsCorrelation) && requestHost && requestHost !== currentHost) {\n return false;\n }\n var includedDomains = config && config.correlationHeaderDomains;\n if (includedDomains) {\n var matchExists_1;\n arrForEach(includedDomains, function (domain) {\n var regex = new RegExp(domain.toLowerCase().replace(/\\\\/g, \"\\\\\\\\\").replace(/\\./g, \"\\\\.\").replace(/\\*/g, \".*\"));\n matchExists_1 = matchExists_1 || regex.test(requestHost);\n });\n if (!matchExists_1) {\n return false;\n }\n }\n var excludedDomains = config && config.correlationHeaderExcludedDomains;\n if (!excludedDomains || excludedDomains[_DYN_LENGTH /* @min:%2elength */] === 0) {\n return true;\n }\n for (var i = 0; i < excludedDomains[_DYN_LENGTH /* @min:%2elength */]; i++) {\n var regex = new RegExp(excludedDomains[i].toLowerCase().replace(/\\\\/g, \"\\\\\\\\\").replace(/\\./g, \"\\\\.\").replace(/\\*/g, \".*\"));\n if (regex.test(requestHost)) {\n return false;\n }\n }\n // if we don't know anything about the requestHost, require the user to use included/excludedDomains.\n // Previously we always returned false for a falsy requestHost\n return requestHost && requestHost[_DYN_LENGTH /* @min:%2elength */] > 0;\n}\n/**\r\n * Combines target appId and target role name from response header.\r\n */\nexport function correlationIdGetCorrelationContext(responseHeader) {\n if (responseHeader) {\n var correlationId = correlationIdGetCorrelationContextValue(responseHeader, RequestHeaders[1 /* eRequestHeaders.requestContextTargetKey */]);\n if (correlationId && correlationId !== _correlationIdPrefix) {\n return correlationId;\n }\n }\n}\n/**\r\n * Gets key from correlation response header\r\n */\nexport function correlationIdGetCorrelationContextValue(responseHeader, key) {\n if (responseHeader) {\n var keyValues = responseHeader[_DYN_SPLIT /* @min:%2esplit */](\",\");\n for (var i = 0; i < keyValues[_DYN_LENGTH /* @min:%2elength */]; ++i) {\n var keyValue = keyValues[i][_DYN_SPLIT /* @min:%2esplit */](\"=\");\n if (keyValue[_DYN_LENGTH /* @min:%2elength */] === 2 && keyValue[0] === key) {\n return keyValue[1];\n }\n }\n }\n}\nexport function AjaxHelperParseDependencyPath(logger, absoluteUrl, method, commandName) {\n var target,\n name = commandName,\n data = commandName;\n if (absoluteUrl && absoluteUrl[_DYN_LENGTH /* @min:%2elength */] > 0) {\n var parsedUrl = urlParseUrl(absoluteUrl);\n target = parsedUrl.host;\n if (!name) {\n if (parsedUrl[_DYN_PATHNAME /* @min:%2epathname */] != null) {\n var pathName = parsedUrl.pathname[_DYN_LENGTH /* @min:%2elength */] === 0 ? \"/\" : parsedUrl[_DYN_PATHNAME /* @min:%2epathname */];\n if (pathName.charAt(0) !== \"/\") {\n pathName = \"/\" + pathName;\n }\n data = parsedUrl[_DYN_PATHNAME /* @min:%2epathname */];\n name = dataSanitizeString(logger, method ? method + \" \" + pathName : pathName);\n } else {\n name = dataSanitizeString(logger, absoluteUrl);\n }\n }\n } else {\n target = commandName;\n name = commandName;\n }\n return {\n target: target,\n name: name,\n data: data\n };\n}\nexport function dateTimeUtilsNow() {\n // returns the window or webworker performance object\n var perf = getPerformance();\n if (perf && perf.now && perf.timing) {\n var now = perf.now() + perf.timing.navigationStart;\n // Known issue with IE where this calculation can be negative, so if it is then ignore and fallback\n if (now > 0) {\n return now;\n }\n }\n return dateNow();\n}\nexport function dateTimeUtilsDuration(start, end) {\n var result = null;\n if (start !== 0 && end !== 0 && !isNullOrUndefined(start) && !isNullOrUndefined(end)) {\n result = end - start;\n }\n return result;\n}\n/**\r\n * Creates a IDistributedTraceContext from an optional telemetryTrace\r\n * @param telemetryTrace - The telemetryTrace instance that is being wrapped\r\n * @param parentCtx - An optional parent distributed trace instance, almost always undefined as this scenario is only used in the case of multiple property handlers.\r\n * @returns A new IDistributedTraceContext instance that is backed by the telemetryTrace or temporary object\r\n */\nexport function createDistributedTraceContextFromTrace(telemetryTrace, parentCtx) {\n var trace = telemetryTrace || {};\n return {\n getName: function () {\n return trace[_DYN_NAME /* @min:%2ename */];\n },\n setName: function (newValue) {\n parentCtx && parentCtx.setName(newValue);\n trace[_DYN_NAME /* @min:%2ename */] = newValue;\n },\n getTraceId: function () {\n return trace.traceID;\n },\n setTraceId: function (newValue) {\n parentCtx && parentCtx.setTraceId(newValue);\n if (isValidTraceId(newValue)) {\n trace.traceID = newValue;\n }\n },\n getSpanId: function () {\n return trace.parentID;\n },\n setSpanId: function (newValue) {\n parentCtx && parentCtx.setSpanId(newValue);\n if (isValidSpanId(newValue)) {\n trace.parentID = newValue;\n }\n },\n getTraceFlags: function () {\n return trace.traceFlags;\n },\n setTraceFlags: function (newTraceFlags) {\n parentCtx && parentCtx.setTraceFlags(newTraceFlags);\n trace.traceFlags = newTraceFlags;\n }\n };\n}\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { createEnumStyle } from \"@microsoft/applicationinsights-core-js\";\nexport var StorageType = createEnumStyle({\n LocalStorage: 0 /* eStorageType.LocalStorage */,\n SessionStorage: 1 /* eStorageType.SessionStorage */\n});\nexport var DistributedTracingModes = createEnumStyle({\n AI: 0 /* eDistributedTracingModes.AI */,\n AI_AND_W3C: 1 /* eDistributedTracingModes.AI_AND_W3C */,\n W3C: 2 /* eDistributedTracingModes.W3C */\n});\n/**\r\n * The EventPersistence contains a set of values that specify the event's persistence.\r\n */\nexport var EventPersistence = createEnumStyle({\n /**\r\n * Normal persistence.\r\n */\n Normal: 1 /* EventPersistenceValue.Normal */,\n\n /**\r\n * Critical persistence.\r\n */\n Critical: 2 /* EventPersistenceValue.Critical */\n});\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { _throwInternal, dumpObj, getExceptionName, getGlobal, getGlobalInst, isNullOrUndefined, objForEachKey } from \"@microsoft/applicationinsights-core-js\";\nimport { StorageType } from \"./Enums\";\nimport { _DYN_REMOVE_ITEM, _DYN_TO_STRING } from \"./__DynamicConstants\";\nvar _canUseLocalStorage = undefined;\nvar _canUseSessionStorage = undefined;\nvar _storagePrefix = \"\";\n/**\r\n * Gets the localStorage object if available\r\n * @returns {Storage} - Returns the storage object if available else returns null\r\n */\nfunction _getLocalStorageObject() {\n if (utlCanUseLocalStorage()) {\n return _getVerifiedStorageObject(StorageType.LocalStorage);\n }\n return null;\n}\n/**\r\n * Tests storage object (localStorage or sessionStorage) to verify that it is usable\r\n * More details here: https://mathiasbynens.be/notes/localstorage-pattern\r\n * @param storageType - Type of storage\r\n * @returns {Storage} Returns storage object verified that it is usable\r\n */\nfunction _getVerifiedStorageObject(storageType) {\n try {\n if (isNullOrUndefined(getGlobal())) {\n return null;\n }\n var uid = new Date()[_DYN_TO_STRING /* @min:%2etoString */]();\n var storage = getGlobalInst(storageType === StorageType.LocalStorage ? \"localStorage\" : \"sessionStorage\");\n var name_1 = _storagePrefix + uid;\n storage.setItem(name_1, uid);\n var fail = storage.getItem(name_1) !== uid;\n storage[_DYN_REMOVE_ITEM /* @min:%2eremoveItem */](name_1);\n if (!fail) {\n return storage;\n }\n } catch (exception) {\n // eslint-disable-next-line no-empty\n }\n return null;\n}\n/**\r\n * Gets the sessionStorage object if available\r\n * @returns {Storage} - Returns the storage object if available else returns null\r\n */\nfunction _getSessionStorageObject() {\n if (utlCanUseSessionStorage()) {\n return _getVerifiedStorageObject(StorageType.SessionStorage);\n }\n return null;\n}\n/**\r\n * Disables the global SDK usage of local or session storage if available\r\n */\nexport function utlDisableStorage() {\n _canUseLocalStorage = false;\n _canUseSessionStorage = false;\n}\nexport function utlSetStoragePrefix(storagePrefix) {\n _storagePrefix = storagePrefix || \"\";\n}\n/**\r\n * Re-enables the global SDK usage of local or session storage if available\r\n */\nexport function utlEnableStorage() {\n _canUseLocalStorage = utlCanUseLocalStorage(true);\n _canUseSessionStorage = utlCanUseSessionStorage(true);\n}\n/**\r\n * Returns whether LocalStorage can be used, if the reset parameter is passed a true this will override\r\n * any previous disable calls.\r\n * @param reset - Should the usage be reset and determined only based on whether LocalStorage is available\r\n */\nexport function utlCanUseLocalStorage(reset) {\n if (reset || _canUseLocalStorage === undefined) {\n _canUseLocalStorage = !!_getVerifiedStorageObject(StorageType.LocalStorage);\n }\n return _canUseLocalStorage;\n}\nexport function utlGetLocalStorage(logger, name) {\n var storage = _getLocalStorageObject();\n if (storage !== null) {\n try {\n return storage.getItem(name);\n } catch (e) {\n _canUseLocalStorage = false;\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 1 /* _eInternalMessageId.BrowserCannotReadLocalStorage */, \"Browser failed read of local storage. \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n }\n return null;\n}\nexport function utlSetLocalStorage(logger, name, data) {\n var storage = _getLocalStorageObject();\n if (storage !== null) {\n try {\n storage.setItem(name, data);\n return true;\n } catch (e) {\n _canUseLocalStorage = false;\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 3 /* _eInternalMessageId.BrowserCannotWriteLocalStorage */, \"Browser failed write to local storage. \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n }\n return false;\n}\nexport function utlRemoveStorage(logger, name) {\n var storage = _getLocalStorageObject();\n if (storage !== null) {\n try {\n storage[_DYN_REMOVE_ITEM /* @min:%2eremoveItem */](name);\n return true;\n } catch (e) {\n _canUseLocalStorage = false;\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 5 /* _eInternalMessageId.BrowserFailedRemovalFromLocalStorage */, \"Browser failed removal of local storage item. \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n }\n return false;\n}\nexport function utlCanUseSessionStorage(reset) {\n if (reset || _canUseSessionStorage === undefined) {\n _canUseSessionStorage = !!_getVerifiedStorageObject(StorageType.SessionStorage);\n }\n return _canUseSessionStorage;\n}\nexport function utlGetSessionStorageKeys() {\n var keys = [];\n if (utlCanUseSessionStorage()) {\n objForEachKey(getGlobalInst(\"sessionStorage\"), function (key) {\n keys.push(key);\n });\n }\n return keys;\n}\nexport function utlGetSessionStorage(logger, name) {\n var storage = _getSessionStorageObject();\n if (storage !== null) {\n try {\n return storage.getItem(name);\n } catch (e) {\n _canUseSessionStorage = false;\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 2 /* _eInternalMessageId.BrowserCannotReadSessionStorage */, \"Browser failed read of session storage. \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n }\n return null;\n}\nexport function utlSetSessionStorage(logger, name, data) {\n var storage = _getSessionStorageObject();\n if (storage !== null) {\n try {\n storage.setItem(name, data);\n return true;\n } catch (e) {\n _canUseSessionStorage = false;\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 4 /* _eInternalMessageId.BrowserCannotWriteSessionStorage */, \"Browser failed write to session storage. \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n }\n return false;\n}\nexport function utlRemoveSessionStorage(logger, name) {\n var storage = _getSessionStorageObject();\n if (storage !== null) {\n try {\n storage[_DYN_REMOVE_ITEM /* @min:%2eremoveItem */](name);\n return true;\n } catch (e) {\n _canUseSessionStorage = false;\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 6 /* _eInternalMessageId.BrowserFailedRemovalFromSessionStorage */, \"Browser failed removal of session storage item. \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n }\n return false;\n}\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nimport { _throwInternal, arrIndexOf, isNotNullOrUndefined, isNullOrUndefined, onConfigChange, randomValue, safeGetLogger, strTrim } from \"@microsoft/applicationinsights-core-js\";\nimport { arrForEach, mathFloor, mathMin, objForEachKey } from \"@nevware21/ts-utils\";\nimport { utlCanUseLocalStorage, utlGetLocalStorage, utlSetLocalStorage } from \"./StorageHelperFuncs\";\nimport { _DYN_COUNT, _DYN_GET_UTCDATE, _DYN_LENGTH, _DYN_MESSAGE, _DYN_PRE_TRIGGER_DATE, _DYN_STRINGIFY } from \"./__DynamicConstants\";\nvar THROTTLE_STORAGE_PREFIX = \"appInsightsThrottle\";\nvar ThrottleMgr = /** @class */function () {\n function ThrottleMgr(core, namePrefix) {\n var _self = this;\n var _canUseLocalStorage;\n var _logger;\n var _config;\n var _localStorageObj;\n var _isTriggered; //_isTriggered is to make sure that we only trigger throttle once a day\n var _namePrefix;\n var _queue;\n var _isReady = false;\n var _isSpecificDaysGiven = false;\n _initConfig();\n // Special internal method to allow the unit tests and DebugPlugin to hook embedded objects\n _self[\"_getDbgPlgTargets\"] = function () {\n return [_queue];\n };\n _self.getConfig = function () {\n return _config;\n };\n /**\r\n * Check if it is the correct day to send message.\r\n * If _isTriggered is true, even if canThrottle returns true, message will not be sent,\r\n * because we only allow triggering sendMessage() once a day.\r\n * @returns if the current date is the valid date to send message\r\n */\n _self.canThrottle = function (msgId) {\n var localObj = _getLocalStorageObjByKey(msgId);\n var cfg = _getCfgByKey(msgId);\n return _canThrottle(cfg, _canUseLocalStorage, localObj);\n };\n /**\r\n * Check if throttle is triggered on current day(UTC)\r\n * if canThrottle returns false, isTriggered will return false\r\n * @returns if throttle is triggered on current day(UTC)\r\n */\n _self.isTriggered = function (msgId) {\n return _isTrigger(msgId);\n };\n /**\r\n * Before isReady set to true, all message will be stored in queue.\r\n * Message will only be sent out after isReady set to true.\r\n * Initial and default value: false\r\n * @returns isReady state\r\n */\n _self.isReady = function () {\n return _isReady;\n };\n /**\r\n * Flush all message with given message key in queue with isReady state set to true.\r\n * @returns if message queue is flushed\r\n */\n _self.flush = function (msgId) {\n try {\n var queue = _getQueueByKey(msgId);\n if (queue && queue[_DYN_LENGTH /* @min:%2elength */] > 0) {\n var items = queue.slice(0);\n _queue[msgId] = [];\n arrForEach(items, function (item) {\n _flushMessage(item.msgID, item[_DYN_MESSAGE /* @min:%2emessage */], item.severity, false);\n });\n return true;\n }\n } catch (err) {\n // eslint-disable-next-line no-empty\n }\n return false;\n };\n /**\r\n * Flush all message in queue with isReady state set to true.\r\n * @returns if message queue is flushed\r\n */\n _self.flushAll = function () {\n try {\n if (_queue) {\n var result_1 = true;\n objForEachKey(_queue, function (key) {\n var isFlushed = _self.flush(parseInt(key));\n result_1 = result_1 && isFlushed;\n });\n return result_1;\n }\n } catch (err) {\n // eslint-disable-next-line no-empty\n }\n return false;\n };\n /**\r\n * Set isReady State\r\n * if isReady set to true, message queue will be flushed automatically.\r\n * @param isReady - isReady State\r\n * @pa\r\n * @returns if message queue is flushed\r\n */\n _self.onReadyState = function (isReady, flushAll) {\n if (flushAll === void 0) {\n flushAll = true;\n }\n _isReady = isNullOrUndefined(isReady) ? true : isReady;\n if (_isReady && flushAll) {\n return _self.flushAll();\n }\n return null;\n };\n _self.sendMessage = function (msgID, message, severity) {\n return _flushMessage(msgID, message, severity, true);\n };\n function _flushMessage(msgID, message, severity, saveUnsentMsg) {\n if (_isReady) {\n var isSampledIn = _canSampledIn(msgID);\n if (!isSampledIn) {\n return;\n }\n var cfg = _getCfgByKey(msgID);\n var localStorageObj = _getLocalStorageObjByKey(msgID);\n var canThrottle = _canThrottle(cfg, _canUseLocalStorage, localStorageObj);\n var throttled = false;\n var number = 0;\n var isTriggered = _isTrigger(msgID);\n try {\n if (canThrottle && !isTriggered) {\n number = mathMin(cfg.limit.maxSendNumber, localStorageObj[_DYN_COUNT /* @min:%2ecount */] + 1);\n localStorageObj[_DYN_COUNT /* @min:%2ecount */] = 0;\n throttled = true;\n _isTriggered[msgID] = true;\n localStorageObj[_DYN_PRE_TRIGGER_DATE /* @min:%2epreTriggerDate */] = new Date();\n } else {\n _isTriggered[msgID] = canThrottle;\n localStorageObj[_DYN_COUNT /* @min:%2ecount */] += 1;\n }\n var localStorageName = _getLocalStorageName(msgID);\n _resetLocalStorage(_logger, localStorageName, localStorageObj);\n for (var i = 0; i < number; i++) {\n _sendMessage(msgID, _logger, message, severity);\n }\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n return {\n isThrottled: throttled,\n throttleNum: number\n };\n } else {\n if (!!saveUnsentMsg) {\n var queue = _getQueueByKey(msgID);\n queue.push({\n msgID: msgID,\n message: message,\n severity: severity\n });\n }\n }\n return null;\n }\n function _initConfig() {\n _logger = safeGetLogger(core);\n _isTriggered = {};\n _localStorageObj = {};\n _queue = {};\n _config = {};\n _setCfgByKey(109 /* _eInternalMessageId.DefaultThrottleMsgKey */);\n _namePrefix = isNotNullOrUndefined(namePrefix) ? namePrefix : \"\";\n core.addUnloadHook(onConfigChange(core.config, function (details) {\n var coreConfig = details.cfg;\n _canUseLocalStorage = utlCanUseLocalStorage();\n var configMgr = coreConfig.throttleMgrCfg || {};\n objForEachKey(configMgr, function (key, cfg) {\n _setCfgByKey(parseInt(key), cfg);\n });\n }));\n }\n function _getCfgByKey(msgID) {\n return _config[msgID] || _config[109 /* _eInternalMessageId.DefaultThrottleMsgKey */];\n }\n function _setCfgByKey(msgID, config) {\n var _a, _b;\n try {\n var cfg = config || {};\n var curCfg = {};\n curCfg.disabled = !!cfg.disabled;\n var configInterval = cfg.interval || {};\n _isSpecificDaysGiven = (configInterval === null || configInterval === void 0 ? void 0 : configInterval.daysOfMonth) && (configInterval === null || configInterval === void 0 ? void 0 : configInterval.daysOfMonth[_DYN_LENGTH /* @min:%2elength */]) > 0;\n curCfg.interval = _getIntervalConfig(configInterval);\n var limit = {\n samplingRate: ((_a = cfg.limit) === null || _a === void 0 ? void 0 : _a.samplingRate) || 100,\n // dafault: every time sent only 1 event\n maxSendNumber: ((_b = cfg.limit) === null || _b === void 0 ? void 0 : _b.maxSendNumber) || 1\n };\n curCfg.limit = limit;\n _config[msgID] = curCfg;\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n }\n function _getIntervalConfig(interval) {\n interval = interval || {};\n var monthInterval = interval === null || interval === void 0 ? void 0 : interval.monthInterval;\n var dayInterval = interval === null || interval === void 0 ? void 0 : interval.dayInterval;\n // default: send data every 3 month each year\n if (isNullOrUndefined(monthInterval) && isNullOrUndefined(dayInterval)) {\n interval.monthInterval = 3;\n if (!_isSpecificDaysGiven) {\n // default: send data on 28th\n interval.daysOfMonth = [28];\n _isSpecificDaysGiven = true;\n }\n }\n interval = {\n // dafault: sent every three months\n monthInterval: interval === null || interval === void 0 ? void 0 : interval.monthInterval,\n dayInterval: interval === null || interval === void 0 ? void 0 : interval.dayInterval,\n daysOfMonth: interval === null || interval === void 0 ? void 0 : interval.daysOfMonth\n };\n return interval;\n }\n function _canThrottle(config, canUseLocalStorage, localStorageObj) {\n if (config && !config.disabled && canUseLocalStorage && isNotNullOrUndefined(localStorageObj)) {\n var curDate = _getThrottleDate();\n var date = localStorageObj.date;\n var interval = config.interval;\n var monthCheck = 1;\n if (interval === null || interval === void 0 ? void 0 : interval.monthInterval) {\n var monthExpand = (curDate.getUTCFullYear() - date.getUTCFullYear()) * 12 + curDate.getUTCMonth() - date.getUTCMonth();\n monthCheck = _checkInterval(interval.monthInterval, 0, monthExpand);\n }\n var dayCheck = 1;\n if (_isSpecificDaysGiven) {\n dayCheck = arrIndexOf(interval.daysOfMonth, curDate[_DYN_GET_UTCDATE /* @min:%2egetUTCDate */]());\n } else if (interval === null || interval === void 0 ? void 0 : interval.dayInterval) {\n var daySpan = mathFloor((curDate.getTime() - date.getTime()) / 86400000);\n dayCheck = _checkInterval(interval.dayInterval, 0, daySpan);\n }\n return monthCheck >= 0 && dayCheck >= 0;\n }\n return false;\n }\n function _getLocalStorageName(msgKey, prefix) {\n var fix = isNotNullOrUndefined(prefix) ? prefix : \"\";\n if (msgKey) {\n return THROTTLE_STORAGE_PREFIX + fix + \"-\" + msgKey;\n }\n return null;\n }\n // returns if throttle is triggered on current Date\n function _isTriggeredOnCurDate(preTriggerDate) {\n try {\n if (preTriggerDate) {\n var curDate = new Date();\n return preTriggerDate.getUTCFullYear() === curDate.getUTCFullYear() && preTriggerDate.getUTCMonth() === curDate.getUTCMonth() && preTriggerDate[_DYN_GET_UTCDATE /* @min:%2egetUTCDate */]() === curDate[_DYN_GET_UTCDATE /* @min:%2egetUTCDate */]();\n }\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n return false;\n }\n // transfer local storage string value to object that identifies start date, current count and preTriggerDate\n function _getLocalStorageObj(value, logger, storageName) {\n try {\n var storageObj = {\n date: _getThrottleDate(),\n count: 0\n };\n if (value) {\n var obj = JSON.parse(value);\n var curObj = {\n date: _getThrottleDate(obj.date) || storageObj.date,\n count: obj[_DYN_COUNT /* @min:%2ecount */] || storageObj[_DYN_COUNT /* @min:%2ecount */],\n preTriggerDate: obj.preTriggerDate ? _getThrottleDate(obj[_DYN_PRE_TRIGGER_DATE /* @min:%2epreTriggerDate */]) : undefined\n };\n return curObj;\n } else {\n _resetLocalStorage(logger, storageName, storageObj);\n return storageObj;\n }\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n return null;\n }\n // if datestr is not defined, current date will be returned\n function _getThrottleDate(dateStr) {\n // if new Date() can't be created through the provided dateStr, null will be returned.\n try {\n if (dateStr) {\n var date = new Date(dateStr);\n //make sure it is a valid Date Object\n if (!isNaN(date.getDate())) {\n return date;\n }\n } else {\n return new Date();\n }\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n return null;\n }\n function _resetLocalStorage(logger, storageName, obj) {\n try {\n return utlSetLocalStorage(logger, storageName, strTrim(JSON[_DYN_STRINGIFY /* @min:%2estringify */](obj)));\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n return false;\n }\n function _checkInterval(interval, start, current) {\n if (interval <= 0) {\n return 1;\n }\n // count from start year\n return current >= start && (current - start) % interval == 0 ? mathFloor((current - start) / interval) + 1 : -1;\n }\n function _sendMessage(msgID, logger, message, severity) {\n _throwInternal(logger, severity || 1 /* eLoggingSeverity.CRITICAL */, msgID, message);\n }\n // NOTE: config.limit.samplingRate is set to 4 decimal places,\n // so config.limit.samplingRate = 1 means 0.0001%\n function _canSampledIn(msgID) {\n try {\n var cfg = _getCfgByKey(msgID);\n return randomValue(1000000) <= cfg.limit.samplingRate;\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n return false;\n }\n function _getLocalStorageObjByKey(key) {\n try {\n var curObj = _localStorageObj[key];\n if (!curObj) {\n var localStorageName = _getLocalStorageName(key, _namePrefix);\n curObj = _getLocalStorageObj(utlGetLocalStorage(_logger, localStorageName), _logger, localStorageName);\n _localStorageObj[key] = curObj;\n }\n return _localStorageObj[key];\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n return null;\n }\n function _isTrigger(key) {\n var isTrigger = _isTriggered[key];\n if (isNullOrUndefined(isTrigger)) {\n isTrigger = false;\n var localStorageObj = _getLocalStorageObjByKey(key);\n if (localStorageObj) {\n isTrigger = _isTriggeredOnCurDate(localStorageObj[_DYN_PRE_TRIGGER_DATE /* @min:%2epreTriggerDate */]);\n }\n _isTriggered[key] = isTrigger;\n }\n return _isTriggered[key];\n }\n function _getQueueByKey(key) {\n _queue = _queue || {};\n if (isNullOrUndefined(_queue[key])) {\n _queue[key] = [];\n }\n return _queue[key];\n }\n }\n return ThrottleMgr;\n}();\nexport { ThrottleMgr };\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { arrReduce, objKeys, strEndsWith } from \"@microsoft/applicationinsights-core-js\";\nimport { DEFAULT_BREEZE_ENDPOINT } from \"./Constants\";\nimport { _DYN_INGESTIONENDPOINT, _DYN_LENGTH, _DYN_SPLIT, _DYN_TO_LOWER_CASE } from \"./__DynamicConstants\";\nvar _FIELDS_SEPARATOR = \";\";\nvar _FIELD_KEY_VALUE_SEPARATOR = \"=\";\nexport function parseConnectionString(connectionString) {\n if (!connectionString) {\n return {};\n }\n var kvPairs = connectionString[_DYN_SPLIT /* @min:%2esplit */](_FIELDS_SEPARATOR);\n var result = arrReduce(kvPairs, function (fields, kv) {\n var kvParts = kv[_DYN_SPLIT /* @min:%2esplit */](_FIELD_KEY_VALUE_SEPARATOR);\n if (kvParts[_DYN_LENGTH /* @min:%2elength */] === 2) {\n // only save fields with valid formats\n var key = kvParts[0][_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\n var value = kvParts[1];\n fields[key] = value;\n }\n return fields;\n }, {});\n if (objKeys(result)[_DYN_LENGTH /* @min:%2elength */] > 0) {\n // this is a valid connection string, so parse the results\n if (result.endpointsuffix) {\n // apply the default endpoints\n var locationPrefix = result.location ? result.location + \".\" : \"\";\n result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */] = result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */] || \"https://\" + locationPrefix + \"dc.\" + result.endpointsuffix;\n }\n // apply user override endpoint or the default endpoints\n result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */] = result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */] || DEFAULT_BREEZE_ENDPOINT;\n if (strEndsWith(result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */], \"/\")) {\n result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */] = result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */].slice(0, -1);\n }\n }\n return result;\n}\nexport var ConnectionStringParser = {\n parse: parseConnectionString\n};\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { toISOString } from \"@microsoft/applicationinsights-core-js\";\nimport { strNotSpecified } from \"../../Constants\";\nimport { _DYN_AI_DATA_CONTRACT, _DYN_NAME } from \"../../__DynamicConstants\";\nimport { dataSanitizeString } from \"./DataSanitizer\";\nvar Envelope = /** @class */function () {\n /**\r\n * Constructs a new instance of telemetry data.\r\n */\n function Envelope(logger, data, name) {\n var _this = this;\n var _self = this;\n _self.ver = 1;\n _self.sampleRate = 100.0;\n _self.tags = {};\n _self[_DYN_NAME /* @min:%2ename */] = dataSanitizeString(logger, name) || strNotSpecified;\n _self.data = data;\n _self.time = toISOString(new Date());\n _self[_DYN_AI_DATA_CONTRACT /* @min:%2eaiDataContract */] = {\n time: 1 /* FieldType.Required */,\n iKey: 1 /* FieldType.Required */,\n name: 1 /* FieldType.Required */,\n sampleRate: function () {\n return _this.sampleRate === 100 ? 4 /* FieldType.Hidden */ : 1 /* FieldType.Required */;\n },\n tags: 1 /* FieldType.Required */,\n data: 1 /* FieldType.Required */\n };\n }\n return Envelope;\n}();\nexport { Envelope };\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { strNotSpecified } from \"../Constants\";\nimport { _DYN_MEASUREMENTS, _DYN_NAME, _DYN_PROPERTIES } from \"../__DynamicConstants\";\nimport { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString } from \"./Common/DataSanitizer\";\nvar Event = /** @class */function () {\n /**\r\n * Constructs a new instance of the EventTelemetry object\r\n */\n function Event(logger, name, properties, measurements) {\n this.aiDataContract = {\n ver: 1 /* FieldType.Required */,\n name: 1 /* FieldType.Required */,\n properties: 0 /* FieldType.Default */,\n measurements: 0 /* FieldType.Default */\n };\n var _self = this;\n _self.ver = 2;\n _self[_DYN_NAME /* @min:%2ename */] = dataSanitizeString(logger, name) || strNotSpecified;\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\n }\n Event.envelopeType = \"Microsoft.ApplicationInsights.{0}.Event\";\n Event.dataType = \"EventData\";\n return Event;\n}();\nexport { Event };\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { __assignFn as __assign } from \"@microsoft/applicationinsights-shims\";\nimport { arrForEach, arrMap, isArray, isError, isFunction, isNullOrUndefined, isObject, isString, strTrim } from \"@microsoft/applicationinsights-core-js\";\nimport { asString, getWindow, objFreeze, strIndexOf } from \"@nevware21/ts-utils\";\nimport { strNotSpecified } from \"../Constants\";\nimport { _DYN_AI_DATA_CONTRACT, _DYN_ASSEMBLY, _DYN_EXCEPTIONS, _DYN_FILE_NAME, _DYN_HAS_FULL_STACK, _DYN_LENGTH, _DYN_LINE, _DYN_MATCH, _DYN_MEASUREMENTS, _DYN_MESSAGE, _DYN_NAME, _DYN_PARSED_STACK, _DYN_PROBLEM_GROUP, _DYN_PROPERTIES, _DYN_SEVERITY_LEVEL, _DYN_SIZE_IN_BYTES, _DYN_SPLIT, _DYN_STRINGIFY, _DYN_TO_STRING, _DYN_TYPE_NAME } from \"../__DynamicConstants\";\nimport { dataSanitizeException, dataSanitizeMeasurements, dataSanitizeMessage, dataSanitizeProperties, dataSanitizeString } from \"./Common/DataSanitizer\";\n// These Regex covers the following patterns\n// 1. Chrome/Firefox/IE/Edge:\n// at functionName (filename:lineNumber:columnNumber)\n// at functionName (filename:lineNumber)\n// at filename:lineNumber:columnNumber\n// at filename:lineNumber\n// at functionName@filename:lineNumber:columnNumber\n// 2. Safari / Opera:\n// functionName@filename:lineNumber:columnNumber\n// functionName@filename:lineNumber\n// filename:lineNumber:columnNumber\n// filename:lineNumber\n// Line ## of scriptname script filename:lineNumber:columnNumber\n// Line ## of scriptname script filename\n// 3. IE/Edge (Additional formats)\n// at functionName@filename:lineNumber\nvar STACKFRAME_BASE_SIZE = 58; // '{\"method\":\"\",\"level\":,\"assembly\":\"\",\"fileName\":\"\",\"line\":}'.length\n/**\r\n * Check if the string conforms to what looks like a stack frame line and not just a general message\r\n * comment or other non-stack related info.\r\n *\r\n * This should be used to filter out any leading \"message\" lines from a stack trace, before attempting to parse\r\n * the individual stack frames. Once you have estabilsted the start of the stack frames you can then use the\r\n * FULL_STACK_FRAME_1, FULL_STACK_FRAME_2, FULL_STACK_FRAME_3, and EXTRACT_FILENAME to parse the individual\r\n * stack frames to extract the method, filename, line number, and column number.\r\n * These may still provide invalid matches, so the sequence of execution is important to avoid providing\r\n * an invalid parsed stack.\r\n */\nvar IS_FRAME = /^\\s{0,50}(from\\s|at\\s|Line\\s{1,5}\\d{1,10}\\s{1,5}of|\\w{1,50}@\\w{1,80}|[^\\(\\s\\n]+:[0-9\\?]+(?::[0-9\\?]+)?)/;\n/**\r\n * Parse a well formed stack frame with both the line and column numbers\r\n * ----------------------------------\r\n * **Primary focus of the matching**\r\n * - at functionName (filename:lineNumber:columnNumber)\r\n * - at filename:lineNumber:columnNumber\r\n * - at functionName@filename:lineNumber:columnNumber\r\n * - functionName (filename:lineNumber:columnNumber)\r\n * - filename:lineNumber:columnNumber\r\n * - functionName@filename:lineNumber:columnNumber\r\n */\nvar FULL_STACK_FRAME_1 = /^(?:\\s{0,50}at)?\\s{0,50}([^\\@\\()\\s]+)?\\s{0,50}(?:\\s|\\@|\\()\\s{0,5}([^\\(\\s\\n\\]]+):([0-9\\?]+):([0-9\\?]+)\\)?$/;\n/**\r\n * Parse a well formed stack frame with only a line number.\r\n * ----------------------------------\r\n * > Note: this WILL also match with line and column number, but the line number is included with the filename\r\n * > you should attempt to match with FULL_STACK_FRAME_1 first.\r\n *\r\n * **Primary focus of the matching (run FULL_STACK_FRAME_1 first)**\r\n * - at functionName (filename:lineNumber)\r\n * - at filename:lineNumber\r\n * - at functionName@filename:lineNumber\r\n * - functionName (filename:lineNumber)\r\n * - filename:lineNumber\r\n * - functionName@filename:lineNumber\r\n *\r\n * **Secondary matches**\r\n * - at functionName (filename:lineNumber:columnNumber)\r\n * - at filename:lineNumber:columnNumber\r\n * - at functionName@filename:lineNumber:columnNumber\r\n * - functionName (filename:lineNumber:columnNumber)\r\n * - filename:lineNumber:columnNumber\r\n * - functionName@filename:lineNumber:columnNumber\r\n */\nvar FULL_STACK_FRAME_2 = /^(?:\\s{0,50}at)?\\s{0,50}([^\\@\\()\\s]+)?\\s{0,50}(?:\\s|\\@|\\()\\s{0,5}([^\\(\\s\\n\\]]+):([0-9\\?]+)\\)?$/;\n/**\r\n * Attempt to Parse a frame that doesn't include a line or column number.\r\n * ----------------------------------\r\n * > Note: this WILL also match lines with a line or line and column number, you should attempt to match with\r\n * both FULL_STACK_FRAME_1 and FULL_STACK_FRAME_2 first to avoid false positives.\r\n *\r\n * **Unexpected Invalid Matches** (Matches that should be avoided -- by using the FULL_STACK_FRAME_1 and FULL_STACK_FRAME_2 first)\r\n * - at https://localhost:44365/static/node_bundles/@microsoft/blah/js/bundle.js:144112:27\r\n * - at https://localhost:44365/static/node_bundles/@microsoft/blah/js/bundle.js:144112:27\r\n *\r\n * **Primary focus of the matching (run FULL_STACK_FRAME_1 first)**\r\n * - at functionName@filename\r\n * - at functionName (filename)\r\n * - at functionName filename\r\n * - at filename <- Will actuall match this as the \"method\" and not the filename (care should be taken to avoid this)\r\n * - functionName@filename\r\n * - functionName (filename)\r\n * - functionName filename\r\n * - functionName\r\n *\r\n * **Secondary matches** (The line and column numbers will be included with the matched filename)\r\n * - at functionName (filename:lineNumber:columnNumber)\r\n * - at functionName (filename:lineNumber)\r\n * - at filename:lineNumber:columnNumber\r\n * - at filename:lineNumber\r\n * - at functionName@filename:lineNumber:columnNumber\r\n * - at functionName@filename:lineNumber\r\n * - functionName (filename:lineNumber:columnNumber)\r\n * - functionName (filename:lineNumber)\r\n * - filename:lineNumber:columnNumber\r\n * - filename:lineNumber\r\n * - functionName@filename:lineNumber:columnNumber\r\n * - functionName@filename:lineNumber\r\n */\nvar FULL_STACK_FRAME_3 = /^(?:\\s{0,50}at)?\\s{0,50}([^\\@\\()\\s]+)?\\s{0,50}(?:\\s|\\@|\\()\\s{0,5}([^\\(\\s\\n\\)\\]]+)\\)?$/;\n/**\r\n * Attempt to extract the filename (with or without line and column numbers) from a string.\r\n * ----------------------------------\r\n * > Note: this will only match the filename (with any line or column numbers) and will\r\n * > return what looks like the filename, however, it will also match random strings that\r\n * > look like a filename, so care should be taken to ensure that the filename is actually\r\n * > a filename before using it.\r\n * >\r\n * > It is recommended to use this in conjunction with the FULL_STACK_FRAME_1, FULL_STACK_FRAME_2, and FULL_STACK_FRAME_3\r\n * > to ensure first to reduce false matches, if all of these fail then you can use this to extract the filename from a random\r\n * > strings to identify any potential filename from a known stack frame line.\r\n *\r\n * **Known Invalid matching**\r\n *\r\n * This regex will basically match any \"final\" string of a line or one that is trailed by a comma, so this should not\r\n * be used as the \"only\" matching regex, but rather as a final fallback to extract the filename from a string.\r\n * If you are certain that the string line is a stack frame and not part of the exception message (lines before the stack)\r\n * or trailing comments, then you can use this to extract the filename and then further parse with PARSE_FILENAME_LINE_COL\r\n * and PARSE_FILENAME_LINE_ONLY to extract any potential the line and column numbers.\r\n *\r\n * **Primary focus of the matching**\r\n * - at (anonymous) @ VM60:1\r\n * - Line 21 of linked script file://localhost/C:/Temp/stacktrace.js\r\n * - Line 11 of inline#1 script in http://localhost:3000/static/js/main.206f4846.js:2:296748\r\n * - Line 68 of inline#2 script in file://localhost/teststack.html\r\n * - at Global code (http://example.com/stacktrace.js:11:1)\r\n */\nvar EXTRACT_FILENAME = /(?:^|\\(|\\s{0,10}[\\w\\)]+\\@)?([^\\(\\n\\s\\]\\)]+)(?:\\:([0-9]+)(?:\\:([0-9]+))?)?\\)?(?:,|$)/;\n/**\r\n * Attempt to extract the filename, line number, and column number from a string.\r\n */\nvar PARSE_FILENAME_LINE_COL = /([^\\(\\s\\n]+):([0-9]+):([0-9]+)$/;\n/**\r\n * Attempt to extract the filename and line number from a string.\r\n */\nvar PARSE_FILENAME_LINE_ONLY = /([^\\(\\s\\n]+):([0-9]+)$/;\nvar NoMethod = \"\";\nvar strError = \"error\";\nvar strStack = \"stack\";\nvar strStackDetails = \"stackDetails\";\nvar strErrorSrc = \"errorSrc\";\nvar strMessage = \"message\";\nvar strDescription = \"description\";\nvar _parseSequence = [{\n re: FULL_STACK_FRAME_1,\n len: 5,\n m: 1,\n fn: 2,\n ln: 3,\n col: 4\n}, {\n chk: _ignoreNative,\n pre: _scrubAnonymous,\n re: FULL_STACK_FRAME_2,\n len: 4,\n m: 1,\n fn: 2,\n ln: 3\n}, {\n re: FULL_STACK_FRAME_3,\n len: 3,\n m: 1,\n fn: 2,\n hdl: _handleFilename\n}, {\n re: EXTRACT_FILENAME,\n len: 2,\n fn: 1,\n hdl: _handleFilename\n}];\nfunction _scrubAnonymous(frame) {\n return frame.replace(/(\\(anonymous\\))/, \"\");\n}\nfunction _ignoreNative(frame) {\n return strIndexOf(frame, \"[native\") < 0;\n}\nfunction _stringify(value, convertToString) {\n var result = value;\n if (result && !isString(result)) {\n if (JSON && JSON[_DYN_STRINGIFY /* @min:%2estringify */]) {\n result = JSON[_DYN_STRINGIFY /* @min:%2estringify */](value);\n if (convertToString && (!result || result === \"{}\")) {\n if (isFunction(value[_DYN_TO_STRING /* @min:%2etoString */])) {\n result = value[_DYN_TO_STRING /* @min:%2etoString */]();\n } else {\n result = \"\" + value;\n }\n }\n } else {\n result = \"\" + value + \" - (Missing JSON.stringify)\";\n }\n }\n return result || \"\";\n}\nfunction _formatMessage(theEvent, errorType) {\n var evtMessage = theEvent;\n if (theEvent) {\n if (evtMessage && !isString(evtMessage)) {\n evtMessage = theEvent[strMessage] || theEvent[strDescription] || evtMessage;\n }\n // Make sure the message is a string\n if (evtMessage && !isString(evtMessage)) {\n // tslint:disable-next-line: prefer-conditional-expression\n evtMessage = _stringify(evtMessage, true);\n }\n if (theEvent[\"filename\"]) {\n // Looks like an event object with filename\n evtMessage = evtMessage + \" @\" + (theEvent[\"filename\"] || \"\") + \":\" + (theEvent[\"lineno\"] || \"?\") + \":\" + (theEvent[\"colno\"] || \"?\");\n }\n }\n // Automatically add the error type to the message if it does already appear to be present\n if (errorType && errorType !== \"String\" && errorType !== \"Object\" && errorType !== \"Error\" && strIndexOf(evtMessage || \"\", errorType) === -1) {\n evtMessage = errorType + \": \" + evtMessage;\n }\n return evtMessage || \"\";\n}\nfunction _isExceptionDetailsInternal(value) {\n try {\n if (isObject(value)) {\n return \"hasFullStack\" in value && \"typeName\" in value;\n }\n } catch (e) {\n // This can happen with some native browser objects, but should not happen for the type we are checking for\n }\n return false;\n}\nfunction _isExceptionInternal(value) {\n try {\n if (isObject(value)) {\n return \"ver\" in value && \"exceptions\" in value && \"properties\" in value;\n }\n } catch (e) {\n // This can happen with some native browser objects, but should not happen for the type we are checking for\n }\n return false;\n}\nfunction _isStackDetails(details) {\n return details && details.src && isString(details.src) && details.obj && isArray(details.obj);\n}\nfunction _convertStackObj(errorStack) {\n var src = errorStack || \"\";\n if (!isString(src)) {\n if (isString(src[strStack])) {\n src = src[strStack];\n } else {\n src = \"\" + src;\n }\n }\n var items = src[_DYN_SPLIT /* @min:%2esplit */](\"\\n\");\n return {\n src: src,\n obj: items\n };\n}\nfunction _getOperaStack(errorMessage) {\n var stack = [];\n var lines = errorMessage[_DYN_SPLIT /* @min:%2esplit */](\"\\n\");\n for (var lp = 0; lp < lines[_DYN_LENGTH /* @min:%2elength */]; lp++) {\n var entry = lines[lp];\n if (lines[lp + 1]) {\n entry += \"@\" + lines[lp + 1];\n lp++;\n }\n stack.push(entry);\n }\n return {\n src: errorMessage,\n obj: stack\n };\n}\nfunction _getStackFromErrorObj(errorObj) {\n var details = null;\n if (errorObj) {\n try {\n /* Using bracket notation is support older browsers (IE 7/8 -- dont remember the version) that throw when using dot\r\n notation for undefined objects and we don't want to loose the error from being reported */\n if (errorObj[strStack]) {\n // Chrome/Firefox\n details = _convertStackObj(errorObj[strStack]);\n } else if (errorObj[strError] && errorObj[strError][strStack]) {\n // Edge error event provides the stack and error object\n details = _convertStackObj(errorObj[strError][strStack]);\n } else if (errorObj[\"exception\"] && errorObj.exception[strStack]) {\n details = _convertStackObj(errorObj.exception[strStack]);\n } else if (_isStackDetails(errorObj)) {\n details = errorObj;\n } else if (_isStackDetails(errorObj[strStackDetails])) {\n details = errorObj[strStackDetails];\n } else if (getWindow() && getWindow()[\"opera\"] && errorObj[strMessage]) {\n // Opera\n details = _getOperaStack(errorObj[_DYN_MESSAGE /* @min:%2emessage */]);\n } else if (errorObj[\"reason\"] && errorObj.reason[strStack]) {\n // UnhandledPromiseRejection\n details = _convertStackObj(errorObj.reason[strStack]);\n } else if (isString(errorObj)) {\n details = _convertStackObj(errorObj);\n } else {\n var evtMessage = errorObj[strMessage] || errorObj[strDescription] || \"\";\n if (isString(errorObj[strErrorSrc])) {\n if (evtMessage) {\n evtMessage += \"\\n\";\n }\n evtMessage += \" from \" + errorObj[strErrorSrc];\n }\n if (evtMessage) {\n details = _convertStackObj(evtMessage);\n }\n }\n } catch (e) {\n // something unexpected happened so to avoid failing to report any error lets swallow the exception\n // and fallback to the callee/caller method\n details = _convertStackObj(e);\n }\n }\n return details || {\n src: \"\",\n obj: null\n };\n}\nfunction _formatStackTrace(stackDetails) {\n var stack = \"\";\n if (stackDetails) {\n if (stackDetails.obj) {\n stack = stackDetails.obj.join(\"\\n\");\n } else {\n stack = stackDetails.src || \"\";\n }\n }\n return stack;\n}\nfunction _parseStack(stack) {\n var parsedStack;\n var frames = stack.obj;\n if (frames && frames[_DYN_LENGTH /* @min:%2elength */] > 0) {\n parsedStack = [];\n var level_1 = 0;\n var foundStackStart_1 = false;\n var totalSizeInBytes_1 = 0;\n arrForEach(frames, function (frame) {\n if (foundStackStart_1 || _isStackFrame(frame)) {\n var theFrame = asString(frame);\n // Once we have found the first stack frame we treat the rest of the lines as part of the stack\n foundStackStart_1 = true;\n var parsedFrame = _extractStackFrame(theFrame, level_1);\n if (parsedFrame) {\n totalSizeInBytes_1 += parsedFrame[_DYN_SIZE_IN_BYTES /* @min:%2esizeInBytes */];\n parsedStack.push(parsedFrame);\n level_1++;\n }\n }\n });\n // DP Constraint - exception parsed stack must be < 32KB\n // remove frames from the middle to meet the threshold\n var exceptionParsedStackThreshold = 32 * 1024;\n if (totalSizeInBytes_1 > exceptionParsedStackThreshold) {\n var left = 0;\n var right = parsedStack[_DYN_LENGTH /* @min:%2elength */] - 1;\n var size = 0;\n var acceptedLeft = left;\n var acceptedRight = right;\n while (left < right) {\n // check size\n var lSize = parsedStack[left][_DYN_SIZE_IN_BYTES /* @min:%2esizeInBytes */];\n var rSize = parsedStack[right][_DYN_SIZE_IN_BYTES /* @min:%2esizeInBytes */];\n size += lSize + rSize;\n if (size > exceptionParsedStackThreshold) {\n // remove extra frames from the middle\n var howMany = acceptedRight - acceptedLeft + 1;\n parsedStack.splice(acceptedLeft, howMany);\n break;\n }\n // update pointers\n acceptedLeft = left;\n acceptedRight = right;\n left++;\n right--;\n }\n }\n }\n return parsedStack;\n}\nfunction _getErrorType(errorType) {\n // Gets the Error Type by passing the constructor (used to get the true type of native error object).\n var typeName = \"\";\n if (errorType) {\n typeName = errorType.typeName || errorType[_DYN_NAME /* @min:%2ename */] || \"\";\n if (!typeName) {\n try {\n var funcNameRegex = /function (.{1,200})\\(/;\n var results = funcNameRegex.exec(errorType.constructor[_DYN_TO_STRING /* @min:%2etoString */]());\n typeName = results && results[_DYN_LENGTH /* @min:%2elength */] > 1 ? results[1] : \"\";\n } catch (e) {\n // eslint-disable-next-line no-empty -- Ignoring any failures as nothing we can do\n }\n }\n }\n return typeName;\n}\n/**\r\n * Formats the provided errorObj for display and reporting, it may be a String, Object, integer or undefined depending on the browser.\r\n * @param errorObj - The supplied errorObj\r\n */\nexport function _formatErrorCode(errorObj) {\n if (errorObj) {\n try {\n if (!isString(errorObj)) {\n var errorType = _getErrorType(errorObj);\n var result = _stringify(errorObj, false);\n if (!result || result === \"{}\") {\n if (errorObj[strError]) {\n // Looks like an MS Error Event\n errorObj = errorObj[strError];\n errorType = _getErrorType(errorObj);\n }\n result = _stringify(errorObj, true);\n }\n if (strIndexOf(result, errorType) !== 0 && errorType !== \"String\") {\n return errorType + \":\" + result;\n }\n return result;\n }\n } catch (e) {\n // eslint-disable-next-line no-empty -- Ignoring any failures as nothing we can do\n }\n }\n // Fallback to just letting the object format itself into a string\n return \"\" + (errorObj || \"\");\n}\nvar Exception = /** @class */function () {\n /**\r\n * Constructs a new instance of the ExceptionTelemetry object\r\n */\n function Exception(logger, exception, properties, measurements, severityLevel, id) {\n this.aiDataContract = {\n ver: 1 /* FieldType.Required */,\n exceptions: 1 /* FieldType.Required */,\n severityLevel: 0 /* FieldType.Default */,\n properties: 0 /* FieldType.Default */,\n measurements: 0 /* FieldType.Default */\n };\n var _self = this;\n _self.ver = 2; // TODO: handle the CS\"4.0\" ==> breeze 2 conversion in a better way\n if (!_isExceptionInternal(exception)) {\n if (!properties) {\n properties = {};\n }\n if (id) {\n properties.id = id;\n }\n _self[_DYN_EXCEPTIONS /* @min:%2eexceptions */] = [_createExceptionDetails(logger, exception, properties)];\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\n if (severityLevel) {\n _self[_DYN_SEVERITY_LEVEL /* @min:%2eseverityLevel */] = severityLevel;\n }\n if (id) {\n _self.id = id;\n }\n } else {\n _self[_DYN_EXCEPTIONS /* @min:%2eexceptions */] = exception[_DYN_EXCEPTIONS /* @min:%2eexceptions */] || [];\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = exception[_DYN_PROPERTIES /* @min:%2eproperties */];\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = exception[_DYN_MEASUREMENTS /* @min:%2emeasurements */];\n if (exception[_DYN_SEVERITY_LEVEL /* @min:%2eseverityLevel */]) {\n _self[_DYN_SEVERITY_LEVEL /* @min:%2eseverityLevel */] = exception[_DYN_SEVERITY_LEVEL /* @min:%2eseverityLevel */];\n }\n if (exception.id) {\n _self.id = exception.id;\n exception[_DYN_PROPERTIES /* @min:%2eproperties */].id = exception.id;\n }\n if (exception[_DYN_PROBLEM_GROUP /* @min:%2eproblemGroup */]) {\n _self[_DYN_PROBLEM_GROUP /* @min:%2eproblemGroup */] = exception[_DYN_PROBLEM_GROUP /* @min:%2eproblemGroup */];\n }\n // bool/int types, use isNullOrUndefined\n if (!isNullOrUndefined(exception.isManual)) {\n _self.isManual = exception.isManual;\n }\n }\n }\n Exception.CreateAutoException = function (message, url, lineNumber, columnNumber, error, evt, stack, errorSrc) {\n var errorType = _getErrorType(error || evt || message);\n return {\n message: _formatMessage(message, errorType),\n url: url,\n lineNumber: lineNumber,\n columnNumber: columnNumber,\n error: _formatErrorCode(error || evt || message),\n evt: _formatErrorCode(evt || message),\n typeName: errorType,\n stackDetails: _getStackFromErrorObj(stack || error || evt),\n errorSrc: errorSrc\n };\n };\n Exception.CreateFromInterface = function (logger, exception, properties, measurements) {\n var exceptions = exception[_DYN_EXCEPTIONS /* @min:%2eexceptions */] && arrMap(exception[_DYN_EXCEPTIONS /* @min:%2eexceptions */], function (ex) {\n return _createExDetailsFromInterface(logger, ex);\n });\n var exceptionData = new Exception(logger, __assign(__assign({}, exception), {\n exceptions: exceptions\n }), properties, measurements);\n return exceptionData;\n };\n Exception.prototype.toInterface = function () {\n var _a = this,\n exceptions = _a.exceptions,\n properties = _a.properties,\n measurements = _a.measurements,\n severityLevel = _a.severityLevel,\n problemGroup = _a.problemGroup,\n id = _a.id,\n isManual = _a.isManual;\n var exceptionDetailsInterface = exceptions instanceof Array && arrMap(exceptions, function (exception) {\n return exception.toInterface();\n }) || undefined;\n return {\n ver: \"4.0\",\n exceptions: exceptionDetailsInterface,\n severityLevel: severityLevel,\n properties: properties,\n measurements: measurements,\n problemGroup: problemGroup,\n id: id,\n isManual: isManual\n };\n };\n /**\r\n * Creates a simple exception with 1 stack frame. Useful for manual constracting of exception.\r\n */\n Exception.CreateSimpleException = function (message, typeName, assembly, fileName, details, line) {\n var _a;\n return {\n exceptions: [(_a = {}, _a[_DYN_HAS_FULL_STACK /* @min:hasFullStack */] = true, _a.message = message, _a.stack = details, _a.typeName = typeName, _a)]\n };\n };\n Exception.envelopeType = \"Microsoft.ApplicationInsights.{0}.Exception\";\n Exception.dataType = \"ExceptionData\";\n Exception.formatError = _formatErrorCode;\n return Exception;\n}();\nexport { Exception };\nvar exDetailsAiDataContract = objFreeze({\n id: 0 /* FieldType.Default */,\n outerId: 0 /* FieldType.Default */,\n typeName: 1 /* FieldType.Required */,\n message: 1 /* FieldType.Required */,\n hasFullStack: 0 /* FieldType.Default */,\n stack: 0 /* FieldType.Default */,\n parsedStack: 2 /* FieldType.Array */\n});\nfunction _toInterface() {\n var _self = this;\n var parsedStack = isArray(_self[_DYN_PARSED_STACK /* @min:%2eparsedStack */]) && arrMap(_self[_DYN_PARSED_STACK /* @min:%2eparsedStack */], function (frame) {\n return _parsedFrameToInterface(frame);\n });\n var exceptionDetailsInterface = {\n id: _self.id,\n outerId: _self.outerId,\n typeName: _self[_DYN_TYPE_NAME /* @min:%2etypeName */],\n message: _self[_DYN_MESSAGE /* @min:%2emessage */],\n hasFullStack: _self[_DYN_HAS_FULL_STACK /* @min:%2ehasFullStack */],\n stack: _self[strStack],\n parsedStack: parsedStack || undefined\n };\n return exceptionDetailsInterface;\n}\nexport function _createExceptionDetails(logger, exception, properties) {\n var _a;\n var id;\n var outerId;\n var typeName;\n var message;\n var hasFullStack;\n var theStack;\n var parsedStack;\n if (!_isExceptionDetailsInternal(exception)) {\n var error = exception;\n var evt = error && error.evt;\n if (!isError(error)) {\n error = error[strError] || evt || error;\n }\n typeName = dataSanitizeString(logger, _getErrorType(error)) || strNotSpecified;\n message = dataSanitizeMessage(logger, _formatMessage(exception || error, typeName)) || strNotSpecified;\n var stack = exception[strStackDetails] || _getStackFromErrorObj(exception);\n parsedStack = _parseStack(stack);\n // after parsedStack is inited, iterate over each frame object, sanitize its assembly field\n if (isArray(parsedStack)) {\n arrMap(parsedStack, function (frame) {\n frame[_DYN_ASSEMBLY /* @min:%2eassembly */] = dataSanitizeString(logger, frame[_DYN_ASSEMBLY /* @min:%2eassembly */]);\n frame[_DYN_FILE_NAME /* @min:%2efileName */] = dataSanitizeString(logger, frame[_DYN_FILE_NAME /* @min:%2efileName */]);\n });\n }\n theStack = dataSanitizeException(logger, _formatStackTrace(stack));\n hasFullStack = isArray(parsedStack) && parsedStack[_DYN_LENGTH /* @min:%2elength */] > 0;\n if (properties) {\n properties[_DYN_TYPE_NAME /* @min:%2etypeName */] = properties[_DYN_TYPE_NAME /* @min:%2etypeName */] || typeName;\n }\n } else {\n typeName = exception[_DYN_TYPE_NAME /* @min:%2etypeName */];\n message = exception[_DYN_MESSAGE /* @min:%2emessage */];\n theStack = exception[strStack];\n parsedStack = exception[_DYN_PARSED_STACK /* @min:%2eparsedStack */] || [];\n hasFullStack = exception[_DYN_HAS_FULL_STACK /* @min:%2ehasFullStack */];\n }\n return _a = {}, _a[_DYN_AI_DATA_CONTRACT /* @min:aiDataContract */] = exDetailsAiDataContract, _a.id = id, _a.outerId = outerId, _a.typeName = typeName, _a.message = message, _a[_DYN_HAS_FULL_STACK /* @min:hasFullStack */] = hasFullStack, _a.stack = theStack, _a.parsedStack = parsedStack, _a.toInterface = _toInterface, _a;\n}\nexport function _createExDetailsFromInterface(logger, exception) {\n var parsedStack = isArray(exception[_DYN_PARSED_STACK /* @min:%2eparsedStack */]) && arrMap(exception[_DYN_PARSED_STACK /* @min:%2eparsedStack */], function (frame) {\n return _stackFrameFromInterface(frame);\n }) || exception[_DYN_PARSED_STACK /* @min:%2eparsedStack */];\n var exceptionDetails = _createExceptionDetails(logger, __assign(__assign({}, exception), {\n parsedStack: parsedStack\n }));\n return exceptionDetails;\n}\nfunction _parseFilename(theFrame, fileName) {\n var lineCol = fileName[_DYN_MATCH /* @min:%2ematch */](PARSE_FILENAME_LINE_COL);\n if (lineCol && lineCol[_DYN_LENGTH /* @min:%2elength */] >= 4) {\n theFrame[_DYN_FILE_NAME /* @min:%2efileName */] = lineCol[1];\n theFrame[_DYN_LINE /* @min:%2eline */] = parseInt(lineCol[2]);\n } else {\n var lineNo = fileName[_DYN_MATCH /* @min:%2ematch */](PARSE_FILENAME_LINE_ONLY);\n if (lineNo && lineNo[_DYN_LENGTH /* @min:%2elength */] >= 3) {\n theFrame[_DYN_FILE_NAME /* @min:%2efileName */] = lineNo[1];\n theFrame[_DYN_LINE /* @min:%2eline */] = parseInt(lineNo[2]);\n } else {\n theFrame[_DYN_FILE_NAME /* @min:%2efileName */] = fileName;\n }\n }\n}\nfunction _handleFilename(theFrame, sequence, matches) {\n var filename = theFrame[_DYN_FILE_NAME /* @min:%2efileName */];\n if (sequence.fn && matches && matches[_DYN_LENGTH /* @min:%2elength */] > sequence.fn) {\n if (sequence.ln && matches[_DYN_LENGTH /* @min:%2elength */] > sequence.ln) {\n filename = strTrim(matches[sequence.fn] || \"\");\n theFrame[_DYN_LINE /* @min:%2eline */] = parseInt(strTrim(matches[sequence.ln] || \"\")) || 0;\n } else {\n filename = strTrim(matches[sequence.fn] || \"\");\n }\n }\n if (filename) {\n _parseFilename(theFrame, filename);\n }\n}\nfunction _isStackFrame(frame) {\n var result = false;\n if (frame && isString(frame)) {\n var trimmedFrame = strTrim(frame);\n if (trimmedFrame) {\n result = IS_FRAME.test(trimmedFrame);\n }\n }\n return result;\n}\nvar stackFrameAiDataContract = objFreeze({\n level: 1 /* FieldType.Required */,\n method: 1 /* FieldType.Required */,\n assembly: 0 /* FieldType.Default */,\n fileName: 0 /* FieldType.Default */,\n line: 0 /* FieldType.Default */\n});\nexport function _extractStackFrame(frame, level) {\n var _a;\n var theFrame;\n if (frame && isString(frame) && strTrim(frame)) {\n theFrame = (_a = {}, _a[_DYN_AI_DATA_CONTRACT /* @min:aiDataContract */] = stackFrameAiDataContract, _a.level = level, _a.assembly = strTrim(frame), _a.method = NoMethod, _a.fileName = \"\", _a.line = 0, _a.sizeInBytes = 0, _a);\n var idx = 0;\n while (idx < _parseSequence[_DYN_LENGTH /* @min:%2elength */]) {\n var sequence = _parseSequence[idx];\n if (sequence.chk && !sequence.chk(frame)) {\n break;\n }\n if (sequence.pre) {\n frame = sequence.pre(frame);\n }\n // Attempt to \"parse\" the stack frame\n var matches = frame[_DYN_MATCH /* @min:%2ematch */](sequence.re);\n if (matches && matches[_DYN_LENGTH /* @min:%2elength */] >= sequence.len) {\n if (sequence.m) {\n theFrame.method = strTrim(matches[sequence.m] || NoMethod);\n }\n if (sequence.hdl) {\n // Run any custom handler\n sequence.hdl(theFrame, sequence, matches);\n } else if (sequence.fn) {\n if (sequence.ln) {\n theFrame[_DYN_FILE_NAME /* @min:%2efileName */] = strTrim(matches[sequence.fn] || \"\");\n theFrame[_DYN_LINE /* @min:%2eline */] = parseInt(strTrim(matches[sequence.ln] || \"\")) || 0;\n } else {\n _parseFilename(theFrame, matches[sequence.fn] || \"\");\n }\n }\n // We found a match so stop looking\n break;\n }\n idx++;\n }\n }\n return _populateFrameSizeInBytes(theFrame);\n}\nfunction _stackFrameFromInterface(frame) {\n var _a;\n var parsedFrame = (_a = {}, _a[_DYN_AI_DATA_CONTRACT /* @min:aiDataContract */] = stackFrameAiDataContract, _a.level = frame.level, _a.method = frame.method, _a.assembly = frame[_DYN_ASSEMBLY /* @min:%2eassembly */], _a.fileName = frame[_DYN_FILE_NAME /* @min:%2efileName */], _a.line = frame[_DYN_LINE /* @min:%2eline */], _a.sizeInBytes = 0, _a);\n return _populateFrameSizeInBytes(parsedFrame);\n}\nfunction _populateFrameSizeInBytes(frame) {\n var sizeInBytes = STACKFRAME_BASE_SIZE;\n if (frame) {\n sizeInBytes += frame.method[_DYN_LENGTH /* @min:%2elength */];\n sizeInBytes += frame.assembly[_DYN_LENGTH /* @min:%2elength */];\n sizeInBytes += frame.fileName[_DYN_LENGTH /* @min:%2elength */];\n sizeInBytes += frame.level.toString()[_DYN_LENGTH /* @min:%2elength */];\n sizeInBytes += frame.line.toString()[_DYN_LENGTH /* @min:%2elength */];\n frame[_DYN_SIZE_IN_BYTES /* @min:%2esizeInBytes */] = sizeInBytes;\n }\n return frame;\n}\nexport function _parsedFrameToInterface(frame) {\n return {\n level: frame.level,\n method: frame.method,\n assembly: frame[_DYN_ASSEMBLY /* @min:%2eassembly */],\n fileName: frame[_DYN_FILE_NAME /* @min:%2efileName */],\n line: frame[_DYN_LINE /* @min:%2eline */]\n };\n}\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nvar DataPoint = /** @class */function () {\n function DataPoint() {\n /**\r\n * The data contract for serializing this object.\r\n */\n this.aiDataContract = {\n name: 1 /* FieldType.Required */,\n kind: 0 /* FieldType.Default */,\n value: 1 /* FieldType.Required */,\n count: 0 /* FieldType.Default */,\n min: 0 /* FieldType.Default */,\n max: 0 /* FieldType.Default */,\n stdDev: 0 /* FieldType.Default */\n };\n /**\r\n * Metric type. Single measurement or the aggregated value.\r\n */\n this.kind = 0 /* DataPointType.Measurement */;\n }\n return DataPoint;\n}();\nexport { DataPoint };\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { strNotSpecified } from \"../Constants\";\nimport { _DYN_COUNT, _DYN_MEASUREMENTS, _DYN_NAME, _DYN_PROPERTIES } from \"../__DynamicConstants\";\nimport { DataPoint } from \"./Common/DataPoint\";\nimport { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString } from \"./Common/DataSanitizer\";\nvar Metric = /** @class */function () {\n /**\r\n * Constructs a new instance of the MetricTelemetry object\r\n */\n function Metric(logger, name, value, count, min, max, stdDev, properties, measurements) {\n this.aiDataContract = {\n ver: 1 /* FieldType.Required */,\n metrics: 1 /* FieldType.Required */,\n properties: 0 /* FieldType.Default */\n };\n var _self = this;\n _self.ver = 2;\n var dataPoint = new DataPoint();\n dataPoint[_DYN_COUNT /* @min:%2ecount */] = count > 0 ? count : undefined;\n dataPoint.max = isNaN(max) || max === null ? undefined : max;\n dataPoint.min = isNaN(min) || min === null ? undefined : min;\n dataPoint[_DYN_NAME /* @min:%2ename */] = dataSanitizeString(logger, name) || strNotSpecified;\n dataPoint.value = value;\n dataPoint.stdDev = isNaN(stdDev) || stdDev === null ? undefined : stdDev;\n _self.metrics = [dataPoint];\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\n }\n Metric.envelopeType = \"Microsoft.ApplicationInsights.{0}.Metric\";\n Metric.dataType = \"MetricData\";\n return Metric;\n}();\nexport { Metric };\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { arrForEach, isString } from \"@microsoft/applicationinsights-core-js\";\nimport { mathFloor, mathRound } from \"@nevware21/ts-utils\";\nimport { _DYN_LENGTH, _DYN_TO_LOWER_CASE } from \"./__DynamicConstants\";\nvar strEmpty = \"\";\nexport function stringToBoolOrDefault(str, defaultValue) {\n if (defaultValue === void 0) {\n defaultValue = false;\n }\n if (str === undefined || str === null) {\n return defaultValue;\n }\n return str.toString()[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]() === \"true\";\n}\n/**\r\n * Convert ms to c# time span format\r\n */\nexport function msToTimeSpan(totalms) {\n if (isNaN(totalms) || totalms < 0) {\n totalms = 0;\n }\n totalms = mathRound(totalms);\n var ms = strEmpty + totalms % 1000;\n var sec = strEmpty + mathFloor(totalms / 1000) % 60;\n var min = strEmpty + mathFloor(totalms / (1000 * 60)) % 60;\n var hour = strEmpty + mathFloor(totalms / (1000 * 60 * 60)) % 24;\n var days = mathFloor(totalms / (1000 * 60 * 60 * 24));\n ms = ms[_DYN_LENGTH /* @min:%2elength */] === 1 ? \"00\" + ms : ms[_DYN_LENGTH /* @min:%2elength */] === 2 ? \"0\" + ms : ms;\n sec = sec[_DYN_LENGTH /* @min:%2elength */] < 2 ? \"0\" + sec : sec;\n min = min[_DYN_LENGTH /* @min:%2elength */] < 2 ? \"0\" + min : min;\n hour = hour[_DYN_LENGTH /* @min:%2elength */] < 2 ? \"0\" + hour : hour;\n return (days > 0 ? days + \".\" : strEmpty) + hour + \":\" + min + \":\" + sec + \".\" + ms;\n}\nexport function getExtensionByName(extensions, identifier) {\n var extension = null;\n arrForEach(extensions, function (value) {\n if (value.identifier === identifier) {\n extension = value;\n return -1;\n }\n });\n return extension;\n}\nexport function isCrossOriginError(message, url, lineNumber, columnNumber, error) {\n return !error && isString(message) && (message === \"Script error.\" || message === \"Script error\");\n}\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { strNotSpecified } from \"../Constants\";\nimport { msToTimeSpan } from \"../HelperFuncs\";\nimport { _DYN_DURATION, _DYN_MEASUREMENTS, _DYN_NAME, _DYN_PROPERTIES } from \"../__DynamicConstants\";\nimport { dataSanitizeId, dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString, dataSanitizeUrl } from \"./Common/DataSanitizer\";\nvar PageView = /** @class */function () {\n /**\r\n * Constructs a new instance of the PageEventTelemetry object\r\n */\n function PageView(logger, name, url, durationMs, properties, measurements, id) {\n this.aiDataContract = {\n ver: 1 /* FieldType.Required */,\n name: 0 /* FieldType.Default */,\n url: 0 /* FieldType.Default */,\n duration: 0 /* FieldType.Default */,\n properties: 0 /* FieldType.Default */,\n measurements: 0 /* FieldType.Default */,\n id: 0 /* FieldType.Default */\n };\n var _self = this;\n _self.ver = 2;\n _self.id = dataSanitizeId(logger, id);\n _self.url = dataSanitizeUrl(logger, url);\n _self[_DYN_NAME /* @min:%2ename */] = dataSanitizeString(logger, name) || strNotSpecified;\n if (!isNaN(durationMs)) {\n _self[_DYN_DURATION /* @min:%2eduration */] = msToTimeSpan(durationMs);\n }\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\n }\n PageView.envelopeType = \"Microsoft.ApplicationInsights.{0}.Pageview\";\n PageView.dataType = \"PageviewData\";\n return PageView;\n}();\nexport { PageView };\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { msToTimeSpan } from \"../HelperFuncs\";\nimport { AjaxHelperParseDependencyPath } from \"../Util\";\nimport { _DYN_DURATION, _DYN_MEASUREMENTS, _DYN_NAME, _DYN_PROPERTIES } from \"../__DynamicConstants\";\nimport { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString, dataSanitizeUrl } from \"./Common/DataSanitizer\";\nvar RemoteDependencyData = /** @class */function () {\n /**\r\n * Constructs a new instance of the RemoteDependencyData object\r\n */\n function RemoteDependencyData(logger, id, absoluteUrl, commandName, value, success, resultCode, method, requestAPI, correlationContext, properties, measurements) {\n if (requestAPI === void 0) {\n requestAPI = \"Ajax\";\n }\n this.aiDataContract = {\n id: 1 /* FieldType.Required */,\n ver: 1 /* FieldType.Required */,\n name: 0 /* FieldType.Default */,\n resultCode: 0 /* FieldType.Default */,\n duration: 0 /* FieldType.Default */,\n success: 0 /* FieldType.Default */,\n data: 0 /* FieldType.Default */,\n target: 0 /* FieldType.Default */,\n type: 0 /* FieldType.Default */,\n properties: 0 /* FieldType.Default */,\n measurements: 0 /* FieldType.Default */,\n kind: 0 /* FieldType.Default */,\n value: 0 /* FieldType.Default */,\n count: 0 /* FieldType.Default */,\n min: 0 /* FieldType.Default */,\n max: 0 /* FieldType.Default */,\n stdDev: 0 /* FieldType.Default */,\n dependencyKind: 0 /* FieldType.Default */,\n dependencySource: 0 /* FieldType.Default */,\n commandName: 0 /* FieldType.Default */,\n dependencyTypeName: 0 /* FieldType.Default */\n };\n var _self = this;\n _self.ver = 2;\n _self.id = id;\n _self[_DYN_DURATION /* @min:%2eduration */] = msToTimeSpan(value);\n _self.success = success;\n _self.resultCode = resultCode + \"\";\n _self.type = dataSanitizeString(logger, requestAPI);\n var dependencyFields = AjaxHelperParseDependencyPath(logger, absoluteUrl, method, commandName);\n _self.data = dataSanitizeUrl(logger, commandName) || dependencyFields.data; // get a value from hosturl if commandName not available\n _self.target = dataSanitizeString(logger, dependencyFields.target);\n if (correlationContext) {\n _self.target = \"\".concat(_self.target, \" | \").concat(correlationContext);\n }\n _self[_DYN_NAME /* @min:%2ename */] = dataSanitizeString(logger, dependencyFields[_DYN_NAME /* @min:%2ename */]);\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\n }\n RemoteDependencyData.envelopeType = \"Microsoft.ApplicationInsights.{0}.RemoteDependency\";\n RemoteDependencyData.dataType = \"RemoteDependencyData\";\n return RemoteDependencyData;\n}();\nexport { RemoteDependencyData };\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { strNotSpecified } from \"../Constants\";\nimport { _DYN_MEASUREMENTS, _DYN_MESSAGE, _DYN_PROPERTIES, _DYN_SEVERITY_LEVEL } from \"../__DynamicConstants\";\nimport { dataSanitizeMeasurements, dataSanitizeMessage, dataSanitizeProperties } from \"./Common/DataSanitizer\";\nvar Trace = /** @class */function () {\n /**\r\n * Constructs a new instance of the TraceTelemetry object\r\n */\n function Trace(logger, message, severityLevel, properties, measurements) {\n this.aiDataContract = {\n ver: 1 /* FieldType.Required */,\n message: 1 /* FieldType.Required */,\n severityLevel: 0 /* FieldType.Default */,\n properties: 0 /* FieldType.Default */\n };\n var _self = this;\n _self.ver = 2;\n message = message || strNotSpecified;\n _self[_DYN_MESSAGE /* @min:%2emessage */] = dataSanitizeMessage(logger, message);\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\n if (severityLevel) {\n _self[_DYN_SEVERITY_LEVEL /* @min:%2eseverityLevel */] = severityLevel;\n }\n }\n Trace.envelopeType = \"Microsoft.ApplicationInsights.{0}.Message\";\n Trace.dataType = \"MessageData\";\n return Trace;\n}();\nexport { Trace };\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { strNotSpecified } from \"../Constants\";\nimport { _DYN_DURATION, _DYN_MEASUREMENTS, _DYN_NAME, _DYN_PROPERTIES } from \"../__DynamicConstants\";\nimport { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString, dataSanitizeUrl } from \"./Common/DataSanitizer\";\nvar PageViewPerformance = /** @class */function () {\n /**\r\n * Constructs a new instance of the PageEventTelemetry object\r\n */\n function PageViewPerformance(logger, name, url, unused, properties, measurements, cs4BaseData) {\n this.aiDataContract = {\n ver: 1 /* FieldType.Required */,\n name: 0 /* FieldType.Default */,\n url: 0 /* FieldType.Default */,\n duration: 0 /* FieldType.Default */,\n perfTotal: 0 /* FieldType.Default */,\n networkConnect: 0 /* FieldType.Default */,\n sentRequest: 0 /* FieldType.Default */,\n receivedResponse: 0 /* FieldType.Default */,\n domProcessing: 0 /* FieldType.Default */,\n properties: 0 /* FieldType.Default */,\n measurements: 0 /* FieldType.Default */\n };\n var _self = this;\n _self.ver = 2;\n _self.url = dataSanitizeUrl(logger, url);\n _self[_DYN_NAME /* @min:%2ename */] = dataSanitizeString(logger, name) || strNotSpecified;\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\n if (cs4BaseData) {\n _self.domProcessing = cs4BaseData.domProcessing;\n _self[_DYN_DURATION /* @min:%2eduration */] = cs4BaseData[_DYN_DURATION /* @min:%2eduration */];\n _self.networkConnect = cs4BaseData.networkConnect;\n _self.perfTotal = cs4BaseData.perfTotal;\n _self.receivedResponse = cs4BaseData.receivedResponse;\n _self.sentRequest = cs4BaseData.sentRequest;\n }\n }\n PageViewPerformance.envelopeType = \"Microsoft.ApplicationInsights.{0}.PageviewPerformance\";\n PageViewPerformance.dataType = \"PageviewPerformanceData\";\n return PageViewPerformance;\n}();\nexport { PageViewPerformance };\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nvar Data = /** @class */function () {\n /**\r\n * Constructs a new instance of telemetry data.\r\n */\n function Data(baseType, data) {\n /**\r\n * The data contract for serializing this object.\r\n */\n this.aiDataContract = {\n baseType: 1 /* FieldType.Required */,\n baseData: 1 /* FieldType.Required */\n };\n this.baseType = baseType;\n this.baseData = data;\n }\n return Data;\n}();\nexport { Data };\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { __extendsFn as __extends } from \"@microsoft/applicationinsights-shims\";\nimport { createClassFromInterface } from \"@microsoft/applicationinsights-core-js\";\nfunction _aiNameFunc(baseName) {\n var aiName = \"ai.\" + baseName + \".\";\n return function (name) {\n return aiName + name;\n };\n}\nvar _aiApplication = _aiNameFunc(\"application\");\nvar _aiDevice = _aiNameFunc(\"device\");\nvar _aiLocation = _aiNameFunc(\"location\");\nvar _aiOperation = _aiNameFunc(\"operation\");\nvar _aiSession = _aiNameFunc(\"session\");\nvar _aiUser = _aiNameFunc(\"user\");\nvar _aiCloud = _aiNameFunc(\"cloud\");\nvar _aiInternal = _aiNameFunc(\"internal\");\nvar ContextTagKeys = /** @class */function (_super) {\n __extends(ContextTagKeys, _super);\n function ContextTagKeys() {\n return _super.call(this) || this;\n }\n return ContextTagKeys;\n}(createClassFromInterface({\n applicationVersion: _aiApplication(\"ver\"),\n applicationBuild: _aiApplication(\"build\"),\n applicationTypeId: _aiApplication(\"typeId\"),\n applicationId: _aiApplication(\"applicationId\"),\n applicationLayer: _aiApplication(\"layer\"),\n deviceId: _aiDevice(\"id\"),\n deviceIp: _aiDevice(\"ip\"),\n deviceLanguage: _aiDevice(\"language\"),\n deviceLocale: _aiDevice(\"locale\"),\n deviceModel: _aiDevice(\"model\"),\n deviceFriendlyName: _aiDevice(\"friendlyName\"),\n deviceNetwork: _aiDevice(\"network\"),\n deviceNetworkName: _aiDevice(\"networkName\"),\n deviceOEMName: _aiDevice(\"oemName\"),\n deviceOS: _aiDevice(\"os\"),\n deviceOSVersion: _aiDevice(\"osVersion\"),\n deviceRoleInstance: _aiDevice(\"roleInstance\"),\n deviceRoleName: _aiDevice(\"roleName\"),\n deviceScreenResolution: _aiDevice(\"screenResolution\"),\n deviceType: _aiDevice(\"type\"),\n deviceMachineName: _aiDevice(\"machineName\"),\n deviceVMName: _aiDevice(\"vmName\"),\n deviceBrowser: _aiDevice(\"browser\"),\n deviceBrowserVersion: _aiDevice(\"browserVersion\"),\n locationIp: _aiLocation(\"ip\"),\n locationCountry: _aiLocation(\"country\"),\n locationProvince: _aiLocation(\"province\"),\n locationCity: _aiLocation(\"city\"),\n operationId: _aiOperation(\"id\"),\n operationName: _aiOperation(\"name\"),\n operationParentId: _aiOperation(\"parentId\"),\n operationRootId: _aiOperation(\"rootId\"),\n operationSyntheticSource: _aiOperation(\"syntheticSource\"),\n operationCorrelationVector: _aiOperation(\"correlationVector\"),\n sessionId: _aiSession(\"id\"),\n sessionIsFirst: _aiSession(\"isFirst\"),\n sessionIsNew: _aiSession(\"isNew\"),\n userAccountAcquisitionDate: _aiUser(\"accountAcquisitionDate\"),\n userAccountId: _aiUser(\"accountId\"),\n userAgent: _aiUser(\"userAgent\"),\n userId: _aiUser(\"id\"),\n userStoreRegion: _aiUser(\"storeRegion\"),\n userAuthUserId: _aiUser(\"authUserId\"),\n userAnonymousUserAcquisitionDate: _aiUser(\"anonUserAcquisitionDate\"),\n userAuthenticatedUserAcquisitionDate: _aiUser(\"authUserAcquisitionDate\"),\n cloudName: _aiCloud(\"name\"),\n cloudRole: _aiCloud(\"role\"),\n cloudRoleVer: _aiCloud(\"roleVer\"),\n cloudRoleInstance: _aiCloud(\"roleInstance\"),\n cloudEnvironment: _aiCloud(\"environment\"),\n cloudLocation: _aiCloud(\"location\"),\n cloudDeploymentUnit: _aiCloud(\"deploymentUnit\"),\n internalNodeName: _aiInternal(\"nodeName\"),\n internalSdkVersion: _aiInternal(\"sdkVersion\"),\n internalAgentVersion: _aiInternal(\"agentVersion\"),\n internalSnippet: _aiInternal(\"snippet\"),\n internalSdkSrc: _aiInternal(\"sdkSrc\")\n}));\nexport { ContextTagKeys };\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { isNullOrUndefined, objForEachKey, throwError, toISOString } from \"@microsoft/applicationinsights-core-js\";\nimport { strIkey, strNotSpecified } from \"./Constants\";\nimport { dataSanitizeString } from \"./Telemetry/Common/DataSanitizer\";\n/**\r\n * Create a telemetry item that the 1DS channel understands\r\n * @param item - domain specific properties; part B\r\n * @param baseType - telemetry item type. ie PageViewData\r\n * @param envelopeName - Name of the envelope, e.g., `Microsoft.ApplicationInsights.\\.PageView`.\r\n * @param customProperties - user defined custom properties; part C\r\n * @param systemProperties - system properties that are added to the context; part A\r\n * @returns ITelemetryItem that is sent to channel\r\n */\nexport function createTelemetryItem(item, baseType, envelopeName, logger, customProperties, systemProperties) {\n envelopeName = dataSanitizeString(logger, envelopeName) || strNotSpecified;\n if (isNullOrUndefined(item) || isNullOrUndefined(baseType) || isNullOrUndefined(envelopeName)) {\n throwError(\"Input doesn't contain all required fields\");\n }\n var iKey = \"\";\n if (item[strIkey]) {\n iKey = item[strIkey];\n delete item[strIkey];\n }\n var telemetryItem = {\n name: envelopeName,\n time: toISOString(new Date()),\n iKey: iKey,\n ext: systemProperties ? systemProperties : {},\n tags: [],\n data: {},\n baseType: baseType,\n baseData: item // Part B\n };\n // Part C\n if (!isNullOrUndefined(customProperties)) {\n objForEachKey(customProperties, function (prop, value) {\n telemetryItem.data[prop] = value;\n });\n }\n return telemetryItem;\n}\nvar TelemetryItemCreator = /** @class */function () {\n function TelemetryItemCreator() {}\n /**\r\n * Create a telemetry item that the 1DS channel understands\r\n * @param item - domain specific properties; part B\r\n * @param baseType - telemetry item type. ie PageViewData\r\n * @param envelopeName - Name of the envelope (e.g., Microsoft.ApplicationInsights.[instrumentationKey].PageView).\r\n * @param customProperties - user defined custom properties; part C\r\n * @param systemProperties - system properties that are added to the context; part A\r\n * @returns ITelemetryItem that is sent to channel\r\n */\n TelemetryItemCreator.create = createTelemetryItem;\n return TelemetryItemCreator;\n}();\nexport { TelemetryItemCreator };\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nimport { ContextTagKeys } from \"./Contracts/ContextTagKeys\";\nexport var Extensions = {\n UserExt: \"user\",\n DeviceExt: \"device\",\n TraceExt: \"trace\",\n WebExt: \"web\",\n AppExt: \"app\",\n OSExt: \"os\",\n SessionExt: \"ses\",\n SDKExt: \"sdk\"\n};\nexport var CtxTagKeys = new ContextTagKeys();\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { getDocument, isFunction } from \"@microsoft/applicationinsights-core-js\";\nexport function createDomEvent(eventName) {\n var event = null;\n if (isFunction(Event)) {\n // Use Event constructor when available\n event = new Event(eventName);\n } else {\n // Event has no constructor in IE\n var doc = getDocument();\n if (doc && doc.createEvent) {\n event = doc.createEvent(\"Event\");\n event.initEvent(eventName, true, true);\n }\n }\n return event;\n}\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nimport { arrForEach, createUniqueNamespace, eventOff, eventOn, getDocument, getNavigator, getWindow, isNullOrUndefined, isUndefined, mergeEvtNamespace } from \"@microsoft/applicationinsights-core-js\";\nfunction _disableEvents(target, evtNamespace) {\n eventOff(target, null, null, evtNamespace);\n}\n/**\r\n * Create a new OfflineListener instance to monitor browser online / offline events\r\n * @param parentEvtNamespace - The parent event namespace to append to any specific events for this instance\r\n */\nexport function createOfflineListener(parentEvtNamespace) {\n var _document = getDocument();\n var _navigator = getNavigator(); // Gets the window.navigator or workerNavigator depending on the global\n var _isListening = false;\n var listenerList = [];\n // Set the initial state\n // rState is changed by the browser, both via events and when we check the navigator.onLine property\n var rState = 1 /* eOfflineValue.Online */;\n if (_navigator && !isNullOrUndefined(_navigator.onLine) && !_navigator.onLine) {\n // navigator.onLine is undefined in react-native\n rState = 2 /* eOfflineValue.Offline */;\n }\n // ustate is changed by the user calling setOnlineState\n var uState = 0 /* eOfflineValue.Unknown */;\n // current state would be updated each time rState or uState is changed\n // it is a resolved value of rState and uState\n var _currentState = calCurrentState();\n var _evtNamespace = mergeEvtNamespace(createUniqueNamespace(\"OfflineListener\"), parentEvtNamespace);\n try {\n if (_enableEvents(getWindow())) {\n _isListening = true;\n }\n if (_document) {\n // Also attach to the document.body or document\n var target = _document.body || _document;\n if (target.ononline) {\n if (_enableEvents(target)) {\n _isListening = true;\n }\n }\n }\n } catch (e) {\n // this makes react-native less angry\n _isListening = false;\n }\n function _enableEvents(target) {\n var enabled = false;\n if (target) {\n enabled = eventOn(target, \"online\", _setOnline, _evtNamespace);\n if (enabled) {\n eventOn(target, \"offline\", _setOffline, _evtNamespace);\n }\n }\n return enabled;\n }\n function _isOnline() {\n return _currentState;\n }\n function calCurrentState() {\n if (uState === 2 /* eOfflineValue.Offline */ || rState === 2 /* eOfflineValue.Offline */) {\n return false;\n }\n return true; // if both unknown, then we assume the network is good\n }\n function listnerNoticeCheck() {\n // we were offline and are now online or we were online and now offline\n var newState = calCurrentState();\n if (_currentState !== newState) {\n _currentState = newState; // use the resolved state to update\n // send all the callbacks with the current state\n arrForEach(listenerList, function (callback) {\n var offlineState = {\n isOnline: _currentState,\n rState: rState,\n uState: uState\n };\n try {\n callback(offlineState);\n } catch (e) {\n // Do nothing, just making sure we run all of the callbacks\n }\n });\n }\n }\n function setOnlineState(newState) {\n uState = newState;\n listnerNoticeCheck();\n }\n function _setOnline() {\n rState = 1 /* eOfflineValue.Online */;\n listnerNoticeCheck();\n }\n function _setOffline() {\n rState = 2 /* eOfflineValue.Offline */;\n listnerNoticeCheck();\n }\n function _unload() {\n var win = getWindow();\n if (win && _isListening) {\n _disableEvents(win, _evtNamespace);\n if (_document) {\n // Also attach to the document.body or document\n var target = _document.body || _document;\n if (!isUndefined(target.ononline)) {\n _disableEvents(target, _evtNamespace);\n }\n }\n _isListening = false;\n }\n }\n function addListener(callback) {\n listenerList.push(callback);\n // Define rm as an instance of IUnloadHook\n return {\n rm: function () {\n var index = listenerList.indexOf(callback);\n if (index > -1) {\n return listenerList.splice(index, 1);\n } else {\n return;\n }\n }\n };\n }\n return {\n isOnline: _isOnline,\n isListening: function () {\n return _isListening;\n },\n unload: _unload,\n addListener: addListener,\n setOnlineState: setOnlineState\n };\n}\n","/*\n * Application Insights JavaScript SDK - Common, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n// Licensed under the\nexport { correlationIdSetPrefix, correlationIdGetPrefix, correlationIdCanIncludeCorrelationHeader, correlationIdGetCorrelationContext, correlationIdGetCorrelationContextValue, dateTimeUtilsNow, dateTimeUtilsDuration, isInternalApplicationInsightsEndpoint, createDistributedTraceContextFromTrace } from \"./Util\";\nexport { ThrottleMgr } from \"./ThrottleMgr\";\nexport { parseConnectionString, ConnectionStringParser } from \"./ConnectionStringParser\";\nexport { RequestHeaders } from \"./RequestResponseHeaders\";\nexport { DisabledPropertyName, ProcessLegacy, SampleRate, HttpMethod, DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH, strNotSpecified } from \"./Constants\";\nexport { Envelope } from \"./Telemetry/Common/Envelope\";\nexport { Event } from \"./Telemetry/Event\";\nexport { Exception } from \"./Telemetry/Exception\";\nexport { Metric } from \"./Telemetry/Metric\";\nexport { PageView } from \"./Telemetry/PageView\";\nexport { RemoteDependencyData } from \"./Telemetry/RemoteDependencyData\";\nexport { Trace } from \"./Telemetry/Trace\";\nexport { PageViewPerformance } from \"./Telemetry/PageViewPerformance\";\nexport { Data } from \"./Telemetry/Common/Data\";\nexport { SeverityLevel } from \"./Interfaces/Contracts/SeverityLevel\";\nexport { ConfigurationManager } from \"./Interfaces/IConfig\";\nexport { ContextTagKeys } from \"./Interfaces/Contracts/ContextTagKeys\";\nexport { dataSanitizeKeyAndAddUniqueness, dataSanitizeKey, dataSanitizeString, dataSanitizeUrl, dataSanitizeMessage, dataSanitizeException, dataSanitizeProperties, dataSanitizeMeasurements, dataSanitizeId, dataSanitizeInput, dsPadNumber } from \"./Telemetry/Common/DataSanitizer\";\nexport { TelemetryItemCreator, createTelemetryItem } from \"./TelemetryItemCreator\";\nexport { CtxTagKeys, Extensions } from \"./Interfaces/PartAExtensions\";\nexport { DistributedTracingModes, EventPersistence } from \"./Enums\";\nexport { stringToBoolOrDefault, msToTimeSpan, getExtensionByName, isCrossOriginError } from \"./HelperFuncs\";\nexport { isBeaconsSupported as isBeaconApiSupported, createTraceParent, parseTraceParent, isValidTraceId, isValidSpanId, isValidTraceParent, isSampledFlag, formatTraceParent, findW3cTraceParent, findAllScripts } from \"@microsoft/applicationinsights-core-js\";\nexport { createDomEvent } from \"./DomHelperFuncs\";\nexport { utlDisableStorage, utlEnableStorage, utlCanUseLocalStorage, utlGetLocalStorage, utlSetLocalStorage, utlRemoveStorage, utlCanUseSessionStorage, utlGetSessionStorageKeys, utlGetSessionStorage, utlSetSessionStorage, utlRemoveSessionStorage, utlSetStoragePrefix } from \"./StorageHelperFuncs\";\nexport { urlParseUrl, urlGetAbsoluteUrl, urlGetPathName, urlGetCompleteUrl, urlParseHost, urlParseFullHost } from \"./UrlHelperFuncs\";\nexport { createOfflineListener } from \"./Offline\";\nexport var PropertiesPluginIdentifier = \"AppInsightsPropertiesPlugin\";\nexport var BreezeChannelIdentifier = \"AppInsightsChannelPlugin\";\nexport var AnalyticsPluginIdentifier = \"ApplicationInsightsAnalytics\";\n","/*\n * Application Insights JavaScript SDK - Web Analytics, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n// @skip-file-minify\n// ##############################################################\n// AUTO GENERATED FILE: This file is Auto Generated during build.\n// ##############################################################\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n// Note: DON'T Export these const from the package as we are still targeting ES5 which can result in a mutable variables that someone could change!!!\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nexport var _DYN_TO_STRING = \"toString\"; // Count: 4\nexport var _DYN_IS_STORAGE_USE_DISAB0 = \"isStorageUseDisabled\"; // Count: 3\nexport var _DYN__ADD_HOOK = \"_addHook\"; // Count: 6\nexport var _DYN_CORE = \"core\"; // Count: 7\nexport var _DYN_DATA_TYPE = \"dataType\"; // Count: 8\nexport var _DYN_ENVELOPE_TYPE = \"envelopeType\"; // Count: 7\nexport var _DYN_DIAG_LOG = \"diagLog\"; // Count: 13\nexport var _DYN_TRACK = \"track\"; // Count: 7\nexport var _DYN_TRACK_PAGE_VIEW = \"trackPageView\"; // Count: 4\nexport var _DYN_TRACK_PREVIOUS_PAGE_1 = \"trackPreviousPageVisit\"; // Count: 3\nexport var _DYN_SEND_PAGE_VIEW_INTER2 = \"sendPageViewInternal\"; // Count: 7\nexport var _DYN_START_TIME = \"startTime\"; // Count: 6\nexport var _DYN_PROPERTIES = \"properties\"; // Count: 5\nexport var _DYN_DURATION = \"duration\"; // Count: 12\nexport var _DYN_SEND_PAGE_VIEW_PERFO3 = \"sendPageViewPerformanceInternal\"; // Count: 3\nexport var _DYN_POPULATE_PAGE_VIEW_P4 = \"populatePageViewPerformanceEvent\"; // Count: 3\nexport var _DYN_HREF = \"href\"; // Count: 6\nexport var _DYN_SEND_EXCEPTION_INTER5 = \"sendExceptionInternal\"; // Count: 2\nexport var _DYN_ERROR = \"error\"; // Count: 5\nexport var _DYN_LINE_NUMBER = \"lineNumber\"; // Count: 4\nexport var _DYN_COLUMN_NUMBER = \"columnNumber\"; // Count: 5\nexport var _DYN__CREATE_AUTO_EXCEPTI6 = \"CreateAutoException\"; // Count: 3\nexport var _DYN_ADD_TELEMETRY_INITIA7 = \"addTelemetryInitializer\"; // Count: 4\nexport var _DYN_OVERRIDE_PAGE_VIEW_D8 = \"overridePageViewDuration\"; // Count: 2\nexport var _DYN_AUTO_EXCEPTION_INSTR9 = \"autoExceptionInstrumented\"; // Count: 3\nexport var _DYN_AUTO_TRACK_PAGE_VISI10 = \"autoTrackPageVisitTime\"; // Count: 2\nexport var _DYN_IS_BROWSER_LINK_TRAC11 = \"isBrowserLinkTrackingEnabled\"; // Count: 2\nexport var _DYN_LENGTH = \"length\"; // Count: 5\nexport var _DYN_ENABLE_AUTO_ROUTE_TR12 = \"enableAutoRouteTracking\"; // Count: 2\nexport var _DYN_ENABLE_UNHANDLED_PRO13 = \"enableUnhandledPromiseRejectionTracking\"; // Count: 2\nexport var _DYN_AUTO_UNHANDLED_PROMI14 = \"autoUnhandledPromiseInstrumented\"; // Count: 3\nexport var _DYN_GET_ENTRIES_BY_TYPE = \"getEntriesByType\"; // Count: 5\nexport var _DYN_IS_PERFORMANCE_TIMIN15 = \"isPerformanceTimingSupported\"; // Count: 2\nexport var _DYN_GET_PERFORMANCE_TIMI16 = \"getPerformanceTiming\"; // Count: 2\nexport var _DYN_NAVIGATION_START = \"navigationStart\"; // Count: 4\nexport var _DYN_SHOULD_COLLECT_DURAT17 = \"shouldCollectDuration\"; // Count: 3\nexport var _DYN_IS_PERFORMANCE_TIMIN18 = \"isPerformanceTimingDataReady\"; // Count: 2\nexport var _DYN_RESPONSE_START = \"responseStart\"; // Count: 5\nexport var _DYN_REQUEST_START = \"requestStart\"; // Count: 3\nexport var _DYN_LOAD_EVENT_END = \"loadEventEnd\"; // Count: 4\nexport var _DYN_RESPONSE_END = \"responseEnd\"; // Count: 5\nexport var _DYN_CONNECT_END = \"connectEnd\"; // Count: 4\n","/*\n * Application Insights JavaScript SDK - Web Analytics, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { dateTimeUtilsDuration } from \"@microsoft/applicationinsights-common\";\nimport { _throwInternal, arrForEach, dumpObj, getDocument, getExceptionName, getLocation, isNullOrUndefined } from \"@microsoft/applicationinsights-core-js\";\nimport { getPerformance, isUndefined, isWebWorker, scheduleTimeout } from \"@nevware21/ts-utils\";\nimport { _DYN_DURATION, _DYN_GET_ENTRIES_BY_TYPE, _DYN_GET_PERFORMANCE_TIMI16, _DYN_HREF, _DYN_IS_PERFORMANCE_TIMIN15, _DYN_IS_PERFORMANCE_TIMIN18, _DYN_LENGTH, _DYN_NAVIGATION_START, _DYN_POPULATE_PAGE_VIEW_P4, _DYN_PROPERTIES, _DYN_SEND_PAGE_VIEW_INTER2, _DYN_SEND_PAGE_VIEW_PERFO3, _DYN_SHOULD_COLLECT_DURAT17, _DYN_START_TIME, _DYN_TRACK_PAGE_VIEW } from \"../../__DynamicConstants\";\n/**\r\n * Class encapsulates sending page views and page view performance telemetry.\r\n */\nvar PageViewManager = /** @class */function () {\n function PageViewManager(appInsights, overridePageViewDuration, core, pageViewPerformanceManager) {\n dynamicProto(PageViewManager, this, function (_self) {\n var queueTimer = null;\n var itemQueue = [];\n var pageViewPerformanceSent = false;\n var firstPageViewSent = false;\n var _logger;\n if (core) {\n _logger = core.logger;\n }\n function _flushChannels(isAsync) {\n if (core) {\n core.flush(isAsync, function () {\n // Event flushed, callback added to prevent promise creation\n });\n }\n }\n function _startTimer() {\n if (!queueTimer) {\n queueTimer = scheduleTimeout(function () {\n queueTimer = null;\n var allItems = itemQueue.slice(0);\n var doFlush = false;\n itemQueue = [];\n arrForEach(allItems, function (item) {\n if (!item()) {\n // Not processed so rescheduled\n itemQueue.push(item);\n } else {\n doFlush = true;\n }\n });\n if (itemQueue[_DYN_LENGTH /* @min:%2elength */] > 0) {\n _startTimer();\n }\n if (doFlush) {\n // We process at least one item so flush the queue\n _flushChannels(true);\n }\n }, 100);\n }\n }\n function _addQueue(cb) {\n itemQueue.push(cb);\n _startTimer();\n }\n _self[_DYN_TRACK_PAGE_VIEW /* @min:%2etrackPageView */] = function (pageView, customProperties) {\n var name = pageView.name;\n if (isNullOrUndefined(name) || typeof name !== \"string\") {\n var doc = getDocument();\n name = pageView.name = doc && doc.title || \"\";\n }\n var uri = pageView.uri;\n if (isNullOrUndefined(uri) || typeof uri !== \"string\") {\n var location_1 = getLocation();\n uri = pageView.uri = location_1 && location_1[_DYN_HREF /* @min:%2ehref */] || \"\";\n }\n if (!firstPageViewSent) {\n var perf = getPerformance();\n // Access the performance timing object\n var navigationEntries = perf && perf[_DYN_GET_ENTRIES_BY_TYPE /* @min:%2egetEntriesByType */] && perf[_DYN_GET_ENTRIES_BY_TYPE /* @min:%2egetEntriesByType */](\"navigation\");\n // Edge Case the navigation Entries may return an empty array and the timeOrigin is not supported on IE\n if (navigationEntries && navigationEntries[0] && !isUndefined(perf.timeOrigin)) {\n // Get the value of loadEventStart\n var loadEventStart = navigationEntries[0].loadEventStart;\n pageView[_DYN_START_TIME /* @min:%2estartTime */] = new Date(perf.timeOrigin + loadEventStart);\n } else {\n // calculate the start time manually\n var duration_1 = (customProperties || pageView[_DYN_PROPERTIES /* @min:%2eproperties */] || {})[_DYN_DURATION /* @min:%2eduration */] || 0;\n pageView[_DYN_START_TIME /* @min:%2estartTime */] = new Date(new Date().getTime() - duration_1);\n }\n firstPageViewSent = true;\n }\n // case 1a. if performance timing is not supported by the browser, send the page view telemetry with the duration provided by the user. If the user\n // do not provide the duration, set duration to undefined\n // Also this is case 4\n if (!pageViewPerformanceManager[_DYN_IS_PERFORMANCE_TIMIN15 /* @min:%2eisPerformanceTimingSupported */]()) {\n appInsights[_DYN_SEND_PAGE_VIEW_INTER2 /* @min:%2esendPageViewInternal */](pageView, customProperties);\n _flushChannels(true);\n if (!isWebWorker()) {\n // no navigation timing (IE 8, iOS Safari 8.4, Opera Mini 8 - see http://caniuse.com/#feat=nav-timing)\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 25 /* _eInternalMessageId.NavigationTimingNotSupported */, \"trackPageView: navigation timing API used for calculation of page duration is not supported in this browser. This page view will be collected without duration and timing info.\");\n }\n return;\n }\n var pageViewSent = false;\n var customDuration;\n // if the performance timing is supported by the browser, calculate the custom duration\n var start = pageViewPerformanceManager[_DYN_GET_PERFORMANCE_TIMI16 /* @min:%2egetPerformanceTiming */]()[_DYN_NAVIGATION_START /* @min:%2enavigationStart */];\n if (start > 0) {\n customDuration = dateTimeUtilsDuration(start, +new Date());\n if (!pageViewPerformanceManager[_DYN_SHOULD_COLLECT_DURAT17 /* @min:%2eshouldCollectDuration */](customDuration)) {\n customDuration = undefined;\n }\n }\n // if the user has provided duration, send a page view telemetry with the provided duration. Otherwise, if\n // overridePageViewDuration is set to true, send a page view telemetry with the custom duration calculated earlier\n var duration;\n if (!isNullOrUndefined(customProperties) && !isNullOrUndefined(customProperties[_DYN_DURATION /* @min:%2eduration */])) {\n duration = customProperties[_DYN_DURATION /* @min:%2eduration */];\n }\n if (overridePageViewDuration || !isNaN(duration)) {\n if (isNaN(duration)) {\n // case 3\n if (!customProperties) {\n customProperties = {};\n }\n customProperties[_DYN_DURATION /* @min:%2eduration */] = customDuration;\n }\n // case 2\n appInsights[_DYN_SEND_PAGE_VIEW_INTER2 /* @min:%2esendPageViewInternal */](pageView, customProperties);\n _flushChannels(true);\n pageViewSent = true;\n }\n // now try to send the page view performance telemetry\n var maxDurationLimit = 60000;\n if (!customProperties) {\n customProperties = {};\n }\n // Queue the event for processing\n _addQueue(function () {\n var processed = false;\n try {\n if (pageViewPerformanceManager[_DYN_IS_PERFORMANCE_TIMIN18 /* @min:%2eisPerformanceTimingDataReady */]()) {\n processed = true;\n var pageViewPerformance = {\n name: name,\n uri: uri\n };\n pageViewPerformanceManager[_DYN_POPULATE_PAGE_VIEW_P4 /* @min:%2epopulatePageViewPerformanceEvent */](pageViewPerformance);\n if (!pageViewPerformance.isValid && !pageViewSent) {\n // If navigation timing gives invalid numbers, then go back to \"override page view duration\" mode.\n // That's the best value we can get that makes sense.\n customProperties[_DYN_DURATION /* @min:%2eduration */] = customDuration;\n appInsights[_DYN_SEND_PAGE_VIEW_INTER2 /* @min:%2esendPageViewInternal */](pageView, customProperties);\n } else {\n if (!pageViewSent) {\n customProperties[_DYN_DURATION /* @min:%2eduration */] = pageViewPerformance.durationMs;\n appInsights[_DYN_SEND_PAGE_VIEW_INTER2 /* @min:%2esendPageViewInternal */](pageView, customProperties);\n }\n if (!pageViewPerformanceSent) {\n appInsights[_DYN_SEND_PAGE_VIEW_PERFO3 /* @min:%2esendPageViewPerformanceInternal */](pageViewPerformance, customProperties);\n pageViewPerformanceSent = true;\n }\n }\n } else if (start > 0 && dateTimeUtilsDuration(start, +new Date()) > maxDurationLimit) {\n // if performance timings are not ready but we exceeded the maximum duration limit, just log a page view telemetry\n // with the maximum duration limit. Otherwise, keep waiting until performance timings are ready\n processed = true;\n if (!pageViewSent) {\n customProperties[_DYN_DURATION /* @min:%2eduration */] = maxDurationLimit;\n appInsights[_DYN_SEND_PAGE_VIEW_INTER2 /* @min:%2esendPageViewInternal */](pageView, customProperties);\n }\n }\n } catch (e) {\n _throwInternal(_logger, 1 /* eLoggingSeverity.CRITICAL */, 38 /* _eInternalMessageId.TrackPVFailedCalc */, \"trackPageView failed on page load calculation: \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n return processed;\n });\n };\n _self.teardown = function (unloadCtx, unloadState) {\n if (queueTimer) {\n queueTimer.cancel();\n queueTimer = null;\n var allItems = itemQueue.slice(0);\n var doFlush_1 = false;\n itemQueue = [];\n arrForEach(allItems, function (item) {\n if (item()) {\n doFlush_1 = true;\n }\n });\n }\n };\n });\n }\n // Removed Stub for PageViewManager.prototype.trackPageView.\n // Removed Stub for PageViewManager.prototype.teardown.\n // This is a workaround for an IE bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n PageViewManager.__ieDyn = 1;\n return PageViewManager;\n}();\nexport { PageViewManager };\n","/*\n * Application Insights JavaScript SDK - Web Analytics, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { dateTimeUtilsDuration, msToTimeSpan } from \"@microsoft/applicationinsights-common\";\nimport { _throwInternal, getNavigator, getPerformance, safeGetLogger } from \"@microsoft/applicationinsights-core-js\";\nimport { mathFloor, strIndexOf } from \"@nevware21/ts-utils\";\nimport { _DYN_CONNECT_END, _DYN_DURATION, _DYN_GET_ENTRIES_BY_TYPE, _DYN_GET_PERFORMANCE_TIMI16, _DYN_IS_PERFORMANCE_TIMIN15, _DYN_IS_PERFORMANCE_TIMIN18, _DYN_LENGTH, _DYN_LOAD_EVENT_END, _DYN_NAVIGATION_START, _DYN_POPULATE_PAGE_VIEW_P4, _DYN_REQUEST_START, _DYN_RESPONSE_END, _DYN_RESPONSE_START, _DYN_SHOULD_COLLECT_DURAT17, _DYN_START_TIME } from \"../../__DynamicConstants\";\nvar MAX_DURATION_ALLOWED = 3600000; // 1h\nvar botAgentNames = [\"googlebot\", \"adsbot-google\", \"apis-google\", \"mediapartners-google\"];\nfunction _isPerformanceTimingSupported() {\n var perf = getPerformance();\n return perf && !!perf.timing;\n}\nfunction _isPerformanceNavigationTimingSupported() {\n var perf = getPerformance();\n return perf && perf.getEntriesByType && perf.getEntriesByType(\"navigation\")[_DYN_LENGTH /* @min:%2elength */] > 0;\n}\nfunction _isPerformanceTimingDataReady() {\n var perf = getPerformance();\n var timing = perf ? perf.timing : 0;\n return timing && timing.domainLookupStart > 0 && timing[_DYN_NAVIGATION_START /* @min:%2enavigationStart */] > 0 && timing[_DYN_RESPONSE_START /* @min:%2eresponseStart */] > 0 && timing[_DYN_REQUEST_START /* @min:%2erequestStart */] > 0 && timing[_DYN_LOAD_EVENT_END /* @min:%2eloadEventEnd */] > 0 && timing[_DYN_RESPONSE_END /* @min:%2eresponseEnd */] > 0 && timing[_DYN_CONNECT_END /* @min:%2econnectEnd */] > 0 && timing.domLoading > 0;\n}\nfunction _getPerformanceTiming() {\n if (_isPerformanceTimingSupported()) {\n return getPerformance().timing;\n }\n return null;\n}\nfunction _getPerformanceNavigationTiming() {\n if (_isPerformanceNavigationTimingSupported()) {\n return getPerformance()[_DYN_GET_ENTRIES_BY_TYPE /* @min:%2egetEntriesByType */](\"navigation\")[0];\n }\n return null;\n}\n/**\r\n* This method tells if given durations should be excluded from collection.\r\n*/\nfunction _shouldCollectDuration() {\n var durations = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n durations[_i] = arguments[_i];\n }\n var _navigator = getNavigator() || {};\n // a full list of Google crawlers user agent strings - https://support.google.com/webmasters/answer/1061943?hl=en\n var userAgent = _navigator.userAgent;\n var isGoogleBot = false;\n if (userAgent) {\n for (var i = 0; i < botAgentNames[_DYN_LENGTH /* @min:%2elength */]; i++) {\n isGoogleBot = isGoogleBot || strIndexOf(userAgent.toLowerCase(), botAgentNames[i]) !== -1;\n }\n }\n if (isGoogleBot) {\n // Don't report durations for GoogleBot, it is returning invalid values in performance.timing API.\n return false;\n } else {\n // for other page views, don't report if it's outside of a reasonable range\n for (var i = 0; i < durations[_DYN_LENGTH /* @min:%2elength */]; i++) {\n if (durations[i] < 0 || durations[i] >= MAX_DURATION_ALLOWED) {\n return false;\n }\n }\n }\n return true;\n}\n/**\r\n * Class encapsulates sending page view performance telemetry.\r\n */\nvar PageViewPerformanceManager = /** @class */function () {\n function PageViewPerformanceManager(core) {\n var _logger = safeGetLogger(core);\n dynamicProto(PageViewPerformanceManager, this, function (_self) {\n _self[_DYN_POPULATE_PAGE_VIEW_P4 /* @min:%2epopulatePageViewPerformanceEvent */] = function (pageViewPerformance) {\n pageViewPerformance.isValid = false;\n /*\r\n * http://www.w3.org/TR/navigation-timing/#processing-model\r\n * |-navigationStart\r\n * | |-connectEnd\r\n * | ||-requestStart\r\n * | || |-responseStart\r\n * | || | |-responseEnd\r\n * | || | |\r\n * | || | | |-loadEventEnd\r\n * |---network---||---request---|---response---|---dom---|\r\n * |--------------------------total----------------------|\r\n *\r\n * total = The difference between the load event of the current document is completed and the first recorded timestamp of the performance entry : https://developer.mozilla.org/en-US/docs/Web/Performance/Navigation_and_resource_timings#duration\r\n * network = Redirect time + App Cache + DNS lookup time + TCP connection time\r\n * request = Request time : https://developer.mozilla.org/en-US/docs/Web/Performance/Navigation_and_resource_timings#request_time\r\n * response = Response time\r\n * dom = Document load time : https://html.spec.whatwg.org/multipage/dom.html#document-load-timing-info\r\n * = Document processing time : https://developers.google.com/web/fundamentals/performance/navigation-and-resource-timing/#document_processing\r\n * + Loading time : https://developers.google.com/web/fundamentals/performance/navigation-and-resource-timing/#loading\r\n */\n var navigationTiming = _getPerformanceNavigationTiming();\n var timing = _getPerformanceTiming();\n var total = 0;\n var network = 0;\n var request = 0;\n var response = 0;\n var dom = 0;\n if (navigationTiming || timing) {\n if (navigationTiming) {\n total = navigationTiming[_DYN_DURATION /* @min:%2eduration */];\n /**\r\n * support both cases:\r\n * - startTime is always zero: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming\r\n * - for older browsers where the startTime is not zero\r\n */\n network = navigationTiming[_DYN_START_TIME /* @min:%2estartTime */] === 0 ? navigationTiming[_DYN_CONNECT_END /* @min:%2econnectEnd */] : dateTimeUtilsDuration(navigationTiming[_DYN_START_TIME /* @min:%2estartTime */], navigationTiming[_DYN_CONNECT_END /* @min:%2econnectEnd */]);\n request = dateTimeUtilsDuration(navigationTiming.requestStart, navigationTiming[_DYN_RESPONSE_START /* @min:%2eresponseStart */]);\n response = dateTimeUtilsDuration(navigationTiming[_DYN_RESPONSE_START /* @min:%2eresponseStart */], navigationTiming[_DYN_RESPONSE_END /* @min:%2eresponseEnd */]);\n dom = dateTimeUtilsDuration(navigationTiming.responseEnd, navigationTiming[_DYN_LOAD_EVENT_END /* @min:%2eloadEventEnd */]);\n } else {\n total = dateTimeUtilsDuration(timing[_DYN_NAVIGATION_START /* @min:%2enavigationStart */], timing[_DYN_LOAD_EVENT_END /* @min:%2eloadEventEnd */]);\n network = dateTimeUtilsDuration(timing[_DYN_NAVIGATION_START /* @min:%2enavigationStart */], timing[_DYN_CONNECT_END /* @min:%2econnectEnd */]);\n request = dateTimeUtilsDuration(timing.requestStart, timing[_DYN_RESPONSE_START /* @min:%2eresponseStart */]);\n response = dateTimeUtilsDuration(timing[_DYN_RESPONSE_START /* @min:%2eresponseStart */], timing[_DYN_RESPONSE_END /* @min:%2eresponseEnd */]);\n dom = dateTimeUtilsDuration(timing.responseEnd, timing[_DYN_LOAD_EVENT_END /* @min:%2eloadEventEnd */]);\n }\n if (total === 0) {\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 10 /* _eInternalMessageId.ErrorPVCalc */, \"error calculating page view performance.\", {\n total: total,\n network: network,\n request: request,\n response: response,\n dom: dom\n });\n } else if (!_self[_DYN_SHOULD_COLLECT_DURAT17 /* @min:%2eshouldCollectDuration */](total, network, request, response, dom)) {\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 45 /* _eInternalMessageId.InvalidDurationValue */, \"Invalid page load duration value. Browser perf data won't be sent.\", {\n total: total,\n network: network,\n request: request,\n response: response,\n dom: dom\n });\n } else if (total < mathFloor(network) + mathFloor(request) + mathFloor(response) + mathFloor(dom)) {\n // some browsers may report individual components incorrectly so that the sum of the parts will be bigger than total PLT\n // in this case, don't report client performance from this page\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 8 /* _eInternalMessageId.ClientPerformanceMathError */, \"client performance math error.\", {\n total: total,\n network: network,\n request: request,\n response: response,\n dom: dom\n });\n } else {\n pageViewPerformance.durationMs = total;\n // // convert to timespans\n pageViewPerformance.perfTotal = pageViewPerformance[_DYN_DURATION /* @min:%2eduration */] = msToTimeSpan(total);\n pageViewPerformance.networkConnect = msToTimeSpan(network);\n pageViewPerformance.sentRequest = msToTimeSpan(request);\n pageViewPerformance.receivedResponse = msToTimeSpan(response);\n pageViewPerformance.domProcessing = msToTimeSpan(dom);\n pageViewPerformance.isValid = true;\n }\n }\n };\n _self[_DYN_GET_PERFORMANCE_TIMI16 /* @min:%2egetPerformanceTiming */] = _getPerformanceTiming;\n _self[_DYN_IS_PERFORMANCE_TIMIN15 /* @min:%2eisPerformanceTimingSupported */] = _isPerformanceTimingSupported;\n _self[_DYN_IS_PERFORMANCE_TIMIN18 /* @min:%2eisPerformanceTimingDataReady */] = _isPerformanceTimingDataReady;\n _self[_DYN_SHOULD_COLLECT_DURAT17 /* @min:%2eshouldCollectDuration */] = _shouldCollectDuration;\n });\n }\n // Removed Stub for PageViewPerformanceManager.prototype.populatePageViewPerformanceEvent.\n // Removed Stub for PageViewPerformanceManager.prototype.getPerformanceTiming.\n // Removed Stub for PageViewPerformanceManager.prototype.isPerformanceTimingSupported.\n // Removed Stub for PageViewPerformanceManager.prototype.isPerformanceTimingDataReady.\n // Removed Stub for PageViewPerformanceManager.prototype.shouldCollectDuration.\n // This is a workaround for an IE bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n PageViewPerformanceManager.__ieDyn = 1;\n return PageViewPerformanceManager;\n}();\nexport { PageViewPerformanceManager };\n","/*\n * Application Insights JavaScript SDK - Web Analytics, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { utlCanUseSessionStorage, utlGetSessionStorage, utlRemoveSessionStorage, utlSetSessionStorage } from \"@microsoft/applicationinsights-common\";\nimport { _warnToConsole, dateNow, dumpObj, getJSON, hasJSON, throwError } from \"@microsoft/applicationinsights-core-js\";\nimport { objDefine } from \"@nevware21/ts-utils\";\nimport { _DYN_TRACK_PREVIOUS_PAGE_1 } from \"../../__DynamicConstants\";\n/**\r\n * Used to track page visit durations\r\n */\nvar PageVisitTimeManager = /** @class */function () {\n /**\r\n * Creates a new instance of PageVisitTimeManager\r\n * @param pageVisitTimeTrackingHandler - Delegate that will be called to send telemetry data to AI (when trackPreviousPageVisit is called)\r\n * @returns {}\r\n */\n function PageVisitTimeManager(logger, pageVisitTimeTrackingHandler) {\n var prevPageVisitDataKeyName = \"prevPageVisitData\";\n dynamicProto(PageVisitTimeManager, this, function (_self) {\n _self[_DYN_TRACK_PREVIOUS_PAGE_1 /* @min:%2etrackPreviousPageVisit */] = function (currentPageName, currentPageUrl) {\n try {\n // Restart timer for new page view\n var prevPageVisitTimeData = restartPageVisitTimer(currentPageName, currentPageUrl);\n // If there was a page already being timed, track the visit time for it now.\n if (prevPageVisitTimeData) {\n pageVisitTimeTrackingHandler(prevPageVisitTimeData.pageName, prevPageVisitTimeData.pageUrl, prevPageVisitTimeData.pageVisitTime);\n }\n } catch (e) {\n _warnToConsole(logger, \"Auto track page visit time failed, metric will not be collected: \" + dumpObj(e));\n }\n };\n /**\r\n * Stops timing of current page (if exists) and starts timing for duration of visit to pageName\r\n * @param pageName - Name of page to begin timing visit duration\r\n * @returns {PageVisitData} Page visit data (including duration) of pageName from last call to start or restart, if exists. Null if not.\r\n */\n function restartPageVisitTimer(pageName, pageUrl) {\n var prevPageVisitData = null;\n try {\n prevPageVisitData = stopPageVisitTimer();\n if (utlCanUseSessionStorage()) {\n if (utlGetSessionStorage(logger, prevPageVisitDataKeyName) != null) {\n throwError(\"Cannot call startPageVisit consecutively without first calling stopPageVisit\");\n }\n var currPageVisitDataStr = getJSON().stringify(new PageVisitData(pageName, pageUrl));\n utlSetSessionStorage(logger, prevPageVisitDataKeyName, currPageVisitDataStr);\n }\n } catch (e) {\n _warnToConsole(logger, \"Call to restart failed: \" + dumpObj(e));\n prevPageVisitData = null;\n }\n return prevPageVisitData;\n }\n /**\r\n * Stops timing of current page, if exists.\r\n * @returns {PageVisitData} Page visit data (including duration) of pageName from call to start, if exists. Null if not.\r\n */\n function stopPageVisitTimer() {\n var prevPageVisitData = null;\n try {\n if (utlCanUseSessionStorage()) {\n // Define end time of page's visit\n var pageVisitEndTime = dateNow();\n // Try to retrieve page name and start time from session storage\n var pageVisitDataJsonStr = utlGetSessionStorage(logger, prevPageVisitDataKeyName);\n if (pageVisitDataJsonStr && hasJSON()) {\n // if previous page data exists, set end time of visit\n prevPageVisitData = getJSON().parse(pageVisitDataJsonStr);\n prevPageVisitData.pageVisitTime = pageVisitEndTime - prevPageVisitData.pageVisitStartTime;\n // Remove data from storage since we already used it\n utlRemoveSessionStorage(logger, prevPageVisitDataKeyName);\n }\n }\n } catch (e) {\n _warnToConsole(logger, \"Stop page visit timer failed: \" + dumpObj(e));\n prevPageVisitData = null;\n }\n return prevPageVisitData;\n }\n // For backward compatibility\n objDefine(_self, \"_logger\", {\n g: function () {\n return logger;\n }\n });\n objDefine(_self, \"pageVisitTimeTrackingHandler\", {\n g: function () {\n return pageVisitTimeTrackingHandler;\n }\n });\n });\n }\n // Removed Stub for PageVisitTimeManager.prototype.trackPreviousPageVisit.\n // This is a workaround for an IE bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n PageVisitTimeManager.__ieDyn = 1;\n return PageVisitTimeManager;\n}();\nexport { PageVisitTimeManager };\nvar PageVisitData = /** @class */function () {\n function PageVisitData(pageName, pageUrl) {\n this.pageVisitStartTime = dateNow();\n this.pageName = pageName;\n this.pageUrl = pageUrl;\n }\n return PageVisitData;\n}();\nexport { PageVisitData };\n","/*\n * Application Insights JavaScript SDK - Web Analytics, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { dateTimeUtilsDuration } from \"@microsoft/applicationinsights-common\";\nimport { _throwInternal } from \"@microsoft/applicationinsights-core-js\";\n/**\r\n * Used to record timed events and page views.\r\n */\nvar Timing = /** @class */function () {\n function Timing(logger, name) {\n var _self = this;\n var _events = {};\n _self.start = function (name) {\n if (typeof _events[name] !== \"undefined\") {\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 62 /* _eInternalMessageId.StartCalledMoreThanOnce */, \"start was called more than once for this event without calling stop.\", {\n name: name,\n key: name\n }, true);\n }\n _events[name] = +new Date();\n };\n _self.stop = function (name, url, properties, measurements) {\n var start = _events[name];\n if (isNaN(start)) {\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 63 /* _eInternalMessageId.StopCalledWithoutStart */, \"stop was called without a corresponding start.\", {\n name: name,\n key: name\n }, true);\n } else {\n var end = +new Date();\n var duration = dateTimeUtilsDuration(start, end);\n _self.action(name, url, duration, properties, measurements);\n }\n delete _events[name];\n _events[name] = undefined;\n };\n }\n return Timing;\n}();\nexport { Timing };\n","/*\n * Application Insights JavaScript SDK - Web Analytics, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n/**\r\n* ApplicationInsights.ts\r\n* @copyright Microsoft 2018\r\n*/\nvar _a;\nimport { __assignFn as __assign, __extendsFn as __extends } from \"@microsoft/applicationinsights-shims\";\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { AnalyticsPluginIdentifier, Event as EventTelemetry, Exception, Metric, PageView, PageViewPerformance, PropertiesPluginIdentifier, RemoteDependencyData, Trace, createDistributedTraceContextFromTrace, createDomEvent, createTelemetryItem, dataSanitizeString, isCrossOriginError, strNotSpecified, utlDisableStorage, utlEnableStorage, utlSetStoragePrefix } from \"@microsoft/applicationinsights-common\";\nimport { BaseTelemetryPlugin, InstrumentEvent, arrForEach, cfgDfBoolean, cfgDfMerge, cfgDfSet, cfgDfString, cfgDfValidate, createProcessTelemetryContext, createUniqueNamespace, dumpObj, eventOff, eventOn, findAllScripts, generateW3CId, getDocument, getExceptionName, getHistory, getLocation, getWindow, hasHistory, hasWindow, isFunction, isNullOrUndefined, isString, isUndefined, mergeEvtNamespace, onConfigChange, safeGetCookieMgr, strUndefined, throwError } from \"@microsoft/applicationinsights-core-js\";\nimport { isArray, isError, objDeepFreeze, objDefine, scheduleTimeout, strIndexOf } from \"@nevware21/ts-utils\";\nimport { _DYN_ADD_TELEMETRY_INITIA7, _DYN_AUTO_EXCEPTION_INSTR9, _DYN_AUTO_TRACK_PAGE_VISI10, _DYN_AUTO_UNHANDLED_PROMI14, _DYN_COLUMN_NUMBER, _DYN_CORE, _DYN_DATA_TYPE, _DYN_DIAG_LOG, _DYN_DURATION, _DYN_ENABLE_AUTO_ROUTE_TR12, _DYN_ENABLE_UNHANDLED_PRO13, _DYN_ENVELOPE_TYPE, _DYN_ERROR, _DYN_HREF, _DYN_IS_BROWSER_LINK_TRAC11, _DYN_IS_STORAGE_USE_DISAB0, _DYN_LENGTH, _DYN_LINE_NUMBER, _DYN_OVERRIDE_PAGE_VIEW_D8, _DYN_POPULATE_PAGE_VIEW_P4, _DYN_PROPERTIES, _DYN_SEND_EXCEPTION_INTER5, _DYN_SEND_PAGE_VIEW_INTER2, _DYN_SEND_PAGE_VIEW_PERFO3, _DYN_START_TIME, _DYN_TO_STRING, _DYN_TRACK, _DYN_TRACK_PAGE_VIEW, _DYN_TRACK_PREVIOUS_PAGE_1, _DYN__ADD_HOOK, _DYN__CREATE_AUTO_EXCEPTI6 } from \"../__DynamicConstants\";\nimport { PageViewManager } from \"./Telemetry/PageViewManager\";\nimport { PageViewPerformanceManager } from \"./Telemetry/PageViewPerformanceManager\";\nimport { PageVisitTimeManager } from \"./Telemetry/PageVisitTimeManager\";\nimport { Timing } from \"./Timing\";\nvar strEvent = \"event\";\nfunction _dispatchEvent(target, evnt) {\n if (target && target.dispatchEvent && evnt) {\n target.dispatchEvent(evnt);\n }\n}\nfunction _getReason(error) {\n if (error && error.reason) {\n var reason = error.reason;\n if (!isString(reason) && isFunction(reason[_DYN_TO_STRING /* @min:%2etoString */])) {\n return reason[_DYN_TO_STRING /* @min:%2etoString */]();\n }\n return dumpObj(reason);\n }\n // Pass the original object down which will eventually get evaluated for any message or description\n return error || \"\";\n}\nvar MinMilliSeconds = 60000;\nvar defaultValues = objDeepFreeze((_a = {\n sessionRenewalMs: cfgDfSet(_chkConfigMilliseconds, 30 * 60 * 1000),\n sessionExpirationMs: cfgDfSet(_chkConfigMilliseconds, 24 * 60 * 60 * 1000),\n disableExceptionTracking: cfgDfBoolean()\n}, _a[_DYN_AUTO_TRACK_PAGE_VISI10 /* @min:autoTrackPageVisitTime */] = cfgDfBoolean(), _a[_DYN_OVERRIDE_PAGE_VIEW_D8 /* @min:overridePageViewDuration */] = cfgDfBoolean(), _a[_DYN_ENABLE_UNHANDLED_PRO13 /* @min:enableUnhandledPromiseRejectionTracking */] = cfgDfBoolean(), _a[_DYN_AUTO_UNHANDLED_PROMI14 /* @min:autoUnhandledPromiseInstrumented */] = false, _a.samplingPercentage = cfgDfValidate(_chkSampling, 100), _a[_DYN_IS_STORAGE_USE_DISAB0 /* @min:isStorageUseDisabled */] = cfgDfBoolean(), _a[_DYN_IS_BROWSER_LINK_TRAC11 /* @min:isBrowserLinkTrackingEnabled */] = cfgDfBoolean(), _a[_DYN_ENABLE_AUTO_ROUTE_TR12 /* @min:enableAutoRouteTracking */] = cfgDfBoolean(), _a.namePrefix = cfgDfString(), _a.enableDebug = cfgDfBoolean(), _a.disableFlushOnBeforeUnload = cfgDfBoolean(), _a.disableFlushOnUnload = cfgDfBoolean(false, \"disableFlushOnBeforeUnload\"), _a.expCfg = cfgDfMerge({\n inclScripts: false,\n expLog: undefined,\n maxLogs: 50\n}), _a));\nfunction _chkConfigMilliseconds(value, defValue) {\n value = value || defValue;\n if (value < MinMilliSeconds) {\n value = MinMilliSeconds;\n }\n return +value;\n}\nfunction _chkSampling(value) {\n return !isNaN(value) && value > 0 && value <= 100;\n}\nfunction _updateStorageUsage(extConfig) {\n // Not resetting the storage usage as someone may have manually called utlDisableStorage, so this will only\n // reset based if the configuration option is provided\n if (!isUndefined(extConfig[_DYN_IS_STORAGE_USE_DISAB0 /* @min:%2eisStorageUseDisabled */])) {\n if (extConfig[_DYN_IS_STORAGE_USE_DISAB0 /* @min:%2eisStorageUseDisabled */]) {\n utlDisableStorage();\n } else {\n utlEnableStorage();\n }\n }\n}\nvar AnalyticsPlugin = /** @class */function (_super) {\n __extends(AnalyticsPlugin, _super);\n function AnalyticsPlugin() {\n var _this = _super.call(this) || this;\n _this.identifier = AnalyticsPluginIdentifier; // do not change name or priority\n _this.priority = 180; // take from reserved priority range 100- 200\n _this.autoRoutePVDelay = 500; // ms; Time to wait after a route change before triggering a pageview to allow DOM changes to take place\n var _eventTracking;\n var _pageTracking;\n var _pageViewManager;\n var _pageViewPerformanceManager;\n var _pageVisitTimeManager;\n var _preInitTelemetryInitializers;\n var _isBrowserLinkTrackingEnabled;\n var _browserLinkInitializerAdded;\n var _enableAutoRouteTracking;\n var _historyListenerAdded;\n var _disableExceptionTracking;\n var _autoExceptionInstrumented;\n var _enableUnhandledPromiseRejectionTracking;\n var _autoUnhandledPromiseInstrumented;\n var _extConfig;\n var _autoTrackPageVisitTime;\n var _expCfg;\n // Counts number of trackAjax invocations.\n // By default we only monitor X ajax call per view to avoid too much load.\n // Default value is set in config.\n // This counter keeps increasing even after the limit is reached.\n var _trackAjaxAttempts = 0;\n // array with max length of 2 that store current url and previous url for SPA page route change trackPageview use.\n var _prevUri; // Assigned in the constructor\n var _currUri;\n var _evtNamespace;\n // For testing error hooks only\n var _errorHookCnt;\n dynamicProto(AnalyticsPlugin, _this, function (_self, _base) {\n var _addHook = _base[_DYN__ADD_HOOK /* @min:%2e_addHook */];\n _initDefaults();\n _self.getCookieMgr = function () {\n return safeGetCookieMgr(_self[_DYN_CORE /* @min:%2ecore */]);\n };\n _self.processTelemetry = function (env, itemCtx) {\n _self.processNext(env, itemCtx);\n };\n _self.trackEvent = function (event, customProperties) {\n try {\n var telemetryItem = createTelemetryItem(event, EventTelemetry[_DYN_DATA_TYPE /* @min:%2edataType */], EventTelemetry[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], _self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), customProperties);\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\n } catch (e) {\n _throwInternal(2 /* eLoggingSeverity.WARNING */, 39 /* _eInternalMessageId.TrackTraceFailed */, \"trackTrace failed, trace will not be collected: \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n };\n /**\r\n * Start timing an extended event. Call `stopTrackEvent` to log the event when it ends.\r\n * @param name - A string that identifies this event uniquely within the document.\r\n */\n _self.startTrackEvent = function (name) {\n try {\n _eventTracking.start(name);\n } catch (e) {\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 29 /* _eInternalMessageId.StartTrackEventFailed */, \"startTrackEvent failed, event will not be collected: \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n };\n /**\r\n * Log an extended event that you started timing with `startTrackEvent`.\r\n * @param name - The string you used to identify this event in `startTrackEvent`.\r\n * @param properties - map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty.\r\n * @param measurements - map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.\r\n */\n _self.stopTrackEvent = function (name, properties, measurements) {\n try {\n _eventTracking.stop(name, undefined, properties, measurements);\n } catch (e) {\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 30 /* _eInternalMessageId.StopTrackEventFailed */, \"stopTrackEvent failed, event will not be collected: \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n };\n /**\r\n * @description Log a diagnostic message\r\n * @param trace - the trace message\r\n * @param customProperties - Additional custom properties to include in the event\r\n */\n _self.trackTrace = function (trace, customProperties) {\n try {\n var telemetryItem = createTelemetryItem(trace, Trace[_DYN_DATA_TYPE /* @min:%2edataType */], Trace[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], _self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), customProperties);\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\n } catch (e) {\n _throwInternal(2 /* eLoggingSeverity.WARNING */, 39 /* _eInternalMessageId.TrackTraceFailed */, \"trackTrace failed, trace will not be collected: \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n };\n /**\r\n * @description Log a numeric value that is not associated with a specific event. Typically\r\n * used to send regular reports of performance indicators. To send single measurement, just\r\n * use the name and average fields of {@link IMetricTelemetry}. If you take measurements\r\n * frequently, you can reduce the telemetry bandwidth by aggregating multiple measurements\r\n * and sending the resulting average at intervals\r\n * @param metric - input object argument. Only name and average are mandatory.\r\n * @param } customProperties additional data used to filter metrics in the\r\n * portal. Defaults to empty.\r\n */\n _self.trackMetric = function (metric, customProperties) {\n try {\n var telemetryItem = createTelemetryItem(metric, Metric[_DYN_DATA_TYPE /* @min:%2edataType */], Metric[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], _self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), customProperties);\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\n } catch (e) {\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 36 /* _eInternalMessageId.TrackMetricFailed */, \"trackMetric failed, metric will not be collected: \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n };\n /**\r\n * Logs that a page or other item was viewed.\r\n * @param IPageViewTelemetry - The string you used as the name in startTrackPage. Defaults to the document title.\r\n * @param customProperties - Additional data used to filter events and metrics. Defaults to empty.\r\n * If a user wants to provide duration for pageLoad, it'll have to be in pageView.properties.duration\r\n */\n _self[_DYN_TRACK_PAGE_VIEW /* @min:%2etrackPageView */] = function (pageView, customProperties) {\n try {\n var inPv = pageView || {};\n _pageViewManager[_DYN_TRACK_PAGE_VIEW /* @min:%2etrackPageView */](inPv, __assign(__assign(__assign({}, inPv.properties), inPv.measurements), customProperties));\n if (_autoTrackPageVisitTime) {\n _pageVisitTimeManager[_DYN_TRACK_PREVIOUS_PAGE_1 /* @min:%2etrackPreviousPageVisit */](inPv.name, inPv.uri);\n }\n } catch (e) {\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 37 /* _eInternalMessageId.TrackPVFailed */, \"trackPageView failed, page view will not be collected: \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n };\n /**\r\n * Create a page view telemetry item and send it to the SDK pipeline through the core.track API\r\n * @param pageView - Page view item to be sent\r\n * @param properties - Custom properties (Part C) that a user can add to the telemetry item\r\n * @param systemProperties - System level properties (Part A) that a user can add to the telemetry item\r\n */\n _self[_DYN_SEND_PAGE_VIEW_INTER2 /* @min:%2esendPageViewInternal */] = function (pageView, properties, systemProperties) {\n var doc = getDocument();\n if (doc) {\n pageView.refUri = pageView.refUri === undefined ? doc.referrer : pageView.refUri;\n }\n if (isNullOrUndefined(pageView[_DYN_START_TIME /* @min:%2estartTime */])) {\n // calculate the start time manually\n var duration = (properties || pageView[_DYN_PROPERTIES /* @min:%2eproperties */] || {})[_DYN_DURATION /* @min:%2eduration */] || 0;\n pageView[_DYN_START_TIME /* @min:%2estartTime */] = new Date(new Date().getTime() - duration);\n }\n var telemetryItem = createTelemetryItem(pageView, PageView[_DYN_DATA_TYPE /* @min:%2edataType */], PageView[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], _self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), properties, systemProperties);\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\n // reset ajaxes counter\n _trackAjaxAttempts = 0;\n };\n /**\r\n * @ignore INTERNAL ONLY\r\n * @param pageViewPerformance\r\n * @param properties\r\n */\n _self[_DYN_SEND_PAGE_VIEW_PERFO3 /* @min:%2esendPageViewPerformanceInternal */] = function (pageViewPerformance, properties, systemProperties) {\n var telemetryItem = createTelemetryItem(pageViewPerformance, PageViewPerformance[_DYN_DATA_TYPE /* @min:%2edataType */], PageViewPerformance[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], _self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), properties, systemProperties);\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\n };\n /**\r\n * Send browser performance metrics.\r\n * @param pageViewPerformance\r\n * @param customProperties\r\n */\n _self.trackPageViewPerformance = function (pageViewPerformance, customProperties) {\n var inPvp = pageViewPerformance || {};\n try {\n _pageViewPerformanceManager[_DYN_POPULATE_PAGE_VIEW_P4 /* @min:%2epopulatePageViewPerformanceEvent */](inPvp);\n _self[_DYN_SEND_PAGE_VIEW_PERFO3 /* @min:%2esendPageViewPerformanceInternal */](inPvp, customProperties);\n } catch (e) {\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 37 /* _eInternalMessageId.TrackPVFailed */, \"trackPageViewPerformance failed, page view will not be collected: \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n };\n /**\r\n * Starts the timer for tracking a page load time. Use this instead of `trackPageView` if you want to control when the page view timer starts and stops,\r\n * but don't want to calculate the duration yourself. This method doesn't send any telemetry. Call `stopTrackPage` to log the end of the page view\r\n * and send the event.\r\n * @param name - A string that idenfities this item, unique within this HTML document. Defaults to the document title.\r\n */\n _self.startTrackPage = function (name) {\n try {\n if (typeof name !== \"string\") {\n var doc = getDocument();\n name = doc && doc.title || \"\";\n }\n _pageTracking.start(name);\n } catch (e) {\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 31 /* _eInternalMessageId.StartTrackFailed */, \"startTrackPage failed, page view may not be collected: \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n };\n /**\r\n * Stops the timer that was started by calling `startTrackPage` and sends the pageview load time telemetry with the specified properties and measurements.\r\n * The duration of the page view will be the time between calling `startTrackPage` and `stopTrackPage`.\r\n * @param name - The string you used as the name in startTrackPage. Defaults to the document title.\r\n * @param url - String - a relative or absolute URL that identifies the page or other item. Defaults to the window location.\r\n * @param properties - map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty.\r\n * @param measurements - map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.\r\n */\n _self.stopTrackPage = function (name, url, properties, measurement) {\n try {\n if (typeof name !== \"string\") {\n var doc = getDocument();\n name = doc && doc.title || \"\";\n }\n if (typeof url !== \"string\") {\n var loc = getLocation();\n url = loc && loc[_DYN_HREF /* @min:%2ehref */] || \"\";\n }\n _pageTracking.stop(name, url, properties, measurement);\n if (_autoTrackPageVisitTime) {\n _pageVisitTimeManager[_DYN_TRACK_PREVIOUS_PAGE_1 /* @min:%2etrackPreviousPageVisit */](name, url);\n }\n } catch (e) {\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 32 /* _eInternalMessageId.StopTrackFailed */, \"stopTrackPage failed, page view will not be collected: \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n };\n /**\r\n * @ignore INTERNAL ONLY\r\n * @param exception\r\n * @param properties\r\n * @param systemProperties\r\n */\n _self[_DYN_SEND_EXCEPTION_INTER5 /* @min:%2esendExceptionInternal */] = function (exception, customProperties, systemProperties) {\n // Adding additional edge cases to handle\n // - Not passing anything (null / undefined)\n var theError = exception && (exception.exception || exception[_DYN_ERROR /* @min:%2eerror */]) ||\n // - Handle someone calling trackException based of v1 API where the exception was the Error\n isError(exception) && exception ||\n // - Handles no error being defined and instead of creating a new Error() instance attempt to map so any stacktrace\n // is preserved and does not list ApplicationInsights code as the source\n {\n name: exception && typeof exception,\n message: exception || strNotSpecified\n };\n // If no exception object was passed assign to an empty object to avoid internal exceptions\n exception = exception || {};\n var exceptionPartB = new Exception(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), theError, exception[_DYN_PROPERTIES /* @min:%2eproperties */] || customProperties, exception.measurements, exception.severityLevel, exception.id).toInterface();\n var doc = getDocument();\n if (doc && (_expCfg === null || _expCfg === void 0 ? void 0 : _expCfg.inclScripts)) {\n var scriptsInfo = findAllScripts(doc);\n exceptionPartB[_DYN_PROPERTIES /* @min:%2eproperties */][\"exceptionScripts\"] = JSON.stringify(scriptsInfo);\n }\n if (_expCfg === null || _expCfg === void 0 ? void 0 : _expCfg.expLog) {\n var logs = _expCfg.expLog();\n if (logs && logs.logs && isArray(logs.logs)) {\n exceptionPartB[_DYN_PROPERTIES /* @min:%2eproperties */][\"exceptionLog\"] = logs.logs.slice(0, _expCfg.maxLogs).join(\"\\n\");\n }\n }\n var telemetryItem = createTelemetryItem(exceptionPartB, Exception[_DYN_DATA_TYPE /* @min:%2edataType */], Exception[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], _self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), customProperties, systemProperties);\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\n };\n /**\r\n * Log an exception you have caught.\r\n *\r\n * @param exception - Object which contains exception to be sent\r\n * @param } customProperties Additional data used to filter pages and metrics in the portal. Defaults to empty.\r\n *\r\n * Any property of type double will be considered a measurement, and will be treated by Application Insights as a metric.\r\n */\n _self.trackException = function (exception, customProperties) {\n if (exception && !exception.exception && exception[_DYN_ERROR /* @min:%2eerror */]) {\n exception.exception = exception[_DYN_ERROR /* @min:%2eerror */];\n }\n try {\n _self[_DYN_SEND_EXCEPTION_INTER5 /* @min:%2esendExceptionInternal */](exception, customProperties);\n } catch (e) {\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 35 /* _eInternalMessageId.TrackExceptionFailed */, \"trackException failed, exception will not be collected: \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n };\n /**\r\n * @description Custom error handler for Application Insights Analytics\r\n * @param exception\r\n */\n _self._onerror = function (exception) {\n var error = exception && exception[_DYN_ERROR /* @min:%2eerror */];\n var evt = exception && exception.evt;\n try {\n if (!evt) {\n var _window = getWindow();\n if (_window) {\n evt = _window[strEvent];\n }\n }\n var url = exception && exception.url || (getDocument() || {}).URL;\n // If no error source is provided assume the default window.onerror handler\n var errorSrc = exception.errorSrc || \"window.onerror@\" + url + \":\" + (exception[_DYN_LINE_NUMBER /* @min:%2elineNumber */] || 0) + \":\" + (exception[_DYN_COLUMN_NUMBER /* @min:%2ecolumnNumber */] || 0);\n var properties = {\n errorSrc: errorSrc,\n url: url,\n lineNumber: exception[_DYN_LINE_NUMBER /* @min:%2elineNumber */] || 0,\n columnNumber: exception[_DYN_COLUMN_NUMBER /* @min:%2ecolumnNumber */] || 0,\n message: exception.message\n };\n if (isCrossOriginError(exception.message, exception.url, exception.lineNumber, exception.columnNumber, exception[_DYN_ERROR /* @min:%2eerror */])) {\n _sendCORSException(Exception[_DYN__CREATE_AUTO_EXCEPTI6 /* @min:%2eCreateAutoException */](\"Script error: The browser's same-origin policy prevents us from getting the details of this exception. Consider using the 'crossorigin' attribute.\", url, exception[_DYN_LINE_NUMBER /* @min:%2elineNumber */] || 0, exception[_DYN_COLUMN_NUMBER /* @min:%2ecolumnNumber */] || 0, error, evt, null, errorSrc), properties);\n } else {\n if (!exception.errorSrc) {\n exception.errorSrc = errorSrc;\n }\n _self.trackException({\n exception: exception,\n severityLevel: 3 /* eSeverityLevel.Error */\n }, properties);\n }\n } catch (e) {\n var errorString = error ? error.name + \", \" + error.message : \"null\";\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 11 /* _eInternalMessageId.ExceptionWhileLoggingError */, \"_onError threw exception while logging error, error will not be collected: \" + getExceptionName(e), {\n exception: dumpObj(e),\n errorString: errorString\n });\n }\n };\n _self[_DYN_ADD_TELEMETRY_INITIA7 /* @min:%2eaddTelemetryInitializer */] = function (telemetryInitializer) {\n if (_self[_DYN_CORE /* @min:%2ecore */]) {\n // Just add to the core\n return _self[_DYN_CORE /* @min:%2ecore */][_DYN_ADD_TELEMETRY_INITIA7 /* @min:%2eaddTelemetryInitializer */](telemetryInitializer);\n }\n // Handle \"pre-initialization\" telemetry initializers (for backward compatibility)\n if (!_preInitTelemetryInitializers) {\n _preInitTelemetryInitializers = [];\n }\n _preInitTelemetryInitializers.push(telemetryInitializer);\n };\n _self.initialize = function (config, core, extensions, pluginChain) {\n if (_self.isInitialized()) {\n return;\n }\n if (isNullOrUndefined(core)) {\n throwError(\"Error initializing\");\n }\n _base.initialize(config, core, extensions, pluginChain);\n try {\n _evtNamespace = mergeEvtNamespace(createUniqueNamespace(_self.identifier), core.evtNamespace && core.evtNamespace());\n if (_preInitTelemetryInitializers) {\n arrForEach(_preInitTelemetryInitializers, function (initializer) {\n core[_DYN_ADD_TELEMETRY_INITIA7 /* @min:%2eaddTelemetryInitializer */](initializer);\n });\n _preInitTelemetryInitializers = null;\n }\n _populateDefaults(config);\n _pageViewPerformanceManager = new PageViewPerformanceManager(_self[_DYN_CORE /* @min:%2ecore */]);\n _pageViewManager = new PageViewManager(_self, _extConfig.overridePageViewDuration, _self[_DYN_CORE /* @min:%2ecore */], _pageViewPerformanceManager);\n _pageVisitTimeManager = new PageVisitTimeManager(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), function (pageName, pageUrl, pageVisitTime) {\n return trackPageVisitTime(pageName, pageUrl, pageVisitTime);\n });\n _eventTracking = new Timing(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), \"trackEvent\");\n _eventTracking.action = function (name, url, duration, properties, measurements) {\n if (!properties) {\n properties = {};\n }\n if (!measurements) {\n measurements = {};\n }\n properties.duration = duration[_DYN_TO_STRING /* @min:%2etoString */]();\n _self.trackEvent({\n name: name,\n properties: properties,\n measurements: measurements\n });\n };\n // initialize page view timing\n _pageTracking = new Timing(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), \"trackPageView\");\n _pageTracking.action = function (name, url, duration, properties, measurements) {\n // duration must be a custom property in order for the collector to extract it\n if (isNullOrUndefined(properties)) {\n properties = {};\n }\n properties.duration = duration[_DYN_TO_STRING /* @min:%2etoString */]();\n var pageViewItem = {\n name: name,\n uri: url,\n properties: properties,\n measurements: measurements\n };\n _self[_DYN_SEND_PAGE_VIEW_INTER2 /* @min:%2esendPageViewInternal */](pageViewItem, properties);\n };\n if (hasWindow()) {\n _updateExceptionTracking();\n _updateLocationChange();\n }\n } catch (e) {\n // resetting the initialized state because of failure\n _self.setInitialized(false);\n throw e;\n }\n };\n _self._doTeardown = function (unloadCtx, unloadState) {\n _pageViewManager && _pageViewManager.teardown(unloadCtx, unloadState);\n // Just register to remove all events associated with this namespace\n eventOff(window, null, null, _evtNamespace);\n _initDefaults();\n };\n _self[\"_getDbgPlgTargets\"] = function () {\n return [_errorHookCnt, _autoExceptionInstrumented];\n };\n function _populateDefaults(config) {\n // it is used for 1DS as well, so config type should be IConfiguration only\n var identifier = _self.identifier;\n var core = _self[_DYN_CORE /* @min:%2ecore */];\n _self[_DYN__ADD_HOOK /* @min:%2e_addHook */](onConfigChange(config, function () {\n var ctx = createProcessTelemetryContext(null, config, core);\n _extConfig = ctx.getExtCfg(identifier, defaultValues);\n // make sure auto exception is instrumented only once and it won't be overriden by the following config changes\n _autoExceptionInstrumented = _autoExceptionInstrumented || config[_DYN_AUTO_EXCEPTION_INSTR9 /* @min:%2eautoExceptionInstrumented */] || _extConfig[_DYN_AUTO_EXCEPTION_INSTR9 /* @min:%2eautoExceptionInstrumented */];\n _expCfg = _extConfig.expCfg;\n _autoTrackPageVisitTime = _extConfig[_DYN_AUTO_TRACK_PAGE_VISI10 /* @min:%2eautoTrackPageVisitTime */];\n if (config.storagePrefix) {\n utlSetStoragePrefix(config.storagePrefix);\n }\n _updateStorageUsage(_extConfig);\n // _updateBrowserLinkTracking\n _isBrowserLinkTrackingEnabled = _extConfig[_DYN_IS_BROWSER_LINK_TRAC11 /* @min:%2eisBrowserLinkTrackingEnabled */];\n _addDefaultTelemetryInitializers();\n }));\n }\n /**\r\n * Log a page visit time\r\n * @param pageName - Name of page\r\n * @param pageVisitDuration - Duration of visit to the page in milliseconds\r\n */\n function trackPageVisitTime(pageName, pageUrl, pageVisitTime) {\n var properties = {\n PageName: pageName,\n PageUrl: pageUrl\n };\n _self.trackMetric({\n name: \"PageVisitTime\",\n average: pageVisitTime,\n max: pageVisitTime,\n min: pageVisitTime,\n sampleCount: 1\n }, properties);\n }\n function _addDefaultTelemetryInitializers() {\n if (!_browserLinkInitializerAdded && _isBrowserLinkTrackingEnabled) {\n var browserLinkPaths_1 = [\"/browserLinkSignalR/\", \"/__browserLink/\"];\n var dropBrowserLinkRequests = function (envelope) {\n if (_isBrowserLinkTrackingEnabled && envelope.baseType === RemoteDependencyData[_DYN_DATA_TYPE /* @min:%2edataType */]) {\n var remoteData = envelope.baseData;\n if (remoteData) {\n for (var i = 0; i < browserLinkPaths_1[_DYN_LENGTH /* @min:%2elength */]; i++) {\n if (remoteData.target && strIndexOf(remoteData.target, browserLinkPaths_1[i]) >= 0) {\n return false;\n }\n }\n }\n }\n return true;\n };\n _self[_DYN__ADD_HOOK /* @min:%2e_addHook */](_self[_DYN_ADD_TELEMETRY_INITIA7 /* @min:%2eaddTelemetryInitializer */](dropBrowserLinkRequests));\n _browserLinkInitializerAdded = true;\n }\n }\n function _sendCORSException(exception, properties) {\n var telemetryItem = createTelemetryItem(exception, Exception[_DYN_DATA_TYPE /* @min:%2edataType */], Exception[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], _self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), properties);\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\n }\n function _updateExceptionTracking() {\n var _window = getWindow();\n var locn = getLocation(true);\n _self[_DYN__ADD_HOOK /* @min:%2e_addHook */](onConfigChange(_extConfig, function () {\n _disableExceptionTracking = _extConfig.disableExceptionTracking;\n if (!_disableExceptionTracking && !_autoExceptionInstrumented && !_extConfig[_DYN_AUTO_EXCEPTION_INSTR9 /* @min:%2eautoExceptionInstrumented */]) {\n // We want to enable exception auto collection and it has not been done so yet\n _addHook(InstrumentEvent(_window, \"onerror\", {\n ns: _evtNamespace,\n rsp: function (callDetails, message, url, lineNumber, columnNumber, error) {\n if (!_disableExceptionTracking && callDetails.rslt !== true) {\n _self._onerror(Exception[_DYN__CREATE_AUTO_EXCEPTI6 /* @min:%2eCreateAutoException */](message, url, lineNumber, columnNumber, error, callDetails.evt));\n }\n }\n }, false));\n _errorHookCnt++;\n _autoExceptionInstrumented = true;\n }\n }));\n _addUnhandledPromiseRejectionTracking(_window, locn);\n }\n function _updateLocationChange() {\n var win = getWindow();\n var locn = getLocation(true);\n _self[_DYN__ADD_HOOK /* @min:%2e_addHook */](onConfigChange(_extConfig, function () {\n _enableAutoRouteTracking = _extConfig[_DYN_ENABLE_AUTO_ROUTE_TR12 /* @min:%2eenableAutoRouteTracking */] === true;\n /**\r\n * Create a custom \"locationchange\" event which is triggered each time the history object is changed\r\n */\n if (win && _enableAutoRouteTracking && !_historyListenerAdded && hasHistory()) {\n var _history = getHistory();\n if (isFunction(_history.pushState) && isFunction(_history.replaceState) && typeof Event !== strUndefined) {\n _addHistoryListener(win, _history, locn);\n }\n }\n }));\n }\n function _getDistributedTraceCtx() {\n var distributedTraceCtx = null;\n if (_self[_DYN_CORE /* @min:%2ecore */] && _self[_DYN_CORE /* @min:%2ecore */].getTraceCtx) {\n distributedTraceCtx = _self[_DYN_CORE /* @min:%2ecore */].getTraceCtx(false);\n }\n if (!distributedTraceCtx) {\n // Fallback when using an older Core and PropertiesPlugin\n var properties = _self[_DYN_CORE /* @min:%2ecore */].getPlugin(PropertiesPluginIdentifier);\n if (properties) {\n var context = properties.plugin.context;\n if (context) {\n distributedTraceCtx = createDistributedTraceContextFromTrace(context.telemetryTrace);\n }\n }\n }\n return distributedTraceCtx;\n }\n /**\r\n * Create a custom \"locationchange\" event which is triggered each time the history object is changed\r\n */\n function _addHistoryListener(win, history, locn) {\n if (_historyListenerAdded) {\n return;\n }\n // Name Prefix is only referenced during the initial initialization and cannot be changed afterwards\n var namePrefix = _extConfig.namePrefix || \"\";\n function _popstateHandler() {\n if (_enableAutoRouteTracking) {\n _dispatchEvent(win, createDomEvent(namePrefix + \"locationchange\"));\n }\n }\n function _locationChangeHandler() {\n // We always track the changes (if the handler is installed) to handle the feature being disabled between location changes\n if (_currUri) {\n _prevUri = _currUri;\n _currUri = locn && locn[_DYN_HREF /* @min:%2ehref */] || \"\";\n } else {\n _currUri = locn && locn[_DYN_HREF /* @min:%2ehref */] || \"\";\n }\n if (_enableAutoRouteTracking) {\n var distributedTraceCtx = _getDistributedTraceCtx();\n if (distributedTraceCtx) {\n distributedTraceCtx.setTraceId(generateW3CId());\n var traceLocationName = \"_unknown_\";\n if (locn && locn.pathname) {\n traceLocationName = locn.pathname + (locn.hash || \"\");\n }\n // This populates the ai.operation.name which has a maximum size of 1024 so we need to sanitize it\n distributedTraceCtx.setName(dataSanitizeString(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), traceLocationName));\n }\n scheduleTimeout(function (uri) {\n // todo: override start time so that it is not affected by autoRoutePVDelay\n _self[_DYN_TRACK_PAGE_VIEW /* @min:%2etrackPageView */]({\n refUri: uri,\n properties: {\n duration: 0\n }\n }); // SPA route change loading durations are undefined, so send 0\n }.bind(_self, _prevUri), _self.autoRoutePVDelay);\n }\n }\n _addHook(InstrumentEvent(history, \"pushState\", {\n ns: _evtNamespace,\n rsp: function () {\n if (_enableAutoRouteTracking) {\n _dispatchEvent(win, createDomEvent(namePrefix + \"pushState\"));\n _dispatchEvent(win, createDomEvent(namePrefix + \"locationchange\"));\n }\n }\n }, true));\n _addHook(InstrumentEvent(history, \"replaceState\", {\n ns: _evtNamespace,\n rsp: function () {\n if (_enableAutoRouteTracking) {\n _dispatchEvent(win, createDomEvent(namePrefix + \"replaceState\"));\n _dispatchEvent(win, createDomEvent(namePrefix + \"locationchange\"));\n }\n }\n }, true));\n eventOn(win, namePrefix + \"popstate\", _popstateHandler, _evtNamespace);\n eventOn(win, namePrefix + \"locationchange\", _locationChangeHandler, _evtNamespace);\n _historyListenerAdded = true;\n }\n function _addUnhandledPromiseRejectionTracking(_window, _location) {\n _self[_DYN__ADD_HOOK /* @min:%2e_addHook */](onConfigChange(_extConfig, function () {\n _enableUnhandledPromiseRejectionTracking = _extConfig[_DYN_ENABLE_UNHANDLED_PRO13 /* @min:%2eenableUnhandledPromiseRejectionTracking */] === true;\n _autoExceptionInstrumented = _autoExceptionInstrumented || _extConfig[_DYN_AUTO_UNHANDLED_PROMI14 /* @min:%2eautoUnhandledPromiseInstrumented */];\n if (_enableUnhandledPromiseRejectionTracking && !_autoUnhandledPromiseInstrumented) {\n // We want to enable exception auto collection and it has not been done so yet\n _addHook(InstrumentEvent(_window, \"onunhandledrejection\", {\n ns: _evtNamespace,\n rsp: function (callDetails, error) {\n if (_enableUnhandledPromiseRejectionTracking && callDetails.rslt !== true) {\n // handled could be typeof function\n _self._onerror(Exception[_DYN__CREATE_AUTO_EXCEPTI6 /* @min:%2eCreateAutoException */](_getReason(error), _location ? _location[_DYN_HREF /* @min:%2ehref */] : \"\", 0, 0, error, callDetails.evt));\n }\n }\n }, false));\n _errorHookCnt++;\n _extConfig[_DYN_AUTO_UNHANDLED_PROMI14 /* @min:%2eautoUnhandledPromiseInstrumented */] = _autoUnhandledPromiseInstrumented = true;\n }\n }));\n }\n /**\r\n * This method will throw exceptions in debug mode or attempt to log the error as a console warning.\r\n * @param severity - The severity of the log message\r\n * @param msgId - The log message.\r\n */\n function _throwInternal(severity, msgId, msg, properties, isUserAct) {\n _self[_DYN_DIAG_LOG /* @min:%2ediagLog */]().throwInternal(severity, msgId, msg, properties, isUserAct);\n }\n function _initDefaults() {\n _eventTracking = null;\n _pageTracking = null;\n _pageViewManager = null;\n _pageViewPerformanceManager = null;\n _pageVisitTimeManager = null;\n _preInitTelemetryInitializers = null;\n _isBrowserLinkTrackingEnabled = false;\n _browserLinkInitializerAdded = false;\n _enableAutoRouteTracking = false;\n _historyListenerAdded = false;\n _disableExceptionTracking = false;\n _autoExceptionInstrumented = false;\n _enableUnhandledPromiseRejectionTracking = false;\n _autoUnhandledPromiseInstrumented = false;\n _autoTrackPageVisitTime = false;\n // Counts number of trackAjax invocations.\n // By default we only monitor X ajax call per view to avoid too much load.\n // Default value is set in config.\n // This counter keeps increasing even after the limit is reached.\n _trackAjaxAttempts = 0;\n // array with max length of 2 that store current url and previous url for SPA page route change trackPageview use.\n var location = getLocation(true);\n _prevUri = location && location[_DYN_HREF /* @min:%2ehref */] || \"\";\n _currUri = null;\n _evtNamespace = null;\n _extConfig = null;\n _errorHookCnt = 0;\n // Define _self.config\n objDefine(_self, \"config\", {\n g: function () {\n return _extConfig;\n }\n });\n }\n // For backward compatibility\n objDefine(_self, \"_pageViewManager\", {\n g: function () {\n return _pageViewManager;\n }\n });\n objDefine(_self, \"_pageViewPerformanceManager\", {\n g: function () {\n return _pageViewPerformanceManager;\n }\n });\n objDefine(_self, \"_pageVisitTimeManager\", {\n g: function () {\n return _pageVisitTimeManager;\n }\n });\n objDefine(_self, \"_evtNamespace\", {\n g: function () {\n return \".\" + _evtNamespace;\n }\n });\n });\n return _this;\n }\n // Removed Stub for AnalyticsPlugin.prototype.getCookieMgr.\n // Removed Stub for AnalyticsPlugin.prototype.processTelemetry.\n // Removed Stub for AnalyticsPlugin.prototype.trackEvent.\n // Removed Stub for AnalyticsPlugin.prototype.startTrackEvent.\n // Removed Stub for AnalyticsPlugin.prototype.stopTrackEvent.\n // Removed Stub for AnalyticsPlugin.prototype.trackTrace.\n // Removed Stub for AnalyticsPlugin.prototype.trackMetric.\n // Removed Stub for AnalyticsPlugin.prototype.trackPageView.\n // Removed Stub for AnalyticsPlugin.prototype.sendPageViewInternal.\n // Removed Stub for AnalyticsPlugin.prototype.sendPageViewPerformanceInternal.\n // Removed Stub for AnalyticsPlugin.prototype.trackPageViewPerformance.\n // Removed Stub for AnalyticsPlugin.prototype.startTrackPage.\n // Removed Stub for AnalyticsPlugin.prototype.stopTrackPage.\n // Removed Stub for AnalyticsPlugin.prototype.sendExceptionInternal.\n // Removed Stub for AnalyticsPlugin.prototype.trackException.\n // Removed Stub for AnalyticsPlugin.prototype._onerror.\n // Removed Stub for AnalyticsPlugin.prototype.addTelemetryInitializer.\n // Removed Stub for AnalyticsPlugin.prototype.initialize.\n AnalyticsPlugin.Version = '3.3.6'; // Not currently used anywhere\n return AnalyticsPlugin;\n}(BaseTelemetryPlugin);\nexport { AnalyticsPlugin };\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n// @skip-file-minify\n// ##############################################################\n// AUTO GENERATED FILE: This file is Auto Generated during build.\n// ##############################################################\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n// Note: DON'T Export these const from the package as we are still targeting ES5 which can result in a mutable variables that someone could change!!!\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nexport var _DYN_FEATURE_OPT_IN = \"featureOptIn\"; // Count: 4\nexport var _DYN_SCHEDULE_FETCH_TIMEO0 = \"scheduleFetchTimeout\"; // Count: 2\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nimport { isNullOrUndefined, isObject, objExtend, objForEachKey, setValueByKey } from \"@nevware21/ts-utils\";\nimport { _DYN_FEATURE_OPT_IN } from \"./__DynamicConstants\";\n/**\r\n * Delete a config key in the given cfg, if the config key exists in nonOverrideConfigs and its value is set to true\r\n * @param cfg - cfg to modify\r\n * @param nonOverrideConfigs - nonOverrideConfigs\r\n * @param curLevel - cur config level, starting at 0\r\n * @param maxLevel - max config level\r\n * @returns new copy of modified configs\r\n */\nexport function replaceByNonOverrideCfg(cfg, nonOverrideConfigs, curLevel, maxLevel) {\n try {\n var exceedMaxLevel = curLevel > maxLevel;\n if (exceedMaxLevel) {\n cfg = null;\n }\n var curCfg_1 = curLevel == 0 ? objExtend({}, cfg) : cfg; // only copy cfg at the begining level\n if (curCfg_1 && nonOverrideConfigs && !exceedMaxLevel) {\n objForEachKey(curCfg_1, function (key) {\n var nonOverrideVal = nonOverrideConfigs[key];\n if (!!nonOverrideVal) {\n if (isObject(curCfg_1[key]) && isObject(nonOverrideVal)) {\n curCfg_1[key] = replaceByNonOverrideCfg(curCfg_1[key], nonOverrideVal, ++curLevel, maxLevel);\n } else {\n delete curCfg_1[key];\n }\n }\n });\n }\n return curCfg_1;\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n // if errors happen, do nothing\n return cfg;\n}\n// CDN Mode, value = B (CDN value = B)\n// |--------------------------------------------------------------------------|-----------|\n// | | none | disabled | enabled | forceOn | forceOff |\n// | ------------------ | ----------- | ----------- | ----------- | --------- | --------- |\n// | User Mode, value = A | none | none | disabled | enabled | enabled | disabled |\n// (user Value = A) | disabled | disabled | disabled | disabled | enabled | disabled |\n// | enabled | enabled | disabled | enabled | enabled | disabled |\n// | none(blockCdn) | none | none | none | none | none |\n// | disabled(blockCdn) | disabled | disabled | disabled | disabled | disabled |\n// | enabled(blockCdn) | enabled | enabled | enabled | enabled | enabled |\n// This matrix identifies how feature based overrides are selected (if present)\n// cdn Mode (cdn Value = B)\n// |---------------------------------------------------------------------------|\n// | | none | disabled | enabled | forceOn | forceOff |\n// | ------------------ | ---------| ---------| ---------| ---------|----------|\n// | User Mode | none | A | A | A || B | B || A | B || A |\n// (user Value = A) | disabled | A | A | A | B || A | B || A |\n// | enabled | A | A | A || B | B || A | B || A |\n// | none(blockCdn) | A | A | A | A | A |\n// | disabled(blockCdn) | A | A | A | A | A |\n// | enabled(blockCdn) | A | A | A | A | A |\n// Note:\n// Where the \"value\" is an object (map) of encoded key/values which will be used to override the real configuration\n// A = either the user supplied enable/disable value (via the `config.featureOptIn[name]`) or if not defined by the user the SDK defaults of the same.\n// B = The enable/disable value obtained from the CDN for the named feature\n// These are evaluated based on the above matrix to either\n// - A (Always the user/sdk value)\n// - B (Always the value from the CDN)\n// - A || B (If A is null or undefined use the value from the CDN (B) otherwise A)\n// - B || A (If B is null or undefined use the user/SDK value otherwise use the value from the CDN)\n//\n// The result of the value may also be null / undefined, which means there are no overrides to apply when the feature is enabled\nvar F = \"featureOptIn.\";\nvar M = \".mode\";\nvar ON = \".onCfg\";\nvar OFF = \".offCfg\";\nexport function resolveCdnFeatureCfg(field, cdnCfg, userOptInDetails) {\n var _a;\n // cdn conifg value\n if (!cdnCfg || !cdnCfg.enabled) {\n return null;\n }\n var cdnFt = (cdnCfg[_DYN_FEATURE_OPT_IN /* @min:%2efeatureOptIn */] || {})[field] || {\n mode: 1 /* CdnFeatureMode.none */\n };\n var cdnM = cdnFt.mode;\n var cdnOnV = cdnFt.onCfg;\n var cdnOffV = cdnFt.offCfg;\n var userFt = (userOptInDetails || {})[field] || {\n mode: 2 /* FeatureOptInMode.disable */\n }; // default user mode is disable\n var userM = userFt.mode;\n var userOnV = userFt.onCfg;\n var userOffV = userFt.offCfg;\n var blockCdn = !!userFt.blockCdnCfg;\n var mFld = F + field + M;\n var onFld = F + field + ON;\n var offFld = F + field + OFF;\n var mode = userM;\n var onV = userOnV;\n var offV = userOffV;\n if (!blockCdn) {\n if (cdnM === 4 /* CdnFeatureMode.forceOn */ || cdnM === 5 /* CdnFeatureMode.forceOff */) {\n mode = cdnM == 4 /* CdnFeatureMode.forceOn */ ? 3 /* FeatureOptInMode.enable */ : 2 /* FeatureOptInMode.disable */;\n onV = cdnOnV || userOnV;\n offV = cdnOffV || userOffV;\n } else if (cdnM === 2 /* CdnFeatureMode.disable */ || userM === 2 /* FeatureOptInMode.disable */) {\n mode = 2 /* FeatureOptInMode.disable */;\n onV = userOnV || cdnOnV;\n offV = userOffV || cdnOffV;\n } else if (cdnM === 3 /* CdnFeatureMode.enable */) {\n mode = 3 /* FeatureOptInMode.enable */;\n onV = userOnV || cdnOnV;\n offV = userOffV || cdnOffV;\n } else if (cdnM === 1 /* CdnFeatureMode.none */ && userM === 1 /* FeatureOptInMode.none */) {\n mode = 1 /* FeatureOptInMode.none */;\n }\n }\n return _a = {}, _a[mFld] = mode, _a[onFld] = onV, _a[offFld] = offV, _a;\n}\n// helper function to get cdn config with opt-in features\nexport function applyCdnfeatureCfg(cdnCfg, core) {\n try {\n if (!cdnCfg || !cdnCfg.enabled) {\n return null;\n }\n if (!cdnCfg[_DYN_FEATURE_OPT_IN /* @min:%2efeatureOptIn */]) {\n return cdnCfg.config;\n }\n var optInMap = cdnCfg[_DYN_FEATURE_OPT_IN /* @min:%2efeatureOptIn */];\n var cdnConfig_1 = cdnCfg.config || {};\n objForEachKey(optInMap, function (key) {\n var featureVal = resolveCdnFeatureCfg(key, cdnCfg, core.config[_DYN_FEATURE_OPT_IN /* @min:%2efeatureOptIn */]);\n if (!isNullOrUndefined(featureVal)) {\n objForEachKey(featureVal, function (config, val) {\n setValueByKey(cdnConfig_1, config, val);\n });\n _overrideCdnCfgByFeature(key, featureVal, cdnConfig_1);\n }\n });\n return cdnConfig_1;\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n return null;\n}\nfunction _overrideCdnCfgByFeature(field, ftVal, config) {\n var mode = ftVal[F + field + M];\n var val = ftVal[F + field + ON];\n var dVal = ftVal[F + field + OFF];\n var target = null;\n if (mode === 3 /* FeatureOptInMode.enable */) {\n target = val;\n }\n if (mode === 2 /* FeatureOptInMode.disable */) {\n target = dVal;\n }\n if (target) {\n objForEachKey(target, function (key, cfg) {\n setValueByKey(config, key, cfg);\n });\n }\n}\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n/**\r\n* CfgSyncPlugin.ts\r\n* @copyright Microsoft 2018\r\n*/\nvar _a;\nimport { __extendsFn as __extends } from \"@microsoft/applicationinsights-shims\";\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { DisabledPropertyName } from \"@microsoft/applicationinsights-common\";\nimport { BaseTelemetryPlugin, createProcessTelemetryContext, createUniqueNamespace, eventOff, eventOn, getGlobal, getJSON, isFetchSupported, isXhrSupported, mergeEvtNamespace, onConfigChange, sendCustomEvent } from \"@microsoft/applicationinsights-core-js\";\nimport { doAwaitResponse } from \"@nevware21/ts-async\";\nimport { isFunction, isNullOrUndefined, isPlainObject, objDeepFreeze, scheduleTimeout } from \"@nevware21/ts-utils\";\nimport { applyCdnfeatureCfg, replaceByNonOverrideCfg } from \"./CfgSyncHelperFuncs\";\nimport { _DYN_SCHEDULE_FETCH_TIMEO0 } from \"./__DynamicConstants\";\nvar EVENT_NAME = \"ai_cfgsync\";\nvar STR_GET_METHOD = \"GET\";\nvar FETCH_TIMEOUT = 1800000; // 30 minutes\nvar udfVal = undefined;\nvar defaultNonOverrideCfg = {\n instrumentationKey: true,\n connectionString: true,\n endpointUrl: true\n};\nvar _defaultConfig = objDeepFreeze((_a = {\n syncMode: 1 /* ICfgSyncMode.Broadcast */,\n blkCdnCfg: udfVal,\n customEvtName: udfVal,\n cfgUrl: udfVal,\n overrideSyncFn: udfVal,\n overrideFetchFn: udfVal,\n onCfgChangeReceive: udfVal\n}, _a[_DYN_SCHEDULE_FETCH_TIMEO0 /* @min:scheduleFetchTimeout */] = FETCH_TIMEOUT, _a.nonOverrideConfigs = defaultNonOverrideCfg, _a.enableAjax = false, _a));\nvar CfgSyncPlugin = /** @class */function (_super) {\n __extends(CfgSyncPlugin, _super);\n function CfgSyncPlugin() {\n var _this = _super.call(this) || this;\n _this.priority = 198;\n _this.identifier = \"AppInsightsCfgSyncPlugin\";\n var _extensionConfig;\n var _mainConfig; // throttle config should be wrapped in IConfiguration\n var _evtName;\n var _evtNamespace;\n var _cfgUrl;\n var _timeoutHandle;\n var _receiveChanges;\n var _broadcastChanges;\n var _blkCdnCfg;\n var _fetchTimeout;\n var _retryCnt;\n var _onCfgChangeReceive;\n var _nonOverrideConfigs;\n var _fetchFn;\n var _overrideFetchFn;\n var _overrideSyncFn;\n var _paused = false;\n var _enableAjax;\n dynamicProto(CfgSyncPlugin, _this, function (_self, _base) {\n _initDefaults();\n _self.initialize = function (config, core, extensions, pluginChain) {\n _base.initialize(config, core, extensions, pluginChain);\n _evtNamespace = mergeEvtNamespace(createUniqueNamespace(_self.identifier), core.evtNamespace && core.evtNamespace());\n _populateDefaults(config);\n };\n _self.getCfg = function () {\n return _mainConfig;\n };\n _self.pause = function () {\n _paused = true;\n _clearScheduledTimer();\n };\n _self.resume = function () {\n _paused = false;\n _setupTimer();\n };\n // used for V2 to manaully trigger config udpate\n _self.setCfg = function (config) {\n return _setCfg(config);\n };\n _self.sync = function (customDetails) {\n return _sendCfgsyncEvents(customDetails);\n };\n _self.updateEventListenerName = function (eventName) {\n return _updateEventListenerName(eventName);\n };\n _self._doTeardown = function (unloadCtx, unloadState) {\n _eventOff();\n _clearScheduledTimer();\n _initDefaults();\n };\n _self[\"_getDbgPlgTargets\"] = function () {\n return [_broadcastChanges, _receiveChanges, _evtName, _blkCdnCfg, _nonOverrideConfigs];\n };\n function _initDefaults() {\n _mainConfig = null;\n _evtName = null;\n _evtNamespace = null;\n _cfgUrl = null;\n _receiveChanges = null;\n _broadcastChanges = null;\n _nonOverrideConfigs = null;\n _timeoutHandle = null;\n _fetchTimeout = null;\n _retryCnt = null;\n _blkCdnCfg = null;\n _enableAjax = false;\n _overrideFetchFn = null;\n _overrideSyncFn = null;\n _onCfgChangeReceive = null;\n }\n function _populateDefaults(config) {\n var identifier = _self.identifier;\n var core = _self.core;\n _self._addHook(onConfigChange(config, function () {\n var ctx = createProcessTelemetryContext(null, config, core);\n _extensionConfig = ctx.getExtCfg(identifier, _defaultConfig);\n var preBlkCdn = _blkCdnCfg;\n _blkCdnCfg = !!_extensionConfig.blkCdnCfg;\n _enableAjax = !!_extensionConfig.enableAjax;\n // avoid initial call\n if (!isNullOrUndefined(preBlkCdn) && preBlkCdn !== _blkCdnCfg) {\n if (!_blkCdnCfg && _cfgUrl) {\n _fetchFn && _fetchFn(_cfgUrl, _onFetchComplete, _broadcastChanges);\n } else {\n _clearScheduledTimer();\n }\n }\n if (isNullOrUndefined(_receiveChanges)) {\n _receiveChanges = _extensionConfig.syncMode === 2 /* ICfgSyncMode.Receive */;\n }\n if (isNullOrUndefined(_broadcastChanges)) {\n _broadcastChanges = _extensionConfig.syncMode === 1 /* ICfgSyncMode.Broadcast */;\n }\n var newEvtName = _extensionConfig.customEvtName || EVENT_NAME;\n if (_evtName !== newEvtName) {\n if (_receiveChanges) {\n _updateEventListenerName(newEvtName);\n } else {\n _eventOff();\n _evtName = newEvtName;\n }\n }\n if (isNullOrUndefined(_cfgUrl)) {\n _cfgUrl = _extensionConfig.cfgUrl;\n }\n // if cfgUrl is set, we will ignore core config change\n if (!_cfgUrl) {\n _mainConfig = config;\n if (_broadcastChanges) {\n _sendCfgsyncEvents();\n }\n }\n }));\n _overrideSyncFn = _extensionConfig.overrideSyncFn;\n _overrideFetchFn = _extensionConfig.overrideFetchFn;\n _onCfgChangeReceive = _extensionConfig.onCfgChangeReceive;\n _nonOverrideConfigs = _extensionConfig.nonOverrideConfigs; // override values should not be changed\n _fetchTimeout = _extensionConfig[_DYN_SCHEDULE_FETCH_TIMEO0 /* @min:%2escheduleFetchTimeout */];\n _fetchFn = _getFetchFnInterface();\n _retryCnt = 0;\n // NOT support cfgURL change to avoid mutiple fetch calls\n if (_cfgUrl && !_blkCdnCfg) {\n _fetchFn && _fetchFn(_cfgUrl, _onFetchComplete, _broadcastChanges);\n }\n }\n function _setCfg(config, isAutoSync) {\n if (config) {\n _mainConfig = config;\n if (!!isAutoSync && !_paused) {\n return _sendCfgsyncEvents();\n }\n if (_receiveChanges && !_paused) {\n _self.core.updateCfg(config);\n return true;\n }\n }\n return false;\n }\n function _eventOff() {\n try {\n var global_1 = getGlobal();\n if (global_1) {\n eventOff(global_1, null, null, _evtNamespace);\n }\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n }\n function _sendCfgsyncEvents(customDetails) {\n try {\n if (!!_overrideSyncFn && isFunction(_overrideSyncFn)) {\n return _overrideSyncFn(_mainConfig, customDetails);\n }\n return sendCustomEvent(_evtName, _mainConfig, customDetails);\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n return false;\n }\n function _updateEventListenerName(name) {\n try {\n _eventOff();\n if (name) {\n _evtName = name;\n _addEventListener();\n }\n return true;\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n return false;\n }\n function _getFetchFnInterface() {\n var _fetchFn = _overrideFetchFn;\n if (isNullOrUndefined(_fetchFn)) {\n if (isFetchSupported()) {\n _fetchFn = _fetchSender;\n } else if (isXhrSupported()) {\n _fetchFn = _xhrSender;\n }\n }\n return _fetchFn;\n }\n function _fetchSender(url, oncomplete, isAutoSync) {\n var global = getGlobal();\n var fetchFn = global && global.fetch || null;\n if (url && fetchFn && isFunction(fetchFn)) {\n try {\n var init = {\n method: STR_GET_METHOD\n };\n if (!_enableAjax) {\n init[DisabledPropertyName] = true;\n }\n var request = new Request(url, init);\n if (!_enableAjax) {\n try {\n // Also try and tag the request (just in case the value in init is not copied over)\n request[DisabledPropertyName] = true;\n } catch (e) {\n // If the environment has locked down the XMLHttpRequest (preventExtensions and/or freeze), this would\n // cause the request to fail and we no telemetry would be sent\n }\n }\n doAwaitResponse(fetch(request), function (result) {\n var response = result.value;\n if (!result.rejected) {\n if (response.ok) {\n doAwaitResponse(response.text(), function (res) {\n _doOnComplete(oncomplete, response.status, res.value, isAutoSync);\n });\n } else {\n _doOnComplete(oncomplete, response.status, null, isAutoSync);\n }\n } else {\n _doOnComplete(oncomplete, 400);\n }\n });\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n }\n }\n function _xhrSender(url, oncomplete, isAutoSync) {\n try {\n var xhr_1 = new XMLHttpRequest();\n if (!_enableAjax) {\n xhr_1[DisabledPropertyName] = true;\n }\n xhr_1.open(STR_GET_METHOD, url);\n xhr_1.onreadystatechange = function () {\n if (xhr_1.readyState === XMLHttpRequest.DONE) {\n _doOnComplete(oncomplete, xhr_1.status, xhr_1.responseText, isAutoSync);\n }\n };\n xhr_1.onerror = function () {\n _doOnComplete(oncomplete, 400);\n };\n xhr_1.ontimeout = function () {\n _doOnComplete(oncomplete, 400);\n };\n xhr_1.send();\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n }\n function _onFetchComplete(status, response, isAutoSync) {\n try {\n if (status >= 200 && status < 400 && response) {\n _retryCnt = 0; // any successful response will reset retry count to 0\n var JSON_1 = getJSON();\n if (JSON_1) {\n var cdnCfg = JSON_1.parse(response); //comments are not allowed\n var cfg = applyCdnfeatureCfg(cdnCfg, _self.core);\n var newCfg = cfg && isPlainObject(cfg) && _replaceTartgetByKeys(cfg);\n newCfg && _setCfg(newCfg, isAutoSync);\n //cfg && _setCfg(cfg, isAutoSync);\n }\n } else {\n _retryCnt++;\n }\n if (_retryCnt < 3) {\n _setupTimer();\n }\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n }\n function _doOnComplete(oncomplete, status, response, isAutoSync) {\n try {\n oncomplete(status, response, isAutoSync);\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n }\n function _addEventListener() {\n if (_receiveChanges) {\n var global_2 = getGlobal();\n if (global_2) {\n try {\n eventOn(global_2, _evtName, function (event) {\n // TODO: add more validation here\n // may include a \"name\" or some other features to check\n var cfgEvent = event && event.detail;\n if (_onCfgChangeReceive && cfgEvent) {\n _onCfgChangeReceive(cfgEvent);\n } else {\n var cfg = cfgEvent && cfgEvent.cfg;\n var newCfg = cfg && isPlainObject(cfg) && _replaceTartgetByKeys(cfg);\n newCfg && _setCfg(newCfg);\n }\n }, _evtNamespace, true);\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n }\n }\n }\n // 4 levels\n function _replaceTartgetByKeys(cfg, level) {\n var _cfg = null;\n try {\n if (cfg) {\n _cfg = replaceByNonOverrideCfg(cfg, _nonOverrideConfigs, 0, 5);\n }\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n return _cfg;\n }\n /**\r\n * Sets up the timer which triggers fetching cdn every 30mins after inital call\r\n */\n function _setupTimer() {\n if (!_timeoutHandle && _fetchTimeout) {\n _timeoutHandle = scheduleTimeout(function () {\n _timeoutHandle = null;\n _fetchFn(_cfgUrl, _onFetchComplete, _broadcastChanges);\n }, _fetchTimeout);\n _timeoutHandle.unref();\n }\n }\n function _clearScheduledTimer() {\n _timeoutHandle && _timeoutHandle.cancel();\n _timeoutHandle = null;\n _retryCnt = 0;\n }\n _self.processTelemetry = function (env, itemCtx) {\n _self.processNext(env, itemCtx);\n };\n });\n return _this;\n }\n // Removed Stub for CfgSyncPlugin.prototype.initialize.\n // Removed Stub for CfgSyncPlugin.prototype.getCfg.\n // Removed Stub for CfgSyncPlugin.prototype.setCfg.\n // Removed Stub for CfgSyncPlugin.prototype.sync.\n // Removed Stub for CfgSyncPlugin.prototype.updateEventListenerName.\n // Removed Stub for CfgSyncPlugin.prototype.pause.\n // Removed Stub for CfgSyncPlugin.prototype.resume.\n //// Removed Stub for CfgSyncPlugin.prototype.processTelemetry.\n // This is a workaround for an IE bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n CfgSyncPlugin.__ieDyn = 1;\n return CfgSyncPlugin;\n}(BaseTelemetryPlugin);\nexport { CfgSyncPlugin };\n","/*\n * Application Insights JavaScript SDK - Channel, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n// ###################################################################################################################################################\n// Note: DON'T Export these const from the package as we are still targeting IE/ES5 this will export a mutable variables that someone could change ###\n// ###################################################################################################################################################\n// Generally you should only put values that are used more than 2 times and then only if not already exposed as a constant (such as SdkCoreNames)\n// as when using \"short\" named values from here they will be will be minified smaller than the SdkCoreNames[eSdkCoreNames.xxxx] value.\nexport var STR_DURATION = \"duration\";\n","/*\n * Application Insights JavaScript SDK - Channel, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n// @skip-file-minify\n// ##############################################################\n// AUTO GENERATED FILE: This file is Auto Generated during build.\n// ##############################################################\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n// Note: DON'T Export these const from the package as we are still targeting ES5 which can result in a mutable variables that someone could change!!!\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nexport var _DYN_TAGS = \"tags\"; // Count: 17\nexport var _DYN_DEVICE_TYPE = \"deviceType\"; // Count: 3\nexport var _DYN_DATA = \"data\"; // Count: 13\nexport var _DYN_NAME = \"name\"; // Count: 8\nexport var _DYN_TRACE_ID = \"traceID\"; // Count: 5\nexport var _DYN_LENGTH = \"length\"; // Count: 38\nexport var _DYN_STRINGIFY = \"stringify\"; // Count: 5\nexport var _DYN_MEASUREMENTS = \"measurements\"; // Count: 7\nexport var _DYN_DATA_TYPE = \"dataType\"; // Count: 10\nexport var _DYN_ENVELOPE_TYPE = \"envelopeType\"; // Count: 7\nexport var _DYN_TO_STRING = \"toString\"; // Count: 7\nexport var _DYN_ENQUEUE = \"enqueue\"; // Count: 7\nexport var _DYN_COUNT = \"count\"; // Count: 7\nexport var _DYN_PUSH = \"push\"; // Count: 9\nexport var _DYN_EMIT_LINE_DELIMITED_0 = \"emitLineDelimitedJson\"; // Count: 3\nexport var _DYN_CLEAR = \"clear\"; // Count: 6\nexport var _DYN_MARK_AS_SENT = \"markAsSent\"; // Count: 4\nexport var _DYN_CLEAR_SENT = \"clearSent\"; // Count: 5\nexport var _DYN_BUFFER_OVERRIDE = \"bufferOverride\"; // Count: 3\nexport var _DYN__BUFFER__KEY = \"BUFFER_KEY\"; // Count: 5\nexport var _DYN__SENT__BUFFER__KEY = \"SENT_BUFFER_KEY\"; // Count: 8\nexport var _DYN_CONCAT = \"concat\"; // Count: 6\nexport var _DYN__MAX__BUFFER__SIZE = \"MAX_BUFFER_SIZE\"; // Count: 5\nexport var _DYN_TRIGGER_SEND = \"triggerSend\"; // Count: 5\nexport var _DYN_DIAG_LOG = \"diagLog\"; // Count: 16\nexport var _DYN_INITIALIZE = \"initialize\"; // Count: 3\nexport var _DYN__SENDER = \"_sender\"; // Count: 5\nexport var _DYN_ENDPOINT_URL = \"endpointUrl\"; // Count: 5\nexport var _DYN_INSTRUMENTATION_KEY = \"instrumentationKey\"; // Count: 5\nexport var _DYN_CUSTOM_HEADERS = \"customHeaders\"; // Count: 3\nexport var _DYN_MAX_BATCH_SIZE_IN_BY1 = \"maxBatchSizeInBytes\"; // Count: 2\nexport var _DYN_ONUNLOAD_DISABLE_BEA2 = \"onunloadDisableBeacon\"; // Count: 3\nexport var _DYN_IS_BEACON_API_DISABL3 = \"isBeaconApiDisabled\"; // Count: 3\nexport var _DYN_ALWAYS_USE_XHR_OVERR4 = \"alwaysUseXhrOverride\"; // Count: 2\nexport var _DYN_ENABLE_SESSION_STORA5 = \"enableSessionStorageBuffer\"; // Count: 2\nexport var _DYN__BUFFER = \"_buffer\"; // Count: 9\nexport var _DYN_ONUNLOAD_DISABLE_FET6 = \"onunloadDisableFetch\"; // Count: 2\nexport var _DYN_DISABLE_SEND_BEACON_7 = \"disableSendBeaconSplit\"; // Count: 2\nexport var _DYN_GET_SENDER_INST = \"getSenderInst\"; // Count: 4\nexport var _DYN__ON_ERROR = \"_onError\"; // Count: 7\nexport var _DYN__ON_PARTIAL_SUCCESS = \"_onPartialSuccess\"; // Count: 3\nexport var _DYN__ON_SUCCESS = \"_onSuccess\"; // Count: 6\nexport var _DYN_ITEMS_RECEIVED = \"itemsReceived\"; // Count: 3\nexport var _DYN_ITEMS_ACCEPTED = \"itemsAccepted\"; // Count: 3\nexport var _DYN_BASE_TYPE = \"baseType\"; // Count: 4\nexport var _DYN_SAMPLE_RATE = \"sampleRate\"; // Count: 4\nexport var _DYN_GET_HASH_CODE_SCORE = \"getHashCodeScore\"; // Count: 4\n","/*\n * Application Insights JavaScript SDK - Channel, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nimport { __assignFn as __assign } from \"@microsoft/applicationinsights-shims\";\nimport { CtxTagKeys, Data, Envelope, Event, Exception, HttpMethod, Metric, PageView, PageViewPerformance, RemoteDependencyData, SampleRate, Trace, dataSanitizeString } from \"@microsoft/applicationinsights-common\";\nimport { _throwInternal, _warnToConsole, getJSON, hasJSON, isNullOrUndefined, isNumber, isString, isTruthy, objForEachKey, optimizeObject, setValue, toISOString } from \"@microsoft/applicationinsights-core-js\";\nimport { STR_DURATION } from \"./InternalConstants\";\nimport { _DYN_DATA, _DYN_DATA_TYPE, _DYN_DEVICE_TYPE, _DYN_ENVELOPE_TYPE, _DYN_LENGTH, _DYN_MEASUREMENTS, _DYN_NAME, _DYN_STRINGIFY, _DYN_TAGS, _DYN_TO_STRING, _DYN_TRACE_ID } from \"./__DynamicConstants\";\n// these two constants are used to filter out properties not needed when trying to extract custom properties and measurements from the incoming payload\nvar strBaseType = \"baseType\";\nvar strBaseData = \"baseData\";\nvar strProperties = \"properties\";\nvar strTrue = \"true\";\nfunction _setValueIf(target, field, value) {\n return setValue(target, field, value, isTruthy);\n}\n/*\r\n * Maps Part A data from CS 4.0\r\n */\nfunction _extractPartAExtensions(logger, item, env) {\n // todo: switch to keys from common in this method\n var envTags = env[_DYN_TAGS /* @min:%2etags */] = env[_DYN_TAGS /* @min:%2etags */] || {};\n var itmExt = item.ext = item.ext || {};\n var itmTags = item[_DYN_TAGS /* @min:%2etags */] = item[_DYN_TAGS /* @min:%2etags */] || [];\n var extUser = itmExt.user;\n if (extUser) {\n _setValueIf(envTags, CtxTagKeys.userAuthUserId, extUser.authId);\n _setValueIf(envTags, CtxTagKeys.userId, extUser.id || extUser.localId);\n }\n var extApp = itmExt.app;\n if (extApp) {\n _setValueIf(envTags, CtxTagKeys.sessionId, extApp.sesId);\n }\n var extDevice = itmExt.device;\n if (extDevice) {\n _setValueIf(envTags, CtxTagKeys.deviceId, extDevice.id || extDevice.localId);\n _setValueIf(envTags, CtxTagKeys[_DYN_DEVICE_TYPE /* @min:%2edeviceType */], extDevice.deviceClass);\n _setValueIf(envTags, CtxTagKeys.deviceIp, extDevice.ip);\n _setValueIf(envTags, CtxTagKeys.deviceModel, extDevice.model);\n _setValueIf(envTags, CtxTagKeys[_DYN_DEVICE_TYPE /* @min:%2edeviceType */], extDevice[_DYN_DEVICE_TYPE /* @min:%2edeviceType */]);\n }\n var web = item.ext.web;\n if (web) {\n _setValueIf(envTags, CtxTagKeys.deviceLanguage, web.browserLang);\n _setValueIf(envTags, CtxTagKeys.deviceBrowserVersion, web.browserVer);\n _setValueIf(envTags, CtxTagKeys.deviceBrowser, web.browser);\n var envData = env[_DYN_DATA /* @min:%2edata */] = env[_DYN_DATA /* @min:%2edata */] || {};\n var envBaseData = envData[strBaseData] = envData[strBaseData] || {};\n var envProps = envBaseData[strProperties] = envBaseData[strProperties] || {};\n _setValueIf(envProps, \"domain\", web.domain);\n _setValueIf(envProps, \"isManual\", web.isManual ? strTrue : null);\n _setValueIf(envProps, \"screenRes\", web.screenRes);\n _setValueIf(envProps, \"userConsent\", web.userConsent ? strTrue : null);\n }\n var extOs = itmExt.os;\n if (extOs) {\n _setValueIf(envTags, CtxTagKeys.deviceOS, extOs[_DYN_NAME /* @min:%2ename */]);\n _setValueIf(envTags, CtxTagKeys.deviceOSVersion, extOs.osVer);\n }\n // No support for mapping Trace.traceState to 2.0 as it is currently empty\n var extTrace = itmExt.trace;\n if (extTrace) {\n _setValueIf(envTags, CtxTagKeys.operationParentId, extTrace.parentID);\n _setValueIf(envTags, CtxTagKeys.operationName, dataSanitizeString(logger, extTrace[_DYN_NAME /* @min:%2ename */]));\n _setValueIf(envTags, CtxTagKeys.operationId, extTrace[_DYN_TRACE_ID /* @min:%2etraceID */]);\n }\n // Sample 4.0 schema\n // {\n // \"time\" : \"2018-09-05T22:51:22.4936Z\",\n // \"name\" : \"MetricWithNamespace\",\n // \"iKey\" : \"ABC-5a4cbd20-e601-4ef5-a3c6-5d6577e4398e\",\n // \"ext\": { \"cloud\": {\n // \"role\": \"WATSON3\",\n // \"roleInstance\": \"CO4AEAP00000260\"\n // },\n // \"device\": {}, \"correlation\": {} },\n // \"tags\": [\n // { \"amazon.region\" : \"east2\" },\n // { \"os.expid\" : \"wp:02df239\" }\n // ]\n // }\n var tgs = {};\n // deals with tags.push({object})\n for (var i = itmTags[_DYN_LENGTH /* @min:%2elength */] - 1; i >= 0; i--) {\n var tg = itmTags[i];\n objForEachKey(tg, function (key, value) {\n tgs[key] = value;\n });\n itmTags.splice(i, 1);\n }\n // deals with tags[key]=value (and handles hasOwnProperty)\n objForEachKey(itmTags, function (tg, value) {\n tgs[tg] = value;\n });\n var theTags = __assign(__assign({}, envTags), tgs);\n if (!theTags[CtxTagKeys.internalSdkVersion]) {\n // Append a version in case it is not already set\n theTags[CtxTagKeys.internalSdkVersion] = dataSanitizeString(logger, \"javascript:\".concat(EnvelopeCreator.Version), 64);\n }\n env[_DYN_TAGS /* @min:%2etags */] = optimizeObject(theTags);\n}\nfunction _extractPropsAndMeasurements(data, properties, measurements) {\n if (!isNullOrUndefined(data)) {\n objForEachKey(data, function (key, value) {\n if (isNumber(value)) {\n measurements[key] = value;\n } else if (isString(value)) {\n properties[key] = value;\n } else if (hasJSON()) {\n properties[key] = getJSON()[_DYN_STRINGIFY /* @min:%2estringify */](value);\n }\n });\n }\n}\nfunction _convertPropsUndefinedToCustomDefinedValue(properties, customUndefinedValue) {\n if (!isNullOrUndefined(properties)) {\n objForEachKey(properties, function (key, value) {\n properties[key] = value || customUndefinedValue;\n });\n }\n}\n// TODO: Do we want this to take logger as arg or use this._logger as nonstatic?\nfunction _createEnvelope(logger, envelopeType, telemetryItem, data) {\n var envelope = new Envelope(logger, data, envelopeType);\n _setValueIf(envelope, \"sampleRate\", telemetryItem[SampleRate]);\n if ((telemetryItem[strBaseData] || {}).startTime) {\n // Starting from Version 3.0.3, the time property will be assigned by the startTime value,\n // which records the loadEvent time for the pageView event.\n envelope.time = toISOString(telemetryItem[strBaseData].startTime);\n }\n envelope.iKey = telemetryItem.iKey;\n var iKeyNoDashes = telemetryItem.iKey.replace(/-/g, \"\");\n envelope[_DYN_NAME /* @min:%2ename */] = envelope[_DYN_NAME /* @min:%2ename */].replace(\"{0}\", iKeyNoDashes);\n // extract all extensions from ctx\n _extractPartAExtensions(logger, telemetryItem, envelope);\n // loop through the envelope tags (extension of Part A) and pick out the ones that should go in outgoing envelope tags\n telemetryItem[_DYN_TAGS /* @min:%2etags */] = telemetryItem[_DYN_TAGS /* @min:%2etags */] || [];\n return optimizeObject(envelope);\n}\nfunction EnvelopeCreatorInit(logger, telemetryItem) {\n if (isNullOrUndefined(telemetryItem[strBaseData])) {\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 46 /* _eInternalMessageId.TelemetryEnvelopeInvalid */, \"telemetryItem.baseData cannot be null.\");\n }\n}\nexport var EnvelopeCreator = {\n Version: '3.3.6'\n};\nexport function DependencyEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\n EnvelopeCreatorInit(logger, telemetryItem);\n var customMeasurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\n var customProperties = telemetryItem[strBaseData][strProperties] || {};\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], customProperties, customMeasurements);\n if (!isNullOrUndefined(customUndefinedValue)) {\n _convertPropsUndefinedToCustomDefinedValue(customProperties, customUndefinedValue);\n }\n var bd = telemetryItem[strBaseData];\n if (isNullOrUndefined(bd)) {\n _warnToConsole(logger, \"Invalid input for dependency data\");\n return null;\n }\n var method = bd[strProperties] && bd[strProperties][HttpMethod] ? bd[strProperties][HttpMethod] : \"GET\";\n var remoteDepData = new RemoteDependencyData(logger, bd.id, bd.target, bd[_DYN_NAME /* @min:%2ename */], bd[STR_DURATION /* @min:%2eduration */], bd.success, bd.responseCode, method, bd.type, bd.correlationContext, customProperties, customMeasurements);\n var data = new Data(RemoteDependencyData[_DYN_DATA_TYPE /* @min:%2edataType */], remoteDepData);\n return _createEnvelope(logger, RemoteDependencyData[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\n}\nexport function EventEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\n EnvelopeCreatorInit(logger, telemetryItem);\n var customProperties = {};\n var customMeasurements = {};\n if (telemetryItem[strBaseType] !== Event[_DYN_DATA_TYPE /* @min:%2edataType */]) {\n customProperties[\"baseTypeSource\"] = telemetryItem[strBaseType]; // save the passed in base type as a property\n }\n if (telemetryItem[strBaseType] === Event[_DYN_DATA_TYPE /* @min:%2edataType */]) {\n // take collection\n customProperties = telemetryItem[strBaseData][strProperties] || {};\n customMeasurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\n } else {\n // if its not a known type, convert to custom event\n if (telemetryItem[strBaseData]) {\n _extractPropsAndMeasurements(telemetryItem[strBaseData], customProperties, customMeasurements);\n }\n }\n // Extract root level properties from part C telemetryItem.data\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], customProperties, customMeasurements);\n if (!isNullOrUndefined(customUndefinedValue)) {\n _convertPropsUndefinedToCustomDefinedValue(customProperties, customUndefinedValue);\n }\n var eventName = telemetryItem[strBaseData][_DYN_NAME /* @min:%2ename */];\n var eventData = new Event(logger, eventName, customProperties, customMeasurements);\n var data = new Data(Event[_DYN_DATA_TYPE /* @min:%2edataType */], eventData);\n return _createEnvelope(logger, Event[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\n}\nexport function ExceptionEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\n EnvelopeCreatorInit(logger, telemetryItem);\n // Extract root level properties from part C telemetryItem.data\n var customMeasurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\n var customProperties = telemetryItem[strBaseData][strProperties] || {};\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], customProperties, customMeasurements);\n if (!isNullOrUndefined(customUndefinedValue)) {\n _convertPropsUndefinedToCustomDefinedValue(customProperties, customUndefinedValue);\n }\n var bd = telemetryItem[strBaseData];\n var exData = Exception.CreateFromInterface(logger, bd, customProperties, customMeasurements);\n var data = new Data(Exception[_DYN_DATA_TYPE /* @min:%2edataType */], exData);\n return _createEnvelope(logger, Exception[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\n}\nexport function MetricEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\n EnvelopeCreatorInit(logger, telemetryItem);\n var baseData = telemetryItem[strBaseData];\n var props = baseData[strProperties] || {};\n var measurements = baseData[_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], props, measurements);\n if (!isNullOrUndefined(customUndefinedValue)) {\n _convertPropsUndefinedToCustomDefinedValue(props, customUndefinedValue);\n }\n var baseMetricData = new Metric(logger, baseData[_DYN_NAME /* @min:%2ename */], baseData.average, baseData.sampleCount, baseData.min, baseData.max, baseData.stdDev, props, measurements);\n var data = new Data(Metric[_DYN_DATA_TYPE /* @min:%2edataType */], baseMetricData);\n return _createEnvelope(logger, Metric[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\n}\nexport function PageViewEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\n EnvelopeCreatorInit(logger, telemetryItem);\n // Since duration is not part of the domain properties in Common Schema, extract it from part C\n var duration;\n var baseData = telemetryItem[strBaseData];\n if (!isNullOrUndefined(baseData) && !isNullOrUndefined(baseData[strProperties]) && !isNullOrUndefined(baseData[strProperties][STR_DURATION])) {\n // from part B properties\n duration = baseData[strProperties][STR_DURATION];\n delete baseData[strProperties][STR_DURATION];\n } else if (!isNullOrUndefined(telemetryItem[_DYN_DATA /* @min:%2edata */]) && !isNullOrUndefined(telemetryItem[_DYN_DATA /* @min:%2edata */][STR_DURATION])) {\n // from custom properties\n duration = telemetryItem[_DYN_DATA /* @min:%2edata */][STR_DURATION];\n delete telemetryItem[_DYN_DATA /* @min:%2edata */][STR_DURATION];\n }\n var bd = telemetryItem[strBaseData];\n // special case: pageview.id is grabbed from current operation id. Analytics plugin is decoupled from properties plugin, so this is done here instead. This can be made a default telemetry intializer instead if needed to be decoupled from channel\n var currentContextId;\n if (((telemetryItem.ext || {}).trace || {})[_DYN_TRACE_ID /* @min:%2etraceID */]) {\n currentContextId = telemetryItem.ext.trace[_DYN_TRACE_ID /* @min:%2etraceID */];\n }\n var id = bd.id || currentContextId;\n var name = bd[_DYN_NAME /* @min:%2ename */];\n var url = bd.uri;\n var properties = bd[strProperties] || {};\n var measurements = bd[_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\n // refUri is a field that Breeze still does not recognize as part of Part B. For now, put it in Part C until it supports it as a domain property\n if (!isNullOrUndefined(bd.refUri)) {\n properties[\"refUri\"] = bd.refUri;\n }\n // pageType is a field that Breeze still does not recognize as part of Part B. For now, put it in Part C until it supports it as a domain property\n if (!isNullOrUndefined(bd.pageType)) {\n properties[\"pageType\"] = bd.pageType;\n }\n // isLoggedIn is a field that Breeze still does not recognize as part of Part B. For now, put it in Part C until it supports it as a domain property\n if (!isNullOrUndefined(bd.isLoggedIn)) {\n properties[\"isLoggedIn\"] = bd.isLoggedIn[_DYN_TO_STRING /* @min:%2etoString */]();\n }\n // pageTags is a field that Breeze still does not recognize as part of Part B. For now, put it in Part C until it supports it as a domain property\n if (!isNullOrUndefined(bd[strProperties])) {\n var pageTags = bd[strProperties];\n objForEachKey(pageTags, function (key, value) {\n properties[key] = value;\n });\n }\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], properties, measurements);\n if (!isNullOrUndefined(customUndefinedValue)) {\n _convertPropsUndefinedToCustomDefinedValue(properties, customUndefinedValue);\n }\n var pageViewData = new PageView(logger, name, url, duration, properties, measurements, id);\n var data = new Data(PageView[_DYN_DATA_TYPE /* @min:%2edataType */], pageViewData);\n return _createEnvelope(logger, PageView[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\n}\nexport function PageViewPerformanceEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\n EnvelopeCreatorInit(logger, telemetryItem);\n var bd = telemetryItem[strBaseData];\n var name = bd[_DYN_NAME /* @min:%2ename */];\n var url = bd.uri || bd.url;\n var properties = bd[strProperties] || {};\n var measurements = bd[_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], properties, measurements);\n if (!isNullOrUndefined(customUndefinedValue)) {\n _convertPropsUndefinedToCustomDefinedValue(properties, customUndefinedValue);\n }\n var baseData = new PageViewPerformance(logger, name, url, undefined, properties, measurements, bd);\n var data = new Data(PageViewPerformance[_DYN_DATA_TYPE /* @min:%2edataType */], baseData);\n return _createEnvelope(logger, PageViewPerformance[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\n}\nexport function TraceEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\n EnvelopeCreatorInit(logger, telemetryItem);\n var message = telemetryItem[strBaseData].message;\n var severityLevel = telemetryItem[strBaseData].severityLevel;\n var props = telemetryItem[strBaseData][strProperties] || {};\n var measurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], props, measurements);\n if (!isNullOrUndefined(customUndefinedValue)) {\n _convertPropsUndefinedToCustomDefinedValue(props, customUndefinedValue);\n }\n var baseData = new Trace(logger, message, severityLevel, props, measurements);\n var data = new Data(Trace[_DYN_DATA_TYPE /* @min:%2edataType */], baseData);\n return _createEnvelope(logger, Trace[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\n}\n","/*\n * Application Insights JavaScript SDK - Channel, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nimport { __extendsFn as __extends } from \"@microsoft/applicationinsights-shims\";\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { utlGetSessionStorage, utlRemoveSessionStorage, utlSetSessionStorage } from \"@microsoft/applicationinsights-common\";\nimport { _throwInternal, arrForEach, arrIndexOf, dumpObj, getExceptionName, getJSON, isArray, isFunction, isNullOrUndefined, isString } from \"@microsoft/applicationinsights-core-js\";\nimport { _DYN_BUFFER_OVERRIDE, _DYN_CLEAR, _DYN_CLEAR_SENT, _DYN_CONCAT, _DYN_COUNT, _DYN_EMIT_LINE_DELIMITED_0, _DYN_ENQUEUE, _DYN_LENGTH, _DYN_MARK_AS_SENT, _DYN_PUSH, _DYN_STRINGIFY, _DYN__BUFFER__KEY, _DYN__MAX__BUFFER__SIZE, _DYN__SENT__BUFFER__KEY } from \"./__DynamicConstants\";\nvar BaseSendBuffer = /** @class */function () {\n function BaseSendBuffer(logger, config) {\n var _buffer = [];\n var _bufferFullMessageSent = false;\n var _maxRetryCnt = config.maxRetryCnt;\n this._get = function () {\n return _buffer;\n };\n this._set = function (buffer) {\n _buffer = buffer;\n return _buffer;\n };\n dynamicProto(BaseSendBuffer, this, function (_self) {\n _self[_DYN_ENQUEUE /* @min:%2eenqueue */] = function (payload) {\n if (_self[_DYN_COUNT /* @min:%2ecount */]() >= config.eventsLimitInMem) {\n // sent internal log only once per page view\n if (!_bufferFullMessageSent) {\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 105 /* _eInternalMessageId.InMemoryStorageBufferFull */, \"Maximum in-memory buffer size reached: \" + _self[_DYN_COUNT /* @min:%2ecount */](), true);\n _bufferFullMessageSent = true;\n }\n return;\n }\n payload.cnt = payload.cnt || 0;\n // max retry is defined, and max retry is reached, do not add the payload to buffer\n if (!isNullOrUndefined(_maxRetryCnt)) {\n if (payload.cnt > _maxRetryCnt) {\n // TODO: add log here on dropping payloads\n return;\n }\n }\n _buffer[_DYN_PUSH /* @min:%2epush */](payload);\n return;\n };\n _self[_DYN_COUNT /* @min:%2ecount */] = function () {\n return _buffer[_DYN_LENGTH /* @min:%2elength */];\n };\n _self.size = function () {\n var size = _buffer[_DYN_LENGTH /* @min:%2elength */];\n for (var lp = 0; lp < _buffer[_DYN_LENGTH /* @min:%2elength */]; lp++) {\n size += _buffer[lp].item[_DYN_LENGTH /* @min:%2elength */];\n }\n if (!config[_DYN_EMIT_LINE_DELIMITED_0 /* @min:%2eemitLineDelimitedJson */]) {\n size += 2;\n }\n return size;\n };\n _self[_DYN_CLEAR /* @min:%2eclear */] = function () {\n _buffer = [];\n _bufferFullMessageSent = false;\n };\n _self.getItems = function () {\n return _buffer.slice(0);\n };\n _self.batchPayloads = function (payloads) {\n if (payloads && payloads[_DYN_LENGTH /* @min:%2elength */] > 0) {\n var payloadStr_1 = [];\n arrForEach(payloads, function (payload) {\n payloadStr_1[_DYN_PUSH /* @min:%2epush */](payload.item);\n });\n var batch = config[_DYN_EMIT_LINE_DELIMITED_0 /* @min:%2eemitLineDelimitedJson */] ? payloadStr_1.join(\"\\n\") : \"[\" + payloadStr_1.join(\",\") + \"]\";\n return batch;\n }\n return null;\n };\n _self.createNew = function (newLogger, newConfig, canUseSessionStorage) {\n var items = _buffer.slice(0);\n newLogger = newLogger || logger;\n newConfig = newConfig || {};\n var newBuffer = !!canUseSessionStorage ? new SessionStorageSendBuffer(newLogger, newConfig) : new ArraySendBuffer(newLogger, newConfig);\n arrForEach(items, function (payload) {\n newBuffer[_DYN_ENQUEUE /* @min:%2eenqueue */](payload);\n });\n return newBuffer;\n };\n });\n }\n // Removed Stub for BaseSendBuffer.prototype.enqueue.\n // Removed Stub for BaseSendBuffer.prototype.count.\n // Removed Stub for BaseSendBuffer.prototype.size.\n // Removed Stub for BaseSendBuffer.prototype.clear.\n // Removed Stub for BaseSendBuffer.prototype.getItems.\n // Removed Stub for BaseSendBuffer.prototype.batchPayloads.\n // Removed Stub for BaseSendBuffer.prototype.createNew.\n // This is a workaround for an IE bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n BaseSendBuffer.__ieDyn = 1;\n return BaseSendBuffer;\n}();\n/*\r\n * An array based send buffer.\r\n */\nvar ArraySendBuffer = /** @class */function (_super) {\n __extends(ArraySendBuffer, _super);\n function ArraySendBuffer(logger, config) {\n var _this = _super.call(this, logger, config) || this;\n dynamicProto(ArraySendBuffer, _this, function (_self, _base) {\n _self[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */] = function (payload) {\n _base[_DYN_CLEAR /* @min:%2eclear */]();\n };\n _self[_DYN_CLEAR_SENT /* @min:%2eclearSent */] = function (payload) {\n // not supported\n };\n });\n return _this;\n }\n // Removed Stub for ArraySendBuffer.prototype.markAsSent.\n // Removed Stub for ArraySendBuffer.prototype.clearSent.\n // This is a workaround for an IE bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n ArraySendBuffer.__ieDyn = 1;\n return ArraySendBuffer;\n}(BaseSendBuffer);\nexport { ArraySendBuffer };\nvar PREVIOUS_KEYS = [\"AI_buffer\", \"AI_sentBuffer\"];\n/*\r\n * Session storage buffer holds a copy of all unsent items in the browser session storage.\r\n */\nvar SessionStorageSendBuffer = /** @class */function (_super) {\n __extends(SessionStorageSendBuffer, _super);\n function SessionStorageSendBuffer(logger, config) {\n var _this = _super.call(this, logger, config) || this;\n var _bufferFullMessageSent = false;\n //Note: should not use config.namePrefix directly, because it will always refers to the latest namePrefix\n var _namePrefix = config === null || config === void 0 ? void 0 : config.namePrefix;\n // TODO: add remove buffer override as well\n var _b = config[_DYN_BUFFER_OVERRIDE /* @min:%2ebufferOverride */] || {\n getItem: utlGetSessionStorage,\n setItem: utlSetSessionStorage\n },\n getItem = _b.getItem,\n setItem = _b.setItem;\n var _maxRetryCnt = config.maxRetryCnt;\n dynamicProto(SessionStorageSendBuffer, _this, function (_self, _base) {\n var bufferItems = _getBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY /* @min:%2eBUFFER_KEY */]);\n var itemsInSentBuffer = _getBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */]);\n var previousItems = _getPreviousEvents();\n var notDeliveredItems = itemsInSentBuffer[_DYN_CONCAT /* @min:%2econcat */](previousItems);\n var buffer = _self._set(bufferItems[_DYN_CONCAT /* @min:%2econcat */](notDeliveredItems));\n // If the buffer has too many items, drop items from the end.\n if (buffer[_DYN_LENGTH /* @min:%2elength */] > SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */]) {\n buffer[_DYN_LENGTH /* @min:%2elength */] = SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */];\n }\n _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */], []);\n _setBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY /* @min:%2eBUFFER_KEY */], buffer);\n _self[_DYN_ENQUEUE /* @min:%2eenqueue */] = function (payload) {\n if (_self[_DYN_COUNT /* @min:%2ecount */]() >= SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */]) {\n // sent internal log only once per page view\n if (!_bufferFullMessageSent) {\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 67 /* _eInternalMessageId.SessionStorageBufferFull */, \"Maximum buffer size reached: \" + _self[_DYN_COUNT /* @min:%2ecount */](), true);\n _bufferFullMessageSent = true;\n }\n return;\n }\n payload.cnt = payload.cnt || 0;\n // max retry is defined, and max retry is reached, do not add the payload to buffer\n if (!isNullOrUndefined(_maxRetryCnt)) {\n if (payload.cnt > _maxRetryCnt) {\n // TODO: add log here on dropping payloads\n return;\n }\n }\n _base[_DYN_ENQUEUE /* @min:%2eenqueue */](payload);\n _setBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY /* @min:%2eBUFFER_KEY */], _self._get());\n };\n _self[_DYN_CLEAR /* @min:%2eclear */] = function () {\n _base[_DYN_CLEAR /* @min:%2eclear */]();\n _setBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY /* @min:%2eBUFFER_KEY */], _self._get());\n _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */], []);\n _bufferFullMessageSent = false;\n };\n _self[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */] = function (payload) {\n _setBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY /* @min:%2eBUFFER_KEY */], _self._set(_removePayloadsFromBuffer(payload, _self._get())));\n var sentElements = _getBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */]);\n if (sentElements instanceof Array && payload instanceof Array) {\n sentElements = sentElements[_DYN_CONCAT /* @min:%2econcat */](payload);\n if (sentElements[_DYN_LENGTH /* @min:%2elength */] > SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */]) {\n // We send telemetry normally. If the SENT_BUFFER is too big we don't add new elements\n // until we receive a response from the backend and the buffer has free space again (see clearSent method)\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 67 /* _eInternalMessageId.SessionStorageBufferFull */, \"Sent buffer reached its maximum size: \" + sentElements[_DYN_LENGTH /* @min:%2elength */], true);\n sentElements[_DYN_LENGTH /* @min:%2elength */] = SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */];\n }\n _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */], sentElements);\n }\n };\n _self[_DYN_CLEAR_SENT /* @min:%2eclearSent */] = function (payload) {\n var sentElements = _getBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */]);\n sentElements = _removePayloadsFromBuffer(payload, sentElements);\n _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */], sentElements);\n };\n _self.createNew = function (newLogger, newConfig, canUseSessionStorage) {\n canUseSessionStorage = !!canUseSessionStorage;\n var unsentItems = _self._get().slice(0);\n var sentItems = _getBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */]).slice(0);\n newLogger = newLogger || logger;\n newConfig = newConfig || {};\n // to make sure that we do not send duplicated payloads when it is switched back to previous one\n _self[_DYN_CLEAR /* @min:%2eclear */]();\n var newBuffer = canUseSessionStorage ? new SessionStorageSendBuffer(newLogger, newConfig) : new ArraySendBuffer(newLogger, newConfig);\n arrForEach(unsentItems, function (payload) {\n newBuffer[_DYN_ENQUEUE /* @min:%2eenqueue */](payload);\n });\n if (canUseSessionStorage) {\n // arr buffer will clear all payloads if markAsSent() is called\n newBuffer[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */](sentItems);\n }\n return newBuffer;\n };\n function _removePayloadsFromBuffer(payloads, buffer) {\n var remaining = [];\n var payloadStr = [];\n arrForEach(payloads, function (payload) {\n payloadStr[_DYN_PUSH /* @min:%2epush */](payload.item);\n });\n arrForEach(buffer, function (value) {\n if (!isFunction(value) && arrIndexOf(payloadStr, value.item) === -1) {\n remaining[_DYN_PUSH /* @min:%2epush */](value);\n }\n });\n return remaining;\n }\n function _getBuffer(key) {\n var prefixedKey = key;\n prefixedKey = _namePrefix ? _namePrefix + \"_\" + prefixedKey : prefixedKey;\n return _getBufferBase(prefixedKey);\n }\n function _getBufferBase(key) {\n try {\n var bufferJson = getItem(logger, key);\n if (bufferJson) {\n var buffer_1 = getJSON().parse(bufferJson);\n if (isString(buffer_1)) {\n // When using some version prototype.js the stringify / parse cycle does not decode array's correctly\n buffer_1 = getJSON().parse(buffer_1);\n }\n if (buffer_1 && isArray(buffer_1)) {\n return buffer_1;\n }\n }\n } catch (e) {\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 42 /* _eInternalMessageId.FailedToRestoreStorageBuffer */, \" storage key: \" + key + \", \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n return [];\n }\n function _setBuffer(key, buffer) {\n var prefixedKey = key;\n try {\n prefixedKey = _namePrefix ? _namePrefix + \"_\" + prefixedKey : prefixedKey;\n var bufferJson = JSON[_DYN_STRINGIFY /* @min:%2estringify */](buffer);\n setItem(logger, prefixedKey, bufferJson);\n } catch (e) {\n // if there was an error, clear the buffer\n // telemetry is stored in the _buffer array so we won't loose any items\n setItem(logger, prefixedKey, JSON[_DYN_STRINGIFY /* @min:%2estringify */]([]));\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 41 /* _eInternalMessageId.FailedToSetStorageBuffer */, \" storage key: \" + prefixedKey + \", \" + getExceptionName(e) + \". Buffer cleared\", {\n exception: dumpObj(e)\n });\n }\n }\n // this removes buffer with prefix+key\n function _getPreviousEvents() {\n var items = [];\n try {\n arrForEach(PREVIOUS_KEYS, function (key) {\n var events = _getItemsFromPreviousKey(key);\n items = items[_DYN_CONCAT /* @min:%2econcat */](events);\n // to make sure that we also transfer items from old prefixed + key buffer\n if (_namePrefix) {\n var prefixedKey = _namePrefix + \"_\" + key;\n var prefixEvents = _getItemsFromPreviousKey(prefixedKey);\n items = items[_DYN_CONCAT /* @min:%2econcat */](prefixEvents);\n }\n });\n return items;\n } catch (e) {\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 41 /* _eInternalMessageId.FailedToSetStorageBuffer */, \"Transfer events from previous buffers: \" + getExceptionName(e) + \". previous Buffer items can not be removed\", {\n exception: dumpObj(e)\n });\n }\n return [];\n }\n // transform string[] to IInternalStorageItem[]\n function _getItemsFromPreviousKey(key) {\n try {\n var items = _getBufferBase(key);\n var transFormedItems_1 = [];\n arrForEach(items, function (item) {\n var internalItem = {\n item: item,\n cnt: 0 // previous events will be default to 0 count\n };\n transFormedItems_1[_DYN_PUSH /* @min:%2epush */](internalItem);\n });\n // remove the session storage if we can add events back\n utlRemoveSessionStorage(logger, key);\n return transFormedItems_1;\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n return [];\n }\n });\n return _this;\n }\n // Removed Stub for SessionStorageSendBuffer.prototype.enqueue.\n // Removed Stub for SessionStorageSendBuffer.prototype.clear.\n // Removed Stub for SessionStorageSendBuffer.prototype.markAsSent.\n // Removed Stub for SessionStorageSendBuffer.prototype.clearSent.\n // Removed Stub for SessionStorageSendBuffer.prototype.createNew.\n var _a;\n _a = SessionStorageSendBuffer;\n SessionStorageSendBuffer.VERSION = \"_1\";\n SessionStorageSendBuffer.BUFFER_KEY = \"AI_buffer\" + _a.VERSION;\n SessionStorageSendBuffer.SENT_BUFFER_KEY = \"AI_sentBuffer\" + _a.VERSION;\n // Maximum number of payloads stored in the buffer. If the buffer is full, new elements will be dropped.\n SessionStorageSendBuffer.MAX_BUFFER_SIZE = 2000;\n return SessionStorageSendBuffer;\n}(BaseSendBuffer);\nexport { SessionStorageSendBuffer };\n","/*\n * Application Insights JavaScript SDK - Channel, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { _throwInternal, getJSON, isArray, isFunction, isObject, objForEachKey } from \"@microsoft/applicationinsights-core-js\";\nimport { _DYN_LENGTH, _DYN_PUSH, _DYN_STRINGIFY, _DYN_TO_STRING } from \"./__DynamicConstants\";\nvar Serializer = /** @class */function () {\n function Serializer(logger) {\n dynamicProto(Serializer, this, function (_self) {\n /**\r\n * Serializes the current object to a JSON string.\r\n */\n _self.serialize = function (input) {\n var output = _serializeObject(input, \"root\");\n try {\n return getJSON()[_DYN_STRINGIFY /* @min:%2estringify */](output);\n } catch (e) {\n // if serialization fails return an empty string\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 48 /* _eInternalMessageId.CannotSerializeObject */, e && isFunction(e[_DYN_TO_STRING /* @min:%2etoString */]) ? e[_DYN_TO_STRING /* @min:%2etoString */]() : \"Error serializing object\", null, true);\n }\n };\n function _serializeObject(source, name) {\n var circularReferenceCheck = \"__aiCircularRefCheck\";\n var output = {};\n if (!source) {\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 48 /* _eInternalMessageId.CannotSerializeObject */, \"cannot serialize object because it is null or undefined\", {\n name: name\n }, true);\n return output;\n }\n if (source[circularReferenceCheck]) {\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 50 /* _eInternalMessageId.CircularReferenceDetected */, \"Circular reference detected while serializing object\", {\n name: name\n }, true);\n return output;\n }\n if (!source.aiDataContract) {\n // special case for measurements/properties/tags\n if (name === \"measurements\") {\n output = _serializeStringMap(source, \"number\", name);\n } else if (name === \"properties\") {\n output = _serializeStringMap(source, \"string\", name);\n } else if (name === \"tags\") {\n output = _serializeStringMap(source, \"string\", name);\n } else if (isArray(source)) {\n output = _serializeArray(source, name);\n } else {\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 49 /* _eInternalMessageId.CannotSerializeObjectNonSerializable */, \"Attempting to serialize an object which does not implement ISerializable\", {\n name: name\n }, true);\n try {\n // verify that the object can be stringified\n getJSON()[_DYN_STRINGIFY /* @min:%2estringify */](source);\n output = source;\n } catch (e) {\n // if serialization fails return an empty string\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 48 /* _eInternalMessageId.CannotSerializeObject */, e && isFunction(e[_DYN_TO_STRING /* @min:%2etoString */]) ? e[_DYN_TO_STRING /* @min:%2etoString */]() : \"Error serializing object\", null, true);\n }\n }\n return output;\n }\n source[circularReferenceCheck] = true;\n objForEachKey(source.aiDataContract, function (field, contract) {\n var isRequired = isFunction(contract) ? contract() & 1 /* FieldType.Required */ : contract & 1 /* FieldType.Required */;\n var isHidden = isFunction(contract) ? contract() & 4 /* FieldType.Hidden */ : contract & 4 /* FieldType.Hidden */;\n var isArray = contract & 2 /* FieldType.Array */;\n var isPresent = source[field] !== undefined;\n var isObj = isObject(source[field]) && source[field] !== null;\n if (isRequired && !isPresent && !isArray) {\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 24 /* _eInternalMessageId.MissingRequiredFieldSpecification */, \"Missing required field specification. The field is required but not present on source\", {\n field: field,\n name: name\n });\n // If not in debug mode, continue and hope the error is permissible\n } else if (!isHidden) {\n // Don't serialize hidden fields\n var value = void 0;\n if (isObj) {\n if (isArray) {\n // special case; recurse on each object in the source array\n value = _serializeArray(source[field], field);\n } else {\n // recurse on the source object in this field\n value = _serializeObject(source[field], field);\n }\n } else {\n // assign the source field to the output even if undefined or required\n value = source[field];\n }\n // only emit this field if the value is defined\n if (value !== undefined) {\n output[field] = value;\n }\n }\n });\n delete source[circularReferenceCheck];\n return output;\n }\n function _serializeArray(sources, name) {\n var output;\n if (!!sources) {\n if (!isArray(sources)) {\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 54 /* _eInternalMessageId.ItemNotInArray */, \"This field was specified as an array in the contract but the item is not an array.\\r\\n\", {\n name: name\n }, true);\n } else {\n output = [];\n for (var i = 0; i < sources[_DYN_LENGTH /* @min:%2elength */]; i++) {\n var source = sources[i];\n var item = _serializeObject(source, name + \"[\" + i + \"]\");\n output[_DYN_PUSH /* @min:%2epush */](item);\n }\n }\n }\n return output;\n }\n function _serializeStringMap(map, expectedType, name) {\n var output;\n if (map) {\n output = {};\n objForEachKey(map, function (field, value) {\n if (expectedType === \"string\") {\n if (value === undefined) {\n output[field] = \"undefined\";\n } else if (value === null) {\n output[field] = \"null\";\n } else if (!value[_DYN_TO_STRING /* @min:%2etoString */]) {\n output[field] = \"invalid field: toString() is not defined.\";\n } else {\n output[field] = value[_DYN_TO_STRING /* @min:%2etoString */]();\n }\n } else if (expectedType === \"number\") {\n if (value === undefined) {\n output[field] = \"undefined\";\n } else if (value === null) {\n output[field] = \"null\";\n } else {\n var num = parseFloat(value);\n output[field] = num;\n }\n } else {\n output[field] = \"invalid field: \" + name + \" is of unknown type.\";\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, output[field], null, true);\n }\n });\n }\n return output;\n }\n });\n }\n // Removed Stub for Serializer.prototype.serialize.\n // This is a workaround for an IE bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n Serializer.__ieDyn = 1;\n return Serializer;\n}();\nexport { Serializer };\n","/*\n * Application Insights JavaScript SDK - Channel, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { _DYN_CONCAT, _DYN_LENGTH } from \"../../__DynamicConstants\";\n// (Magic number) DJB algorithm can't work on shorter strings (results in poor distribution\nvar MIN_INPUT_LENGTH = 8;\nvar HashCodeScoreGenerator = /** @class */function () {\n function HashCodeScoreGenerator() {}\n HashCodeScoreGenerator.prototype.getHashCodeScore = function (key) {\n var score = this.getHashCode(key) / HashCodeScoreGenerator.INT_MAX_VALUE;\n return score * 100;\n };\n HashCodeScoreGenerator.prototype.getHashCode = function (input) {\n if (input === \"\") {\n return 0;\n }\n while (input[_DYN_LENGTH /* @min:%2elength */] < MIN_INPUT_LENGTH) {\n input = input[_DYN_CONCAT /* @min:%2econcat */](input);\n }\n // 5381 is a magic number: http://stackoverflow.com/questions/10696223/reason-for-5381-number-in-djb-hash-function\n var hash = 5381;\n for (var i = 0; i < input[_DYN_LENGTH /* @min:%2elength */]; ++i) {\n hash = (hash << 5) + hash + input.charCodeAt(i);\n // 'hash' is of number type which means 53 bit integer (http://www.ecma-international.org/ecma-262/6.0/#sec-ecmascript-language-types-number-type)\n // 'hash & hash' will keep it 32 bit integer - just to make it clearer what the result is.\n hash = hash & hash;\n }\n return Math.abs(hash);\n };\n // We're using 32 bit math, hence max value is (2^31 - 1)\n HashCodeScoreGenerator.INT_MAX_VALUE = 2147483647;\n return HashCodeScoreGenerator;\n}();\nexport { HashCodeScoreGenerator };\n","/*\n * Application Insights JavaScript SDK - Channel, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { ContextTagKeys } from \"@microsoft/applicationinsights-common\";\nimport { _DYN_GET_HASH_CODE_SCORE, _DYN_TAGS, _DYN_TRACE_ID } from \"../../__DynamicConstants\";\nimport { HashCodeScoreGenerator } from \"./HashCodeScoreGenerator\";\nvar SamplingScoreGenerator = /** @class */function () {\n function SamplingScoreGenerator() {\n var _self = this;\n var hashCodeGenerator = new HashCodeScoreGenerator();\n var keys = new ContextTagKeys();\n _self.getSamplingScore = function (item) {\n var score = 0;\n if (item[_DYN_TAGS /* @min:%2etags */] && item[_DYN_TAGS /* @min:%2etags */][keys.userId]) {\n // search in tags first, then ext\n score = hashCodeGenerator.getHashCodeScore(item[_DYN_TAGS /* @min:%2etags */][keys.userId]);\n } else if (item.ext && item.ext.user && item.ext.user.id) {\n score = hashCodeGenerator[_DYN_GET_HASH_CODE_SCORE /* @min:%2egetHashCodeScore */](item.ext.user.id);\n } else if (item[_DYN_TAGS /* @min:%2etags */] && item[_DYN_TAGS /* @min:%2etags */][keys.operationId]) {\n // search in tags first, then ext\n score = hashCodeGenerator.getHashCodeScore(item[_DYN_TAGS /* @min:%2etags */][keys.operationId]);\n } else if (item.ext && item.ext.telemetryTrace && item.ext.telemetryTrace[_DYN_TRACE_ID /* @min:%2etraceID */]) {\n score = hashCodeGenerator.getHashCodeScore(item.ext.telemetryTrace[_DYN_TRACE_ID /* @min:%2etraceID */]);\n } else {\n // tslint:disable-next-line:insecure-random\n score = Math.random() * 100;\n }\n return score;\n };\n }\n return SamplingScoreGenerator;\n}();\nexport { SamplingScoreGenerator };\n","/*\n * Application Insights JavaScript SDK - Channel, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { Metric } from \"@microsoft/applicationinsights-common\";\nimport { safeGetLogger } from \"@microsoft/applicationinsights-core-js\";\nimport { _DYN_DATA_TYPE, _DYN_SAMPLE_RATE } from \"../__DynamicConstants\";\nimport { SamplingScoreGenerator } from \"./SamplingScoreGenerators/SamplingScoreGenerator\";\nvar Sample = /** @class */function () {\n function Sample(sampleRate, logger) {\n // We're using 32 bit math, hence max value is (2^31 - 1)\n this.INT_MAX_VALUE = 2147483647;\n var _logger = logger || safeGetLogger(null);\n if (sampleRate > 100 || sampleRate < 0) {\n _logger.throwInternal(2 /* eLoggingSeverity.WARNING */, 58 /* _eInternalMessageId.SampleRateOutOfRange */, \"Sampling rate is out of range (0..100). Sampling will be disabled, you may be sending too much data which may affect your AI service level.\", {\n samplingRate: sampleRate\n }, true);\n sampleRate = 100;\n }\n this[_DYN_SAMPLE_RATE /* @min:%2esampleRate */] = sampleRate;\n this.samplingScoreGenerator = new SamplingScoreGenerator();\n }\n /**\r\n * Determines if an envelope is sampled in (i.e. will be sent) or not (i.e. will be dropped).\r\n */\n Sample.prototype.isSampledIn = function (envelope) {\n var samplingPercentage = this[_DYN_SAMPLE_RATE /* @min:%2esampleRate */]; // 0 - 100\n var isSampledIn = false;\n if (samplingPercentage === null || samplingPercentage === undefined || samplingPercentage >= 100) {\n return true;\n } else if (envelope.baseType === Metric[_DYN_DATA_TYPE /* @min:%2edataType */]) {\n // exclude MetricData telemetry from sampling\n return true;\n }\n isSampledIn = this.samplingScoreGenerator.getSamplingScore(envelope) < samplingPercentage;\n return isSampledIn;\n };\n return Sample;\n}();\nexport { Sample };\n","/*\n * Application Insights JavaScript SDK - Channel, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\nvar _a, _b;\nimport { __assignFn as __assign, __extendsFn as __extends } from \"@microsoft/applicationinsights-shims\";\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { BreezeChannelIdentifier, DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH, Event, Exception, Metric, PageView, PageViewPerformance, ProcessLegacy, RemoteDependencyData, RequestHeaders, SampleRate, Trace, createOfflineListener, isInternalApplicationInsightsEndpoint, utlCanUseSessionStorage, utlSetStoragePrefix } from \"@microsoft/applicationinsights-common\";\nimport { ActiveStatus, BaseTelemetryPlugin, SenderPostManager, _throwInternal, _warnToConsole, arrForEach, cfgDfBoolean, cfgDfValidate, createProcessTelemetryContext, createUniqueNamespace, dateNow, dumpObj, formatErrorMessageXdr, formatErrorMessageXhr, getExceptionName, getIEVersion, isArray, isBeaconsSupported, isFetchSupported, isNullOrUndefined, mergeEvtNamespace, objExtend, onConfigChange, parseResponse, prependTransports, runTargetUnload } from \"@microsoft/applicationinsights-core-js\";\nimport { isNumber, isPromiseLike, isString, isTruthy, mathFloor, mathMax, mathMin, objDeepFreeze, objDefine, scheduleTimeout } from \"@nevware21/ts-utils\";\nimport { DependencyEnvelopeCreator, EventEnvelopeCreator, ExceptionEnvelopeCreator, MetricEnvelopeCreator, PageViewEnvelopeCreator, PageViewPerformanceEnvelopeCreator, TraceEnvelopeCreator } from \"./EnvelopeCreator\";\nimport { ArraySendBuffer, SessionStorageSendBuffer } from \"./SendBuffer\";\nimport { Serializer } from \"./Serializer\";\nimport { Sample } from \"./TelemetryProcessors/Sample\";\nimport { _DYN_ALWAYS_USE_XHR_OVERR4, _DYN_BASE_TYPE, _DYN_BUFFER_OVERRIDE, _DYN_CLEAR, _DYN_CLEAR_SENT, _DYN_COUNT, _DYN_CUSTOM_HEADERS, _DYN_DIAG_LOG, _DYN_DISABLE_SEND_BEACON_7, _DYN_EMIT_LINE_DELIMITED_0, _DYN_ENABLE_SESSION_STORA5, _DYN_ENDPOINT_URL, _DYN_ENQUEUE, _DYN_GET_SENDER_INST, _DYN_INITIALIZE, _DYN_INSTRUMENTATION_KEY, _DYN_IS_BEACON_API_DISABL3, _DYN_ITEMS_ACCEPTED, _DYN_ITEMS_RECEIVED, _DYN_LENGTH, _DYN_MARK_AS_SENT, _DYN_MAX_BATCH_SIZE_IN_BY1, _DYN_ONUNLOAD_DISABLE_BEA2, _DYN_ONUNLOAD_DISABLE_FET6, _DYN_PUSH, _DYN_SAMPLE_RATE, _DYN_TAGS, _DYN_TRIGGER_SEND, _DYN__BUFFER, _DYN__ON_ERROR, _DYN__ON_PARTIAL_SUCCESS, _DYN__ON_SUCCESS, _DYN__SENDER } from \"./__DynamicConstants\";\nvar UNDEFINED_VALUE = undefined;\nvar EMPTY_STR = \"\";\nvar FetchSyncRequestSizeLimitBytes = 65000; // approx 64kb (the current Edge, Firefox and Chrome max limit)\nfunction _getResponseText(xhr) {\n try {\n return xhr.responseText;\n } catch (e) {\n // Best effort, as XHR may throw while XDR wont so just ignore\n }\n return null;\n}\nfunction isOverrideFn(httpXHROverride) {\n return httpXHROverride && httpXHROverride.sendPOST;\n}\nvar defaultAppInsightsChannelConfig = objDeepFreeze((_a = {\n // Use the default value (handles empty string in the configuration)\n endpointUrl: cfgDfValidate(isTruthy, DEFAULT_BREEZE_ENDPOINT + DEFAULT_BREEZE_PATH)\n}, _a[_DYN_EMIT_LINE_DELIMITED_0 /* @min:emitLineDelimitedJson */] = cfgDfBoolean(), _a.maxBatchInterval = 15000, _a[_DYN_MAX_BATCH_SIZE_IN_BY1 /* @min:maxBatchSizeInBytes */] = 102400, _a.disableTelemetry = cfgDfBoolean(), _a[_DYN_ENABLE_SESSION_STORA5 /* @min:enableSessionStorageBuffer */] = cfgDfBoolean(true), _a.isRetryDisabled = cfgDfBoolean(), _a[_DYN_IS_BEACON_API_DISABL3 /* @min:isBeaconApiDisabled */] = cfgDfBoolean(true), _a[_DYN_DISABLE_SEND_BEACON_7 /* @min:disableSendBeaconSplit */] = cfgDfBoolean(true), _a.disableXhr = cfgDfBoolean(), _a[_DYN_ONUNLOAD_DISABLE_FET6 /* @min:onunloadDisableFetch */] = cfgDfBoolean(), _a[_DYN_ONUNLOAD_DISABLE_BEA2 /* @min:onunloadDisableBeacon */] = cfgDfBoolean(), _a[_DYN_INSTRUMENTATION_KEY /* @min:instrumentationKey */] = UNDEFINED_VALUE, _a.namePrefix = UNDEFINED_VALUE, _a.samplingPercentage = cfgDfValidate(_chkSampling, 100), _a[_DYN_CUSTOM_HEADERS /* @min:customHeaders */] = UNDEFINED_VALUE, _a.convertUndefined = UNDEFINED_VALUE, _a.eventsLimitInMem = 10000, _a[_DYN_BUFFER_OVERRIDE /* @min:bufferOverride */] = false, _a.httpXHROverride = {\n isVal: isOverrideFn,\n v: UNDEFINED_VALUE\n}, _a[_DYN_ALWAYS_USE_XHR_OVERR4 /* @min:alwaysUseXhrOverride */] = cfgDfBoolean(), _a.transports = UNDEFINED_VALUE, _a.retryCodes = UNDEFINED_VALUE, _a.maxRetryCnt = {\n isVal: isNumber,\n v: 10\n}, _a));\nfunction _chkSampling(value) {\n return !isNaN(value) && value > 0 && value <= 100;\n}\nvar EnvelopeTypeCreator = (_b = {}, _b[Event.dataType] = EventEnvelopeCreator, _b[Trace.dataType] = TraceEnvelopeCreator, _b[PageView.dataType] = PageViewEnvelopeCreator, _b[PageViewPerformance.dataType] = PageViewPerformanceEnvelopeCreator, _b[Exception.dataType] = ExceptionEnvelopeCreator, _b[Metric.dataType] = MetricEnvelopeCreator, _b[RemoteDependencyData.dataType] = DependencyEnvelopeCreator, _b);\nvar Sender = /** @class */function (_super) {\n __extends(Sender, _super);\n function Sender() {\n var _this = _super.call(this) || this;\n _this.priority = 1001;\n _this.identifier = BreezeChannelIdentifier;\n // Don't set the defaults here, set them in the _initDefaults() as this is also called during unload\n var _consecutiveErrors; // How many times in a row a retryable error condition has occurred.\n var _retryAt; // The time to retry at in milliseconds from 1970/01/01 (this makes the timer calculation easy).\n var _lastSend; // The time of the last send operation.\n var _paused; // Flag indicating that the sending should be paused\n var _timeoutHandle; // Handle to the timer for delayed sending of batches of data.\n var _serializer;\n var _stamp_specific_redirects;\n var _headers;\n var _syncFetchPayload = 0; // Keep track of the outstanding sync fetch payload total (as sync fetch has limits)\n var _syncUnloadSender; // The identified sender to use for the synchronous unload stage\n var _offlineListener;\n var _evtNamespace;\n var _endpointUrl;\n var _orgEndpointUrl;\n var _maxBatchSizeInBytes;\n var _beaconSupported;\n var _beaconOnUnloadSupported;\n var _beaconNormalSupported;\n var _customHeaders;\n var _disableTelemetry;\n var _instrumentationKey;\n var _convertUndefined;\n var _isRetryDisabled;\n var _maxBatchInterval;\n var _sessionStorageUsed;\n var _bufferOverrideUsed;\n var _namePrefix;\n var _enableSendPromise;\n var _alwaysUseCustomSend;\n var _disableXhr;\n var _fetchKeepAlive;\n var _xhrSend;\n var _fallbackSend;\n var _disableBeaconSplit;\n var _sendPostMgr;\n var _retryCodes;\n dynamicProto(Sender, _this, function (_self, _base) {\n _initDefaults();\n _self.pause = function () {\n _clearScheduledTimer();\n _paused = true;\n };\n _self.resume = function () {\n if (_paused) {\n _paused = false;\n _retryAt = null;\n // flush if we have exceeded the max-size already\n _checkMaxSize();\n _setupTimer();\n }\n };\n _self.flush = function (isAsync, callBack, sendReason) {\n if (isAsync === void 0) {\n isAsync = true;\n }\n if (!_paused) {\n // Clear the normal schedule timer as we are going to try and flush ASAP\n _clearScheduledTimer();\n try {\n return _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */](isAsync, null, sendReason || 1 /* SendRequestReason.ManualFlush */);\n } catch (e) {\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 22 /* _eInternalMessageId.FlushFailed */, \"flush failed, telemetry will not be collected: \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n }\n };\n _self.onunloadFlush = function () {\n if (!_paused) {\n if (_beaconSupported || _alwaysUseCustomSend) {\n try {\n return _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */](true, _doUnloadSend, 2 /* SendRequestReason.Unload */);\n } catch (e) {\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 20 /* _eInternalMessageId.FailedToSendQueuedTelemetry */, \"failed to flush with beacon sender on page unload, telemetry will not be collected: \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n } else {\n _self.flush(false);\n }\n }\n };\n _self.addHeader = function (name, value) {\n _headers[name] = value;\n };\n _self[_DYN_INITIALIZE /* @min:%2einitialize */] = function (config, core, extensions, pluginChain) {\n if (_self.isInitialized()) {\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 28 /* _eInternalMessageId.SenderNotInitialized */, \"Sender is already initialized\");\n }\n _base[_DYN_INITIALIZE /* @min:%2einitialize */](config, core, extensions, pluginChain);\n var identifier = _self.identifier;\n _serializer = new Serializer(core.logger);\n _consecutiveErrors = 0;\n _retryAt = null;\n _lastSend = 0;\n _self[_DYN__SENDER /* @min:%2e_sender */] = null;\n _stamp_specific_redirects = 0;\n var diagLog = _self[_DYN_DIAG_LOG /* @min:%2ediagLog */]();\n _evtNamespace = mergeEvtNamespace(createUniqueNamespace(\"Sender\"), core.evtNamespace && core.evtNamespace());\n _offlineListener = createOfflineListener(_evtNamespace);\n // This function will be re-called whenever any referenced configuration is changed\n _self._addHook(onConfigChange(config, function (details) {\n var config = details.cfg;\n if (config.storagePrefix) {\n utlSetStoragePrefix(config.storagePrefix);\n }\n var ctx = createProcessTelemetryContext(null, config, core);\n // getExtCfg only finds undefined values from core\n var senderConfig = ctx.getExtCfg(identifier, defaultAppInsightsChannelConfig);\n var curExtUrl = senderConfig[_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */];\n // if it is not inital change (_endpointUrl has value)\n // if current sender endpoint url is not changed directly\n // means ExtCfg is not changed directly\n // then we need to monitor endpoint url changes from core\n if (_endpointUrl && curExtUrl === _endpointUrl) {\n var coreUrl = config[_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */];\n // if core endpoint url is changed\n if (coreUrl && coreUrl !== curExtUrl) {\n // and endpoint promise changes is handled by this as well\n senderConfig[_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */] = coreUrl;\n }\n }\n if (isPromiseLike(senderConfig[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */])) {\n // if it is promise, means the endpoint url is from core.endpointurl\n senderConfig[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */] = config[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */];\n }\n objDefine(_self, \"_senderConfig\", {\n g: function () {\n return senderConfig;\n }\n });\n // Only update the endpoint if the original config !== the current config\n // This is so any redirect endpointUrl is not overwritten\n if (_orgEndpointUrl !== senderConfig[_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */]) {\n if (_orgEndpointUrl) {\n // TODO: add doc to remind users to flush before changing endpoint, otherwise all unsent payload will be sent to new endpoint\n }\n _endpointUrl = _orgEndpointUrl = senderConfig[_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */];\n }\n // or is not string\n if (core.activeStatus() === ActiveStatus.PENDING) {\n // waiting for core promises to be resolved\n // NOTE: if active status is set to pending, stop sending, clear timer here\n _self.pause();\n } else if (core.activeStatus() === ActiveStatus.ACTIVE) {\n // core status changed from pending to other status\n _self.resume();\n }\n if (_customHeaders && _customHeaders !== senderConfig[_DYN_CUSTOM_HEADERS /* @min:%2ecustomHeaders */]) {\n // Removing any previously defined custom headers as they have changed\n arrForEach(_customHeaders, function (customHeader) {\n delete _headers[customHeader.header];\n });\n }\n _maxBatchSizeInBytes = senderConfig[_DYN_MAX_BATCH_SIZE_IN_BY1 /* @min:%2emaxBatchSizeInBytes */];\n _beaconSupported = (senderConfig[_DYN_ONUNLOAD_DISABLE_BEA2 /* @min:%2eonunloadDisableBeacon */] === false || senderConfig[_DYN_IS_BEACON_API_DISABL3 /* @min:%2eisBeaconApiDisabled */] === false) && isBeaconsSupported();\n _beaconOnUnloadSupported = senderConfig[_DYN_ONUNLOAD_DISABLE_BEA2 /* @min:%2eonunloadDisableBeacon */] === false && isBeaconsSupported();\n _beaconNormalSupported = senderConfig[_DYN_IS_BEACON_API_DISABL3 /* @min:%2eisBeaconApiDisabled */] === false && isBeaconsSupported();\n _alwaysUseCustomSend = senderConfig[_DYN_ALWAYS_USE_XHR_OVERR4 /* @min:%2ealwaysUseXhrOverride */];\n _disableXhr = !!senderConfig.disableXhr;\n _retryCodes = senderConfig.retryCodes;\n var bufferOverride = senderConfig[_DYN_BUFFER_OVERRIDE /* @min:%2ebufferOverride */];\n var canUseSessionStorage = !!senderConfig[_DYN_ENABLE_SESSION_STORA5 /* @min:%2eenableSessionStorageBuffer */] && (!!bufferOverride || utlCanUseSessionStorage());\n var namePrefix = senderConfig.namePrefix;\n //Note: emitLineDelimitedJson and eventsLimitInMem is directly accessed via config in senderBuffer\n //Therefore, if canUseSessionStorage is not changed, we do not need to re initialize a new one\n var shouldUpdate = canUseSessionStorage !== _sessionStorageUsed || canUseSessionStorage && _namePrefix !== namePrefix // prefixName is only used in session storage\n || canUseSessionStorage && _bufferOverrideUsed !== bufferOverride;\n if (_self[_DYN__BUFFER /* @min:%2e_buffer */]) {\n // case1 (Pre and Now enableSessionStorageBuffer settings are same)\n // if namePrefix changes, transfer current buffer to new buffer\n // else no action needed\n //case2 (Pre and Now enableSessionStorageBuffer settings are changed)\n // transfer current buffer to new buffer\n if (shouldUpdate) {\n try {\n _self[_DYN__BUFFER /* @min:%2e_buffer */] = _self[_DYN__BUFFER /* @min:%2e_buffer */].createNew(diagLog, senderConfig, canUseSessionStorage);\n } catch (e) {\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 12 /* _eInternalMessageId.FailedAddingTelemetryToBuffer */, \"failed to transfer telemetry to different buffer storage, telemetry will be lost: \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n }\n _checkMaxSize();\n } else {\n _self[_DYN__BUFFER /* @min:%2e_buffer */] = canUseSessionStorage ? new SessionStorageSendBuffer(diagLog, senderConfig) : new ArraySendBuffer(diagLog, senderConfig);\n }\n _namePrefix = namePrefix;\n _sessionStorageUsed = canUseSessionStorage;\n _bufferOverrideUsed = bufferOverride;\n _fetchKeepAlive = !senderConfig[_DYN_ONUNLOAD_DISABLE_FET6 /* @min:%2eonunloadDisableFetch */] && isFetchSupported(true);\n _disableBeaconSplit = !!senderConfig[_DYN_DISABLE_SEND_BEACON_7 /* @min:%2edisableSendBeaconSplit */];\n _self._sample = new Sample(senderConfig.samplingPercentage, diagLog);\n _instrumentationKey = senderConfig[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */];\n if (!isPromiseLike(_instrumentationKey) && !_validateInstrumentationKey(_instrumentationKey, config)) {\n _throwInternal(diagLog, 1 /* eLoggingSeverity.CRITICAL */, 100 /* _eInternalMessageId.InvalidInstrumentationKey */, \"Invalid Instrumentation key \" + _instrumentationKey);\n }\n _customHeaders = senderConfig[_DYN_CUSTOM_HEADERS /* @min:%2ecustomHeaders */];\n if (isString(_endpointUrl) && !isInternalApplicationInsightsEndpoint(_endpointUrl) && _customHeaders && _customHeaders[_DYN_LENGTH /* @min:%2elength */] > 0) {\n arrForEach(_customHeaders, function (customHeader) {\n _this.addHeader(customHeader.header, customHeader.value);\n });\n } else {\n _customHeaders = null;\n }\n _enableSendPromise = senderConfig.enableSendPromise;\n var sendPostConfig = _getSendPostMgrConfig();\n // only init it once\n if (!_sendPostMgr) {\n _sendPostMgr = new SenderPostManager();\n _sendPostMgr[_DYN_INITIALIZE /* @min:%2einitialize */](sendPostConfig, diagLog);\n } else {\n _sendPostMgr.SetConfig(sendPostConfig);\n }\n var customInterface = senderConfig.httpXHROverride;\n var httpInterface = null;\n var syncInterface = null;\n // User requested transport(s) values > Beacon > Fetch > XHR\n // Beacon would be filtered out if user has set disableBeaconApi to true at _getSenderInterface\n var theTransports = prependTransports([3 /* TransportType.Beacon */, 1 /* TransportType.Xhr */, 2 /* TransportType.Fetch */], senderConfig.transports);\n httpInterface = _sendPostMgr && _sendPostMgr[_DYN_GET_SENDER_INST /* @min:%2egetSenderInst */](theTransports, false);\n var xhrInterface = _sendPostMgr && _sendPostMgr.getFallbackInst();\n _xhrSend = function (payload, isAsync) {\n return _doSend(xhrInterface, payload, isAsync);\n };\n _fallbackSend = function (payload, isAsync) {\n return _doSend(xhrInterface, payload, isAsync, false);\n };\n httpInterface = _alwaysUseCustomSend ? customInterface : httpInterface || customInterface || xhrInterface;\n _self[_DYN__SENDER /* @min:%2e_sender */] = function (payload, isAsync) {\n return _doSend(httpInterface, payload, isAsync);\n };\n if (_fetchKeepAlive) {\n // Try and use the fetch with keepalive\n _syncUnloadSender = _fetchKeepAliveSender;\n }\n var syncTransports = prependTransports([3 /* TransportType.Beacon */, 1 /* TransportType.Xhr */], senderConfig.unloadTransports);\n if (!_fetchKeepAlive) {\n // remove fetch from theTransports\n syncTransports = syncTransports.filter(function (transport) {\n return transport !== 2 /* TransportType.Fetch */;\n });\n }\n syncInterface = _sendPostMgr && _sendPostMgr[_DYN_GET_SENDER_INST /* @min:%2egetSenderInst */](syncTransports, true);\n syncInterface = _alwaysUseCustomSend ? customInterface : syncInterface || customInterface;\n if ((_alwaysUseCustomSend || senderConfig.unloadTransports || !_syncUnloadSender) && syncInterface) {\n _syncUnloadSender = function (payload, isAsync) {\n return _doSend(syncInterface, payload, isAsync);\n };\n }\n if (!_syncUnloadSender) {\n _syncUnloadSender = _xhrSend;\n }\n _disableTelemetry = senderConfig.disableTelemetry;\n _convertUndefined = senderConfig.convertUndefined || UNDEFINED_VALUE;\n _isRetryDisabled = senderConfig.isRetryDisabled;\n _maxBatchInterval = senderConfig.maxBatchInterval;\n }));\n };\n _self.processTelemetry = function (telemetryItem, itemCtx) {\n itemCtx = _self._getTelCtx(itemCtx);\n var diagLogger = itemCtx[_DYN_DIAG_LOG /* @min:%2ediagLog */]();\n try {\n var isValidate = _validate(telemetryItem, diagLogger);\n if (!isValidate) {\n return;\n }\n var aiEnvelope = _getEnvelope(telemetryItem, diagLogger);\n if (!aiEnvelope) {\n return;\n }\n // check if the incoming payload is too large, truncate if necessary\n var payload = _serializer.serialize(aiEnvelope);\n // flush if we would exceed the max-size limit by adding this item\n var buffer = _self[_DYN__BUFFER /* @min:%2e_buffer */];\n _checkMaxSize(payload);\n var payloadItem = {\n item: payload,\n cnt: 0 // inital cnt will always be 0\n };\n // enqueue the payload\n buffer[_DYN_ENQUEUE /* @min:%2eenqueue */](payloadItem);\n // ensure an invocation timeout is set\n _setupTimer();\n } catch (e) {\n _throwInternal(diagLogger, 2 /* eLoggingSeverity.WARNING */, 12 /* _eInternalMessageId.FailedAddingTelemetryToBuffer */, \"Failed adding telemetry to the sender's buffer, some telemetry will be lost: \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n // hand off the telemetry item to the next plugin\n _self.processNext(telemetryItem, itemCtx);\n };\n _self.isCompletelyIdle = function () {\n return !_paused && _syncFetchPayload === 0 && _self._buffer[_DYN_COUNT /* @min:%2ecount */]() === 0;\n };\n _self.getOfflineListener = function () {\n return _offlineListener;\n };\n /**\r\n * xhr state changes\r\n */\n _self._xhrReadyStateChange = function (xhr, payload, countOfItemsInPayload) {\n // since version 3.2.0, this function is no-op\n if (_isStringArr(payload)) {\n return;\n }\n return _xhrReadyStateChange(xhr, payload, countOfItemsInPayload);\n };\n /**\r\n * Immediately send buffered data\r\n * @param async - Indicates if the events should be sent asynchronously\r\n * @param forcedSender - Indicates the forcedSender, undefined if not passed\r\n */\n _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */] = function (async, forcedSender, sendReason) {\n if (async === void 0) {\n async = true;\n }\n var result;\n if (!_paused) {\n try {\n var buffer = _self[_DYN__BUFFER /* @min:%2e_buffer */];\n // Send data only if disableTelemetry is false\n if (!_disableTelemetry) {\n if (buffer[_DYN_COUNT /* @min:%2ecount */]() > 0) {\n var payload = buffer.getItems();\n _notifySendRequest(sendReason || 0 /* SendRequestReason.Undefined */, async);\n // invoke send\n if (forcedSender) {\n result = forcedSender.call(_self, payload, async);\n } else {\n result = _self[_DYN__SENDER /* @min:%2e_sender */](payload, async);\n }\n }\n // update lastSend time to enable throttling\n _lastSend = +new Date();\n } else {\n buffer[_DYN_CLEAR /* @min:%2eclear */]();\n }\n _clearScheduledTimer();\n } catch (e) {\n /* Ignore this error for IE under v10 */\n var ieVer = getIEVersion();\n if (!ieVer || ieVer > 9) {\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 40 /* _eInternalMessageId.TransmissionFailed */, \"Telemetry transmission failed, some telemetry will be lost: \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n }\n }\n return result;\n };\n _self.getOfflineSupport = function () {\n return {\n getUrl: function () {\n return _endpointUrl;\n },\n createPayload: _createPayload,\n serialize: _serialize,\n batch: _batch,\n shouldProcess: function (evt) {\n return !!_validate(evt);\n }\n };\n };\n _self._doTeardown = function (unloadCtx, unloadState) {\n _self.onunloadFlush();\n runTargetUnload(_offlineListener, false);\n _initDefaults();\n };\n /**\r\n * error handler\r\n */\n _self[_DYN__ON_ERROR /* @min:%2e_onError */] = function (payload, message, event) {\n // since version 3.1.3, string[] is no-op\n if (_isStringArr(payload)) {\n return;\n }\n return _onError(payload, message, event);\n };\n /**\r\n * partial success handler\r\n */\n _self[_DYN__ON_PARTIAL_SUCCESS /* @min:%2e_onPartialSuccess */] = function (payload, results) {\n // since version 3.1.3, string[] is no-op\n if (_isStringArr(payload)) {\n return;\n }\n return _onPartialSuccess(payload, results);\n };\n /**\r\n * success handler\r\n */\n _self[_DYN__ON_SUCCESS /* @min:%2e_onSuccess */] = function (payload, countOfItemsInPayload) {\n // since version 3.1.3, string[] is no-op\n if (_isStringArr(payload)) {\n return;\n }\n return _onSuccess(payload, countOfItemsInPayload);\n //_self._buffer && _self._buffer.clearSent(payload);\n };\n /**\r\n * xdr state changes\r\n */\n _self._xdrOnLoad = function (xdr, payload) {\n // since version 3.1.3, string[] is no-op\n if (_isStringArr(payload)) {\n return;\n }\n return _xdrOnLoad(xdr, payload);\n };\n function _xdrOnLoad(xdr, payload) {\n var responseText = _getResponseText(xdr);\n if (xdr && (responseText + \"\" === \"200\" || responseText === \"\")) {\n _consecutiveErrors = 0;\n _self[_DYN__ON_SUCCESS /* @min:%2e_onSuccess */](payload, 0);\n } else {\n var results = parseResponse(responseText);\n if (results && results[_DYN_ITEMS_RECEIVED /* @min:%2eitemsReceived */] && results[_DYN_ITEMS_RECEIVED /* @min:%2eitemsReceived */] > results[_DYN_ITEMS_ACCEPTED /* @min:%2eitemsAccepted */] && !_isRetryDisabled) {\n _self[_DYN__ON_PARTIAL_SUCCESS /* @min:%2e_onPartialSuccess */](payload, results);\n } else {\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, formatErrorMessageXdr(xdr));\n }\n }\n }\n function _getSendPostMgrConfig() {\n try {\n var onCompleteFuncs = {\n xdrOnComplete: function (xdr, oncomplete, payload) {\n var data = _getPayloadArr(payload);\n if (!data) {\n return;\n }\n return _xdrOnLoad(xdr, data);\n },\n fetchOnComplete: function (response, onComplete, resValue, payload) {\n var data = _getPayloadArr(payload);\n if (!data) {\n return;\n }\n return _checkResponsStatus(response.status, data, response.url, data[_DYN_LENGTH /* @min:%2elength */], response.statusText, resValue || \"\");\n },\n xhrOnComplete: function (request, oncomplete, payload) {\n var data = _getPayloadArr(payload);\n if (!data) {\n return;\n }\n return _xhrReadyStateChange(request, data, data[_DYN_LENGTH /* @min:%2elength */]);\n },\n beaconOnRetry: function (data, onComplete, canSend) {\n return _onBeaconRetry(data, onComplete, canSend);\n }\n };\n var config = {\n enableSendPromise: _enableSendPromise,\n isOneDs: false,\n disableCredentials: false,\n disableXhr: _disableXhr,\n disableBeacon: !_beaconNormalSupported,\n disableBeaconSync: !_beaconOnUnloadSupported,\n senderOnCompleteCallBack: onCompleteFuncs\n };\n return config;\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n return null;\n }\n /**\r\n * xhr state changes\r\n */\n function _xhrReadyStateChange(xhr, payload, countOfItemsInPayload) {\n if (xhr.readyState === 4) {\n _checkResponsStatus(xhr.status, payload, xhr.responseURL, countOfItemsInPayload, formatErrorMessageXhr(xhr), _getResponseText(xhr) || xhr.response);\n }\n }\n /**\r\n * error handler\r\n */\n function _onError(payload, message, event) {\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 26 /* _eInternalMessageId.OnError */, \"Failed to send telemetry.\", {\n message: message\n });\n _self._buffer && _self._buffer[_DYN_CLEAR_SENT /* @min:%2eclearSent */](payload);\n }\n /**\r\n * partial success handler\r\n */\n function _onPartialSuccess(payload, results) {\n var failed = [];\n var retry = [];\n // Iterate through the reversed array of errors so that splicing doesn't have invalid indexes after the first item.\n var errors = results.errors.reverse();\n for (var _i = 0, errors_1 = errors; _i < errors_1.length; _i++) {\n var error = errors_1[_i];\n var extracted = payload.splice(error.index, 1)[0];\n if (_isRetriable(error.statusCode)) {\n retry[_DYN_PUSH /* @min:%2epush */](extracted);\n } else {\n // All other errors, including: 402 (Monthly quota exceeded) and 439 (Too many requests and refresh cache).\n failed[_DYN_PUSH /* @min:%2epush */](extracted);\n }\n }\n if (payload[_DYN_LENGTH /* @min:%2elength */] > 0) {\n _self[_DYN__ON_SUCCESS /* @min:%2e_onSuccess */](payload, results[_DYN_ITEMS_ACCEPTED /* @min:%2eitemsAccepted */]);\n }\n if (failed[_DYN_LENGTH /* @min:%2elength */] > 0) {\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](failed, formatErrorMessageXhr(null, [\"partial success\", results[_DYN_ITEMS_ACCEPTED /* @min:%2eitemsAccepted */], \"of\", results.itemsReceived].join(\" \")));\n }\n if (retry[_DYN_LENGTH /* @min:%2elength */] > 0) {\n _resendPayload(retry);\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \"Partial success. \" + \"Delivered: \" + payload[_DYN_LENGTH /* @min:%2elength */] + \", Failed: \" + failed[_DYN_LENGTH /* @min:%2elength */] + \". Will retry to send \" + retry[_DYN_LENGTH /* @min:%2elength */] + \" our of \" + results[_DYN_ITEMS_RECEIVED /* @min:%2eitemsReceived */] + \" items\");\n }\n }\n /**\r\n * success handler\r\n */\n function _onSuccess(payload, countOfItemsInPayload) {\n _self._buffer && _self._buffer[_DYN_CLEAR_SENT /* @min:%2eclearSent */](payload);\n }\n function _getPayloadArr(payload) {\n try {\n if (payload) {\n var internalPayload = payload;\n var arr = internalPayload.oriPayload;\n if (arr && arr[_DYN_LENGTH /* @min:%2elength */]) {\n return arr;\n }\n return null;\n }\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n return null;\n }\n function _validate(telemetryItem, diagLogger) {\n if (_disableTelemetry) {\n // Do not send/save data\n return false;\n }\n // validate input\n if (!telemetryItem) {\n diagLogger && _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 7 /* _eInternalMessageId.CannotSendEmptyTelemetry */, \"Cannot send empty telemetry\");\n return false;\n }\n // validate event\n if (telemetryItem.baseData && !telemetryItem[_DYN_BASE_TYPE /* @min:%2ebaseType */]) {\n diagLogger && _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 70 /* _eInternalMessageId.InvalidEvent */, \"Cannot send telemetry without baseData and baseType\");\n return false;\n }\n if (!telemetryItem[_DYN_BASE_TYPE /* @min:%2ebaseType */]) {\n // Default\n telemetryItem[_DYN_BASE_TYPE /* @min:%2ebaseType */] = \"EventData\";\n }\n // ensure a sender was constructed\n if (!_self[_DYN__SENDER /* @min:%2e_sender */]) {\n diagLogger && _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 28 /* _eInternalMessageId.SenderNotInitialized */, \"Sender was not initialized\");\n return false;\n }\n // check if this item should be sampled in, else add sampleRate tag\n if (!_isSampledIn(telemetryItem)) {\n // Item is sampled out, do not send it\n diagLogger && _throwInternal(diagLogger, 2 /* eLoggingSeverity.WARNING */, 33 /* _eInternalMessageId.TelemetrySampledAndNotSent */, \"Telemetry item was sampled out and not sent\", {\n SampleRate: _self._sample[_DYN_SAMPLE_RATE /* @min:%2esampleRate */]\n });\n return false;\n } else {\n telemetryItem[SampleRate] = _self._sample[_DYN_SAMPLE_RATE /* @min:%2esampleRate */];\n }\n return true;\n }\n function _getEnvelope(telemetryItem, diagLogger) {\n // construct an envelope that Application Insights endpoint can understand\n // if ikey of telemetry is provided and not empty, envelope will use this iKey instead of senderConfig iKey\n var defaultEnvelopeIkey = telemetryItem.iKey || _instrumentationKey;\n var aiEnvelope = Sender.constructEnvelope(telemetryItem, defaultEnvelopeIkey, diagLogger, _convertUndefined);\n if (!aiEnvelope) {\n _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 47 /* _eInternalMessageId.CreateEnvelopeError */, \"Unable to create an AppInsights envelope\");\n return;\n }\n var doNotSendItem = false;\n // this is for running in legacy mode, where customer may already have a custom initializer present\n if (telemetryItem[_DYN_TAGS /* @min:%2etags */] && telemetryItem[_DYN_TAGS /* @min:%2etags */][ProcessLegacy]) {\n arrForEach(telemetryItem[_DYN_TAGS /* @min:%2etags */][ProcessLegacy], function (callBack) {\n try {\n if (callBack && callBack(aiEnvelope) === false) {\n doNotSendItem = true;\n _warnToConsole(diagLogger, \"Telemetry processor check returns false\");\n }\n } catch (e) {\n // log error but dont stop executing rest of the telemetry initializers\n // doNotSendItem = true;\n _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 64 /* _eInternalMessageId.TelemetryInitializerFailed */, \"One of telemetry initializers failed, telemetry item will not be sent: \" + getExceptionName(e), {\n exception: dumpObj(e)\n }, true);\n }\n });\n delete telemetryItem[_DYN_TAGS /* @min:%2etags */][ProcessLegacy];\n }\n if (doNotSendItem) {\n return; // do not send, no need to execute next plugin\n }\n return aiEnvelope;\n }\n function _serialize(item) {\n var rlt = EMPTY_STR;\n var diagLogger = _self[_DYN_DIAG_LOG /* @min:%2ediagLog */]();\n try {\n var valid = _validate(item, diagLogger);\n var envelope = null;\n if (valid) {\n envelope = _getEnvelope(item, diagLogger);\n }\n if (envelope) {\n rlt = _serializer.serialize(envelope);\n }\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n return rlt;\n }\n function _batch(arr) {\n var rlt = EMPTY_STR;\n if (arr && arr[_DYN_LENGTH /* @min:%2elength */]) {\n rlt = \"[\" + arr.join(\",\") + \"]\";\n }\n return rlt;\n }\n function _createPayload(data) {\n var headers = _getHeaders();\n return {\n urlString: _endpointUrl,\n data: data,\n headers: headers\n };\n }\n function _isSampledIn(envelope) {\n return _self._sample.isSampledIn(envelope);\n }\n function _getOnComplete(payload, status, headers, response) {\n // ***********************************************************************************************\n //TODO: handle other status codes\n if (status === 200 && payload) {\n _self._onSuccess(payload, payload[_DYN_LENGTH /* @min:%2elength */]);\n } else {\n response && _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, response);\n }\n }\n function _doSend(sendInterface, payload, isAsync, markAsSent) {\n if (markAsSent === void 0) {\n markAsSent = true;\n }\n var onComplete = function (status, headers, response) {\n return _getOnComplete(payload, status, headers, response);\n };\n var payloadData = _getPayload(payload);\n var sendPostFunc = sendInterface && sendInterface.sendPOST;\n if (sendPostFunc && payloadData) {\n // ***********************************************************************************************\n // mark payload as sent at the beginning of calling each send function\n if (markAsSent) {\n _self._buffer[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */](payload);\n }\n return sendPostFunc(payloadData, onComplete, !isAsync);\n }\n return null;\n }\n function _getPayload(payload) {\n if (isArray(payload) && payload[_DYN_LENGTH /* @min:%2elength */] > 0) {\n var batch = _self[_DYN__BUFFER /* @min:%2e_buffer */].batchPayloads(payload);\n var headers = _getHeaders();\n var payloadData = {\n data: batch,\n urlString: _endpointUrl,\n headers: headers,\n disableXhrSync: _disableXhr,\n disableFetchKeepAlive: !_fetchKeepAlive,\n oriPayload: payload\n };\n return payloadData;\n }\n return null;\n }\n function _getHeaders() {\n try {\n var headers = _headers || {};\n if (isInternalApplicationInsightsEndpoint(_endpointUrl)) {\n headers[RequestHeaders[6 /* eRequestHeaders.sdkContextHeader */]] = RequestHeaders[7 /* eRequestHeaders.sdkContextHeaderAppIdRequest */];\n }\n return headers;\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n return null;\n }\n function _checkMaxSize(incomingPayload) {\n var incomingSize = incomingPayload ? incomingPayload[_DYN_LENGTH /* @min:%2elength */] : 0;\n if (_self[_DYN__BUFFER /* @min:%2e_buffer */].size() + incomingSize > _maxBatchSizeInBytes) {\n if (!_offlineListener || _offlineListener.isOnline()) {\n // only trigger send when currently online\n _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */](true, null, 10 /* SendRequestReason.MaxBatchSize */);\n }\n return true;\n }\n return false;\n }\n function _checkResponsStatus(status, payload, responseUrl, countOfItemsInPayload, errorMessage, res) {\n var response = null;\n if (!_self._appId) {\n response = parseResponse(res);\n if (response && response.appId) {\n _self._appId = response.appId;\n }\n }\n if ((status < 200 || status >= 300) && status !== 0) {\n // Update End Point url if permanent redirect or moved permanently\n // Updates the end point url before retry\n if (status === 301 || status === 307 || status === 308) {\n if (!_checkAndUpdateEndPointUrl(responseUrl)) {\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, errorMessage);\n return;\n }\n }\n if (_offlineListener && !_offlineListener.isOnline()) {\n // offline\n // Note: Don't check for status == 0, since adblock gives this code\n if (!_isRetryDisabled) {\n var offlineBackOffMultiplier = 10; // arbritrary number\n _resendPayload(payload, offlineBackOffMultiplier);\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". Offline - Response Code: \".concat(status, \". Offline status: \").concat(!_offlineListener.isOnline(), \". Will retry to send \").concat(payload.length, \" items.\"));\n }\n return;\n }\n if (!_isRetryDisabled && _isRetriable(status)) {\n _resendPayload(payload);\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". \" + \"Response code \" + status + \". Will retry to send \" + payload[_DYN_LENGTH /* @min:%2elength */] + \" items.\");\n } else {\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, errorMessage);\n }\n } else {\n // check if the xhr's responseURL or fetch's response.url is same as endpoint url\n // TODO after 10 redirects force send telemetry with 'redirect=false' as query parameter.\n _checkAndUpdateEndPointUrl(responseUrl);\n if (status === 206) {\n if (!response) {\n response = parseResponse(res);\n }\n if (response && !_isRetryDisabled) {\n _self[_DYN__ON_PARTIAL_SUCCESS /* @min:%2e_onPartialSuccess */](payload, response);\n } else {\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, errorMessage);\n }\n } else {\n _consecutiveErrors = 0;\n _self[_DYN__ON_SUCCESS /* @min:%2e_onSuccess */](payload, countOfItemsInPayload);\n }\n }\n }\n function _checkAndUpdateEndPointUrl(responseUrl) {\n // Maximum stamp specific redirects allowed(uncomment this when breeze is ready with not allowing redirects feature)\n if (_stamp_specific_redirects >= 10) {\n // _self._senderConfig.endpointUrl = () => Sender._getDefaultAppInsightsChannelConfig().endpointUrl()+\"/?redirect=false\";\n // _stamp_specific_redirects = 0;\n return false;\n }\n if (!isNullOrUndefined(responseUrl) && responseUrl !== \"\") {\n if (responseUrl !== _endpointUrl) {\n _endpointUrl = responseUrl;\n ++_stamp_specific_redirects;\n return true;\n }\n }\n return false;\n }\n function _doUnloadSend(payload, isAsync) {\n if (_syncUnloadSender) {\n // We are unloading so always call the sender with sync set to false\n _syncUnloadSender(payload, false);\n } else {\n // Fallback to the previous beacon Sender (which causes a CORB warning on chrome now)\n var beaconInst = _sendPostMgr && _sendPostMgr[_DYN_GET_SENDER_INST /* @min:%2egetSenderInst */]([3 /* TransportType.Beacon */], true);\n return _doSend(beaconInst, payload, isAsync);\n }\n }\n function _onBeaconRetry(payload, onComplete, canSend) {\n var internalPayload = payload;\n var data = internalPayload && internalPayload.oriPayload;\n if (!_disableBeaconSplit) {\n // Failed to send entire payload so try and split data and try to send as much events as possible\n var droppedPayload = [];\n for (var lp = 0; lp < data[_DYN_LENGTH /* @min:%2elength */]; lp++) {\n var thePayload = data[lp];\n var arr = [thePayload];\n var item = _getPayload(arr);\n if (!canSend(item, onComplete)) {\n // Can't send anymore, so split the batch and drop the rest\n droppedPayload[_DYN_PUSH /* @min:%2epush */](thePayload);\n } else {\n _self._onSuccess(arr, arr[_DYN_LENGTH /* @min:%2elength */]);\n }\n }\n if (droppedPayload[_DYN_LENGTH /* @min:%2elength */] > 0) {\n _fallbackSend && _fallbackSend(droppedPayload, true);\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". \" + \"Failed to send telemetry with Beacon API, retried with normal sender.\");\n }\n } else {\n _fallbackSend && _fallbackSend(data, true);\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". \" + \"Failed to send telemetry with Beacon API, retried with normal sender.\");\n }\n }\n function _isStringArr(arr) {\n try {\n if (arr && arr[_DYN_LENGTH /* @min:%2elength */]) {\n return isString(arr[0]);\n }\n } catch (e) {\n //TODO: log, sender use IInternalStorageItem instead of string since 3.1.3\n }\n return null;\n }\n function _fetchKeepAliveSender(payload, isAsync) {\n var transport = null;\n if (isArray(payload)) {\n var payloadSize = payload[_DYN_LENGTH /* @min:%2elength */];\n for (var lp = 0; lp < payload[_DYN_LENGTH /* @min:%2elength */]; lp++) {\n payloadSize += payload[lp].item[_DYN_LENGTH /* @min:%2elength */];\n }\n var syncFetchPayload = _sendPostMgr.getSyncFetchPayload();\n if (syncFetchPayload + payloadSize <= FetchSyncRequestSizeLimitBytes) {\n transport = 2 /* TransportType.Fetch */;\n } else if (isBeaconsSupported()) {\n // Fallback to beacon sender as we at least get told which events can't be scheduled\n transport = 3 /* TransportType.Beacon */;\n } else {\n // Payload is going to be too big so just try and send via XHR\n transport = 1 /* TransportType.Xhr */;\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". \" + \"Failed to send telemetry with Beacon API, retried with xhrSender.\");\n }\n var inst = _sendPostMgr && _sendPostMgr[_DYN_GET_SENDER_INST /* @min:%2egetSenderInst */]([transport], true);\n return _doSend(inst, payload, isAsync);\n }\n return null;\n }\n /**\r\n * Resend payload. Adds payload back to the send buffer and setup a send timer (with exponential backoff).\r\n * @param payload\r\n */\n function _resendPayload(payload, linearFactor) {\n if (linearFactor === void 0) {\n linearFactor = 1;\n }\n if (!payload || payload[_DYN_LENGTH /* @min:%2elength */] === 0) {\n return;\n }\n var buffer = _self[_DYN__BUFFER /* @min:%2e_buffer */];\n buffer[_DYN_CLEAR_SENT /* @min:%2eclearSent */](payload);\n _consecutiveErrors++;\n for (var _i = 0, payload_1 = payload; _i < payload_1.length; _i++) {\n var item = payload_1[_i];\n item.cnt = item.cnt || 0; // to make sure we have cnt for each payload\n item.cnt++; // when resend, increase cnt\n buffer[_DYN_ENQUEUE /* @min:%2eenqueue */](item);\n }\n // setup timer\n _setRetryTime(linearFactor);\n _setupTimer();\n }\n /**\r\n * Calculates the time to wait before retrying in case of an error based on\r\n * http://en.wikipedia.org/wiki/Exponential_backoff\r\n */\n function _setRetryTime(linearFactor) {\n var SlotDelayInSeconds = 10;\n var delayInSeconds;\n if (_consecutiveErrors <= 1) {\n delayInSeconds = SlotDelayInSeconds;\n } else {\n var backOffSlot = (Math.pow(2, _consecutiveErrors) - 1) / 2;\n // tslint:disable-next-line:insecure-random\n var backOffDelay = mathFloor(Math.random() * backOffSlot * SlotDelayInSeconds) + 1;\n backOffDelay = linearFactor * backOffDelay;\n delayInSeconds = mathMax(mathMin(backOffDelay, 3600), SlotDelayInSeconds);\n }\n // TODO: Log the backoff time like the C# version does.\n var retryAfterTimeSpan = dateNow() + delayInSeconds * 1000;\n // TODO: Log the retry at time like the C# version does.\n _retryAt = retryAfterTimeSpan;\n }\n /**\r\n * Sets up the timer which triggers actually sending the data.\r\n */\n function _setupTimer() {\n if (!_timeoutHandle && !_paused) {\n var retryInterval = _retryAt ? mathMax(0, _retryAt - dateNow()) : 0;\n var timerValue = mathMax(_maxBatchInterval, retryInterval);\n _timeoutHandle = scheduleTimeout(function () {\n _timeoutHandle = null;\n _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */](true, null, 1 /* SendRequestReason.NormalSchedule */);\n }, timerValue);\n }\n }\n function _clearScheduledTimer() {\n _timeoutHandle && _timeoutHandle.cancel();\n _timeoutHandle = null;\n _retryAt = null;\n }\n /**\r\n * Checks if the SDK should resend the payload after receiving this status code from the backend.\r\n * @param statusCode\r\n */\n function _isRetriable(statusCode) {\n // retryCodes = [] means should not retry\n if (!isNullOrUndefined(_retryCodes)) {\n return _retryCodes[_DYN_LENGTH /* @min:%2elength */] && _retryCodes.indexOf(statusCode) > -1;\n }\n return statusCode === 401 // Unauthorized\n // Removing as private links can return a 403 which causes excessive retries and session storage usage\n // || statusCode === 403 // Forbidden\n || statusCode === 408 // Timeout\n || statusCode === 429 // Too many requests.\n || statusCode === 500 // Internal server error.\n || statusCode === 502 // Bad Gateway.\n || statusCode === 503 // Service unavailable.\n || statusCode === 504; // Gateway timeout.\n }\n // Using function lookups for backward compatibility as the getNotifyMgr() did not exist until after v2.5.6\n function _getNotifyMgr() {\n var func = \"getNotifyMgr\";\n if (_self.core[func]) {\n return _self.core[func]();\n }\n // using _self.core['_notificationManager'] for backward compatibility\n return _self.core[\"_notificationManager\"];\n }\n function _notifySendRequest(sendRequest, isAsync) {\n var manager = _getNotifyMgr();\n if (manager && manager.eventsSendRequest) {\n try {\n manager.eventsSendRequest(sendRequest, isAsync);\n } catch (e) {\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 74 /* _eInternalMessageId.NotificationException */, \"send request notification failed: \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n }\n }\n /**\r\n * Validate UUID Format\r\n * Specs taken from https://tools.ietf.org/html/rfc4122 and breeze repo\r\n */\n function _validateInstrumentationKey(instrumentationKey, config) {\n var disableValidation = config.disableInstrumentationKeyValidation;\n var disableIKeyValidationFlag = isNullOrUndefined(disableValidation) ? false : disableValidation;\n if (disableIKeyValidationFlag) {\n return true;\n }\n var UUID_Regex = \"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$\";\n var regexp = new RegExp(UUID_Regex);\n return regexp.test(instrumentationKey);\n }\n function _initDefaults() {\n _self[_DYN__SENDER /* @min:%2e_sender */] = null;\n _self[_DYN__BUFFER /* @min:%2e_buffer */] = null;\n _self._appId = null;\n _self._sample = null;\n _headers = {};\n _offlineListener = null;\n _consecutiveErrors = 0;\n _retryAt = null;\n _lastSend = null;\n _paused = false;\n _timeoutHandle = null;\n _serializer = null;\n _stamp_specific_redirects = 0;\n _syncFetchPayload = 0;\n _syncUnloadSender = null;\n _evtNamespace = null;\n _endpointUrl = null;\n _orgEndpointUrl = null;\n _maxBatchSizeInBytes = 0;\n _beaconSupported = false;\n _customHeaders = null;\n _disableTelemetry = false;\n _instrumentationKey = null;\n _convertUndefined = UNDEFINED_VALUE;\n _isRetryDisabled = false;\n _sessionStorageUsed = null;\n _namePrefix = UNDEFINED_VALUE;\n _disableXhr = false;\n _fetchKeepAlive = false;\n _disableBeaconSplit = false;\n _xhrSend = null;\n _fallbackSend = null;\n _sendPostMgr = null;\n objDefine(_self, \"_senderConfig\", {\n g: function () {\n return objExtend({}, defaultAppInsightsChannelConfig);\n }\n });\n }\n });\n return _this;\n }\n Sender.constructEnvelope = function (orig, iKey, logger, convertUndefined) {\n var envelope;\n if (iKey !== orig.iKey && !isNullOrUndefined(iKey)) {\n envelope = __assign(__assign({}, orig), {\n iKey: iKey\n });\n } else {\n envelope = orig;\n }\n var creator = EnvelopeTypeCreator[envelope.baseType] || EventEnvelopeCreator;\n return creator(logger, envelope, convertUndefined);\n };\n // Removed Stub for Sender.prototype.pause.\n // Removed Stub for Sender.prototype.resume.\n // Removed Stub for Sender.prototype.flush.\n // Removed Stub for Sender.prototype.onunloadFlush.\n // Removed Stub for Sender.prototype.initialize.\n // Removed Stub for Sender.prototype.processTelemetry.\n // Removed Stub for Sender.prototype._xhrReadyStateChange.\n // Removed Stub for Sender.prototype.triggerSend.\n // Removed Stub for Sender.prototype._onError.\n // Removed Stub for Sender.prototype._onPartialSuccess.\n // Removed Stub for Sender.prototype._onSuccess.\n // Removed Stub for Sender.prototype._xdrOnLoad.\n // Removed Stub for Sender.prototype.addHeader.\n // Removed Stub for Sender.prototype.isCompletelyIdle.\n // Removed Stub for Sender.prototype.getOfflineSupport.\n // Removed Stub for Sender.prototype.getOfflineListener.\n return Sender;\n}(BaseTelemetryPlugin);\nexport { Sender };\n","/*\n * Application Insights JavaScript SDK - Dependencies Plugin, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n// ###################################################################################################################################################\n// Note: DON'T Export these const from the package as we are still targeting IE/ES5 this will export a mutable variables that someone could change ###\n// ###################################################################################################################################################\n// Generally you should only put values that are used more than 2 times and then only if not already exposed as a constant (such as SdkCoreNames)\n// as when using \"short\" named values from here they will be will be minified smaller than the SdkCoreNames[eSdkCoreNames.xxxx] value.\nexport var STR_DURATION = \"duration\";\nexport var STR_PROPERTIES = \"properties\";\n","/*\n * Application Insights JavaScript SDK - Dependencies Plugin, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n// @skip-file-minify\n// ##############################################################\n// AUTO GENERATED FILE: This file is Auto Generated during build.\n// ##############################################################\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n// Note: DON'T Export these const from the package as we are still targeting ES5 which can result in a mutable variables that someone could change!!!\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nexport var _DYN_REQUEST_URL = \"requestUrl\"; // Count: 11\nexport var _DYN_LENGTH = \"length\"; // Count: 8\nexport var _DYN_TRACE_ID = \"traceID\"; // Count: 8\nexport var _DYN_SPAN_ID = \"spanID\"; // Count: 8\nexport var _DYN_TRACE_FLAGS = \"traceFlags\"; // Count: 11\nexport var _DYN_CONTEXT = \"context\"; // Count: 5\nexport var _DYN_ABORTED = \"aborted\"; // Count: 6\nexport var _DYN__ADD_HOOK = \"_addHook\"; // Count: 4\nexport var _DYN_CORE = \"core\"; // Count: 7\nexport var _DYN_INCLUDE_CORRELATION_0 = \"includeCorrelationHeaders\"; // Count: 4\nexport var _DYN_GET_ABSOLUTE_URL = \"getAbsoluteUrl\"; // Count: 3\nexport var _DYN_HEADERS = \"headers\"; // Count: 7\nexport var _DYN_REQUEST_HEADERS = \"requestHeaders\"; // Count: 13\nexport var _DYN_SET_REQUEST_HEADER = \"setRequestHeader\"; // Count: 3\nexport var _DYN_TRACK_DEPENDENCY_DAT1 = \"trackDependencyDataInternal\"; // Count: 2\nexport var _DYN_START_TIME = \"startTime\"; // Count: 5\nexport var _DYN_TO_LOWER_CASE = \"toLowerCase\"; // Count: 6\nexport var _DYN_ENABLE_REQUEST_HEADE2 = \"enableRequestHeaderTracking\"; // Count: 3\nexport var _DYN_ENABLE_AJAX_ERROR_ST3 = \"enableAjaxErrorStatusText\"; // Count: 2\nexport var _DYN_ENABLE_AJAX_PERF_TRA4 = \"enableAjaxPerfTracking\"; // Count: 2\nexport var _DYN_MAX_AJAX_CALLS_PER_V5 = \"maxAjaxCallsPerView\"; // Count: 2\nexport var _DYN_EXCLUDE_REQUEST_FROM6 = \"excludeRequestFromAutoTrackingPatterns\"; // Count: 2\nexport var _DYN_DISABLE_AJAX_TRACKIN7 = \"disableAjaxTracking\"; // Count: 3\nexport var _DYN_AJAX_PERF_LOOKUP_DEL8 = \"ajaxPerfLookupDelay\"; // Count: 2\nexport var _DYN_DISABLE_FETCH_TRACKI9 = \"disableFetchTracking\"; // Count: 2\nexport var _DYN_ENABLE_RESPONSE_HEAD10 = \"enableResponseHeaderTracking\"; // Count: 2\nexport var _DYN_STATUS = \"status\"; // Count: 11\nexport var _DYN_STATUS_TEXT = \"statusText\"; // Count: 7\nexport var _DYN_HEADER_MAP = \"headerMap\"; // Count: 5\nexport var _DYN_REQUEST_SENT_TIME = \"requestSentTime\"; // Count: 9\nexport var _DYN_GET_TRACE_ID = \"getTraceId\"; // Count: 3\nexport var _DYN_GET_TRACE_FLAGS = \"getTraceFlags\"; // Count: 3\nexport var _DYN_METHOD = \"method\"; // Count: 8\nexport var _DYN_ERROR_STATUS_TEXT = \"errorStatusText\"; // Count: 3\nexport var _DYN_STATE_CHANGE_ATTACHE11 = \"stateChangeAttached\"; // Count: 2\nexport var _DYN_RESPONSE_TEXT = \"responseText\"; // Count: 6\nexport var _DYN_RESPONSE_FINISHED_TI12 = \"responseFinishedTime\"; // Count: 7\nexport var _DYN__CREATE_TRACK_ITEM = \"CreateTrackItem\"; // Count: 3\nexport var _DYN_GET_ALL_RESPONSE_HEA13 = \"getAllResponseHeaders\"; // Count: 2\nexport var _DYN_GET_PART_APROPS = \"getPartAProps\"; // Count: 3\nexport var _DYN_PERF_MARK = \"perfMark\"; // Count: 4\nexport var _DYN_PERF_TIMING = \"perfTiming\"; // Count: 3\nexport var _DYN_AJAX_DIAGNOSTICS_MES14 = \"ajaxDiagnosticsMessage\"; // Count: 3\nexport var _DYN_CORRELATION_CONTEXT = \"correlationContext\"; // Count: 3\nexport var _DYN_AJAX_TOTAL_DURATION = \"ajaxTotalDuration\"; // Count: 3\nexport var _DYN_EVENT_TRACE_CTX = \"eventTraceCtx\"; // Count: 3\n","/*\n * Application Insights JavaScript SDK - Dependencies Plugin, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { Extensions, dataSanitizeUrl, dateTimeUtilsDuration, msToTimeSpan, urlGetAbsoluteUrl, urlGetCompleteUrl } from \"@microsoft/applicationinsights-common\";\nimport { arrForEach, isNullOrUndefined, isNumber, isString, normalizeJsName, objForEachKey, objKeys } from \"@microsoft/applicationinsights-core-js\";\nimport { mathRound } from \"@nevware21/ts-utils\";\nimport { STR_DURATION, STR_PROPERTIES } from \"./InternalConstants\";\nimport { _DYN_ABORTED, _DYN_AJAX_TOTAL_DURATION, _DYN_CORRELATION_CONTEXT, _DYN_ERROR_STATUS_TEXT, _DYN_EVENT_TRACE_CTX, _DYN_GET_ABSOLUTE_URL, _DYN_GET_PART_APROPS, _DYN_GET_TRACE_FLAGS, _DYN_GET_TRACE_ID, _DYN_HEADER_MAP, _DYN_LENGTH, _DYN_METHOD, _DYN_PERF_MARK, _DYN_PERF_TIMING, _DYN_REQUEST_HEADERS, _DYN_REQUEST_SENT_TIME, _DYN_REQUEST_URL, _DYN_RESPONSE_FINISHED_TI12, _DYN_SPAN_ID, _DYN_START_TIME, _DYN_STATE_CHANGE_ATTACHE11, _DYN_STATUS, _DYN_STATUS_TEXT, _DYN_TRACE_FLAGS, _DYN_TRACE_ID, _DYN__CREATE_TRACK_ITEM } from \"./__DynamicConstants\";\n/** @ignore */\nfunction _calcPerfDuration(resourceEntry, start, end) {\n var result = 0;\n var from = resourceEntry[start];\n var to = resourceEntry[end];\n if (from && to) {\n result = dateTimeUtilsDuration(from, to);\n }\n return result;\n}\n/** @ignore */\nfunction _setPerfDuration(props, name, resourceEntry, start, end) {\n var result = 0;\n var value = _calcPerfDuration(resourceEntry, start, end);\n if (value) {\n result = _setPerfValue(props, name, msToTimeSpan(value));\n }\n return result;\n}\n/** @ignore */\nfunction _setPerfValue(props, name, value) {\n var strPerf = \"ajaxPerf\";\n var result = 0;\n if (props && name && value) {\n var perfData = props[strPerf] = props[strPerf] || {};\n perfData[name] = value;\n result = 1;\n }\n return result;\n}\n/** @ignore */\nfunction _populatePerfData(ajaxData, dependency) {\n /*\r\n * https://developer.mozilla.org/en-US/docs/Web/API/Resource_Timing_API/Using_the_Resource_Timing_API\r\n * | -startTime\r\n * | -redirectStart\r\n * | | -redirectEnd\r\n * | | | -fetchStart\r\n * | | | | -domainLookupStart\r\n * | | | | |- domainLookupEnd\r\n * | | | | | | -connectStart\r\n * | | | | | | | -secureConnectionStart\r\n * | | | | | | | | -connectEnd\r\n * | | | | | | | | | -requestStart\r\n * | | | | | | | | | | | -responseStart\r\n * | | | | | | | | | | | | | -responseEnd\r\n * +------------+-+---+----------------+-+--+--------+-+-----------+-+------------+-+\r\n * |--redirect--| |---|--domainLookup--| |--connect--| |--request--| |--response--| |\r\n * |-------------------networkConnect----------------|\r\n * | |---------sentRequest--------|\r\n * |------------------------------------perfTotal-----------------------------------|\r\n */\n var resourceEntry = ajaxData[_DYN_PERF_TIMING /* @min:%2eperfTiming */];\n var props = dependency[STR_PROPERTIES /* @min:%2eproperties */] || {};\n var propsSet = 0;\n var strName = \"name\";\n var strStart = \"Start\";\n var strEnd = \"End\";\n var strDomainLookup = \"domainLookup\";\n var strConnect = \"connect\";\n var strRedirect = \"redirect\";\n var strRequest = \"request\";\n var strResponse = \"response\";\n var strStartTime = \"startTime\";\n var strDomainLookupStart = strDomainLookup + strStart;\n var strDomainLookupEnd = strDomainLookup + strEnd;\n var strConnectStart = strConnect + strStart;\n var strConnectEnd = strConnect + strEnd;\n var strRequestStart = strRequest + strStart;\n var strRequestEnd = strRequest + strEnd;\n var strResponseStart = strResponse + strStart;\n var strResponseEnd = strResponse + strEnd;\n var strRedirectStart = strRedirect + strStart;\n var strRedirectEnd = strRedirect = strEnd;\n var strTransferSize = \"transferSize\";\n var strEncodedBodySize = \"encodedBodySize\";\n var strDecodedBodySize = \"decodedBodySize\";\n var strServerTiming = \"serverTiming\";\n if (resourceEntry) {\n // redirect\n propsSet |= _setPerfDuration(props, strRedirect, resourceEntry, strRedirectStart, strRedirectEnd);\n // domainLookup\n propsSet |= _setPerfDuration(props, strDomainLookup, resourceEntry, strDomainLookupStart, strDomainLookupEnd);\n // connect\n propsSet |= _setPerfDuration(props, strConnect, resourceEntry, strConnectStart, strConnectEnd);\n // request\n propsSet |= _setPerfDuration(props, strRequest, resourceEntry, strRequestStart, strRequestEnd);\n // response\n propsSet |= _setPerfDuration(props, strResponse, resourceEntry, strResponseStart, strResponseEnd);\n // Network connection time\n propsSet |= _setPerfDuration(props, \"networkConnect\", resourceEntry, strStartTime, strConnectEnd);\n // Sent Request\n propsSet |= _setPerfDuration(props, \"sentRequest\", resourceEntry, strRequestStart, strResponseEnd);\n // PerfTotal / Duration\n var duration = resourceEntry[STR_DURATION /* @min:%2eduration */];\n if (!duration) {\n duration = _calcPerfDuration(resourceEntry, strStartTime, strResponseEnd) || 0;\n }\n propsSet |= _setPerfValue(props, STR_DURATION, duration);\n propsSet |= _setPerfValue(props, \"perfTotal\", duration);\n var serverTiming = resourceEntry[strServerTiming];\n if (serverTiming) {\n var server_1 = {};\n arrForEach(serverTiming, function (value, idx) {\n var name = normalizeJsName(value[strName] || \"\" + idx);\n var newValue = server_1[name] || {};\n objForEachKey(value, function (key, val) {\n if (key !== strName && isString(val) || isNumber(val)) {\n if (newValue[key]) {\n val = newValue[key] + \";\" + val;\n }\n if (val || !isString(val)) {\n // Only set the value if it has a value and it's not an empty string\n newValue[key] = val;\n }\n }\n });\n server_1[name] = newValue;\n });\n propsSet |= _setPerfValue(props, strServerTiming, server_1);\n }\n propsSet |= _setPerfValue(props, strTransferSize, resourceEntry[strTransferSize]);\n propsSet |= _setPerfValue(props, strEncodedBodySize, resourceEntry[strEncodedBodySize]);\n propsSet |= _setPerfValue(props, strDecodedBodySize, resourceEntry[strDecodedBodySize]);\n } else {\n if (ajaxData[_DYN_PERF_MARK /* @min:%2eperfMark */]) {\n propsSet |= _setPerfValue(props, \"missing\", ajaxData.perfAttempts);\n }\n }\n if (propsSet) {\n dependency[STR_PROPERTIES /* @min:%2eproperties */] = props;\n }\n}\nvar XHRMonitoringState = /** @class */function () {\n function XHRMonitoringState() {\n var self = this;\n self.openDone = false;\n self.setRequestHeaderDone = false;\n self.sendDone = false;\n self.abortDone = false;\n // True, if onreadyStateChangeCallback function attached to xhr, otherwise false\n self[_DYN_STATE_CHANGE_ATTACHE11 /* @min:%2estateChangeAttached */] = false;\n }\n return XHRMonitoringState;\n}();\nexport { XHRMonitoringState };\nvar ajaxRecord = /** @class */function () {\n function ajaxRecord(traceId, spanId, logger, traceCtx) {\n var self = this;\n var _logger = logger;\n var strResponseText = \"responseText\";\n // Assigning the initial/default values within the constructor to avoid typescript from creating a bunch of\n // this.XXXX = null\n self[_DYN_PERF_MARK /* @min:%2eperfMark */] = null;\n self.completed = false;\n self.requestHeadersSize = null;\n self[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */] = null;\n self.responseReceivingDuration = null;\n self.callbackDuration = null;\n self[_DYN_AJAX_TOTAL_DURATION /* @min:%2eajaxTotalDuration */] = null;\n self[_DYN_ABORTED /* @min:%2eaborted */] = 0;\n self.pageUrl = null;\n self[_DYN_REQUEST_URL /* @min:%2erequestUrl */] = null;\n self.requestSize = 0;\n self[_DYN_METHOD /* @min:%2emethod */] = null;\n self[_DYN_STATUS /* @min:%2estatus */] = null;\n self[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */] = null;\n self.responseStartedTime = null;\n self[_DYN_RESPONSE_FINISHED_TI12 /* @min:%2eresponseFinishedTime */] = null;\n self.callbackFinishedTime = null;\n self.endTime = null;\n self.xhrMonitoringState = new XHRMonitoringState();\n self.clientFailure = 0;\n self[_DYN_TRACE_ID /* @min:%2etraceID */] = traceId;\n self[_DYN_SPAN_ID /* @min:%2espanID */] = spanId;\n self[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = traceCtx === null || traceCtx === void 0 ? void 0 : traceCtx.getTraceFlags();\n if (traceCtx) {\n self[_DYN_EVENT_TRACE_CTX /* @min:%2eeventTraceCtx */] = {\n traceId: traceCtx[_DYN_GET_TRACE_ID /* @min:%2egetTraceId */](),\n spanId: traceCtx.getSpanId(),\n traceFlags: traceCtx[_DYN_GET_TRACE_FLAGS /* @min:%2egetTraceFlags */]()\n };\n } else {\n self[_DYN_EVENT_TRACE_CTX /* @min:%2eeventTraceCtx */] = null;\n }\n dynamicProto(ajaxRecord, self, function (self) {\n self.getAbsoluteUrl = function () {\n return self[_DYN_REQUEST_URL /* @min:%2erequestUrl */] ? urlGetAbsoluteUrl(self[_DYN_REQUEST_URL /* @min:%2erequestUrl */]) : null;\n };\n self.getPathName = function () {\n return self[_DYN_REQUEST_URL /* @min:%2erequestUrl */] ? dataSanitizeUrl(_logger, urlGetCompleteUrl(self[_DYN_METHOD /* @min:%2emethod */], self[_DYN_REQUEST_URL /* @min:%2erequestUrl */])) : null;\n };\n self[_DYN__CREATE_TRACK_ITEM /* @min:%2eCreateTrackItem */] = function (ajaxType, enableRequestHeaderTracking, getResponse) {\n var _a;\n // round to 3 decimal points\n self.ajaxTotalDuration = mathRound(dateTimeUtilsDuration(self.requestSentTime, self.responseFinishedTime) * 1000) / 1000;\n if (self[_DYN_AJAX_TOTAL_DURATION /* @min:%2eajaxTotalDuration */] < 0) {\n return null;\n }\n var dependency = (_a = {\n id: \"|\" + self[_DYN_TRACE_ID /* @min:%2etraceID */] + \".\" + self[_DYN_SPAN_ID /* @min:%2espanID */],\n target: self[_DYN_GET_ABSOLUTE_URL /* @min:%2egetAbsoluteUrl */](),\n name: self.getPathName(),\n type: ajaxType,\n startTime: null,\n duration: self[_DYN_AJAX_TOTAL_DURATION /* @min:%2eajaxTotalDuration */],\n success: +self[_DYN_STATUS /* @min:%2estatus */] >= 200 && +self[_DYN_STATUS /* @min:%2estatus */] < 400,\n responseCode: +self[_DYN_STATUS /* @min:%2estatus */]\n }, _a[STR_PROPERTIES] = {\n HttpMethod: self[_DYN_METHOD /* @min:%2emethod */]\n }, _a);\n var props = dependency[STR_PROPERTIES];\n if (self[_DYN_ABORTED /* @min:%2eaborted */]) {\n props[_DYN_ABORTED /* @min:%2eaborted */] = true;\n }\n if (self[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */]) {\n // Set the correct dependency start time\n dependency[_DYN_START_TIME /* @min:%2estartTime */] = new Date();\n dependency[_DYN_START_TIME /* @min:%2estartTime */].setTime(self[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */]);\n }\n // Add Ajax perf details if available\n _populatePerfData(self, dependency);\n if (enableRequestHeaderTracking) {\n if (objKeys(self.requestHeaders)[_DYN_LENGTH /* @min:%2elength */] > 0) {\n props[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */] = self[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */];\n }\n }\n if (getResponse) {\n var response = getResponse();\n if (response) {\n // enrich dependency target with correlation context from the server\n var correlationContext = response[_DYN_CORRELATION_CONTEXT /* @min:%2ecorrelationContext */];\n if (correlationContext) {\n dependency.correlationContext = /* dependency.target + \" | \" + */correlationContext;\n }\n if (response[_DYN_HEADER_MAP /* @min:%2eheaderMap */]) {\n if (objKeys(response.headerMap)[_DYN_LENGTH /* @min:%2elength */] > 0) {\n props.responseHeaders = response[_DYN_HEADER_MAP /* @min:%2eheaderMap */];\n }\n }\n if (self[_DYN_ERROR_STATUS_TEXT /* @min:%2eerrorStatusText */]) {\n if (self[_DYN_STATUS /* @min:%2estatus */] >= 400) {\n var responseType = response.type;\n if (responseType === \"\" || responseType === \"text\") {\n props.responseText = response.responseText ? response[_DYN_STATUS_TEXT /* @min:%2estatusText */] + \" - \" + response[strResponseText] : response[_DYN_STATUS_TEXT /* @min:%2estatusText */];\n }\n if (responseType === \"json\") {\n props.responseText = response.response ? response[_DYN_STATUS_TEXT /* @min:%2estatusText */] + \" - \" + JSON.stringify(response.response) : response[_DYN_STATUS_TEXT /* @min:%2estatusText */];\n }\n } else if (self[_DYN_STATUS /* @min:%2estatus */] === 0) {\n props.responseText = response[_DYN_STATUS_TEXT /* @min:%2estatusText */] || \"\";\n }\n }\n }\n }\n return dependency;\n };\n self[_DYN_GET_PART_APROPS /* @min:%2egetPartAProps */] = function () {\n var partA = null;\n var traceCtx = self[_DYN_EVENT_TRACE_CTX /* @min:%2eeventTraceCtx */];\n if (traceCtx && (traceCtx.traceId || traceCtx.spanId)) {\n partA = {};\n var traceExt = partA[Extensions.TraceExt] = {\n traceID: traceCtx.traceId,\n parentID: traceCtx.spanId\n };\n if (!isNullOrUndefined(traceCtx[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */])) {\n traceExt[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = traceCtx[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */];\n }\n }\n return partA;\n };\n });\n }\n // Removed Stub for ajaxRecord.prototype.getAbsoluteUrl.\n // Removed Stub for ajaxRecord.prototype.getPathName.\n // Removed Stub for ajaxRecord.prototype.CreateTrackItem.\n // Removed Stub for ajaxRecord.prototype.getPartAProps.\n // This is a workaround for an IE bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n ajaxRecord.__ieDyn = 1;\n return ajaxRecord;\n}();\nexport { ajaxRecord };\n","/*\n * Application Insights JavaScript SDK - Dependencies Plugin, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nvar _a;\nimport { __assignFn as __assign, __extendsFn as __extends } from \"@microsoft/applicationinsights-shims\";\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { DisabledPropertyName, PropertiesPluginIdentifier, RemoteDependencyData, RequestHeaders, correlationIdCanIncludeCorrelationHeader, correlationIdGetCorrelationContext, createDistributedTraceContextFromTrace, createTelemetryItem, createTraceParent, dateTimeUtilsNow, formatTraceParent, isInternalApplicationInsightsEndpoint } from \"@microsoft/applicationinsights-common\";\nimport { BaseTelemetryPlugin, InstrumentFunc, InstrumentProto, _throwInternal, arrForEach, createProcessTelemetryContext, createUniqueNamespace, dumpObj, eventOn, generateW3CId, getExceptionName, getGlobal, getIEVersion, getLocation, getPerformance, isFunction, isNullOrUndefined, isString, isXhrSupported, mergeEvtNamespace, onConfigChange, strPrototype, strTrim } from \"@microsoft/applicationinsights-core-js\";\nimport { isWebWorker, objFreeze, scheduleTimeout, strIndexOf, strSplit, strSubstr } from \"@nevware21/ts-utils\";\nimport { STR_PROPERTIES } from \"./InternalConstants\";\nimport { _DYN_ABORTED, _DYN_AJAX_DIAGNOSTICS_MES14, _DYN_AJAX_PERF_LOOKUP_DEL8, _DYN_CONTEXT, _DYN_CORE, _DYN_CORRELATION_CONTEXT, _DYN_DISABLE_AJAX_TRACKIN7, _DYN_DISABLE_FETCH_TRACKI9, _DYN_ENABLE_AJAX_ERROR_ST3, _DYN_ENABLE_AJAX_PERF_TRA4, _DYN_ENABLE_REQUEST_HEADE2, _DYN_ENABLE_RESPONSE_HEAD10, _DYN_ERROR_STATUS_TEXT, _DYN_EXCLUDE_REQUEST_FROM6, _DYN_GET_ABSOLUTE_URL, _DYN_GET_ALL_RESPONSE_HEA13, _DYN_GET_PART_APROPS, _DYN_GET_TRACE_FLAGS, _DYN_GET_TRACE_ID, _DYN_HEADERS, _DYN_HEADER_MAP, _DYN_INCLUDE_CORRELATION_0, _DYN_LENGTH, _DYN_MAX_AJAX_CALLS_PER_V5, _DYN_METHOD, _DYN_PERF_MARK, _DYN_PERF_TIMING, _DYN_REQUEST_HEADERS, _DYN_REQUEST_SENT_TIME, _DYN_REQUEST_URL, _DYN_RESPONSE_FINISHED_TI12, _DYN_RESPONSE_TEXT, _DYN_SET_REQUEST_HEADER, _DYN_SPAN_ID, _DYN_START_TIME, _DYN_STATE_CHANGE_ATTACHE11, _DYN_STATUS, _DYN_STATUS_TEXT, _DYN_TO_LOWER_CASE, _DYN_TRACE_FLAGS, _DYN_TRACE_ID, _DYN_TRACK_DEPENDENCY_DAT1, _DYN__ADD_HOOK, _DYN__CREATE_TRACK_ITEM } from \"./__DynamicConstants\";\nimport { ajaxRecord } from \"./ajaxRecord\";\n// const AJAX_MONITOR_PREFIX = \"ai.ajxmn.\";\nvar strDiagLog = \"diagLog\";\nvar AJAX_DATA_CONTAINER = \"_ajaxData\";\nvar STR_FETCH = \"fetch\";\nvar ERROR_HEADER = \"Failed to monitor XMLHttpRequest\";\nvar ERROR_PREFIX = \", monitoring data for this ajax call \";\nvar ERROR_POSTFIX = ERROR_PREFIX + \"may be incorrect.\";\nvar ERROR_NOT_SENT = ERROR_PREFIX + \"won't be sent.\";\nvar CORRELATION_HEADER_ERROR = \"Failed to get Request-Context correlation header as it may be not included in the response or not accessible.\";\nvar CUSTOM_REQUEST_CONTEXT_ERROR = \"Failed to add custom defined request context as configured call back may missing a null check.\";\nvar FAILED_TO_CALCULATE_DURATION_ERROR = \"Failed to calculate the duration of the \";\n// Using a global value so that to handle same iKey with multiple app insights instances (mostly for testing)\nvar _markCount = 0;\n/** @Ignore */\nfunction _supportsFetch() {\n var _global = getGlobal();\n if (!_global || isNullOrUndefined(_global.Request) || isNullOrUndefined(_global.Request[strPrototype]) || isNullOrUndefined(_global[STR_FETCH])) {\n return null;\n }\n return _global[STR_FETCH];\n}\n/**\r\n * Determines whether ajax monitoring can be enabled on this document\r\n * @returns True if Ajax monitoring is supported on this page, otherwise false\r\n * @ignore\r\n */\nfunction _supportsAjaxMonitoring(ajaxMonitorInstance, ajaxDataId) {\n var _a;\n var result = false;\n if (isXhrSupported()) {\n var proto = XMLHttpRequest[strPrototype];\n result = !isNullOrUndefined(proto) && !isNullOrUndefined(proto.open) &&\n // eslint-disable-line security/detect-non-literal-fs-filename -- false positive\n !isNullOrUndefined(proto.send) && !isNullOrUndefined(proto.abort);\n }\n var ieVer = getIEVersion();\n if (ieVer && ieVer < 9) {\n result = false;\n }\n if (result) {\n // Disable if the XmlHttpRequest can't be extended or hooked\n try {\n var xhr = new XMLHttpRequest();\n var xhrData = {\n xh: [],\n i: (_a = {}, _a[ajaxDataId] = {}, _a)\n };\n xhr[AJAX_DATA_CONTAINER] = xhrData;\n // Check that we can update the prototype\n var theOpen = XMLHttpRequest[strPrototype].open;\n XMLHttpRequest[strPrototype].open = theOpen;\n } catch (e) {\n // We can't decorate the xhr object so disable monitoring\n result = false;\n _throwInternalCritical(ajaxMonitorInstance, 15 /* _eInternalMessageId.FailedMonitorAjaxOpen */, \"Failed to enable XMLHttpRequest monitoring, extension is not supported\", {\n exception: dumpObj(e)\n });\n }\n }\n return result;\n}\n/**\r\n * Internal helper to fetch the SDK instance tracking data for this XHR request\r\n * @param xhr\r\n * @param ajaxDataId\r\n * @returns\r\n */\nvar _getAjaxData = function (xhr, ajaxDataId) {\n if (xhr && ajaxDataId && xhr[AJAX_DATA_CONTAINER]) {\n return (xhr[AJAX_DATA_CONTAINER].i || {})[ajaxDataId];\n }\n return null;\n};\n/**\r\n * @ignore\r\n * Internal helper to track the singleton shared tracking headers, so we can attempt to not create headers\r\n * that might cause an issue if multiple values are populated.\r\n * @param xhr - The instrumented XHR instance\r\n */\nvar _addSharedXhrHeaders = function (xhr, name, value) {\n if (xhr) {\n var headers = (xhr[AJAX_DATA_CONTAINER] || {}).xh;\n if (headers) {\n headers.push({\n n: name,\n v: value\n });\n }\n }\n};\nvar _isHeaderSet = function (xhr, name) {\n var isPresent = false;\n if (xhr) {\n var headers = (xhr[AJAX_DATA_CONTAINER] || {}).xh;\n if (headers) {\n arrForEach(headers, function (header) {\n if (header.n === name) {\n isPresent = true;\n return -1;\n }\n });\n }\n }\n return isPresent;\n};\n/** @Ignore */\nfunction _getFailedAjaxDiagnosticsMessage(xhr, ajaxDataId) {\n var result = \"\";\n try {\n var ajaxData = _getAjaxData(xhr, ajaxDataId);\n if (ajaxData && ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */]) {\n result += \"(url: '\" + ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */] + \"')\";\n }\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n return result;\n}\n/** @ignore */\nfunction _throwInternalCritical(ajaxMonitorInstance, msgId, message, properties, isUserAct) {\n _throwInternal(ajaxMonitorInstance[strDiagLog](), 1 /* eLoggingSeverity.CRITICAL */, msgId, message, properties, isUserAct);\n}\n/** @ignore */\nfunction _throwInternalWarning(ajaxMonitorInstance, msgId, message, properties, isUserAct) {\n _throwInternal(ajaxMonitorInstance[strDiagLog](), 2 /* eLoggingSeverity.WARNING */, msgId, message, properties, isUserAct);\n}\n/** @Ignore */\nfunction _createErrorCallbackFunc(ajaxMonitorInstance, internalMessage, message) {\n // tslint:disable-next-line\n return function (callDetails) {\n var _a;\n _throwInternalCritical(ajaxMonitorInstance, internalMessage, message, (_a = {}, _a[_DYN_AJAX_DIAGNOSTICS_MES14 /* @min:ajaxDiagnosticsMessage */] = _getFailedAjaxDiagnosticsMessage(callDetails.inst, ajaxMonitorInstance._ajaxDataId), _a.exception = dumpObj(callDetails.err), _a));\n };\n}\nfunction _indexOf(value, match) {\n if (value && match) {\n return strIndexOf(value, match);\n }\n return -1;\n}\nfunction _addHandler(container, id, theFunc) {\n var theHandler = {\n id: id,\n fn: theFunc\n };\n container.push(theHandler);\n return {\n remove: function () {\n arrForEach(container, function (initializer, idx) {\n if (initializer.id === theHandler.id) {\n container.splice(idx, 1);\n return -1;\n }\n });\n }\n };\n}\nfunction _processDependencyContainer(core, container, details, message) {\n var result = true;\n arrForEach(container, function (theFunc, idx) {\n try {\n if (theFunc.fn.call(null, details) === false) {\n result = false;\n }\n } catch (e) {\n _throwInternal(core && core.logger, 1 /* eLoggingSeverity.CRITICAL */, 64 /* _eInternalMessageId.TelemetryInitializerFailed */, \"Dependency \" + message + \" [#\" + idx + \"] failed: \" + getExceptionName(e), {\n exception: dumpObj(e)\n }, true);\n }\n });\n return result;\n}\nfunction _processDependencyListeners(listeners, core, ajaxData, xhr, input, init) {\n var initializersCount = listeners[_DYN_LENGTH /* @min:%2elength */];\n if (initializersCount > 0) {\n var details = {\n core: core,\n xhr: xhr,\n input: input,\n init: init,\n traceId: ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */],\n spanId: ajaxData[_DYN_SPAN_ID /* @min:%2espanID */],\n traceFlags: ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */],\n context: ajaxData[_DYN_CONTEXT /* @min:%2econtext */] || {},\n aborted: !!ajaxData[_DYN_ABORTED /* @min:%2eaborted */]\n };\n _processDependencyContainer(core, listeners, details, \"listener\");\n ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */] = details.traceId;\n ajaxData[_DYN_SPAN_ID /* @min:%2espanID */] = details.spanId;\n ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = details[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */];\n ajaxData[_DYN_CONTEXT /* @min:%2econtext */] = details[_DYN_CONTEXT /* @min:%2econtext */];\n }\n}\nvar BLOB_CORE = \"*.blob.core.\";\nexport var DfltAjaxCorrelationHeaderExDomains = objFreeze([BLOB_CORE + \"windows.net\", BLOB_CORE + \"chinacloudapi.cn\", BLOB_CORE + \"cloudapi.de\", BLOB_CORE + \"usgovcloudapi.net\"]);\nvar _internalExcludeEndpoints = [/https:\\/\\/[^\\/]*(\\.pipe\\.aria|aria\\.pipe|events\\.data|collector\\.azure)\\.[^\\/]+\\/(OneCollector\\/1|Collector\\/3)\\.0/i];\nvar _defaultConfig = objFreeze((_a = {}, _a[_DYN_MAX_AJAX_CALLS_PER_V5 /* @min:maxAjaxCallsPerView */] = 500, _a[_DYN_DISABLE_AJAX_TRACKIN7 /* @min:disableAjaxTracking */] = false, _a[_DYN_DISABLE_FETCH_TRACKI9 /* @min:disableFetchTracking */] = false, _a[_DYN_EXCLUDE_REQUEST_FROM6 /* @min:excludeRequestFromAutoTrackingPatterns */] = undefined, _a.disableCorrelationHeaders = false, _a.distributedTracingMode = 1 /* eDistributedTracingModes.AI_AND_W3C */, _a.correlationHeaderExcludedDomains = DfltAjaxCorrelationHeaderExDomains, _a.correlationHeaderDomains = undefined, _a.correlationHeaderExcludePatterns = undefined, _a.appId = undefined, _a.enableCorsCorrelation = false, _a[_DYN_ENABLE_REQUEST_HEADE2 /* @min:enableRequestHeaderTracking */] = false, _a[_DYN_ENABLE_RESPONSE_HEAD10 /* @min:enableResponseHeaderTracking */] = false, _a[_DYN_ENABLE_AJAX_ERROR_ST3 /* @min:enableAjaxErrorStatusText */] = false, _a[_DYN_ENABLE_AJAX_PERF_TRA4 /* @min:enableAjaxPerfTracking */] = false, _a.maxAjaxPerfLookupAttempts = 3, _a[_DYN_AJAX_PERF_LOOKUP_DEL8 /* @min:ajaxPerfLookupDelay */] = 25, _a.ignoreHeaders = [\"Authorization\", \"X-API-Key\", \"WWW-Authenticate\"], _a.addRequestContext = undefined, _a.addIntEndpoints = true, _a));\nvar AjaxMonitor = /** @class */function (_super) {\n __extends(AjaxMonitor, _super);\n function AjaxMonitor() {\n var _this = _super.call(this) || this;\n _this.identifier = AjaxMonitor.identifier;\n _this.priority = 120;\n var _fetchInitialized; // fetch monitoring initialized\n var _xhrInitialized; // XHR monitoring initialized\n var _currentWindowHost;\n var _extensionConfig;\n var _enableRequestHeaderTracking;\n var _enableAjaxErrorStatusText;\n var _trackAjaxAttempts;\n var _context;\n var _isUsingW3CHeaders;\n var _isUsingAIHeaders;\n var _markPrefix;\n var _enableAjaxPerfTracking;\n var _maxAjaxCallsPerView;\n var _enableResponseHeaderTracking;\n var _disabledUrls;\n var _disableAjaxTracking;\n var _disableFetchTracking;\n var _excludeRequestFromAutoTrackingPatterns;\n var _addRequestContext;\n var _evtNamespace;\n var _ajaxDataId;\n var _dependencyHandlerId;\n var _dependencyListeners;\n var _dependencyInitializers;\n var _ignoreHeaders;\n var _maxAjaxPerfLookupAttempts;\n var _ajaxPerfLookupDelay;\n var _distributedTracingMode;\n var _appId;\n var _polyfillInitialized;\n dynamicProto(AjaxMonitor, _this, function (_self, _base) {\n var _addHook = _base[_DYN__ADD_HOOK /* @min:%2e_addHook */];\n _initDefaults();\n _self.initialize = function (config, core, extensions, pluginChain) {\n if (!_self.isInitialized()) {\n _base.initialize(config, core, extensions, pluginChain);\n _evtNamespace = mergeEvtNamespace(createUniqueNamespace(\"ajax\"), core && core.evtNamespace && core.evtNamespace());\n _populateDefaults(config);\n _instrumentXhr();\n _instrumentFetch();\n _populateContext();\n }\n };\n _self._doTeardown = function () {\n _initDefaults();\n };\n _self.trackDependencyData = function (dependency, properties) {\n _reportDependencyInternal(_dependencyInitializers, _self[_DYN_CORE /* @min:%2ecore */], null, dependency, properties);\n };\n _self[_DYN_INCLUDE_CORRELATION_0 /* @min:%2eincludeCorrelationHeaders */] = function (ajaxData, input, init, xhr) {\n // Test Hook to allow the overriding of the location host\n var currentWindowHost = _self[\"_currentWindowHost\"] || _currentWindowHost;\n _processDependencyListeners(_dependencyListeners, _self[_DYN_CORE /* @min:%2ecore */], ajaxData, xhr, input, init);\n if (input || input === \"\") {\n // Fetch\n if (correlationIdCanIncludeCorrelationHeader(_extensionConfig, ajaxData[_DYN_GET_ABSOLUTE_URL /* @min:%2egetAbsoluteUrl */](), currentWindowHost)) {\n if (!init) {\n init = {};\n }\n // init headers override original request headers\n // so, if they exist use only them, otherwise use request's because they should have been applied in the first place\n // not using original request headers will result in them being lost\n var headers = new Headers(init[_DYN_HEADERS /* @min:%2eheaders */] || (input instanceof Request ? input[_DYN_HEADERS /* @min:%2eheaders */] || {} : {}));\n if (_isUsingAIHeaders) {\n var id = \"|\" + ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */] + \".\" + ajaxData[_DYN_SPAN_ID /* @min:%2espanID */];\n headers.set(RequestHeaders[3 /* eRequestHeaders.requestIdHeader */], id);\n if (_enableRequestHeaderTracking) {\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[3 /* eRequestHeaders.requestIdHeader */]] = id;\n }\n }\n var appId = _appId || _context && _context.appId();\n if (appId) {\n headers.set(RequestHeaders[0 /* eRequestHeaders.requestContextHeader */], RequestHeaders[2 /* eRequestHeaders.requestContextAppIdFormat */] + appId);\n if (_enableRequestHeaderTracking) {\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[0 /* eRequestHeaders.requestContextHeader */]] = RequestHeaders[2 /* eRequestHeaders.requestContextAppIdFormat */] + appId;\n }\n }\n if (_isUsingW3CHeaders) {\n var traceFlags = ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */];\n if (isNullOrUndefined(traceFlags)) {\n traceFlags = 0x01;\n }\n var traceParent = formatTraceParent(createTraceParent(ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */], ajaxData[_DYN_SPAN_ID /* @min:%2espanID */], traceFlags));\n headers.set(RequestHeaders[4 /* eRequestHeaders.traceParentHeader */], traceParent);\n if (_enableRequestHeaderTracking) {\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[4 /* eRequestHeaders.traceParentHeader */]] = traceParent;\n }\n }\n init[_DYN_HEADERS /* @min:%2eheaders */] = headers;\n }\n return init;\n } else if (xhr) {\n // XHR\n if (correlationIdCanIncludeCorrelationHeader(_extensionConfig, ajaxData[_DYN_GET_ABSOLUTE_URL /* @min:%2egetAbsoluteUrl */](), currentWindowHost)) {\n if (_isUsingAIHeaders) {\n if (!_isHeaderSet(xhr, RequestHeaders[3 /* eRequestHeaders.requestIdHeader */])) {\n var id = \"|\" + ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */] + \".\" + ajaxData[_DYN_SPAN_ID /* @min:%2espanID */];\n xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](RequestHeaders[3 /* eRequestHeaders.requestIdHeader */], id);\n if (_enableRequestHeaderTracking) {\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[3 /* eRequestHeaders.requestIdHeader */]] = id;\n }\n } else {\n _throwInternalWarning(_self, 71 /* _eInternalMessageId.FailedMonitorAjaxSetRequestHeader */, \"Unable to set [\" + RequestHeaders[3 /* eRequestHeaders.requestIdHeader */] + \"] as it has already been set by another instance\");\n }\n }\n var appId = _appId || _context && _context.appId();\n if (appId) {\n if (!_isHeaderSet(xhr, RequestHeaders[0 /* eRequestHeaders.requestContextHeader */])) {\n xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](RequestHeaders[0 /* eRequestHeaders.requestContextHeader */], RequestHeaders[2 /* eRequestHeaders.requestContextAppIdFormat */] + appId);\n if (_enableRequestHeaderTracking) {\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[0 /* eRequestHeaders.requestContextHeader */]] = RequestHeaders[2 /* eRequestHeaders.requestContextAppIdFormat */] + appId;\n }\n } else {\n _throwInternalWarning(_self, 71 /* _eInternalMessageId.FailedMonitorAjaxSetRequestHeader */, \"Unable to set [\" + RequestHeaders[0 /* eRequestHeaders.requestContextHeader */] + \"] as it has already been set by another instance\");\n }\n }\n if (_isUsingW3CHeaders) {\n var traceFlags = ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */];\n if (isNullOrUndefined(traceFlags)) {\n traceFlags = 0x01;\n }\n if (!_isHeaderSet(xhr, RequestHeaders[4 /* eRequestHeaders.traceParentHeader */])) {\n var traceParent = formatTraceParent(createTraceParent(ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */], ajaxData[_DYN_SPAN_ID /* @min:%2espanID */], traceFlags));\n xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](RequestHeaders[4 /* eRequestHeaders.traceParentHeader */], traceParent);\n if (_enableRequestHeaderTracking) {\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[4 /* eRequestHeaders.traceParentHeader */]] = traceParent;\n }\n } else {\n _throwInternalWarning(_self, 71 /* _eInternalMessageId.FailedMonitorAjaxSetRequestHeader */, \"Unable to set [\" + RequestHeaders[4 /* eRequestHeaders.traceParentHeader */] + \"] as it has already been set by another instance\");\n }\n }\n }\n return xhr;\n }\n return undefined;\n };\n _self[_DYN_TRACK_DEPENDENCY_DAT1 /* @min:%2etrackDependencyDataInternal */] = function (dependency, properties, systemProperties) {\n if (_maxAjaxCallsPerView === -1 || _trackAjaxAttempts < _maxAjaxCallsPerView) {\n // Hack since expected format in w3c mode is |abc.def.\n // Non-w3c format is |abc.def\n // @todo Remove if better solution is available, e.g. handle in portal\n if ((_distributedTracingMode === 2 /* eDistributedTracingModes.W3C */ || _distributedTracingMode === 1 /* eDistributedTracingModes.AI_AND_W3C */) && typeof dependency.id === \"string\" && dependency.id[dependency.id[_DYN_LENGTH /* @min:%2elength */] - 1] !== \".\") {\n dependency.id += \".\";\n }\n if (isNullOrUndefined(dependency[_DYN_START_TIME /* @min:%2estartTime */])) {\n dependency[_DYN_START_TIME /* @min:%2estartTime */] = new Date();\n }\n var item = createTelemetryItem(dependency, RemoteDependencyData.dataType, RemoteDependencyData.envelopeType, _self[strDiagLog](), properties, systemProperties);\n _self[_DYN_CORE /* @min:%2ecore */].track(item);\n } else if (_trackAjaxAttempts === _maxAjaxCallsPerView) {\n _throwInternalCritical(_self, 55 /* _eInternalMessageId.MaxAjaxPerPVExceeded */, \"Maximum ajax per page view limit reached, ajax monitoring is paused until the next trackPageView(). In order to increase the limit set the maxAjaxCallsPerView configuration parameter.\", true);\n }\n ++_trackAjaxAttempts;\n };\n _self.addDependencyListener = function (dependencyListener) {\n return _addHandler(_dependencyListeners, _dependencyHandlerId++, dependencyListener);\n };\n _self.addDependencyInitializer = function (dependencyInitializer) {\n return _addHandler(_dependencyInitializers, _dependencyHandlerId++, dependencyInitializer);\n };\n function _initDefaults() {\n var location = getLocation();\n _fetchInitialized = false; // fetch monitoring initialized\n _xhrInitialized = false; // XHR monitoring initialized\n _polyfillInitialized = false; // polyfill monitoring initialized\n _currentWindowHost = location && location.host && location.host[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\n _extensionConfig = null;\n _enableRequestHeaderTracking = false;\n _enableAjaxErrorStatusText = false;\n _trackAjaxAttempts = 0;\n _context = null;\n _isUsingW3CHeaders = false;\n _isUsingAIHeaders = false;\n _markPrefix = null;\n _enableAjaxPerfTracking = false;\n _maxAjaxCallsPerView = 0;\n _enableResponseHeaderTracking = false;\n _disabledUrls = {};\n _disableAjaxTracking = false;\n _disableFetchTracking = false;\n _excludeRequestFromAutoTrackingPatterns = null;\n _addRequestContext = null;\n _evtNamespace = null;\n _dependencyHandlerId = 0;\n _dependencyListeners = [];\n _dependencyInitializers = [];\n _ajaxDataId = createUniqueNamespace(\"ajaxData\");\n _self._ajaxDataId = _ajaxDataId;\n _ignoreHeaders = null;\n _maxAjaxPerfLookupAttempts = 1;\n _ajaxPerfLookupDelay = 1;\n _distributedTracingMode = 1 /* eDistributedTracingModes.AI_AND_W3C */;\n _appId = null;\n }\n function _populateDefaults(config) {\n _self[_DYN__ADD_HOOK /* @min:%2e_addHook */](onConfigChange(config, function (details) {\n var config = details.cfg;\n var ctx = createProcessTelemetryContext(null, config, _self[_DYN_CORE /* @min:%2ecore */]);\n _extensionConfig = ctx.getExtCfg(AjaxMonitor.identifier, _defaultConfig);\n _distributedTracingMode = _extensionConfig.distributedTracingMode;\n _enableRequestHeaderTracking = _extensionConfig[_DYN_ENABLE_REQUEST_HEADE2 /* @min:%2eenableRequestHeaderTracking */];\n _enableAjaxErrorStatusText = _extensionConfig[_DYN_ENABLE_AJAX_ERROR_ST3 /* @min:%2eenableAjaxErrorStatusText */];\n _enableAjaxPerfTracking = _extensionConfig[_DYN_ENABLE_AJAX_PERF_TRA4 /* @min:%2eenableAjaxPerfTracking */];\n _maxAjaxCallsPerView = _extensionConfig[_DYN_MAX_AJAX_CALLS_PER_V5 /* @min:%2emaxAjaxCallsPerView */];\n _excludeRequestFromAutoTrackingPatterns = [].concat(_extensionConfig[_DYN_EXCLUDE_REQUEST_FROM6 /* @min:%2eexcludeRequestFromAutoTrackingPatterns */] || [], _extensionConfig.addIntEndpoints !== false ? _internalExcludeEndpoints : []);\n _addRequestContext = _extensionConfig.addRequestContext;\n _isUsingAIHeaders = _distributedTracingMode === 0 /* eDistributedTracingModes.AI */ || _distributedTracingMode === 1 /* eDistributedTracingModes.AI_AND_W3C */;\n _isUsingW3CHeaders = _distributedTracingMode === 1 /* eDistributedTracingModes.AI_AND_W3C */ || _distributedTracingMode === 2 /* eDistributedTracingModes.W3C */;\n if (_enableAjaxPerfTracking) {\n _markPrefix = _ajaxDataId;\n }\n _disableAjaxTracking = !!_extensionConfig[_DYN_DISABLE_AJAX_TRACKIN7 /* @min:%2edisableAjaxTracking */];\n _maxAjaxPerfLookupAttempts = _extensionConfig.maxAjaxPerfLookupAttempts;\n _ajaxPerfLookupDelay = _extensionConfig[_DYN_AJAX_PERF_LOOKUP_DEL8 /* @min:%2eajaxPerfLookupDelay */];\n _ignoreHeaders = _extensionConfig.ignoreHeaders;\n _appId = _extensionConfig.appId;\n }));\n }\n function _populateContext() {\n var propExt = _self[_DYN_CORE /* @min:%2ecore */].getPlugin(PropertiesPluginIdentifier);\n if (propExt) {\n _context = propExt.plugin[_DYN_CONTEXT /* @min:%2econtext */]; // we could move IPropertiesPlugin to common as well\n }\n }\n // discard the header if it's defined as ignoreHeaders in ICorrelationConfig\n function _canIncludeHeaders(header) {\n var rlt = true;\n if (header || _ignoreHeaders) {\n arrForEach(_ignoreHeaders, function (key) {\n if (key[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]() === header[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]()) {\n rlt = false;\n return -1;\n }\n });\n }\n return rlt;\n }\n // Fetch Stuff\n function _instrumentFetch() {\n var fetch = _supportsFetch();\n if (!fetch) {\n return;\n }\n var global = getGlobal();\n var isPolyfill = fetch.polyfill;\n _self[_DYN__ADD_HOOK /* @min:%2e_addHook */](onConfigChange(_extensionConfig, function () {\n _disableFetchTracking = !!_extensionConfig[_DYN_DISABLE_FETCH_TRACKI9 /* @min:%2edisableFetchTracking */];\n _enableResponseHeaderTracking = _extensionConfig[_DYN_ENABLE_RESPONSE_HEAD10 /* @min:%2eenableResponseHeaderTracking */];\n if (!_disableFetchTracking && !_fetchInitialized) {\n _addHook(InstrumentFunc(global, STR_FETCH, {\n ns: _evtNamespace,\n // Add request hook\n req: function (callDetails, input, init) {\n var fetchData;\n if (!_disableFetchTracking && _fetchInitialized && !_isDisabledRequest(null, input, init) &&\n // If we have a polyfil and XHR instrumented then let XHR report otherwise we get duplicates\n !(isPolyfill && _xhrInitialized)) {\n var ctx = callDetails.ctx();\n fetchData = _createFetchRecord(input, init);\n var newInit = _self[_DYN_INCLUDE_CORRELATION_0 /* @min:%2eincludeCorrelationHeaders */](fetchData, input, init);\n if (newInit !== init) {\n callDetails.set(1, newInit);\n }\n ctx.data = fetchData;\n }\n },\n rsp: function (callDetails, input) {\n if (!_disableFetchTracking) {\n var fetchData_1 = callDetails.ctx().data;\n if (fetchData_1) {\n // Replace the result with the new promise from this code\n callDetails.rslt = callDetails.rslt.then(function (response) {\n _reportFetchMetrics(callDetails, (response || {})[_DYN_STATUS /* @min:%2estatus */], input, response, fetchData_1, function () {\n var _a;\n var ajaxResponse = (_a = {\n statusText: (response || {})[_DYN_STATUS_TEXT /* @min:%2estatusText */],\n headerMap: null\n }, _a[_DYN_CORRELATION_CONTEXT /* @min:correlationContext */] = _getFetchCorrelationContext(response), _a);\n if (_enableResponseHeaderTracking && response) {\n var responseHeaderMap_1 = {};\n response.headers.forEach(function (value, name) {\n if (_canIncludeHeaders(name)) {\n responseHeaderMap_1[name] = value;\n }\n });\n ajaxResponse[_DYN_HEADER_MAP /* @min:%2eheaderMap */] = responseHeaderMap_1;\n }\n return ajaxResponse;\n });\n return response;\n }).catch(function (reason) {\n _reportFetchMetrics(callDetails, 0, input, null, fetchData_1, null, {\n error: reason.message || dumpObj(reason)\n });\n throw reason;\n });\n }\n }\n },\n // Create an error callback to report any hook errors\n hkErr: _createErrorCallbackFunc(_self, 15 /* _eInternalMessageId.FailedMonitorAjaxOpen */, \"Failed to monitor Window.fetch\" + ERROR_POSTFIX)\n }, true, isWebWorker()));\n _fetchInitialized = true;\n } else if (isPolyfill && !_polyfillInitialized) {\n // If fetch is a polyfill we need to capture the request to ensure that we correctly track\n // disabled request URLS (i.e. internal urls) to ensure we don't end up in a constant loop\n // of reporting ourselves, for example React Native uses a polyfill for fetch\n // Note: Polyfill implementations that don't support the \"polyfill\" tag are not supported\n // the workaround is to add a polyfill property to your fetch implementation before initializing\n // App Insights\n _addHook(InstrumentFunc(global, STR_FETCH, {\n ns: _evtNamespace,\n req: function (callDetails, input, init) {\n // Just call so that we record any disabled URL\n _isDisabledRequest(null, input, init);\n }\n }));\n _polyfillInitialized = true;\n }\n }));\n if (isPolyfill) {\n // retag the instrumented fetch with the same polyfill settings this is mostly for testing\n // But also supports multiple App Insights usages\n global[STR_FETCH].polyfill = isPolyfill;\n }\n }\n function _hookProto(target, funcName, callbacks) {\n _addHook(InstrumentProto(target, funcName, callbacks));\n }\n function _instrumentXhr() {\n if (!_supportsAjaxMonitoring(_self, _ajaxDataId)) {\n return;\n }\n _self[_DYN__ADD_HOOK /* @min:%2e_addHook */](onConfigChange(_extensionConfig, function () {\n _disableAjaxTracking = !!_extensionConfig[_DYN_DISABLE_AJAX_TRACKIN7 /* @min:%2edisableAjaxTracking */];\n _enableRequestHeaderTracking = _extensionConfig[_DYN_ENABLE_REQUEST_HEADE2 /* @min:%2eenableRequestHeaderTracking */];\n if (!_disableAjaxTracking && !_xhrInitialized) {\n // Instrument open\n _hookProto(XMLHttpRequest, \"open\", {\n ns: _evtNamespace,\n req: function (callDetails, method, url, async) {\n if (!_disableAjaxTracking) {\n var xhr = callDetails.inst;\n var ajaxData = _getAjaxData(xhr, _ajaxDataId);\n if (!_isDisabledRequest(xhr, url) && _isMonitoredXhrInstance(xhr, ajaxData, true)) {\n if (!ajaxData || !ajaxData.xhrMonitoringState.openDone) {\n // Only create a single ajaxData (even when multiple AI instances are running)\n ajaxData = _openHandler(xhr, method, url, async);\n }\n // always attach to the on ready state change (required for handling multiple instances)\n _attachToOnReadyStateChange(xhr, ajaxData);\n }\n }\n },\n hkErr: _createErrorCallbackFunc(_self, 15 /* _eInternalMessageId.FailedMonitorAjaxOpen */, ERROR_HEADER + \".open\" + ERROR_POSTFIX)\n });\n // Instrument send\n _hookProto(XMLHttpRequest, \"send\", {\n ns: _evtNamespace,\n req: function (callDetails, context) {\n if (!_disableAjaxTracking) {\n var xhr = callDetails.inst;\n var ajaxData = _getAjaxData(xhr, _ajaxDataId);\n if (_isMonitoredXhrInstance(xhr, ajaxData) && !ajaxData.xhrMonitoringState.sendDone) {\n _createMarkId(\"xhr\", ajaxData);\n ajaxData[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */] = dateTimeUtilsNow();\n _self[_DYN_INCLUDE_CORRELATION_0 /* @min:%2eincludeCorrelationHeaders */](ajaxData, undefined, undefined, xhr);\n ajaxData.xhrMonitoringState.sendDone = true;\n }\n }\n },\n hkErr: _createErrorCallbackFunc(_self, 17 /* _eInternalMessageId.FailedMonitorAjaxSend */, ERROR_HEADER + ERROR_POSTFIX)\n });\n // Instrument abort\n _hookProto(XMLHttpRequest, \"abort\", {\n ns: _evtNamespace,\n req: function (callDetails) {\n if (!_disableAjaxTracking) {\n var xhr = callDetails.inst;\n var ajaxData = _getAjaxData(xhr, _ajaxDataId);\n if (_isMonitoredXhrInstance(xhr, ajaxData) && !ajaxData.xhrMonitoringState.abortDone) {\n ajaxData[_DYN_ABORTED /* @min:%2eaborted */] = 1;\n ajaxData.xhrMonitoringState.abortDone = true;\n }\n }\n },\n hkErr: _createErrorCallbackFunc(_self, 13 /* _eInternalMessageId.FailedMonitorAjaxAbort */, ERROR_HEADER + \".abort\" + ERROR_POSTFIX)\n });\n // Instrument setRequestHeader\n _hookProto(XMLHttpRequest, \"setRequestHeader\", {\n ns: _evtNamespace,\n req: function (callDetails, header, value) {\n if (!_disableAjaxTracking) {\n var xhr = callDetails.inst;\n var ajaxData = _getAjaxData(xhr, _ajaxDataId);\n if (ajaxData && _isMonitoredXhrInstance(xhr, ajaxData)) {\n _addSharedXhrHeaders(xhr, header, value);\n if (_enableRequestHeaderTracking && _canIncludeHeaders(header)) {\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][header] = value;\n }\n }\n }\n },\n hkErr: _createErrorCallbackFunc(_self, 71 /* _eInternalMessageId.FailedMonitorAjaxSetRequestHeader */, ERROR_HEADER + \".setRequestHeader\" + ERROR_POSTFIX)\n });\n _xhrInitialized = true;\n }\n }));\n }\n function _isDisabledRequest(xhr, request, init) {\n var isDisabled = false;\n var theUrl = ((!isString(request) ? (request || {}).url || \"\" : request) || \"\")[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\n // check excludeRequestFromAutoTrackingPatterns before stripping off any query string\n arrForEach(_excludeRequestFromAutoTrackingPatterns, function (regex) {\n var theRegex = regex;\n if (isString(regex)) {\n theRegex = new RegExp(regex);\n }\n if (!isDisabled) {\n isDisabled = theRegex.test(theUrl);\n }\n });\n // if request url matches with exclude regex pattern, return true and no need to check for headers\n if (isDisabled) {\n return isDisabled;\n }\n var idx = _indexOf(theUrl, \"?\");\n var idx2 = _indexOf(theUrl, \"#\");\n if (idx === -1 || idx2 !== -1 && idx2 < idx) {\n idx = idx2;\n }\n if (idx !== -1) {\n // Strip off any Query string\n theUrl = theUrl.substring(0, idx);\n }\n // check that this instance is not not used by ajax call performed inside client side monitoring to send data to collector\n if (!isNullOrUndefined(xhr)) {\n // Look on the XMLHttpRequest of the URL string value\n isDisabled = xhr[DisabledPropertyName] === true || theUrl[DisabledPropertyName] === true;\n } else if (!isNullOrUndefined(request)) {\n // fetch\n // Look for DisabledPropertyName in either Request or RequestInit\n isDisabled = (typeof request === \"object\" ? request[DisabledPropertyName] === true : false) || (init ? init[DisabledPropertyName] === true : false);\n }\n // Also add extra check just in case the XHR or fetch objects where not decorated with the DisableProperty due to sealing or freezing\n if (!isDisabled && theUrl && isInternalApplicationInsightsEndpoint(theUrl)) {\n isDisabled = true;\n }\n if (isDisabled) {\n // Add the disabled url if not present\n if (!_disabledUrls[theUrl]) {\n _disabledUrls[theUrl] = 1;\n }\n } else {\n // Check to see if the url is listed as disabled\n if (_disabledUrls[theUrl]) {\n isDisabled = true;\n }\n }\n return isDisabled;\n }\n /// Verifies that particular instance of XMLHttpRequest needs to be monitored\n /// Optional parameter. True if ajaxData must be excluded from verification\n /// True if instance needs to be monitored, otherwise false\n function _isMonitoredXhrInstance(xhr, ajaxData, excludeAjaxDataValidation) {\n var ajaxValidation = true;\n var initialized = _xhrInitialized;\n if (!isNullOrUndefined(xhr)) {\n ajaxValidation = excludeAjaxDataValidation === true || !isNullOrUndefined(ajaxData);\n }\n // checking to see that all interested functions on xhr were instrumented\n return initialized\n // checking on ajaxData to see that it was not removed in user code\n && ajaxValidation;\n }\n function _getDistributedTraceCtx() {\n var distributedTraceCtx = null;\n if (_self[_DYN_CORE /* @min:%2ecore */] && _self[_DYN_CORE /* @min:%2ecore */].getTraceCtx) {\n distributedTraceCtx = _self[_DYN_CORE /* @min:%2ecore */].getTraceCtx(false);\n }\n // Fall back\n if (!distributedTraceCtx && _context && _context.telemetryTrace) {\n distributedTraceCtx = createDistributedTraceContextFromTrace(_context.telemetryTrace);\n }\n return distributedTraceCtx;\n }\n function _openHandler(xhr, method, url, async) {\n var _a;\n var distributedTraceCtx = _getDistributedTraceCtx();\n var traceID = distributedTraceCtx && distributedTraceCtx[_DYN_GET_TRACE_ID /* @min:%2egetTraceId */]() || generateW3CId();\n var spanID = strSubstr(generateW3CId(), 0, 16);\n var xhrRequestData = xhr[AJAX_DATA_CONTAINER] = xhr[AJAX_DATA_CONTAINER] || {\n xh: [],\n i: {}\n };\n var ajaxDataCntr = xhrRequestData.i = xhrRequestData.i || {};\n var ajaxData = ajaxDataCntr[_ajaxDataId] = ajaxDataCntr[_ajaxDataId] || new ajaxRecord(traceID, spanID, _self[strDiagLog](), (_a = _self.core) === null || _a === void 0 ? void 0 : _a.getTraceCtx());\n ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = distributedTraceCtx && distributedTraceCtx[_DYN_GET_TRACE_FLAGS /* @min:%2egetTraceFlags */]();\n ajaxData[_DYN_METHOD /* @min:%2emethod */] = method;\n ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */] = url;\n ajaxData.xhrMonitoringState.openDone = true;\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */] = {};\n ajaxData.async = async;\n ajaxData[_DYN_ERROR_STATUS_TEXT /* @min:%2eerrorStatusText */] = _enableAjaxErrorStatusText;\n return ajaxData;\n }\n function _attachToOnReadyStateChange(xhr, ajaxData) {\n ajaxData.xhrMonitoringState[_DYN_STATE_CHANGE_ATTACHE11 /* @min:%2estateChangeAttached */] = eventOn(xhr, \"readystatechange\", function () {\n var _a;\n try {\n if (xhr && xhr.readyState === 4 && _isMonitoredXhrInstance(xhr, ajaxData)) {\n _onAjaxComplete(xhr);\n }\n } catch (e) {\n var exceptionText = dumpObj(e);\n // ignore messages with c00c023f, as this a known IE9 XHR abort issue\n if (!exceptionText || _indexOf(exceptionText[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */](), \"c00c023f\") === -1) {\n _throwInternalCritical(_self, 16 /* _eInternalMessageId.FailedMonitorAjaxRSC */, ERROR_HEADER + \" 'readystatechange' event handler\" + ERROR_POSTFIX, (_a = {}, _a[_DYN_AJAX_DIAGNOSTICS_MES14 /* @min:ajaxDiagnosticsMessage */] = _getFailedAjaxDiagnosticsMessage(xhr, _ajaxDataId), _a.exception = exceptionText, _a));\n }\n }\n }, _evtNamespace);\n }\n function _getResponseText(xhr) {\n try {\n var responseType = xhr.responseType;\n if (responseType === \"\" || responseType === \"text\") {\n // As per the specification responseText is only valid if the type is an empty string or \"text\"\n return xhr[_DYN_RESPONSE_TEXT /* @min:%2eresponseText */];\n }\n } catch (e) {\n // This shouldn't happen because of the above check -- but just in case, so just ignore\n }\n return null;\n }\n function _onAjaxComplete(xhr) {\n var ajaxData = _getAjaxData(xhr, _ajaxDataId);\n ajaxData[_DYN_RESPONSE_FINISHED_TI12 /* @min:%2eresponseFinishedTime */] = dateTimeUtilsNow();\n ajaxData[_DYN_STATUS /* @min:%2estatus */] = xhr[_DYN_STATUS /* @min:%2estatus */];\n function _reportXhrError(e, failedProps) {\n var errorProps = failedProps || {};\n errorProps[\"ajaxDiagnosticsMessage\"] = _getFailedAjaxDiagnosticsMessage(xhr, _ajaxDataId);\n if (e) {\n errorProps[\"exception\"] = dumpObj(e);\n }\n _throwInternalWarning(_self, 14 /* _eInternalMessageId.FailedMonitorAjaxDur */, FAILED_TO_CALCULATE_DURATION_ERROR + \"ajax call\" + ERROR_NOT_SENT, errorProps);\n }\n _findPerfResourceEntry(\"xmlhttprequest\", ajaxData, function () {\n try {\n var dependency = ajaxData[_DYN__CREATE_TRACK_ITEM /* @min:%2eCreateTrackItem */](\"Ajax\", _enableRequestHeaderTracking, function () {\n var _a;\n var ajaxResponse = (_a = {\n statusText: xhr[_DYN_STATUS_TEXT /* @min:%2estatusText */],\n headerMap: null\n }, _a[_DYN_CORRELATION_CONTEXT /* @min:correlationContext */] = _getAjaxCorrelationContext(xhr), _a.type = xhr.responseType, _a[_DYN_RESPONSE_TEXT /* @min:responseText */] = _getResponseText(xhr), _a.response = xhr.response, _a);\n if (_enableResponseHeaderTracking) {\n var headers = xhr[_DYN_GET_ALL_RESPONSE_HEA13 /* @min:%2egetAllResponseHeaders */]();\n if (headers) {\n // xhr.getAllResponseHeaders() method returns all the response headers, separated by CRLF, as a string or null\n // the regex converts the header string into an array of individual headers\n var arr = strTrim(headers).split(/[\\r\\n]+/);\n var responseHeaderMap_2 = {};\n arrForEach(arr, function (line) {\n var parts = line.split(\": \");\n var header = parts.shift();\n var value = parts.join(\": \");\n if (_canIncludeHeaders(header)) {\n responseHeaderMap_2[header] = value;\n }\n });\n ajaxResponse[_DYN_HEADER_MAP /* @min:%2eheaderMap */] = responseHeaderMap_2;\n }\n }\n return ajaxResponse;\n });\n var properties = void 0;\n try {\n if (!!_addRequestContext) {\n properties = _addRequestContext({\n status: xhr[_DYN_STATUS /* @min:%2estatus */],\n xhr: xhr\n });\n }\n } catch (e) {\n _throwInternalWarning(_self, 104 /* _eInternalMessageId.FailedAddingCustomDefinedRequestContext */, CUSTOM_REQUEST_CONTEXT_ERROR);\n }\n if (dependency) {\n if (properties !== undefined) {\n dependency[STR_PROPERTIES /* @min:%2eproperties */] = __assign(__assign({}, dependency.properties), properties);\n }\n var sysProperties = ajaxData[_DYN_GET_PART_APROPS /* @min:%2egetPartAProps */]();\n _reportDependencyInternal(_dependencyInitializers, _self[_DYN_CORE /* @min:%2ecore */], ajaxData, dependency, null, sysProperties);\n } else {\n _reportXhrError(null, {\n requestSentTime: ajaxData[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */],\n responseFinishedTime: ajaxData[_DYN_RESPONSE_FINISHED_TI12 /* @min:%2eresponseFinishedTime */]\n });\n }\n } finally {\n // cleanup telemetry data\n try {\n var xhrRequestData = xhr[AJAX_DATA_CONTAINER] || {\n i: {}\n };\n var ajaxDataCntr = xhrRequestData.i || {};\n if (ajaxDataCntr[_ajaxDataId]) {\n ajaxDataCntr[_ajaxDataId] = null;\n }\n } catch (e) {\n // May throw in environments that prevent extension or freeze xhr\n }\n }\n }, function (e) {\n _reportXhrError(e, null);\n });\n }\n function _getAjaxCorrelationContext(xhr) {\n var _a;\n try {\n var responseHeadersString = xhr[_DYN_GET_ALL_RESPONSE_HEA13 /* @min:%2egetAllResponseHeaders */]();\n if (responseHeadersString !== null) {\n var index = _indexOf(responseHeadersString[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */](), RequestHeaders[8 /* eRequestHeaders.requestContextHeaderLowerCase */]);\n if (index !== -1) {\n var responseHeader = xhr.getResponseHeader(RequestHeaders[0 /* eRequestHeaders.requestContextHeader */]);\n return correlationIdGetCorrelationContext(responseHeader);\n }\n }\n } catch (e) {\n _throwInternalWarning(_self, 18 /* _eInternalMessageId.FailedMonitorAjaxGetCorrelationHeader */, CORRELATION_HEADER_ERROR, (_a = {}, _a[_DYN_AJAX_DIAGNOSTICS_MES14 /* @min:ajaxDiagnosticsMessage */] = _getFailedAjaxDiagnosticsMessage(xhr, _ajaxDataId), _a.exception = dumpObj(e), _a));\n }\n }\n function _createMarkId(type, ajaxData) {\n if (ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */] && _markPrefix && _enableAjaxPerfTracking) {\n var performance_1 = getPerformance();\n if (performance_1 && isFunction(performance_1.mark)) {\n _markCount++;\n var markId = _markPrefix + type + \"#\" + _markCount;\n performance_1.mark(markId);\n var entries = performance_1.getEntriesByName(markId);\n if (entries && entries[_DYN_LENGTH /* @min:%2elength */] === 1) {\n ajaxData[_DYN_PERF_MARK /* @min:%2eperfMark */] = entries[0];\n }\n }\n }\n }\n function _findPerfResourceEntry(initiatorType, ajaxData, trackCallback, reportError) {\n var perfMark = ajaxData[_DYN_PERF_MARK /* @min:%2eperfMark */];\n var performance = getPerformance();\n var maxAttempts = _maxAjaxPerfLookupAttempts;\n var retryDelay = _ajaxPerfLookupDelay;\n var requestUrl = ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */];\n var attempt = 0;\n (function locateResourceTiming() {\n try {\n if (performance && perfMark) {\n attempt++;\n var perfTiming = null;\n var entries = performance.getEntries();\n for (var lp = entries[_DYN_LENGTH /* @min:%2elength */] - 1; lp >= 0; lp--) {\n var entry = entries[lp];\n if (entry) {\n if (entry.entryType === \"resource\") {\n if (entry.initiatorType === initiatorType && (_indexOf(entry.name, requestUrl) !== -1 || _indexOf(requestUrl, entry.name) !== -1)) {\n perfTiming = entry;\n }\n } else if (entry.entryType === \"mark\" && entry.name === perfMark.name) {\n // We hit the start event\n ajaxData[_DYN_PERF_TIMING /* @min:%2eperfTiming */] = perfTiming;\n break;\n }\n if (entry[_DYN_START_TIME /* @min:%2estartTime */] < perfMark[_DYN_START_TIME /* @min:%2estartTime */] - 1000) {\n // Fallback to try and reduce the time spent looking for the perf entry\n break;\n }\n }\n }\n }\n if (!perfMark ||\n // - we don't have a perfMark or\n ajaxData[_DYN_PERF_TIMING /* @min:%2eperfTiming */] ||\n // - we have not found the perf entry or\n attempt >= maxAttempts ||\n // - we have tried too many attempts or\n ajaxData.async === false) {\n // - this is a sync request\n if (perfMark && isFunction(performance.clearMarks)) {\n // Remove the mark so we don't fill up the performance resources too much\n performance.clearMarks(perfMark.name);\n }\n ajaxData.perfAttempts = attempt;\n // just continue and report the track event\n trackCallback();\n } else {\n // We need to wait for the browser to populate the window.performance entry\n // This needs to be at least 1ms as waiting <= 1 (on firefox) is not enough time for fetch or xhr,\n // this is a scheduling issue for the browser implementation\n scheduleTimeout(locateResourceTiming, retryDelay);\n }\n } catch (e) {\n reportError(e);\n }\n })();\n }\n function _createFetchRecord(input, init) {\n var _a;\n var distributedTraceCtx = _getDistributedTraceCtx();\n var traceID = distributedTraceCtx && distributedTraceCtx[_DYN_GET_TRACE_ID /* @min:%2egetTraceId */]() || generateW3CId();\n var spanID = strSubstr(generateW3CId(), 0, 16);\n var ajaxData = new ajaxRecord(traceID, spanID, _self[strDiagLog](), (_a = _self.core) === null || _a === void 0 ? void 0 : _a.getTraceCtx());\n ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = distributedTraceCtx && distributedTraceCtx[_DYN_GET_TRACE_FLAGS /* @min:%2egetTraceFlags */]();\n ajaxData[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */] = dateTimeUtilsNow();\n ajaxData[_DYN_ERROR_STATUS_TEXT /* @min:%2eerrorStatusText */] = _enableAjaxErrorStatusText;\n var requestUrl;\n if (input instanceof Request) {\n requestUrl = (input || {}).url || \"\";\n } else {\n requestUrl = input;\n }\n if (requestUrl === \"\") {\n var location_1 = getLocation();\n if (location_1 && location_1.href) {\n requestUrl = strSplit(location_1.href, \"#\")[0];\n }\n }\n ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */] = requestUrl;\n var method = \"GET\";\n if (init && init[_DYN_METHOD /* @min:%2emethod */]) {\n method = init[_DYN_METHOD /* @min:%2emethod */];\n } else if (input && input instanceof Request) {\n method = input[_DYN_METHOD /* @min:%2emethod */];\n }\n ajaxData[_DYN_METHOD /* @min:%2emethod */] = method;\n var requestHeaders = {};\n if (_enableRequestHeaderTracking) {\n var headers = new Headers((init ? init[_DYN_HEADERS /* @min:%2eheaders */] : 0) || (input instanceof Request ? input[_DYN_HEADERS /* @min:%2eheaders */] || {} : {}));\n headers.forEach(function (value, key) {\n if (_canIncludeHeaders(key)) {\n requestHeaders[key] = value;\n }\n });\n }\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */] = requestHeaders;\n _createMarkId(STR_FETCH, ajaxData);\n return ajaxData;\n }\n function _getFailedFetchDiagnosticsMessage(input) {\n var result = \"\";\n try {\n if (!isNullOrUndefined(input)) {\n if (typeof input === \"string\") {\n result += \"(url: '\".concat(input, \"')\");\n } else {\n result += \"(url: '\".concat(input.url, \"')\");\n }\n }\n } catch (e) {\n _throwInternalCritical(_self, 15 /* _eInternalMessageId.FailedMonitorAjaxOpen */, \"Failed to grab failed fetch diagnostics message\", {\n exception: dumpObj(e)\n });\n }\n return result;\n }\n function _reportFetchMetrics(callDetails, status, input, response, ajaxData, getResponse, properties) {\n if (!ajaxData) {\n return;\n }\n function _reportFetchError(msgId, e, failedProps) {\n var errorProps = failedProps || {};\n errorProps[\"fetchDiagnosticsMessage\"] = _getFailedFetchDiagnosticsMessage(input);\n if (e) {\n errorProps[\"exception\"] = dumpObj(e);\n }\n _throwInternalWarning(_self, msgId, FAILED_TO_CALCULATE_DURATION_ERROR + \"fetch call\" + ERROR_NOT_SENT, errorProps);\n }\n ajaxData[_DYN_RESPONSE_FINISHED_TI12 /* @min:%2eresponseFinishedTime */] = dateTimeUtilsNow();\n ajaxData[_DYN_STATUS /* @min:%2estatus */] = status;\n _findPerfResourceEntry(STR_FETCH, ajaxData, function () {\n var dependency = ajaxData[_DYN__CREATE_TRACK_ITEM /* @min:%2eCreateTrackItem */](\"Fetch\", _enableRequestHeaderTracking, getResponse);\n var properties;\n try {\n if (!!_addRequestContext) {\n properties = _addRequestContext({\n status: status,\n request: input,\n response: response\n });\n }\n } catch (e) {\n _throwInternalWarning(_self, 104 /* _eInternalMessageId.FailedAddingCustomDefinedRequestContext */, CUSTOM_REQUEST_CONTEXT_ERROR);\n }\n if (dependency) {\n if (properties !== undefined) {\n dependency[STR_PROPERTIES /* @min:%2eproperties */] = __assign(__assign({}, dependency.properties), properties);\n }\n var sysProperties = ajaxData[_DYN_GET_PART_APROPS /* @min:%2egetPartAProps */]();\n _reportDependencyInternal(_dependencyInitializers, _self[_DYN_CORE /* @min:%2ecore */], ajaxData, dependency, null, sysProperties);\n } else {\n _reportFetchError(14 /* _eInternalMessageId.FailedMonitorAjaxDur */, null, {\n requestSentTime: ajaxData[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */],\n responseFinishedTime: ajaxData[_DYN_RESPONSE_FINISHED_TI12 /* @min:%2eresponseFinishedTime */]\n });\n }\n }, function (e) {\n _reportFetchError(18 /* _eInternalMessageId.FailedMonitorAjaxGetCorrelationHeader */, e, null);\n });\n }\n function _getFetchCorrelationContext(response) {\n if (response && response[_DYN_HEADERS /* @min:%2eheaders */]) {\n try {\n var responseHeader = response[_DYN_HEADERS /* @min:%2eheaders */].get(RequestHeaders[0 /* eRequestHeaders.requestContextHeader */]);\n return correlationIdGetCorrelationContext(responseHeader);\n } catch (e) {\n _throwInternalWarning(_self, 18 /* _eInternalMessageId.FailedMonitorAjaxGetCorrelationHeader */, CORRELATION_HEADER_ERROR, {\n fetchDiagnosticsMessage: _getFailedFetchDiagnosticsMessage(response),\n exception: dumpObj(e)\n });\n }\n }\n }\n function _reportDependencyInternal(initializers, core, ajaxData, dependency, properties, systemProperties) {\n var result = true;\n var initializersCount = initializers[_DYN_LENGTH /* @min:%2elength */];\n if (initializersCount > 0) {\n var details = {\n item: dependency,\n properties: properties,\n sysProperties: systemProperties,\n context: ajaxData ? ajaxData[_DYN_CONTEXT /* @min:%2econtext */] : null,\n aborted: ajaxData ? !!ajaxData[_DYN_ABORTED /* @min:%2eaborted */] : false\n };\n result = _processDependencyContainer(core, initializers, details, \"initializer\");\n }\n if (result) {\n _self[_DYN_TRACK_DEPENDENCY_DAT1 /* @min:%2etrackDependencyDataInternal */](dependency, properties, systemProperties);\n }\n }\n });\n return _this;\n }\n // Removed Stub for AjaxMonitor.prototype.initialize.\n AjaxMonitor.prototype.processTelemetry = function (item, itemCtx) {\n this.processNext(item, itemCtx);\n };\n // Removed Stub for AjaxMonitor.prototype.trackDependencyData.\n // Removed Stub for AjaxMonitor.prototype.includeCorrelationHeaders.\n // Removed Stub for AjaxMonitor.prototype.addDependencyListener.\n /**\r\n * Add an dependency telemetry initializer callback function to allow populating additional properties or drop the request.\r\n * It is called after the dependency call has completed and any available performance details are available. A dependency\r\n * initializer is similar to the TelemetryInitializer function but it allows you to block the reporting of the dependency\r\n * request so that it doesn't count against the `maxAjaxCallsPerView`.\r\n * @param dependencyInitializer - The Dependency Telemetry Initializer function\r\n * @returns - A IDependencyInitializerHandler to enable the initializer to be removed\r\n */\n AjaxMonitor.prototype.addDependencyInitializer = function (dependencyInitializer) {\n return null;\n };\n // Removed Stub for AjaxMonitor.prototype.trackDependencyDataInternal.\n AjaxMonitor.identifier = \"AjaxDependencyPlugin\";\n return AjaxMonitor;\n}(BaseTelemetryPlugin);\nexport { AjaxMonitor };\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nvar Application = /** @class */function () {\n function Application() {}\n return Application;\n}();\nexport { Application };\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nvar Device = /** @class */function () {\n /**\r\n * Constructs a new instance of the Device class\r\n */\n function Device() {\n // don't attempt to fingerprint browsers\n this.id = \"browser\";\n // Device type is a dimension in our data platform\n // Setting it to 'Browser' allows to separate client and server dependencies/exceptions\n this.deviceClass = \"Browser\";\n }\n return Device;\n}();\nexport { Device };\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { onConfigChange } from \"@microsoft/applicationinsights-core-js\";\nvar Version = '3.3.6';\nvar Internal = /** @class */function () {\n /**\r\n * Constructs a new instance of the internal telemetry data class.\r\n */\n function Internal(config, unloadHookContainer) {\n var _this = this;\n var unloadHook = onConfigChange(config, function () {\n var prefix = config.sdkExtension;\n _this.sdkVersion = (prefix ? prefix + \"_\" : \"\") + \"javascript:\" + Version;\n });\n unloadHookContainer && unloadHookContainer.add(unloadHook);\n }\n return Internal;\n}();\nexport { Internal };\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nvar Location = /** @class */function () {\n function Location() {}\n return Location;\n}();\nexport { Location };\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n// @skip-file-minify\n// ##############################################################\n// AUTO GENERATED FILE: This file is Auto Generated during build.\n// ##############################################################\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n// Note: DON'T Export these const from the package as we are still targeting ES5 which can result in a mutable variables that someone could change!!!\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nexport var _DYN_SESSION = \"session\"; // Count: 4\nexport var _DYN_SESSION_MANAGER = \"sessionManager\"; // Count: 3\nexport var _DYN_IS_USER_COOKIE_SET = \"isUserCookieSet\"; // Count: 4\nexport var _DYN_IS_NEW_USER = \"isNewUser\"; // Count: 4\nexport var _DYN_GET_TRACE_CTX = \"getTraceCtx\"; // Count: 3\nexport var _DYN_TELEMETRY_TRACE = \"telemetryTrace\"; // Count: 3\nexport var _DYN_APPLY_SESSION_CONTEX0 = \"applySessionContext\"; // Count: 2\nexport var _DYN_APPLY_APPLICATION_CO1 = \"applyApplicationContext\"; // Count: 2\nexport var _DYN_APPLY_OPERATION_CONT2 = \"applyOperationContext\"; // Count: 2\nexport var _DYN_APPLY_OPERATING_SYST3 = \"applyOperatingSystemContxt\"; // Count: 2\nexport var _DYN_APPLY_LOCATION_CONTE4 = \"applyLocationContext\"; // Count: 2\nexport var _DYN_APPLY_INTERNAL_CONTE5 = \"applyInternalContext\"; // Count: 2\nexport var _DYN_GET_SESSION_ID = \"getSessionId\"; // Count: 4\nexport var _DYN_SESSION_COOKIE_POSTF6 = \"sessionCookiePostfix\"; // Count: 2\nexport var _DYN_AUTOMATIC_SESSION = \"automaticSession\"; // Count: 6\nexport var _DYN_ACCOUNT_ID = \"accountId\"; // Count: 6\nexport var _DYN_AUTHENTICATED_ID = \"authenticatedId\"; // Count: 6\nexport var _DYN_ACQUISITION_DATE = \"acquisitionDate\"; // Count: 5\nexport var _DYN_RENEWAL_DATE = \"renewalDate\"; // Count: 4\nexport var _DYN_COOKIE_SEPARATOR = \"cookieSeparator\"; // Count: 5\nexport var _DYN_AUTH_USER_COOKIE_NAM7 = \"authUserCookieName\"; // Count: 3\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { utlCanUseLocalStorage, utlGetLocalStorage, utlSetLocalStorage } from \"@microsoft/applicationinsights-common\";\nimport { _throwInternal, dateNow, dumpObj, getExceptionName, isFunction, newId, onConfigChange, safeGetCookieMgr, safeGetLogger } from \"@microsoft/applicationinsights-core-js\";\nimport { _DYN_ACQUISITION_DATE, _DYN_AUTOMATIC_SESSION, _DYN_RENEWAL_DATE, _DYN_SESSION_COOKIE_POSTF6 } from \"../__DynamicConstants\";\nvar SESSION_COOKIE_NAME = \"ai_session\";\nvar ACQUISITION_SPAN = 86400000; // 24 hours in ms\nvar RENEWAL_SPAN = 1800000; // 30 minutes in ms\nvar COOKIE_UPDATE_INTERVAL = 60000; // 1 minute in ms\nvar Session = /** @class */function () {\n function Session() {}\n return Session;\n}();\nexport { Session };\nvar _SessionManager = /** @class */function () {\n function _SessionManager(config, core, unloadHookContainer) {\n var self = this;\n var _storageNamePrefix;\n var _cookieUpdatedTimestamp;\n var _logger = safeGetLogger(core);\n var _cookieManager = safeGetCookieMgr(core);\n var _sessionExpirationMs;\n var _sessionRenewalMs;\n dynamicProto(_SessionManager, self, function (_self) {\n if (!config) {\n config = {};\n }\n var unloadHook = onConfigChange(config, function (details) {\n _sessionExpirationMs = config.sessionExpirationMs || ACQUISITION_SPAN;\n _sessionRenewalMs = config.sessionRenewalMs || RENEWAL_SPAN;\n // sessionCookiePostfix takes the preference if it is configured, otherwise takes namePrefix if configured.\n var sessionCookiePostfix = config[_DYN_SESSION_COOKIE_POSTF6 /* @min:%2esessionCookiePostfix */] || config.namePrefix || \"\";\n _storageNamePrefix = SESSION_COOKIE_NAME + sessionCookiePostfix;\n });\n unloadHookContainer && unloadHookContainer.add(unloadHook);\n _self[_DYN_AUTOMATIC_SESSION /* @min:%2eautomaticSession */] = new Session();\n _self.update = function () {\n // Always using Date getTime() as there is a bug in older IE instances that causes the performance timings to have the hi-bit set eg 0x800000000 causing\n // the number to be incorrect.\n var nowMs = dateNow();\n var isExpired = false;\n var session = _self[_DYN_AUTOMATIC_SESSION /* @min:%2eautomaticSession */];\n if (!session.id) {\n isExpired = !_initializeAutomaticSession(session, nowMs);\n }\n if (!isExpired && _sessionExpirationMs > 0) {\n var timeSinceAcqMs = nowMs - session[_DYN_ACQUISITION_DATE /* @min:%2eacquisitionDate */];\n var timeSinceRenewalMs = nowMs - session[_DYN_RENEWAL_DATE /* @min:%2erenewalDate */];\n isExpired = timeSinceAcqMs < 0 || timeSinceRenewalMs < 0; // expired if the acquisition or last renewal are in the future\n isExpired = isExpired || timeSinceAcqMs > _sessionExpirationMs; // expired if the time since acquisition is more than session Expiration\n isExpired = isExpired || timeSinceRenewalMs > _sessionRenewalMs; // expired if the time since last renewal is more than renewal period\n }\n // renew if acquisitionSpan or renewalSpan has elapsed\n if (isExpired) {\n // update automaticSession so session state has correct id\n _renew(nowMs);\n } else {\n // do not update the cookie more often than cookieUpdateInterval\n if (!_cookieUpdatedTimestamp || nowMs - _cookieUpdatedTimestamp > COOKIE_UPDATE_INTERVAL) {\n _setCookie(session, nowMs);\n }\n }\n };\n /**\r\n * Record the current state of the automatic session and store it in our cookie string format\r\n * into the browser's local storage. This is used to restore the session data when the cookie\r\n * expires.\r\n */\n _self.backup = function () {\n var session = _self[_DYN_AUTOMATIC_SESSION /* @min:%2eautomaticSession */];\n _setStorage(session.id, session[_DYN_ACQUISITION_DATE /* @min:%2eacquisitionDate */], session[_DYN_RENEWAL_DATE /* @min:%2erenewalDate */]);\n };\n /**\r\n * Use config.namePrefix + ai_session cookie data or local storage data (when the cookie is unavailable) to\r\n * initialize the automatic session.\r\n * @returns true if values set otherwise false\r\n */\n function _initializeAutomaticSession(session, now) {\n var isValid = false;\n var cookieValue = _cookieManager.get(_storageNamePrefix);\n if (cookieValue && isFunction(cookieValue.split)) {\n isValid = _initializeAutomaticSessionWithData(session, cookieValue);\n } else {\n // There's no cookie, but we might have session data in local storage\n // This can happen if the session expired or the user actively deleted the cookie\n // We only want to recover data if the cookie is missing from expiry. We should respect the user's wishes if the cookie was deleted actively.\n // The User class handles this for us and deletes our local storage object if the persistent user cookie was removed.\n var storageValue = utlGetLocalStorage(_logger, _storageNamePrefix);\n if (storageValue) {\n isValid = _initializeAutomaticSessionWithData(session, storageValue);\n }\n }\n return isValid || !!session.id;\n }\n /**\r\n * Extract id, acquisitionDate, and renewalDate from an ai_session payload string and\r\n * use this data to initialize automaticSession.\r\n *\r\n * @param sessionData - The string stored in an ai_session cookie or local storage backup\r\n * @returns true if values set otherwise false\r\n */\n function _initializeAutomaticSessionWithData(session, sessionData) {\n var isValid = false;\n var sessionReset = \", session will be reset\";\n var tokens = sessionData.split(\"|\");\n if (tokens.length >= 2) {\n try {\n var acqMs = +tokens[1] || 0;\n var renewalMs = +tokens[2] || 0;\n if (isNaN(acqMs) || acqMs <= 0) {\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 27 /* _eInternalMessageId.SessionRenewalDateIsZero */, \"AI session acquisition date is 0\" + sessionReset);\n } else if (isNaN(renewalMs) || renewalMs <= 0) {\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 27 /* _eInternalMessageId.SessionRenewalDateIsZero */, \"AI session renewal date is 0\" + sessionReset);\n } else if (tokens[0]) {\n // Everything looks valid so set the values\n session.id = tokens[0];\n session[_DYN_ACQUISITION_DATE /* @min:%2eacquisitionDate */] = acqMs;\n session[_DYN_RENEWAL_DATE /* @min:%2erenewalDate */] = renewalMs;\n isValid = true;\n }\n } catch (e) {\n _throwInternal(_logger, 1 /* eLoggingSeverity.CRITICAL */, 9 /* _eInternalMessageId.ErrorParsingAISessionCookie */, \"Error parsing ai_session value [\" + (sessionData || \"\") + \"]\" + sessionReset + \" - \" + getExceptionName(e), {\n exception: dumpObj(e)\n });\n }\n }\n return isValid;\n }\n function _renew(nowMs) {\n var getNewId = config.getNewId || newId;\n _self[_DYN_AUTOMATIC_SESSION /* @min:%2eautomaticSession */].id = getNewId(config.idLength || 22);\n _self[_DYN_AUTOMATIC_SESSION /* @min:%2eautomaticSession */][_DYN_ACQUISITION_DATE /* @min:%2eacquisitionDate */] = nowMs;\n _setCookie(_self[_DYN_AUTOMATIC_SESSION /* @min:%2eautomaticSession */], nowMs);\n // If this browser does not support local storage, fire an internal log to keep track of it at this point\n if (!utlCanUseLocalStorage()) {\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 0 /* _eInternalMessageId.BrowserDoesNotSupportLocalStorage */, \"Browser does not support local storage. Session durations will be inaccurate.\");\n }\n }\n function _setCookie(session, nowMs) {\n var acq = session[_DYN_ACQUISITION_DATE /* @min:%2eacquisitionDate */];\n session[_DYN_RENEWAL_DATE /* @min:%2erenewalDate */] = nowMs;\n var renewalPeriodMs = _sessionRenewalMs;\n // Set cookie to expire after the session expiry time passes or the session renewal deadline, whichever is sooner\n // Expiring the cookie will cause the session to expire even if the user isn't on the page\n var acqTimeLeftMs = acq + _sessionExpirationMs - nowMs;\n var cookie = [session.id, acq, nowMs];\n var maxAgeSec = 0;\n if (acqTimeLeftMs < renewalPeriodMs) {\n maxAgeSec = acqTimeLeftMs / 1000;\n } else {\n maxAgeSec = renewalPeriodMs / 1000;\n }\n var cookieDomain = config.cookieDomain || null;\n // if sessionExpirationMs is set to 0, it means the expiry is set to 0 for this session cookie\n // A cookie with 0 expiry in the session cookie will never expire for that browser session. If the browser is closed the cookie expires.\n // Depending on the browser, another instance does not inherit this cookie, however, another tab will\n _cookieManager.set(_storageNamePrefix, cookie.join(\"|\"), _sessionExpirationMs > 0 ? maxAgeSec : null, cookieDomain);\n _cookieUpdatedTimestamp = nowMs;\n }\n function _setStorage(guid, acq, renewal) {\n // Keep data in local storage to retain the last session id, allowing us to cleanly end the session when it expires\n // Browsers that don't support local storage won't be able to end sessions cleanly from the client\n // The server will notice this and end the sessions itself, with loss of accurate session duration\n utlSetLocalStorage(_logger, _storageNamePrefix, [guid, acq, renewal].join(\"|\"));\n }\n });\n }\n // Removed Stub for _SessionManager.prototype.update.\n // Removed Stub for _SessionManager.prototype.backup.\n // This is a workaround for an IE bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n _SessionManager.__ieDyn = 1;\n return _SessionManager;\n}();\nexport { _SessionManager };\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport { dataSanitizeString } from \"@microsoft/applicationinsights-common\";\nimport { generateW3CId, getLocation } from \"@microsoft/applicationinsights-core-js\";\nvar TelemetryTrace = /** @class */function () {\n function TelemetryTrace(id, parentId, name, logger) {\n var _self = this;\n _self.traceID = id || generateW3CId();\n _self.parentID = parentId;\n var location = getLocation();\n if (!name && location && location.pathname) {\n name = location.pathname;\n }\n _self.name = dataSanitizeString(logger, name);\n }\n return TelemetryTrace;\n}();\nexport { TelemetryTrace };\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { utlRemoveStorage } from \"@microsoft/applicationinsights-common\";\nimport { _throwInternal, newId, onConfigChange, safeGetCookieMgr, safeGetLogger, toISOString } from \"@microsoft/applicationinsights-core-js\";\nimport { objDefine } from \"@nevware21/ts-utils\";\nimport { _DYN_ACCOUNT_ID, _DYN_AUTHENTICATED_ID, _DYN_AUTH_USER_COOKIE_NAM7, _DYN_COOKIE_SEPARATOR, _DYN_IS_NEW_USER, _DYN_IS_USER_COOKIE_SET } from \"../__DynamicConstants\";\nfunction _validateUserInput(id) {\n // Validate:\n // 1. Id is a non-empty string.\n // 2. It does not contain special characters for cookies.\n if (typeof id !== \"string\" || !id || id.match(/,|;|=| |\\|/)) {\n return false;\n }\n return true;\n}\nvar User = /** @class */function () {\n function User(config, core, unloadHookContainer) {\n /**\r\n * A flag indicating whether this represents a new user\r\n */\n this.isNewUser = false;\n /**\r\n * A flag indicating whether the user cookie has been set\r\n */\n this.isUserCookieSet = false;\n var _logger = safeGetLogger(core);\n var _cookieManager = safeGetCookieMgr(core);\n var _storageNamePrefix;\n dynamicProto(User, this, function (_self) {\n // Define _self.config\n objDefine(_self, \"config\", {\n g: function () {\n return config;\n }\n });\n var unloadHook = onConfigChange(config, function () {\n var userCookiePostfix = config.userCookiePostfix || \"\";\n _storageNamePrefix = User.userCookieName + userCookiePostfix;\n // get userId or create new one if none exists\n var cookie = _cookieManager.get(_storageNamePrefix);\n if (cookie) {\n _self[_DYN_IS_NEW_USER /* @min:%2eisNewUser */] = false;\n var params = cookie.split(User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]);\n if (params.length > 0) {\n _self.id = params[0];\n // we already have a cookie\n _self[_DYN_IS_USER_COOKIE_SET /* @min:%2eisUserCookieSet */] = !!_self.id;\n }\n }\n if (!_self.id) {\n _self.id = _generateNewId();\n var newCookie = _generateNewCookie(_self.id);\n _setUserCookie(newCookie.join(User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]));\n // If we have an config.namePrefix() + ai_session in local storage this means the user actively removed our cookies.\n // We should respect their wishes and clear ourselves from local storage\n var name_1 = (config.namePrefix || \"\") + \"ai_session\";\n utlRemoveStorage(_logger, name_1);\n }\n // We still take the account id from the ctor param for backward compatibility.\n // But if the the customer set the accountId through the newer setAuthenticatedUserContext API, we will override it.\n _self[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] = config[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] || undefined;\n // Get the auth user id and account id from the cookie if exists\n // Cookie is in the pattern: |\n var authCookie = _cookieManager.get(User[_DYN_AUTH_USER_COOKIE_NAM7 /* @min:%2eauthUserCookieName */]);\n if (authCookie) {\n authCookie = decodeURI(authCookie);\n var authCookieString = authCookie.split(User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]);\n if (authCookieString[0]) {\n _self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */] = authCookieString[0];\n }\n if (authCookieString.length > 1 && authCookieString[1]) {\n _self[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] = authCookieString[1];\n }\n }\n });\n unloadHookContainer && unloadHookContainer.add(unloadHook);\n function _generateNewId() {\n var theConfig = config || {};\n var getNewId = theConfig.getNewId || newId;\n var id = getNewId(theConfig.idLength ? config.idLength : 22);\n return id;\n }\n function _generateNewCookie(userId) {\n var acqStr = toISOString(new Date());\n _self.accountAcquisitionDate = acqStr;\n _self[_DYN_IS_NEW_USER /* @min:%2eisNewUser */] = true;\n var newCookie = [userId, acqStr];\n return newCookie;\n }\n function _setUserCookie(cookie) {\n // without expiration, cookies expire at the end of the session\n // set it to 365 days from now\n // 365 * 24 * 60 * 60 = 31536000\n var oneYear = 31536000;\n _self[_DYN_IS_USER_COOKIE_SET /* @min:%2eisUserCookieSet */] = _cookieManager.set(_storageNamePrefix, cookie, oneYear);\n }\n _self.setAuthenticatedUserContext = function (authenticatedUserId, accountId, storeInCookie) {\n if (storeInCookie === void 0) {\n storeInCookie = false;\n }\n // Validate inputs to ensure no cookie control characters.\n var isInvalidInput = !_validateUserInput(authenticatedUserId) || accountId && !_validateUserInput(accountId);\n if (isInvalidInput) {\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 60 /* _eInternalMessageId.SetAuthContextFailedAccountName */, \"Setting auth user context failed. \" + \"User auth/account id should be of type string, and not contain commas, semi-colons, equal signs, spaces, or vertical-bars.\", true);\n return;\n }\n // Create cookie string.\n _self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */] = authenticatedUserId;\n var authCookie = _self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */];\n if (accountId) {\n _self[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] = accountId;\n authCookie = [_self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */], _self.accountId].join(User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]);\n }\n if (storeInCookie) {\n // Set the cookie. No expiration date because this is a session cookie (expires when browser closed).\n // Encoding the cookie to handle unexpected unicode characters.\n _cookieManager.set(User[_DYN_AUTH_USER_COOKIE_NAM7 /* @min:%2eauthUserCookieName */], encodeURI(authCookie));\n }\n };\n /**\r\n * Clears the authenticated user id and the account id from the user context.\r\n * @returns {}\r\n */\n _self.clearAuthenticatedUserContext = function () {\n _self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */] = null;\n _self[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] = null;\n _cookieManager.del(User[_DYN_AUTH_USER_COOKIE_NAM7 /* @min:%2eauthUserCookieName */]);\n };\n _self.update = function (userId) {\n // Optimizations to avoid setting and processing the cookie when not needed\n if (_self.id !== userId || !_self[_DYN_IS_USER_COOKIE_SET /* @min:%2eisUserCookieSet */]) {\n var user_id = userId ? userId : _generateNewId();\n var user_cookie = _generateNewCookie(user_id);\n _setUserCookie(user_cookie.join(User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]));\n }\n };\n });\n }\n // Removed Stub for User.prototype.setAuthenticatedUserContext.\n // Removed Stub for User.prototype.clearAuthenticatedUserContext.\n // Removed Stub for User.prototype.update.\n User.cookieSeparator = \"|\";\n User.userCookieName = \"ai_user\";\n User.authUserCookieName = \"ai_authUser\";\n return User;\n}();\nexport { User };\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n/**\r\n* TelemetryContext.ts\r\n* @copyright Microsoft 2018\r\n*/\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { CtxTagKeys, Extensions, PageView, dataSanitizeString } from \"@microsoft/applicationinsights-common\";\nimport { _InternalLogMessage, getSetValue, hasWindow, isNullOrUndefined, isString, objKeys, setValue } from \"@microsoft/applicationinsights-core-js\";\nimport { Application } from \"./Context/Application\";\nimport { Device } from \"./Context/Device\";\nimport { Internal } from \"./Context/Internal\";\nimport { Location } from \"./Context/Location\";\nimport { Session, _SessionManager } from \"./Context/Session\";\nimport { TelemetryTrace } from \"./Context/TelemetryTrace\";\nimport { User } from \"./Context/User\";\nimport { _DYN_ACCOUNT_ID, _DYN_APPLY_APPLICATION_CO1, _DYN_APPLY_INTERNAL_CONTE5, _DYN_APPLY_LOCATION_CONTE4, _DYN_APPLY_OPERATING_SYST3, _DYN_APPLY_OPERATION_CONT2, _DYN_APPLY_SESSION_CONTEX0, _DYN_AUTHENTICATED_ID, _DYN_AUTOMATIC_SESSION, _DYN_GET_SESSION_ID, _DYN_SESSION, _DYN_SESSION_MANAGER, _DYN_TELEMETRY_TRACE } from \"./__DynamicConstants\";\nvar strExt = \"ext\";\nvar strTags = \"tags\";\nfunction _removeEmpty(target, name) {\n if (target && target[name] && objKeys(target[name]).length === 0) {\n delete target[name];\n }\n}\nfunction _nullResult() {\n return null;\n}\nvar TelemetryContext = /** @class */function () {\n function TelemetryContext(core, defaultConfig, previousTraceCtx, unloadHookContainer) {\n var _this = this;\n var logger = core.logger;\n dynamicProto(TelemetryContext, this, function (_self) {\n _self.appId = _nullResult;\n _self[_DYN_GET_SESSION_ID /* @min:%2egetSessionId */] = _nullResult;\n _self.application = new Application();\n _self.internal = new Internal(defaultConfig, unloadHookContainer);\n if (hasWindow()) {\n _self[_DYN_SESSION_MANAGER /* @min:%2esessionManager */] = new _SessionManager(defaultConfig, core, unloadHookContainer);\n _self.device = new Device();\n _self.location = new Location();\n _self.user = new User(defaultConfig, core, unloadHookContainer);\n var traceId = void 0;\n var parentId = void 0;\n var name_1;\n if (previousTraceCtx) {\n traceId = previousTraceCtx.getTraceId();\n parentId = previousTraceCtx.getSpanId();\n name_1 = previousTraceCtx.getName();\n }\n _self[_DYN_TELEMETRY_TRACE /* @min:%2etelemetryTrace */] = new TelemetryTrace(traceId, parentId, name_1, logger);\n _self[_DYN_SESSION /* @min:%2esession */] = new Session();\n }\n _self[_DYN_GET_SESSION_ID /* @min:%2egetSessionId */] = function () {\n var session = _self[_DYN_SESSION /* @min:%2esession */];\n var sesId = null;\n // If customer set session info, apply their context; otherwise apply context automatically generated\n if (session && isString(session.id)) {\n sesId = session.id;\n } else {\n // Gets the automatic session if it exists or an empty object\n var autoSession = (_self[_DYN_SESSION_MANAGER /* @min:%2esessionManager */] || {})[_DYN_AUTOMATIC_SESSION /* @min:%2eautomaticSession */];\n sesId = autoSession && isString(autoSession.id) ? autoSession.id : null;\n }\n return sesId;\n };\n _self[_DYN_APPLY_SESSION_CONTEX0 /* @min:%2eapplySessionContext */] = function (evt, itemCtx) {\n setValue(getSetValue(evt.ext, Extensions.AppExt), \"sesId\", _self[_DYN_GET_SESSION_ID /* @min:%2egetSessionId */](), isString);\n };\n _self[_DYN_APPLY_OPERATING_SYST3 /* @min:%2eapplyOperatingSystemContxt */] = function (evt, itemCtx) {\n setValue(evt.ext, Extensions.OSExt, _self.os);\n };\n _self[_DYN_APPLY_APPLICATION_CO1 /* @min:%2eapplyApplicationContext */] = function (evt, itemCtx) {\n var application = _self.application;\n if (application) {\n // evt.ext.app\n var tags = getSetValue(evt, strTags);\n setValue(tags, CtxTagKeys.applicationVersion, application.ver, isString);\n setValue(tags, CtxTagKeys.applicationBuild, application.build, isString);\n }\n };\n _self.applyDeviceContext = function (evt, itemCtx) {\n var device = _self.device;\n if (device) {\n // evt.ext.device\n var extDevice = getSetValue(getSetValue(evt, strExt), Extensions.DeviceExt);\n setValue(extDevice, \"localId\", device.id, isString);\n setValue(extDevice, \"ip\", device.ip, isString);\n setValue(extDevice, \"model\", device.model, isString);\n setValue(extDevice, \"deviceClass\", device.deviceClass, isString);\n }\n };\n _self[_DYN_APPLY_INTERNAL_CONTE5 /* @min:%2eapplyInternalContext */] = function (evt, itemCtx) {\n var internal = _self.internal;\n if (internal) {\n var tags = getSetValue(evt, strTags);\n setValue(tags, CtxTagKeys.internalAgentVersion, internal.agentVersion, isString); // not mapped in CS 4.0\n setValue(tags, CtxTagKeys.internalSdkVersion, dataSanitizeString(logger, internal.sdkVersion, 64), isString);\n if (evt.baseType === _InternalLogMessage.dataType || evt.baseType === PageView.dataType) {\n setValue(tags, CtxTagKeys.internalSnippet, internal.snippetVer, isString);\n setValue(tags, CtxTagKeys.internalSdkSrc, internal.sdkSrc, isString);\n }\n }\n };\n _self[_DYN_APPLY_LOCATION_CONTE4 /* @min:%2eapplyLocationContext */] = function (evt, itemCtx) {\n var location = _this.location;\n if (location) {\n setValue(getSetValue(evt, strTags, []), CtxTagKeys.locationIp, location.ip, isString);\n }\n };\n _self[_DYN_APPLY_OPERATION_CONT2 /* @min:%2eapplyOperationContext */] = function (evt, itemCtx) {\n var telemetryTrace = _self[_DYN_TELEMETRY_TRACE /* @min:%2etelemetryTrace */];\n if (telemetryTrace) {\n var extTrace = getSetValue(getSetValue(evt, strExt), Extensions.TraceExt, {\n traceID: undefined,\n parentID: undefined\n });\n setValue(extTrace, \"traceID\", telemetryTrace.traceID, isString, isNullOrUndefined);\n setValue(extTrace, \"name\", telemetryTrace.name, isString, isNullOrUndefined);\n setValue(extTrace, \"parentID\", telemetryTrace.parentID, isString, isNullOrUndefined);\n }\n };\n _self.applyWebContext = function (evt, itemCtx) {\n var web = _this.web;\n if (web) {\n setValue(getSetValue(evt, strExt), Extensions.WebExt, web);\n }\n };\n _self.applyUserContext = function (evt, itemCtx) {\n var user = _self.user;\n if (user) {\n var tags = getSetValue(evt, strTags, []);\n // stays in tags\n setValue(tags, CtxTagKeys.userAccountId, user[_DYN_ACCOUNT_ID /* @min:%2eaccountId */], isString);\n // CS 4.0\n var extUser = getSetValue(getSetValue(evt, strExt), Extensions.UserExt);\n setValue(extUser, \"id\", user.id, isString);\n setValue(extUser, \"authId\", user[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */], isString);\n }\n };\n _self.cleanUp = function (evt, itemCtx) {\n var ext = evt.ext;\n if (ext) {\n _removeEmpty(ext, Extensions.DeviceExt);\n _removeEmpty(ext, Extensions.UserExt);\n _removeEmpty(ext, Extensions.WebExt);\n _removeEmpty(ext, Extensions.OSExt);\n _removeEmpty(ext, Extensions.AppExt);\n _removeEmpty(ext, Extensions.TraceExt);\n }\n };\n });\n }\n // Removed Stub for TelemetryContext.prototype.applySessionContext.\n // Removed Stub for TelemetryContext.prototype.applyOperatingSystemContxt.\n // Removed Stub for TelemetryContext.prototype.applyApplicationContext.\n // Removed Stub for TelemetryContext.prototype.applyDeviceContext.\n // Removed Stub for TelemetryContext.prototype.applyInternalContext.\n // Removed Stub for TelemetryContext.prototype.applyLocationContext.\n // Removed Stub for TelemetryContext.prototype.applyOperationContext.\n // Removed Stub for TelemetryContext.prototype.applyWebContext.\n // Removed Stub for TelemetryContext.prototype.applyUserContext.\n // Removed Stub for TelemetryContext.prototype.cleanUp.\n // This is a workaround for an IE bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n TelemetryContext.__ieDyn = 1;\n return TelemetryContext;\n}();\nexport { TelemetryContext };\n","/*\n * Application Insights JavaScript SDK - Properties Plugin, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n/**\r\n* PropertiesPlugin.ts\r\n* @copyright Microsoft 2018\r\n*/\nvar _a;\nimport { __extendsFn as __extends } from \"@microsoft/applicationinsights-shims\";\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { BreezeChannelIdentifier, PageView, PropertiesPluginIdentifier, createDistributedTraceContextFromTrace, utlSetStoragePrefix } from \"@microsoft/applicationinsights-common\";\nimport { BaseTelemetryPlugin, _InternalLogMessage, _logInternalMessage, createProcessTelemetryContext, getNavigator, getSetValue, isNullOrUndefined, onConfigChange } from \"@microsoft/applicationinsights-core-js\";\nimport { objDeepFreeze, objDefine } from \"@nevware21/ts-utils\";\nimport { TelemetryContext } from \"./TelemetryContext\";\nimport { _DYN_APPLY_APPLICATION_CO1, _DYN_APPLY_INTERNAL_CONTE5, _DYN_APPLY_LOCATION_CONTE4, _DYN_APPLY_OPERATING_SYST3, _DYN_APPLY_OPERATION_CONT2, _DYN_APPLY_SESSION_CONTEX0, _DYN_GET_SESSION_ID, _DYN_GET_TRACE_CTX, _DYN_IS_NEW_USER, _DYN_IS_USER_COOKIE_SET, _DYN_SESSION, _DYN_SESSION_COOKIE_POSTF6, _DYN_SESSION_MANAGER, _DYN_TELEMETRY_TRACE } from \"./__DynamicConstants\";\nvar undefString;\nvar nullValue = null;\nvar _defaultConfig = objDeepFreeze((_a = {\n accountId: nullValue,\n sessionRenewalMs: 30 * 60 * 1000,\n samplingPercentage: 100,\n sessionExpirationMs: 24 * 60 * 60 * 1000,\n cookieDomain: nullValue,\n sdkExtension: nullValue,\n isBrowserLinkTrackingEnabled: false,\n appId: nullValue\n}, _a[_DYN_GET_SESSION_ID /* @min:getSessionId */] = nullValue, _a.namePrefix = undefString, _a[_DYN_SESSION_COOKIE_POSTF6 /* @min:sessionCookiePostfix */] = undefString, _a.userCookiePostfix = undefString, _a.idLength = 22, _a.getNewId = nullValue, _a));\nvar PropertiesPlugin = /** @class */function (_super) {\n __extends(PropertiesPlugin, _super);\n function PropertiesPlugin() {\n var _this = _super.call(this) || this;\n _this.priority = 110;\n _this.identifier = PropertiesPluginIdentifier;\n var _extensionConfig;\n var _distributedTraceCtx;\n var _previousTraceCtx;\n var _context;\n var _disableUserInitMessage;\n dynamicProto(PropertiesPlugin, _this, function (_self, _base) {\n _initDefaults();\n objDefine(_self, \"context\", {\n g: function () {\n return _context;\n }\n });\n _self.initialize = function (config, core, extensions, pluginChain) {\n _base.initialize(config, core, extensions, pluginChain);\n _populateDefaults(config);\n };\n /**\r\n * Add Part A fields to the event\r\n * @param event - The event that needs to be processed\r\n */\n _self.processTelemetry = function (event, itemCtx) {\n if (!isNullOrUndefined(event)) {\n itemCtx = _self._getTelCtx(itemCtx);\n // If the envelope is PageView, reset the internal message count so that we can send internal telemetry for the new page.\n if (event.name === PageView.envelopeType) {\n itemCtx.diagLog().resetInternalMessageCount();\n }\n var theContext = _context || {};\n if (theContext[_DYN_SESSION /* @min:%2esession */]) {\n // If customer did not provide custom session id update the session manager\n if (typeof _context[_DYN_SESSION /* @min:%2esession */].id !== \"string\" && theContext[_DYN_SESSION_MANAGER /* @min:%2esessionManager */]) {\n theContext[_DYN_SESSION_MANAGER /* @min:%2esessionManager */].update();\n }\n }\n var userCtx = theContext.user;\n if (userCtx && !userCtx[_DYN_IS_USER_COOKIE_SET /* @min:%2eisUserCookieSet */]) {\n userCtx.update(theContext.user.id);\n }\n _processTelemetryInternal(event, itemCtx);\n if (userCtx && userCtx[_DYN_IS_NEW_USER /* @min:%2eisNewUser */]) {\n userCtx[_DYN_IS_NEW_USER /* @min:%2eisNewUser */] = false;\n if (!_disableUserInitMessage) {\n var message = new _InternalLogMessage(72 /* _eInternalMessageId.SendBrowserInfoOnUserInit */, (getNavigator() || {}).userAgent || \"\");\n _logInternalMessage(itemCtx.diagLog(), 1 /* eLoggingSeverity.CRITICAL */, message);\n }\n }\n _self.processNext(event, itemCtx);\n }\n };\n _self._doTeardown = function (unloadCtx, unloadState) {\n var core = (unloadCtx || {}).core();\n if (core && core[_DYN_GET_TRACE_CTX /* @min:%2egetTraceCtx */]) {\n var traceCtx = core[_DYN_GET_TRACE_CTX /* @min:%2egetTraceCtx */](false);\n if (traceCtx === _distributedTraceCtx) {\n core.setTraceCtx(_previousTraceCtx);\n }\n }\n _initDefaults();\n };\n function _initDefaults() {\n _extensionConfig = null;\n _distributedTraceCtx = null;\n _previousTraceCtx = null;\n _context = null;\n _disableUserInitMessage = true;\n }\n function _populateDefaults(config) {\n var identifier = _self.identifier;\n var core = _self.core;\n // This function will be re-called whenever any referenced configuration is changed\n _self._addHook(onConfigChange(config, function () {\n var ctx = createProcessTelemetryContext(null, config, core);\n if (config.storagePrefix) {\n utlSetStoragePrefix(config.storagePrefix);\n }\n _disableUserInitMessage = config.disableUserInitMessage === false ? false : true;\n _extensionConfig = ctx.getExtCfg(identifier, _defaultConfig);\n // Test hook to allow accessing the internal values -- explicitly not defined as an available property on the class\n _self[\"_extConfig\"] = _extensionConfig;\n }));\n // This is outside of the onConfigChange as we don't want to update (replace) these values whenever a referenced config item changes\n _previousTraceCtx = core[_DYN_GET_TRACE_CTX /* @min:%2egetTraceCtx */](false);\n _context = new TelemetryContext(core, _extensionConfig, _previousTraceCtx, _self._unloadHooks);\n _distributedTraceCtx = createDistributedTraceContextFromTrace(_self.context[_DYN_TELEMETRY_TRACE /* @min:%2etelemetryTrace */], _previousTraceCtx);\n core.setTraceCtx(_distributedTraceCtx);\n _self.context.appId = function () {\n var breezeChannel = core.getPlugin(BreezeChannelIdentifier);\n return breezeChannel ? breezeChannel.plugin[\"_appId\"] : null;\n };\n }\n function _processTelemetryInternal(evt, itemCtx) {\n // Set Part A fields\n getSetValue(evt, \"tags\", []);\n getSetValue(evt, \"ext\", {});\n var ctx = _self.context;\n ctx[_DYN_APPLY_SESSION_CONTEX0 /* @min:%2eapplySessionContext */](evt, itemCtx);\n ctx[_DYN_APPLY_APPLICATION_CO1 /* @min:%2eapplyApplicationContext */](evt, itemCtx);\n ctx.applyDeviceContext(evt, itemCtx);\n ctx[_DYN_APPLY_OPERATION_CONT2 /* @min:%2eapplyOperationContext */](evt, itemCtx);\n ctx.applyUserContext(evt, itemCtx);\n ctx[_DYN_APPLY_OPERATING_SYST3 /* @min:%2eapplyOperatingSystemContxt */](evt, itemCtx);\n ctx.applyWebContext(evt, itemCtx);\n ctx[_DYN_APPLY_LOCATION_CONTE4 /* @min:%2eapplyLocationContext */](evt, itemCtx); // legacy tags\n ctx[_DYN_APPLY_INTERNAL_CONTE5 /* @min:%2eapplyInternalContext */](evt, itemCtx); // legacy tags\n ctx.cleanUp(evt, itemCtx);\n }\n });\n return _this;\n }\n // Removed Stub for PropertiesPlugin.prototype.initialize.\n // Removed Stub for PropertiesPlugin.prototype.processTelemetry.\n // This is a workaround for an IE bug when using dynamicProto() with classes that don't have any\n // non-dynamic functions or static properties/functions when using uglify-js to minify the resulting code.\n PropertiesPlugin.__ieDyn = 1;\n return PropertiesPlugin;\n}(BaseTelemetryPlugin);\nexport default PropertiesPlugin;\n","/*\n * Application Insights JavaScript SDK - Web, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n// ###################################################################################################################################################\n// Note: DON'T Export these const from the package as we are still targeting IE/ES5 this will export a mutable variables that someone could change ###\n// ###################################################################################################################################################\n// Generally you should only put values that are used more than 2 times and then only if not already exposed as a constant (such as SdkCoreNames)\n// as when using \"short\" named values from here they will be will be minified smaller than the SdkCoreNames[eSdkCoreNames.xxxx] value.\nvar _AUTHENTICATED_USER_CONTEXT = \"AuthenticatedUserContext\";\nvar _TRACK = \"track\";\nexport var STR_EMPTY = \"\";\nexport var STR_SNIPPET = \"snippet\";\nexport var STR_GET_COOKIE_MGR = \"getCookieMgr\";\nexport var STR_START_TRACK_PAGE = \"startTrackPage\";\nexport var STR_STOP_TRACK_PAGE = \"stopTrackPage\";\nexport var STR_FLUSH = \"flush\";\nexport var STR_START_TRACK_EVENT = \"startTrackEvent\";\nexport var STR_STOP_TRACK_EVENT = \"stopTrackEvent\";\nexport var STR_ADD_TELEMETRY_INITIALIZER = \"addTelemetryInitializer\";\nexport var STR_ADD_TELEMETRY_INITIALIZERS = STR_ADD_TELEMETRY_INITIALIZER + \"s\";\nexport var STR_POLL_INTERNAL_LOGS = \"pollInternalLogs\";\nexport var STR_GET_PLUGIN = \"getPlugin\";\nexport var STR_EVT_NAMESPACE = \"evtNamespace\";\nexport var STR_TRACK_EVENT = _TRACK + \"Event\";\nexport var STR_TRACK_TRACE = _TRACK + \"Trace\";\nexport var STR_TRACK_METRIC = _TRACK + \"Metric\";\nexport var STR_TRACK_PAGE_VIEW = _TRACK + \"PageView\";\nexport var STR_TRACK_EXCEPTION = _TRACK + \"Exception\";\nexport var STR_TRACK_DEPENDENCY_DATA = _TRACK + \"DependencyData\";\nexport var STR_SET_AUTHENTICATED_USER_CONTEXT = \"set\" + _AUTHENTICATED_USER_CONTEXT;\nexport var STR_CLEAR_AUTHENTICATED_USER_CONTEXT = \"clear\" + _AUTHENTICATED_USER_CONTEXT;\nexport var CONFIG_ENDPOINT_URL = \"https://js.monitor.azure.com/scripts/b/ai.config.1.cfg.json\";\n","/*\n * Application Insights JavaScript SDK - Web, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n// @skip-file-minify\n// ##############################################################\n// AUTO GENERATED FILE: This file is Auto Generated during build.\n// ##############################################################\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n// Note: DON'T Export these const from the package as we are still targeting ES5 which can result in a mutable variables that someone could change!!!\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nexport var _DYN_VERSION = \"version\"; // Count: 6\nexport var _DYN_QUEUE = \"queue\"; // Count: 6\nexport var _DYN_CONNECTION_STRING = \"connectionString\"; // Count: 4\nexport var _DYN_INSTRUMENTATION_KEY = \"instrumentationKey\"; // Count: 5\nexport var _DYN_USER_OVERRIDE_ENDPOI0 = \"userOverrideEndpointUrl\"; // Count: 6\nexport var _DYN_ENDPOINT_URL = \"endpointUrl\"; // Count: 5\nexport var _DYN_ONUNLOAD_FLUSH = \"onunloadFlush\"; // Count: 6\nexport var _DYN_CONTEXT = \"context\"; // Count: 5\nexport var _DYN_ADD_HOUSEKEEPING_BEF1 = \"addHousekeepingBeforeUnload\"; // Count: 2\nexport var _DYN_SEND_MESSAGE = \"sendMessage\"; // Count: 3\nexport var _DYN_UPDATE_SNIPPET_DEFIN2 = \"updateSnippetDefinitions\"; // Count: 2\n","/*\n * Application Insights JavaScript SDK - Web, 3.3.6\n * Copyright (c) Microsoft and contributors. All rights reserved.\n */\n\n\"use strict\";\n\nvar _a, _b, _c, _d;\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\nimport { AnalyticsPlugin } from \"@microsoft/applicationinsights-analytics-js\";\nimport { CfgSyncPlugin } from \"@microsoft/applicationinsights-cfgsync-js\";\nimport { Sender } from \"@microsoft/applicationinsights-channel-js\";\nimport { AnalyticsPluginIdentifier, DEFAULT_BREEZE_PATH, PropertiesPluginIdentifier, ThrottleMgr, parseConnectionString } from \"@microsoft/applicationinsights-common\";\nimport { AppInsightsCore, _throwInternal, addPageHideEventListener, addPageUnloadEventListener, cfgDfMerge, cfgDfValidate, createDynamicConfig, createProcessTelemetryContext, createUniqueNamespace, doPerf, hasDocument, hasWindow, isArray, isFeatureEnabled, isFunction, isNullOrUndefined, isReactNative, isString, mergeEvtNamespace, onConfigChange, proxyAssign, proxyFunctions, removePageHideEventListener, removePageUnloadEventListener } from \"@microsoft/applicationinsights-core-js\";\nimport { AjaxPlugin as DependenciesPlugin } from \"@microsoft/applicationinsights-dependencies-js\";\nimport { PropertiesPlugin } from \"@microsoft/applicationinsights-properties-js\";\nimport { createPromise, createSyncPromise, doAwaitResponse } from \"@nevware21/ts-async\";\nimport { arrForEach, arrIndexOf, isPromiseLike, objDefine, objForEachKey, strIndexOf, throwUnsupported } from \"@nevware21/ts-utils\";\nimport { CONFIG_ENDPOINT_URL, STR_ADD_TELEMETRY_INITIALIZER, STR_CLEAR_AUTHENTICATED_USER_CONTEXT, STR_EVT_NAMESPACE, STR_FLUSH, STR_GET_COOKIE_MGR, STR_GET_PLUGIN, STR_POLL_INTERNAL_LOGS, STR_SET_AUTHENTICATED_USER_CONTEXT, STR_SNIPPET, STR_START_TRACK_EVENT, STR_START_TRACK_PAGE, STR_STOP_TRACK_EVENT, STR_STOP_TRACK_PAGE, STR_TRACK_DEPENDENCY_DATA, STR_TRACK_EVENT, STR_TRACK_EXCEPTION, STR_TRACK_METRIC, STR_TRACK_PAGE_VIEW, STR_TRACK_TRACE } from \"./InternalConstants\";\nimport { _DYN_ADD_HOUSEKEEPING_BEF1, _DYN_CONNECTION_STRING, _DYN_CONTEXT, _DYN_ENDPOINT_URL, _DYN_INSTRUMENTATION_KEY, _DYN_ONUNLOAD_FLUSH, _DYN_QUEUE, _DYN_SEND_MESSAGE, _DYN_UPDATE_SNIPPET_DEFIN2, _DYN_USER_OVERRIDE_ENDPOI0, _DYN_VERSION } from \"./__DynamicConstants\";\nvar _internalSdkSrc;\n// This is an exclude list of properties that should not be updated during initialization\n// They include a combination of private and internal property names\nvar _ignoreUpdateSnippetProperties = [STR_SNIPPET, \"dependencies\", \"properties\", \"_snippetVersion\", \"appInsightsNew\", \"getSKUDefaults\"];\nvar IKEY_USAGE = \"iKeyUsage\";\nvar CDN_USAGE = \"CdnUsage\";\nvar SDK_LOADER_VER = \"SdkLoaderVer\";\nvar UNDEFINED_VALUE = undefined;\nvar default_limit = {\n samplingRate: 100,\n maxSendNumber: 1\n};\nvar default_interval = {\n monthInterval: 3,\n daysOfMonth: [28]\n};\nvar default_throttle_config = {\n disabled: true,\n limit: cfgDfMerge(default_limit),\n interval: cfgDfMerge(default_interval)\n};\n// We need to include all properties that we only reference that we want to be dynamically updatable here\n// So they are converted even when not specified in the passed configuration\nvar defaultConfigValues = (_a = {}, _a[_DYN_CONNECTION_STRING /* @min:connectionString */] = UNDEFINED_VALUE, _a.endpointUrl = UNDEFINED_VALUE, _a[_DYN_INSTRUMENTATION_KEY /* @min:instrumentationKey */] = UNDEFINED_VALUE, _a[_DYN_USER_OVERRIDE_ENDPOI0 /* @min:userOverrideEndpointUrl */] = UNDEFINED_VALUE, _a.diagnosticLogInterval = cfgDfValidate(_chkDiagLevel, 10000), _a.featureOptIn = (_b = {}, _b[IKEY_USAGE] = {\n mode: 3 /* FeatureOptInMode.enable */\n}, _b[CDN_USAGE] = {\n mode: 2 /* FeatureOptInMode.disable */\n}, _b[SDK_LOADER_VER] = {\n mode: 2 /* FeatureOptInMode.disable */\n}, _b), _a.throttleMgrCfg = cfgDfMerge((_c = {}, _c[109 /* _eInternalMessageId.DefaultThrottleMsgKey */] = cfgDfMerge(default_throttle_config), _c[106 /* _eInternalMessageId.InstrumentationKeyDeprecation */] = cfgDfMerge(default_throttle_config), _c[111 /* _eInternalMessageId.SdkLdrUpdate */] = cfgDfMerge(default_throttle_config), _c[110 /* _eInternalMessageId.CdnDeprecation */] = cfgDfMerge(default_throttle_config), _c)), _a.extensionConfig = cfgDfMerge((_d = {}, _d[\"AppInsightsCfgSyncPlugin\"] = cfgDfMerge({\n cfgUrl: CONFIG_ENDPOINT_URL,\n syncMode: 2 /* ICfgSyncMode.Receive */\n}), _d)), _a);\nfunction _chkDiagLevel(value) {\n // Make sure we have a value > 0\n return value && value > 0;\n}\n/**\r\n * Application Insights API\r\n * @group Entrypoint\r\n * @group Classes\r\n * @class Initialization\r\n * @implements {IApplicationInsights}\r\n */\nvar AppInsightsSku = /** @class */function () {\n function AppInsightsSku(snippet) {\n var _this = this;\n // NOTE!: DON'T set default values here, instead set them in the _initDefaults() function as it is also called during teardown()\n var dependencies;\n var properties;\n var _sender;\n var _snippetVersion;\n var _evtNamespace;\n var _houseKeepingNamespace;\n var _core;\n var _config;\n var _analyticsPlugin;\n var _cfgSyncPlugin;\n var _throttleMgr;\n var _iKeySentMessage;\n var _cdnSentMessage;\n var _sdkVerSentMessage;\n dynamicProto(AppInsightsSku, this, function (_self) {\n _initDefaults();\n objDefine(_self, \"config\", {\n g: function () {\n return _config;\n }\n });\n arrForEach([\"pluginVersionStringArr\", \"pluginVersionString\"], function (key) {\n objDefine(_self, key, {\n g: function () {\n if (_core) {\n return _core[key];\n }\n return null;\n }\n });\n });\n // initialize the queue and config in case they are undefined\n _snippetVersion = \"\" + (snippet.sv || snippet[_DYN_VERSION /* @min:%2eversion */] || \"\");\n snippet[_DYN_QUEUE /* @min:%2equeue */] = snippet[_DYN_QUEUE /* @min:%2equeue */] || [];\n snippet[_DYN_VERSION /* @min:%2eversion */] = snippet[_DYN_VERSION /* @min:%2eversion */] || 2.0; // Default to new version\n var cfgHandler = createDynamicConfig(snippet.config || {}, defaultConfigValues);\n _config = cfgHandler.cfg;\n _analyticsPlugin = new AnalyticsPlugin();\n objDefine(_self, \"appInsights\", {\n g: function () {\n return _analyticsPlugin;\n }\n });\n properties = new PropertiesPlugin();\n dependencies = new DependenciesPlugin();\n _sender = new Sender();\n _core = new AppInsightsCore();\n objDefine(_self, \"core\", {\n g: function () {\n return _core;\n }\n });\n // Will get recalled if any referenced values are changed\n _addUnloadHook(onConfigChange(cfgHandler, function () {\n var configCs = _config[_DYN_CONNECTION_STRING /* @min:%2econnectionString */];\n function _parseCs() {\n return createSyncPromise(function (resolve, reject) {\n doAwaitResponse(configCs, function (res) {\n var curCs = res && res.value;\n var parsedCs = null;\n if (!res.rejected && curCs) {\n // replace cs with resolved values in case of circular promises\n _config[_DYN_CONNECTION_STRING /* @min:%2econnectionString */] = curCs;\n parsedCs = parseConnectionString(curCs);\n }\n // if can't resolve cs promise, null will be returned\n resolve(parsedCs);\n });\n });\n }\n if (isPromiseLike(configCs)) {\n var ikeyPromise = createSyncPromise(function (resolve, reject) {\n _parseCs().then(function (cs) {\n var ikey = _config[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */];\n ikey = cs && cs.instrumentationkey || ikey;\n resolve(ikey);\n }).catch(function (e) {\n // parseCs will always resolve(unless timeout)\n // return null in case any error happens\n resolve(null);\n });\n });\n var url = _config[_DYN_USER_OVERRIDE_ENDPOI0 /* @min:%2euserOverrideEndpointUrl */];\n if (isNullOrUndefined(url)) {\n url = createSyncPromise(function (resolve, reject) {\n _parseCs().then(function (cs) {\n var url = _config[_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */];\n var ingest = cs && cs.ingestionendpoint;\n url = ingest ? ingest + DEFAULT_BREEZE_PATH : url;\n resolve(url);\n }).catch(function (e) {\n // parseCs will always resolve(unless timeout)\n // return null in case any error happens\n resolve(null);\n });\n });\n }\n _config[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */] = ikeyPromise;\n _config[_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */] = url;\n }\n if (isString(configCs) && configCs) {\n // confirm if promiselike function present\n // handle cs promise here\n // add cases to oneNote\n var cs = parseConnectionString(configCs);\n var ingest = cs.ingestionendpoint;\n _config.endpointUrl = _config[_DYN_USER_OVERRIDE_ENDPOI0 /* @min:%2euserOverrideEndpointUrl */] ? _config[_DYN_USER_OVERRIDE_ENDPOI0 /* @min:%2euserOverrideEndpointUrl */] : ingest + DEFAULT_BREEZE_PATH; // add /v2/track\n _config[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */] = cs.instrumentationkey || _config[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */];\n }\n // userOverrideEndpointUrl have the highest priority\n _config.endpointUrl = _config[_DYN_USER_OVERRIDE_ENDPOI0 /* @min:%2euserOverrideEndpointUrl */] ? _config[_DYN_USER_OVERRIDE_ENDPOI0 /* @min:%2euserOverrideEndpointUrl */] : _config[_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */];\n }));\n _self[STR_SNIPPET /* @min:%2esnippet */] = snippet;\n _self[STR_FLUSH /* @min:%2eflush */] = function (async, callBack) {\n if (async === void 0) {\n async = true;\n }\n var result;\n doPerf(_core, function () {\n return \"AISKU.flush\";\n }, function () {\n if (async && !callBack) {\n result = createPromise(function (resolve) {\n callBack = resolve;\n });\n }\n var waiting = 1;\n var flushDone = function () {\n waiting--;\n if (waiting === 0) {\n callBack();\n }\n };\n arrForEach(_core.getChannels(), function (channel) {\n if (channel) {\n waiting++;\n channel[STR_FLUSH /* @min:%2eflush */](async, flushDone);\n }\n });\n // decrement the initial \"waiting\"\n flushDone();\n }, null, async);\n return result;\n };\n _self[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */] = function (async) {\n if (async === void 0) {\n async = true;\n }\n arrForEach(_core.getChannels(), function (channel) {\n if (channel[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */]) {\n channel[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */]();\n } else {\n channel[STR_FLUSH /* @min:%2eflush */](async);\n }\n });\n };\n _self.loadAppInsights = function (legacyMode, logger, notificationManager) {\n if (legacyMode === void 0) {\n legacyMode = false;\n }\n if (legacyMode) {\n throwUnsupported(\"Legacy Mode is no longer supported\");\n }\n function _updateSnippetProperties(snippet) {\n if (snippet) {\n var snippetVer = \"\";\n if (!isNullOrUndefined(_snippetVersion)) {\n snippetVer += _snippetVersion;\n }\n if (_self[_DYN_CONTEXT /* @min:%2econtext */] && _self[_DYN_CONTEXT /* @min:%2econtext */].internal) {\n _self[_DYN_CONTEXT /* @min:%2econtext */].internal.snippetVer = snippetVer || \"-\";\n }\n // apply updated properties to the global instance (snippet)\n objForEachKey(_self, function (field, value) {\n if (isString(field) && !isFunction(value) && field && field[0] !== \"_\" &&\n // Don't copy \"internal\" values\n arrIndexOf(_ignoreUpdateSnippetProperties, field) === -1) {\n if (snippet[field] !== value) {\n snippet[field] = value;\n }\n }\n });\n }\n }\n doPerf(_self.core, function () {\n return \"AISKU.loadAppInsights\";\n }, function () {\n // initialize core\n _core.initialize(_config, [_sender, properties, dependencies, _analyticsPlugin, _cfgSyncPlugin], logger, notificationManager);\n objDefine(_self, \"context\", {\n g: function () {\n return properties[_DYN_CONTEXT /* @min:%2econtext */];\n }\n });\n if (!_throttleMgr) {\n _throttleMgr = new ThrottleMgr(_core);\n }\n var sdkSrc = _findSdkSourceFile();\n if (sdkSrc && _self[_DYN_CONTEXT /* @min:%2econtext */]) {\n _self[_DYN_CONTEXT /* @min:%2econtext */].internal.sdkSrc = sdkSrc;\n }\n _updateSnippetProperties(_self[STR_SNIPPET /* @min:%2esnippet */]);\n // Empty queue of all api calls logged prior to sdk download\n _self.emptyQueue();\n _self[STR_POLL_INTERNAL_LOGS /* @min:%2epollInternalLogs */]();\n _self[_DYN_ADD_HOUSEKEEPING_BEF1 /* @min:%2eaddHousekeepingBeforeUnload */](_self);\n _addUnloadHook(onConfigChange(cfgHandler, function () {\n var defaultEnable = false;\n if (_config.throttleMgrCfg[109 /* _eInternalMessageId.DefaultThrottleMsgKey */]) {\n defaultEnable = !_config.throttleMgrCfg[109 /* _eInternalMessageId.DefaultThrottleMsgKey */].disabled;\n }\n if (!_throttleMgr.isReady() && _config.extensionConfig && _config.extensionConfig[_cfgSyncPlugin.identifier] && defaultEnable) {\n // set ready state to true will automatically trigger flush()\n _throttleMgr.onReadyState(true);\n }\n if (!_iKeySentMessage && !_config[_DYN_CONNECTION_STRING /* @min:%2econnectionString */] && isFeatureEnabled(IKEY_USAGE, _config)) {\n _throttleMgr[_DYN_SEND_MESSAGE /* @min:%2esendMessage */](106 /* _eInternalMessageId.InstrumentationKeyDeprecation */, \"See Instrumentation key support at aka.ms/IkeyMigrate\");\n _iKeySentMessage = true;\n }\n if (!_cdnSentMessage && _self[_DYN_CONTEXT /* @min:%2econtext */].internal.sdkSrc && _self[_DYN_CONTEXT /* @min:%2econtext */].internal.sdkSrc.indexOf(\"az416426\") != -1 && isFeatureEnabled(CDN_USAGE, _config)) {\n _throttleMgr[_DYN_SEND_MESSAGE /* @min:%2esendMessage */](110 /* _eInternalMessageId.CdnDeprecation */, \"See Cdn support notice at aka.ms/JsActiveCdn\");\n _cdnSentMessage = true;\n }\n if (!_sdkVerSentMessage && parseInt(_snippetVersion) < 6 && isFeatureEnabled(SDK_LOADER_VER, _config)) {\n _throttleMgr[_DYN_SEND_MESSAGE /* @min:%2esendMessage */](111 /* _eInternalMessageId.SdkLdrUpdate */, \"An updated Sdk Loader is available, see aka.ms/SnippetVer\");\n _sdkVerSentMessage = true;\n }\n }));\n });\n return _self;\n };\n _self[_DYN_UPDATE_SNIPPET_DEFIN2 /* @min:%2eupdateSnippetDefinitions */] = function (snippet) {\n // apply full appInsights to the global instance\n // Note: This must be called before loadAppInsights is called\n proxyAssign(snippet, _self, function (name) {\n // Not excluding names prefixed with \"_\" as we need to proxy some functions like _onError\n return name && arrIndexOf(_ignoreUpdateSnippetProperties, name) === -1;\n });\n };\n _self.emptyQueue = function () {\n // call functions that were queued before the main script was loaded\n try {\n if (isArray(_self.snippet[_DYN_QUEUE /* @min:%2equeue */])) {\n // note: do not check length in the for-loop conditional in case something goes wrong and the stub methods are not overridden.\n var length_1 = _self.snippet[_DYN_QUEUE /* @min:%2equeue */].length;\n for (var i = 0; i < length_1; i++) {\n var call = _self.snippet[_DYN_QUEUE /* @min:%2equeue */][i];\n call();\n }\n _self.snippet[_DYN_QUEUE /* @min:%2equeue */] = undefined;\n delete _self.snippet[_DYN_QUEUE /* @min:%2equeue */];\n }\n } catch (exception) {\n var properties_1 = {};\n if (exception && isFunction(exception.toString)) {\n properties_1.exception = exception.toString();\n }\n // need from core\n // Microsoft.ApplicationInsights._InternalLogging.throwInternal(\n // eLoggingSeverity.WARNING,\n // _eInternalMessageId.FailedToSendQueuedTelemetry,\n // \"Failed to send queued telemetry\",\n // properties);\n }\n };\n _self[_DYN_ADD_HOUSEKEEPING_BEF1 /* @min:%2eaddHousekeepingBeforeUnload */] = function (appInsightsInstance) {\n // Add callback to push events when the user navigates away\n if (hasWindow() || hasDocument()) {\n var performHousekeeping_1 = function () {\n // Adds the ability to flush all data before the page unloads.\n // Note: This approach tries to push a sync request with all the pending events onbeforeunload.\n // Firefox does not respect this.Other browsers DO push out the call with < 100% hit rate.\n // Telemetry here will help us analyze how effective this approach is.\n // Another approach would be to make this call sync with a acceptable timeout to reduce the\n // impact on user experience.\n // appInsightsInstance.context._sender.triggerSend();\n appInsightsInstance[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */](false);\n // Back up the current session to local storage\n // This lets us close expired sessions after the cookies themselves expire\n if (isFunction(_self.core[STR_GET_PLUGIN /* @min:%2egetPlugin */])) {\n var loadedPlugin = _this.core[STR_GET_PLUGIN /* @min:%2egetPlugin */](PropertiesPluginIdentifier);\n if (loadedPlugin) {\n var propertiesPlugin = loadedPlugin.plugin;\n if (propertiesPlugin && propertiesPlugin[_DYN_CONTEXT /* @min:%2econtext */] && propertiesPlugin[_DYN_CONTEXT /* @min:%2econtext */]._sessionManager) {\n propertiesPlugin[_DYN_CONTEXT /* @min:%2econtext */]._sessionManager.backup();\n }\n }\n }\n };\n var added_1 = false;\n if (!_houseKeepingNamespace) {\n _houseKeepingNamespace = mergeEvtNamespace(_evtNamespace, _core[STR_EVT_NAMESPACE /* @min:%2eevtNamespace */] && _core[STR_EVT_NAMESPACE /* @min:%2eevtNamespace */]());\n }\n // Will be recalled if any referenced config properties change\n _addUnloadHook(onConfigChange(_config, function (details) {\n var coreConfig = details.cfg;\n var analyticsPlugin = appInsightsInstance.appInsights;\n var ctx = createProcessTelemetryContext(null, coreConfig, analyticsPlugin.core);\n var extConfig = ctx.getExtCfg(analyticsPlugin.identifier || AnalyticsPluginIdentifier);\n // As we could get recalled, remove any previously registered event handlers first\n _removePageEventHandlers();\n var excludePageUnloadEvents = coreConfig.disablePageUnloadEvents;\n if (!extConfig.disableFlushOnBeforeUnload) {\n // Hook the unload event for the document, window and body to ensure that the client events are flushed to the server\n // As just hooking the window does not always fire (on chrome) for page navigation's.\n if (addPageUnloadEventListener(performHousekeeping_1, excludePageUnloadEvents, _houseKeepingNamespace)) {\n added_1 = true;\n }\n // We also need to hook the pagehide and visibilitychange events as not all versions of Safari support load/unload events.\n if (addPageHideEventListener(performHousekeeping_1, excludePageUnloadEvents, _houseKeepingNamespace)) {\n added_1 = true;\n }\n // A reactNative app may not have a window and therefore the beforeunload/pagehide events -- so don't\n // log the failure in this case\n if (!added_1 && !isReactNative()) {\n _throwInternal(_core.logger, 1 /* eLoggingSeverity.CRITICAL */, 19 /* _eInternalMessageId.FailedToAddHandlerForOnBeforeUnload */, \"Could not add handler for beforeunload and pagehide\");\n }\n }\n if (!added_1 && !extConfig.disableFlushOnUnload) {\n // If we didn't add the normal set then attempt to add the pagehide and visibilitychange only\n addPageHideEventListener(performHousekeeping_1, excludePageUnloadEvents, _houseKeepingNamespace);\n }\n }));\n }\n };\n _self.getSender = function () {\n return _sender;\n };\n _self.unload = function (isAsync, unloadComplete, cbTimeout) {\n var unloadDone = false;\n var result;\n if (isAsync && !unloadComplete) {\n result = createPromise(function (resolve) {\n // Set the callback to the promise resolve callback\n unloadComplete = resolve;\n });\n }\n function _unloadCallback(unloadState) {\n if (!unloadDone) {\n unloadDone = true;\n _initDefaults();\n unloadComplete && unloadComplete(unloadState);\n }\n }\n _self[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */](isAsync);\n _removePageEventHandlers();\n _core.unload && _core.unload(isAsync, _unloadCallback, cbTimeout);\n return result;\n };\n proxyFunctions(_self, _analyticsPlugin, [STR_GET_COOKIE_MGR, STR_TRACK_EVENT, STR_TRACK_PAGE_VIEW, \"trackPageViewPerformance\", STR_TRACK_EXCEPTION, \"_onerror\", STR_TRACK_TRACE, STR_TRACK_METRIC, STR_START_TRACK_PAGE, STR_STOP_TRACK_PAGE, STR_START_TRACK_EVENT, STR_STOP_TRACK_EVENT]);\n proxyFunctions(_self, _getCurrentDependencies, [STR_TRACK_DEPENDENCY_DATA, \"addDependencyListener\", \"addDependencyInitializer\"]);\n proxyFunctions(_self, _core, [STR_ADD_TELEMETRY_INITIALIZER, STR_POLL_INTERNAL_LOGS, \"stopPollingInternalLogs\", STR_GET_PLUGIN, \"addPlugin\", STR_EVT_NAMESPACE, \"addUnloadCb\", \"getTraceCtx\", \"updateCfg\", \"onCfgChange\"]);\n proxyFunctions(_self, function () {\n var context = properties[_DYN_CONTEXT /* @min:%2econtext */];\n return context ? context.user : null;\n }, [STR_SET_AUTHENTICATED_USER_CONTEXT, STR_CLEAR_AUTHENTICATED_USER_CONTEXT]);\n // Using a function to support the dynamic adding / removal of plugins, so this will always return the current value\n function _getCurrentDependencies() {\n return dependencies;\n }\n function _initDefaults() {\n _evtNamespace = createUniqueNamespace(\"AISKU\");\n _houseKeepingNamespace = null;\n dependencies = null;\n properties = null;\n _sender = null;\n _snippetVersion = null;\n _throttleMgr = null;\n _iKeySentMessage = false;\n _cdnSentMessage = false;\n _sdkVerSentMessage = false;\n _cfgSyncPlugin = new CfgSyncPlugin();\n }\n function _removePageEventHandlers() {\n // Remove any registered event handlers\n if (_houseKeepingNamespace) {\n removePageUnloadEventListener(null, _houseKeepingNamespace);\n removePageHideEventListener(null, _houseKeepingNamespace);\n }\n }\n function _addUnloadHook(hooks) {\n _core.addUnloadHook(hooks);\n }\n });\n }\n // Analytics Plugin\n // Removed Stub for AppInsightsSku.prototype.getCookieMgr.\n // Removed Stub for AppInsightsSku.prototype.trackEvent.\n // Removed Stub for AppInsightsSku.prototype.trackPageView.\n // Removed Stub for AppInsightsSku.prototype.trackPageViewPerformance.\n // Removed Stub for AppInsightsSku.prototype.trackException.\n // Removed Stub for AppInsightsSku.prototype._onerror.\n // Removed Stub for AppInsightsSku.prototype.trackTrace.\n // Removed Stub for AppInsightsSku.prototype.trackMetric.\n // Removed Stub for AppInsightsSku.prototype.startTrackPage.\n // Removed Stub for AppInsightsSku.prototype.stopTrackPage.\n // Removed Stub for AppInsightsSku.prototype.startTrackEvent.\n // Removed Stub for AppInsightsSku.prototype.stopTrackEvent.\n // Removed Stub for AppInsightsSku.prototype.addTelemetryInitializer.\n // Properties Plugin\n // Removed Stub for AppInsightsSku.prototype.setAuthenticatedUserContext.\n // Removed Stub for AppInsightsSku.prototype.clearAuthenticatedUserContext.\n // Dependencies Plugin\n // Removed Stub for AppInsightsSku.prototype.trackDependencyData.\n // Misc\n // Removed Stub for AppInsightsSku.prototype.flush.\n // Removed Stub for AppInsightsSku.prototype.onunloadFlush.\n // Removed Stub for AppInsightsSku.prototype.loadAppInsights.\n // Removed Stub for AppInsightsSku.prototype.updateSnippetDefinitions.\n // Removed Stub for AppInsightsSku.prototype.emptyQueue.\n // Removed Stub for AppInsightsSku.prototype.pollInternalLogs.\n // Removed Stub for AppInsightsSku.prototype.stopPollingInternalLogs.\n // Removed Stub for AppInsightsSku.prototype.addHousekeepingBeforeUnload.\n // Removed Stub for AppInsightsSku.prototype.getSender.\n // Removed Stub for AppInsightsSku.prototype.unload.\n // Removed Stub for AppInsightsSku.prototype.getPlugin.\n // Removed Stub for AppInsightsSku.prototype.addPlugin.\n // Removed Stub for AppInsightsSku.prototype.updateCfg.\n // Removed Stub for AppInsightsSku.prototype.evtNamespace.\n // Removed Stub for AppInsightsSku.prototype.addUnloadCb.\n // Removed Stub for AppInsightsSku.prototype.addDependencyListener.\n /**\r\n * Add an dependency telemetry initializer callback function to allow populating additional properties or drop the request.\r\n * It is called after the dependency call has completed and any available performance details are available. A dependency\r\n * initializer is similar to the TelemetryInitializer function but it allows you to block the reporting of the dependency\r\n * request so that it doesn't count against the `maxAjaxCallsPerView`.\r\n * @param dependencyInitializer - The Dependency Telemetry Initializer function\r\n * @returns - A IDependencyInitializerHandler to enable the initializer to be removed\r\n */\n AppInsightsSku.prototype.addDependencyInitializer = function (dependencyInitializer) {\n return null;\n };\n // Removed Stub for AppInsightsSku.prototype.getTraceCtx.\n // Removed Stub for AppInsightsSku.prototype.onCfgChange.\n return AppInsightsSku;\n}();\nexport { AppInsightsSku };\n// tslint:disable-next-line\nexport function _findSdkSourceFile() {\n if (_internalSdkSrc) {\n // Use the cached value\n return _internalSdkSrc;\n }\n var sdkSrc = null;\n var isModule = false;\n var cdns = [\"://js.monitor.azure.com/\", \"://az416426.vo.msecnd.net/\"];\n try {\n // Try and determine whether the sdk is being loaded from the CDN\n // currentScript is only valid during initial processing\n var scrpt = (document || {}).currentScript;\n if (scrpt) {\n sdkSrc = scrpt.src;\n // } else {\n // // We need to update to at least typescript 2.9 for this to work :-(\n // // Leaving as a stub for now so after we upgrade this breadcrumb is available\n // let meta = import.meta;\n // sdkSrc = (meta || {}).url;\n // isModule = true;\n }\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n if (sdkSrc) {\n try {\n var url_1 = sdkSrc.toLowerCase();\n if (url_1) {\n var src_1 = \"\";\n arrForEach(cdns, function (value, idx) {\n if (strIndexOf(url_1, value) !== -1) {\n src_1 = \"cdn\" + (idx + 1);\n if (strIndexOf(url_1, \"/scripts/\") === -1) {\n if (strIndexOf(url_1, \"/next/\") !== -1) {\n src_1 += \"-next\";\n } else if (strIndexOf(url_1, \"/beta/\") !== -1) {\n src_1 += \"-beta\";\n }\n }\n _internalSdkSrc = src_1 + (isModule ? \".mod\" : \"\");\n return -1;\n }\n });\n }\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n // Cache the found value so we don't have to look it up again\n _internalSdkSrc = sdkSrc;\n }\n return _internalSdkSrc;\n}\n","import { Injectable } from '@angular/core';\r\nimport { ApplicationInsights, ICustomProperties } from '@microsoft/applicationinsights-web';\r\n\r\nimport { environment } from '../../../environments/environment';\r\n\r\n@Injectable()\r\nexport class LoggingService {\r\n appInsights: ApplicationInsights;\r\n\r\n constructor() {\r\n this.appInsights = new ApplicationInsights({\r\n config: {\r\n connectionString: environment.appInsightsConnectionString,\r\n enableAutoRouteTracking: true // option to log all route changes\r\n }\r\n });\r\n\r\n this.appInsights.loadAppInsights();\r\n this.appInsights.trackPageView();\r\n }\r\n\r\n logPageView(name?: string, url?: string) { // option to call manually\r\n this.appInsights.trackPageView({\r\n name: name,\r\n uri: url\r\n });\r\n }\r\n\r\n logEvent(name: string, customProperties?: ICustomProperties) {\r\n this.appInsights.trackEvent({ name: name }, customProperties);\r\n }\r\n\r\n logMetric(name: string, average: number, customProperties?: ICustomProperties) {\r\n this.appInsights.trackMetric({ name: name, average: average }, customProperties);\r\n }\r\n\r\n logException(exception: Error, severityLevel?: number) {\r\n this.appInsights.trackException({ exception: exception, severityLevel: severityLevel });\r\n }\r\n\r\n logTrace(message: string, customProperties?: ICustomProperties) {\r\n this.appInsights.trackTrace({ message: message }, customProperties);\r\n }\r\n}\r\n","import { Component } from '@angular/core';\r\nimport { RouterOutlet } from '@angular/router';\r\n\r\nimport { LoggingService } from './core/services/logging.service';\r\n\r\n@Component({\r\n selector: 'app-root',\r\n templateUrl: './app.component.html',\r\n standalone: true,\r\n imports: [RouterOutlet]\r\n})\r\nexport class AppComponent {\r\n constructor(private loggingService: LoggingService) {\r\n this.loggingService.logEvent('Session started');\r\n }\r\n}\r\n","\r\n\r\n","/*!\n * perfect-scrollbar v1.5.6\n * Copyright 2024 Hyunje Jun, MDBootstrap and Contributors\n * Licensed under MIT\n */\n\nfunction get(element) {\n return getComputedStyle(element);\n}\nfunction set(element, obj) {\n for (var key in obj) {\n var val = obj[key];\n if (typeof val === 'number') {\n val = val + \"px\";\n }\n element.style[key] = val;\n }\n return element;\n}\nfunction div(className) {\n var div = document.createElement('div');\n div.className = className;\n return div;\n}\nvar elMatches = typeof Element !== 'undefined' && (Element.prototype.matches || Element.prototype.webkitMatchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector);\nfunction matches(element, query) {\n if (!elMatches) {\n throw new Error('No element matching method supported');\n }\n return elMatches.call(element, query);\n}\nfunction remove(element) {\n if (element.remove) {\n element.remove();\n } else {\n if (element.parentNode) {\n element.parentNode.removeChild(element);\n }\n }\n}\nfunction queryChildren(element, selector) {\n return Array.prototype.filter.call(element.children, function (child) {\n return matches(child, selector);\n });\n}\nvar cls = {\n main: 'ps',\n rtl: 'ps__rtl',\n element: {\n thumb: function (x) {\n return \"ps__thumb-\" + x;\n },\n rail: function (x) {\n return \"ps__rail-\" + x;\n },\n consuming: 'ps__child--consume'\n },\n state: {\n focus: 'ps--focus',\n clicking: 'ps--clicking',\n active: function (x) {\n return \"ps--active-\" + x;\n },\n scrolling: function (x) {\n return \"ps--scrolling-\" + x;\n }\n }\n};\n\n/*\n * Helper methods\n */\nvar scrollingClassTimeout = {\n x: null,\n y: null\n};\nfunction addScrollingClass(i, x) {\n var classList = i.element.classList;\n var className = cls.state.scrolling(x);\n if (classList.contains(className)) {\n clearTimeout(scrollingClassTimeout[x]);\n } else {\n classList.add(className);\n }\n}\nfunction removeScrollingClass(i, x) {\n scrollingClassTimeout[x] = setTimeout(function () {\n return i.isAlive && i.element.classList.remove(cls.state.scrolling(x));\n }, i.settings.scrollingThreshold);\n}\nfunction setScrollingClassInstantly(i, x) {\n addScrollingClass(i, x);\n removeScrollingClass(i, x);\n}\nvar EventElement = function EventElement(element) {\n this.element = element;\n this.handlers = {};\n};\nvar prototypeAccessors = {\n isEmpty: {\n configurable: true\n }\n};\nEventElement.prototype.bind = function bind(eventName, handler) {\n if (typeof this.handlers[eventName] === 'undefined') {\n this.handlers[eventName] = [];\n }\n this.handlers[eventName].push(handler);\n this.element.addEventListener(eventName, handler, false);\n};\nEventElement.prototype.unbind = function unbind(eventName, target) {\n var this$1 = this;\n this.handlers[eventName] = this.handlers[eventName].filter(function (handler) {\n if (target && handler !== target) {\n return true;\n }\n this$1.element.removeEventListener(eventName, handler, false);\n return false;\n });\n};\nEventElement.prototype.unbindAll = function unbindAll() {\n for (var name in this.handlers) {\n this.unbind(name);\n }\n};\nprototypeAccessors.isEmpty.get = function () {\n var this$1 = this;\n return Object.keys(this.handlers).every(function (key) {\n return this$1.handlers[key].length === 0;\n });\n};\nObject.defineProperties(EventElement.prototype, prototypeAccessors);\nvar EventManager = function EventManager() {\n this.eventElements = [];\n};\nEventManager.prototype.eventElement = function eventElement(element) {\n var ee = this.eventElements.filter(function (ee) {\n return ee.element === element;\n })[0];\n if (!ee) {\n ee = new EventElement(element);\n this.eventElements.push(ee);\n }\n return ee;\n};\nEventManager.prototype.bind = function bind(element, eventName, handler) {\n this.eventElement(element).bind(eventName, handler);\n};\nEventManager.prototype.unbind = function unbind(element, eventName, handler) {\n var ee = this.eventElement(element);\n ee.unbind(eventName, handler);\n if (ee.isEmpty) {\n // remove\n this.eventElements.splice(this.eventElements.indexOf(ee), 1);\n }\n};\nEventManager.prototype.unbindAll = function unbindAll() {\n this.eventElements.forEach(function (e) {\n return e.unbindAll();\n });\n this.eventElements = [];\n};\nEventManager.prototype.once = function once(element, eventName, handler) {\n var ee = this.eventElement(element);\n var onceHandler = function (evt) {\n ee.unbind(eventName, onceHandler);\n handler(evt);\n };\n ee.bind(eventName, onceHandler);\n};\nfunction createEvent(name) {\n if (typeof window.CustomEvent === 'function') {\n return new CustomEvent(name);\n }\n var evt = document.createEvent('CustomEvent');\n evt.initCustomEvent(name, false, false, undefined);\n return evt;\n}\nfunction processScrollDiff(i, axis, diff, useScrollingClass, forceFireReachEvent) {\n if (useScrollingClass === void 0) useScrollingClass = true;\n if (forceFireReachEvent === void 0) forceFireReachEvent = false;\n var fields;\n if (axis === 'top') {\n fields = ['contentHeight', 'containerHeight', 'scrollTop', 'y', 'up', 'down'];\n } else if (axis === 'left') {\n fields = ['contentWidth', 'containerWidth', 'scrollLeft', 'x', 'left', 'right'];\n } else {\n throw new Error('A proper axis should be provided');\n }\n processScrollDiff$1(i, diff, fields, useScrollingClass, forceFireReachEvent);\n}\nfunction processScrollDiff$1(i, diff, ref, useScrollingClass, forceFireReachEvent) {\n var contentHeight = ref[0];\n var containerHeight = ref[1];\n var scrollTop = ref[2];\n var y = ref[3];\n var up = ref[4];\n var down = ref[5];\n if (useScrollingClass === void 0) useScrollingClass = true;\n if (forceFireReachEvent === void 0) forceFireReachEvent = false;\n var element = i.element;\n\n // reset reach\n i.reach[y] = null;\n\n // 1 for subpixel rounding\n if (element[scrollTop] < 1) {\n i.reach[y] = 'start';\n }\n\n // 1 for subpixel rounding\n if (element[scrollTop] > i[contentHeight] - i[containerHeight] - 1) {\n i.reach[y] = 'end';\n }\n if (diff) {\n element.dispatchEvent(createEvent(\"ps-scroll-\" + y));\n if (diff < 0) {\n element.dispatchEvent(createEvent(\"ps-scroll-\" + up));\n } else if (diff > 0) {\n element.dispatchEvent(createEvent(\"ps-scroll-\" + down));\n }\n if (useScrollingClass) {\n setScrollingClassInstantly(i, y);\n }\n }\n if (i.reach[y] && (diff || forceFireReachEvent)) {\n element.dispatchEvent(createEvent(\"ps-\" + y + \"-reach-\" + i.reach[y]));\n }\n}\nfunction toInt(x) {\n return parseInt(x, 10) || 0;\n}\nfunction isEditable(el) {\n return matches(el, 'input,[contenteditable]') || matches(el, 'select,[contenteditable]') || matches(el, 'textarea,[contenteditable]') || matches(el, 'button,[contenteditable]');\n}\nfunction outerWidth(element) {\n var styles = get(element);\n return toInt(styles.width) + toInt(styles.paddingLeft) + toInt(styles.paddingRight) + toInt(styles.borderLeftWidth) + toInt(styles.borderRightWidth);\n}\nvar env = {\n isWebKit: typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style,\n supportsTouch: typeof window !== 'undefined' && ('ontouchstart' in window || 'maxTouchPoints' in window.navigator && window.navigator.maxTouchPoints > 0 || window.DocumentTouch && document instanceof window.DocumentTouch),\n supportsIePointer: typeof navigator !== 'undefined' && navigator.msMaxTouchPoints,\n isChrome: typeof navigator !== 'undefined' && /Chrome/i.test(navigator && navigator.userAgent)\n};\n\n/* eslint-disable no-lonely-if */\n\nfunction updateGeometry(i) {\n var element = i.element;\n var roundedScrollTop = Math.floor(element.scrollTop);\n var rect = element.getBoundingClientRect();\n i.containerWidth = Math.floor(rect.width);\n i.containerHeight = Math.floor(rect.height);\n i.contentWidth = element.scrollWidth;\n i.contentHeight = element.scrollHeight;\n if (!element.contains(i.scrollbarXRail)) {\n // clean up and append\n queryChildren(element, cls.element.rail('x')).forEach(function (el) {\n return remove(el);\n });\n element.appendChild(i.scrollbarXRail);\n }\n if (!element.contains(i.scrollbarYRail)) {\n // clean up and append\n queryChildren(element, cls.element.rail('y')).forEach(function (el) {\n return remove(el);\n });\n element.appendChild(i.scrollbarYRail);\n }\n if (!i.settings.suppressScrollX && i.containerWidth + i.settings.scrollXMarginOffset < i.contentWidth) {\n i.scrollbarXActive = true;\n i.railXWidth = i.containerWidth - i.railXMarginWidth;\n i.railXRatio = i.containerWidth / i.railXWidth;\n i.scrollbarXWidth = getThumbSize(i, toInt(i.railXWidth * i.containerWidth / i.contentWidth));\n i.scrollbarXLeft = toInt((i.negativeScrollAdjustment + element.scrollLeft) * (i.railXWidth - i.scrollbarXWidth) / (i.contentWidth - i.containerWidth));\n } else {\n i.scrollbarXActive = false;\n }\n if (!i.settings.suppressScrollY && i.containerHeight + i.settings.scrollYMarginOffset < i.contentHeight) {\n i.scrollbarYActive = true;\n i.railYHeight = i.containerHeight - i.railYMarginHeight;\n i.railYRatio = i.containerHeight / i.railYHeight;\n i.scrollbarYHeight = getThumbSize(i, toInt(i.railYHeight * i.containerHeight / i.contentHeight));\n i.scrollbarYTop = toInt(roundedScrollTop * (i.railYHeight - i.scrollbarYHeight) / (i.contentHeight - i.containerHeight));\n } else {\n i.scrollbarYActive = false;\n }\n if (i.scrollbarXLeft >= i.railXWidth - i.scrollbarXWidth) {\n i.scrollbarXLeft = i.railXWidth - i.scrollbarXWidth;\n }\n if (i.scrollbarYTop >= i.railYHeight - i.scrollbarYHeight) {\n i.scrollbarYTop = i.railYHeight - i.scrollbarYHeight;\n }\n updateCss(element, i);\n if (i.scrollbarXActive) {\n element.classList.add(cls.state.active('x'));\n } else {\n element.classList.remove(cls.state.active('x'));\n i.scrollbarXWidth = 0;\n i.scrollbarXLeft = 0;\n element.scrollLeft = i.isRtl === true ? i.contentWidth : 0;\n }\n if (i.scrollbarYActive) {\n element.classList.add(cls.state.active('y'));\n } else {\n element.classList.remove(cls.state.active('y'));\n i.scrollbarYHeight = 0;\n i.scrollbarYTop = 0;\n element.scrollTop = 0;\n }\n}\nfunction getThumbSize(i, thumbSize) {\n if (i.settings.minScrollbarLength) {\n thumbSize = Math.max(thumbSize, i.settings.minScrollbarLength);\n }\n if (i.settings.maxScrollbarLength) {\n thumbSize = Math.min(thumbSize, i.settings.maxScrollbarLength);\n }\n return thumbSize;\n}\nfunction updateCss(element, i) {\n var xRailOffset = {\n width: i.railXWidth\n };\n var roundedScrollTop = Math.floor(element.scrollTop);\n if (i.isRtl) {\n xRailOffset.left = i.negativeScrollAdjustment + element.scrollLeft + i.containerWidth - i.contentWidth;\n } else {\n xRailOffset.left = element.scrollLeft;\n }\n if (i.isScrollbarXUsingBottom) {\n xRailOffset.bottom = i.scrollbarXBottom - roundedScrollTop;\n } else {\n xRailOffset.top = i.scrollbarXTop + roundedScrollTop;\n }\n set(i.scrollbarXRail, xRailOffset);\n var yRailOffset = {\n top: roundedScrollTop,\n height: i.railYHeight\n };\n if (i.isScrollbarYUsingRight) {\n if (i.isRtl) {\n yRailOffset.right = i.contentWidth - (i.negativeScrollAdjustment + element.scrollLeft) - i.scrollbarYRight - i.scrollbarYOuterWidth - 9;\n } else {\n yRailOffset.right = i.scrollbarYRight - element.scrollLeft;\n }\n } else {\n if (i.isRtl) {\n yRailOffset.left = i.negativeScrollAdjustment + element.scrollLeft + i.containerWidth * 2 - i.contentWidth - i.scrollbarYLeft - i.scrollbarYOuterWidth;\n } else {\n yRailOffset.left = i.scrollbarYLeft + element.scrollLeft;\n }\n }\n set(i.scrollbarYRail, yRailOffset);\n set(i.scrollbarX, {\n left: i.scrollbarXLeft,\n width: i.scrollbarXWidth - i.railBorderXWidth\n });\n set(i.scrollbarY, {\n top: i.scrollbarYTop,\n height: i.scrollbarYHeight - i.railBorderYWidth\n });\n}\n\n/* eslint-disable */\n\nfunction clickRail(i) {\n // const element = i.element;\n\n i.event.bind(i.scrollbarY, 'mousedown', function (e) {\n return e.stopPropagation();\n });\n i.event.bind(i.scrollbarYRail, 'mousedown', function (e) {\n var positionTop = e.pageY - window.pageYOffset - i.scrollbarYRail.getBoundingClientRect().top;\n var direction = positionTop > i.scrollbarYTop ? 1 : -1;\n i.element.scrollTop += direction * i.containerHeight;\n updateGeometry(i);\n e.stopPropagation();\n });\n i.event.bind(i.scrollbarX, 'mousedown', function (e) {\n return e.stopPropagation();\n });\n i.event.bind(i.scrollbarXRail, 'mousedown', function (e) {\n var positionLeft = e.pageX - window.pageXOffset - i.scrollbarXRail.getBoundingClientRect().left;\n var direction = positionLeft > i.scrollbarXLeft ? 1 : -1;\n i.element.scrollLeft += direction * i.containerWidth;\n updateGeometry(i);\n e.stopPropagation();\n });\n}\nvar activeSlider = null; // Variable to track the currently active slider\n\nfunction setupScrollHandlers(i) {\n bindMouseScrollHandler(i, ['containerHeight', 'contentHeight', 'pageY', 'railYHeight', 'scrollbarY', 'scrollbarYHeight', 'scrollTop', 'y', 'scrollbarYRail']);\n bindMouseScrollHandler(i, ['containerWidth', 'contentWidth', 'pageX', 'railXWidth', 'scrollbarX', 'scrollbarXWidth', 'scrollLeft', 'x', 'scrollbarXRail']);\n}\nfunction bindMouseScrollHandler(i, ref) {\n var containerDimension = ref[0];\n var contentDimension = ref[1];\n var pageAxis = ref[2];\n var railDimension = ref[3];\n var scrollbarAxis = ref[4];\n var scrollbarDimension = ref[5];\n var scrollAxis = ref[6];\n var axis = ref[7];\n var scrollbarRail = ref[8];\n var element = i.element;\n var startingScrollPosition = null;\n var startingMousePagePosition = null;\n var scrollBy = null;\n function moveHandler(e) {\n if (e.touches && e.touches[0]) {\n e[pageAxis] = e.touches[0][\"page\" + axis.toUpperCase()];\n }\n\n // Only move if the active slider is the one we started with\n if (activeSlider === scrollbarAxis) {\n element[scrollAxis] = startingScrollPosition + scrollBy * (e[pageAxis] - startingMousePagePosition);\n addScrollingClass(i, axis);\n updateGeometry(i);\n e.stopPropagation();\n e.preventDefault();\n }\n }\n function endHandler() {\n removeScrollingClass(i, axis);\n i[scrollbarRail].classList.remove(cls.state.clicking);\n document.removeEventListener('mousemove', moveHandler);\n document.removeEventListener('mouseup', endHandler);\n document.removeEventListener('touchmove', moveHandler);\n document.removeEventListener('touchend', endHandler);\n activeSlider = null; // Reset active slider when interaction ends\n }\n function bindMoves(e) {\n if (activeSlider === null) {\n // Only bind if no slider is currently active\n activeSlider = scrollbarAxis; // Set current slider as active\n\n startingScrollPosition = element[scrollAxis];\n if (e.touches) {\n e[pageAxis] = e.touches[0][\"page\" + axis.toUpperCase()];\n }\n startingMousePagePosition = e[pageAxis];\n scrollBy = (i[contentDimension] - i[containerDimension]) / (i[railDimension] - i[scrollbarDimension]);\n if (!e.touches) {\n document.addEventListener('mousemove', moveHandler);\n document.addEventListener('mouseup', endHandler);\n } else {\n document.addEventListener('touchmove', moveHandler, {\n passive: false\n });\n document.addEventListener('touchend', endHandler);\n }\n i[scrollbarRail].classList.add(cls.state.clicking);\n }\n e.stopPropagation();\n if (e.cancelable) {\n e.preventDefault();\n }\n }\n i[scrollbarAxis].addEventListener('mousedown', bindMoves);\n i[scrollbarAxis].addEventListener('touchstart', bindMoves);\n}\n\n/* eslint-disable */\n\nfunction keyboard(i) {\n var element = i.element;\n var elementHovered = function () {\n return matches(element, ':hover');\n };\n var scrollbarFocused = function () {\n return matches(i.scrollbarX, ':focus') || matches(i.scrollbarY, ':focus');\n };\n function shouldPreventDefault(deltaX, deltaY) {\n var scrollTop = Math.floor(element.scrollTop);\n if (deltaX === 0) {\n if (!i.scrollbarYActive) {\n return false;\n }\n if (scrollTop === 0 && deltaY > 0 || scrollTop >= i.contentHeight - i.containerHeight && deltaY < 0) {\n return !i.settings.wheelPropagation;\n }\n }\n var scrollLeft = element.scrollLeft;\n if (deltaY === 0) {\n if (!i.scrollbarXActive) {\n return false;\n }\n if (scrollLeft === 0 && deltaX < 0 || scrollLeft >= i.contentWidth - i.containerWidth && deltaX > 0) {\n return !i.settings.wheelPropagation;\n }\n }\n return true;\n }\n i.event.bind(i.ownerDocument, 'keydown', function (e) {\n if (e.isDefaultPrevented && e.isDefaultPrevented() || e.defaultPrevented) {\n return;\n }\n if (!elementHovered() && !scrollbarFocused()) {\n return;\n }\n var activeElement = document.activeElement ? document.activeElement : i.ownerDocument.activeElement;\n if (activeElement) {\n if (activeElement.tagName === 'IFRAME') {\n activeElement = activeElement.contentDocument.activeElement;\n } else {\n // go deeper if element is a webcomponent\n while (activeElement.shadowRoot) {\n activeElement = activeElement.shadowRoot.activeElement;\n }\n }\n if (isEditable(activeElement)) {\n return;\n }\n }\n var deltaX = 0;\n var deltaY = 0;\n switch (e.which) {\n case 37:\n // left\n if (e.metaKey) {\n deltaX = -i.contentWidth;\n } else if (e.altKey) {\n deltaX = -i.containerWidth;\n } else {\n deltaX = -30;\n }\n break;\n case 38:\n // up\n if (e.metaKey) {\n deltaY = i.contentHeight;\n } else if (e.altKey) {\n deltaY = i.containerHeight;\n } else {\n deltaY = 30;\n }\n break;\n case 39:\n // right\n if (e.metaKey) {\n deltaX = i.contentWidth;\n } else if (e.altKey) {\n deltaX = i.containerWidth;\n } else {\n deltaX = 30;\n }\n break;\n case 40:\n // down\n if (e.metaKey) {\n deltaY = -i.contentHeight;\n } else if (e.altKey) {\n deltaY = -i.containerHeight;\n } else {\n deltaY = -30;\n }\n break;\n case 32:\n // space bar\n if (e.shiftKey) {\n deltaY = i.containerHeight;\n } else {\n deltaY = -i.containerHeight;\n }\n break;\n case 33:\n // page up\n deltaY = i.containerHeight;\n break;\n case 34:\n // page down\n deltaY = -i.containerHeight;\n break;\n case 36:\n // home\n deltaY = i.contentHeight;\n break;\n case 35:\n // end\n deltaY = -i.contentHeight;\n break;\n default:\n return;\n }\n if (i.settings.suppressScrollX && deltaX !== 0) {\n return;\n }\n if (i.settings.suppressScrollY && deltaY !== 0) {\n return;\n }\n element.scrollTop -= deltaY;\n element.scrollLeft += deltaX;\n updateGeometry(i);\n if (shouldPreventDefault(deltaX, deltaY)) {\n e.preventDefault();\n }\n });\n}\n\n/* eslint-disable */\n\nfunction wheel(i) {\n var element = i.element;\n function shouldPreventDefault(deltaX, deltaY) {\n var roundedScrollTop = Math.floor(element.scrollTop);\n var isTop = element.scrollTop === 0;\n var isBottom = roundedScrollTop + element.offsetHeight === element.scrollHeight;\n var isLeft = element.scrollLeft === 0;\n var isRight = element.scrollLeft + element.offsetWidth === element.scrollWidth;\n var hitsBound;\n\n // pick axis with primary direction\n if (Math.abs(deltaY) > Math.abs(deltaX)) {\n hitsBound = isTop || isBottom;\n } else {\n hitsBound = isLeft || isRight;\n }\n return hitsBound ? !i.settings.wheelPropagation : true;\n }\n function getDeltaFromEvent(e) {\n var deltaX = e.deltaX;\n var deltaY = -1 * e.deltaY;\n if (typeof deltaX === 'undefined' || typeof deltaY === 'undefined') {\n // OS X Safari\n deltaX = -1 * e.wheelDeltaX / 6;\n deltaY = e.wheelDeltaY / 6;\n }\n if (e.deltaMode && e.deltaMode === 1) {\n // Firefox in deltaMode 1: Line scrolling\n deltaX *= 10;\n deltaY *= 10;\n }\n if (deltaX !== deltaX && deltaY !== deltaY /* NaN checks */) {\n // IE in some mouse drivers\n deltaX = 0;\n deltaY = e.wheelDelta;\n }\n if (e.shiftKey) {\n // reverse axis with shift key\n return [-deltaY, -deltaX];\n }\n return [deltaX, deltaY];\n }\n function shouldBeConsumedByChild(target, deltaX, deltaY) {\n // FIXME: this is a workaround for