any>(funcName: keyof T, clsProto: T, polyFunc: P) => {\r\n let clsFn = clsProto && clsProto[funcName];\r\n\r\n return function(thisArg: any): ReturnType {\r\n let theFunc = (thisArg && thisArg[funcName]) || clsFn;\r\n if (theFunc || polyFunc) {\r\n let theArgs = arguments;\r\n return ((theFunc || polyFunc) as Function).apply(thisArg, theFunc ? _arrSlice.call(theArgs, 1) : theArgs);\r\n }\r\n\r\n _throwMissingFunction(funcName, thisArg);\r\n };\r\n}\r\n\r\n/**\r\n * @internal\r\n * @ignore\r\n * Internal helper to lookup and return the named property from the first argument (which becomes the this)\r\n *\r\n * @since 0.4.2\r\n * @typeParam T - The type of the object which contains the propName\r\n * @param propName - The property name\r\n * @returns The value of the property\r\n */\r\nexport function _unwrapProp(propName: keyof T) {\r\n return function (thisArg: T) {\r\n return thisArg[propName];\r\n };\r\n}","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { INDEX_OF, LAST_INDEX_OF, StrProto } from \"../internal/constants\";\r\nimport { _unwrapFunction } from \"../internal/unwrapFunction\";\r\n\r\n/**\r\n * The `strIndexOf()` method, given two arguments: the string and a substring to search for, searches\r\n * the entire calling string, and returns the index of the first occurrence of the specified substring.\r\n * Given a thrid argument: a number, the method returns the first occurrence of the specified substring\r\n * at an index greater than or equal to the specified number.\r\n * @group String\r\n * @param value - The value to be checked for the seeach string\r\n * @param searchString - The substring to search for in the value\r\n * @param position - The starting position to search from\r\n * @example\r\n * ```ts\r\n * strIndexOf('hello world', '') // returns 0\r\n * strIndexOf('hello world', '', 0) // returns 0\r\n * strIndexOf('hello world', '', 3) // returns 3\r\n * strIndexOf('hello world', '', 8) // returns 8\r\n *\r\n * // However, if the thrid argument is greater than the length of the string\r\n * strIndexOf('hello world', '', 11) // returns 11\r\n * strIndexOf('hello world', '', 13) // returns 11\r\n * strIndexOf('hello world', '', 22) // returns 11\r\n *\r\n * strIndexOf('Blue Whale', 'Blue') // returns 0\r\n * strIndexOf('Blue Whale', 'Blute') // returns -1\r\n * strIndexOf('Blue Whale', 'Whale', 0) // returns 5\r\n * strIndexOf('Blue Whale', 'Whale', 5) // returns 5\r\n * strIndexOf('Blue Whale', 'Whale', 7) // returns -1\r\n * strIndexOf('Blue Whale', '') // returns 0\r\n * strIndexOf('Blue Whale', '', 9) // returns 9\r\n * strIndexOf('Blue Whale', '', 10) // returns 10\r\n * strIndexOf('Blue Whale', '', 11) // returns 10\r\n * ```\r\n */\r\nexport const strIndexOf: (value: string, searchString: string, position?: number) => number = _unwrapFunction(INDEX_OF, StrProto);\r\n\r\n/**\r\n * The `strLastIndexOf()` method, given two arguments: the string and a substring to search for, searches\r\n * the entire calling string, and returns the index of the last occurrence of the specified substring.\r\n * Given a third argument: a number, the method returns the last occurrence of the specified substring\r\n * at an index less than or equal to the specified number.\r\n * @group String\r\n * @param value - The value to be checked for the seeach string\r\n * @param searchString - The substring to search for in the value\r\n * @param position - The starting position to search from\r\n * @example\r\n * ```ts\r\n * strLastIndexOf('canal', 'a'); // returns 3\r\n * strLastIndexOf('canal', 'a', 2); // returns 1\r\n * strLastIndexOf('canal', 'a', 0); // returns -1\r\n * strLastIndexOf('canal', 'x'); // returns -1\r\n * strLastIndexOf('canal', 'c', -5); // returns 0\r\n * strLastIndexOf('canal', 'c', 0); // returns 0\r\n * strLastIndexOf('canal', ''); // returns 5\r\n * strLastIndexOf('canal', '', 2); // returns 2\r\n * ```\r\n */\r\nexport const strLastIndexOf: (value: string, searchString: string, position?: number) => number = _unwrapFunction(LAST_INDEX_OF, StrProto);\r\n","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { LENGTH } from \"../internal/constants\";\r\n\r\n/**\r\n * Calls the provided `callbackFn` function once for each element in an array in ascending index order. It is not invoked for index properties\r\n * that have been deleted or are uninitialized. And unlike the ES6 forEach() you CAN stop or break the iteration by returning -1 from the\r\n * `callbackFn` function.\r\n *\r\n * The range (number of elements) processed by arrForEach() is set before the first call to the `callbackFn`. Any elements added beyond the range\r\n * or elements which as assigned to indexes already processed will not be visited by the `callbackFn`.\r\n * @group Array\r\n * @group ArrayLike\r\n * @typeParam T - Identifies the element type of the array\r\n * @param theArray - The array or array like object of elements to be searched.\r\n * @param callbackfn A `synchronous` function that accepts up to three arguments. arrForEach calls the callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, null or undefined\r\n * the array will be used as the this value.\r\n * @remarks\r\n * arrForEach expects a `synchronous` function.\r\n * arrForEach does not wait for promises. Make sure you are aware of the implications while using promises (or async functions) as forEach callback.\r\n * @example\r\n * ```ts\r\n * const items = ['item1', 'item2', 'item3'];\r\n * const copyItems = [];\r\n *\r\n * // before using for loop\r\n * for (let i = 0; i < items.length; i++) {\r\n * copyItems.push(items[i]);\r\n * }\r\n *\r\n * // before using forEach()\r\n * items.forEach((item) => {\r\n * copyItems.push(item);\r\n * });\r\n *\r\n * // after\r\n * arrForEach(items, (item) => {\r\n * copyItems.push(item);\r\n * // May return -1 to abort the iteration\r\n * });\r\n *\r\n * // Also supports input as an array like object\r\n * const items = { length: 3, 0: 'item1', 1: 'item2', 2: 'item3' };\r\n * ```\r\n */\r\nexport function arrForEach(theArray: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => void | number, thisArg?: any): void {\r\n if (theArray) {\r\n const len = theArray[LENGTH] >>> 0;\r\n for (let idx = 0; idx < len; idx++) {\r\n if (idx in theArray) {\r\n if (callbackfn.call(thisArg || theArray, theArray[idx], idx, theArray) === -1) {\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n}\r\n","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2023 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { _unwrapInstFunction } from \"../internal/unwrapFunction\";\r\n\r\n/**\r\n * The `fnCall` function calls the function with the given `thisArg` as the `this` value and with\r\n * al of the `_args` provided as it's `arguments.\r\n *\r\n * > This is almost identical to `fnApply`, except that the function arguments are passed to `fnCall`\r\n * individually as a list, while with `fnApply` that are combined into a single array argument.\r\n *\r\n * Normally, when calling a function, the value of `this` inside the function is the object that the\r\n * function was accessed on. With `fnCall()`, you can pass an arbitrary value as the `this` when calling an\r\n * existing function, without first attaching the function to the object as a property. This allows you\r\n * to use methods of one object as generic utility functions.\r\n *\r\n * @since 0.9.8\r\n * @group Function\r\n *\r\n * @param fn - The function to be called\r\n * @param thisArg - The value of `this` provided for the call to `fn`. If the function is not in strict mode,\r\n * `null` and `undefined` will be replaced with the global object, and primitive values will be converted to objects.\r\n * @param _args - The zero or more arguments to be passed to the `fn` function.\r\n * @returns The result of calling the function with the specified `this` value and arguments.\r\n * @example\r\n * ```ts\r\n * // min / max number in an array\r\n * let max = fnCall(Math.max, null, 21, 42, 84, 168, 7, 3);\r\n * // 168\r\n *\r\n * let min = fnCall(Math.min, null, 21, 42, 84, 168, 7, 3);\r\n * // 3\r\n *\r\n * const module1 = {\r\n * prefix: \"Hello\",\r\n * x: 21,\r\n * getX() {\r\n * return this.x;\r\n * },\r\n * log(value: string) {\r\n * return this.prefix + \" \" + value + \" : \" + this.x\r\n * }\r\n * };\r\n *\r\n * // The 'this' parameter of 'getX' is bound to 'module'.\r\n * module1.getX(); // 21\r\n * module1.log(\"Darkness\"); // Hello Darkness : 21\r\n *\r\n * // Create a new function 'boundGetX' with the 'this' parameter bound to 'module'.\r\n * let module2 = {\r\n * prefix: \"my\",\r\n * x: 42\r\n * };\r\n *\r\n * // Call the function of module1 with module2 as it's this\r\n * fnCall(module1.getX, module2); // 42\r\n * fnCall(module1.log, module2, \"friend\"); // my friend : 42\r\n * ```\r\n */\r\nexport const fnCall: any, T>(fn: F, thisArg: T, ..._args: any[]) => ReturnType = _unwrapInstFunction(\"call\");\r\n","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { fnCall } from \"../funcs/fnCall\";\r\nimport { getWindow, hasWindow } from \"../helpers/environment\";\r\nimport { CONSTRUCTOR, FUNCTION, ObjClass, OBJECT, PROTOTYPE } from \"../internal/constants\";\r\nimport { objHasOwnProperty } from \"./has_own_prop\";\r\nimport { objGetPrototypeOf } from \"./object\";\r\n\r\n// Use to cache the result of Object.cont\r\nlet _fnToString: () => string;\r\nlet _objCtrFnString: string;\r\nlet _gblWindow: Window;\r\n\r\n/**\r\n * Checks to see if the past value is a plain object (not a class/array) value.\r\n * Object are considered to be \"plain\" if they are created with no prototype `Object.create(null)`\r\n * or by using the Object global (native) function, all other \"objects\" ar\r\n * @since 0.4.4\r\n * @group Type Identity\r\n * @group Object\r\n * @param value - The value to check\r\n * @returns true if `value` is a normal plain object\r\n * @example\r\n * ```ts\r\n * console.log(isPlainObject({ 0: 'a', 1: 'b', 2: 'c' })); // true\r\n * console.log(isPlainObject({ 100: 'a', 2: 'b', 7: 'c' })); // true\r\n * console.log(isPlainObject(objCreate(null))); // true\r\n *\r\n * const myObj = objCreate({}, {\r\n * getFoo: {\r\n * value() { return this.foo; }\r\n * }\r\n * });\r\n * myObj.foo = 1;\r\n * console.log(isPlainObject(myObj)); // true\r\n *\r\n * console.log(isPlainObject(['a', 'b', 'c'])); // false\r\n * console.log(isPlainObject(new Date())); // false\r\n * console.log(isPlainObject(new Error(\"An Error\"))); // false\r\n * console.log(isPlainObject(null)); // false\r\n * console.log(isPlainObject(undefined)); // false\r\n * console.log(isPlainObject(\"null\")); // false\r\n * console.log(isPlainObject(\"undefined\")); // false\r\n * console.log(isPlainObject(\"1\")); // false\r\n * console.log(isPlainObject(\"aa\")); // false\r\n * ```\r\n */\r\nexport function isPlainObject(value: any): value is object {\r\n if (!value || typeof value !== OBJECT) {\r\n return false;\r\n }\r\n\r\n if (!_gblWindow) {\r\n // Lazily cache the current global window value and default it to \"true\" (so we bypass this check in the future)\r\n _gblWindow = hasWindow() ? getWindow() : (true as any);\r\n }\r\n\r\n let result = false;\r\n if (value !== _gblWindow) {\r\n\r\n if (!_objCtrFnString) {\r\n // Lazily caching what the runtime reports as the object function constructor (as a string)\r\n // Using an current function lookup to find what this runtime calls a \"native\" function\r\n _fnToString = Function[PROTOTYPE].toString;\r\n _objCtrFnString = fnCall(_fnToString, ObjClass);\r\n }\r\n\r\n try {\r\n let proto = objGetPrototypeOf(value);\r\n\r\n // No prototype so looks like an object created with Object.create(null)\r\n result = !proto;\r\n if (!result) {\r\n if (objHasOwnProperty(proto, CONSTRUCTOR)) {\r\n proto = proto[CONSTRUCTOR]\r\n }\r\n \r\n result = proto && typeof proto === FUNCTION && _fnToString.call(proto) === _objCtrFnString;\r\n }\r\n } catch (ex) {\r\n // Something went wrong, so it's not an object we are playing with\r\n }\r\n }\r\n\r\n return result;\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n// ###################################################################################################################################################\r\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 ###\r\n// ###################################################################################################################################################\r\nexport var UNDEFINED_VALUE = undefined;\r\nexport var STR_EMPTY = \"\";\r\nexport var STR_CHANNELS = \"channels\";\r\nexport var STR_CORE = \"core\";\r\nexport var STR_CREATE_PERF_MGR = \"createPerfMgr\";\r\nexport var STR_DISABLED = \"disabled\";\r\nexport var STR_EXTENSION_CONFIG = \"extensionConfig\";\r\nexport var STR_EXTENSIONS = \"extensions\";\r\nexport var STR_PROCESS_TELEMETRY = \"processTelemetry\";\r\nexport var STR_PRIORITY = \"priority\";\r\nexport var STR_EVENTS_SENT = \"eventsSent\";\r\nexport var STR_EVENTS_DISCARDED = \"eventsDiscarded\";\r\nexport var STR_EVENTS_SEND_REQUEST = \"eventsSendRequest\";\r\nexport var STR_PERF_EVENT = \"perfEvent\";\r\nexport var STR_GET_PERF_MGR = \"getPerfMgr\";\r\nexport var STR_DOMAIN = \"domain\";\r\nexport var STR_PATH = \"path\";\r\nexport var STR_NOT_DYNAMIC_ERROR = \"Not dynamic - \";\r\n//# sourceMappingURL=InternalConstants.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { ObjAssign, ObjClass } from \"@microsoft/applicationinsights-shims\";\r\nimport { arrForEach, asString as asString21, isArray, isBoolean, isError, isFunction, isNullOrUndefined, isObject, isPlainObject, isString, isUndefined, objDeepFreeze, objDefine, objForEachKey, objHasOwn, strIndexOf } from \"@nevware21/ts-utils\";\r\nimport { _DYN_APPLY, _DYN_LENGTH, _DYN_NAME, _DYN_REPLACE } from \"../__DynamicConstants\";\r\nimport { STR_EMPTY } from \"./InternalConstants\";\r\n// RESTRICT and AVOID circular dependencies you should not import other contained modules or export the contents of this file directly\r\n// Added to help with minification\r\nvar strGetPrototypeOf = \"getPrototypeOf\";\r\nvar rCamelCase = /-([a-z])/g;\r\nvar rNormalizeInvalid = /([^\\w\\d_$])/g;\r\nvar rLeadingNumeric = /^(\\d+[\\w\\d_$])/;\r\nexport var _getObjProto = Object[strGetPrototypeOf];\r\nexport function isNotUndefined(value) {\r\n return !isUndefined(value);\r\n}\r\nexport function isNotNullOrUndefined(value) {\r\n return !isNullOrUndefined(value);\r\n}\r\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 */\r\nexport function normalizeJsName(name) {\r\n var value = name;\r\n if (value && isString(value)) {\r\n // CamelCase everything after the \"-\" and remove the dash\r\n value = value[_DYN_REPLACE /* @min:%2ereplace */](rCamelCase, function (_all, letter) {\r\n return letter.toUpperCase();\r\n });\r\n value = value[_DYN_REPLACE /* @min:%2ereplace */](rNormalizeInvalid, \"_\");\r\n value = value[_DYN_REPLACE /* @min:%2ereplace */](rLeadingNumeric, function (_all, match) {\r\n return \"_\" + match;\r\n });\r\n }\r\n return value;\r\n}\r\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 */\r\nexport function strContains(value, search) {\r\n if (value && search) {\r\n return strIndexOf(value, search) !== -1;\r\n }\r\n return false;\r\n}\r\n/**\r\n * Convert a date to I.S.O. format in IE8\r\n */\r\nexport function toISOString(date) {\r\n return date && date.toISOString() || \"\";\r\n}\r\nexport var deepFreeze = objDeepFreeze;\r\n/**\r\n * Returns the name of object if it's an Error. Otherwise, returns empty string.\r\n */\r\nexport function getExceptionName(object) {\r\n if (isError(object)) {\r\n return object[_DYN_NAME /* @min:%2ename */];\r\n }\r\n return STR_EMPTY;\r\n}\r\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 */\r\nexport function setValue(target, field, value, valChk, srcChk) {\r\n var theValue = value;\r\n if (target) {\r\n theValue = target[field];\r\n if (theValue !== value && (!srcChk || srcChk(theValue)) && (!valChk || valChk(value))) {\r\n theValue = value;\r\n target[field] = theValue;\r\n }\r\n }\r\n return theValue;\r\n}\r\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 */\r\nexport function getSetValue(target, field, defValue) {\r\n var theValue;\r\n if (target) {\r\n theValue = target[field];\r\n if (!theValue && isNullOrUndefined(theValue)) {\r\n // Supports having the default as null\r\n theValue = !isUndefined(defValue) ? defValue : {};\r\n target[field] = theValue;\r\n }\r\n }\r\n else {\r\n // Expanded for performance so we only check defValue if required\r\n theValue = !isUndefined(defValue) ? defValue : {};\r\n }\r\n return theValue;\r\n}\r\nfunction _createProxyFunction(source, funcName) {\r\n var srcFunc = null;\r\n var src = null;\r\n if (isFunction(source)) {\r\n srcFunc = source;\r\n }\r\n else {\r\n src = source;\r\n }\r\n return function () {\r\n // Capture the original arguments passed to the method\r\n var originalArguments = arguments;\r\n if (srcFunc) {\r\n src = srcFunc();\r\n }\r\n if (src) {\r\n return src[funcName][_DYN_APPLY /* @min:%2eapply */](src, originalArguments);\r\n }\r\n };\r\n}\r\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 */\r\nexport function proxyAssign(target, source, chkSet) {\r\n if (target && source && isObject(target) && isObject(source)) {\r\n var _loop_1 = function (field) {\r\n if (isString(field)) {\r\n var value = source[field];\r\n if (isFunction(value)) {\r\n if (!chkSet || chkSet(field, true, source, target)) {\r\n // Create a proxy function rather than just copying the (possible) prototype to the new object as an instance function\r\n target[field] = _createProxyFunction(source, field);\r\n }\r\n }\r\n else if (!chkSet || chkSet(field, false, source, target)) {\r\n if (objHasOwn(target, field)) {\r\n // Remove any previous instance property\r\n delete target[field];\r\n }\r\n objDefine(target, field, {\r\n g: function () {\r\n return source[field];\r\n },\r\n s: function (theValue) {\r\n source[field] = theValue;\r\n }\r\n });\r\n }\r\n }\r\n };\r\n // effectively apply/proxy full source to the target instance\r\n for (var field in source) {\r\n _loop_1(field);\r\n }\r\n }\r\n return target;\r\n}\r\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 */\r\nexport function proxyFunctionAs(target, name, source, theFunc, overwriteTarget) {\r\n if (target && name && source) {\r\n if (overwriteTarget !== false || isUndefined(target[name])) {\r\n target[name] = _createProxyFunction(source, theFunc);\r\n }\r\n }\r\n}\r\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 */\r\nexport function proxyFunctions(target, source, functionsToProxy, overwriteTarget) {\r\n if (target && source && isObject(target) && isArray(functionsToProxy)) {\r\n arrForEach(functionsToProxy, function (theFuncName) {\r\n if (isString(theFuncName)) {\r\n proxyFunctionAs(target, theFuncName, source, theFuncName, overwriteTarget);\r\n }\r\n });\r\n }\r\n return target;\r\n}\r\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 */\r\nexport function createClassFromInterface(defaults) {\r\n return /** @class */ (function () {\r\n function class_1() {\r\n var _this = this;\r\n if (defaults) {\r\n objForEachKey(defaults, function (field, value) {\r\n _this[field] = value;\r\n });\r\n }\r\n }\r\n return class_1;\r\n }());\r\n}\r\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 */\r\nexport function optimizeObject(theObject) {\r\n // V8 Optimization to cause the JIT compiler to create a new optimized object for looking up the own properties\r\n // primarily for object with <= 19 properties for >= 20 the effect is reduced or non-existent\r\n if (theObject && ObjAssign) {\r\n theObject = ObjClass(ObjAssign({}, theObject));\r\n }\r\n return theObject;\r\n}\r\nexport function objExtend(obj1, obj2, obj3, obj4, obj5, obj6) {\r\n // Variables\r\n var theArgs = arguments;\r\n var extended = theArgs[0] || {};\r\n var argLen = theArgs[_DYN_LENGTH /* @min:%2elength */];\r\n var deep = false;\r\n var idx = 1;\r\n // Check for \"Deep\" flag\r\n if (argLen > 0 && isBoolean(extended)) {\r\n deep = extended;\r\n extended = theArgs[idx] || {};\r\n idx++;\r\n }\r\n // Handle case when target is a string or something (possible in deep copy)\r\n if (!isObject(extended)) {\r\n extended = {};\r\n }\r\n // Loop through each remaining object and conduct a merge\r\n for (; idx < argLen; idx++) {\r\n var arg = theArgs[idx];\r\n var isArgArray = isArray(arg);\r\n var isArgObj = isObject(arg);\r\n for (var prop in arg) {\r\n var propOk = (isArgArray && (prop in arg)) || (isArgObj && objHasOwn(arg, prop));\r\n if (!propOk) {\r\n continue;\r\n }\r\n var newValue = arg[prop];\r\n var isNewArray = void 0;\r\n // If deep merge and property is an object, merge properties\r\n if (deep && newValue && ((isNewArray = isArray(newValue)) || isPlainObject(newValue))) {\r\n // Grab the current value of the extended object\r\n var clone = extended[prop];\r\n if (isNewArray) {\r\n if (!isArray(clone)) {\r\n // We can't \"merge\" an array with a non-array so overwrite the original\r\n clone = [];\r\n }\r\n }\r\n else if (!isPlainObject(clone)) {\r\n // We can't \"merge\" an object with a non-object\r\n clone = {};\r\n }\r\n // Never move the original objects always clone them\r\n newValue = objExtend(deep, clone, newValue);\r\n }\r\n // Assign the new (or previous) value (unless undefined)\r\n if (newValue !== undefined) {\r\n extended[prop] = newValue;\r\n }\r\n }\r\n }\r\n return extended;\r\n}\r\nexport var asString = asString21;\r\n//# sourceMappingURL=HelperFuncs.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\"use strict\";\r\nimport { strShimObject, strShimPrototype, strShimUndefined } from \"@microsoft/applicationinsights-shims\";\r\nimport { getDocument, getInst, getNavigator, getPerformance, hasNavigator, isString, isUndefined, strIndexOf } from \"@nevware21/ts-utils\";\r\nimport { _DYN_LENGTH, _DYN_NAME, _DYN_SPLIT, _DYN_TO_LOWER_CASE, _DYN_USER_AGENT } from \"../__DynamicConstants\";\r\nimport { strContains } from \"./HelperFuncs\";\r\nimport { STR_EMPTY } from \"./InternalConstants\";\r\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 */\r\nvar strDocumentMode = \"documentMode\";\r\nvar strLocation = \"location\";\r\nvar strConsole = \"console\";\r\nvar strPerformance = \"performance\";\r\nvar strJSON = \"JSON\";\r\nvar strCrypto = \"crypto\";\r\nvar strMsCrypto = \"msCrypto\";\r\nvar strReactNative = \"ReactNative\";\r\nvar strMsie = \"msie\";\r\nvar strTrident = \"trident/\";\r\nvar strXMLHttpRequest = \"XMLHttpRequest\";\r\nvar _isTrident = null;\r\nvar _navUserAgentCheck = null;\r\nvar _enableMocks = false;\r\nvar _useXDomainRequest = null;\r\nvar _beaconsSupported = null;\r\nfunction _hasProperty(theClass, property) {\r\n var supported = false;\r\n if (theClass) {\r\n try {\r\n supported = property in theClass;\r\n if (!supported) {\r\n var proto = theClass[strShimPrototype];\r\n if (proto) {\r\n supported = property in proto;\r\n }\r\n }\r\n }\r\n catch (e) {\r\n // Do Nothing\r\n }\r\n if (!supported) {\r\n try {\r\n var tmp = new theClass();\r\n supported = !isUndefined(tmp[property]);\r\n }\r\n catch (e) {\r\n // Do Nothing\r\n }\r\n }\r\n }\r\n return supported;\r\n}\r\n/**\r\n * Enable the lookup of test mock objects if requested\r\n * @param enabled\r\n */\r\nexport function setEnableEnvMocks(enabled) {\r\n _enableMocks = enabled;\r\n}\r\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 */\r\nexport function getLocation(checkForMock) {\r\n if (checkForMock && _enableMocks) {\r\n var mockLocation = getInst(\"__mockLocation\");\r\n if (mockLocation) {\r\n return mockLocation;\r\n }\r\n }\r\n if (typeof location === strShimObject && location) {\r\n return location;\r\n }\r\n return getInst(strLocation);\r\n}\r\n/**\r\n * Returns the global console object\r\n */\r\nexport function getConsole() {\r\n if (typeof console !== strShimUndefined) {\r\n return console;\r\n }\r\n return getInst(strConsole);\r\n}\r\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 */\r\nexport function hasJSON() {\r\n return Boolean((typeof JSON === strShimObject && JSON) || getInst(strJSON) !== null);\r\n}\r\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 */\r\nexport function getJSON() {\r\n if (hasJSON()) {\r\n return JSON || getInst(strJSON);\r\n }\r\n return null;\r\n}\r\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 */\r\nexport function getCrypto() {\r\n return getInst(strCrypto);\r\n}\r\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 */\r\nexport function getMsCrypto() {\r\n return getInst(strMsCrypto);\r\n}\r\n/**\r\n * Returns whether the environment is reporting that we are running in a React Native Environment\r\n */\r\nexport function isReactNative() {\r\n // If running in React Native, navigator.product will be populated\r\n var nav = getNavigator();\r\n if (nav && nav.product) {\r\n return nav.product === strReactNative;\r\n }\r\n return false;\r\n}\r\n/**\r\n * Identifies whether the current environment appears to be IE\r\n */\r\nexport function isIE() {\r\n var nav = getNavigator();\r\n if (nav && (nav[_DYN_USER_AGENT /* @min:%2euserAgent */] !== _navUserAgentCheck || _isTrident === null)) {\r\n // Added to support test mocking of the user agent\r\n _navUserAgentCheck = nav[_DYN_USER_AGENT /* @min:%2euserAgent */];\r\n var userAgent = (_navUserAgentCheck || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\r\n _isTrident = (strContains(userAgent, strMsie) || strContains(userAgent, strTrident));\r\n }\r\n return _isTrident;\r\n}\r\n/**\r\n * Gets IE version returning the document emulation mode if we are running on IE, or null otherwise\r\n */\r\nexport function getIEVersion(userAgentStr) {\r\n if (userAgentStr === void 0) { userAgentStr = null; }\r\n if (!userAgentStr) {\r\n var navigator_1 = getNavigator() || {};\r\n userAgentStr = navigator_1 ? (navigator_1.userAgent || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]() : STR_EMPTY;\r\n }\r\n var ua = (userAgentStr || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\r\n // Also check for documentMode in case X-UA-Compatible meta tag was included in HTML.\r\n if (strContains(ua, strMsie)) {\r\n var doc = getDocument() || {};\r\n return Math.max(parseInt(ua[_DYN_SPLIT /* @min:%2esplit */](strMsie)[1]), (doc[strDocumentMode] || 0));\r\n }\r\n else if (strContains(ua, strTrident)) {\r\n var tridentVer = parseInt(ua[_DYN_SPLIT /* @min:%2esplit */](strTrident)[1]);\r\n if (tridentVer) {\r\n return tridentVer + 4;\r\n }\r\n }\r\n return null;\r\n}\r\nexport function isSafari(userAgentStr) {\r\n if (!userAgentStr || !isString(userAgentStr)) {\r\n var navigator_2 = getNavigator() || {};\r\n userAgentStr = navigator_2 ? (navigator_2.userAgent || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]() : STR_EMPTY;\r\n }\r\n var ua = (userAgentStr || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\r\n return (strIndexOf(ua, \"safari\") >= 0);\r\n}\r\n/**\r\n * Checks if HTML5 Beacons are supported in the current environment.\r\n * @returns True if supported, false otherwise.\r\n */\r\nexport function isBeaconsSupported() {\r\n if (_beaconsSupported === null) {\r\n _beaconsSupported = hasNavigator() && Boolean(getNavigator().sendBeacon);\r\n }\r\n return _beaconsSupported;\r\n}\r\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 */\r\nexport function isFetchSupported(withKeepAlive) {\r\n var isSupported = false;\r\n try {\r\n isSupported = !!getInst(\"fetch\");\r\n var request = getInst(\"Request\");\r\n if (isSupported && withKeepAlive && request) {\r\n isSupported = _hasProperty(request, \"keepalive\");\r\n }\r\n }\r\n catch (e) {\r\n // Just Swallow any failure during availability checks\r\n }\r\n return isSupported;\r\n}\r\nexport function useXDomainRequest() {\r\n if (_useXDomainRequest === null) {\r\n _useXDomainRequest = (typeof XDomainRequest !== strShimUndefined);\r\n if (_useXDomainRequest && isXhrSupported()) {\r\n _useXDomainRequest = _useXDomainRequest && !_hasProperty(getInst(strXMLHttpRequest), \"withCredentials\");\r\n }\r\n }\r\n return _useXDomainRequest;\r\n}\r\n/**\r\n * Checks if XMLHttpRequest is supported\r\n * @returns True if supported, otherwise false\r\n */\r\nexport function isXhrSupported() {\r\n var isSupported = false;\r\n try {\r\n var xmlHttpRequest = getInst(strXMLHttpRequest);\r\n isSupported = !!xmlHttpRequest;\r\n }\r\n catch (e) {\r\n // Just Swallow any failure during availability checks\r\n }\r\n return isSupported;\r\n}\r\nfunction _getNamedValue(values, name) {\r\n if (values) {\r\n for (var i = 0; i < values[_DYN_LENGTH /* @min:%2elength */]; i++) {\r\n var value = values[i];\r\n if (value[_DYN_NAME /* @min:%2ename */]) {\r\n if (value[_DYN_NAME /* @min:%2ename */] === name) {\r\n return value;\r\n }\r\n }\r\n }\r\n }\r\n return {};\r\n}\r\n/**\r\n * Helper function to fetch the named meta-tag from the page.\r\n * @param name\r\n */\r\nexport function findMetaTag(name) {\r\n var doc = getDocument();\r\n if (doc && name) {\r\n // Look for a meta-tag\r\n return _getNamedValue(doc.querySelectorAll(\"meta\"), name).content;\r\n }\r\n return null;\r\n}\r\n/**\r\n * Helper function to fetch the named server timing value from the page response (first navigation event).\r\n * @param name\r\n */\r\nexport function findNamedServerTiming(name) {\r\n var value;\r\n var perf = getPerformance();\r\n if (perf) {\r\n // Try looking for a server-timing header\r\n var navPerf = perf.getEntriesByType(\"navigation\") || [];\r\n value = _getNamedValue((navPerf[_DYN_LENGTH /* @min:%2elength */] > 0 ? navPerf[0] : {}).serverTiming, name).description;\r\n }\r\n return value;\r\n}\r\n//# sourceMappingURL=EnvUtils.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { utcNow } from \"@nevware21/ts-utils\";\r\nimport { _DYN_LENGTH } from \"../__DynamicConstants\";\r\nimport { getCrypto, getMsCrypto, isIE } from \"./EnvUtils\";\r\nimport { STR_EMPTY } from \"./InternalConstants\";\r\nvar UInt32Mask = 0x100000000;\r\nvar MaxUInt32 = 0xffffffff;\r\nvar SEED1 = 123456789;\r\nvar SEED2 = 987654321;\r\n// MWC based Random generator (for IE)\r\nvar _mwcSeeded = false;\r\nvar _mwcW = SEED1;\r\nvar _mwcZ = SEED2;\r\n// Takes any integer\r\nfunction _mwcSeed(seedValue) {\r\n if (seedValue < 0) {\r\n // Make sure we end up with a positive number and not -ve one.\r\n seedValue >>>= 0;\r\n }\r\n _mwcW = (SEED1 + seedValue) & MaxUInt32;\r\n _mwcZ = (SEED2 - seedValue) & MaxUInt32;\r\n _mwcSeeded = true;\r\n}\r\nfunction _autoSeedMwc() {\r\n // Simple initialization using default Math.random() - So we inherit any entropy from the browser\r\n // and bitwise XOR with the current milliseconds\r\n try {\r\n var now = utcNow() & 0x7fffffff;\r\n _mwcSeed(((Math.random() * UInt32Mask) ^ now) + now);\r\n }\r\n catch (e) {\r\n // Don't crash if something goes wrong\r\n }\r\n}\r\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\r\n */\r\nexport function randomValue(maxValue) {\r\n if (maxValue > 0) {\r\n return Math.floor((random32() / MaxUInt32) * (maxValue + 1)) >>> 0;\r\n }\r\n return 0;\r\n}\r\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 */\r\nexport function random32(signed) {\r\n var value = 0;\r\n var c = getCrypto() || getMsCrypto();\r\n if (c && c.getRandomValues) {\r\n // Make sure the number is converted into the specified range (-0x80000000..0x7FFFFFFF)\r\n value = c.getRandomValues(new Uint32Array(1))[0] & MaxUInt32;\r\n }\r\n if (value === 0 && isIE()) {\r\n // For IE 6, 7, 8 (especially on XP) Math.random is not very random\r\n if (!_mwcSeeded) {\r\n // Set the seed for the Mwc algorithm\r\n _autoSeedMwc();\r\n }\r\n // Don't use Math.random for IE\r\n // Make sure the number is converted into the specified range (-0x80000000..0x7FFFFFFF)\r\n value = mwcRandom32() & MaxUInt32;\r\n }\r\n if (value === 0) {\r\n // Make sure the number is converted into the specified range (-0x80000000..0x7FFFFFFF)\r\n value = Math.floor((UInt32Mask * Math.random()) | 0);\r\n }\r\n if (!signed) {\r\n // Make sure we end up with a positive number and not -ve one.\r\n value >>>= 0;\r\n }\r\n return value;\r\n}\r\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 */\r\nexport function mwcRandomSeed(value) {\r\n if (!value) {\r\n _autoSeedMwc();\r\n }\r\n else {\r\n _mwcSeed(value);\r\n }\r\n}\r\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 */\r\nexport function mwcRandom32(signed) {\r\n _mwcZ = (36969 * (_mwcZ & 0xFFFF) + (_mwcZ >> 16)) & MaxUInt32;\r\n _mwcW = (18000 * (_mwcW & 0xFFFF) + (_mwcW >> 16)) & MaxUInt32;\r\n var value = (((_mwcZ << 16) + (_mwcW & 0xFFFF)) >>> 0) & MaxUInt32 | 0;\r\n if (!signed) {\r\n // Make sure we end up with a positive number and not -ve one.\r\n value >>>= 0;\r\n }\r\n return value;\r\n}\r\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 */\r\nexport function newId(maxLength) {\r\n if (maxLength === void 0) { maxLength = 22; }\r\n var base64chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\r\n // Start with an initial random number, consuming the value in reverse byte order\r\n var number = random32() >>> 0; // Make sure it's a +ve number\r\n var chars = 0;\r\n var result = STR_EMPTY;\r\n while (result[_DYN_LENGTH /* @min:%2elength */] < maxLength) {\r\n chars++;\r\n result += base64chars.charAt(number & 0x3F);\r\n number >>>= 6; // Zero fill with right shift\r\n if (chars === 5) {\r\n // 5 base64 characters === 30 bits so we don't have enough bits for another base64 char\r\n // So add on another 30 bits and make sure it's +ve\r\n number = (((random32() << 2) & 0xFFFFFFFF) | (number & 0x03)) >>> 0;\r\n chars = 0; // We need to reset the number every 5 chars (30 bits)\r\n }\r\n }\r\n return result;\r\n}\r\n//# sourceMappingURL=RandomHelper.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { objDefine } from \"@nevware21/ts-utils\";\r\nimport { _DYN_NODE_TYPE } from \"../__DynamicConstants\";\r\nimport { normalizeJsName } from \"./HelperFuncs\";\r\nimport { STR_EMPTY } from \"./InternalConstants\";\r\nimport { newId } from \"./RandomHelper\";\r\nvar version = '3.0.2';\r\nvar instanceName = \".\" + newId(6);\r\nvar _dataUid = 0;\r\n// Accepts only:\r\n// - Node\r\n// - Node.ELEMENT_NODE\r\n// - Node.DOCUMENT_NODE\r\n// - Object\r\n// - Any\r\nfunction _canAcceptData(target) {\r\n return target[_DYN_NODE_TYPE /* @min:%2enodeType */] === 1 || target[_DYN_NODE_TYPE /* @min:%2enodeType */] === 9 || !(+target[_DYN_NODE_TYPE /* @min:%2enodeType */]);\r\n}\r\nfunction _getCache(data, target) {\r\n var theCache = target[data.id];\r\n if (!theCache) {\r\n theCache = {};\r\n try {\r\n if (_canAcceptData(target)) {\r\n objDefine(target, data.id, {\r\n e: false,\r\n v: theCache\r\n });\r\n }\r\n }\r\n catch (e) {\r\n // Not all environments allow extending all objects, so just ignore the cache in those cases\r\n }\r\n }\r\n return theCache;\r\n}\r\nexport function createUniqueNamespace(name, includeVersion) {\r\n if (includeVersion === void 0) { includeVersion = false; }\r\n return normalizeJsName(name + (_dataUid++) + (includeVersion ? \".\" + version : STR_EMPTY) + instanceName);\r\n}\r\nexport function createElmNodeData(name) {\r\n var data = {\r\n id: createUniqueNamespace(\"_aiData-\" + (name || STR_EMPTY) + \".\" + version),\r\n accept: function (target) {\r\n return _canAcceptData(target);\r\n },\r\n get: function (target, name, defValue, addDefault) {\r\n var theCache = target[data.id];\r\n if (!theCache) {\r\n if (addDefault) {\r\n // Side effect is adds the cache\r\n theCache = _getCache(data, target);\r\n theCache[normalizeJsName(name)] = defValue;\r\n }\r\n return defValue;\r\n }\r\n return theCache[normalizeJsName(name)];\r\n },\r\n kill: function (target, name) {\r\n if (target && target[name]) {\r\n try {\r\n delete target[name];\r\n }\r\n catch (e) {\r\n // Just cleaning up, so if this fails -- ignore\r\n }\r\n }\r\n }\r\n };\r\n return data;\r\n}\r\n//# sourceMappingURL=DataCacheHelper.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { asString, isArray, isDefined, isNullOrUndefined, isObject, isPlainObject, isUndefined, objForEachKey, objHasOwn } from \"@nevware21/ts-utils\";\r\nimport { _DYN_BLK_VAL, _DYN_LENGTH, _DYN_RD_ONLY } from \"../__DynamicConstants\";\r\nfunction _isConfigDefaults(value) {\r\n return (value && isObject(value) && (value.isVal || value.fb || objHasOwn(value, \"v\") || objHasOwn(value, \"mrg\") || objHasOwn(value, \"ref\") || value.set));\r\n}\r\nfunction _getDefault(dynamicHandler, theConfig, cfgDefaults) {\r\n var defValue;\r\n var isDefaultValid = cfgDefaults.dfVal || isDefined;\r\n // There is a fallback config key so try and grab that first\r\n if (theConfig && cfgDefaults.fb) {\r\n var fallbacks = cfgDefaults.fb;\r\n if (!isArray(fallbacks)) {\r\n fallbacks = [fallbacks];\r\n }\r\n for (var lp = 0; lp < fallbacks[_DYN_LENGTH /* @min:%2elength */]; lp++) {\r\n var fallback = fallbacks[lp];\r\n var fbValue = theConfig[fallback];\r\n if (isDefaultValid(fbValue)) {\r\n defValue = fbValue;\r\n }\r\n else if (dynamicHandler) {\r\n // Needed to ensure that the fallback value (and potentially) new field is also dynamic even if null/undefined\r\n fbValue = dynamicHandler.cfg[fallback];\r\n if (isDefaultValid(fbValue)) {\r\n defValue = fbValue;\r\n }\r\n // Needed to ensure that the fallback value (and potentially) new field is also dynamic even if null/undefined\r\n dynamicHandler.set(dynamicHandler.cfg, asString(fallback), fbValue);\r\n }\r\n if (isDefaultValid(defValue)) {\r\n // We have a valid default so break out of the look\r\n break;\r\n }\r\n }\r\n }\r\n // If the value is still not defined and we have a default value then use that\r\n if (!isDefaultValid(defValue) && isDefaultValid(cfgDefaults.v)) {\r\n defValue = cfgDefaults.v;\r\n }\r\n return defValue;\r\n}\r\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 */\r\nfunction _resolveDefaultValue(dynamicHandler, theConfig, cfgDefaults) {\r\n var theValue = cfgDefaults;\r\n if (cfgDefaults && _isConfigDefaults(cfgDefaults)) {\r\n theValue = _getDefault(dynamicHandler, theConfig, cfgDefaults);\r\n }\r\n if (theValue) {\r\n if (_isConfigDefaults(theValue)) {\r\n theValue = _resolveDefaultValue(dynamicHandler, theConfig, theValue);\r\n }\r\n var newValue_1;\r\n if (isArray(theValue)) {\r\n newValue_1 = [];\r\n newValue_1[_DYN_LENGTH /* @min:%2elength */] = theValue[_DYN_LENGTH /* @min:%2elength */];\r\n }\r\n else if (isPlainObject(theValue)) {\r\n newValue_1 = {};\r\n }\r\n if (newValue_1) {\r\n objForEachKey(theValue, function (key, value) {\r\n if (value && _isConfigDefaults(value)) {\r\n value = _resolveDefaultValue(dynamicHandler, theConfig, value);\r\n }\r\n newValue_1[key] = value;\r\n });\r\n theValue = newValue_1;\r\n }\r\n }\r\n return theValue;\r\n}\r\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 */\r\nexport function _applyDefaultValue(dynamicHandler, theConfig, name, defaultValue) {\r\n // Resolve the initial config value from the provided value or use the defined default\r\n var isValid;\r\n var setFn;\r\n var defValue;\r\n var cfgDefaults = defaultValue;\r\n var mergeDf;\r\n var reference;\r\n var readOnly;\r\n var blkDynamicValue;\r\n if (_isConfigDefaults(cfgDefaults)) {\r\n // looks like a IConfigDefault\r\n isValid = cfgDefaults.isVal;\r\n setFn = cfgDefaults.set;\r\n readOnly = cfgDefaults[_DYN_RD_ONLY /* @min:%2erdOnly */];\r\n blkDynamicValue = cfgDefaults[_DYN_BLK_VAL /* @min:%2eblkVal */];\r\n mergeDf = cfgDefaults.mrg;\r\n reference = cfgDefaults.ref;\r\n if (!reference && isUndefined(reference)) {\r\n reference = !!mergeDf;\r\n }\r\n defValue = _getDefault(dynamicHandler, theConfig, cfgDefaults);\r\n }\r\n else {\r\n defValue = defaultValue;\r\n }\r\n if (blkDynamicValue) {\r\n // Mark the property so that any value assigned will be blocked from conversion, we need to do this\r\n // before assigning or fetching the value to ensure it's not converted\r\n dynamicHandler[_DYN_BLK_VAL /* @min:%2eblkVal */](theConfig, name);\r\n }\r\n // Set the value to the default value;\r\n var theValue;\r\n var usingDefault = true;\r\n var cfgValue = theConfig[name];\r\n // try and get and user provided values\r\n if (cfgValue || !isNullOrUndefined(cfgValue)) {\r\n // Use the defined theConfig[name] value\r\n theValue = cfgValue;\r\n usingDefault = false;\r\n // The values are different and we have a special default value check, which is used to\r\n // override config values like empty strings to continue using the default\r\n if (isValid && theValue !== defValue && !isValid(theValue)) {\r\n theValue = defValue;\r\n usingDefault = true;\r\n }\r\n if (setFn) {\r\n theValue = setFn(theValue, defValue, theConfig);\r\n usingDefault = theValue === defValue;\r\n }\r\n }\r\n if (!usingDefault) {\r\n if (isPlainObject(theValue) || isArray(defValue)) {\r\n // we are using the user supplied value and it's an object\r\n if (mergeDf && defValue && (isPlainObject(defValue) || isArray(defValue))) {\r\n // Resolve/apply the defaults\r\n objForEachKey(defValue, function (dfName, dfValue) {\r\n // Sets the value and makes it dynamic (if it doesn't already exist)\r\n _applyDefaultValue(dynamicHandler, theValue, dfName, dfValue);\r\n });\r\n }\r\n }\r\n }\r\n else if (defValue) {\r\n // Just resolve the default\r\n theValue = _resolveDefaultValue(dynamicHandler, theConfig, defValue);\r\n }\r\n else {\r\n theValue = defValue;\r\n }\r\n // if (theValue && usingDefault && (isPlainObject(theValue) || isArray(theValue))) {\r\n // theValue = _cfgDeepCopy(theValue);\r\n // }\r\n // Needed to ensure that the (potentially) new field is dynamic even if null/undefined\r\n dynamicHandler.set(theConfig, name, theValue);\r\n if (reference) {\r\n dynamicHandler.ref(theConfig, name);\r\n }\r\n if (readOnly) {\r\n dynamicHandler[_DYN_RD_ONLY /* @min:%2erdOnly */](theConfig, name);\r\n }\r\n}\r\n//# sourceMappingURL=ConfigDefaults.js.map","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { ArrProto, INDEX_OF, LAST_INDEX_OF } from \"../internal/constants\";\r\nimport { _unwrapFunction } from \"../internal/unwrapFunction\";\r\n\r\n/**\r\n * The arrIndexOf() method returns the first index at which a given element can be found in the array,\r\n * or -1 if it is not present.\r\n * `arrIndexOf()` compares searchElement to elements of the Array using strict equality (the same\r\n * method used by the === or triple-equals operator).\r\n * @group Array\r\n * @group ArrayLike\r\n * @typeParam T - Identifies the type of array elements\r\n * @param theArray - The array or array like object of elements to be searched.\r\n * @param searchElement - The element to locate in the array.\r\n * @param fromIndex - The index to start the search at. If the index is greater than or equal to\r\n * the array's length, -1 is returned, which means the array will not be searched. If the provided\r\n * index value is a negative number, it is taken as the offset from the end of the array.\r\n * Note: if the provided index is negative, the array is still searched from front to back. If the\r\n * provided index is 0, then the whole array will be searched. Default: 0 (entire array is searched).\r\n * @return The first index of the element in the array; -1 if not found.\r\n * @example\r\n * ```ts\r\n * const array = [2, 9, 9];\r\n * arrIndexOf(array, 2); // 0\r\n * arrIndexOf(array, 7); // -1\r\n * arrIndexOf(array, 9, 2); // 2\r\n * arrIndexOf(array, 2, -1); // -1\r\n * arrIndexOf(array, 2, -3); // 0\r\n *\r\n * let indices: number[] = [];\r\n * const array = ['a', 'b', 'a', 'c', 'a', 'd'];\r\n * const element = 'a';\r\n * let idx = arrIndexOf(array, element);\r\n * while (idx !== -1) {\r\n * indices.push(idx);\r\n * idx = arrIndexOf(array, element, idx + 1);\r\n * }\r\n * console.log(indices);\r\n * // [0, 2, 4]\r\n *\r\n * function updateVegetablesCollection (veggies, veggie) {\r\n * if (arrIndexOf(veggies, veggie) === -1) {\r\n * veggies.push(veggie);\r\n * console.log('New veggies collection is : ' + veggies);\r\n * } else {\r\n * console.log(veggie + ' already exists in the veggies collection.');\r\n * }\r\n * }\r\n *\r\n * let veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];\r\n *\r\n * updateVegetablesCollection(veggies, 'spinach');\r\n * // New veggies collection is : potato,tomato,chillies,green-pepper,spinach\r\n * updateVegetablesCollection(veggies, 'spinach');\r\n * // spinach already exists in the veggies collection.\r\n *\r\n * // Array Like\r\n * let arrayLike = {\r\n * length: 3,\r\n * 0: \"potato\",\r\n * 1: \"tomato\",\r\n * 2: \"chillies\",\r\n * 3: \"green-pepper\" // Not checked as index is > length\r\n * };\r\n *\r\n * arrIndexOf(arrayLike, \"potato\"); // 0\r\n * arrIndexOf(arrayLike, \"tomato\"); // 1\r\n * arrIndexOf(arrayLike, \"chillies\"); 2\r\n * arrIndexOf(arrayLike, \"green-pepper\"); // -1\r\n * ```\r\n */\r\nexport const arrIndexOf: (theArray: ArrayLike, searchElement: T, fromIndex?: number) => number = _unwrapFunction(INDEX_OF, ArrProto);\r\n\r\n/**\r\n * The arrLastIndexOf() method returns the last index at which a given element can be found in the array,\r\n * or -1 if it is not present.\r\n * `arrLastIndexOf()` compares searchElement to elements of the Array using strict equality (the same\r\n * method used by the === or triple-equals operator). [NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN)\r\n * values are never compared as equal, so arrLastIndexOf() always returns -1 when searchElement is NaN.\r\n *\r\n * The arrLastIndexOf() method skips empty slots in sparse arrays.\r\n *\r\n * The arrLastIndexOf() method is generic. It only expects the this value to have a length property and integer-keyed properties.\r\n *\r\n * @since 0.8.0\r\n * @group Array\r\n * @group ArrayLike\r\n * @typeParam T - Identifies the type of array elements\r\n * @param theArray - The array or array like object of elements to be searched.\r\n * @param searchElement - The element to locate in the array.\r\n * @param fromIndex - Zero-based index at which to start searching backwards, converted to an integer.\r\n * - Negative index counts back from the end of the array — if fromIndex < 0, fromIndex + array.length is used.\r\n * - If fromIndex < -array.length, the array is not searched and -1 is returned. You can think of it conceptually\r\n * as starting at a nonexistent position before the beginning of the array and going backwards from there. There\r\n * are no array elements on the way, so searchElement is never found.\r\n * - If fromIndex >= array.length or fromIndex is omitted, array.length - 1 is used, causing the entire array to\r\n * be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements.\r\n * @return The first index of the element in the array; -1 if not found.\r\n * @example\r\n * ```ts\r\n * const numbers = [2, 5, 9, 2];\r\n * arrLastIndexOf(numbers, 2); // 3\r\n * arrLastIndexOf(numbers, 7); // -1\r\n * arrLastIndexOf(numbers, 2, 3); // 3\r\n * arrLastIndexOf(numbers, 2, 2); // 0\r\n * arrLastIndexOf(numbers, 2, -2); // 0\r\n * arrLastIndexOf(numbers, 2, -1); // 3\r\n *\r\n * let indices: number[] = [];\r\n * const array = [\"a\", \"b\", \"a\", \"c\", \"a\", \"d\"];\r\n * const element = \"a\";\r\n * let idx = arrLastIndexOf(array, element);\r\n * while (idx !== -1) {\r\n * indices.push(idx);\r\n * idx = arrLastIndexOf(array, element, idx ? idx - 1 : -(array.length + 1));\r\n * }\r\n * console.log(indices);\r\n * // [4, 2, 0]\r\n *\r\n * function updateVegetablesCollection (veggies, veggie) {\r\n * if (arrLastIndexOf(veggies, veggie) === -1) {\r\n * veggies.push(veggie);\r\n * console.log('New veggies collection is : ' + veggies);\r\n * } else {\r\n * console.log(veggie + ' already exists in the veggies collection.');\r\n * }\r\n * }\r\n *\r\n * let veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];\r\n *\r\n * updateVegetablesCollection(veggies, 'spinach');\r\n * // New veggies collection is : potato,tomato,chillies,green-pepper,spinach\r\n * updateVegetablesCollection(veggies, 'spinach');\r\n * // spinach already exists in the veggies collection.\r\n *\r\n * // Array Like\r\n * let arrayLike = {\r\n * length: 3,\r\n * 0: \"potato\",\r\n * 1: \"tomato\",\r\n * 2: \"chillies\",\r\n * 3: \"green-pepper\" // Not checked as index is > length\r\n * };\r\n *\r\n * arrLastIndexOf(arrayLike, \"potato\"); // 0\r\n * arrLastIndexOf(arrayLike, \"tomato\"); // 1\r\n * arrLastIndexOf(arrayLike, \"chillies\"); 2\r\n * arrLastIndexOf(arrayLike, \"green-pepper\"); // -1\r\n * ```\r\n */\r\nexport const arrLastIndexOf: (theArray: ArrayLike, searchElement: T, fromIndex?: number) => number = _unwrapFunction(LAST_INDEX_OF, ArrProto);","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { objForEachKey } from \"../object/for_each_key\";\r\n\r\n/**\r\n * @internal\r\n * @ignore\r\n * Internal constant enum used to identify the mapping values for the _createMap function\r\n */\r\nexport const enum eMapValues {\r\n Key = 0,\r\n Value = 1\r\n}\r\n\r\n/**\r\n * @internal\r\n * @ignore\r\n * Internal Helper function to create a key and value mapped representation of the values\r\n * @param values - The source values\r\n * @param keyType - Identifies the value to populate against the key\r\n * @param valueType - Identifies the value to populate against the value\r\n * @param completeFn - The function to call to complete the map (used to freeze the instance)\r\n * @returns\r\n */\r\nexport function _createKeyValueMap(values: any, keyType: eMapValues, valueType: eMapValues, completeFn: (value: T) => T) {\r\n let theMap: any = {};\r\n objForEachKey(values, (key, value) => {\r\n theMap[key] = keyType ? value : key;\r\n theMap[value] = valueType ? value : key;\r\n });\r\n\r\n return completeFn(theMap);\r\n}\r\n","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\nimport { createEnumKeyMap } from \"../helpers/enum\";\r\n\r\n/**\r\n * Identifies the Symbol static properties which are symbols themselves as a constant\r\n * enum to aid in minification when fetching them from the global symbol implementation.\r\n *\r\n * See: [Well Known Symbols](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol#well-known_symbols)\r\n * @group Symbol\r\n */\r\nexport const enum WellKnownSymbols {\r\n /**\r\n * The Symbol.asyncIterator symbol is a builtin symbol that is used to access an\r\n * object's @@asyncIterator method. In order for an object to be async iterable,\r\n * it must have a Symbol.asyncIterator key.\r\n *\r\n * See: [Symbol.asyncIterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator)\r\n */\r\n asyncIterator = 0,\r\n\r\n /**\r\n * The Symbol.hasInstance well-known symbol is used to determine if a constructor\r\n * object recognizes an object as its instance. The instanceof operator's behavior\r\n * can be customized by this symbol.\r\n *\r\n * See: [Symbol.hasInstance](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance)\r\n */\r\n hasInstance = 1,\r\n\r\n /**\r\n * The @@isConcatSpreadable symbol (Symbol.isConcatSpreadable) can be defined as an\r\n * own or inherited property and its value is a boolean. It can control behavior for\r\n * arrays and array-like objects:\r\n * - For array objects, the default behavior is to spread (flatten) elements.\r\n * Symbol.isConcatSpreadable can avoid flattening in these cases.\r\n * - For array-like objects, the default behavior is no spreading or flattening.\r\n * Symbol.isConcatSpreadable can force flattening in these cases.\r\n *\r\n * See: [Symbol.isConcatSpreadable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/isConcatSpreadable)\r\n */\r\n isConcatSpreadable = 2,\r\n\r\n /**\r\n * Whenever an object needs to be iterated (such as at the beginning of a for..of loop),\r\n * its @@iterator method is called with no arguments, and the returned iterator is used\r\n * to obtain the values to be iterated.\r\n *\r\n * See: [Symbol.iterator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator)\r\n */\r\n iterator = 3,\r\n\r\n /**\r\n * This function is also used to identify if objects have the behavior of regular expressions.\r\n * For example, the methods String.prototype.startsWith(), String.prototype.endsWith() and\r\n * String.prototype.includes(), check if their first argument is a regular expression and\r\n * will throw a TypeError if they are. Now, if the match symbol is set to false (or a Falsy\r\n * value), it indicates that the object is not intended to be used as a regular expression object.\r\n *\r\n * See: [Symbol.match](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/match)\r\n */\r\n match = 4,\r\n\r\n /**\r\n * The Symbol.matchAll well-known symbol returns an iterator, that yields matches of the regular\r\n * expression against a string. This function is called by the String.prototype.matchAll() method.\r\n *\r\n * See: [Symbol.matchAll](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/matchAll)\r\n */\r\n matchAll = 5,\r\n\r\n /**\r\n * The Symbol.replace well-known symbol specifies the method that replaces matched substrings\r\n * of a string. This function is called by the String.prototype.replace() method.\r\n *\r\n * For more information, [RegExp.prototype[@@replace]](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@replace)()\r\n * and [String.prototype.replace](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/replace)().\r\n *\r\n * See: [Symbol.replace](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/replace)\r\n */\r\n replace = 6,\r\n\r\n /**\r\n * The Symbol.search well-known symbol specifies the method that returns the index within a\r\n * string that matches the regular expression. This function is called by the\r\n * [String.prototype.search()](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/search)\r\n * method.\r\n *\r\n * For more information, see [RegExp.prototype[@@search]](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@search)()\r\n * and [String.prototype.search()](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/search).\r\n *\r\n * See: [Symbol.species](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/species)\r\n */\r\n search = 7,\r\n\r\n /**\r\n * The well-known symbol Symbol.species specifies a function-valued property that the constructor\r\n * function uses to create derived objects.\r\n * See: [Symbol.species](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/species)\r\n */\r\n species = 8,\r\n\r\n /**\r\n * The Symbol.split well-known symbol specifies the method that splits a string at the indices\r\n * that match a regular expression. This function is called by the String.prototype.split() method.\r\n *\r\n * For more information, see [RegExp.prototype[@@split]](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@split)()\r\n * and [String.prototype.split()](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/split).\r\n * See: [Symbol.split](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/split)\r\n */\r\n split = 9,\r\n\r\n /**\r\n * With the help of the Symbol.toPrimitive property (used as a function value), an object can be\r\n * converted to a primitive value. The function is called with a string argument hint, which\r\n * specifies the preferred type of the result primitive value. The hint argument can be one of\r\n * \"number\", \"string\", and \"default\".\r\n *\r\n * See: [Symbol.toPrimitive](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive)\r\n */\r\n toPrimitive = 10,\r\n\r\n /**\r\n * The Symbol.toStringTag well-known symbol is a string valued property that is used in the\r\n * creation of the default string description of an object. It is accessed internally by the\r\n * [Object.prototype.toString](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/toString)()\r\n * method.\r\n *\r\n * See: [Symbol.toStringTag](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag)\r\n */\r\n toStringTag = 11,\r\n\r\n /**\r\n * The Symbol.unscopables well-known symbol is used to specify an object value of whose own\r\n * and inherited property names are excluded from the with environment bindings of the associated\r\n * object.\r\n *\r\n * See: [Symbol.unscopables](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol/unscopables)\r\n */\r\n unscopables = 12\r\n}\r\n\r\n/**\r\n * @ignore\r\n * @internal\r\n */\r\nexport const _wellKnownSymbolMap = createEnumKeyMap({\r\n asyncIterator: WellKnownSymbols.asyncIterator,\r\n hasInstance: WellKnownSymbols.hasInstance,\r\n isConcatSpreadable: WellKnownSymbols.isConcatSpreadable,\r\n iterator: WellKnownSymbols.iterator,\r\n match: WellKnownSymbols.match,\r\n matchAll: WellKnownSymbols.matchAll,\r\n replace: WellKnownSymbols.replace,\r\n search: WellKnownSymbols.search,\r\n species: WellKnownSymbols.species,\r\n split: WellKnownSymbols.split,\r\n toPrimitive: WellKnownSymbols.toPrimitive,\r\n toStringTag: WellKnownSymbols.toStringTag,\r\n unscopables: WellKnownSymbols.unscopables\r\n});\r\n\r\n","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { WellKnownSymbols, _wellKnownSymbolMap } from \"../symbol/well_known\";\r\nimport { throwTypeError } from \"../helpers/throw\";\r\nimport { POLYFILL_TAG, SYMBOL } from \"../internal/constants\";\r\nimport { objHasOwn } from \"../object/has_own\";\r\nimport { asString } from \"../string/as_string\";\r\nimport { _GlobalPolySymbols, _getGlobalConfig } from \"../internal/global\";\r\nimport { strStartsWith } from \"../string/starts_with\";\r\n\r\nlet _polySymbols: _GlobalPolySymbols;\r\n\r\nfunction _globalSymbolRegistry(): _GlobalPolySymbols {\r\n if (!_polySymbols) {\r\n let gblCfg = _getGlobalConfig();\r\n _polySymbols = gblCfg.gblSym = gblCfg.gblSym || { k: {}, s:{} };\r\n }\r\n\r\n return _polySymbols;\r\n}\r\n\r\nlet _wellKnownSymbolCache: { [key in keyof typeof WellKnownSymbols ]: symbol } = {} as any;\r\n\r\n/**\r\n * Returns a new (polyfill) Symbol object for the provided description that's guaranteed to be unique.\r\n * Symbols are often used to add unique property keys to an object that won't collide with keys any\r\n * other code might add to the object, and which are hidden from any mechanisms other code will\r\n * typically use to access the object. That enables a form of weak encapsulation, or a weak form of\r\n * information hiding.\r\n * @group Polyfill\r\n * @group Symbol\r\n * @param description - The description of the symbol\r\n * @returns A new polyfill version of a Symbol object\r\n */\r\nexport function polyNewSymbol(description?: string | number): symbol {\r\n let theSymbol: symbol = {\r\n description: asString(description),\r\n toString: () => SYMBOL + \"(\" + description + \")\"\r\n } as symbol;\r\n\r\n // Tag the symbol so we know it a polyfill\r\n theSymbol[POLYFILL_TAG] = true;\r\n\r\n return theSymbol;\r\n}\r\n\r\n/**\r\n * Returns a Symbol object from the global symbol registry matching the given key if found.\r\n * Otherwise, returns a new symbol with this key.\r\n * @group Polyfill\r\n * @group Symbol\r\n * @param key key to search for.\r\n */\r\nexport function polySymbolFor(key: string): symbol {\r\n let registry = _globalSymbolRegistry();\r\n if (!objHasOwn(registry, key)) {\r\n let newSymbol = polyNewSymbol(key);\r\n registry.k[key] = newSymbol;\r\n registry.s[newSymbol] = asString(key);\r\n }\r\n\r\n return registry.k[key];\r\n}\r\n\r\n/**\r\n * Returns a key from the global symbol registry matching the given Symbol if found.\r\n * Otherwise, returns a undefined.\r\n * @group Polyfill\r\n * @group Symbol\r\n * @param sym Symbol to find the key for.\r\n */\r\nexport function polySymbolKeyFor(sym: symbol): string | undefined {\r\n if (!sym || !sym.toString || !strStartsWith(sym.toString(), SYMBOL)) {\r\n throwTypeError((sym as any) + \" is not a symbol\");\r\n }\r\n\r\n return _globalSymbolRegistry().s[sym];\r\n}\r\n\r\n/**\r\n * Returns the polyfill version of a well-known global symbol, this will only return\r\n * known values.\r\n * @example\r\n * ```ts\r\n * // Always returns the polyfill version, even if Symbols are supported in the runtime\r\n * polyGetKnownSymbol(\"toStringTag\") === polyGetKnownSymbol(\"toStringTag\"); // true\r\n * polyGetKnownSymbol(WellKnownSymbols.toStringTag) === polyGetKnownSymbol(\"toStringTag\"); // true\r\n * polyGetKnownSymbol(\"toStringTag\") !== Symbol.toStringTag; // true\r\n * polyGetKnownSymbol(WellKnownSymbols.toStringTag) !== Symbol.toStringTag; // true\r\n * polyGetKnownSymbol(\"toStringTag\") !== polySymbolFor(\"toStringTag\"); // true\r\n * polyGetKnownSymbol(WellKnownSymbols.toStringTag) !== polySymbolFor(\"toStringTag\"); // true\r\n * polyGetKnownSymbol(\"toStringTag\") !== polyNewSymbol(\"toStringTag\"); // true\r\n * polyGetKnownSymbol(WellKnownSymbols.toStringTag) !== polyNewSymbol(\"toStringTag\"); // true\r\n * ```\r\n * @group Polyfill\r\n * @group Symbol\r\n * @param name - The property name to return (if it exists) for Symbol\r\n * @returns The value of the property if present\r\n */\r\nexport function polyGetKnownSymbol(name: string | WellKnownSymbols): symbol {\r\n let result: symbol;\r\n let knownName = _wellKnownSymbolMap[name];\r\n if (knownName) {\r\n result = _wellKnownSymbolCache[knownName] = _wellKnownSymbolCache[knownName] || polyNewSymbol(SYMBOL + \".\" + knownName);\r\n }\r\n\r\n return result\r\n}\r\n","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { eMapValues, _createKeyValueMap } from \"../internal/map\";\r\nimport { objForEachKey } from \"../object/for_each_key\";\r\nimport { objDeepFreeze } from \"../object/object\";\r\n\r\n/**\r\n * A type that identifies an enum class generated from a constant enum.\r\n * @group Enum\r\n * @typeParam E - The constant enum type\r\n *\r\n * Returned from {@link createEnum}\r\n */\r\nexport declare type EnumCls = { readonly [key in keyof E extends string | number | symbol ? keyof E : never]: key extends string ? E[key] : key };\r\n\r\n/**\r\n * A type that identifies an object whose property values are generally mapped to the key of the source type.\r\n * @group Enum\r\n * @typeParam E - The source constant enum type which isendifies the keys and values\r\n * @typeParam I - The resulting set of keys from the source type.\r\n *\r\n * Returned from {@link createEnumKeyMap}\r\n */\r\nexport declare type EnumNameMap = { readonly [key in keyof E extends string | number | symbol ? keyof E : never]: key extends string ? key : keyof E } & I;\r\n\r\n/**\r\n * A type that identifies an object whose property values are mapped to the resulting values of the source objects keys.\r\n * @group Enum\r\n * @typeParam E - The source type which identifies the keys.\r\n * @typeParam V - The resulting set of keys from the source type.\r\n *\r\n * Returned from {@link createEnumValueMap}\r\n */\r\nexport declare type EnumValueMap = { readonly [key in keyof E extends string | number | symbol ? keyof E : never]: key extends string ? E[key] : E[key] } & V;\r\n\r\n/**\r\n * A type that maps the keys of E to the type of V.\r\n * @group Enum\r\n * @typeParam E - The type of object that defines the Key (typically a constant enum)\r\n * @typeParam V - The value type, typically `string`, `number` but may also be a complex type.\r\n *\r\n * Returned from {@link createSimpleMap}\r\n */\r\nexport declare type EnumTypeMap = { readonly [key in keyof E extends string ? keyof E : never]: V };\r\n\r\n/**\r\n * Create a TypeScript style enum class which is a mapping that maps from the key -> value and the value -> key.\r\n * This is effectively the same as defining a non-constant enum, but this only repeats the \"Name\" of the enum value once.\r\n * @group Enum\r\n * @example\r\n * ```ts\r\n * const enum Animal {\r\n * Dog = 0,\r\n * Cat = 1,\r\n * Butterfly = 2,\r\n * Bear = 3\r\n * }\r\n * const Animals = createEnum({\r\n * Dog: Animal.Dog,\r\n * Cat: Animal.Cat,\r\n * Butterfly: Animal.Butterfly,\r\n * Bear: Animal.Bear\r\n * });\r\n * // You end up with an object that maps everything to the name\r\n * Animals.Dog === 0; // true\r\n * Animals[0] === \"Dog\"; // true\r\n * Animals[\"Dog\"] === 0; // true\r\n * Animals.Cat === 1; // true\r\n * Animals[1] === \"Cat\"; // true\r\n * Animals[\"Cat\"] === 1; // true\r\n * ```\r\n\r\n * @param values - The values to populate on the new object\r\n * @typeParam E - Identifies the const enum type being mapped\r\n * @returns A new frozen (immutable) object which looks and acts like a TypeScript Enum class.\r\n */\r\nexport function createEnum(values: { [key in keyof E]: E[keyof E] }): EnumCls {\r\n return _createKeyValueMap(values, eMapValues.Value, eMapValues.Key, objDeepFreeze);\r\n}\r\n\r\n/**\r\n * Create a map object which contains both the property key and value which both map to the key,\r\n * E[key] => key and E[value] => key.\r\n * @group Enum\r\n * @example\r\n * ```ts\r\n * const enum Animal {\r\n * Dog = 0,\r\n * Cat = 1,\r\n * Butterfly = 2,\r\n * Bear = 3\r\n * }\r\n * const animalMap = createEnumKeyMap({\r\n * Dog: Animal.Dog,\r\n * Cat: Animal.Cat,\r\n * Butterfly: Animal.Butterfly,\r\n * Bear: Animal.Bear\r\n * });\r\n * // You end up with an object that maps everything to the name\r\n * animalMap.Dog === \"Dog\"; // true\r\n * animalMap[0] === \"Dog\"; // true\r\n * animalMap[\"Dog\"] === \"Dog\"; // true\r\n * animalMap.Cat === \"Cat\"; // true\r\n * animalMap[1] === \"Cat\"; // true\r\n * animalMap[\"Cat\"] === \"Cat\"; // true\r\n * // Helper function to always return the \"Name\" of the type of animal\r\n * function getAnimalType(type: string | number | Animal) {\r\n * return animalMap[type];\r\n * }\r\n * ```\r\n * @param values - The values to populate on the new object\r\n * @typeParam E - Identifies the const enum type being mapped\r\n * @returns A new frozen (immutable) object which contains a property for each key and value that returns the value.\r\n */\r\nexport function createEnumKeyMap(values: { [key in keyof E]: E[keyof E] }): EnumNameMap {\r\n return _createKeyValueMap(values, eMapValues.Key, eMapValues.Key, objDeepFreeze);\r\n}\r\n\r\n/**\r\n * Create a map object which contains both the perperty key and value which both map to the resulting value,\r\n * E[key] => value and E[value] => value.\r\n * @group Enum\r\n * @example\r\n * ```ts\r\n * const enum Animal {\r\n * Dog = 0,\r\n * Cat = 1,\r\n * Butterfly = 2,\r\n * Bear = 3\r\n * }\r\n * const animalMap = createEnumValueMap({\r\n * Dog: Animal.Dog,\r\n * Cat: Animal.Cat,\r\n * Butterfly: Animal.Butterfly,\r\n * Bear: Animal.Bear\r\n * });\r\n * // You end up with an object that maps everything to the name\r\n * animalMap.Dog === 0; // true\r\n * animalMap[0] === 0; // true\r\n * animalMap[\"Dog\"] === 0; // true\r\n * animalMap.Cat === 1; // true\r\n * animalMap[1] === 1; // true\r\n * animalMap[\"Cat\"] === 1; // true\r\n *\r\n * // Helper function to always return the \"Name\" of the type of animal\r\n * function getAnimalValue(type: string | number | Animal) {\r\n * return animalMap[type];\r\n * }\r\n * ```\r\n\r\n * @param values - The values to populate on the new object\r\n * @typeParam E - Identifies the const enum type being mapped\r\n * @returns A new frozen (immutable) object which contains a property for each key and value that returns the value.\r\n */\r\nexport function createEnumValueMap(values: { [key in keyof E]: E[keyof E] }): EnumValueMap {\r\n return _createKeyValueMap(values, eMapValues.Value, eMapValues.Value, objDeepFreeze);\r\n}\r\n\r\n/**\r\n * Create a map object which contains both the perperty key and value which both map to the requested\r\n * generic mapValue with a type of V, E[key] => mapValue and E[value] => mapValue.\r\n * @group Enum\r\n * @example\r\n * ```ts\r\n * const enum Animal {\r\n * Dog = 0,\r\n * Cat = 1,\r\n * Butterfly = 2,\r\n * Bear = 3\r\n * };\r\n * // Creates a simple mapping to a string value\r\n * const animalFamilyMap = createValueMap({\r\n * Dog: [ Animal.Dog, \"Canidae\"],\r\n * Cat: [ Animal.Cat, \"Felidae\"],\r\n * Butterfly: [ Animal.Butterfly, \"Papilionidae\"],\r\n * Bear: [ Animal.Bear, \"Ursidae\"]\r\n * });\r\n * // You end up with an object that maps everything to the name\r\n * animalMap.Dog === \"Canidae\"; // true with typeof animalMap.Dog is \"string\"\r\n * animalMap[0] === \"Canidae\"; // true with typeof animalMap[0] is \"string\"\r\n * animalMap[\"Dog\"] === \"Canidae\"; // true with typeof animalMap[\"Dog\"] is \"string\"\r\n * animalMap.Cat === \"Felidae\"; // true with typeof animalMap.Cat is \"string\"\r\n * animalMap[1] === \"Felidae\"; // true with typeof animalMap[1] is \"string\"\r\n * animalMap[\"Cat\"] === \"Felidae\"; // true with typeof animalMap[\"Cat\"] is \"string\"\r\n * ```\r\n * @param values - The values to populate on the new object\r\n * @typeParam E - Identifies the const enum type (eg. typeof Animal);\r\n * @typeParam V - Identifies the type of the mapping `string`; `number`; etc is not restructed to primitive types.\r\n * @returns A new frozen (immutable) object which contains a property for each key and value that returns the defiend mapped value.\r\n */\r\nexport function createSimpleMap(values: { [key in keyof E]: [ E[keyof E], V] }): EnumTypeMap {\r\n let mapClass: any = {};\r\n objForEachKey(values, (key, value) => {\r\n mapClass[key] = value[1];\r\n mapClass[value[0]] = value[1];\r\n });\r\n\r\n return objDeepFreeze(mapClass);\r\n}\r\n\r\n/**\r\n * Create a strongly types map object which contains both the perperty key and value which both map\r\n * to the requested mapValue,\r\n * E[key] => mapValue and E[value] => mapValue.\r\n * - E = the const enum type (typeof Animal);\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 * @group Enum\r\n * @example\r\n * ```ts\r\n * // Create a strongly types map\r\n * const animalFamilyMap = createTypeMap({\r\n * Dog: [ Animal.Dog, \"Canidae\"],\r\n * Cat: [ Animal.Cat, \"Felidae\"],\r\n * Butterfly: [ Animal.Butterfly, \"Papilionidae\"],\r\n * Bear: [ Animal.Bear, \"Ursidae\"]\r\n * });\r\n * // You end up with a strongly types result for each value\r\n * animalMap.Dog === \"Canidae\"; // true with typeof animalMap.Dog is (const) \"Canidae\"\r\n * animalMap[0] === \"Canidae\"; // true with typeof animalMap[0] is \"Canidae\"\r\n * animalMap[\"Dog\"] === \"Canidae\"; // true with typeof animalMap[\"Dog\"] is \"Canidae\"\r\n * animalMap.Cat === \"Felidae\"; // true with typeof animalMap.Cat is \"Felidae\"\r\n * animalMap[1] === \"Felidae\"; // true with typeof animalMap[1] is \"Felidae\"\r\n * animalMap[\"Cat\"] === \"Felidae\"; // true with typeof animalMap[\"Cat\"] is \"Felidae\"\r\n *\r\n * or using an interface to define the direct string mappings\r\n *\r\n * interface IAnimalFamilyMap {\r\n * Dog: \"Canidae\",\r\n * Cat: \"Felidae\",\r\n * Butterfly: \"Papilionidae\",\r\n * Bear: \"Ursidae\"\r\n * }\r\n *\r\n * // Create a strongly types map\r\n * const animalFamilyMap = createTypeMap({\r\n * Dog: [ Animal.Dog, \"Canidae\"],\r\n * Cat: [ Animal.Cat, \"Felidae\"],\r\n * Butterfly: [ Animal.Butterfly, \"Papilionidae\"],\r\n * Bear: [ Animal.Bear, \"Ursidae\"]\r\n * });\r\n *\r\n * // You also end up with a strongly types result for each value\r\n * animalMap.Dog === \"Canidae\"; // true with typeof animalMap.Dog is (const) \"Canidae\"\r\n * animalMap[0] === \"Canidae\"; // true with typeof animalMap[0] is \"Canidae\"\r\n * animalMap[\"Dog\"] === \"Canidae\"; // true with typeof animalMap[\"Dog\"] is \"Canidae\"\r\n * animalMap.Cat === \"Felidae\"; // true with typeof animalMap.Cat is \"Felidae\"\r\n * animalMap[1] === \"Felidae\"; // true with typeof animalMap[1] is \"Felidae\"\r\n * animalMap[\"Cat\"] === \"Felidae\"; // true with typeof animalMap[\"Cat\"] is \"Felidae\"\r\n * ```\r\n * @param values - The values to populate on the new object\r\n * @typeParam E - Identifies the enum type\r\n * @typeParam T - Identifies the return type that is being created via the mapping.\r\n * @returns A new frozen (immutable) object which contains a property for each key and value that returns the defiend mapped value.\r\n */\r\nexport function createTypeMap(values: { [key in keyof E]: [ E[keyof E], T[keyof T] ] }): T {\r\n return createSimpleMap(values as any) as unknown as T;\r\n}","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { NULL_VALUE, SYMBOL, UNDEF_VALUE } from \"../internal/constants\";\r\nimport { polyGetKnownSymbol, polyNewSymbol, polySymbolFor, polySymbolKeyFor } from \"../polyfills/symbol\";\r\nimport { WellKnownSymbols, _wellKnownSymbolMap } from \"./well_known\";\r\nimport { _createIs } from \"../helpers/base\";\r\nimport { ILazyValue, _globalLazyTestHooks } from \"../helpers/lazy\";\r\nimport { safeGetLazy } from \"../helpers/safe_lazy\";\r\nimport { lazySafeGetInst } from \"../helpers/environment\";\r\n\r\nlet _symbol: ILazyValue;\r\nlet _symbolFor: ILazyValue<(key: string) => symbol>;\r\nlet _symbolKeyFor: ILazyValue<(sym: symbol) => string | undefined>;\r\n\r\nfunction _getSymbolValue(name: string): ILazyValue {\r\n return safeGetLazy(function() {\r\n return (_symbol.v ? _symbol[name] : UNDEF_VALUE) as T;\r\n }, UNDEF_VALUE);\r\n}\r\n\r\n/**\r\n * Checks if the type of value is a symbol.\r\n * @group Symbol\r\n * @param {any} value - Value to be checked.\r\n * @return {boolean} True if the value is a symbol, false otherwise.\r\n */\r\nexport const isSymbol: (value: any) => value is symbol = _createIs(\"symbol\");\r\n\r\n/**\r\n * Helper to identify whether the runtime support the Symbols either via native or an installed polyfill\r\n * @group Symbol\r\n * @returns true if Symbol's are support otherwise false\r\n */\r\nexport function hasSymbol(): boolean {\r\n return !!getSymbol();\r\n}\r\n\r\n/**\r\n * If Symbols are supported then attempt to return the named Symbol\r\n * @group Symbol\r\n * @returns The value of the named Symbol (if available)\r\n */\r\nexport function getSymbol(): Symbol {\r\n let resetCache = !_symbol || (_globalLazyTestHooks && _globalLazyTestHooks.lzy && !_symbol.b);\r\n resetCache && (_symbol = lazySafeGetInst(SYMBOL));\r\n (!_symbolFor || resetCache) && (_symbolFor = _getSymbolValue(\"for\"));\r\n (!_symbolKeyFor || resetCache) && (_symbolKeyFor = _getSymbolValue(\"keyFor\"));\r\n \r\n return _symbol.v;\r\n}\r\n\r\n/**\r\n * If Symbols are supported then get the property of the global Symbol, if Symbol's are\r\n * not supported and noPoly is true it returns null. Used to access the well known symbols.\r\n * @group Symbol\r\n * @param name - The property name to return (if it exists) for Symbol\r\n * @param noPoly - Flag indicating whether to return a polyfill if symbols are not supported.\r\n * @returns The value of the property if present\r\n * @example\r\n * ```ts\r\n * // If Symbol is supported in the runtime\r\n * getKnownSymbol(\"toStringTag\") === Symbol.toStringTag; // true\r\n * getKnownSymbol(WellKnownSymbols.toStringTag) === Symbol.toStringTag; // true\r\n * ```\r\n */\r\nexport function getKnownSymbol(name: string | WellKnownSymbols, noPoly?: boolean): T {\r\n let knownName = _wellKnownSymbolMap[name];\r\n // Cause lazy symbol to get initialized\r\n (!_symbol || (_globalLazyTestHooks.lzy && !_symbol.b)) && getSymbol();\r\n\r\n return _symbol.v ? _symbol.v[knownName || name] : (!noPoly ? polyGetKnownSymbol(name) : UNDEF_VALUE);\r\n}\r\n\r\n/**\r\n * Returns a new unique Symbol value. If noPoly is true and symbols are not supported\r\n * then this will return null.\r\n * @group Symbol\r\n * @param description Description of the new Symbol object.\r\n * @param noPoly - Flag indicating whether to return a polyfil if symbols are not supported.\r\n * @returns The new symbol\r\n */\r\nexport function newSymbol(description?: string | number, noPoly?: boolean): symbol {\r\n // Cause lazy _symbol to get initialized\r\n (!_symbol || (_globalLazyTestHooks.lzy && !_symbol.b)) && getSymbol();\r\n\r\n return _symbol.v ? (_symbol.v as any)(description) : (!noPoly ? polyNewSymbol(description) : NULL_VALUE);\r\n}\r\n\r\n/**\r\n * Returns a Symbol object from the global symbol registry matching the given key if found.\r\n * Otherwise, returns a new symbol with this key. This will always return a polyfill if symbols\r\n * are not supported.\r\n * @group Symbol\r\n * @param key key to search for.\r\n */\r\nexport function symbolFor(key: string): symbol {\r\n // Cause lazy symbol to get initialized\r\n (!_symbolFor || (_globalLazyTestHooks.lzy && !_symbol.b)) && getSymbol();\r\n\r\n return (_symbolFor.v || polySymbolFor)(key);\r\n}\r\n\r\n/**\r\n * Returns a key from the global symbol registry matching the given Symbol if found.\r\n * Otherwise, returns a undefined. This will always attempt to lookup the polyfill\r\n * implementation if symbols are not supported\r\n * @group Symbol\r\n * @param sym Symbol to find the key for.\r\n */\r\nexport function symbolKeyFor(sym: symbol): string | undefined {\r\n // Cause lazy symbol to get initialized\r\n (!_symbolKeyFor || (_globalLazyTestHooks.lzy && !_symbol.b)) && getSymbol();\r\n\r\n return (_symbolKeyFor.v || polySymbolKeyFor)(sym);\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { isArray, isPlainObject, objForEachKey, symbolFor, throwTypeError } from \"@nevware21/ts-utils\";\r\nimport { _DYN_LENGTH } from \"../__DynamicConstants\";\r\n// Using Symbol.for so that if the same symbol was already created it would be returned\r\n// To handle multiple instances using potentially different versions we are not using\r\n// createUniqueNamespace()\r\nexport var CFG_HANDLER_LINK = symbolFor(\"[[ai_dynCfg_1]]\");\r\n/**\r\n * @internal\r\n * @ignore\r\n * The symbol to tag objects / arrays with if they should not be converted\r\n */\r\nvar BLOCK_DYNAMIC = symbolFor(\"[[ai_blkDynCfg_1]]\");\r\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 */\r\nvar FORCE_DYNAMIC = symbolFor(\"[[ai_frcDynCfg_1]]\");\r\nexport function _cfgDeepCopy(source) {\r\n if (source) {\r\n var target_1;\r\n if (isArray(source)) {\r\n target_1 = [];\r\n target_1[_DYN_LENGTH /* @min:%2elength */] = source[_DYN_LENGTH /* @min:%2elength */];\r\n }\r\n else if (isPlainObject(source)) {\r\n target_1 = {};\r\n }\r\n if (target_1) {\r\n // Copying index values by property name as the extensionConfig can be an array or object\r\n objForEachKey(source, function (key, value) {\r\n // Perform a deep copy of the object\r\n target_1[key] = _cfgDeepCopy(value);\r\n });\r\n return target_1;\r\n }\r\n }\r\n return source;\r\n}\r\n/**\r\n * @internal\r\n * Get the dynamic config handler if the value is already dynamic\r\n * @param value\r\n * @returns\r\n */\r\nexport function getDynamicConfigHandler(value) {\r\n if (value) {\r\n var handler = value[CFG_HANDLER_LINK] || value;\r\n if (handler.cfg && (handler.cfg === value || handler.cfg[CFG_HANDLER_LINK] === handler)) {\r\n return handler;\r\n }\r\n }\r\n return null;\r\n}\r\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 */\r\nexport function blockDynamicConversion(value) {\r\n if (value && (isPlainObject(value) || isArray(value))) {\r\n try {\r\n value[BLOCK_DYNAMIC] = true;\r\n }\r\n catch (e) {\r\n // Don't throw for this case as it's an ask only\r\n }\r\n }\r\n return value;\r\n}\r\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 */\r\nexport function forceDynamicConversion(value) {\r\n if (value) {\r\n try {\r\n value[FORCE_DYNAMIC] = true;\r\n }\r\n catch (e) {\r\n // Don't throw for this case as it's an ask only\r\n }\r\n }\r\n return value;\r\n}\r\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 */\r\nexport function _canMakeDynamic(getFunc, state, value) {\r\n var result = false;\r\n // Object must exist and be truthy\r\n if (value && !getFunc[state.blkVal]) {\r\n // Tagged as always convert\r\n result = value[FORCE_DYNAMIC];\r\n // Check that it's not explicitly tagged as blocked\r\n if (!result && !value[BLOCK_DYNAMIC]) {\r\n // Only convert plain objects or arrays by default\r\n result = isPlainObject(value) || isArray(value);\r\n }\r\n }\r\n return result;\r\n}\r\n/**\r\n * Throws an invalid access exception\r\n * @param message - The message to include in the exception\r\n */\r\nexport function throwInvalidAccess(message) {\r\n throwTypeError(\"InvalidAccess:\" + message);\r\n}\r\n//# sourceMappingURL=DynamicSupport.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { arrForEach, arrIndexOf, dumpObj, isArray, objDefine, objDefineProp, objForEachKey, objGetOwnPropertyDescriptor } from \"@nevware21/ts-utils\";\r\nimport { UNDEFINED_VALUE } from \"../JavaScriptSDK/InternalConstants\";\r\nimport { _DYN_APPLY, _DYN_HDLR, _DYN_LOGGER, _DYN_PUSH, _DYN_SPLICE, _DYN_THROW_INTERNAL } from \"../__DynamicConstants\";\r\nimport { CFG_HANDLER_LINK, _canMakeDynamic, blockDynamicConversion, throwInvalidAccess } from \"./DynamicSupport\";\r\nvar arrayMethodsToPatch = [\r\n \"push\",\r\n \"pop\",\r\n \"shift\",\r\n \"unshift\",\r\n \"splice\"\r\n];\r\nexport var _throwDynamicError = function (logger, name, desc, e) {\r\n logger && logger[_DYN_THROW_INTERNAL /* @min:%2ethrowInternal */](3 /* eLoggingSeverity.DEBUG */, 108 /* _eInternalMessageId.DynamicConfigException */, \"\".concat(desc, \" [\").concat(name, \"] failed - \") + dumpObj(e));\r\n};\r\nfunction _patchArray(state, target, name) {\r\n if (isArray(target)) {\r\n // Monkey Patch the methods that might change the array\r\n arrForEach(arrayMethodsToPatch, function (method) {\r\n var orgMethod = target[method];\r\n target[method] = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n var result = orgMethod[_DYN_APPLY /* @min:%2eapply */](this, args);\r\n // items may be added, removed or moved so need to make some new dynamic properties\r\n _makeDynamicObject(state, target, name, \"Patching\");\r\n return result;\r\n };\r\n });\r\n }\r\n}\r\nfunction _getOwnPropGetter(target, name) {\r\n var propDesc = objGetOwnPropertyDescriptor(target, name);\r\n return propDesc && propDesc.get;\r\n}\r\nfunction _createDynamicProperty(state, theConfig, name, value) {\r\n // Does not appear to be dynamic so lets make it so\r\n var detail = {\r\n n: name,\r\n h: [],\r\n trk: function (handler) {\r\n if (handler && handler.fn) {\r\n if (arrIndexOf(detail.h, handler) === -1) {\r\n // Add this handler to the collection that should be notified when the value changes\r\n detail.h[_DYN_PUSH /* @min:%2epush */](handler);\r\n }\r\n state.trk(handler, detail);\r\n }\r\n },\r\n clr: function (handler) {\r\n var idx = arrIndexOf(detail.h, handler);\r\n if (idx !== -1) {\r\n detail.h[_DYN_SPLICE /* @min:%2esplice */](idx, 1);\r\n }\r\n }\r\n };\r\n // Flag to optimize lookup response time by avoiding additional function calls\r\n var checkDynamic = true;\r\n var isObjectOrArray = false;\r\n function _getProperty() {\r\n if (checkDynamic) {\r\n isObjectOrArray = isObjectOrArray || _canMakeDynamic(_getProperty, state, value);\r\n // Make sure that if it's an object that we make it dynamic\r\n if (value && !value[CFG_HANDLER_LINK] && isObjectOrArray) {\r\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\r\n value = _makeDynamicObject(state, value, name, \"Converting\");\r\n }\r\n // If it needed to be converted it now has been\r\n checkDynamic = false;\r\n }\r\n // If there is an active handler then add it to the tracking set of handlers\r\n var activeHandler = state.act;\r\n if (activeHandler) {\r\n detail.trk(activeHandler);\r\n }\r\n return value;\r\n }\r\n // Tag this getter as our dynamic property and provide shortcut for notifying a change\r\n _getProperty[state.prop] = {\r\n chng: function () {\r\n state.add(detail);\r\n }\r\n };\r\n function _setProperty(newValue) {\r\n if (value !== newValue) {\r\n if (!!_getProperty[state.ro] && !state.upd) {\r\n // field is marked as readonly so return false\r\n throwInvalidAccess(\"[\" + name + \"] is read-only:\" + dumpObj(theConfig));\r\n }\r\n if (checkDynamic) {\r\n isObjectOrArray = isObjectOrArray || _canMakeDynamic(_getProperty, state, value);\r\n checkDynamic = false;\r\n }\r\n // The value must be a plain object or an array to enforce the reference (in-place updates)\r\n var isReferenced = isObjectOrArray && _getProperty[state.rf];\r\n if (isObjectOrArray) {\r\n // We are about to replace a plain object or an array\r\n if (isReferenced) {\r\n // Reassign the properties from the current value to the same properties from the newValue\r\n // This will set properties not in the newValue to undefined\r\n objForEachKey(value, function (key) {\r\n value[key] = newValue ? newValue[key] : UNDEFINED_VALUE;\r\n });\r\n // Now assign / re-assign value with all of the keys from newValue\r\n try {\r\n objForEachKey(newValue, function (key, theValue) {\r\n _setDynamicProperty(state, value, key, theValue);\r\n });\r\n // Now drop newValue so when we assign value later it keeps the existing reference\r\n newValue = value;\r\n }\r\n catch (e) {\r\n // Unable to convert to dynamic property so just leave as non-dynamic\r\n _throwDynamicError((state.hdlr || {})[_DYN_LOGGER /* @min:%2elogger */], name, \"Assigning\", e);\r\n // Mark as not an object or array so we don't try and do this again\r\n isObjectOrArray = false;\r\n }\r\n }\r\n else if (value && value[CFG_HANDLER_LINK]) {\r\n // As we are replacing the value, if it's already dynamic then we need to notify the listeners\r\n // for every property it has already\r\n objForEachKey(value, function (key) {\r\n // Check if the value is dynamic\r\n var getter = _getOwnPropGetter(value, key);\r\n if (getter) {\r\n // And if it is tell it's listeners that the value has changed\r\n var valueState = getter[state.prop];\r\n valueState && valueState.chng();\r\n }\r\n });\r\n }\r\n }\r\n if (newValue !== value) {\r\n var newIsObjectOrArray = newValue && _canMakeDynamic(_getProperty, state, newValue);\r\n if (!isReferenced && newIsObjectOrArray) {\r\n // As the newValue is an object/array lets preemptively make it dynamic\r\n newValue = _makeDynamicObject(state, newValue, name, \"Converting\");\r\n }\r\n // Now assign the internal \"value\" to the newValue\r\n value = newValue;\r\n isObjectOrArray = newIsObjectOrArray;\r\n }\r\n // Cause any listeners to be scheduled for notification\r\n state.add(detail);\r\n }\r\n }\r\n objDefine(theConfig, detail.n, { g: _getProperty, s: _setProperty });\r\n}\r\nexport function _setDynamicProperty(state, target, name, value) {\r\n if (target) {\r\n // To be a dynamic property it needs to have a get function\r\n var getter = _getOwnPropGetter(target, name);\r\n var isDynamic = getter && !!getter[state.prop];\r\n if (!isDynamic) {\r\n _createDynamicProperty(state, target, name, value);\r\n }\r\n else {\r\n // Looks like it's already dynamic just assign the new value\r\n target[name] = value;\r\n }\r\n }\r\n return target;\r\n}\r\nexport function _setDynamicPropertyState(state, target, name, flags) {\r\n if (target) {\r\n // To be a dynamic property it needs to have a get function\r\n var getter = _getOwnPropGetter(target, name);\r\n var isDynamic = getter && !!getter[state.prop];\r\n var inPlace = flags && flags[0 /* _eSetDynamicPropertyFlags.inPlace */];\r\n var rdOnly = flags && flags[1 /* _eSetDynamicPropertyFlags.readOnly */];\r\n var blkProp = flags && flags[2 /* _eSetDynamicPropertyFlags.blockDynamicProperty */];\r\n if (!isDynamic) {\r\n if (blkProp) {\r\n try {\r\n // Attempt to mark the target as blocked from conversion\r\n blockDynamicConversion(target);\r\n }\r\n catch (e) {\r\n _throwDynamicError((state.hdlr || {})[_DYN_LOGGER /* @min:%2elogger */], name, \"Blocking\", e);\r\n }\r\n }\r\n try {\r\n // Make sure it's dynamic so that we can tag the property as per the state\r\n _setDynamicProperty(state, target, name, target[name]);\r\n getter = _getOwnPropGetter(target, name);\r\n }\r\n catch (e) {\r\n // Unable to convert to dynamic property so just leave as non-dynamic\r\n _throwDynamicError((state.hdlr || {})[_DYN_LOGGER /* @min:%2elogger */], name, \"State\", e);\r\n }\r\n }\r\n // Assign the optional flags if true\r\n if (inPlace) {\r\n getter[state.rf] = inPlace;\r\n }\r\n if (rdOnly) {\r\n getter[state.ro] = rdOnly;\r\n }\r\n if (blkProp) {\r\n getter[state.blkVal] = true;\r\n }\r\n }\r\n return target;\r\n}\r\nexport function _makeDynamicObject(state, target, name, desc) {\r\n try {\r\n // Assign target with new value properties (converting into dynamic properties in the process)\r\n objForEachKey(target, function (key, value) {\r\n // Assign and/or make the property dynamic\r\n _setDynamicProperty(state, target, key, value);\r\n });\r\n if (!target[CFG_HANDLER_LINK]) {\r\n // Link the config back to the dynamic config details\r\n objDefineProp(target, CFG_HANDLER_LINK, {\r\n get: function () {\r\n return state[_DYN_HDLR /* @min:%2ehdlr */];\r\n }\r\n });\r\n _patchArray(state, target, name);\r\n }\r\n }\r\n catch (e) {\r\n // Unable to convert to dynamic property so just leave as non-dynamic\r\n _throwDynamicError((state.hdlr || {})[_DYN_LOGGER /* @min:%2elogger */], name, desc, e);\r\n }\r\n return target;\r\n}\r\n//# sourceMappingURL=DynamicProperty.js.map","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { ArrProto, SLICE } from \"../internal/constants\";\r\nimport { _unwrapFunction } from \"../internal/unwrapFunction\";\r\n\r\n/**\r\n * The arrSlice() method returns a shallow copy of a portion of an array into a new array object\r\n * selected from start to end (end not included) where start and end represent the index of items\r\n * in that array. The original array will not be modified.\r\n *\r\n * The `arrSlice()` method is a copying method. It does not alter this but instead returns a shallow\r\n * copy that contains some of the same elements as the ones from the original array.\r\n *\r\n * The `arrSlice()` method preserves empty slots. If the sliced portion is sparse, the returned arra\r\n * is sparse as well.\r\n *\r\n * The `arrSlice()` method is generic. It only expects the this value to have a length property and\r\n * integer-keyed properties.\r\n *\r\n * For both start and end, a negative index can be used to indicate an offset from the end of the array.\r\n * For example, -2 refers to the second to last element of the array.\r\n * @since 0.9.3\r\n * @group Array\r\n * @group ArrayLike\r\n * @param start Zero-based index at which to start extraction, converted to an integer.\r\n * - Negative index counts back from the end of the array — if start < 0, start + array.length is used.\r\n * - If start < -array.length or start is omitted, 0 is used.\r\n * - If start >= array.length, nothing is extracted.\r\n * @param end Zero-based index at which to end extraction, converted to an integer. slice() extracts\r\n * up to but not including end.\r\n * - Negative index counts back from the end of the array — if end < 0, end + array.length is used.\r\n * - If end < -array.length, 0 is used.\r\n * - If end >= array.length or end is omitted, array.length is used, causing all elements until the\r\n * end to be extracted.\r\n * - If end is positioned before or at start after normalization, nothing is extracted.\r\n * @example\r\n * ```ts\r\n * const lyrics = [\"Hello\", \"Darkness\", \"my\", \"old\", \"friend.\", \"I've\", \"come\", \"to\", \"talk\" ];\r\n *\r\n * arrSlice(lyrics); // [ \"Hello\", \"Darkness\", \"my\", \"old\", \"friend.\", \"I've\", \"come\", \"to\", \"talk\" ]\r\n * arrSlice(lyrics, 1, 3); // [ \"Darkness\", \"my\" ]\r\n * arrSlicw(lyrics, 2); // [ \"my\", \"old\", \"friend.\", \"I've\", \"come\", \"to\", \"talk\" ]\r\n * arrSlice(lyrics, 2, 4); // [ \"my\", \"old\" ]\r\n * arrSlice(lyrics, 1, 5); // [ \"Darkness\", \"my\", \"old\", \"friend.\" ]\r\n * arrSlice(lyrics, -2); // [ \"to\", \"talk\" ]\r\n * arrSlice(lyrics, 2, -1); // [ \"my\", \"old\", \"friend.\", \"I've\", \"come\", \"to\" ]\r\n * ```\r\n */\r\nexport const arrSlice: (theArray: ArrayLike, start?: number, end?: number) => T[] = _unwrapFunction(SLICE, ArrProto);\r\n","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2023 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { _unwrapInstFunction } from \"../internal/unwrapFunction\";\r\n\r\n/**\r\n * The `fnApply` function calls the specified `fn` function with the given `thisArg` as the `this` value,\r\n * and the optional `argArray` arguments provided as an array (or an Array-Like Object).\r\n *\r\n * Normally, when calling a function, the value of `this` inside the function is the object that the\r\n * function was accessed on. With `fnApply()`, you can assign an arbitrary value as this when calling an\r\n * existing function, without first attaching the function to the object as a property. This allows you\r\n * to use methods of one object as generic utility functions.\r\n *\r\n * You can also use any kind of object which is ArrayLike as the second parameter. In practice, this means\r\n * that it needs to have a length property, and integer (\"index\") properties in the range (0..length - 1).\r\n * For example, you could use a NodeList, or a custom object like `{ 'length': 2, '0': 'eat', '1': 'bananas' }`.\r\n * You can also use `arguments`.\r\n *\r\n * @since 0.9.8\r\n * @group Function\r\n *\r\n * @param fn - The function to be called\r\n * @param thisArg - The value of `this` provided for the call to `fn`. If the function is not in strict mode,\r\n * `null` and `undefined` will be replaced with the global object, and primitive values will be converted to objects.\r\n * @param argArray - An array-like object, specifying the arguments with which `fn` should be called, or `null` or\r\n * `undefined` if no arguments should be provided to the function.\r\n * @returns The result of calling the function with the specified `this` value and arguments.\r\n * @example\r\n * ```ts\r\n * // min / max number in an array\r\n * let max = fnApply(Math.max, null, [ 21, 42, 84, 168, 7, 3 ]);\r\n * // 168\r\n *\r\n * let min = fnApply(Math.min, null, [ 21, 42, 84, 168, 7, 3 ]);\r\n * // 3\r\n *\r\n * const module1 = {\r\n * prefix: \"Hello\",\r\n * x: 21,\r\n * getX() {\r\n * return this.x;\r\n * },\r\n * log(value: string) {\r\n * return this.prefix + \" \" + value + \" : \" + this.x\r\n * }\r\n * };\r\n *\r\n * // The 'this' parameter of 'getX' is bound to 'module'.\r\n * module1.getX(); // 21\r\n * module1.log(\"Darkness\"); // Hello Darkness : 21\r\n *\r\n * // Create a new function 'boundGetX' with the 'this' parameter bound to 'module'.\r\n * let module2 = {\r\n * prefix: \"my\",\r\n * x: 42\r\n * };\r\n *\r\n * // Call the function of module1 with module2 as it's this\r\n * fnApply(module1.getX, module2); // 42\r\n * fnApply(module1.log, module2, [ \"friend\" ]); // my friend : 42\r\n * ```\r\n */\r\nexport const fnApply: any, T>(fn: F, thisArg: T, argArray?: ArrayLike) => ReturnType = _unwrapInstFunction(\"apply\");\r\n","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { NULL_VALUE } from \"../internal/constants\";\r\nimport { objDefineProp } from \"../object/define\";\r\n\r\nconst REF = \"ref\";\r\nconst UNREF = \"un\" + REF as \"unref\";\r\nconst HAS_REF = \"hasRef\";\r\nconst ENABLED = \"enabled\";\r\n\r\n/**\r\n * A Timer handler which is returned from {@link scheduleTimeout} which contains functions to\r\n * cancel or restart (refresh) the timeout function.\r\n *\r\n * @since 0.4.4\r\n * @group Timer\r\n */\r\nexport interface ITimerHandler {\r\n /**\r\n * Cancels a timeout that was previously scheduled, after calling this function any previously\r\n * scheduled timer will not execute.\r\n * @example\r\n * ```ts\r\n * let theTimer = scheduleTimeout(...);\r\n * theTimer.cancel();\r\n * ```\r\n */\r\n cancel(): void;\r\n\r\n /**\r\n * Reschedules the timer to call its callback at the previously specified duration\r\n * adjusted to the current time. This is useful for refreshing a timer without allocating\r\n * a new JavaScript object.\r\n *\r\n * Using this on a timer that has already called its callback will reactivate the timer.\r\n * Calling on a timer that has not yet executed will just reschedule the current timer.\r\n * @example\r\n * ```ts\r\n * let theTimer = scheduleTimeout(...);\r\n * // The timer will be restarted (if already executed) or rescheduled (if it has not yet executed)\r\n * theTimer.refresh();\r\n * ```\r\n */\r\n refresh(): ITimerHandler;\r\n\r\n /**\r\n * When called, requests that the event loop not exit so long when the ITimerHandler is active.\r\n * Calling timer.ref() multiple times will have no effect. By default, all ITimerHandler objects\r\n * will create \"ref'ed\" instances, making it normally unnecessary to call timer.ref() unless\r\n * timer.unref() had been called previously.\r\n * @since 0.7.0\r\n * @returns the ITimerHandler instance\r\n * @example\r\n * ```ts\r\n * let theTimer = createTimeout(...);\r\n *\r\n * // Make sure the timer is referenced (the default) so that the runtime (Node) does not terminate\r\n * // if there is a waiting referenced timer.\r\n * theTimer.ref();\r\n * ```\r\n */\r\n ref(): this;\r\n\r\n /**\r\n * When called, the any active ITimerHandler instance will not require the event loop to remain\r\n * active (Node.js). If there is no other activity keeping the event loop running, the process may\r\n * exit before the ITimerHandler instance callback is invoked. Calling timer.unref() multiple times\r\n * will have no effect.\r\n * @since 0.7.0\r\n * @returns the ITimerHandler instance\r\n * @example\r\n * ```ts\r\n * let theTimer = createTimeout(...);\r\n *\r\n * // Unreference the timer so that the runtime (Node) may terminate if nothing else is running.\r\n * theTimer.unref();\r\n * ```\r\n */\r\n unref(): this;\r\n\r\n /**\r\n * If true, any running referenced `ITimerHandler` instance will keep the Node.js event loop active.\r\n * @since 0.7.0\r\n * @example\r\n * ```ts\r\n * let theTimer = createTimeout(...);\r\n *\r\n * // Unreference the timer so that the runtime (Node) may terminate if nothing else is running.\r\n * theTimer.unref();\r\n * let hasRef = theTimer.hasRef(); // false\r\n *\r\n * theTimer.ref();\r\n * hasRef = theTimer.hasRef(); // true\r\n * ```\r\n */\r\n hasRef(): boolean;\r\n\r\n /**\r\n * Gets or Sets a flag indicating if the underlying timer is currently enabled and running.\r\n * Setting the enabled flag to the same as it's current value has no effect, setting to `true`\r\n * when already `true` will not {@link ITimerHandler.refresh | refresh}() the timer.\r\n * And setting to 'false` will {@link ITimerHandler.cancel | cancel}() the timer.\r\n * @since 0.8.1\r\n * @example\r\n * ```ts\r\n * let theTimer = createTimeout(...);\r\n *\r\n * // Check if enabled\r\n * theTimer.enabled; // false\r\n *\r\n * // Start the timer\r\n * theTimer.enabled = true; // Same as calling refresh()\r\n * theTimer.enabled; //true\r\n *\r\n * // Has no effect as it's already running\r\n * theTimer.enabled = true;\r\n *\r\n * // Will refresh / restart the time\r\n * theTimer.refresh()\r\n *\r\n * let theTimer = scheduleTimeout(...);\r\n *\r\n * // Check if enabled\r\n * theTimer.enabled; // true\r\n * ```\r\n */\r\n enabled: boolean;\r\n}\r\n\r\n/**\r\n * @ignore\r\n * @internal\r\n */\r\nexport interface _TimerHandler {\r\n /**\r\n * The public handler to return to the caller\r\n */\r\n h: ITimerHandler,\r\n\r\n /**\r\n * The callback function that should be called when the timer operation\r\n * has completed and will not automatically rescheduled\r\n * @returns\r\n */\r\n dn: () => void\r\n}\r\n\r\n/**\r\n * @ignore\r\n * @internal\r\n * Internal function to create and manage an ITimerHandler implementation, the object returned from this function\r\n * it directly used / returned by the pulic functions used to create timers (idle, interval and timeout)\r\n * @param startTimer - Should the timer be started as part of creating the handler\r\n * @param refreshFn - The function used to create/start or refresh the timer\r\n * @param cancelFn - The function used to cancel the timer.\r\n * @returns The new ITimerHandler instance\r\n */\r\nexport function _createTimerHandler(startTimer: boolean, refreshFn: (timerId: T) => T, cancelFn: (timerId: T) => void): _TimerHandler {\r\n let ref = true;\r\n let timerId: T = startTimer ? refreshFn(NULL_VALUE) : NULL_VALUE;\r\n let theTimerHandler: ITimerHandler;\r\n\r\n const _unref = () => {\r\n ref = false;\r\n timerId && timerId[UNREF] && timerId[UNREF]();\r\n return theTimerHandler;\r\n };\r\n\r\n const _ref = () => {\r\n ref = true;\r\n timerId && timerId[REF] && timerId[REF]();\r\n return theTimerHandler;\r\n };\r\n\r\n const _hasRef = () => {\r\n if (timerId && timerId[HAS_REF]) {\r\n return timerId[HAS_REF]();\r\n }\r\n return ref;\r\n };\r\n\r\n const _refresh = () => {\r\n timerId = refreshFn(timerId);\r\n if (!ref) {\r\n _unref();\r\n }\r\n\r\n return theTimerHandler;\r\n };\r\n\r\n const _cancel = () => {\r\n timerId && cancelFn(timerId);\r\n timerId = NULL_VALUE;\r\n };\r\n\r\n const _setEnabled = (value: boolean) => {\r\n !value && timerId && _cancel();\r\n value && !timerId && _refresh();\r\n }\r\n\r\n theTimerHandler = {\r\n cancel: _cancel,\r\n refresh: _refresh,\r\n [HAS_REF]: _hasRef,\r\n [REF]: _ref,\r\n [UNREF]: _unref,\r\n [ENABLED]: false\r\n };\r\n\r\n objDefineProp(theTimerHandler, ENABLED, {\r\n get: () => !!timerId,\r\n set: _setEnabled\r\n });\r\n\r\n return {\r\n h: theTimerHandler,\r\n dn: () => {\r\n timerId = NULL_VALUE;\r\n }\r\n };\r\n}\r\n","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { arrSlice } from \"../array/slice\";\r\nimport { fnApply } from \"../funcs/fnApply\";\r\nimport { isArray } from \"../helpers/base\";\r\nimport { UNDEF_VALUE } from \"../internal/constants\";\r\nimport { ITimerHandler, _createTimerHandler } from \"./handler\";\r\n\r\nfunction _createTimeoutWith(self: any, startTimer: boolean, overrideFn: TimeoutOverrideFn | TimeoutOverrideFuncs, theArgs: any[]): ITimerHandler {\r\n let isArr = isArray(overrideFn);\r\n let len = isArr ? overrideFn.length : 0;\r\n let setFn: TimeoutOverrideFn = (len > 0 ? overrideFn[0] : (!isArr ? overrideFn : UNDEF_VALUE)) || setTimeout;\r\n let clearFn: ClearTimeoutOverrideFn = (len > 1 ? overrideFn[1] : UNDEF_VALUE) || clearTimeout;\r\n\r\n let timerFn = theArgs[0];\r\n theArgs[0] = function () {\r\n handler.dn();\r\n fnApply(timerFn, self, arrSlice(arguments));\r\n };\r\n \r\n let handler = _createTimerHandler(startTimer, (timerId?: any) => {\r\n if (timerId) {\r\n if (timerId.refresh) {\r\n timerId.refresh();\r\n return timerId;\r\n }\r\n\r\n fnApply(clearFn, self, [ timerId ]);\r\n }\r\n\r\n return fnApply(setFn, self, theArgs);\r\n }, function (timerId: any) {\r\n fnApply(clearFn, self, [ timerId ]);\r\n });\r\n\r\n return handler.h;\r\n}\r\n\r\n/**\r\n * The signature of the override timeout function used to create a new timeout instance, it follows the same signature as\r\n * the native `setTimeout` API.\r\n * @since 0.4.4\r\n * @group Timer\r\n * @param callback - A function to be executed after the timer expires.\r\n * @param ms - The time, in milliseconds that the timer should wait before the specified function or code is executed.\r\n * If this parameter is omitted, a value of 0 is used, meaning execute \"immediately\", or more accurately, the next event cycle.\r\n * @param args - Additional arguments which are passed through to the function specified by callback.\r\n * @return The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout().\r\n * This value can be passed to clearTimeout() to cancel the timeout.\r\n */\r\nexport type TimeoutOverrideFn = (callback: (...args: TArgs) => void, ms?: number, ...args: TArgs) => number | any;\r\n\r\n/**\r\n * The signatire of the function to override clearing a previous timeout created with the {@link TimeoutOverrideFn}, it will be passed\r\n * the result returned from the {@link TimeoutOverrideFn} call.\r\n * @since 0.4.5\r\n * @group Timer\r\n * @param timeoutId - The value returned from the previous {@link TimeoutOverrideFn}.\r\n */\r\nexport type ClearTimeoutOverrideFn = (timeoutId: number | any) => void;\r\n\r\n/**\r\n * Defines the array signature used to pass the override set and clean functions for creating a timeout.\r\n * The first index [0] is the set function to be used and the second index [1] is the clear function to be used.\r\n * @since 0.4.5\r\n * @group Timer\r\n */\r\nexport type TimeoutOverrideFuncs = [ TimeoutOverrideFn | null, ClearTimeoutOverrideFn | null ];\r\n\r\n/**\r\n * Creates and starts a timer which executes a function or specified piece of code once the timer expires, this is simular\r\n * to using `setTimeout` but provides a return object for cancelling and restarting (refresh) the timer.\r\n *\r\n * The timer may be cancelled (cleared) by calling the `cancel()` function on the returned {@link ITimerHandler}, or\r\n * you can \"reschedule\" and/or \"restart\" the timer by calling the `refresh()` function on the returned {@link ITimerHandler}\r\n * instance\r\n *\r\n * @since 0.4.4\r\n * @group Timer\r\n *\r\n * @param callback - The function to be executed after the timer expires.\r\n * @param timeout - The time, in milliseconds that the timer should wait before the specified\r\n * function or code is executed. If this parameter is omitted, a value of 0 is used, meaning\r\n * execute \"immediately\", or more accurately, the next event cycle.\r\n * @param args - Additional arguments which are passed through to the function specified by `callback`.\r\n * @returns A {@link ITimerHandler} instance which can be used to cancel the timeout.\r\n * @example\r\n * ```ts\r\n * let timeoutCalled = false;\r\n * let theTimeout = scheduleTimeout(() => {\r\n * // This callback will be called after 100ms as this uses setTimeout()\r\n * timeoutCalled = true;\r\n * }, 100);\r\n *\r\n * // Instead of calling clearTimeout() with the returned value from setTimeout() the returned\r\n * // handler instance can be used instead to cancel the timer\r\n * theTimeout.cancel();\r\n * theTimeout.enabled; // false\r\n *\r\n * // You can start the timer via enabled\r\n * theTimeout.enabled = true;\r\n *\r\n * // You can also \"restart\" the timer, whether it has previously triggered not not via the `refresh()`\r\n * theTimeout.refresh();\r\n * ```\r\n */\r\nexport function scheduleTimeout(callback: (...args: A) => void, timeout: number, ...args: A): ITimerHandler;\r\nexport function scheduleTimeout(callback: (...args: A) => void, timeout: number): ITimerHandler {\r\n return _createTimeoutWith(this, true, UNDEF_VALUE, arrSlice(arguments));\r\n}\r\n\r\n/**\r\n * Creates and starts a timer which executes a function or specified piece of code once the timer expires. The overrideFn will be\r\n * used to create the timer, this is simular to using `setTimeout` but provides a return object for cancelling and restarting\r\n * (refresh) the timer.\r\n *\r\n * The timer may be cancelled (cleared) by calling the `cancel()` function on the returned {@link ITimerHandler}, or\r\n * you can \"reschedule\" and/or \"restart\" the timer by calling the `refresh()` function on the returned {@link ITimerHandler}\r\n * instance\r\n *\r\n * @since 0.4.4\r\n * @group Timer\r\n *\r\n * @param overrideFn - setTimeout override function this will be called instead of the `setTimeout`, if the value\r\n * of `overrideFn` is null or undefined it will revert back to the native `setTimeout`. May also be an array with contains\r\n * both the setTimeout and clearTimeout override functions, if either is not provided the default native functions will be used\r\n * @param callback - The function to be executed after the timer expires.\r\n * @param timeout - The time, in milliseconds that the timer should wait before the specified\r\n * function or code is executed. If this parameter is omitted, a value of 0 is used, meaning\r\n * execute \"immediately\", or more accurately, the next event cycle.\r\n * @param args - Additional arguments which are passed through to the function specified by `callback`.\r\n * @returns A {@link ITimerHandler} instance which can be used to cancel the timeout.\r\n * @example\r\n * ```ts\r\n * let timeoutCalled = false;\r\n * // Your own \"setTimeout\" implementation to allow you to perform additional operations or possible wrap\r\n * // the callback to add timings.\r\n * function newSetTimeoutFn(callback: TimeoutOverrideFn) {\r\n * overrideCalled ++;\r\n * return setTimeout(callback, timeout);\r\n * }\r\n *\r\n * let theTimeout = scheduleTimeoutWith(newSetTimeoutFn, () => {\r\n * // This callback will be called after 100ms as this uses setTimeout()\r\n * timeoutCalled = true;\r\n * }, 100);\r\n *\r\n * // Instead of calling clearTimeout() with the returned value from setTimeout() the returned\r\n * // handler instance can be used instead to cancel the timer\r\n * theTimeout.cancel();\r\n * theTimeout.enabled; // false\r\n *\r\n * // You can start the timer via enabled\r\n * theTimeout.enabled = true;\r\n *\r\n * // You can also \"restart\" the timer, whether it has previously triggered not not via the `refresh()`\r\n * theTimeout.refresh();\r\n * ```\r\n * @example\r\n * ```ts\r\n * let timeoutCalled = false;\r\n * // Your own \"setTimeout\" implementation to allow you to perform additional operations or possible wrap\r\n * // the callback to add timings.\r\n * function newSetTimeoutFn(callback: TimeoutOverrideFn) {\r\n * overrideCalled ++;\r\n * return setTimeout(callback, timeout);\r\n * }\r\n *\r\n * // Your own \"clearTimeout\" implementation to allow you to perform additional operations or possible wrap\r\n * // the callback to add timings.\r\n * function newClearTimeoutFn(timeoutId: number) {\r\n * overrideCalled ++;\r\n * return clearTimeout( timeout);\r\n * }\r\n *\r\n * let theTimeout = scheduleTimeoutWith([newSetTimeoutFn, newClearTimeoutFn], () => {\r\n * // This callback will be called after 100ms as this uses setTimeout()\r\n * timeoutCalled = true;\r\n * }, 100);\r\n *\r\n * // Instead of calling clearTimeout() with the returned value from setTimeout() the returned\r\n * // handler instance can be used instead to cancel the timer, internally this will call the newClearTimeoutFn\r\n * theTimeout.cancel();\r\n * theTimeout.enabled; // false\r\n *\r\n * // You can start the timer via enabled\r\n * theTimeout.enabled = true;\r\n *\r\n * // You can also \"restart\" the timer, whether it has previously triggered not not via the `refresh()`\r\n * theTimeout.refresh();\r\n * ```\r\n */\r\nexport function scheduleTimeoutWith(overrideFn: TimeoutOverrideFn | TimeoutOverrideFuncs, callback: (...args: A) => void, timeout: number, ...args: A): ITimerHandler;\r\nexport function scheduleTimeoutWith(overrideFn: TimeoutOverrideFn | TimeoutOverrideFuncs, callback: (...args: A) => void, timeout: number): ITimerHandler {\r\n return _createTimeoutWith(this, true, overrideFn, arrSlice(arguments, 1));\r\n}\r\n\r\n/**\r\n * Creates a non-running (paused) timer which will execute a function or specified piece of code when enabled and the timer expires,\r\n * this is simular to using `scheduleTimeout` but the timer is not enabled (running) and you MUST call `refresh` to start the timer.\r\n *\r\n * The timer may be cancelled (cleared) by calling the `cancel()` function on the returned {@link ITimerHandler}, or\r\n * you can \"reschedule\" and/or \"restart\" the timer by calling the `refresh()` function on the returned {@link ITimerHandler}\r\n * instance\r\n *\r\n * @since 0.7.0\r\n * @group Timer\r\n *\r\n * @param callback - The function to be executed after the timer expires.\r\n * @param timeout - The time, in milliseconds that the timer should wait before the specified\r\n * function or code is executed. If this parameter is omitted, a value of 0 is used, meaning\r\n * execute \"immediately\", or more accurately, the next event cycle.\r\n * @param args - Additional arguments which are passed through to the function specified by `callback`.\r\n * @returns A {@link ITimerHandler} instance which can be used to cancel the timeout.\r\n * @example\r\n * ```ts\r\n * let timeoutCalled = false;\r\n * let theTimeout = createTimeout(() => {\r\n * // This callback will be called after 100ms as this uses setTimeout()\r\n * timeoutCalled = true;\r\n * }, 100);\r\n *\r\n * // As the timer is not started you will need to call \"refresh\" to start the timer\r\n * theTimeout.refresh();\r\n *\r\n * // or set enabled to true\r\n * theTimeout.enabled = true;\r\n * ```\r\n */\r\nexport function createTimeout(callback: (...args: A) => void, timeout: number, ...args: A): ITimerHandler;\r\nexport function createTimeout(callback: (...args: A) => void, timeout: number): ITimerHandler {\r\n return _createTimeoutWith(this, false, UNDEF_VALUE, arrSlice(arguments));\r\n}\r\n\r\n/**\r\n * Creates a non-running (paused) timer which will execute a function or specified piece of code when enabled once the timer expires.\r\n * The overrideFn will be used to create the timer, this is simular to using `scheduleTimeoutWith` but the timer is not enabled (running)\r\n * and you MUST call `refresh` to start the timer.\r\n *\r\n * The timer may be cancelled (cleared) by calling the `cancel()` function on the returned {@link ITimerHandler}, or\r\n * you can \"reschedule\" and/or \"restart\" the timer by calling the `refresh()` function on the returned {@link ITimerHandler}\r\n * instance\r\n *\r\n * @since 0.7.0\r\n * @group Timer\r\n *\r\n * @param overrideFn - setTimeout override function this will be called instead of the `setTimeout`, if the value\r\n * of `overrideFn` is null or undefined it will revert back to the native `setTimeout`. May also be an array with contains\r\n * both the setTimeout and clearTimeout override functions, if either is not provided the default native functions will be used\r\n * @param callback - The function to be executed after the timer expires.\r\n * @param timeout - The time, in milliseconds that the timer should wait before the specified\r\n * function or code is executed. If this parameter is omitted, a value of 0 is used, meaning\r\n * execute \"immediately\", or more accurately, the next event cycle.\r\n * @param args - Additional arguments which are passed through to the function specified by `callback`.\r\n * @returns A {@link ITimerHandler} instance which can be used to cancel the timeout.\r\n * @example\r\n * ```ts\r\n * let timeoutCalled = false;\r\n * // Your own \"setTimeout\" implementation to allow you to perform additional operations or possible wrap\r\n * // the callback to add timings.\r\n * function newSetTimeoutFn(callback: TimeoutOverrideFn) {\r\n * overrideCalled ++;\r\n * return setTimeout(callback, timeout);\r\n * }\r\n *\r\n * let theTimeout = createTimeoutWith(newSetTimeoutFn, () => {\r\n * // This callback will be called after 100ms as this uses setTimeout()\r\n * timeoutCalled = true;\r\n * }, 100);\r\n *\r\n * // As the timer is not started you will need to call \"refresh\" to start the timer\r\n * theTimeout.refresh();\r\n *\r\n * // or set enabled to true\r\n * theTimeout.enabled = true;\r\n * ```\r\n * @example\r\n * ```ts\r\n * let timeoutCalled = false;\r\n * // Your own \"setTimeout\" implementation to allow you to perform additional operations or possible wrap\r\n * // the callback to add timings.\r\n * function newSetTimeoutFn(callback: TimeoutOverrideFn) {\r\n * overrideCalled ++;\r\n * return setTimeout(callback, timeout);\r\n * }\r\n *\r\n * // Your own \"clearTimeout\" implementation to allow you to perform additional operations or possible wrap\r\n * // the callback to add timings.\r\n * function newClearTimeoutFn(timeoutId: number) {\r\n * overrideCalled ++;\r\n * return clearTimeout( timeout);\r\n * }\r\n *\r\n * let theTimeout = createTimeoutWith([newSetTimeoutFn, newClearTimeoutFn], () => {\r\n * // This callback will be called after 100ms as this uses setTimeout()\r\n * timeoutCalled = true;\r\n * }, 100);\r\n *\r\n * // As the timer is not started you will need to call \"refresh\" to start the timer\r\n * theTimeout.refresh();\r\n *\r\n * // or set enabled to true\r\n * theTimeout.enabled = true;\r\n * ```\r\n */\r\nexport function createTimeoutWith(overrideFn: TimeoutOverrideFn | TimeoutOverrideFuncs, callback: (...args: A) => void, timeout: number, ...args: A): ITimerHandler;\r\nexport function createTimeoutWith(overrideFn: TimeoutOverrideFn | TimeoutOverrideFuncs, callback: (...args: A) => void, timeout: number): ITimerHandler {\r\n return _createTimeoutWith(this, false, overrideFn, arrSlice(arguments, 1));\r\n}\r\n","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { ILazyValue, getLazy } from \"../helpers/lazy\";\r\nimport { ObjClass, __PROTO__ } from \"../internal/constants\";\r\nimport { objForEachKey } from \"./for_each_key\";\r\n\r\nlet _isProtoArray: ILazyValue;\r\n\r\n/**\r\n * The objSetPrototypeOf() method sets the prototype (i.e., the internal [Prototype] property) of a specified\r\n * object to another object or null.\r\n * @group Object\r\n * @param obj - The object which is to have it's prototype set.\r\n * @param proto - The object's new prototype (an object or null)\r\n * @returns The specified object.\r\n */\r\nexport function objSetPrototypeOf(obj: any, proto: object) {\r\n let fn = ObjClass[\"setPrototypeOf\"] ||\r\n // tslint:disable-next-line: only-arrow-functions\r\n function (d: any, b: any) {\r\n !_isProtoArray && (_isProtoArray = getLazy(() => ({ [__PROTO__]: [] } instanceof Array)));\r\n _isProtoArray.v ? d[__PROTO__] = b : objForEachKey(b, (key: any, value: any) => d[key] = value );\r\n };\r\n\r\n return fn(obj, proto);\r\n}","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { arrSlice } from \"../array/slice\";\r\nimport { fnApply } from \"../funcs/fnApply\";\r\nimport { CONSTRUCTOR, NAME, NULL_VALUE, PROTOTYPE } from \"../internal/constants\";\r\nimport { objCreate } from \"../object/create\";\r\nimport { objDefine } from \"../object/define\";\r\nimport { objGetPrototypeOf } from \"../object/object\";\r\nimport { objSetPrototypeOf } from \"../object/set_proto\";\r\n\r\n/**\r\n * Defines the definition of the custom error constructor\r\n * Used by: {@link createCustomError}\r\n * @group Error\r\n */\r\nexport interface CustomErrorConstructor extends ErrorConstructor {\r\n new(message?: string): T;\r\n (message?: string): T;\r\n readonly prototype: T;\r\n}\r\n\r\n/**\r\n * @internal\r\n * @ignore\r\n */\r\nconst _createCustomError = (name: string, d: any, b: any): T => {\r\n _safeDefineName(d, name);\r\n d = objSetPrototypeOf(d, b);\r\n function __() {\r\n this.constructor = d;\r\n _safeDefineName(this, name);\r\n }\r\n\r\n d[PROTOTYPE] = b === NULL_VALUE ? objCreate(b) : ((__ as any)[PROTOTYPE] = b[PROTOTYPE], new (__ as any)());\r\n\r\n return d;\r\n};\r\n\r\nconst _safeSetName = (baseClass: any, name: string) => {\r\n try {\r\n name && (baseClass[NAME] = name);\r\n //name && (baseClass[PROTOTYPE][NAME] = name);\r\n } catch(e) {\r\n // Do nothing\r\n }\r\n};\r\n\r\nconst _safeDefineName = (target: any, name: string) => {\r\n try {\r\n objDefine(target, NAME, { v: name, c: true, e: false });\r\n } catch (e) {\r\n // Do nothing\r\n }\r\n};\r\n\r\n/**\r\n * Create a Custom Error class which may be used to throw custom errors.\r\n * @group Error\r\n * @param name - The name of the Custom Error\r\n * @param constructCb - [Optional] An optional callback function to call when a\r\n * new Customer Error instance is being created.\r\n * @param errorBase - [Optional] (since v0.9.6) The error class to extend for this class, defaults to Error.\r\n * @returns A new Error `class`\r\n * @example\r\n * ```ts\r\n * import { createCustomError, isError } from \"@nevware21/ts-utils\";\r\n *\r\n * // For an error that just contains a message\r\n * let myCustomErrorError = createCustomError(\"MessageError\");\r\n *\r\n * try {\r\n * throw new myCustomErrorError(\"Error Message!\");\r\n * } catch(e) {\r\n * // e.name === MessageError\r\n * // isError(e) === true;\r\n * // Object.prototype.toString.call(e) === \"[object Error]\";\r\n * }\r\n *\r\n * // Or a more complex error object\r\n * interface MyCriticalErrorConstructor extends CustomErrorConstructor {\r\n * new(message: string, file: string, line: number, col: number): MyCriticalError;\r\n * (message: string, file: string, line: number, col: number): MyCriticalError;\r\n * }\r\n *\r\n * interface MyCriticalError extends Error {\r\n * readonly errorId: number;\r\n * readonly args: any[]; // Holds all of the arguments passed during construction\r\n * }\r\n *\r\n * let _totalErrors = 0;\r\n * let myCustomError = createCustomError(\"CriticalError\", (self, args) => {\r\n * _totalErrors++;\r\n * self.errorId = _totalErrors;\r\n * self.args = args;\r\n * });\r\n *\r\n * try {\r\n * throw new myCustomError(\"Not Again!\");\r\n * } catch(e) {\r\n * // e.name === CriticalError\r\n * // isError(e) === true;\r\n * // Object.prototype.toString.call(e) === \"[object Error]\";\r\n * }\r\n *\r\n * // ----------------------------------------------------------\r\n * // Extending another custom error class\r\n * // ----------------------------------------------------------\r\n *\r\n * let AppError = createCustomError(\"ApplicationError\");\r\n * let theAppError = new appError();\r\n *\r\n * isError(theAppError); // true\r\n * theAppError instanceof Error; // true\r\n * theAppError instanceof AppError; // true\r\n *\r\n * let StartupError = createCustomError(\"StartupError\", null, AppError);\r\n * let theStartupError = new StartupError();\r\n *\r\n * isError(theStartupError); // true\r\n * theStartupError instanceof Error; // true\r\n * theStartupError instanceof AppError; // true\r\n * theStartupError instanceof StartupError; // true\r\n * ```\r\n */\r\nexport function createCustomError(\r\n name: string,\r\n constructCb?: ((self: any, args: IArguments) => void) | null,\r\n errorBase?: B): T {\r\n\r\n let theBaseClass = errorBase || Error;\r\n let orgName = theBaseClass[PROTOTYPE][NAME];\r\n let captureFn = Error.captureStackTrace;\r\n return _createCustomError(name, function (this: any) {\r\n let _this = this;\r\n try {\r\n _safeSetName(theBaseClass, name);\r\n let _self = fnApply(theBaseClass, _this, arrSlice(arguments)) || _this;\r\n if (_self !== _this) {\r\n // Looks like runtime error constructor reset the prototype chain, so restore it\r\n let orgProto = objGetPrototypeOf(_this);\r\n if (orgProto !== objGetPrototypeOf(_self)) {\r\n objSetPrototypeOf(_self, orgProto);\r\n }\r\n }\r\n\r\n // Make sure we only capture our stack details\r\n captureFn && captureFn(_self, _this[CONSTRUCTOR]);\r\n \r\n // Run the provided construction function\r\n constructCb && constructCb(_self, arguments);\r\n \r\n return _self;\r\n } finally {\r\n _safeSetName(theBaseClass, orgName);\r\n }\r\n }, theBaseClass);\r\n}\r\n\r\n/**\r\n * @internal\r\n * @ignore\r\n */\r\nlet _unsupportedError: CustomErrorConstructor;\r\n\r\n/**\r\n * Throw a custom `UnsupportedError` Error instance with the given message.\r\n * @group Error\r\n * @param message - The message to include in the exception\r\n * @example\r\n * ```ts\r\n * import { throwUnsupported } from \"@nevware21/ts-utils\";\r\n *\r\n * if (!window) {\r\n * throwUnsupported(\"A window is needed for this operation\");\r\n * }\r\n * ```\r\n */\r\nexport function throwUnsupported(message?: string): never {\r\n if (!_unsupportedError) {\r\n // Lazily create the class\r\n _unsupportedError = createCustomError(\"UnsupportedError\");\r\n }\r\n\r\n throw new _unsupportedError(message);\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { arrForEach, createCustomError, dumpObj } from \"@nevware21/ts-utils\";\r\nimport { _DYN_LENGTH } from \"../__DynamicConstants\";\r\nvar aggregationErrorType;\r\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 */\r\nexport function throwAggregationError(message, sourceErrors) {\r\n if (!aggregationErrorType) {\r\n aggregationErrorType = createCustomError(\"AggregationError\", function (self, args) {\r\n if (args[_DYN_LENGTH /* @min:%2elength */] > 1) {\r\n // Save the provided errors\r\n self.errors = args[1];\r\n }\r\n });\r\n }\r\n var theMessage = message || \"One or more errors occurred.\";\r\n arrForEach(sourceErrors, function (srcError, idx) {\r\n theMessage += \"\\n\".concat(idx, \" > \").concat(dumpObj(srcError));\r\n });\r\n throw new aggregationErrorType(theMessage, sourceErrors || []);\r\n}\r\n//# sourceMappingURL=AggregationError.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { arrForEach, arrIndexOf, dumpObj, newSymbol, scheduleTimeout } from \"@nevware21/ts-utils\";\r\nimport { throwAggregationError } from \"../JavaScriptSDK/AggregationError\";\r\nimport { _DYN_BLK_VAL, _DYN_CANCEL, _DYN_HDLR, _DYN_LENGTH, _DYN_LOGGER, _DYN_NOTIFY, _DYN_PUSH, _DYN_RD_ONLY, _DYN_SET_DF, _DYN_THROW_INTERNAL } from \"../__DynamicConstants\";\r\nvar symPrefix = \"[[ai_\";\r\nvar symPostfix = \"]]\";\r\nexport function _createState(cfgHandler) {\r\n var _a;\r\n var dynamicPropertySymbol = newSymbol(symPrefix + \"get\" + cfgHandler.uid + symPostfix);\r\n var dynamicPropertyReadOnly = newSymbol(symPrefix + \"ro\" + cfgHandler.uid + symPostfix);\r\n var dynamicPropertyReferenced = newSymbol(symPrefix + \"rf\" + cfgHandler.uid + symPostfix);\r\n var dynamicPropertyBlockValue = newSymbol(symPrefix + \"blkVal\" + cfgHandler.uid + symPostfix);\r\n var dynamicPropertyDetail = newSymbol(symPrefix + \"dtl\" + cfgHandler.uid + symPostfix);\r\n var _waitingHandlers = null;\r\n var _watcherTimer = null;\r\n var theState;\r\n function _useHandler(activeHandler, callback) {\r\n var prevWatcher = theState.act;\r\n try {\r\n theState.act = activeHandler;\r\n if (activeHandler && activeHandler[dynamicPropertyDetail]) {\r\n // Clear out the previously tracked details for this handler, so that access are re-evaluated\r\n arrForEach(activeHandler[dynamicPropertyDetail], function (detail) {\r\n detail.clr(activeHandler);\r\n });\r\n activeHandler[dynamicPropertyDetail] = [];\r\n }\r\n callback({\r\n cfg: cfgHandler.cfg,\r\n set: cfgHandler.set.bind(cfgHandler),\r\n setDf: cfgHandler[_DYN_SET_DF /* @min:%2esetDf */].bind(cfgHandler),\r\n ref: cfgHandler.ref.bind(cfgHandler),\r\n rdOnly: cfgHandler[_DYN_RD_ONLY /* @min:%2erdOnly */].bind(cfgHandler)\r\n });\r\n }\r\n catch (e) {\r\n var logger = cfgHandler[_DYN_LOGGER /* @min:%2elogger */];\r\n if (logger) {\r\n // Don't let one individual failure break everyone\r\n logger[_DYN_THROW_INTERNAL /* @min:%2ethrowInternal */](1 /* eLoggingSeverity.CRITICAL */, 107 /* _eInternalMessageId.ConfigWatcherException */, dumpObj(e));\r\n }\r\n // Re-throw the exception so that any true \"error\" is reported back to the called\r\n throw e;\r\n }\r\n finally {\r\n theState.act = prevWatcher || null;\r\n }\r\n }\r\n function _notifyWatchers() {\r\n if (_waitingHandlers) {\r\n var notifyHandlers = _waitingHandlers;\r\n _waitingHandlers = null;\r\n // Stop any timer as we are running them now anyway\r\n _watcherTimer && _watcherTimer[_DYN_CANCEL /* @min:%2ecancel */]();\r\n _watcherTimer = null;\r\n var watcherFailures_1 = [];\r\n // Now run the handlers\r\n arrForEach(notifyHandlers, function (handler) {\r\n if (handler) {\r\n if (handler[dynamicPropertyDetail]) {\r\n arrForEach(handler[dynamicPropertyDetail], function (detail) {\r\n // Clear out this handler from previously tracked details, so that access are re-evaluated\r\n detail.clr(handler);\r\n });\r\n handler[dynamicPropertyDetail] = null;\r\n }\r\n // The handler may have self removed as part of another handler so re-check\r\n if (handler.fn) {\r\n try {\r\n _useHandler(handler, handler.fn);\r\n }\r\n catch (e) {\r\n // Don't let a single failing watcher cause other watches to fail\r\n watcherFailures_1[_DYN_PUSH /* @min:%2epush */](e);\r\n }\r\n }\r\n }\r\n });\r\n // During notification we may have had additional updates -- so notify those updates as well\r\n if (_waitingHandlers) {\r\n try {\r\n _notifyWatchers();\r\n }\r\n catch (e) {\r\n watcherFailures_1[_DYN_PUSH /* @min:%2epush */](e);\r\n }\r\n }\r\n if (watcherFailures_1[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n throwAggregationError(\"Watcher error(s): \", watcherFailures_1);\r\n }\r\n }\r\n }\r\n function _addWatcher(detail) {\r\n if (detail && detail.h[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n if (!_waitingHandlers) {\r\n _waitingHandlers = [];\r\n }\r\n if (!_watcherTimer) {\r\n _watcherTimer = scheduleTimeout(function () {\r\n _watcherTimer = null;\r\n _notifyWatchers();\r\n }, 0);\r\n }\r\n // Add all of the handlers for this detail (if not already present) - using normal for-loop for performance\r\n for (var idx = 0; idx < detail.h[_DYN_LENGTH /* @min:%2elength */]; idx++) {\r\n var handler = detail.h[idx];\r\n // Add this handler to the collection of handlers to re-execute\r\n if (handler && arrIndexOf(_waitingHandlers, handler) === -1) {\r\n _waitingHandlers[_DYN_PUSH /* @min:%2epush */](handler);\r\n }\r\n }\r\n }\r\n }\r\n function _trackHandler(handler, detail) {\r\n if (handler) {\r\n var details = handler[dynamicPropertyDetail] = handler[dynamicPropertyDetail] || [];\r\n if (arrIndexOf(details, detail) === -1) {\r\n // If this detail is not already listed as tracked then add it so that we re-evaluate it's usage\r\n details[_DYN_PUSH /* @min:%2epush */](detail);\r\n }\r\n }\r\n }\r\n theState = (_a = {\r\n prop: dynamicPropertySymbol,\r\n ro: dynamicPropertyReadOnly,\r\n rf: dynamicPropertyReferenced\r\n },\r\n _a[_DYN_BLK_VAL /* @min:blkVal */] = dynamicPropertyBlockValue,\r\n _a[_DYN_HDLR /* @min:hdlr */] = cfgHandler,\r\n _a.add = _addWatcher,\r\n _a[_DYN_NOTIFY /* @min:notify */] = _notifyWatchers,\r\n _a.use = _useHandler,\r\n _a.trk = _trackHandler,\r\n _a);\r\n return theState;\r\n}\r\n//# sourceMappingURL=DynamicState.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { dumpObj, isUndefined, objDefine, objForEachKey } from \"@nevware21/ts-utils\";\r\nimport { createUniqueNamespace } from \"../JavaScriptSDK/DataCacheHelper\";\r\nimport { STR_NOT_DYNAMIC_ERROR } from \"../JavaScriptSDK/InternalConstants\";\r\nimport { _DYN_BLK_VAL, _DYN_LOGGER, _DYN_NOTIFY, _DYN_RD_ONLY, _DYN_SET_DF, _DYN_THROW_INTERNAL, _DYN_WARN_TO_CONSOLE, _DYN_WATCH } from \"../__DynamicConstants\";\r\nimport { _applyDefaultValue } from \"./ConfigDefaults\";\r\nimport { _makeDynamicObject, _setDynamicProperty, _setDynamicPropertyState, _throwDynamicError } from \"./DynamicProperty\";\r\nimport { _createState } from \"./DynamicState\";\r\nimport { CFG_HANDLER_LINK, _cfgDeepCopy, getDynamicConfigHandler, throwInvalidAccess } from \"./DynamicSupport\";\r\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 */\r\nfunction _createAndUseHandler(state, configHandler) {\r\n var handler = {\r\n fn: configHandler,\r\n rm: function () {\r\n // Clear all references to the handler so it can be garbage collected\r\n // This will also cause this handler to never get called and eventually removed\r\n handler.fn = null;\r\n state = null;\r\n configHandler = null;\r\n }\r\n };\r\n state.use(handler, configHandler);\r\n return handler;\r\n}\r\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 */\r\nfunction _createDynamicHandler(logger, target, inPlace) {\r\n var _a;\r\n var dynamicHandler = getDynamicConfigHandler(target);\r\n if (dynamicHandler) {\r\n // The passed config is already dynamic so return it's tracker\r\n return dynamicHandler;\r\n }\r\n var uid = createUniqueNamespace(\"dyncfg\", true);\r\n var newTarget = (target && inPlace !== false) ? target : _cfgDeepCopy(target);\r\n var theState;\r\n function _notifyWatchers() {\r\n theState[_DYN_NOTIFY /* @min:%2enotify */]();\r\n }\r\n function _setValue(target, name, value) {\r\n try {\r\n target = _setDynamicProperty(theState, target, name, value);\r\n }\r\n catch (e) {\r\n // Unable to convert to dynamic property so just leave as non-dynamic\r\n _throwDynamicError(logger, name, \"Setting value\", e);\r\n }\r\n return target[name];\r\n }\r\n function _watch(configHandler) {\r\n return _createAndUseHandler(theState, configHandler);\r\n }\r\n function _block(configHandler, allowUpdate) {\r\n theState.use(null, function (details) {\r\n var prevUpd = theState.upd;\r\n try {\r\n if (!isUndefined(allowUpdate)) {\r\n theState.upd = allowUpdate;\r\n }\r\n configHandler(details);\r\n }\r\n finally {\r\n theState.upd = prevUpd;\r\n }\r\n });\r\n }\r\n function _ref(target, name) {\r\n var _a;\r\n // Make sure it's dynamic and mark as referenced with it's current value\r\n return _setDynamicPropertyState(theState, target, name, (_a = {}, _a[0 /* _eSetDynamicPropertyFlags.inPlace */] = true, _a))[name];\r\n }\r\n function _rdOnly(target, name) {\r\n var _a;\r\n // Make sure it's dynamic and mark as readonly with it's current value\r\n return _setDynamicPropertyState(theState, target, name, (_a = {}, _a[1 /* _eSetDynamicPropertyFlags.readOnly */] = true, _a))[name];\r\n }\r\n function _blkPropValue(target, name) {\r\n var _a;\r\n // Make sure it's dynamic and mark as readonly with it's current value\r\n return _setDynamicPropertyState(theState, target, name, (_a = {}, _a[2 /* _eSetDynamicPropertyFlags.blockDynamicProperty */] = true, _a))[name];\r\n }\r\n function _applyDefaults(theConfig, defaultValues) {\r\n if (defaultValues) {\r\n // Resolve/apply the defaults\r\n objForEachKey(defaultValues, function (name, value) {\r\n // Sets the value and makes it dynamic (if it doesn't already exist)\r\n _applyDefaultValue(cfgHandler, theConfig, name, value);\r\n });\r\n }\r\n return theConfig;\r\n }\r\n var cfgHandler = (_a = {\r\n uid: null,\r\n cfg: newTarget\r\n },\r\n _a[_DYN_LOGGER /* @min:logger */] = logger,\r\n _a[_DYN_NOTIFY /* @min:notify */] = _notifyWatchers,\r\n _a.set = _setValue,\r\n _a[_DYN_SET_DF /* @min:setDf */] = _applyDefaults,\r\n _a[_DYN_WATCH /* @min:watch */] = _watch,\r\n _a.ref = _ref,\r\n _a[_DYN_RD_ONLY /* @min:rdOnly */] = _rdOnly,\r\n _a[_DYN_BLK_VAL /* @min:blkVal */] = _blkPropValue,\r\n _a._block = _block,\r\n _a);\r\n objDefine(cfgHandler, \"uid\", {\r\n c: false,\r\n e: false,\r\n w: false,\r\n v: uid\r\n });\r\n theState = _createState(cfgHandler);\r\n // Setup tracking for all defined default keys\r\n _makeDynamicObject(theState, newTarget, \"config\", \"Creating\");\r\n return cfgHandler;\r\n}\r\n/**\r\n * Log an invalid access message to the console\r\n * @param message\r\n */\r\nfunction _logInvalidAccess(logger, message) {\r\n if (logger) {\r\n logger[_DYN_WARN_TO_CONSOLE /* @min:%2ewarnToConsole */](message);\r\n logger[_DYN_THROW_INTERNAL /* @min:%2ethrowInternal */](2 /* eLoggingSeverity.WARNING */, 108 /* _eInternalMessageId.DynamicConfigException */, message);\r\n }\r\n else {\r\n // We don't have a logger so just throw an exception\r\n throwInvalidAccess(message);\r\n }\r\n}\r\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 */\r\nexport function createDynamicConfig(config, defaultConfig, logger, inPlace) {\r\n var dynamicHandler = _createDynamicHandler(logger, config || {}, inPlace);\r\n if (defaultConfig) {\r\n dynamicHandler[_DYN_SET_DF /* @min:%2esetDf */](dynamicHandler.cfg, defaultConfig);\r\n }\r\n return dynamicHandler;\r\n}\r\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 config\r\n * @param configHandler\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 */\r\nexport function onConfigChange(config, configHandler, logger) {\r\n var handler = config[CFG_HANDLER_LINK] || config;\r\n if (handler.cfg && (handler.cfg === config || handler.cfg[CFG_HANDLER_LINK] === handler)) {\r\n return handler[_DYN_WATCH /* @min:%2ewatch */](configHandler);\r\n }\r\n _logInvalidAccess(logger, STR_NOT_DYNAMIC_ERROR + dumpObj(config));\r\n return createDynamicConfig(config, null, logger)[_DYN_WATCH /* @min:%2ewatch */](configHandler);\r\n}\r\n//# sourceMappingURL=DynamicConfig.js.map","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { isNullOrUndefined } from \"../helpers/base\";\r\nimport { dumpObj } from \"../helpers/diagnostics\";\r\nimport { throwTypeError } from \"../helpers/throw\";\r\nimport { EMPTY } from \"../internal/constants\";\r\n\r\nfunction _createTrimFn(exp: RegExp): (value: string) => string {\r\n return function _doTrim(value: string): string {\r\n if (isNullOrUndefined(value)) {\r\n throwTypeError(\"strTrim called [\" + dumpObj(value) + \"]\")\r\n }\r\n \r\n if (value && value.replace) {\r\n value = value.replace(exp, EMPTY);\r\n }\r\n \r\n return value;\r\n }\r\n}\r\n\r\n/**\r\n * The trim() method removes whitespace from both ends of a string and returns a new string,\r\n * without modifying the original string. Whitespace in this context is all the whitespace\r\n * characters (space, tab, no-break space, etc.) and all the line terminator characters\r\n * (LF, CR, etc.).\r\n * @group Polyfill\r\n * @group String\r\n * @param value - The string value to be trimmed.\r\n * @returns A new string representing str stripped of whitespace from both its beginning and end.\r\n * If neither the beginning or end of str has any whitespace, a new string is still returned (essentially\r\n * a copy of str), with no exception being thrown.\r\n * To return a new string with whitespace trimmed from just one end, use `strTrimStart()` or `strTrimEnd()`.\r\n */\r\nexport const polyStrTrim = _createTrimFn(/^\\s+|(?=\\s)\\s+$/g);\r\n\r\n/**\r\n * The `polyStrTrimStart()` method removes whitespace from the beginning of a string.\r\n * @group Polyfill\r\n * @group String\r\n * @param value - The value to be trimmed.\r\n * @returns A new string representing str stripped of whitespace from its beginning (left side).\r\n * If the beginning of str has no whitespace, a new string is still returned (essentially a copy of str),\r\n * with no exception being thrown.\r\n */\r\nexport const polyStrTrimStart = _createTrimFn(/^\\s+/g);\r\n \r\n/**\r\n * The `polyStrTrimEnd()` method removes whitespace from the end of a string.\r\n * @group Polyfill\r\n * @group String\r\n * @param value - The value to be trimmed.\r\n * @returns A new string representing str stripped of whitespace from its end (right side).\r\n * If the end of str has no whitespace, a new string is still returned (essentially a copy of str),\r\n * with no exception being thrown.\r\n */\r\nexport const polyStrTrimEnd = _createTrimFn(/(?=\\s)\\s+$/g);\r\n","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { StrProto } from \"../internal/constants\";\r\nimport { _unwrapFunctionWithPoly } from \"../internal/unwrapFunction\";\r\nimport { polyStrTrim, polyStrTrimEnd, polyStrTrimStart } from \"../polyfills/trim\";\r\n\r\n/**\r\n * The trim() method removes whitespace from both ends of a string and returns a new string,\r\n * without modifying the original string. Whitespace in this context is all the whitespace\r\n * characters (space, tab, no-break space, etc.) and all the line terminator characters\r\n * (LF, CR, etc.).\r\n * @group String\r\n * @param value - The string value to be trimmed.\r\n * @returns A new string representing str stripped of whitespace from both its beginning and end.\r\n * If neither the beginning or end of str has any whitespace, a new string is still returned (essentially\r\n * a copy of str), with no exception being thrown.\r\n * To return a new string with whitespace trimmed from just one end, use `strTrimStart()` or `strTrimEnd()`.\r\n */\r\nexport const strTrim: (value: string) => string = _unwrapFunctionWithPoly(\"trim\", StrProto, polyStrTrim);\r\n\r\n/**\r\n * The `strTrimStart()` method removes whitespace from the beginning of a string.\r\n * @group String\r\n * @param value - The value to be trimmed.\r\n * @returns A new string representing str stripped of whitespace from its beginning (left side).\r\n * If the beginning of str has no whitespace, a new string is still returned (essentially a copy of str),\r\n * with no exception being thrown.\r\n */\r\nexport const strTrimStart: (value: string) => string = _unwrapFunctionWithPoly(\"trimStart\", StrProto, polyStrTrimStart);\r\n\r\n/**\r\n * Alias for `strTrimStart()` method removes whitespace from the beginning of a string.\r\n * @group String\r\n * @param value - The value to be trimmed.\r\n * @returns A new string representing str stripped of whitespace from its beginning (left side).\r\n * If the beginning of str has no whitespace, a new string is still returned (essentially a copy of str),\r\n * with no exception being thrown.\r\n */\r\nexport const strTrimLeft = strTrimStart;\r\n\r\n/**\r\n * The `strTrimEnd()` method removes whitespace from the end of a string.\r\n * @group String\r\n * @param value - The value to be trimmed.\r\n * @returns A new string representing str stripped of whitespace from its end (right side).\r\n * If the end of str has no whitespace, a new string is still returned (essentially a copy of str),\r\n * with no exception being thrown.\r\n */\r\nexport const strTrimEnd: (value: string) => string = _unwrapFunctionWithPoly(\"trimEnd\", StrProto, polyStrTrimEnd);\r\n\r\n/**\r\n * Alias for `strTrimEnd()` method removes whitespace from the end of a string.\r\n * @group String\r\n * @param value - The value to be trimmed.\r\n * @returns A new string representing str stripped of whitespace from its end (right side).\r\n * If the end of str has no whitespace, a new string is still returned (essentially a copy of str),\r\n * with no exception being thrown.\r\n */\r\nexport const strTrimRight = strTrimEnd;\r\n","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { MathCls } from \"../internal/constants\";\r\n\r\n/**\r\n * The mathMin() function returns the lowest-valued number passed into it, or NaN if any\r\n * parameter isn't a number and can't be converted into one.\r\n *\r\n * If no arguments are given, the result is Infinity.\r\n *\r\n * If at least one of arguments cannot be converted to a number, the result is NaN.\r\n *\r\n * @since 0.4.2\r\n * @group Math\r\n * @param values - Zero or more numbers among which the lowest value will be selected and returned.\r\n * @returns The smallest of the given numbers. If any one or more of the parameters cannot\r\n * be converted into a number, NaN is returned. The result is Infinity if no parameters are provided.\r\n * @example\r\n * ```ts\r\n * const x = 10, y = -20;\r\n * const z = Math.min(x, y); // -20\r\n * ```\r\n */\r\nexport const mathMin: (...values: number[]) => number = MathCls.min;\r\n\r\n/**\r\n * The `mathMax()` function returns the largest of the zero or more numbers given as input\r\n * parameters, or NaN if any parameter isn't a number and can't be converted into one.\r\n *\r\n * If no arguments are given, the result is -Infinity.\r\n *\r\n * If at least one of arguments cannot be converted to a number, the result is NaN.\r\n *\r\n * @since 0.4.2\r\n * @group Math\r\n * @param values - Zero or more numbers among which the largest value will be selected and returned.\r\n * @returns The largest of the given numbers. If any one or more of the parameters cannot be\r\n * converted into a number, NaN is returned. The result is -Infinity if no parameters are provided.\r\n * @example\r\n * ```ts\r\n * mathMax(10, 20); // 20\r\n * mathMax(-10, -20); // -10\r\n * mathMax(-10, 20); // 20\r\n * ```\r\n */\r\nexport const mathMax: (...values: number[]) => number = MathCls.max;\r\n","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { SLICE, StrProto } from \"../internal/constants\";\r\nimport { _unwrapFunction } from \"../internal/unwrapFunction\";\r\n\r\n/**\r\n * The `strSlice()` method extracts a section of a string and returns it as a new string, without\r\n * modifying the original string.\r\n * `strSlice()` extracts the text from one string and returns a new string. Changes to the text in one\r\n * string do not affect the other string.\r\n * `strSlice()` extracts up to but not including endIndex. str.slice(1, 4) extracts the second character\r\n * through the fourth character (characters indexed 1, 2, and 3).\r\n * As an example, strSlice(2, -1) extracts the third character through the second to last character\r\n * in the string.\r\n * @group String\r\n * @param value - The value to haveextract a number\r\n * @param beginIndex - The zero-based index at which to begin extraction.\r\n * If `beginIndex` is negative, `strSlice()` begins extraction from `value.length + beginIndex`.\r\n * (E.g. `strSlice(\"test\", -2)` returns \"st\")\r\n * If `beginIndex` is omitted, undefined, or cannot be converted to a number (using Number(`beginIndex`)),\r\n * strSlice() begins extraction from the beginning of the string. (E.g. `strSlice(\"test\")` returns \"test\")\r\n * If `beginIndex` is greater than or equal to `value.length`, an empty string is returned.\r\n * (E.g. `strSlice(\"test\", 4)` returns \"\")\r\n * @param endIndex - The index of the first character to exclude from the returned substring.\r\n * If `endIndex` is omitted, undefined, or cannot be converted to a number (using Number(`endIndex`))\r\n * strSlice() extracts to the end of the string. (E.g. `strSlice(\"test\", 2)` returns \"st\")\r\n * If `endIndex` is greater than `value.length`, strSlice() also extracts to the end of the string.\r\n * (E.g. strSlice(\"test\", 2, 10)` returns \"st\")\r\n * If `endIndex` is negative, `strSlice()` treats it as `value.length + endIndex`. (E.g, if `endIndex`\r\n * is -2, it is treated as `value.length - 2` and `strSlice(\"test\", 1, -2)` returns \"e\") .\r\n * If `endIndex` represents a position that is before the one represented by startIndex, `strSlice()`\r\n * returns \"\". (E.g `strSlice(\"test\", 2, -10)`, strSlice(\"test\", -1, -2)` or `strSlice(\"test\", 3, 2)`).\r\n * @returns A new string containing the extracted section of the string.\r\n */\r\nexport const strSlice: (value: string, beginIndex: number, endIndex?: number) => string = _unwrapFunction(SLICE, StrProto);\r\n","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { isNullOrUndefined, isUndefined } from \"../helpers/base\";\r\nimport { dumpObj } from \"../helpers/diagnostics\";\r\nimport { throwTypeError } from \"../helpers/throw\";\r\nimport { EMPTY, LENGTH, StrProto } from \"../internal/constants\";\r\nimport { _unwrapFunction, _unwrapFunctionWithPoly } from \"../internal/unwrapFunction\";\r\nimport { mathMax } from \"../math/min_max\";\r\nimport { strSlice } from \"./slice\";\r\n\r\n/**\r\n * The `strSubstring()` method returns the part of the string between the start and end indexes, or to the end of the string.\r\n *\r\n * `strSubstring()` extracts characters from indexStart up to but not including indexEnd. In particular:\r\n * - If `indexEnd` is omitted, strSubstring() extracts characters to the end of the string.\r\n * - If `indexStart` is equal to indexEnd, strSubstring() returns an empty string.\r\n * - If `indexStart` is greater than indexEnd, then the effect of strSubstring() is as if the two arguments were swapped; see example below.\r\n *\r\n * Any argument value that is less than 0 or greater than `value.length` is treated as if it were 0 and `value.length`, respectively.\r\n *\r\n * Any argument value that is NaN is treated as if it were 0.\r\n * @group String\r\n * @param value - The string value to return the substring from.\r\n * @param indexStart - The index of the first character to include in the returned substring.\r\n * @param indexEnd - The index of the first character to exclude from the returned substring.\r\n * @return A new string containing the specified part of the given string\r\n * @example\r\n * ```ts\r\n * const anyString = 'Nevware21';\r\n * // Displays 'N'\r\n * console.log(strSubstring(anyString, 0, 1));\r\n * console.log(strSubstring(anyString, 1, 0));\r\n *\r\n * // Displays 'Nevwar'\r\n * console.log(strSubstring(anyString, 0, 6));\r\n *\r\n * // Displays 'are21'\r\n * console.log(strSubstring(anyString, 4));\r\n *\r\n * // Displays 'are'\r\n * console.log(strSubstring(anyString, 4, 7));\r\n *\r\n * // Displays '21'\r\n * console.log(strSubstring(anyString, 7, 4));\r\n *\r\n * // Displays 'Nevware'\r\n * console.log(strSubstring(anyString, 0, 7));\r\n *\r\n * // Displays 'Nevware21'\r\n * console.log(strSubstring(anyString, 0, 10));\r\n * ```\r\n */\r\nexport const strSubstring: (value: string, indexStart: number, indexEnd?: number) => string = _unwrapFunction(\"substring\", StrProto);\r\n\r\n/**\r\n * The strSubstr() method returns a portion of the string, starting at the specified index and extending for a given\r\n * number of characters afterwards.\r\n *\r\n * @since 0.4.2\r\n * @group String\r\n * @param value - The string value to return the substring from.\r\n * @param start - The index of the first character to include in the returned substring.\r\n * @param length - The number of characters to extract.\r\n * @returns A new string containing the specified part of the given string.\r\n */\r\nexport const strSubstr: (value: string, indexStart: number, indexEnd?: number) => string = _unwrapFunctionWithPoly(\"substr\", StrProto, polyStrSubstr);\r\n\r\n/**\r\n * The polyStrSubstr() method returns a portion of the string, starting at the specified index and extending for a given\r\n * number of characters afterwards.\r\n *\r\n * @since 0.4.2\r\n * @group String\r\n * @group Polyfill\r\n * @param value - The string value to return the substring from.\r\n * @param start - The index of the first character to include in the returned substring.\r\n * @param length - The number of characters to extract.\r\n * @returns A new string containing the specified part of the given string.\r\n */\r\nexport function polyStrSubstr(value: string, start: number, length?: number): string {\r\n if (isNullOrUndefined(value)) {\r\n throwTypeError(\"'polyStrSubstr called with invalid \" + dumpObj(value));\r\n }\r\n\r\n if (length < 0) {\r\n return EMPTY;\r\n }\r\n\r\n // If start is omitted or undefined, its treated as zero\r\n start = start || 0;\r\n\r\n if (start < 0) {\r\n start = mathMax(start + value[LENGTH], 0);\r\n }\r\n\r\n if (isUndefined(length)) {\r\n return strSlice(value, start);\r\n }\r\n\r\n return strSlice(value, start, start + length);\r\n}\r\n\r\n/**\r\n * Returns a substring of the string starting from the left.\r\n *\r\n * `strLeft()` extracts the number of characters from left of the string up to the count. In particular:\r\n * - If `count` is less than zero, strLeft() returns an empty string.\r\n * - If `count` is less than `value.length', strLeft() returns a new string with the `count` number of characters from the left of the string.\r\n * - If `count` is greater than `value.length`, then the value original value is returned.\r\n *\r\n * Any argument value that is NaN is treated as if it were 0.\r\n *\r\n * @since 0.4.2\r\n * @group String\r\n * @param value - The string value to return the substring from.\r\n * @param count - The number of characters to extract\r\n * @returns The substring based on the count number of characters from the right\r\n * @example\r\n * ```ts\r\n * strLeft(\"Nevware21\", -1); // \"\"\r\n * strLeft(\"Nevware21\", 0); // \"\"\r\n * strLeft(\"Nevware21\", 1); // \"N\"\r\n * strLeft(\"Nevware21\", 3); // \"Nev\"\r\n * strLeft(\"Nevware21\", 21); // \"Nevware21\"\r\n * ```\r\n */\r\nexport function strLeft(value: string, count: number): string {\r\n return strSubstring(value, 0, count);\r\n}\r\n\r\n/**\r\n * Returns a substring of the string starting from the right.\r\n *\r\n * `strRight()` extracts the number of characters from right of the string up to the count. In particular:\r\n * - If `count` is less than zero, strRight() returns an empty string.\r\n * - If `count` is less than `value.length', strRight() returns a new string with the `count` number of characters from the right of the string.\r\n * - If `count` is greater than `value.length`, then the value original value is returned.\r\n *\r\n * Any argument value that is NaN is treated as if it were 0.\r\n *\r\n * @since 0.4.2\r\n * @group String\r\n * @param value - The string value to return the substring from.\r\n * @param count - The number of characters to extract\r\n * @returns The substring based on the count number of characters from the right\r\n * @example\r\n * ```ts\r\n * strRight(\"Nevware21\", -1); // \"\"\r\n * strRight(\"Nevware21\", 0); // \"\"\r\n * strRight(\"Nevware21\", 1); // \"1\"\r\n * strRight(\"Nevware21\", 3); // \"e21\"\r\n * strRight(\"Nevware21\", 21); // \"Nevware21\"\r\n * ```\r\n */\r\nexport function strRight(value: string, count: number): string {\r\n let len = value[LENGTH];\r\n if (count <= 0) {\r\n return EMPTY;\r\n }\r\n\r\n return len > count ? strSubstring(value, len - count) : value;\r\n}","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { isString, isUndefined } from \"../helpers/base\";\r\nimport { dumpObj } from \"../helpers/diagnostics\";\r\nimport { throwTypeError } from \"../helpers/throw\";\r\nimport { LENGTH, StrProto } from \"../internal/constants\";\r\nimport { _unwrapFunctionWithPoly } from \"../internal/unwrapFunction\";\r\nimport { asString } from \"./as_string\";\r\nimport { strSubstring } from \"./substring\";\r\n\r\n/**\r\n * This method lets you determine whether or not a string ends with another string. This method is case-sensitive.\r\n * @group String\r\n * @param value - The value to be checked\r\n * @param searchString - The characters to be searched for at the end of `value` string.\r\n * @param length - If provided, it is used as the length of `value`. Defaults to value.length.\r\n */\r\nexport const strEndsWith: (value: string, searchString: string, length?: number) => boolean = _unwrapFunctionWithPoly(\"endsWith\", StrProto, polyStrEndsWith);\r\n\r\n/**\r\n * This method lets you determine whether or not a string ends with another string. This method is case-sensitive.\r\n * @group Polyfill\r\n * @group String\r\n * @param value - The value to be checked\r\n * @param searchString - The characters to be searched for at the end of `value` string.\r\n * @param length - If provided, it is used as the length of `value`. Defaults to value.length.\r\n */\r\nexport function polyStrEndsWith(value: string, searchString: string, length?: number): boolean {\r\n if (!isString(value)) {\r\n throwTypeError(\"'\" + dumpObj(value) + \"' is not a string\");\r\n }\r\n\r\n let searchValue = isString(searchString) ? searchString : asString(searchString);\r\n let chkLen = searchValue[LENGTH];\r\n let len = value[LENGTH];\r\n let end = !isUndefined(length) && length < len ? length : len;\r\n\r\n return strSubstring(value, end - chkLen, end) === searchValue;\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { asString, isBoolean, isFunction, isNullOrUndefined, isString } from \"@nevware21/ts-utils\";\r\nimport { STR_EMPTY } from \"../JavaScriptSDK/InternalConstants\";\r\nimport { _DYN_BLK_VAL, _DYN_TO_LOWER_CASE } from \"../__DynamicConstants\";\r\n/**\r\n * @internal\r\n * @ignore\r\n * @param str\r\n * @param defaultValue\r\n * @returns\r\n */\r\nfunction _stringToBoolOrDefault(theValue, defaultValue, theConfig) {\r\n if (!theValue && isNullOrUndefined(theValue)) {\r\n return defaultValue;\r\n }\r\n if (isBoolean(theValue)) {\r\n return theValue;\r\n }\r\n return asString(theValue)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]() === \"true\";\r\n}\r\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 */\r\nexport function cfgDfMerge(defaultValue) {\r\n return {\r\n mrg: true,\r\n v: defaultValue\r\n };\r\n}\r\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 */\r\nexport function cfgDfSet(setter, defaultValue) {\r\n return {\r\n set: setter,\r\n v: defaultValue\r\n };\r\n}\r\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 */\r\nexport function cfgDfValidate(validator, defaultValue, fallBackName) {\r\n return {\r\n fb: fallBackName,\r\n isVal: validator,\r\n v: defaultValue\r\n };\r\n}\r\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 */\r\nexport function cfgDfBoolean(defaultValue, fallBackName) {\r\n return {\r\n fb: fallBackName,\r\n set: _stringToBoolOrDefault,\r\n v: !!defaultValue\r\n };\r\n}\r\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 */\r\nexport function cfgDfFunc(defaultValue) {\r\n return {\r\n isVal: isFunction,\r\n v: defaultValue || null\r\n };\r\n}\r\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 */\r\nexport function cfgDfString(defaultValue) {\r\n return {\r\n isVal: isString,\r\n v: asString(defaultValue || STR_EMPTY)\r\n };\r\n}\r\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 */\r\nexport function cfgDfBlockPropValue(defaultValue) {\r\n var _a;\r\n return _a = {},\r\n _a[_DYN_BLK_VAL /* @min:blkVal */] = true,\r\n _a.v = defaultValue,\r\n _a;\r\n}\r\n//# sourceMappingURL=ConfigDefaultHelpers.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { getInst } from \"@nevware21/ts-utils\";\r\nimport { _DYN_APPLY, _DYN_LENGTH } from \"../__DynamicConstants\";\r\nimport { STR_EVENTS_DISCARDED, STR_EVENTS_SEND_REQUEST, STR_EVENTS_SENT, STR_PERF_EVENT } from \"./InternalConstants\";\r\nvar listenerFuncs = [STR_EVENTS_SENT, STR_EVENTS_DISCARDED, STR_EVENTS_SEND_REQUEST, STR_PERF_EVENT];\r\nvar _aiNamespace = null;\r\nvar _debugListener;\r\nfunction _listenerProxyFunc(name, config) {\r\n return function () {\r\n var args = arguments;\r\n var dbgExt = getDebugExt(config);\r\n if (dbgExt) {\r\n var listener = dbgExt.listener;\r\n if (listener && listener[name]) {\r\n listener[name][_DYN_APPLY /* @min:%2eapply */](listener, args);\r\n }\r\n }\r\n };\r\n}\r\nfunction _getExtensionNamespace() {\r\n // Cache the lookup of the global namespace object\r\n var target = getInst(\"Microsoft\");\r\n if (target) {\r\n _aiNamespace = target[\"ApplicationInsights\"];\r\n }\r\n return _aiNamespace;\r\n}\r\nexport function getDebugExt(config) {\r\n var ns = _aiNamespace;\r\n if (!ns && config.disableDbgExt !== true) {\r\n ns = _aiNamespace || _getExtensionNamespace();\r\n }\r\n return ns ? ns[\"ChromeDbgExt\"] : null;\r\n}\r\nexport function getDebugListener(config) {\r\n if (!_debugListener) {\r\n _debugListener = {};\r\n for (var lp = 0; lp < listenerFuncs[_DYN_LENGTH /* @min:%2elength */]; lp++) {\r\n _debugListener[listenerFuncs[lp]] = _listenerProxyFunc(listenerFuncs[lp], config);\r\n }\r\n }\r\n return _debugListener;\r\n}\r\n//# sourceMappingURL=DbgExtensionUtils.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\"use strict\";\r\nvar _a;\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { dumpObj, isFunction, isUndefined } from \"@nevware21/ts-utils\";\r\nimport { createDynamicConfig, onConfigChange } from \"../Config/DynamicConfig\";\r\nimport { _DYN_DIAG_LOG, _DYN_LOGGER, _DYN_LOGGING_LEVEL_CONSOL4, _DYN_LOG_INTERNAL_MESSAGE, _DYN_MESSAGE, _DYN_MESSAGE_ID, _DYN_PUSH, _DYN_REPLACE, _DYN_THROW_INTERNAL, _DYN_UNLOAD, _DYN_WARN_TO_CONSOLE } from \"../__DynamicConstants\";\r\nimport { getDebugExt } from \"./DbgExtensionUtils\";\r\nimport { getConsole, getJSON, hasJSON } from \"./EnvUtils\";\r\nimport { STR_EMPTY } from \"./InternalConstants\";\r\nvar STR_WARN_TO_CONSOLE = \"warnToConsole\";\r\n/**\r\n * For user non actionable traces use AI Internal prefix.\r\n */\r\nvar AiNonUserActionablePrefix = \"AI (Internal): \";\r\n/**\r\n * Prefix of the traces in portal.\r\n */\r\nvar AiUserActionablePrefix = \"AI: \";\r\n/**\r\n * Session storage key for the prefix for the key indicating message type already logged\r\n */\r\nvar AIInternalMessagePrefix = \"AITR_\";\r\nvar defaultValues = {\r\n loggingLevelConsole: 0,\r\n loggingLevelTelemetry: 1,\r\n maxMessageLimit: 25,\r\n enableDebug: false\r\n};\r\nvar _logFuncs = (_a = {},\r\n _a[0 /* eLoggingSeverity.DISABLED */] = null,\r\n _a[1 /* eLoggingSeverity.CRITICAL */] = \"errorToConsole\",\r\n _a[2 /* eLoggingSeverity.WARNING */] = STR_WARN_TO_CONSOLE,\r\n _a[3 /* eLoggingSeverity.DEBUG */] = \"debugToConsole\",\r\n _a);\r\nfunction _sanitizeDiagnosticText(text) {\r\n if (text) {\r\n return \"\\\"\" + text[_DYN_REPLACE /* @min:%2ereplace */](/\\\"/g, STR_EMPTY) + \"\\\"\";\r\n }\r\n return STR_EMPTY;\r\n}\r\nfunction _logToConsole(func, message) {\r\n var theConsole = getConsole();\r\n if (!!theConsole) {\r\n var logFunc = \"log\";\r\n if (theConsole[func]) {\r\n logFunc = func;\r\n }\r\n if (isFunction(theConsole[logFunc])) {\r\n theConsole[logFunc](message);\r\n }\r\n }\r\n}\r\nvar _InternalLogMessage = /** @class */ (function () {\r\n function _InternalLogMessage(msgId, msg, isUserAct, properties) {\r\n if (isUserAct === void 0) { isUserAct = false; }\r\n var _self = this;\r\n _self[_DYN_MESSAGE_ID /* @min:%2emessageId */] = msgId;\r\n _self[_DYN_MESSAGE /* @min:%2emessage */] =\r\n (isUserAct ? AiUserActionablePrefix : AiNonUserActionablePrefix) +\r\n msgId;\r\n var strProps = STR_EMPTY;\r\n if (hasJSON()) {\r\n strProps = getJSON().stringify(properties);\r\n }\r\n var diagnosticText = (msg ? \" message:\" + _sanitizeDiagnosticText(msg) : STR_EMPTY) +\r\n (properties ? \" props:\" + _sanitizeDiagnosticText(strProps) : STR_EMPTY);\r\n _self[_DYN_MESSAGE /* @min:%2emessage */] += diagnosticText;\r\n }\r\n _InternalLogMessage.dataType = \"MessageData\";\r\n return _InternalLogMessage;\r\n}());\r\nexport { _InternalLogMessage };\r\nexport function safeGetLogger(core, config) {\r\n return (core || {})[_DYN_LOGGER /* @min:%2elogger */] || new DiagnosticLogger(config);\r\n}\r\nvar DiagnosticLogger = /** @class */ (function () {\r\n function DiagnosticLogger(config) {\r\n this.identifier = \"DiagnosticLogger\";\r\n /**\r\n * The internal logging queue\r\n */\r\n this.queue = [];\r\n /**\r\n * Count of internal messages sent\r\n */\r\n var _messageCount = 0;\r\n /**\r\n * Holds information about what message types were already logged to console or sent to server.\r\n */\r\n var _messageLogged = {};\r\n var _loggingLevelConsole;\r\n var _loggingLevelTelemetry;\r\n var _maxInternalMessageLimit;\r\n var _enableDebug;\r\n var _unloadHandler;\r\n dynamicProto(DiagnosticLogger, this, function (_self) {\r\n _unloadHandler = _setDefaultsFromConfig(config || {});\r\n _self.consoleLoggingLevel = function () { return _loggingLevelConsole; };\r\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 - {LoggingSeverity} - The severity of the log message\r\n * @param message - {_InternalLogMessage} - The log message.\r\n */\r\n _self[_DYN_THROW_INTERNAL /* @min:%2ethrowInternal */] = function (severity, msgId, msg, properties, isUserAct) {\r\n if (isUserAct === void 0) { isUserAct = false; }\r\n var message = new _InternalLogMessage(msgId, msg, isUserAct, properties);\r\n if (_enableDebug) {\r\n throw dumpObj(message);\r\n }\r\n else {\r\n // Get the logging function and fallback to warnToConsole of for some reason errorToConsole doesn't exist\r\n var logFunc = _logFuncs[severity] || STR_WARN_TO_CONSOLE;\r\n if (!isUndefined(message[_DYN_MESSAGE /* @min:%2emessage */])) {\r\n if (isUserAct) {\r\n // check if this message type was already logged to console for this page view and if so, don't log it again\r\n var messageKey = +message[_DYN_MESSAGE_ID /* @min:%2emessageId */];\r\n if (!_messageLogged[messageKey] && _loggingLevelConsole >= severity) {\r\n _self[logFunc](message[_DYN_MESSAGE /* @min:%2emessage */]);\r\n _messageLogged[messageKey] = true;\r\n }\r\n }\r\n else {\r\n // Only log traces if the console Logging Level is >= the throwInternal severity level\r\n if (_loggingLevelConsole >= severity) {\r\n _self[logFunc](message[_DYN_MESSAGE /* @min:%2emessage */]);\r\n }\r\n }\r\n _logInternalMessage(severity, message);\r\n }\r\n else {\r\n _debugExtMsg(\"throw\" + (severity === 1 /* eLoggingSeverity.CRITICAL */ ? \"Critical\" : \"Warning\"), message);\r\n }\r\n }\r\n };\r\n _self.debugToConsole = function (message) {\r\n _logToConsole(\"debug\", message);\r\n _debugExtMsg(\"warning\", message);\r\n };\r\n _self[_DYN_WARN_TO_CONSOLE /* @min:%2ewarnToConsole */] = function (message) {\r\n _logToConsole(\"warn\", message);\r\n _debugExtMsg(\"warning\", message);\r\n };\r\n _self.errorToConsole = function (message) {\r\n _logToConsole(\"error\", message);\r\n _debugExtMsg(\"error\", message);\r\n };\r\n _self.resetInternalMessageCount = function () {\r\n _messageCount = 0;\r\n _messageLogged = {};\r\n };\r\n _self[_DYN_LOG_INTERNAL_MESSAGE /* @min:%2elogInternalMessage */] = _logInternalMessage;\r\n _self[_DYN_UNLOAD /* @min:%2eunload */] = function (isAsync) {\r\n _unloadHandler && _unloadHandler.rm();\r\n _unloadHandler = null;\r\n };\r\n function _logInternalMessage(severity, message) {\r\n if (_areInternalMessagesThrottled()) {\r\n return;\r\n }\r\n // check if this message type was already logged for this session and if so, don't log it again\r\n var logMessage = true;\r\n var messageKey = AIInternalMessagePrefix + message[_DYN_MESSAGE_ID /* @min:%2emessageId */];\r\n // if the session storage is not available, limit to only one message type per page view\r\n if (_messageLogged[messageKey]) {\r\n logMessage = false;\r\n }\r\n else {\r\n _messageLogged[messageKey] = true;\r\n }\r\n if (logMessage) {\r\n // Push the event in the internal queue\r\n if (severity <= _loggingLevelTelemetry) {\r\n _self.queue[_DYN_PUSH /* @min:%2epush */](message);\r\n _messageCount++;\r\n _debugExtMsg((severity === 1 /* eLoggingSeverity.CRITICAL */ ? \"error\" : \"warn\"), message);\r\n }\r\n // When throttle limit reached, send a special event\r\n if (_messageCount === _maxInternalMessageLimit) {\r\n var throttleLimitMessage = \"Internal events throttle limit per PageView reached for this app.\";\r\n var throttleMessage = new _InternalLogMessage(23 /* _eInternalMessageId.MessageLimitPerPVExceeded */, throttleLimitMessage, false);\r\n _self.queue[_DYN_PUSH /* @min:%2epush */](throttleMessage);\r\n if (severity === 1 /* eLoggingSeverity.CRITICAL */) {\r\n _self.errorToConsole(throttleLimitMessage);\r\n }\r\n else {\r\n _self[_DYN_WARN_TO_CONSOLE /* @min:%2ewarnToConsole */](throttleLimitMessage);\r\n }\r\n }\r\n }\r\n }\r\n function _setDefaultsFromConfig(config) {\r\n // make sure the config is dynamic\r\n return onConfigChange(createDynamicConfig(config, defaultValues, _self).cfg, function (details) {\r\n var config = details.cfg;\r\n _loggingLevelConsole = config[_DYN_LOGGING_LEVEL_CONSOL4 /* @min:%2eloggingLevelConsole */];\r\n _loggingLevelTelemetry = config.loggingLevelTelemetry;\r\n _maxInternalMessageLimit = config.maxMessageLimit;\r\n _enableDebug = config.enableDebug;\r\n });\r\n }\r\n function _areInternalMessagesThrottled() {\r\n return _messageCount >= _maxInternalMessageLimit;\r\n }\r\n function _debugExtMsg(name, data) {\r\n var dbgExt = getDebugExt(config || {});\r\n if (dbgExt && dbgExt[_DYN_DIAG_LOG /* @min:%2ediagLog */]) {\r\n dbgExt[_DYN_DIAG_LOG /* @min:%2ediagLog */](name, data);\r\n }\r\n }\r\n });\r\n }\r\n /**\r\n * 0: OFF (default)\r\n * 1: CRITICAL\r\n * 2: >= WARNING\r\n */\r\n DiagnosticLogger.prototype.consoleLoggingLevel = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return 0;\r\n };\r\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 - {LoggingSeverity} - The severity of the log message\r\n * @param message - {_InternalLogMessage} - The log message.\r\n */\r\n DiagnosticLogger.prototype.throwInternal = function (severity, msgId, msg, properties, isUserAct) {\r\n if (isUserAct === void 0) { isUserAct = false; }\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * This will write a debug message to the console if possible\r\n * @param message - {string} - The debug message\r\n */\r\n DiagnosticLogger.prototype.debugToConsole = function (message) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * This will write a warning to the console if possible\r\n * @param message - {string} - The warning message\r\n */\r\n DiagnosticLogger.prototype.warnToConsole = function (message) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * This will write an error to the console if possible\r\n * @param message - {string} - The warning message\r\n */\r\n DiagnosticLogger.prototype.errorToConsole = function (message) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Resets the internal message count\r\n */\r\n DiagnosticLogger.prototype.resetInternalMessageCount = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Logs a message to the internal queue.\r\n * @param severity - {LoggingSeverity} - The severity of the log message\r\n * @param message - {_InternalLogMessage} - The message to log.\r\n */\r\n DiagnosticLogger.prototype.logInternalMessage = function (severity, message) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Unload and remove any state that this IDiagnosticLogger may be holding, this is generally called when the\r\n * owning SDK is being unloaded.\r\n * @param isAsync - Can the unload be performed asynchronously (default)\r\n * @return If the unload occurs synchronously then nothing should be returned, if happening asynchronously then\r\n * the function should return an [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * / Promise to allow any listeners to wait for the operation to complete.\r\n */\r\n DiagnosticLogger.prototype.unload = function (isAsync) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n return DiagnosticLogger;\r\n}());\r\nexport { DiagnosticLogger };\r\nfunction _getLogger(logger) {\r\n return (logger || new DiagnosticLogger());\r\n}\r\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 - {LoggingSeverity} - The severity of the log message\r\n * @param message - {_InternalLogMessage} - The log message.\r\n */\r\nexport function _throwInternal(logger, severity, msgId, msg, properties, isUserAct) {\r\n if (isUserAct === void 0) { isUserAct = false; }\r\n _getLogger(logger)[_DYN_THROW_INTERNAL /* @min:%2ethrowInternal */](severity, msgId, msg, properties, isUserAct);\r\n}\r\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 - {_InternalLogMessage} - The log message.\r\n */\r\nexport function _warnToConsole(logger, message) {\r\n _getLogger(logger)[_DYN_WARN_TO_CONSOLE /* @min:%2ewarnToConsole */](message);\r\n}\r\n/**\r\n * Logs a message to the internal queue.\r\n * @param logger - The Diagnostic Logger instance to use.\r\n * @param severity - {LoggingSeverity} - The severity of the log message\r\n * @param message - {_InternalLogMessage} - The message to log.\r\n */\r\nexport function _logInternalMessage(logger, severity, message) {\r\n _getLogger(logger)[_DYN_LOG_INTERNAL_MESSAGE /* @min:%2elogInternalMessage */](severity, message);\r\n}\r\n//# sourceMappingURL=DiagnosticLogger.js.map","var _a, _b;\r\nimport { arrForEach, arrIndexOf, dumpObj, getDocument, getLazy, getNavigator, isArray, isFunction, isNullOrUndefined, isString, isTruthy, isUndefined, objForEachKey, strEndsWith, strIndexOf, strLeft, strSubstring, strTrim, utcNow } from \"@nevware21/ts-utils\";\r\nimport { cfgDfMerge } from \"../Config/ConfigDefaultHelpers\";\r\nimport { createDynamicConfig, onConfigChange } from \"../Config/DynamicConfig\";\r\nimport { _DYN_ENABLED, _DYN_LENGTH, _DYN_LOGGER, _DYN_SET_DF, _DYN_SPLIT, _DYN_UNLOAD, _DYN_USER_AGENT } from \"../__DynamicConstants\";\r\nimport { _throwInternal } from \"./DiagnosticLogger\";\r\nimport { getLocation, isIE } from \"./EnvUtils\";\r\nimport { getExceptionName, isNotNullOrUndefined, setValue, strContains } from \"./HelperFuncs\";\r\nimport { STR_DOMAIN, STR_EMPTY, STR_PATH, UNDEFINED_VALUE } from \"./InternalConstants\";\r\nvar strToGMTString = \"toGMTString\";\r\nvar strToUTCString = \"toUTCString\";\r\nvar strCookie = \"cookie\";\r\nvar strExpires = \"expires\";\r\nvar strIsCookieUseDisabled = \"isCookieUseDisabled\";\r\nvar strDisableCookiesUsage = \"disableCookiesUsage\";\r\nvar strConfigCookieMgr = \"_ckMgr\";\r\nvar _supportsCookies = null;\r\nvar _allowUaSameSite = null;\r\nvar _parsedCookieValue = null;\r\nvar _doc;\r\nvar _cookieCache = {};\r\nvar _globalCookieConfig = {};\r\n// // `isCookieUseDisabled` is deprecated, so explicitly casting as a key of IConfiguration to avoid typing error\r\n// // when both isCookieUseDisabled and disableCookiesUsage are used disableCookiesUsage will take precedent, which is\r\n// // why its listed first\r\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 */\r\nvar rootDefaultConfig = (_a = {\r\n cookieCfg: cfgDfMerge((_b = {},\r\n _b[STR_DOMAIN] = { fb: \"cookieDomain\", dfVal: isNotNullOrUndefined },\r\n _b.path = { fb: \"cookiePath\", dfVal: isNotNullOrUndefined },\r\n _b.enabled = UNDEFINED_VALUE,\r\n _b.ignoreCookies = UNDEFINED_VALUE,\r\n _b.blockedCookies = UNDEFINED_VALUE,\r\n _b)),\r\n cookieDomain: UNDEFINED_VALUE,\r\n cookiePath: UNDEFINED_VALUE\r\n },\r\n _a[strDisableCookiesUsage] = UNDEFINED_VALUE,\r\n _a);\r\nfunction _getDoc() {\r\n !_doc && (_doc = getLazy(function () { return getDocument(); }));\r\n}\r\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 */\r\nfunction _gblCookieMgr(config, logger) {\r\n // Stash the global instance against the BaseCookieMgr class\r\n var inst = createCookieMgr[strConfigCookieMgr] || _globalCookieConfig[strConfigCookieMgr];\r\n if (!inst) {\r\n // Note: not using the getSetValue() helper as that would require always creating a temporary cookieMgr\r\n // that ultimately is never used\r\n inst = createCookieMgr[strConfigCookieMgr] = createCookieMgr(config, logger);\r\n _globalCookieConfig[strConfigCookieMgr] = inst;\r\n }\r\n return inst;\r\n}\r\nfunction _isMgrEnabled(cookieMgr) {\r\n if (cookieMgr) {\r\n return cookieMgr.isEnabled();\r\n }\r\n return true;\r\n}\r\nfunction _isIgnoredCookie(cookieMgrCfg, name) {\r\n if (name && cookieMgrCfg && isArray(cookieMgrCfg.ignoreCookies)) {\r\n return arrIndexOf(cookieMgrCfg.ignoreCookies, name) !== -1;\r\n }\r\n return false;\r\n}\r\nfunction _isBlockedCookie(cookieMgrCfg, name) {\r\n if (name && cookieMgrCfg && isArray(cookieMgrCfg.blockedCookies)) {\r\n if (arrIndexOf(cookieMgrCfg.blockedCookies, name) !== -1) {\r\n return true;\r\n }\r\n }\r\n return _isIgnoredCookie(cookieMgrCfg, name);\r\n}\r\nfunction _isCfgEnabled(rootConfig, cookieMgrConfig) {\r\n var isCfgEnabled = cookieMgrConfig[_DYN_ENABLED /* @min:%2eenabled */];\r\n if (isNullOrUndefined(isCfgEnabled)) {\r\n // Set the enabled from the provided setting or the legacy root values\r\n var cookieEnabled = void 0;\r\n // This field is deprecated and dynamic updates will not be fully supported\r\n if (!isUndefined(rootConfig[strIsCookieUseDisabled])) {\r\n cookieEnabled = !rootConfig[strIsCookieUseDisabled];\r\n }\r\n // If this value is defined it takes precedent over the above\r\n if (!isUndefined(rootConfig[strDisableCookiesUsage])) {\r\n cookieEnabled = !rootConfig[strDisableCookiesUsage];\r\n }\r\n // Not setting the cookieMgrConfig.enabled as that will update (set) the global dynamic config\r\n // So future \"updates\" then may not be as expected\r\n isCfgEnabled = cookieEnabled;\r\n }\r\n return isCfgEnabled;\r\n}\r\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\r\n * @param config\r\n * @returns\r\n */\r\nexport function safeGetCookieMgr(core, config) {\r\n var cookieMgr;\r\n if (core) {\r\n // Always returns an instance\r\n cookieMgr = core.getCookieMgr();\r\n }\r\n else if (config) {\r\n var cookieCfg = config.cookieCfg;\r\n if (cookieCfg && cookieCfg[strConfigCookieMgr]) {\r\n cookieMgr = cookieCfg[strConfigCookieMgr];\r\n }\r\n else {\r\n cookieMgr = createCookieMgr(config);\r\n }\r\n }\r\n if (!cookieMgr) {\r\n // Get or initialize the default global (legacy) cookie manager if we couldn't find one\r\n cookieMgr = _gblCookieMgr(config, (core || {})[_DYN_LOGGER /* @min:%2elogger */]);\r\n }\r\n return cookieMgr;\r\n}\r\nexport function createCookieMgr(rootConfig, logger) {\r\n var _a;\r\n var cookieMgrConfig;\r\n var _path;\r\n var _domain;\r\n var unloadHandler;\r\n // Explicitly checking against false, so that setting to undefined will === true\r\n var _enabled;\r\n var _getCookieFn;\r\n var _setCookieFn;\r\n var _delCookieFn;\r\n // Make sure the root config is dynamic as it may be the global config\r\n rootConfig = createDynamicConfig(rootConfig || _globalCookieConfig, null, logger).cfg;\r\n // Will get recalled if the referenced configuration is changed\r\n unloadHandler = onConfigChange(rootConfig, function (details) {\r\n // Make sure the root config has all of the the defaults to the root config to ensure they are dynamic\r\n details[_DYN_SET_DF /* @min:%2esetDf */](details.cfg, rootDefaultConfig);\r\n // Create and apply the defaults to the cookieCfg element\r\n cookieMgrConfig = details.ref(details.cfg, \"cookieCfg\"); // details.setDf(details.cfg.cookieCfg, defaultConfig);\r\n _path = cookieMgrConfig[STR_PATH /* @min:%2epath */] || \"/\";\r\n _domain = cookieMgrConfig[STR_DOMAIN /* @min:%2edomain */];\r\n // Explicitly checking against false, so that setting to undefined will === true\r\n _enabled = _isCfgEnabled(rootConfig, cookieMgrConfig) !== false;\r\n _getCookieFn = cookieMgrConfig.getCookie || _getCookieValue;\r\n _setCookieFn = cookieMgrConfig.setCookie || _setCookieValue;\r\n _delCookieFn = cookieMgrConfig.delCookie || _setCookieValue;\r\n }, logger);\r\n var cookieMgr = (_a = {\r\n isEnabled: function () {\r\n var enabled = _isCfgEnabled(rootConfig, cookieMgrConfig) !== false && _enabled && areCookiesSupported(logger);\r\n // Using an indirect lookup for any global cookie manager to support tree shaking for SDK's\r\n // that don't use the \"applicationinsights-core\" version of the default cookie function\r\n var gblManager = _globalCookieConfig[strConfigCookieMgr];\r\n if (enabled && gblManager && cookieMgr !== gblManager) {\r\n // Make sure the GlobalCookie Manager instance (if not this instance) is also enabled.\r\n // As the global (deprecated) functions may have been called (for backward compatibility)\r\n enabled = _isMgrEnabled(gblManager);\r\n }\r\n return enabled;\r\n },\r\n setEnabled: function (value) {\r\n // Explicitly checking against false, so that setting to undefined will === true\r\n _enabled = value !== false;\r\n cookieMgrConfig[_DYN_ENABLED /* @min:%2eenabled */] = value;\r\n },\r\n set: function (name, value, maxAgeSec, domain, path) {\r\n var result = false;\r\n if (_isMgrEnabled(cookieMgr) && !_isBlockedCookie(cookieMgrConfig, name)) {\r\n var values = {};\r\n var theValue = strTrim(value || STR_EMPTY);\r\n var idx = strIndexOf(theValue, \";\");\r\n if (idx !== -1) {\r\n theValue = strTrim(strLeft(value, idx));\r\n values = _extractParts(strSubstring(value, idx + 1));\r\n }\r\n // Only update domain if not already present (isUndefined) and the value is truthy (not null, undefined or empty string)\r\n setValue(values, STR_DOMAIN, domain || _domain, isTruthy, isUndefined);\r\n if (!isNullOrUndefined(maxAgeSec)) {\r\n var _isIE = isIE();\r\n if (isUndefined(values[strExpires])) {\r\n var nowMs = utcNow();\r\n // Only add expires if not already present\r\n var expireMs = nowMs + (maxAgeSec * 1000);\r\n // Sanity check, if zero or -ve then ignore\r\n if (expireMs > 0) {\r\n var expiry = new Date();\r\n expiry.setTime(expireMs);\r\n setValue(values, strExpires, _formatDate(expiry, !_isIE ? strToUTCString : strToGMTString) || _formatDate(expiry, _isIE ? strToGMTString : strToUTCString) || STR_EMPTY, isTruthy);\r\n }\r\n }\r\n if (!_isIE) {\r\n // Only replace if not already present\r\n setValue(values, \"max-age\", STR_EMPTY + maxAgeSec, null, isUndefined);\r\n }\r\n }\r\n var location_1 = getLocation();\r\n if (location_1 && location_1.protocol === \"https:\") {\r\n setValue(values, \"secure\", null, null, isUndefined);\r\n // Only set same site if not also secure\r\n if (_allowUaSameSite === null) {\r\n _allowUaSameSite = !uaDisallowsSameSiteNone((getNavigator() || {})[_DYN_USER_AGENT /* @min:%2euserAgent */]);\r\n }\r\n if (_allowUaSameSite) {\r\n setValue(values, \"SameSite\", \"None\", null, isUndefined);\r\n }\r\n }\r\n setValue(values, STR_PATH, path || _path, null, isUndefined);\r\n //let setCookieFn = cookieMgrConfig.setCookie || _setCookieValue;\r\n _setCookieFn(name, _formatCookieValue(theValue, values));\r\n result = true;\r\n }\r\n return result;\r\n },\r\n get: function (name) {\r\n var value = STR_EMPTY;\r\n if (_isMgrEnabled(cookieMgr) && !_isIgnoredCookie(cookieMgrConfig, name)) {\r\n value = _getCookieFn(name);\r\n }\r\n return value;\r\n },\r\n del: function (name, path) {\r\n var result = false;\r\n if (_isMgrEnabled(cookieMgr)) {\r\n // Only remove the cookie if the manager and cookie support has not been disabled\r\n result = cookieMgr.purge(name, path);\r\n }\r\n return result;\r\n },\r\n purge: function (name, path) {\r\n var _a;\r\n var result = false;\r\n if (areCookiesSupported(logger)) {\r\n // Setting the expiration date in the past immediately removes the cookie\r\n var values = (_a = {},\r\n _a[STR_PATH] = path ? path : \"/\",\r\n _a[strExpires] = \"Thu, 01 Jan 1970 00:00:01 GMT\",\r\n _a);\r\n if (!isIE()) {\r\n // Set max age to expire now\r\n values[\"max-age\"] = \"0\";\r\n }\r\n // let delCookie = cookieMgrConfig.delCookie || _setCookieValue;\r\n _delCookieFn(name, _formatCookieValue(STR_EMPTY, values));\r\n result = true;\r\n }\r\n return result;\r\n }\r\n },\r\n _a[_DYN_UNLOAD /* @min:unload */] = function (isAsync) {\r\n unloadHandler && unloadHandler.rm();\r\n unloadHandler = null;\r\n },\r\n _a);\r\n // Associated this cookie manager with the config\r\n cookieMgr[strConfigCookieMgr] = cookieMgr;\r\n return cookieMgr;\r\n}\r\n/*\r\n* Helper method to tell if document.cookie object is supported by the runtime\r\n*/\r\nexport function areCookiesSupported(logger) {\r\n if (_supportsCookies === null) {\r\n _supportsCookies = false;\r\n !_doc && _getDoc();\r\n try {\r\n var doc = _doc.v || {};\r\n _supportsCookies = doc[strCookie] !== undefined;\r\n }\r\n catch (e) {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 68 /* _eInternalMessageId.CannotAccessCookie */, \"Cannot access document.cookie - \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n return _supportsCookies;\r\n}\r\nfunction _extractParts(theValue) {\r\n var values = {};\r\n if (theValue && theValue[_DYN_LENGTH /* @min:%2elength */]) {\r\n var parts = strTrim(theValue)[_DYN_SPLIT /* @min:%2esplit */](\";\");\r\n arrForEach(parts, function (thePart) {\r\n thePart = strTrim(thePart || STR_EMPTY);\r\n if (thePart) {\r\n var idx = strIndexOf(thePart, \"=\");\r\n if (idx === -1) {\r\n values[thePart] = null;\r\n }\r\n else {\r\n values[strTrim(strLeft(thePart, idx))] = strTrim(strSubstring(thePart, idx + 1));\r\n }\r\n }\r\n });\r\n }\r\n return values;\r\n}\r\nfunction _formatDate(theDate, func) {\r\n if (isFunction(theDate[func])) {\r\n return theDate[func]();\r\n }\r\n return null;\r\n}\r\nfunction _formatCookieValue(value, values) {\r\n var cookieValue = value || STR_EMPTY;\r\n objForEachKey(values, function (name, theValue) {\r\n cookieValue += \"; \" + name + (!isNullOrUndefined(theValue) ? \"=\" + theValue : STR_EMPTY);\r\n });\r\n return cookieValue;\r\n}\r\nfunction _getCookieValue(name) {\r\n var cookieValue = STR_EMPTY;\r\n !_doc && _getDoc();\r\n if (_doc.v) {\r\n var theCookie = _doc.v[strCookie] || STR_EMPTY;\r\n if (_parsedCookieValue !== theCookie) {\r\n _cookieCache = _extractParts(theCookie);\r\n _parsedCookieValue = theCookie;\r\n }\r\n cookieValue = strTrim(_cookieCache[name] || STR_EMPTY);\r\n }\r\n return cookieValue;\r\n}\r\nfunction _setCookieValue(name, cookieValue) {\r\n !_doc && _getDoc();\r\n if (_doc.v) {\r\n _doc.v[strCookie] = name + \"=\" + cookieValue;\r\n }\r\n}\r\nexport function uaDisallowsSameSiteNone(userAgent) {\r\n if (!isString(userAgent)) {\r\n return false;\r\n }\r\n // Cover all iOS based browsers here. This includes:\r\n // - Safari on iOS 12 for iPhone, iPod Touch, iPad\r\n // - WkWebview on iOS 12 for iPhone, iPod Touch, iPad\r\n // - Chrome on iOS 12 for iPhone, iPod Touch, iPad\r\n // All of which are broken by SameSite=None, because they use the iOS networking stack\r\n if (strContains(userAgent, \"CPU iPhone OS 12\") || strContains(userAgent, \"iPad; CPU OS 12\")) {\r\n return true;\r\n }\r\n // Cover Mac OS X based browsers that use the Mac OS networking stack. This includes:\r\n // - Safari on Mac OS X\r\n // This does not include:\r\n // - Internal browser on Mac OS X\r\n // - Chrome on Mac OS X\r\n // - Chromium on Mac OS X\r\n // Because they do not use the Mac OS networking stack.\r\n if (strContains(userAgent, \"Macintosh; Intel Mac OS X 10_14\") && strContains(userAgent, \"Version/\") && strContains(userAgent, \"Safari\")) {\r\n return true;\r\n }\r\n // Cover Mac OS X internal browsers that use the Mac OS networking stack. This includes:\r\n // - Internal browser on Mac OS X\r\n // This does not include:\r\n // - Safari on Mac OS X\r\n // - Chrome on Mac OS X\r\n // - Chromium on Mac OS X\r\n // Because they do not use the Mac OS networking stack.\r\n if (strContains(userAgent, \"Macintosh; Intel Mac OS X 10_14\") && strEndsWith(userAgent, \"AppleWebKit/605.1.15 (KHTML, like Gecko)\")) {\r\n return true;\r\n }\r\n // Cover Chrome 50-69, because some versions are broken by SameSite=None, and none in this range require it.\r\n // Note: this covers some pre-Chromium Edge versions, but pre-Chromim Edge does not require SameSite=None, so this is fine.\r\n // Note: this regex applies to Windows, Mac OS X, and Linux, deliberately.\r\n if (strContains(userAgent, \"Chrome/5\") || strContains(userAgent, \"Chrome/6\")) {\r\n return true;\r\n }\r\n // Unreal Engine runs Chromium 59, but does not advertise as Chrome until 4.23. Treat versions of Unreal\r\n // that don't specify their Chrome version as lacking support for SameSite=None.\r\n if (strContains(userAgent, \"UnrealEngine\") && !strContains(userAgent, \"Chrome\")) {\r\n return true;\r\n }\r\n // UCBrowser < 12.13.2 ignores Set-Cookie headers with SameSite=None\r\n // NB: this rule isn't complete - you need regex to make a complete rule.\r\n // See: https://www.chromium.org/updates/same-site/incompatible-clients\r\n if (strContains(userAgent, \"UCBrowser/12\") || strContains(userAgent, \"UCBrowser/11\")) {\r\n return true;\r\n }\r\n return false;\r\n}\r\n//# sourceMappingURL=CookieMgr.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { isArray, isFunction, objDefine, utcNow } from \"@nevware21/ts-utils\";\r\nimport { _DYN_COMPLETE, _DYN_GET_CTX, _DYN_IS_ASYNC, _DYN_IS_CHILD_EVT, _DYN_LENGTH, _DYN_NAME, _DYN_PUSH, _DYN_SET_CTX, _DYN_TIME } from \"../__DynamicConstants\";\r\nimport { STR_GET_PERF_MGR, STR_PERF_EVENT } from \"./InternalConstants\";\r\nvar strExecutionContextKey = \"ctx\";\r\nvar strParentContextKey = \"ParentContextKey\";\r\nvar strChildrenContextKey = \"ChildrenContextKey\";\r\nvar _defaultPerfManager = null;\r\nvar PerfEvent = /** @class */ (function () {\r\n function PerfEvent(name, payloadDetails, isAsync) {\r\n var _self = this;\r\n _self.start = utcNow();\r\n _self[_DYN_NAME /* @min:%2ename */] = name;\r\n _self[_DYN_IS_ASYNC /* @min:%2eisAsync */] = isAsync;\r\n _self[_DYN_IS_CHILD_EVT /* @min:%2eisChildEvt */] = function () { return false; };\r\n if (isFunction(payloadDetails)) {\r\n // Create an accessor to minimize the potential performance impact of executing the payloadDetails callback\r\n var theDetails_1;\r\n objDefine(_self, \"payload\", {\r\n g: function () {\r\n // Delay the execution of the payloadDetails until needed\r\n if (!theDetails_1 && isFunction(payloadDetails)) {\r\n theDetails_1 = payloadDetails();\r\n // clear it out now so the referenced objects can be garbage collected\r\n payloadDetails = null;\r\n }\r\n return theDetails_1;\r\n }\r\n });\r\n }\r\n _self[_DYN_GET_CTX /* @min:%2egetCtx */] = function (key) {\r\n if (key) {\r\n // The parent and child links are located directly on the object (for better viewing in the DebugPlugin)\r\n if (key === PerfEvent[strParentContextKey] || key === PerfEvent[strChildrenContextKey]) {\r\n return _self[key];\r\n }\r\n return (_self[strExecutionContextKey] || {})[key];\r\n }\r\n return null;\r\n };\r\n _self[_DYN_SET_CTX /* @min:%2esetCtx */] = function (key, value) {\r\n if (key) {\r\n // Put the parent and child links directly on the object (for better viewing in the DebugPlugin)\r\n if (key === PerfEvent[strParentContextKey]) {\r\n // Simple assumption, if we are setting a parent then we must be a child\r\n if (!_self[key]) {\r\n _self[_DYN_IS_CHILD_EVT /* @min:%2eisChildEvt */] = function () { return true; };\r\n }\r\n _self[key] = value;\r\n }\r\n else if (key === PerfEvent[strChildrenContextKey]) {\r\n _self[key] = value;\r\n }\r\n else {\r\n var ctx = _self[strExecutionContextKey] = _self[strExecutionContextKey] || {};\r\n ctx[key] = value;\r\n }\r\n }\r\n };\r\n _self[_DYN_COMPLETE /* @min:%2ecomplete */] = function () {\r\n var childTime = 0;\r\n var childEvts = _self[_DYN_GET_CTX /* @min:%2egetCtx */](PerfEvent[strChildrenContextKey]);\r\n if (isArray(childEvts)) {\r\n for (var lp = 0; lp < childEvts[_DYN_LENGTH /* @min:%2elength */]; lp++) {\r\n var childEvt = childEvts[lp];\r\n if (childEvt) {\r\n childTime += childEvt[_DYN_TIME /* @min:%2etime */];\r\n }\r\n }\r\n }\r\n _self[_DYN_TIME /* @min:%2etime */] = utcNow() - _self.start;\r\n _self.exTime = _self[_DYN_TIME /* @min:%2etime */] - childTime;\r\n _self[_DYN_COMPLETE /* @min:%2ecomplete */] = function () { };\r\n };\r\n }\r\n PerfEvent.ParentContextKey = \"parent\";\r\n PerfEvent.ChildrenContextKey = \"childEvts\";\r\n return PerfEvent;\r\n}());\r\nexport { PerfEvent };\r\nvar PerfManager = /** @class */ (function () {\r\n function PerfManager(manager) {\r\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 */\r\n this.ctx = {};\r\n dynamicProto(PerfManager, this, function (_self) {\r\n _self.create = function (src, payloadDetails, isAsync) {\r\n // TODO (@MSNev): at some point we will want to add additional configuration to \"select\" which events to instrument\r\n // for now this is just a simple do everything.\r\n return new PerfEvent(src, payloadDetails, isAsync);\r\n };\r\n _self.fire = function (perfEvent) {\r\n if (perfEvent) {\r\n perfEvent[_DYN_COMPLETE /* @min:%2ecomplete */]();\r\n if (manager && isFunction(manager[STR_PERF_EVENT /* @min:%2eperfEvent */])) {\r\n manager[STR_PERF_EVENT /* @min:%2eperfEvent */](perfEvent);\r\n }\r\n }\r\n };\r\n _self[_DYN_SET_CTX /* @min:%2esetCtx */] = function (key, value) {\r\n if (key) {\r\n var ctx = _self[strExecutionContextKey] = _self[strExecutionContextKey] || {};\r\n ctx[key] = value;\r\n }\r\n };\r\n _self[_DYN_GET_CTX /* @min:%2egetCtx */] = function (key) {\r\n return (_self[strExecutionContextKey] || {})[key];\r\n };\r\n });\r\n }\r\n /**\r\n * Create a new event and start timing, the manager may return null/undefined to indicate that it does not\r\n * want to monitor this source event.\r\n * @param src - The source name of the event\r\n * @param payloadDetails - An optional callback function to fetch the payload details for the event.\r\n * @param isAsync - Is the event occurring from a async event\r\n */\r\n PerfManager.prototype.create = function (src, payload, isAsync) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Complete the perfEvent and fire any notifications.\r\n * @param perfEvent - Fire the event which will also complete the passed event\r\n */\r\n PerfManager.prototype.fire = function (perfEvent) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Set an execution context value\r\n * @param key - The context key name\r\n * @param value - The value\r\n */\r\n PerfManager.prototype.setCtx = function (key, value) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Get the execution context value\r\n * @param key - The context key\r\n */\r\n PerfManager.prototype.getCtx = function (key) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n return PerfManager;\r\n}());\r\nexport { PerfManager };\r\nvar doPerfActiveKey = \"CoreUtils.doPerf\";\r\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 */\r\nexport function doPerf(mgrSource, getSource, func, details, isAsync) {\r\n if (mgrSource) {\r\n var perfMgr = mgrSource;\r\n if (perfMgr[STR_GET_PERF_MGR]) {\r\n // Looks like a perf manager provider object\r\n perfMgr = perfMgr[STR_GET_PERF_MGR]();\r\n }\r\n if (perfMgr) {\r\n var perfEvt = void 0;\r\n var currentActive = perfMgr[_DYN_GET_CTX /* @min:%2egetCtx */](doPerfActiveKey);\r\n try {\r\n perfEvt = perfMgr.create(getSource(), details, isAsync);\r\n if (perfEvt) {\r\n if (currentActive && perfEvt[_DYN_SET_CTX /* @min:%2esetCtx */]) {\r\n perfEvt[_DYN_SET_CTX /* @min:%2esetCtx */](PerfEvent[strParentContextKey], currentActive);\r\n if (currentActive[_DYN_GET_CTX /* @min:%2egetCtx */] && currentActive[_DYN_SET_CTX /* @min:%2esetCtx */]) {\r\n var children = currentActive[_DYN_GET_CTX /* @min:%2egetCtx */](PerfEvent[strChildrenContextKey]);\r\n if (!children) {\r\n children = [];\r\n currentActive[_DYN_SET_CTX /* @min:%2esetCtx */](PerfEvent[strChildrenContextKey], children);\r\n }\r\n children[_DYN_PUSH /* @min:%2epush */](perfEvt);\r\n }\r\n }\r\n // Set this event as the active event now\r\n perfMgr[_DYN_SET_CTX /* @min:%2esetCtx */](doPerfActiveKey, perfEvt);\r\n return func(perfEvt);\r\n }\r\n }\r\n catch (ex) {\r\n if (perfEvt && perfEvt[_DYN_SET_CTX /* @min:%2esetCtx */]) {\r\n perfEvt[_DYN_SET_CTX /* @min:%2esetCtx */](\"exception\", ex);\r\n }\r\n }\r\n finally {\r\n // fire the perf event\r\n if (perfEvt) {\r\n perfMgr.fire(perfEvt);\r\n }\r\n // Reset the active event to the previous value\r\n perfMgr[_DYN_SET_CTX /* @min:%2esetCtx */](doPerfActiveKey, currentActive);\r\n }\r\n }\r\n }\r\n return func();\r\n}\r\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 */\r\nexport function setGblPerfMgr(perfManager) {\r\n _defaultPerfManager = perfManager;\r\n}\r\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 */\r\nexport function getGblPerfMgr() {\r\n return _defaultPerfManager;\r\n}\r\n//# sourceMappingURL=PerfManager.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\"use strict\";\r\nimport { strShimUndefined } from \"@microsoft/applicationinsights-shims\";\r\nimport { strSubstr, strSubstring } from \"@nevware21/ts-utils\";\r\nimport { _DYN_LENGTH } from \"../__DynamicConstants\";\r\nimport { STR_EMPTY } from \"./InternalConstants\";\r\nimport { random32 } from \"./RandomHelper\";\r\n// Added to help with minfication\r\nexport var Undefined = strShimUndefined;\r\nexport function newGuid() {\r\n var uuid = generateW3CId();\r\n return strSubstring(uuid, 0, 8) + \"-\" + strSubstring(uuid, 8, 12) + \"-\" + strSubstring(uuid, 12, 16) + \"-\" + strSubstring(uuid, 16, 20) + \"-\" + strSubstring(uuid, 20);\r\n}\r\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 */\r\nexport function strEndsWith(value, search) {\r\n if (value && search) {\r\n var len = value[_DYN_LENGTH /* @min:%2elength */];\r\n var start = len - search[_DYN_LENGTH /* @min:%2elength */];\r\n return strSubstring(value, start >= 0 ? start : 0, len) === search;\r\n }\r\n return false;\r\n}\r\n/**\r\n * generate W3C trace id\r\n */\r\nexport function generateW3CId() {\r\n var hexValues = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\"];\r\n // rfc4122 version 4 UUID without dashes and with lowercase letters\r\n var oct = STR_EMPTY, tmp;\r\n for (var a = 0; a < 4; a++) {\r\n tmp = random32();\r\n oct +=\r\n hexValues[tmp & 0xF] +\r\n hexValues[tmp >> 4 & 0xF] +\r\n hexValues[tmp >> 8 & 0xF] +\r\n hexValues[tmp >> 12 & 0xF] +\r\n hexValues[tmp >> 16 & 0xF] +\r\n hexValues[tmp >> 20 & 0xF] +\r\n hexValues[tmp >> 24 & 0xF] +\r\n hexValues[tmp >> 28 & 0xF];\r\n }\r\n // \"Set the two most significant bits (bits 6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively\"\r\n var clockSequenceHi = hexValues[8 + (random32() & 0x03) | 0];\r\n return strSubstr(oct, 0, 8) + strSubstr(oct, 9, 4) + \"4\" + strSubstr(oct, 13, 3) + clockSequenceHi + strSubstr(oct, 16, 3) + strSubstr(oct, 19, 12);\r\n}\r\n//# sourceMappingURL=CoreUtils.js.map","import { isArray, isString, strLeft, strTrim } from \"@nevware21/ts-utils\";\r\nimport { _DYN_LENGTH, _DYN_SPAN_ID, _DYN_TO_LOWER_CASE, _DYN_TRACE_FLAGS, _DYN_TRACE_ID, _DYN_VERSION } from \"../__DynamicConstants\";\r\nimport { generateW3CId } from \"./CoreUtils\";\r\nimport { findMetaTag, findNamedServerTiming } from \"./EnvUtils\";\r\nimport { STR_EMPTY } from \"./InternalConstants\";\r\n// using {0,16} for leading and trailing whitespace just to constrain the possible runtime of a random string\r\nvar TRACE_PARENT_REGEX = /^([\\da-f]{2})-([\\da-f]{32})-([\\da-f]{16})-([\\da-f]{2})(-[^\\s]{1,64})?$/i;\r\nvar DEFAULT_VERSION = \"00\";\r\nvar INVALID_VERSION = \"ff\";\r\nvar INVALID_TRACE_ID = \"00000000000000000000000000000000\";\r\nvar INVALID_SPAN_ID = \"0000000000000000\";\r\nvar SAMPLED_FLAG = 0x01;\r\nfunction _isValid(value, len, invalidValue) {\r\n if (value && value[_DYN_LENGTH /* @min:%2elength */] === len && value !== invalidValue) {\r\n return !!value.match(/^[\\da-f]*$/i);\r\n }\r\n return false;\r\n}\r\nfunction _formatValue(value, len, defValue) {\r\n if (_isValid(value, len)) {\r\n return value;\r\n }\r\n return defValue;\r\n}\r\nfunction _formatFlags(value) {\r\n if (isNaN(value) || value < 0 || value > 255) {\r\n value = 0x01;\r\n }\r\n var result = value.toString(16);\r\n while (result[_DYN_LENGTH /* @min:%2elength */] < 2) {\r\n result = \"0\" + result;\r\n }\r\n return result;\r\n}\r\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 */\r\nexport function createTraceParent(traceId, spanId, flags, version) {\r\n var _a;\r\n return _a = {},\r\n _a[_DYN_VERSION /* @min:version */] = _isValid(version, 2, INVALID_VERSION) ? version : DEFAULT_VERSION,\r\n _a[_DYN_TRACE_ID /* @min:traceId */] = isValidTraceId(traceId) ? traceId : generateW3CId(),\r\n _a[_DYN_SPAN_ID /* @min:spanId */] = isValidSpanId(spanId) ? spanId : strLeft(generateW3CId(), 16),\r\n _a.traceFlags = flags >= 0 && flags <= 0xFF ? flags : 1,\r\n _a;\r\n}\r\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\r\n * @returns\r\n */\r\nexport function parseTraceParent(value) {\r\n var _a;\r\n if (!value) {\r\n // Don't pass a null/undefined or empty string\r\n return null;\r\n }\r\n if (isArray(value)) {\r\n // The value may have been encoded on the page into an array so handle this automatically\r\n value = value[0] || \"\";\r\n }\r\n if (!value || !isString(value) || value[_DYN_LENGTH /* @min:%2elength */] > 8192) {\r\n // limit potential processing based on total length\r\n return null;\r\n }\r\n // See https://www.w3.org/TR/trace-context/#versioning-of-traceparent\r\n var match = TRACE_PARENT_REGEX.exec(strTrim(value));\r\n if (!match || // No match\r\n match[1] === INVALID_VERSION || // version ff is forbidden\r\n match[2] === INVALID_TRACE_ID || // All zeros is considered to be invalid\r\n match[3] === INVALID_SPAN_ID) { // All zeros is considered to be invalid\r\n return null;\r\n }\r\n return _a = {\r\n version: (match[1] || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */](),\r\n traceId: (match[2] || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */](),\r\n spanId: (match[3] || STR_EMPTY)[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]()\r\n },\r\n _a[_DYN_TRACE_FLAGS /* @min:traceFlags */] = parseInt(match[4], 16),\r\n _a;\r\n}\r\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 */\r\nexport function isValidTraceId(value) {\r\n return _isValid(value, 32, INVALID_TRACE_ID);\r\n}\r\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 */\r\nexport function isValidSpanId(value) {\r\n return _isValid(value, 16, INVALID_SPAN_ID);\r\n}\r\n/**\r\n * Validates that the provided ITraceParent instance conforms to the currently supported specifications\r\n * @param value\r\n * @returns\r\n */\r\nexport function isValidTraceParent(value) {\r\n if (!value ||\r\n !_isValid(value[_DYN_VERSION /* @min:%2eversion */], 2, INVALID_VERSION) ||\r\n !_isValid(value[_DYN_TRACE_ID /* @min:%2etraceId */], 32, INVALID_TRACE_ID) ||\r\n !_isValid(value[_DYN_SPAN_ID /* @min:%2espanId */], 16, INVALID_SPAN_ID) ||\r\n !_isValid(_formatFlags(value[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */]), 2)) {\r\n // Each known field must contain a valid value\r\n return false;\r\n }\r\n return true;\r\n}\r\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 */\r\nexport function isSampledFlag(value) {\r\n if (isValidTraceParent(value)) {\r\n return (value[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] & SAMPLED_FLAG) === SAMPLED_FLAG;\r\n }\r\n return false;\r\n}\r\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 */\r\nexport function formatTraceParent(value) {\r\n if (value) {\r\n // Special Note: This only supports formatting as version 00, future versions should encode any known supported version\r\n // So parsing a future version will populate the correct version value but reformatting will reduce it to version 00.\r\n var flags = _formatFlags(value[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */]);\r\n if (!_isValid(flags, 2)) {\r\n flags = \"01\";\r\n }\r\n var version = value[_DYN_VERSION /* @min:%2eversion */] || DEFAULT_VERSION;\r\n if (version !== \"00\" && version !== \"ff\") {\r\n // Reduce version to \"00\"\r\n version = DEFAULT_VERSION;\r\n }\r\n // Format as version 00\r\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());\r\n }\r\n return \"\";\r\n}\r\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 * @returns\r\n */\r\nexport function findW3cTraceParent() {\r\n var name = \"traceparent\";\r\n var traceParent = parseTraceParent(findMetaTag(name));\r\n if (!traceParent) {\r\n traceParent = parseTraceParent(findNamedServerTiming(name));\r\n }\r\n return traceParent;\r\n}\r\n//# sourceMappingURL=W3cTraceParent.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\"use strict\";\r\nimport { arrForEach, isFunction } from \"@nevware21/ts-utils\";\r\nimport { _DYN_GET_NEXT, _DYN_GET_PLUGIN, _DYN_INITIALIZE, _DYN_IS_INITIALIZED, _DYN_LENGTH, _DYN_NAME, _DYN_PUSH, _DYN_SET_NEXT_PLUGIN, _DYN_SPAN_ID, _DYN_TEARDOWN, _DYN_TRACE_FLAGS, _DYN_TRACE_ID, _DYN__DO_TEARDOWN } from \"../__DynamicConstants\";\r\nimport { createElmNodeData } from \"./DataCacheHelper\";\r\nimport { STR_CORE, STR_PRIORITY, STR_PROCESS_TELEMETRY } from \"./InternalConstants\";\r\nimport { isValidSpanId, isValidTraceId } from \"./W3cTraceParent\";\r\nvar pluginStateData = createElmNodeData(\"plugin\");\r\nexport function _getPluginState(plugin) {\r\n return pluginStateData.get(plugin, \"state\", {}, true);\r\n}\r\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 */\r\nexport function initializePlugins(processContext, extensions) {\r\n // Set the next plugin and identified the uninitialized plugins\r\n var initPlugins = [];\r\n var lastPlugin = null;\r\n var proxy = processContext[_DYN_GET_NEXT /* @min:%2egetNext */]();\r\n var pluginState;\r\n while (proxy) {\r\n var thePlugin = proxy[_DYN_GET_PLUGIN /* @min:%2egetPlugin */]();\r\n if (thePlugin) {\r\n if (lastPlugin && lastPlugin[_DYN_SET_NEXT_PLUGIN /* @min:%2esetNextPlugin */] && thePlugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */]) {\r\n // Set this plugin as the next for the previous one\r\n lastPlugin[_DYN_SET_NEXT_PLUGIN /* @min:%2esetNextPlugin */](thePlugin);\r\n }\r\n pluginState = _getPluginState(thePlugin);\r\n var isInitialized = !!pluginState[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */];\r\n if (thePlugin[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */]) {\r\n isInitialized = thePlugin[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */]();\r\n }\r\n if (!isInitialized) {\r\n initPlugins[_DYN_PUSH /* @min:%2epush */](thePlugin);\r\n }\r\n lastPlugin = thePlugin;\r\n proxy = proxy[_DYN_GET_NEXT /* @min:%2egetNext */]();\r\n }\r\n }\r\n // Now initialize the plugins\r\n arrForEach(initPlugins, function (thePlugin) {\r\n var core = processContext[STR_CORE /* @min:%2ecore */]();\r\n thePlugin[_DYN_INITIALIZE /* @min:%2einitialize */](processContext.getCfg(), core, extensions, processContext[_DYN_GET_NEXT /* @min:%2egetNext */]());\r\n pluginState = _getPluginState(thePlugin);\r\n // Only add the core to the state if the plugin didn't set it (doesn't extend from BaseTelemetryPlugin)\r\n if (!thePlugin[STR_CORE] && !pluginState[STR_CORE]) {\r\n pluginState[STR_CORE] = core;\r\n }\r\n pluginState[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */] = true;\r\n delete pluginState[_DYN_TEARDOWN /* @min:%2eteardown */];\r\n });\r\n}\r\nexport function sortPlugins(plugins) {\r\n // Sort by priority\r\n return plugins.sort(function (extA, extB) {\r\n var result = 0;\r\n if (extB) {\r\n var bHasProcess = extB[STR_PROCESS_TELEMETRY];\r\n if (extA[STR_PROCESS_TELEMETRY]) {\r\n result = bHasProcess ? extA[STR_PRIORITY] - extB[STR_PRIORITY] : 1;\r\n }\r\n else if (bHasProcess) {\r\n result = -1;\r\n }\r\n }\r\n else {\r\n result = extA ? 1 : -1;\r\n }\r\n return result;\r\n });\r\n // sort complete\r\n}\r\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 */\r\nexport function unloadComponents(components, unloadCtx, unloadState, asyncCallback) {\r\n var idx = 0;\r\n function _doUnload() {\r\n while (idx < components[_DYN_LENGTH /* @min:%2elength */]) {\r\n var component = components[idx++];\r\n if (component) {\r\n var func = component._doUnload || component[_DYN__DO_TEARDOWN /* @min:%2e_doTeardown */];\r\n if (isFunction(func)) {\r\n if (func.call(component, unloadCtx, unloadState, _doUnload) === true) {\r\n return true;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return _doUnload();\r\n}\r\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 */\r\nexport function createDistributedTraceContext(parentCtx) {\r\n var trace = {};\r\n return {\r\n getName: function () {\r\n return trace[_DYN_NAME /* @min:%2ename */];\r\n },\r\n setName: function (newValue) {\r\n parentCtx && parentCtx.setName(newValue);\r\n trace[_DYN_NAME /* @min:%2ename */] = newValue;\r\n },\r\n getTraceId: function () {\r\n return trace[_DYN_TRACE_ID /* @min:%2etraceId */];\r\n },\r\n setTraceId: function (newValue) {\r\n parentCtx && parentCtx.setTraceId(newValue);\r\n if (isValidTraceId(newValue)) {\r\n trace[_DYN_TRACE_ID /* @min:%2etraceId */] = newValue;\r\n }\r\n },\r\n getSpanId: function () {\r\n return trace[_DYN_SPAN_ID /* @min:%2espanId */];\r\n },\r\n setSpanId: function (newValue) {\r\n parentCtx && parentCtx.setSpanId(newValue);\r\n if (isValidSpanId(newValue)) {\r\n trace[_DYN_SPAN_ID /* @min:%2espanId */] = newValue;\r\n }\r\n },\r\n getTraceFlags: function () {\r\n return trace[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */];\r\n },\r\n setTraceFlags: function (newTraceFlags) {\r\n parentCtx && parentCtx.setTraceFlags(newTraceFlags);\r\n trace[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = newTraceFlags;\r\n }\r\n };\r\n}\r\n//# sourceMappingURL=TelemetryHelpers.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\"use strict\";\r\nimport { arrForEach, dumpObj, isArray, isFunction, isNullOrUndefined, isUndefined, objForEachKey, objFreeze, objKeys } from \"@nevware21/ts-utils\";\r\nimport { _applyDefaultValue } from \"../Config/ConfigDefaults\";\r\nimport { createDynamicConfig } from \"../Config/DynamicConfig\";\r\nimport { _DYN_CREATE_NEW, _DYN_DIAG_LOG, _DYN_GET_NEXT, _DYN_GET_PLUGIN, _DYN_IDENTIFIER, _DYN_IS_ASYNC, _DYN_IS_INITIALIZED, _DYN_LENGTH, _DYN_LOGGER, _DYN_PROCESS_NEXT, _DYN_PUSH, _DYN_SET_DF, _DYN_SET_NEXT_PLUGIN, _DYN_TEARDOWN, _DYN_UNLOAD, _DYN_UPDATE } from \"../__DynamicConstants\";\r\nimport { _throwInternal, safeGetLogger } from \"./DiagnosticLogger\";\r\nimport { proxyFunctions } from \"./HelperFuncs\";\r\nimport { STR_CORE, STR_DISABLED, STR_EMPTY, STR_EXTENSION_CONFIG, STR_PRIORITY, STR_PROCESS_TELEMETRY } from \"./InternalConstants\";\r\nimport { doPerf } from \"./PerfManager\";\r\nimport { _getPluginState } from \"./TelemetryHelpers\";\r\nvar strTelemetryPluginChain = \"TelemetryPluginChain\";\r\nvar strHasRunFlags = \"_hasRun\";\r\nvar strGetTelCtx = \"_getTelCtx\";\r\nvar _chainId = 0;\r\nfunction _getNextProxyStart(proxy, core, startAt) {\r\n while (proxy) {\r\n if (proxy[_DYN_GET_PLUGIN /* @min:%2egetPlugin */]() === startAt) {\r\n return proxy;\r\n }\r\n proxy = proxy[_DYN_GET_NEXT /* @min:%2egetNext */]();\r\n }\r\n // This wasn't found in the existing chain so create an isolated one with just this plugin\r\n return createTelemetryProxyChain([startAt], core.config || {}, core);\r\n}\r\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 */\r\nfunction _createInternalContext(telemetryChain, dynamicHandler, core, startAt) {\r\n // We have a special case where we want to start execution from this specific plugin\r\n // or we simply reuse the existing telemetry plugin chain (normal execution case)\r\n var _nextProxy = null; // By Default set as no next plugin\r\n var _onComplete = [];\r\n if (!dynamicHandler) {\r\n dynamicHandler = createDynamicConfig({}, null, core[_DYN_LOGGER /* @min:%2elogger */]);\r\n }\r\n if (startAt !== null) {\r\n // There is no next element (null) vs not defined (undefined) so use the full chain\r\n _nextProxy = startAt ? _getNextProxyStart(telemetryChain, core, startAt) : telemetryChain;\r\n }\r\n var context = {\r\n _next: _moveNext,\r\n ctx: {\r\n core: function () {\r\n return core;\r\n },\r\n diagLog: function () {\r\n return safeGetLogger(core, dynamicHandler.cfg);\r\n },\r\n getCfg: function () {\r\n return dynamicHandler.cfg;\r\n },\r\n getExtCfg: _resolveExtCfg,\r\n getConfig: _getConfig,\r\n hasNext: function () {\r\n return !!_nextProxy;\r\n },\r\n getNext: function () {\r\n return _nextProxy;\r\n },\r\n setNext: function (nextPlugin) {\r\n _nextProxy = nextPlugin;\r\n },\r\n iterate: _iterateChain,\r\n onComplete: _addOnComplete\r\n }\r\n };\r\n function _addOnComplete(onComplete, that) {\r\n var args = [];\r\n for (var _i = 2; _i < arguments.length; _i++) {\r\n args[_i - 2] = arguments[_i];\r\n }\r\n if (onComplete) {\r\n _onComplete[_DYN_PUSH /* @min:%2epush */]({\r\n func: onComplete,\r\n self: !isUndefined(that) ? that : context.ctx,\r\n args: args\r\n });\r\n }\r\n }\r\n function _moveNext() {\r\n var nextProxy = _nextProxy;\r\n // Automatically move to the next plugin\r\n _nextProxy = nextProxy ? nextProxy[_DYN_GET_NEXT /* @min:%2egetNext */]() : null;\r\n if (!nextProxy) {\r\n var onComplete = _onComplete;\r\n if (onComplete && onComplete[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n arrForEach(onComplete, function (completeDetails) {\r\n try {\r\n completeDetails.func.call(completeDetails.self, completeDetails.args);\r\n }\r\n catch (e) {\r\n _throwInternal(core[_DYN_LOGGER /* @min:%2elogger */], 2 /* eLoggingSeverity.WARNING */, 73 /* _eInternalMessageId.PluginException */, \"Unexpected Exception during onComplete - \" + dumpObj(e));\r\n }\r\n });\r\n _onComplete = [];\r\n }\r\n }\r\n return nextProxy;\r\n }\r\n function _getExtCfg(identifier, createIfMissing) {\r\n var idCfg = null;\r\n var cfg = dynamicHandler.cfg;\r\n if (cfg && identifier) {\r\n var extCfg = cfg[STR_EXTENSION_CONFIG /* @min:%2eextensionConfig */];\r\n if (!extCfg && createIfMissing) {\r\n extCfg = {};\r\n }\r\n // Always set the value so that the property always exists\r\n cfg[STR_EXTENSION_CONFIG] = extCfg; // Note: it is valid for the \"value\" to be undefined\r\n // Calling `ref()` has a side effect of causing the referenced property to become dynamic (if not already)\r\n extCfg = dynamicHandler.ref(cfg, STR_EXTENSION_CONFIG);\r\n if (extCfg) {\r\n idCfg = extCfg[identifier];\r\n if (!idCfg && createIfMissing) {\r\n idCfg = {};\r\n }\r\n // Always set the value so that the property always exists\r\n extCfg[identifier] = idCfg; // Note: it is valid for the \"value\" to be undefined\r\n // Calling `ref()` has a side effect of causing the referenced property to become dynamic (if not already)\r\n idCfg = dynamicHandler.ref(extCfg, identifier);\r\n }\r\n }\r\n return idCfg;\r\n }\r\n function _resolveExtCfg(identifier, defaultValues) {\r\n var newConfig = _getExtCfg(identifier, true);\r\n if (defaultValues) {\r\n // Enumerate over the defaultValues and if not already populated attempt to\r\n // find a value from the root config or use the default value\r\n objForEachKey(defaultValues, function (field, defaultValue) {\r\n // for each unspecified field, set the default value\r\n if (isNullOrUndefined(newConfig[field])) {\r\n var cfgValue = dynamicHandler.cfg[field];\r\n if (cfgValue || !isNullOrUndefined(cfgValue)) {\r\n newConfig[field] = cfgValue;\r\n }\r\n }\r\n _applyDefaultValue(dynamicHandler, newConfig, field, defaultValue);\r\n });\r\n }\r\n return dynamicHandler[_DYN_SET_DF /* @min:%2esetDf */](newConfig, defaultValues);\r\n }\r\n function _getConfig(identifier, field, defaultValue) {\r\n if (defaultValue === void 0) { defaultValue = false; }\r\n var theValue;\r\n var extConfig = _getExtCfg(identifier, false);\r\n var rootConfig = dynamicHandler.cfg;\r\n if (extConfig && (extConfig[field] || !isNullOrUndefined(extConfig[field]))) {\r\n theValue = extConfig[field];\r\n }\r\n else if (rootConfig[field] || !isNullOrUndefined(rootConfig[field])) {\r\n theValue = rootConfig[field];\r\n }\r\n return (theValue || !isNullOrUndefined(theValue)) ? theValue : defaultValue;\r\n }\r\n function _iterateChain(cb) {\r\n // Keep processing until we reach the end of the chain\r\n var nextPlugin;\r\n while (!!(nextPlugin = context._next())) {\r\n var plugin = nextPlugin[_DYN_GET_PLUGIN /* @min:%2egetPlugin */]();\r\n if (plugin) {\r\n // callback with the current on\r\n cb(plugin);\r\n }\r\n }\r\n }\r\n return context;\r\n}\r\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 */\r\nexport function createProcessTelemetryContext(telemetryChain, cfg, core, startAt) {\r\n var config = createDynamicConfig(cfg);\r\n var internalContext = _createInternalContext(telemetryChain, config, core, startAt);\r\n var context = internalContext.ctx;\r\n function _processNext(env) {\r\n var nextPlugin = internalContext._next();\r\n if (nextPlugin) {\r\n // Run the next plugin which will call \"processNext()\"\r\n nextPlugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */](env, context);\r\n }\r\n return !nextPlugin;\r\n }\r\n function _createNew(plugins, startAt) {\r\n if (plugins === void 0) { plugins = null; }\r\n if (isArray(plugins)) {\r\n plugins = createTelemetryProxyChain(plugins, config.cfg, core, startAt);\r\n }\r\n return createProcessTelemetryContext(plugins || context[_DYN_GET_NEXT /* @min:%2egetNext */](), config.cfg, core, startAt);\r\n }\r\n context[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */] = _processNext;\r\n context[_DYN_CREATE_NEW /* @min:%2ecreateNew */] = _createNew;\r\n return context;\r\n}\r\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 */\r\nexport function createProcessTelemetryUnloadContext(telemetryChain, core, startAt) {\r\n var config = createDynamicConfig(core.config);\r\n var internalContext = _createInternalContext(telemetryChain, config, core, startAt);\r\n var context = internalContext.ctx;\r\n function _processNext(unloadState) {\r\n var nextPlugin = internalContext._next();\r\n nextPlugin && nextPlugin[_DYN_UNLOAD /* @min:%2eunload */](context, unloadState);\r\n return !nextPlugin;\r\n }\r\n function _createNew(plugins, startAt) {\r\n if (plugins === void 0) { plugins = null; }\r\n if (isArray(plugins)) {\r\n plugins = createTelemetryProxyChain(plugins, config.cfg, core, startAt);\r\n }\r\n return createProcessTelemetryUnloadContext(plugins || context[_DYN_GET_NEXT /* @min:%2egetNext */](), core, startAt);\r\n }\r\n context[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */] = _processNext;\r\n context[_DYN_CREATE_NEW /* @min:%2ecreateNew */] = _createNew;\r\n return context;\r\n}\r\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 */\r\nexport function createProcessTelemetryUpdateContext(telemetryChain, core, startAt) {\r\n var config = createDynamicConfig(core.config);\r\n var internalContext = _createInternalContext(telemetryChain, config, core, startAt);\r\n var context = internalContext.ctx;\r\n function _processNext(updateState) {\r\n return context.iterate(function (plugin) {\r\n if (isFunction(plugin[_DYN_UPDATE /* @min:%2eupdate */])) {\r\n plugin[_DYN_UPDATE /* @min:%2eupdate */](context, updateState);\r\n }\r\n });\r\n }\r\n function _createNew(plugins, startAt) {\r\n if (plugins === void 0) { plugins = null; }\r\n if (isArray(plugins)) {\r\n plugins = createTelemetryProxyChain(plugins, config.cfg, core, startAt);\r\n }\r\n return createProcessTelemetryUpdateContext(plugins || context[_DYN_GET_NEXT /* @min:%2egetNext */](), core, startAt);\r\n }\r\n context[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */] = _processNext;\r\n context[_DYN_CREATE_NEW /* @min:%2ecreateNew */] = _createNew;\r\n return context;\r\n}\r\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 */\r\nexport function createTelemetryProxyChain(plugins, config, core, startAt) {\r\n var firstProxy = null;\r\n var add = startAt ? false : true;\r\n if (isArray(plugins) && plugins[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n // Create the proxies and wire up the next plugin chain\r\n var lastProxy_1 = null;\r\n arrForEach(plugins, function (thePlugin) {\r\n if (!add && startAt === thePlugin) {\r\n add = true;\r\n }\r\n if (add && thePlugin && isFunction(thePlugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */])) {\r\n // Only add plugins that are processors\r\n var newProxy = createTelemetryPluginProxy(thePlugin, config, core);\r\n if (!firstProxy) {\r\n firstProxy = newProxy;\r\n }\r\n if (lastProxy_1) {\r\n // Set this new proxy as the next for the previous one\r\n lastProxy_1._setNext(newProxy);\r\n }\r\n lastProxy_1 = newProxy;\r\n }\r\n });\r\n }\r\n if (startAt && !firstProxy) {\r\n // Special case where the \"startAt\" was not in the original list of plugins\r\n return createTelemetryProxyChain([startAt], config, core);\r\n }\r\n return firstProxy;\r\n}\r\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 */\r\nexport function createTelemetryPluginProxy(plugin, config, core) {\r\n var nextProxy = null;\r\n var hasProcessTelemetry = isFunction(plugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */]);\r\n var hasSetNext = isFunction(plugin[_DYN_SET_NEXT_PLUGIN /* @min:%2esetNextPlugin */]);\r\n var chainId;\r\n if (plugin) {\r\n chainId = plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */] + \"-\" + plugin[STR_PRIORITY /* @min:%2epriority */] + \"-\" + _chainId++;\r\n }\r\n else {\r\n chainId = \"Unknown-0-\" + _chainId++;\r\n }\r\n var proxyChain = {\r\n getPlugin: function () {\r\n return plugin;\r\n },\r\n getNext: function () {\r\n return nextProxy;\r\n },\r\n processTelemetry: _processTelemetry,\r\n unload: _unloadPlugin,\r\n update: _updatePlugin,\r\n _id: chainId,\r\n _setNext: function (nextPlugin) {\r\n nextProxy = nextPlugin;\r\n }\r\n };\r\n function _getTelCtx() {\r\n var itemCtx;\r\n // Looks like a plugin didn't pass the (optional) context, so create a new one\r\n if (plugin && isFunction(plugin[strGetTelCtx])) {\r\n // This plugin extends from the BaseTelemetryPlugin so lets use it\r\n itemCtx = plugin[strGetTelCtx]();\r\n }\r\n if (!itemCtx) {\r\n // Create a temporary one\r\n itemCtx = createProcessTelemetryContext(proxyChain, config, core);\r\n }\r\n return itemCtx;\r\n }\r\n function _processChain(itemCtx, processPluginFn, name, details, isAsync) {\r\n var hasRun = false;\r\n var identifier = plugin ? plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */] : strTelemetryPluginChain;\r\n var hasRunContext = itemCtx[strHasRunFlags];\r\n if (!hasRunContext) {\r\n // Assign and populate\r\n hasRunContext = itemCtx[strHasRunFlags] = {};\r\n }\r\n // Ensure that we keep the context in sync\r\n itemCtx.setNext(nextProxy);\r\n if (plugin) {\r\n doPerf(itemCtx[STR_CORE /* @min:%2ecore */](), function () { return identifier + \":\" + name; }, function () {\r\n // Mark this component as having run\r\n hasRunContext[chainId] = true;\r\n try {\r\n // Set a flag on the next plugin so we know if it was attempted to be executed\r\n var nextId = nextProxy ? nextProxy._id : STR_EMPTY;\r\n if (nextId) {\r\n hasRunContext[nextId] = false;\r\n }\r\n hasRun = processPluginFn(itemCtx);\r\n }\r\n catch (error) {\r\n var hasNextRun = nextProxy ? hasRunContext[nextProxy._id] : true;\r\n if (hasNextRun) {\r\n // The next plugin after us has already run so set this one as complete\r\n hasRun = true;\r\n }\r\n if (!nextProxy || !hasNextRun) {\r\n // Either we have no next plugin or the current one did not attempt to call the next plugin\r\n // Which means the current one is the root of the failure so log/report this failure\r\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));\r\n }\r\n }\r\n }, details, isAsync);\r\n }\r\n return hasRun;\r\n }\r\n function _processTelemetry(env, itemCtx) {\r\n itemCtx = itemCtx || _getTelCtx();\r\n function _callProcessTelemetry(itemCtx) {\r\n if (!plugin || !hasProcessTelemetry) {\r\n return false;\r\n }\r\n var pluginState = _getPluginState(plugin);\r\n if (pluginState[_DYN_TEARDOWN /* @min:%2eteardown */] || pluginState[STR_DISABLED]) {\r\n return false;\r\n }\r\n // Ensure that we keep the context in sync (for processNext()), just in case a plugin\r\n // doesn't calls processTelemetry() instead of itemContext.processNext() or some\r\n // other form of error occurred\r\n if (hasSetNext) {\r\n // Backward compatibility setting the next plugin on the instance\r\n plugin[_DYN_SET_NEXT_PLUGIN /* @min:%2esetNextPlugin */](nextProxy);\r\n }\r\n plugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */](env, itemCtx);\r\n // Process Telemetry is expected to call itemCtx.processNext() or nextPlugin.processTelemetry()\r\n return true;\r\n }\r\n if (!_processChain(itemCtx, _callProcessTelemetry, \"processTelemetry\", function () { return ({ item: env }); }, !(env.sync))) {\r\n // The underlying plugin is either not defined, not enabled or does not have a processTelemetry implementation\r\n // so we still want the next plugin to be executed.\r\n itemCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](env);\r\n }\r\n }\r\n function _unloadPlugin(unloadCtx, unloadState) {\r\n function _callTeardown() {\r\n // Setting default of hasRun as false so the proxyProcessFn() is called as teardown() doesn't have to exist or call unloadNext().\r\n var hasRun = false;\r\n if (plugin) {\r\n var pluginState = _getPluginState(plugin);\r\n var pluginCore = plugin[STR_CORE] || pluginState[STR_CORE /* @min:%2ecore */];\r\n // Only teardown the plugin if it was initialized by the current core (i.e. It's not a shared plugin)\r\n if (plugin && (!pluginCore || pluginCore === unloadCtx.core()) && !pluginState[_DYN_TEARDOWN /* @min:%2eteardown */]) {\r\n // Handle plugins that don't extend from the BaseTelemetryPlugin\r\n pluginState[STR_CORE /* @min:%2ecore */] = null;\r\n pluginState[_DYN_TEARDOWN /* @min:%2eteardown */] = true;\r\n pluginState[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */] = false;\r\n if (plugin[_DYN_TEARDOWN /* @min:%2eteardown */] && plugin[_DYN_TEARDOWN /* @min:%2eteardown */](unloadCtx, unloadState) === true) {\r\n // plugin told us that it was going to (or has) call unloadCtx.processNext()\r\n hasRun = true;\r\n }\r\n }\r\n }\r\n return hasRun;\r\n }\r\n if (!_processChain(unloadCtx, _callTeardown, \"unload\", function () { }, unloadState[_DYN_IS_ASYNC /* @min:%2eisAsync */])) {\r\n // Only called if we hasRun was not true\r\n unloadCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](unloadState);\r\n }\r\n }\r\n function _updatePlugin(updateCtx, updateState) {\r\n function _callUpdate() {\r\n // Setting default of hasRun as false so the proxyProcessFn() is called as teardown() doesn't have to exist or call unloadNext().\r\n var hasRun = false;\r\n if (plugin) {\r\n var pluginState = _getPluginState(plugin);\r\n var pluginCore = plugin[STR_CORE] || pluginState[STR_CORE /* @min:%2ecore */];\r\n // Only update the plugin if it was initialized by the current core (i.e. It's not a shared plugin)\r\n if (plugin && (!pluginCore || pluginCore === updateCtx.core()) && !pluginState[_DYN_TEARDOWN /* @min:%2eteardown */]) {\r\n if (plugin[_DYN_UPDATE /* @min:%2eupdate */] && plugin[_DYN_UPDATE /* @min:%2eupdate */](updateCtx, updateState) === true) {\r\n // plugin told us that it was going to (or has) call unloadCtx.processNext()\r\n hasRun = true;\r\n }\r\n }\r\n }\r\n return hasRun;\r\n }\r\n if (!_processChain(updateCtx, _callUpdate, \"update\", function () { }, false)) {\r\n // Only called if we hasRun was not true\r\n updateCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](updateState);\r\n }\r\n }\r\n return objFreeze(proxyChain);\r\n}\r\n/**\r\n * This class will be removed!\r\n * @deprecated use createProcessTelemetryContext() instead\r\n */\r\nvar ProcessTelemetryContext = /** @class */ (function () {\r\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 */\r\n function ProcessTelemetryContext(pluginChain, config, core, startAt) {\r\n var _self = this;\r\n var context = createProcessTelemetryContext(pluginChain, config, core, startAt);\r\n // Proxy all functions of the context to this object\r\n proxyFunctions(_self, context, objKeys(context));\r\n }\r\n return ProcessTelemetryContext;\r\n}());\r\nexport { ProcessTelemetryContext };\r\n//# sourceMappingURL=ProcessTelemetryContext.js.map","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { ILazyValue, getLazy } from \"../helpers/lazy\";\r\nimport { DONE, VALUE } from \"../internal/constants\";\r\nimport { getKnownSymbol } from \"../symbol/symbol\";\r\nimport { WellKnownSymbols } from \"../symbol/well_known\";\r\nimport { isIterator } from \"./iterator\";\r\n\r\nlet _iterSymbol: ILazyValue;\r\n\r\n/**\r\n * Calls the provided `callbackFn` function once for each element in the iterator or iterator returned by\r\n * the iterable and processed in the same order as returned by the iterator. As with the {@link arrForEach}\r\n * you CAN stop / break the iteration by returning -1 from the`callbackFn` function.\r\n *\r\n * The order of processing is not reset if you add or remove elements to the iterator, the actual behavior\r\n * will depend on the iterator imeplementation.\r\n *\r\n * If the passed `iter` is both an Iterable and Iterator the Iterator interface takes preceedence.\r\n * @remarks\r\n * If Symbols are NOT supported then the iterable MUST be using the same polyFill for the well know symbols,\r\n * if you are targetting a mixed environment you SHOULD either\r\n * - only use the polyfill Symbol's provided by this library\r\n * - ensure that you add any symbol polyfills BEFORE these utilities\r\n * iterForOf expects a `synchronous` function.\r\n * iterForOf does not wait for promises. Make sure you are aware of the implications while using\r\n * promises (or async functions) as forEach callback.\r\n *\r\n * @since 0.4.2\r\n * @group Iterator\r\n * @typeParam T - Identifies the element type of the iterator\r\n * @param callbackfn A `synchronous` function that accepts up to three arguments. iterForOf calls the\r\n * callbackfn function one time for each element returned by the iterator.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is\r\n * omitted, null or undefined the iterator will be used as the this value.\r\n * @throws Any exception thrown while processing the iterator\r\n * @example\r\n * ```ts\r\n * const items = {\r\n * 'item1': 'value1',\r\n * 'item2': 'value2',\r\n * 'item3': 'value3\r\n * };\r\n * const copyItems = [];\r\n *\r\n * iterForOf(items, (item) => {\r\n * copyItems.push(item);\r\n * // May return -1 to abort the iteration\r\n * });\r\n * ```\r\n */\r\nexport function iterForOf(iter: Iterator | Iterable, callbackfn: (value: T, count?: number, iter?: Iterator) => void | number, thisArg?: any): void {\r\n if (iter) {\r\n if (!isIterator(iter)) {\r\n !_iterSymbol && (_iterSymbol = getLazy(() => getKnownSymbol(WellKnownSymbols.iterator)));\r\n iter = iter[_iterSymbol.v] ? iter[_iterSymbol.v]() : null;\r\n }\r\n \r\n if (isIterator(iter)) {\r\n let err: { e: any };\r\n let iterResult: IteratorResult;\r\n try {\r\n let count = 0;\r\n while(!(iterResult = iter.next())[DONE]) {\r\n if (callbackfn.call(thisArg || iter, iterResult[VALUE], count, iter) === -1) {\r\n break;\r\n }\r\n \r\n count++;\r\n }\r\n } catch (failed) {\r\n err = { e: failed };\r\n if (iter.throw) {\r\n iterResult = null;\r\n iter.throw(err);\r\n }\r\n } finally {\r\n try {\r\n if (iterResult && !iterResult[DONE]) {\r\n iter.return && iter.return(iterResult);\r\n }\r\n } finally {\r\n if (err) {\r\n // eslint-disable-next-line no-unsafe-finally\r\n throw err.e;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\"use strict\";\r\nvar _a;\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { isFunction, objDefine } from \"@nevware21/ts-utils\";\r\nimport { createDynamicConfig } from \"../Config/DynamicConfig\";\r\nimport { _DYN_CREATE_NEW, _DYN_DIAG_LOG, _DYN_GET_NEXT, _DYN_GET_PROCESS_TEL_CONT0, _DYN_INITIALIZE, _DYN_IS_ASYNC, _DYN_IS_INITIALIZED, _DYN_PROCESS_NEXT, _DYN_SET_NEXT_PLUGIN, _DYN_TEARDOWN, _DYN_UPDATE, _DYN__DO_TEARDOWN } from \"../__DynamicConstants\";\r\nimport { safeGetLogger } from \"./DiagnosticLogger\";\r\nimport { isNotNullOrUndefined, proxyFunctionAs } from \"./HelperFuncs\";\r\nimport { STR_CORE, STR_EXTENSION_CONFIG, STR_PROCESS_TELEMETRY } from \"./InternalConstants\";\r\nimport { createProcessTelemetryContext, createProcessTelemetryUnloadContext, createProcessTelemetryUpdateContext } from \"./ProcessTelemetryContext\";\r\nimport { createUnloadHandlerContainer } from \"./UnloadHandlerContainer\";\r\nimport { createUnloadHookContainer } from \"./UnloadHookContainer\";\r\nvar strGetPlugin = \"getPlugin\";\r\nvar defaultValues = (_a = {},\r\n _a[STR_EXTENSION_CONFIG] = { isVal: isNotNullOrUndefined, v: {} },\r\n _a);\r\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 */\r\nvar BaseTelemetryPlugin = /** @class */ (function () {\r\n function BaseTelemetryPlugin() {\r\n var _self = this; // Setting _self here as it's used outside of the dynamicProto as well\r\n // NOTE!: DON'T set default values here, instead set them in the _initDefaults() function as it is also called during teardown()\r\n var _isinitialized;\r\n var _rootCtx; // Used as the root context, holding the current config and initialized core\r\n var _nextPlugin; // Used for backward compatibility where plugins don't call the main pipeline\r\n var _unloadHandlerContainer;\r\n var _hookContainer;\r\n _initDefaults();\r\n dynamicProto(BaseTelemetryPlugin, _self, function (_self) {\r\n _self[_DYN_INITIALIZE /* @min:%2einitialize */] = function (config, core, extensions, pluginChain) {\r\n _setDefaults(config, core, pluginChain);\r\n _isinitialized = true;\r\n };\r\n _self[_DYN_TEARDOWN /* @min:%2eteardown */] = function (unloadCtx, unloadState) {\r\n var _a;\r\n // If this plugin has already been torn down (not operational) or is not initialized (core is not set)\r\n // or the core being used for unload was not the same core used for initialization.\r\n var core = _self[STR_CORE /* @min:%2ecore */];\r\n if (!core || (unloadCtx && core !== unloadCtx[STR_CORE /* @min:%2ecore */]())) {\r\n // Do Nothing as either the plugin is not initialized or was not initialized by the current core\r\n return;\r\n }\r\n var result;\r\n var unloadDone = false;\r\n var theUnloadCtx = unloadCtx || createProcessTelemetryUnloadContext(null, core, _nextPlugin && _nextPlugin[strGetPlugin] ? _nextPlugin[strGetPlugin]() : _nextPlugin);\r\n var theUnloadState = unloadState || (_a = {\r\n reason: 0 /* TelemetryUnloadReason.ManualTeardown */\r\n },\r\n _a[_DYN_IS_ASYNC /* @min:isAsync */] = false,\r\n _a);\r\n function _unloadCallback() {\r\n if (!unloadDone) {\r\n unloadDone = true;\r\n _unloadHandlerContainer.run(theUnloadCtx, unloadState);\r\n _hookContainer.run(theUnloadCtx[_DYN_DIAG_LOG /* @min:%2ediagLog */]());\r\n if (result === true) {\r\n theUnloadCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](theUnloadState);\r\n }\r\n _initDefaults();\r\n }\r\n }\r\n if (!_self[_DYN__DO_TEARDOWN /* @min:%2e_doTeardown */] || _self[_DYN__DO_TEARDOWN /* @min:%2e_doTeardown */](theUnloadCtx, theUnloadState, _unloadCallback) !== true) {\r\n _unloadCallback();\r\n }\r\n else {\r\n // Tell the caller that we will be calling processNext()\r\n result = true;\r\n }\r\n return result;\r\n };\r\n _self[_DYN_UPDATE /* @min:%2eupdate */] = function (updateCtx, updateState) {\r\n // If this plugin has already been torn down (not operational) or is not initialized (core is not set)\r\n // or the core being used for unload was not the same core used for initialization.\r\n var core = _self[STR_CORE /* @min:%2ecore */];\r\n if (!core || (updateCtx && core !== updateCtx[STR_CORE /* @min:%2ecore */]())) {\r\n // Do Nothing\r\n return;\r\n }\r\n var result;\r\n var updateDone = false;\r\n var theUpdateCtx = updateCtx || createProcessTelemetryUpdateContext(null, core, _nextPlugin && _nextPlugin[strGetPlugin] ? _nextPlugin[strGetPlugin]() : _nextPlugin);\r\n var theUpdateState = updateState || {\r\n reason: 0 /* TelemetryUpdateReason.Unknown */\r\n };\r\n function _updateCallback() {\r\n if (!updateDone) {\r\n updateDone = true;\r\n _setDefaults(theUpdateCtx.getCfg(), theUpdateCtx.core(), theUpdateCtx[_DYN_GET_NEXT /* @min:%2egetNext */]());\r\n }\r\n }\r\n if (!_self._doUpdate || _self._doUpdate(theUpdateCtx, theUpdateState, _updateCallback) !== true) {\r\n _updateCallback();\r\n }\r\n else {\r\n result = true;\r\n }\r\n return result;\r\n };\r\n proxyFunctionAs(_self, \"_addUnloadCb\", function () { return _unloadHandlerContainer; }, \"add\");\r\n proxyFunctionAs(_self, \"_addHook\", function () { return _hookContainer; }, \"add\");\r\n objDefine(_self, \"_unloadHooks\", { g: function () { return _hookContainer; } });\r\n });\r\n // These are added after the dynamicProto so that are not moved to the prototype\r\n _self[_DYN_DIAG_LOG /* @min:%2ediagLog */] = function (itemCtx) {\r\n return _getTelCtx(itemCtx)[_DYN_DIAG_LOG /* @min:%2ediagLog */]();\r\n };\r\n _self[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */] = function () {\r\n return _isinitialized;\r\n };\r\n _self.setInitialized = function (isInitialized) {\r\n _isinitialized = isInitialized;\r\n };\r\n // _self.getNextPlugin = () => DO NOT IMPLEMENT\r\n // Sub-classes of this base class *should* not be relying on this value and instead\r\n // should use processNext() function. If you require access to the plugin use the\r\n // IProcessTelemetryContext.getNext().getPlugin() while in the pipeline, Note getNext() may return null.\r\n _self[_DYN_SET_NEXT_PLUGIN /* @min:%2esetNextPlugin */] = function (next) {\r\n _nextPlugin = next;\r\n };\r\n _self[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */] = function (env, itemCtx) {\r\n if (itemCtx) {\r\n // Normal core execution sequence\r\n itemCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](env);\r\n }\r\n else if (_nextPlugin && isFunction(_nextPlugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */])) {\r\n // Looks like backward compatibility or out of band processing. And as it looks\r\n // like a ITelemetryPlugin or ITelemetryPluginChain, just call processTelemetry\r\n _nextPlugin[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */](env, null);\r\n }\r\n };\r\n _self._getTelCtx = _getTelCtx;\r\n function _getTelCtx(currentCtx) {\r\n if (currentCtx === void 0) { currentCtx = null; }\r\n var itemCtx = currentCtx;\r\n if (!itemCtx) {\r\n var rootCtx = _rootCtx || createProcessTelemetryContext(null, {}, _self[STR_CORE /* @min:%2ecore */]);\r\n // tslint:disable-next-line: prefer-conditional-expression\r\n if (_nextPlugin && _nextPlugin[strGetPlugin]) {\r\n // Looks like a chain object\r\n itemCtx = rootCtx[_DYN_CREATE_NEW /* @min:%2ecreateNew */](null, _nextPlugin[strGetPlugin]);\r\n }\r\n else {\r\n itemCtx = rootCtx[_DYN_CREATE_NEW /* @min:%2ecreateNew */](null, _nextPlugin);\r\n }\r\n }\r\n return itemCtx;\r\n }\r\n function _setDefaults(config, core, pluginChain) {\r\n // Make sure the extensionConfig exists and the config is dynamic\r\n createDynamicConfig(config, defaultValues, safeGetLogger(core));\r\n if (!pluginChain && core) {\r\n // Get the first plugin from the core\r\n pluginChain = core[_DYN_GET_PROCESS_TEL_CONT0 /* @min:%2egetProcessTelContext */]()[_DYN_GET_NEXT /* @min:%2egetNext */]();\r\n }\r\n var nextPlugin = _nextPlugin;\r\n if (_nextPlugin && _nextPlugin[strGetPlugin]) {\r\n // If it looks like a proxy/chain then get the plugin\r\n nextPlugin = _nextPlugin[strGetPlugin]();\r\n }\r\n // Support legacy plugins where core was defined as a property\r\n _self[STR_CORE /* @min:%2ecore */] = core;\r\n _rootCtx = createProcessTelemetryContext(pluginChain, config, core, nextPlugin);\r\n }\r\n function _initDefaults() {\r\n _isinitialized = false;\r\n _self[STR_CORE /* @min:%2ecore */] = null;\r\n _rootCtx = null;\r\n _nextPlugin = null;\r\n _hookContainer = createUnloadHookContainer();\r\n _unloadHandlerContainer = createUnloadHandlerContainer();\r\n }\r\n }\r\n BaseTelemetryPlugin.prototype.initialize = function (config, core, extensions, pluginChain) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Tear down the plugin and remove any hooked value, the plugin should be removed so that it is no longer initialized and\r\n * therefore could be re-initialized after being torn down. The plugin should ensure that once this has been called any further\r\n * processTelemetry calls are ignored and it just calls the processNext() with the provided context.\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 * @returns boolean - true if the plugin has or will call processNext(), this for backward compatibility as previously teardown was synchronous and returned nothing.\r\n */\r\n BaseTelemetryPlugin.prototype.teardown = function (unloadCtx, unloadState) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return false;\r\n };\r\n /**\r\n * The the plugin should re-evaluate configuration and update any cached configuration settings.\r\n * @param updateCtx - This is the context that should be used during updating.\r\n * @param updateState - The details / state of the update process, it holds details like the current and previous configuration.\r\n * @returns boolean - true if the plugin has or will call updateCtx.processNext(), this allows the plugin to perform any asynchronous operations.\r\n */\r\n BaseTelemetryPlugin.prototype.update = function (updateCtx, updateState) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Add an unload handler that will be called when the SDK is being unloaded\r\n * @param handler - the handler\r\n */\r\n BaseTelemetryPlugin.prototype._addUnloadCb = function (handler) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Add this hook so that it is automatically removed during unloading\r\n * @param hooks - The single hook or an array of IInstrumentHook objects\r\n */\r\n BaseTelemetryPlugin.prototype._addHook = function (hooks) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n return BaseTelemetryPlugin;\r\n}());\r\nexport { BaseTelemetryPlugin };\r\n//# sourceMappingURL=BaseTelemetryPlugin.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { arrForEach, dumpObj } from \"@nevware21/ts-utils\";\r\nimport { _DYN_DIAG_LOG, _DYN_PUSH } from \"../__DynamicConstants\";\r\nimport { _throwInternal } from \"./DiagnosticLogger\";\r\nexport function createUnloadHandlerContainer() {\r\n var handlers = [];\r\n function _addHandler(handler) {\r\n if (handler) {\r\n handlers[_DYN_PUSH /* @min:%2epush */](handler);\r\n }\r\n }\r\n function _runHandlers(unloadCtx, unloadState) {\r\n arrForEach(handlers, function (handler) {\r\n try {\r\n handler(unloadCtx, unloadState);\r\n }\r\n catch (e) {\r\n _throwInternal(unloadCtx[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 73 /* _eInternalMessageId.PluginException */, \"Unexpected error calling unload handler - \" + dumpObj(e));\r\n }\r\n });\r\n handlers = [];\r\n }\r\n return {\r\n add: _addHandler,\r\n run: _runHandlers\r\n };\r\n}\r\n//# sourceMappingURL=UnloadHandlerContainer.js.map","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { getKnownSymbol } from \"../symbol/symbol\";\r\nimport { WellKnownSymbols } from \"../symbol/well_known\";\r\nimport { isFunction, isStrictNullOrUndefined } from \"../helpers/base\";\r\n\r\n/**\r\n * Checks if the type of value looks like an iterator instance (contains a next function).\r\n *\r\n * @since 0.4.0\r\n * @group Type Identity\r\n * @group Iterator\r\n * @typeParam T - Identifies the return type of the iterator defaults to any\r\n * @param value - The value to be checked\r\n * @returns {boolean} True if the value is an Iterator, otherwise false\r\n * @example\r\n * ```ts\r\n * isIterator(null); // false\r\n * isIterator(undefined); // false\r\n * isIterator(\"null\"); // false (Strings are iterable but not iterators)\r\n * isIterator([]); // false (Arrays are iterable but not iterators)\r\n * isIterator({\r\n * next: function() { return true }\r\n * }); // true, iterators must contain a \"next\" function\r\n * ```\r\n */\r\nexport function isIterator(value: any): value is Iterator {\r\n return !!value && isFunction(value.next);\r\n}\r\n\r\n/**\r\n * Checks if the value looks like it is iterable, contains a [symbol.iterator].\r\n *\r\n * @since 0.4.0\r\n * @group Type Identity\r\n * @group Iterator\r\n * @typeParam T - Identifies the return type of the iterator\r\n * @param value - The value to be checked\r\n * @returns {boolean} True if the value is an Iterable, otherwise false\r\n * @example\r\n * ```ts\r\n * isIterable(null); // false\r\n * isIterable(undefined); // false\r\n * isIterable(\"null\"); // true (Strings are iterable)\r\n * isIterable([]); // true (Arrays are iterable)\r\n * ```\r\n */\r\nexport function isIterable(value: any): value is Iterable {\r\n return !isStrictNullOrUndefined(value) && isFunction(value[getKnownSymbol(WellKnownSymbols.iterator)]);\r\n}","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { isArray, isUndefined } from \"../helpers/base\";\r\nimport { isIterable, isIterator } from \"../iterator/iterator\";\r\nimport { iterForOf } from \"../iterator/forOf\";\r\nimport { fnApply } from \"../funcs/fnApply\";\r\n\r\n/**\r\n * Appends the `elms` to the `target` where the elms may be an array, a single object\r\n * or an iterator object\r\n * @group Array\r\n * @group Iterator\r\n * @example\r\n * ```ts\r\n * let theArray = arrAppend([], 1);\r\n * arrAppend(theArray, [ 2, 3, 4 ]);\r\n * arrAppend(theArray, [ \"a\", \"b\", \"c\" ]);\r\n * // theArray is now [ 1, 2, 3, 4, \"a\", \"b\", \"c\" ]\r\n * ```\r\n * @param target - The target array\r\n * @param elms - The item, array of items an iterable or iterator object of items to add to the target\r\n * @returns The passed in target array\r\n * @example\r\n * ```ts\r\n * // Adding a single value\r\n * arrAppend([], undefined); // []\r\n * arrAppend([], 0); // [ 0 ]\r\n * arrAppend([1], undefined); // [ 1 ]\r\n * arrAppend([1], 2); // [ 1, 2 ]\r\n *\r\n * // Adding an array\r\n * arrAppend([], [] as number[]); // []\r\n * arrAppend([], [0]); // [ 0 ]\r\n * arrAppend([1], []); // [ 1 ]\r\n * arrAppend([1], [2]); // [ 1, 2 ]\r\n *\r\n * // Adding with an iterator\r\n * arrAppend([], ([] as number[]).values()); // []\r\n * arrAppend([], [0].values()); // [ 0 ]\r\n * arrAppend([1], [].keys()); // [ 1 ]\r\n * arrAppend([1], [2].values()); // [ 1, 2 ]\r\n * arrAppend([1], [2].keys()); // [ 1, 0 ] - 0 is from the index from the first element\r\n * ```\r\n */\r\nexport function arrAppend(target: T[], elms: T | T[] | Iterator): T[] {\r\n if (!isUndefined(elms) && target) {\r\n if (isArray(elms)) {\r\n // This is not just \"target.push(elms)\" but becomes effectively \"target.push(elms[0], elms[1], ...)\"\r\n fnApply(target.push, target, elms);\r\n } else if (isIterator(elms) || isIterable(elms)) {\r\n iterForOf(elms, (elm) => {\r\n target.push(elm);\r\n });\r\n } else {\r\n target.push(elms);\r\n }\r\n }\r\n\r\n return target;\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { arrAppend, arrForEach, dumpObj } from \"@nevware21/ts-utils\";\r\nimport { _throwInternal } from \"./DiagnosticLogger\";\r\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 */\r\nexport function createUnloadHookContainer() {\r\n var _hooks = [];\r\n function _doUnload(logger) {\r\n var oldHooks = _hooks;\r\n _hooks = [];\r\n // Remove all registered unload hooks\r\n arrForEach(oldHooks, function (fn) {\r\n // allow either rm or remove callback function\r\n try {\r\n (fn.rm || fn.remove).call(fn);\r\n }\r\n catch (e) {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 73 /* _eInternalMessageId.PluginException */, \"Unloading:\" + dumpObj(e));\r\n }\r\n });\r\n }\r\n function _addHook(hooks) {\r\n if (hooks) {\r\n arrAppend(_hooks, hooks);\r\n }\r\n }\r\n return {\r\n run: _doUnload,\r\n add: _addHook\r\n };\r\n}\r\n//# sourceMappingURL=UnloadHookContainer.js.map","/**\r\n* ReactPlugin.ts\r\n* @copyright Microsoft 2019\r\n*/\r\nimport { __extends } from \"tslib\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { AnalyticsPluginIdentifier } from \"@microsoft/applicationinsights-common\";\r\nimport { BaseTelemetryPlugin, _throwInternal, isFunction, proxyFunctions, safeGetCookieMgr, onConfigChange, objDefineAccessors } from \"@microsoft/applicationinsights-core-js\";\r\nimport { objDeepFreeze } from \"@nevware21/ts-utils\";\r\nvar defaultReactExtensionConfig = objDeepFreeze({\r\n history: { blkVal: true, v: undefined }\r\n});\r\nvar ReactPlugin = /** @class */ (function (_super) {\r\n __extends(ReactPlugin, _super);\r\n function ReactPlugin() {\r\n var _this = _super.call(this) || this;\r\n _this.priority = 185;\r\n _this.identifier = 'ReactPlugin';\r\n var _analyticsPlugin;\r\n var _extensionConfig;\r\n var _unlisten;\r\n var _pageViewTimer;\r\n var _pageViewTracked;\r\n dynamicProto(ReactPlugin, _this, function (_self, _base) {\r\n _initDefaults();\r\n _self.initialize = function (config, core, extensions, pluginChain) {\r\n _super.prototype.initialize.call(_this, config, core, extensions, pluginChain);\r\n _self._addHook(onConfigChange(config, function (details) {\r\n var _a;\r\n var ctx = _self._getTelCtx();\r\n _extensionConfig = ctx.getExtCfg(_this.identifier, defaultReactExtensionConfig);\r\n _analyticsPlugin = (_a = core.getPlugin(AnalyticsPluginIdentifier)) === null || _a === void 0 ? void 0 : _a.plugin;\r\n if (isFunction(_unlisten)) {\r\n _unlisten();\r\n _unlisten = null;\r\n }\r\n if (_extensionConfig.history) {\r\n _addHistoryListener(_extensionConfig.history);\r\n if (!_pageViewTracked) {\r\n var pageViewTelemetry = {\r\n uri: _extensionConfig.history.location.pathname\r\n };\r\n _self.trackPageView(pageViewTelemetry);\r\n _pageViewTracked = true;\r\n }\r\n }\r\n }));\r\n };\r\n _self.getCookieMgr = function () {\r\n return safeGetCookieMgr(_self.core);\r\n };\r\n _self.getAppInsights = _getAnalytics;\r\n _self.processTelemetry = function (event, itemCtx) {\r\n _self.processNext(event, itemCtx);\r\n };\r\n _self._doTeardown = function (unloadCtx, unloadState, asyncCallback) {\r\n if (isFunction(_unlisten)) {\r\n _unlisten();\r\n }\r\n if (_pageViewTimer) {\r\n clearTimeout(_pageViewTimer);\r\n }\r\n _initDefaults();\r\n };\r\n // Proxy the analytics functions\r\n proxyFunctions(_self, _getAnalytics, [\r\n \"trackMetric\",\r\n \"trackPageView\",\r\n \"trackEvent\",\r\n \"trackException\",\r\n \"trackTrace\",\r\n ]);\r\n function _initDefaults() {\r\n _analyticsPlugin = null;\r\n _extensionConfig = null;\r\n _unlisten = null;\r\n _pageViewTimer = null;\r\n _pageViewTracked = false;\r\n }\r\n function _getAnalytics() {\r\n if (!_analyticsPlugin) {\r\n _throwInternal(_self.diagLog(), 1 /* eLoggingSeverity.CRITICAL */, 64 /* _eInternalMessageId.TelemetryInitializerFailed */, \"Analytics plugin is not available, React plugin telemetry will not be sent: \");\r\n }\r\n return _analyticsPlugin;\r\n }\r\n function _addHistoryListener(history) {\r\n var locationListener = function (arg) {\r\n // v4 of the history API passes \"location\" as the first argument, while v5 passes an object that contains location and action \r\n var locn = null;\r\n if (\"location\" in arg) {\r\n // Looks like v5\r\n locn = arg[\"location\"];\r\n }\r\n else {\r\n locn = arg;\r\n }\r\n // Timeout to ensure any changes to the DOM made by route changes get included in pageView telemetry\r\n _pageViewTimer = setTimeout(function () {\r\n _pageViewTimer = null;\r\n var pageViewTelemetry = { uri: locn.pathname };\r\n _self.trackPageView(pageViewTelemetry);\r\n }, 500);\r\n };\r\n _unlisten = history.listen(locationListener);\r\n }\r\n objDefineAccessors(_self, \"_extensionConfig\", function () { return _extensionConfig; });\r\n });\r\n return _this;\r\n }\r\n ReactPlugin.prototype.initialize = function (config, core, extensions, pluginChain) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Get the current cookie manager for this instance\r\n */\r\n ReactPlugin.prototype.getCookieMgr = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Get application insights instance.\r\n */\r\n ReactPlugin.prototype.getAppInsights = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Add Part A fields to the event\r\n * @param event The event that needs to be processed\r\n */\r\n ReactPlugin.prototype.processTelemetry = function (event, itemCtx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n ReactPlugin.prototype.trackMetric = function (metric, customProperties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n ReactPlugin.prototype.trackPageView = function (pageView) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n ReactPlugin.prototype.trackEvent = function (event, customProperties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n ReactPlugin.prototype.trackException = function (exception, customProperties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n ReactPlugin.prototype.trackTrace = function (trace, customProperties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n return ReactPlugin;\r\n}(BaseTelemetryPlugin));\r\nexport default ReactPlugin;\r\n//# sourceMappingURL=ReactPlugin.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { createEnum, createTypeMap } from \"@nevware21/ts-utils\";\r\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 */\r\nexport var createEnumStyle = createEnum;\r\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 */\r\nexport var createValueMap = createTypeMap;\r\n//# sourceMappingURL=EnumHelperFuncs.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { createEnumStyle } from \"@microsoft/applicationinsights-core-js\";\r\nexport var StorageType = createEnumStyle({\r\n LocalStorage: 0 /* eStorageType.LocalStorage */,\r\n SessionStorage: 1 /* eStorageType.SessionStorage */\r\n});\r\nexport var DistributedTracingModes = createEnumStyle({\r\n AI: 0 /* eDistributedTracingModes.AI */,\r\n AI_AND_W3C: 1 /* eDistributedTracingModes.AI_AND_W3C */,\r\n W3C: 2 /* eDistributedTracingModes.W3C */\r\n});\r\n//# sourceMappingURL=Enums.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n// @skip-file-minify\r\n// ##############################################################\r\n// AUTO GENERATED FILE: This file is Auto Generated during build.\r\n// ##############################################################\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\nexport var _DYN_SPLIT = \"split\"; // Count: 6\r\nexport var _DYN_LENGTH = \"length\"; // Count: 41\r\nexport var _DYN_TO_LOWER_CASE = \"toLowerCase\"; // Count: 6\r\nexport var _DYN_INGESTIONENDPOINT = \"ingestionendpoint\"; // Count: 4\r\nexport var _DYN_TO_STRING = \"toString\"; // Count: 9\r\nexport var _DYN_REMOVE_ITEM = \"removeItem\"; // Count: 3\r\nexport var _DYN_NAME = \"name\"; // Count: 11\r\nexport var _DYN_MESSAGE = \"message\"; // Count: 10\r\nexport var _DYN_COUNT = \"count\"; // Count: 8\r\nexport var _DYN_PRE_TRIGGER_DATE = \"preTriggerDate\"; // Count: 4\r\nexport var _DYN_DISABLED = \"disabled\"; // Count: 3\r\nexport var _DYN_INTERVAL = \"interval\"; // Count: 3\r\nexport var _DYN_DAYS_OF_MONTH = \"daysOfMonth\"; // Count: 3\r\nexport var _DYN_DATE = \"date\"; // Count: 5\r\nexport var _DYN_GET_UTCDATE = \"getUTCDate\"; // Count: 3\r\nexport var _DYN_STRINGIFY = \"stringify\"; // Count: 4\r\nexport var _DYN_PATHNAME = \"pathname\"; // Count: 4\r\nexport var _DYN_CORRELATION_HEADER_E0 = \"correlationHeaderExcludePatterns\"; // Count: 2\r\nexport var _DYN_EXTENSION_CONFIG = \"extensionConfig\"; // Count: 4\r\nexport var _DYN_EXCEPTIONS = \"exceptions\"; // Count: 6\r\nexport var _DYN_PARSED_STACK = \"parsedStack\"; // Count: 13\r\nexport var _DYN_PROPERTIES = \"properties\"; // Count: 9\r\nexport var _DYN_MEASUREMENTS = \"measurements\"; // Count: 9\r\nexport var _DYN_SIZE_IN_BYTES = \"sizeInBytes\"; // Count: 11\r\nexport var _DYN_TYPE_NAME = \"typeName\"; // Count: 11\r\nexport var _DYN_SEVERITY_LEVEL = \"severityLevel\"; // Count: 5\r\nexport var _DYN_PROBLEM_GROUP = \"problemGroup\"; // Count: 3\r\nexport var _DYN_IS_MANUAL = \"isManual\"; // Count: 3\r\nexport var _DYN__CREATE_FROM_INTERFA1 = \"CreateFromInterface\"; // Count: 2\r\nexport var _DYN_ASSEMBLY = \"assembly\"; // Count: 7\r\nexport var _DYN_HAS_FULL_STACK = \"hasFullStack\"; // Count: 6\r\nexport var _DYN_LEVEL = \"level\"; // Count: 5\r\nexport var _DYN_METHOD = \"method\"; // Count: 7\r\nexport var _DYN_FILE_NAME = \"fileName\"; // Count: 6\r\nexport var _DYN_LINE = \"line\"; // Count: 6\r\nexport var _DYN_DURATION = \"duration\"; // Count: 4\r\nexport var _DYN_RECEIVED_RESPONSE = \"receivedResponse\"; // Count: 2\r\n//# sourceMappingURL=__DynamicConstants.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { _throwInternal, dumpObj, getExceptionName, getGlobal, getGlobalInst, isNullOrUndefined, objForEachKey } from \"@microsoft/applicationinsights-core-js\";\r\nimport { StorageType } from \"./Enums\";\r\nimport { _DYN_REMOVE_ITEM, _DYN_TO_STRING } from \"./__DynamicConstants\";\r\nvar _canUseLocalStorage = undefined;\r\nvar _canUseSessionStorage = undefined;\r\n/**\r\n * Gets the localStorage object if available\r\n * @return {Storage} - Returns the storage object if available else returns null\r\n */\r\nfunction _getLocalStorageObject() {\r\n if (utlCanUseLocalStorage()) {\r\n return _getVerifiedStorageObject(StorageType.LocalStorage);\r\n }\r\n return null;\r\n}\r\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 * @return {Storage} Returns storage object verified that it is usable\r\n */\r\nfunction _getVerifiedStorageObject(storageType) {\r\n try {\r\n if (isNullOrUndefined(getGlobal())) {\r\n return null;\r\n }\r\n var uid = (new Date)[_DYN_TO_STRING /* @min:%2etoString */]();\r\n var storage = getGlobalInst(storageType === StorageType.LocalStorage ? \"localStorage\" : \"sessionStorage\");\r\n storage.setItem(uid, uid);\r\n var fail = storage.getItem(uid) !== uid;\r\n storage[_DYN_REMOVE_ITEM /* @min:%2eremoveItem */](uid);\r\n if (!fail) {\r\n return storage;\r\n }\r\n }\r\n catch (exception) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return null;\r\n}\r\n/**\r\n * Gets the sessionStorage object if available\r\n * @return {Storage} - Returns the storage object if available else returns null\r\n */\r\nfunction _getSessionStorageObject() {\r\n if (utlCanUseSessionStorage()) {\r\n return _getVerifiedStorageObject(StorageType.SessionStorage);\r\n }\r\n return null;\r\n}\r\n/**\r\n * Disables the global SDK usage of local or session storage if available\r\n */\r\nexport function utlDisableStorage() {\r\n _canUseLocalStorage = false;\r\n _canUseSessionStorage = false;\r\n}\r\n/**\r\n * Re-enables the global SDK usage of local or session storage if available\r\n */\r\nexport function utlEnableStorage() {\r\n _canUseLocalStorage = utlCanUseLocalStorage(true);\r\n _canUseSessionStorage = utlCanUseSessionStorage(true);\r\n}\r\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 */\r\nexport function utlCanUseLocalStorage(reset) {\r\n if (reset || _canUseLocalStorage === undefined) {\r\n _canUseLocalStorage = !!_getVerifiedStorageObject(StorageType.LocalStorage);\r\n }\r\n return _canUseLocalStorage;\r\n}\r\nexport function utlGetLocalStorage(logger, name) {\r\n var storage = _getLocalStorageObject();\r\n if (storage !== null) {\r\n try {\r\n return storage.getItem(name);\r\n }\r\n catch (e) {\r\n _canUseLocalStorage = false;\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 1 /* _eInternalMessageId.BrowserCannotReadLocalStorage */, \"Browser failed read of local storage. \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n return null;\r\n}\r\nexport function utlSetLocalStorage(logger, name, data) {\r\n var storage = _getLocalStorageObject();\r\n if (storage !== null) {\r\n try {\r\n storage.setItem(name, data);\r\n return true;\r\n }\r\n catch (e) {\r\n _canUseLocalStorage = false;\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 3 /* _eInternalMessageId.BrowserCannotWriteLocalStorage */, \"Browser failed write to local storage. \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n return false;\r\n}\r\nexport function utlRemoveStorage(logger, name) {\r\n var storage = _getLocalStorageObject();\r\n if (storage !== null) {\r\n try {\r\n storage[_DYN_REMOVE_ITEM /* @min:%2eremoveItem */](name);\r\n return true;\r\n }\r\n catch (e) {\r\n _canUseLocalStorage = false;\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 5 /* _eInternalMessageId.BrowserFailedRemovalFromLocalStorage */, \"Browser failed removal of local storage item. \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n return false;\r\n}\r\nexport function utlCanUseSessionStorage(reset) {\r\n if (reset || _canUseSessionStorage === undefined) {\r\n _canUseSessionStorage = !!_getVerifiedStorageObject(StorageType.SessionStorage);\r\n }\r\n return _canUseSessionStorage;\r\n}\r\nexport function utlGetSessionStorageKeys() {\r\n var keys = [];\r\n if (utlCanUseSessionStorage()) {\r\n objForEachKey(getGlobalInst(\"sessionStorage\"), function (key) {\r\n keys.push(key);\r\n });\r\n }\r\n return keys;\r\n}\r\nexport function utlGetSessionStorage(logger, name) {\r\n var storage = _getSessionStorageObject();\r\n if (storage !== null) {\r\n try {\r\n return storage.getItem(name);\r\n }\r\n catch (e) {\r\n _canUseSessionStorage = false;\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 2 /* _eInternalMessageId.BrowserCannotReadSessionStorage */, \"Browser failed read of session storage. \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n return null;\r\n}\r\nexport function utlSetSessionStorage(logger, name, data) {\r\n var storage = _getSessionStorageObject();\r\n if (storage !== null) {\r\n try {\r\n storage.setItem(name, data);\r\n return true;\r\n }\r\n catch (e) {\r\n _canUseSessionStorage = false;\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 4 /* _eInternalMessageId.BrowserCannotWriteSessionStorage */, \"Browser failed write to session storage. \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n return false;\r\n}\r\nexport function utlRemoveSessionStorage(logger, name) {\r\n var storage = _getSessionStorageObject();\r\n if (storage !== null) {\r\n try {\r\n storage[_DYN_REMOVE_ITEM /* @min:%2eremoveItem */](name);\r\n return true;\r\n }\r\n catch (e) {\r\n _canUseSessionStorage = false;\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 6 /* _eInternalMessageId.BrowserFailedRemovalFromSessionStorage */, \"Browser failed removal of session storage item. \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n return false;\r\n}\r\n//# sourceMappingURL=StorageHelperFuncs.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\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 */\r\nexport var DisabledPropertyName = \"Microsoft_ApplicationInsights_BypassAjaxInstrumentation\";\r\nexport var SampleRate = \"sampleRate\";\r\nexport var ProcessLegacy = \"ProcessLegacy\";\r\nexport var HttpMethod = \"http.method\";\r\nexport var DEFAULT_BREEZE_ENDPOINT = \"https://dc.services.visualstudio.com\";\r\nexport var DEFAULT_BREEZE_PATH = \"/v2/track\";\r\nexport var strNotSpecified = \"not_specified\";\r\nexport var strIkey = \"iKey\";\r\n//# sourceMappingURL=Constants.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { _throwInternal, getJSON, hasJSON, isObject, objForEachKey, strTrim } from \"@microsoft/applicationinsights-core-js\";\r\nimport { asString, strSubstr, strSubstring } from \"@nevware21/ts-utils\";\r\nimport { _DYN_LENGTH, _DYN_STRINGIFY, _DYN_TO_STRING } from \"../../__DynamicConstants\";\r\nexport function dataSanitizeKeyAndAddUniqueness(logger, key, map) {\r\n var origLength = key[_DYN_LENGTH /* @min:%2elength */];\r\n var field = dataSanitizeKey(logger, key);\r\n // validation truncated the length. We need to add uniqueness\r\n if (field[_DYN_LENGTH /* @min:%2elength */] !== origLength) {\r\n var i = 0;\r\n var uniqueField = field;\r\n while (map[uniqueField] !== undefined) {\r\n i++;\r\n uniqueField = strSubstring(field, 0, 150 /* DataSanitizerValues.MAX_NAME_LENGTH */ - 3) + dsPadNumber(i);\r\n }\r\n field = uniqueField;\r\n }\r\n return field;\r\n}\r\nexport function dataSanitizeKey(logger, name) {\r\n var nameTrunc;\r\n if (name) {\r\n // Remove any leading or trailing whitespace\r\n name = strTrim(asString(name));\r\n // truncate the string to 150 chars\r\n if (name[_DYN_LENGTH /* @min:%2elength */] > 150 /* DataSanitizerValues.MAX_NAME_LENGTH */) {\r\n nameTrunc = strSubstring(name, 0, 150 /* DataSanitizerValues.MAX_NAME_LENGTH */);\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 57 /* _eInternalMessageId.NameTooLong */, \"name is too long. It has been truncated to \" + 150 /* DataSanitizerValues.MAX_NAME_LENGTH */ + \" characters.\", { name: name }, true);\r\n }\r\n }\r\n return nameTrunc || name;\r\n}\r\nexport function dataSanitizeString(logger, value, maxLength) {\r\n if (maxLength === void 0) { maxLength = 1024 /* DataSanitizerValues.MAX_STRING_LENGTH */; }\r\n var valueTrunc;\r\n if (value) {\r\n maxLength = maxLength ? maxLength : 1024 /* DataSanitizerValues.MAX_STRING_LENGTH */; // in case default parameters dont work\r\n value = strTrim(asString(value));\r\n if (value[_DYN_LENGTH /* @min:%2elength */] > maxLength) {\r\n valueTrunc = strSubstring(value, 0, maxLength);\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 61 /* _eInternalMessageId.StringValueTooLong */, \"string value is too long. It has been truncated to \" + maxLength + \" characters.\", { value: value }, true);\r\n }\r\n }\r\n return valueTrunc || value;\r\n}\r\nexport function dataSanitizeUrl(logger, url) {\r\n return dataSanitizeInput(logger, url, 2048 /* DataSanitizerValues.MAX_URL_LENGTH */, 66 /* _eInternalMessageId.UrlTooLong */);\r\n}\r\nexport function dataSanitizeMessage(logger, message) {\r\n var messageTrunc;\r\n if (message) {\r\n if (message[_DYN_LENGTH /* @min:%2elength */] > 32768 /* DataSanitizerValues.MAX_MESSAGE_LENGTH */) {\r\n messageTrunc = strSubstring(message, 0, 32768 /* DataSanitizerValues.MAX_MESSAGE_LENGTH */);\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 56 /* _eInternalMessageId.MessageTruncated */, \"message is too long, it has been truncated to \" + 32768 /* DataSanitizerValues.MAX_MESSAGE_LENGTH */ + \" characters.\", { message: message }, true);\r\n }\r\n }\r\n return messageTrunc || message;\r\n}\r\nexport function dataSanitizeException(logger, exception) {\r\n var exceptionTrunc;\r\n if (exception) {\r\n // Make surte its a string\r\n var value = \"\" + exception;\r\n if (value[_DYN_LENGTH /* @min:%2elength */] > 32768 /* DataSanitizerValues.MAX_EXCEPTION_LENGTH */) {\r\n exceptionTrunc = strSubstring(value, 0, 32768 /* DataSanitizerValues.MAX_EXCEPTION_LENGTH */);\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 52 /* _eInternalMessageId.ExceptionTruncated */, \"exception is too long, it has been truncated to \" + 32768 /* DataSanitizerValues.MAX_EXCEPTION_LENGTH */ + \" characters.\", { exception: exception }, true);\r\n }\r\n }\r\n return exceptionTrunc || exception;\r\n}\r\nexport function dataSanitizeProperties(logger, properties) {\r\n if (properties) {\r\n var tempProps_1 = {};\r\n objForEachKey(properties, function (prop, value) {\r\n if (isObject(value) && hasJSON()) {\r\n // Stringify any part C properties\r\n try {\r\n value = getJSON()[_DYN_STRINGIFY /* @min:%2estringify */](value);\r\n }\r\n catch (e) {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 49 /* _eInternalMessageId.CannotSerializeObjectNonSerializable */, \"custom property is not valid\", { exception: e }, true);\r\n }\r\n }\r\n value = dataSanitizeString(logger, value, 8192 /* DataSanitizerValues.MAX_PROPERTY_LENGTH */);\r\n prop = dataSanitizeKeyAndAddUniqueness(logger, prop, tempProps_1);\r\n tempProps_1[prop] = value;\r\n });\r\n properties = tempProps_1;\r\n }\r\n return properties;\r\n}\r\nexport function dataSanitizeMeasurements(logger, measurements) {\r\n if (measurements) {\r\n var tempMeasurements_1 = {};\r\n objForEachKey(measurements, function (measure, value) {\r\n measure = dataSanitizeKeyAndAddUniqueness(logger, measure, tempMeasurements_1);\r\n tempMeasurements_1[measure] = value;\r\n });\r\n measurements = tempMeasurements_1;\r\n }\r\n return measurements;\r\n}\r\nexport function dataSanitizeId(logger, id) {\r\n return id ? dataSanitizeInput(logger, id, 128 /* DataSanitizerValues.MAX_ID_LENGTH */, 69 /* _eInternalMessageId.IdTooLong */)[_DYN_TO_STRING /* @min:%2etoString */]() : id;\r\n}\r\nexport function dataSanitizeInput(logger, input, maxLength, _msgId) {\r\n var inputTrunc;\r\n if (input) {\r\n input = strTrim(asString(input));\r\n if (input[_DYN_LENGTH /* @min:%2elength */] > maxLength) {\r\n inputTrunc = strSubstring(input, 0, maxLength);\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, _msgId, \"input is too long, it has been truncated to \" + maxLength + \" characters.\", { data: input }, true);\r\n }\r\n }\r\n return inputTrunc || input;\r\n}\r\nexport function dsPadNumber(num) {\r\n var s = \"00\" + num;\r\n return strSubstr(s, s[_DYN_LENGTH /* @min:%2elength */] - 3);\r\n}\r\n//# sourceMappingURL=DataSanitizer.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { isNullOrUndefined, objForEachKey, throwError, toISOString } from \"@microsoft/applicationinsights-core-js\";\r\nimport { strIkey, strNotSpecified } from \"./Constants\";\r\nimport { dataSanitizeString } from \"./Telemetry/Common/DataSanitizer\";\r\nimport { _DYN_NAME } from \"./__DynamicConstants\";\r\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. ie 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 */\r\nexport function createTelemetryItem(item, baseType, envelopeName, logger, customProperties, systemProperties) {\r\n var _a;\r\n envelopeName = dataSanitizeString(logger, envelopeName) || strNotSpecified;\r\n if (isNullOrUndefined(item) ||\r\n isNullOrUndefined(baseType) ||\r\n isNullOrUndefined(envelopeName)) {\r\n throwError(\"Input doesn't contain all required fields\");\r\n }\r\n var iKey = \"\";\r\n if (item[strIkey]) {\r\n iKey = item[strIkey];\r\n delete item[strIkey];\r\n }\r\n var telemetryItem = (_a = {},\r\n _a[_DYN_NAME /* @min:name */] = envelopeName,\r\n _a.time = toISOString(new Date()),\r\n _a.iKey = iKey,\r\n _a.ext = systemProperties ? systemProperties : {},\r\n _a.tags = [],\r\n _a.data = {},\r\n _a.baseType = baseType,\r\n _a.baseData = item // Part B\r\n ,\r\n _a);\r\n // Part C\r\n if (!isNullOrUndefined(customProperties)) {\r\n objForEachKey(customProperties, function (prop, value) {\r\n telemetryItem.data[prop] = value;\r\n });\r\n }\r\n return telemetryItem;\r\n}\r\nvar TelemetryItemCreator = /** @class */ (function () {\r\n function TelemetryItemCreator() {\r\n }\r\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. ie 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 */\r\n TelemetryItemCreator.create = createTelemetryItem;\r\n return TelemetryItemCreator;\r\n}());\r\nexport { TelemetryItemCreator };\r\n//# sourceMappingURL=TelemetryItemCreator.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { strNotSpecified } from \"../Constants\";\r\nimport { _DYN_MEASUREMENTS, _DYN_NAME, _DYN_PROPERTIES } from \"../__DynamicConstants\";\r\nimport { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString } from \"./Common/DataSanitizer\";\r\nvar Event = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of the EventTelemetry object\r\n */\r\n function Event(logger, name, properties, measurements) {\r\n this.aiDataContract = {\r\n ver: 1 /* FieldType.Required */,\r\n name: 1 /* FieldType.Required */,\r\n properties: 0 /* FieldType.Default */,\r\n measurements: 0 /* FieldType.Default */\r\n };\r\n var _self = this;\r\n _self.ver = 2;\r\n _self[_DYN_NAME /* @min:%2ename */] = dataSanitizeString(logger, name) || strNotSpecified;\r\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\r\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\r\n }\r\n Event.envelopeType = \"Microsoft.ApplicationInsights.{0}.Event\";\r\n Event.dataType = \"EventData\";\r\n return Event;\r\n}());\r\nexport { Event };\r\n//# sourceMappingURL=Event.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { strNotSpecified } from \"../Constants\";\r\nimport { _DYN_MEASUREMENTS, _DYN_MESSAGE, _DYN_PROPERTIES, _DYN_SEVERITY_LEVEL } from \"../__DynamicConstants\";\r\nimport { dataSanitizeMeasurements, dataSanitizeMessage, dataSanitizeProperties } from \"./Common/DataSanitizer\";\r\nvar Trace = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of the TraceTelemetry object\r\n */\r\n function Trace(logger, message, severityLevel, properties, measurements) {\r\n this.aiDataContract = {\r\n ver: 1 /* FieldType.Required */,\r\n message: 1 /* FieldType.Required */,\r\n severityLevel: 0 /* FieldType.Default */,\r\n properties: 0 /* FieldType.Default */\r\n };\r\n var _self = this;\r\n _self.ver = 2;\r\n message = message || strNotSpecified;\r\n _self[_DYN_MESSAGE /* @min:%2emessage */] = dataSanitizeMessage(logger, message);\r\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\r\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\r\n if (severityLevel) {\r\n _self[_DYN_SEVERITY_LEVEL /* @min:%2eseverityLevel */] = severityLevel;\r\n }\r\n }\r\n Trace.envelopeType = \"Microsoft.ApplicationInsights.{0}.Message\";\r\n Trace.dataType = \"MessageData\";\r\n return Trace;\r\n}());\r\nexport { Trace };\r\n//# sourceMappingURL=Trace.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nvar DataPoint = /** @class */ (function () {\r\n function DataPoint() {\r\n /**\r\n * The data contract for serializing this object.\r\n */\r\n this.aiDataContract = {\r\n name: 1 /* FieldType.Required */,\r\n kind: 0 /* FieldType.Default */,\r\n value: 1 /* FieldType.Required */,\r\n count: 0 /* FieldType.Default */,\r\n min: 0 /* FieldType.Default */,\r\n max: 0 /* FieldType.Default */,\r\n stdDev: 0 /* FieldType.Default */\r\n };\r\n /**\r\n * Metric type. Single measurement or the aggregated value.\r\n */\r\n this.kind = 0 /* DataPointType.Measurement */;\r\n }\r\n return DataPoint;\r\n}());\r\nexport { DataPoint };\r\n//# sourceMappingURL=DataPoint.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { strNotSpecified } from \"../Constants\";\r\nimport { _DYN_COUNT, _DYN_MEASUREMENTS, _DYN_NAME, _DYN_PROPERTIES } from \"../__DynamicConstants\";\r\nimport { DataPoint } from \"./Common/DataPoint\";\r\nimport { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString } from \"./Common/DataSanitizer\";\r\nvar Metric = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of the MetricTelemetry object\r\n */\r\n function Metric(logger, name, value, count, min, max, stdDev, properties, measurements) {\r\n this.aiDataContract = {\r\n ver: 1 /* FieldType.Required */,\r\n metrics: 1 /* FieldType.Required */,\r\n properties: 0 /* FieldType.Default */\r\n };\r\n var _self = this;\r\n _self.ver = 2;\r\n var dataPoint = new DataPoint();\r\n dataPoint[_DYN_COUNT /* @min:%2ecount */] = count > 0 ? count : undefined;\r\n dataPoint.max = isNaN(max) || max === null ? undefined : max;\r\n dataPoint.min = isNaN(min) || min === null ? undefined : min;\r\n dataPoint[_DYN_NAME /* @min:%2ename */] = dataSanitizeString(logger, name) || strNotSpecified;\r\n dataPoint.value = value;\r\n dataPoint.stdDev = isNaN(stdDev) || stdDev === null ? undefined : stdDev;\r\n _self.metrics = [dataPoint];\r\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\r\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\r\n }\r\n Metric.envelopeType = \"Microsoft.ApplicationInsights.{0}.Metric\";\r\n Metric.dataType = \"MetricData\";\r\n return Metric;\r\n}());\r\nexport { Metric };\r\n//# sourceMappingURL=Metric.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { arrForEach, isString } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_LENGTH, _DYN_TO_LOWER_CASE } from \"./__DynamicConstants\";\r\nvar strEmpty = \"\";\r\nexport function stringToBoolOrDefault(str, defaultValue) {\r\n if (defaultValue === void 0) { defaultValue = false; }\r\n if (str === undefined || str === null) {\r\n return defaultValue;\r\n }\r\n return str.toString()[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]() === \"true\";\r\n}\r\n/**\r\n * Convert ms to c# time span format\r\n */\r\nexport function msToTimeSpan(totalms) {\r\n if (isNaN(totalms) || totalms < 0) {\r\n totalms = 0;\r\n }\r\n totalms = Math.round(totalms);\r\n var ms = strEmpty + totalms % 1000;\r\n var sec = strEmpty + Math.floor(totalms / 1000) % 60;\r\n var min = strEmpty + Math.floor(totalms / (1000 * 60)) % 60;\r\n var hour = strEmpty + Math.floor(totalms / (1000 * 60 * 60)) % 24;\r\n var days = Math.floor(totalms / (1000 * 60 * 60 * 24));\r\n ms = ms[_DYN_LENGTH /* @min:%2elength */] === 1 ? \"00\" + ms : ms[_DYN_LENGTH /* @min:%2elength */] === 2 ? \"0\" + ms : ms;\r\n sec = sec[_DYN_LENGTH /* @min:%2elength */] < 2 ? \"0\" + sec : sec;\r\n min = min[_DYN_LENGTH /* @min:%2elength */] < 2 ? \"0\" + min : min;\r\n hour = hour[_DYN_LENGTH /* @min:%2elength */] < 2 ? \"0\" + hour : hour;\r\n return (days > 0 ? days + \".\" : strEmpty) + hour + \":\" + min + \":\" + sec + \".\" + ms;\r\n}\r\nexport function getExtensionByName(extensions, identifier) {\r\n var extension = null;\r\n arrForEach(extensions, function (value) {\r\n if (value.identifier === identifier) {\r\n extension = value;\r\n return -1;\r\n }\r\n });\r\n return extension;\r\n}\r\nexport function isCrossOriginError(message, url, lineNumber, columnNumber, error) {\r\n return !error && isString(message) && (message === \"Script error.\" || message === \"Script error\");\r\n}\r\n//# sourceMappingURL=HelperFuncs.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { strNotSpecified } from \"../Constants\";\r\nimport { msToTimeSpan } from \"../HelperFuncs\";\r\nimport { _DYN_DURATION, _DYN_MEASUREMENTS, _DYN_NAME, _DYN_PROPERTIES } from \"../__DynamicConstants\";\r\nimport { dataSanitizeId, dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString, dataSanitizeUrl } from \"./Common/DataSanitizer\";\r\nvar PageView = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of the PageEventTelemetry object\r\n */\r\n function PageView(logger, name, url, durationMs, properties, measurements, id) {\r\n this.aiDataContract = {\r\n ver: 1 /* FieldType.Required */,\r\n name: 0 /* FieldType.Default */,\r\n url: 0 /* FieldType.Default */,\r\n duration: 0 /* FieldType.Default */,\r\n properties: 0 /* FieldType.Default */,\r\n measurements: 0 /* FieldType.Default */,\r\n id: 0 /* FieldType.Default */\r\n };\r\n var _self = this;\r\n _self.ver = 2;\r\n _self.id = dataSanitizeId(logger, id);\r\n _self.url = dataSanitizeUrl(logger, url);\r\n _self[_DYN_NAME /* @min:%2ename */] = dataSanitizeString(logger, name) || strNotSpecified;\r\n if (!isNaN(durationMs)) {\r\n _self[_DYN_DURATION /* @min:%2eduration */] = msToTimeSpan(durationMs);\r\n }\r\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\r\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\r\n }\r\n PageView.envelopeType = \"Microsoft.ApplicationInsights.{0}.Pageview\";\r\n PageView.dataType = \"PageviewData\";\r\n return PageView;\r\n}());\r\nexport { PageView };\r\n//# sourceMappingURL=PageView.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { strNotSpecified } from \"../Constants\";\r\nimport { _DYN_DURATION, _DYN_MEASUREMENTS, _DYN_NAME, _DYN_PROPERTIES, _DYN_RECEIVED_RESPONSE } from \"../__DynamicConstants\";\r\nimport { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString, dataSanitizeUrl } from \"./Common/DataSanitizer\";\r\nvar PageViewPerformance = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of the PageEventTelemetry object\r\n */\r\n function PageViewPerformance(logger, name, url, unused, properties, measurements, cs4BaseData) {\r\n this.aiDataContract = {\r\n ver: 1 /* FieldType.Required */,\r\n name: 0 /* FieldType.Default */,\r\n url: 0 /* FieldType.Default */,\r\n duration: 0 /* FieldType.Default */,\r\n perfTotal: 0 /* FieldType.Default */,\r\n networkConnect: 0 /* FieldType.Default */,\r\n sentRequest: 0 /* FieldType.Default */,\r\n receivedResponse: 0 /* FieldType.Default */,\r\n domProcessing: 0 /* FieldType.Default */,\r\n properties: 0 /* FieldType.Default */,\r\n measurements: 0 /* FieldType.Default */\r\n };\r\n var _self = this;\r\n _self.ver = 2;\r\n _self.url = dataSanitizeUrl(logger, url);\r\n _self[_DYN_NAME /* @min:%2ename */] = dataSanitizeString(logger, name) || strNotSpecified;\r\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\r\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\r\n if (cs4BaseData) {\r\n _self.domProcessing = cs4BaseData.domProcessing;\r\n _self[_DYN_DURATION /* @min:%2eduration */] = cs4BaseData[_DYN_DURATION /* @min:%2eduration */];\r\n _self.networkConnect = cs4BaseData.networkConnect;\r\n _self.perfTotal = cs4BaseData.perfTotal;\r\n _self[_DYN_RECEIVED_RESPONSE /* @min:%2ereceivedResponse */] = cs4BaseData[_DYN_RECEIVED_RESPONSE /* @min:%2ereceivedResponse */];\r\n _self.sentRequest = cs4BaseData.sentRequest;\r\n }\r\n }\r\n PageViewPerformance.envelopeType = \"Microsoft.ApplicationInsights.{0}.PageviewPerformance\";\r\n PageViewPerformance.dataType = \"PageviewPerformanceData\";\r\n return PageViewPerformance;\r\n}());\r\nexport { PageViewPerformance };\r\n//# sourceMappingURL=PageViewPerformance.js.map","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { ArrProto } from \"../internal/constants\";\r\nimport { _unwrapFunction } from \"../internal/unwrapFunction\";\r\nimport { ArrMapCallbackFn } from \"./callbacks\";\r\n\r\n/**\r\n * The arrMap() method creates a new array populated with the results of calling a provided function on every\r\n * element in the calling array.\r\n *\r\n * `arrMap` calls a provided callbackFn function once for each element in an array, in order, and constructs\r\n * a new array from the results. callbackFn is invoked only for indexes of the array which have assigned\r\n * values (including undefined).\r\n *\r\n * It is not called for missing elements of the array; that is:\r\n * - indexes that have never been set;\r\n * - indexes which have been deleted.\r\n *\r\n * @since 0.3.3\r\n * @group Array\r\n * @group ArrayLike\r\n * @typeParam T - Identifies the type of the array elements\r\n * @typeParam R - Identifies the type of the elements returned by the callback function, defaults to T.\r\n * @param theArray - The array or array like object of elements to be searched.\r\n * @param callbackFn - The function that is called for evetn element of `theArray`.\r\n * @param thisArg - The value to use as the `this` when executing the `callbackFn`.\r\n * @example\r\n * ```ts\r\n * const numbers = [1, 4, 9];\r\n * const roots = arrMap(numbers, (num) => Math.sqrt(num));\r\n *\r\n * // roots is now [1, 2, 3]\r\n * // numbers is still [1, 4, 9]\r\n *\r\n * const kvArray = [{ key: 1, value: 10 },\r\n * { key: 2, value: 20 },\r\n * { key: 3, value: 30 }];\r\n *\r\n * const reformattedArray = arrMap(kvArray, ({ key, value}) => ({ [key]: value }));\r\n *\r\n * // reformattedArray is now [{1: 10}, {2: 20}, {3: 30}],\r\n *\r\n * // kvArray is still:\r\n * // [{key: 1, value: 10},\r\n * // {key: 2, value: 20},\r\n * // {key: 3, value: 30}]\r\n *\r\n * // Also supports Array Like objects with same output\r\n * const kvArray = {\r\n * length: 3,\r\n * 0: { key: 1, value: 10 },\r\n * 1: { key: 2, value: 20 },\r\n * 2: { key: 3, value: 30 }\r\n * };\r\n * ```\r\n */\r\nexport const arrMap: (theArray: ArrayLike, callbackFn: ArrMapCallbackFn, thisArg?: any) => R[] = _unwrapFunction(\"map\", ArrProto);\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { __assign } from \"tslib\";\r\nimport { arrForEach, arrMap, isArray, isError, isFunction, isNullOrUndefined, isObject, isString, strTrim } from \"@microsoft/applicationinsights-core-js\";\r\nimport { strIndexOf } from \"@nevware21/ts-utils\";\r\nimport { strNotSpecified } from \"../Constants\";\r\nimport { _DYN_ASSEMBLY, _DYN_EXCEPTIONS, _DYN_FILE_NAME, _DYN_HAS_FULL_STACK, _DYN_IS_MANUAL, _DYN_LENGTH, _DYN_LEVEL, _DYN_LINE, _DYN_MEASUREMENTS, _DYN_MESSAGE, _DYN_METHOD, _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, _DYN__CREATE_FROM_INTERFA1 } from \"../__DynamicConstants\";\r\nimport { dataSanitizeException, dataSanitizeMeasurements, dataSanitizeMessage, dataSanitizeProperties, dataSanitizeString } from \"./Common/DataSanitizer\";\r\nvar NoMethod = \"\";\r\nvar strError = \"error\";\r\nvar strStack = \"stack\";\r\nvar strStackDetails = \"stackDetails\";\r\nvar strErrorSrc = \"errorSrc\";\r\nvar strMessage = \"message\";\r\nvar strDescription = \"description\";\r\nfunction _stringify(value, convertToString) {\r\n var result = value;\r\n if (result && !isString(result)) {\r\n if (JSON && JSON[_DYN_STRINGIFY /* @min:%2estringify */]) {\r\n result = JSON[_DYN_STRINGIFY /* @min:%2estringify */](value);\r\n if (convertToString && (!result || result === \"{}\")) {\r\n if (isFunction(value[_DYN_TO_STRING /* @min:%2etoString */])) {\r\n result = value[_DYN_TO_STRING /* @min:%2etoString */]();\r\n }\r\n else {\r\n result = \"\" + value;\r\n }\r\n }\r\n }\r\n else {\r\n result = \"\" + value + \" - (Missing JSON.stringify)\";\r\n }\r\n }\r\n return result || \"\";\r\n}\r\nfunction _formatMessage(theEvent, errorType) {\r\n var evtMessage = theEvent;\r\n if (theEvent) {\r\n if (evtMessage && !isString(evtMessage)) {\r\n evtMessage = theEvent[strMessage] || theEvent[strDescription] || evtMessage;\r\n }\r\n // Make sure the message is a string\r\n if (evtMessage && !isString(evtMessage)) {\r\n // tslint:disable-next-line: prefer-conditional-expression\r\n evtMessage = _stringify(evtMessage, true);\r\n }\r\n if (theEvent[\"filename\"]) {\r\n // Looks like an event object with filename\r\n evtMessage = evtMessage + \" @\" + (theEvent[\"filename\"] || \"\") + \":\" + (theEvent[\"lineno\"] || \"?\") + \":\" + (theEvent[\"colno\"] || \"?\");\r\n }\r\n }\r\n // Automatically add the error type to the message if it does already appear to be present\r\n if (errorType && errorType !== \"String\" && errorType !== \"Object\" && errorType !== \"Error\" && strIndexOf(evtMessage || \"\", errorType) === -1) {\r\n evtMessage = errorType + \": \" + evtMessage;\r\n }\r\n return evtMessage || \"\";\r\n}\r\nfunction _isExceptionDetailsInternal(value) {\r\n try {\r\n if (isObject(value)) {\r\n return \"hasFullStack\" in value && \"typeName\" in value;\r\n }\r\n }\r\n catch (e) {\r\n // This can happen with some native browser objects, but should not happen for the type we are checking for\r\n }\r\n return false;\r\n}\r\nfunction _isExceptionInternal(value) {\r\n try {\r\n if (isObject(value)) {\r\n return (\"ver\" in value && \"exceptions\" in value && \"properties\" in value);\r\n }\r\n }\r\n catch (e) {\r\n // This can happen with some native browser objects, but should not happen for the type we are checking for\r\n }\r\n return false;\r\n}\r\nfunction _isStackDetails(details) {\r\n return details && details.src && isString(details.src) && details.obj && isArray(details.obj);\r\n}\r\nfunction _convertStackObj(errorStack) {\r\n var src = errorStack || \"\";\r\n if (!isString(src)) {\r\n if (isString(src[strStack])) {\r\n src = src[strStack];\r\n }\r\n else {\r\n src = \"\" + src;\r\n }\r\n }\r\n var items = src[_DYN_SPLIT /* @min:%2esplit */](\"\\n\");\r\n return {\r\n src: src,\r\n obj: items\r\n };\r\n}\r\nfunction _getOperaStack(errorMessage) {\r\n var stack = [];\r\n var lines = errorMessage[_DYN_SPLIT /* @min:%2esplit */](\"\\n\");\r\n for (var lp = 0; lp < lines[_DYN_LENGTH /* @min:%2elength */]; lp++) {\r\n var entry = lines[lp];\r\n if (lines[lp + 1]) {\r\n entry += \"@\" + lines[lp + 1];\r\n lp++;\r\n }\r\n stack.push(entry);\r\n }\r\n return {\r\n src: errorMessage,\r\n obj: stack\r\n };\r\n}\r\nfunction _getStackFromErrorObj(errorObj) {\r\n var details = null;\r\n if (errorObj) {\r\n try {\r\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 */\r\n if (errorObj[strStack]) {\r\n // Chrome/Firefox\r\n details = _convertStackObj(errorObj[strStack]);\r\n }\r\n else if (errorObj[strError] && errorObj[strError][strStack]) {\r\n // Edge error event provides the stack and error object\r\n details = _convertStackObj(errorObj[strError][strStack]);\r\n }\r\n else if (errorObj[\"exception\"] && errorObj.exception[strStack]) {\r\n details = _convertStackObj(errorObj.exception[strStack]);\r\n }\r\n else if (_isStackDetails(errorObj)) {\r\n details = errorObj;\r\n }\r\n else if (_isStackDetails(errorObj[strStackDetails])) {\r\n details = errorObj[strStackDetails];\r\n }\r\n else if (window && window[\"opera\"] && errorObj[strMessage]) {\r\n // Opera\r\n details = _getOperaStack(errorObj[_DYN_MESSAGE /* @min:%2emessage */]);\r\n }\r\n else if (errorObj[\"reason\"] && errorObj.reason[strStack]) {\r\n // UnhandledPromiseRejection\r\n details = _convertStackObj(errorObj.reason[strStack]);\r\n }\r\n else if (isString(errorObj)) {\r\n details = _convertStackObj(errorObj);\r\n }\r\n else {\r\n var evtMessage = errorObj[strMessage] || errorObj[strDescription] || \"\";\r\n if (isString(errorObj[strErrorSrc])) {\r\n if (evtMessage) {\r\n evtMessage += \"\\n\";\r\n }\r\n evtMessage += \" from \" + errorObj[strErrorSrc];\r\n }\r\n if (evtMessage) {\r\n details = _convertStackObj(evtMessage);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n // something unexpected happened so to avoid failing to report any error lets swallow the exception\r\n // and fallback to the callee/caller method\r\n details = _convertStackObj(e);\r\n }\r\n }\r\n return details || {\r\n src: \"\",\r\n obj: null\r\n };\r\n}\r\nfunction _formatStackTrace(stackDetails) {\r\n var stack = \"\";\r\n if (stackDetails) {\r\n if (stackDetails.obj) {\r\n arrForEach(stackDetails.obj, function (entry) {\r\n stack += entry + \"\\n\";\r\n });\r\n }\r\n else {\r\n stack = stackDetails.src || \"\";\r\n }\r\n }\r\n return stack;\r\n}\r\nfunction _parseStack(stack) {\r\n var parsedStack;\r\n var frames = stack.obj;\r\n if (frames && frames[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n parsedStack = [];\r\n var level_1 = 0;\r\n var totalSizeInBytes_1 = 0;\r\n arrForEach(frames, function (frame) {\r\n var theFrame = frame[_DYN_TO_STRING /* @min:%2etoString */]();\r\n if (_StackFrame.regex.test(theFrame)) {\r\n var parsedFrame = new _StackFrame(theFrame, level_1++);\r\n totalSizeInBytes_1 += parsedFrame[_DYN_SIZE_IN_BYTES /* @min:%2esizeInBytes */];\r\n parsedStack.push(parsedFrame);\r\n }\r\n });\r\n // DP Constraint - exception parsed stack must be < 32KB\r\n // remove frames from the middle to meet the threshold\r\n var exceptionParsedStackThreshold = 32 * 1024;\r\n if (totalSizeInBytes_1 > exceptionParsedStackThreshold) {\r\n var left = 0;\r\n var right = parsedStack[_DYN_LENGTH /* @min:%2elength */] - 1;\r\n var size = 0;\r\n var acceptedLeft = left;\r\n var acceptedRight = right;\r\n while (left < right) {\r\n // check size\r\n var lSize = parsedStack[left][_DYN_SIZE_IN_BYTES /* @min:%2esizeInBytes */];\r\n var rSize = parsedStack[right][_DYN_SIZE_IN_BYTES /* @min:%2esizeInBytes */];\r\n size += lSize + rSize;\r\n if (size > exceptionParsedStackThreshold) {\r\n // remove extra frames from the middle\r\n var howMany = acceptedRight - acceptedLeft + 1;\r\n parsedStack.splice(acceptedLeft, howMany);\r\n break;\r\n }\r\n // update pointers\r\n acceptedLeft = left;\r\n acceptedRight = right;\r\n left++;\r\n right--;\r\n }\r\n }\r\n }\r\n return parsedStack;\r\n}\r\nfunction _getErrorType(errorType) {\r\n // Gets the Error Type by passing the constructor (used to get the true type of native error object).\r\n var typeName = \"\";\r\n if (errorType) {\r\n typeName = errorType.typeName || errorType[_DYN_NAME /* @min:%2ename */] || \"\";\r\n if (!typeName) {\r\n try {\r\n var funcNameRegex = /function (.{1,200})\\(/;\r\n var results = (funcNameRegex).exec((errorType).constructor[_DYN_TO_STRING /* @min:%2etoString */]());\r\n typeName = (results && results[_DYN_LENGTH /* @min:%2elength */] > 1) ? results[1] : \"\";\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty -- Ignoring any failures as nothing we can do\r\n }\r\n }\r\n }\r\n return typeName;\r\n}\r\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 */\r\nexport function _formatErrorCode(errorObj) {\r\n if (errorObj) {\r\n try {\r\n if (!isString(errorObj)) {\r\n var errorType = _getErrorType(errorObj);\r\n var result = _stringify(errorObj, false);\r\n if (!result || result === \"{}\") {\r\n if (errorObj[strError]) {\r\n // Looks like an MS Error Event\r\n errorObj = errorObj[strError];\r\n errorType = _getErrorType(errorObj);\r\n }\r\n result = _stringify(errorObj, true);\r\n }\r\n if (strIndexOf(result, errorType) !== 0 && errorType !== \"String\") {\r\n return errorType + \":\" + result;\r\n }\r\n return result;\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty -- Ignoring any failures as nothing we can do\r\n }\r\n }\r\n // Fallback to just letting the object format itself into a string\r\n return \"\" + (errorObj || \"\");\r\n}\r\nvar Exception = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of the ExceptionTelemetry object\r\n */\r\n function Exception(logger, exception, properties, measurements, severityLevel, id) {\r\n this.aiDataContract = {\r\n ver: 1 /* FieldType.Required */,\r\n exceptions: 1 /* FieldType.Required */,\r\n severityLevel: 0 /* FieldType.Default */,\r\n properties: 0 /* FieldType.Default */,\r\n measurements: 0 /* FieldType.Default */\r\n };\r\n var _self = this;\r\n _self.ver = 2; // TODO: handle the CS\"4.0\" ==> breeze 2 conversion in a better way\r\n if (!_isExceptionInternal(exception)) {\r\n if (!properties) {\r\n properties = {};\r\n }\r\n _self[_DYN_EXCEPTIONS /* @min:%2eexceptions */] = [new _ExceptionDetails(logger, exception, properties)];\r\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\r\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\r\n if (severityLevel) {\r\n _self[_DYN_SEVERITY_LEVEL /* @min:%2eseverityLevel */] = severityLevel;\r\n }\r\n if (id) {\r\n _self.id = id;\r\n }\r\n }\r\n else {\r\n _self[_DYN_EXCEPTIONS /* @min:%2eexceptions */] = exception[_DYN_EXCEPTIONS /* @min:%2eexceptions */] || [];\r\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = exception[_DYN_PROPERTIES /* @min:%2eproperties */];\r\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = exception[_DYN_MEASUREMENTS /* @min:%2emeasurements */];\r\n if (exception[_DYN_SEVERITY_LEVEL /* @min:%2eseverityLevel */]) {\r\n _self[_DYN_SEVERITY_LEVEL /* @min:%2eseverityLevel */] = exception[_DYN_SEVERITY_LEVEL /* @min:%2eseverityLevel */];\r\n }\r\n if (exception.id) {\r\n _self.id = exception.id;\r\n }\r\n if (exception[_DYN_PROBLEM_GROUP /* @min:%2eproblemGroup */]) {\r\n _self[_DYN_PROBLEM_GROUP /* @min:%2eproblemGroup */] = exception[_DYN_PROBLEM_GROUP /* @min:%2eproblemGroup */];\r\n }\r\n // bool/int types, use isNullOrUndefined\r\n if (!isNullOrUndefined(exception[_DYN_IS_MANUAL /* @min:%2eisManual */])) {\r\n _self[_DYN_IS_MANUAL /* @min:%2eisManual */] = exception[_DYN_IS_MANUAL /* @min:%2eisManual */];\r\n }\r\n }\r\n }\r\n Exception.CreateAutoException = function (message, url, lineNumber, columnNumber, error, evt, stack, errorSrc) {\r\n var _a;\r\n var errorType = _getErrorType(error || evt || message);\r\n return _a = {},\r\n _a[_DYN_MESSAGE /* @min:message */] = _formatMessage(message, errorType),\r\n _a.url = url,\r\n _a.lineNumber = lineNumber,\r\n _a.columnNumber = columnNumber,\r\n _a.error = _formatErrorCode(error || evt || message),\r\n _a.evt = _formatErrorCode(evt || message),\r\n _a[_DYN_TYPE_NAME /* @min:typeName */] = errorType,\r\n _a.stackDetails = _getStackFromErrorObj(stack || error || evt),\r\n _a.errorSrc = errorSrc,\r\n _a;\r\n };\r\n Exception.CreateFromInterface = function (logger, exception, properties, measurements) {\r\n var exceptions = exception[_DYN_EXCEPTIONS /* @min:%2eexceptions */]\r\n && arrMap(exception[_DYN_EXCEPTIONS /* @min:%2eexceptions */], function (ex) { return _ExceptionDetails[_DYN__CREATE_FROM_INTERFA1 /* @min:%2eCreateFromInterface */](logger, ex); });\r\n var exceptionData = new Exception(logger, __assign(__assign({}, exception), { exceptions: exceptions }), properties, measurements);\r\n return exceptionData;\r\n };\r\n Exception.prototype.toInterface = function () {\r\n var _a;\r\n var _b = this, exceptions = _b.exceptions, properties = _b.properties, measurements = _b.measurements, severityLevel = _b.severityLevel, problemGroup = _b.problemGroup, id = _b.id, isManual = _b.isManual;\r\n var exceptionDetailsInterface = exceptions instanceof Array\r\n && arrMap(exceptions, function (exception) { return exception.toInterface(); })\r\n || undefined;\r\n return _a = {\r\n ver: \"4.0\"\r\n },\r\n _a[_DYN_EXCEPTIONS /* @min:exceptions */] = exceptionDetailsInterface,\r\n _a.severityLevel = severityLevel,\r\n _a.properties = properties,\r\n _a.measurements = measurements,\r\n _a.problemGroup = problemGroup,\r\n _a.id = id,\r\n _a.isManual = isManual,\r\n _a;\r\n };\r\n /**\r\n * Creates a simple exception with 1 stack frame. Useful for manual constracting of exception.\r\n */\r\n Exception.CreateSimpleException = function (message, typeName, assembly, fileName, details, line) {\r\n var _a;\r\n return {\r\n exceptions: [\r\n (_a = {},\r\n _a[_DYN_HAS_FULL_STACK /* @min:hasFullStack */] = true,\r\n _a.message = message,\r\n _a.stack = details,\r\n _a.typeName = typeName,\r\n _a)\r\n ]\r\n };\r\n };\r\n Exception.envelopeType = \"Microsoft.ApplicationInsights.{0}.Exception\";\r\n Exception.dataType = \"ExceptionData\";\r\n Exception.formatError = _formatErrorCode;\r\n return Exception;\r\n}());\r\nexport { Exception };\r\nvar _ExceptionDetails = /** @class */ (function () {\r\n function _ExceptionDetails(logger, exception, properties) {\r\n this.aiDataContract = {\r\n id: 0 /* FieldType.Default */,\r\n outerId: 0 /* FieldType.Default */,\r\n typeName: 1 /* FieldType.Required */,\r\n message: 1 /* FieldType.Required */,\r\n hasFullStack: 0 /* FieldType.Default */,\r\n stack: 0 /* FieldType.Default */,\r\n parsedStack: 2 /* FieldType.Array */\r\n };\r\n var _self = this;\r\n if (!_isExceptionDetailsInternal(exception)) {\r\n var error = exception;\r\n var evt = error && error.evt;\r\n if (!isError(error)) {\r\n error = error[strError] || evt || error;\r\n }\r\n _self[_DYN_TYPE_NAME /* @min:%2etypeName */] = dataSanitizeString(logger, _getErrorType(error)) || strNotSpecified;\r\n _self[_DYN_MESSAGE /* @min:%2emessage */] = dataSanitizeMessage(logger, _formatMessage(exception || error, _self[_DYN_TYPE_NAME /* @min:%2etypeName */])) || strNotSpecified;\r\n var stack = exception[strStackDetails] || _getStackFromErrorObj(exception);\r\n _self[_DYN_PARSED_STACK /* @min:%2eparsedStack */] = _parseStack(stack);\r\n // after parsedStack is inited, iterate over each frame object, sanitize its assembly field\r\n if (isArray(_self[_DYN_PARSED_STACK /* @min:%2eparsedStack */])) {\r\n arrMap(_self[_DYN_PARSED_STACK /* @min:%2eparsedStack */], function (frame) { return frame[_DYN_ASSEMBLY /* @min:%2eassembly */] = dataSanitizeString(logger, frame[_DYN_ASSEMBLY /* @min:%2eassembly */]); });\r\n }\r\n _self[strStack] = dataSanitizeException(logger, _formatStackTrace(stack));\r\n _self.hasFullStack = isArray(_self.parsedStack) && _self.parsedStack[_DYN_LENGTH /* @min:%2elength */] > 0;\r\n if (properties) {\r\n properties[_DYN_TYPE_NAME /* @min:%2etypeName */] = properties[_DYN_TYPE_NAME /* @min:%2etypeName */] || _self[_DYN_TYPE_NAME /* @min:%2etypeName */];\r\n }\r\n }\r\n else {\r\n _self[_DYN_TYPE_NAME /* @min:%2etypeName */] = exception[_DYN_TYPE_NAME /* @min:%2etypeName */];\r\n _self[_DYN_MESSAGE /* @min:%2emessage */] = exception[_DYN_MESSAGE /* @min:%2emessage */];\r\n _self[strStack] = exception[strStack];\r\n _self[_DYN_PARSED_STACK /* @min:%2eparsedStack */] = exception[_DYN_PARSED_STACK /* @min:%2eparsedStack */] || [];\r\n _self[_DYN_HAS_FULL_STACK /* @min:%2ehasFullStack */] = exception[_DYN_HAS_FULL_STACK /* @min:%2ehasFullStack */];\r\n }\r\n }\r\n _ExceptionDetails.prototype.toInterface = function () {\r\n var _a;\r\n var _self = this;\r\n var parsedStack = _self[_DYN_PARSED_STACK /* @min:%2eparsedStack */] instanceof Array\r\n && arrMap(_self[_DYN_PARSED_STACK /* @min:%2eparsedStack */], function (frame) { return frame.toInterface(); });\r\n var exceptionDetailsInterface = (_a = {\r\n id: _self.id,\r\n outerId: _self.outerId,\r\n typeName: _self[_DYN_TYPE_NAME /* @min:%2etypeName */],\r\n message: _self[_DYN_MESSAGE /* @min:%2emessage */],\r\n hasFullStack: _self[_DYN_HAS_FULL_STACK /* @min:%2ehasFullStack */],\r\n stack: _self[strStack]\r\n },\r\n _a[_DYN_PARSED_STACK /* @min:parsedStack */] = parsedStack || undefined,\r\n _a);\r\n return exceptionDetailsInterface;\r\n };\r\n _ExceptionDetails.CreateFromInterface = function (logger, exception) {\r\n var parsedStack = (exception[_DYN_PARSED_STACK /* @min:%2eparsedStack */] instanceof Array\r\n && arrMap(exception[_DYN_PARSED_STACK /* @min:%2eparsedStack */], function (frame) { return _StackFrame[_DYN__CREATE_FROM_INTERFA1 /* @min:%2eCreateFromInterface */](frame); }))\r\n || exception[_DYN_PARSED_STACK /* @min:%2eparsedStack */];\r\n var exceptionDetails = new _ExceptionDetails(logger, __assign(__assign({}, exception), { parsedStack: parsedStack }));\r\n return exceptionDetails;\r\n };\r\n return _ExceptionDetails;\r\n}());\r\nexport { _ExceptionDetails };\r\nvar _StackFrame = /** @class */ (function () {\r\n function _StackFrame(sourceFrame, level) {\r\n this.aiDataContract = {\r\n level: 1 /* FieldType.Required */,\r\n method: 1 /* FieldType.Required */,\r\n assembly: 0 /* FieldType.Default */,\r\n fileName: 0 /* FieldType.Default */,\r\n line: 0 /* FieldType.Default */\r\n };\r\n var _self = this;\r\n _self[_DYN_SIZE_IN_BYTES /* @min:%2esizeInBytes */] = 0;\r\n // Not converting this to isString() as typescript uses this logic to \"understand\" the different\r\n // types for the 2 different code paths\r\n if (typeof sourceFrame === \"string\") {\r\n var frame = sourceFrame;\r\n _self[_DYN_LEVEL /* @min:%2elevel */] = level;\r\n _self[_DYN_METHOD /* @min:%2emethod */] = NoMethod;\r\n _self[_DYN_ASSEMBLY /* @min:%2eassembly */] = strTrim(frame);\r\n _self[_DYN_FILE_NAME /* @min:%2efileName */] = \"\";\r\n _self[_DYN_LINE /* @min:%2eline */] = 0;\r\n var matches = frame.match(_StackFrame.regex);\r\n if (matches && matches[_DYN_LENGTH /* @min:%2elength */] >= 5) {\r\n _self[_DYN_METHOD /* @min:%2emethod */] = strTrim(matches[2]) || _self[_DYN_METHOD /* @min:%2emethod */];\r\n _self[_DYN_FILE_NAME /* @min:%2efileName */] = strTrim(matches[4]);\r\n _self[_DYN_LINE /* @min:%2eline */] = parseInt(matches[5]) || 0;\r\n }\r\n }\r\n else {\r\n _self[_DYN_LEVEL /* @min:%2elevel */] = sourceFrame[_DYN_LEVEL /* @min:%2elevel */];\r\n _self[_DYN_METHOD /* @min:%2emethod */] = sourceFrame[_DYN_METHOD /* @min:%2emethod */];\r\n _self[_DYN_ASSEMBLY /* @min:%2eassembly */] = sourceFrame[_DYN_ASSEMBLY /* @min:%2eassembly */];\r\n _self[_DYN_FILE_NAME /* @min:%2efileName */] = sourceFrame[_DYN_FILE_NAME /* @min:%2efileName */];\r\n _self[_DYN_LINE /* @min:%2eline */] = sourceFrame[_DYN_LINE /* @min:%2eline */];\r\n _self[_DYN_SIZE_IN_BYTES /* @min:%2esizeInBytes */] = 0;\r\n }\r\n _self.sizeInBytes += _self.method[_DYN_LENGTH /* @min:%2elength */];\r\n _self.sizeInBytes += _self.fileName[_DYN_LENGTH /* @min:%2elength */];\r\n _self.sizeInBytes += _self.assembly[_DYN_LENGTH /* @min:%2elength */];\r\n // todo: these might need to be removed depending on how the back-end settles on their size calculation\r\n _self[_DYN_SIZE_IN_BYTES /* @min:%2esizeInBytes */] += _StackFrame.baseSize;\r\n _self.sizeInBytes += _self.level.toString()[_DYN_LENGTH /* @min:%2elength */];\r\n _self.sizeInBytes += _self.line.toString()[_DYN_LENGTH /* @min:%2elength */];\r\n }\r\n _StackFrame.CreateFromInterface = function (frame) {\r\n return new _StackFrame(frame, null /* level is available in frame interface */);\r\n };\r\n _StackFrame.prototype.toInterface = function () {\r\n var _self = this;\r\n return {\r\n level: _self[_DYN_LEVEL /* @min:%2elevel */],\r\n method: _self[_DYN_METHOD /* @min:%2emethod */],\r\n assembly: _self[_DYN_ASSEMBLY /* @min:%2eassembly */],\r\n fileName: _self[_DYN_FILE_NAME /* @min:%2efileName */],\r\n line: _self[_DYN_LINE /* @min:%2eline */]\r\n };\r\n };\r\n // regex to match stack frames from ie/chrome/ff\r\n // methodName=$2, fileName=$4, lineNo=$5, column=$6\r\n _StackFrame.regex = /^([\\s]+at)?[\\s]{0,50}([^\\@\\()]+?)[\\s]{0,50}(\\@|\\()([^\\(\\n]+):([0-9]+):([0-9]+)(\\)?)$/;\r\n _StackFrame.baseSize = 58; // '{\"method\":\"\",\"level\":,\"assembly\":\"\",\"fileName\":\"\",\"line\":}'.length\r\n return _StackFrame;\r\n}());\r\nexport { _StackFrame };\r\n//# sourceMappingURL=Exception.js.map","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { utcNow } from \"./date\";\r\nimport { lazySafeGetInst } from \"./environment\";\r\nimport { ILazyValue, _globalLazyTestHooks } from \"./lazy\";\r\n\r\nlet _perf: ILazyValue\r\n\r\n/**\r\n * Identify whether the runtimne contains a `performance` object\r\n *\r\n * @since 0.4.4\r\n * @group Environment\r\n * @returns\r\n */\r\nexport function hasPerformance(): boolean {\r\n return !!getPerformance();\r\n}\r\n\r\n/**\r\n * Returns the global `performance` Object if available, which can be used to\r\n * gather performance information about the current document. It serves as the\r\n * point of exposure for the Performance Timeline API, the High Resolution Time\r\n * API, the Navigation Timing API, the User Timing API, and the Resource Timing API.\r\n *\r\n * @since 0.4.4\r\n * @group Environment\r\n * @returns The global performance object if available.\r\n */\r\nexport function getPerformance(): Performance {\r\n (!_perf || (!_perf.b && _globalLazyTestHooks && _globalLazyTestHooks.lzy)) && (_perf = lazySafeGetInst(\"performance\"));\r\n return _perf.v;\r\n}\r\n\r\n/**\r\n * Returns the number of milliseconds that has elapsed since the time origin, if\r\n * the runtime does not support the `performance` API it will fallback to return\r\n * the number of milliseconds since the unix epoch.\r\n *\r\n * @since 0.4.4\r\n * @group Timer\r\n *\r\n * @returns The number of milliseconds as a `DOMHighResTimeStamp` double value or\r\n * an integer depending on the runtime.\r\n * @example\r\n * ```ts\r\n * let now = perfNow();\r\n * ```\r\n */\r\nexport function perfNow(): number {\r\n let perf = getPerformance();\r\n if (perf && perf.now) {\r\n return perf.now();\r\n }\r\n\r\n return utcNow();\r\n}\r\n\r\n/**\r\n * Return the number of milliseconds that have elapsed since the provided `startTime`\r\n * the `startTime` MUST be obtained from {@link perfNow} to ensure the correct elapsed\r\n * value is returned.\r\n *\r\n * @since 0.4.4\r\n * @group Timer\r\n *\r\n * @param startTime - The startTime obtained from `perfNow`\r\n * @returns The number of milliseconds that have elapsed since the startTime.\r\n * @example\r\n * ```ts\r\n * let start = perfNow();\r\n * // Do some work\r\n * let totalTime = elapsedTime(start);\r\n * ```\r\n */\r\nexport function elapsedTime(startTime: number): number {\r\n return perfNow() - startTime;\r\n}","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { createValueMap } from \"@microsoft/applicationinsights-core-js\";\r\nexport var RequestHeaders = createValueMap({\r\n requestContextHeader: [0 /* eRequestHeaders.requestContextHeader */, \"Request-Context\"],\r\n requestContextTargetKey: [1 /* eRequestHeaders.requestContextTargetKey */, \"appId\"],\r\n requestContextAppIdFormat: [2 /* eRequestHeaders.requestContextAppIdFormat */, \"appId=cid-v1:\"],\r\n requestIdHeader: [3 /* eRequestHeaders.requestIdHeader */, \"Request-Id\"],\r\n traceParentHeader: [4 /* eRequestHeaders.traceParentHeader */, \"traceparent\"],\r\n traceStateHeader: [5 /* eRequestHeaders.traceStateHeader */, \"tracestate\"],\r\n sdkContextHeader: [6 /* eRequestHeaders.sdkContextHeader */, \"Sdk-Context\"],\r\n sdkContextHeaderAppIdRequest: [7 /* eRequestHeaders.sdkContextHeaderAppIdRequest */, \"appId\"],\r\n requestContextHeaderLowerCase: [8 /* eRequestHeaders.requestContextHeaderLowerCase */, \"request-context\"]\r\n});\r\n//# sourceMappingURL=RequestResponseHeaders.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { getDocument, isString } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_LENGTH, _DYN_PATHNAME, _DYN_TO_LOWER_CASE } from \"./__DynamicConstants\";\r\nvar _document = getDocument() || {};\r\nvar _htmlAnchorIdx = 0;\r\n// Use an array of temporary values as it's possible for multiple calls to parseUrl() will be called with different URLs\r\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\r\nvar _htmlAnchorElement = [null, null, null, null, null];\r\nexport function urlParseUrl(url) {\r\n var anchorIdx = _htmlAnchorIdx;\r\n var anchorCache = _htmlAnchorElement;\r\n var tempAnchor = anchorCache[anchorIdx];\r\n if (!_document.createElement) {\r\n // Always create the temp instance if createElement is not available\r\n tempAnchor = { host: urlParseHost(url, true) };\r\n }\r\n else if (!anchorCache[anchorIdx]) {\r\n // Create and cache the unattached anchor instance\r\n tempAnchor = anchorCache[anchorIdx] = _document.createElement(\"a\");\r\n }\r\n tempAnchor.href = url;\r\n // Move the cache index forward\r\n anchorIdx++;\r\n if (anchorIdx >= anchorCache[_DYN_LENGTH /* @min:%2elength */]) {\r\n anchorIdx = 0;\r\n }\r\n _htmlAnchorIdx = anchorIdx;\r\n return tempAnchor;\r\n}\r\nexport function urlGetAbsoluteUrl(url) {\r\n var result;\r\n var a = urlParseUrl(url);\r\n if (a) {\r\n result = a.href;\r\n }\r\n return result;\r\n}\r\nexport function urlGetPathName(url) {\r\n var result;\r\n var a = urlParseUrl(url);\r\n if (a) {\r\n result = a[_DYN_PATHNAME /* @min:%2epathname */];\r\n }\r\n return result;\r\n}\r\nexport function urlGetCompleteUrl(method, absoluteUrl) {\r\n if (method) {\r\n return method.toUpperCase() + \" \" + absoluteUrl;\r\n }\r\n return absoluteUrl;\r\n}\r\n// Fallback method to grab host from url if document.createElement method is not available\r\nexport function urlParseHost(url, inclPort) {\r\n var fullHost = urlParseFullHost(url, inclPort) || \"\";\r\n if (fullHost) {\r\n var match = fullHost.match(/(www\\d{0,5}\\.)?([^\\/:]{1,256})(:\\d{1,20})?/i);\r\n if (match != null && match[_DYN_LENGTH /* @min:%2elength */] > 3 && isString(match[2]) && match[2][_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n return match[2] + (match[3] || \"\");\r\n }\r\n }\r\n return fullHost;\r\n}\r\nexport function urlParseFullHost(url, inclPort) {\r\n var result = null;\r\n if (url) {\r\n var match = url.match(/(\\w{1,150}):\\/\\/([^\\/:]{1,256})(:\\d{1,20})?/i);\r\n if (match != null && match[_DYN_LENGTH /* @min:%2elength */] > 2 && isString(match[2]) && match[2][_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n result = match[2] || \"\";\r\n if (inclPort && match[_DYN_LENGTH /* @min:%2elength */] > 2) {\r\n var protocol = (match[1] || \"\")[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\r\n var port = match[3] || \"\";\r\n // IE includes the standard port so pass it off if it's the same as the protocol\r\n if (protocol === \"http\" && port === \":80\") {\r\n port = \"\";\r\n }\r\n else if (protocol === \"https\" && port === \":443\") {\r\n port = \"\";\r\n }\r\n result += port;\r\n }\r\n }\r\n }\r\n return result;\r\n}\r\n//# sourceMappingURL=UrlHelperFuncs.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { arrForEach, arrIndexOf, dateNow, getPerformance, isNullOrUndefined, isValidSpanId, isValidTraceId } from \"@microsoft/applicationinsights-core-js\";\r\nimport { strIndexOf } from \"@nevware21/ts-utils\";\r\nimport { DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH } from \"./Constants\";\r\nimport { RequestHeaders } from \"./RequestResponseHeaders\";\r\nimport { dataSanitizeString } from \"./Telemetry/Common/DataSanitizer\";\r\nimport { urlParseFullHost, urlParseUrl } from \"./UrlHelperFuncs\";\r\nimport { _DYN_CORRELATION_HEADER_E0, _DYN_LENGTH, _DYN_NAME, _DYN_PATHNAME, _DYN_SPLIT, _DYN_TO_LOWER_CASE } from \"./__DynamicConstants\";\r\n// listing only non-geo specific locations\r\nvar _internalEndpoints = [\r\n DEFAULT_BREEZE_ENDPOINT + DEFAULT_BREEZE_PATH,\r\n \"https://breeze.aimon.applicationinsights.io\" + DEFAULT_BREEZE_PATH,\r\n \"https://dc-int.services.visualstudio.com\" + DEFAULT_BREEZE_PATH\r\n];\r\nvar _correlationIdPrefix = \"cid-v1:\";\r\nexport function isInternalApplicationInsightsEndpoint(endpointUrl) {\r\n return arrIndexOf(_internalEndpoints, endpointUrl[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]()) !== -1;\r\n}\r\nexport function correlationIdSetPrefix(prefix) {\r\n _correlationIdPrefix = prefix;\r\n}\r\nexport function correlationIdGetPrefix() {\r\n return _correlationIdPrefix;\r\n}\r\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 */\r\nexport function correlationIdCanIncludeCorrelationHeader(config, requestUrl, currentHost) {\r\n if (!requestUrl || (config && config.disableCorrelationHeaders)) {\r\n return false;\r\n }\r\n if (config && config[_DYN_CORRELATION_HEADER_E0 /* @min:%2ecorrelationHeaderExcludePatterns */]) {\r\n for (var i = 0; i < config.correlationHeaderExcludePatterns[_DYN_LENGTH /* @min:%2elength */]; i++) {\r\n if (config[_DYN_CORRELATION_HEADER_E0 /* @min:%2ecorrelationHeaderExcludePatterns */][i].test(requestUrl)) {\r\n return false;\r\n }\r\n }\r\n }\r\n var requestHost = urlParseUrl(requestUrl).host[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\r\n if (requestHost && (strIndexOf(requestHost, \":443\") !== -1 || strIndexOf(requestHost, \":80\") !== -1)) {\r\n // [Bug #1260] IE can include the port even for http and https URLs so if present\r\n // try and parse it to remove if it matches the default protocol port\r\n requestHost = (urlParseFullHost(requestUrl, true) || \"\")[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\r\n }\r\n if ((!config || !config.enableCorsCorrelation) && (requestHost && requestHost !== currentHost)) {\r\n return false;\r\n }\r\n var includedDomains = config && config.correlationHeaderDomains;\r\n if (includedDomains) {\r\n var matchExists_1;\r\n arrForEach(includedDomains, function (domain) {\r\n var regex = new RegExp(domain.toLowerCase().replace(/\\\\/g, \"\\\\\\\\\").replace(/\\./g, \"\\\\.\").replace(/\\*/g, \".*\"));\r\n matchExists_1 = matchExists_1 || regex.test(requestHost);\r\n });\r\n if (!matchExists_1) {\r\n return false;\r\n }\r\n }\r\n var excludedDomains = config && config.correlationHeaderExcludedDomains;\r\n if (!excludedDomains || excludedDomains[_DYN_LENGTH /* @min:%2elength */] === 0) {\r\n return true;\r\n }\r\n for (var i = 0; i < excludedDomains[_DYN_LENGTH /* @min:%2elength */]; i++) {\r\n var regex = new RegExp(excludedDomains[i].toLowerCase().replace(/\\\\/g, \"\\\\\\\\\").replace(/\\./g, \"\\\\.\").replace(/\\*/g, \".*\"));\r\n if (regex.test(requestHost)) {\r\n return false;\r\n }\r\n }\r\n // if we don't know anything about the requestHost, require the user to use included/excludedDomains.\r\n // Previously we always returned false for a falsy requestHost\r\n return requestHost && requestHost[_DYN_LENGTH /* @min:%2elength */] > 0;\r\n}\r\n/**\r\n * Combines target appId and target role name from response header.\r\n */\r\nexport function correlationIdGetCorrelationContext(responseHeader) {\r\n if (responseHeader) {\r\n var correlationId = correlationIdGetCorrelationContextValue(responseHeader, RequestHeaders[1 /* eRequestHeaders.requestContextTargetKey */]);\r\n if (correlationId && correlationId !== _correlationIdPrefix) {\r\n return correlationId;\r\n }\r\n }\r\n}\r\n/**\r\n * Gets key from correlation response header\r\n */\r\nexport function correlationIdGetCorrelationContextValue(responseHeader, key) {\r\n if (responseHeader) {\r\n var keyValues = responseHeader[_DYN_SPLIT /* @min:%2esplit */](\",\");\r\n for (var i = 0; i < keyValues[_DYN_LENGTH /* @min:%2elength */]; ++i) {\r\n var keyValue = keyValues[i][_DYN_SPLIT /* @min:%2esplit */](\"=\");\r\n if (keyValue[_DYN_LENGTH /* @min:%2elength */] === 2 && keyValue[0] === key) {\r\n return keyValue[1];\r\n }\r\n }\r\n }\r\n}\r\nexport function AjaxHelperParseDependencyPath(logger, absoluteUrl, method, commandName) {\r\n var target, name = commandName, data = commandName;\r\n if (absoluteUrl && absoluteUrl[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n var parsedUrl = urlParseUrl(absoluteUrl);\r\n target = parsedUrl.host;\r\n if (!name) {\r\n if (parsedUrl[_DYN_PATHNAME /* @min:%2epathname */] != null) {\r\n var pathName = (parsedUrl.pathname[_DYN_LENGTH /* @min:%2elength */] === 0) ? \"/\" : parsedUrl[_DYN_PATHNAME /* @min:%2epathname */];\r\n if (pathName.charAt(0) !== \"/\") {\r\n pathName = \"/\" + pathName;\r\n }\r\n data = parsedUrl[_DYN_PATHNAME /* @min:%2epathname */];\r\n name = dataSanitizeString(logger, method ? method + \" \" + pathName : pathName);\r\n }\r\n else {\r\n name = dataSanitizeString(logger, absoluteUrl);\r\n }\r\n }\r\n }\r\n else {\r\n target = commandName;\r\n name = commandName;\r\n }\r\n return {\r\n target: target,\r\n name: name,\r\n data: data\r\n };\r\n}\r\nexport function dateTimeUtilsNow() {\r\n // returns the window or webworker performance object\r\n var perf = getPerformance();\r\n if (perf && perf.now && perf.timing) {\r\n var now = perf.now() + perf.timing.navigationStart;\r\n // Known issue with IE where this calculation can be negative, so if it is then ignore and fallback\r\n if (now > 0) {\r\n return now;\r\n }\r\n }\r\n return dateNow();\r\n}\r\nexport function dateTimeUtilsDuration(start, end) {\r\n var result = null;\r\n if (start !== 0 && end !== 0 && !isNullOrUndefined(start) && !isNullOrUndefined(end)) {\r\n result = end - start;\r\n }\r\n return result;\r\n}\r\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 */\r\nexport function createDistributedTraceContextFromTrace(telemetryTrace, parentCtx) {\r\n var trace = telemetryTrace || {};\r\n return {\r\n getName: function () {\r\n return trace[_DYN_NAME /* @min:%2ename */];\r\n },\r\n setName: function (newValue) {\r\n parentCtx && parentCtx.setName(newValue);\r\n trace[_DYN_NAME /* @min:%2ename */] = newValue;\r\n },\r\n getTraceId: function () {\r\n return trace.traceID;\r\n },\r\n setTraceId: function (newValue) {\r\n parentCtx && parentCtx.setTraceId(newValue);\r\n if (isValidTraceId(newValue)) {\r\n trace.traceID = newValue;\r\n }\r\n },\r\n getSpanId: function () {\r\n return trace.parentID;\r\n },\r\n setSpanId: function (newValue) {\r\n parentCtx && parentCtx.setSpanId(newValue);\r\n if (isValidSpanId(newValue)) {\r\n trace.parentID = newValue;\r\n }\r\n },\r\n getTraceFlags: function () {\r\n return trace.traceFlags;\r\n },\r\n setTraceFlags: function (newTraceFlags) {\r\n parentCtx && parentCtx.setTraceFlags(newTraceFlags);\r\n trace.traceFlags = newTraceFlags;\r\n }\r\n };\r\n}\r\n//# sourceMappingURL=Util.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { msToTimeSpan } from \"../HelperFuncs\";\r\nimport { AjaxHelperParseDependencyPath } from \"../Util\";\r\nimport { _DYN_DURATION, _DYN_MEASUREMENTS, _DYN_NAME, _DYN_PROPERTIES } from \"../__DynamicConstants\";\r\nimport { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString, dataSanitizeUrl } from \"./Common/DataSanitizer\";\r\nvar RemoteDependencyData = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of the RemoteDependencyData object\r\n */\r\n function RemoteDependencyData(logger, id, absoluteUrl, commandName, value, success, resultCode, method, requestAPI, correlationContext, properties, measurements) {\r\n if (requestAPI === void 0) { requestAPI = \"Ajax\"; }\r\n this.aiDataContract = {\r\n id: 1 /* FieldType.Required */,\r\n ver: 1 /* FieldType.Required */,\r\n name: 0 /* FieldType.Default */,\r\n resultCode: 0 /* FieldType.Default */,\r\n duration: 0 /* FieldType.Default */,\r\n success: 0 /* FieldType.Default */,\r\n data: 0 /* FieldType.Default */,\r\n target: 0 /* FieldType.Default */,\r\n type: 0 /* FieldType.Default */,\r\n properties: 0 /* FieldType.Default */,\r\n measurements: 0 /* FieldType.Default */,\r\n kind: 0 /* FieldType.Default */,\r\n value: 0 /* FieldType.Default */,\r\n count: 0 /* FieldType.Default */,\r\n min: 0 /* FieldType.Default */,\r\n max: 0 /* FieldType.Default */,\r\n stdDev: 0 /* FieldType.Default */,\r\n dependencyKind: 0 /* FieldType.Default */,\r\n dependencySource: 0 /* FieldType.Default */,\r\n commandName: 0 /* FieldType.Default */,\r\n dependencyTypeName: 0 /* FieldType.Default */\r\n };\r\n var _self = this;\r\n _self.ver = 2;\r\n _self.id = id;\r\n _self[_DYN_DURATION /* @min:%2eduration */] = msToTimeSpan(value);\r\n _self.success = success;\r\n _self.resultCode = resultCode + \"\";\r\n _self.type = dataSanitizeString(logger, requestAPI);\r\n var dependencyFields = AjaxHelperParseDependencyPath(logger, absoluteUrl, method, commandName);\r\n _self.data = dataSanitizeUrl(logger, commandName) || dependencyFields.data; // get a value from hosturl if commandName not available\r\n _self.target = dataSanitizeString(logger, dependencyFields.target);\r\n if (correlationContext) {\r\n _self.target = \"\".concat(_self.target, \" | \").concat(correlationContext);\r\n }\r\n _self[_DYN_NAME /* @min:%2ename */] = dataSanitizeString(logger, dependencyFields[_DYN_NAME /* @min:%2ename */]);\r\n _self[_DYN_PROPERTIES /* @min:%2eproperties */] = dataSanitizeProperties(logger, properties);\r\n _self[_DYN_MEASUREMENTS /* @min:%2emeasurements */] = dataSanitizeMeasurements(logger, measurements);\r\n }\r\n RemoteDependencyData.envelopeType = \"Microsoft.ApplicationInsights.{0}.RemoteDependency\";\r\n RemoteDependencyData.dataType = \"RemoteDependencyData\";\r\n return RemoteDependencyData;\r\n}());\r\nexport { RemoteDependencyData };\r\n//# sourceMappingURL=RemoteDependencyData.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { getDocument, isFunction } from \"@microsoft/applicationinsights-core-js\";\r\nexport function createDomEvent(eventName) {\r\n var event = null;\r\n if (isFunction(Event)) { // Use Event constructor when available\r\n event = new Event(eventName);\r\n }\r\n else { // Event has no constructor in IE\r\n var doc = getDocument();\r\n if (doc && doc.createEvent) {\r\n event = doc.createEvent(\"Event\");\r\n event.initEvent(eventName, true, true);\r\n }\r\n }\r\n return event;\r\n}\r\n//# sourceMappingURL=DomHelperFuncs.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { arrForEach, arrIndexOf, getDocument, getWindow, isArray, objForEachKey, objKeys } from \"@nevware21/ts-utils\";\r\nimport { _DYN_HANDLER, _DYN_LENGTH, _DYN_NAME, _DYN_PUSH, _DYN_REPLACE, _DYN_SPLICE, _DYN_SPLIT, _DYN_TYPE } from \"../__DynamicConstants\";\r\nimport { createElmNodeData, createUniqueNamespace } from \"./DataCacheHelper\";\r\nimport { STR_EMPTY } from \"./InternalConstants\";\r\n// Added to help with minfication\r\nvar strOnPrefix = \"on\";\r\nvar strAttachEvent = \"attachEvent\";\r\nvar strAddEventHelper = \"addEventListener\";\r\nvar strDetachEvent = \"detachEvent\";\r\nvar strRemoveEventListener = \"removeEventListener\";\r\nvar strEvents = \"events\";\r\nvar strVisibilityChangeEvt = \"visibilitychange\";\r\nvar strPageHide = \"pagehide\";\r\nvar strPageShow = \"pageshow\";\r\nvar strUnload = \"unload\";\r\nvar strBeforeUnload = \"beforeunload\";\r\nvar strPageHideNamespace = createUniqueNamespace(\"aiEvtPageHide\");\r\nvar strPageShowNamespace = createUniqueNamespace(\"aiEvtPageShow\");\r\nvar rRemoveEmptyNs = /\\.[\\.]+/g;\r\nvar rRemoveTrailingEmptyNs = /[\\.]+$/;\r\nvar _guid = 1;\r\nvar elmNodeData = createElmNodeData(\"events\");\r\nvar eventNamespace = /^([^.]*)(?:\\.(.+)|)/;\r\nfunction _normalizeNamespace(name) {\r\n if (name && name[_DYN_REPLACE /* @min:%2ereplace */]) {\r\n return name[_DYN_REPLACE /* @min:%2ereplace */](/^[\\s\\.]+|(?=[\\s\\.])[\\.\\s]+$/g, STR_EMPTY);\r\n }\r\n return name;\r\n}\r\nfunction _getEvtNamespace(eventName, evtNamespace) {\r\n var _a;\r\n if (evtNamespace) {\r\n var theNamespace_1 = STR_EMPTY;\r\n if (isArray(evtNamespace)) {\r\n theNamespace_1 = STR_EMPTY;\r\n arrForEach(evtNamespace, function (name) {\r\n name = _normalizeNamespace(name);\r\n if (name) {\r\n if (name[0] !== \".\") {\r\n name = \".\" + name;\r\n }\r\n theNamespace_1 += name;\r\n }\r\n });\r\n }\r\n else {\r\n theNamespace_1 = _normalizeNamespace(evtNamespace);\r\n }\r\n if (theNamespace_1) {\r\n if (theNamespace_1[0] !== \".\") {\r\n theNamespace_1 = \".\" + theNamespace_1;\r\n }\r\n // We may only have the namespace and not an eventName\r\n eventName = (eventName || STR_EMPTY) + theNamespace_1;\r\n }\r\n }\r\n var parsedEvent = (eventNamespace.exec(eventName || STR_EMPTY) || []);\r\n return _a = {},\r\n _a[_DYN_TYPE /* @min:type */] = parsedEvent[1],\r\n _a.ns = ((parsedEvent[2] || STR_EMPTY).replace(rRemoveEmptyNs, \".\").replace(rRemoveTrailingEmptyNs, STR_EMPTY)[_DYN_SPLIT /* @min:%2esplit */](\".\").sort()).join(\".\"),\r\n _a;\r\n}\r\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 */\r\nexport function __getRegisteredEvents(target, eventName, evtNamespace) {\r\n var theEvents = [];\r\n var eventCache = elmNodeData.get(target, strEvents, {}, false);\r\n var evtName = _getEvtNamespace(eventName, evtNamespace);\r\n objForEachKey(eventCache, function (evtType, registeredEvents) {\r\n arrForEach(registeredEvents, function (value) {\r\n var _a;\r\n if (!evtName[_DYN_TYPE /* @min:%2etype */] || evtName[_DYN_TYPE /* @min:%2etype */] === value.evtName[_DYN_TYPE /* @min:%2etype */]) {\r\n if (!evtName.ns || evtName.ns === evtName.ns) {\r\n theEvents[_DYN_PUSH /* @min:%2epush */]((_a = {},\r\n _a[_DYN_NAME /* @min:name */] = value.evtName[_DYN_TYPE /* @min:%2etype */] + (value.evtName.ns ? \".\" + value.evtName.ns : STR_EMPTY),\r\n _a.handler = value[_DYN_HANDLER /* @min:%2ehandler */],\r\n _a));\r\n }\r\n }\r\n });\r\n });\r\n return theEvents;\r\n}\r\n// Exported for internal unit testing only\r\nfunction _getRegisteredEvents(target, evtName, addDefault) {\r\n if (addDefault === void 0) { addDefault = true; }\r\n var aiEvts = elmNodeData.get(target, strEvents, {}, addDefault);\r\n var registeredEvents = aiEvts[evtName];\r\n if (!registeredEvents) {\r\n registeredEvents = aiEvts[evtName] = [];\r\n }\r\n return registeredEvents;\r\n}\r\nfunction _doDetach(obj, evtName, handlerRef, useCapture) {\r\n if (obj && evtName && evtName[_DYN_TYPE /* @min:%2etype */]) {\r\n if (obj[strRemoveEventListener]) {\r\n obj[strRemoveEventListener](evtName[_DYN_TYPE /* @min:%2etype */], handlerRef, useCapture);\r\n }\r\n else if (obj[strDetachEvent]) {\r\n obj[strDetachEvent](strOnPrefix + evtName[_DYN_TYPE /* @min:%2etype */], handlerRef);\r\n }\r\n }\r\n}\r\nfunction _doAttach(obj, evtName, handlerRef, useCapture) {\r\n var result = false;\r\n if (obj && evtName && evtName[_DYN_TYPE /* @min:%2etype */] && handlerRef) {\r\n if (obj[strAddEventHelper]) {\r\n // all browsers except IE before version 9\r\n obj[strAddEventHelper](evtName[_DYN_TYPE /* @min:%2etype */], handlerRef, useCapture);\r\n result = true;\r\n }\r\n else if (obj[strAttachEvent]) {\r\n // IE before version 9\r\n obj[strAttachEvent](strOnPrefix + evtName[_DYN_TYPE /* @min:%2etype */], handlerRef);\r\n result = true;\r\n }\r\n }\r\n return result;\r\n}\r\nfunction _doUnregister(target, events, evtName, unRegFn) {\r\n var idx = events[_DYN_LENGTH /* @min:%2elength */];\r\n while (idx--) {\r\n var theEvent = events[idx];\r\n if (theEvent) {\r\n if (!evtName.ns || evtName.ns === theEvent.evtName.ns) {\r\n if (!unRegFn || unRegFn(theEvent)) {\r\n _doDetach(target, theEvent.evtName, theEvent[_DYN_HANDLER /* @min:%2ehandler */], theEvent.capture);\r\n // Remove the registered event\r\n events[_DYN_SPLICE /* @min:%2esplice */](idx, 1);\r\n }\r\n }\r\n }\r\n }\r\n}\r\nfunction _unregisterEvents(target, evtName, unRegFn) {\r\n if (evtName[_DYN_TYPE /* @min:%2etype */]) {\r\n _doUnregister(target, _getRegisteredEvents(target, evtName[_DYN_TYPE /* @min:%2etype */]), evtName, unRegFn);\r\n }\r\n else {\r\n var eventCache = elmNodeData.get(target, strEvents, {});\r\n objForEachKey(eventCache, function (evtType, events) {\r\n _doUnregister(target, events, evtName, unRegFn);\r\n });\r\n // Cleanup\r\n if (objKeys(eventCache)[_DYN_LENGTH /* @min:%2elength */] === 0) {\r\n elmNodeData.kill(target, strEvents);\r\n }\r\n }\r\n}\r\nexport function mergeEvtNamespace(theNamespace, namespaces) {\r\n var newNamespaces;\r\n if (namespaces) {\r\n if (isArray(namespaces)) {\r\n newNamespaces = [theNamespace].concat(namespaces);\r\n }\r\n else {\r\n newNamespaces = [theNamespace, namespaces];\r\n }\r\n // resort the namespaces so they are always in order\r\n newNamespaces = (_getEvtNamespace(\"xx\", newNamespaces).ns)[_DYN_SPLIT /* @min:%2esplit */](\".\");\r\n }\r\n else {\r\n newNamespaces = theNamespace;\r\n }\r\n return newNamespaces;\r\n}\r\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 */\r\nexport function eventOn(target, eventName, handlerRef, evtNamespace, useCapture) {\r\n var _a;\r\n if (useCapture === void 0) { useCapture = false; }\r\n var result = false;\r\n if (target) {\r\n try {\r\n var evtName = _getEvtNamespace(eventName, evtNamespace);\r\n result = _doAttach(target, evtName, handlerRef, useCapture);\r\n if (result && elmNodeData.accept(target)) {\r\n var registeredEvent = (_a = {\r\n guid: _guid++,\r\n evtName: evtName\r\n },\r\n _a[_DYN_HANDLER /* @min:handler */] = handlerRef,\r\n _a.capture = useCapture,\r\n _a);\r\n _getRegisteredEvents(target, evtName.type)[_DYN_PUSH /* @min:%2epush */](registeredEvent);\r\n }\r\n }\r\n catch (e) {\r\n // Just Ignore any error so that we don't break any execution path\r\n }\r\n }\r\n return result;\r\n}\r\n/**\r\n * Removes an event handler for the specified event\r\n * @param Object - to remove the event from\r\n * @param eventName - {string} - 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 - {any} - 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 */\r\nexport function eventOff(target, eventName, handlerRef, evtNamespace, useCapture) {\r\n if (useCapture === void 0) { useCapture = false; }\r\n if (target) {\r\n try {\r\n var evtName_1 = _getEvtNamespace(eventName, evtNamespace);\r\n var found_1 = false;\r\n _unregisterEvents(target, evtName_1, function (regEvent) {\r\n if ((evtName_1.ns && !handlerRef) || regEvent[_DYN_HANDLER /* @min:%2ehandler */] === handlerRef) {\r\n found_1 = true;\r\n return true;\r\n }\r\n return false;\r\n });\r\n if (!found_1) {\r\n // fallback to try and remove as requested\r\n _doDetach(target, evtName_1, handlerRef, useCapture);\r\n }\r\n }\r\n catch (e) {\r\n // Just Ignore any error so that we don't break any execution path\r\n }\r\n }\r\n}\r\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 */\r\nexport function attachEvent(obj, eventNameWithoutOn, handlerRef, useCapture) {\r\n if (useCapture === void 0) { useCapture = false; }\r\n return eventOn(obj, eventNameWithoutOn, handlerRef, null, useCapture);\r\n}\r\n/**\r\n * Removes an event handler for the specified event\r\n * @param Object - to remove the event from\r\n * @param eventNameWithoutOn - {string} - 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 - {any} - 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 */\r\nexport function detachEvent(obj, eventNameWithoutOn, handlerRef, useCapture) {\r\n if (useCapture === void 0) { useCapture = false; }\r\n eventOff(obj, eventNameWithoutOn, handlerRef, null, useCapture);\r\n}\r\n/**\r\n * Trys to add an event handler for the specified event to the window, body and document\r\n * @param eventName - {string} - The name of the event\r\n * @param callback - {any} - 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 * @return {boolean} - true if the handler was successfully added\r\n */\r\nexport function addEventHandler(eventName, callback, evtNamespace) {\r\n var result = false;\r\n var w = getWindow();\r\n if (w) {\r\n result = eventOn(w, eventName, callback, evtNamespace);\r\n result = eventOn(w[\"body\"], eventName, callback, evtNamespace) || result;\r\n }\r\n var doc = getDocument();\r\n if (doc) {\r\n result = eventOn(doc, eventName, callback, evtNamespace) || result;\r\n }\r\n return result;\r\n}\r\n/**\r\n * Trys to remove event handler(s) for the specified event/namespace to the window, body and document\r\n * @param eventName - {string} - 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 - {any} - - 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 */\r\nexport function removeEventHandler(eventName, callback, evtNamespace) {\r\n var w = getWindow();\r\n if (w) {\r\n eventOff(w, eventName, callback, evtNamespace);\r\n eventOff(w[\"body\"], eventName, callback, evtNamespace);\r\n }\r\n var doc = getDocument();\r\n if (doc) {\r\n eventOff(doc, eventName, callback, evtNamespace);\r\n }\r\n}\r\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 */\r\nfunction _addEventListeners(events, listener, excludeEvents, evtNamespace) {\r\n var added = false;\r\n if (listener && events && events[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n arrForEach(events, function (name) {\r\n if (name) {\r\n if (!excludeEvents || arrIndexOf(excludeEvents, name) === -1) {\r\n added = addEventHandler(name, listener, evtNamespace) || added;\r\n }\r\n }\r\n });\r\n }\r\n return added;\r\n}\r\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 */\r\nexport function addEventListeners(events, listener, excludeEvents, evtNamespace) {\r\n var added = false;\r\n if (listener && events && isArray(events)) {\r\n added = _addEventListeners(events, listener, excludeEvents, evtNamespace);\r\n if (!added && excludeEvents && excludeEvents[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n // Failed to add any listeners and we excluded some, so just attempt to add the excluded events\r\n added = _addEventListeners(events, listener, null, evtNamespace);\r\n }\r\n }\r\n return added;\r\n}\r\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 */\r\nexport function removeEventListeners(events, listener, evtNamespace) {\r\n if (events && isArray(events)) {\r\n arrForEach(events, function (name) {\r\n if (name) {\r\n removeEventHandler(name, listener, evtNamespace);\r\n }\r\n });\r\n }\r\n}\r\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 */\r\nexport function addPageUnloadEventListener(listener, excludeEvents, evtNamespace) {\r\n // Hook the unload event for the document, window and body to ensure that the client events are flushed to the server\r\n // As just hooking the window does not always fire (on chrome) for page navigation's.\r\n return addEventListeners([strBeforeUnload, strUnload, strPageHide], listener, excludeEvents, evtNamespace);\r\n}\r\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 */\r\nexport function removePageUnloadEventListener(listener, evtNamespace) {\r\n removeEventListeners([strBeforeUnload, strUnload, strPageHide], listener, evtNamespace);\r\n}\r\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 */\r\nexport function addPageHideEventListener(listener, excludeEvents, evtNamespace) {\r\n function _handlePageVisibility(evt) {\r\n var doc = getDocument();\r\n if (listener && doc && doc.visibilityState === \"hidden\") {\r\n listener(evt);\r\n }\r\n }\r\n // add the unique page show namespace to any provided namespace so we can only remove the ones added by \"pagehide\"\r\n var newNamespaces = mergeEvtNamespace(strPageHideNamespace, evtNamespace);\r\n var pageUnloadAdded = _addEventListeners([strPageHide], listener, excludeEvents, newNamespaces);\r\n if (!excludeEvents || arrIndexOf(excludeEvents, strVisibilityChangeEvt) === -1) {\r\n pageUnloadAdded = _addEventListeners([strVisibilityChangeEvt], _handlePageVisibility, excludeEvents, newNamespaces) || pageUnloadAdded;\r\n }\r\n if (!pageUnloadAdded && excludeEvents) {\r\n // Failed to add any listeners and we where requested to exclude some, so just call again without excluding anything\r\n pageUnloadAdded = addPageHideEventListener(listener, null, evtNamespace);\r\n }\r\n return pageUnloadAdded;\r\n}\r\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 */\r\nexport function removePageHideEventListener(listener, evtNamespace) {\r\n // add the unique page show namespace to any provided namespace so we only remove the ones added by \"pagehide\"\r\n var newNamespaces = mergeEvtNamespace(strPageHideNamespace, evtNamespace);\r\n removeEventListeners([strPageHide], listener, newNamespaces);\r\n removeEventListeners([strVisibilityChangeEvt], null, newNamespaces);\r\n}\r\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 */\r\nexport function addPageShowEventListener(listener, excludeEvents, evtNamespace) {\r\n function _handlePageVisibility(evt) {\r\n var doc = getDocument();\r\n if (listener && doc && doc.visibilityState === \"visible\") {\r\n listener(evt);\r\n }\r\n }\r\n // add the unique page show namespace to any provided namespace so we can only remove the ones added by \"pageshow\"\r\n var newNamespaces = mergeEvtNamespace(strPageShowNamespace, evtNamespace);\r\n var pageShowAdded = _addEventListeners([strPageShow], listener, excludeEvents, newNamespaces);\r\n pageShowAdded = _addEventListeners([strVisibilityChangeEvt], _handlePageVisibility, excludeEvents, newNamespaces) || pageShowAdded;\r\n if (!pageShowAdded && excludeEvents) {\r\n // Failed to add any listeners and we where requested to exclude some, so just call again without excluding anything\r\n pageShowAdded = addPageShowEventListener(listener, null, evtNamespace);\r\n }\r\n return pageShowAdded;\r\n}\r\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 */\r\nexport function removePageShowEventListener(listener, evtNamespace) {\r\n // add the unique page show namespace to any provided namespace so we only remove the ones added by \"pageshow\"\r\n var newNamespaces = mergeEvtNamespace(strPageShowNamespace, evtNamespace);\r\n removeEventListeners([strPageShow], listener, newNamespaces);\r\n removeEventListeners([strVisibilityChangeEvt], null, newNamespaces);\r\n}\r\n//# sourceMappingURL=EventHelpers.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { strShimFunction, strShimPrototype } from \"@microsoft/applicationinsights-shims\";\r\nimport { getInst, objHasOwnProperty } from \"@nevware21/ts-utils\";\r\nimport { _DYN_APPLY, _DYN_LENGTH, _DYN_NAME, _DYN_PUSH, _DYN_SPLICE } from \"../__DynamicConstants\";\r\nimport { _getObjProto } from \"./HelperFuncs\";\r\nvar aiInstrumentHooks = \"_aiHooks\";\r\nvar cbNames = [\r\n \"req\", \"rsp\", \"hkErr\", \"fnErr\"\r\n];\r\n/** @ignore */\r\nfunction _arrLoop(arr, fn) {\r\n if (arr) {\r\n for (var lp = 0; lp < arr[_DYN_LENGTH /* @min:%2elength */]; lp++) {\r\n if (fn(arr[lp], lp)) {\r\n break;\r\n }\r\n }\r\n }\r\n}\r\n/** @ignore */\r\nfunction _doCallbacks(hooks, callDetails, cbArgs, hookCtx, type) {\r\n if (type >= 0 /* CallbackType.Request */ && type <= 2 /* CallbackType.HookError */) {\r\n _arrLoop(hooks, function (hook, idx) {\r\n var cbks = hook.cbks;\r\n var cb = cbks[cbNames[type]];\r\n if (cb) {\r\n // Set the specific hook context implementation using a lazy creation pattern\r\n callDetails.ctx = function () {\r\n var ctx = hookCtx[idx] = (hookCtx[idx] || {});\r\n return ctx;\r\n };\r\n try {\r\n cb[_DYN_APPLY /* @min:%2eapply */](callDetails.inst, cbArgs);\r\n }\r\n catch (err) {\r\n var orgEx = callDetails.err;\r\n try {\r\n // Report Hook error via the callback\r\n var hookErrorCb = cbks[cbNames[2 /* CallbackType.HookError */]];\r\n if (hookErrorCb) {\r\n callDetails.err = err;\r\n hookErrorCb[_DYN_APPLY /* @min:%2eapply */](callDetails.inst, cbArgs);\r\n }\r\n }\r\n catch (e) {\r\n // Not much we can do here -- swallowing the exception to avoid crashing the hosting app\r\n }\r\n finally {\r\n // restore the original exception (if any)\r\n callDetails.err = orgEx;\r\n }\r\n }\r\n }\r\n });\r\n }\r\n}\r\n/** @ignore */\r\nfunction _createFunctionHook(aiHook) {\r\n // Define a temporary method that queues-up a the real method call\r\n return function () {\r\n var _a;\r\n var funcThis = this;\r\n // Capture the original arguments passed to the method\r\n var orgArgs = arguments;\r\n var hooks = aiHook.h;\r\n var funcArgs = (_a = {},\r\n _a[_DYN_NAME /* @min:name */] = aiHook.n,\r\n _a.inst = funcThis,\r\n _a.ctx = null,\r\n _a.set = _replaceArg,\r\n _a);\r\n var hookCtx = [];\r\n var cbArgs = _createArgs([funcArgs], orgArgs);\r\n funcArgs.evt = getInst(\"event\");\r\n function _createArgs(target, theArgs) {\r\n _arrLoop(theArgs, function (arg) {\r\n target[_DYN_PUSH /* @min:%2epush */](arg);\r\n });\r\n return target;\r\n }\r\n function _replaceArg(idx, value) {\r\n orgArgs = _createArgs([], orgArgs);\r\n orgArgs[idx] = value;\r\n cbArgs = _createArgs([funcArgs], orgArgs);\r\n }\r\n // Call the pre-request hooks\r\n _doCallbacks(hooks, funcArgs, cbArgs, hookCtx, 0 /* CallbackType.Request */);\r\n // Call the original function was called\r\n var theFunc = aiHook.f;\r\n if (theFunc) {\r\n try {\r\n funcArgs.rslt = theFunc[_DYN_APPLY /* @min:%2eapply */](funcThis, orgArgs);\r\n }\r\n catch (err) {\r\n // Report the request callback\r\n funcArgs.err = err;\r\n _doCallbacks(hooks, funcArgs, cbArgs, hookCtx, 3 /* CallbackType.FunctionError */);\r\n // rethrow the original exception so anyone listening for it can catch the exception\r\n throw err;\r\n }\r\n }\r\n // Call the post-request hooks\r\n _doCallbacks(hooks, funcArgs, cbArgs, hookCtx, 1 /* CallbackType.Response */);\r\n return funcArgs.rslt;\r\n };\r\n}\r\n/** @ignore */\r\nfunction _getOwner(target, name, checkPrototype, checkParentProto) {\r\n var owner = null;\r\n if (target) {\r\n if (objHasOwnProperty(target, name)) {\r\n owner = target;\r\n }\r\n else if (checkPrototype) {\r\n owner = _getOwner(_getObjProto(target), name, checkParentProto, false);\r\n }\r\n }\r\n return owner;\r\n}\r\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 */\r\nexport function InstrumentProto(target, funcName, callbacks) {\r\n if (target) {\r\n return InstrumentFunc(target[strShimPrototype], funcName, callbacks, false);\r\n }\r\n return null;\r\n}\r\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 */\r\nexport function InstrumentProtos(target, funcNames, callbacks) {\r\n if (target) {\r\n return InstrumentFuncs(target[strShimPrototype], funcNames, callbacks, false);\r\n }\r\n return null;\r\n}\r\nfunction _createInstrumentHook(owner, funcName, fn, callbacks) {\r\n var aiHook = fn && fn[aiInstrumentHooks];\r\n if (!aiHook) {\r\n // Only hook the function once\r\n aiHook = {\r\n i: 0,\r\n n: funcName,\r\n f: fn,\r\n h: []\r\n };\r\n // Override (hook) the original function\r\n var newFunc = _createFunctionHook(aiHook);\r\n newFunc[aiInstrumentHooks] = aiHook; // Tag and store the function hooks\r\n owner[funcName] = newFunc;\r\n }\r\n var theHook = {\r\n // tslint:disable:object-literal-shorthand\r\n id: aiHook.i,\r\n cbks: callbacks,\r\n rm: function () {\r\n // DO NOT Use () => { shorthand for the function as the this gets replaced\r\n // with the outer this and not the this for theHook instance.\r\n var id = this.id;\r\n _arrLoop(aiHook.h, function (hook, idx) {\r\n if (hook.id === id) {\r\n aiHook.h[_DYN_SPLICE /* @min:%2esplice */](idx, 1);\r\n return 1;\r\n }\r\n });\r\n }\r\n // tslint:enable:object-literal-shorthand\r\n };\r\n aiHook.i++;\r\n aiHook.h[_DYN_PUSH /* @min:%2epush */](theHook);\r\n return theHook;\r\n}\r\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 */\r\nexport function InstrumentFunc(target, funcName, callbacks, checkPrototype, checkParentProto) {\r\n if (checkPrototype === void 0) { checkPrototype = true; }\r\n if (target && funcName && callbacks) {\r\n var owner = _getOwner(target, funcName, checkPrototype, checkParentProto);\r\n if (owner) {\r\n var fn = owner[funcName];\r\n if (typeof fn === strShimFunction) {\r\n return _createInstrumentHook(owner, funcName, fn, callbacks);\r\n }\r\n }\r\n }\r\n return null;\r\n}\r\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 */\r\nexport function InstrumentFuncs(target, funcNames, callbacks, checkPrototype, checkParentProto) {\r\n if (checkPrototype === void 0) { checkPrototype = true; }\r\n var hooks = null;\r\n _arrLoop(funcNames, function (funcName) {\r\n var hook = InstrumentFunc(target, funcName, callbacks, checkPrototype, checkParentProto);\r\n if (hook) {\r\n if (!hooks) {\r\n hooks = [];\r\n }\r\n hooks[_DYN_PUSH /* @min:%2epush */](hook);\r\n }\r\n });\r\n return hooks;\r\n}\r\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 */\r\nexport function InstrumentEvent(target, evtName, callbacks, checkPrototype, checkParentProto) {\r\n if (target && evtName && callbacks) {\r\n var owner = _getOwner(target, evtName, checkPrototype, checkParentProto) || target;\r\n if (owner) {\r\n return _createInstrumentHook(owner, evtName, owner[evtName], callbacks);\r\n }\r\n }\r\n return null;\r\n}\r\n//# sourceMappingURL=InstrumentHooks.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n// @skip-file-minify\r\n// ##############################################################\r\n// AUTO GENERATED FILE: This file is Auto Generated during build.\r\n// ##############################################################\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\nexport var _DYN_TO_STRING = \"toString\"; // Count: 4\r\nexport var _DYN_IS_STORAGE_USE_DISAB0 = \"isStorageUseDisabled\"; // Count: 3\r\nexport var _DYN__ADD_HOOK = \"_addHook\"; // Count: 6\r\nexport var _DYN_CORE = \"core\"; // Count: 7\r\nexport var _DYN_DATA_TYPE = \"dataType\"; // Count: 8\r\nexport var _DYN_ENVELOPE_TYPE = \"envelopeType\"; // Count: 7\r\nexport var _DYN_DIAG_LOG = \"diagLog\"; // Count: 13\r\nexport var _DYN_TRACK = \"track\"; // Count: 7\r\nexport var _DYN_TRACK_PAGE_VIEW = \"trackPageView\"; // Count: 4\r\nexport var _DYN_TRACK_PREVIOUS_PAGE_1 = \"trackPreviousPageVisit\"; // Count: 3\r\nexport var _DYN_SEND_PAGE_VIEW_INTER2 = \"sendPageViewInternal\"; // Count: 7\r\nexport var _DYN_SEND_PAGE_VIEW_PERFO3 = \"sendPageViewPerformanceInternal\"; // Count: 3\r\nexport var _DYN_POPULATE_PAGE_VIEW_P4 = \"populatePageViewPerformanceEvent\"; // Count: 3\r\nexport var _DYN_HREF = \"href\"; // Count: 6\r\nexport var _DYN_SEND_EXCEPTION_INTER5 = \"sendExceptionInternal\"; // Count: 2\r\nexport var _DYN_EXCEPTION = \"exception\"; // Count: 3\r\nexport var _DYN_ERROR = \"error\"; // Count: 5\r\nexport var _DYN__ONERROR = \"_onerror\"; // Count: 3\r\nexport var _DYN_ERROR_SRC = \"errorSrc\"; // Count: 3\r\nexport var _DYN_LINE_NUMBER = \"lineNumber\"; // Count: 5\r\nexport var _DYN_COLUMN_NUMBER = \"columnNumber\"; // Count: 5\r\nexport var _DYN_MESSAGE = \"message\"; // Count: 4\r\nexport var _DYN__CREATE_AUTO_EXCEPTI6 = \"CreateAutoException\"; // Count: 3\r\nexport var _DYN_ADD_TELEMETRY_INITIA7 = \"addTelemetryInitializer\"; // Count: 4\r\nexport var _DYN_OVERRIDE_PAGE_VIEW_D8 = \"overridePageViewDuration\"; // Count: 2\r\nexport var _DYN_DURATION = \"duration\"; // Count: 10\r\nexport var _DYN_AUTO_TRACK_PAGE_VISI9 = \"autoTrackPageVisitTime\"; // Count: 2\r\nexport var _DYN_IS_BROWSER_LINK_TRAC10 = \"isBrowserLinkTrackingEnabled\"; // Count: 2\r\nexport var _DYN_LENGTH = \"length\"; // Count: 5\r\nexport var _DYN_ENABLE_AUTO_ROUTE_TR11 = \"enableAutoRouteTracking\"; // Count: 2\r\nexport var _DYN_ENABLE_UNHANDLED_PRO12 = \"enableUnhandledPromiseRejectionTracking\"; // Count: 2\r\nexport var _DYN_AUTO_UNHANDLED_PROMI13 = \"autoUnhandledPromiseInstrumented\"; // Count: 3\r\nexport var _DYN_IS_PERFORMANCE_TIMIN14 = \"isPerformanceTimingSupported\"; // Count: 2\r\nexport var _DYN_GET_PERFORMANCE_TIMI15 = \"getPerformanceTiming\"; // Count: 2\r\nexport var _DYN_NAVIGATION_START = \"navigationStart\"; // Count: 4\r\nexport var _DYN_SHOULD_COLLECT_DURAT16 = \"shouldCollectDuration\"; // Count: 3\r\nexport var _DYN_IS_PERFORMANCE_TIMIN17 = \"isPerformanceTimingDataReady\"; // Count: 2\r\nexport var _DYN_GET_ENTRIES_BY_TYPE = \"getEntriesByType\"; // Count: 3\r\nexport var _DYN_RESPONSE_START = \"responseStart\"; // Count: 5\r\nexport var _DYN_REQUEST_START = \"requestStart\"; // Count: 3\r\nexport var _DYN_LOAD_EVENT_END = \"loadEventEnd\"; // Count: 4\r\nexport var _DYN_RESPONSE_END = \"responseEnd\"; // Count: 5\r\nexport var _DYN_CONNECT_END = \"connectEnd\"; // Count: 4\r\nexport var _DYN_PAGE_VISIT_START_TIM18 = \"pageVisitStartTime\"; // Count: 2\r\n//# sourceMappingURL=__DynamicConstants.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { dateTimeUtilsDuration } from \"@microsoft/applicationinsights-common\";\r\nimport { _throwInternal, arrForEach, dumpObj, getDocument, getExceptionName, getLocation, isNullOrUndefined } from \"@microsoft/applicationinsights-core-js\";\r\nimport { isWebWorker, scheduleTimeout } from \"@nevware21/ts-utils\";\r\nimport { _DYN_DURATION, _DYN_GET_PERFORMANCE_TIMI15, _DYN_HREF, _DYN_IS_PERFORMANCE_TIMIN14, _DYN_IS_PERFORMANCE_TIMIN17, _DYN_LENGTH, _DYN_NAVIGATION_START, _DYN_POPULATE_PAGE_VIEW_P4, _DYN_SEND_PAGE_VIEW_INTER2, _DYN_SEND_PAGE_VIEW_PERFO3, _DYN_SHOULD_COLLECT_DURAT16, _DYN_TRACK_PAGE_VIEW } from \"../../__DynamicConstants\";\r\n/**\r\n * Class encapsulates sending page views and page view performance telemetry.\r\n */\r\nvar PageViewManager = /** @class */ (function () {\r\n function PageViewManager(appInsights, overridePageViewDuration, core, pageViewPerformanceManager) {\r\n dynamicProto(PageViewManager, this, function (_self) {\r\n var queueTimer = null;\r\n var itemQueue = [];\r\n var pageViewPerformanceSent = false;\r\n var _logger;\r\n if (core) {\r\n _logger = core.logger;\r\n }\r\n function _flushChannels(isAsync) {\r\n if (core) {\r\n core.flush(isAsync, function () {\r\n // Event flushed, callback added to prevent promise creation\r\n });\r\n }\r\n }\r\n function _startTimer() {\r\n if (!queueTimer) {\r\n queueTimer = scheduleTimeout((function () {\r\n queueTimer = null;\r\n var allItems = itemQueue.slice(0);\r\n var doFlush = false;\r\n itemQueue = [];\r\n arrForEach(allItems, function (item) {\r\n if (!item()) {\r\n // Not processed so rescheduled\r\n itemQueue.push(item);\r\n }\r\n else {\r\n doFlush = true;\r\n }\r\n });\r\n if (itemQueue[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n _startTimer();\r\n }\r\n if (doFlush) {\r\n // We process at least one item so flush the queue\r\n _flushChannels(true);\r\n }\r\n }), 100);\r\n }\r\n }\r\n function _addQueue(cb) {\r\n itemQueue.push(cb);\r\n _startTimer();\r\n }\r\n _self[_DYN_TRACK_PAGE_VIEW /* @min:%2etrackPageView */] = function (pageView, customProperties) {\r\n var name = pageView.name;\r\n if (isNullOrUndefined(name) || typeof name !== \"string\") {\r\n var doc = getDocument();\r\n name = pageView.name = doc && doc.title || \"\";\r\n }\r\n var uri = pageView.uri;\r\n if (isNullOrUndefined(uri) || typeof uri !== \"string\") {\r\n var location_1 = getLocation();\r\n uri = pageView.uri = location_1 && location_1[_DYN_HREF /* @min:%2ehref */] || \"\";\r\n }\r\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\r\n // do not provide the duration, set duration to undefined\r\n // Also this is case 4\r\n if (!pageViewPerformanceManager[_DYN_IS_PERFORMANCE_TIMIN14 /* @min:%2eisPerformanceTimingSupported */]()) {\r\n appInsights[_DYN_SEND_PAGE_VIEW_INTER2 /* @min:%2esendPageViewInternal */](pageView, customProperties);\r\n _flushChannels(true);\r\n if (!isWebWorker()) {\r\n // no navigation timing (IE 8, iOS Safari 8.4, Opera Mini 8 - see http://caniuse.com/#feat=nav-timing)\r\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.\");\r\n }\r\n return;\r\n }\r\n var pageViewSent = false;\r\n var customDuration;\r\n // if the performance timing is supported by the browser, calculate the custom duration\r\n var start = pageViewPerformanceManager[_DYN_GET_PERFORMANCE_TIMI15 /* @min:%2egetPerformanceTiming */]()[_DYN_NAVIGATION_START /* @min:%2enavigationStart */];\r\n if (start > 0) {\r\n customDuration = dateTimeUtilsDuration(start, +new Date);\r\n if (!pageViewPerformanceManager[_DYN_SHOULD_COLLECT_DURAT16 /* @min:%2eshouldCollectDuration */](customDuration)) {\r\n customDuration = undefined;\r\n }\r\n }\r\n // if the user has provided duration, send a page view telemetry with the provided duration. Otherwise, if\r\n // overridePageViewDuration is set to true, send a page view telemetry with the custom duration calculated earlier\r\n var duration;\r\n if (!isNullOrUndefined(customProperties) &&\r\n !isNullOrUndefined(customProperties[_DYN_DURATION /* @min:%2eduration */])) {\r\n duration = customProperties[_DYN_DURATION /* @min:%2eduration */];\r\n }\r\n if (overridePageViewDuration || !isNaN(duration)) {\r\n if (isNaN(duration)) {\r\n // case 3\r\n if (!customProperties) {\r\n customProperties = {};\r\n }\r\n customProperties[_DYN_DURATION /* @min:%2eduration */] = customDuration;\r\n }\r\n // case 2\r\n appInsights[_DYN_SEND_PAGE_VIEW_INTER2 /* @min:%2esendPageViewInternal */](pageView, customProperties);\r\n _flushChannels(true);\r\n pageViewSent = true;\r\n }\r\n // now try to send the page view performance telemetry\r\n var maxDurationLimit = 60000;\r\n if (!customProperties) {\r\n customProperties = {};\r\n }\r\n // Queue the event for processing\r\n _addQueue(function () {\r\n var processed = false;\r\n try {\r\n if (pageViewPerformanceManager[_DYN_IS_PERFORMANCE_TIMIN17 /* @min:%2eisPerformanceTimingDataReady */]()) {\r\n processed = true;\r\n var pageViewPerformance = {\r\n name: name,\r\n uri: uri\r\n };\r\n pageViewPerformanceManager[_DYN_POPULATE_PAGE_VIEW_P4 /* @min:%2epopulatePageViewPerformanceEvent */](pageViewPerformance);\r\n if (!pageViewPerformance.isValid && !pageViewSent) {\r\n // If navigation timing gives invalid numbers, then go back to \"override page view duration\" mode.\r\n // That's the best value we can get that makes sense.\r\n customProperties[_DYN_DURATION /* @min:%2eduration */] = customDuration;\r\n appInsights[_DYN_SEND_PAGE_VIEW_INTER2 /* @min:%2esendPageViewInternal */](pageView, customProperties);\r\n }\r\n else {\r\n if (!pageViewSent) {\r\n customProperties[_DYN_DURATION /* @min:%2eduration */] = pageViewPerformance.durationMs;\r\n appInsights[_DYN_SEND_PAGE_VIEW_INTER2 /* @min:%2esendPageViewInternal */](pageView, customProperties);\r\n }\r\n if (!pageViewPerformanceSent) {\r\n appInsights[_DYN_SEND_PAGE_VIEW_PERFO3 /* @min:%2esendPageViewPerformanceInternal */](pageViewPerformance, customProperties);\r\n pageViewPerformanceSent = true;\r\n }\r\n }\r\n }\r\n else if (start > 0 && dateTimeUtilsDuration(start, +new Date) > maxDurationLimit) {\r\n // if performance timings are not ready but we exceeded the maximum duration limit, just log a page view telemetry\r\n // with the maximum duration limit. Otherwise, keep waiting until performance timings are ready\r\n processed = true;\r\n if (!pageViewSent) {\r\n customProperties[_DYN_DURATION /* @min:%2eduration */] = maxDurationLimit;\r\n appInsights[_DYN_SEND_PAGE_VIEW_INTER2 /* @min:%2esendPageViewInternal */](pageView, customProperties);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n _throwInternal(_logger, 1 /* eLoggingSeverity.CRITICAL */, 38 /* _eInternalMessageId.TrackPVFailedCalc */, \"trackPageView failed on page load calculation: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n return processed;\r\n });\r\n };\r\n _self.teardown = function (unloadCtx, unloadState) {\r\n if (queueTimer) {\r\n clearInterval(queueTimer);\r\n queueTimer = null;\r\n var allItems = itemQueue.slice(0);\r\n var doFlush_1 = false;\r\n itemQueue = [];\r\n arrForEach(allItems, function (item) {\r\n if (item()) {\r\n doFlush_1 = true;\r\n }\r\n });\r\n }\r\n };\r\n });\r\n }\r\n /**\r\n * Currently supported cases:\r\n * 1) (default case) track page view called with default parameters, overridePageViewDuration = false. Page view is sent with page view performance when navigation timing data is available.\r\n * a. If navigation timing is not supported then page view is sent right away with undefined duration. Page view performance is not sent.\r\n * 2) overridePageViewDuration = true, custom duration provided. Custom duration is used, page view sends right away.\r\n * 3) overridePageViewDuration = true, custom duration NOT provided. Page view is sent right away, duration is time spent from page load till now (or undefined if navigation timing is not supported).\r\n * 4) overridePageViewDuration = false, custom duration is provided. Page view is sent right away with custom duration.\r\n *\r\n * In all cases page view performance is sent once (only for the 1st call of trackPageView), or not sent if navigation timing is not supported.\r\n */\r\n PageViewManager.prototype.trackPageView = function (pageView, customProperties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n PageViewManager.prototype.teardown = function (unloadCtx, unloadState) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n return PageViewManager;\r\n}());\r\nexport { PageViewManager };\r\n//# sourceMappingURL=PageViewManager.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { dateTimeUtilsDuration, msToTimeSpan } from \"@microsoft/applicationinsights-common\";\r\nimport { _throwInternal, getNavigator, getPerformance, safeGetLogger } from \"@microsoft/applicationinsights-core-js\";\r\nimport { strIndexOf } from \"@nevware21/ts-utils\";\r\nimport { _DYN_CONNECT_END, _DYN_DURATION, _DYN_GET_ENTRIES_BY_TYPE, _DYN_GET_PERFORMANCE_TIMI15, _DYN_IS_PERFORMANCE_TIMIN14, _DYN_IS_PERFORMANCE_TIMIN17, _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_DURAT16 } from \"../../__DynamicConstants\";\r\nvar MAX_DURATION_ALLOWED = 3600000; // 1h\r\nvar botAgentNames = [\"googlebot\", \"adsbot-google\", \"apis-google\", \"mediapartners-google\"];\r\nfunction _isPerformanceTimingSupported() {\r\n var perf = getPerformance();\r\n return perf && !!perf.timing;\r\n}\r\nfunction _isPerformanceNavigationTimingSupported() {\r\n var perf = getPerformance();\r\n return perf && perf.getEntriesByType && perf.getEntriesByType(\"navigation\")[_DYN_LENGTH /* @min:%2elength */] > 0;\r\n}\r\nfunction _isPerformanceTimingDataReady() {\r\n var perf = getPerformance();\r\n var timing = perf ? perf.timing : 0;\r\n return timing\r\n && timing.domainLookupStart > 0\r\n && timing[_DYN_NAVIGATION_START /* @min:%2enavigationStart */] > 0\r\n && timing[_DYN_RESPONSE_START /* @min:%2eresponseStart */] > 0\r\n && timing[_DYN_REQUEST_START /* @min:%2erequestStart */] > 0\r\n && timing[_DYN_LOAD_EVENT_END /* @min:%2eloadEventEnd */] > 0\r\n && timing[_DYN_RESPONSE_END /* @min:%2eresponseEnd */] > 0\r\n && timing[_DYN_CONNECT_END /* @min:%2econnectEnd */] > 0\r\n && timing.domLoading > 0;\r\n}\r\nfunction _getPerformanceTiming() {\r\n if (_isPerformanceTimingSupported()) {\r\n return getPerformance().timing;\r\n }\r\n return null;\r\n}\r\nfunction _getPerformanceNavigationTiming() {\r\n if (_isPerformanceNavigationTimingSupported()) {\r\n return getPerformance()[_DYN_GET_ENTRIES_BY_TYPE /* @min:%2egetEntriesByType */](\"navigation\")[0];\r\n }\r\n return null;\r\n}\r\n/**\r\n* This method tells if given durations should be excluded from collection.\r\n*/\r\nfunction _shouldCollectDuration() {\r\n var durations = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n durations[_i] = arguments[_i];\r\n }\r\n var _navigator = getNavigator() || {};\r\n // a full list of Google crawlers user agent strings - https://support.google.com/webmasters/answer/1061943?hl=en\r\n var userAgent = _navigator.userAgent;\r\n var isGoogleBot = false;\r\n if (userAgent) {\r\n for (var i = 0; i < botAgentNames[_DYN_LENGTH /* @min:%2elength */]; i++) {\r\n isGoogleBot = isGoogleBot || strIndexOf(userAgent.toLowerCase(), botAgentNames[i]) !== -1;\r\n }\r\n }\r\n if (isGoogleBot) {\r\n // Don't report durations for GoogleBot, it is returning invalid values in performance.timing API.\r\n return false;\r\n }\r\n else {\r\n // for other page views, don't report if it's outside of a reasonable range\r\n for (var i = 0; i < durations[_DYN_LENGTH /* @min:%2elength */]; i++) {\r\n if (durations[i] < 0 || durations[i] >= MAX_DURATION_ALLOWED) {\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n}\r\n/**\r\n * Class encapsulates sending page view performance telemetry.\r\n */\r\nvar PageViewPerformanceManager = /** @class */ (function () {\r\n function PageViewPerformanceManager(core) {\r\n var _logger = safeGetLogger(core);\r\n dynamicProto(PageViewPerformanceManager, this, function (_self) {\r\n _self[_DYN_POPULATE_PAGE_VIEW_P4 /* @min:%2epopulatePageViewPerformanceEvent */] = function (pageViewPerformance) {\r\n pageViewPerformance.isValid = false;\r\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 */\r\n var navigationTiming = _getPerformanceNavigationTiming();\r\n var timing = _getPerformanceTiming();\r\n var total = 0;\r\n var network = 0;\r\n var request = 0;\r\n var response = 0;\r\n var dom = 0;\r\n if (navigationTiming || timing) {\r\n if (navigationTiming) {\r\n total = navigationTiming[_DYN_DURATION /* @min:%2eduration */];\r\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 */\r\n network = navigationTiming.startTime === 0 ? navigationTiming[_DYN_CONNECT_END /* @min:%2econnectEnd */] : dateTimeUtilsDuration(navigationTiming.startTime, navigationTiming[_DYN_CONNECT_END /* @min:%2econnectEnd */]);\r\n request = dateTimeUtilsDuration(navigationTiming.requestStart, navigationTiming[_DYN_RESPONSE_START /* @min:%2eresponseStart */]);\r\n response = dateTimeUtilsDuration(navigationTiming[_DYN_RESPONSE_START /* @min:%2eresponseStart */], navigationTiming[_DYN_RESPONSE_END /* @min:%2eresponseEnd */]);\r\n dom = dateTimeUtilsDuration(navigationTiming.responseEnd, navigationTiming[_DYN_LOAD_EVENT_END /* @min:%2eloadEventEnd */]);\r\n }\r\n else {\r\n total = dateTimeUtilsDuration(timing[_DYN_NAVIGATION_START /* @min:%2enavigationStart */], timing[_DYN_LOAD_EVENT_END /* @min:%2eloadEventEnd */]);\r\n network = dateTimeUtilsDuration(timing[_DYN_NAVIGATION_START /* @min:%2enavigationStart */], timing[_DYN_CONNECT_END /* @min:%2econnectEnd */]);\r\n request = dateTimeUtilsDuration(timing.requestStart, timing[_DYN_RESPONSE_START /* @min:%2eresponseStart */]);\r\n response = dateTimeUtilsDuration(timing[_DYN_RESPONSE_START /* @min:%2eresponseStart */], timing[_DYN_RESPONSE_END /* @min:%2eresponseEnd */]);\r\n dom = dateTimeUtilsDuration(timing.responseEnd, timing[_DYN_LOAD_EVENT_END /* @min:%2eloadEventEnd */]);\r\n }\r\n if (total === 0) {\r\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 10 /* _eInternalMessageId.ErrorPVCalc */, \"error calculating page view performance.\", { total: total, network: network, request: request, response: response, dom: dom });\r\n }\r\n else if (!_self[_DYN_SHOULD_COLLECT_DURAT16 /* @min:%2eshouldCollectDuration */](total, network, request, response, dom)) {\r\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 45 /* _eInternalMessageId.InvalidDurationValue */, \"Invalid page load duration value. Browser perf data won't be sent.\", { total: total, network: network, request: request, response: response, dom: dom });\r\n }\r\n else if (total < Math.floor(network) + Math.floor(request) + Math.floor(response) + Math.floor(dom)) {\r\n // some browsers may report individual components incorrectly so that the sum of the parts will be bigger than total PLT\r\n // in this case, don't report client performance from this page\r\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 8 /* _eInternalMessageId.ClientPerformanceMathError */, \"client performance math error.\", { total: total, network: network, request: request, response: response, dom: dom });\r\n }\r\n else {\r\n pageViewPerformance.durationMs = total;\r\n // // convert to timespans\r\n pageViewPerformance.perfTotal = pageViewPerformance[_DYN_DURATION /* @min:%2eduration */] = msToTimeSpan(total);\r\n pageViewPerformance.networkConnect = msToTimeSpan(network);\r\n pageViewPerformance.sentRequest = msToTimeSpan(request);\r\n pageViewPerformance.receivedResponse = msToTimeSpan(response);\r\n pageViewPerformance.domProcessing = msToTimeSpan(dom);\r\n pageViewPerformance.isValid = true;\r\n }\r\n }\r\n };\r\n _self[_DYN_GET_PERFORMANCE_TIMI15 /* @min:%2egetPerformanceTiming */] = _getPerformanceTiming;\r\n _self[_DYN_IS_PERFORMANCE_TIMIN14 /* @min:%2eisPerformanceTimingSupported */] = _isPerformanceTimingSupported;\r\n _self[_DYN_IS_PERFORMANCE_TIMIN17 /* @min:%2eisPerformanceTimingDataReady */] = _isPerformanceTimingDataReady;\r\n _self[_DYN_SHOULD_COLLECT_DURAT16 /* @min:%2eshouldCollectDuration */] = _shouldCollectDuration;\r\n });\r\n }\r\n PageViewPerformanceManager.prototype.populatePageViewPerformanceEvent = function (pageViewPerformance) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n PageViewPerformanceManager.prototype.getPerformanceTiming = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Returns true is window performance timing API is supported, false otherwise.\r\n */\r\n PageViewPerformanceManager.prototype.isPerformanceTimingSupported = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return true;\r\n };\r\n /**\r\n * As page loads different parts of performance timing numbers get set. When all of them are set we can report it.\r\n * Returns true if ready, false otherwise.\r\n */\r\n PageViewPerformanceManager.prototype.isPerformanceTimingDataReady = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return true;\r\n };\r\n /**\r\n * This method tells if given durations should be excluded from collection.\r\n */\r\n PageViewPerformanceManager.prototype.shouldCollectDuration = function () {\r\n var durations = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n durations[_i] = arguments[_i];\r\n }\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return true;\r\n };\r\n return PageViewPerformanceManager;\r\n}());\r\nexport { PageViewPerformanceManager };\r\n//# sourceMappingURL=PageViewPerformanceManager.js.map","/**\r\n* ApplicationInsights.ts\r\n* @copyright Microsoft 2018\r\n*/\r\nvar _a;\r\nimport { __assign, __extends } from \"tslib\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { AnalyticsPluginIdentifier, Event as EventTelemetry, Exception, Metric, PageView, PageViewPerformance, PropertiesPluginIdentifier, RemoteDependencyData, Trace, createDistributedTraceContextFromTrace, createDomEvent, createTelemetryItem, dataSanitizeString, isCrossOriginError, strNotSpecified, utlDisableStorage, utlEnableStorage } from \"@microsoft/applicationinsights-common\";\r\nimport { BaseTelemetryPlugin, InstrumentEvent, arrForEach, cfgDfBoolean, cfgDfSet, cfgDfString, cfgDfValidate, createProcessTelemetryContext, createUniqueNamespace, dumpObj, eventOff, eventOn, generateW3CId, getDocument, getExceptionName, getHistory, getLocation, getWindow, hasHistory, hasWindow, isFunction, isNullOrUndefined, isString, isUndefined, mergeEvtNamespace, onConfigChange, safeGetCookieMgr, strUndefined, throwError } from \"@microsoft/applicationinsights-core-js\";\r\nimport { isError, objDeepFreeze, objDefine, scheduleTimeout, strIndexOf } from \"@nevware21/ts-utils\";\r\nimport { _DYN_ADD_TELEMETRY_INITIA7, _DYN_AUTO_TRACK_PAGE_VISI9, _DYN_AUTO_UNHANDLED_PROMI13, _DYN_COLUMN_NUMBER, _DYN_CORE, _DYN_DATA_TYPE, _DYN_DIAG_LOG, _DYN_ENABLE_AUTO_ROUTE_TR11, _DYN_ENABLE_UNHANDLED_PRO12, _DYN_ENVELOPE_TYPE, _DYN_ERROR, _DYN_ERROR_SRC, _DYN_EXCEPTION, _DYN_HREF, _DYN_IS_BROWSER_LINK_TRAC10, _DYN_IS_STORAGE_USE_DISAB0, _DYN_LENGTH, _DYN_LINE_NUMBER, _DYN_MESSAGE, _DYN_OVERRIDE_PAGE_VIEW_D8, _DYN_POPULATE_PAGE_VIEW_P4, _DYN_SEND_EXCEPTION_INTER5, _DYN_SEND_PAGE_VIEW_INTER2, _DYN_SEND_PAGE_VIEW_PERFO3, _DYN_TO_STRING, _DYN_TRACK, _DYN_TRACK_PAGE_VIEW, _DYN_TRACK_PREVIOUS_PAGE_1, _DYN__ADD_HOOK, _DYN__CREATE_AUTO_EXCEPTI6, _DYN__ONERROR } from \"../__DynamicConstants\";\r\nimport { PageViewManager } from \"./Telemetry/PageViewManager\";\r\nimport { PageViewPerformanceManager } from \"./Telemetry/PageViewPerformanceManager\";\r\nimport { PageVisitTimeManager } from \"./Telemetry/PageVisitTimeManager\";\r\nimport { Timing } from \"./Timing\";\r\nvar strEvent = \"event\";\r\nfunction _dispatchEvent(target, evnt) {\r\n if (target && target.dispatchEvent && evnt) {\r\n target.dispatchEvent(evnt);\r\n }\r\n}\r\nfunction _getReason(error) {\r\n if (error && error.reason) {\r\n var reason = error.reason;\r\n if (!isString(reason) && isFunction(reason[_DYN_TO_STRING /* @min:%2etoString */])) {\r\n return reason[_DYN_TO_STRING /* @min:%2etoString */]();\r\n }\r\n return dumpObj(reason);\r\n }\r\n // Pass the original object down which will eventually get evaluated for any message or description\r\n return error || \"\";\r\n}\r\nvar MinMilliSeconds = 60000;\r\nvar defaultValues = objDeepFreeze((_a = {\r\n sessionRenewalMs: cfgDfSet(_chkConfigMilliseconds, 30 * 60 * 1000),\r\n sessionExpirationMs: cfgDfSet(_chkConfigMilliseconds, 24 * 60 * 60 * 1000),\r\n disableExceptionTracking: cfgDfBoolean()\r\n },\r\n _a[_DYN_AUTO_TRACK_PAGE_VISI9 /* @min:autoTrackPageVisitTime */] = cfgDfBoolean(),\r\n _a[_DYN_OVERRIDE_PAGE_VIEW_D8 /* @min:overridePageViewDuration */] = cfgDfBoolean(),\r\n _a[_DYN_ENABLE_UNHANDLED_PRO12 /* @min:enableUnhandledPromiseRejectionTracking */] = cfgDfBoolean(),\r\n _a[_DYN_AUTO_UNHANDLED_PROMI13 /* @min:autoUnhandledPromiseInstrumented */] = false,\r\n _a.samplingPercentage = cfgDfValidate(_chkSampling, 100),\r\n _a[_DYN_IS_STORAGE_USE_DISAB0 /* @min:isStorageUseDisabled */] = cfgDfBoolean(),\r\n _a[_DYN_IS_BROWSER_LINK_TRAC10 /* @min:isBrowserLinkTrackingEnabled */] = cfgDfBoolean(),\r\n _a[_DYN_ENABLE_AUTO_ROUTE_TR11 /* @min:enableAutoRouteTracking */] = cfgDfBoolean(),\r\n _a.namePrefix = cfgDfString(),\r\n _a.enableDebug = cfgDfBoolean(),\r\n _a.disableFlushOnBeforeUnload = cfgDfBoolean(),\r\n _a.disableFlushOnUnload = cfgDfBoolean(false, \"disableFlushOnBeforeUnload\"),\r\n _a));\r\nfunction _chkConfigMilliseconds(value, defValue) {\r\n value = value || defValue;\r\n if (value < MinMilliSeconds) {\r\n value = MinMilliSeconds;\r\n }\r\n return +value;\r\n}\r\nfunction _chkSampling(value) {\r\n return !isNaN(value) && value > 0 && value <= 100;\r\n}\r\nfunction _updateStorageUsage(extConfig) {\r\n // Not resetting the storage usage as someone may have manually called utlDisableStorage, so this will only\r\n // reset based if the configuration option is provided\r\n if (!isUndefined(extConfig[_DYN_IS_STORAGE_USE_DISAB0 /* @min:%2eisStorageUseDisabled */])) {\r\n if (extConfig[_DYN_IS_STORAGE_USE_DISAB0 /* @min:%2eisStorageUseDisabled */]) {\r\n utlDisableStorage();\r\n }\r\n else {\r\n utlEnableStorage();\r\n }\r\n }\r\n}\r\nvar AnalyticsPlugin = /** @class */ (function (_super) {\r\n __extends(AnalyticsPlugin, _super);\r\n function AnalyticsPlugin() {\r\n var _this = _super.call(this) || this;\r\n _this.identifier = AnalyticsPluginIdentifier; // do not change name or priority\r\n _this.priority = 180; // take from reserved priority range 100- 200\r\n _this.autoRoutePVDelay = 500; // ms; Time to wait after a route change before triggering a pageview to allow DOM changes to take place\r\n var _eventTracking;\r\n var _pageTracking;\r\n var _pageViewManager;\r\n var _pageViewPerformanceManager;\r\n var _pageVisitTimeManager;\r\n var _preInitTelemetryInitializers;\r\n var _isBrowserLinkTrackingEnabled;\r\n var _browserLinkInitializerAdded;\r\n var _enableAutoRouteTracking;\r\n var _historyListenerAdded;\r\n var _disableExceptionTracking;\r\n var _autoExceptionInstrumented;\r\n var _enableUnhandledPromiseRejectionTracking;\r\n var _autoUnhandledPromiseInstrumented;\r\n var _extConfig;\r\n var _autoTrackPageVisitTime;\r\n // Counts number of trackAjax invocations.\r\n // By default we only monitor X ajax call per view to avoid too much load.\r\n // Default value is set in config.\r\n // This counter keeps increasing even after the limit is reached.\r\n var _trackAjaxAttempts = 0;\r\n // array with max length of 2 that store current url and previous url for SPA page route change trackPageview use.\r\n var _prevUri; // Assigned in the constructor\r\n var _currUri;\r\n var _evtNamespace;\r\n dynamicProto(AnalyticsPlugin, _this, function (_self, _base) {\r\n var _addHook = _base[_DYN__ADD_HOOK /* @min:%2e_addHook */];\r\n _initDefaults();\r\n _self.getCookieMgr = function () {\r\n return safeGetCookieMgr(_self[_DYN_CORE /* @min:%2ecore */]);\r\n };\r\n _self.processTelemetry = function (env, itemCtx) {\r\n _self.processNext(env, itemCtx);\r\n };\r\n _self.trackEvent = function (event, customProperties) {\r\n try {\r\n var telemetryItem = createTelemetryItem(event, EventTelemetry[_DYN_DATA_TYPE /* @min:%2edataType */], EventTelemetry[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], _self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), customProperties);\r\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\r\n }\r\n catch (e) {\r\n _throwInternal(2 /* eLoggingSeverity.WARNING */, 39 /* _eInternalMessageId.TrackTraceFailed */, \"trackTrace failed, trace will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\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 */\r\n _self.startTrackEvent = function (name) {\r\n try {\r\n _eventTracking.start(name);\r\n }\r\n catch (e) {\r\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 29 /* _eInternalMessageId.StartTrackEventFailed */, \"startTrackEvent failed, event will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\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 */\r\n _self.stopTrackEvent = function (name, properties, measurements) {\r\n try {\r\n _eventTracking.stop(name, undefined, properties, measurements);\r\n }\r\n catch (e) {\r\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 30 /* _eInternalMessageId.StopTrackEventFailed */, \"stopTrackEvent failed, event will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\n /**\r\n * @description Log a diagnostic message\r\n * @param trace\r\n * @param ICustomProperties.\r\n * @memberof ApplicationInsights\r\n */\r\n _self.trackTrace = function (trace, customProperties) {\r\n try {\r\n var telemetryItem = createTelemetryItem(trace, Trace[_DYN_DATA_TYPE /* @min:%2edataType */], Trace[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], _self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), customProperties);\r\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\r\n }\r\n catch (e) {\r\n _throwInternal(2 /* eLoggingSeverity.WARNING */, 39 /* _eInternalMessageId.TrackTraceFailed */, \"trackTrace failed, trace will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\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 * @memberof ApplicationInsights\r\n */\r\n _self.trackMetric = function (metric, customProperties) {\r\n try {\r\n var telemetryItem = createTelemetryItem(metric, Metric[_DYN_DATA_TYPE /* @min:%2edataType */], Metric[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], _self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), customProperties);\r\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\r\n }\r\n catch (e) {\r\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 36 /* _eInternalMessageId.TrackMetricFailed */, \"trackMetric failed, metric will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\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 */\r\n _self[_DYN_TRACK_PAGE_VIEW /* @min:%2etrackPageView */] = function (pageView, customProperties) {\r\n try {\r\n var inPv = pageView || {};\r\n _pageViewManager[_DYN_TRACK_PAGE_VIEW /* @min:%2etrackPageView */](inPv, __assign(__assign(__assign({}, inPv.properties), inPv.measurements), customProperties));\r\n if (_autoTrackPageVisitTime) {\r\n _pageVisitTimeManager[_DYN_TRACK_PREVIOUS_PAGE_1 /* @min:%2etrackPreviousPageVisit */](inPv.name, inPv.uri);\r\n }\r\n }\r\n catch (e) {\r\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 37 /* _eInternalMessageId.TrackPVFailed */, \"trackPageView failed, page view will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\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 */\r\n _self[_DYN_SEND_PAGE_VIEW_INTER2 /* @min:%2esendPageViewInternal */] = function (pageView, properties, systemProperties) {\r\n var doc = getDocument();\r\n if (doc) {\r\n pageView.refUri = pageView.refUri === undefined ? doc.referrer : pageView.refUri;\r\n }\r\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);\r\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\r\n // reset ajaxes counter\r\n _trackAjaxAttempts = 0;\r\n };\r\n /**\r\n * @ignore INTERNAL ONLY\r\n * @param pageViewPerformance\r\n * @param properties\r\n */\r\n _self[_DYN_SEND_PAGE_VIEW_PERFO3 /* @min:%2esendPageViewPerformanceInternal */] = function (pageViewPerformance, properties, systemProperties) {\r\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);\r\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\r\n };\r\n /**\r\n * Send browser performance metrics.\r\n * @param pageViewPerformance\r\n * @param customProperties\r\n */\r\n _self.trackPageViewPerformance = function (pageViewPerformance, customProperties) {\r\n var inPvp = pageViewPerformance || {};\r\n try {\r\n _pageViewPerformanceManager[_DYN_POPULATE_PAGE_VIEW_P4 /* @min:%2epopulatePageViewPerformanceEvent */](inPvp);\r\n _self[_DYN_SEND_PAGE_VIEW_PERFO3 /* @min:%2esendPageViewPerformanceInternal */](inPvp, customProperties);\r\n }\r\n catch (e) {\r\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 37 /* _eInternalMessageId.TrackPVFailed */, \"trackPageViewPerformance failed, page view will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\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 */\r\n _self.startTrackPage = function (name) {\r\n try {\r\n if (typeof name !== \"string\") {\r\n var doc = getDocument();\r\n name = doc && doc.title || \"\";\r\n }\r\n _pageTracking.start(name);\r\n }\r\n catch (e) {\r\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 31 /* _eInternalMessageId.StartTrackFailed */, \"startTrackPage failed, page view may not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\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 */\r\n _self.stopTrackPage = function (name, url, properties, measurement) {\r\n try {\r\n if (typeof name !== \"string\") {\r\n var doc = getDocument();\r\n name = doc && doc.title || \"\";\r\n }\r\n if (typeof url !== \"string\") {\r\n var loc = getLocation();\r\n url = loc && loc[_DYN_HREF /* @min:%2ehref */] || \"\";\r\n }\r\n _pageTracking.stop(name, url, properties, measurement);\r\n if (_autoTrackPageVisitTime) {\r\n _pageVisitTimeManager[_DYN_TRACK_PREVIOUS_PAGE_1 /* @min:%2etrackPreviousPageVisit */](name, url);\r\n }\r\n }\r\n catch (e) {\r\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 32 /* _eInternalMessageId.StopTrackFailed */, \"stopTrackPage failed, page view will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\n /**\r\n * @ignore INTERNAL ONLY\r\n * @param exception\r\n * @param properties\r\n * @param systemProperties\r\n */\r\n _self[_DYN_SEND_EXCEPTION_INTER5 /* @min:%2esendExceptionInternal */] = function (exception, customProperties, systemProperties) {\r\n // Adding additional edge cases to handle\r\n // - Not passing anything (null / undefined)\r\n var theError = (exception && (exception[_DYN_EXCEPTION /* @min:%2eexception */] || exception[_DYN_ERROR /* @min:%2eerror */])) ||\r\n // - Handle someone calling trackException based of v1 API where the exception was the Error\r\n isError(exception) && exception ||\r\n // - Handles no error being defined and instead of creating a new Error() instance attempt to map so any stacktrace\r\n // is preserved and does not list ApplicationInsights code as the source\r\n { name: (exception && typeof exception), message: exception || strNotSpecified };\r\n // If no exception object was passed assign to an empty object to avoid internal exceptions\r\n exception = exception || {};\r\n var exceptionPartB = new Exception(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), theError, exception.properties || customProperties, exception.measurements, exception.severityLevel, exception.id).toInterface();\r\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);\r\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\r\n };\r\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 * @memberof ApplicationInsights\r\n */\r\n _self.trackException = function (exception, customProperties) {\r\n if (exception && !exception[_DYN_EXCEPTION /* @min:%2eexception */] && exception[_DYN_ERROR /* @min:%2eerror */]) {\r\n exception[_DYN_EXCEPTION /* @min:%2eexception */] = exception[_DYN_ERROR /* @min:%2eerror */];\r\n }\r\n try {\r\n _self[_DYN_SEND_EXCEPTION_INTER5 /* @min:%2esendExceptionInternal */](exception, customProperties);\r\n }\r\n catch (e) {\r\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 35 /* _eInternalMessageId.TrackExceptionFailed */, \"trackException failed, exception will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n };\r\n /**\r\n * @description Custom error handler for Application Insights Analytics\r\n * @param exception\r\n * @memberof ApplicationInsights\r\n */\r\n _self[_DYN__ONERROR /* @min:%2e_onerror */] = function (exception) {\r\n var error = exception && exception[_DYN_ERROR /* @min:%2eerror */];\r\n var evt = exception && exception.evt;\r\n try {\r\n if (!evt) {\r\n var _window = getWindow();\r\n if (_window) {\r\n evt = _window[strEvent];\r\n }\r\n }\r\n var url = (exception && exception.url) || (getDocument() || {}).URL;\r\n // If no error source is provided assume the default window.onerror handler\r\n var errorSrc = exception[_DYN_ERROR_SRC /* @min:%2eerrorSrc */] || \"window.onerror@\" + url + \":\" + (exception[_DYN_LINE_NUMBER /* @min:%2elineNumber */] || 0) + \":\" + (exception[_DYN_COLUMN_NUMBER /* @min:%2ecolumnNumber */] || 0);\r\n var properties = {\r\n errorSrc: errorSrc,\r\n url: url,\r\n lineNumber: exception[_DYN_LINE_NUMBER /* @min:%2elineNumber */] || 0,\r\n columnNumber: exception[_DYN_COLUMN_NUMBER /* @min:%2ecolumnNumber */] || 0,\r\n message: exception[_DYN_MESSAGE /* @min:%2emessage */]\r\n };\r\n if (isCrossOriginError(exception.message, exception.url, exception.lineNumber, exception.columnNumber, exception[_DYN_ERROR /* @min:%2eerror */])) {\r\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);\r\n }\r\n else {\r\n if (!exception[_DYN_ERROR_SRC /* @min:%2eerrorSrc */]) {\r\n exception[_DYN_ERROR_SRC /* @min:%2eerrorSrc */] = errorSrc;\r\n }\r\n _self.trackException({ exception: exception, severityLevel: 3 /* eSeverityLevel.Error */ }, properties);\r\n }\r\n }\r\n catch (e) {\r\n var errorString = error ? (error.name + \", \" + error[_DYN_MESSAGE /* @min:%2emessage */]) : \"null\";\r\n _throwInternal(1 /* eLoggingSeverity.CRITICAL */, 11 /* _eInternalMessageId.ExceptionWhileLoggingError */, \"_onError threw exception while logging error, error will not be collected: \"\r\n + getExceptionName(e), { exception: dumpObj(e), errorString: errorString });\r\n }\r\n };\r\n _self[_DYN_ADD_TELEMETRY_INITIA7 /* @min:%2eaddTelemetryInitializer */] = function (telemetryInitializer) {\r\n if (_self[_DYN_CORE /* @min:%2ecore */]) {\r\n // Just add to the core\r\n return _self[_DYN_CORE /* @min:%2ecore */][_DYN_ADD_TELEMETRY_INITIA7 /* @min:%2eaddTelemetryInitializer */](telemetryInitializer);\r\n }\r\n // Handle \"pre-initialization\" telemetry initializers (for backward compatibility)\r\n if (!_preInitTelemetryInitializers) {\r\n _preInitTelemetryInitializers = [];\r\n }\r\n _preInitTelemetryInitializers.push(telemetryInitializer);\r\n };\r\n _self.initialize = function (config, core, extensions, pluginChain) {\r\n if (_self.isInitialized()) {\r\n return;\r\n }\r\n if (isNullOrUndefined(core)) {\r\n throwError(\"Error initializing\");\r\n }\r\n _base.initialize(config, core, extensions, pluginChain);\r\n try {\r\n _evtNamespace = mergeEvtNamespace(createUniqueNamespace(_self.identifier), core.evtNamespace && core.evtNamespace());\r\n if (_preInitTelemetryInitializers) {\r\n arrForEach(_preInitTelemetryInitializers, function (initializer) {\r\n core[_DYN_ADD_TELEMETRY_INITIA7 /* @min:%2eaddTelemetryInitializer */](initializer);\r\n });\r\n _preInitTelemetryInitializers = null;\r\n }\r\n _populateDefaults(config);\r\n _pageViewPerformanceManager = new PageViewPerformanceManager(_self[_DYN_CORE /* @min:%2ecore */]);\r\n _pageViewManager = new PageViewManager(_self, _extConfig.overridePageViewDuration, _self[_DYN_CORE /* @min:%2ecore */], _pageViewPerformanceManager);\r\n _pageVisitTimeManager = new PageVisitTimeManager(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), function (pageName, pageUrl, pageVisitTime) { return trackPageVisitTime(pageName, pageUrl, pageVisitTime); });\r\n _eventTracking = new Timing(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), \"trackEvent\");\r\n _eventTracking.action =\r\n function (name, url, duration, properties, measurements) {\r\n if (!properties) {\r\n properties = {};\r\n }\r\n if (!measurements) {\r\n measurements = {};\r\n }\r\n properties.duration = duration[_DYN_TO_STRING /* @min:%2etoString */]();\r\n _self.trackEvent({ name: name, properties: properties, measurements: measurements });\r\n };\r\n // initialize page view timing\r\n _pageTracking = new Timing(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), \"trackPageView\");\r\n _pageTracking.action = function (name, url, duration, properties, measurements) {\r\n // duration must be a custom property in order for the collector to extract it\r\n if (isNullOrUndefined(properties)) {\r\n properties = {};\r\n }\r\n properties.duration = duration[_DYN_TO_STRING /* @min:%2etoString */]();\r\n var pageViewItem = {\r\n name: name,\r\n uri: url,\r\n properties: properties,\r\n measurements: measurements\r\n };\r\n _self[_DYN_SEND_PAGE_VIEW_INTER2 /* @min:%2esendPageViewInternal */](pageViewItem, properties);\r\n };\r\n if (hasWindow()) {\r\n _updateExceptionTracking();\r\n _updateLocationChange();\r\n }\r\n }\r\n catch (e) {\r\n // resetting the initialized state because of failure\r\n _self.setInitialized(false);\r\n throw e;\r\n }\r\n };\r\n _self._doTeardown = function (unloadCtx, unloadState) {\r\n _pageViewManager && _pageViewManager.teardown(unloadCtx, unloadState);\r\n // Just register to remove all events associated with this namespace\r\n eventOff(window, null, null, _evtNamespace);\r\n _initDefaults();\r\n };\r\n function _populateDefaults(config) {\r\n var identifier = _self.identifier;\r\n var core = _self[_DYN_CORE /* @min:%2ecore */];\r\n _self[_DYN__ADD_HOOK /* @min:%2e_addHook */](onConfigChange(config, function () {\r\n var ctx = createProcessTelemetryContext(null, config, core);\r\n _extConfig = ctx.getExtCfg(identifier, defaultValues);\r\n _autoTrackPageVisitTime = _extConfig[_DYN_AUTO_TRACK_PAGE_VISI9 /* @min:%2eautoTrackPageVisitTime */];\r\n _updateStorageUsage(_extConfig);\r\n // _updateBrowserLinkTracking\r\n _isBrowserLinkTrackingEnabled = _extConfig[_DYN_IS_BROWSER_LINK_TRAC10 /* @min:%2eisBrowserLinkTrackingEnabled */];\r\n _addDefaultTelemetryInitializers();\r\n }));\r\n }\r\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 */\r\n function trackPageVisitTime(pageName, pageUrl, pageVisitTime) {\r\n var properties = { PageName: pageName, PageUrl: pageUrl };\r\n _self.trackMetric({\r\n name: \"PageVisitTime\",\r\n average: pageVisitTime,\r\n max: pageVisitTime,\r\n min: pageVisitTime,\r\n sampleCount: 1\r\n }, properties);\r\n }\r\n function _addDefaultTelemetryInitializers() {\r\n if (!_browserLinkInitializerAdded && _isBrowserLinkTrackingEnabled) {\r\n var browserLinkPaths_1 = [\"/browserLinkSignalR/\", \"/__browserLink/\"];\r\n var dropBrowserLinkRequests = function (envelope) {\r\n if (_isBrowserLinkTrackingEnabled && envelope.baseType === RemoteDependencyData[_DYN_DATA_TYPE /* @min:%2edataType */]) {\r\n var remoteData = envelope.baseData;\r\n if (remoteData) {\r\n for (var i = 0; i < browserLinkPaths_1[_DYN_LENGTH /* @min:%2elength */]; i++) {\r\n if (remoteData.target && strIndexOf(remoteData.target, browserLinkPaths_1[i]) >= 0) {\r\n return false;\r\n }\r\n }\r\n }\r\n }\r\n return true;\r\n };\r\n _self[_DYN__ADD_HOOK /* @min:%2e_addHook */](_self[_DYN_ADD_TELEMETRY_INITIA7 /* @min:%2eaddTelemetryInitializer */](dropBrowserLinkRequests));\r\n _browserLinkInitializerAdded = true;\r\n }\r\n }\r\n function _sendCORSException(exception, properties) {\r\n var telemetryItem = createTelemetryItem(exception, Exception[_DYN_DATA_TYPE /* @min:%2edataType */], Exception[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], _self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), properties);\r\n _self[_DYN_CORE /* @min:%2ecore */][_DYN_TRACK /* @min:%2etrack */](telemetryItem);\r\n }\r\n function _updateExceptionTracking() {\r\n var _window = getWindow();\r\n var locn = getLocation(true);\r\n _self[_DYN__ADD_HOOK /* @min:%2e_addHook */](onConfigChange(_extConfig, function () {\r\n _disableExceptionTracking = _extConfig.disableExceptionTracking;\r\n if (!_disableExceptionTracking && !_autoExceptionInstrumented && !_extConfig.autoExceptionInstrumented) {\r\n // We want to enable exception auto collection and it has not been done so yet\r\n _addHook(InstrumentEvent(_window, \"onerror\", {\r\n ns: _evtNamespace,\r\n rsp: function (callDetails, message, url, lineNumber, columnNumber, error) {\r\n if (!_disableExceptionTracking && callDetails.rslt !== true) {\r\n _self[_DYN__ONERROR /* @min:%2e_onerror */](Exception[_DYN__CREATE_AUTO_EXCEPTI6 /* @min:%2eCreateAutoException */](message, url, lineNumber, columnNumber, error, callDetails.evt));\r\n }\r\n }\r\n }, false));\r\n _autoExceptionInstrumented = true;\r\n }\r\n }));\r\n _addUnhandledPromiseRejectionTracking(_window, locn);\r\n }\r\n function _updateLocationChange() {\r\n var win = getWindow();\r\n var locn = getLocation(true);\r\n _self[_DYN__ADD_HOOK /* @min:%2e_addHook */](onConfigChange(_extConfig, function () {\r\n _enableAutoRouteTracking = _extConfig[_DYN_ENABLE_AUTO_ROUTE_TR11 /* @min:%2eenableAutoRouteTracking */] === true;\r\n /**\r\n * Create a custom \"locationchange\" event which is triggered each time the history object is changed\r\n */\r\n if (win && _enableAutoRouteTracking && !_historyListenerAdded && hasHistory()) {\r\n var _history = getHistory();\r\n if (isFunction(_history.pushState) && isFunction(_history.replaceState) && typeof Event !== strUndefined) {\r\n _addHistoryListener(win, _history, locn);\r\n }\r\n }\r\n }));\r\n }\r\n function _getDistributedTraceCtx() {\r\n var distributedTraceCtx = null;\r\n if (_self[_DYN_CORE /* @min:%2ecore */] && _self[_DYN_CORE /* @min:%2ecore */].getTraceCtx) {\r\n distributedTraceCtx = _self[_DYN_CORE /* @min:%2ecore */].getTraceCtx(false);\r\n }\r\n if (!distributedTraceCtx) {\r\n // Fallback when using an older Core and PropertiesPlugin\r\n var properties = _self[_DYN_CORE /* @min:%2ecore */].getPlugin(PropertiesPluginIdentifier);\r\n if (properties) {\r\n var context = properties.plugin.context;\r\n if (context) {\r\n distributedTraceCtx = createDistributedTraceContextFromTrace(context.telemetryTrace);\r\n }\r\n }\r\n }\r\n return distributedTraceCtx;\r\n }\r\n /**\r\n * Create a custom \"locationchange\" event which is triggered each time the history object is changed\r\n */\r\n function _addHistoryListener(win, history, locn) {\r\n if (_historyListenerAdded) {\r\n return;\r\n }\r\n // Name Prefix is only referenced during the initial initialization and cannot be changed afterwards\r\n var namePrefix = _extConfig.namePrefix || \"\";\r\n function _popstateHandler() {\r\n if (_enableAutoRouteTracking) {\r\n _dispatchEvent(win, createDomEvent(namePrefix + \"locationchange\"));\r\n }\r\n }\r\n function _locationChangeHandler() {\r\n // We always track the changes (if the handler is installed) to handle the feature being disabled between location changes\r\n if (_currUri) {\r\n _prevUri = _currUri;\r\n _currUri = locn && locn[_DYN_HREF /* @min:%2ehref */] || \"\";\r\n }\r\n else {\r\n _currUri = locn && locn[_DYN_HREF /* @min:%2ehref */] || \"\";\r\n }\r\n if (_enableAutoRouteTracking) {\r\n var distributedTraceCtx = _getDistributedTraceCtx();\r\n if (distributedTraceCtx) {\r\n distributedTraceCtx.setTraceId(generateW3CId());\r\n var traceLocationName = \"_unknown_\";\r\n if (locn && locn.pathname) {\r\n traceLocationName = locn.pathname + (locn.hash || \"\");\r\n }\r\n // This populates the ai.operation.name which has a maximum size of 1024 so we need to sanitize it\r\n distributedTraceCtx.setName(dataSanitizeString(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), traceLocationName));\r\n }\r\n scheduleTimeout((function (uri) {\r\n // todo: override start time so that it is not affected by autoRoutePVDelay\r\n _self[_DYN_TRACK_PAGE_VIEW /* @min:%2etrackPageView */]({ refUri: uri, properties: { duration: 0 } }); // SPA route change loading durations are undefined, so send 0\r\n }).bind(_self, _prevUri), _self.autoRoutePVDelay);\r\n }\r\n }\r\n _addHook(InstrumentEvent(history, \"pushState\", {\r\n ns: _evtNamespace,\r\n rsp: function () {\r\n if (_enableAutoRouteTracking) {\r\n _dispatchEvent(win, createDomEvent(namePrefix + \"pushState\"));\r\n _dispatchEvent(win, createDomEvent(namePrefix + \"locationchange\"));\r\n }\r\n }\r\n }, true));\r\n _addHook(InstrumentEvent(history, \"replaceState\", {\r\n ns: _evtNamespace,\r\n rsp: function () {\r\n if (_enableAutoRouteTracking) {\r\n _dispatchEvent(win, createDomEvent(namePrefix + \"replaceState\"));\r\n _dispatchEvent(win, createDomEvent(namePrefix + \"locationchange\"));\r\n }\r\n }\r\n }, true));\r\n eventOn(win, namePrefix + \"popstate\", _popstateHandler, _evtNamespace);\r\n eventOn(win, namePrefix + \"locationchange\", _locationChangeHandler, _evtNamespace);\r\n _historyListenerAdded = true;\r\n }\r\n function _addUnhandledPromiseRejectionTracking(_window, _location) {\r\n _self[_DYN__ADD_HOOK /* @min:%2e_addHook */](onConfigChange(_extConfig, function () {\r\n _enableUnhandledPromiseRejectionTracking = _extConfig[_DYN_ENABLE_UNHANDLED_PRO12 /* @min:%2eenableUnhandledPromiseRejectionTracking */] === true;\r\n _autoExceptionInstrumented = _autoExceptionInstrumented || _extConfig[_DYN_AUTO_UNHANDLED_PROMI13 /* @min:%2eautoUnhandledPromiseInstrumented */];\r\n if (_enableUnhandledPromiseRejectionTracking && !_autoUnhandledPromiseInstrumented) {\r\n // We want to enable exception auto collection and it has not been done so yet\r\n _addHook(InstrumentEvent(_window, \"onunhandledrejection\", {\r\n ns: _evtNamespace,\r\n rsp: function (callDetails, error) {\r\n if (_enableUnhandledPromiseRejectionTracking && callDetails.rslt !== true) { // handled could be typeof function\r\n _self[_DYN__ONERROR /* @min:%2e_onerror */](Exception[_DYN__CREATE_AUTO_EXCEPTI6 /* @min:%2eCreateAutoException */](_getReason(error), _location ? _location[_DYN_HREF /* @min:%2ehref */] : \"\", 0, 0, error, callDetails.evt));\r\n }\r\n }\r\n }, false));\r\n _extConfig[_DYN_AUTO_UNHANDLED_PROMI13 /* @min:%2eautoUnhandledPromiseInstrumented */] = _autoUnhandledPromiseInstrumented = true;\r\n }\r\n }));\r\n }\r\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 - {eLoggingSeverity} - The severity of the log message\r\n * @param msgId - {_eInternalLogMessage} - The log message.\r\n */\r\n function _throwInternal(severity, msgId, msg, properties, isUserAct) {\r\n _self[_DYN_DIAG_LOG /* @min:%2ediagLog */]().throwInternal(severity, msgId, msg, properties, isUserAct);\r\n }\r\n function _initDefaults() {\r\n _eventTracking = null;\r\n _pageTracking = null;\r\n _pageViewManager = null;\r\n _pageViewPerformanceManager = null;\r\n _pageVisitTimeManager = null;\r\n _preInitTelemetryInitializers = null;\r\n _isBrowserLinkTrackingEnabled = false;\r\n _browserLinkInitializerAdded = false;\r\n _enableAutoRouteTracking = false;\r\n _historyListenerAdded = false;\r\n _disableExceptionTracking = false;\r\n _autoExceptionInstrumented = false;\r\n _enableUnhandledPromiseRejectionTracking = false;\r\n _autoUnhandledPromiseInstrumented = false;\r\n _autoTrackPageVisitTime = false;\r\n // Counts number of trackAjax invocations.\r\n // By default we only monitor X ajax call per view to avoid too much load.\r\n // Default value is set in config.\r\n // This counter keeps increasing even after the limit is reached.\r\n _trackAjaxAttempts = 0;\r\n // array with max length of 2 that store current url and previous url for SPA page route change trackPageview use.\r\n var location = getLocation(true);\r\n _prevUri = location && location[_DYN_HREF /* @min:%2ehref */] || \"\";\r\n _currUri = null;\r\n _evtNamespace = null;\r\n _extConfig = null;\r\n // Define _self.config\r\n objDefine(_self, \"config\", {\r\n g: function () { return _extConfig; }\r\n });\r\n }\r\n // For backward compatibility\r\n objDefine(_self, \"_pageViewManager\", { g: function () { return _pageViewManager; } });\r\n objDefine(_self, \"_pageViewPerformanceManager\", { g: function () { return _pageViewPerformanceManager; } });\r\n objDefine(_self, \"_pageVisitTimeManager\", { g: function () { return _pageVisitTimeManager; } });\r\n objDefine(_self, \"_evtNamespace\", { g: function () { return \".\" + _evtNamespace; } });\r\n });\r\n return _this;\r\n }\r\n /**\r\n * Get the current cookie manager for this instance\r\n */\r\n AnalyticsPlugin.prototype.getCookieMgr = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n AnalyticsPlugin.prototype.processTelemetry = function (env, itemCtx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AnalyticsPlugin.prototype.trackEvent = function (event, customProperties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\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 */\r\n AnalyticsPlugin.prototype.startTrackEvent = function (name) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\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 */\r\n AnalyticsPlugin.prototype.stopTrackEvent = function (name, properties, measurements) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * @description Log a diagnostic message\r\n * @param trace\r\n * @param ICustomProperties.\r\n * @memberof ApplicationInsights\r\n */\r\n AnalyticsPlugin.prototype.trackTrace = function (trace, customProperties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\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 * @memberof ApplicationInsights\r\n */\r\n AnalyticsPlugin.prototype.trackMetric = function (metric, customProperties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\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 */\r\n AnalyticsPlugin.prototype.trackPageView = function (pageView, customProperties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\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 */\r\n AnalyticsPlugin.prototype.sendPageViewInternal = function (pageView, properties, systemProperties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * @ignore INTERNAL ONLY\r\n * @param pageViewPerformance\r\n * @param properties\r\n */\r\n AnalyticsPlugin.prototype.sendPageViewPerformanceInternal = function (pageViewPerformance, properties, systemProperties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Send browser performance metrics.\r\n * @param pageViewPerformance\r\n * @param customProperties\r\n */\r\n AnalyticsPlugin.prototype.trackPageViewPerformance = function (pageViewPerformance, customProperties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\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 */\r\n AnalyticsPlugin.prototype.startTrackPage = function (name) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\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 */\r\n AnalyticsPlugin.prototype.stopTrackPage = function (name, url, properties, measurement) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * @ignore INTERNAL ONLY\r\n * @param exception\r\n * @param properties\r\n * @param systemProperties\r\n */\r\n AnalyticsPlugin.prototype.sendExceptionInternal = function (exception, customProperties, systemProperties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\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 * @memberof ApplicationInsights\r\n */\r\n AnalyticsPlugin.prototype.trackException = function (exception, customProperties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * @description Custom error handler for Application Insights Analytics\r\n * @param exception\r\n * @memberof ApplicationInsights\r\n */\r\n AnalyticsPlugin.prototype._onerror = function (exception) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AnalyticsPlugin.prototype.addTelemetryInitializer = function (telemetryInitializer) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n AnalyticsPlugin.prototype.initialize = function (config, core, extensions, pluginChain) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AnalyticsPlugin.Version = '3.0.2'; // Not currently used anywhere\r\n return AnalyticsPlugin;\r\n}(BaseTelemetryPlugin));\r\nexport { AnalyticsPlugin };\r\n//# sourceMappingURL=AnalyticsPlugin.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { utlCanUseSessionStorage, utlGetSessionStorage, utlRemoveSessionStorage, utlSetSessionStorage } from \"@microsoft/applicationinsights-common\";\r\nimport { _warnToConsole, dateNow, dumpObj, getJSON, hasJSON, throwError } from \"@microsoft/applicationinsights-core-js\";\r\nimport { objDefine } from \"@nevware21/ts-utils\";\r\nimport { _DYN_PAGE_VISIT_START_TIM18, _DYN_TRACK_PREVIOUS_PAGE_1 } from \"../../__DynamicConstants\";\r\n/**\r\n * Used to track page visit durations\r\n */\r\nvar PageVisitTimeManager = /** @class */ (function () {\r\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 */\r\n function PageVisitTimeManager(logger, pageVisitTimeTrackingHandler) {\r\n var prevPageVisitDataKeyName = \"prevPageVisitData\";\r\n dynamicProto(PageVisitTimeManager, this, function (_self) {\r\n _self[_DYN_TRACK_PREVIOUS_PAGE_1 /* @min:%2etrackPreviousPageVisit */] = function (currentPageName, currentPageUrl) {\r\n try {\r\n // Restart timer for new page view\r\n var prevPageVisitTimeData = restartPageVisitTimer(currentPageName, currentPageUrl);\r\n // If there was a page already being timed, track the visit time for it now.\r\n if (prevPageVisitTimeData) {\r\n pageVisitTimeTrackingHandler(prevPageVisitTimeData.pageName, prevPageVisitTimeData.pageUrl, prevPageVisitTimeData.pageVisitTime);\r\n }\r\n }\r\n catch (e) {\r\n _warnToConsole(logger, \"Auto track page visit time failed, metric will not be collected: \" + dumpObj(e));\r\n }\r\n };\r\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 */\r\n function restartPageVisitTimer(pageName, pageUrl) {\r\n var prevPageVisitData = null;\r\n try {\r\n prevPageVisitData = stopPageVisitTimer();\r\n if (utlCanUseSessionStorage()) {\r\n if (utlGetSessionStorage(logger, prevPageVisitDataKeyName) != null) {\r\n throwError(\"Cannot call startPageVisit consecutively without first calling stopPageVisit\");\r\n }\r\n var currPageVisitDataStr = getJSON().stringify(new PageVisitData(pageName, pageUrl));\r\n utlSetSessionStorage(logger, prevPageVisitDataKeyName, currPageVisitDataStr);\r\n }\r\n }\r\n catch (e) {\r\n _warnToConsole(logger, \"Call to restart failed: \" + dumpObj(e));\r\n prevPageVisitData = null;\r\n }\r\n return prevPageVisitData;\r\n }\r\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 */\r\n function stopPageVisitTimer() {\r\n var prevPageVisitData = null;\r\n try {\r\n if (utlCanUseSessionStorage()) {\r\n // Define end time of page's visit\r\n var pageVisitEndTime = dateNow();\r\n // Try to retrieve page name and start time from session storage\r\n var pageVisitDataJsonStr = utlGetSessionStorage(logger, prevPageVisitDataKeyName);\r\n if (pageVisitDataJsonStr && hasJSON()) {\r\n // if previous page data exists, set end time of visit\r\n prevPageVisitData = getJSON().parse(pageVisitDataJsonStr);\r\n prevPageVisitData.pageVisitTime = pageVisitEndTime - prevPageVisitData[_DYN_PAGE_VISIT_START_TIM18 /* @min:%2epageVisitStartTime */];\r\n // Remove data from storage since we already used it\r\n utlRemoveSessionStorage(logger, prevPageVisitDataKeyName);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n _warnToConsole(logger, \"Stop page visit timer failed: \" + dumpObj(e));\r\n prevPageVisitData = null;\r\n }\r\n return prevPageVisitData;\r\n }\r\n // For backward compatibility\r\n objDefine(_self, \"_logger\", { g: function () { return logger; } });\r\n objDefine(_self, \"pageVisitTimeTrackingHandler\", { g: function () { return pageVisitTimeTrackingHandler; } });\r\n });\r\n }\r\n /**\r\n * Tracks the previous page visit time telemetry (if exists) and starts timing of new page visit time\r\n * @param currentPageName - Name of page to begin timing for visit duration\r\n * @param currentPageUrl - Url of page to begin timing for visit duration\r\n */\r\n PageVisitTimeManager.prototype.trackPreviousPageVisit = function (currentPageName, currentPageUrl) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n return PageVisitTimeManager;\r\n}());\r\nexport { PageVisitTimeManager };\r\nvar PageVisitData = /** @class */ (function () {\r\n function PageVisitData(pageName, pageUrl) {\r\n this[_DYN_PAGE_VISIT_START_TIM18 /* @min:%2epageVisitStartTime */] = dateNow();\r\n this.pageName = pageName;\r\n this.pageUrl = pageUrl;\r\n }\r\n return PageVisitData;\r\n}());\r\nexport { PageVisitData };\r\n//# sourceMappingURL=PageVisitTimeManager.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { dateTimeUtilsDuration } from \"@microsoft/applicationinsights-common\";\r\nimport { _throwInternal } from \"@microsoft/applicationinsights-core-js\";\r\n/**\r\n * Used to record timed events and page views.\r\n */\r\nvar Timing = /** @class */ (function () {\r\n function Timing(logger, name) {\r\n var _self = this;\r\n var _events = {};\r\n _self.start = function (name) {\r\n if (typeof _events[name] !== \"undefined\") {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 62 /* _eInternalMessageId.StartCalledMoreThanOnce */, \"start was called more than once for this event without calling stop.\", { name: name, key: name }, true);\r\n }\r\n _events[name] = +new Date;\r\n };\r\n _self.stop = function (name, url, properties, measurements) {\r\n var start = _events[name];\r\n if (isNaN(start)) {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 63 /* _eInternalMessageId.StopCalledWithoutStart */, \"stop was called without a corresponding start.\", { name: name, key: name }, true);\r\n }\r\n else {\r\n var end = +new Date;\r\n var duration = dateTimeUtilsDuration(start, end);\r\n _self.action(name, url, duration, properties, measurements);\r\n }\r\n delete _events[name];\r\n _events[name] = undefined;\r\n };\r\n }\r\n return Timing;\r\n}());\r\nexport { Timing };\r\n//# sourceMappingURL=Timing.js.map","/*\r\n * @nevware21/ts-async\r\n * https://github.com/nevware21/ts-async\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { objDefineProp } from \"@nevware21/ts-utils\";\r\n\r\nlet _debugState: any;\r\nlet _debugResult: any;\r\nlet _debugHandled: any;\r\n\r\n/**\r\n * @internal\r\n * @ignore\r\n */\r\nexport let _promiseDebugEnabled = false;\r\n\r\nlet _theLogger: (id: string, message: string) => void = null;\r\n\r\n/**\r\n * @internal\r\n * @ignore Internal function enable logging the internal state of the promise during execution, this code and references are\r\n * removed from the production artifacts\r\n */\r\nexport function _debugLog(id: string, message: string) {\r\n //#ifdef DEBUG\r\n //#:(!DEBUG) if (_theLogger) {\r\n //#:(!DEBUG) _theLogger(id, message);\r\n //#:(!DEBUG) }\r\n //#endif\r\n}\r\n\r\n/**\r\n * @internal\r\n * @ignore\r\n * Internal function to add the debug state to the promise so that it provides simular visibility as you would\r\n * see from native promises\r\n * @param thePromise - The Promise implementation\r\n * @param stateFn - The function to return the state of the promise\r\n * @param resultFn - The function to return the result (settled value) of the promise\r\n * @param handledFn - The function to return whether the promise has been handled (used for throwing\r\n * unhandled rejection events)\r\n */\r\nexport function _addDebugState(thePromise: any, stateFn: () => string, resultFn: () => string, handledFn: () => boolean) {\r\n // While the IPromise implementations provide a `state` property, keeping the `[[PromiseState]]`\r\n // as native promises also have a non-enumerable property of the same name\r\n _debugState = _debugState || { toString: () => \"[[PromiseState]]\" };\r\n _debugResult = _debugResult || { toString: () => \"[[PromiseResult]]\" };\r\n _debugHandled = _debugHandled || { toString: () => \"[[PromiseIsHandled]]\" };\r\n \r\n objDefineProp(thePromise, _debugState, { get: stateFn });\r\n objDefineProp(thePromise, _debugResult, { get: resultFn });\r\n objDefineProp(thePromise, _debugHandled, { get: handledFn });\r\n}\r\n\r\n/**\r\n * Debug helper to enable internal debugging of the promise implementations. Disabled by default.\r\n * For the generated packages included in the npm package the `logger` will not be called as the\r\n * `_debugLog` function that uses this logger is removed during packaging.\r\n *\r\n * It is available directly from the repository for unit testing.\r\n *\r\n * @group Debug\r\n * @param enabled - Should debugging be enabled (defaults `false`, when `true` promises will have\r\n * additional debug properties and the `toString` will include extra details.\r\n * @param logger - Optional logger that will log internal state changes, only called in debug\r\n * builds as the calling function is removed is the production artifacts.\r\n * @example\r\n * ```ts\r\n * // The Id is the id of the promise\r\n * // The message is the internal debug message\r\n * function promiseDebugLogger(id: string, message: string) {\r\n * if (console && console.log) {\r\n * console.log(id, message);\r\n * }\r\n * }\r\n *\r\n * setPromiseDebugState(true, promiseDebugLogger);\r\n *\r\n * // While the logger will not be called for the production packages\r\n * // Setting the `enabled` flag to tru will cause each promise to have\r\n * // the following additional properties added\r\n * // [[PromiseState]]; => Same as the `state` property\r\n * // [[PromiseResult]]; => The settled value\r\n * // [[PromiseIsHandled]] => Identifies if the promise has been handled\r\n * // It will also cause the `toString` for the promise to include additional\r\n * // debugging information\r\n * ```\r\n */\r\nexport function setPromiseDebugState(enabled: boolean, logger?: (id: string, message: string) => void) {\r\n _promiseDebugEnabled = enabled;\r\n _theLogger = logger;\r\n}","/*\r\n * @nevware21/ts-async\r\n * https://github.com/nevware21/ts-async\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { isPromiseLike } from \"@nevware21/ts-utils\";\r\nimport { AwaitResponse } from \"../interfaces/await-response\";\r\nimport { IPromise } from \"../interfaces/IPromise\";\r\nimport { FinallyPromiseHandler, RejectedPromiseHandler, ResolvedPromiseHandler } from \"../interfaces/types\";\r\n\r\n/**\r\n * Helper to coallesce the promise resolved / reject into a single callback to simplify error handling.\r\n * @group Await Helper\r\n * @param value - The value or promise like value to wait for\r\n * @param cb - The callback to call with the response of the promise as an IAwaitResponse object.\r\n */\r\nexport function doAwaitResponse(value: T | Promise, cb: (response: AwaitResponse) => void): T | Promise;\r\nexport function doAwaitResponse(value: T | PromiseLike, cb: (response: AwaitResponse) => void): T | PromiseLike;\r\nexport function doAwaitResponse(value: T | IPromise, cb: (response: AwaitResponse) => void): T | IPromise {\r\n return doAwait(value as any, (value) => {\r\n cb && cb({\r\n value: value,\r\n rejected: false\r\n });\r\n },\r\n (reason) => {\r\n cb && cb({\r\n rejected: true,\r\n reason: reason\r\n });\r\n });\r\n}\r\n\r\n/**\r\n * Wait for the promise to resolve or reject, if resolved the callback function will be called with it's value and if\r\n * rejected the rejectFn will be called with the reason. If the passed promise argument is not a promise the callback\r\n * will be called synchronously with the value.\r\n * @group Await Helper\r\n * @param value - The value or promise like value to wait for\r\n * @param resolveFn - The callback to call on the promise successful resolving.\r\n * @param rejectFn - The callback to call when the promise rejects\r\n * @param finallyFn - The callback to call once the promise has resolved or rejected\r\n * @returns The passed value, if it is a promise and there is either a resolve or reject handler\r\n * then it will return a chained promise with the value from the resolve or reject handler (depending\r\n * whether it resolve or rejects)\r\n * @example\r\n * ```ts\r\n * let promise = createPromise((resolve, reject) => {\r\n * resolve(42);\r\n * });\r\n *\r\n * // Handle via a chained promise\r\n * let chainedPromise = promise.then((value) => {\r\n * // Do something with the value\r\n * });\r\n *\r\n * // Handle via doAwait\r\n * doAwait(promise, (value) => {\r\n * // Do something with the value\r\n * });\r\n *\r\n * // It can also handle the raw value, so you could process the result of either a\r\n * // synchrounous return of the value or a Promise\r\n * doAwait(42, (value) => {\r\n * // Do something with the value\r\n * });\r\n * ```\r\n */\r\nexport function doAwait(value: T | Promise, resolveFn: ResolvedPromiseHandler, rejectFn?: RejectedPromiseHandler, finallyFn?: FinallyPromiseHandler): T | Promise;\r\n\r\n/**\r\n * Wait for the promise to resolve or reject, if resolved the callback function will be called with it's value and if\r\n * rejected the rejectFn will be called with the reason. If the passed promise argument is not a promise the callback\r\n * will be called synchronously with the value.\r\n * @group Await Helper\r\n * @param value - The value or promise like value to wait for\r\n * @param resolveFn - The callback to call on the promise successful resolving.\r\n * @param rejectFn - The callback to call when the promise rejects\r\n * @param finallyFn - The callback to call once the promise has resolved or rejected\r\n * @returns The passed value, if it is a promise and there is either a resolve or reject handler\r\n * then it will return a chained promise with the value from the resolve or reject handler (depending\r\n * whether it resolve or rejects)\r\n * @example\r\n * ```ts\r\n * let promise = createPromise((resolve, reject) => {\r\n * resolve(42);\r\n * });\r\n *\r\n * // Handle via a chained promise\r\n * let chainedPromise = promise.then((value) => {\r\n * // Do something with the value\r\n * });\r\n *\r\n * // Handle via doAwait\r\n * doAwait(promise, (value) => {\r\n * // Do something with the value\r\n * });\r\n *\r\n * // It can also handle the raw value, so you could process the result of either a\r\n * // synchrounous return of the value or a Promise\r\n * doAwait(42, (value) => {\r\n * // Do something with the value\r\n * });\r\n * ```\r\n */\r\nexport function doAwait(value: T | PromiseLike, resolveFn: ResolvedPromiseHandler, rejectFn?: RejectedPromiseHandler, finallyFn?: FinallyPromiseHandler): T | PromiseLike;\r\n\r\n/**\r\n * Wait for the promise to resolve or reject, if resolved the callback function will be called with it's value and if\r\n * rejected the rejectFn will be called with the reason. If the passed promise argument is not a promise the callback\r\n * will be called synchronously with the value.\r\n * @group Await Helper\r\n * @param value - The value or promise like value to wait for\r\n * @param resolveFn - The callback to call on the promise successful resolving.\r\n * @param rejectFn - The callback to call when the promise rejects\r\n * @returns The passed value, if it is a promise and there is either a resolve or reject handler\r\n * then it will return a chained promise with the value from the resolve or reject handler (depending\r\n * whether it resolve or rejects)\r\n * @example\r\n * ```ts\r\n * let promise = createPromise((resolve, reject) => {\r\n * resolve(42);\r\n * });\r\n *\r\n * // Handle via a chained promise\r\n * let chainedPromise = promise.then((value) => {\r\n * // Do something with the value\r\n * });\r\n *\r\n * // Handle via doAwait\r\n * doAwait(promise, (value) => {\r\n * // Do something with the value\r\n * });\r\n *\r\n * // It can also handle the raw value, so you could process the result of either a\r\n * // synchrounous return of the value or a Promise\r\n * doAwait(42, (value) => {\r\n * // Do something with the value\r\n * });\r\n * ```\r\n */\r\nexport function doAwait(value: T | IPromise, resolveFn: ResolvedPromiseHandler, rejectFn?: RejectedPromiseHandler, finallyFn?: FinallyPromiseHandler): T | IPromise {\r\n let result = value;\r\n \r\n if (isPromiseLike(value)) {\r\n if (resolveFn || rejectFn) {\r\n result = value.then(resolveFn, rejectFn) as any;\r\n }\r\n } else {\r\n resolveFn && resolveFn(value as T);\r\n }\r\n\r\n if (finallyFn) {\r\n result = doFinally(result as any, finallyFn);\r\n }\r\n\r\n return result as any;\r\n}\r\n\r\n/**\r\n * Wait for the promise to resolve or reject and then call the finallyFn. If the passed promise argument is not a promise the callback\r\n * will be called synchronously with the value. If the passed promise doesn't implement finally then a finally implementation will be\r\n * simulated using then(..., ...).\r\n * @group Await Helper\r\n * @param value - The value or promise like value to wait for\r\n * @param finallyFn - The finally function to call once the promise has resolved or rejected\r\n */\r\nexport function doFinally(value: T | Promise, finallyFn: FinallyPromiseHandler): T | Promise;\r\n\r\n/**\r\n * Wait for the promise to resolve or reject and then call the finallyFn. If the passed promise argument is not a promise the callback\r\n * will be called synchronously with the value. If the passed promise doesn't implement finally then a finally implementation will be\r\n * simulated using then(..., ...).\r\n * @group Await Helper\r\n * @param value - The value or promise like value to wait for\r\n * @param finallyFn - The finally function to call once the promise has resolved or rejected\r\n */\r\nexport function doFinally(value: T | PromiseLike, finallyFn: FinallyPromiseHandler): T | PromiseLike;\r\n\r\n/**\r\n * Wait for the promise to resolve or reject and then call the finallyFn. If the passed promise argument is not a promise the callback\r\n * will be called synchronously with the value. If the passed promise doesn't implement finally then a finally implementation will be\r\n * simulated using then(..., ...).\r\n * @group Await Helper\r\n * @param value - The value or promise like value to wait for\r\n * @param finallyFn - The finally function to call once the promise has resolved or rejected\r\n */\r\nexport function doFinally(value: T | IPromise, finallyFn: FinallyPromiseHandler): T | IPromise {\r\n let result = value;\r\n if (finallyFn) {\r\n if (isPromiseLike(value)) {\r\n if ((value as IPromise).finally) {\r\n result = (value as IPromise).finally(finallyFn);\r\n } else {\r\n // Simulate finally if not available\r\n result = value.then(\r\n function(value) {\r\n finallyFn();\r\n return value;\r\n }, function(reason: any) {\r\n finallyFn();\r\n throw reason;\r\n });\r\n }\r\n } else {\r\n finallyFn();\r\n }\r\n }\r\n\r\n return result;\r\n}","/*\r\n * @nevware21/ts-async\r\n * https://github.com/nevware21/ts-async\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\n/**\r\n * @ignore -- Don't include in the generated documentation\r\n * @internal\r\n */\r\nexport const enum ePromiseState {\r\n Pending = 0,\r\n Resolving = 1,\r\n Resolved = 2,\r\n Rejected = 3\r\n}\r\n\r\n/**\r\n * @ignore -- Don't include in the generated documentation\r\n * @internal\r\n */\r\nexport const STRING_STATES: string[] = [\r\n \"pending\", \"resolving\", \"resolved\", \"rejected\"\r\n];\r\n","/*\r\n * @nevware21/ts-async\r\n * https://github.com/nevware21/ts-async\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { dumpObj, getDocument, safeGetLazy, ILazyValue, getInst } from \"@nevware21/ts-utils\";\r\n\r\nconst DISPATCH_EVENT = \"dispatchEvent\";\r\nlet _hasInitEvent: ILazyValue;\r\n\r\n/**\r\n * @internal\r\n * @ignore\r\n * @param target\r\n * @param evtName\r\n * @param populateEvent\r\n * @param useNewEvent\r\n */\r\nexport function emitEvent(target: any, evtName: string, populateEvent: (theEvt: Event | any) => Event | any, useNewEvent: boolean) {\r\n\r\n let doc = getDocument();\r\n !_hasInitEvent && (_hasInitEvent = safeGetLazy(() => {\r\n let evt: any;\r\n if (doc && doc.createEvent) {\r\n evt = doc.createEvent(\"Event\");\r\n }\r\n \r\n return (!!evt && evt.initEvent);\r\n }, null));\r\n\r\n let theEvt: Event = _hasInitEvent.v ? doc.createEvent(\"Event\") : (useNewEvent ? new Event(evtName) : {} as Event);\r\n populateEvent && populateEvent(theEvt);\r\n\r\n if (_hasInitEvent.v) {\r\n theEvt.initEvent(evtName, false, true);\r\n }\r\n\r\n if (theEvt && target[DISPATCH_EVENT]) {\r\n target[DISPATCH_EVENT](theEvt);\r\n } else {\r\n let handler = target[\"on\" + evtName];\r\n if (handler) {\r\n handler(theEvt);\r\n } else {\r\n let theConsole = getInst(\"console\");\r\n theConsole && (theConsole[\"error\"] || theConsole[\"log\"])(evtName, dumpObj(theEvt));\r\n }\r\n }\r\n}\r\n","/*\r\n * @nevware21/ts-async\r\n * https://github.com/nevware21/ts-async\r\n *\r\n * Copyright (c) 2023 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nexport const STR_PROMISE = \"Promise\";","/*\r\n * @nevware21/ts-async\r\n * https://github.com/nevware21/ts-async\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport {\r\n arrForEach, arrSlice, dumpObj, getKnownSymbol, hasSymbol, isFunction, isPromiseLike, isUndefined,\r\n throwTypeError, WellKnownSymbols, objToString, scheduleTimeout, ITimerHandler, getWindow, isNode,\r\n getGlobal, ILazyValue, objDefine, objDefineProp, lazySafeGetInst\r\n} from \"@nevware21/ts-utils\";\r\nimport { doAwait } from \"./await\";\r\nimport { _addDebugState, _debugLog, _promiseDebugEnabled } from \"./debug\";\r\nimport { IPromise } from \"../interfaces/IPromise\";\r\nimport { PromisePendingProcessor } from \"./itemProcessor\";\r\nimport {\r\n FinallyPromiseHandler, PromiseCreatorFn, PromiseExecutor, RejectedPromiseHandler, ResolvedPromiseHandler\r\n} from \"../interfaces/types\";\r\nimport { ePromiseState, STRING_STATES } from \"../internal/state\";\r\nimport { emitEvent } from \"./event\";\r\nimport { STR_PROMISE } from \"../internal/constants\";\r\n\r\nconst NODE_UNHANDLED_REJECTION = \"unhandledRejection\";\r\nconst UNHANDLED_REJECTION = NODE_UNHANDLED_REJECTION.toLowerCase();\r\n\r\nlet _currentPromiseId: number[] = [];\r\nlet _uniquePromiseId = 0;\r\nlet _unhandledRejectionTimeout = 10;\r\n\r\nlet _hasPromiseRejectionEvent: ILazyValue;\r\n\r\nfunction dumpFnObj(value: any) {\r\n if (isFunction(value)) {\r\n return value.toString();\r\n }\r\n\r\n return dumpObj(value);\r\n}\r\n\r\n/**\r\n * @ignore\r\n * @internal\r\n *\r\n * Implementing a simple synchronous promise interface for support within any environment that\r\n * doesn't support the Promise API\r\n * @param newPromise - The delegate function used to create a new promise object\r\n * @param processor - The function to use to process the pending\r\n * @param executor - The resolve function\r\n * @param additionalArgs - [Optional] Additional arguments that will be passed to the PromiseCreatorFn\r\n */\r\nexport function _createPromise(newPromise: PromiseCreatorFn, processor: PromisePendingProcessor, executor: PromiseExecutor, ...additionalArgs: any): IPromise;\r\nexport function _createPromise(newPromise: PromiseCreatorFn, processor: PromisePendingProcessor, executor: PromiseExecutor): IPromise {\r\n let additionalArgs = arrSlice(arguments, 3);\r\n let _state = ePromiseState.Pending;\r\n let _hasResolved = false;\r\n let _settledValue: T;\r\n let _queue: (() => void)[] = [];\r\n let _id = _uniquePromiseId++;\r\n let _parentId = _currentPromiseId.length > 0 ? _currentPromiseId[_currentPromiseId.length - 1] : undefined;\r\n let _handled = false;\r\n let _unHandledRejectionHandler: ITimerHandler = null;\r\n let _thePromise: IPromise;\r\n\r\n !_hasPromiseRejectionEvent && (_hasPromiseRejectionEvent = lazySafeGetInst(STR_PROMISE + \"RejectionEvent\"));\r\n\r\n // https://tc39.es/ecma262/#sec-promise.prototype.then\r\n const _then = (onResolved?: ResolvedPromiseHandler, onRejected?: RejectedPromiseHandler): IPromise => {\r\n try {\r\n _currentPromiseId.push(_id);\r\n _handled = true;\r\n _unHandledRejectionHandler && _unHandledRejectionHandler.cancel();\r\n _unHandledRejectionHandler = null;\r\n\r\n //#ifdef DEBUG\r\n //#:(!DEBUG) _debugLog(_toString(), \"then(\" + dumpFnObj(onResolved)+ \", \" + dumpFnObj(onResolved) + \")\");\r\n //#endif\r\n let thenPromise = newPromise(function (resolve, reject) {\r\n // Queue the new promise returned to be resolved or rejected\r\n // when this promise settles.\r\n _queue.push(function () {\r\n // https://tc39.es/ecma262/#sec-newpromisereactionjob\r\n //let value: any;\r\n try {\r\n // First call the onFulfilled or onRejected handler, on the settled value\r\n // of this promise. If the corresponding `handler` does not exist, simply\r\n // pass through the settled value.\r\n //#ifdef DEBUG\r\n //#:(!DEBUG) _debugLog(_toString(), \"Handling settled value \" + dumpFnObj(_settledValue));\r\n //#endif\r\n let handler = _state === ePromiseState.Resolved ? onResolved : onRejected;\r\n let value = isUndefined(handler) ? _settledValue : (isFunction(handler) ? handler(_settledValue) : handler);\r\n //#ifdef DEBUG\r\n //#:(!DEBUG) _debugLog(_toString(), \"Handling Result \" + dumpFnObj(value));\r\n //#endif\r\n \r\n if (isPromiseLike(value)) {\r\n // The called handlers returned a new promise, so the chained promise\r\n // will follow the state of this promise.\r\n value.then(resolve as any, reject);\r\n } else if (handler) {\r\n // If we have a handler then chained promises are always \"resolved\" with the result returned\r\n resolve(value as any);\r\n } else if (_state === ePromiseState.Rejected) {\r\n // If this promise is rejected then the chained promise should be rejected\r\n // with either the settled value of this promise or the return value of the handler.\r\n reject(value);\r\n } else {\r\n // If this promise is fulfilled, then the chained promise is also fulfilled\r\n // with either the settled value of this promise or the return value of the handler.\r\n resolve(value as any);\r\n }\r\n } catch (e) {\r\n reject(e);\r\n }\r\n });\r\n \r\n //#ifdef DEBUG\r\n //#:(!DEBUG) _debugLog(_toString(), \"Added to Queue \" + _queue.length);\r\n //#endif\r\n \r\n // If this promise is already settled, then immediately process the callback we\r\n // just added to the queue.\r\n if (_hasResolved) {\r\n _processQueue();\r\n }\r\n }, additionalArgs);\r\n \r\n //#ifdef DEBUG\r\n //#:(!DEBUG) _debugLog(_toString(), \"Created -> \" + thenPromise.toString());\r\n //#endif\r\n \r\n return thenPromise;\r\n \r\n } finally {\r\n _currentPromiseId.pop();\r\n }\r\n }\r\n\r\n // https://tc39.es/ecma262/#sec-promise.prototype.catch\r\n const _catch = (onRejected: RejectedPromiseHandler) => {\r\n // Reuse then onRejected to support rejection\r\n return _then(undefined, onRejected);\r\n }\r\n\r\n // https://tc39.es/ecma262/#sec-promise.prototype.finally\r\n const _finally = (onFinally: FinallyPromiseHandler): IPromise => {\r\n let thenFinally: any = onFinally;\r\n let catchFinally: any = onFinally;\r\n if (isFunction(onFinally)) {\r\n thenFinally = function(value: TResult1 | TResult2) {\r\n onFinally && onFinally();\r\n return value;\r\n }\r\n \r\n catchFinally = function(reason: any) {\r\n onFinally && onFinally();\r\n throw reason;\r\n }\r\n }\r\n\r\n return _then(thenFinally as any, catchFinally as any);\r\n }\r\n\r\n const _strState = () => {\r\n return STRING_STATES[_state];\r\n }\r\n\r\n const _processQueue = () => {\r\n if (_queue.length > 0) {\r\n // The onFulfilled and onRejected handlers must be called asynchronously. Thus,\r\n // we make a copy of the queue and work on it once the current call stack unwinds.\r\n let pending = _queue.slice();\r\n _queue = [];\r\n\r\n //#ifdef DEBUG\r\n //#:(!DEBUG) _debugLog(_toString(), \"Processing queue \" + pending.length);\r\n //#endif\r\n\r\n _handled = true;\r\n processor(pending);\r\n //#ifdef DEBUG\r\n //#:(!DEBUG) _debugLog(_toString(), \"Processing done\");\r\n //#endif\r\n _unHandledRejectionHandler && _unHandledRejectionHandler.cancel();\r\n _unHandledRejectionHandler = null;\r\n\r\n } else {\r\n //#ifdef DEBUG\r\n //#:(!DEBUG) _debugLog(_toString(), \"Empty Processing queue \");\r\n //#endif\r\n }\r\n }\r\n\r\n const _createSettleIfFn = (newState: ePromiseState, allowState: ePromiseState) => {\r\n return (theValue: T) => {\r\n if (_state === allowState) {\r\n if (newState === ePromiseState.Resolved && isPromiseLike(theValue)) {\r\n _state = ePromiseState.Resolving;\r\n //#ifdef DEBUG\r\n //#:(!DEBUG) _debugLog(_toString(), \"Resolving\");\r\n //#endif\r\n theValue.then(\r\n _createSettleIfFn(ePromiseState.Resolved, ePromiseState.Resolving),\r\n _createSettleIfFn(ePromiseState.Rejected, ePromiseState.Resolving));\r\n return;\r\n }\r\n\r\n _state = newState;\r\n _hasResolved = true;\r\n _settledValue = theValue;\r\n //#ifdef DEBUG\r\n //#:(!DEBUG) _debugLog(_toString(), _strState());\r\n //#endif\r\n _processQueue();\r\n if (!_handled && newState === ePromiseState.Rejected && !_unHandledRejectionHandler) {\r\n _unHandledRejectionHandler = scheduleTimeout(_notifyUnhandledRejection, _unhandledRejectionTimeout)\r\n }\r\n } else {\r\n //#ifdef DEBUG\r\n //#:(!DEBUG) _debugLog(_toString(), \"Already \" + _strState());\r\n //#endif\r\n }\r\n };\r\n }\r\n\r\n const _notifyUnhandledRejection = () => {\r\n if (!_handled) {\r\n if (isNode()) {\r\n //#ifdef DEBUG\r\n //#:(!DEBUG) _debugLog(_toString(), \"Emitting \" + NODE_UNHANDLED_REJECTION);\r\n //#endif\r\n process.emit(NODE_UNHANDLED_REJECTION, _settledValue, _thePromise);\r\n } else {\r\n let gbl = getWindow() || getGlobal();\r\n \r\n //#ifdef DEBUG\r\n //#:(!DEBUG) _debugLog(_toString(), \"Emitting \" + UNHANDLED_REJECTION);\r\n //#endif\r\n emitEvent(gbl, UNHANDLED_REJECTION, (theEvt: any) => {\r\n objDefine(theEvt, \"promise\", { g: () => _thePromise });\r\n theEvt.reason = _settledValue;\r\n return theEvt;\r\n }, !!_hasPromiseRejectionEvent.v);\r\n }\r\n }\r\n }\r\n\r\n _thePromise = {\r\n then: _then,\r\n \"catch\": _catch,\r\n finally: _finally\r\n } as any;\r\n\r\n objDefineProp(_thePromise, \"state\", {\r\n get: _strState\r\n });\r\n\r\n if (_promiseDebugEnabled) {\r\n // eslint-disable-next-line brace-style\r\n _addDebugState(_thePromise, _strState, () => { return objToString(_settledValue); }, () => _handled);\r\n }\r\n\r\n if (hasSymbol()) {\r\n _thePromise[getKnownSymbol(WellKnownSymbols.toStringTag)] = \"IPromise\";\r\n }\r\n\r\n const _toString = () => {\r\n return \"IPromise\" + (_promiseDebugEnabled ? \"[\" + _id + (!isUndefined(_parentId) ? (\":\" + _parentId) : \"\") + \"]\" : \"\") + \" \" + _strState() + (_hasResolved ? (\" - \" + dumpFnObj(_settledValue)) : \"\");\r\n }\r\n\r\n _thePromise.toString = _toString;\r\n\r\n (function _initialize() {\r\n if (!isFunction(executor)) {\r\n throwTypeError(STR_PROMISE + \": executor is not a function - \" + dumpFnObj(executor));\r\n }\r\n\r\n const _rejectFn = _createSettleIfFn(ePromiseState.Rejected, ePromiseState.Pending);\r\n try {\r\n //#ifdef DEBUG\r\n //#:(!DEBUG) _debugLog(_toString(), \"Executing\");\r\n //#endif\r\n executor.call(\r\n _thePromise,\r\n _createSettleIfFn(ePromiseState.Resolved, ePromiseState.Pending),\r\n _rejectFn);\r\n } catch (e) {\r\n _rejectFn(e);\r\n }\r\n })();\r\n\r\n //#ifdef DEBUG\r\n //#:(!DEBUG) _debugLog(_toString(), \"Returning\");\r\n //#endif\r\n return _thePromise;\r\n}\r\n\r\n/**\r\n * @ignore\r\n * @internal\r\n * Returns a function which when called will return a new Promise object that resolves to an array of the\r\n * results from the input promises. The returned promise will resolve when all of the inputs' promises have\r\n * resolved, or if the input contains no promises. It rejects immediately upon any of the input promises\r\n * rejected or non-promises throwing an error, and will reject with this first rejection message / error.\r\n * @param newPromise - The delegate function used to create a new promise object the new promise instance.\r\n * @returns A function to create a promise that will be resolved when all arguments are resolved.\r\n */\r\nexport function _createAllPromise(newPromise: PromiseCreatorFn): (input: PromiseLike[], ...additionalArgs: any) => IPromise {\r\n return function (input: PromiseLike[]): IPromise {\r\n let additionalArgs = arrSlice(arguments, 1);\r\n return newPromise((resolve, reject) => {\r\n try {\r\n let values = [] as any;\r\n let pending = 1; // Prefix to 1 so we finish iterating over all of the input promises first\r\n\r\n arrForEach(input, (item, idx) => {\r\n if (item) {\r\n pending++;\r\n doAwait(item, (value) => {\r\n // Set the result values\r\n values[idx] = value;\r\n if (--pending === 0) {\r\n resolve(values);\r\n }\r\n }, reject);\r\n }\r\n });\r\n\r\n // Now decrement the pending so that we finish correctly\r\n pending--;\r\n if (pending === 0) {\r\n // All promises were either resolved or where not a promise\r\n resolve(values);\r\n }\r\n } catch (e) {\r\n reject(e);\r\n }\r\n }, additionalArgs);\r\n };\r\n}\r\n\r\n/**\r\n * @ignore\r\n * @internal\r\n * The createResolvedPromise returns a PromiseLike object that is resolved with a given value. If the value is\r\n * PromiseLike (i.e. has a \"then\" method), the returned promise will \"follow\" that thenable, adopting its eventual\r\n * state; otherwise the returned promise will be fulfilled with the value. This function flattens nested layers\r\n * of promise-like objects (e.g. a promise that resolves to a promise that resolves to something) into a single layer.\r\n * @param newPromise - The delegate function used to create a new promise object\r\n * @param value Argument to be resolved by this Promise. Can also be a Promise or a thenable to resolve.\r\n * @param additionalArgs - Any additional arguments that should be passed to the delegate to assist with the creation of\r\n * the new promise instance.\r\n */\r\nexport function _createResolvedPromise(newPromise: PromiseCreatorFn): (value: T, ...additionalArgs: any) => IPromise {\r\n return function (value: T): IPromise {\r\n let additionalArgs = arrSlice(arguments, 1);\r\n if (isPromiseLike(value)) {\r\n return value as unknown as IPromise;\r\n }\r\n \r\n return newPromise((resolve) => {\r\n resolve(value);\r\n }, additionalArgs);\r\n };\r\n}\r\n\r\n/**\r\n * @ignore\r\n * @internal\r\n * Return a promise like object that is rejected with the given reason.\r\n * @param newPromise - The delegate function used to create a new promise object\r\n * @param reason - The rejection reason\r\n * @param additionalArgs - Any additional arguments that should be passed to the delegate to assist with the creation of\r\n * the new promise instance.\r\n */\r\nexport function _createRejectedPromise(newPromise: PromiseCreatorFn): (reason: any, ...additionalArgs: any) => IPromise {\r\n return function (reason: any): IPromise {\r\n let additionalArgs = arrSlice(arguments, 1);\r\n return newPromise((_resolve, reject) => {\r\n reject(reason);\r\n }, additionalArgs);\r\n };\r\n}\r\n","/*\r\n * @nevware21/ts-async\r\n * https://github.com/nevware21/ts-async\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { arrForEach, isNumber, scheduleIdleCallback, scheduleTimeout } from \"@nevware21/ts-utils\";\r\nimport { IPromise } from \"../interfaces/IPromise\";\r\nimport { PromiseExecutor } from \"../interfaces/types\";\r\n\r\nexport type PromisePendingProcessor = (pending: PromisePendingFn[]) => void;\r\nexport type PromisePendingFn = () => void;\r\nexport type PromiseCreatorFn = (newExecutor: PromiseExecutor, ...extraArgs: any) => IPromise;\r\n\r\nconst _processPendingItems = (pending: PromisePendingFn[]) => {\r\n arrForEach(pending, (fn: PromisePendingFn) => {\r\n try {\r\n fn();\r\n } catch (e) {\r\n // Don't let 1 failing handler break all others\r\n // TODO: Add some form of error reporting (i.e. Call any registered JS error handler so the error is reported)\r\n }\r\n });\r\n}\r\n\r\n/**\r\n * @internal\r\n * @ignore\r\n * Return an item processor that processes all of the pending items synchronously\r\n * @return An item processor\r\n */\r\nexport function syncItemProcessor(): (pending: PromisePendingFn[]) => void {\r\n return _processPendingItems;\r\n}\r\n\r\n/**\r\n * @internal\r\n * @ignore\r\n * Return an item processor that processes all of the pending items asynchronously using the optional timeout.\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero.\r\n * @return An item processor\r\n */\r\nexport function timeoutItemProcessor(timeout?: number): (pending: PromisePendingFn[]) => void {\r\n let callbackTimeout = isNumber(timeout) ? timeout : 0;\r\n\r\n return (pending: PromisePendingFn[]) => {\r\n scheduleTimeout(() => {\r\n _processPendingItems(pending);\r\n }, callbackTimeout);\r\n }\r\n}\r\n\r\n/**\r\n * @internal\r\n * @ignore\r\n * Return an item processor that processes all of the pending items using an idle callback (if available) or based on\r\n * a timeout (when `requestIdenCallback` is not supported) using the optional timeout.\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero.\r\n * @return An item processor\r\n */\r\nexport function idleItemProcessor(timeout?: number): (pending: PromisePendingFn[]) => void {\r\n let options: any;\r\n if (timeout >= 0) {\r\n options = {\r\n timeout: +timeout\r\n };\r\n }\r\n\r\n return (pending: PromisePendingFn[]) => {\r\n scheduleIdleCallback((deadline: IdleDeadline) => {\r\n _processPendingItems(pending);\r\n }, options);\r\n };\r\n}","/*\r\n * @nevware21/ts-async\r\n * https://github.com/nevware21/ts-async\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { _createAllPromise, _createPromise, _createRejectedPromise, _createResolvedPromise } from \"./base\";\r\nimport { IPromise } from \"../interfaces/IPromise\";\r\nimport { timeoutItemProcessor } from \"./itemProcessor\";\r\nimport { PromiseExecutor } from \"../interfaces/types\";\r\n\r\n/**\r\n * Creates an asynchronous Promise instance that when resolved or rejected will execute it's pending chained operations\r\n * __asynchronously__ using the optional provided timeout value to schedule when the chained items will be ececuted.\r\n * @group Async\r\n * @group Promise\r\n * @param executor - The function to be executed during the creation of the promise. Any errors thrown in the executor will\r\n * cause the promise to be rejected. The return value of the executor is always ignored\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero.\r\n */\r\nexport function createAsyncPromise(executor: PromiseExecutor, timeout?: number): IPromise {\r\n return _createPromise(createAsyncPromise, timeoutItemProcessor(timeout), executor, timeout);\r\n}\r\n\r\n/**\r\n * Returns a single asynchronous Promise instance that resolves to an array of the results from the input promises.\r\n * This returned promise will resolve and execute it's pending chained operations __asynchronously__ using the optional\r\n * provided timeout value to schedule when the chained items will be executed, or if the input contains no promises.\r\n * It rejects immediately upon any of the input promises rejected or non-promises throwing an error,\r\n * and will reject with this first rejection message / error.\r\n * When resolved or rejected any additional chained operations will execute __asynchronously__ using the optional\r\n * timeout value to schedul when the chained item will be executed (eg. `then()`; `catch()`; `finally()`).\r\n * @group Async\r\n * @group All\r\n * @param input - The array of promises to wait to be resolved / rejected before resolving or rejecting the new promise\r\n * @param timeout\r\n * @returns\r\n * \r\n * - An already resolved `Promise`, if the input passed is empty.\r\n *
- A pending `Promise` in all other cases. This returned promise is then resolved/rejected __synchronously__\r\n * (as soon as the pending items is empty) when all the promises in the given input have resolved, or if any of the\r\n * promises reject.\r\n *
\r\n */\r\nexport const createAsyncAllPromise: (input: PromiseLike[], timeout?: number) => IPromise = _createAllPromise(createAsyncPromise);\r\n\r\n// /**\r\n// * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\r\n// * or rejected.\r\n// * @param values An array of Promises.\r\n// * @returns A new Promise.\r\n// */\r\n// race(values: T): Promise>;\r\n//export const createAsyncRacePromise: (values: T): IPromise;\r\n\r\n/**\r\n * Returns a single asynchronous Promise instance that is already resolved with the given value. If the value passed is\r\n * a promise then that promise is returned instead of creating a new asynchronous promise instance.\r\n * If a new instance is returned then any chained operations will execute __asynchronously__ using the optional\r\n * timeout value to schedule when the chained items will be executed.(eg. `then()`; `finally()`).\r\n * @group Async\r\n * @group Resolved\r\n * @param value - The value to be used by this `Promise`. Can also be a `Promise` or a thenable to resolve.\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero.\r\n */\r\nexport const createAsyncResolvedPromise: (value: T, timeout?: number) => IPromise = _createResolvedPromise(createAsyncPromise);\r\n\r\n/**\r\n * Returns a single asynchronous Promise instance that is already rejected with the given reason.\r\n * Any chained operations will execute __asynchronously__ using the optional timeout value to schedule\r\n * when then chained items will be executed. (eg. `catch()`; `finally()`).\r\n * @group Async\r\n * @group Rejected\r\n * @param reason - The rejection reason\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero.\r\n */\r\nexport const createAsyncRejectedPromise: (reason: any, timeout?: number) => IPromise = _createRejectedPromise(createAsyncPromise);\r\n","/*\r\n * @nevware21/ts-async\r\n * https://github.com/nevware21/ts-async\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { createAsyncPromise } from \"./asyncPromise\";\r\nimport { _createAllPromise, _createRejectedPromise, _createResolvedPromise } from \"./base\";\r\nimport { IPromise } from \"../interfaces/IPromise\";\r\nimport { ePromiseState, STRING_STATES } from \"../internal/state\";\r\nimport { PromiseExecutor } from \"../interfaces/types\";\r\nimport { dumpObj, lazySafeGetInst, ILazyValue, isFunction, objDefineProp, throwTypeError } from \"@nevware21/ts-utils\";\r\nimport { STR_PROMISE } from \"../internal/constants\";\r\n\r\nlet _isPromiseSupported: ILazyValue;\r\n\r\n/**\r\n * Creates a Promise instance that when resolved or rejected will execute it's pending chained operations using the\r\n * available native Promise implementation.\r\n * If runtime does not support native `Promise` class (or no polyfill is available) this function will fallback to using\r\n * `createAsyncPromise` which will resolve them __asynchronously__ using the optional provided timeout value to\r\n * schedule when the chained items will be executed.\r\n * @group Alias\r\n * @group Promise\r\n * @group Native\r\n * @param executor - The function to be executed during the creation of the promise. Any errors thrown in the executor will\r\n * cause the promise to be rejected. The return value of the executor is always ignored\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero.\r\n */\r\nexport function createNativePromise(executor: PromiseExecutor, timeout?: number): IPromise {\r\n !_isPromiseSupported && (_isPromiseSupported = lazySafeGetInst(STR_PROMISE));\r\n\r\n const PrmCls = _isPromiseSupported.v;\r\n if (!PrmCls) {\r\n return createAsyncPromise(executor);\r\n }\r\n\r\n if (!isFunction(executor)) {\r\n throwTypeError(STR_PROMISE + \": executor is not a function - \" + dumpObj(executor));\r\n }\r\n\r\n let _state = ePromiseState.Pending;\r\n\r\n function _strState() {\r\n return STRING_STATES[_state];\r\n }\r\n\r\n let thePromise = new PrmCls((resolve, reject) => {\r\n function _resolve(value: T) {\r\n _state = ePromiseState.Resolved;\r\n resolve(value);\r\n }\r\n\r\n function _reject(reason: any) {\r\n _state = ePromiseState.Rejected;\r\n reject(reason);\r\n }\r\n\r\n executor(_resolve, _reject);\r\n\r\n }) as IPromise;\r\n\r\n objDefineProp(thePromise, \"state\", {\r\n get: _strState\r\n });\r\n\r\n return thePromise;\r\n}\r\n\r\n/**\r\n * Returns a single asynchronous Promise instance that resolves to an array of the results from the input promises.\r\n * This returned promise will resolve and execute it's pending chained operations __asynchronously__ using the optional\r\n * provided timeout value to schedule when the chained items will be executed, or if the input contains no promises.\r\n * It rejects immediately upon any of the input promises rejected or non-promises throwing an error,\r\n * and will reject with this first rejection message / error.\r\n * If the runtime doesn't support the Promise.all it will fallback back to an asynchronous Promise implementation.\r\n * @group Alias\r\n * @group All\r\n * @group Native\r\n * @param input - The array of promises to wait to be resolved / rejected before resolving or rejecting the new promise\r\n * @param timeout\r\n * @returns\r\n * \r\n * - An already resolved `Promise`, if the input passed is empty.\r\n *
- A pending `Promise` in all other cases. This returned promise is then resolved/rejected __synchronously__\r\n * (as soon as the pending items is empty) when all the promises in the given input have resolved, or if any of the\r\n * promises reject.\r\n *
\r\n */\r\nexport const createNativeAllPromise: (input: PromiseLike[], timeout?: number) => IPromise = _createAllPromise(createNativePromise);\r\n\r\n/**\r\n * Returns a single asynchronous Promise instance that is already resolved with the given value. If the value passed is\r\n * a promise then that promise is returned instead of creating a new asynchronous promise instance.\r\n * If a new instance is returned then any chained operations will execute __asynchronously__ using the optional\r\n * timeout value to schedule when the chained items will be executed.(eg. `then()`; `finally()`).\r\n * @group Alias\r\n * @group Resolved\r\n * @group Native\r\n * @param value - The value to be used by this `Promise`. Can also be a `Promise` or a thenable to resolve.\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero.\r\n */\r\nexport const createNativeResolvedPromise: (value: T, timeout?: number) => Promise = _createResolvedPromise(createNativePromise);\r\n\r\n/**\r\n * Returns a single asynchronous Promise instance that is already rejected with the given reason.\r\n * Any chained operations will execute __asynchronously__ using the optional timeout value to schedule\r\n * when then chained items will be executed. (eg. `catch()`; `finally()`).\r\n * @group Alias\r\n * @group Rejected\r\n * @group Native\r\n * @param reason - The rejection reason\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero.\r\n */\r\nexport const createNativeRejectedPromise: (reason: any, timeout?: number) => Promise = _createRejectedPromise(createNativePromise);\r\n","/*\r\n * @nevware21/ts-async\r\n * https://github.com/nevware21/ts-async\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { getLazy, ILazyValue } from \"@nevware21/ts-utils\";\r\nimport { _createAllPromise, _createRejectedPromise, _createResolvedPromise } from \"./base\";\r\nimport { IPromise } from \"../interfaces/IPromise\";\r\nimport { createNativePromise } from \"./nativePromise\";\r\nimport { PromiseExecutor } from \"../interfaces/types\";\r\n\r\nlet _promiseCreator: ILazyValue<(executor: PromiseExecutor, timeout?: number) => IPromise>;\r\n\r\n/**\r\n * Set the default promise implementation to use when calling `createPromise`; `createAllPromise`; `createResolvedPromise`\r\n * and `createRejectedPromise`. This is effective a global value and changing this will affect ALL callers of these\r\n * functions, as such these functions should only be used when switching implementations would have not unexpected\r\n * consequences like switching from a `createSyncPromise` to `createIdlePromise` where idle promises have a possibility\r\n * of never getting called during application shutdown or during an expected timeframe.\r\n * @group Alias\r\n * @group Promise\r\n * @param creator - The creator function to call when a new promise is required.\r\n */\r\nexport function setCreatePromiseImpl(\r\n creator: (executor: PromiseExecutor, timeout?: number) => IPromise\r\n) {\r\n _promiseCreator = creator ? getLazy(() => creator) : null;\r\n}\r\n\r\n/**\r\n * Creates a Promise instance using the current default promise creator that when resolved or rejected will execute\r\n * it's pending chained operations.\r\n * @group Alias\r\n * @group Promise\r\n * @param executor - The function to be executed during the creation of the promise. Any errors thrown in the executor will\r\n * cause the promise to be rejected. The return value of the executor is always ignored\r\n * @param timeout - [Optional] timeout to wait before processing the items, defaults to zero.\r\n */\r\nexport function createPromise(executor: PromiseExecutor, timeout?: number): IPromise {\r\n !_promiseCreator && (_promiseCreator = getLazy(() => createNativePromise));\r\n\r\n return _promiseCreator.v.call(this, executor, timeout);\r\n}\r\n\r\n/**\r\n * Returns a single asynchronous Promise instance that resolves to an array of the results from the input promises.\r\n * This returned promise will resolve and execute it's pending chained operations __asynchronously__ using the optional\r\n * provided timeout value to schedule when the chained items will be executed, or if the input contains no promises.\r\n * It rejects immediately upon any of the input promises rejected or non-promises throwing an error,\r\n * and will reject with this first rejection message / error.\r\n * If the runtime doesn't support the Promise.all it will fallback back to an asynchronous Promise implementation.\r\n * @group Alias\r\n * @group All\r\n * @param input - The array of promises to wait to be resolved / rejected before resolving or rejecting the new promise\r\n * @param timeout\r\n * @returns\r\n * \r\n * - An already resolved `Promise`, if the input passed is empty.\r\n *
- A pending `Promise` in all other cases. This returned promise is then resolved/rejected __synchronously__\r\n * (as soon as the pending items is empty) when all the promises in the given input have resolved, or if any of the\r\n * promises reject.\r\n *
\r\n */\r\nexport const createAllPromise: (input: PromiseLike[], timeout?: number) => IPromise = _createAllPromise(createPromise);\r\n\r\n/**\r\n * Returns a single asynchronous Promise instance that is already resolved with the given value. If the value passed is\r\n * a promise then that promise is returned instead of creating a new asynchronous promise instance.\r\n * If a new instance is returned then any chained operations will execute __asynchronously__ using the optional\r\n * timeout value to schedule when the chained items will be executed.(eg. `then()`; `finally()`).\r\n * @group Alias\r\n * @group Resolved\r\n * @param value - The value to be used by this `Promise`. Can also be a `Promise` or a thenable to resolve.\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero.\r\n */\r\nexport const createResolvedPromise: (value: T, timeout?: number) => IPromise = _createResolvedPromise(createPromise);\r\n\r\n/**\r\n * Returns a single asynchronous Promise instance that is already rejected with the given reason.\r\n * Any chained operations will execute __asynchronously__ using the optional timeout value to schedule\r\n * when then chained items will be executed. (eg. `catch()`; `finally()`).\r\n * @group Alias\r\n * @group Rejected\r\n * @param reason - The rejection reason\r\n * @param timeout - Optional timeout to wait before processing the items, defaults to zero.\r\n */\r\nexport const createRejectedPromise: (reason: any, timeout?: number) => IPromise = _createRejectedPromise(createPromise);\r\n","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { LENGTH } from \"../internal/constants\";\r\nimport { _unwrapProp } from \"../internal/unwrapFunction\";\r\n\r\n/**\r\n * Interface to identify that an object contains the length property used as a type\r\n * constraint for {@link getLength}\r\n *\r\n * @since 0.4.2\r\n * @group String\r\n * @group Array\r\n * @group Object\r\n */\r\nexport interface IGetLength {\r\n\r\n /**\r\n * Identifies the property that returns the length of the instance\r\n */\r\n length: unknown;\r\n}\r\n\r\n/**\r\n * Helper to return the length value of an object, this will return the value\r\n * of the \"length\" property. Generally used to return the length of a string or array.\r\n *\r\n * @since 0.4.2\r\n * @group Array\r\n * @group String\r\n * @group String\r\n * @group Array\r\n * @group Object\r\n * @param value - The value to return the length property from, must contain a `length` property\r\n * @example\r\n * ```ts\r\n * getLength(\"\"); // returns 0\r\n * getLength(\"Hello World\"); // returns 11\r\n * getLength([]); // returns 0;\r\n * getLength([0, 1, 2, 3]); // returns 4;\r\n * getLength({ length: 42}); // returns 42\r\n * getLength({ length: () => 53; }); // returns the function that if called would return 53\r\n * ```\r\n */\r\nexport const getLength: (value: T) => T[\"length\"] = _unwrapProp(LENGTH);\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { createPromise, doAwaitResponse } from \"@nevware21/ts-async\";\r\nimport { arrSlice, getLength } from \"@nevware21/ts-utils\";\r\nimport { _DYN_UNLOAD } from \"../__DynamicConstants\";\r\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 */\r\nexport function runTargetUnload(target, isAsync) {\r\n if (target && target[_DYN_UNLOAD /* @min:%2eunload */]) {\r\n return target[_DYN_UNLOAD /* @min:%2eunload */](isAsync);\r\n }\r\n}\r\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 */\r\nexport function doUnloadAll(targets, isAsync, done) {\r\n var result;\r\n if (!done) {\r\n result = createPromise(function (resolved) {\r\n done = resolved;\r\n });\r\n }\r\n if (targets && getLength(targets) > 0) {\r\n doAwaitResponse(runTargetUnload(targets[0], isAsync), function () {\r\n doUnloadAll(arrSlice(targets, 1), isAsync, done);\r\n });\r\n }\r\n else {\r\n done();\r\n }\r\n return result;\r\n}\r\n//# sourceMappingURL=AsyncUtils.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { __extends } from \"tslib\";\r\nimport { createClassFromInterface } from \"@microsoft/applicationinsights-core-js\";\r\nfunction _aiNameFunc(baseName) {\r\n var aiName = \"ai.\" + baseName + \".\";\r\n return function (name) {\r\n return aiName + name;\r\n };\r\n}\r\nvar _aiApplication = _aiNameFunc(\"application\");\r\nvar _aiDevice = _aiNameFunc(\"device\");\r\nvar _aiLocation = _aiNameFunc(\"location\");\r\nvar _aiOperation = _aiNameFunc(\"operation\");\r\nvar _aiSession = _aiNameFunc(\"session\");\r\nvar _aiUser = _aiNameFunc(\"user\");\r\nvar _aiCloud = _aiNameFunc(\"cloud\");\r\nvar _aiInternal = _aiNameFunc(\"internal\");\r\nvar ContextTagKeys = /** @class */ (function (_super) {\r\n __extends(ContextTagKeys, _super);\r\n function ContextTagKeys() {\r\n return _super.call(this) || this;\r\n }\r\n return ContextTagKeys;\r\n}(createClassFromInterface({\r\n applicationVersion: _aiApplication(\"ver\"),\r\n applicationBuild: _aiApplication(\"build\"),\r\n applicationTypeId: _aiApplication(\"typeId\"),\r\n applicationId: _aiApplication(\"applicationId\"),\r\n applicationLayer: _aiApplication(\"layer\"),\r\n deviceId: _aiDevice(\"id\"),\r\n deviceIp: _aiDevice(\"ip\"),\r\n deviceLanguage: _aiDevice(\"language\"),\r\n deviceLocale: _aiDevice(\"locale\"),\r\n deviceModel: _aiDevice(\"model\"),\r\n deviceFriendlyName: _aiDevice(\"friendlyName\"),\r\n deviceNetwork: _aiDevice(\"network\"),\r\n deviceNetworkName: _aiDevice(\"networkName\"),\r\n deviceOEMName: _aiDevice(\"oemName\"),\r\n deviceOS: _aiDevice(\"os\"),\r\n deviceOSVersion: _aiDevice(\"osVersion\"),\r\n deviceRoleInstance: _aiDevice(\"roleInstance\"),\r\n deviceRoleName: _aiDevice(\"roleName\"),\r\n deviceScreenResolution: _aiDevice(\"screenResolution\"),\r\n deviceType: _aiDevice(\"type\"),\r\n deviceMachineName: _aiDevice(\"machineName\"),\r\n deviceVMName: _aiDevice(\"vmName\"),\r\n deviceBrowser: _aiDevice(\"browser\"),\r\n deviceBrowserVersion: _aiDevice(\"browserVersion\"),\r\n locationIp: _aiLocation(\"ip\"),\r\n locationCountry: _aiLocation(\"country\"),\r\n locationProvince: _aiLocation(\"province\"),\r\n locationCity: _aiLocation(\"city\"),\r\n operationId: _aiOperation(\"id\"),\r\n operationName: _aiOperation(\"name\"),\r\n operationParentId: _aiOperation(\"parentId\"),\r\n operationRootId: _aiOperation(\"rootId\"),\r\n operationSyntheticSource: _aiOperation(\"syntheticSource\"),\r\n operationCorrelationVector: _aiOperation(\"correlationVector\"),\r\n sessionId: _aiSession(\"id\"),\r\n sessionIsFirst: _aiSession(\"isFirst\"),\r\n sessionIsNew: _aiSession(\"isNew\"),\r\n userAccountAcquisitionDate: _aiUser(\"accountAcquisitionDate\"),\r\n userAccountId: _aiUser(\"accountId\"),\r\n userAgent: _aiUser(\"userAgent\"),\r\n userId: _aiUser(\"id\"),\r\n userStoreRegion: _aiUser(\"storeRegion\"),\r\n userAuthUserId: _aiUser(\"authUserId\"),\r\n userAnonymousUserAcquisitionDate: _aiUser(\"anonUserAcquisitionDate\"),\r\n userAuthenticatedUserAcquisitionDate: _aiUser(\"authUserAcquisitionDate\"),\r\n cloudName: _aiCloud(\"name\"),\r\n cloudRole: _aiCloud(\"role\"),\r\n cloudRoleVer: _aiCloud(\"roleVer\"),\r\n cloudRoleInstance: _aiCloud(\"roleInstance\"),\r\n cloudEnvironment: _aiCloud(\"environment\"),\r\n cloudLocation: _aiCloud(\"location\"),\r\n cloudDeploymentUnit: _aiCloud(\"deploymentUnit\"),\r\n internalNodeName: _aiInternal(\"nodeName\"),\r\n internalSdkVersion: _aiInternal(\"sdkVersion\"),\r\n internalAgentVersion: _aiInternal(\"agentVersion\"),\r\n internalSnippet: _aiInternal(\"snippet\"),\r\n internalSdkSrc: _aiInternal(\"sdkSrc\")\r\n})));\r\nexport { ContextTagKeys };\r\n//# sourceMappingURL=ContextTagKeys.js.map","import { ContextTagKeys } from \"./Contracts/ContextTagKeys\";\r\nexport var Extensions = {\r\n UserExt: \"user\",\r\n DeviceExt: \"device\",\r\n TraceExt: \"trace\",\r\n WebExt: \"web\",\r\n AppExt: \"app\",\r\n OSExt: \"os\",\r\n SessionExt: \"ses\",\r\n SDKExt: \"sdk\"\r\n};\r\nexport var CtxTagKeys = new ContextTagKeys();\r\n//# sourceMappingURL=PartAExtensions.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { toISOString } from \"@microsoft/applicationinsights-core-js\";\r\nimport { strNotSpecified } from \"../../Constants\";\r\nimport { _DYN_NAME } from \"../../__DynamicConstants\";\r\nimport { dataSanitizeString } from \"./DataSanitizer\";\r\nvar Envelope = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of telemetry data.\r\n */\r\n function Envelope(logger, data, name) {\r\n var _this = this;\r\n var _self = this;\r\n _self.ver = 1;\r\n _self.sampleRate = 100.0;\r\n _self.tags = {};\r\n _self[_DYN_NAME /* @min:%2ename */] = dataSanitizeString(logger, name) || strNotSpecified;\r\n _self.data = data;\r\n _self.time = toISOString(new Date());\r\n _self.aiDataContract = {\r\n time: 1 /* FieldType.Required */,\r\n iKey: 1 /* FieldType.Required */,\r\n name: 1 /* FieldType.Required */,\r\n sampleRate: function () {\r\n return (_this.sampleRate === 100) ? 4 /* FieldType.Hidden */ : 1 /* FieldType.Required */;\r\n },\r\n tags: 1 /* FieldType.Required */,\r\n data: 1 /* FieldType.Required */\r\n };\r\n }\r\n return Envelope;\r\n}());\r\nexport { Envelope };\r\n//# sourceMappingURL=Envelope.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nvar Data = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of telemetry data.\r\n */\r\n function Data(baseType, data) {\r\n /**\r\n * The data contract for serializing this object.\r\n */\r\n this.aiDataContract = {\r\n baseType: 1 /* FieldType.Required */,\r\n baseData: 1 /* FieldType.Required */\r\n };\r\n this.baseType = baseType;\r\n this.baseData = data;\r\n }\r\n return Data;\r\n}());\r\nexport { Data };\r\n//# sourceMappingURL=Data.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n// ###################################################################################################################################################\r\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 ###\r\n// ###################################################################################################################################################\r\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)\r\n// as when using \"short\" named values from here they will be will be minified smaller than the SdkCoreNames[eSdkCoreNames.xxxx] value.\r\nexport var STR_DURATION = \"duration\";\r\n//# sourceMappingURL=InternalConstants.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n// @skip-file-minify\r\n// ##############################################################\r\n// AUTO GENERATED FILE: This file is Auto Generated during build.\r\n// ##############################################################\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\nexport var _DYN_TAGS = \"tags\"; // Count: 17\r\nexport var _DYN_DEVICE_TYPE = \"deviceType\"; // Count: 3\r\nexport var _DYN_DATA = \"data\"; // Count: 13\r\nexport var _DYN_NAME = \"name\"; // Count: 8\r\nexport var _DYN_TRACE_ID = \"traceID\"; // Count: 5\r\nexport var _DYN_LENGTH = \"length\"; // Count: 36\r\nexport var _DYN_STRINGIFY = \"stringify\"; // Count: 5\r\nexport var _DYN_MEASUREMENTS = \"measurements\"; // Count: 7\r\nexport var _DYN_DATA_TYPE = \"dataType\"; // Count: 10\r\nexport var _DYN_ENVELOPE_TYPE = \"envelopeType\"; // Count: 7\r\nexport var _DYN_TO_STRING = \"toString\"; // Count: 7\r\nexport var _DYN_ON_LINE = \"onLine\"; // Count: 4\r\nexport var _DYN_IS_ONLINE = \"isOnline\"; // Count: 3\r\nexport var _DYN__GET = \"_get\"; // Count: 5\r\nexport var _DYN_ENQUEUE = \"enqueue\"; // Count: 7\r\nexport var _DYN_COUNT = \"count\"; // Count: 6\r\nexport var _DYN_EVENTS_LIMIT_IN_MEM = \"eventsLimitInMem\"; // Count: 2\r\nexport var _DYN_PUSH = \"push\"; // Count: 6\r\nexport var _DYN_EMIT_LINE_DELIMITED_0 = \"emitLineDelimitedJson\"; // Count: 3\r\nexport var _DYN_CLEAR = \"clear\"; // Count: 7\r\nexport var _DYN_BATCH_PAYLOADS = \"batchPayloads\"; // Count: 5\r\nexport var _DYN_CREATE_NEW = \"createNew\"; // Count: 3\r\nexport var _DYN_MARK_AS_SENT = \"markAsSent\"; // Count: 7\r\nexport var _DYN_CLEAR_SENT = \"clearSent\"; // Count: 5\r\nexport var _DYN_BUFFER_OVERRIDE = \"bufferOverride\"; // Count: 3\r\nexport var _DYN__BUFFER__KEY = \"BUFFER_KEY\"; // Count: 5\r\nexport var _DYN__SENT__BUFFER__KEY = \"SENT_BUFFER_KEY\"; // Count: 8\r\nexport var _DYN__MAX__BUFFER__SIZE = \"MAX_BUFFER_SIZE\"; // Count: 5\r\nexport var _DYN_TRIGGER_SEND = \"triggerSend\"; // Count: 5\r\nexport var _DYN_DIAG_LOG = \"diagLog\"; // Count: 16\r\nexport var _DYN__SENDER = \"_sender\"; // Count: 5\r\nexport var _DYN_CUSTOM_HEADERS = \"customHeaders\"; // Count: 3\r\nexport var _DYN_MAX_BATCH_SIZE_IN_BY1 = \"maxBatchSizeInBytes\"; // Count: 2\r\nexport var _DYN_ONUNLOAD_DISABLE_BEA2 = \"onunloadDisableBeacon\"; // Count: 2\r\nexport var _DYN_IS_BEACON_API_DISABL3 = \"isBeaconApiDisabled\"; // Count: 3\r\nexport var _DYN_ENABLE_SESSION_STORA4 = \"enableSessionStorageBuffer\"; // Count: 2\r\nexport var _DYN__BUFFER = \"_buffer\"; // Count: 11\r\nexport var _DYN_INSTRUMENTATION_KEY = \"instrumentationKey\"; // Count: 2\r\nexport var _DYN_DISABLE_XHR = \"disableXhr\"; // Count: 5\r\nexport var _DYN_ONUNLOAD_DISABLE_FET5 = \"onunloadDisableFetch\"; // Count: 2\r\nexport var _DYN_CONVERT_UNDEFINED = \"convertUndefined\"; // Count: 2\r\nexport var _DYN_MAX_BATCH_INTERVAL = \"maxBatchInterval\"; // Count: 2\r\nexport var _DYN_BASE_TYPE = \"baseType\"; // Count: 4\r\nexport var _DYN_SAMPLE_RATE = \"sampleRate\"; // Count: 4\r\nexport var _DYN__XHR_READY_STATE_CHA6 = \"_xhrReadyStateChange\"; // Count: 2\r\nexport var _DYN__ON_ERROR = \"_onError\"; // Count: 11\r\nexport var _DYN__ON_PARTIAL_SUCCESS = \"_onPartialSuccess\"; // Count: 3\r\nexport var _DYN__ON_SUCCESS = \"_onSuccess\"; // Count: 6\r\nexport var _DYN_ITEMS_ACCEPTED = \"itemsAccepted\"; // Count: 5\r\nexport var _DYN_ITEMS_RECEIVED = \"itemsReceived\"; // Count: 6\r\nexport var _DYN_SET_REQUEST_HEADER = \"setRequestHeader\"; // Count: 3\r\nexport var _DYN_EVENTS_SEND_REQUEST = \"eventsSendRequest\"; // Count: 2\r\nexport var _DYN_GET_SAMPLING_SCORE = \"getSamplingScore\"; // Count: 2\r\nexport var _DYN_GET_HASH_CODE_SCORE = \"getHashCodeScore\"; // Count: 4\r\n//# sourceMappingURL=__DynamicConstants.js.map","import { __assign } from \"tslib\";\r\nimport { CtxTagKeys, Data, Envelope, Event, Exception, HttpMethod, Metric, PageView, PageViewPerformance, RemoteDependencyData, SampleRate, Trace, dataSanitizeString } from \"@microsoft/applicationinsights-common\";\r\nimport { _throwInternal, _warnToConsole, getJSON, hasJSON, isNullOrUndefined, isNumber, isString, isTruthy, objForEachKey, optimizeObject, setValue, toISOString } from \"@microsoft/applicationinsights-core-js\";\r\nimport { STR_DURATION } from \"./InternalConstants\";\r\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\";\r\n// these two constants are used to filter out properties not needed when trying to extract custom properties and measurements from the incoming payload\r\nvar strBaseType = \"baseType\";\r\nvar strBaseData = \"baseData\";\r\nvar strProperties = \"properties\";\r\nvar strTrue = \"true\";\r\nfunction _setValueIf(target, field, value) {\r\n return setValue(target, field, value, isTruthy);\r\n}\r\n/*\r\n * Maps Part A data from CS 4.0\r\n */\r\nfunction _extractPartAExtensions(logger, item, env) {\r\n // todo: switch to keys from common in this method\r\n var envTags = env[_DYN_TAGS /* @min:%2etags */] = env[_DYN_TAGS /* @min:%2etags */] || {};\r\n var itmExt = item.ext = item.ext || {};\r\n var itmTags = item[_DYN_TAGS /* @min:%2etags */] = item[_DYN_TAGS /* @min:%2etags */] || [];\r\n var extUser = itmExt.user;\r\n if (extUser) {\r\n _setValueIf(envTags, CtxTagKeys.userAuthUserId, extUser.authId);\r\n _setValueIf(envTags, CtxTagKeys.userId, extUser.id || extUser.localId);\r\n }\r\n var extApp = itmExt.app;\r\n if (extApp) {\r\n _setValueIf(envTags, CtxTagKeys.sessionId, extApp.sesId);\r\n }\r\n var extDevice = itmExt.device;\r\n if (extDevice) {\r\n _setValueIf(envTags, CtxTagKeys.deviceId, extDevice.id || extDevice.localId);\r\n _setValueIf(envTags, CtxTagKeys[_DYN_DEVICE_TYPE /* @min:%2edeviceType */], extDevice.deviceClass);\r\n _setValueIf(envTags, CtxTagKeys.deviceIp, extDevice.ip);\r\n _setValueIf(envTags, CtxTagKeys.deviceModel, extDevice.model);\r\n _setValueIf(envTags, CtxTagKeys[_DYN_DEVICE_TYPE /* @min:%2edeviceType */], extDevice[_DYN_DEVICE_TYPE /* @min:%2edeviceType */]);\r\n }\r\n var web = item.ext.web;\r\n if (web) {\r\n _setValueIf(envTags, CtxTagKeys.deviceLanguage, web.browserLang);\r\n _setValueIf(envTags, CtxTagKeys.deviceBrowserVersion, web.browserVer);\r\n _setValueIf(envTags, CtxTagKeys.deviceBrowser, web.browser);\r\n var envData = env[_DYN_DATA /* @min:%2edata */] = env[_DYN_DATA /* @min:%2edata */] || {};\r\n var envBaseData = envData[strBaseData] = envData[strBaseData] || {};\r\n var envProps = envBaseData[strProperties] = envBaseData[strProperties] || {};\r\n _setValueIf(envProps, \"domain\", web.domain);\r\n _setValueIf(envProps, \"isManual\", web.isManual ? strTrue : null);\r\n _setValueIf(envProps, \"screenRes\", web.screenRes);\r\n _setValueIf(envProps, \"userConsent\", web.userConsent ? strTrue : null);\r\n }\r\n var extOs = itmExt.os;\r\n if (extOs) {\r\n _setValueIf(envTags, CtxTagKeys.deviceOS, extOs[_DYN_NAME /* @min:%2ename */]);\r\n }\r\n // No support for mapping Trace.traceState to 2.0 as it is currently empty\r\n var extTrace = itmExt.trace;\r\n if (extTrace) {\r\n _setValueIf(envTags, CtxTagKeys.operationParentId, extTrace.parentID);\r\n _setValueIf(envTags, CtxTagKeys.operationName, dataSanitizeString(logger, extTrace[_DYN_NAME /* @min:%2ename */]));\r\n _setValueIf(envTags, CtxTagKeys.operationId, extTrace[_DYN_TRACE_ID /* @min:%2etraceID */]);\r\n }\r\n // Sample 4.0 schema\r\n // {\r\n // \"time\" : \"2018-09-05T22:51:22.4936Z\",\r\n // \"name\" : \"MetricWithNamespace\",\r\n // \"iKey\" : \"ABC-5a4cbd20-e601-4ef5-a3c6-5d6577e4398e\",\r\n // \"ext\": { \"cloud\": {\r\n // \"role\": \"WATSON3\",\r\n // \"roleInstance\": \"CO4AEAP00000260\"\r\n // },\r\n // \"device\": {}, \"correlation\": {} },\r\n // \"tags\": [\r\n // { \"amazon.region\" : \"east2\" },\r\n // { \"os.expid\" : \"wp:02df239\" }\r\n // ]\r\n // }\r\n var tgs = {};\r\n // deals with tags.push({object})\r\n for (var i = itmTags[_DYN_LENGTH /* @min:%2elength */] - 1; i >= 0; i--) {\r\n var tg = itmTags[i];\r\n objForEachKey(tg, function (key, value) {\r\n tgs[key] = value;\r\n });\r\n itmTags.splice(i, 1);\r\n }\r\n // deals with tags[key]=value (and handles hasOwnProperty)\r\n objForEachKey(itmTags, function (tg, value) {\r\n tgs[tg] = value;\r\n });\r\n var theTags = __assign(__assign({}, envTags), tgs);\r\n if (!theTags[CtxTagKeys.internalSdkVersion]) {\r\n // Append a version in case it is not already set\r\n theTags[CtxTagKeys.internalSdkVersion] = dataSanitizeString(logger, \"javascript:\".concat(EnvelopeCreator.Version), 64);\r\n }\r\n env[_DYN_TAGS /* @min:%2etags */] = optimizeObject(theTags);\r\n}\r\nfunction _extractPropsAndMeasurements(data, properties, measurements) {\r\n if (!isNullOrUndefined(data)) {\r\n objForEachKey(data, function (key, value) {\r\n if (isNumber(value)) {\r\n measurements[key] = value;\r\n }\r\n else if (isString(value)) {\r\n properties[key] = value;\r\n }\r\n else if (hasJSON()) {\r\n properties[key] = getJSON()[_DYN_STRINGIFY /* @min:%2estringify */](value);\r\n }\r\n });\r\n }\r\n}\r\nfunction _convertPropsUndefinedToCustomDefinedValue(properties, customUndefinedValue) {\r\n if (!isNullOrUndefined(properties)) {\r\n objForEachKey(properties, function (key, value) {\r\n properties[key] = value || customUndefinedValue;\r\n });\r\n }\r\n}\r\n// TODO: Do we want this to take logger as arg or use this._logger as nonstatic?\r\nfunction _createEnvelope(logger, envelopeType, telemetryItem, data) {\r\n var envelope = new Envelope(logger, data, envelopeType);\r\n _setValueIf(envelope, \"sampleRate\", telemetryItem[SampleRate]);\r\n if ((telemetryItem[strBaseData] || {}).startTime) {\r\n envelope.time = toISOString(telemetryItem[strBaseData].startTime);\r\n }\r\n envelope.iKey = telemetryItem.iKey;\r\n var iKeyNoDashes = telemetryItem.iKey.replace(/-/g, \"\");\r\n envelope[_DYN_NAME /* @min:%2ename */] = envelope[_DYN_NAME /* @min:%2ename */].replace(\"{0}\", iKeyNoDashes);\r\n // extract all extensions from ctx\r\n _extractPartAExtensions(logger, telemetryItem, envelope);\r\n // loop through the envelope tags (extension of Part A) and pick out the ones that should go in outgoing envelope tags\r\n telemetryItem[_DYN_TAGS /* @min:%2etags */] = telemetryItem[_DYN_TAGS /* @min:%2etags */] || [];\r\n return optimizeObject(envelope);\r\n}\r\nfunction EnvelopeCreatorInit(logger, telemetryItem) {\r\n if (isNullOrUndefined(telemetryItem[strBaseData])) {\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 46 /* _eInternalMessageId.TelemetryEnvelopeInvalid */, \"telemetryItem.baseData cannot be null.\");\r\n }\r\n}\r\nexport var EnvelopeCreator = {\r\n Version: '3.0.2'\r\n};\r\nexport function DependencyEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n var customMeasurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n var customProperties = telemetryItem[strBaseData][strProperties] || {};\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], customProperties, customMeasurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(customProperties, customUndefinedValue);\r\n }\r\n var bd = telemetryItem[strBaseData];\r\n if (isNullOrUndefined(bd)) {\r\n _warnToConsole(logger, \"Invalid input for dependency data\");\r\n return null;\r\n }\r\n var method = bd[strProperties] && bd[strProperties][HttpMethod] ? bd[strProperties][HttpMethod] : \"GET\";\r\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);\r\n var data = new Data(RemoteDependencyData[_DYN_DATA_TYPE /* @min:%2edataType */], remoteDepData);\r\n return _createEnvelope(logger, RemoteDependencyData[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\nexport function EventEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n var customProperties = {};\r\n var customMeasurements = {};\r\n if (telemetryItem[strBaseType] !== Event[_DYN_DATA_TYPE /* @min:%2edataType */]) {\r\n customProperties[\"baseTypeSource\"] = telemetryItem[strBaseType]; // save the passed in base type as a property\r\n }\r\n if (telemetryItem[strBaseType] === Event[_DYN_DATA_TYPE /* @min:%2edataType */]) { // take collection\r\n customProperties = telemetryItem[strBaseData][strProperties] || {};\r\n customMeasurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n }\r\n else { // if its not a known type, convert to custom event\r\n if (telemetryItem[strBaseData]) {\r\n _extractPropsAndMeasurements(telemetryItem[strBaseData], customProperties, customMeasurements);\r\n }\r\n }\r\n // Extract root level properties from part C telemetryItem.data\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], customProperties, customMeasurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(customProperties, customUndefinedValue);\r\n }\r\n var eventName = telemetryItem[strBaseData][_DYN_NAME /* @min:%2ename */];\r\n var eventData = new Event(logger, eventName, customProperties, customMeasurements);\r\n var data = new Data(Event[_DYN_DATA_TYPE /* @min:%2edataType */], eventData);\r\n return _createEnvelope(logger, Event[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\nexport function ExceptionEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n // Extract root level properties from part C telemetryItem.data\r\n var customMeasurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n var customProperties = telemetryItem[strBaseData][strProperties] || {};\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], customProperties, customMeasurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(customProperties, customUndefinedValue);\r\n }\r\n var bd = telemetryItem[strBaseData];\r\n var exData = Exception.CreateFromInterface(logger, bd, customProperties, customMeasurements);\r\n var data = new Data(Exception[_DYN_DATA_TYPE /* @min:%2edataType */], exData);\r\n return _createEnvelope(logger, Exception[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\nexport function MetricEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n var baseData = telemetryItem[strBaseData];\r\n var props = baseData[strProperties] || {};\r\n var measurements = baseData[_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], props, measurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(props, customUndefinedValue);\r\n }\r\n var baseMetricData = new Metric(logger, baseData[_DYN_NAME /* @min:%2ename */], baseData.average, baseData.sampleCount, baseData.min, baseData.max, baseData.stdDev, props, measurements);\r\n var data = new Data(Metric[_DYN_DATA_TYPE /* @min:%2edataType */], baseMetricData);\r\n return _createEnvelope(logger, Metric[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\nexport function PageViewEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n // Since duration is not part of the domain properties in Common Schema, extract it from part C\r\n var duration;\r\n var baseData = telemetryItem[strBaseData];\r\n if (!isNullOrUndefined(baseData) &&\r\n !isNullOrUndefined(baseData[strProperties]) &&\r\n !isNullOrUndefined(baseData[strProperties][STR_DURATION])) { // from part B properties\r\n duration = baseData[strProperties][STR_DURATION];\r\n delete baseData[strProperties][STR_DURATION];\r\n }\r\n else if (!isNullOrUndefined(telemetryItem[_DYN_DATA /* @min:%2edata */]) &&\r\n !isNullOrUndefined(telemetryItem[_DYN_DATA /* @min:%2edata */][STR_DURATION])) { // from custom properties\r\n duration = telemetryItem[_DYN_DATA /* @min:%2edata */][STR_DURATION];\r\n delete telemetryItem[_DYN_DATA /* @min:%2edata */][STR_DURATION];\r\n }\r\n var bd = telemetryItem[strBaseData];\r\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\r\n var currentContextId;\r\n if (((telemetryItem.ext || {}).trace || {})[_DYN_TRACE_ID /* @min:%2etraceID */]) {\r\n currentContextId = telemetryItem.ext.trace[_DYN_TRACE_ID /* @min:%2etraceID */];\r\n }\r\n var id = bd.id || currentContextId;\r\n var name = bd[_DYN_NAME /* @min:%2ename */];\r\n var url = bd.uri;\r\n var properties = bd[strProperties] || {};\r\n var measurements = bd[_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\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\r\n if (!isNullOrUndefined(bd.refUri)) {\r\n properties[\"refUri\"] = bd.refUri;\r\n }\r\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\r\n if (!isNullOrUndefined(bd.pageType)) {\r\n properties[\"pageType\"] = bd.pageType;\r\n }\r\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\r\n if (!isNullOrUndefined(bd.isLoggedIn)) {\r\n properties[\"isLoggedIn\"] = bd.isLoggedIn[_DYN_TO_STRING /* @min:%2etoString */]();\r\n }\r\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\r\n if (!isNullOrUndefined(bd[strProperties])) {\r\n var pageTags = bd[strProperties];\r\n objForEachKey(pageTags, function (key, value) {\r\n properties[key] = value;\r\n });\r\n }\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], properties, measurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(properties, customUndefinedValue);\r\n }\r\n var pageViewData = new PageView(logger, name, url, duration, properties, measurements, id);\r\n var data = new Data(PageView[_DYN_DATA_TYPE /* @min:%2edataType */], pageViewData);\r\n return _createEnvelope(logger, PageView[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\nexport function PageViewPerformanceEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n var bd = telemetryItem[strBaseData];\r\n var name = bd[_DYN_NAME /* @min:%2ename */];\r\n var url = bd.uri || bd.url;\r\n var properties = bd[strProperties] || {};\r\n var measurements = bd[_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], properties, measurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(properties, customUndefinedValue);\r\n }\r\n var baseData = new PageViewPerformance(logger, name, url, undefined, properties, measurements, bd);\r\n var data = new Data(PageViewPerformance[_DYN_DATA_TYPE /* @min:%2edataType */], baseData);\r\n return _createEnvelope(logger, PageViewPerformance[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\nexport function TraceEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {\r\n EnvelopeCreatorInit(logger, telemetryItem);\r\n var message = telemetryItem[strBaseData].message;\r\n var severityLevel = telemetryItem[strBaseData].severityLevel;\r\n var props = telemetryItem[strBaseData][strProperties] || {};\r\n var measurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS /* @min:%2emeasurements */] || {};\r\n _extractPropsAndMeasurements(telemetryItem[_DYN_DATA /* @min:%2edata */], props, measurements);\r\n if (!isNullOrUndefined(customUndefinedValue)) {\r\n _convertPropsUndefinedToCustomDefinedValue(props, customUndefinedValue);\r\n }\r\n var baseData = new Trace(logger, message, severityLevel, props, measurements);\r\n var data = new Data(Trace[_DYN_DATA_TYPE /* @min:%2edataType */], baseData);\r\n return _createEnvelope(logger, Trace[_DYN_ENVELOPE_TYPE /* @min:%2eenvelopeType */], telemetryItem, data);\r\n}\r\n//# sourceMappingURL=EnvelopeCreator.js.map","import { createUniqueNamespace, eventOff, eventOn, getDocument, getNavigator, getWindow, isNullOrUndefined, isUndefined, mergeEvtNamespace } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_IS_ONLINE, _DYN_ON_LINE } from \"./__DynamicConstants\";\r\nfunction _disableEvents(target, evtNamespace) {\r\n eventOff(target, null, null, evtNamespace);\r\n}\r\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 */\r\nexport function createOfflineListener(parentEvtNamespace) {\r\n var _a;\r\n var _document = getDocument();\r\n var _navigator = getNavigator(); // Gets the window.navigator or workerNavigator depending on the global\r\n var _isListening = false;\r\n var _onlineStatus = true;\r\n var _evtNamespace = mergeEvtNamespace(createUniqueNamespace(\"OfflineListener\"), parentEvtNamespace);\r\n try {\r\n if (_enableEvents(getWindow())) {\r\n _isListening = true;\r\n }\r\n if (_document) {\r\n // Also attach to the document.body or document\r\n var target = _document.body || _document;\r\n if (target.ononline) {\r\n if (_enableEvents(target)) {\r\n _isListening = true;\r\n }\r\n }\r\n }\r\n if (_isListening) {\r\n // We are listening to events so lets set the current status rather than assuming we are online #1538\r\n if (_navigator && !isNullOrUndefined(_navigator[_DYN_ON_LINE /* @min:%2eonLine */])) { // navigator.onLine is undefined in react-native\r\n _onlineStatus = _navigator[_DYN_ON_LINE /* @min:%2eonLine */];\r\n }\r\n }\r\n }\r\n catch (e) {\r\n // this makes react-native less angry\r\n _isListening = false;\r\n }\r\n function _enableEvents(target) {\r\n var enabled = false;\r\n if (target) {\r\n enabled = eventOn(target, \"online\", _setOnline, _evtNamespace);\r\n if (enabled) {\r\n eventOn(target, \"offline\", _setOffline, _evtNamespace);\r\n }\r\n }\r\n return enabled;\r\n }\r\n function _setOnline() {\r\n _onlineStatus = true;\r\n }\r\n function _setOffline() {\r\n _onlineStatus = false;\r\n }\r\n function _isOnline() {\r\n var result = true;\r\n if (_isListening) {\r\n result = _onlineStatus;\r\n }\r\n else if (_navigator && !isNullOrUndefined(_navigator[_DYN_ON_LINE /* @min:%2eonLine */])) { // navigator.onLine is undefined in react-native\r\n result = _navigator[_DYN_ON_LINE /* @min:%2eonLine */];\r\n }\r\n return result;\r\n }\r\n function _unload() {\r\n var win = getWindow();\r\n if (win && _isListening) {\r\n _disableEvents(win, _evtNamespace);\r\n if (_document) {\r\n // Also attach to the document.body or document\r\n var target = _document.body || _document;\r\n if (!isUndefined(target.ononline)) {\r\n _disableEvents(target, _evtNamespace);\r\n }\r\n }\r\n _isListening = false;\r\n }\r\n }\r\n return _a = {},\r\n _a[_DYN_IS_ONLINE /* @min:isOnline */] = _isOnline,\r\n _a.isListening = function () { return _isListening; },\r\n _a.unload = _unload,\r\n _a;\r\n}\r\n//# sourceMappingURL=Offline.js.map","import { __extends } from \"tslib\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { utlGetSessionStorage, utlSetSessionStorage } from \"@microsoft/applicationinsights-common\";\r\nimport { _throwInternal, arrForEach, arrIndexOf, dumpObj, getExceptionName, getJSON, isArray, isFunction, isString } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_BATCH_PAYLOADS, _DYN_BUFFER_OVERRIDE, _DYN_CLEAR, _DYN_CLEAR_SENT, _DYN_COUNT, _DYN_CREATE_NEW, _DYN_EMIT_LINE_DELIMITED_0, _DYN_ENQUEUE, _DYN_EVENTS_LIMIT_IN_MEM, _DYN_LENGTH, _DYN_MARK_AS_SENT, _DYN_PUSH, _DYN_STRINGIFY, _DYN__BUFFER__KEY, _DYN__GET, _DYN__MAX__BUFFER__SIZE, _DYN__SENT__BUFFER__KEY } from \"./__DynamicConstants\";\r\nvar BaseSendBuffer = /** @class */ (function () {\r\n function BaseSendBuffer(logger, config) {\r\n var _buffer = [];\r\n var _bufferFullMessageSent = false;\r\n this[_DYN__GET /* @min:%2e_get */] = function () {\r\n return _buffer;\r\n };\r\n this._set = function (buffer) {\r\n _buffer = buffer;\r\n return _buffer;\r\n };\r\n dynamicProto(BaseSendBuffer, this, function (_self) {\r\n _self[_DYN_ENQUEUE /* @min:%2eenqueue */] = function (payload) {\r\n if (_self[_DYN_COUNT /* @min:%2ecount */]() >= config[_DYN_EVENTS_LIMIT_IN_MEM /* @min:%2eeventsLimitInMem */]) {\r\n // sent internal log only once per page view\r\n if (!_bufferFullMessageSent) {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 105 /* _eInternalMessageId.InMemoryStorageBufferFull */, \"Maximum in-memory buffer size reached: \" + _self[_DYN_COUNT /* @min:%2ecount */](), true);\r\n _bufferFullMessageSent = true;\r\n }\r\n return;\r\n }\r\n _buffer[_DYN_PUSH /* @min:%2epush */](payload);\r\n };\r\n _self[_DYN_COUNT /* @min:%2ecount */] = function () {\r\n return _buffer[_DYN_LENGTH /* @min:%2elength */];\r\n };\r\n _self.size = function () {\r\n var size = _buffer[_DYN_LENGTH /* @min:%2elength */];\r\n for (var lp = 0; lp < _buffer[_DYN_LENGTH /* @min:%2elength */]; lp++) {\r\n size += _buffer[lp][_DYN_LENGTH /* @min:%2elength */];\r\n }\r\n if (!config[_DYN_EMIT_LINE_DELIMITED_0 /* @min:%2eemitLineDelimitedJson */]) {\r\n size += 2;\r\n }\r\n return size;\r\n };\r\n _self[_DYN_CLEAR /* @min:%2eclear */] = function () {\r\n _buffer = [];\r\n _bufferFullMessageSent = false;\r\n };\r\n _self.getItems = function () {\r\n return _buffer.slice(0);\r\n };\r\n _self[_DYN_BATCH_PAYLOADS /* @min:%2ebatchPayloads */] = function (payload) {\r\n if (payload && payload[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n var batch = config[_DYN_EMIT_LINE_DELIMITED_0 /* @min:%2eemitLineDelimitedJson */] ?\r\n payload.join(\"\\n\") :\r\n \"[\" + payload.join(\",\") + \"]\";\r\n return batch;\r\n }\r\n return null;\r\n };\r\n _self[_DYN_CREATE_NEW /* @min:%2ecreateNew */] = function (newLogger, newConfig, canUseSessionStorage) {\r\n var items = _buffer.slice(0);\r\n newLogger = newLogger || logger;\r\n newConfig = newConfig || {};\r\n var newBuffer = !!canUseSessionStorage ? new SessionStorageSendBuffer(newLogger, newConfig) : new ArraySendBuffer(newLogger, newConfig);\r\n arrForEach(items, function (payload) {\r\n newBuffer[_DYN_ENQUEUE /* @min:%2eenqueue */](payload);\r\n });\r\n return newBuffer;\r\n };\r\n });\r\n }\r\n BaseSendBuffer.prototype.enqueue = function (payload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n BaseSendBuffer.prototype.count = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return 0;\r\n };\r\n BaseSendBuffer.prototype.size = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return 0;\r\n };\r\n BaseSendBuffer.prototype.clear = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n BaseSendBuffer.prototype.getItems = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n BaseSendBuffer.prototype.batchPayloads = function (payload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n BaseSendBuffer.prototype.createNew = function (newLogger, newConfig, canUseSessionStorage) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n return BaseSendBuffer;\r\n}());\r\n/*\r\n * An array based send buffer.\r\n */\r\nvar ArraySendBuffer = /** @class */ (function (_super) {\r\n __extends(ArraySendBuffer, _super);\r\n function ArraySendBuffer(logger, config) {\r\n var _this = _super.call(this, logger, config) || this;\r\n dynamicProto(ArraySendBuffer, _this, function (_self, _base) {\r\n _self[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */] = function (payload) {\r\n _base[_DYN_CLEAR /* @min:%2eclear */]();\r\n };\r\n _self[_DYN_CLEAR_SENT /* @min:%2eclearSent */] = function (payload) {\r\n // not supported\r\n };\r\n });\r\n return _this;\r\n }\r\n ArraySendBuffer.prototype.markAsSent = function (payload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n ArraySendBuffer.prototype.clearSent = function (payload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n return ArraySendBuffer;\r\n}(BaseSendBuffer));\r\nexport { ArraySendBuffer };\r\n/*\r\n * Session storage buffer holds a copy of all unsent items in the browser session storage.\r\n */\r\nvar SessionStorageSendBuffer = /** @class */ (function (_super) {\r\n __extends(SessionStorageSendBuffer, _super);\r\n function SessionStorageSendBuffer(logger, config) {\r\n var _this = _super.call(this, logger, config) || this;\r\n var _bufferFullMessageSent = false;\r\n //Note: should not use config.namePrefix directly, because it will always refers to the latest namePrefix\r\n var _namePrefix = config === null || config === void 0 ? void 0 : config.namePrefix;\r\n var _a = config[_DYN_BUFFER_OVERRIDE /* @min:%2ebufferOverride */] || { getItem: utlGetSessionStorage, setItem: utlSetSessionStorage }, getItem = _a.getItem, setItem = _a.setItem;\r\n dynamicProto(SessionStorageSendBuffer, _this, function (_self, _base) {\r\n var bufferItems = _getBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY /* @min:%2eBUFFER_KEY */]);\r\n var notDeliveredItems = _getBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */]);\r\n var buffer = _self._set(bufferItems.concat(notDeliveredItems));\r\n // If the buffer has too many items, drop items from the end.\r\n if (buffer[_DYN_LENGTH /* @min:%2elength */] > SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */]) {\r\n buffer[_DYN_LENGTH /* @min:%2elength */] = SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */];\r\n }\r\n _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */], []);\r\n _setBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY /* @min:%2eBUFFER_KEY */], buffer);\r\n _self[_DYN_ENQUEUE /* @min:%2eenqueue */] = function (payload) {\r\n if (_self[_DYN_COUNT /* @min:%2ecount */]() >= SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */]) {\r\n // sent internal log only once per page view\r\n if (!_bufferFullMessageSent) {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 67 /* _eInternalMessageId.SessionStorageBufferFull */, \"Maximum buffer size reached: \" + _self[_DYN_COUNT /* @min:%2ecount */](), true);\r\n _bufferFullMessageSent = true;\r\n }\r\n return;\r\n }\r\n _base[_DYN_ENQUEUE /* @min:%2eenqueue */](payload);\r\n _setBuffer(SessionStorageSendBuffer.BUFFER_KEY, _self[_DYN__GET /* @min:%2e_get */]());\r\n };\r\n _self[_DYN_CLEAR /* @min:%2eclear */] = function () {\r\n _base[_DYN_CLEAR /* @min:%2eclear */]();\r\n _setBuffer(SessionStorageSendBuffer.BUFFER_KEY, _self[_DYN__GET /* @min:%2e_get */]());\r\n _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */], []);\r\n _bufferFullMessageSent = false;\r\n };\r\n _self[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */] = function (payload) {\r\n _setBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY /* @min:%2eBUFFER_KEY */], _self._set(_removePayloadsFromBuffer(payload, _self[_DYN__GET /* @min:%2e_get */]())));\r\n var sentElements = _getBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */]);\r\n if (sentElements instanceof Array && payload instanceof Array) {\r\n sentElements = sentElements.concat(payload);\r\n if (sentElements[_DYN_LENGTH /* @min:%2elength */] > SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */]) {\r\n // We send telemetry normally. If the SENT_BUFFER is too big we don't add new elements\r\n // until we receive a response from the backend and the buffer has free space again (see clearSent method)\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 67 /* _eInternalMessageId.SessionStorageBufferFull */, \"Sent buffer reached its maximum size: \" + sentElements[_DYN_LENGTH /* @min:%2elength */], true);\r\n sentElements[_DYN_LENGTH /* @min:%2elength */] = SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE /* @min:%2eMAX_BUFFER_SIZE */];\r\n }\r\n _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */], sentElements);\r\n }\r\n };\r\n _self[_DYN_CLEAR_SENT /* @min:%2eclearSent */] = function (payload) {\r\n var sentElements = _getBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */]);\r\n sentElements = _removePayloadsFromBuffer(payload, sentElements);\r\n _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */], sentElements);\r\n };\r\n _self[_DYN_CREATE_NEW /* @min:%2ecreateNew */] = function (newLogger, newConfig, canUseSessionStorage) {\r\n canUseSessionStorage = !!canUseSessionStorage;\r\n var unsentItems = _self[_DYN__GET /* @min:%2e_get */]().slice(0);\r\n var sentItems = _getBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY /* @min:%2eSENT_BUFFER_KEY */]).slice(0);\r\n newLogger = newLogger || logger;\r\n newConfig = newConfig || {};\r\n // to make sure that we do not send duplicated payloads when it is switched back to previous one\r\n _self[_DYN_CLEAR /* @min:%2eclear */]();\r\n var newBuffer = canUseSessionStorage ? new SessionStorageSendBuffer(newLogger, newConfig) : new ArraySendBuffer(newLogger, newConfig);\r\n arrForEach(unsentItems, function (payload) {\r\n newBuffer[_DYN_ENQUEUE /* @min:%2eenqueue */](payload);\r\n });\r\n if (canUseSessionStorage) {\r\n // arr buffer will clear all payloads if markAsSent() is called\r\n newBuffer[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */](sentItems);\r\n }\r\n return newBuffer;\r\n };\r\n function _removePayloadsFromBuffer(payloads, buffer) {\r\n var remaining = [];\r\n arrForEach(buffer, function (value) {\r\n if (!isFunction(value) && arrIndexOf(payloads, value) === -1) {\r\n remaining[_DYN_PUSH /* @min:%2epush */](value);\r\n }\r\n });\r\n return remaining;\r\n }\r\n function _getBuffer(key) {\r\n var prefixedKey = key;\r\n try {\r\n prefixedKey = _namePrefix ? _namePrefix + \"_\" + prefixedKey : prefixedKey;\r\n var bufferJson = getItem(logger, prefixedKey);\r\n if (bufferJson) {\r\n var buffer_1 = getJSON().parse(bufferJson);\r\n if (isString(buffer_1)) {\r\n // When using some version prototype.js the stringify / parse cycle does not decode array's correctly\r\n buffer_1 = getJSON().parse(buffer_1);\r\n }\r\n if (buffer_1 && isArray(buffer_1)) {\r\n return buffer_1;\r\n }\r\n }\r\n }\r\n catch (e) {\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 42 /* _eInternalMessageId.FailedToRestoreStorageBuffer */, \" storage key: \" + prefixedKey + \", \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n return [];\r\n }\r\n function _setBuffer(key, buffer) {\r\n var prefixedKey = key;\r\n try {\r\n prefixedKey = _namePrefix ? _namePrefix + \"_\" + prefixedKey : prefixedKey;\r\n var bufferJson = JSON[_DYN_STRINGIFY /* @min:%2estringify */](buffer);\r\n setItem(logger, prefixedKey, bufferJson);\r\n }\r\n catch (e) {\r\n // if there was an error, clear the buffer\r\n // telemetry is stored in the _buffer array so we won't loose any items\r\n setItem(logger, prefixedKey, JSON[_DYN_STRINGIFY /* @min:%2estringify */]([]));\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 41 /* _eInternalMessageId.FailedToSetStorageBuffer */, \" storage key: \" + prefixedKey + \", \" + getExceptionName(e) + \". Buffer cleared\", { exception: dumpObj(e) });\r\n }\r\n }\r\n });\r\n return _this;\r\n }\r\n SessionStorageSendBuffer.prototype.enqueue = function (payload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n SessionStorageSendBuffer.prototype.clear = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n SessionStorageSendBuffer.prototype.markAsSent = function (payload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n SessionStorageSendBuffer.prototype.clearSent = function (payload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n SessionStorageSendBuffer.prototype.createNew = function (newLogger, newConfig, canUseSessionStorage) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n SessionStorageSendBuffer.BUFFER_KEY = \"AI_buffer\";\r\n SessionStorageSendBuffer.SENT_BUFFER_KEY = \"AI_sentBuffer\";\r\n // Maximum number of payloads stored in the buffer. If the buffer is full, new elements will be dropped.\r\n SessionStorageSendBuffer.MAX_BUFFER_SIZE = 2000;\r\n return SessionStorageSendBuffer;\r\n}(BaseSendBuffer));\r\nexport { SessionStorageSendBuffer };\r\n//# sourceMappingURL=SendBuffer.js.map","var _a, _b;\r\nimport { __assign, __extends } from \"tslib\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { BreezeChannelIdentifier, DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH, DisabledPropertyName, Event, Exception, Metric, PageView, PageViewPerformance, ProcessLegacy, RemoteDependencyData, RequestHeaders, SampleRate, Trace, isInternalApplicationInsightsEndpoint, utlCanUseSessionStorage } from \"@microsoft/applicationinsights-common\";\r\nimport { BaseTelemetryPlugin, _throwInternal, _warnToConsole, arrForEach, cfgDfBoolean, cfgDfValidate, createProcessTelemetryContext, createUniqueNamespace, dateNow, dumpObj, getExceptionName, getIEVersion, getJSON, getNavigator, getWindow, isArray, isBeaconsSupported, isFetchSupported, isNullOrUndefined, isXhrSupported, mergeEvtNamespace, objExtend, objKeys, onConfigChange, runTargetUnload, useXDomainRequest } from \"@microsoft/applicationinsights-core-js\";\r\nimport { createPromise, doAwaitResponse } from \"@nevware21/ts-async\";\r\nimport { isTruthy, objDeepFreeze, objDefine, scheduleTimeout } from \"@nevware21/ts-utils\";\r\nimport { DependencyEnvelopeCreator, EventEnvelopeCreator, ExceptionEnvelopeCreator, MetricEnvelopeCreator, PageViewEnvelopeCreator, PageViewPerformanceEnvelopeCreator, TraceEnvelopeCreator } from \"./EnvelopeCreator\";\r\nimport { createOfflineListener } from \"./Offline\";\r\nimport { ArraySendBuffer, SessionStorageSendBuffer } from \"./SendBuffer\";\r\nimport { Serializer } from \"./Serializer\";\r\nimport { Sample } from \"./TelemetryProcessors/Sample\";\r\nimport { _DYN_BASE_TYPE, _DYN_BATCH_PAYLOADS, _DYN_BUFFER_OVERRIDE, _DYN_CLEAR, _DYN_CLEAR_SENT, _DYN_CONVERT_UNDEFINED, _DYN_COUNT, _DYN_CREATE_NEW, _DYN_CUSTOM_HEADERS, _DYN_DIAG_LOG, _DYN_DISABLE_XHR, _DYN_EMIT_LINE_DELIMITED_0, _DYN_ENABLE_SESSION_STORA4, _DYN_ENQUEUE, _DYN_EVENTS_LIMIT_IN_MEM, _DYN_EVENTS_SEND_REQUEST, _DYN_INSTRUMENTATION_KEY, _DYN_IS_BEACON_API_DISABL3, _DYN_IS_ONLINE, _DYN_ITEMS_ACCEPTED, _DYN_ITEMS_RECEIVED, _DYN_LENGTH, _DYN_MARK_AS_SENT, _DYN_MAX_BATCH_INTERVAL, _DYN_MAX_BATCH_SIZE_IN_BY1, _DYN_ONUNLOAD_DISABLE_BEA2, _DYN_ONUNLOAD_DISABLE_FET5, _DYN_PUSH, _DYN_SAMPLE_RATE, _DYN_SET_REQUEST_HEADER, _DYN_TAGS, _DYN_TRIGGER_SEND, _DYN__BUFFER, _DYN__ON_ERROR, _DYN__ON_PARTIAL_SUCCESS, _DYN__ON_SUCCESS, _DYN__SENDER, _DYN__XHR_READY_STATE_CHA6 } from \"./__DynamicConstants\";\r\nvar UNDEFINED_VALUE = undefined;\r\nvar FetchSyncRequestSizeLimitBytes = 65000; // approx 64kb (the current Edge, Firefox and Chrome max limit)\r\nfunction _getResponseText(xhr) {\r\n try {\r\n return xhr.responseText;\r\n }\r\n catch (e) {\r\n // Best effort, as XHR may throw while XDR wont so just ignore\r\n }\r\n return null;\r\n}\r\nvar defaultAppInsightsChannelConfig = objDeepFreeze((_a = {\r\n // Use the default value (handles empty string in the configuration)\r\n endpointUrl: cfgDfValidate(isTruthy, DEFAULT_BREEZE_ENDPOINT + DEFAULT_BREEZE_PATH)\r\n },\r\n _a[_DYN_EMIT_LINE_DELIMITED_0 /* @min:emitLineDelimitedJson */] = cfgDfBoolean(),\r\n _a[_DYN_MAX_BATCH_INTERVAL /* @min:maxBatchInterval */] = 15000,\r\n _a[_DYN_MAX_BATCH_SIZE_IN_BY1 /* @min:maxBatchSizeInBytes */] = 102400,\r\n _a.disableTelemetry = cfgDfBoolean(),\r\n _a[_DYN_ENABLE_SESSION_STORA4 /* @min:enableSessionStorageBuffer */] = cfgDfBoolean(true),\r\n _a.isRetryDisabled = cfgDfBoolean(),\r\n _a[_DYN_IS_BEACON_API_DISABL3 /* @min:isBeaconApiDisabled */] = cfgDfBoolean(true),\r\n _a[_DYN_DISABLE_XHR /* @min:disableXhr */] = cfgDfBoolean(),\r\n _a[_DYN_ONUNLOAD_DISABLE_FET5 /* @min:onunloadDisableFetch */] = cfgDfBoolean(),\r\n _a[_DYN_ONUNLOAD_DISABLE_BEA2 /* @min:onunloadDisableBeacon */] = cfgDfBoolean(),\r\n _a[_DYN_INSTRUMENTATION_KEY /* @min:instrumentationKey */] = UNDEFINED_VALUE,\r\n _a.namePrefix = UNDEFINED_VALUE,\r\n _a.samplingPercentage = cfgDfValidate(_chkSampling, 100),\r\n _a[_DYN_CUSTOM_HEADERS /* @min:customHeaders */] = UNDEFINED_VALUE,\r\n _a[_DYN_CONVERT_UNDEFINED /* @min:convertUndefined */] = UNDEFINED_VALUE,\r\n _a[_DYN_EVENTS_LIMIT_IN_MEM /* @min:eventsLimitInMem */] = 10000,\r\n _a[_DYN_BUFFER_OVERRIDE /* @min:bufferOverride */] = false,\r\n _a));\r\nfunction _chkSampling(value) {\r\n return !isNaN(value) && value > 0 && value <= 100;\r\n}\r\nvar EnvelopeTypeCreator = (_b = {},\r\n _b[Event.dataType] = EventEnvelopeCreator,\r\n _b[Trace.dataType] = TraceEnvelopeCreator,\r\n _b[PageView.dataType] = PageViewEnvelopeCreator,\r\n _b[PageViewPerformance.dataType] = PageViewPerformanceEnvelopeCreator,\r\n _b[Exception.dataType] = ExceptionEnvelopeCreator,\r\n _b[Metric.dataType] = MetricEnvelopeCreator,\r\n _b[RemoteDependencyData.dataType] = DependencyEnvelopeCreator,\r\n _b);\r\nvar Sender = /** @class */ (function (_super) {\r\n __extends(Sender, _super);\r\n function Sender() {\r\n var _this = _super.call(this) || this;\r\n _this.priority = 1001;\r\n _this.identifier = BreezeChannelIdentifier;\r\n // Don't set the defaults here, set them in the _initDefaults() as this is also called during unload\r\n var _consecutiveErrors; // How many times in a row a retryable error condition has occurred.\r\n var _retryAt; // The time to retry at in milliseconds from 1970/01/01 (this makes the timer calculation easy).\r\n var _lastSend; // The time of the last send operation.\r\n var _paused; // Flag indicating that the sending should be paused\r\n var _timeoutHandle; // Handle to the timer for delayed sending of batches of data.\r\n var _serializer;\r\n var _stamp_specific_redirects;\r\n var _headers;\r\n var _syncFetchPayload = 0; // Keep track of the outstanding sync fetch payload total (as sync fetch has limits)\r\n var _fallbackSender; // The sender to use if the payload size is too large\r\n var _syncUnloadSender; // The identified sender to use for the synchronous unload stage\r\n var _offlineListener;\r\n var _evtNamespace;\r\n var _endpointUrl;\r\n var _orgEndpointUrl;\r\n var _maxBatchSizeInBytes;\r\n var _beaconSupported;\r\n var _customHeaders;\r\n var _disableTelemetry;\r\n var _instrumentationKey;\r\n var _convertUndefined;\r\n var _isRetryDisabled;\r\n var _maxBatchInterval;\r\n var _sessionStorageUsed;\r\n var _bufferOverrideUsed;\r\n var _namePrefix;\r\n var _enableSendPromise;\r\n dynamicProto(Sender, _this, function (_self, _base) {\r\n _initDefaults();\r\n _self.pause = function () {\r\n _clearScheduledTimer();\r\n _paused = true;\r\n };\r\n _self.resume = function () {\r\n if (_paused) {\r\n _paused = false;\r\n _retryAt = null;\r\n // flush if we have exceeded the max-size already\r\n _checkMaxSize();\r\n _setupTimer();\r\n }\r\n };\r\n _self.flush = function (isAsync, callBack, sendReason) {\r\n if (isAsync === void 0) { isAsync = true; }\r\n if (!_paused) {\r\n // Clear the normal schedule timer as we are going to try and flush ASAP\r\n _clearScheduledTimer();\r\n try {\r\n return _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */](isAsync, null, sendReason || 1 /* SendRequestReason.ManualFlush */);\r\n }\r\n catch (e) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 22 /* _eInternalMessageId.FlushFailed */, \"flush failed, telemetry will not be collected: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n };\r\n _self.onunloadFlush = function () {\r\n if (!_paused) {\r\n if (_beaconSupported) {\r\n try {\r\n return _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */](true, _doUnloadSend, 2 /* SendRequestReason.Unload */);\r\n }\r\n catch (e) {\r\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), { exception: dumpObj(e) });\r\n }\r\n }\r\n else {\r\n _self.flush(false);\r\n }\r\n }\r\n };\r\n _self.addHeader = function (name, value) {\r\n _headers[name] = value;\r\n };\r\n _self.initialize = function (config, core, extensions, pluginChain) {\r\n if (_self.isInitialized()) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 28 /* _eInternalMessageId.SenderNotInitialized */, \"Sender is already initialized\");\r\n }\r\n _base.initialize(config, core, extensions, pluginChain);\r\n var identifier = _self.identifier;\r\n _serializer = new Serializer(core.logger);\r\n _consecutiveErrors = 0;\r\n _retryAt = null;\r\n _lastSend = 0;\r\n _self[_DYN__SENDER /* @min:%2e_sender */] = null;\r\n _stamp_specific_redirects = 0;\r\n var diagLog = _self[_DYN_DIAG_LOG /* @min:%2ediagLog */]();\r\n _evtNamespace = mergeEvtNamespace(createUniqueNamespace(\"Sender\"), core.evtNamespace && core.evtNamespace());\r\n _offlineListener = createOfflineListener(_evtNamespace);\r\n // This function will be re-called whenever any referenced configuration is changed\r\n _self._addHook(onConfigChange(config, function (details) {\r\n var config = details.cfg;\r\n var ctx = createProcessTelemetryContext(null, config, core);\r\n var senderConfig = ctx.getExtCfg(identifier, defaultAppInsightsChannelConfig);\r\n objDefine(_self, \"_senderConfig\", {\r\n g: function () {\r\n return senderConfig;\r\n }\r\n });\r\n // Only update the endpoint if the original config !== the current config\r\n // This is so any redirect endpointUrl is not overwritten\r\n if (_orgEndpointUrl !== senderConfig.endpointUrl) {\r\n if (_orgEndpointUrl) {\r\n // TODO: add doc to remind users to flush before changing endpoint, otherwise all unsent payload will be sent to new endpoint\r\n }\r\n _endpointUrl = _orgEndpointUrl = senderConfig.endpointUrl;\r\n }\r\n if (_customHeaders && _customHeaders !== senderConfig[_DYN_CUSTOM_HEADERS /* @min:%2ecustomHeaders */]) {\r\n // Removing any previously defined custom headers as they have changed\r\n arrForEach(_customHeaders, function (customHeader) {\r\n delete _headers[customHeader.header];\r\n });\r\n }\r\n _maxBatchSizeInBytes = senderConfig[_DYN_MAX_BATCH_SIZE_IN_BY1 /* @min:%2emaxBatchSizeInBytes */];\r\n _beaconSupported = (senderConfig[_DYN_ONUNLOAD_DISABLE_BEA2 /* @min:%2eonunloadDisableBeacon */] === false || senderConfig[_DYN_IS_BEACON_API_DISABL3 /* @min:%2eisBeaconApiDisabled */] === false) && isBeaconsSupported();\r\n var bufferOverride = senderConfig[_DYN_BUFFER_OVERRIDE /* @min:%2ebufferOverride */];\r\n var canUseSessionStorage = !!senderConfig[_DYN_ENABLE_SESSION_STORA4 /* @min:%2eenableSessionStorageBuffer */] &&\r\n (!!bufferOverride || utlCanUseSessionStorage());\r\n var namePrefix = senderConfig.namePrefix;\r\n //Note: emitLineDelimitedJson and eventsLimitInMem is directly accessed via config in senderBuffer\r\n //Therefore, if canUseSessionStorage is not changed, we do not need to re initialize a new one\r\n var shouldUpdate = (canUseSessionStorage !== _sessionStorageUsed)\r\n || (canUseSessionStorage && (_namePrefix !== namePrefix)) // prefixName is only used in session storage\r\n || (canUseSessionStorage && (_bufferOverrideUsed !== bufferOverride));\r\n if (_self[_DYN__BUFFER /* @min:%2e_buffer */]) {\r\n // case1 (Pre and Now enableSessionStorageBuffer settings are same)\r\n // if namePrefix changes, transfer current buffer to new buffer\r\n // else no action needed\r\n //case2 (Pre and Now enableSessionStorageBuffer settings are changed)\r\n // transfer current buffer to new buffer\r\n if (shouldUpdate) {\r\n try {\r\n _self._buffer = _self._buffer[_DYN_CREATE_NEW /* @min:%2ecreateNew */](diagLog, senderConfig, canUseSessionStorage);\r\n }\r\n catch (e) {\r\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), { exception: dumpObj(e) });\r\n }\r\n }\r\n _checkMaxSize();\r\n }\r\n else {\r\n _self[_DYN__BUFFER /* @min:%2e_buffer */] = canUseSessionStorage\r\n ? new SessionStorageSendBuffer(diagLog, senderConfig) : new ArraySendBuffer(diagLog, senderConfig);\r\n }\r\n _namePrefix = namePrefix;\r\n _sessionStorageUsed = canUseSessionStorage;\r\n _bufferOverrideUsed = bufferOverride;\r\n _self._sample = new Sample(senderConfig.samplingPercentage, diagLog);\r\n _instrumentationKey = senderConfig[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */];\r\n if (!_validateInstrumentationKey(_instrumentationKey, config)) {\r\n _throwInternal(diagLog, 1 /* eLoggingSeverity.CRITICAL */, 100 /* _eInternalMessageId.InvalidInstrumentationKey */, \"Invalid Instrumentation key \" + _instrumentationKey);\r\n }\r\n _customHeaders = senderConfig[_DYN_CUSTOM_HEADERS /* @min:%2ecustomHeaders */];\r\n if (!isInternalApplicationInsightsEndpoint(_endpointUrl) && _customHeaders && _customHeaders[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n arrForEach(_customHeaders, function (customHeader) {\r\n _this.addHeader(customHeader.header, customHeader.value);\r\n });\r\n }\r\n else {\r\n _customHeaders = null;\r\n }\r\n _enableSendPromise = senderConfig.enableSendPromise;\r\n var sendPostFunc = null;\r\n if (!senderConfig[_DYN_DISABLE_XHR /* @min:%2edisableXhr */] && useXDomainRequest()) {\r\n sendPostFunc = _xdrSender; // IE 8 and 9\r\n }\r\n else if (!senderConfig[_DYN_DISABLE_XHR /* @min:%2edisableXhr */] && isXhrSupported()) {\r\n sendPostFunc = _xhrSender;\r\n }\r\n if (!sendPostFunc && isFetchSupported()) {\r\n sendPostFunc = _fetchSender;\r\n }\r\n // always fallback to XHR\r\n _fallbackSender = sendPostFunc || _xhrSender;\r\n if (!senderConfig[_DYN_IS_BEACON_API_DISABL3 /* @min:%2eisBeaconApiDisabled */] && isBeaconsSupported()) {\r\n // Config is set to always used beacon sending\r\n sendPostFunc = _beaconSender;\r\n }\r\n _self[_DYN__SENDER /* @min:%2e_sender */] = sendPostFunc || _xhrSender;\r\n if (!senderConfig[_DYN_ONUNLOAD_DISABLE_FET5 /* @min:%2eonunloadDisableFetch */] && isFetchSupported(true)) {\r\n // Try and use the fetch with keepalive\r\n _syncUnloadSender = _fetchKeepAliveSender;\r\n }\r\n else if (isBeaconsSupported()) {\r\n // Try and use sendBeacon\r\n _syncUnloadSender = _beaconSender;\r\n }\r\n else if (!senderConfig[_DYN_DISABLE_XHR /* @min:%2edisableXhr */] && useXDomainRequest()) {\r\n _syncUnloadSender = _xdrSender; // IE 8 and 9\r\n }\r\n else if (!senderConfig[_DYN_DISABLE_XHR /* @min:%2edisableXhr */] && isXhrSupported()) {\r\n _syncUnloadSender = _xhrSender;\r\n }\r\n else {\r\n _syncUnloadSender = _fallbackSender;\r\n }\r\n _disableTelemetry = senderConfig.disableTelemetry;\r\n _convertUndefined = senderConfig[_DYN_CONVERT_UNDEFINED /* @min:%2econvertUndefined */] || UNDEFINED_VALUE;\r\n _isRetryDisabled = senderConfig.isRetryDisabled;\r\n _maxBatchInterval = senderConfig[_DYN_MAX_BATCH_INTERVAL /* @min:%2emaxBatchInterval */];\r\n }));\r\n };\r\n _self.processTelemetry = function (telemetryItem, itemCtx) {\r\n itemCtx = _self._getTelCtx(itemCtx);\r\n var diagLogger = itemCtx[_DYN_DIAG_LOG /* @min:%2ediagLog */]();\r\n try {\r\n // if master off switch is set, don't send any data\r\n if (_disableTelemetry) {\r\n // Do not send/save data\r\n return;\r\n }\r\n // validate input\r\n if (!telemetryItem) {\r\n _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 7 /* _eInternalMessageId.CannotSendEmptyTelemetry */, \"Cannot send empty telemetry\");\r\n return;\r\n }\r\n // validate event\r\n if (telemetryItem.baseData && !telemetryItem[_DYN_BASE_TYPE /* @min:%2ebaseType */]) {\r\n _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 70 /* _eInternalMessageId.InvalidEvent */, \"Cannot send telemetry without baseData and baseType\");\r\n return;\r\n }\r\n if (!telemetryItem[_DYN_BASE_TYPE /* @min:%2ebaseType */]) {\r\n // Default\r\n telemetryItem[_DYN_BASE_TYPE /* @min:%2ebaseType */] = \"EventData\";\r\n }\r\n // ensure a sender was constructed\r\n if (!_self[_DYN__SENDER /* @min:%2e_sender */]) {\r\n _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 28 /* _eInternalMessageId.SenderNotInitialized */, \"Sender was not initialized\");\r\n return;\r\n }\r\n // check if this item should be sampled in, else add sampleRate tag\r\n if (!_isSampledIn(telemetryItem)) {\r\n // Item is sampled out, do not send it\r\n _throwInternal(diagLogger, 2 /* eLoggingSeverity.WARNING */, 33 /* _eInternalMessageId.TelemetrySampledAndNotSent */, \"Telemetry item was sampled out and not sent\", { SampleRate: _self._sample[_DYN_SAMPLE_RATE /* @min:%2esampleRate */] });\r\n return;\r\n }\r\n else {\r\n telemetryItem[SampleRate] = _self._sample[_DYN_SAMPLE_RATE /* @min:%2esampleRate */];\r\n }\r\n // construct an envelope that Application Insights endpoint can understand\r\n // if ikey of telemetry is provided and not empty, envelope will use this iKey instead of senderConfig iKey\r\n var defaultEnvelopeIkey = telemetryItem.iKey || _instrumentationKey;\r\n var aiEnvelope_1 = Sender.constructEnvelope(telemetryItem, defaultEnvelopeIkey, diagLogger, _convertUndefined);\r\n if (!aiEnvelope_1) {\r\n _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 47 /* _eInternalMessageId.CreateEnvelopeError */, \"Unable to create an AppInsights envelope\");\r\n return;\r\n }\r\n var doNotSendItem_1 = false;\r\n // this is for running in legacy mode, where customer may already have a custom initializer present\r\n if (telemetryItem[_DYN_TAGS /* @min:%2etags */] && telemetryItem[_DYN_TAGS /* @min:%2etags */][ProcessLegacy]) {\r\n arrForEach(telemetryItem[_DYN_TAGS /* @min:%2etags */][ProcessLegacy], function (callBack) {\r\n try {\r\n if (callBack && callBack(aiEnvelope_1) === false) {\r\n doNotSendItem_1 = true;\r\n _warnToConsole(diagLogger, \"Telemetry processor check returns false\");\r\n }\r\n }\r\n catch (e) {\r\n // log error but dont stop executing rest of the telemetry initializers\r\n // doNotSendItem = true;\r\n _throwInternal(diagLogger, 1 /* eLoggingSeverity.CRITICAL */, 64 /* _eInternalMessageId.TelemetryInitializerFailed */, \"One of telemetry initializers failed, telemetry item will not be sent: \" + getExceptionName(e), { exception: dumpObj(e) }, true);\r\n }\r\n });\r\n delete telemetryItem[_DYN_TAGS /* @min:%2etags */][ProcessLegacy];\r\n }\r\n if (doNotSendItem_1) {\r\n return; // do not send, no need to execute next plugin\r\n }\r\n // check if the incoming payload is too large, truncate if necessary\r\n var payload = _serializer.serialize(aiEnvelope_1);\r\n // flush if we would exceed the max-size limit by adding this item\r\n var buffer = _self[_DYN__BUFFER /* @min:%2e_buffer */];\r\n _checkMaxSize(payload);\r\n // enqueue the payload\r\n buffer[_DYN_ENQUEUE /* @min:%2eenqueue */](payload);\r\n // ensure an invocation timeout is set\r\n _setupTimer();\r\n }\r\n catch (e) {\r\n _throwInternal(diagLogger, 2 /* eLoggingSeverity.WARNING */, 12 /* _eInternalMessageId.FailedAddingTelemetryToBuffer */, \"Failed adding telemetry to the sender's buffer, some telemetry will be lost: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n // hand off the telemetry item to the next plugin\r\n _self.processNext(telemetryItem, itemCtx);\r\n };\r\n /**\r\n * xhr state changes\r\n */\r\n _self[_DYN__XHR_READY_STATE_CHA6 /* @min:%2e_xhrReadyStateChange */] = function (xhr, payload, countOfItemsInPayload) {\r\n if (xhr.readyState === 4) {\r\n _checkResponsStatus(xhr.status, payload, xhr.responseURL, countOfItemsInPayload, _formatErrorMessageXhr(xhr), _getResponseText(xhr) || xhr.response);\r\n }\r\n };\r\n /**\r\n * Immediately send buffered data\r\n * @param async - {boolean} - Indicates if the events should be sent asynchronously\r\n * @param forcedSender - {SenderFunction} - Indicates the forcedSender, undefined if not passed\r\n */\r\n _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */] = function (async, forcedSender, sendReason) {\r\n if (async === void 0) { async = true; }\r\n var result;\r\n if (!_paused) {\r\n try {\r\n var buffer = _self[_DYN__BUFFER /* @min:%2e_buffer */];\r\n // Send data only if disableTelemetry is false\r\n if (!_disableTelemetry) {\r\n if (buffer[_DYN_COUNT /* @min:%2ecount */]() > 0) {\r\n var payload = buffer.getItems();\r\n _notifySendRequest(sendReason || 0 /* SendRequestReason.Undefined */, async);\r\n // invoke send\r\n if (forcedSender) {\r\n result = forcedSender.call(_self, payload, async);\r\n }\r\n else {\r\n result = _self[_DYN__SENDER /* @min:%2e_sender */](payload, async);\r\n }\r\n }\r\n // update lastSend time to enable throttling\r\n _lastSend = +new Date;\r\n }\r\n else {\r\n buffer[_DYN_CLEAR /* @min:%2eclear */]();\r\n }\r\n _clearScheduledTimer();\r\n }\r\n catch (e) {\r\n /* Ignore this error for IE under v10 */\r\n var ieVer = getIEVersion();\r\n if (!ieVer || ieVer > 9) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 40 /* _eInternalMessageId.TransmissionFailed */, \"Telemetry transmission failed, some telemetry will be lost: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n }\r\n return result;\r\n };\r\n _self._doTeardown = function (unloadCtx, unloadState) {\r\n _self.onunloadFlush();\r\n runTargetUnload(_offlineListener, false);\r\n _initDefaults();\r\n };\r\n /**\r\n * error handler\r\n */\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */] = function (payload, message, event) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 26 /* _eInternalMessageId.OnError */, \"Failed to send telemetry.\", { message: message });\r\n _self._buffer && _self._buffer[_DYN_CLEAR_SENT /* @min:%2eclearSent */](payload);\r\n };\r\n /**\r\n * partial success handler\r\n */\r\n _self[_DYN__ON_PARTIAL_SUCCESS /* @min:%2e_onPartialSuccess */] = function (payload, results) {\r\n var failed = [];\r\n var retry = [];\r\n // Iterate through the reversed array of errors so that splicing doesn't have invalid indexes after the first item.\r\n var errors = results.errors.reverse();\r\n for (var _i = 0, errors_1 = errors; _i < errors_1.length; _i++) {\r\n var error = errors_1[_i];\r\n var extracted = payload.splice(error.index, 1)[0];\r\n if (_isRetriable(error.statusCode)) {\r\n retry[_DYN_PUSH /* @min:%2epush */](extracted);\r\n }\r\n else {\r\n // All other errors, including: 402 (Monthly quota exceeded) and 439 (Too many requests and refresh cache).\r\n failed[_DYN_PUSH /* @min:%2epush */](extracted);\r\n }\r\n }\r\n if (payload[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n _self[_DYN__ON_SUCCESS /* @min:%2e_onSuccess */](payload, results[_DYN_ITEMS_ACCEPTED /* @min:%2eitemsAccepted */]);\r\n }\r\n if (failed[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](failed, _formatErrorMessageXhr(null, [\"partial success\", results[_DYN_ITEMS_ACCEPTED /* @min:%2eitemsAccepted */], \"of\", results.itemsReceived].join(\" \")));\r\n }\r\n if (retry[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n _resendPayload(retry);\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \"Partial success. \" +\r\n \"Delivered: \" + payload[_DYN_LENGTH /* @min:%2elength */] + \", Failed: \" + failed[_DYN_LENGTH /* @min:%2elength */] +\r\n \". Will retry to send \" + retry[_DYN_LENGTH /* @min:%2elength */] + \" our of \" + results[_DYN_ITEMS_RECEIVED /* @min:%2eitemsReceived */] + \" items\");\r\n }\r\n };\r\n /**\r\n * success handler\r\n */\r\n _self[_DYN__ON_SUCCESS /* @min:%2e_onSuccess */] = function (payload, countOfItemsInPayload) {\r\n _self._buffer && _self._buffer[_DYN_CLEAR_SENT /* @min:%2eclearSent */](payload);\r\n };\r\n /**\r\n * xdr state changes\r\n */\r\n _self._xdrOnLoad = function (xdr, payload) {\r\n var responseText = _getResponseText(xdr);\r\n if (xdr && (responseText + \"\" === \"200\" || responseText === \"\")) {\r\n _consecutiveErrors = 0;\r\n _self[_DYN__ON_SUCCESS /* @min:%2e_onSuccess */](payload, 0);\r\n }\r\n else {\r\n var results = _parseResponse(responseText);\r\n if (results && results.itemsReceived && results.itemsReceived > results[_DYN_ITEMS_ACCEPTED /* @min:%2eitemsAccepted */]\r\n && !_isRetryDisabled) {\r\n _self[_DYN__ON_PARTIAL_SUCCESS /* @min:%2e_onPartialSuccess */](payload, results);\r\n }\r\n else {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, _formatErrorMessageXdr(xdr));\r\n }\r\n }\r\n };\r\n function _isSampledIn(envelope) {\r\n return _self._sample.isSampledIn(envelope);\r\n }\r\n function _checkMaxSize(incomingPayload) {\r\n var incomingSize = incomingPayload ? incomingPayload[_DYN_LENGTH /* @min:%2elength */] : 0;\r\n if ((_self[_DYN__BUFFER /* @min:%2e_buffer */].size() + incomingSize) > _maxBatchSizeInBytes) {\r\n if (!_offlineListener || _offlineListener[_DYN_IS_ONLINE /* @min:%2eisOnline */]()) { // only trigger send when currently online\r\n _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */](true, null, 10 /* SendRequestReason.MaxBatchSize */);\r\n }\r\n return true;\r\n }\r\n return false;\r\n }\r\n function _checkResponsStatus(status, payload, responseUrl, countOfItemsInPayload, errorMessage, res) {\r\n var response = null;\r\n if (!_self._appId) {\r\n response = _parseResponse(res);\r\n if (response && response.appId) {\r\n _self._appId = response.appId;\r\n }\r\n }\r\n if ((status < 200 || status >= 300) && status !== 0) {\r\n // Update End Point url if permanent redirect or moved permanently\r\n // Updates the end point url before retry\r\n if (status === 301 || status === 307 || status === 308) {\r\n if (!_checkAndUpdateEndPointUrl(responseUrl)) {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, errorMessage);\r\n return;\r\n }\r\n }\r\n if (!_isRetryDisabled && _isRetriable(status)) {\r\n _resendPayload(payload);\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". \" +\r\n \"Response code \" + status + \". Will retry to send \" + payload[_DYN_LENGTH /* @min:%2elength */] + \" items.\");\r\n }\r\n else {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, errorMessage);\r\n }\r\n }\r\n else if (_offlineListener && !_offlineListener[_DYN_IS_ONLINE /* @min:%2eisOnline */]()) { // offline\r\n // Note: Don't check for status == 0, since adblock gives this code\r\n if (!_isRetryDisabled) {\r\n var offlineBackOffMultiplier = 10; // arbritrary number\r\n _resendPayload(payload, offlineBackOffMultiplier);\r\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.\"));\r\n }\r\n }\r\n else {\r\n // check if the xhr's responseURL or fetch's response.url is same as endpoint url\r\n // TODO after 10 redirects force send telemetry with 'redirect=false' as query parameter.\r\n _checkAndUpdateEndPointUrl(responseUrl);\r\n if (status === 206) {\r\n if (!response) {\r\n response = _parseResponse(res);\r\n }\r\n if (response && !_isRetryDisabled) {\r\n _self[_DYN__ON_PARTIAL_SUCCESS /* @min:%2e_onPartialSuccess */](payload, response);\r\n }\r\n else {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, errorMessage);\r\n }\r\n }\r\n else {\r\n _consecutiveErrors = 0;\r\n _self[_DYN__ON_SUCCESS /* @min:%2e_onSuccess */](payload, countOfItemsInPayload);\r\n }\r\n }\r\n }\r\n function _checkAndUpdateEndPointUrl(responseUrl) {\r\n // Maximum stamp specific redirects allowed(uncomment this when breeze is ready with not allowing redirects feature)\r\n if (_stamp_specific_redirects >= 10) {\r\n // _self._senderConfig.endpointUrl = () => Sender._getDefaultAppInsightsChannelConfig().endpointUrl()+\"/?redirect=false\";\r\n // _stamp_specific_redirects = 0;\r\n return false;\r\n }\r\n if (!isNullOrUndefined(responseUrl) && responseUrl !== \"\") {\r\n if (responseUrl !== _endpointUrl) {\r\n _endpointUrl = responseUrl;\r\n ++_stamp_specific_redirects;\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n function _doUnloadSend(payload, isAsync) {\r\n if (_syncUnloadSender) {\r\n // We are unloading so always call the sender with sync set to false\r\n _syncUnloadSender(payload, false);\r\n }\r\n else {\r\n // Fallback to the previous beacon Sender (which causes a CORB warning on chrome now)\r\n _beaconSender(payload, isAsync);\r\n }\r\n }\r\n function _doBeaconSend(payload) {\r\n var nav = getNavigator();\r\n var buffer = _self[_DYN__BUFFER /* @min:%2e_buffer */];\r\n var url = _endpointUrl;\r\n var batch = _self._buffer[_DYN_BATCH_PAYLOADS /* @min:%2ebatchPayloads */](payload);\r\n // Chrome only allows CORS-safelisted values for the sendBeacon data argument\r\n // see: https://bugs.chromium.org/p/chromium/issues/detail?id=720283\r\n var plainTextBatch = new Blob([batch], { type: \"text/plain;charset=UTF-8\" });\r\n // The sendBeacon method returns true if the user agent is able to successfully queue the data for transfer. Otherwise it returns false.\r\n var queued = nav.sendBeacon(url, plainTextBatch);\r\n if (queued) {\r\n buffer[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */](payload);\r\n // no response from beaconSender, clear buffer\r\n _self._onSuccess(payload, payload[_DYN_LENGTH /* @min:%2elength */]);\r\n }\r\n return queued;\r\n }\r\n /**\r\n * Send Beacon API request\r\n * @param payload - {string} - The data payload to be sent.\r\n * @param isAsync - {boolean} - 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 */\r\n function _beaconSender(payload, isAsync) {\r\n if (isArray(payload) && payload[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n // The sendBeacon method returns true if the user agent is able to successfully queue the data for transfer. Otherwise it returns false.\r\n if (!_doBeaconSend(payload)) {\r\n // Failed to send entire payload so try and split data and try to send as much events as possible\r\n var droppedPayload = [];\r\n for (var lp = 0; lp < payload[_DYN_LENGTH /* @min:%2elength */]; lp++) {\r\n var thePayload = payload[lp];\r\n if (!_doBeaconSend([thePayload])) {\r\n // Can't send anymore, so split the batch and drop the rest\r\n droppedPayload[_DYN_PUSH /* @min:%2epush */](thePayload);\r\n }\r\n }\r\n if (droppedPayload[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n _fallbackSender && _fallbackSender(droppedPayload, true);\r\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.\");\r\n }\r\n }\r\n }\r\n }\r\n /**\r\n * Send XMLHttpRequest\r\n * @param payload - {string} - The data payload to be sent.\r\n * @param isAsync - {boolean} - Indicates if the request should be sent asynchronously\r\n */\r\n function _xhrSender(payload, isAsync) {\r\n var thePromise;\r\n var resolveFunc;\r\n var rejectFunc;\r\n var xhr = new XMLHttpRequest();\r\n var endPointUrl = _endpointUrl;\r\n try {\r\n xhr[DisabledPropertyName] = true;\r\n }\r\n catch (e) {\r\n // If the environment has locked down the XMLHttpRequest (preventExtensions and/or freeze), this would\r\n // cause the request to fail and we no telemetry would be sent\r\n }\r\n xhr.open(\"POST\", endPointUrl, isAsync);\r\n xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](\"Content-type\", \"application/json\");\r\n // append Sdk-Context request header only in case of breeze endpoint\r\n if (isInternalApplicationInsightsEndpoint(endPointUrl)) {\r\n xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](RequestHeaders[6 /* eRequestHeaders.sdkContextHeader */], RequestHeaders[7 /* eRequestHeaders.sdkContextHeaderAppIdRequest */]);\r\n }\r\n arrForEach(objKeys(_headers), function (headerName) {\r\n xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](headerName, _headers[headerName]);\r\n });\r\n xhr.onreadystatechange = function () {\r\n _self._xhrReadyStateChange(xhr, payload, payload[_DYN_LENGTH /* @min:%2elength */]);\r\n if (xhr.readyState === 4) {\r\n resolveFunc && resolveFunc(true);\r\n }\r\n };\r\n xhr.onerror = function (event) {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, _formatErrorMessageXhr(xhr), event);\r\n rejectFunc && rejectFunc(event);\r\n };\r\n if (isAsync && _enableSendPromise) {\r\n thePromise = createPromise(function (resolve, reject) {\r\n resolveFunc = resolve;\r\n rejectFunc = reject;\r\n });\r\n }\r\n // compose an array of payloads\r\n var batch = _self._buffer[_DYN_BATCH_PAYLOADS /* @min:%2ebatchPayloads */](payload);\r\n xhr.send(batch);\r\n _self._buffer[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */](payload);\r\n return thePromise;\r\n }\r\n function _fetchKeepAliveSender(payload, isAsync) {\r\n if (isArray(payload)) {\r\n var payloadSize = payload[_DYN_LENGTH /* @min:%2elength */];\r\n for (var lp = 0; lp < payload[_DYN_LENGTH /* @min:%2elength */]; lp++) {\r\n payloadSize += payload[lp][_DYN_LENGTH /* @min:%2elength */];\r\n }\r\n if ((_syncFetchPayload + payloadSize) <= FetchSyncRequestSizeLimitBytes) {\r\n _doFetchSender(payload, false);\r\n }\r\n else if (isBeaconsSupported()) {\r\n // Fallback to beacon sender as we at least get told which events can't be scheduled\r\n _beaconSender(payload, isAsync);\r\n }\r\n else {\r\n // Payload is going to be too big so just try and send via XHR\r\n _fallbackSender && _fallbackSender(payload, true);\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". \" + \"Failed to send telemetry with Beacon API, retried with xhrSender.\");\r\n }\r\n }\r\n }\r\n /**\r\n * Send fetch API request\r\n * @param payload - {string} - The data payload to be sent.\r\n * @param isAsync - {boolean} - not used\r\n */\r\n function _fetchSender(payload, isAsync) {\r\n return _doFetchSender(payload, true);\r\n }\r\n /**\r\n * Send fetch API request\r\n * @param payload - {string} - The data payload to be sent.\r\n * @param isAsync - {boolean} - For fetch this identifies whether we are \"unloading\" (false) or a normal request\r\n */\r\n function _doFetchSender(payload, isAsync) {\r\n var _a;\r\n var endPointUrl = _endpointUrl;\r\n var batch = _self._buffer[_DYN_BATCH_PAYLOADS /* @min:%2ebatchPayloads */](payload);\r\n var plainTextBatch = new Blob([batch], { type: \"application/json\" });\r\n var thePromise;\r\n var resolveFunc;\r\n var rejectFunc;\r\n var requestHeaders = new Headers();\r\n var batchLength = batch[_DYN_LENGTH /* @min:%2elength */];\r\n var ignoreResponse = false;\r\n var responseHandled = false;\r\n // append Sdk-Context request header only in case of breeze endpoint\r\n if (isInternalApplicationInsightsEndpoint(endPointUrl)) {\r\n requestHeaders.append(RequestHeaders[6 /* eRequestHeaders.sdkContextHeader */], RequestHeaders[7 /* eRequestHeaders.sdkContextHeaderAppIdRequest */]);\r\n }\r\n arrForEach(objKeys(_headers), function (headerName) {\r\n requestHeaders.append(headerName, _headers[headerName]);\r\n });\r\n var init = (_a = {\r\n method: \"POST\",\r\n headers: requestHeaders,\r\n body: plainTextBatch\r\n },\r\n _a[DisabledPropertyName] = true // Mark so we don't attempt to track this request\r\n ,\r\n _a);\r\n if (!isAsync) {\r\n init.keepalive = true;\r\n // As a sync request (during unload), it is unlikely that we will get a chance to process the response so\r\n // just like beacon send assume that the events have been accepted and processed\r\n ignoreResponse = true;\r\n _syncFetchPayload += batchLength;\r\n }\r\n var request = new Request(endPointUrl, init);\r\n try {\r\n // Also try and tag the request (just in case the value in init is not copied over)\r\n request[DisabledPropertyName] = true;\r\n }\r\n catch (e) {\r\n // If the environment has locked down the XMLHttpRequest (preventExtensions and/or freeze), this would\r\n // cause the request to fail and we no telemetry would be sent\r\n }\r\n _self._buffer[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */](payload);\r\n if (isAsync && _enableSendPromise) {\r\n thePromise = createPromise(function (resolve, reject) {\r\n resolveFunc = resolve;\r\n rejectFunc = reject;\r\n });\r\n }\r\n try {\r\n doAwaitResponse(fetch(request), function (result) {\r\n if (!isAsync) {\r\n _syncFetchPayload -= batchLength;\r\n batchLength = 0;\r\n }\r\n if (!responseHandled) {\r\n responseHandled = true;\r\n if (!result.rejected) {\r\n var response_1 = result.value;\r\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 */\r\n if (!response_1.ok) {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, response_1.statusText);\r\n resolveFunc && resolveFunc(false);\r\n }\r\n else {\r\n doAwaitResponse(response_1.text(), function (resp) {\r\n _checkResponsStatus(response_1.status, payload, response_1.url, payload[_DYN_LENGTH /* @min:%2elength */], response_1.statusText, resp.value || \"\");\r\n resolveFunc && resolveFunc(true);\r\n });\r\n }\r\n }\r\n else {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, result.reason && result.reason.message);\r\n rejectFunc && rejectFunc(result.reason);\r\n }\r\n }\r\n });\r\n }\r\n catch (e) {\r\n if (!responseHandled) {\r\n _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, dumpObj(e));\r\n rejectFunc && rejectFunc(e);\r\n }\r\n }\r\n if (ignoreResponse && !responseHandled) {\r\n // Assume success during unload processing as we most likely won't get the response\r\n responseHandled = true;\r\n _self._onSuccess(payload, payload[_DYN_LENGTH /* @min:%2elength */]);\r\n resolveFunc && resolveFunc(true);\r\n }\r\n return thePromise;\r\n }\r\n /**\r\n * Parses the response from the backend.\r\n * @param response - XMLHttpRequest or XDomainRequest response\r\n */\r\n function _parseResponse(response) {\r\n try {\r\n if (response && response !== \"\") {\r\n var result = getJSON().parse(response);\r\n if (result && result.itemsReceived && result.itemsReceived >= result[_DYN_ITEMS_ACCEPTED /* @min:%2eitemsAccepted */] &&\r\n result.itemsReceived - result.itemsAccepted === result.errors[_DYN_LENGTH /* @min:%2elength */]) {\r\n return result;\r\n }\r\n }\r\n }\r\n catch (e) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 43 /* _eInternalMessageId.InvalidBackendResponse */, \"Cannot parse the response. \" + getExceptionName(e), {\r\n response: response\r\n });\r\n }\r\n return null;\r\n }\r\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 */\r\n function _resendPayload(payload, linearFactor) {\r\n if (linearFactor === void 0) { linearFactor = 1; }\r\n if (!payload || payload[_DYN_LENGTH /* @min:%2elength */] === 0) {\r\n return;\r\n }\r\n var buffer = _self[_DYN__BUFFER /* @min:%2e_buffer */];\r\n buffer[_DYN_CLEAR_SENT /* @min:%2eclearSent */](payload);\r\n _consecutiveErrors++;\r\n for (var _i = 0, payload_1 = payload; _i < payload_1.length; _i++) {\r\n var item = payload_1[_i];\r\n buffer[_DYN_ENQUEUE /* @min:%2eenqueue */](item);\r\n }\r\n // setup timer\r\n _setRetryTime(linearFactor);\r\n _setupTimer();\r\n }\r\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 */\r\n function _setRetryTime(linearFactor) {\r\n var SlotDelayInSeconds = 10;\r\n var delayInSeconds;\r\n if (_consecutiveErrors <= 1) {\r\n delayInSeconds = SlotDelayInSeconds;\r\n }\r\n else {\r\n var backOffSlot = (Math.pow(2, _consecutiveErrors) - 1) / 2;\r\n // tslint:disable-next-line:insecure-random\r\n var backOffDelay = Math.floor(Math.random() * backOffSlot * SlotDelayInSeconds) + 1;\r\n backOffDelay = linearFactor * backOffDelay;\r\n delayInSeconds = Math.max(Math.min(backOffDelay, 3600), SlotDelayInSeconds);\r\n }\r\n // TODO: Log the backoff time like the C# version does.\r\n var retryAfterTimeSpan = dateNow() + (delayInSeconds * 1000);\r\n // TODO: Log the retry at time like the C# version does.\r\n _retryAt = retryAfterTimeSpan;\r\n }\r\n /**\r\n * Sets up the timer which triggers actually sending the data.\r\n */\r\n function _setupTimer() {\r\n if (!_timeoutHandle && !_paused) {\r\n var retryInterval = _retryAt ? Math.max(0, _retryAt - dateNow()) : 0;\r\n var timerValue = Math.max(_maxBatchInterval, retryInterval);\r\n _timeoutHandle = scheduleTimeout(function () {\r\n _timeoutHandle = null;\r\n _self[_DYN_TRIGGER_SEND /* @min:%2etriggerSend */](true, null, 1 /* SendRequestReason.NormalSchedule */);\r\n }, timerValue);\r\n }\r\n }\r\n function _clearScheduledTimer() {\r\n _timeoutHandle && _timeoutHandle.cancel();\r\n _timeoutHandle = null;\r\n _retryAt = null;\r\n }\r\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 */\r\n function _isRetriable(statusCode) {\r\n return statusCode === 401 // Unauthorized\r\n || statusCode === 403 // Forbidden\r\n || statusCode === 408 // Timeout\r\n || statusCode === 429 // Too many requests.\r\n || statusCode === 500 // Internal server error.\r\n || statusCode === 502 // Bad Gateway.\r\n || statusCode === 503 // Service unavailable.\r\n || statusCode === 504; // Gateway timeout.\r\n }\r\n function _formatErrorMessageXhr(xhr, message) {\r\n if (xhr) {\r\n return \"XMLHttpRequest,Status:\" + xhr.status + \",Response:\" + _getResponseText(xhr) || xhr.response || \"\";\r\n }\r\n return message;\r\n }\r\n /**\r\n * Send XDomainRequest\r\n * @param payload - {string} - The data payload to be sent.\r\n * @param isAsync - {boolean} - Indicates if the request should be sent asynchronously\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 */\r\n function _xdrSender(payload, isAsync) {\r\n var buffer = _self[_DYN__BUFFER /* @min:%2e_buffer */];\r\n var _window = getWindow();\r\n var xdr = new XDomainRequest();\r\n // NOTE: xdr may send previous retry payload to new endpoint since we are not able to check response URL\r\n xdr.onload = function () { return _self._xdrOnLoad(xdr, payload); };\r\n xdr.onerror = function (event) { return _self[_DYN__ON_ERROR /* @min:%2e_onError */](payload, _formatErrorMessageXdr(xdr), event); };\r\n // XDomainRequest requires the same protocol as the hosting page.\r\n // If the protocol doesn't match, we can't send the telemetry :(.\r\n var hostingProtocol = _window && _window.location && _window.location.protocol || \"\";\r\n if (_endpointUrl.lastIndexOf(hostingProtocol, 0) !== 0) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 2 /* eLoggingSeverity.WARNING */, 40 /* _eInternalMessageId.TransmissionFailed */, \". \" +\r\n \"Cannot send XDomain request. The endpoint URL protocol doesn't match the hosting page protocol.\");\r\n buffer[_DYN_CLEAR /* @min:%2eclear */]();\r\n return;\r\n }\r\n var endpointUrl = _endpointUrl.replace(/^(https?:)/, \"\");\r\n xdr.open(\"POST\", endpointUrl);\r\n // compose an array of payloads\r\n var batch = buffer[_DYN_BATCH_PAYLOADS /* @min:%2ebatchPayloads */](payload);\r\n xdr.send(batch);\r\n buffer[_DYN_MARK_AS_SENT /* @min:%2emarkAsSent */](payload);\r\n }\r\n function _formatErrorMessageXdr(xdr, message) {\r\n if (xdr) {\r\n return \"XDomainRequest,Response:\" + _getResponseText(xdr) || \"\";\r\n }\r\n return message;\r\n }\r\n // Using function lookups for backward compatibility as the getNotifyMgr() did not exist until after v2.5.6\r\n function _getNotifyMgr() {\r\n var func = \"getNotifyMgr\";\r\n if (_self.core[func]) {\r\n return _self.core[func]();\r\n }\r\n // using _self.core['_notificationManager'] for backward compatibility\r\n return _self.core[\"_notificationManager\"];\r\n }\r\n function _notifySendRequest(sendRequest, isAsync) {\r\n var manager = _getNotifyMgr();\r\n if (manager && manager[_DYN_EVENTS_SEND_REQUEST /* @min:%2eeventsSendRequest */]) {\r\n try {\r\n manager[_DYN_EVENTS_SEND_REQUEST /* @min:%2eeventsSendRequest */](sendRequest, isAsync);\r\n }\r\n catch (e) {\r\n _throwInternal(_self[_DYN_DIAG_LOG /* @min:%2ediagLog */](), 1 /* eLoggingSeverity.CRITICAL */, 74 /* _eInternalMessageId.NotificationException */, \"send request notification failed: \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n }\r\n /**\r\n * Validate UUID Format\r\n * Specs taken from https://tools.ietf.org/html/rfc4122 and breeze repo\r\n */\r\n function _validateInstrumentationKey(instrumentationKey, config) {\r\n var disableValidation = config.disableInstrumentationKeyValidation;\r\n var disableIKeyValidationFlag = isNullOrUndefined(disableValidation) ? false : disableValidation;\r\n if (disableIKeyValidationFlag) {\r\n return true;\r\n }\r\n var UUID_Regex = \"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$\";\r\n var regexp = new RegExp(UUID_Regex);\r\n return regexp.test(instrumentationKey);\r\n }\r\n function _initDefaults() {\r\n _self[_DYN__SENDER /* @min:%2e_sender */] = null;\r\n _self[_DYN__BUFFER /* @min:%2e_buffer */] = null;\r\n _self._appId = null;\r\n _self._sample = null;\r\n _headers = {};\r\n _offlineListener = null;\r\n _consecutiveErrors = 0;\r\n _retryAt = null;\r\n _lastSend = null;\r\n _paused = false;\r\n _timeoutHandle = null;\r\n _serializer = null;\r\n _stamp_specific_redirects = 0;\r\n _syncFetchPayload = 0;\r\n _fallbackSender = null;\r\n _syncUnloadSender = null;\r\n _evtNamespace = null;\r\n _endpointUrl = null;\r\n _orgEndpointUrl = null;\r\n _maxBatchSizeInBytes = 0;\r\n _beaconSupported = false;\r\n _customHeaders = null;\r\n _disableTelemetry = false;\r\n _instrumentationKey = null;\r\n _convertUndefined = UNDEFINED_VALUE;\r\n _isRetryDisabled = false;\r\n _sessionStorageUsed = null;\r\n _namePrefix = UNDEFINED_VALUE;\r\n objDefine(_self, \"_senderConfig\", {\r\n g: function () {\r\n return objExtend({}, defaultAppInsightsChannelConfig);\r\n }\r\n });\r\n }\r\n });\r\n return _this;\r\n }\r\n Sender.constructEnvelope = function (orig, iKey, logger, convertUndefined) {\r\n var envelope;\r\n if (iKey !== orig.iKey && !isNullOrUndefined(iKey)) {\r\n envelope = __assign(__assign({}, orig), { iKey: iKey });\r\n }\r\n else {\r\n envelope = orig;\r\n }\r\n var creator = EnvelopeTypeCreator[envelope.baseType] || EventEnvelopeCreator;\r\n return creator(logger, envelope, convertUndefined);\r\n };\r\n /**\r\n * Pause the sending (transmission) of events, this will cause all events to be batched only until the maximum limits are\r\n * hit at which point new events are dropped. Will also cause events to NOT be sent during page unload, so if Session storage\r\n * is disabled events will be lost.\r\n * SessionStorage Limit is 2000 events, In-Memory (Array) Storage is 10,000 events (can be configured via the eventsLimitInMem).\r\n */\r\n Sender.prototype.pause = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Resume the sending (transmission) of events, this will restart the timer and any batched events will be sent using the normal\r\n * send interval.\r\n */\r\n Sender.prototype.resume = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Flush to send data immediately; channel should default to sending data asynchronously. If executing asynchronously (the default) and\r\n * you DO NOT pass a callback function then a [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * will be returned which will resolve once the flush is complete. The actual implementation of the `IPromise`\r\n * will be a native Promise (if supported) or the default as supplied by [ts-async library](https://github.com/nevware21/ts-async)\r\n * @param async - send data asynchronously when true\r\n * @param callBack - if specified, notify caller when send is complete, the channel should return true to indicate to the caller that it will be called.\r\n * If the caller doesn't return true the caller should assume that it may never be called.\r\n * @param sendReason - specify the reason that you are calling \"flush\" defaults to ManualFlush (1) if not specified\r\n * @returns - If a callback is provided `true` to indicate that callback will be called after the flush is complete otherwise the caller\r\n * should assume that any provided callback will never be called, Nothing or if occurring asynchronously a\r\n * [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) which will be resolved once the unload is complete,\r\n * the [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) will only be returned when no callback is provided\r\n * and async is true.\r\n */\r\n Sender.prototype.flush = function (async, callBack) {\r\n if (async === void 0) { async = true; }\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Flush the batched events synchronously (if possible -- based on configuration).\r\n * Will not flush if the Send has been paused.\r\n */\r\n Sender.prototype.onunloadFlush = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n Sender.prototype.initialize = function (config, core, extensions, pluginChain) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n Sender.prototype.processTelemetry = function (telemetryItem, itemCtx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * xhr state changes\r\n */\r\n Sender.prototype._xhrReadyStateChange = function (xhr, payload, countOfItemsInPayload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Trigger the immediate send of buffered data; If executing asynchronously (the default) this may (not required) return\r\n * an [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) that will resolve once the\r\n * send is complete. The actual implementation of the `IPromise` will be a native Promise (if supported) or the default\r\n * as supplied by [ts-async library](https://github.com/nevware21/ts-async)\r\n * @param async - Indicates if the events should be sent asynchronously\r\n * @param forcedSender - {SenderFunction} - Indicates the forcedSender, undefined if not passed\r\n * @returns - Nothing or optionally, if occurring asynchronously a [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * which will be resolved (or reject) once the send is complete, the [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * should only be returned when async is true.\r\n */\r\n Sender.prototype.triggerSend = function (async, forcedSender, sendReason) {\r\n if (async === void 0) { async = true; }\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * error handler\r\n */\r\n Sender.prototype._onError = function (payload, message, event) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * partial success handler\r\n */\r\n Sender.prototype._onPartialSuccess = function (payload, results) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * success handler\r\n */\r\n Sender.prototype._onSuccess = function (payload, countOfItemsInPayload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * xdr state changes\r\n */\r\n Sender.prototype._xdrOnLoad = function (xdr, payload) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Add header to request\r\n * @param name - Header name.\r\n * @param value - Header value.\r\n */\r\n Sender.prototype.addHeader = function (name, value) {\r\n // @DynamicProtoStub - DO NOT add any code as this will be removed during packaging\r\n };\r\n return Sender;\r\n}(BaseTelemetryPlugin));\r\nexport { Sender };\r\n//# sourceMappingURL=Sender.js.map","import dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { _throwInternal, getJSON, isArray, isFunction, isObject, objForEachKey } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_LENGTH, _DYN_PUSH, _DYN_STRINGIFY, _DYN_TO_STRING } from \"./__DynamicConstants\";\r\nvar Serializer = /** @class */ (function () {\r\n function Serializer(logger) {\r\n dynamicProto(Serializer, this, function (_self) {\r\n /**\r\n * Serializes the current object to a JSON string.\r\n */\r\n _self.serialize = function (input) {\r\n var output = _serializeObject(input, \"root\");\r\n try {\r\n return getJSON()[_DYN_STRINGIFY /* @min:%2estringify */](output);\r\n }\r\n catch (e) {\r\n // if serialization fails return an empty string\r\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);\r\n }\r\n };\r\n function _serializeObject(source, name) {\r\n var circularReferenceCheck = \"__aiCircularRefCheck\";\r\n var output = {};\r\n if (!source) {\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 48 /* _eInternalMessageId.CannotSerializeObject */, \"cannot serialize object because it is null or undefined\", { name: name }, true);\r\n return output;\r\n }\r\n if (source[circularReferenceCheck]) {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 50 /* _eInternalMessageId.CircularReferenceDetected */, \"Circular reference detected while serializing object\", { name: name }, true);\r\n return output;\r\n }\r\n if (!source.aiDataContract) {\r\n // special case for measurements/properties/tags\r\n if (name === \"measurements\") {\r\n output = _serializeStringMap(source, \"number\", name);\r\n }\r\n else if (name === \"properties\") {\r\n output = _serializeStringMap(source, \"string\", name);\r\n }\r\n else if (name === \"tags\") {\r\n output = _serializeStringMap(source, \"string\", name);\r\n }\r\n else if (isArray(source)) {\r\n output = _serializeArray(source, name);\r\n }\r\n else {\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 49 /* _eInternalMessageId.CannotSerializeObjectNonSerializable */, \"Attempting to serialize an object which does not implement ISerializable\", { name: name }, true);\r\n try {\r\n // verify that the object can be stringified\r\n getJSON()[_DYN_STRINGIFY /* @min:%2estringify */](source);\r\n output = source;\r\n }\r\n catch (e) {\r\n // if serialization fails return an empty string\r\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);\r\n }\r\n }\r\n return output;\r\n }\r\n source[circularReferenceCheck] = true;\r\n objForEachKey(source.aiDataContract, function (field, contract) {\r\n var isRequired = (isFunction(contract)) ? (contract() & 1 /* FieldType.Required */) : (contract & 1 /* FieldType.Required */);\r\n var isHidden = (isFunction(contract)) ? (contract() & 4 /* FieldType.Hidden */) : (contract & 4 /* FieldType.Hidden */);\r\n var isArray = contract & 2 /* FieldType.Array */;\r\n var isPresent = source[field] !== undefined;\r\n var isObj = isObject(source[field]) && source[field] !== null;\r\n if (isRequired && !isPresent && !isArray) {\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, 24 /* _eInternalMessageId.MissingRequiredFieldSpecification */, \"Missing required field specification. The field is required but not present on source\", { field: field, name: name });\r\n // If not in debug mode, continue and hope the error is permissible\r\n }\r\n else if (!isHidden) { // Don't serialize hidden fields\r\n var value = void 0;\r\n if (isObj) {\r\n if (isArray) {\r\n // special case; recurse on each object in the source array\r\n value = _serializeArray(source[field], field);\r\n }\r\n else {\r\n // recurse on the source object in this field\r\n value = _serializeObject(source[field], field);\r\n }\r\n }\r\n else {\r\n // assign the source field to the output even if undefined or required\r\n value = source[field];\r\n }\r\n // only emit this field if the value is defined\r\n if (value !== undefined) {\r\n output[field] = value;\r\n }\r\n }\r\n });\r\n delete source[circularReferenceCheck];\r\n return output;\r\n }\r\n function _serializeArray(sources, name) {\r\n var output;\r\n if (!!sources) {\r\n if (!isArray(sources)) {\r\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\", { name: name }, true);\r\n }\r\n else {\r\n output = [];\r\n for (var i = 0; i < sources[_DYN_LENGTH /* @min:%2elength */]; i++) {\r\n var source = sources[i];\r\n var item = _serializeObject(source, name + \"[\" + i + \"]\");\r\n output[_DYN_PUSH /* @min:%2epush */](item);\r\n }\r\n }\r\n }\r\n return output;\r\n }\r\n function _serializeStringMap(map, expectedType, name) {\r\n var output;\r\n if (map) {\r\n output = {};\r\n objForEachKey(map, function (field, value) {\r\n if (expectedType === \"string\") {\r\n if (value === undefined) {\r\n output[field] = \"undefined\";\r\n }\r\n else if (value === null) {\r\n output[field] = \"null\";\r\n }\r\n else if (!value[_DYN_TO_STRING /* @min:%2etoString */]) {\r\n output[field] = \"invalid field: toString() is not defined.\";\r\n }\r\n else {\r\n output[field] = value[_DYN_TO_STRING /* @min:%2etoString */]();\r\n }\r\n }\r\n else if (expectedType === \"number\") {\r\n if (value === undefined) {\r\n output[field] = \"undefined\";\r\n }\r\n else if (value === null) {\r\n output[field] = \"null\";\r\n }\r\n else {\r\n var num = parseFloat(value);\r\n if (isNaN(num)) {\r\n output[field] = \"NaN\";\r\n }\r\n else {\r\n output[field] = num;\r\n }\r\n }\r\n }\r\n else {\r\n output[field] = \"invalid field: \" + name + \" is of unknown type.\";\r\n _throwInternal(logger, 1 /* eLoggingSeverity.CRITICAL */, output[field], null, true);\r\n }\r\n });\r\n }\r\n return output;\r\n }\r\n });\r\n }\r\n /**\r\n * Serializes the current object to a JSON string.\r\n */\r\n Serializer.prototype.serialize = function (input) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n return Serializer;\r\n}());\r\nexport { Serializer };\r\n//# sourceMappingURL=Serializer.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { _DYN_LENGTH } from \"../../__DynamicConstants\";\r\n// (Magic number) DJB algorithm can't work on shorter strings (results in poor distribution\r\nvar MIN_INPUT_LENGTH = 8;\r\nvar HashCodeScoreGenerator = /** @class */ (function () {\r\n function HashCodeScoreGenerator() {\r\n }\r\n HashCodeScoreGenerator.prototype.getHashCodeScore = function (key) {\r\n var score = this.getHashCode(key) / HashCodeScoreGenerator.INT_MAX_VALUE;\r\n return score * 100;\r\n };\r\n HashCodeScoreGenerator.prototype.getHashCode = function (input) {\r\n if (input === \"\") {\r\n return 0;\r\n }\r\n while (input[_DYN_LENGTH /* @min:%2elength */] < MIN_INPUT_LENGTH) {\r\n input = input.concat(input);\r\n }\r\n // 5381 is a magic number: http://stackoverflow.com/questions/10696223/reason-for-5381-number-in-djb-hash-function\r\n var hash = 5381;\r\n for (var i = 0; i < input[_DYN_LENGTH /* @min:%2elength */]; ++i) {\r\n hash = ((hash << 5) + hash) + input.charCodeAt(i);\r\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)\r\n // 'hash & hash' will keep it 32 bit integer - just to make it clearer what the result is.\r\n hash = hash & hash;\r\n }\r\n return Math.abs(hash);\r\n };\r\n // We're using 32 bit math, hence max value is (2^31 - 1)\r\n HashCodeScoreGenerator.INT_MAX_VALUE = 2147483647;\r\n return HashCodeScoreGenerator;\r\n}());\r\nexport { HashCodeScoreGenerator };\r\n//# sourceMappingURL=HashCodeScoreGenerator.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { ContextTagKeys } from \"@microsoft/applicationinsights-common\";\r\nimport { _DYN_GET_HASH_CODE_SCORE, _DYN_GET_SAMPLING_SCORE, _DYN_TAGS, _DYN_TRACE_ID } from \"../../__DynamicConstants\";\r\nimport { HashCodeScoreGenerator } from \"./HashCodeScoreGenerator\";\r\nvar SamplingScoreGenerator = /** @class */ (function () {\r\n function SamplingScoreGenerator() {\r\n var _self = this;\r\n var hashCodeGenerator = new HashCodeScoreGenerator();\r\n var keys = new ContextTagKeys();\r\n _self[_DYN_GET_SAMPLING_SCORE /* @min:%2egetSamplingScore */] = function (item) {\r\n var score = 0;\r\n if (item[_DYN_TAGS /* @min:%2etags */] && item[_DYN_TAGS /* @min:%2etags */][keys.userId]) { // search in tags first, then ext\r\n score = hashCodeGenerator.getHashCodeScore(item[_DYN_TAGS /* @min:%2etags */][keys.userId]);\r\n }\r\n else if (item.ext && item.ext.user && item.ext.user.id) {\r\n score = hashCodeGenerator[_DYN_GET_HASH_CODE_SCORE /* @min:%2egetHashCodeScore */](item.ext.user.id);\r\n }\r\n else if (item[_DYN_TAGS /* @min:%2etags */] && item[_DYN_TAGS /* @min:%2etags */][keys.operationId]) { // search in tags first, then ext\r\n score = hashCodeGenerator.getHashCodeScore(item[_DYN_TAGS /* @min:%2etags */][keys.operationId]);\r\n }\r\n else if (item.ext && item.ext.telemetryTrace && item.ext.telemetryTrace[_DYN_TRACE_ID /* @min:%2etraceID */]) {\r\n score = hashCodeGenerator.getHashCodeScore(item.ext.telemetryTrace[_DYN_TRACE_ID /* @min:%2etraceID */]);\r\n }\r\n else {\r\n // tslint:disable-next-line:insecure-random\r\n score = (Math.random() * 100);\r\n }\r\n return score;\r\n };\r\n }\r\n return SamplingScoreGenerator;\r\n}());\r\nexport { SamplingScoreGenerator };\r\n//# sourceMappingURL=SamplingScoreGenerator.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { Metric } from \"@microsoft/applicationinsights-common\";\r\nimport { safeGetLogger } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_DATA_TYPE, _DYN_GET_SAMPLING_SCORE, _DYN_SAMPLE_RATE } from \"../__DynamicConstants\";\r\nimport { SamplingScoreGenerator } from \"./SamplingScoreGenerators/SamplingScoreGenerator\";\r\nvar Sample = /** @class */ (function () {\r\n function Sample(sampleRate, logger) {\r\n // We're using 32 bit math, hence max value is (2^31 - 1)\r\n this.INT_MAX_VALUE = 2147483647;\r\n var _logger = logger || safeGetLogger(null);\r\n if (sampleRate > 100 || sampleRate < 0) {\r\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.\", { samplingRate: sampleRate }, true);\r\n sampleRate = 100;\r\n }\r\n this[_DYN_SAMPLE_RATE /* @min:%2esampleRate */] = sampleRate;\r\n this.samplingScoreGenerator = new SamplingScoreGenerator();\r\n }\r\n /**\r\n * Determines if an envelope is sampled in (i.e. will be sent) or not (i.e. will be dropped).\r\n */\r\n Sample.prototype.isSampledIn = function (envelope) {\r\n var samplingPercentage = this[_DYN_SAMPLE_RATE /* @min:%2esampleRate */]; // 0 - 100\r\n var isSampledIn = false;\r\n if (samplingPercentage === null || samplingPercentage === undefined || samplingPercentage >= 100) {\r\n return true;\r\n }\r\n else if (envelope.baseType === Metric[_DYN_DATA_TYPE /* @min:%2edataType */]) {\r\n // exclude MetricData telemetry from sampling\r\n return true;\r\n }\r\n isSampledIn = this.samplingScoreGenerator[_DYN_GET_SAMPLING_SCORE /* @min:%2egetSamplingScore */](envelope) < samplingPercentage;\r\n return isSampledIn;\r\n };\r\n return Sample;\r\n}());\r\nexport { Sample };\r\n//# sourceMappingURL=Sample.js.map","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { ArrProto } from \"../internal/constants\";\r\nimport { _unwrapFunction } from \"../internal/unwrapFunction\";\r\n\r\n/**\r\n * The `reducer` function called for {@link arrReduce}.\r\n * @group Array\r\n * @group ArrayLike\r\n * @typeParam T - Identifies the type of array elements\r\n * @typeParam R - Identifies the type of the return array elements (defaults to T)\r\n * @param previousValue - The value resulting from the previous call to callbackFn. On first call, initialValue if\r\n * specified, otherwise the value of array[0].\r\n * @param currentValue - The value of the current element. On first call, the value of array[0] if an initialValue\r\n * was specified, otherwise the value of array[1].\r\n * @param currentIndex - The index position of currentValue in the array. On first call, 0 if initialValue was\r\n * specified, otherwise 1.\r\n * @param array -The array being traversed.\r\n */\r\nexport type ArrReduceCallbackFn = (previousValue: T | R, currentValue: T, currentIndex: number, array: T[]) => R;\r\n\r\n/**\r\n * The arrReduce() method executes a user-supplied \"reducer\" callback function on each element of the array,\r\n * in order, passing in the return value from the calculation on the preceding element. The final result of\r\n * running the reducer across all elements of the array is a single value.\r\n *\r\n * The first time that the callback is run there is no \"return value of the previous calculation\". If supplied,\r\n * an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial\r\n * value and iteration starts from the next element (index 1 instead of index 0).\r\n * @group Array\r\n * @group ArrayLike\r\n * @typeParam T - Identifies the type of array elements\r\n * @param theArray - The array or array like object of elements to be searched.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n * @returns The value that results from running the \"reducer\" callback function to completion over the entire array.\r\n * @example\r\n * ```ts\r\n * const getMax = (a: number, b: number) => Math.max(a, b);\r\n *\r\n * // callback is invoked for each element in the array starting at index 0\r\n * arrReduce([1, 100], getMax, 50); // 100\r\n * arrReduce([ 50], getMax, 10); // 50\r\n *\r\n * // callback is invoked once for element at index 1\r\n * arrReduce([1, 100], getMax); // 100\r\n *\r\n * // callback is not invoked\r\n * arrReduce([ 50], getMax); // 50\r\n * arrReduce([ ], getMax, 1); // 1\r\n *\r\n * arrReduce([ ], getMax); // throws TypeError\r\n *\r\n * // Also supports Array like objects\r\n * arrReduce({ length: 2, 0: 1, 1: 100 }, getMax, 50); // 100\r\n * arrReduce({ length: 1, 0: 50 }, getMax, 10); // 50\r\n *\r\n * // callback is invoked once for element at index 1\r\n * arrReduce({ length: 2, 0: 1, 1: 100 }, getMax); // 100\r\n *\r\n * // callback is not invoked\r\n * arrReduce({ length: 1, 0: 50 }, getMax); // 50\r\n * arrReduce({ length: 0 }, getMax, 1); // 1\r\n * ```\r\n */\r\nexport const arrReduce: (theArray: ArrayLike, callbackfn: ArrReduceCallbackFn, initialValue?: T | R) => R = _unwrapFunction(\"reduce\", ArrProto);\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { arrReduce, objKeys } from \"@microsoft/applicationinsights-core-js\";\r\nimport { DEFAULT_BREEZE_ENDPOINT } from \"./Constants\";\r\nimport { _DYN_INGESTIONENDPOINT, _DYN_LENGTH, _DYN_SPLIT, _DYN_TO_LOWER_CASE } from \"./__DynamicConstants\";\r\nvar _FIELDS_SEPARATOR = \";\";\r\nvar _FIELD_KEY_VALUE_SEPARATOR = \"=\";\r\nexport function parseConnectionString(connectionString) {\r\n if (!connectionString) {\r\n return {};\r\n }\r\n var kvPairs = connectionString[_DYN_SPLIT /* @min:%2esplit */](_FIELDS_SEPARATOR);\r\n var result = arrReduce(kvPairs, function (fields, kv) {\r\n var kvParts = kv[_DYN_SPLIT /* @min:%2esplit */](_FIELD_KEY_VALUE_SEPARATOR);\r\n if (kvParts[_DYN_LENGTH /* @min:%2elength */] === 2) { // only save fields with valid formats\r\n var key = kvParts[0][_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\r\n var value = kvParts[1];\r\n fields[key] = value;\r\n }\r\n return fields;\r\n }, {});\r\n if (objKeys(result)[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n // this is a valid connection string, so parse the results\r\n if (result.endpointsuffix) {\r\n // use endpoint suffix where overrides are not provided\r\n var locationPrefix = result.location ? result.location + \".\" : \"\";\r\n result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */] = result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */] || (\"https://\" + locationPrefix + \"dc.\" + result.endpointsuffix);\r\n }\r\n // apply the default endpoints\r\n result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */] = result[_DYN_INGESTIONENDPOINT /* @min:%2eingestionendpoint */] || DEFAULT_BREEZE_ENDPOINT;\r\n }\r\n return result;\r\n}\r\nexport var ConnectionStringParser = {\r\n parse: parseConnectionString\r\n};\r\n//# sourceMappingURL=ConnectionStringParser.js.map","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { arrForEach } from \"../array/forEach\";\r\nimport { fnCall } from \"../funcs/fnCall\";\r\nimport { isArray, isDate, isNullOrUndefined, isPrimitiveType } from \"../helpers/base\";\r\nimport { FUNCTION, NULL_VALUE, OBJECT } from \"../internal/constants\";\r\nimport { objDefine } from \"./define\";\r\nimport { isPlainObject } from \"./is_plain_object\";\r\n\r\n/**\r\n * @internal\r\n * @ignore\r\n * Provides the current context while performing a deep copy\r\n */\r\ninterface _DeepCopyContext {\r\n handler: ObjDeepCopyHandler;\r\n src: any;\r\n path?: Array;\r\n}\r\n\r\n/**\r\n * @internal\r\n * @ignore\r\n * Defines the type used for tracking visited objects during deep copy to identify recursive\r\n * objects.\r\n */\r\ninterface _RecursiveVisitMap {\r\n k: any;\r\n v: any;\r\n}\r\n\r\n/**\r\n * @internal\r\n * @ignore\r\n * Generic Object deep copy handler which creates a new plain object and copies enumerable properties from\r\n * the source to the new target plain object. The source object does not have to be a plain object.\r\n * @param details - The details object for the current property being copied\r\n * @returns true if the handler processed the field.\r\n */\r\nconst _defaultDeepCopyHandler = (details: IObjDeepCopyHandlerDetails): boolean => {\r\n // Make sure we at least copy plain objects\r\n details.value && plainObjDeepCopyHandler(details);\r\n\r\n // Always return true so that the iteration completes\r\n return true;\r\n};\r\n\r\n/**\r\n * @internal\r\n * @ignore\r\n * The ordered default deep copy handlers\r\n */\r\nconst defaultDeepCopyHandlers: ObjDeepCopyHandler[] = [\r\n arrayDeepCopyHandler,\r\n plainObjDeepCopyHandler,\r\n functionDeepCopyHandler,\r\n dateDeepCopyHandler\r\n];\r\n\r\n/**\r\n * @internal\r\n * @ignore\r\n * Helper function used for detecting and handling recursive properties\r\n * @param visitMap - The current map of objects that have been visited\r\n * @param source - The value (object) to be copied\r\n * @param newPath - The new access path from the origin to the current property\r\n * @param cb - The callback function to call if the current object has not already been processed.\r\n * @returns The new deep copied property, may be incomplete as the object is recursive and is still in the process of being copied\r\n */\r\nfunction _getSetVisited(visitMap: _RecursiveVisitMap[], source: any, newPath: Array, cb: (newEntry: _RecursiveVisitMap) => void) {\r\n let theEntry: _RecursiveVisitMap;\r\n arrForEach(visitMap, (entry) => {\r\n if (entry.k === source) {\r\n theEntry = entry;\r\n return -1;\r\n }\r\n });\r\n\r\n if (!theEntry) {\r\n // Add the target to the visit map so that deep nested objects refer to the single instance\r\n // Even if we have not finished processing it yet.\r\n theEntry = { k: source, v: source };\r\n visitMap.push(theEntry);\r\n\r\n // Now call the copy callback so that it populates the target\r\n cb(theEntry);\r\n }\r\n\r\n return theEntry.v;\r\n}\r\n\r\n/**\r\n * @internal\r\n * @ignore\r\n * Internal helper which performs the recursive deep copy\r\n * @param visitMap - The current map of objects that have been visited\r\n * @param value - The value being copied\r\n * @param ctx - The current copy context\r\n * @param key - [Optional] the current `key` for the value from the source object\r\n * @returns The new deep copied instance of the value.\r\n */\r\nfunction _deepCopy(visitMap: _RecursiveVisitMap[], value: T, ctx: _DeepCopyContext, key?: string | number | symbol): T {\r\n let userHandler = ctx.handler;\r\n let newPath = ctx.path ? (key ? ctx.path.concat(key) : ctx.path) : [];\r\n\r\n let newCtx: _DeepCopyContext = {\r\n handler: ctx.handler,\r\n src: ctx.src,\r\n path: newPath\r\n };\r\n\r\n const theType = typeof value;\r\n let isPlain = false;\r\n let isPrim = false;\r\n if (value && theType === OBJECT) {\r\n isPlain = isPlainObject(value);\r\n } else {\r\n isPrim = value === NULL_VALUE || isPrimitiveType(theType);\r\n }\r\n\r\n let details: IObjDeepCopyHandlerDetails = {\r\n type: theType,\r\n isPrim: isPrim,\r\n isPlain: isPlain,\r\n value: value,\r\n result: value,\r\n path: newPath,\r\n origin: ctx.src,\r\n copy: (source: T, newKey?: string | number | symbol): T => {\r\n return _deepCopy(visitMap, source, newKey ? newCtx : ctx, newKey);\r\n },\r\n copyTo: (target: T, source: T): T => {\r\n return _copyProps(visitMap, target, source, newCtx);\r\n }\r\n };\r\n\r\n if (!details.isPrim) {\r\n return _getSetVisited(visitMap, value, newPath, (newEntry) => {\r\n\r\n // Use an accessor to set the new value onto the new entry\r\n objDefine(details, \"result\", {\r\n g: function () {\r\n return newEntry.v;\r\n },\r\n s: function (newValue: any) {\r\n newEntry.v = newValue;\r\n }\r\n });\r\n\r\n let idx = 0;\r\n let handler = userHandler;\r\n while (!fnCall(handler || (idx < defaultDeepCopyHandlers.length ? defaultDeepCopyHandlers[idx++] : _defaultDeepCopyHandler), ctx, details)) {\r\n handler = NULL_VALUE;\r\n }\r\n });\r\n }\r\n\r\n // Allow the user handler to override the provided value\r\n if (userHandler && fnCall(userHandler, ctx, details)) {\r\n return details.result;\r\n }\r\n\r\n return value;\r\n}\r\n\r\n/**\r\n * @internal\r\n * @ignore\r\n * Internal helper to copy all of the enumerable properties from the source object to the new target object\r\n * @param visitMap - The current map of objects that have been visited\r\n * @param target - The target object to copy the properties to.\r\n * @param source - The source object to copy the properties from.\r\n * @param ctx - The current deep copy context\r\n * @returns The populated target object\r\n */\r\nfunction _copyProps(visitMap: _RecursiveVisitMap[], target: T, source: T, ctx: _DeepCopyContext) {\r\n if (!isNullOrUndefined(source)) {\r\n // Copy all properties (not just own properties)\r\n for (const key in source) {\r\n // Perform a deep copy of the object\r\n target[key] = _deepCopy(visitMap, source[key], ctx, key);\r\n }\r\n }\r\n\r\n return target;\r\n}\r\n\r\n/**\r\n * Object helper to copy all of the enumerable properties from the source object to the target, the\r\n * properties are copied via {@link objDeepCopy}. Automatic handling of recursive properties was added in v0.4.4\r\n * @group Object\r\n * @param target - The target object to populated\r\n * @param source - The source object to copy the properties from\r\n * @param handler - An optional callback that lets you provide / overide the deep cloning (Since 0.4.4)\r\n * @returns The target object\r\n * @example\r\n * ```ts\r\n * let a: any = { a: 1 };\r\n * let b: any = { b: 2, d: new Date(), e: new TestClass(\"Hello Darkness\") };\r\n * a.b = b; // { a: 1, b: { b: 2} }\r\n * b.a = a; // { a: 1, b: { b: 2, a: { a: 1, { b: 2, a: ... }}}}\r\n *\r\n * function copyHandler(details: IObjDeepCopyHandlerDetails) {\r\n * // details.origin === a\r\n * // details.path[] is the path to the current value\r\n * if (details.value && isDate(details.value)) {\r\n * // So for the date path === [ \"b\", \"d\" ] which represents\r\n * // details.origin[\"b\"][\"d\"] === The Date\r\n *\r\n * // Create a clone the Date object and set as the \"newValue\"\r\n * details.value = new Date(details.value.getTime());\r\n *\r\n * // Return true to indicate that we have \"handled\" the conversion\r\n * // See objDeepCopy example for just reusing the original value (just don't replace details.value)\r\n * return true;\r\n * }\r\n *\r\n * return false;\r\n * }\r\n *\r\n * let c: any = objCopyProps({}, a, copyHandler);\r\n *\r\n * assert.notEqual(a, c, \"check a and c are not the same\");\r\n * assert.ok(c !== c.b.a, \"The root object won't be the same for the target reference as are are copying properties to our target\");\r\n * assert.ok(c.b === c.b.a.b, \"Check that the 2 'b' references are the same object\");\r\n * assert.ok(c.b.a === c.b.a.b.a, \"Check that the 2 'a' references are the same object\");\r\n * assert.ok(c.b.d === c.b.a.b.d, \"Check that the 2 'd' references are the same object\");\r\n * assert.ok(isDate(c.b.d), \"The copied date is still real 'Date' instance\");\r\n * assert.notEqual(c.b.d, a.b.d, \"And the copied date is not the same as the original\");\r\n * assert.equal(c.b.d.getTime(), a.b.d.getTime(), \"But the dates are the same\");\r\n *\r\n * assert.ok(isObject(c.b.d), \"The copied date is now an object\");\r\n * ```\r\n */\r\nexport function objCopyProps(target: T, source: any, handler?: ObjDeepCopyHandler) {\r\n let ctx: _DeepCopyContext = {\r\n handler: handler,\r\n src: source,\r\n path: []\r\n };\r\n\r\n return _copyProps([], target, source, ctx);\r\n}\r\n\r\n/**\r\n * Context details passed to the deep copy handler to allow it parse the current value based on the original source\r\n * and path to reach the current value. The provided value should be updated with the value to by copied into the\r\n * new deep copy and will be used when the handler returns true.\r\n * @since 0.4.4\r\n * @group Object - Deep Copy\r\n */\r\nexport interface IObjDeepCopyHandlerDetails {\r\n /**\r\n * Identifies the type of the value as per `typeof value`, saves each check having to process this value.\r\n */\r\n type: string;\r\n\r\n /**\r\n * Identifies whether the type of the value is considered to be a primitive value\r\n */\r\n isPrim: boolean;\r\n\r\n /**\r\n * Identifies whether the type is a plain object or not, this also saves each handler from checking\r\n * the `type`, currently the type will also be \"object\" if this is `true`.\r\n * @since 0.9.6\r\n */\r\n isPlain: boolean;\r\n\r\n /**\r\n * The current value to be processed, replace this value with the new deep copied value to use when returning\r\n * true from the handler. Ignored when the handler returns false.\r\n */\r\n readonly value: any;\r\n\r\n /**\r\n * Replace this value with the new deep copied value (defaults to the same as the value property) this value will be\r\n * used when returning true from the handler. Ignored when the handler returns false.\r\n */\r\n result: any;\r\n\r\n /**\r\n * A array of keys from the orginal source (origin) object which lead to the current value\r\n */\r\n path: Array;\r\n\r\n /**\r\n * The original source object passed into the `objDeepCopy()` or `objCopyProps()` functions.\r\n */\r\n origin?: any;\r\n\r\n /**\r\n * Continue the deep copy with the current context and recursive checks, effectively calls {@link objDeepCopy}\r\n * but keeps the current context and recursive references.\r\n * @param source - The source object to be copied\r\n */\r\n copy(source: T, key?: string | number | symbol): T;\r\n\r\n /**\r\n * Continue the deep copy with the current context and recursive checks by copying all of the properties\r\n * from the source to the target instance, effectively calls {@link objCopyProps} but keeps the current context\r\n * and recursive references.\r\n * @param target - The target object to populated\r\n * @param source - The source object to copy the properties from\r\n */\r\n copyTo(target: T, source: T): T;\r\n}\r\n\r\n/**\r\n * An optional deep copy handler that lets you provide your own logic for deep copying objects, will\r\n * only be called once per object/property combination, so if an object is recursively included it\r\n * will only get called for the first instance.\r\n * Handlers SHOULD assign the \"result\" value with the new target instance BEFORE performing any additional deep copying,\r\n * so any recursive objects will get a reference to the new instance and not keep attempting to create new copies.\r\n * @since 0.4.4\r\n * @group Object - Deep Copy\r\n * @return true if handled and the value in details should be used otherwise false to continue with the default handling\r\n * The library includes several helpers which can be reused by any user provided handler\r\n * - {@link functionDeepCopyHandler} - Used to copy functions\r\n * - {@link arrayDeepCopyHandler} - Used to copy arrays\r\n * - {@link plainObjDeepCopyHandler} - Used to copy plain objects\r\n * - {@link dateDeepCopyHandler} - Used to copy date instances\r\n */\r\nexport type ObjDeepCopyHandler = (details: IObjDeepCopyHandlerDetails) => boolean;\r\n\r\n/**\r\n * Performs a deep copy of the source object, this is designed to work with base (plain) objects, arrays and primitives\r\n * if the source object contains class objects they will either be not cloned or may be considered non-operational after\r\n * performing a deep copy. ie. This is performing a deep copy of the objects properties so that altering the copy will\r\n * not mutate the source object hierarchy.\r\n * Automatic handling of recursive properties was added in v0.4.4.\r\n * @group Object\r\n * @group Object - Deep Copy\r\n * @param source - The source object to be copied\r\n * @param handler - An optional callback that lets you provide / overide the deep cloning (Since 0.4.4)\r\n * @return A new object which contains a deep copy of the source properties\r\n * @example\r\n * ```ts\r\n * let a: any = { a: 1 };\r\n * let b: any = { b: 2, d: new Date(), e: new TestClass(\"Hello Darkness\") };\r\n * a.b = b; // { a: 1, b: { b: 2} }\r\n * b.a = a; // { a: 1, b: { b: 2, a: { a: 1, { b: 2, a: ... }}}}\r\n *\r\n * function copyHandler(details: IObjDeepCopyHandlerDetails) {\r\n * // details.origin === a\r\n * // details.path[] is the path to the current value\r\n * if (details.value && isDate(details.value)) {\r\n * // So for the date path === [ \"b\", \"d\" ] which represents\r\n * // details.origin[\"b\"][\"d\"] === The Date\r\n *\r\n * // Return true to indicate that we have \"handled\" the conversion\r\n * // Which in this case will reuse the existing instance (as we didn't replace details.value)\r\n * // See objCopyProps example for replacing the Date instance\r\n * return true;\r\n * }\r\n *\r\n * return false;\r\n * }\r\n *\r\n * let c: any = objDeepCopy(a, copyHandler);\r\n *\r\n * assert.notEqual(a, c, \"check a and c are not the same\");\r\n * assert.ok(c === c.b.a, \"The root object won't be the same for the target reference\");\r\n * assert.ok(c.b === c.b.a.b, \"Check that the 2 'b' references are the same object\");\r\n * assert.ok(c.b.a === c.b.a.b.a, \"Check that the 2 'a' references are the same object\");\r\n * assert.ok(c.b.d === c.b.a.b.d, \"Check that the 2 'd' references are the same object\");\r\n * assert.ok(isDate(c.b.d), \"The copied date is still real 'Date' instance\");\r\n * assert.equal(c.b.d, a.b.d, \"And the copied date is the original date\");\r\n * assert.equal(c.b.d.getTime(), a.b.d.getTime(), \"But the dates are the same\");\r\n * assert.ok(isObject(c.b.d), \"The copied date is now an object\");\r\n * assert.ok(!isError(c.b.e), \"The copied error is no longer a real 'Error' instance\");\r\n * assert.ok(isObject(c.b.e), \"The copied error is now an object\");\r\n * assert.equal(42, c.b.e.value, \"Expect that the local property was copied\");\r\n * ```\r\n */\r\nexport function objDeepCopy(source: T, handler?: ObjDeepCopyHandler): T {\r\n let ctx: _DeepCopyContext = {\r\n handler: handler,\r\n src: source\r\n };\r\n\r\n return _deepCopy([], source, ctx);\r\n}\r\n\r\n/**\r\n * Deep copy handler to identify and copy arrays.\r\n * @since 0.4.4\r\n * @group Object - Deep Copy\r\n * @param details - The details object for the current property being copied\r\n * @returns `true` if the current value is a function otherwise `false`\r\n */\r\nexport function arrayDeepCopyHandler(details: IObjDeepCopyHandlerDetails): boolean {\r\n let value = details.value;\r\n if (isArray(value)) {\r\n // Assign the \"result\" value before performing any additional deep Copying, so any recursive object get a reference to this instance\r\n let target: any[] = details.result = [];\r\n target.length = value.length;\r\n\r\n // Copying all properties as arrays can contain non-indexed based properties\r\n details.copyTo(target, value);\r\n return true;\r\n }\r\n\r\n return false;\r\n}\r\n\r\n/**\r\n * Deep copy handler to identify and copy Date instances.\r\n * @since 0.4.4\r\n * @group Object - Deep Copy\r\n * @param details - The details object for the current property being copied\r\n * @returns `true` if the current value is a function otherwise `false`\r\n */\r\nexport function dateDeepCopyHandler(details: IObjDeepCopyHandlerDetails) {\r\n let value = details.value;\r\n if (isDate(value)) {\r\n details.result = new Date(value.getTime());\r\n return true;\r\n }\r\n\r\n return false;\r\n}\r\n\r\n/**\r\n * Deep copy handler to identify and copy functions. This handler just returns the original\r\n * function so the original function will be assigned to any new deep copied instance.\r\n * @since 0.4.4\r\n * @group Object - Deep Copy\r\n * @param details - The details object for the current property being copied\r\n * @returns `true` if the current value is a function otherwise `false`\r\n */\r\nexport function functionDeepCopyHandler(details: IObjDeepCopyHandlerDetails): boolean {\r\n if (details.type === FUNCTION) {\r\n return true;\r\n }\r\n\r\n return false;\r\n}\r\n\r\n/**\r\n * Deep copy handler to identify and copy plain objects.\r\n * @since 0.4.4\r\n * @group Object - Deep Copy\r\n * @param details - The details object for the current property being copied\r\n * @returns `true` if the current value is a function otherwise `false`\r\n */\r\nexport function plainObjDeepCopyHandler(details: IObjDeepCopyHandlerDetails): boolean {\r\n let value = details.value;\r\n if (value && details.isPlain) {\r\n // Assign the \"result\" value before performing any additional deep Copying, so any recursive object get a reference to this instance\r\n let target = details.result = {};\r\n details.copyTo(target, value);\r\n return true;\r\n }\r\n\r\n return false;\r\n}\r\n","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { arrForEach } from \"../array/forEach\";\r\nimport { arrSlice } from \"../array/slice\";\r\nimport { objCopyProps, objDeepCopy } from \"../object/copy\";\r\n\r\n/**\r\n * @internal\r\n * @ignore\r\n */\r\nfunction _doExtend(target: T, theArgs: any[]): any {\r\n arrForEach(theArgs, (theArg) => {\r\n objCopyProps(target, theArg);\r\n });\r\n\r\n return target;\r\n}\r\n\r\n/**\r\n * Create a new object by merging the passed arguments, this is effectively the same as calling `objExtend({}, ...theArgs)` where\r\n * all of the arguments are added to a new object that is returned.\r\n * @group Object\r\n * @param target - The original object to be extended.\r\n * @param theArgs - The optional number of arguments to be copied\r\n * @returns - A new object or the original\r\n */\r\nexport function deepExtend(target: T, ...theArgs: any): T & any;\r\nexport function deepExtend(target: T, obj1?: T1, obj2?: T2, obj3?: T3, obj4?: T4, obj5?: T5, obj6?: T6): T & T1 & T2 & T3 & T4 & T5 & T6 {\r\n return _doExtend(objDeepCopy(target) || {}, arrSlice(arguments));\r\n}\r\n \r\n/**\r\n * Extend the target object by merging the passed arguments into it\r\n * @group Object\r\n * @param target - The object to be extended or overwritten\r\n * @param theArgs - The optional number of arguments to be copied\r\n * @returns - A new object or the original\r\n */\r\nexport function objExtend(target: T, ...theArgs: any): T & any;\r\nexport function objExtend(target: T, obj1?: T1, obj2?: T2, obj3?: T3, obj4?: T4, obj5?: T5, obj6?: T6): T & T1 & T2 & T3 & T4 & T5 & T6 {\r\n return _doExtend(target || {}, arrSlice(arguments));\r\n}\r\n\r\n ","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nexport var ChannelControllerPriority = 500;\r\n//# sourceMappingURL=Constants.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { createAllPromise, createPromise, doAwaitResponse } from \"@nevware21/ts-async\";\r\nimport { arrForEach, arrIndexOf, objDefine, scheduleTimeout } from \"@nevware21/ts-utils\";\r\nimport { createDynamicConfig } from \"../Config/DynamicConfig\";\r\nimport { _DYN_ADD_NOTIFICATION_LIS1, _DYN_IS_ASYNC, _DYN_IS_CHILD_EVT, _DYN_PUSH, _DYN_REMOVE_NOTIFICATION_2, _DYN_SPLICE, _DYN_UNLOAD, _DYN_WATCH } from \"../__DynamicConstants\";\r\nimport { STR_EVENTS_DISCARDED, STR_EVENTS_SEND_REQUEST, STR_EVENTS_SENT, STR_PERF_EVENT } from \"./InternalConstants\";\r\nvar defaultValues = {\r\n perfEvtsSendAll: false\r\n};\r\nfunction _runListeners(listeners, name, isAsync, callback) {\r\n arrForEach(listeners, function (listener) {\r\n if (listener && listener[name]) {\r\n if (isAsync) {\r\n scheduleTimeout(function () { return callback(listener); }, 0);\r\n }\r\n else {\r\n try {\r\n callback(listener);\r\n }\r\n catch (e) {\r\n // Catch errors to ensure we don't block sending the requests\r\n }\r\n }\r\n }\r\n });\r\n}\r\n/**\r\n * Class to manage sending notifications to all the listeners.\r\n */\r\nvar NotificationManager = /** @class */ (function () {\r\n function NotificationManager(config) {\r\n this.listeners = [];\r\n var perfEvtsSendAll;\r\n var unloadHandler;\r\n var _listeners = [];\r\n var cfgHandler = createDynamicConfig(config, defaultValues);\r\n unloadHandler = cfgHandler[_DYN_WATCH /* @min:%2ewatch */](function (details) {\r\n perfEvtsSendAll = !!details.cfg.perfEvtsSendAll;\r\n });\r\n dynamicProto(NotificationManager, this, function (_self) {\r\n objDefine(_self, \"listeners\", {\r\n g: function () { return _listeners; }\r\n });\r\n _self[_DYN_ADD_NOTIFICATION_LIS1 /* @min:%2eaddNotificationListener */] = function (listener) {\r\n _listeners[_DYN_PUSH /* @min:%2epush */](listener);\r\n };\r\n /**\r\n * Removes all instances of the listener.\r\n * @param listener - AWTNotificationListener to remove.\r\n */\r\n _self[_DYN_REMOVE_NOTIFICATION_2 /* @min:%2eremoveNotificationListener */] = function (listener) {\r\n var index = arrIndexOf(_listeners, listener);\r\n while (index > -1) {\r\n _listeners[_DYN_SPLICE /* @min:%2esplice */](index, 1);\r\n index = arrIndexOf(_listeners, listener);\r\n }\r\n };\r\n /**\r\n * Notification for events sent.\r\n * @param events - The array of events that have been sent.\r\n */\r\n _self[STR_EVENTS_SENT /* @min:%2eeventsSent */] = function (events) {\r\n _runListeners(_listeners, STR_EVENTS_SENT, true, function (listener) {\r\n listener[STR_EVENTS_SENT /* @min:%2eeventsSent */](events);\r\n });\r\n };\r\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 */\r\n _self[STR_EVENTS_DISCARDED /* @min:%2eeventsDiscarded */] = function (events, reason) {\r\n _runListeners(_listeners, STR_EVENTS_DISCARDED, true, function (listener) {\r\n listener[STR_EVENTS_DISCARDED /* @min:%2eeventsDiscarded */](events, reason);\r\n });\r\n };\r\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 */\r\n _self[STR_EVENTS_SEND_REQUEST /* @min:%2eeventsSendRequest */] = function (sendReason, isAsync) {\r\n _runListeners(_listeners, STR_EVENTS_SEND_REQUEST, isAsync, function (listener) {\r\n listener[STR_EVENTS_SEND_REQUEST /* @min:%2eeventsSendRequest */](sendReason, isAsync);\r\n });\r\n };\r\n _self[STR_PERF_EVENT /* @min:%2eperfEvent */] = function (perfEvent) {\r\n if (perfEvent) {\r\n // Send all events or only parent events\r\n if (perfEvtsSendAll || !perfEvent[_DYN_IS_CHILD_EVT /* @min:%2eisChildEvt */]()) {\r\n _runListeners(_listeners, STR_PERF_EVENT, false, function (listener) {\r\n if (perfEvent[_DYN_IS_ASYNC /* @min:%2eisAsync */]) {\r\n scheduleTimeout(function () { return listener[STR_PERF_EVENT /* @min:%2eperfEvent */](perfEvent); }, 0);\r\n }\r\n else {\r\n listener[STR_PERF_EVENT /* @min:%2eperfEvent */](perfEvent);\r\n }\r\n });\r\n }\r\n }\r\n };\r\n _self[_DYN_UNLOAD /* @min:%2eunload */] = function (isAsync) {\r\n var _finishUnload = function () {\r\n unloadHandler && unloadHandler.rm();\r\n unloadHandler = null;\r\n _listeners = [];\r\n };\r\n var waiting;\r\n _runListeners(_listeners, \"unload\", false, function (listener) {\r\n var asyncUnload = listener[_DYN_UNLOAD /* @min:%2eunload */](isAsync);\r\n if (asyncUnload) {\r\n if (!waiting) {\r\n waiting = [];\r\n }\r\n waiting[_DYN_PUSH /* @min:%2epush */](asyncUnload);\r\n }\r\n });\r\n if (waiting) {\r\n return createPromise(function (resolve) {\r\n return doAwaitResponse(createAllPromise(waiting), function () {\r\n _finishUnload();\r\n resolve();\r\n });\r\n });\r\n }\r\n else {\r\n _finishUnload();\r\n }\r\n };\r\n });\r\n }\r\n /**\r\n * Adds a notification listener.\r\n * @param listener - The notification listener to be added.\r\n */\r\n NotificationManager.prototype.addNotificationListener = function (listener) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Removes all instances of the listener.\r\n * @param listener - AWTNotificationListener to remove.\r\n */\r\n NotificationManager.prototype.removeNotificationListener = function (listener) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Notification for events sent.\r\n * @param events - The array of events that have been sent.\r\n */\r\n NotificationManager.prototype.eventsSent = function (events) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\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 */\r\n NotificationManager.prototype.eventsDiscarded = function (events, reason) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\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 */\r\n NotificationManager.prototype.eventsSendRequest = function (sendReason, isAsync) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * [Optional] This event is sent if you have enabled perf events, they are primarily used to track internal performance testing and debugging\r\n * the event can be displayed via the debug plugin extension.\r\n * @param perfEvent\r\n */\r\n NotificationManager.prototype.perfEvent = function (perfEvent) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Unload and remove any state that this INotificationManager may be holding, this is generally called when the\r\n * owning SDK is being unloaded.\r\n * @param isAsync - Can the unload be performed asynchronously (default)\r\n * @return If the unload occurs synchronously then nothing should be returned, if happening asynchronously then\r\n * the function should return an [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * / Promise to allow any listeners to wait for the operation to complete.\r\n */\r\n NotificationManager.prototype.unload = function (isAsync) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n return NotificationManager;\r\n}());\r\nexport { NotificationManager };\r\n//# sourceMappingURL=NotificationManager.js.map","// // Copyright (c) Microsoft Corporation. All rights reserved.\r\n// // Licensed under the MIT License.\r\nimport { __extends } from \"tslib\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { arrAppend, arrForEach, dumpObj } from \"@nevware21/ts-utils\";\r\nimport { _DYN_APPLY, _DYN_DIAG_LOG, _DYN_LENGTH, _DYN_PROCESS_NEXT, _DYN_SPLICE, _DYN__DO_TEARDOWN } from \"../__DynamicConstants\";\r\nimport { BaseTelemetryPlugin } from \"./BaseTelemetryPlugin\";\r\nimport { _throwInternal } from \"./DiagnosticLogger\";\r\nimport { getExceptionName } from \"./HelperFuncs\";\r\nimport { STR_PROCESS_TELEMETRY } from \"./InternalConstants\";\r\nfunction _addInitializer(_initializers, id, telemetryInitializer) {\r\n var theInitializer = {\r\n id: id,\r\n fn: telemetryInitializer\r\n };\r\n arrAppend(_initializers, theInitializer);\r\n var handler = {\r\n remove: function () {\r\n arrForEach(_initializers, function (initializer, idx) {\r\n if (initializer.id === theInitializer.id) {\r\n _initializers[_DYN_SPLICE /* @min:%2esplice */](idx, 1);\r\n return -1;\r\n }\r\n });\r\n }\r\n };\r\n return handler;\r\n}\r\nfunction _runInitializers(_initializers, item, logger) {\r\n var doNotSendItem = false;\r\n var telemetryInitializersCount = _initializers[_DYN_LENGTH /* @min:%2elength */];\r\n for (var i = 0; i < telemetryInitializersCount; ++i) {\r\n var telemetryInitializer = _initializers[i];\r\n if (telemetryInitializer) {\r\n try {\r\n if (telemetryInitializer.fn[_DYN_APPLY /* @min:%2eapply */](null, [item]) === false) {\r\n doNotSendItem = true;\r\n break;\r\n }\r\n }\r\n catch (e) {\r\n // log error but dont stop executing rest of the telemetry initializers\r\n // doNotSendItem = true;\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 64 /* _eInternalMessageId.TelemetryInitializerFailed */, \"Telemetry initializer failed: \" + getExceptionName(e), { exception: dumpObj(e) }, true);\r\n }\r\n }\r\n }\r\n return !doNotSendItem;\r\n}\r\nvar TelemetryInitializerPlugin = /** @class */ (function (_super) {\r\n __extends(TelemetryInitializerPlugin, _super);\r\n function TelemetryInitializerPlugin() {\r\n var _this = _super.call(this) || this;\r\n _this.identifier = \"TelemetryInitializerPlugin\";\r\n _this.priority = 199;\r\n // NOTE!: DON'T set default values here, instead set them in the _initDefaults() function as it is also called during teardown()\r\n var _id;\r\n var _initializers;\r\n _initDefaults();\r\n dynamicProto(TelemetryInitializerPlugin, _this, function (_self, _base) {\r\n _self.addTelemetryInitializer = function (telemetryInitializer) {\r\n return _addInitializer(_initializers, _id++, telemetryInitializer);\r\n };\r\n _self[STR_PROCESS_TELEMETRY /* @min:%2eprocessTelemetry */] = function (item, itemCtx) {\r\n if (_runInitializers(_initializers, item, itemCtx ? itemCtx[_DYN_DIAG_LOG /* @min:%2ediagLog */]() : _self[_DYN_DIAG_LOG /* @min:%2ediagLog */]())) {\r\n _self[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](item, itemCtx);\r\n }\r\n };\r\n _self[_DYN__DO_TEARDOWN /* @min:%2e_doTeardown */] = function () {\r\n _initDefaults();\r\n };\r\n });\r\n function _initDefaults() {\r\n _id = 0;\r\n _initializers = [];\r\n }\r\n return _this;\r\n }\r\n /**\r\n * Add a telemetry processor to decorate or drop telemetry events.\r\n * @param telemetryInitializer - The Telemetry Initializer function\r\n * @returns - A ITelemetryInitializerHandler to enable the initializer to be removed\r\n */\r\n TelemetryInitializerPlugin.prototype.addTelemetryInitializer = function (telemetryInitializer) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n TelemetryInitializerPlugin.prototype.processTelemetry = function (env, itemCtx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n return TelemetryInitializerPlugin;\r\n}(BaseTelemetryPlugin));\r\nexport { TelemetryInitializerPlugin };\r\n//# sourceMappingURL=TelemetryInitializerPlugin.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\"use strict\";\r\nvar _a;\r\nimport { __spreadArray } from \"tslib\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { createPromise } from \"@nevware21/ts-async\";\r\nimport { arrAppend, arrForEach, arrIndexOf, createTimeout, deepExtend, hasDocument, isFunction, isNullOrUndefined, isPlainObject, objDeepFreeze, objDefine, objForEachKey, objFreeze, objHasOwn, scheduleTimeout, throwError } from \"@nevware21/ts-utils\";\r\nimport { createDynamicConfig, onConfigChange } from \"../Config/DynamicConfig\";\r\nimport { _DYN_ADD_NOTIFICATION_LIS1, _DYN_CANCEL, _DYN_CREATE_NEW, _DYN_ENABLED, _DYN_GET_NOTIFY_MGR, _DYN_GET_PLUGIN, _DYN_GET_PROCESS_TEL_CONT0, _DYN_IDENTIFIER, _DYN_INITIALIZE, _DYN_IS_ASYNC, _DYN_IS_INITIALIZED, _DYN_LENGTH, _DYN_LOGGER, _DYN_LOGGING_LEVEL_CONSOL4, _DYN_MESSAGE, _DYN_MESSAGE_ID, _DYN_NAME, _DYN_NOTIFY, _DYN_ON_COMPLETE, _DYN_POLL_INTERNAL_LOGS, _DYN_PROCESS_NEXT, _DYN_PUSH, _DYN_REMOVE_NOTIFICATION_2, _DYN_SET_DF, _DYN_SPLICE, _DYN_STOP_POLLING_INTERNA3, _DYN_TEARDOWN, _DYN_TIME, _DYN_UNLOAD, _DYN_VERSION, _DYN_WATCH } from \"../__DynamicConstants\";\r\nimport { doUnloadAll, runTargetUnload } from \"./AsyncUtils\";\r\nimport { ChannelControllerPriority } from \"./Constants\";\r\nimport { createCookieMgr } from \"./CookieMgr\";\r\nimport { createUniqueNamespace } from \"./DataCacheHelper\";\r\nimport { getDebugListener } from \"./DbgExtensionUtils\";\r\nimport { DiagnosticLogger, _InternalLogMessage, _throwInternal, _warnToConsole } from \"./DiagnosticLogger\";\r\nimport { getSetValue, proxyFunctionAs, proxyFunctions, toISOString } from \"./HelperFuncs\";\r\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\";\r\nimport { NotificationManager } from \"./NotificationManager\";\r\nimport { PerfManager, doPerf, getGblPerfMgr } from \"./PerfManager\";\r\nimport { createProcessTelemetryContext, createProcessTelemetryUnloadContext, createProcessTelemetryUpdateContext, createTelemetryProxyChain } from \"./ProcessTelemetryContext\";\r\nimport { _getPluginState, createDistributedTraceContext, initializePlugins, sortPlugins } from \"./TelemetryHelpers\";\r\nimport { TelemetryInitializerPlugin } from \"./TelemetryInitializerPlugin\";\r\nimport { createUnloadHandlerContainer } from \"./UnloadHandlerContainer\";\r\nimport { createUnloadHookContainer } from \"./UnloadHookContainer\";\r\nvar strValidationError = \"Plugins must provide initialize method\";\r\nvar strNotificationManager = \"_notificationManager\";\r\nvar strSdkUnloadingError = \"SDK is still unloading...\";\r\nvar strSdkNotInitialized = \"SDK is not initialized\";\r\n// const strPluginUnloadFailed = \"Failed to unload plugin\";\r\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 */\r\nvar defaultConfig = objDeepFreeze((_a = {\r\n cookieCfg: {}\r\n },\r\n _a[STR_EXTENSIONS] = { rdOnly: true, ref: true, v: [] },\r\n _a[STR_CHANNELS] = { rdOnly: true, ref: true, v: [] },\r\n _a[STR_EXTENSION_CONFIG] = { ref: true, v: {} },\r\n _a[STR_CREATE_PERF_MGR] = UNDEFINED_VALUE,\r\n _a.loggingLevelConsole = 0 /* eLoggingSeverity.DISABLED */,\r\n _a.diagnosticLogInterval = UNDEFINED_VALUE,\r\n _a));\r\n/**\r\n * Helper to create the default performance manager\r\n * @param core\r\n * @param notificationMgr\r\n */\r\nfunction _createPerfManager(core, notificationMgr) {\r\n return new PerfManager(notificationMgr);\r\n}\r\nfunction _validateExtensions(logger, channelPriority, allExtensions) {\r\n var _a;\r\n // Concat all available extensions\r\n var coreExtensions = [];\r\n var channels = [];\r\n // Check if any two extensions have the same priority, then warn to console\r\n // And extract the local extensions from the\r\n var extPriorities = {};\r\n // Extension validation\r\n arrForEach(allExtensions, function (ext) {\r\n // Check for ext.initialize\r\n if (isNullOrUndefined(ext) || isNullOrUndefined(ext[_DYN_INITIALIZE /* @min:%2einitialize */])) {\r\n throwError(strValidationError);\r\n }\r\n var extPriority = ext[STR_PRIORITY /* @min:%2epriority */];\r\n var identifier = ext[_DYN_IDENTIFIER /* @min:%2eidentifier */];\r\n if (ext && extPriority) {\r\n if (!isNullOrUndefined(extPriorities[extPriority])) {\r\n _warnToConsole(logger, \"Two extensions have same priority #\" + extPriority + \" - \" + extPriorities[extPriority] + \", \" + identifier);\r\n }\r\n else {\r\n // set a value\r\n extPriorities[extPriority] = identifier;\r\n }\r\n }\r\n // Split extensions to core and channels\r\n if (!extPriority || extPriority < channelPriority) {\r\n // Add to core extension that will be managed by AppInsightsCore\r\n coreExtensions[_DYN_PUSH /* @min:%2epush */](ext);\r\n }\r\n else {\r\n channels[_DYN_PUSH /* @min:%2epush */](ext);\r\n }\r\n });\r\n return _a = {},\r\n _a[STR_CORE /* @min:core */] = coreExtensions,\r\n _a[STR_CHANNELS /* @min:channels */] = channels,\r\n _a;\r\n}\r\nfunction _isPluginPresent(thePlugin, plugins) {\r\n var exists = false;\r\n arrForEach(plugins, function (plugin) {\r\n if (plugin === thePlugin) {\r\n exists = true;\r\n return -1;\r\n }\r\n });\r\n return exists;\r\n}\r\nfunction _deepMergeConfig(details, target, newValues, merge) {\r\n // Lets assign the new values to the existing config\r\n if (newValues) {\r\n objForEachKey(newValues, function (key, value) {\r\n if (merge) {\r\n if (isPlainObject(value) && isPlainObject(target[key])) {\r\n // The target is an object and it has a value\r\n _deepMergeConfig(details, target[key], value, merge);\r\n }\r\n }\r\n if (merge && isPlainObject(value) && isPlainObject(target[key])) {\r\n // The target is an object and it has a value\r\n _deepMergeConfig(details, target[key], value, merge);\r\n }\r\n else {\r\n // Just Assign (replace) and/or make the property dynamic\r\n details.set(target, key, value);\r\n }\r\n });\r\n }\r\n}\r\nfunction _findWatcher(listeners, newWatcher) {\r\n var theListener = null;\r\n var idx = -1;\r\n arrForEach(listeners, function (listener, lp) {\r\n if (listener.w === newWatcher) {\r\n theListener = listener;\r\n idx = lp;\r\n return -1;\r\n }\r\n });\r\n return { i: idx, l: theListener };\r\n}\r\nfunction _addDelayedCfgListener(listeners, newWatcher) {\r\n var theListener = _findWatcher(listeners, newWatcher).l;\r\n if (!theListener) {\r\n theListener = {\r\n w: newWatcher,\r\n rm: function () {\r\n var fnd = _findWatcher(listeners, newWatcher);\r\n if (fnd.i !== -1) {\r\n listeners[_DYN_SPLICE /* @min:%2esplice */](fnd.i, 1);\r\n }\r\n }\r\n };\r\n listeners[_DYN_PUSH /* @min:%2epush */](theListener);\r\n }\r\n return theListener;\r\n}\r\nfunction _registerDelayedCfgListener(config, listeners, logger) {\r\n arrForEach(listeners, function (listener) {\r\n var unloadHdl = onConfigChange(config, listener.w, logger);\r\n delete listener.w; // Clear the listener reference so it will get garbage collected.\r\n // replace the remove function\r\n listener.rm = function () {\r\n unloadHdl.rm();\r\n };\r\n });\r\n}\r\nvar AppInsightsCore = /** @class */ (function () {\r\n function AppInsightsCore() {\r\n // NOTE!: DON'T set default values here, instead set them in the _initDefaults() function as it is also called during teardown()\r\n var _configHandler;\r\n var _isInitialized;\r\n var _logger;\r\n var _eventQueue;\r\n var _notificationManager;\r\n var _perfManager;\r\n var _cfgPerfManager;\r\n var _cookieManager;\r\n var _pluginChain;\r\n var _configExtensions;\r\n var _channelConfig;\r\n var _channels;\r\n var _isUnloading;\r\n var _telemetryInitializerPlugin;\r\n var _internalLogsEventName;\r\n var _evtNamespace;\r\n var _unloadHandlers;\r\n var _hookContainer;\r\n var _debugListener;\r\n var _traceCtx;\r\n var _instrumentationKey;\r\n var _cfgListeners;\r\n var _extensions;\r\n var _pluginVersionStringArr;\r\n var _pluginVersionString;\r\n /**\r\n * Internal log poller\r\n */\r\n var _internalLogPoller;\r\n var _internalLogPollerListening;\r\n var _forceStopInternalLogPoller;\r\n dynamicProto(AppInsightsCore, this, function (_self) {\r\n // Set the default values (also called during teardown)\r\n _initDefaults();\r\n // Special internal method to allow the unit tests and DebugPlugin to hook embedded objects\r\n _self[\"_getDbgPlgTargets\"] = function () {\r\n return [_extensions];\r\n };\r\n _self[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */] = function () { return _isInitialized; };\r\n // Creating the self.initialize = ()\r\n _self[_DYN_INITIALIZE /* @min:%2einitialize */] = function (config, extensions, logger, notificationManager) {\r\n if (_isUnloading) {\r\n throwError(strSdkUnloadingError);\r\n }\r\n // Make sure core is only initialized once\r\n if (_self[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */]()) {\r\n throwError(\"Core cannot be initialized more than once\");\r\n }\r\n _configHandler = createDynamicConfig(config, defaultConfig, logger || _self[_DYN_LOGGER /* @min:%2elogger */], false);\r\n // Re-assigning the local config property so we don't have any references to the passed value and it can be garbage collected\r\n config = _configHandler.cfg;\r\n // This will be \"re-run\" if the referenced config properties are changed\r\n _addUnloadHook(_configHandler[_DYN_WATCH /* @min:%2ewatch */](function (details) {\r\n _instrumentationKey = details.cfg.instrumentationKey;\r\n // Mark the extensionConfig and all first level keys as referenced\r\n // This is so that calls to getExtCfg() will always return the same object\r\n // Even when a user may \"re-assign\" the plugin properties (or it's unloaded/reloaded)\r\n var extCfg = details.ref(details.cfg, STR_EXTENSION_CONFIG);\r\n objForEachKey(extCfg, function (key) {\r\n details.ref(extCfg, key);\r\n });\r\n if (isNullOrUndefined(_instrumentationKey)) {\r\n throwError(\"Please provide instrumentation key\");\r\n }\r\n }));\r\n _notificationManager = notificationManager;\r\n _initDebugListener();\r\n _initPerfManager();\r\n _self[_DYN_LOGGER /* @min:%2elogger */] = logger;\r\n var cfgExtensions = config[STR_EXTENSIONS /* @min:%2eextensions */];\r\n // Extension validation\r\n _configExtensions = [];\r\n _configExtensions[_DYN_PUSH /* @min:%2epush */].apply(_configExtensions, __spreadArray(__spreadArray([], extensions, false), cfgExtensions, false));\r\n _channelConfig = config[STR_CHANNELS /* @min:%2echannels */];\r\n _initPluginChain(null);\r\n if (!_channels || _channels[_DYN_LENGTH /* @min:%2elength */] === 0) {\r\n throwError(\"No \" + STR_CHANNELS + \" available\");\r\n }\r\n if (_channelConfig && _channelConfig[_DYN_LENGTH /* @min:%2elength */] > 1) {\r\n var teeController = _self[_DYN_GET_PLUGIN /* @min:%2egetPlugin */](\"TeeChannelController\");\r\n if (!teeController || !teeController.plugin) {\r\n _throwInternal(_logger, 1 /* eLoggingSeverity.CRITICAL */, 28 /* _eInternalMessageId.SenderNotInitialized */, \"TeeChannel required\");\r\n }\r\n }\r\n _registerDelayedCfgListener(config, _cfgListeners, _logger);\r\n _cfgListeners = null;\r\n _isInitialized = true;\r\n _self.releaseQueue();\r\n _self[_DYN_POLL_INTERNAL_LOGS /* @min:%2epollInternalLogs */]();\r\n };\r\n _self.getChannels = function () {\r\n var controls = [];\r\n if (_channels) {\r\n arrForEach(_channels, function (channel) {\r\n controls[_DYN_PUSH /* @min:%2epush */](channel);\r\n });\r\n }\r\n return objFreeze(controls);\r\n };\r\n _self.track = function (telemetryItem) {\r\n doPerf(_self[STR_GET_PERF_MGR /* @min:%2egetPerfMgr */](), function () { return \"AppInsightsCore:track\"; }, function () {\r\n if (telemetryItem === null) {\r\n _notifyInvalidEvent(telemetryItem);\r\n // throw error\r\n throwError(\"Invalid telemetry item\");\r\n }\r\n // do basic validation before sending it through the pipeline\r\n if (!telemetryItem[_DYN_NAME /* @min:%2ename */] && isNullOrUndefined(telemetryItem[_DYN_NAME /* @min:%2ename */])) {\r\n _notifyInvalidEvent(telemetryItem);\r\n throwError(\"telemetry name required\");\r\n }\r\n // setup default iKey if not passed in\r\n telemetryItem.iKey = telemetryItem.iKey || _instrumentationKey;\r\n // add default timestamp if not passed in\r\n telemetryItem[_DYN_TIME /* @min:%2etime */] = telemetryItem[_DYN_TIME /* @min:%2etime */] || toISOString(new Date());\r\n // Common Schema 4.0\r\n telemetryItem.ver = telemetryItem.ver || \"4.0\";\r\n if (!_isUnloading && _self[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */]()) {\r\n // Process the telemetry plugin chain\r\n _createTelCtx()[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](telemetryItem);\r\n }\r\n else {\r\n // Queue events until all extensions are initialized\r\n _eventQueue[_DYN_PUSH /* @min:%2epush */](telemetryItem);\r\n }\r\n }, function () { return ({ item: telemetryItem }); }, !(telemetryItem.sync));\r\n };\r\n _self[_DYN_GET_PROCESS_TEL_CONT0 /* @min:%2egetProcessTelContext */] = _createTelCtx;\r\n _self[_DYN_GET_NOTIFY_MGR /* @min:%2egetNotifyMgr */] = function () {\r\n if (!_notificationManager) {\r\n _notificationManager = new NotificationManager(_configHandler.cfg);\r\n // For backward compatibility only\r\n _self[strNotificationManager] = _notificationManager;\r\n }\r\n return _notificationManager;\r\n };\r\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 */\r\n _self[_DYN_ADD_NOTIFICATION_LIS1 /* @min:%2eaddNotificationListener */] = function (listener) {\r\n _self[_DYN_GET_NOTIFY_MGR /* @min:%2egetNotifyMgr */]()[_DYN_ADD_NOTIFICATION_LIS1 /* @min:%2eaddNotificationListener */](listener);\r\n };\r\n /**\r\n * Removes all instances of the listener.\r\n * @param listener - INotificationListener to remove.\r\n */\r\n _self[_DYN_REMOVE_NOTIFICATION_2 /* @min:%2eremoveNotificationListener */] = function (listener) {\r\n if (_notificationManager) {\r\n _notificationManager[_DYN_REMOVE_NOTIFICATION_2 /* @min:%2eremoveNotificationListener */](listener);\r\n }\r\n };\r\n _self.getCookieMgr = function () {\r\n if (!_cookieManager) {\r\n _cookieManager = createCookieMgr(_configHandler.cfg, _self[_DYN_LOGGER /* @min:%2elogger */]);\r\n }\r\n return _cookieManager;\r\n };\r\n _self.setCookieMgr = function (cookieMgr) {\r\n if (_cookieManager !== cookieMgr) {\r\n runTargetUnload(_cookieManager, false);\r\n _cookieManager = cookieMgr;\r\n }\r\n };\r\n _self[STR_GET_PERF_MGR /* @min:%2egetPerfMgr */] = function () {\r\n if (!_perfManager && !_cfgPerfManager) {\r\n _addUnloadHook(_configHandler[_DYN_WATCH /* @min:%2ewatch */](function (details) {\r\n if (details.cfg.enablePerfMgr) {\r\n var createPerfMgr = details.cfg[STR_CREATE_PERF_MGR /* @min:%2ecreatePerfMgr */];\r\n if (isFunction(createPerfMgr)) {\r\n _cfgPerfManager = createPerfMgr(_self, _self[_DYN_GET_NOTIFY_MGR /* @min:%2egetNotifyMgr */]());\r\n }\r\n }\r\n }));\r\n }\r\n return _perfManager || _cfgPerfManager || getGblPerfMgr();\r\n };\r\n _self.setPerfMgr = function (perfMgr) {\r\n _perfManager = perfMgr;\r\n };\r\n _self.eventCnt = function () {\r\n return _eventQueue[_DYN_LENGTH /* @min:%2elength */];\r\n };\r\n _self.releaseQueue = function () {\r\n if (_isInitialized && _eventQueue[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n var eventQueue = _eventQueue;\r\n _eventQueue = [];\r\n arrForEach(eventQueue, function (event) {\r\n _createTelCtx()[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](event);\r\n });\r\n }\r\n };\r\n _self[_DYN_POLL_INTERNAL_LOGS /* @min:%2epollInternalLogs */] = function (eventName) {\r\n _internalLogsEventName = eventName || null;\r\n _forceStopInternalLogPoller = false;\r\n _internalLogPoller && _internalLogPoller[_DYN_CANCEL /* @min:%2ecancel */]();\r\n return _startLogPoller(true);\r\n };\r\n function _startLogPoller(alwaysStart) {\r\n if ((!_internalLogPoller || !_internalLogPoller[_DYN_ENABLED /* @min:%2eenabled */]) && !_forceStopInternalLogPoller) {\r\n var shouldStart = alwaysStart || (_logger && _logger.queue[_DYN_LENGTH /* @min:%2elength */] > 0);\r\n if (shouldStart) {\r\n if (!_internalLogPollerListening) {\r\n _internalLogPollerListening = true;\r\n // listen for any configuration changes so that changes to the\r\n // interval will cause the timer to be re-initialized\r\n _addUnloadHook(_configHandler[_DYN_WATCH /* @min:%2ewatch */](function (details) {\r\n var interval = details.cfg.diagnosticLogInterval;\r\n if (!interval || !(interval > 0)) {\r\n interval = 10000;\r\n }\r\n var isRunning = false;\r\n if (_internalLogPoller) {\r\n // It was already created so remember it's running and cancel\r\n isRunning = _internalLogPoller[_DYN_ENABLED /* @min:%2eenabled */];\r\n _internalLogPoller[_DYN_CANCEL /* @min:%2ecancel */]();\r\n }\r\n // Create / reconfigure\r\n _internalLogPoller = createTimeout(_flushInternalLogs, interval);\r\n _internalLogPoller.unref();\r\n // Restart if previously running\r\n _internalLogPoller[_DYN_ENABLED /* @min:%2eenabled */] = isRunning;\r\n }));\r\n }\r\n _internalLogPoller[_DYN_ENABLED /* @min:%2eenabled */] = true;\r\n }\r\n }\r\n return _internalLogPoller;\r\n }\r\n _self[_DYN_STOP_POLLING_INTERNA3 /* @min:%2estopPollingInternalLogs */] = function () {\r\n _forceStopInternalLogPoller = true;\r\n _internalLogPoller && _internalLogPoller[_DYN_CANCEL /* @min:%2ecancel */]();\r\n _flushInternalLogs();\r\n };\r\n // Add addTelemetryInitializer\r\n proxyFunctions(_self, function () { return _telemetryInitializerPlugin; }, [\"addTelemetryInitializer\"]);\r\n _self[_DYN_UNLOAD /* @min:%2eunload */] = function (isAsync, unloadComplete, cbTimeout) {\r\n var _a;\r\n if (isAsync === void 0) { isAsync = true; }\r\n if (!_isInitialized) {\r\n // The SDK is not initialized\r\n throwError(strSdkNotInitialized);\r\n }\r\n // Check if the SDK still unloading so throw\r\n if (_isUnloading) {\r\n // The SDK is already unloading\r\n throwError(strSdkUnloadingError);\r\n }\r\n var unloadState = (_a = {\r\n reason: 50 /* TelemetryUnloadReason.SdkUnload */\r\n },\r\n _a[_DYN_IS_ASYNC /* @min:isAsync */] = isAsync,\r\n _a.flushComplete = false,\r\n _a);\r\n var result;\r\n if (isAsync && !unloadComplete) {\r\n result = createPromise(function (resolve) {\r\n // Set the callback to the promise resolve callback\r\n unloadComplete = resolve;\r\n });\r\n }\r\n var processUnloadCtx = createProcessTelemetryUnloadContext(_getPluginChain(), _self);\r\n processUnloadCtx[_DYN_ON_COMPLETE /* @min:%2eonComplete */](function () {\r\n _hookContainer.run(_self[_DYN_LOGGER /* @min:%2elogger */]);\r\n // Run any \"unload\" functions for the _cookieManager, _notificationManager and _logger\r\n doUnloadAll([_cookieManager, _notificationManager, _logger], isAsync, function () {\r\n _initDefaults();\r\n unloadComplete && unloadComplete(unloadState);\r\n });\r\n }, _self);\r\n function _doUnload(flushComplete) {\r\n unloadState.flushComplete = flushComplete;\r\n _isUnloading = true;\r\n // Run all of the unload handlers first (before unloading the plugins)\r\n _unloadHandlers.run(processUnloadCtx, unloadState);\r\n // Stop polling the internal logs\r\n _self[_DYN_STOP_POLLING_INTERNA3 /* @min:%2estopPollingInternalLogs */]();\r\n // Start unloading the components, from this point onwards the SDK should be considered to be in an unstable state\r\n processUnloadCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](unloadState);\r\n }\r\n _flushInternalLogs();\r\n if (!_flushChannels(isAsync, _doUnload, 6 /* SendRequestReason.SdkUnload */, cbTimeout)) {\r\n _doUnload(false);\r\n }\r\n return result;\r\n };\r\n _self[_DYN_GET_PLUGIN /* @min:%2egetPlugin */] = _getPlugin;\r\n _self.addPlugin = function (plugin, replaceExisting, isAsync, addCb) {\r\n if (!plugin) {\r\n addCb && addCb(false);\r\n _logOrThrowError(strValidationError);\r\n return;\r\n }\r\n var existingPlugin = _getPlugin(plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */]);\r\n if (existingPlugin && !replaceExisting) {\r\n addCb && addCb(false);\r\n _logOrThrowError(\"Plugin [\" + plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */] + \"] is already loaded!\");\r\n return;\r\n }\r\n var updateState = {\r\n reason: 16 /* TelemetryUpdateReason.PluginAdded */\r\n };\r\n function _addPlugin(removed) {\r\n _configExtensions[_DYN_PUSH /* @min:%2epush */](plugin);\r\n updateState.added = [plugin];\r\n // Re-Initialize the plugin chain\r\n _initPluginChain(updateState);\r\n addCb && addCb(true);\r\n }\r\n if (existingPlugin) {\r\n var removedPlugins_1 = [existingPlugin.plugin];\r\n var unloadState = {\r\n reason: 2 /* TelemetryUnloadReason.PluginReplace */,\r\n isAsync: !!isAsync\r\n };\r\n _removePlugins(removedPlugins_1, unloadState, function (removed) {\r\n if (!removed) {\r\n // Previous plugin was successfully removed or was not installed\r\n addCb && addCb(false);\r\n }\r\n else {\r\n updateState.removed = removedPlugins_1;\r\n updateState.reason |= 32 /* TelemetryUpdateReason.PluginRemoved */;\r\n _addPlugin(true);\r\n }\r\n });\r\n }\r\n else {\r\n _addPlugin(false);\r\n }\r\n };\r\n _self.updateCfg = function (newConfig, mergeExisting) {\r\n if (mergeExisting === void 0) { mergeExisting = true; }\r\n var updateState;\r\n if (_self[_DYN_IS_INITIALIZED /* @min:%2eisInitialized */]()) {\r\n updateState = {\r\n reason: 1 /* TelemetryUpdateReason.ConfigurationChanged */,\r\n cfg: _configHandler.cfg,\r\n oldCfg: deepExtend({}, _configHandler.cfg),\r\n newConfig: deepExtend({}, newConfig),\r\n merge: mergeExisting\r\n };\r\n newConfig = updateState.newConfig;\r\n var cfg = _configHandler.cfg;\r\n // replace the immutable (if initialized) values\r\n // We don't currently allow updating the extensions and channels via the update config\r\n // So overwriting any user provided values to reuse the existing values\r\n newConfig[STR_EXTENSIONS /* @min:%2eextensions */] = cfg[STR_EXTENSIONS /* @min:%2eextensions */];\r\n newConfig[STR_CHANNELS /* @min:%2echannels */] = cfg[STR_CHANNELS /* @min:%2echannels */];\r\n }\r\n // Explicitly blocking any previous config watchers so that they don't get called because\r\n // of this bulk update (Probably not necessary)\r\n _configHandler._block(function (details) {\r\n // Lets assign the new values to the existing config either overwriting or re-assigning\r\n var theConfig = details.cfg;\r\n _deepMergeConfig(details, theConfig, newConfig, mergeExisting);\r\n if (!mergeExisting) {\r\n // Remove (unassign) the values \"missing\" from the newConfig and also not in the default config\r\n objForEachKey(theConfig, function (key) {\r\n if (!objHasOwn(newConfig, key)) {\r\n // Set the value to undefined\r\n details.set(theConfig, key, UNDEFINED_VALUE);\r\n }\r\n });\r\n }\r\n // Apply defaults to the new config\r\n details[_DYN_SET_DF /* @min:%2esetDf */](theConfig, defaultConfig);\r\n }, true);\r\n // Now execute all of the listeners (synchronously) so they update their values immediately\r\n _configHandler[_DYN_NOTIFY /* @min:%2enotify */]();\r\n if (updateState) {\r\n _doUpdate(updateState);\r\n }\r\n };\r\n _self.evtNamespace = function () {\r\n return _evtNamespace;\r\n };\r\n _self.flush = _flushChannels;\r\n _self.getTraceCtx = function (createNew) {\r\n if (!_traceCtx) {\r\n _traceCtx = createDistributedTraceContext();\r\n }\r\n return _traceCtx;\r\n };\r\n _self.setTraceCtx = function (traceCtx) {\r\n _traceCtx = traceCtx || null;\r\n };\r\n _self.addUnloadHook = _addUnloadHook;\r\n // Create the addUnloadCb\r\n proxyFunctionAs(_self, \"addUnloadCb\", function () { return _unloadHandlers; }, \"add\");\r\n _self.onCfgChange = function (handler) {\r\n var unloadHook;\r\n if (!_isInitialized) {\r\n unloadHook = _addDelayedCfgListener(_cfgListeners, handler);\r\n }\r\n else {\r\n unloadHook = onConfigChange(_configHandler.cfg, handler, _self[_DYN_LOGGER /* @min:%2elogger */]);\r\n }\r\n return {\r\n rm: function () {\r\n unloadHook.rm();\r\n }\r\n };\r\n };\r\n _self.getWParam = function () {\r\n return (hasDocument() || !!_configHandler.cfg.enableWParam) ? 0 : -1;\r\n };\r\n function _setPluginVersions() {\r\n var thePlugins = {};\r\n _pluginVersionStringArr = [];\r\n var _addPluginVersions = function (plugins) {\r\n if (plugins) {\r\n arrForEach(plugins, function (plugin) {\r\n if (plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */] && plugin[_DYN_VERSION /* @min:%2eversion */] && !thePlugins[plugin.identifier]) {\r\n var ver = plugin[_DYN_IDENTIFIER /* @min:%2eidentifier */] + \"=\" + plugin[_DYN_VERSION /* @min:%2eversion */];\r\n _pluginVersionStringArr[_DYN_PUSH /* @min:%2epush */](ver);\r\n thePlugins[plugin.identifier] = plugin;\r\n }\r\n });\r\n }\r\n };\r\n _addPluginVersions(_channels);\r\n if (_channelConfig) {\r\n arrForEach(_channelConfig, function (channels) {\r\n _addPluginVersions(channels);\r\n });\r\n }\r\n _addPluginVersions(_configExtensions);\r\n }\r\n function _initDefaults() {\r\n _isInitialized = false;\r\n // Use a default logger so initialization errors are not dropped on the floor with full logging\r\n _configHandler = createDynamicConfig({}, defaultConfig, _self[_DYN_LOGGER /* @min:%2elogger */]);\r\n // Set the logging level to critical so that any critical initialization failures are displayed on the console\r\n _configHandler.cfg[_DYN_LOGGING_LEVEL_CONSOL4 /* @min:%2eloggingLevelConsole */] = 1 /* eLoggingSeverity.CRITICAL */;\r\n // Define _self.config\r\n objDefine(_self, \"config\", {\r\n g: function () { return _configHandler.cfg; },\r\n s: function (newValue) {\r\n _self.updateCfg(newValue, false);\r\n }\r\n });\r\n objDefine(_self, \"pluginVersionStringArr\", {\r\n g: function () {\r\n if (!_pluginVersionStringArr) {\r\n _setPluginVersions();\r\n }\r\n return _pluginVersionStringArr;\r\n }\r\n });\r\n objDefine(_self, \"pluginVersionString\", {\r\n g: function () {\r\n if (!_pluginVersionString) {\r\n if (!_pluginVersionStringArr) {\r\n _setPluginVersions();\r\n }\r\n _pluginVersionString = _pluginVersionStringArr.join(\";\");\r\n }\r\n return _pluginVersionString || STR_EMPTY;\r\n }\r\n });\r\n objDefine(_self, \"logger\", {\r\n g: function () {\r\n if (!_logger) {\r\n _logger = new DiagnosticLogger(_configHandler.cfg);\r\n _configHandler[_DYN_LOGGER /* @min:%2elogger */] = _logger;\r\n }\r\n return _logger;\r\n },\r\n s: function (newLogger) {\r\n _configHandler[_DYN_LOGGER /* @min:%2elogger */] = newLogger;\r\n if (_logger !== newLogger) {\r\n runTargetUnload(_logger, false);\r\n _logger = newLogger;\r\n }\r\n }\r\n });\r\n _self[_DYN_LOGGER /* @min:%2elogger */] = new DiagnosticLogger(_configHandler.cfg);\r\n _extensions = [];\r\n var cfgExtensions = _self.config[STR_EXTENSIONS /* @min:%2eextensions */] || [];\r\n cfgExtensions.splice(0, cfgExtensions[_DYN_LENGTH /* @min:%2elength */]);\r\n arrAppend(cfgExtensions, _extensions);\r\n _telemetryInitializerPlugin = new TelemetryInitializerPlugin();\r\n _eventQueue = [];\r\n runTargetUnload(_notificationManager, false);\r\n _notificationManager = null;\r\n _perfManager = null;\r\n _cfgPerfManager = null;\r\n runTargetUnload(_cookieManager, false);\r\n _cookieManager = null;\r\n _pluginChain = null;\r\n _configExtensions = [];\r\n _channelConfig = null;\r\n _channels = null;\r\n _isUnloading = false;\r\n _internalLogsEventName = null;\r\n _evtNamespace = createUniqueNamespace(\"AIBaseCore\", true);\r\n _unloadHandlers = createUnloadHandlerContainer();\r\n _traceCtx = null;\r\n _instrumentationKey = null;\r\n _hookContainer = createUnloadHookContainer();\r\n _cfgListeners = [];\r\n _pluginVersionString = null;\r\n _pluginVersionStringArr = null;\r\n _forceStopInternalLogPoller = false;\r\n }\r\n function _createTelCtx() {\r\n var theCtx = createProcessTelemetryContext(_getPluginChain(), _configHandler.cfg, _self);\r\n theCtx[_DYN_ON_COMPLETE /* @min:%2eonComplete */](_startLogPoller);\r\n return theCtx;\r\n }\r\n // Initialize or Re-initialize the plugins\r\n function _initPluginChain(updateState) {\r\n // Extension validation\r\n var theExtensions = _validateExtensions(_self[_DYN_LOGGER /* @min:%2elogger */], ChannelControllerPriority, _configExtensions);\r\n _pluginChain = null;\r\n _pluginVersionString = null;\r\n _pluginVersionStringArr = null;\r\n // Get the primary channel queue and include as part of the normal extensions\r\n _channels = (_channelConfig || [])[0] || [];\r\n // Add any channels provided in the extensions and sort them\r\n _channels = sortPlugins(arrAppend(_channels, theExtensions[STR_CHANNELS /* @min:%2echannels */]));\r\n // Create an array of all extensions, including the _channels\r\n var allExtensions = arrAppend(sortPlugins(theExtensions[STR_CORE /* @min:%2ecore */]), _channels);\r\n // Required to allow plugins to call core.getPlugin() during their own initialization\r\n _extensions = objFreeze(allExtensions);\r\n // This has a side effect of adding the extensions passed during initialization\r\n // into the config.extensions, so you can see all of the extensions loaded.\r\n // This will also get updated by the addPlugin() and remove plugin code.\r\n var cfgExtensions = _self.config[STR_EXTENSIONS /* @min:%2eextensions */] || [];\r\n cfgExtensions.splice(0, cfgExtensions[_DYN_LENGTH /* @min:%2elength */]);\r\n arrAppend(cfgExtensions, _extensions);\r\n var rootCtx = _createTelCtx();\r\n // Initializing the channels first\r\n if (_channels && _channels[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n initializePlugins(rootCtx[_DYN_CREATE_NEW /* @min:%2ecreateNew */](_channels), allExtensions);\r\n }\r\n // Now initialize the normal extensions (explicitly not including the _channels as this can cause duplicate initialization)\r\n initializePlugins(rootCtx, allExtensions);\r\n if (updateState) {\r\n _doUpdate(updateState);\r\n }\r\n }\r\n function _getPlugin(pluginIdentifier) {\r\n var theExt = null;\r\n var thePlugin = null;\r\n var channelHosts = [];\r\n arrForEach(_extensions, function (ext) {\r\n if (ext[_DYN_IDENTIFIER /* @min:%2eidentifier */] === pluginIdentifier && ext !== _telemetryInitializerPlugin) {\r\n thePlugin = ext;\r\n return -1;\r\n }\r\n if (ext.getChannel) {\r\n channelHosts[_DYN_PUSH /* @min:%2epush */](ext);\r\n }\r\n });\r\n if (!thePlugin && channelHosts[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n arrForEach(channelHosts, function (host) {\r\n thePlugin = host.getChannel(pluginIdentifier);\r\n if (!thePlugin) {\r\n return -1;\r\n }\r\n });\r\n }\r\n if (thePlugin) {\r\n theExt = {\r\n plugin: thePlugin,\r\n setEnabled: function (enabled) {\r\n _getPluginState(thePlugin)[STR_DISABLED] = !enabled;\r\n },\r\n isEnabled: function () {\r\n var pluginState = _getPluginState(thePlugin);\r\n return !pluginState[_DYN_TEARDOWN /* @min:%2eteardown */] && !pluginState[STR_DISABLED];\r\n },\r\n remove: function (isAsync, removeCb) {\r\n var _a;\r\n if (isAsync === void 0) { isAsync = true; }\r\n var pluginsToRemove = [thePlugin];\r\n var unloadState = (_a = {\r\n reason: 1 /* TelemetryUnloadReason.PluginUnload */\r\n },\r\n _a[_DYN_IS_ASYNC /* @min:isAsync */] = isAsync,\r\n _a);\r\n _removePlugins(pluginsToRemove, unloadState, function (removed) {\r\n if (removed) {\r\n // Re-Initialize the plugin chain\r\n _initPluginChain({\r\n reason: 32 /* TelemetryUpdateReason.PluginRemoved */,\r\n removed: pluginsToRemove\r\n });\r\n }\r\n removeCb && removeCb(removed);\r\n });\r\n }\r\n };\r\n }\r\n return theExt;\r\n }\r\n function _getPluginChain() {\r\n if (!_pluginChain) {\r\n // copy the collection of extensions\r\n var extensions = (_extensions || []).slice();\r\n // During add / remove this may get called again, so don't read if already present\r\n if (arrIndexOf(extensions, _telemetryInitializerPlugin) === -1) {\r\n extensions[_DYN_PUSH /* @min:%2epush */](_telemetryInitializerPlugin);\r\n }\r\n _pluginChain = createTelemetryProxyChain(sortPlugins(extensions), _configHandler.cfg, _self);\r\n }\r\n return _pluginChain;\r\n }\r\n function _removePlugins(thePlugins, unloadState, removeComplete) {\r\n if (thePlugins && thePlugins[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n var unloadChain = createTelemetryProxyChain(thePlugins, _configHandler.cfg, _self);\r\n var unloadCtx = createProcessTelemetryUnloadContext(unloadChain, _self);\r\n unloadCtx[_DYN_ON_COMPLETE /* @min:%2eonComplete */](function () {\r\n var removed = false;\r\n // Remove the listed config extensions\r\n var newConfigExtensions = [];\r\n arrForEach(_configExtensions, function (plugin, idx) {\r\n if (!_isPluginPresent(plugin, thePlugins)) {\r\n newConfigExtensions[_DYN_PUSH /* @min:%2epush */](plugin);\r\n }\r\n else {\r\n removed = true;\r\n }\r\n });\r\n _configExtensions = newConfigExtensions;\r\n _pluginVersionString = null;\r\n _pluginVersionStringArr = null;\r\n // Re-Create the channel config\r\n var newChannelConfig = [];\r\n if (_channelConfig) {\r\n arrForEach(_channelConfig, function (queue, idx) {\r\n var newQueue = [];\r\n arrForEach(queue, function (channel) {\r\n if (!_isPluginPresent(channel, thePlugins)) {\r\n newQueue[_DYN_PUSH /* @min:%2epush */](channel);\r\n }\r\n else {\r\n removed = true;\r\n }\r\n });\r\n newChannelConfig[_DYN_PUSH /* @min:%2epush */](newQueue);\r\n });\r\n _channelConfig = newChannelConfig;\r\n }\r\n removeComplete && removeComplete(removed);\r\n _startLogPoller();\r\n });\r\n unloadCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](unloadState);\r\n }\r\n else {\r\n removeComplete(false);\r\n }\r\n }\r\n function _flushInternalLogs() {\r\n if (_logger && _logger.queue) {\r\n var queue = _logger.queue.slice(0);\r\n _logger.queue[_DYN_LENGTH /* @min:%2elength */] = 0;\r\n arrForEach(queue, function (logMessage) {\r\n var _a;\r\n var item = (_a = {},\r\n _a[_DYN_NAME /* @min:name */] = _internalLogsEventName ? _internalLogsEventName : \"InternalMessageId: \" + logMessage[_DYN_MESSAGE_ID /* @min:%2emessageId */],\r\n _a.iKey = _instrumentationKey,\r\n _a[_DYN_TIME /* @min:time */] = toISOString(new Date()),\r\n _a.baseType = _InternalLogMessage.dataType,\r\n _a.baseData = { message: logMessage[_DYN_MESSAGE /* @min:%2emessage */] },\r\n _a);\r\n _self.track(item);\r\n });\r\n }\r\n }\r\n function _flushChannels(isAsync, callBack, sendReason, cbTimeout) {\r\n // Setting waiting to one so that we don't call the callBack until we finish iterating\r\n var waiting = 1;\r\n var doneIterating = false;\r\n var cbTimer = null;\r\n cbTimeout = cbTimeout || 5000;\r\n function doCallback() {\r\n waiting--;\r\n if (doneIterating && waiting === 0) {\r\n cbTimer && cbTimer[_DYN_CANCEL /* @min:%2ecancel */]();\r\n cbTimer = null;\r\n callBack && callBack(doneIterating);\r\n callBack = null;\r\n }\r\n }\r\n if (_channels && _channels[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n var flushCtx = _createTelCtx()[_DYN_CREATE_NEW /* @min:%2ecreateNew */](_channels);\r\n flushCtx.iterate(function (plugin) {\r\n if (plugin.flush) {\r\n waiting++;\r\n var handled_1 = false;\r\n // Not all channels will call this callback for every scenario\r\n if (!plugin.flush(isAsync, function () {\r\n handled_1 = true;\r\n doCallback();\r\n }, sendReason)) {\r\n if (!handled_1) {\r\n // If any channel doesn't return true and it didn't call the callback, then we should assume that the callback\r\n // will never be called, so use a timeout to allow the channel(s) some time to \"finish\" before triggering any\r\n // followup function (such as unloading)\r\n if (isAsync && cbTimer == null) {\r\n cbTimer = scheduleTimeout(function () {\r\n cbTimer = null;\r\n doCallback();\r\n }, cbTimeout);\r\n }\r\n else {\r\n doCallback();\r\n }\r\n }\r\n }\r\n }\r\n });\r\n }\r\n doneIterating = true;\r\n doCallback();\r\n return true;\r\n }\r\n function _initDebugListener() {\r\n // Lazily ensure that the notification manager is created\r\n !_notificationManager && _self[_DYN_GET_NOTIFY_MGR /* @min:%2egetNotifyMgr */]();\r\n // Will get recalled if any referenced config values are changed\r\n _addUnloadHook(_configHandler[_DYN_WATCH /* @min:%2ewatch */](function (details) {\r\n var disableDbgExt = details.cfg.disableDbgExt;\r\n if (disableDbgExt === true && _debugListener) {\r\n // Remove any previously loaded debug listener\r\n _notificationManager[_DYN_REMOVE_NOTIFICATION_2 /* @min:%2eremoveNotificationListener */](_debugListener);\r\n _debugListener = null;\r\n }\r\n if (_notificationManager && !_debugListener && disableDbgExt !== true) {\r\n _debugListener = getDebugListener(details.cfg);\r\n _notificationManager[_DYN_ADD_NOTIFICATION_LIS1 /* @min:%2eaddNotificationListener */](_debugListener);\r\n }\r\n }));\r\n }\r\n function _initPerfManager() {\r\n // Will get recalled if any referenced config values are changed\r\n _addUnloadHook(_configHandler[_DYN_WATCH /* @min:%2ewatch */](function (details) {\r\n var enablePerfMgr = details.cfg.enablePerfMgr;\r\n if (!enablePerfMgr && _cfgPerfManager) {\r\n // Remove any existing config based performance manager\r\n _cfgPerfManager = null;\r\n }\r\n if (enablePerfMgr) {\r\n // Set the performance manager creation function if not defined\r\n getSetValue(details.cfg, STR_CREATE_PERF_MGR, _createPerfManager);\r\n }\r\n }));\r\n }\r\n function _doUpdate(updateState) {\r\n var updateCtx = createProcessTelemetryUpdateContext(_getPluginChain(), _self);\r\n updateCtx[_DYN_ON_COMPLETE /* @min:%2eonComplete */](_startLogPoller);\r\n if (!_self._updateHook || _self._updateHook(updateCtx, updateState) !== true) {\r\n updateCtx[_DYN_PROCESS_NEXT /* @min:%2eprocessNext */](updateState);\r\n }\r\n }\r\n function _logOrThrowError(message) {\r\n var logger = _self[_DYN_LOGGER /* @min:%2elogger */];\r\n if (logger) {\r\n // there should always be a logger\r\n _throwInternal(logger, 2 /* eLoggingSeverity.WARNING */, 73 /* _eInternalMessageId.PluginException */, message);\r\n _startLogPoller();\r\n }\r\n else {\r\n throwError(message);\r\n }\r\n }\r\n function _notifyInvalidEvent(telemetryItem) {\r\n var manager = _self[_DYN_GET_NOTIFY_MGR /* @min:%2egetNotifyMgr */]();\r\n if (manager) {\r\n manager[STR_EVENTS_DISCARDED /* @min:%2eeventsDiscarded */]([telemetryItem], 2 /* eEventsDiscardedReason.InvalidEvent */);\r\n }\r\n }\r\n function _addUnloadHook(hooks) {\r\n _hookContainer.add(hooks);\r\n }\r\n });\r\n }\r\n AppInsightsCore.prototype.initialize = function (config, extensions, logger, notificationManager) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AppInsightsCore.prototype.getChannels = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n AppInsightsCore.prototype.track = function (telemetryItem) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AppInsightsCore.prototype.getProcessTelContext = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n AppInsightsCore.prototype.getNotifyMgr = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\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 */\r\n AppInsightsCore.prototype.addNotificationListener = function (listener) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Removes all instances of the listener.\r\n * @param listener - INotificationListener to remove.\r\n */\r\n AppInsightsCore.prototype.removeNotificationListener = function (listener) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Get the current cookie manager for this instance\r\n */\r\n AppInsightsCore.prototype.getCookieMgr = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Set the current cookie manager for this instance\r\n * @param cookieMgr - The manager, if set to null/undefined will cause the default to be created\r\n */\r\n AppInsightsCore.prototype.setCookieMgr = function (cookieMgr) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AppInsightsCore.prototype.getPerfMgr = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n AppInsightsCore.prototype.setPerfMgr = function (perfMgr) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AppInsightsCore.prototype.eventCnt = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return 0;\r\n };\r\n /**\r\n * Enable the timer that checks the logger.queue for log messages to be flushed.\r\n * Note: Since 3.0.1 and 2.8.13 this is no longer an interval timer but is a normal\r\n * timer that is only started when this function is called and then subsequently\r\n * only _if_ there are any logger.queue messages to be sent.\r\n */\r\n AppInsightsCore.prototype.pollInternalLogs = function (eventName) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Stop the timer that log messages from logger.queue when available\r\n */\r\n AppInsightsCore.prototype.stopPollingInternalLogs = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Add a telemetry processor to decorate or drop telemetry events.\r\n * @param telemetryInitializer - The Telemetry Initializer function\r\n * @returns - A ITelemetryInitializerHandler to enable the initializer to be removed\r\n */\r\n AppInsightsCore.prototype.addTelemetryInitializer = function (telemetryInitializer) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Unload and Tear down the SDK and any initialized plugins, after calling this the SDK will be considered\r\n * to be un-initialized and non-operational, re-initializing the SDK should only be attempted if the previous\r\n * unload call return `true` stating that all plugins reported that they also unloaded, the recommended\r\n * approach is to create a new instance and initialize that instance.\r\n * This is due to possible unexpected side effects caused by plugins not supporting unload / teardown, unable\r\n * to successfully remove any global references or they may just be completing the unload process asynchronously.\r\n * If you pass isAsync as `true` (also the default) and DO NOT pass a callback function then an [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * will be returned which will resolve once the unload is complete. The actual implementation of the `IPromise`\r\n * will be a native Promise (if supported) or the default as supplied by [ts-async library](https://github.com/nevware21/ts-async)\r\n * @param isAsync - Can the unload be performed asynchronously (default)\r\n * @param unloadComplete - An optional callback that will be called once the unload has completed\r\n * @param cbTimeout - An optional timeout to wait for any flush operations to complete before proceeding with the\r\n * unload. Defaults to 5 seconds.\r\n * @return Nothing or if occurring asynchronously a [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * which will be resolved once the unload is complete, the [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * will only be returned when no callback is provided and isAsync is true\r\n */\r\n AppInsightsCore.prototype.unload = function (isAsync, unloadComplete, cbTimeout) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AppInsightsCore.prototype.getPlugin = function (pluginIdentifier) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Add a new plugin to the installation\r\n * @param plugin - The new plugin to add\r\n * @param replaceExisting - should any existing plugin be replaced, default is false\r\n * @param doAsync - Should the add be performed asynchronously\r\n * @param addCb - [Optional] callback to call after the plugin has been added\r\n */\r\n AppInsightsCore.prototype.addPlugin = function (plugin, replaceExisting, doAsync, addCb) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Update the configuration used and broadcast the changes to all loaded plugins\r\n * @param newConfig - The new configuration is apply\r\n * @param mergeExisting - Should the new configuration merge with the existing or just replace it. Default is to true.\r\n */\r\n AppInsightsCore.prototype.updateCfg = function (newConfig, mergeExisting) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Returns the unique event namespace that should be used\r\n */\r\n AppInsightsCore.prototype.evtNamespace = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Add an unload handler that will be called when the SDK is being unloaded\r\n * @param handler - the handler\r\n */\r\n AppInsightsCore.prototype.addUnloadCb = function (handler) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Flush and send any batched / cached data immediately\r\n * @param async - send data asynchronously when true (defaults to true)\r\n * @param callBack - if specified, notify caller when send is complete, the channel should return true to indicate to the caller that it will be called.\r\n * If the caller doesn't return true the caller should assume that it may never be called.\r\n * @param sendReason - specify the reason that you are calling \"flush\" defaults to ManualFlush (1) if not specified\r\n * @returns - true if the callback will be return after the flush is complete otherwise the caller should assume that any provided callback will never be called\r\n */\r\n AppInsightsCore.prototype.flush = function (isAsync, callBack, sendReason) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Gets the current distributed trace context for this instance if available\r\n * @param createNew - Optional flag to create a new instance if one doesn't currently exist, defaults to true\r\n */\r\n AppInsightsCore.prototype.getTraceCtx = function (createNew) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Sets the current distributed trace context for this instance if available\r\n */\r\n AppInsightsCore.prototype.setTraceCtx = function (newTracectx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Add this hook so that it is automatically removed during unloading\r\n * @param hooks - The single hook or an array of IInstrumentHook objects\r\n */\r\n AppInsightsCore.prototype.addUnloadHook = function (hooks) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Watches and tracks changes for accesses to the current config, and if the accessed config changes the\r\n * handler will be recalled.\r\n * @param handler\r\n * @returns A watcher handler instance that can be used to remove itself when being unloaded\r\n */\r\n AppInsightsCore.prototype.onCfgChange = function (handler) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n AppInsightsCore.prototype.releaseQueue = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Hook for Core extensions to allow them to update their own configuration before updating all of the plugins.\r\n * @param updateCtx - The plugin update context\r\n * @param updateState - The Update State\r\n * @returns boolean - True means the extension class will call updateState otherwise the Core will\r\n */\r\n AppInsightsCore.prototype._updateHook = function (updateCtx, updateState) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return false;\r\n };\r\n return AppInsightsCore;\r\n}());\r\nexport { AppInsightsCore };\r\n//# sourceMappingURL=AppInsightsCore.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n// ###################################################################################################################################################\r\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 ###\r\n// ###################################################################################################################################################\r\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)\r\n// as when using \"short\" named values from here they will be will be minified smaller than the SdkCoreNames[eSdkCoreNames.xxxx] value.\r\nexport var STR_DURATION = \"duration\";\r\nexport var STR_PROPERTIES = \"properties\";\r\n//# sourceMappingURL=InternalConstants.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n// @skip-file-minify\r\n// ##############################################################\r\n// AUTO GENERATED FILE: This file is Auto Generated during build.\r\n// ##############################################################\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\nexport var _DYN_REQUEST_URL = \"requestUrl\"; // Count: 12\r\nexport var _DYN_INST = \"inst\"; // Count: 5\r\nexport var _DYN_LENGTH = \"length\"; // Count: 10\r\nexport var _DYN_TRACE_ID = \"traceID\"; // Count: 9\r\nexport var _DYN_SPAN_ID = \"spanID\"; // Count: 8\r\nexport var _DYN_TRACE_FLAGS = \"traceFlags\"; // Count: 13\r\nexport var _DYN_CONTEXT = \"context\"; // Count: 7\r\nexport var _DYN_ABORTED = \"aborted\"; // Count: 7\r\nexport var _DYN_TRACE_ID0 = \"traceId\"; // Count: 5\r\nexport var _DYN_SPAN_ID1 = \"spanId\"; // Count: 5\r\nexport var _DYN__ADD_HOOK = \"_addHook\"; // Count: 4\r\nexport var _DYN_CORE = \"core\"; // Count: 8\r\nexport var _DYN_INCLUDE_CORRELATION_2 = \"includeCorrelationHeaders\"; // Count: 4\r\nexport var _DYN_GET_ABSOLUTE_URL = \"getAbsoluteUrl\"; // Count: 3\r\nexport var _DYN_HEADERS = \"headers\"; // Count: 6\r\nexport var _DYN_REQUEST_HEADERS = \"requestHeaders\"; // Count: 13\r\nexport var _DYN_SET_REQUEST_HEADER = \"setRequestHeader\"; // Count: 3\r\nexport var _DYN_TRACK_DEPENDENCY_DAT3 = \"trackDependencyDataInternal\"; // Count: 2\r\nexport var _DYN_START_TIME = \"startTime\"; // Count: 6\r\nexport var _DYN_TO_LOWER_CASE = \"toLowerCase\"; // Count: 6\r\nexport var _DYN_ENABLE_REQUEST_HEADE4 = \"enableRequestHeaderTracking\"; // Count: 3\r\nexport var _DYN_ENABLE_AJAX_ERROR_ST5 = \"enableAjaxErrorStatusText\"; // Count: 2\r\nexport var _DYN_ENABLE_AJAX_PERF_TRA6 = \"enableAjaxPerfTracking\"; // Count: 2\r\nexport var _DYN_MAX_AJAX_CALLS_PER_V7 = \"maxAjaxCallsPerView\"; // Count: 2\r\nexport var _DYN_EXCLUDE_REQUEST_FROM8 = \"excludeRequestFromAutoTrackingPatterns\"; // Count: 2\r\nexport var _DYN_ADD_REQUEST_CONTEXT = \"addRequestContext\"; // Count: 2\r\nexport var _DYN_DISABLE_AJAX_TRACKIN9 = \"disableAjaxTracking\"; // Count: 3\r\nexport var _DYN_AJAX_PERF_LOOKUP_DEL10 = \"ajaxPerfLookupDelay\"; // Count: 2\r\nexport var _DYN_DISABLE_FETCH_TRACKI11 = \"disableFetchTracking\"; // Count: 2\r\nexport var _DYN_ENABLE_RESPONSE_HEAD12 = \"enableResponseHeaderTracking\"; // Count: 2\r\nexport var _DYN_STATUS = \"status\"; // Count: 11\r\nexport var _DYN_STATUS_TEXT = \"statusText\"; // Count: 9\r\nexport var _DYN_HEADER_MAP = \"headerMap\"; // Count: 8\r\nexport var _DYN_OPEN_DONE = \"openDone\"; // Count: 3\r\nexport var _DYN_SEND_DONE = \"sendDone\"; // Count: 3\r\nexport var _DYN_REQUEST_SENT_TIME = \"requestSentTime\"; // Count: 9\r\nexport var _DYN_ABORT_DONE = \"abortDone\"; // Count: 3\r\nexport var _DYN_GET_TRACE_ID = \"getTraceId\"; // Count: 3\r\nexport var _DYN_GET_TRACE_FLAGS = \"getTraceFlags\"; // Count: 3\r\nexport var _DYN_METHOD = \"method\"; // Count: 8\r\nexport var _DYN_ERROR_STATUS_TEXT = \"errorStatusText\"; // Count: 3\r\nexport var _DYN_STATE_CHANGE_ATTACHE13 = \"stateChangeAttached\"; // Count: 2\r\nexport var _DYN_RESPONSE_TEXT = \"responseText\"; // Count: 6\r\nexport var _DYN_RESPONSE_FINISHED_TI14 = \"responseFinishedTime\"; // Count: 7\r\nexport var _DYN__CREATE_TRACK_ITEM = \"CreateTrackItem\"; // Count: 3\r\nexport var _DYN_RESPONSE = \"response\"; // Count: 4\r\nexport var _DYN_GET_ALL_RESPONSE_HEA15 = \"getAllResponseHeaders\"; // Count: 2\r\nexport var _DYN_GET_PART_APROPS = \"getPartAProps\"; // Count: 3\r\nexport var _DYN_PERF_MARK = \"perfMark\"; // Count: 4\r\nexport var _DYN_NAME = \"name\"; // Count: 6\r\nexport var _DYN_PERF_TIMING = \"perfTiming\"; // Count: 3\r\nexport var _DYN_EXCEPTION = \"exception\"; // Count: 5\r\nexport var _DYN_AJAX_DIAGNOSTICS_MES16 = \"ajaxDiagnosticsMessage\"; // Count: 3\r\nexport var _DYN_CORRELATION_CONTEXT = \"correlationContext\"; // Count: 3\r\nexport var _DYN_AJAX_TOTAL_DURATION = \"ajaxTotalDuration\"; // Count: 3\r\nexport var _DYN_EVENT_TRACE_CTX = \"eventTraceCtx\"; // Count: 3\r\n//# sourceMappingURL=__DynamicConstants.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { Extensions, dataSanitizeUrl, dateTimeUtilsDuration, msToTimeSpan, urlGetAbsoluteUrl, urlGetCompleteUrl } from \"@microsoft/applicationinsights-common\";\r\nimport { arrForEach, isNullOrUndefined, isNumber, isString, normalizeJsName, objForEachKey, objKeys } from \"@microsoft/applicationinsights-core-js\";\r\nimport { STR_DURATION, STR_PROPERTIES } from \"./InternalConstants\";\r\nimport { _DYN_ABORTED, _DYN_ABORT_DONE, _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_NAME, _DYN_OPEN_DONE, _DYN_PERF_MARK, _DYN_PERF_TIMING, _DYN_REQUEST_HEADERS, _DYN_REQUEST_SENT_TIME, _DYN_REQUEST_URL, _DYN_RESPONSE, _DYN_RESPONSE_FINISHED_TI14, _DYN_SEND_DONE, _DYN_SPAN_ID, _DYN_SPAN_ID1, _DYN_START_TIME, _DYN_STATE_CHANGE_ATTACHE13, _DYN_STATUS, _DYN_STATUS_TEXT, _DYN_TRACE_FLAGS, _DYN_TRACE_ID, _DYN_TRACE_ID0, _DYN__CREATE_TRACK_ITEM } from \"./__DynamicConstants\";\r\n/** @ignore */\r\nfunction _calcPerfDuration(resourceEntry, start, end) {\r\n var result = 0;\r\n var from = resourceEntry[start];\r\n var to = resourceEntry[end];\r\n if (from && to) {\r\n result = dateTimeUtilsDuration(from, to);\r\n }\r\n return result;\r\n}\r\n/** @ignore */\r\nfunction _setPerfDuration(props, name, resourceEntry, start, end) {\r\n var result = 0;\r\n var value = _calcPerfDuration(resourceEntry, start, end);\r\n if (value) {\r\n result = _setPerfValue(props, name, msToTimeSpan(value));\r\n }\r\n return result;\r\n}\r\n/** @ignore */\r\nfunction _setPerfValue(props, name, value) {\r\n var strPerf = \"ajaxPerf\";\r\n var result = 0;\r\n if (props && name && value) {\r\n var perfData = props[strPerf] = (props[strPerf] || {});\r\n perfData[name] = value;\r\n result = 1;\r\n }\r\n return result;\r\n}\r\n/** @ignore */\r\nfunction _populatePerfData(ajaxData, dependency) {\r\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 */\r\n var resourceEntry = ajaxData[_DYN_PERF_TIMING /* @min:%2eperfTiming */];\r\n var props = dependency[STR_PROPERTIES /* @min:%2eproperties */] || {};\r\n var propsSet = 0;\r\n var strName = \"name\";\r\n var strStart = \"Start\";\r\n var strEnd = \"End\";\r\n var strDomainLookup = \"domainLookup\";\r\n var strConnect = \"connect\";\r\n var strRedirect = \"redirect\";\r\n var strRequest = \"request\";\r\n var strResponse = \"response\";\r\n var strStartTime = \"startTime\";\r\n var strDomainLookupStart = strDomainLookup + strStart;\r\n var strDomainLookupEnd = strDomainLookup + strEnd;\r\n var strConnectStart = strConnect + strStart;\r\n var strConnectEnd = strConnect + strEnd;\r\n var strRequestStart = strRequest + strStart;\r\n var strRequestEnd = strRequest + strEnd;\r\n var strResponseStart = strResponse + strStart;\r\n var strResponseEnd = strResponse + strEnd;\r\n var strRedirectStart = strRedirect + strStart;\r\n var strRedirectEnd = strRedirect = strEnd;\r\n var strTransferSize = \"transferSize\";\r\n var strEncodedBodySize = \"encodedBodySize\";\r\n var strDecodedBodySize = \"decodedBodySize\";\r\n var strServerTiming = \"serverTiming\";\r\n if (resourceEntry) {\r\n // redirect\r\n propsSet |= _setPerfDuration(props, strRedirect, resourceEntry, strRedirectStart, strRedirectEnd);\r\n // domainLookup\r\n propsSet |= _setPerfDuration(props, strDomainLookup, resourceEntry, strDomainLookupStart, strDomainLookupEnd);\r\n // connect\r\n propsSet |= _setPerfDuration(props, strConnect, resourceEntry, strConnectStart, strConnectEnd);\r\n // request\r\n propsSet |= _setPerfDuration(props, strRequest, resourceEntry, strRequestStart, strRequestEnd);\r\n // response\r\n propsSet |= _setPerfDuration(props, strResponse, resourceEntry, strResponseStart, strResponseEnd);\r\n // Network connection time\r\n propsSet |= _setPerfDuration(props, \"networkConnect\", resourceEntry, strStartTime, strConnectEnd);\r\n // Sent Request\r\n propsSet |= _setPerfDuration(props, \"sentRequest\", resourceEntry, strRequestStart, strResponseEnd);\r\n // PerfTotal / Duration\r\n var duration = resourceEntry[STR_DURATION /* @min:%2eduration */];\r\n if (!duration) {\r\n duration = _calcPerfDuration(resourceEntry, strStartTime, strResponseEnd) || 0;\r\n }\r\n propsSet |= _setPerfValue(props, STR_DURATION, duration);\r\n propsSet |= _setPerfValue(props, \"perfTotal\", duration);\r\n var serverTiming = resourceEntry[strServerTiming];\r\n if (serverTiming) {\r\n var server_1 = {};\r\n arrForEach(serverTiming, function (value, idx) {\r\n var name = normalizeJsName(value[strName] || \"\" + idx);\r\n var newValue = server_1[name] || {};\r\n objForEachKey(value, function (key, val) {\r\n if (key !== strName && isString(val) || isNumber(val)) {\r\n if (newValue[key]) {\r\n val = newValue[key] + \";\" + val;\r\n }\r\n if (val || !isString(val)) {\r\n // Only set the value if it has a value and it's not an empty string\r\n newValue[key] = val;\r\n }\r\n }\r\n });\r\n server_1[name] = newValue;\r\n });\r\n propsSet |= _setPerfValue(props, strServerTiming, server_1);\r\n }\r\n propsSet |= _setPerfValue(props, strTransferSize, resourceEntry[strTransferSize]);\r\n propsSet |= _setPerfValue(props, strEncodedBodySize, resourceEntry[strEncodedBodySize]);\r\n propsSet |= _setPerfValue(props, strDecodedBodySize, resourceEntry[strDecodedBodySize]);\r\n }\r\n else {\r\n if (ajaxData[_DYN_PERF_MARK /* @min:%2eperfMark */]) {\r\n propsSet |= _setPerfValue(props, \"missing\", ajaxData.perfAttempts);\r\n }\r\n }\r\n if (propsSet) {\r\n dependency[STR_PROPERTIES /* @min:%2eproperties */] = props;\r\n }\r\n}\r\nvar XHRMonitoringState = /** @class */ (function () {\r\n function XHRMonitoringState() {\r\n var self = this;\r\n self[_DYN_OPEN_DONE /* @min:%2eopenDone */] = false;\r\n self.setRequestHeaderDone = false;\r\n self[_DYN_SEND_DONE /* @min:%2esendDone */] = false;\r\n self[_DYN_ABORT_DONE /* @min:%2eabortDone */] = false;\r\n // True, if onreadyStateChangeCallback function attached to xhr, otherwise false\r\n self[_DYN_STATE_CHANGE_ATTACHE13 /* @min:%2estateChangeAttached */] = false;\r\n }\r\n return XHRMonitoringState;\r\n}());\r\nexport { XHRMonitoringState };\r\nvar ajaxRecord = /** @class */ (function () {\r\n function ajaxRecord(traceId, spanId, logger, traceCtx) {\r\n var _a;\r\n var self = this;\r\n var _logger = logger;\r\n var strResponseText = \"responseText\";\r\n // Assigning the initial/default values within the constructor to avoid typescript from creating a bunch of\r\n // this.XXXX = null\r\n self[_DYN_PERF_MARK /* @min:%2eperfMark */] = null;\r\n self.completed = false;\r\n self.requestHeadersSize = null;\r\n self[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */] = null;\r\n self.responseReceivingDuration = null;\r\n self.callbackDuration = null;\r\n self[_DYN_AJAX_TOTAL_DURATION /* @min:%2eajaxTotalDuration */] = null;\r\n self[_DYN_ABORTED /* @min:%2eaborted */] = 0;\r\n self.pageUrl = null;\r\n self[_DYN_REQUEST_URL /* @min:%2erequestUrl */] = null;\r\n self.requestSize = 0;\r\n self[_DYN_METHOD /* @min:%2emethod */] = null;\r\n self[_DYN_STATUS /* @min:%2estatus */] = null;\r\n self[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */] = null;\r\n self.responseStartedTime = null;\r\n self[_DYN_RESPONSE_FINISHED_TI14 /* @min:%2eresponseFinishedTime */] = null;\r\n self.callbackFinishedTime = null;\r\n self.endTime = null;\r\n self.xhrMonitoringState = new XHRMonitoringState();\r\n self.clientFailure = 0;\r\n self[_DYN_TRACE_ID /* @min:%2etraceID */] = traceId;\r\n self[_DYN_SPAN_ID /* @min:%2espanID */] = spanId;\r\n self[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = traceCtx === null || traceCtx === void 0 ? void 0 : traceCtx.getTraceFlags();\r\n if (traceCtx) {\r\n self[_DYN_EVENT_TRACE_CTX /* @min:%2eeventTraceCtx */] = (_a = {},\r\n _a[_DYN_TRACE_ID0 /* @min:traceId */] = traceCtx[_DYN_GET_TRACE_ID /* @min:%2egetTraceId */](),\r\n _a[_DYN_SPAN_ID1 /* @min:spanId */] = traceCtx.getSpanId(),\r\n _a[_DYN_TRACE_FLAGS /* @min:traceFlags */] = traceCtx[_DYN_GET_TRACE_FLAGS /* @min:%2egetTraceFlags */](),\r\n _a);\r\n }\r\n else {\r\n self[_DYN_EVENT_TRACE_CTX /* @min:%2eeventTraceCtx */] = null;\r\n }\r\n dynamicProto(ajaxRecord, self, function (self) {\r\n self.getAbsoluteUrl = function () {\r\n return self[_DYN_REQUEST_URL /* @min:%2erequestUrl */] ? urlGetAbsoluteUrl(self[_DYN_REQUEST_URL /* @min:%2erequestUrl */]) : null;\r\n };\r\n self.getPathName = function () {\r\n return self[_DYN_REQUEST_URL /* @min:%2erequestUrl */] ? dataSanitizeUrl(_logger, urlGetCompleteUrl(self[_DYN_METHOD /* @min:%2emethod */], self[_DYN_REQUEST_URL /* @min:%2erequestUrl */])) : null;\r\n };\r\n self[_DYN__CREATE_TRACK_ITEM /* @min:%2eCreateTrackItem */] = function (ajaxType, enableRequestHeaderTracking, getResponse) {\r\n var _a;\r\n // round to 3 decimal points\r\n self.ajaxTotalDuration = Math.round(dateTimeUtilsDuration(self.requestSentTime, self.responseFinishedTime) * 1000) / 1000;\r\n if (self[_DYN_AJAX_TOTAL_DURATION /* @min:%2eajaxTotalDuration */] < 0) {\r\n return null;\r\n }\r\n var dependency = (_a = {\r\n id: \"|\" + self[_DYN_TRACE_ID /* @min:%2etraceID */] + \".\" + self[_DYN_SPAN_ID /* @min:%2espanID */],\r\n target: self[_DYN_GET_ABSOLUTE_URL /* @min:%2egetAbsoluteUrl */]()\r\n },\r\n _a[_DYN_NAME /* @min:name */] = self.getPathName(),\r\n _a.type = ajaxType,\r\n _a[_DYN_START_TIME /* @min:startTime */] = null,\r\n _a.duration = self[_DYN_AJAX_TOTAL_DURATION /* @min:%2eajaxTotalDuration */],\r\n _a.success = (+(self[_DYN_STATUS /* @min:%2estatus */])) >= 200 && (+(self[_DYN_STATUS /* @min:%2estatus */])) < 400,\r\n _a.responseCode = (+(self[_DYN_STATUS /* @min:%2estatus */])),\r\n _a[STR_PROPERTIES] = { HttpMethod: self[_DYN_METHOD /* @min:%2emethod */] },\r\n _a);\r\n var props = dependency[STR_PROPERTIES];\r\n if (self[_DYN_ABORTED /* @min:%2eaborted */]) {\r\n props[_DYN_ABORTED /* @min:%2eaborted */] = true;\r\n }\r\n if (self[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */]) {\r\n // Set the correct dependency start time\r\n dependency[_DYN_START_TIME /* @min:%2estartTime */] = new Date();\r\n dependency[_DYN_START_TIME /* @min:%2estartTime */].setTime(self[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */]);\r\n }\r\n // Add Ajax perf details if available\r\n _populatePerfData(self, dependency);\r\n if (enableRequestHeaderTracking) {\r\n if (objKeys(self.requestHeaders)[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n props[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */] = self[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */];\r\n }\r\n }\r\n if (getResponse) {\r\n var response = getResponse();\r\n if (response) {\r\n // enrich dependency target with correlation context from the server\r\n var correlationContext = response[_DYN_CORRELATION_CONTEXT /* @min:%2ecorrelationContext */];\r\n if (correlationContext) {\r\n dependency.correlationContext = /* dependency.target + \" | \" + */ correlationContext;\r\n }\r\n if (response[_DYN_HEADER_MAP /* @min:%2eheaderMap */]) {\r\n if (objKeys(response.headerMap)[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n props.responseHeaders = response[_DYN_HEADER_MAP /* @min:%2eheaderMap */];\r\n }\r\n }\r\n if (self[_DYN_ERROR_STATUS_TEXT /* @min:%2eerrorStatusText */]) {\r\n if (self[_DYN_STATUS /* @min:%2estatus */] >= 400) {\r\n var responseType = response.type;\r\n if (responseType === \"\" || responseType === \"text\") {\r\n props.responseText = response.responseText ? response[_DYN_STATUS_TEXT /* @min:%2estatusText */] + \" - \" + response[strResponseText] : response[_DYN_STATUS_TEXT /* @min:%2estatusText */];\r\n }\r\n if (responseType === \"json\") {\r\n props.responseText = response.response ? response[_DYN_STATUS_TEXT /* @min:%2estatusText */] + \" - \" + JSON.stringify(response[_DYN_RESPONSE /* @min:%2eresponse */]) : response[_DYN_STATUS_TEXT /* @min:%2estatusText */];\r\n }\r\n }\r\n else if (self[_DYN_STATUS /* @min:%2estatus */] === 0) {\r\n props.responseText = response[_DYN_STATUS_TEXT /* @min:%2estatusText */] || \"\";\r\n }\r\n }\r\n }\r\n }\r\n return dependency;\r\n };\r\n self[_DYN_GET_PART_APROPS /* @min:%2egetPartAProps */] = function () {\r\n var _a;\r\n var partA = null;\r\n var traceCtx = self[_DYN_EVENT_TRACE_CTX /* @min:%2eeventTraceCtx */];\r\n if (traceCtx && (traceCtx[_DYN_TRACE_ID0 /* @min:%2etraceId */] || traceCtx[_DYN_SPAN_ID1 /* @min:%2espanId */])) {\r\n partA = {};\r\n var traceExt = partA[Extensions.TraceExt] = (_a = {},\r\n _a[_DYN_TRACE_ID /* @min:traceID */] = traceCtx[_DYN_TRACE_ID0 /* @min:%2etraceId */],\r\n _a.parentID = traceCtx[_DYN_SPAN_ID1 /* @min:%2espanId */],\r\n _a);\r\n if (!isNullOrUndefined(traceCtx[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */])) {\r\n traceExt[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = traceCtx[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */];\r\n }\r\n }\r\n return partA;\r\n };\r\n });\r\n }\r\n ajaxRecord.prototype.getAbsoluteUrl = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n ajaxRecord.prototype.getPathName = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n ajaxRecord.prototype.CreateTrackItem = function (ajaxType, enableRequestHeaderTracking, getResponse) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n ajaxRecord.prototype.getPartAProps = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n return ajaxRecord;\r\n}());\r\nexport { ajaxRecord };\r\n//# sourceMappingURL=ajaxRecord.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nvar _a;\r\nimport { __assign, __extends } from \"tslib\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { DisabledPropertyName, PropertiesPluginIdentifier, RemoteDependencyData, RequestHeaders, correlationIdCanIncludeCorrelationHeader, correlationIdGetCorrelationContext, createDistributedTraceContextFromTrace, createTelemetryItem, createTraceParent, dateTimeUtilsNow, formatTraceParent, isInternalApplicationInsightsEndpoint } from \"@microsoft/applicationinsights-common\";\r\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\";\r\nimport { isWebWorker, objFreeze, scheduleTimeout, strIndexOf, strSubstr, strSubstring } from \"@nevware21/ts-utils\";\r\nimport { STR_PROPERTIES } from \"./InternalConstants\";\r\nimport { _DYN_ABORTED, _DYN_ABORT_DONE, _DYN_ADD_REQUEST_CONTEXT, _DYN_AJAX_DIAGNOSTICS_MES16, _DYN_AJAX_PERF_LOOKUP_DEL10, _DYN_CONTEXT, _DYN_CORE, _DYN_CORRELATION_CONTEXT, _DYN_DISABLE_AJAX_TRACKIN9, _DYN_DISABLE_FETCH_TRACKI11, _DYN_ENABLE_AJAX_ERROR_ST5, _DYN_ENABLE_AJAX_PERF_TRA6, _DYN_ENABLE_REQUEST_HEADE4, _DYN_ENABLE_RESPONSE_HEAD12, _DYN_ERROR_STATUS_TEXT, _DYN_EXCEPTION, _DYN_EXCLUDE_REQUEST_FROM8, _DYN_GET_ABSOLUTE_URL, _DYN_GET_ALL_RESPONSE_HEA15, _DYN_GET_PART_APROPS, _DYN_GET_TRACE_FLAGS, _DYN_GET_TRACE_ID, _DYN_HEADERS, _DYN_HEADER_MAP, _DYN_INCLUDE_CORRELATION_2, _DYN_INST, _DYN_LENGTH, _DYN_MAX_AJAX_CALLS_PER_V7, _DYN_METHOD, _DYN_NAME, _DYN_OPEN_DONE, _DYN_PERF_MARK, _DYN_PERF_TIMING, _DYN_REQUEST_HEADERS, _DYN_REQUEST_SENT_TIME, _DYN_REQUEST_URL, _DYN_RESPONSE, _DYN_RESPONSE_FINISHED_TI14, _DYN_RESPONSE_TEXT, _DYN_SEND_DONE, _DYN_SET_REQUEST_HEADER, _DYN_SPAN_ID, _DYN_SPAN_ID1, _DYN_START_TIME, _DYN_STATE_CHANGE_ATTACHE13, _DYN_STATUS, _DYN_STATUS_TEXT, _DYN_TO_LOWER_CASE, _DYN_TRACE_FLAGS, _DYN_TRACE_ID, _DYN_TRACE_ID0, _DYN_TRACK_DEPENDENCY_DAT3, _DYN__ADD_HOOK, _DYN__CREATE_TRACK_ITEM } from \"./__DynamicConstants\";\r\nimport { ajaxRecord } from \"./ajaxRecord\";\r\nvar AJAX_MONITOR_PREFIX = \"ai.ajxmn.\";\r\nvar strDiagLog = \"diagLog\";\r\nvar strAjaxData = \"ajaxData\";\r\nvar STR_FETCH = \"fetch\";\r\nvar ERROR_HEADER = \"Failed to monitor XMLHttpRequest\";\r\nvar ERROR_PREFIX = \", monitoring data for this ajax call \";\r\nvar ERROR_POSTFIX = ERROR_PREFIX + \"may be incorrect.\";\r\nvar ERROR_NOT_SENT = ERROR_PREFIX + \"won't be sent.\";\r\nvar CORRELATION_HEADER_ERROR = \"Failed to get Request-Context correlation header as it may be not included in the response or not accessible.\";\r\nvar CUSTOM_REQUEST_CONTEXT_ERROR = \"Failed to add custom defined request context as configured call back may missing a null check.\";\r\nvar FAILED_TO_CALCULATE_DURATION_ERROR = \"Failed to calculate the duration of the \";\r\n// Using a global value so that to handle same iKey with multiple app insights instances (mostly for testing)\r\nvar _markCount = 0;\r\n/** @Ignore */\r\nfunction _supportsFetch() {\r\n var _global = getGlobal();\r\n if (!_global ||\r\n isNullOrUndefined(_global.Request) ||\r\n isNullOrUndefined(_global.Request[strPrototype]) ||\r\n isNullOrUndefined(_global[STR_FETCH])) {\r\n return null;\r\n }\r\n return _global[STR_FETCH];\r\n}\r\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 */\r\nfunction _supportsAjaxMonitoring(ajaxMonitorInstance) {\r\n var _a;\r\n var result = false;\r\n if (isXhrSupported()) {\r\n var proto = XMLHttpRequest[strPrototype];\r\n result = !isNullOrUndefined(proto) &&\r\n !isNullOrUndefined(proto.open) && // eslint-disable-line security/detect-non-literal-fs-filename -- false positive\r\n !isNullOrUndefined(proto.send) &&\r\n !isNullOrUndefined(proto.abort);\r\n }\r\n var ieVer = getIEVersion();\r\n if (ieVer && ieVer < 9) {\r\n result = false;\r\n }\r\n if (result) {\r\n // Disable if the XmlHttpRequest can't be extended or hooked\r\n try {\r\n var xhr = new XMLHttpRequest();\r\n xhr[strAjaxData] = {};\r\n // Check that we can update the prototype\r\n var theOpen = XMLHttpRequest[strPrototype].open;\r\n XMLHttpRequest[strPrototype].open = theOpen;\r\n }\r\n catch (e) {\r\n // We can't decorate the xhr object so disable monitoring\r\n result = false;\r\n _throwInternalCritical(ajaxMonitorInstance, 15 /* _eInternalMessageId.FailedMonitorAjaxOpen */, \"Failed to enable XMLHttpRequest monitoring, extension is not supported\", (_a = {},\r\n _a[_DYN_EXCEPTION /* @min:exception */] = dumpObj(e),\r\n _a));\r\n }\r\n }\r\n return result;\r\n}\r\n/** @Ignore */\r\nfunction _getFailedAjaxDiagnosticsMessage(xhr) {\r\n var result = \"\";\r\n try {\r\n if (xhr && xhr[strAjaxData] && xhr[strAjaxData][_DYN_REQUEST_URL /* @min:%2erequestUrl */]) {\r\n result += \"(url: '\" + xhr[strAjaxData][_DYN_REQUEST_URL /* @min:%2erequestUrl */] + \"')\";\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n return result;\r\n}\r\n/** @ignore */\r\nfunction _throwInternalCritical(ajaxMonitorInstance, msgId, message, properties, isUserAct) {\r\n _throwInternal(ajaxMonitorInstance[strDiagLog](), 1 /* eLoggingSeverity.CRITICAL */, msgId, message, properties, isUserAct);\r\n}\r\n/** @ignore */\r\nfunction _throwInternalWarning(ajaxMonitorInstance, msgId, message, properties, isUserAct) {\r\n _throwInternal(ajaxMonitorInstance[strDiagLog](), 2 /* eLoggingSeverity.WARNING */, msgId, message, properties, isUserAct);\r\n}\r\n/** @Ignore */\r\nfunction _createErrorCallbackFunc(ajaxMonitorInstance, internalMessage, message) {\r\n // tslint:disable-next-line\r\n return function (args) {\r\n var _a;\r\n _throwInternalCritical(ajaxMonitorInstance, internalMessage, message, (_a = {\r\n ajaxDiagnosticsMessage: _getFailedAjaxDiagnosticsMessage(args[_DYN_INST /* @min:%2einst */])\r\n },\r\n _a[_DYN_EXCEPTION /* @min:exception */] = dumpObj(args.err),\r\n _a));\r\n };\r\n}\r\nfunction _indexOf(value, match) {\r\n if (value && match) {\r\n return strIndexOf(value, match);\r\n }\r\n return -1;\r\n}\r\nfunction _addHandler(container, id, theFunc) {\r\n var theHandler = {\r\n id: id,\r\n fn: theFunc\r\n };\r\n container.push(theHandler);\r\n return {\r\n remove: function () {\r\n arrForEach(container, function (initializer, idx) {\r\n if (initializer.id === theHandler.id) {\r\n container.splice(idx, 1);\r\n return -1;\r\n }\r\n });\r\n }\r\n };\r\n}\r\nfunction _processDependencyContainer(core, container, details, message) {\r\n var result = true;\r\n arrForEach(container, function (theFunc, idx) {\r\n try {\r\n if (theFunc.fn.call(null, details) === false) {\r\n result = false;\r\n }\r\n }\r\n catch (e) {\r\n _throwInternal(core && core.logger, 1 /* eLoggingSeverity.CRITICAL */, 64 /* _eInternalMessageId.TelemetryInitializerFailed */, \"Dependency \" + message + \" [#\" + idx + \"] failed: \" + getExceptionName(e), { exception: dumpObj(e) }, true);\r\n }\r\n });\r\n return result;\r\n}\r\nfunction _processDependencyListeners(listeners, core, ajaxData, xhr, input, init) {\r\n var _a;\r\n var initializersCount = listeners[_DYN_LENGTH /* @min:%2elength */];\r\n if (initializersCount > 0) {\r\n var details = (_a = {},\r\n _a[_DYN_CORE /* @min:core */] = core,\r\n _a.xhr = xhr,\r\n _a.input = input,\r\n _a.init = init,\r\n _a.traceId = ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */],\r\n _a.spanId = ajaxData[_DYN_SPAN_ID /* @min:%2espanID */],\r\n _a.traceFlags = ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */],\r\n _a.context = ajaxData[_DYN_CONTEXT /* @min:%2econtext */] || {},\r\n _a.aborted = !!ajaxData[_DYN_ABORTED /* @min:%2eaborted */],\r\n _a);\r\n _processDependencyContainer(core, listeners, details, \"listener\");\r\n ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */] = details[_DYN_TRACE_ID0 /* @min:%2etraceId */];\r\n ajaxData[_DYN_SPAN_ID /* @min:%2espanID */] = details[_DYN_SPAN_ID1 /* @min:%2espanId */];\r\n ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = details[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */];\r\n ajaxData[_DYN_CONTEXT /* @min:%2econtext */] = details[_DYN_CONTEXT /* @min:%2econtext */];\r\n }\r\n}\r\nvar BLOB_CORE = \"*.blob.core.\";\r\nexport var DfltAjaxCorrelationHeaderExDomains = objFreeze([\r\n BLOB_CORE + \"windows.net\",\r\n BLOB_CORE + \"chinacloudapi.cn\",\r\n BLOB_CORE + \"cloudapi.de\",\r\n BLOB_CORE + \"usgovcloudapi.net\"\r\n]);\r\nvar _internalExcludeEndpoints = [\r\n /https:\\/\\/[^\\/]*(\\.pipe\\.aria|aria\\.pipe|events\\.data|collector\\.azure)\\.[^\\/]+\\/(OneCollector\\/1|Collector\\/3)\\.0/i\r\n];\r\nvar _defaultConfig = objFreeze((_a = {},\r\n _a[_DYN_MAX_AJAX_CALLS_PER_V7 /* @min:maxAjaxCallsPerView */] = 500,\r\n _a[_DYN_DISABLE_AJAX_TRACKIN9 /* @min:disableAjaxTracking */] = false,\r\n _a[_DYN_DISABLE_FETCH_TRACKI11 /* @min:disableFetchTracking */] = false,\r\n _a[_DYN_EXCLUDE_REQUEST_FROM8 /* @min:excludeRequestFromAutoTrackingPatterns */] = undefined,\r\n _a.disableCorrelationHeaders = false,\r\n _a.distributedTracingMode = 1 /* eDistributedTracingModes.AI_AND_W3C */,\r\n _a.correlationHeaderExcludedDomains = DfltAjaxCorrelationHeaderExDomains,\r\n _a.correlationHeaderDomains = undefined,\r\n _a.correlationHeaderExcludePatterns = undefined,\r\n _a.appId = undefined,\r\n _a.enableCorsCorrelation = false,\r\n _a[_DYN_ENABLE_REQUEST_HEADE4 /* @min:enableRequestHeaderTracking */] = false,\r\n _a[_DYN_ENABLE_RESPONSE_HEAD12 /* @min:enableResponseHeaderTracking */] = false,\r\n _a[_DYN_ENABLE_AJAX_ERROR_ST5 /* @min:enableAjaxErrorStatusText */] = false,\r\n _a[_DYN_ENABLE_AJAX_PERF_TRA6 /* @min:enableAjaxPerfTracking */] = false,\r\n _a.maxAjaxPerfLookupAttempts = 3,\r\n _a[_DYN_AJAX_PERF_LOOKUP_DEL10 /* @min:ajaxPerfLookupDelay */] = 25,\r\n _a.ignoreHeaders = [\r\n \"Authorization\",\r\n \"X-API-Key\",\r\n \"WWW-Authenticate\"\r\n ],\r\n _a[_DYN_ADD_REQUEST_CONTEXT /* @min:addRequestContext */] = undefined,\r\n _a.addIntEndpoints = true,\r\n _a));\r\nvar AjaxMonitor = /** @class */ (function (_super) {\r\n __extends(AjaxMonitor, _super);\r\n function AjaxMonitor() {\r\n var _this = _super.call(this) || this;\r\n _this.identifier = AjaxMonitor.identifier;\r\n _this.priority = 120;\r\n var _fetchInitialized; // fetch monitoring initialized\r\n var _xhrInitialized; // XHR monitoring initialized\r\n var _currentWindowHost;\r\n var _extensionConfig;\r\n var _enableRequestHeaderTracking;\r\n var _enableAjaxErrorStatusText;\r\n var _trackAjaxAttempts;\r\n var _context;\r\n var _isUsingW3CHeaders;\r\n var _isUsingAIHeaders;\r\n var _markPrefix;\r\n var _enableAjaxPerfTracking;\r\n var _maxAjaxCallsPerView;\r\n var _enableResponseHeaderTracking;\r\n var _disabledUrls;\r\n var _disableAjaxTracking;\r\n var _disableFetchTracking;\r\n var _excludeRequestFromAutoTrackingPatterns;\r\n var _addRequestContext;\r\n var _evtNamespace;\r\n var _dependencyHandlerId;\r\n var _dependencyListeners;\r\n var _dependencyInitializers;\r\n var _ignoreHeaders;\r\n var _maxAjaxPerfLookupAttempts;\r\n var _ajaxPerfLookupDelay;\r\n var _distributedTracingMode;\r\n var _appId;\r\n var _polyfillInitialized;\r\n dynamicProto(AjaxMonitor, _this, function (_self, _base) {\r\n var _addHook = _base[_DYN__ADD_HOOK /* @min:%2e_addHook */];\r\n _initDefaults();\r\n _self.initialize = function (config, core, extensions, pluginChain) {\r\n if (!_self.isInitialized()) {\r\n _base.initialize(config, core, extensions, pluginChain);\r\n _evtNamespace = mergeEvtNamespace(createUniqueNamespace(\"ajax\"), core && core.evtNamespace && core.evtNamespace());\r\n _populateDefaults(config);\r\n _instrumentXhr();\r\n _instrumentFetch();\r\n _populateContext();\r\n }\r\n };\r\n _self._doTeardown = function () {\r\n _initDefaults();\r\n };\r\n _self.trackDependencyData = function (dependency, properties) {\r\n _reportDependencyInternal(_dependencyInitializers, _self[_DYN_CORE /* @min:%2ecore */], null, dependency, properties);\r\n };\r\n _self[_DYN_INCLUDE_CORRELATION_2 /* @min:%2eincludeCorrelationHeaders */] = function (ajaxData, input, init, xhr) {\r\n // Test Hook to allow the overriding of the location host\r\n var currentWindowHost = _self[\"_currentWindowHost\"] || _currentWindowHost;\r\n _processDependencyListeners(_dependencyListeners, _self[_DYN_CORE /* @min:%2ecore */], ajaxData, xhr, input, init);\r\n if (input) { // Fetch\r\n if (correlationIdCanIncludeCorrelationHeader(_extensionConfig, ajaxData[_DYN_GET_ABSOLUTE_URL /* @min:%2egetAbsoluteUrl */](), currentWindowHost)) {\r\n if (!init) {\r\n init = {};\r\n }\r\n // init headers override original request headers\r\n // so, if they exist use only them, otherwise use request's because they should have been applied in the first place\r\n // not using original request headers will result in them being lost\r\n var headers = new Headers(init[_DYN_HEADERS /* @min:%2eheaders */] || (input instanceof Request ? (input[_DYN_HEADERS /* @min:%2eheaders */] || {}) : {}));\r\n if (_isUsingAIHeaders) {\r\n var id = \"|\" + ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */] + \".\" + ajaxData[_DYN_SPAN_ID /* @min:%2espanID */];\r\n headers.set(RequestHeaders[3 /* eRequestHeaders.requestIdHeader */], id);\r\n if (_enableRequestHeaderTracking) {\r\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[3 /* eRequestHeaders.requestIdHeader */]] = id;\r\n }\r\n }\r\n var appId = _appId || (_context && _context.appId());\r\n if (appId) {\r\n headers.set(RequestHeaders[0 /* eRequestHeaders.requestContextHeader */], RequestHeaders[2 /* eRequestHeaders.requestContextAppIdFormat */] + appId);\r\n if (_enableRequestHeaderTracking) {\r\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[0 /* eRequestHeaders.requestContextHeader */]] = RequestHeaders[2 /* eRequestHeaders.requestContextAppIdFormat */] + appId;\r\n }\r\n }\r\n if (_isUsingW3CHeaders) {\r\n var traceFlags = ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */];\r\n if (isNullOrUndefined(traceFlags)) {\r\n traceFlags = 0x01;\r\n }\r\n var traceParent = formatTraceParent(createTraceParent(ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */], ajaxData[_DYN_SPAN_ID /* @min:%2espanID */], traceFlags));\r\n headers.set(RequestHeaders[4 /* eRequestHeaders.traceParentHeader */], traceParent);\r\n if (_enableRequestHeaderTracking) {\r\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[4 /* eRequestHeaders.traceParentHeader */]] = traceParent;\r\n }\r\n }\r\n init[_DYN_HEADERS /* @min:%2eheaders */] = headers;\r\n }\r\n return init;\r\n }\r\n else if (xhr) { // XHR\r\n if (correlationIdCanIncludeCorrelationHeader(_extensionConfig, ajaxData[_DYN_GET_ABSOLUTE_URL /* @min:%2egetAbsoluteUrl */](), currentWindowHost)) {\r\n if (_isUsingAIHeaders) {\r\n var id = \"|\" + ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */] + \".\" + ajaxData[_DYN_SPAN_ID /* @min:%2espanID */];\r\n xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](RequestHeaders[3 /* eRequestHeaders.requestIdHeader */], id);\r\n if (_enableRequestHeaderTracking) {\r\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[3 /* eRequestHeaders.requestIdHeader */]] = id;\r\n }\r\n }\r\n var appId = _appId || (_context && _context.appId());\r\n if (appId) {\r\n xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](RequestHeaders[0 /* eRequestHeaders.requestContextHeader */], RequestHeaders[2 /* eRequestHeaders.requestContextAppIdFormat */] + appId);\r\n if (_enableRequestHeaderTracking) {\r\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[0 /* eRequestHeaders.requestContextHeader */]] = RequestHeaders[2 /* eRequestHeaders.requestContextAppIdFormat */] + appId;\r\n }\r\n }\r\n if (_isUsingW3CHeaders) {\r\n var traceFlags = ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */];\r\n if (isNullOrUndefined(traceFlags)) {\r\n traceFlags = 0x01;\r\n }\r\n var traceParent = formatTraceParent(createTraceParent(ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */], ajaxData[_DYN_SPAN_ID /* @min:%2espanID */], traceFlags));\r\n xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](RequestHeaders[4 /* eRequestHeaders.traceParentHeader */], traceParent);\r\n if (_enableRequestHeaderTracking) {\r\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[4 /* eRequestHeaders.traceParentHeader */]] = traceParent;\r\n }\r\n }\r\n }\r\n return xhr;\r\n }\r\n return undefined;\r\n };\r\n _self[_DYN_TRACK_DEPENDENCY_DAT3 /* @min:%2etrackDependencyDataInternal */] = function (dependency, properties, systemProperties) {\r\n if (_maxAjaxCallsPerView === -1 || _trackAjaxAttempts < _maxAjaxCallsPerView) {\r\n // Hack since expected format in w3c mode is |abc.def.\r\n // Non-w3c format is |abc.def\r\n // @todo Remove if better solution is available, e.g. handle in portal\r\n if ((_distributedTracingMode === 2 /* eDistributedTracingModes.W3C */\r\n || _distributedTracingMode === 1 /* eDistributedTracingModes.AI_AND_W3C */)\r\n && typeof dependency.id === \"string\" && dependency.id[dependency.id[_DYN_LENGTH /* @min:%2elength */] - 1] !== \".\") {\r\n dependency.id += \".\";\r\n }\r\n if (isNullOrUndefined(dependency[_DYN_START_TIME /* @min:%2estartTime */])) {\r\n dependency[_DYN_START_TIME /* @min:%2estartTime */] = new Date();\r\n }\r\n var item = createTelemetryItem(dependency, RemoteDependencyData.dataType, RemoteDependencyData.envelopeType, _self[strDiagLog](), properties, systemProperties);\r\n _self[_DYN_CORE /* @min:%2ecore */].track(item);\r\n }\r\n else if (_trackAjaxAttempts === _maxAjaxCallsPerView) {\r\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);\r\n }\r\n ++_trackAjaxAttempts;\r\n };\r\n _self.addDependencyListener = function (dependencyListener) {\r\n return _addHandler(_dependencyListeners, _dependencyHandlerId++, dependencyListener);\r\n };\r\n _self.addDependencyInitializer = function (dependencyInitializer) {\r\n return _addHandler(_dependencyInitializers, _dependencyHandlerId++, dependencyInitializer);\r\n };\r\n function _initDefaults() {\r\n var location = getLocation();\r\n _fetchInitialized = false; // fetch monitoring initialized\r\n _xhrInitialized = false; // XHR monitoring initialized\r\n _polyfillInitialized = false; // polyfill monitoring initialized\r\n _currentWindowHost = location && location.host && location.host[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\r\n _extensionConfig = null;\r\n _enableRequestHeaderTracking = false;\r\n _enableAjaxErrorStatusText = false;\r\n _trackAjaxAttempts = 0;\r\n _context = null;\r\n _isUsingW3CHeaders = false;\r\n _isUsingAIHeaders = false;\r\n _markPrefix = null;\r\n _enableAjaxPerfTracking = false;\r\n _maxAjaxCallsPerView = 0;\r\n _enableResponseHeaderTracking = false;\r\n _disabledUrls = {};\r\n _disableAjaxTracking = false;\r\n _disableFetchTracking = false;\r\n _excludeRequestFromAutoTrackingPatterns = null;\r\n _addRequestContext = null;\r\n _evtNamespace = null;\r\n _dependencyHandlerId = 0;\r\n _dependencyListeners = [];\r\n _dependencyInitializers = [];\r\n _ignoreHeaders = null;\r\n _maxAjaxPerfLookupAttempts = 1;\r\n _ajaxPerfLookupDelay = 1;\r\n _distributedTracingMode = 1 /* eDistributedTracingModes.AI_AND_W3C */;\r\n _appId = null;\r\n }\r\n function _populateDefaults(config) {\r\n _self[_DYN__ADD_HOOK /* @min:%2e_addHook */](onConfigChange(config, function (details) {\r\n var config = details.cfg;\r\n var ctx = createProcessTelemetryContext(null, config, _self[_DYN_CORE /* @min:%2ecore */]);\r\n _extensionConfig = ctx.getExtCfg(AjaxMonitor.identifier, _defaultConfig);\r\n _distributedTracingMode = _extensionConfig.distributedTracingMode;\r\n _enableRequestHeaderTracking = _extensionConfig[_DYN_ENABLE_REQUEST_HEADE4 /* @min:%2eenableRequestHeaderTracking */];\r\n _enableAjaxErrorStatusText = _extensionConfig[_DYN_ENABLE_AJAX_ERROR_ST5 /* @min:%2eenableAjaxErrorStatusText */];\r\n _enableAjaxPerfTracking = _extensionConfig[_DYN_ENABLE_AJAX_PERF_TRA6 /* @min:%2eenableAjaxPerfTracking */];\r\n _maxAjaxCallsPerView = _extensionConfig[_DYN_MAX_AJAX_CALLS_PER_V7 /* @min:%2emaxAjaxCallsPerView */];\r\n _excludeRequestFromAutoTrackingPatterns = [].concat(_extensionConfig[_DYN_EXCLUDE_REQUEST_FROM8 /* @min:%2eexcludeRequestFromAutoTrackingPatterns */] || [], _extensionConfig.addIntEndpoints !== false ? _internalExcludeEndpoints : []);\r\n _addRequestContext = _extensionConfig[_DYN_ADD_REQUEST_CONTEXT /* @min:%2eaddRequestContext */];\r\n _isUsingAIHeaders = _distributedTracingMode === 0 /* eDistributedTracingModes.AI */ || _distributedTracingMode === 1 /* eDistributedTracingModes.AI_AND_W3C */;\r\n _isUsingW3CHeaders = _distributedTracingMode === 1 /* eDistributedTracingModes.AI_AND_W3C */ || _distributedTracingMode === 2 /* eDistributedTracingModes.W3C */;\r\n if (_enableAjaxPerfTracking) {\r\n var iKey = config.instrumentationKey || \"unkwn\";\r\n if (iKey[_DYN_LENGTH /* @min:%2elength */] > 5) {\r\n _markPrefix = AJAX_MONITOR_PREFIX + strSubstring(iKey, iKey[_DYN_LENGTH /* @min:%2elength */] - 5) + \".\";\r\n }\r\n else {\r\n _markPrefix = AJAX_MONITOR_PREFIX + iKey + \".\";\r\n }\r\n }\r\n _disableAjaxTracking = !!_extensionConfig[_DYN_DISABLE_AJAX_TRACKIN9 /* @min:%2edisableAjaxTracking */];\r\n _maxAjaxPerfLookupAttempts = _extensionConfig.maxAjaxPerfLookupAttempts;\r\n _ajaxPerfLookupDelay = _extensionConfig[_DYN_AJAX_PERF_LOOKUP_DEL10 /* @min:%2eajaxPerfLookupDelay */];\r\n _ignoreHeaders = _extensionConfig.ignoreHeaders;\r\n _appId = _extensionConfig.appId;\r\n }));\r\n }\r\n function _populateContext() {\r\n var propExt = _self[_DYN_CORE /* @min:%2ecore */].getPlugin(PropertiesPluginIdentifier);\r\n if (propExt) {\r\n _context = propExt.plugin[_DYN_CONTEXT /* @min:%2econtext */]; // we could move IPropertiesPlugin to common as well\r\n }\r\n }\r\n // discard the header if it's defined as ignoreHeaders in ICorrelationConfig\r\n function _canIncludeHeaders(header) {\r\n var rlt = true;\r\n if (header || _ignoreHeaders) {\r\n arrForEach(_ignoreHeaders, (function (key) {\r\n if (key[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]() === header[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]()) {\r\n rlt = false;\r\n return -1;\r\n }\r\n }));\r\n }\r\n return rlt;\r\n }\r\n // Fetch Stuff\r\n function _instrumentFetch() {\r\n var fetch = _supportsFetch();\r\n if (!fetch) {\r\n return;\r\n }\r\n var global = getGlobal();\r\n var isPolyfill = fetch.polyfill;\r\n _self[_DYN__ADD_HOOK /* @min:%2e_addHook */](onConfigChange(_extensionConfig, function () {\r\n _disableFetchTracking = !!_extensionConfig[_DYN_DISABLE_FETCH_TRACKI11 /* @min:%2edisableFetchTracking */];\r\n _enableResponseHeaderTracking = _extensionConfig[_DYN_ENABLE_RESPONSE_HEAD12 /* @min:%2eenableResponseHeaderTracking */];\r\n if (!_disableFetchTracking && !_fetchInitialized) {\r\n _addHook(InstrumentFunc(global, STR_FETCH, {\r\n ns: _evtNamespace,\r\n // Add request hook\r\n req: function (callDetails, input, init) {\r\n var fetchData;\r\n if (!_disableFetchTracking && _fetchInitialized &&\r\n !_isDisabledRequest(null, input, init) &&\r\n // If we have a polyfil and XHR instrumented then let XHR report otherwise we get duplicates\r\n !(isPolyfill && _xhrInitialized)) {\r\n var ctx = callDetails.ctx();\r\n fetchData = _createFetchRecord(input, init);\r\n var newInit = _self[_DYN_INCLUDE_CORRELATION_2 /* @min:%2eincludeCorrelationHeaders */](fetchData, input, init);\r\n if (newInit !== init) {\r\n callDetails.set(1, newInit);\r\n }\r\n ctx.data = fetchData;\r\n }\r\n },\r\n rsp: function (callDetails, input) {\r\n if (!_disableFetchTracking) {\r\n var fetchData_1 = callDetails.ctx().data;\r\n if (fetchData_1) {\r\n // Replace the result with the new promise from this code\r\n callDetails.rslt = callDetails.rslt.then(function (response) {\r\n _reportFetchMetrics(callDetails, (response || {})[_DYN_STATUS /* @min:%2estatus */], input, response, fetchData_1, function () {\r\n var _a;\r\n var ajaxResponse = (_a = {\r\n statusText: (response || {})[_DYN_STATUS_TEXT /* @min:%2estatusText */]\r\n },\r\n _a[_DYN_HEADER_MAP /* @min:headerMap */] = null,\r\n _a[_DYN_CORRELATION_CONTEXT /* @min:correlationContext */] = _getFetchCorrelationContext(response),\r\n _a);\r\n if (_enableResponseHeaderTracking && response) {\r\n var responseHeaderMap_1 = {};\r\n response.headers.forEach(function (value, name) {\r\n if (_canIncludeHeaders(name)) {\r\n responseHeaderMap_1[name] = value;\r\n }\r\n });\r\n ajaxResponse[_DYN_HEADER_MAP /* @min:%2eheaderMap */] = responseHeaderMap_1;\r\n }\r\n return ajaxResponse;\r\n });\r\n return response;\r\n })\r\n .catch(function (reason) {\r\n _reportFetchMetrics(callDetails, 0, input, null, fetchData_1, null, { error: reason.message || dumpObj(reason) });\r\n throw reason;\r\n });\r\n }\r\n }\r\n },\r\n // Create an error callback to report any hook errors\r\n hkErr: _createErrorCallbackFunc(_self, 15 /* _eInternalMessageId.FailedMonitorAjaxOpen */, \"Failed to monitor Window.fetch\" + ERROR_POSTFIX)\r\n }, true, isWebWorker()));\r\n _fetchInitialized = true;\r\n }\r\n else if (isPolyfill && !_polyfillInitialized) {\r\n // If fetch is a polyfill we need to capture the request to ensure that we correctly track\r\n // disabled request URLS (i.e. internal urls) to ensure we don't end up in a constant loop\r\n // of reporting ourselves, for example React Native uses a polyfill for fetch\r\n // Note: Polyfill implementations that don't support the \"polyfill\" tag are not supported\r\n // the workaround is to add a polyfill property to your fetch implementation before initializing\r\n // App Insights\r\n _addHook(InstrumentFunc(global, STR_FETCH, {\r\n ns: _evtNamespace,\r\n req: function (callDetails, input, init) {\r\n // Just call so that we record any disabled URL\r\n _isDisabledRequest(null, input, init);\r\n }\r\n }));\r\n _polyfillInitialized = true;\r\n }\r\n }));\r\n if (isPolyfill) {\r\n // retag the instrumented fetch with the same polyfill settings this is mostly for testing\r\n // But also supports multiple App Insights usages\r\n global[STR_FETCH].polyfill = isPolyfill;\r\n }\r\n }\r\n function _hookProto(target, funcName, callbacks) {\r\n _addHook(InstrumentProto(target, funcName, callbacks));\r\n }\r\n function _instrumentXhr() {\r\n if (!_supportsAjaxMonitoring(_self)) {\r\n return;\r\n }\r\n _self[_DYN__ADD_HOOK /* @min:%2e_addHook */](onConfigChange(_extensionConfig, function () {\r\n _disableAjaxTracking = !!_extensionConfig[_DYN_DISABLE_AJAX_TRACKIN9 /* @min:%2edisableAjaxTracking */];\r\n _enableRequestHeaderTracking = _extensionConfig[_DYN_ENABLE_REQUEST_HEADE4 /* @min:%2eenableRequestHeaderTracking */];\r\n if (!_disableAjaxTracking && !_xhrInitialized) {\r\n // Instrument open\r\n _hookProto(XMLHttpRequest, \"open\", {\r\n ns: _evtNamespace,\r\n req: function (args, method, url, async) {\r\n if (!_disableAjaxTracking) {\r\n var xhr = args[_DYN_INST /* @min:%2einst */];\r\n var ajaxData = xhr[strAjaxData];\r\n if (!_isDisabledRequest(xhr, url) && _isMonitoredXhrInstance(xhr, true)) {\r\n if (!ajaxData || !ajaxData.xhrMonitoringState[_DYN_OPEN_DONE /* @min:%2eopenDone */]) {\r\n // Only create a single ajaxData (even when multiple AI instances are running)\r\n _openHandler(xhr, method, url, async);\r\n }\r\n // always attach to the on ready state change (required for handling multiple instances)\r\n _attachToOnReadyStateChange(xhr);\r\n }\r\n }\r\n },\r\n hkErr: _createErrorCallbackFunc(_self, 15 /* _eInternalMessageId.FailedMonitorAjaxOpen */, ERROR_HEADER + \".open\" + ERROR_POSTFIX)\r\n });\r\n // Instrument send\r\n _hookProto(XMLHttpRequest, \"send\", {\r\n ns: _evtNamespace,\r\n req: function (args, context) {\r\n if (!_disableAjaxTracking) {\r\n var xhr = args[_DYN_INST /* @min:%2einst */];\r\n var ajaxData = xhr[strAjaxData];\r\n if (_isMonitoredXhrInstance(xhr) && !ajaxData.xhrMonitoringState[_DYN_SEND_DONE /* @min:%2esendDone */]) {\r\n _createMarkId(\"xhr\", ajaxData);\r\n ajaxData[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */] = dateTimeUtilsNow();\r\n _self[_DYN_INCLUDE_CORRELATION_2 /* @min:%2eincludeCorrelationHeaders */](ajaxData, undefined, undefined, xhr);\r\n ajaxData.xhrMonitoringState[_DYN_SEND_DONE /* @min:%2esendDone */] = true;\r\n }\r\n }\r\n },\r\n hkErr: _createErrorCallbackFunc(_self, 17 /* _eInternalMessageId.FailedMonitorAjaxSend */, ERROR_HEADER + ERROR_POSTFIX)\r\n });\r\n // Instrument abort\r\n _hookProto(XMLHttpRequest, \"abort\", {\r\n ns: _evtNamespace,\r\n req: function (args) {\r\n if (!_disableAjaxTracking) {\r\n var xhr = args[_DYN_INST /* @min:%2einst */];\r\n var ajaxData = xhr[strAjaxData];\r\n if (_isMonitoredXhrInstance(xhr) && !ajaxData.xhrMonitoringState[_DYN_ABORT_DONE /* @min:%2eabortDone */]) {\r\n ajaxData[_DYN_ABORTED /* @min:%2eaborted */] = 1;\r\n ajaxData.xhrMonitoringState[_DYN_ABORT_DONE /* @min:%2eabortDone */] = true;\r\n }\r\n }\r\n },\r\n hkErr: _createErrorCallbackFunc(_self, 13 /* _eInternalMessageId.FailedMonitorAjaxAbort */, ERROR_HEADER + \".abort\" + ERROR_POSTFIX)\r\n });\r\n // Instrument setRequestHeader\r\n _hookProto(XMLHttpRequest, \"setRequestHeader\", {\r\n ns: _evtNamespace,\r\n req: function (args, header, value) {\r\n if (!_disableAjaxTracking && _enableRequestHeaderTracking) {\r\n var xhr = args[_DYN_INST /* @min:%2einst */];\r\n if (_isMonitoredXhrInstance(xhr) && _canIncludeHeaders(header)) {\r\n xhr[strAjaxData][_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][header] = value;\r\n }\r\n }\r\n },\r\n hkErr: _createErrorCallbackFunc(_self, 71 /* _eInternalMessageId.FailedMonitorAjaxSetRequestHeader */, ERROR_HEADER + \".setRequestHeader\" + ERROR_POSTFIX)\r\n });\r\n _xhrInitialized = true;\r\n }\r\n }));\r\n }\r\n function _isDisabledRequest(xhr, request, init) {\r\n var isDisabled = false;\r\n var theUrl = ((!isString(request) ? (request || {}).url || \"\" : request) || \"\")[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();\r\n // check excludeRequestFromAutoTrackingPatterns before stripping off any query string\r\n arrForEach(_excludeRequestFromAutoTrackingPatterns, function (regex) {\r\n var theRegex = regex;\r\n if (isString(regex)) {\r\n theRegex = new RegExp(regex);\r\n }\r\n if (!isDisabled) {\r\n isDisabled = theRegex.test(theUrl);\r\n }\r\n });\r\n // if request url matches with exclude regex pattern, return true and no need to check for headers\r\n if (isDisabled) {\r\n return isDisabled;\r\n }\r\n var idx = _indexOf(theUrl, \"?\");\r\n var idx2 = _indexOf(theUrl, \"#\");\r\n if (idx === -1 || (idx2 !== -1 && idx2 < idx)) {\r\n idx = idx2;\r\n }\r\n if (idx !== -1) {\r\n // Strip off any Query string\r\n theUrl = theUrl.substring(0, idx);\r\n }\r\n // check that this instance is not not used by ajax call performed inside client side monitoring to send data to collector\r\n if (!isNullOrUndefined(xhr)) {\r\n // Look on the XMLHttpRequest of the URL string value\r\n isDisabled = xhr[DisabledPropertyName] === true || theUrl[DisabledPropertyName] === true;\r\n }\r\n else if (!isNullOrUndefined(request)) { // fetch\r\n // Look for DisabledPropertyName in either Request or RequestInit\r\n isDisabled = (typeof request === \"object\" ? request[DisabledPropertyName] === true : false) ||\r\n (init ? init[DisabledPropertyName] === true : false);\r\n }\r\n // Also add extra check just in case the XHR or fetch objects where not decorated with the DisableProperty due to sealing or freezing\r\n if (!isDisabled && theUrl && isInternalApplicationInsightsEndpoint(theUrl)) {\r\n isDisabled = true;\r\n }\r\n if (isDisabled) {\r\n // Add the disabled url if not present\r\n if (!_disabledUrls[theUrl]) {\r\n _disabledUrls[theUrl] = 1;\r\n }\r\n }\r\n else {\r\n // Check to see if the url is listed as disabled\r\n if (_disabledUrls[theUrl]) {\r\n isDisabled = true;\r\n }\r\n }\r\n return isDisabled;\r\n }\r\n /// Verifies that particalar instance of XMLHttpRequest needs to be monitored\r\n /// Optional parameter. True if ajaxData must be excluded from verification\r\n /// True if instance needs to be monitored, otherwise false\r\n function _isMonitoredXhrInstance(xhr, excludeAjaxDataValidation) {\r\n var ajaxValidation = true;\r\n var initialized = _xhrInitialized;\r\n if (!isNullOrUndefined(xhr)) {\r\n ajaxValidation = excludeAjaxDataValidation === true || !isNullOrUndefined(xhr[strAjaxData]);\r\n }\r\n // checking to see that all interested functions on xhr were instrumented\r\n return initialized\r\n // checking on ajaxData to see that it was not removed in user code\r\n && ajaxValidation;\r\n }\r\n function _getDistributedTraceCtx() {\r\n var distributedTraceCtx = null;\r\n if (_self[_DYN_CORE /* @min:%2ecore */] && _self[_DYN_CORE /* @min:%2ecore */].getTraceCtx) {\r\n distributedTraceCtx = _self[_DYN_CORE /* @min:%2ecore */].getTraceCtx(false);\r\n }\r\n // Fall back\r\n if (!distributedTraceCtx && _context && _context.telemetryTrace) {\r\n distributedTraceCtx = createDistributedTraceContextFromTrace(_context.telemetryTrace);\r\n }\r\n return distributedTraceCtx;\r\n }\r\n function _openHandler(xhr, method, url, async) {\r\n var _a;\r\n var distributedTraceCtx = _getDistributedTraceCtx();\r\n var traceID = (distributedTraceCtx && distributedTraceCtx[_DYN_GET_TRACE_ID /* @min:%2egetTraceId */]()) || generateW3CId();\r\n var spanID = strSubstr(generateW3CId(), 0, 16);\r\n var ajaxData = new ajaxRecord(traceID, spanID, _self[strDiagLog](), (_a = _self.core) === null || _a === void 0 ? void 0 : _a.getTraceCtx());\r\n ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = distributedTraceCtx && distributedTraceCtx[_DYN_GET_TRACE_FLAGS /* @min:%2egetTraceFlags */]();\r\n ajaxData[_DYN_METHOD /* @min:%2emethod */] = method;\r\n ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */] = url;\r\n ajaxData.xhrMonitoringState[_DYN_OPEN_DONE /* @min:%2eopenDone */] = true;\r\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */] = {};\r\n ajaxData.async = async;\r\n ajaxData[_DYN_ERROR_STATUS_TEXT /* @min:%2eerrorStatusText */] = _enableAjaxErrorStatusText;\r\n xhr[strAjaxData] = ajaxData;\r\n }\r\n function _attachToOnReadyStateChange(xhr) {\r\n xhr[strAjaxData].xhrMonitoringState[_DYN_STATE_CHANGE_ATTACHE13 /* @min:%2estateChangeAttached */] = eventOn(xhr, \"readystatechange\", function () {\r\n var _a;\r\n try {\r\n if (xhr && xhr.readyState === 4 && _isMonitoredXhrInstance(xhr)) {\r\n _onAjaxComplete(xhr);\r\n }\r\n }\r\n catch (e) {\r\n var exceptionText = dumpObj(e);\r\n // ignore messages with c00c023f, as this a known IE9 XHR abort issue\r\n if (!exceptionText || _indexOf(exceptionText[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */](), \"c00c023f\") === -1) {\r\n _throwInternalCritical(_self, 16 /* _eInternalMessageId.FailedMonitorAjaxRSC */, ERROR_HEADER + \" 'readystatechange' event handler\" + ERROR_POSTFIX, (_a = {},\r\n _a[_DYN_AJAX_DIAGNOSTICS_MES16 /* @min:ajaxDiagnosticsMessage */] = _getFailedAjaxDiagnosticsMessage(xhr),\r\n _a[_DYN_EXCEPTION /* @min:exception */] = exceptionText,\r\n _a));\r\n }\r\n }\r\n }, _evtNamespace);\r\n }\r\n function _getResponseText(xhr) {\r\n try {\r\n var responseType = xhr.responseType;\r\n if (responseType === \"\" || responseType === \"text\") {\r\n // As per the specification responseText is only valid if the type is an empty string or \"text\"\r\n return xhr[_DYN_RESPONSE_TEXT /* @min:%2eresponseText */];\r\n }\r\n }\r\n catch (e) {\r\n // This shouldn't happen because of the above check -- but just in case, so just ignore\r\n }\r\n return null;\r\n }\r\n function _onAjaxComplete(xhr) {\r\n var ajaxData = xhr[strAjaxData];\r\n ajaxData[_DYN_RESPONSE_FINISHED_TI14 /* @min:%2eresponseFinishedTime */] = dateTimeUtilsNow();\r\n ajaxData[_DYN_STATUS /* @min:%2estatus */] = xhr[_DYN_STATUS /* @min:%2estatus */];\r\n function _reportXhrError(e, failedProps) {\r\n var errorProps = failedProps || {};\r\n errorProps[\"ajaxDiagnosticsMessage\"] = _getFailedAjaxDiagnosticsMessage(xhr);\r\n if (e) {\r\n errorProps[\"exception\"] = dumpObj(e);\r\n }\r\n _throwInternalWarning(_self, 14 /* _eInternalMessageId.FailedMonitorAjaxDur */, FAILED_TO_CALCULATE_DURATION_ERROR + \"ajax call\" + ERROR_NOT_SENT, errorProps);\r\n }\r\n _findPerfResourceEntry(\"xmlhttprequest\", ajaxData, function () {\r\n try {\r\n var dependency = ajaxData[_DYN__CREATE_TRACK_ITEM /* @min:%2eCreateTrackItem */](\"Ajax\", _enableRequestHeaderTracking, function () {\r\n var _a;\r\n var ajaxResponse = (_a = {\r\n statusText: xhr[_DYN_STATUS_TEXT /* @min:%2estatusText */]\r\n },\r\n _a[_DYN_HEADER_MAP /* @min:headerMap */] = null,\r\n _a[_DYN_CORRELATION_CONTEXT /* @min:correlationContext */] = _getAjaxCorrelationContext(xhr),\r\n _a.type = xhr.responseType,\r\n _a[_DYN_RESPONSE_TEXT /* @min:responseText */] = _getResponseText(xhr),\r\n _a.response = xhr[_DYN_RESPONSE /* @min:%2eresponse */],\r\n _a);\r\n if (_enableResponseHeaderTracking) {\r\n var headers = xhr[_DYN_GET_ALL_RESPONSE_HEA15 /* @min:%2egetAllResponseHeaders */]();\r\n if (headers) {\r\n // xhr.getAllResponseHeaders() method returns all the response headers, separated by CRLF, as a string or null\r\n // the regex converts the header string into an array of individual headers\r\n var arr = strTrim(headers).split(/[\\r\\n]+/);\r\n var responseHeaderMap_2 = {};\r\n arrForEach(arr, function (line) {\r\n var parts = line.split(\": \");\r\n var header = parts.shift();\r\n var value = parts.join(\": \");\r\n if (_canIncludeHeaders(header)) {\r\n responseHeaderMap_2[header] = value;\r\n }\r\n });\r\n ajaxResponse[_DYN_HEADER_MAP /* @min:%2eheaderMap */] = responseHeaderMap_2;\r\n }\r\n }\r\n return ajaxResponse;\r\n });\r\n var properties = void 0;\r\n try {\r\n if (!!_addRequestContext) {\r\n properties = _addRequestContext({ status: xhr[_DYN_STATUS /* @min:%2estatus */], xhr: xhr });\r\n }\r\n }\r\n catch (e) {\r\n _throwInternalWarning(_self, 104 /* _eInternalMessageId.FailedAddingCustomDefinedRequestContext */, CUSTOM_REQUEST_CONTEXT_ERROR);\r\n }\r\n if (dependency) {\r\n if (properties !== undefined) {\r\n dependency[STR_PROPERTIES /* @min:%2eproperties */] = __assign(__assign({}, dependency.properties), properties);\r\n }\r\n var sysProperties = ajaxData[_DYN_GET_PART_APROPS /* @min:%2egetPartAProps */]();\r\n _reportDependencyInternal(_dependencyInitializers, _self[_DYN_CORE /* @min:%2ecore */], ajaxData, dependency, null, sysProperties);\r\n }\r\n else {\r\n _reportXhrError(null, {\r\n requestSentTime: ajaxData[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */],\r\n responseFinishedTime: ajaxData[_DYN_RESPONSE_FINISHED_TI14 /* @min:%2eresponseFinishedTime */]\r\n });\r\n }\r\n }\r\n finally {\r\n // cleanup telemetry data\r\n try {\r\n xhr[strAjaxData] = null;\r\n }\r\n catch (e) {\r\n // May throw in environments that prevent extension or freeze xhr\r\n }\r\n }\r\n }, function (e) {\r\n _reportXhrError(e, null);\r\n });\r\n }\r\n function _getAjaxCorrelationContext(xhr) {\r\n var _a;\r\n try {\r\n var responseHeadersString = xhr[_DYN_GET_ALL_RESPONSE_HEA15 /* @min:%2egetAllResponseHeaders */]();\r\n if (responseHeadersString !== null) {\r\n var index = _indexOf(responseHeadersString[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */](), RequestHeaders[8 /* eRequestHeaders.requestContextHeaderLowerCase */]);\r\n if (index !== -1) {\r\n var responseHeader = xhr.getResponseHeader(RequestHeaders[0 /* eRequestHeaders.requestContextHeader */]);\r\n return correlationIdGetCorrelationContext(responseHeader);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n _throwInternalWarning(_self, 18 /* _eInternalMessageId.FailedMonitorAjaxGetCorrelationHeader */, CORRELATION_HEADER_ERROR, (_a = {},\r\n _a[_DYN_AJAX_DIAGNOSTICS_MES16 /* @min:ajaxDiagnosticsMessage */] = _getFailedAjaxDiagnosticsMessage(xhr),\r\n _a[_DYN_EXCEPTION /* @min:exception */] = dumpObj(e),\r\n _a));\r\n }\r\n }\r\n function _createMarkId(type, ajaxData) {\r\n if (ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */] && _markPrefix && _enableAjaxPerfTracking) {\r\n var performance_1 = getPerformance();\r\n if (performance_1 && isFunction(performance_1.mark)) {\r\n _markCount++;\r\n var markId = _markPrefix + type + \"#\" + _markCount;\r\n performance_1.mark(markId);\r\n var entries = performance_1.getEntriesByName(markId);\r\n if (entries && entries[_DYN_LENGTH /* @min:%2elength */] === 1) {\r\n ajaxData[_DYN_PERF_MARK /* @min:%2eperfMark */] = entries[0];\r\n }\r\n }\r\n }\r\n }\r\n function _findPerfResourceEntry(initiatorType, ajaxData, trackCallback, reportError) {\r\n var perfMark = ajaxData[_DYN_PERF_MARK /* @min:%2eperfMark */];\r\n var performance = getPerformance();\r\n var maxAttempts = _maxAjaxPerfLookupAttempts;\r\n var retryDelay = _ajaxPerfLookupDelay;\r\n var requestUrl = ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */];\r\n var attempt = 0;\r\n (function locateResourceTiming() {\r\n try {\r\n if (performance && perfMark) {\r\n attempt++;\r\n var perfTiming = null;\r\n var entries = performance.getEntries();\r\n for (var lp = entries[_DYN_LENGTH /* @min:%2elength */] - 1; lp >= 0; lp--) {\r\n var entry = entries[lp];\r\n if (entry) {\r\n if (entry.entryType === \"resource\") {\r\n if (entry.initiatorType === initiatorType &&\r\n (_indexOf(entry[_DYN_NAME /* @min:%2ename */], requestUrl) !== -1 || _indexOf(requestUrl, entry[_DYN_NAME /* @min:%2ename */]) !== -1)) {\r\n perfTiming = entry;\r\n }\r\n }\r\n else if (entry.entryType === \"mark\" && entry[_DYN_NAME /* @min:%2ename */] === perfMark[_DYN_NAME /* @min:%2ename */]) {\r\n // We hit the start event\r\n ajaxData[_DYN_PERF_TIMING /* @min:%2eperfTiming */] = perfTiming;\r\n break;\r\n }\r\n if (entry[_DYN_START_TIME /* @min:%2estartTime */] < perfMark[_DYN_START_TIME /* @min:%2estartTime */] - 1000) {\r\n // Fallback to try and reduce the time spent looking for the perf entry\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n if (!perfMark || // - we don't have a perfMark or\r\n ajaxData[_DYN_PERF_TIMING /* @min:%2eperfTiming */] || // - we have not found the perf entry or\r\n attempt >= maxAttempts || // - we have tried too many attempts or\r\n ajaxData.async === false) { // - this is a sync request\r\n if (perfMark && isFunction(performance.clearMarks)) {\r\n // Remove the mark so we don't fill up the performance resources too much\r\n performance.clearMarks(perfMark[_DYN_NAME /* @min:%2ename */]);\r\n }\r\n ajaxData.perfAttempts = attempt;\r\n // just continue and report the track event\r\n trackCallback();\r\n }\r\n else {\r\n // We need to wait for the browser to populate the window.performance entry\r\n // This needs to be at least 1ms as waiting <= 1 (on firefox) is not enough time for fetch or xhr,\r\n // this is a scheduling issue for the browser implementation\r\n scheduleTimeout(locateResourceTiming, retryDelay);\r\n }\r\n }\r\n catch (e) {\r\n reportError(e);\r\n }\r\n })();\r\n }\r\n function _createFetchRecord(input, init) {\r\n var _a;\r\n var distributedTraceCtx = _getDistributedTraceCtx();\r\n var traceID = (distributedTraceCtx && distributedTraceCtx[_DYN_GET_TRACE_ID /* @min:%2egetTraceId */]()) || generateW3CId();\r\n var spanID = strSubstr(generateW3CId(), 0, 16);\r\n var ajaxData = new ajaxRecord(traceID, spanID, _self[strDiagLog](), (_a = _self.core) === null || _a === void 0 ? void 0 : _a.getTraceCtx());\r\n ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = distributedTraceCtx && distributedTraceCtx[_DYN_GET_TRACE_FLAGS /* @min:%2egetTraceFlags */]();\r\n ajaxData[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */] = dateTimeUtilsNow();\r\n ajaxData[_DYN_ERROR_STATUS_TEXT /* @min:%2eerrorStatusText */] = _enableAjaxErrorStatusText;\r\n if (input instanceof Request) {\r\n ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */] = input ? input.url : \"\";\r\n }\r\n else {\r\n ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */] = input;\r\n }\r\n var method = \"GET\";\r\n if (init && init[_DYN_METHOD /* @min:%2emethod */]) {\r\n method = init[_DYN_METHOD /* @min:%2emethod */];\r\n }\r\n else if (input && input instanceof Request) {\r\n method = input[_DYN_METHOD /* @min:%2emethod */];\r\n }\r\n ajaxData[_DYN_METHOD /* @min:%2emethod */] = method;\r\n var requestHeaders = {};\r\n if (_enableRequestHeaderTracking) {\r\n var headers = new Headers((init ? init[_DYN_HEADERS /* @min:%2eheaders */] : 0) || (input instanceof Request ? (input[_DYN_HEADERS /* @min:%2eheaders */] || {}) : {}));\r\n headers.forEach(function (value, key) {\r\n if (_canIncludeHeaders(key)) {\r\n requestHeaders[key] = value;\r\n }\r\n });\r\n }\r\n ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */] = requestHeaders;\r\n _createMarkId(STR_FETCH, ajaxData);\r\n return ajaxData;\r\n }\r\n function _getFailedFetchDiagnosticsMessage(input) {\r\n var result = \"\";\r\n try {\r\n if (!isNullOrUndefined(input)) {\r\n if (typeof (input) === \"string\") {\r\n result += \"(url: '\".concat(input, \"')\");\r\n }\r\n else {\r\n result += \"(url: '\".concat(input.url, \"')\");\r\n }\r\n }\r\n }\r\n catch (e) {\r\n _throwInternalCritical(_self, 15 /* _eInternalMessageId.FailedMonitorAjaxOpen */, \"Failed to grab failed fetch diagnostics message\", { exception: dumpObj(e) });\r\n }\r\n return result;\r\n }\r\n function _reportFetchMetrics(callDetails, status, input, response, ajaxData, getResponse, properties) {\r\n if (!ajaxData) {\r\n return;\r\n }\r\n function _reportFetchError(msgId, e, failedProps) {\r\n var errorProps = failedProps || {};\r\n errorProps[\"fetchDiagnosticsMessage\"] = _getFailedFetchDiagnosticsMessage(input);\r\n if (e) {\r\n errorProps[\"exception\"] = dumpObj(e);\r\n }\r\n _throwInternalWarning(_self, msgId, FAILED_TO_CALCULATE_DURATION_ERROR + \"fetch call\" + ERROR_NOT_SENT, errorProps);\r\n }\r\n ajaxData[_DYN_RESPONSE_FINISHED_TI14 /* @min:%2eresponseFinishedTime */] = dateTimeUtilsNow();\r\n ajaxData[_DYN_STATUS /* @min:%2estatus */] = status;\r\n _findPerfResourceEntry(STR_FETCH, ajaxData, function () {\r\n var dependency = ajaxData[_DYN__CREATE_TRACK_ITEM /* @min:%2eCreateTrackItem */](\"Fetch\", _enableRequestHeaderTracking, getResponse);\r\n var properties;\r\n try {\r\n if (!!_addRequestContext) {\r\n properties = _addRequestContext({ status: status, request: input, response: response });\r\n }\r\n }\r\n catch (e) {\r\n _throwInternalWarning(_self, 104 /* _eInternalMessageId.FailedAddingCustomDefinedRequestContext */, CUSTOM_REQUEST_CONTEXT_ERROR);\r\n }\r\n if (dependency) {\r\n if (properties !== undefined) {\r\n dependency[STR_PROPERTIES /* @min:%2eproperties */] = __assign(__assign({}, dependency.properties), properties);\r\n }\r\n var sysProperties = ajaxData[_DYN_GET_PART_APROPS /* @min:%2egetPartAProps */]();\r\n _reportDependencyInternal(_dependencyInitializers, _self[_DYN_CORE /* @min:%2ecore */], ajaxData, dependency, null, sysProperties);\r\n }\r\n else {\r\n _reportFetchError(14 /* _eInternalMessageId.FailedMonitorAjaxDur */, null, {\r\n requestSentTime: ajaxData[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */],\r\n responseFinishedTime: ajaxData[_DYN_RESPONSE_FINISHED_TI14 /* @min:%2eresponseFinishedTime */]\r\n });\r\n }\r\n }, function (e) {\r\n _reportFetchError(18 /* _eInternalMessageId.FailedMonitorAjaxGetCorrelationHeader */, e, null);\r\n });\r\n }\r\n function _getFetchCorrelationContext(response) {\r\n var _a;\r\n if (response && response[_DYN_HEADERS /* @min:%2eheaders */]) {\r\n try {\r\n var responseHeader = response[_DYN_HEADERS /* @min:%2eheaders */].get(RequestHeaders[0 /* eRequestHeaders.requestContextHeader */]);\r\n return correlationIdGetCorrelationContext(responseHeader);\r\n }\r\n catch (e) {\r\n _throwInternalWarning(_self, 18 /* _eInternalMessageId.FailedMonitorAjaxGetCorrelationHeader */, CORRELATION_HEADER_ERROR, (_a = {\r\n fetchDiagnosticsMessage: _getFailedFetchDiagnosticsMessage(response)\r\n },\r\n _a[_DYN_EXCEPTION /* @min:exception */] = dumpObj(e),\r\n _a));\r\n }\r\n }\r\n }\r\n function _reportDependencyInternal(initializers, core, ajaxData, dependency, properties, systemProperties) {\r\n var _a;\r\n var result = true;\r\n var initializersCount = initializers[_DYN_LENGTH /* @min:%2elength */];\r\n if (initializersCount > 0) {\r\n var details = (_a = {\r\n item: dependency\r\n },\r\n _a[STR_PROPERTIES /* @min:properties */] = properties,\r\n _a.sysProperties = systemProperties,\r\n _a.context = ajaxData ? ajaxData[_DYN_CONTEXT /* @min:%2econtext */] : null,\r\n _a.aborted = ajaxData ? !!ajaxData[_DYN_ABORTED /* @min:%2eaborted */] : false,\r\n _a);\r\n result = _processDependencyContainer(core, initializers, details, \"initializer\");\r\n }\r\n if (result) {\r\n _self[_DYN_TRACK_DEPENDENCY_DAT3 /* @min:%2etrackDependencyDataInternal */](dependency, properties, systemProperties);\r\n }\r\n }\r\n });\r\n return _this;\r\n }\r\n AjaxMonitor.prototype.initialize = function (config, core, extensions, pluginChain) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AjaxMonitor.prototype.processTelemetry = function (item, itemCtx) {\r\n this.processNext(item, itemCtx);\r\n };\r\n /**\r\n * Logs dependency call\r\n * @param dependencyData - dependency data object\r\n */\r\n AjaxMonitor.prototype.trackDependencyData = function (dependency, properties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AjaxMonitor.prototype.includeCorrelationHeaders = function (ajaxData, input, init, xhr) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Add an ajax listener which is called just prior to the request being sent and before the correlation headers are added, to allow you\r\n * to access the headers and modify the values used to generate the distributed tracing correlation headers.\r\n * @param dependencyListener - The Telemetry Initializer function\r\n * @returns - A IDependencyListenerHandler to enable the initializer to be removed\r\n */\r\n AjaxMonitor.prototype.addDependencyListener = function (dependencyListener) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\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 */\r\n AjaxMonitor.prototype.addDependencyInitializer = function (dependencyInitializer) {\r\n return null;\r\n };\r\n /**\r\n * Protected function to allow sub classes the chance to add additional properties to the dependency event\r\n * before it's sent. This function calls track, so sub-classes must call this function after they have\r\n * populated their properties.\r\n * @param dependencyData - dependency data object\r\n */\r\n AjaxMonitor.prototype.trackDependencyDataInternal = function (dependency, properties, systemProperties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AjaxMonitor.identifier = \"AjaxDependencyPlugin\";\r\n return AjaxMonitor;\r\n}(BaseTelemetryPlugin));\r\nexport { AjaxMonitor };\r\n//# sourceMappingURL=ajax.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nvar Application = /** @class */ (function () {\r\n function Application() {\r\n }\r\n return Application;\r\n}());\r\nexport { Application };\r\n//# sourceMappingURL=Application.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nvar Device = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of the Device class\r\n */\r\n function Device() {\r\n // don't attempt to fingerprint browsers\r\n this.id = \"browser\";\r\n // Device type is a dimension in our data platform\r\n // Setting it to 'Browser' allows to separate client and server dependencies/exceptions\r\n this.deviceClass = \"Browser\";\r\n }\r\n return Device;\r\n}());\r\nexport { Device };\r\n//# sourceMappingURL=Device.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { onConfigChange } from \"@microsoft/applicationinsights-core-js\";\r\nvar Version = '3.0.2';\r\nvar Internal = /** @class */ (function () {\r\n /**\r\n * Constructs a new instance of the internal telemetry data class.\r\n */\r\n function Internal(config, unloadHookContainer) {\r\n var _this = this;\r\n var unloadHook = onConfigChange((config), function () {\r\n var prefix = config.sdkExtension;\r\n _this.sdkVersion = (prefix ? prefix + \"_\" : \"\") + \"javascript:\" + Version;\r\n });\r\n unloadHookContainer && unloadHookContainer.add(unloadHook);\r\n }\r\n return Internal;\r\n}());\r\nexport { Internal };\r\n//# sourceMappingURL=Internal.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nvar Location = /** @class */ (function () {\r\n function Location() {\r\n }\r\n return Location;\r\n}());\r\nexport { Location };\r\n//# sourceMappingURL=Location.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n// @skip-file-minify\r\n// ##############################################################\r\n// AUTO GENERATED FILE: This file is Auto Generated during build.\r\n// ##############################################################\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\nexport var _DYN_SESSION_MANAGER = \"sessionManager\"; // Count: 3\r\nexport var _DYN_UPDATE = \"update\"; // Count: 4\r\nexport var _DYN_IS_USER_COOKIE_SET = \"isUserCookieSet\"; // Count: 4\r\nexport var _DYN_IS_NEW_USER = \"isNewUser\"; // Count: 4\r\nexport var _DYN_GET_TRACE_CTX = \"getTraceCtx\"; // Count: 3\r\nexport var _DYN_TELEMETRY_TRACE = \"telemetryTrace\"; // Count: 3\r\nexport var _DYN_APPLY_SESSION_CONTEX0 = \"applySessionContext\"; // Count: 2\r\nexport var _DYN_APPLY_APPLICATION_CO1 = \"applyApplicationContext\"; // Count: 2\r\nexport var _DYN_APPLY_DEVICE_CONTEXT = \"applyDeviceContext\"; // Count: 2\r\nexport var _DYN_APPLY_OPERATION_CONT2 = \"applyOperationContext\"; // Count: 2\r\nexport var _DYN_APPLY_USER_CONTEXT = \"applyUserContext\"; // Count: 2\r\nexport var _DYN_APPLY_OPERATING_SYST3 = \"applyOperatingSystemContxt\"; // Count: 2\r\nexport var _DYN_APPLY_LOCATION_CONTE4 = \"applyLocationContext\"; // Count: 2\r\nexport var _DYN_APPLY_INTERNAL_CONTE5 = \"applyInternalContext\"; // Count: 2\r\nexport var _DYN_ACCOUNT_ID = \"accountId\"; // Count: 7\r\nexport var _DYN_GET_SESSION_ID = \"getSessionId\"; // Count: 4\r\nexport var _DYN_NAME_PREFIX = \"namePrefix\"; // Count: 3\r\nexport var _DYN_SESSION_COOKIE_POSTF6 = \"sessionCookiePostfix\"; // Count: 2\r\nexport var _DYN_USER_COOKIE_POSTFIX = \"userCookiePostfix\"; // Count: 2\r\nexport var _DYN_ID_LENGTH = \"idLength\"; // Count: 4\r\nexport var _DYN_GET_NEW_ID = \"getNewId\"; // Count: 3\r\nexport var _DYN_LENGTH = \"length\"; // Count: 4\r\nexport var _DYN_AUTOMATIC_SESSION = \"automaticSession\"; // Count: 5\r\nexport var _DYN_AUTHENTICATED_ID = \"authenticatedId\"; // Count: 6\r\nexport var _DYN_ACQUISITION_DATE = \"acquisitionDate\"; // Count: 5\r\nexport var _DYN_RENEWAL_DATE = \"renewalDate\"; // Count: 4\r\nexport var _DYN_JOIN = \"join\"; // Count: 5\r\nexport var _DYN_COOKIE_SEPARATOR = \"cookieSeparator\"; // Count: 5\r\nexport var _DYN_AUTH_USER_COOKIE_NAM7 = \"authUserCookieName\"; // Count: 3\r\n//# sourceMappingURL=__DynamicConstants.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { utlCanUseLocalStorage, utlGetLocalStorage, utlSetLocalStorage } from \"@microsoft/applicationinsights-common\";\r\nimport { _throwInternal, dateNow, dumpObj, getExceptionName, isFunction, newId, onConfigChange, safeGetCookieMgr, safeGetLogger } from \"@microsoft/applicationinsights-core-js\";\r\nimport { _DYN_ACQUISITION_DATE, _DYN_AUTOMATIC_SESSION, _DYN_GET_NEW_ID, _DYN_ID_LENGTH, _DYN_JOIN, _DYN_LENGTH, _DYN_NAME_PREFIX, _DYN_RENEWAL_DATE, _DYN_UPDATE } from \"../__DynamicConstants\";\r\nvar SESSION_COOKIE_NAME = \"ai_session\";\r\nvar ACQUISITION_SPAN = 86400000; // 24 hours in ms\r\nvar RENEWAL_SPAN = 1800000; // 30 minutes in ms\r\nvar COOKIE_UPDATE_INTERVAL = 60000; // 1 minute in ms\r\nvar Session = /** @class */ (function () {\r\n function Session() {\r\n }\r\n return Session;\r\n}());\r\nexport { Session };\r\nvar _SessionManager = /** @class */ (function () {\r\n function _SessionManager(config, core, unloadHookContainer) {\r\n var self = this;\r\n var _storageNamePrefix;\r\n var _cookieUpdatedTimestamp;\r\n var _logger = safeGetLogger(core);\r\n var _cookieManager = safeGetCookieMgr(core);\r\n var _sessionExpirationMs;\r\n var _sessionRenewalMs;\r\n dynamicProto(_SessionManager, self, function (_self) {\r\n if (!config) {\r\n config = {};\r\n }\r\n var unloadHook = onConfigChange(config, function (details) {\r\n _sessionExpirationMs = config.sessionExpirationMs || ACQUISITION_SPAN;\r\n _sessionRenewalMs = config.sessionRenewalMs || RENEWAL_SPAN;\r\n // sessionCookiePostfix takes the preference if it is configured, otherwise takes namePrefix if configured.\r\n var sessionCookiePostfix = config.sessionCookiePostfix || config[_DYN_NAME_PREFIX /* @min:%2enamePrefix */] || \"\";\r\n _storageNamePrefix = SESSION_COOKIE_NAME + sessionCookiePostfix;\r\n });\r\n unloadHookContainer && unloadHookContainer.add(unloadHook);\r\n _self[_DYN_AUTOMATIC_SESSION /* @min:%2eautomaticSession */] = new Session();\r\n _self[_DYN_UPDATE /* @min:%2eupdate */] = function () {\r\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\r\n // the number to be incorrect.\r\n var nowMs = dateNow();\r\n var isExpired = false;\r\n var session = _self[_DYN_AUTOMATIC_SESSION /* @min:%2eautomaticSession */];\r\n if (!session.id) {\r\n isExpired = !_initializeAutomaticSession(session, nowMs);\r\n }\r\n if (!isExpired && _sessionExpirationMs > 0) {\r\n var timeSinceAcqMs = nowMs - session[_DYN_ACQUISITION_DATE /* @min:%2eacquisitionDate */];\r\n var timeSinceRenewalMs = nowMs - session[_DYN_RENEWAL_DATE /* @min:%2erenewalDate */];\r\n isExpired = timeSinceAcqMs < 0 || timeSinceRenewalMs < 0; // expired if the acquisition or last renewal are in the future\r\n isExpired = isExpired || timeSinceAcqMs > _sessionExpirationMs; // expired if the time since acquisition is more than session Expiration\r\n isExpired = isExpired || timeSinceRenewalMs > _sessionRenewalMs; // expired if the time since last renewal is more than renewal period\r\n }\r\n // renew if acquisitionSpan or renewalSpan has elapsed\r\n if (isExpired) {\r\n // update automaticSession so session state has correct id\r\n _renew(nowMs);\r\n }\r\n else {\r\n // do not update the cookie more often than cookieUpdateInterval\r\n if (!_cookieUpdatedTimestamp || nowMs - _cookieUpdatedTimestamp > COOKIE_UPDATE_INTERVAL) {\r\n _setCookie(session, nowMs);\r\n }\r\n }\r\n };\r\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 */\r\n _self.backup = function () {\r\n var session = _self[_DYN_AUTOMATIC_SESSION /* @min:%2eautomaticSession */];\r\n _setStorage(session.id, session[_DYN_ACQUISITION_DATE /* @min:%2eacquisitionDate */], session[_DYN_RENEWAL_DATE /* @min:%2erenewalDate */]);\r\n };\r\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 */\r\n function _initializeAutomaticSession(session, now) {\r\n var isValid = false;\r\n var cookieValue = _cookieManager.get(_storageNamePrefix);\r\n if (cookieValue && isFunction(cookieValue.split)) {\r\n isValid = _initializeAutomaticSessionWithData(session, cookieValue);\r\n }\r\n else {\r\n // There's no cookie, but we might have session data in local storage\r\n // This can happen if the session expired or the user actively deleted the cookie\r\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.\r\n // The User class handles this for us and deletes our local storage object if the persistent user cookie was removed.\r\n var storageValue = utlGetLocalStorage(_logger, _storageNamePrefix);\r\n if (storageValue) {\r\n isValid = _initializeAutomaticSessionWithData(session, storageValue);\r\n }\r\n }\r\n return isValid || !!session.id;\r\n }\r\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 */\r\n function _initializeAutomaticSessionWithData(session, sessionData) {\r\n var isValid = false;\r\n var sessionReset = \", session will be reset\";\r\n var tokens = sessionData.split(\"|\");\r\n if (tokens[_DYN_LENGTH /* @min:%2elength */] >= 2) {\r\n try {\r\n var acqMs = +tokens[1] || 0;\r\n var renewalMs = +tokens[2] || 0;\r\n if (isNaN(acqMs) || acqMs <= 0) {\r\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 27 /* _eInternalMessageId.SessionRenewalDateIsZero */, \"AI session acquisition date is 0\" + sessionReset);\r\n }\r\n else if (isNaN(renewalMs) || renewalMs <= 0) {\r\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 27 /* _eInternalMessageId.SessionRenewalDateIsZero */, \"AI session renewal date is 0\" + sessionReset);\r\n }\r\n else if (tokens[0]) {\r\n // Everything looks valid so set the values\r\n session.id = tokens[0];\r\n session[_DYN_ACQUISITION_DATE /* @min:%2eacquisitionDate */] = acqMs;\r\n session[_DYN_RENEWAL_DATE /* @min:%2erenewalDate */] = renewalMs;\r\n isValid = true;\r\n }\r\n }\r\n catch (e) {\r\n _throwInternal(_logger, 1 /* eLoggingSeverity.CRITICAL */, 9 /* _eInternalMessageId.ErrorParsingAISessionCookie */, \"Error parsing ai_session value [\" + (sessionData || \"\") + \"]\" + sessionReset + \" - \" + getExceptionName(e), { exception: dumpObj(e) });\r\n }\r\n }\r\n return isValid;\r\n }\r\n function _renew(nowMs) {\r\n var getNewId = config[_DYN_GET_NEW_ID /* @min:%2egetNewId */] || newId;\r\n _self.automaticSession.id = getNewId(config[_DYN_ID_LENGTH /* @min:%2eidLength */] || 22);\r\n _self[_DYN_AUTOMATIC_SESSION /* @min:%2eautomaticSession */][_DYN_ACQUISITION_DATE /* @min:%2eacquisitionDate */] = nowMs;\r\n _setCookie(_self[_DYN_AUTOMATIC_SESSION /* @min:%2eautomaticSession */], nowMs);\r\n // If this browser does not support local storage, fire an internal log to keep track of it at this point\r\n if (!utlCanUseLocalStorage()) {\r\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 0 /* _eInternalMessageId.BrowserDoesNotSupportLocalStorage */, \"Browser does not support local storage. Session durations will be inaccurate.\");\r\n }\r\n }\r\n function _setCookie(session, nowMs) {\r\n var acq = session[_DYN_ACQUISITION_DATE /* @min:%2eacquisitionDate */];\r\n session[_DYN_RENEWAL_DATE /* @min:%2erenewalDate */] = nowMs;\r\n var renewalPeriodMs = _sessionRenewalMs;\r\n // Set cookie to expire after the session expiry time passes or the session renewal deadline, whichever is sooner\r\n // Expiring the cookie will cause the session to expire even if the user isn't on the page\r\n var acqTimeLeftMs = (acq + _sessionExpirationMs) - nowMs;\r\n var cookie = [session.id, acq, nowMs];\r\n var maxAgeSec = 0;\r\n if (acqTimeLeftMs < renewalPeriodMs) {\r\n maxAgeSec = acqTimeLeftMs / 1000;\r\n }\r\n else {\r\n maxAgeSec = renewalPeriodMs / 1000;\r\n }\r\n var cookieDomain = config.cookieDomain || null;\r\n // if sessionExpirationMs is set to 0, it means the expiry is set to 0 for this session cookie\r\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.\r\n // Depending on the browser, another instance does not inherit this cookie, however, another tab will\r\n _cookieManager.set(_storageNamePrefix, cookie[_DYN_JOIN /* @min:%2ejoin */](\"|\"), _sessionExpirationMs > 0 ? maxAgeSec : null, cookieDomain);\r\n _cookieUpdatedTimestamp = nowMs;\r\n }\r\n function _setStorage(guid, acq, renewal) {\r\n // Keep data in local storage to retain the last session id, allowing us to cleanly end the session when it expires\r\n // Browsers that don't support local storage won't be able to end sessions cleanly from the client\r\n // The server will notice this and end the sessions itself, with loss of accurate session duration\r\n utlSetLocalStorage(_logger, _storageNamePrefix, [guid, acq, renewal][_DYN_JOIN /* @min:%2ejoin */](\"|\"));\r\n }\r\n });\r\n }\r\n _SessionManager.prototype.update = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\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 */\r\n _SessionManager.prototype.backup = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n return _SessionManager;\r\n}());\r\nexport { _SessionManager };\r\n//# sourceMappingURL=Session.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { dataSanitizeString } from \"@microsoft/applicationinsights-common\";\r\nimport { generateW3CId, getLocation } from \"@microsoft/applicationinsights-core-js\";\r\nvar TelemetryTrace = /** @class */ (function () {\r\n function TelemetryTrace(id, parentId, name, logger) {\r\n var _self = this;\r\n _self.traceID = id || generateW3CId();\r\n _self.parentID = parentId;\r\n var location = getLocation();\r\n if (!name && location && location.pathname) {\r\n name = location.pathname;\r\n }\r\n _self.name = dataSanitizeString(logger, name);\r\n }\r\n return TelemetryTrace;\r\n}());\r\nexport { TelemetryTrace };\r\n//# sourceMappingURL=TelemetryTrace.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { utlRemoveStorage } from \"@microsoft/applicationinsights-common\";\r\nimport { _throwInternal, newId, onConfigChange, safeGetCookieMgr, safeGetLogger, toISOString } from \"@microsoft/applicationinsights-core-js\";\r\nimport { objDefine } from \"@nevware21/ts-utils\";\r\nimport { _DYN_ACCOUNT_ID, _DYN_AUTHENTICATED_ID, _DYN_AUTH_USER_COOKIE_NAM7, _DYN_COOKIE_SEPARATOR, _DYN_GET_NEW_ID, _DYN_ID_LENGTH, _DYN_IS_NEW_USER, _DYN_IS_USER_COOKIE_SET, _DYN_JOIN, _DYN_LENGTH, _DYN_NAME_PREFIX, _DYN_UPDATE, _DYN_USER_COOKIE_POSTFIX } from \"../__DynamicConstants\";\r\nfunction _validateUserInput(id) {\r\n // Validate:\r\n // 1. Id is a non-empty string.\r\n // 2. It does not contain special characters for cookies.\r\n if (typeof id !== \"string\" ||\r\n !id ||\r\n id.match(/,|;|=| |\\|/)) {\r\n return false;\r\n }\r\n return true;\r\n}\r\nvar User = /** @class */ (function () {\r\n function User(config, core, unloadHookContainer) {\r\n /**\r\n * A flag indicating whether this represents a new user\r\n */\r\n this.isNewUser = false;\r\n /**\r\n * A flag indicating whether the user cookie has been set\r\n */\r\n this.isUserCookieSet = false;\r\n var _logger = safeGetLogger(core);\r\n var _cookieManager = safeGetCookieMgr(core);\r\n var _storageNamePrefix;\r\n dynamicProto(User, this, function (_self) {\r\n // Define _self.config\r\n objDefine(_self, \"config\", {\r\n g: function () { return config; }\r\n });\r\n var unloadHook = onConfigChange(config, function () {\r\n var userCookiePostfix = config[_DYN_USER_COOKIE_POSTFIX /* @min:%2euserCookiePostfix */] || \"\";\r\n _storageNamePrefix = User.userCookieName + userCookiePostfix;\r\n // get userId or create new one if none exists\r\n var cookie = _cookieManager.get(_storageNamePrefix);\r\n if (cookie) {\r\n _self[_DYN_IS_NEW_USER /* @min:%2eisNewUser */] = false;\r\n var params = cookie.split(User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]);\r\n if (params[_DYN_LENGTH /* @min:%2elength */] > 0) {\r\n _self.id = params[0];\r\n // we already have a cookie\r\n _self[_DYN_IS_USER_COOKIE_SET /* @min:%2eisUserCookieSet */] = !!_self.id;\r\n }\r\n }\r\n if (!_self.id) {\r\n _self.id = _generateNewId();\r\n var newCookie = _generateNewCookie(_self.id);\r\n _setUserCookie(newCookie[_DYN_JOIN /* @min:%2ejoin */](User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]));\r\n // If we have an config.namePrefix() + ai_session in local storage this means the user actively removed our cookies.\r\n // We should respect their wishes and clear ourselves from local storage\r\n var name_1 = (config[_DYN_NAME_PREFIX /* @min:%2enamePrefix */] || \"\") + \"ai_session\";\r\n utlRemoveStorage(_logger, name_1);\r\n }\r\n // We still take the account id from the ctor param for backward compatibility.\r\n // But if the the customer set the accountId through the newer setAuthenticatedUserContext API, we will override it.\r\n _self[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] = config[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] || undefined;\r\n // Get the auth user id and account id from the cookie if exists\r\n // Cookie is in the pattern: |\r\n var authCookie = _cookieManager.get(User[_DYN_AUTH_USER_COOKIE_NAM7 /* @min:%2eauthUserCookieName */]);\r\n if (authCookie) {\r\n authCookie = decodeURI(authCookie);\r\n var authCookieString = authCookie.split(User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]);\r\n if (authCookieString[0]) {\r\n _self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */] = authCookieString[0];\r\n }\r\n if (authCookieString[_DYN_LENGTH /* @min:%2elength */] > 1 && authCookieString[1]) {\r\n _self[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] = authCookieString[1];\r\n }\r\n }\r\n });\r\n unloadHookContainer && unloadHookContainer.add(unloadHook);\r\n function _generateNewId() {\r\n var theConfig = (config || {});\r\n var getNewId = theConfig[_DYN_GET_NEW_ID /* @min:%2egetNewId */] || newId;\r\n var id = getNewId(theConfig[_DYN_ID_LENGTH /* @min:%2eidLength */] ? config[_DYN_ID_LENGTH /* @min:%2eidLength */] : 22);\r\n return id;\r\n }\r\n function _generateNewCookie(userId) {\r\n var acqStr = toISOString(new Date());\r\n _self.accountAcquisitionDate = acqStr;\r\n _self[_DYN_IS_NEW_USER /* @min:%2eisNewUser */] = true;\r\n var newCookie = [userId, acqStr];\r\n return newCookie;\r\n }\r\n function _setUserCookie(cookie) {\r\n // without expiration, cookies expire at the end of the session\r\n // set it to 365 days from now\r\n // 365 * 24 * 60 * 60 = 31536000\r\n var oneYear = 31536000;\r\n _self[_DYN_IS_USER_COOKIE_SET /* @min:%2eisUserCookieSet */] = _cookieManager.set(_storageNamePrefix, cookie, oneYear);\r\n }\r\n _self.setAuthenticatedUserContext = function (authenticatedUserId, accountId, storeInCookie) {\r\n if (storeInCookie === void 0) { storeInCookie = false; }\r\n // Validate inputs to ensure no cookie control characters.\r\n var isInvalidInput = !_validateUserInput(authenticatedUserId) || (accountId && !_validateUserInput(accountId));\r\n if (isInvalidInput) {\r\n _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 60 /* _eInternalMessageId.SetAuthContextFailedAccountName */, \"Setting auth user context failed. \" +\r\n \"User auth/account id should be of type string, and not contain commas, semi-colons, equal signs, spaces, or vertical-bars.\", true);\r\n return;\r\n }\r\n // Create cookie string.\r\n _self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */] = authenticatedUserId;\r\n var authCookie = _self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */];\r\n if (accountId) {\r\n _self[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] = accountId;\r\n authCookie = [_self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */], _self.accountId][_DYN_JOIN /* @min:%2ejoin */](User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]);\r\n }\r\n if (storeInCookie) {\r\n // Set the cookie. No expiration date because this is a session cookie (expires when browser closed).\r\n // Encoding the cookie to handle unexpected unicode characters.\r\n _cookieManager.set(User[_DYN_AUTH_USER_COOKIE_NAM7 /* @min:%2eauthUserCookieName */], encodeURI(authCookie));\r\n }\r\n };\r\n /**\r\n * Clears the authenticated user id and the account id from the user context.\r\n * @returns {}\r\n */\r\n _self.clearAuthenticatedUserContext = function () {\r\n _self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */] = null;\r\n _self[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] = null;\r\n _cookieManager.del(User[_DYN_AUTH_USER_COOKIE_NAM7 /* @min:%2eauthUserCookieName */]);\r\n };\r\n _self[_DYN_UPDATE /* @min:%2eupdate */] = function (userId) {\r\n // Optimizations to avoid setting and processing the cookie when not needed\r\n if (_self.id !== userId || !_self[_DYN_IS_USER_COOKIE_SET /* @min:%2eisUserCookieSet */]) {\r\n var user_id = userId ? userId : _generateNewId();\r\n var user_cookie = _generateNewCookie(user_id);\r\n _setUserCookie(user_cookie[_DYN_JOIN /* @min:%2ejoin */](User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]));\r\n }\r\n };\r\n });\r\n }\r\n /**\r\n * Sets the authenticated user id and the account id in this session.\r\n *\r\n * @param authenticatedUserId - {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service.\r\n * @param accountId - {string} - An optional string to represent the account associated with the authenticated user.\r\n */\r\n User.prototype.setAuthenticatedUserContext = function (authenticatedUserId, accountId, storeInCookie) {\r\n if (storeInCookie === void 0) { storeInCookie = false; }\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Clears the authenticated user id and the account id from the user context.\r\n * @returns {}\r\n */\r\n User.prototype.clearAuthenticatedUserContext = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Update or create the user cookie if cookies where previously disabled or the new userId does not match the existing value.\r\n * If you pass nothing a new random user id will be created.\r\n * @param userId - Specific either the current (via appInsights.context.user.id) or new id that you want to set\r\n */\r\n User.prototype.update = function (userId) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n User.cookieSeparator = \"|\";\r\n User.userCookieName = \"ai_user\";\r\n User.authUserCookieName = \"ai_authUser\";\r\n return User;\r\n}());\r\nexport { User };\r\n//# sourceMappingURL=User.js.map","/**\r\n* TelemetryContext.ts\r\n* @copyright Microsoft 2018\r\n*/\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { CtxTagKeys, Extensions, PageView, dataSanitizeString } from \"@microsoft/applicationinsights-common\";\r\nimport { _InternalLogMessage, getSetValue, hasWindow, isNullOrUndefined, isString, objKeys, setValue } from \"@microsoft/applicationinsights-core-js\";\r\nimport { Application } from \"./Context/Application\";\r\nimport { Device } from \"./Context/Device\";\r\nimport { Internal } from \"./Context/Internal\";\r\nimport { Location } from \"./Context/Location\";\r\nimport { Session, _SessionManager } from \"./Context/Session\";\r\nimport { TelemetryTrace } from \"./Context/TelemetryTrace\";\r\nimport { User } from \"./Context/User\";\r\nimport { _DYN_ACCOUNT_ID, _DYN_APPLY_APPLICATION_CO1, _DYN_APPLY_DEVICE_CONTEXT, _DYN_APPLY_INTERNAL_CONTE5, _DYN_APPLY_LOCATION_CONTE4, _DYN_APPLY_OPERATING_SYST3, _DYN_APPLY_OPERATION_CONT2, _DYN_APPLY_SESSION_CONTEX0, _DYN_APPLY_USER_CONTEXT, _DYN_AUTHENTICATED_ID, _DYN_AUTOMATIC_SESSION, _DYN_GET_SESSION_ID, _DYN_LENGTH, _DYN_SESSION_MANAGER, _DYN_TELEMETRY_TRACE } from \"./__DynamicConstants\";\r\nvar strExt = \"ext\";\r\nvar strTags = \"tags\";\r\nfunction _removeEmpty(target, name) {\r\n if (target && target[name] && objKeys(target[name])[_DYN_LENGTH /* @min:%2elength */] === 0) {\r\n delete target[name];\r\n }\r\n}\r\nfunction _nullResult() {\r\n return null;\r\n}\r\nvar TelemetryContext = /** @class */ (function () {\r\n function TelemetryContext(core, defaultConfig, previousTraceCtx, unloadHookContainer) {\r\n var _this = this;\r\n var logger = core.logger;\r\n dynamicProto(TelemetryContext, this, function (_self) {\r\n _self.appId = _nullResult;\r\n _self[_DYN_GET_SESSION_ID /* @min:%2egetSessionId */] = _nullResult;\r\n _self.application = new Application();\r\n _self.internal = new Internal(defaultConfig, unloadHookContainer);\r\n if (hasWindow()) {\r\n _self[_DYN_SESSION_MANAGER /* @min:%2esessionManager */] = new _SessionManager(defaultConfig, core, unloadHookContainer);\r\n _self.device = new Device();\r\n _self.location = new Location();\r\n _self.user = new User(defaultConfig, core, unloadHookContainer);\r\n var traceId = void 0;\r\n var parentId = void 0;\r\n var name_1;\r\n if (previousTraceCtx) {\r\n traceId = previousTraceCtx.getTraceId();\r\n parentId = previousTraceCtx.getSpanId();\r\n name_1 = previousTraceCtx.getName();\r\n }\r\n _self[_DYN_TELEMETRY_TRACE /* @min:%2etelemetryTrace */] = new TelemetryTrace(traceId, parentId, name_1, logger);\r\n _self.session = new Session();\r\n }\r\n _self[_DYN_GET_SESSION_ID /* @min:%2egetSessionId */] = function () {\r\n var session = _self.session;\r\n var sesId = null;\r\n // If customer set session info, apply their context; otherwise apply context automatically generated\r\n if (session && isString(session.id)) {\r\n sesId = session.id;\r\n }\r\n else {\r\n // Gets the automatic session if it exists or an empty object\r\n var autoSession = (_self[_DYN_SESSION_MANAGER /* @min:%2esessionManager */] || {})[_DYN_AUTOMATIC_SESSION /* @min:%2eautomaticSession */];\r\n sesId = autoSession && isString(autoSession.id) ? autoSession.id : null;\r\n }\r\n return sesId;\r\n };\r\n _self[_DYN_APPLY_SESSION_CONTEX0 /* @min:%2eapplySessionContext */] = function (evt, itemCtx) {\r\n setValue(getSetValue(evt.ext, Extensions.AppExt), \"sesId\", _self[_DYN_GET_SESSION_ID /* @min:%2egetSessionId */](), isString);\r\n };\r\n _self[_DYN_APPLY_OPERATING_SYST3 /* @min:%2eapplyOperatingSystemContxt */] = function (evt, itemCtx) {\r\n setValue(evt.ext, Extensions.OSExt, _self.os);\r\n };\r\n _self[_DYN_APPLY_APPLICATION_CO1 /* @min:%2eapplyApplicationContext */] = function (evt, itemCtx) {\r\n var application = _self.application;\r\n if (application) {\r\n // evt.ext.app\r\n var tags = getSetValue(evt, strTags);\r\n setValue(tags, CtxTagKeys.applicationVersion, application.ver, isString);\r\n setValue(tags, CtxTagKeys.applicationBuild, application.build, isString);\r\n }\r\n };\r\n _self[_DYN_APPLY_DEVICE_CONTEXT /* @min:%2eapplyDeviceContext */] = function (evt, itemCtx) {\r\n var device = _self.device;\r\n if (device) {\r\n // evt.ext.device\r\n var extDevice = getSetValue(getSetValue(evt, strExt), Extensions.DeviceExt);\r\n setValue(extDevice, \"localId\", device.id, isString);\r\n setValue(extDevice, \"ip\", device.ip, isString);\r\n setValue(extDevice, \"model\", device.model, isString);\r\n setValue(extDevice, \"deviceClass\", device.deviceClass, isString);\r\n }\r\n };\r\n _self[_DYN_APPLY_INTERNAL_CONTE5 /* @min:%2eapplyInternalContext */] = function (evt, itemCtx) {\r\n var internal = _self.internal;\r\n if (internal) {\r\n var tags = getSetValue(evt, strTags);\r\n setValue(tags, CtxTagKeys.internalAgentVersion, internal.agentVersion, isString); // not mapped in CS 4.0\r\n setValue(tags, CtxTagKeys.internalSdkVersion, dataSanitizeString(logger, internal.sdkVersion, 64), isString);\r\n if (evt.baseType === _InternalLogMessage.dataType || evt.baseType === PageView.dataType) {\r\n setValue(tags, CtxTagKeys.internalSnippet, internal.snippetVer, isString);\r\n setValue(tags, CtxTagKeys.internalSdkSrc, internal.sdkSrc, isString);\r\n }\r\n }\r\n };\r\n _self[_DYN_APPLY_LOCATION_CONTE4 /* @min:%2eapplyLocationContext */] = function (evt, itemCtx) {\r\n var location = _this.location;\r\n if (location) {\r\n setValue(getSetValue(evt, strTags, []), CtxTagKeys.locationIp, location.ip, isString);\r\n }\r\n };\r\n _self[_DYN_APPLY_OPERATION_CONT2 /* @min:%2eapplyOperationContext */] = function (evt, itemCtx) {\r\n var telemetryTrace = _self[_DYN_TELEMETRY_TRACE /* @min:%2etelemetryTrace */];\r\n if (telemetryTrace) {\r\n var extTrace = getSetValue(getSetValue(evt, strExt), Extensions.TraceExt, { traceID: undefined, parentID: undefined });\r\n setValue(extTrace, \"traceID\", telemetryTrace.traceID, isString, isNullOrUndefined);\r\n setValue(extTrace, \"name\", telemetryTrace.name, isString, isNullOrUndefined);\r\n setValue(extTrace, \"parentID\", telemetryTrace.parentID, isString, isNullOrUndefined);\r\n }\r\n };\r\n _self.applyWebContext = function (evt, itemCtx) {\r\n var web = _this.web;\r\n if (web) {\r\n setValue(getSetValue(evt, strExt), Extensions.WebExt, web);\r\n }\r\n };\r\n _self[_DYN_APPLY_USER_CONTEXT /* @min:%2eapplyUserContext */] = function (evt, itemCtx) {\r\n var user = _self.user;\r\n if (user) {\r\n var tags = getSetValue(evt, strTags, []);\r\n // stays in tags\r\n setValue(tags, CtxTagKeys.userAccountId, user[_DYN_ACCOUNT_ID /* @min:%2eaccountId */], isString);\r\n // CS 4.0\r\n var extUser = getSetValue(getSetValue(evt, strExt), Extensions.UserExt);\r\n setValue(extUser, \"id\", user.id, isString);\r\n setValue(extUser, \"authId\", user[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */], isString);\r\n }\r\n };\r\n _self.cleanUp = function (evt, itemCtx) {\r\n var ext = evt.ext;\r\n if (ext) {\r\n _removeEmpty(ext, Extensions.DeviceExt);\r\n _removeEmpty(ext, Extensions.UserExt);\r\n _removeEmpty(ext, Extensions.WebExt);\r\n _removeEmpty(ext, Extensions.OSExt);\r\n _removeEmpty(ext, Extensions.AppExt);\r\n _removeEmpty(ext, Extensions.TraceExt);\r\n }\r\n };\r\n });\r\n }\r\n TelemetryContext.prototype.applySessionContext = function (evt, itemCtx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n TelemetryContext.prototype.applyOperatingSystemContxt = function (event, itemCtx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n TelemetryContext.prototype.applyApplicationContext = function (event, itemCtx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n TelemetryContext.prototype.applyDeviceContext = function (event, itemCtx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n TelemetryContext.prototype.applyInternalContext = function (event, itemCtx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n TelemetryContext.prototype.applyLocationContext = function (event, itemCtx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n TelemetryContext.prototype.applyOperationContext = function (event, itemCtx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n TelemetryContext.prototype.applyWebContext = function (event, itemCtx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n TelemetryContext.prototype.applyUserContext = function (event, itemCtx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n TelemetryContext.prototype.cleanUp = function (event, itemCtx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n return TelemetryContext;\r\n}());\r\nexport { TelemetryContext };\r\n//# sourceMappingURL=TelemetryContext.js.map","/**\r\n* PropertiesPlugin.ts\r\n* @copyright Microsoft 2018\r\n*/\r\nvar _a;\r\nimport { __extends } from \"tslib\";\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { BreezeChannelIdentifier, PageView, PropertiesPluginIdentifier, createDistributedTraceContextFromTrace } from \"@microsoft/applicationinsights-common\";\r\nimport { BaseTelemetryPlugin, _InternalLogMessage, _logInternalMessage, createProcessTelemetryContext, getNavigator, getSetValue, isNullOrUndefined, onConfigChange } from \"@microsoft/applicationinsights-core-js\";\r\nimport { objDeepFreeze, objDefine } from \"@nevware21/ts-utils\";\r\nimport { TelemetryContext } from \"./TelemetryContext\";\r\nimport { _DYN_ACCOUNT_ID, _DYN_APPLY_APPLICATION_CO1, _DYN_APPLY_DEVICE_CONTEXT, _DYN_APPLY_INTERNAL_CONTE5, _DYN_APPLY_LOCATION_CONTE4, _DYN_APPLY_OPERATING_SYST3, _DYN_APPLY_OPERATION_CONT2, _DYN_APPLY_SESSION_CONTEX0, _DYN_APPLY_USER_CONTEXT, _DYN_GET_NEW_ID, _DYN_GET_SESSION_ID, _DYN_GET_TRACE_CTX, _DYN_ID_LENGTH, _DYN_IS_NEW_USER, _DYN_IS_USER_COOKIE_SET, _DYN_NAME_PREFIX, _DYN_SESSION_COOKIE_POSTF6, _DYN_SESSION_MANAGER, _DYN_TELEMETRY_TRACE, _DYN_UPDATE, _DYN_USER_COOKIE_POSTFIX } from \"./__DynamicConstants\";\r\nvar undefString;\r\nvar nullValue = null;\r\nvar _defaultConfig = objDeepFreeze((_a = {},\r\n _a[_DYN_ACCOUNT_ID /* @min:accountId */] = nullValue,\r\n _a.sessionRenewalMs = 30 * 60 * 1000,\r\n _a.samplingPercentage = 100,\r\n _a.sessionExpirationMs = 24 * 60 * 60 * 1000,\r\n _a.cookieDomain = nullValue,\r\n _a.sdkExtension = nullValue,\r\n _a.isBrowserLinkTrackingEnabled = false,\r\n _a.appId = nullValue,\r\n _a[_DYN_GET_SESSION_ID /* @min:getSessionId */] = nullValue,\r\n _a[_DYN_NAME_PREFIX /* @min:namePrefix */] = undefString,\r\n _a[_DYN_SESSION_COOKIE_POSTF6 /* @min:sessionCookiePostfix */] = undefString,\r\n _a[_DYN_USER_COOKIE_POSTFIX /* @min:userCookiePostfix */] = undefString,\r\n _a[_DYN_ID_LENGTH /* @min:idLength */] = 22,\r\n _a[_DYN_GET_NEW_ID /* @min:getNewId */] = nullValue,\r\n _a));\r\nvar PropertiesPlugin = /** @class */ (function (_super) {\r\n __extends(PropertiesPlugin, _super);\r\n function PropertiesPlugin() {\r\n var _this = _super.call(this) || this;\r\n _this.priority = 110;\r\n _this.identifier = PropertiesPluginIdentifier;\r\n var _extensionConfig;\r\n var _distributedTraceCtx;\r\n var _previousTraceCtx;\r\n var _context;\r\n dynamicProto(PropertiesPlugin, _this, function (_self, _base) {\r\n _initDefaults();\r\n objDefine(_self, \"context\", {\r\n g: function () {\r\n return _context;\r\n }\r\n });\r\n _self.initialize = function (config, core, extensions, pluginChain) {\r\n _base.initialize(config, core, extensions, pluginChain);\r\n _populateDefaults(config);\r\n };\r\n /**\r\n * Add Part A fields to the event\r\n * @param event - The event that needs to be processed\r\n */\r\n _self.processTelemetry = function (event, itemCtx) {\r\n if (!isNullOrUndefined(event)) {\r\n itemCtx = _self._getTelCtx(itemCtx);\r\n // If the envelope is PageView, reset the internal message count so that we can send internal telemetry for the new page.\r\n if (event.name === PageView.envelopeType) {\r\n itemCtx.diagLog().resetInternalMessageCount();\r\n }\r\n var theContext = (_context || {});\r\n if (theContext.session) {\r\n // If customer did not provide custom session id update the session manager\r\n if (typeof _context.session.id !== \"string\" && theContext[_DYN_SESSION_MANAGER /* @min:%2esessionManager */]) {\r\n theContext[_DYN_SESSION_MANAGER /* @min:%2esessionManager */][_DYN_UPDATE /* @min:%2eupdate */]();\r\n }\r\n }\r\n var userCtx = theContext.user;\r\n if (userCtx && !userCtx[_DYN_IS_USER_COOKIE_SET /* @min:%2eisUserCookieSet */]) {\r\n userCtx[_DYN_UPDATE /* @min:%2eupdate */](theContext.user.id);\r\n }\r\n _processTelemetryInternal(event, itemCtx);\r\n if (userCtx && userCtx[_DYN_IS_NEW_USER /* @min:%2eisNewUser */]) {\r\n userCtx[_DYN_IS_NEW_USER /* @min:%2eisNewUser */] = false;\r\n var message = new _InternalLogMessage(72 /* _eInternalMessageId.SendBrowserInfoOnUserInit */, ((getNavigator() || {}).userAgent || \"\"));\r\n _logInternalMessage(itemCtx.diagLog(), 1 /* eLoggingSeverity.CRITICAL */, message);\r\n }\r\n _self.processNext(event, itemCtx);\r\n }\r\n };\r\n _self._doTeardown = function (unloadCtx, unloadState) {\r\n var core = (unloadCtx || {}).core();\r\n if (core && core[_DYN_GET_TRACE_CTX /* @min:%2egetTraceCtx */]) {\r\n var traceCtx = core[_DYN_GET_TRACE_CTX /* @min:%2egetTraceCtx */](false);\r\n if (traceCtx === _distributedTraceCtx) {\r\n core.setTraceCtx(_previousTraceCtx);\r\n }\r\n }\r\n _initDefaults();\r\n };\r\n function _initDefaults() {\r\n _extensionConfig = null;\r\n _distributedTraceCtx = null;\r\n _previousTraceCtx = null;\r\n _context = null;\r\n }\r\n function _populateDefaults(config) {\r\n var identifier = _self.identifier;\r\n var core = _self.core;\r\n // This function will be re-called whenever any referenced configuration is changed\r\n _self._addHook(onConfigChange(config, function () {\r\n var ctx = createProcessTelemetryContext(null, config, core);\r\n _extensionConfig = ctx.getExtCfg(identifier, _defaultConfig);\r\n // Test hook to allow accessing the internal values -- explicitly not defined as an available property on the class\r\n _self[\"_extConfig\"] = _extensionConfig;\r\n }));\r\n // This is outside of the onConfigChange as we don't want to update (replace) these values whenever a referenced config item changes\r\n _previousTraceCtx = core[_DYN_GET_TRACE_CTX /* @min:%2egetTraceCtx */](false);\r\n _context = new TelemetryContext(core, _extensionConfig, _previousTraceCtx, _self._unloadHooks);\r\n _distributedTraceCtx = createDistributedTraceContextFromTrace(_self.context[_DYN_TELEMETRY_TRACE /* @min:%2etelemetryTrace */], _previousTraceCtx);\r\n core.setTraceCtx(_distributedTraceCtx);\r\n _self.context.appId = function () {\r\n var breezeChannel = core.getPlugin(BreezeChannelIdentifier);\r\n return breezeChannel ? breezeChannel.plugin[\"_appId\"] : null;\r\n };\r\n }\r\n function _processTelemetryInternal(evt, itemCtx) {\r\n // Set Part A fields\r\n getSetValue(evt, \"tags\", []);\r\n getSetValue(evt, \"ext\", {});\r\n var ctx = _self.context;\r\n ctx[_DYN_APPLY_SESSION_CONTEX0 /* @min:%2eapplySessionContext */](evt, itemCtx);\r\n ctx[_DYN_APPLY_APPLICATION_CO1 /* @min:%2eapplyApplicationContext */](evt, itemCtx);\r\n ctx[_DYN_APPLY_DEVICE_CONTEXT /* @min:%2eapplyDeviceContext */](evt, itemCtx);\r\n ctx[_DYN_APPLY_OPERATION_CONT2 /* @min:%2eapplyOperationContext */](evt, itemCtx);\r\n ctx[_DYN_APPLY_USER_CONTEXT /* @min:%2eapplyUserContext */](evt, itemCtx);\r\n ctx[_DYN_APPLY_OPERATING_SYST3 /* @min:%2eapplyOperatingSystemContxt */](evt, itemCtx);\r\n ctx.applyWebContext(evt, itemCtx);\r\n ctx[_DYN_APPLY_LOCATION_CONTE4 /* @min:%2eapplyLocationContext */](evt, itemCtx); // legacy tags\r\n ctx[_DYN_APPLY_INTERNAL_CONTE5 /* @min:%2eapplyInternalContext */](evt, itemCtx); // legacy tags\r\n ctx.cleanUp(evt, itemCtx);\r\n }\r\n });\r\n return _this;\r\n }\r\n PropertiesPlugin.prototype.initialize = function (config, core, extensions, pluginChain) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Add Part A fields to the event\r\n * @param event - The event that needs to be processed\r\n */\r\n PropertiesPlugin.prototype.processTelemetry = function (event, itemCtx) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n return PropertiesPlugin;\r\n}(BaseTelemetryPlugin));\r\nexport default PropertiesPlugin;\r\n//# sourceMappingURL=PropertiesPlugin.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\"use strict\";\r\nvar _a;\r\nimport dynamicProto from \"@microsoft/dynamicproto-js\";\r\nimport { AnalyticsPlugin } from \"@microsoft/applicationinsights-analytics-js\";\r\nimport { Sender } from \"@microsoft/applicationinsights-channel-js\";\r\nimport { DEFAULT_BREEZE_PATH, PropertiesPluginIdentifier, parseConnectionString } from \"@microsoft/applicationinsights-common\";\r\nimport { AppInsightsCore, _throwInternal, addPageHideEventListener, addPageUnloadEventListener, cfgDfValidate, createDynamicConfig, createUniqueNamespace, doPerf, hasDocument, hasWindow, isArray, isFunction, isNullOrUndefined, isReactNative, isString, mergeEvtNamespace, onConfigChange, proxyAssign, proxyFunctions, removePageHideEventListener, removePageUnloadEventListener } from \"@microsoft/applicationinsights-core-js\";\r\nimport { AjaxPlugin as DependenciesPlugin } from \"@microsoft/applicationinsights-dependencies-js\";\r\nimport { PropertiesPlugin } from \"@microsoft/applicationinsights-properties-js\";\r\nimport { createPromise } from \"@nevware21/ts-async\";\r\nimport { arrForEach, arrIndexOf, objDefine, objForEachKey, strIndexOf, throwUnsupported } from \"@nevware21/ts-utils\";\r\nimport { 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\";\r\nimport { _DYN_ADD_HOUSEKEEPING_BEF1, _DYN_CONNECTION_STRING, _DYN_CONTEXT, _DYN_DISABLE_IKEY_DEPRECA0, _DYN_ENDPOINT_URL, _DYN_INSTRUMENTATION_KEY, _DYN_ONUNLOAD_FLUSH, _DYN_QUEUE, _DYN_UPDATE_SNIPPET_DEFIN2, _DYN_VERSION } from \"./__DynamicConstants\";\r\nvar _internalSdkSrc;\r\n// This is an exclude list of properties that should not be updated during initialization\r\n// They include a combination of private and internal property names\r\nvar _ignoreUpdateSnippetProperties = [\r\n STR_SNIPPET, \"dependencies\", \"properties\", \"_snippetVersion\", \"appInsightsNew\", \"getSKUDefaults\"\r\n];\r\nvar UNDEFINED_VALUE = undefined;\r\n// We need to include all properties that we only reference that we want to be dynamically updatable here\r\n// So they are converted even when not specified in the passed configuration\r\nvar defaultConfigValues = (_a = {},\r\n _a[_DYN_CONNECTION_STRING /* @min:connectionString */] = UNDEFINED_VALUE,\r\n _a[_DYN_ENDPOINT_URL /* @min:endpointUrl */] = UNDEFINED_VALUE,\r\n _a[_DYN_INSTRUMENTATION_KEY /* @min:instrumentationKey */] = UNDEFINED_VALUE,\r\n _a.diagnosticLogInterval = cfgDfValidate(_chkDiagLevel, 10000),\r\n _a);\r\nfunction _chkDiagLevel(value) {\r\n // Make sure we have a value > 0\r\n return value && value > 0;\r\n}\r\n/**\r\n * Application Insights API\r\n * @class Initialization\r\n * @implements {IApplicationInsights}\r\n */\r\nvar AppInsightsSku = /** @class */ (function () {\r\n function AppInsightsSku(snippet) {\r\n var _this = this;\r\n // NOTE!: DON'T set default values here, instead set them in the _initDefaults() function as it is also called during teardown()\r\n var dependencies;\r\n var properties;\r\n var _sender;\r\n var _snippetVersion;\r\n var _evtNamespace;\r\n var _houseKeepingNamespace;\r\n var _core;\r\n var _config;\r\n var _analyticsPlugin;\r\n dynamicProto(AppInsightsSku, this, function (_self) {\r\n _initDefaults();\r\n objDefine(_self, \"config\", {\r\n g: function () {\r\n return _config;\r\n }\r\n });\r\n arrForEach([\"pluginVersionStringArr\", \"pluginVersionString\"], function (key) {\r\n objDefine(_self, key, {\r\n g: function () {\r\n if (_core) {\r\n return _core[key];\r\n }\r\n return null;\r\n }\r\n });\r\n });\r\n // initialize the queue and config in case they are undefined\r\n _snippetVersion = \"\" + (snippet.sv || snippet[_DYN_VERSION /* @min:%2eversion */] || \"\");\r\n snippet[_DYN_QUEUE /* @min:%2equeue */] = snippet[_DYN_QUEUE /* @min:%2equeue */] || [];\r\n snippet[_DYN_VERSION /* @min:%2eversion */] = snippet[_DYN_VERSION /* @min:%2eversion */] || 2.0; // Default to new version\r\n var cfgHandler = createDynamicConfig(snippet.config || {}, defaultConfigValues);\r\n _config = cfgHandler.cfg;\r\n _analyticsPlugin = new AnalyticsPlugin();\r\n objDefine(_self, \"appInsights\", {\r\n g: function () {\r\n return _analyticsPlugin;\r\n }\r\n });\r\n properties = new PropertiesPlugin();\r\n dependencies = new DependenciesPlugin();\r\n _sender = new Sender();\r\n _core = new AppInsightsCore();\r\n objDefine(_self, \"core\", {\r\n g: function () {\r\n return _core;\r\n }\r\n });\r\n // Will get recalled if any referenced values are changed\r\n _addUnloadHook(onConfigChange(cfgHandler, function () {\r\n if (_config[_DYN_CONNECTION_STRING /* @min:%2econnectionString */]) {\r\n var cs = parseConnectionString(_config[_DYN_CONNECTION_STRING /* @min:%2econnectionString */]);\r\n var ingest = cs.ingestionendpoint;\r\n _config[_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */] = ingest ? (ingest + DEFAULT_BREEZE_PATH) : _config[_DYN_ENDPOINT_URL /* @min:%2eendpointUrl */]; // only add /v2/track when from connectionstring\r\n _config[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */] = cs.instrumentationkey || _config[_DYN_INSTRUMENTATION_KEY /* @min:%2einstrumentationKey */];\r\n }\r\n }));\r\n // Outside of the onConfigChange as we only want to do this once\r\n var isErrMessageDisabled = isNullOrUndefined(_config[_DYN_DISABLE_IKEY_DEPRECA0 /* @min:%2edisableIkeyDeprecationMessage */]) ? true : _config[_DYN_DISABLE_IKEY_DEPRECA0 /* @min:%2edisableIkeyDeprecationMessage */];\r\n if (!_config[_DYN_CONNECTION_STRING /* @min:%2econnectionString */] && !isErrMessageDisabled) {\r\n _throwInternal(_core.logger, 1 /* eLoggingSeverity.CRITICAL */, 106 /* _eInternalMessageId.InstrumentationKeyDeprecation */, \"Instrumentation key support will end soon, see aka.ms/IkeyMigrate\");\r\n }\r\n _self[STR_SNIPPET /* @min:%2esnippet */] = snippet;\r\n _self[STR_FLUSH /* @min:%2eflush */] = function (async, callBack) {\r\n if (async === void 0) { async = true; }\r\n var result;\r\n doPerf(_core, function () { return \"AISKU.flush\"; }, function () {\r\n if (async && !callBack) {\r\n result = createPromise(function (resolve) {\r\n callBack = resolve;\r\n });\r\n }\r\n var waiting = 1;\r\n var flushDone = function () {\r\n waiting--;\r\n if (waiting === 0) {\r\n callBack();\r\n }\r\n };\r\n arrForEach(_core.getChannels(), function (channel) {\r\n if (channel) {\r\n waiting++;\r\n channel[STR_FLUSH /* @min:%2eflush */](async, flushDone);\r\n }\r\n });\r\n // decrement the initial \"waiting\"\r\n flushDone();\r\n }, null, async);\r\n return result;\r\n };\r\n _self[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */] = function (async) {\r\n if (async === void 0) { async = true; }\r\n arrForEach(_core.getChannels(), function (channel) {\r\n if (channel[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */]) {\r\n channel[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */]();\r\n }\r\n else {\r\n channel[STR_FLUSH /* @min:%2eflush */](async);\r\n }\r\n });\r\n };\r\n _self.loadAppInsights = function (legacyMode, logger, notificationManager) {\r\n if (legacyMode === void 0) { legacyMode = false; }\r\n if (legacyMode) {\r\n throwUnsupported(\"Legacy Mode is no longer supported\");\r\n }\r\n function _updateSnippetProperties(snippet) {\r\n if (snippet) {\r\n var snippetVer = \"\";\r\n if (!isNullOrUndefined(_snippetVersion)) {\r\n snippetVer += _snippetVersion;\r\n }\r\n if (_self[_DYN_CONTEXT /* @min:%2econtext */] && _self[_DYN_CONTEXT /* @min:%2econtext */].internal) {\r\n _self[_DYN_CONTEXT /* @min:%2econtext */].internal.snippetVer = snippetVer || \"-\";\r\n }\r\n // apply updated properties to the global instance (snippet)\r\n objForEachKey(_self, function (field, value) {\r\n if (isString(field) &&\r\n !isFunction(value) &&\r\n field && field[0] !== \"_\" && // Don't copy \"internal\" values\r\n arrIndexOf(_ignoreUpdateSnippetProperties, field) === -1) {\r\n if (snippet[field] !== value) {\r\n snippet[field] = value;\r\n }\r\n }\r\n });\r\n }\r\n }\r\n doPerf(_self.core, function () { return \"AISKU.loadAppInsights\"; }, function () {\r\n // initialize core\r\n _core.initialize(_config, [_sender, properties, dependencies, _analyticsPlugin], logger, notificationManager);\r\n objDefine(_self, \"context\", {\r\n g: function () { return properties[_DYN_CONTEXT /* @min:%2econtext */]; }\r\n });\r\n var sdkSrc = _findSdkSourceFile();\r\n if (sdkSrc && _self[_DYN_CONTEXT /* @min:%2econtext */]) {\r\n _self[_DYN_CONTEXT /* @min:%2econtext */].internal.sdkSrc = sdkSrc;\r\n }\r\n _updateSnippetProperties(_self[STR_SNIPPET /* @min:%2esnippet */]);\r\n // Empty queue of all api calls logged prior to sdk download\r\n _self.emptyQueue();\r\n _self[STR_POLL_INTERNAL_LOGS /* @min:%2epollInternalLogs */]();\r\n _self[_DYN_ADD_HOUSEKEEPING_BEF1 /* @min:%2eaddHousekeepingBeforeUnload */](_self);\r\n });\r\n return _self;\r\n };\r\n _self[_DYN_UPDATE_SNIPPET_DEFIN2 /* @min:%2eupdateSnippetDefinitions */] = function (snippet) {\r\n // apply full appInsights to the global instance\r\n // Note: This must be called before loadAppInsights is called\r\n proxyAssign(snippet, _self, function (name) {\r\n // Not excluding names prefixed with \"_\" as we need to proxy some functions like _onError\r\n return name && arrIndexOf(_ignoreUpdateSnippetProperties, name) === -1;\r\n });\r\n };\r\n _self.emptyQueue = function () {\r\n // call functions that were queued before the main script was loaded\r\n try {\r\n if (isArray(_self.snippet[_DYN_QUEUE /* @min:%2equeue */])) {\r\n // note: do not check length in the for-loop conditional in case something goes wrong and the stub methods are not overridden.\r\n var length_1 = _self.snippet[_DYN_QUEUE /* @min:%2equeue */].length;\r\n for (var i = 0; i < length_1; i++) {\r\n var call = _self.snippet[_DYN_QUEUE /* @min:%2equeue */][i];\r\n call();\r\n }\r\n _self.snippet[_DYN_QUEUE /* @min:%2equeue */] = undefined;\r\n delete _self.snippet[_DYN_QUEUE /* @min:%2equeue */];\r\n }\r\n }\r\n catch (exception) {\r\n var properties_1 = {};\r\n if (exception && isFunction(exception.toString)) {\r\n properties_1.exception = exception.toString();\r\n }\r\n // need from core\r\n // Microsoft.ApplicationInsights._InternalLogging.throwInternal(\r\n // eLoggingSeverity.WARNING,\r\n // _eInternalMessageId.FailedToSendQueuedTelemetry,\r\n // \"Failed to send queued telemetry\",\r\n // properties);\r\n }\r\n };\r\n _self[_DYN_ADD_HOUSEKEEPING_BEF1 /* @min:%2eaddHousekeepingBeforeUnload */] = function (appInsightsInstance) {\r\n // Add callback to push events when the user navigates away\r\n if (hasWindow() || hasDocument()) {\r\n var performHousekeeping_1 = function () {\r\n // Adds the ability to flush all data before the page unloads.\r\n // Note: This approach tries to push a sync request with all the pending events onbeforeunload.\r\n // Firefox does not respect this.Other browsers DO push out the call with < 100% hit rate.\r\n // Telemetry here will help us analyze how effective this approach is.\r\n // Another approach would be to make this call sync with a acceptable timeout to reduce the\r\n // impact on user experience.\r\n // appInsightsInstance.context._sender.triggerSend();\r\n appInsightsInstance[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */](false);\r\n // Back up the current session to local storage\r\n // This lets us close expired sessions after the cookies themselves expire\r\n if (isFunction(_self.core[STR_GET_PLUGIN /* @min:%2egetPlugin */])) {\r\n var loadedPlugin = _this.core[STR_GET_PLUGIN /* @min:%2egetPlugin */](PropertiesPluginIdentifier);\r\n if (loadedPlugin) {\r\n var propertiesPlugin = loadedPlugin.plugin;\r\n if (propertiesPlugin && propertiesPlugin[_DYN_CONTEXT /* @min:%2econtext */] && propertiesPlugin[_DYN_CONTEXT /* @min:%2econtext */]._sessionManager) {\r\n propertiesPlugin[_DYN_CONTEXT /* @min:%2econtext */]._sessionManager.backup();\r\n }\r\n }\r\n }\r\n };\r\n var added_1 = false;\r\n var analyticsPlugin_1 = appInsightsInstance.appInsights;\r\n var theConfig_1 = analyticsPlugin_1.config;\r\n if (!_houseKeepingNamespace) {\r\n _houseKeepingNamespace = mergeEvtNamespace(_evtNamespace, _core[STR_EVT_NAMESPACE /* @min:%2eevtNamespace */] && _core[STR_EVT_NAMESPACE /* @min:%2eevtNamespace */]());\r\n }\r\n // Will be recalled if any referenced config properties change\r\n _addUnloadHook(onConfigChange(_config, function () {\r\n // As we could get recalled, remove any previously registered event handlers first\r\n _removePageEventHandlers();\r\n var excludePageUnloadEvents = theConfig_1.disablePageUnloadEvents;\r\n if (!theConfig_1.disableFlushOnBeforeUnload) {\r\n // Hook the unload event for the document, window and body to ensure that the client events are flushed to the server\r\n // As just hooking the window does not always fire (on chrome) for page navigation's.\r\n if (addPageUnloadEventListener(performHousekeeping_1, excludePageUnloadEvents, _houseKeepingNamespace)) {\r\n added_1 = true;\r\n }\r\n // We also need to hook the pagehide and visibilitychange events as not all versions of Safari support load/unload events.\r\n if (addPageHideEventListener(performHousekeeping_1, excludePageUnloadEvents, _houseKeepingNamespace)) {\r\n added_1 = true;\r\n }\r\n // A reactNative app may not have a window and therefore the beforeunload/pagehide events -- so don't\r\n // log the failure in this case\r\n if (!added_1 && !isReactNative()) {\r\n _throwInternal(analyticsPlugin_1.core.logger, 1 /* eLoggingSeverity.CRITICAL */, 19 /* _eInternalMessageId.FailedToAddHandlerForOnBeforeUnload */, \"Could not add handler for beforeunload and pagehide\");\r\n }\r\n }\r\n if (!added_1 && !theConfig_1.disableFlushOnUnload) {\r\n // If we didn't add the normal set then attempt to add the pagehide and visibilitychange only\r\n addPageHideEventListener(performHousekeeping_1, excludePageUnloadEvents, _houseKeepingNamespace);\r\n }\r\n }));\r\n }\r\n };\r\n _self.getSender = function () {\r\n return _sender;\r\n };\r\n _self.unload = function (isAsync, unloadComplete, cbTimeout) {\r\n var unloadDone = false;\r\n var result;\r\n if (isAsync && !unloadComplete) {\r\n result = createPromise(function (resolve) {\r\n // Set the callback to the promise resolve callback\r\n unloadComplete = resolve;\r\n });\r\n }\r\n function _unloadCallback(unloadState) {\r\n if (!unloadDone) {\r\n unloadDone = true;\r\n _initDefaults();\r\n unloadComplete && unloadComplete(unloadState);\r\n }\r\n }\r\n _self[_DYN_ONUNLOAD_FLUSH /* @min:%2eonunloadFlush */](isAsync);\r\n _removePageEventHandlers();\r\n _core.unload && _core.unload(isAsync, _unloadCallback, cbTimeout);\r\n return result;\r\n };\r\n proxyFunctions(_self, _analyticsPlugin, [\r\n STR_GET_COOKIE_MGR,\r\n STR_TRACK_EVENT,\r\n STR_TRACK_PAGE_VIEW,\r\n \"trackPageViewPerformance\",\r\n STR_TRACK_EXCEPTION,\r\n \"_onerror\",\r\n STR_TRACK_TRACE,\r\n STR_TRACK_METRIC,\r\n STR_START_TRACK_PAGE,\r\n STR_STOP_TRACK_PAGE,\r\n STR_START_TRACK_EVENT,\r\n STR_STOP_TRACK_EVENT\r\n ]);\r\n proxyFunctions(_self, _getCurrentDependencies, [\r\n STR_TRACK_DEPENDENCY_DATA,\r\n \"addDependencyListener\",\r\n \"addDependencyInitializer\"\r\n ]);\r\n proxyFunctions(_self, _core, [\r\n STR_ADD_TELEMETRY_INITIALIZER,\r\n STR_POLL_INTERNAL_LOGS,\r\n \"stopPollingInternalLogs\",\r\n STR_GET_PLUGIN,\r\n \"addPlugin\",\r\n STR_EVT_NAMESPACE,\r\n \"addUnloadCb\",\r\n \"getTraceCtx\",\r\n \"updateCfg\",\r\n \"onCfgChange\"\r\n ]);\r\n proxyFunctions(_self, function () {\r\n var context = properties[_DYN_CONTEXT /* @min:%2econtext */];\r\n return context ? context.user : null;\r\n }, [\r\n STR_SET_AUTHENTICATED_USER_CONTEXT,\r\n STR_CLEAR_AUTHENTICATED_USER_CONTEXT\r\n ]);\r\n // Using a function to support the dynamic adding / removal of plugins, so this will always return the current value\r\n function _getCurrentDependencies() {\r\n return dependencies;\r\n }\r\n function _initDefaults() {\r\n _evtNamespace = createUniqueNamespace(\"AISKU\");\r\n _houseKeepingNamespace = null;\r\n dependencies = null;\r\n properties = null;\r\n _sender = null;\r\n _snippetVersion = null;\r\n }\r\n function _removePageEventHandlers() {\r\n // Remove any registered event handlers\r\n if (_houseKeepingNamespace) {\r\n removePageUnloadEventListener(null, _houseKeepingNamespace);\r\n removePageHideEventListener(null, _houseKeepingNamespace);\r\n }\r\n }\r\n function _addUnloadHook(hooks) {\r\n _core.addUnloadHook(hooks);\r\n }\r\n });\r\n }\r\n // Analytics Plugin\r\n /**\r\n * Get the current cookie manager for this instance\r\n */\r\n AppInsightsSku.prototype.getCookieMgr = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Log a user action or other occurrence.\r\n * @param event\r\n * @param [customProperties]\r\n * @memberof Initialization\r\n */\r\n AppInsightsSku.prototype.trackEvent = function (event, customProperties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Logs that a page, or similar container was displayed to the user.\r\n * @param pageView\r\n * @memberof Initialization\r\n */\r\n AppInsightsSku.prototype.trackPageView = function (pageView) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Log a bag of performance information via the customProperties field.\r\n * @param pageViewPerformance\r\n * @memberof Initialization\r\n */\r\n AppInsightsSku.prototype.trackPageViewPerformance = function (pageViewPerformance) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Log an exception that you have caught.\r\n * @param exception\r\n * @param } customProperties Additional data used to filter pages and metrics in the portal. Defaults to empty.\r\n * @memberof Initialization\r\n */\r\n AppInsightsSku.prototype.trackException = function (exception, customProperties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Manually send uncaught exception telemetry. This method is automatically triggered\r\n * on a window.onerror event.\r\n * @param exception\r\n * @memberof Initialization\r\n */\r\n AppInsightsSku.prototype._onerror = function (exception) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Log a diagnostic scenario such entering or leaving a function.\r\n * @param trace\r\n * @param [customProperties]\r\n * @memberof Initialization\r\n */\r\n AppInsightsSku.prototype.trackTrace = function (trace, customProperties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Log a numeric value that is not associated with a specific event. Typically used\r\n * to send regular reports of performance indicators.\r\n *\r\n * To send a single measurement, just use the `name` and `average` fields\r\n * of {@link IMetricTelemetry}.\r\n *\r\n * If you take measurements frequently, you can reduce the telemetry bandwidth by\r\n * aggregating multiple measurements and sending the resulting average and modifying\r\n * the `sampleCount` field of {@link IMetricTelemetry}.\r\n * @param metric - input object argument. Only `name` and `average` are mandatory.\r\n * @param [customProperties]\r\n * @memberof Initialization\r\n */\r\n AppInsightsSku.prototype.trackMetric = function (metric, customProperties) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\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 */\r\n AppInsightsSku.prototype.startTrackPage = function (name) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\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 */\r\n AppInsightsSku.prototype.stopTrackPage = function (name, url, customProperties, measurements) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AppInsightsSku.prototype.startTrackEvent = function (name) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\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 */\r\n AppInsightsSku.prototype.stopTrackEvent = function (name, properties, measurements) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AppInsightsSku.prototype.addTelemetryInitializer = function (telemetryInitializer) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n // Properties Plugin\r\n /**\r\n * Set the authenticated user id and the account id. Used for identifying a specific signed-in user. Parameters must not contain whitespace or ,;=|\r\n *\r\n * The method will only set the `authenticatedUserId` and `accountId` in the current page view. To set them for the whole session, you should set `storeInCookie = true`\r\n * @param authenticatedUserId\r\n * @param [accountId]\r\n * @param [storeInCookie=false]\r\n */\r\n AppInsightsSku.prototype.setAuthenticatedUserContext = function (authenticatedUserId, accountId, storeInCookie) {\r\n if (storeInCookie === void 0) { storeInCookie = false; }\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Clears the authenticated user id and account id. The associated cookie is cleared, if present.\r\n */\r\n AppInsightsSku.prototype.clearAuthenticatedUserContext = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n // Dependencies Plugin\r\n /**\r\n * Log a dependency call (e.g. ajax)\r\n * @param dependency\r\n * @memberof Initialization\r\n */\r\n AppInsightsSku.prototype.trackDependencyData = function (dependency) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n // Misc\r\n /**\r\n * Attempt to flush data immediately; If executing asynchronously (the default) and\r\n * you DO NOT pass a callback function then a [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * will be returned which will resolve once the flush is complete. The actual implementation of the `IPromise`\r\n * will be a native Promise (if supported) or the default as supplied by [ts-async library](https://github.com/nevware21/ts-async)\r\n * @param async - send data asynchronously when true\r\n * @param callBack - if specified, notify caller when send is complete, the channel should return true to indicate to the caller that it will be called.\r\n * If the caller doesn't return true the caller should assume that it may never be called.\r\n * @returns - If a callback is provided `true` to indicate that callback will be called after the flush is complete otherwise the caller\r\n * should assume that any provided callback will never be called, Nothing or if occurring asynchronously a\r\n * [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) which will be resolved once the unload is complete,\r\n * the [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html) will only be returned when no callback is provided\r\n * and async is true.\r\n */\r\n AppInsightsSku.prototype.flush = function (async, callBack) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Manually trigger an immediate send of all telemetry still in the buffer using beacon Sender.\r\n * Fall back to xhr sender if beacon is not supported.\r\n * @param [async=true]\r\n * @memberof Initialization\r\n */\r\n AppInsightsSku.prototype.onunloadFlush = function (async) {\r\n if (async === void 0) { async = true; }\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Initialize this instance of ApplicationInsights\r\n * @returns {IApplicationInsights}\r\n * @memberof Initialization\r\n * @param legacyMode - MUST always be false, it is no longer supported from v3.x onwards\r\n */\r\n AppInsightsSku.prototype.loadAppInsights = function (legacyMode, logger, notificationManager) {\r\n if (legacyMode === void 0) { legacyMode = false; }\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Overwrite the lazy loaded fields of global window snippet to contain the\r\n * actual initialized API methods\r\n * @param snippet\r\n * @memberof Initialization\r\n */\r\n AppInsightsSku.prototype.updateSnippetDefinitions = function (snippet) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Call any functions that were queued before the main script was loaded\r\n * @memberof Initialization\r\n */\r\n AppInsightsSku.prototype.emptyQueue = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AppInsightsSku.prototype.pollInternalLogs = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AppInsightsSku.prototype.stopPollingInternalLogs = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AppInsightsSku.prototype.addHousekeepingBeforeUnload = function (appInsightsInstance) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n AppInsightsSku.prototype.getSender = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Unload and Tear down the SDK and any initialized plugins, after calling this the SDK will be considered\r\n * to be un-initialized and non-operational, re-initializing the SDK should only be attempted if the previous\r\n * unload call return `true` stating that all plugins reported that they also unloaded, the recommended\r\n * approach is to create a new instance and initialize that instance.\r\n * This is due to possible unexpected side effects caused by plugins not supporting unload / teardown, unable\r\n * to successfully remove any global references or they may just be completing the unload process asynchronously.\r\n * If you pass isAsync as true and do not provide\r\n * If you pass isAsync as `true` (also the default) and DO NOT pass a callback function then an [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * will be returned which will resolve once the unload is complete. The actual implementation of the `IPromise`\r\n * will be a native Promise (if supported) or the default as supplied by [ts-async library](https://github.com/nevware21/ts-async)\r\n * @param isAsync - Can the unload be performed asynchronously (default)\r\n * @param unloadComplete - An optional callback that will be called once the unload has completed\r\n * @param cbTimeout - An optional timeout to wait for any flush operations to complete before proceeding with the\r\n * unload. Defaults to 5 seconds.\r\n * @return Nothing or if occurring asynchronously a [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * which will be resolved once the unload is complete, the [IPromise](https://nevware21.github.io/ts-async/typedoc/interfaces/IPromise.html)\r\n * will only be returned when no callback is provided and isAsync is true\r\n */\r\n AppInsightsSku.prototype.unload = function (isAsync, unloadComplete, cbTimeout) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n AppInsightsSku.prototype.getPlugin = function (pluginIdentifier) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Add a new plugin to the installation\r\n * @param plugin - The new plugin to add\r\n * @param replaceExisting - should any existing plugin be replaced, default is false\r\n * @param doAsync - Should the add be performed asynchronously\r\n * @param addCb - [Optional] callback to call after the plugin has been added\r\n */\r\n AppInsightsSku.prototype.addPlugin = function (plugin, replaceExisting, doAsync, addCb) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Update the configuration used and broadcast the changes to all loaded plugins\r\n * @param newConfig - The new configuration is apply\r\n * @param mergeExisting - Should the new configuration merge with the existing or just replace it. Default is to merge.\r\n */\r\n AppInsightsSku.prototype.updateCfg = function (newConfig, mergeExisting) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Returns the unique event namespace that should be used\r\n */\r\n AppInsightsSku.prototype.evtNamespace = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Add an unload handler that will be called when the SDK is being unloaded\r\n * @param handler - the handler\r\n */\r\n AppInsightsSku.prototype.addUnloadCb = function (handler) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n };\r\n /**\r\n * Add an ajax listener which is called just prior to the request being sent and before the correlation headers are added, to allow you\r\n * to access the headers and modify the values used to generate the distributed tracing correlation headers. (added in v2.8.4)\r\n * @param dependencyListener - The Telemetry Initializer function\r\n * @returns - A IDependencyListenerHandler to enable the initializer to be removed\r\n */\r\n AppInsightsSku.prototype.addDependencyListener = function (dependencyListener) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\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 */\r\n AppInsightsSku.prototype.addDependencyInitializer = function (dependencyInitializer) {\r\n return null;\r\n };\r\n /**\r\n * Gets the current distributed trace context for this instance if available\r\n */\r\n AppInsightsSku.prototype.getTraceCtx = function () {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n /**\r\n * Watches and tracks changes for accesses to the current config, and if the accessed config changes the\r\n * handler will be recalled.\r\n * @param handler\r\n * @returns A watcher handler instance that can be used to remove itself when being unloaded\r\n */\r\n AppInsightsSku.prototype.onCfgChange = function (handler) {\r\n // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging\r\n return null;\r\n };\r\n return AppInsightsSku;\r\n}());\r\nexport { AppInsightsSku };\r\n// tslint:disable-next-line\r\nexport function _findSdkSourceFile() {\r\n if (_internalSdkSrc) {\r\n // Use the cached value\r\n return _internalSdkSrc;\r\n }\r\n var sdkSrc = null;\r\n var isModule = false;\r\n var cdns = [\r\n \"://js.monitor.azure.com/\",\r\n \"://az416426.vo.msecnd.net/\"\r\n ];\r\n try {\r\n // Try and determine whether the sdk is being loaded from the CDN\r\n // currentScript is only valid during initial processing\r\n var scrpt = (document || {}).currentScript;\r\n if (scrpt) {\r\n sdkSrc = scrpt.src;\r\n // } else {\r\n // // We need to update to at least typescript 2.9 for this to work :-(\r\n // // Leaving as a stub for now so after we upgrade this breadcrumb is available\r\n // let meta = import.meta;\r\n // sdkSrc = (meta || {}).url;\r\n // isModule = true;\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n if (sdkSrc) {\r\n try {\r\n var url_1 = sdkSrc.toLowerCase();\r\n if (url_1) {\r\n var src_1 = \"\";\r\n arrForEach(cdns, function (value, idx) {\r\n if (strIndexOf(url_1, value) !== -1) {\r\n src_1 = \"cdn\" + (idx + 1);\r\n if (strIndexOf(url_1, \"/scripts/\") === -1) {\r\n if (strIndexOf(url_1, \"/next/\") !== -1) {\r\n src_1 += \"-next\";\r\n }\r\n else if (strIndexOf(url_1, \"/beta/\") !== -1) {\r\n src_1 += \"-beta\";\r\n }\r\n }\r\n _internalSdkSrc = src_1 + (isModule ? \".mod\" : \"\");\r\n return -1;\r\n }\r\n });\r\n }\r\n }\r\n catch (e) {\r\n // eslint-disable-next-line no-empty\r\n }\r\n // Cache the found value so we don't have to look it up again\r\n _internalSdkSrc = sdkSrc;\r\n }\r\n return _internalSdkSrc;\r\n}\r\n//# sourceMappingURL=AISku.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n// ###################################################################################################################################################\r\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 ###\r\n// ###################################################################################################################################################\r\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)\r\n// as when using \"short\" named values from here they will be will be minified smaller than the SdkCoreNames[eSdkCoreNames.xxxx] value.\r\nvar _AUTHENTICATED_USER_CONTEXT = \"AuthenticatedUserContext\";\r\nvar _TRACK = \"track\";\r\nexport var STR_EMPTY = \"\";\r\nexport var STR_SNIPPET = \"snippet\";\r\nexport var STR_GET_COOKIE_MGR = \"getCookieMgr\";\r\nexport var STR_START_TRACK_PAGE = \"startTrackPage\";\r\nexport var STR_STOP_TRACK_PAGE = \"stopTrackPage\";\r\nexport var STR_FLUSH = \"flush\";\r\nexport var STR_START_TRACK_EVENT = \"startTrackEvent\";\r\nexport var STR_STOP_TRACK_EVENT = \"stopTrackEvent\";\r\nexport var STR_ADD_TELEMETRY_INITIALIZER = \"addTelemetryInitializer\";\r\nexport var STR_ADD_TELEMETRY_INITIALIZERS = STR_ADD_TELEMETRY_INITIALIZER + \"s\";\r\nexport var STR_POLL_INTERNAL_LOGS = \"pollInternalLogs\";\r\nexport var STR_GET_PLUGIN = \"getPlugin\";\r\nexport var STR_EVT_NAMESPACE = \"evtNamespace\";\r\nexport var STR_TRACK_EVENT = _TRACK + \"Event\";\r\nexport var STR_TRACK_TRACE = _TRACK + \"Trace\";\r\nexport var STR_TRACK_METRIC = _TRACK + \"Metric\";\r\nexport var STR_TRACK_PAGE_VIEW = _TRACK + \"PageView\";\r\nexport var STR_TRACK_EXCEPTION = _TRACK + \"Exception\";\r\nexport var STR_TRACK_DEPENDENCY_DATA = _TRACK + \"DependencyData\";\r\nexport var STR_SET_AUTHENTICATED_USER_CONTEXT = \"set\" + _AUTHENTICATED_USER_CONTEXT;\r\nexport var STR_CLEAR_AUTHENTICATED_USER_CONTEXT = \"clear\" + _AUTHENTICATED_USER_CONTEXT;\r\n//# sourceMappingURL=InternalConstants.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n// @skip-file-minify\r\n// ##############################################################\r\n// AUTO GENERATED FILE: This file is Auto Generated during build.\r\n// ##############################################################\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!\r\n// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\nexport var _DYN_VERSION = \"version\"; // Count: 6\r\nexport var _DYN_QUEUE = \"queue\"; // Count: 6\r\nexport var _DYN_CONNECTION_STRING = \"connectionString\"; // Count: 4\r\nexport var _DYN_ENDPOINT_URL = \"endpointUrl\"; // Count: 3\r\nexport var _DYN_INSTRUMENTATION_KEY = \"instrumentationKey\"; // Count: 3\r\nexport var _DYN_DISABLE_IKEY_DEPRECA0 = \"disableIkeyDeprecationMessage\"; // Count: 2\r\nexport var _DYN_ONUNLOAD_FLUSH = \"onunloadFlush\"; // Count: 6\r\nexport var _DYN_CONTEXT = \"context\"; // Count: 5\r\nexport var _DYN_ADD_HOUSEKEEPING_BEF1 = \"addHousekeepingBeforeUnload\"; // Count: 2\r\nexport var _DYN_UPDATE_SNIPPET_DEFIN2 = \"updateSnippetDefinitions\"; // Count: 2\r\n//# sourceMappingURL=__DynamicConstants.js.map","import { ReactPlugin } from \"@microsoft/applicationinsights-react-js\";\nimport { ApplicationInsights } from \"@microsoft/applicationinsights-web\";\nimport { createBrowserHistory } from \"history\";\n\nconst browserHistory = createBrowserHistory({ basename: \"\" });\nconst reactPlugin = new ReactPlugin();\nconst appInsights = new ApplicationInsights({\n config: {\n instrumentationKey: process.env.REACT_APP_APPINSIGHTS_INSTRUMENTATION_KEY,\n extensions: [reactPlugin],\n extensionConfig: {\n [reactPlugin.identifier]: { history: browserHistory },\n },\n },\n});\n\nappInsights.loadAppInsights();\n\nexport { appInsights, reactPlugin };\n","import { ReactSession } from \"react-client-session\";\n\nimport { encrypt, getHeaders, responseFormatter } from \"./utilService\";\n\nconst BASE_URL = process.env.REACT_APP_BASE_URL;\n\n//Fetch the compare table data\nexport const getComapareList = async (params) => {\n const apiResponse = await fetch(BASE_URL + \"/alternative/v4\", {\n headers: getHeaders(),\n body: JSON.stringify({\n userId: encrypt(ReactSession.get(\"email\")),\n ...params,\n }),\n method: \"POST\",\n });\n\n return responseFormatter(apiResponse);\n};\n\n//search the refineFilter data\nexport const getRefineFilterData = async (params) => {\n const apiResponse = await fetch(BASE_URL + \"/refinefilter\", {\n headers: getHeaders(),\n body: JSON.stringify({\n userId: encrypt(ReactSession.get(\"email\")),\n ...params,\n }),\n method: \"POST\",\n });\n\n return responseFormatter(apiResponse);\n};\n\nexport const getComparisonDetails = async (params) => {\n const apiResponse = await fetch(BASE_URL + \"/alternative/detailsV6\", {\n headers: getHeaders(),\n body: JSON.stringify({\n userId: encrypt(ReactSession.get(\"email\")),\n ...params,\n }),\n method: \"POST\",\n });\n\n return responseFormatter(apiResponse);\n};\nexport const getComparisonDetailsCost = async (params) => {\n const apiResponse = await fetch(BASE_URL + \"/alternative/detailsCost\", {\n headers: getHeaders(),\n body: JSON.stringify({\n userId: encrypt(ReactSession.get(\"email\")),\n ...params,\n }),\n method: \"POST\",\n });\n\n return responseFormatter(apiResponse);\n};\n\nexport const getMatchAverageCSV = async (params) => {\n const apiResponse = await fetch(BASE_URL + \"/downloadcsvV1\", {\n headers: getHeaders(),\n body: JSON.stringify({\n userId: encrypt(ReactSession.get(\"email\")),\n ...params,\n }),\n method: \"POST\",\n });\n\n return responseFormatter(apiResponse);\n};\n\nexport const getCapacityCSV = async (params) => {\n const apiResponse = await fetch(BASE_URL + \"/capacitydownloadcsv\", {\n headers: getHeaders(),\n body: JSON.stringify({\n userId: encrypt(ReactSession.get(\"email\")),\n ...params,\n }),\n method: \"POST\",\n });\n\n return responseFormatter(apiResponse);\n};\n\nexport const getSKUDetails = async (params) => {\n const apiResponse = await fetch(\n BASE_URL + \"/alternative/details/plantlevel/V3\",\n {\n headers: getHeaders(),\n body: JSON.stringify({\n userId: encrypt(ReactSession.get(\"email\")),\n ...params,\n }),\n method: \"POST\",\n }\n );\n\n return responseFormatter(apiResponse);\n};\n","import { ReactSession } from \"react-client-session\";\n\nimport { encrypt, getHeaders, responseFormatter } from \"./utilService\";\n\nconst BASE_URL = process.env.REACT_APP_BASE_URL;\n\nexport const getDashboardData = async () => {\n const apiResponse = await fetch(BASE_URL + \"/high_level_data\", {\n headers: getHeaders(),\n body: JSON.stringify({\n userId: encrypt(ReactSession.get(\"email\")),\n }),\n method: \"POST\",\n });\n\n return responseFormatter(apiResponse);\n};\n\n//Fetch the Recent searches data\nexport const getRecentSearchData = async () => {\n const apiResponse = await fetch(BASE_URL + \"/recent_search\", {\n headers: getHeaders(),\n body: JSON.stringify({\n userId: encrypt(ReactSession.get(\"email\")),\n }),\n method: \"POST\",\n });\n\n return responseFormatter(apiResponse);\n};\n\n//Fetch the Favorites searches data\nexport const getFavSearchData = async (params) => {\n const apiResponse = await fetch(BASE_URL + \"/favorite/read\", {\n headers: getHeaders(),\n body: JSON.stringify({\n ...params,\n userId: encrypt(ReactSession.get(\"email\")),\n }),\n method: \"POST\",\n });\n\n return responseFormatter(apiResponse);\n};\n\n//Add the Favorite searches\nexport const addFavSearch = async (params) => {\n const apiResponse = await fetch(BASE_URL + \"/favorite/write\", {\n headers: getHeaders(),\n body: JSON.stringify({\n ...params,\n userId: encrypt(ReactSession.get(\"email\")),\n }),\n method: \"POST\",\n });\n\n return responseFormatter(apiResponse);\n};\n\n//Delete the Favorite searches\nexport const deleteFavSearch = async (params) => {\n const apiResponse = await fetch(BASE_URL + \"/favorite/delete\", {\n headers: getHeaders(),\n body: JSON.stringify({\n ...params,\n userId: encrypt(ReactSession.get(\"email\")),\n }),\n method: \"POST\",\n });\n\n return responseFormatter(apiResponse);\n};\n\n//Delete the recent searches\nexport const deleteRecntSearch = async (params) => {\n const apiResponse = await fetch(BASE_URL + \"/recent_search_delete\", {\n headers: getHeaders(),\n body: JSON.stringify({\n ...params,\n userId: encrypt(ReactSession.get(\"email\")),\n }),\n method: \"POST\",\n });\n\n return responseFormatter(apiResponse);\n};\n\n//Delete the recent searches\nexport const checkUserInfo = async () => {\n const apiResponse = await fetch(BASE_URL + \"/check/userinfo\", {\n headers: getHeaders(),\n body: JSON.stringify({\n randomCode: \"d\",\n userId: encrypt(ReactSession.get(\"email\")),\n }),\n method: \"POST\",\n });\n\n return responseFormatter(apiResponse);\n};\n","import { ReactSession } from \"react-client-session\";\n\nimport { encrypt, getHeaders } from \"./utilService\";\n\nconst BASE_URL = process.env.REACT_APP_BASE_URL;\n\nexport const getDefaultFilterOptionsForSKU = async () => {\n const apiResponse = await fetch(BASE_URL + \"/default_api/v2\", {\n headers: getHeaders(),\n body: JSON.stringify({\n randomCode: \"d\",\n userId: encrypt(ReactSession.get(\"email\")),\n }),\n method: \"POST\",\n });\n\n if (!apiResponse.ok) {\n // logout\n if (apiResponse.status === 440) {\n sessionStorage.clear();\n window.location.reload();\n }\n\n return {\n success: false,\n data: null,\n error: {\n message: `An error has occured: ${apiResponse.status}`,\n },\n };\n }\n\n const data = await apiResponse.json();\n\n return {\n success: true,\n data: data,\n error: null,\n };\n};\n\nexport const getFilterOptionsForSKU = async (params) => {\n const apiResponse = await fetch(BASE_URL + \"/filter/v8\", {\n headers: getHeaders(),\n body: JSON.stringify({\n brand: params.brand || null,\n category: params.category || null,\n centerRegion: params.centerRegion || null,\n country: params.country || null,\n division: params.division || null,\n form: params.form || null,\n product: params.product || null,\n subSector: params.subSector || null,\n subregion: params.subregion || null,\n userId: encrypt(ReactSession.get(\"email\")),\n }),\n method: \"POST\",\n });\n\n if (!apiResponse.ok) {\n // logout\n if (apiResponse.status === 440) {\n sessionStorage.clear();\n window.location.reload();\n }\n\n return {\n success: false,\n data: null,\n error: {\n message: `An error has occured: ${apiResponse.status}`,\n },\n };\n }\n\n const data = await apiResponse.json();\n\n return {\n success: true,\n data: data,\n error: null,\n };\n};\n\nexport const getFilterOptionsForSKUBySearch = async (params) => {\n const apiResponse = await fetch(BASE_URL + \"/onsearch\", {\n headers: getHeaders(),\n body: JSON.stringify({\n brand: \"\",\n category: \"\",\n centerRegion: \"\",\n country: \"\",\n division: \"\",\n form: \"\",\n sku: \"\",\n subSector: \"\",\n subregion: \"\",\n userId: encrypt(ReactSession.get(\"email\")),\n ...params,\n }),\n method: \"POST\",\n });\n\n if (!apiResponse.ok) {\n // logout\n if (apiResponse.status === 440) {\n sessionStorage.clear();\n window.location.reload();\n }\n\n return {\n success: false,\n data: null,\n error: {\n message: `An error has occured: ${apiResponse.status}`,\n },\n };\n }\n\n const data = await apiResponse.json();\n\n return {\n success: true,\n data: data,\n error: null,\n };\n};\n\nexport const getDefaultFilterOptionsForDC = async () => {\n const apiResponse = await fetch(BASE_URL + \"/plant/default2\", {\n headers: getHeaders(),\n body: JSON.stringify({\n randomCode: \"d\",\n userId: encrypt(ReactSession.get(\"email\")),\n }),\n method: \"POST\",\n });\n\n if (!apiResponse.ok) {\n // logout\n if (apiResponse.status === 440) {\n sessionStorage.clear();\n window.location.reload();\n }\n\n return {\n success: false,\n data: null,\n error: {\n message: `An error has occured: ${apiResponse.status}`,\n },\n };\n }\n\n const data = await apiResponse.json();\n\n return {\n success: true,\n data: data,\n error: null,\n };\n};\n\nexport const getFilterOptionsForDC = async (params) => {\n const apiResponse = await fetch(BASE_URL + \"/plant/filterv1\", {\n headers: getHeaders(),\n body: JSON.stringify({\n centerRegion: params.centerRegion || null,\n country: params.country || null,\n distributionCenter: params.distributionCenter || null,\n subregion: params.subregion || null,\n userId: encrypt(ReactSession.get(\"email\")),\n ...params,\n }),\n method: \"POST\",\n });\n\n if (!apiResponse.ok) {\n // logout\n if (apiResponse.status === 440) {\n sessionStorage.clear();\n window.location.reload();\n }\n\n return {\n success: false,\n data: null,\n error: {\n message: `An error has occured: ${apiResponse.status}`,\n },\n };\n }\n\n const data = await apiResponse.json();\n\n return {\n success: true,\n data: data,\n error: null,\n };\n};\n","import { ReactSession } from \"react-client-session\";\n\nimport { encrypt, getHeaders, responseFormatter } from \"./utilService\";\nconst BASE_URL = process.env.REACT_APP_BASE_URL;\n\n//Fetch the simulation data\nexport const getSimulationData = async (params) => {\n const apiResponse = await fetch(BASE_URL + \"/simulationrmdata\", {\n headers: getHeaders(),\n body: JSON.stringify({\n userId: encrypt(ReactSession.get(\"email\")),\n ...params,\n }),\n method: \"POST\",\n });\n\n return responseFormatter(apiResponse);\n\n // return new Promise((resolve, reject) => {\n // setTimeout(() => {\n // resolve({\n // success: true,\n // data: stimulateData,\n // error: null,\n // });\n // }, 2000);\n // });\n};\n\n//Fetch all add modal data\nexport const getAddItemsData = async (params) => {\n const apiResponse = await fetch(BASE_URL + \"/additemsdefault\", {\n headers: getHeaders(),\n body: JSON.stringify({\n ...params,\n }),\n method: \"POST\",\n });\n\n return responseFormatter(apiResponse);\n};\n\nexport const getSourcingUnits = async (params) => {\n const apiResponse = await fetch(BASE_URL + \"/findsimulatealternative\", {\n headers: getHeaders(),\n body: JSON.stringify({\n userId: encrypt(ReactSession.get(\"email\")),\n ...params,\n }),\n method: \"POST\",\n });\n\n return responseFormatter(apiResponse);\n};\n\nexport const getPlantDetails = async (params) => {\n const apiResponse = await fetch(BASE_URL + \"/simulationplantdetails\", {\n headers: getHeaders(),\n body: JSON.stringify({\n userId: encrypt(ReactSession.get(\"email\")),\n ...params,\n }),\n method: \"POST\",\n });\n\n return responseFormatter(apiResponse);\n};\n\nexport const getSimulateCSV = async (params) => {\n const apiResponse = await fetch(BASE_URL + \"/simulatedownload\", {\n headers: getHeaders(),\n body: JSON.stringify({\n userId: encrypt(ReactSession.get(\"email\")),\n ...params,\n }),\n method: \"POST\",\n });\n\n return responseFormatter(apiResponse);\n};\n","import CryptoJS from \"crypto-js\";\nimport Papa from \"papaparse\";\nimport { ReactSession } from \"react-client-session\";\n\nimport { msalConfig } from \"../sso/authConfig\";\n\nconst BASE_URL = process.env.REACT_APP_BASE_URL;\n\nexport const encrypt = (string) => {\n const key1 = \"AAAAAAAAAAAAAAAA\";\n const key2 = \"BBBBBBBBBBBBBBBB\";\n\n const key = CryptoJS.enc.Utf8.parse(key1);\n const iv = CryptoJS.enc.Utf8.parse(key2);\n\n const encrypted = CryptoJS.AES.encrypt(string, key, {\n iv: iv,\n mode: CryptoJS.mode.CBC,\n });\n return encrypted.toString();\n};\n\nexport const getAccessToken = () => {\n const msalTokenKeys = JSON.parse(\n sessionStorage.getItem(\"msal.token.keys.\" + msalConfig.auth.clientId) ||\n \"{}\"\n );\n const accessToken = msalTokenKeys?.accessToken?.[0];\n const accessTokenValues = JSON.parse(\n sessionStorage.getItem(accessToken) || \"{}\"\n );\n\n return accessTokenValues.secret || \"\";\n};\n\nexport const getUserDetails = () => {\n const msalTokenKeys = JSON.parse(\n sessionStorage.getItem(\"msal.token.keys.\" + msalConfig.auth.clientId) ||\n \"{}\"\n );\n\n const accessToken = msalTokenKeys?.accessToken?.[0];\n const accessTokenValues = JSON.parse(\n sessionStorage.getItem(accessToken) || \"{}\"\n );\n\n const idToken =\n accessTokenValues.homeAccountId +\n \"-\" +\n accessTokenValues.environment +\n \"-\" +\n accessTokenValues.realm;\n const idTokenValues = JSON.parse(sessionStorage.getItem(idToken) || \"{}\");\n\n return {\n name: idTokenValues.name || \"\",\n email: idTokenValues.username || \"\",\n role: idTokenValues.idTokenClaims.roles[0] || \"\",\n };\n};\n\nexport const getHeaders = () => {\n return {\n authorization: \"Bearer \" + getAccessToken(),\n from: encrypt(ReactSession.get(\"email\")),\n to: ReactSession.get(\"role\"),\n \"x-frame-options\": `allow-from ${BASE_URL}`,\n \"Content-Type\": \"application/json\",\n };\n};\n\nexport const responseFormatter = async (apiResponse) => {\n if (!apiResponse.ok) {\n // logout\n if (apiResponse.status === 440) {\n sessionStorage.clear();\n window.location.reload();\n }\n\n return {\n success: false,\n data: null,\n error: {\n message: `An error has occured: ${apiResponse.status}`,\n },\n };\n }\n\n const data = await apiResponse.json();\n\n return {\n success: true,\n data: data,\n error: null,\n };\n};\n\nexport const getUTFOptions = () => {\n const currentYear = new Date().getFullYear();\n const currentMonth = new Date().getMonth();\n const dataCurrentYear = [];\n const dataMiddleYears = [];\n\n for (let i = currentMonth + 1; i > 0; i--) {\n dataCurrentYear.push({\n label: `${i} ${currentYear}`,\n value: `${i} ${currentYear}`,\n });\n }\n\n for (let i = currentYear - 1; i > 2021; i--) {\n for (let j = 12; j > 0; j--) {\n dataMiddleYears.push({\n label: `${j} ${i}`,\n value: `${j} ${i}`,\n });\n }\n }\n\n const data2021 = [\n { label: \"12 2021\", value: \"12 2021\" },\n { label: \"11 2021\", value: \"11 2021\" },\n { label: \"10 2021\", value: \"10 2021\" },\n { label: \"9 2021\", value: \"9 2021\" },\n { label: \"8 2021\", value: \"8 2021\" },\n ];\n\n return [...dataCurrentYear, ...dataMiddleYears, ...data2021];\n};\n\nexport const downloadCSV = (data, filename) => {\n const csvData = Papa.unparse(data);\n const blob = new Blob([csvData], { type: \"text/csv;charset=utf-8;\" });\n const url = window.URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = url;\n a.download = filename + \".csv\";\n document.body.appendChild(a);\n a.click();\n document.body.removeChild(a);\n};\n\nexport const convertToCurrencyFormat = (value, format = \"EUR\") => {\n if (isNaN(value)) {\n return value;\n }\n\n return new Intl.NumberFormat(navigator.language, {\n style: \"currency\",\n currency: format,\n }).format(value);\n};\n\nexport const isPilot = () => {\n return true;\n return window.location.pathname.startsWith(\"/pilot/\");\n};\n\n// to get the url for pilot\nexport const getPathPrefix = (pathname) => {\n if (window.location.pathname.startsWith(\"/pilot/\")) {\n return \"/pilot\" + pathname;\n }\n\n return pathname;\n};\n\nexport const formatDays = (numDays) => {\n const years = Math.floor(numDays / 365);\n const remainingDaysWithoutYears = numDays % 365;\n const weeks = Math.floor(remainingDaysWithoutYears / 7);\n const remainingDays = remainingDaysWithoutYears % 7;\n\n let result = '';\n\n if (years > 0) {\n result += `${years} year${years > 1 ? 's' : ''} `;\n }\n\n if (weeks > 0) {\n result += `${weeks} week${weeks > 1 ? 's' : ''} `;\n }\n\n if (remainingDays > 0) {\n result += `${remainingDays} day${remainingDays > 1 ? 's' : ''}`;\n }\n\n return result.trim();\n}\n\nexport function removeDuplicates(array, property) {\n const seen = new Set();\n return array.filter(obj => {\n const propertyValue = obj[property];\n if (!seen.has(propertyValue)) {\n seen.add(propertyValue);\n return true;\n }\n return false;\n });\n}\n\n\nexport function alterateAlternativeResult(data) {\n return data.reduce((acc, obj) => {\n let existingEntry = acc.find(entry => (entry.PlantCode === obj.PlantCode) && entry.PlantName === obj.PlantName);\n\n if (existingEntry) {\n existingEntry.MatchBrand.push(obj.MatchBrand);\n } else {\n acc.push({ ...obj, MatchBrand: [obj.MatchBrand] });\n }\n\n return acc;\n }, []);\n}","export const msalConfig = {\n auth: {\n clientId: process.env.REACT_APP_SSO_CLIENT_ID,\n authority: `https://login.microsoftonline.com/${process.env.REACT_APP_SSO_TENANT_ID}/`, //\"Enter_the_Cloud_Instance_Id_Here/Enter_the_Tenant_Info_Here\", // This is a URL (e.g. https://login.microsoftonline.com/{your tenant ID})\n redirectUri: process.env.REACT_APP_SSO_REDIRECT_URI, //\"Enter_the_Redirect_Uri_Here\",\n },\n cache: {\n cacheLocation: \"sessionStorage\", // This configures where your cache will be stored\n storeAuthStateInCookie: false, // Set this to \"true\" if you are having issues on IE11 or Edge\n },\n};\n\n// Add scopes here for ID token to be used at Microsoft identity platform endpoints.\nexport const loginRequest = {\n scopes: [\"User.Read\"],\n};\n\n// Add the endpoints here for Microsoft Graph API services you'd like to use.\nexport const graphConfig = {\n graphMeEndpoint: \"https://graph.microsoft.com/v1.0/me\",\n};\n","import { inputToRGB, rgbToHex, rgbToHsv } from '@ctrl/tinycolor';\nvar hueStep = 2; // 色相阶梯\n\nvar saturationStep = 0.16; // 饱和度阶梯,浅色部分\n\nvar saturationStep2 = 0.05; // 饱和度阶梯,深色部分\n\nvar brightnessStep1 = 0.05; // 亮度阶梯,浅色部分\n\nvar brightnessStep2 = 0.15; // 亮度阶梯,深色部分\n\nvar lightColorCount = 5; // 浅色数量,主色上\n\nvar darkColorCount = 4; // 深色数量,主色下\n// 暗色主题颜色映射关系表\n\nvar darkColorMap = [{\n index: 7,\n opacity: 0.15\n}, {\n index: 6,\n opacity: 0.25\n}, {\n index: 5,\n opacity: 0.3\n}, {\n index: 5,\n opacity: 0.45\n}, {\n index: 5,\n opacity: 0.65\n}, {\n index: 5,\n opacity: 0.85\n}, {\n index: 4,\n opacity: 0.9\n}, {\n index: 3,\n opacity: 0.95\n}, {\n index: 2,\n opacity: 0.97\n}, {\n index: 1,\n opacity: 0.98\n}];\n\n// Wrapper function ported from TinyColor.prototype.toHsv\n// Keep it here because of `hsv.h * 360`\nfunction toHsv(_ref) {\n var r = _ref.r,\n g = _ref.g,\n b = _ref.b;\n var hsv = rgbToHsv(r, g, b);\n return {\n h: hsv.h * 360,\n s: hsv.s,\n v: hsv.v\n };\n} // Wrapper function ported from TinyColor.prototype.toHexString\n// Keep it here because of the prefix `#`\n\n\nfunction toHex(_ref2) {\n var r = _ref2.r,\n g = _ref2.g,\n b = _ref2.b;\n return \"#\".concat(rgbToHex(r, g, b, false));\n} // Wrapper function ported from TinyColor.prototype.mix, not treeshakable.\n// Amount in range [0, 1]\n// Assume color1 & color2 has no alpha, since the following src code did so.\n\n\nfunction mix(rgb1, rgb2, amount) {\n var p = amount / 100;\n var rgb = {\n r: (rgb2.r - rgb1.r) * p + rgb1.r,\n g: (rgb2.g - rgb1.g) * p + rgb1.g,\n b: (rgb2.b - rgb1.b) * p + rgb1.b\n };\n return rgb;\n}\n\nfunction getHue(hsv, i, light) {\n var hue; // 根据色相不同,色相转向不同\n\n if (Math.round(hsv.h) >= 60 && Math.round(hsv.h) <= 240) {\n hue = light ? Math.round(hsv.h) - hueStep * i : Math.round(hsv.h) + hueStep * i;\n } else {\n hue = light ? Math.round(hsv.h) + hueStep * i : Math.round(hsv.h) - hueStep * i;\n }\n\n if (hue < 0) {\n hue += 360;\n } else if (hue >= 360) {\n hue -= 360;\n }\n\n return hue;\n}\n\nfunction getSaturation(hsv, i, light) {\n // grey color don't change saturation\n if (hsv.h === 0 && hsv.s === 0) {\n return hsv.s;\n }\n\n var saturation;\n\n if (light) {\n saturation = hsv.s - saturationStep * i;\n } else if (i === darkColorCount) {\n saturation = hsv.s + saturationStep;\n } else {\n saturation = hsv.s + saturationStep2 * i;\n } // 边界值修正\n\n\n if (saturation > 1) {\n saturation = 1;\n } // 第一格的 s 限制在 0.06-0.1 之间\n\n\n if (light && i === lightColorCount && saturation > 0.1) {\n saturation = 0.1;\n }\n\n if (saturation < 0.06) {\n saturation = 0.06;\n }\n\n return Number(saturation.toFixed(2));\n}\n\nfunction getValue(hsv, i, light) {\n var value;\n\n if (light) {\n value = hsv.v + brightnessStep1 * i;\n } else {\n value = hsv.v - brightnessStep2 * i;\n }\n\n if (value > 1) {\n value = 1;\n }\n\n return Number(value.toFixed(2));\n}\n\nexport default function generate(color) {\n var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var patterns = [];\n var pColor = inputToRGB(color);\n\n for (var i = lightColorCount; i > 0; i -= 1) {\n var hsv = toHsv(pColor);\n var colorString = toHex(inputToRGB({\n h: getHue(hsv, i, true),\n s: getSaturation(hsv, i, true),\n v: getValue(hsv, i, true)\n }));\n patterns.push(colorString);\n }\n\n patterns.push(toHex(pColor));\n\n for (var _i = 1; _i <= darkColorCount; _i += 1) {\n var _hsv = toHsv(pColor);\n\n var _colorString = toHex(inputToRGB({\n h: getHue(_hsv, _i),\n s: getSaturation(_hsv, _i),\n v: getValue(_hsv, _i)\n }));\n\n patterns.push(_colorString);\n } // dark theme patterns\n\n\n if (opts.theme === 'dark') {\n return darkColorMap.map(function (_ref3) {\n var index = _ref3.index,\n opacity = _ref3.opacity;\n var darkColorString = toHex(mix(inputToRGB(opts.backgroundColor || '#141414'), inputToRGB(patterns[index]), opacity * 100));\n return darkColorString;\n });\n }\n\n return patterns;\n}","import generate from \"./generate\";\nvar presetPrimaryColors = {\n red: '#F5222D',\n volcano: '#FA541C',\n orange: '#FA8C16',\n gold: '#FAAD14',\n yellow: '#FADB14',\n lime: '#A0D911',\n green: '#52C41A',\n cyan: '#13C2C2',\n blue: '#1677FF',\n geekblue: '#2F54EB',\n purple: '#722ED1',\n magenta: '#EB2F96',\n grey: '#666666'\n};\nvar presetPalettes = {};\nvar presetDarkPalettes = {};\nObject.keys(presetPrimaryColors).forEach(function (key) {\n presetPalettes[key] = generate(presetPrimaryColors[key]);\n presetPalettes[key].primary = presetPalettes[key][5]; // dark presetPalettes\n\n presetDarkPalettes[key] = generate(presetPrimaryColors[key], {\n theme: 'dark',\n backgroundColor: '#141414'\n });\n presetDarkPalettes[key].primary = presetDarkPalettes[key][5];\n});\nvar red = presetPalettes.red;\nvar volcano = presetPalettes.volcano;\nvar gold = presetPalettes.gold;\nvar orange = presetPalettes.orange;\nvar yellow = presetPalettes.yellow;\nvar lime = presetPalettes.lime;\nvar green = presetPalettes.green;\nvar cyan = presetPalettes.cyan;\nvar blue = presetPalettes.blue;\nvar geekblue = presetPalettes.geekblue;\nvar purple = presetPalettes.purple;\nvar magenta = presetPalettes.magenta;\nvar grey = presetPalettes.grey;\nvar gray = presetPalettes.grey;\nexport { generate, presetPalettes, presetDarkPalettes, presetPrimaryColors, red, volcano, orange, gold, yellow, lime, green, cyan, blue, geekblue, purple, magenta, grey, gray };","/* eslint-disable */\n// Inspired by https://github.com/garycourt/murmurhash-js\n// Ported from https://github.com/aappleby/smhasher/blob/61a0530f28277f2e850bfc39600ce61d02b518de/src/MurmurHash2.cpp#L37-L86\nfunction murmur2(str) {\n // 'm' and 'r' are mixing constants generated offline.\n // They're not really 'magic', they just happen to work well.\n // const m = 0x5bd1e995;\n // const r = 24;\n // Initialize the hash\n var h = 0; // Mix 4 bytes at a time into the hash\n\n var k,\n i = 0,\n len = str.length;\n\n for (; len >= 4; ++i, len -= 4) {\n k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24;\n k =\n /* Math.imul(k, m): */\n (k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16);\n k ^=\n /* k >>> r: */\n k >>> 24;\n h =\n /* Math.imul(k, m): */\n (k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16) ^\n /* Math.imul(h, m): */\n (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);\n } // Handle the last few bytes of the input array\n\n\n switch (len) {\n case 3:\n h ^= (str.charCodeAt(i + 2) & 0xff) << 16;\n\n case 2:\n h ^= (str.charCodeAt(i + 1) & 0xff) << 8;\n\n case 1:\n h ^= str.charCodeAt(i) & 0xff;\n h =\n /* Math.imul(h, m): */\n (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);\n } // Do a few final mixes of the hash to ensure the last few\n // bytes are well-incorporated.\n\n\n h ^= h >>> 13;\n h =\n /* Math.imul(h, m): */\n (h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);\n return ((h ^ h >>> 15) >>> 0).toString(36);\n}\n\nexport default murmur2;\n","import _classCallCheck from \"@babel/runtime/helpers/esm/classCallCheck\";\nimport _createClass from \"@babel/runtime/helpers/esm/createClass\";\nimport _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\n// [times, realValue]\n\nvar SPLIT = '%';\nvar Entity = /*#__PURE__*/function () {\n function Entity(instanceId) {\n _classCallCheck(this, Entity);\n _defineProperty(this, \"instanceId\", void 0);\n /** @private Internal cache map. Do not access this directly */\n _defineProperty(this, \"cache\", new Map());\n this.instanceId = instanceId;\n }\n _createClass(Entity, [{\n key: \"get\",\n value: function get(keys) {\n return this.cache.get(keys.join(SPLIT)) || null;\n }\n }, {\n key: \"update\",\n value: function update(keys, valueFn) {\n var path = keys.join(SPLIT);\n var prevValue = this.cache.get(path);\n var nextValue = valueFn(prevValue);\n if (nextValue === null) {\n this.cache.delete(path);\n } else {\n this.cache.set(path, nextValue);\n }\n }\n }]);\n return Entity;\n}();\nexport default Entity;","import _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nvar _excluded = [\"children\"];\nimport useMemo from \"rc-util/es/hooks/useMemo\";\nimport isEqual from \"rc-util/es/isEqual\";\nimport * as React from 'react';\nimport CacheEntity from \"./Cache\";\nexport var ATTR_TOKEN = 'data-token-hash';\nexport var ATTR_MARK = 'data-css-hash';\nexport var ATTR_CACHE_PATH = 'data-cache-path';\n\n// Mark css-in-js instance in style element\nexport var CSS_IN_JS_INSTANCE = '__cssinjs_instance__';\nexport function createCache() {\n var cssinjsInstanceId = Math.random().toString(12).slice(2);\n\n // Tricky SSR: Move all inline style to the head.\n // PS: We do not recommend tricky mode.\n if (typeof document !== 'undefined' && document.head && document.body) {\n var styles = document.body.querySelectorAll(\"style[\".concat(ATTR_MARK, \"]\")) || [];\n var firstChild = document.head.firstChild;\n Array.from(styles).forEach(function (style) {\n style[CSS_IN_JS_INSTANCE] = style[CSS_IN_JS_INSTANCE] || cssinjsInstanceId;\n\n // Not force move if no head\n if (style[CSS_IN_JS_INSTANCE] === cssinjsInstanceId) {\n document.head.insertBefore(style, firstChild);\n }\n });\n\n // Deduplicate of moved styles\n var styleHash = {};\n Array.from(document.querySelectorAll(\"style[\".concat(ATTR_MARK, \"]\"))).forEach(function (style) {\n var hash = style.getAttribute(ATTR_MARK);\n if (styleHash[hash]) {\n if (style[CSS_IN_JS_INSTANCE] === cssinjsInstanceId) {\n var _style$parentNode;\n (_style$parentNode = style.parentNode) === null || _style$parentNode === void 0 ? void 0 : _style$parentNode.removeChild(style);\n }\n } else {\n styleHash[hash] = true;\n }\n });\n }\n return new CacheEntity(cssinjsInstanceId);\n}\nvar StyleContext = /*#__PURE__*/React.createContext({\n hashPriority: 'low',\n cache: createCache(),\n defaultCache: true\n});\nexport var StyleProvider = function StyleProvider(props) {\n var children = props.children,\n restProps = _objectWithoutProperties(props, _excluded);\n var parentContext = React.useContext(StyleContext);\n var context = useMemo(function () {\n var mergedContext = _objectSpread({}, parentContext);\n Object.keys(restProps).forEach(function (key) {\n var value = restProps[key];\n if (restProps[key] !== undefined) {\n mergedContext[key] = value;\n }\n });\n var cache = restProps.cache;\n mergedContext.cache = mergedContext.cache || createCache();\n mergedContext.defaultCache = !cache && parentContext.defaultCache;\n return mergedContext;\n }, [parentContext, restProps], function (prev, next) {\n return !isEqual(prev[0], next[0], true) || !isEqual(prev[1], next[1], true);\n });\n return /*#__PURE__*/React.createElement(StyleContext.Provider, {\n value: context\n }, children);\n};\nexport default StyleContext;","import _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport _classCallCheck from \"@babel/runtime/helpers/esm/classCallCheck\";\nimport _createClass from \"@babel/runtime/helpers/esm/createClass\";\nimport _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\n// ================================== Cache ==================================\n\nexport function sameDerivativeOption(left, right) {\n if (left.length !== right.length) {\n return false;\n }\n for (var i = 0; i < left.length; i++) {\n if (left[i] !== right[i]) {\n return false;\n }\n }\n return true;\n}\nvar ThemeCache = /*#__PURE__*/function () {\n function ThemeCache() {\n _classCallCheck(this, ThemeCache);\n _defineProperty(this, \"cache\", void 0);\n _defineProperty(this, \"keys\", void 0);\n _defineProperty(this, \"cacheCallTimes\", void 0);\n this.cache = new Map();\n this.keys = [];\n this.cacheCallTimes = 0;\n }\n _createClass(ThemeCache, [{\n key: \"size\",\n value: function size() {\n return this.keys.length;\n }\n }, {\n key: \"internalGet\",\n value: function internalGet(derivativeOption) {\n var _cache2, _cache3;\n var updateCallTimes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n var cache = {\n map: this.cache\n };\n derivativeOption.forEach(function (derivative) {\n if (!cache) {\n cache = undefined;\n } else {\n var _cache, _cache$map;\n cache = (_cache = cache) === null || _cache === void 0 ? void 0 : (_cache$map = _cache.map) === null || _cache$map === void 0 ? void 0 : _cache$map.get(derivative);\n }\n });\n if ((_cache2 = cache) !== null && _cache2 !== void 0 && _cache2.value && updateCallTimes) {\n cache.value[1] = this.cacheCallTimes++;\n }\n return (_cache3 = cache) === null || _cache3 === void 0 ? void 0 : _cache3.value;\n }\n }, {\n key: \"get\",\n value: function get(derivativeOption) {\n var _this$internalGet;\n return (_this$internalGet = this.internalGet(derivativeOption, true)) === null || _this$internalGet === void 0 ? void 0 : _this$internalGet[0];\n }\n }, {\n key: \"has\",\n value: function has(derivativeOption) {\n return !!this.internalGet(derivativeOption);\n }\n }, {\n key: \"set\",\n value: function set(derivativeOption, value) {\n var _this = this;\n // New cache\n if (!this.has(derivativeOption)) {\n if (this.size() + 1 > ThemeCache.MAX_CACHE_SIZE + ThemeCache.MAX_CACHE_OFFSET) {\n var _this$keys$reduce = this.keys.reduce(function (result, key) {\n var _result = _slicedToArray(result, 2),\n callTimes = _result[1];\n if (_this.internalGet(key)[1] < callTimes) {\n return [key, _this.internalGet(key)[1]];\n }\n return result;\n }, [this.keys[0], this.cacheCallTimes]),\n _this$keys$reduce2 = _slicedToArray(_this$keys$reduce, 1),\n targetKey = _this$keys$reduce2[0];\n this.delete(targetKey);\n }\n this.keys.push(derivativeOption);\n }\n var cache = this.cache;\n derivativeOption.forEach(function (derivative, index) {\n if (index === derivativeOption.length - 1) {\n cache.set(derivative, {\n value: [value, _this.cacheCallTimes++]\n });\n } else {\n var cacheValue = cache.get(derivative);\n if (!cacheValue) {\n cache.set(derivative, {\n map: new Map()\n });\n } else if (!cacheValue.map) {\n cacheValue.map = new Map();\n }\n cache = cache.get(derivative).map;\n }\n });\n }\n }, {\n key: \"deleteByPath\",\n value: function deleteByPath(currentCache, derivatives) {\n var cache = currentCache.get(derivatives[0]);\n if (derivatives.length === 1) {\n var _cache$value;\n if (!cache.map) {\n currentCache.delete(derivatives[0]);\n } else {\n currentCache.set(derivatives[0], {\n map: cache.map\n });\n }\n return (_cache$value = cache.value) === null || _cache$value === void 0 ? void 0 : _cache$value[0];\n }\n var result = this.deleteByPath(cache.map, derivatives.slice(1));\n if ((!cache.map || cache.map.size === 0) && !cache.value) {\n currentCache.delete(derivatives[0]);\n }\n return result;\n }\n }, {\n key: \"delete\",\n value: function _delete(derivativeOption) {\n // If cache exists\n if (this.has(derivativeOption)) {\n this.keys = this.keys.filter(function (item) {\n return !sameDerivativeOption(item, derivativeOption);\n });\n return this.deleteByPath(this.cache, derivativeOption);\n }\n return undefined;\n }\n }]);\n return ThemeCache;\n}();\n_defineProperty(ThemeCache, \"MAX_CACHE_SIZE\", 20);\n_defineProperty(ThemeCache, \"MAX_CACHE_OFFSET\", 5);\nexport { ThemeCache as default };","import _classCallCheck from \"@babel/runtime/helpers/esm/classCallCheck\";\nimport _createClass from \"@babel/runtime/helpers/esm/createClass\";\nimport _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport { warning } from \"rc-util/es/warning\";\nvar uuid = 0;\n\n/**\n * Theme with algorithms to derive tokens from design tokens.\n * Use `createTheme` first which will help to manage the theme instance cache.\n */\nvar Theme = /*#__PURE__*/function () {\n function Theme(derivatives) {\n _classCallCheck(this, Theme);\n _defineProperty(this, \"derivatives\", void 0);\n _defineProperty(this, \"id\", void 0);\n this.derivatives = Array.isArray(derivatives) ? derivatives : [derivatives];\n this.id = uuid;\n if (derivatives.length === 0) {\n warning(derivatives.length > 0, '[Ant Design CSS-in-JS] Theme should have at least one derivative function.');\n }\n uuid += 1;\n }\n _createClass(Theme, [{\n key: \"getDerivativeToken\",\n value: function getDerivativeToken(token) {\n return this.derivatives.reduce(function (result, derivative) {\n return derivative(token, result);\n }, undefined);\n }\n }]);\n return Theme;\n}();\nexport { Theme as default };","import ThemeCache from \"./ThemeCache\";\nimport Theme from \"./Theme\";\nvar cacheThemes = new ThemeCache();\n\n/**\n * Same as new Theme, but will always return same one if `derivative` not changed.\n */\nexport default function createTheme(derivatives) {\n var derivativeArr = Array.isArray(derivatives) ? derivatives : [derivatives];\n // Create new theme if not exist\n if (!cacheThemes.has(derivativeArr)) {\n cacheThemes.set(derivativeArr, new Theme(derivativeArr));\n }\n\n // Get theme from cache and return\n return cacheThemes.get(derivativeArr);\n}","import _typeof from \"@babel/runtime/helpers/esm/typeof\";\nimport hash from '@emotion/hash';\nimport canUseDom from \"rc-util/es/Dom/canUseDom\";\nimport { removeCSS, updateCSS } from \"rc-util/es/Dom/dynamicCSS\";\nimport { Theme } from \"./theme\";\nexport function flattenToken(token) {\n var str = '';\n Object.keys(token).forEach(function (key) {\n var value = token[key];\n str += key;\n if (value instanceof Theme) {\n str += value.id;\n } else if (value && _typeof(value) === 'object') {\n str += flattenToken(value);\n } else {\n str += value;\n }\n });\n return str;\n}\n\n/**\n * Convert derivative token to key string\n */\nexport function token2key(token, salt) {\n return hash(\"\".concat(salt, \"_\").concat(flattenToken(token)));\n}\nvar randomSelectorKey = \"random-\".concat(Date.now(), \"-\").concat(Math.random()).replace(/\\./g, '');\n\n// Magic `content` for detect selector support\nvar checkContent = '_bAmBoO_';\nfunction supportSelector(styleStr, handleElement, supportCheck) {\n if (canUseDom()) {\n var _getComputedStyle$con, _ele$parentNode;\n updateCSS(styleStr, randomSelectorKey);\n var _ele = document.createElement('div');\n _ele.style.position = 'fixed';\n _ele.style.left = '0';\n _ele.style.top = '0';\n handleElement === null || handleElement === void 0 ? void 0 : handleElement(_ele);\n document.body.appendChild(_ele);\n if (process.env.NODE_ENV !== 'production') {\n _ele.innerHTML = 'Test';\n _ele.style.zIndex = '9999999';\n }\n var support = supportCheck ? supportCheck(_ele) : (_getComputedStyle$con = getComputedStyle(_ele).content) === null || _getComputedStyle$con === void 0 ? void 0 : _getComputedStyle$con.includes(checkContent);\n (_ele$parentNode = _ele.parentNode) === null || _ele$parentNode === void 0 ? void 0 : _ele$parentNode.removeChild(_ele);\n removeCSS(randomSelectorKey);\n return support;\n }\n return false;\n}\nvar canLayer = undefined;\nexport function supportLayer() {\n if (canLayer === undefined) {\n canLayer = supportSelector(\"@layer \".concat(randomSelectorKey, \" { .\").concat(randomSelectorKey, \" { content: \\\"\").concat(checkContent, \"\\\"!important; } }\"), function (ele) {\n ele.className = randomSelectorKey;\n });\n }\n return canLayer;\n}\nvar canWhere = undefined;\nexport function supportWhere() {\n if (canWhere === undefined) {\n canWhere = supportSelector(\":where(.\".concat(randomSelectorKey, \") { content: \\\"\").concat(checkContent, \"\\\"!important; }\"), function (ele) {\n ele.className = randomSelectorKey;\n });\n }\n return canWhere;\n}\nvar canLogic = undefined;\nexport function supportLogicProps() {\n if (canLogic === undefined) {\n canLogic = supportSelector(\".\".concat(randomSelectorKey, \" { inset-block: 93px !important; }\"), function (ele) {\n ele.className = randomSelectorKey;\n }, function (ele) {\n return getComputedStyle(ele).bottom === '93px';\n });\n }\n return canLogic;\n}","import _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\n// import canUseDom from 'rc-util/lib/Dom/canUseDom';\nimport useLayoutEffect from \"rc-util/es/hooks/useLayoutEffect\";\nimport * as React from 'react';\n\n// We need fully clone React function here\n// to avoid webpack warning React 17 do not export `useId`\nvar fullClone = _objectSpread({}, React);\nvar useInsertionEffect = fullClone.useInsertionEffect;\n/**\n * Polyfill `useInsertionEffect` for React < 18\n * @param renderEffect will be executed in `useMemo`, and do not have callback\n * @param effect will be executed in `useLayoutEffect`\n * @param deps\n */\nvar useInsertionEffectPolyfill = function useInsertionEffectPolyfill(renderEffect, effect, deps) {\n React.useMemo(renderEffect, deps);\n useLayoutEffect(function () {\n return effect(true);\n }, deps);\n};\n\n/**\n * Compatible `useInsertionEffect`\n * will use `useInsertionEffect` if React version >= 18,\n * otherwise use `useInsertionEffectPolyfill`.\n */\nvar useCompatibleInsertionEffect = useInsertionEffect ? function (renderEffect, effect, deps) {\n return useInsertionEffect(function () {\n renderEffect();\n return effect();\n }, deps);\n} : useInsertionEffectPolyfill;\nexport default useCompatibleInsertionEffect;","function useProdHMR() {\n return false;\n}\nvar webpackHMR = false;\nfunction useDevHMR() {\n return webpackHMR;\n}\nexport default process.env.NODE_ENV === 'production' ? useProdHMR : useDevHMR;\n\n// Webpack `module.hot.accept` do not support any deps update trigger\n// We have to hack handler to force mark as HRM\nif (process.env.NODE_ENV !== 'production' && typeof module !== 'undefined' && module && module.hot && typeof window !== 'undefined') {\n var win = window;\n if (typeof win.webpackHotUpdate === 'function') {\n var originWebpackHotUpdate = win.webpackHotUpdate;\n win.webpackHotUpdate = function () {\n webpackHMR = true;\n setTimeout(function () {\n webpackHMR = false;\n }, 0);\n return originWebpackHotUpdate.apply(void 0, arguments);\n };\n }\n}","import _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport _toConsumableArray from \"@babel/runtime/helpers/esm/toConsumableArray\";\nimport * as React from 'react';\nimport StyleContext from \"../StyleContext\";\nimport useCompatibleInsertionEffect from \"./useCompatibleInsertionEffect\";\nimport useHMR from \"./useHMR\";\nexport default function useGlobalCache(prefix, keyPath, cacheFn, onCacheRemove,\n// Add additional effect trigger by `useInsertionEffect`\nonCacheEffect) {\n var _React$useContext = React.useContext(StyleContext),\n globalCache = _React$useContext.cache;\n var fullPath = [prefix].concat(_toConsumableArray(keyPath));\n var deps = fullPath.join('_');\n var HMRUpdate = useHMR();\n var buildCache = function buildCache(updater) {\n globalCache.update(fullPath, function (prevCache) {\n var _ref = prevCache || [],\n _ref2 = _slicedToArray(_ref, 2),\n _ref2$ = _ref2[0],\n times = _ref2$ === void 0 ? 0 : _ref2$,\n cache = _ref2[1];\n\n // HMR should always ignore cache since developer may change it\n var tmpCache = cache;\n if (process.env.NODE_ENV !== 'production' && cache && HMRUpdate) {\n onCacheRemove === null || onCacheRemove === void 0 ? void 0 : onCacheRemove(tmpCache, HMRUpdate);\n tmpCache = null;\n }\n var mergedCache = tmpCache || cacheFn();\n var data = [times, mergedCache];\n\n // Call updater if need additional logic\n return updater ? updater(data) : data;\n });\n };\n\n // Create cache\n React.useMemo(function () {\n buildCache();\n }, /* eslint-disable react-hooks/exhaustive-deps */\n [deps]\n /* eslint-enable */);\n\n var cacheEntity = globalCache.get(fullPath);\n\n // HMR clean the cache but not trigger `useMemo` again\n // Let's fallback of this\n // ref https://github.com/ant-design/cssinjs/issues/127\n if (process.env.NODE_ENV !== 'production' && !cacheEntity) {\n buildCache();\n cacheEntity = globalCache.get(fullPath);\n }\n var cacheContent = cacheEntity[1];\n\n // Remove if no need anymore\n useCompatibleInsertionEffect(function () {\n onCacheEffect === null || onCacheEffect === void 0 ? void 0 : onCacheEffect(cacheContent);\n }, function (polyfill) {\n // It's bad to call build again in effect.\n // But we have to do this since StrictMode will call effect twice\n // which will clear cache on the first time.\n buildCache(function (_ref3) {\n var _ref4 = _slicedToArray(_ref3, 2),\n times = _ref4[0],\n cache = _ref4[1];\n if (polyfill && times === 0) {\n onCacheEffect === null || onCacheEffect === void 0 ? void 0 : onCacheEffect(cacheContent);\n }\n return [times + 1, cache];\n });\n return function () {\n globalCache.update(fullPath, function (prevCache) {\n var _ref5 = prevCache || [],\n _ref6 = _slicedToArray(_ref5, 2),\n _ref6$ = _ref6[0],\n times = _ref6$ === void 0 ? 0 : _ref6$,\n cache = _ref6[1];\n var nextCount = times - 1;\n if (nextCount === 0) {\n onCacheRemove === null || onCacheRemove === void 0 ? void 0 : onCacheRemove(cache, false);\n return null;\n }\n return [times - 1, cache];\n });\n };\n }, [deps]);\n return cacheContent;\n}","import _toConsumableArray from \"@babel/runtime/helpers/esm/toConsumableArray\";\nimport _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\nimport hash from '@emotion/hash';\nimport * as React from 'react';\nimport { useContext } from 'react';\nimport StyleContext, { ATTR_TOKEN, CSS_IN_JS_INSTANCE } from \"../StyleContext\";\nimport { flattenToken, token2key } from \"../util\";\nimport useGlobalCache from \"./useGlobalCache\";\nvar EMPTY_OVERRIDE = {};\n\n// Generate different prefix to make user selector break in production env.\n// This helps developer not to do style override directly on the hash id.\nvar hashPrefix = process.env.NODE_ENV !== 'production' ? 'css-dev-only-do-not-override' : 'css';\nvar tokenKeys = new Map();\nfunction recordCleanToken(tokenKey) {\n tokenKeys.set(tokenKey, (tokenKeys.get(tokenKey) || 0) + 1);\n}\nfunction removeStyleTags(key, instanceId) {\n if (typeof document !== 'undefined') {\n var styles = document.querySelectorAll(\"style[\".concat(ATTR_TOKEN, \"=\\\"\").concat(key, \"\\\"]\"));\n styles.forEach(function (style) {\n if (style[CSS_IN_JS_INSTANCE] === instanceId) {\n var _style$parentNode;\n (_style$parentNode = style.parentNode) === null || _style$parentNode === void 0 ? void 0 : _style$parentNode.removeChild(style);\n }\n });\n }\n}\nvar TOKEN_THRESHOLD = 0;\n\n// Remove will check current keys first\nfunction cleanTokenStyle(tokenKey, instanceId) {\n tokenKeys.set(tokenKey, (tokenKeys.get(tokenKey) || 0) - 1);\n var tokenKeyList = Array.from(tokenKeys.keys());\n var cleanableKeyList = tokenKeyList.filter(function (key) {\n var count = tokenKeys.get(key) || 0;\n return count <= 0;\n });\n\n // Should keep tokens under threshold for not to insert style too often\n if (tokenKeyList.length - cleanableKeyList.length > TOKEN_THRESHOLD) {\n cleanableKeyList.forEach(function (key) {\n removeStyleTags(key, instanceId);\n tokenKeys.delete(key);\n });\n }\n}\nexport var getComputedToken = function getComputedToken(originToken, overrideToken, theme, format) {\n var derivativeToken = theme.getDerivativeToken(originToken);\n\n // Merge with override\n var mergedDerivativeToken = _objectSpread(_objectSpread({}, derivativeToken), overrideToken);\n\n // Format if needed\n if (format) {\n mergedDerivativeToken = format(mergedDerivativeToken);\n }\n return mergedDerivativeToken;\n};\n\n/**\n * Cache theme derivative token as global shared one\n * @param theme Theme entity\n * @param tokens List of tokens, used for cache. Please do not dynamic generate object directly\n * @param option Additional config\n * @returns Call Theme.getDerivativeToken(tokenObject) to get token\n */\nexport default function useCacheToken(theme, tokens) {\n var option = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n var _useContext = useContext(StyleContext),\n instanceId = _useContext.cache.instanceId;\n var _option$salt = option.salt,\n salt = _option$salt === void 0 ? '' : _option$salt,\n _option$override = option.override,\n override = _option$override === void 0 ? EMPTY_OVERRIDE : _option$override,\n formatToken = option.formatToken,\n compute = option.getComputedToken;\n\n // Basic - We do basic cache here\n var mergedToken = React.useMemo(function () {\n return Object.assign.apply(Object, [{}].concat(_toConsumableArray(tokens)));\n }, [tokens]);\n var tokenStr = React.useMemo(function () {\n return flattenToken(mergedToken);\n }, [mergedToken]);\n var overrideTokenStr = React.useMemo(function () {\n return flattenToken(override);\n }, [override]);\n var cachedToken = useGlobalCache('token', [salt, theme.id, tokenStr, overrideTokenStr], function () {\n var mergedDerivativeToken = compute ? compute(mergedToken, override, theme) : getComputedToken(mergedToken, override, theme, formatToken);\n\n // Optimize for `useStyleRegister` performance\n var tokenKey = token2key(mergedDerivativeToken, salt);\n mergedDerivativeToken._tokenKey = tokenKey;\n recordCleanToken(tokenKey);\n var hashId = \"\".concat(hashPrefix, \"-\").concat(hash(tokenKey));\n mergedDerivativeToken._hashId = hashId; // Not used\n\n return [mergedDerivativeToken, hashId];\n }, function (cache) {\n // Remove token will remove all related style\n cleanTokenStyle(cache[0]._tokenKey, instanceId);\n });\n return cachedToken;\n}","var unitlessKeys = {\n animationIterationCount: 1,\n borderImageOutset: 1,\n borderImageSlice: 1,\n borderImageWidth: 1,\n boxFlex: 1,\n boxFlexGroup: 1,\n boxOrdinalGroup: 1,\n columnCount: 1,\n columns: 1,\n flex: 1,\n flexGrow: 1,\n flexPositive: 1,\n flexShrink: 1,\n flexNegative: 1,\n flexOrder: 1,\n gridRow: 1,\n gridRowEnd: 1,\n gridRowSpan: 1,\n gridRowStart: 1,\n gridColumn: 1,\n gridColumnEnd: 1,\n gridColumnSpan: 1,\n gridColumnStart: 1,\n msGridRow: 1,\n msGridRowSpan: 1,\n msGridColumn: 1,\n msGridColumnSpan: 1,\n fontWeight: 1,\n lineHeight: 1,\n opacity: 1,\n order: 1,\n orphans: 1,\n tabSize: 1,\n widows: 1,\n zIndex: 1,\n zoom: 1,\n WebkitLineClamp: 1,\n // SVG-related properties\n fillOpacity: 1,\n floodOpacity: 1,\n stopOpacity: 1,\n strokeDasharray: 1,\n strokeDashoffset: 1,\n strokeMiterlimit: 1,\n strokeOpacity: 1,\n strokeWidth: 1\n};\n\nexport default unitlessKeys;\n","export var MS = '-ms-'\nexport var MOZ = '-moz-'\nexport var WEBKIT = '-webkit-'\n\nexport var COMMENT = 'comm'\nexport var RULESET = 'rule'\nexport var DECLARATION = 'decl'\n\nexport var PAGE = '@page'\nexport var MEDIA = '@media'\nexport var IMPORT = '@import'\nexport var CHARSET = '@charset'\nexport var VIEWPORT = '@viewport'\nexport var SUPPORTS = '@supports'\nexport var DOCUMENT = '@document'\nexport var NAMESPACE = '@namespace'\nexport var KEYFRAMES = '@keyframes'\nexport var FONT_FACE = '@font-face'\nexport var COUNTER_STYLE = '@counter-style'\nexport var FONT_FEATURE_VALUES = '@font-feature-values'\nexport var LAYER = '@layer'\n","/**\n * @param {number}\n * @return {number}\n */\nexport var abs = Math.abs\n\n/**\n * @param {number}\n * @return {string}\n */\nexport var from = String.fromCharCode\n\n/**\n * @param {object}\n * @return {object}\n */\nexport var assign = Object.assign\n\n/**\n * @param {string} value\n * @param {number} length\n * @return {number}\n */\nexport function hash (value, length) {\n\treturn charat(value, 0) ^ 45 ? (((((((length << 2) ^ charat(value, 0)) << 2) ^ charat(value, 1)) << 2) ^ charat(value, 2)) << 2) ^ charat(value, 3) : 0\n}\n\n/**\n * @param {string} value\n * @return {string}\n */\nexport function trim (value) {\n\treturn value.trim()\n}\n\n/**\n * @param {string} value\n * @param {RegExp} pattern\n * @return {string?}\n */\nexport function match (value, pattern) {\n\treturn (value = pattern.exec(value)) ? value[0] : value\n}\n\n/**\n * @param {string} value\n * @param {(string|RegExp)} pattern\n * @param {string} replacement\n * @return {string}\n */\nexport function replace (value, pattern, replacement) {\n\treturn value.replace(pattern, replacement)\n}\n\n/**\n * @param {string} value\n * @param {string} search\n * @return {number}\n */\nexport function indexof (value, search) {\n\treturn value.indexOf(search)\n}\n\n/**\n * @param {string} value\n * @param {number} index\n * @return {number}\n */\nexport function charat (value, index) {\n\treturn value.charCodeAt(index) | 0\n}\n\n/**\n * @param {string} value\n * @param {number} begin\n * @param {number} end\n * @return {string}\n */\nexport function substr (value, begin, end) {\n\treturn value.slice(begin, end)\n}\n\n/**\n * @param {string} value\n * @return {number}\n */\nexport function strlen (value) {\n\treturn value.length\n}\n\n/**\n * @param {any[]} value\n * @return {number}\n */\nexport function sizeof (value) {\n\treturn value.length\n}\n\n/**\n * @param {any} value\n * @param {any[]} array\n * @return {any}\n */\nexport function append (value, array) {\n\treturn array.push(value), value\n}\n\n/**\n * @param {string[]} array\n * @param {function} callback\n * @return {string}\n */\nexport function combine (array, callback) {\n\treturn array.map(callback).join('')\n}\n\n/**\n * @param {string[]} array\n * @param {RegExp} pattern\n * @return {string[]}\n */\nexport function filter (array, pattern) {\n\treturn array.filter(function (value) { return !match(value, pattern) })\n}\n","import {IMPORT, LAYER, COMMENT, RULESET, DECLARATION, KEYFRAMES} from './Enum.js'\nimport {strlen} from './Utility.js'\n\n/**\n * @param {object[]} children\n * @param {function} callback\n * @return {string}\n */\nexport function serialize (children, callback) {\n\tvar output = ''\n\n\tfor (var i = 0; i < children.length; i++)\n\t\toutput += callback(children[i], i, children, callback) || ''\n\n\treturn output\n}\n\n/**\n * @param {object} element\n * @param {number} index\n * @param {object[]} children\n * @param {function} callback\n * @return {string}\n */\nexport function stringify (element, index, children, callback) {\n\tswitch (element.type) {\n\t\tcase LAYER: if (element.children.length) break\n\t\tcase IMPORT: case DECLARATION: return element.return = element.return || element.value\n\t\tcase COMMENT: return ''\n\t\tcase KEYFRAMES: return element.return = element.value + '{' + serialize(element.children, callback) + '}'\n\t\tcase RULESET: if (!strlen(element.value = element.props.join(','))) return ''\n\t}\n\n\treturn strlen(children = serialize(element.children, callback)) ? element.return = element.value + '{' + children + '}' : ''\n}\n","import {from, trim, charat, strlen, substr, append, assign} from './Utility.js'\n\nexport var line = 1\nexport var column = 1\nexport var length = 0\nexport var position = 0\nexport var character = 0\nexport var characters = ''\n\n/**\n * @param {string} value\n * @param {object | null} root\n * @param {object | null} parent\n * @param {string} type\n * @param {string[] | string} props\n * @param {object[] | string} children\n * @param {object[]} siblings\n * @param {number} length\n */\nexport function node (value, root, parent, type, props, children, length, siblings) {\n\treturn {value: value, root: root, parent: parent, type: type, props: props, children: children, line: line, column: column, length: length, return: '', siblings: siblings}\n}\n\n/**\n * @param {object} root\n * @param {object} props\n * @return {object}\n */\nexport function copy (root, props) {\n\treturn assign(node('', null, null, '', null, null, 0, root.siblings), root, {length: -root.length}, props)\n}\n\n/**\n * @param {object} root\n */\nexport function lift (root) {\n\twhile (root.root)\n\t\troot = copy(root.root, {children: [root]})\n\n\tappend(root, root.siblings)\n}\n\n/**\n * @return {number}\n */\nexport function char () {\n\treturn character\n}\n\n/**\n * @return {number}\n */\nexport function prev () {\n\tcharacter = position > 0 ? charat(characters, --position) : 0\n\n\tif (column--, character === 10)\n\t\tcolumn = 1, line--\n\n\treturn character\n}\n\n/**\n * @return {number}\n */\nexport function next () {\n\tcharacter = position < length ? charat(characters, position++) : 0\n\n\tif (column++, character === 10)\n\t\tcolumn = 1, line++\n\n\treturn character\n}\n\n/**\n * @return {number}\n */\nexport function peek () {\n\treturn charat(characters, position)\n}\n\n/**\n * @return {number}\n */\nexport function caret () {\n\treturn position\n}\n\n/**\n * @param {number} begin\n * @param {number} end\n * @return {string}\n */\nexport function slice (begin, end) {\n\treturn substr(characters, begin, end)\n}\n\n/**\n * @param {number} type\n * @return {number}\n */\nexport function token (type) {\n\tswitch (type) {\n\t\t// \\0 \\t \\n \\r \\s whitespace token\n\t\tcase 0: case 9: case 10: case 13: case 32:\n\t\t\treturn 5\n\t\t// ! + , / > @ ~ isolate token\n\t\tcase 33: case 43: case 44: case 47: case 62: case 64: case 126:\n\t\t// ; { } breakpoint token\n\t\tcase 59: case 123: case 125:\n\t\t\treturn 4\n\t\t// : accompanied token\n\t\tcase 58:\n\t\t\treturn 3\n\t\t// \" ' ( [ opening delimit token\n\t\tcase 34: case 39: case 40: case 91:\n\t\t\treturn 2\n\t\t// ) ] closing delimit token\n\t\tcase 41: case 93:\n\t\t\treturn 1\n\t}\n\n\treturn 0\n}\n\n/**\n * @param {string} value\n * @return {any[]}\n */\nexport function alloc (value) {\n\treturn line = column = 1, length = strlen(characters = value), position = 0, []\n}\n\n/**\n * @param {any} value\n * @return {any}\n */\nexport function dealloc (value) {\n\treturn characters = '', value\n}\n\n/**\n * @param {number} type\n * @return {string}\n */\nexport function delimit (type) {\n\treturn trim(slice(position - 1, delimiter(type === 91 ? type + 2 : type === 40 ? type + 1 : type)))\n}\n\n/**\n * @param {string} value\n * @return {string[]}\n */\nexport function tokenize (value) {\n\treturn dealloc(tokenizer(alloc(value)))\n}\n\n/**\n * @param {number} type\n * @return {string}\n */\nexport function whitespace (type) {\n\twhile (character = peek())\n\t\tif (character < 33)\n\t\t\tnext()\n\t\telse\n\t\t\tbreak\n\n\treturn token(type) > 2 || token(character) > 3 ? '' : ' '\n}\n\n/**\n * @param {string[]} children\n * @return {string[]}\n */\nexport function tokenizer (children) {\n\twhile (next())\n\t\tswitch (token(character)) {\n\t\t\tcase 0: append(identifier(position - 1), children)\n\t\t\t\tbreak\n\t\t\tcase 2: append(delimit(character), children)\n\t\t\t\tbreak\n\t\t\tdefault: append(from(character), children)\n\t\t}\n\n\treturn children\n}\n\n/**\n * @param {number} index\n * @param {number} count\n * @return {string}\n */\nexport function escaping (index, count) {\n\twhile (--count && next())\n\t\t// not 0-9 A-F a-f\n\t\tif (character < 48 || character > 102 || (character > 57 && character < 65) || (character > 70 && character < 97))\n\t\t\tbreak\n\n\treturn slice(index, caret() + (count < 6 && peek() == 32 && next() == 32))\n}\n\n/**\n * @param {number} type\n * @return {number}\n */\nexport function delimiter (type) {\n\twhile (next())\n\t\tswitch (character) {\n\t\t\t// ] ) \" '\n\t\t\tcase type:\n\t\t\t\treturn position\n\t\t\t// \" '\n\t\t\tcase 34: case 39:\n\t\t\t\tif (type !== 34 && type !== 39)\n\t\t\t\t\tdelimiter(character)\n\t\t\t\tbreak\n\t\t\t// (\n\t\t\tcase 40:\n\t\t\t\tif (type === 41)\n\t\t\t\t\tdelimiter(type)\n\t\t\t\tbreak\n\t\t\t// \\\n\t\t\tcase 92:\n\t\t\t\tnext()\n\t\t\t\tbreak\n\t\t}\n\n\treturn position\n}\n\n/**\n * @param {number} type\n * @param {number} index\n * @return {number}\n */\nexport function commenter (type, index) {\n\twhile (next())\n\t\t// //\n\t\tif (type + character === 47 + 10)\n\t\t\tbreak\n\t\t// /*\n\t\telse if (type + character === 42 + 42 && peek() === 47)\n\t\t\tbreak\n\n\treturn '/*' + slice(index, position - 1) + '*' + from(type === 47 ? type : next())\n}\n\n/**\n * @param {number} index\n * @return {string}\n */\nexport function identifier (index) {\n\twhile (!token(peek()))\n\t\tnext()\n\n\treturn slice(index, position)\n}\n","import {COMMENT, RULESET, DECLARATION} from './Enum.js'\nimport {abs, charat, trim, from, sizeof, strlen, substr, append, replace, indexof} from './Utility.js'\nimport {node, char, prev, next, peek, caret, alloc, dealloc, delimit, whitespace, escaping, identifier, commenter} from './Tokenizer.js'\n\n/**\n * @param {string} value\n * @return {object[]}\n */\nexport function compile (value) {\n\treturn dealloc(parse('', null, null, null, [''], value = alloc(value), 0, [0], value))\n}\n\n/**\n * @param {string} value\n * @param {object} root\n * @param {object?} parent\n * @param {string[]} rule\n * @param {string[]} rules\n * @param {string[]} rulesets\n * @param {number[]} pseudo\n * @param {number[]} points\n * @param {string[]} declarations\n * @return {object}\n */\nexport function parse (value, root, parent, rule, rules, rulesets, pseudo, points, declarations) {\n\tvar index = 0\n\tvar offset = 0\n\tvar length = pseudo\n\tvar atrule = 0\n\tvar property = 0\n\tvar previous = 0\n\tvar variable = 1\n\tvar scanning = 1\n\tvar ampersand = 1\n\tvar character = 0\n\tvar type = ''\n\tvar props = rules\n\tvar children = rulesets\n\tvar reference = rule\n\tvar characters = type\n\n\twhile (scanning)\n\t\tswitch (previous = character, character = next()) {\n\t\t\t// (\n\t\t\tcase 40:\n\t\t\t\tif (previous != 108 && charat(characters, length - 1) == 58) {\n\t\t\t\t\tif (indexof(characters += replace(delimit(character), '&', '&\\f'), '&\\f') != -1)\n\t\t\t\t\t\tampersand = -1\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t// \" ' [\n\t\t\tcase 34: case 39: case 91:\n\t\t\t\tcharacters += delimit(character)\n\t\t\t\tbreak\n\t\t\t// \\t \\n \\r \\s\n\t\t\tcase 9: case 10: case 13: case 32:\n\t\t\t\tcharacters += whitespace(previous)\n\t\t\t\tbreak\n\t\t\t// \\\n\t\t\tcase 92:\n\t\t\t\tcharacters += escaping(caret() - 1, 7)\n\t\t\t\tcontinue\n\t\t\t// /\n\t\t\tcase 47:\n\t\t\t\tswitch (peek()) {\n\t\t\t\t\tcase 42: case 47:\n\t\t\t\t\t\tappend(comment(commenter(next(), caret()), root, parent, declarations), declarations)\n\t\t\t\t\t\tbreak\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tcharacters += '/'\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t// {\n\t\t\tcase 123 * variable:\n\t\t\t\tpoints[index++] = strlen(characters) * ampersand\n\t\t\t// } ; \\0\n\t\t\tcase 125 * variable: case 59: case 0:\n\t\t\t\tswitch (character) {\n\t\t\t\t\t// \\0 }\n\t\t\t\t\tcase 0: case 125: scanning = 0\n\t\t\t\t\t// ;\n\t\t\t\t\tcase 59 + offset: if (ampersand == -1) characters = replace(characters, /\\f/g, '')\n\t\t\t\t\t\tif (property > 0 && (strlen(characters) - length))\n\t\t\t\t\t\t\tappend(property > 32 ? declaration(characters + ';', rule, parent, length - 1, declarations) : declaration(replace(characters, ' ', '') + ';', rule, parent, length - 2, declarations), declarations)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t// @ ;\n\t\t\t\t\tcase 59: characters += ';'\n\t\t\t\t\t// { rule/at-rule\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tappend(reference = ruleset(characters, root, parent, index, offset, rules, points, type, props = [], children = [], length, rulesets), rulesets)\n\n\t\t\t\t\t\tif (character === 123)\n\t\t\t\t\t\t\tif (offset === 0)\n\t\t\t\t\t\t\t\tparse(characters, root, reference, reference, props, rulesets, length, points, children)\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tswitch (atrule === 99 && charat(characters, 3) === 110 ? 100 : atrule) {\n\t\t\t\t\t\t\t\t\t// d l m s\n\t\t\t\t\t\t\t\t\tcase 100: case 108: case 109: case 115:\n\t\t\t\t\t\t\t\t\t\tparse(value, reference, reference, rule && append(ruleset(value, reference, reference, 0, 0, rules, points, type, rules, props = [], length, children), children), rules, children, length, points, rule ? props : children)\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t\tparse(characters, reference, reference, reference, [''], children, 0, points, children)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tindex = offset = property = 0, variable = ampersand = 1, type = characters = '', length = pseudo\n\t\t\t\tbreak\n\t\t\t// :\n\t\t\tcase 58:\n\t\t\t\tlength = 1 + strlen(characters), property = previous\n\t\t\tdefault:\n\t\t\t\tif (variable < 1)\n\t\t\t\t\tif (character == 123)\n\t\t\t\t\t\t--variable\n\t\t\t\t\telse if (character == 125 && variable++ == 0 && prev() == 125)\n\t\t\t\t\t\tcontinue\n\n\t\t\t\tswitch (characters += from(character), character * variable) {\n\t\t\t\t\t// &\n\t\t\t\t\tcase 38:\n\t\t\t\t\t\tampersand = offset > 0 ? 1 : (characters += '\\f', -1)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t// ,\n\t\t\t\t\tcase 44:\n\t\t\t\t\t\tpoints[index++] = (strlen(characters) - 1) * ampersand, ampersand = 1\n\t\t\t\t\t\tbreak\n\t\t\t\t\t// @\n\t\t\t\t\tcase 64:\n\t\t\t\t\t\t// -\n\t\t\t\t\t\tif (peek() === 45)\n\t\t\t\t\t\t\tcharacters += delimit(next())\n\n\t\t\t\t\t\tatrule = peek(), offset = length = strlen(type = characters += identifier(caret())), character++\n\t\t\t\t\t\tbreak\n\t\t\t\t\t// -\n\t\t\t\t\tcase 45:\n\t\t\t\t\t\tif (previous === 45 && strlen(characters) == 2)\n\t\t\t\t\t\t\tvariable = 0\n\t\t\t\t}\n\t\t}\n\n\treturn rulesets\n}\n\n/**\n * @param {string} value\n * @param {object} root\n * @param {object?} parent\n * @param {number} index\n * @param {number} offset\n * @param {string[]} rules\n * @param {number[]} points\n * @param {string} type\n * @param {string[]} props\n * @param {string[]} children\n * @param {number} length\n * @param {object[]} siblings\n * @return {object}\n */\nexport function ruleset (value, root, parent, index, offset, rules, points, type, props, children, length, siblings) {\n\tvar post = offset - 1\n\tvar rule = offset === 0 ? rules : ['']\n\tvar size = sizeof(rule)\n\n\tfor (var i = 0, j = 0, k = 0; i < index; ++i)\n\t\tfor (var x = 0, y = substr(value, post + 1, post = abs(j = points[i])), z = value; x < size; ++x)\n\t\t\tif (z = trim(j > 0 ? rule[x] + ' ' + y : replace(y, /&\\f/g, rule[x])))\n\t\t\t\tprops[k++] = z\n\n\treturn node(value, root, parent, offset === 0 ? RULESET : type, props, children, length, siblings)\n}\n\n/**\n * @param {number} value\n * @param {object} root\n * @param {object?} parent\n * @param {object[]} siblings\n * @return {object}\n */\nexport function comment (value, root, parent, siblings) {\n\treturn node(value, root, parent, COMMENT, from(char()), substr(value, 2, -2), 0, siblings)\n}\n\n/**\n * @param {string} value\n * @param {object} root\n * @param {object?} parent\n * @param {number} length\n * @param {object[]} siblings\n * @return {object}\n */\nexport function declaration (value, root, parent, length, siblings) {\n\treturn node(value, root, parent, DECLARATION, substr(value, 0, length), substr(value, length + 1, -1), length, siblings)\n}\n","import { lintWarning } from \"./utils\";\nfunction isConcatSelector(selector) {\n var _selector$match;\n var notContent = ((_selector$match = selector.match(/:not\\(([^)]*)\\)/)) === null || _selector$match === void 0 ? void 0 : _selector$match[1]) || '';\n\n // split selector. e.g.\n // `h1#a.b` => ['h1', #a', '.b']\n var splitCells = notContent.split(/(\\[[^[]*])|(?=[.#])/).filter(function (str) {\n return str;\n });\n return splitCells.length > 1;\n}\nfunction parsePath(info) {\n return info.parentSelectors.reduce(function (prev, cur) {\n if (!prev) {\n return cur;\n }\n return cur.includes('&') ? cur.replace(/&/g, prev) : \"\".concat(prev, \" \").concat(cur);\n }, '');\n}\nvar linter = function linter(key, value, info) {\n var parentSelectorPath = parsePath(info);\n var notList = parentSelectorPath.match(/:not\\([^)]*\\)/g) || [];\n if (notList.length > 0 && notList.some(isConcatSelector)) {\n lintWarning(\"Concat ':not' selector not support in legacy browsers.\", info);\n }\n};\nexport default linter;","import _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport canUseDom from \"rc-util/es/Dom/canUseDom\";\nimport { ATTR_MARK } from \"../../StyleContext\";\nexport var ATTR_CACHE_MAP = 'data-ant-cssinjs-cache-path';\n\n/**\n * This marks style from the css file.\n * Which means not exist in `` tag.\n */\nexport var CSS_FILE_STYLE = '_FILE_STYLE__';\nexport function serialize(cachePathMap) {\n return Object.keys(cachePathMap).map(function (path) {\n var hash = cachePathMap[path];\n return \"\".concat(path, \":\").concat(hash);\n }).join(';');\n}\nvar cachePathMap;\nvar fromCSSFile = true;\n\n/**\n * @private Test usage only. Can save remove if no need.\n */\nexport function reset(mockCache) {\n var fromFile = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n cachePathMap = mockCache;\n fromCSSFile = fromFile;\n}\nexport function prepare() {\n if (!cachePathMap) {\n cachePathMap = {};\n if (canUseDom()) {\n var div = document.createElement('div');\n div.className = ATTR_CACHE_MAP;\n div.style.position = 'fixed';\n div.style.visibility = 'hidden';\n div.style.top = '-9999px';\n document.body.appendChild(div);\n var content = getComputedStyle(div).content || '';\n content = content.replace(/^\"/, '').replace(/\"$/, '');\n\n // Fill data\n content.split(';').forEach(function (item) {\n var _item$split = item.split(':'),\n _item$split2 = _slicedToArray(_item$split, 2),\n path = _item$split2[0],\n hash = _item$split2[1];\n cachePathMap[path] = hash;\n });\n\n // Remove inline record style\n var inlineMapStyle = document.querySelector(\"style[\".concat(ATTR_CACHE_MAP, \"]\"));\n if (inlineMapStyle) {\n var _inlineMapStyle$paren;\n fromCSSFile = false;\n (_inlineMapStyle$paren = inlineMapStyle.parentNode) === null || _inlineMapStyle$paren === void 0 ? void 0 : _inlineMapStyle$paren.removeChild(inlineMapStyle);\n }\n document.body.removeChild(div);\n }\n }\n}\nexport function existPath(path) {\n prepare();\n return !!cachePathMap[path];\n}\nexport function getStyleAndHash(path) {\n var hash = cachePathMap[path];\n var styleStr = null;\n if (hash && canUseDom()) {\n if (fromCSSFile) {\n styleStr = CSS_FILE_STYLE;\n } else {\n var _style = document.querySelector(\"style[\".concat(ATTR_MARK, \"=\\\"\").concat(cachePathMap[path], \"\\\"]\"));\n if (_style) {\n styleStr = _style.innerHTML;\n } else {\n // Clean up since not exist anymore\n delete cachePathMap[path];\n }\n }\n }\n return [styleStr, hash];\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\nimport _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport _toConsumableArray from \"@babel/runtime/helpers/esm/toConsumableArray\";\nimport _typeof from \"@babel/runtime/helpers/esm/typeof\";\nimport hash from '@emotion/hash';\nimport canUseDom from \"rc-util/es/Dom/canUseDom\";\nimport { removeCSS, updateCSS } from \"rc-util/es/Dom/dynamicCSS\";\nimport * as React from 'react';\n// @ts-ignore\nimport unitless from '@emotion/unitless';\nimport { compile, serialize, stringify } from 'stylis';\nimport { contentQuotesLinter, hashedAnimationLinter } from \"../../linters\";\nimport StyleContext, { ATTR_CACHE_PATH, ATTR_MARK, ATTR_TOKEN, CSS_IN_JS_INSTANCE } from \"../../StyleContext\";\nimport { supportLayer } from \"../../util\";\nimport useGlobalCache from \"../useGlobalCache\";\nimport { ATTR_CACHE_MAP, CSS_FILE_STYLE, existPath, getStyleAndHash, serialize as serializeCacheMap } from \"./cacheMapUtil\";\nvar isClientSide = canUseDom();\nvar SKIP_CHECK = '_skip_check_';\nvar MULTI_VALUE = '_multi_value_';\n// ============================================================================\n// == Parser ==\n// ============================================================================\n// Preprocessor style content to browser support one\nexport function normalizeStyle(styleStr) {\n var serialized = serialize(compile(styleStr), stringify);\n return serialized.replace(/\\{%%%\\:[^;];}/g, ';');\n}\nfunction isCompoundCSSProperty(value) {\n return _typeof(value) === 'object' && value && (SKIP_CHECK in value || MULTI_VALUE in value);\n}\n\n// 注入 hash 值\nfunction injectSelectorHash(key, hashId, hashPriority) {\n if (!hashId) {\n return key;\n }\n var hashClassName = \".\".concat(hashId);\n var hashSelector = hashPriority === 'low' ? \":where(\".concat(hashClassName, \")\") : hashClassName;\n\n // 注入 hashId\n var keys = key.split(',').map(function (k) {\n var _firstPath$match;\n var fullPath = k.trim().split(/\\s+/);\n\n // 如果 Selector 第一个是 HTML Element,那我们就插到它的后面。反之,就插到最前面。\n var firstPath = fullPath[0] || '';\n var htmlElement = ((_firstPath$match = firstPath.match(/^\\w+/)) === null || _firstPath$match === void 0 ? void 0 : _firstPath$match[0]) || '';\n firstPath = \"\".concat(htmlElement).concat(hashSelector).concat(firstPath.slice(htmlElement.length));\n return [firstPath].concat(_toConsumableArray(fullPath.slice(1))).join(' ');\n });\n return keys.join(',');\n}\n// Parse CSSObject to style content\nexport var parseStyle = function parseStyle(interpolation) {\n var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {\n root: true,\n parentSelectors: []\n },\n root = _ref.root,\n injectHash = _ref.injectHash,\n parentSelectors = _ref.parentSelectors;\n var hashId = config.hashId,\n layer = config.layer,\n path = config.path,\n hashPriority = config.hashPriority,\n _config$transformers = config.transformers,\n transformers = _config$transformers === void 0 ? [] : _config$transformers,\n _config$linters = config.linters,\n linters = _config$linters === void 0 ? [] : _config$linters;\n var styleStr = '';\n var effectStyle = {};\n function parseKeyframes(keyframes) {\n var animationName = keyframes.getName(hashId);\n if (!effectStyle[animationName]) {\n var _parseStyle = parseStyle(keyframes.style, config, {\n root: false,\n parentSelectors: parentSelectors\n }),\n _parseStyle2 = _slicedToArray(_parseStyle, 1),\n _parsedStr = _parseStyle2[0];\n effectStyle[animationName] = \"@keyframes \".concat(keyframes.getName(hashId)).concat(_parsedStr);\n }\n }\n function flattenList(list) {\n var fullList = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];\n list.forEach(function (item) {\n if (Array.isArray(item)) {\n flattenList(item, fullList);\n } else if (item) {\n fullList.push(item);\n }\n });\n return fullList;\n }\n var flattenStyleList = flattenList(Array.isArray(interpolation) ? interpolation : [interpolation]);\n flattenStyleList.forEach(function (originStyle) {\n // Only root level can use raw string\n var style = typeof originStyle === 'string' && !root ? {} : originStyle;\n if (typeof style === 'string') {\n styleStr += \"\".concat(style, \"\\n\");\n } else if (style._keyframe) {\n // Keyframe\n parseKeyframes(style);\n } else {\n var mergedStyle = transformers.reduce(function (prev, trans) {\n var _trans$visit;\n return (trans === null || trans === void 0 ? void 0 : (_trans$visit = trans.visit) === null || _trans$visit === void 0 ? void 0 : _trans$visit.call(trans, prev)) || prev;\n }, style);\n\n // Normal CSSObject\n Object.keys(mergedStyle).forEach(function (key) {\n var value = mergedStyle[key];\n if (_typeof(value) === 'object' && value && (key !== 'animationName' || !value._keyframe) && !isCompoundCSSProperty(value)) {\n var subInjectHash = false;\n\n // 当成嵌套对象来处理\n var mergedKey = key.trim();\n // Whether treat child as root. In most case it is false.\n var nextRoot = false;\n\n // 拆分多个选择器\n if ((root || injectHash) && hashId) {\n if (mergedKey.startsWith('@')) {\n // 略过媒体查询,交给子节点继续插入 hashId\n subInjectHash = true;\n } else {\n // 注入 hashId\n mergedKey = injectSelectorHash(key, hashId, hashPriority);\n }\n } else if (root && !hashId && (mergedKey === '&' || mergedKey === '')) {\n // In case of `{ '&': { a: { color: 'red' } } }` or `{ '': { a: { color: 'red' } } }` without hashId,\n // we will get `&{a:{color:red;}}` or `{a:{color:red;}}` string for stylis to compile.\n // But it does not conform to stylis syntax,\n // and finally we will get `{color:red;}` as css, which is wrong.\n // So we need to remove key in root, and treat child `{ a: { color: 'red' } }` as root.\n mergedKey = '';\n nextRoot = true;\n }\n var _parseStyle3 = parseStyle(value, config, {\n root: nextRoot,\n injectHash: subInjectHash,\n parentSelectors: [].concat(_toConsumableArray(parentSelectors), [mergedKey])\n }),\n _parseStyle4 = _slicedToArray(_parseStyle3, 2),\n _parsedStr2 = _parseStyle4[0],\n childEffectStyle = _parseStyle4[1];\n effectStyle = _objectSpread(_objectSpread({}, effectStyle), childEffectStyle);\n styleStr += \"\".concat(mergedKey).concat(_parsedStr2);\n } else {\n var _value;\n function appendStyle(cssKey, cssValue) {\n if (process.env.NODE_ENV !== 'production' && (_typeof(value) !== 'object' || !(value !== null && value !== void 0 && value[SKIP_CHECK]))) {\n [contentQuotesLinter, hashedAnimationLinter].concat(_toConsumableArray(linters)).forEach(function (linter) {\n return linter(cssKey, cssValue, {\n path: path,\n hashId: hashId,\n parentSelectors: parentSelectors\n });\n });\n }\n\n // 如果是样式则直接插入\n var styleName = cssKey.replace(/[A-Z]/g, function (match) {\n return \"-\".concat(match.toLowerCase());\n });\n\n // Auto suffix with px\n var formatValue = cssValue;\n if (!unitless[cssKey] && typeof formatValue === 'number' && formatValue !== 0) {\n formatValue = \"\".concat(formatValue, \"px\");\n }\n\n // handle animationName & Keyframe value\n if (cssKey === 'animationName' && cssValue !== null && cssValue !== void 0 && cssValue._keyframe) {\n parseKeyframes(cssValue);\n formatValue = cssValue.getName(hashId);\n }\n styleStr += \"\".concat(styleName, \":\").concat(formatValue, \";\");\n }\n var actualValue = (_value = value === null || value === void 0 ? void 0 : value.value) !== null && _value !== void 0 ? _value : value;\n if (_typeof(value) === 'object' && value !== null && value !== void 0 && value[MULTI_VALUE] && Array.isArray(actualValue)) {\n actualValue.forEach(function (item) {\n appendStyle(key, item);\n });\n } else {\n appendStyle(key, actualValue);\n }\n }\n });\n }\n });\n if (!root) {\n styleStr = \"{\".concat(styleStr, \"}\");\n } else if (layer && supportLayer()) {\n var layerCells = layer.split(',');\n var layerName = layerCells[layerCells.length - 1].trim();\n styleStr = \"@layer \".concat(layerName, \" {\").concat(styleStr, \"}\");\n\n // Order of layer if needed\n if (layerCells.length > 1) {\n // zombieJ: stylis do not support layer order, so we need to handle it manually.\n styleStr = \"@layer \".concat(layer, \"{%%%:%}\").concat(styleStr);\n }\n }\n return [styleStr, effectStyle];\n};\n\n// ============================================================================\n// == Register ==\n// ============================================================================\nfunction uniqueHash(path, styleStr) {\n return hash(\"\".concat(path.join('%')).concat(styleStr));\n}\nfunction Empty() {\n return null;\n}\n\n/**\n * Register a style to the global style sheet.\n */\nexport default function useStyleRegister(info, styleFn) {\n var token = info.token,\n path = info.path,\n hashId = info.hashId,\n layer = info.layer,\n nonce = info.nonce,\n clientOnly = info.clientOnly,\n _info$order = info.order,\n order = _info$order === void 0 ? 0 : _info$order;\n var _React$useContext = React.useContext(StyleContext),\n autoClear = _React$useContext.autoClear,\n mock = _React$useContext.mock,\n defaultCache = _React$useContext.defaultCache,\n hashPriority = _React$useContext.hashPriority,\n container = _React$useContext.container,\n ssrInline = _React$useContext.ssrInline,\n transformers = _React$useContext.transformers,\n linters = _React$useContext.linters,\n cache = _React$useContext.cache;\n var tokenKey = token._tokenKey;\n var fullPath = [tokenKey].concat(_toConsumableArray(path));\n\n // Check if need insert style\n var isMergedClientSide = isClientSide;\n if (process.env.NODE_ENV !== 'production' && mock !== undefined) {\n isMergedClientSide = mock === 'client';\n }\n var _useGlobalCache = useGlobalCache('style', fullPath,\n // Create cache if needed\n function () {\n var cachePath = fullPath.join('|');\n\n // Get style from SSR inline style directly\n if (existPath(cachePath)) {\n var _getStyleAndHash = getStyleAndHash(cachePath),\n _getStyleAndHash2 = _slicedToArray(_getStyleAndHash, 2),\n inlineCacheStyleStr = _getStyleAndHash2[0],\n styleHash = _getStyleAndHash2[1];\n if (inlineCacheStyleStr) {\n return [inlineCacheStyleStr, tokenKey, styleHash, {}, clientOnly, order];\n }\n }\n\n // Generate style\n var styleObj = styleFn();\n var _parseStyle5 = parseStyle(styleObj, {\n hashId: hashId,\n hashPriority: hashPriority,\n layer: layer,\n path: path.join('-'),\n transformers: transformers,\n linters: linters\n }),\n _parseStyle6 = _slicedToArray(_parseStyle5, 2),\n parsedStyle = _parseStyle6[0],\n effectStyle = _parseStyle6[1];\n var styleStr = normalizeStyle(parsedStyle);\n var styleId = uniqueHash(fullPath, styleStr);\n return [styleStr, tokenKey, styleId, effectStyle, clientOnly, order];\n },\n // Remove cache if no need\n function (_ref2, fromHMR) {\n var _ref3 = _slicedToArray(_ref2, 3),\n styleId = _ref3[2];\n if ((fromHMR || autoClear) && isClientSide) {\n removeCSS(styleId, {\n mark: ATTR_MARK\n });\n }\n },\n // Effect: Inject style here\n function (_ref4) {\n var _ref5 = _slicedToArray(_ref4, 4),\n styleStr = _ref5[0],\n _ = _ref5[1],\n styleId = _ref5[2],\n effectStyle = _ref5[3];\n if (isMergedClientSide && styleStr !== CSS_FILE_STYLE) {\n var mergedCSSConfig = {\n mark: ATTR_MARK,\n prepend: 'queue',\n attachTo: container,\n priority: order\n };\n var nonceStr = typeof nonce === 'function' ? nonce() : nonce;\n if (nonceStr) {\n mergedCSSConfig.csp = {\n nonce: nonceStr\n };\n }\n var _style = updateCSS(styleStr, styleId, mergedCSSConfig);\n _style[CSS_IN_JS_INSTANCE] = cache.instanceId;\n\n // Used for `useCacheToken` to remove on batch when token removed\n _style.setAttribute(ATTR_TOKEN, tokenKey);\n\n // Debug usage. Dev only\n if (process.env.NODE_ENV !== 'production') {\n _style.setAttribute(ATTR_CACHE_PATH, fullPath.join('|'));\n }\n\n // Inject client side effect style\n Object.keys(effectStyle).forEach(function (effectKey) {\n updateCSS(normalizeStyle(effectStyle[effectKey]), \"_effect-\".concat(effectKey), mergedCSSConfig);\n });\n }\n }),\n _useGlobalCache2 = _slicedToArray(_useGlobalCache, 3),\n cachedStyleStr = _useGlobalCache2[0],\n cachedTokenKey = _useGlobalCache2[1],\n cachedStyleId = _useGlobalCache2[2];\n return function (node) {\n var styleNode;\n if (!ssrInline || isMergedClientSide || !defaultCache) {\n styleNode = /*#__PURE__*/React.createElement(Empty, null);\n } else {\n var _ref6;\n styleNode = /*#__PURE__*/React.createElement(\"style\", _extends({}, (_ref6 = {}, _defineProperty(_ref6, ATTR_TOKEN, cachedTokenKey), _defineProperty(_ref6, ATTR_MARK, cachedStyleId), _ref6), {\n dangerouslySetInnerHTML: {\n __html: cachedStyleStr\n }\n }));\n }\n return /*#__PURE__*/React.createElement(React.Fragment, null, styleNode, node);\n };\n}\n\n// ============================================================================\n// == SSR ==\n// ============================================================================\nexport function extractStyle(cache) {\n var plain = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n var matchPrefix = \"style%\";\n\n // prefix with `style` is used for `useStyleRegister` to cache style context\n var styleKeys = Array.from(cache.cache.keys()).filter(function (key) {\n return key.startsWith(matchPrefix);\n });\n\n // Common effect styles like animation\n var effectStyles = {};\n\n // Mapping of cachePath to style hash\n var cachePathMap = {};\n var styleText = '';\n function toStyleStr(style, tokenKey, styleId) {\n var _objectSpread2;\n var customizeAttrs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n var attrs = _objectSpread(_objectSpread({}, customizeAttrs), {}, (_objectSpread2 = {}, _defineProperty(_objectSpread2, ATTR_TOKEN, tokenKey), _defineProperty(_objectSpread2, ATTR_MARK, styleId), _objectSpread2));\n var attrStr = Object.keys(attrs).map(function (attr) {\n var val = attrs[attr];\n return val ? \"\".concat(attr, \"=\\\"\").concat(val, \"\\\"\") : null;\n }).filter(function (v) {\n return v;\n }).join(' ');\n return plain ? style : \"\");\n }\n\n // ====================== Fill Style ======================\n\n var orderStyles = styleKeys.map(function (key) {\n var cachePath = key.slice(matchPrefix.length).replace(/%/g, '|');\n var _2 = _slicedToArray(cache.cache.get(key)[1], 6),\n styleStr = _2[0],\n tokenKey = _2[1],\n styleId = _2[2],\n effectStyle = _2[3],\n clientOnly = _2[4],\n order = _2[5];\n\n // Skip client only style\n if (clientOnly) {\n return null;\n }\n\n // ====================== Style ======================\n // Used for rc-util\n var sharedAttrs = {\n 'data-rc-order': 'prependQueue',\n 'data-rc-priority': \"\".concat(order)\n };\n var keyStyleText = toStyleStr(styleStr, tokenKey, styleId, sharedAttrs);\n\n // Save cache path with hash mapping\n cachePathMap[cachePath] = styleId;\n\n // =============== Create effect style ===============\n if (effectStyle) {\n Object.keys(effectStyle).forEach(function (effectKey) {\n // Effect style can be reused\n if (!effectStyles[effectKey]) {\n effectStyles[effectKey] = true;\n keyStyleText += toStyleStr(normalizeStyle(effectStyle[effectKey]), tokenKey, \"_effect-\".concat(effectKey), sharedAttrs);\n }\n });\n }\n var ret = [order, keyStyleText];\n return ret;\n }).filter(function (o) {\n return o;\n });\n orderStyles.sort(function (o1, o2) {\n return o1[0] - o2[0];\n }).forEach(function (_ref7) {\n var _ref8 = _slicedToArray(_ref7, 2),\n style = _ref8[1];\n styleText += style;\n });\n\n // ==================== Fill Cache Path ====================\n styleText += toStyleStr(\".\".concat(ATTR_CACHE_MAP, \"{content:\\\"\").concat(serializeCacheMap(cachePathMap), \"\\\";}\"), undefined, undefined, _defineProperty({}, ATTR_CACHE_MAP, ATTR_CACHE_MAP));\n return styleText;\n}","import _classCallCheck from \"@babel/runtime/helpers/esm/classCallCheck\";\nimport _createClass from \"@babel/runtime/helpers/esm/createClass\";\nimport _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nvar Keyframe = /*#__PURE__*/function () {\n function Keyframe(name, style) {\n _classCallCheck(this, Keyframe);\n _defineProperty(this, \"name\", void 0);\n _defineProperty(this, \"style\", void 0);\n _defineProperty(this, \"_keyframe\", true);\n this.name = name;\n this.style = style;\n }\n _createClass(Keyframe, [{\n key: \"getName\",\n value: function getName() {\n var hashId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';\n return hashId ? \"\".concat(hashId, \"-\").concat(this.name) : this.name;\n }\n }]);\n return Keyframe;\n}();\nexport default Keyframe;","import _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nfunction splitValues(value) {\n if (typeof value === 'number') {\n return [[value], false];\n }\n var rawStyle = String(value).trim();\n var importantCells = rawStyle.match(/(.*)(!important)/);\n var splitStyle = (importantCells ? importantCells[1] : rawStyle).trim().split(/\\s+/);\n\n // Combine styles split in brackets, like `calc(1px + 2px)`\n var temp = '';\n var brackets = 0;\n return [splitStyle.reduce(function (list, item) {\n if (item.includes('(')) {\n temp += item;\n brackets += item.split('(').length - 1;\n } else if (item.includes(')')) {\n temp += item;\n brackets -= item.split(')').length - 1;\n if (brackets === 0) {\n list.push(temp);\n temp = '';\n }\n } else if (brackets > 0) {\n temp += item;\n } else {\n list.push(item);\n }\n return list;\n }, []), !!importantCells];\n}\nfunction noSplit(list) {\n list.notSplit = true;\n return list;\n}\nvar keyMap = {\n // Inset\n inset: ['top', 'right', 'bottom', 'left'],\n insetBlock: ['top', 'bottom'],\n insetBlockStart: ['top'],\n insetBlockEnd: ['bottom'],\n insetInline: ['left', 'right'],\n insetInlineStart: ['left'],\n insetInlineEnd: ['right'],\n // Margin\n marginBlock: ['marginTop', 'marginBottom'],\n marginBlockStart: ['marginTop'],\n marginBlockEnd: ['marginBottom'],\n marginInline: ['marginLeft', 'marginRight'],\n marginInlineStart: ['marginLeft'],\n marginInlineEnd: ['marginRight'],\n // Padding\n paddingBlock: ['paddingTop', 'paddingBottom'],\n paddingBlockStart: ['paddingTop'],\n paddingBlockEnd: ['paddingBottom'],\n paddingInline: ['paddingLeft', 'paddingRight'],\n paddingInlineStart: ['paddingLeft'],\n paddingInlineEnd: ['paddingRight'],\n // Border\n borderBlock: noSplit(['borderTop', 'borderBottom']),\n borderBlockStart: noSplit(['borderTop']),\n borderBlockEnd: noSplit(['borderBottom']),\n borderInline: noSplit(['borderLeft', 'borderRight']),\n borderInlineStart: noSplit(['borderLeft']),\n borderInlineEnd: noSplit(['borderRight']),\n // Border width\n borderBlockWidth: ['borderTopWidth', 'borderBottomWidth'],\n borderBlockStartWidth: ['borderTopWidth'],\n borderBlockEndWidth: ['borderBottomWidth'],\n borderInlineWidth: ['borderLeftWidth', 'borderRightWidth'],\n borderInlineStartWidth: ['borderLeftWidth'],\n borderInlineEndWidth: ['borderRightWidth'],\n // Border style\n borderBlockStyle: ['borderTopStyle', 'borderBottomStyle'],\n borderBlockStartStyle: ['borderTopStyle'],\n borderBlockEndStyle: ['borderBottomStyle'],\n borderInlineStyle: ['borderLeftStyle', 'borderRightStyle'],\n borderInlineStartStyle: ['borderLeftStyle'],\n borderInlineEndStyle: ['borderRightStyle'],\n // Border color\n borderBlockColor: ['borderTopColor', 'borderBottomColor'],\n borderBlockStartColor: ['borderTopColor'],\n borderBlockEndColor: ['borderBottomColor'],\n borderInlineColor: ['borderLeftColor', 'borderRightColor'],\n borderInlineStartColor: ['borderLeftColor'],\n borderInlineEndColor: ['borderRightColor'],\n // Border radius\n borderStartStartRadius: ['borderTopLeftRadius'],\n borderStartEndRadius: ['borderTopRightRadius'],\n borderEndStartRadius: ['borderBottomLeftRadius'],\n borderEndEndRadius: ['borderBottomRightRadius']\n};\nfunction wrapImportantAndSkipCheck(value, important) {\n var parsedValue = value;\n if (important) {\n parsedValue = \"\".concat(parsedValue, \" !important\");\n }\n return {\n _skip_check_: true,\n value: parsedValue\n };\n}\n\n/**\n * Convert css logical properties to legacy properties.\n * Such as: `margin-block-start` to `margin-top`.\n * Transform list:\n * - inset\n * - margin\n * - padding\n * - border\n */\nvar transform = {\n visit: function visit(cssObj) {\n var clone = {};\n Object.keys(cssObj).forEach(function (key) {\n var value = cssObj[key];\n var matchValue = keyMap[key];\n if (matchValue && (typeof value === 'number' || typeof value === 'string')) {\n var _splitValues = splitValues(value),\n _splitValues2 = _slicedToArray(_splitValues, 2),\n _values = _splitValues2[0],\n _important = _splitValues2[1];\n if (matchValue.length && matchValue.notSplit) {\n // not split means always give same value like border\n matchValue.forEach(function (matchKey) {\n clone[matchKey] = wrapImportantAndSkipCheck(value, _important);\n });\n } else if (matchValue.length === 1) {\n // Handle like `marginBlockStart` => `marginTop`\n clone[matchValue[0]] = wrapImportantAndSkipCheck(value, _important);\n } else if (matchValue.length === 2) {\n // Handle like `marginBlock` => `marginTop` & `marginBottom`\n matchValue.forEach(function (matchKey, index) {\n var _values$index;\n clone[matchKey] = wrapImportantAndSkipCheck((_values$index = _values[index]) !== null && _values$index !== void 0 ? _values$index : _values[0], _important);\n });\n } else if (matchValue.length === 4) {\n // Handle like `inset` => `top` & `right` & `bottom` & `left`\n matchValue.forEach(function (matchKey, index) {\n var _ref, _values$index2;\n clone[matchKey] = wrapImportantAndSkipCheck((_ref = (_values$index2 = _values[index]) !== null && _values$index2 !== void 0 ? _values$index2 : _values[index - 2]) !== null && _ref !== void 0 ? _ref : _values[0], _important);\n });\n } else {\n clone[key] = value;\n }\n } else {\n clone[key] = value;\n }\n });\n return clone;\n }\n};\nexport default transform;","import _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\nimport _typeof from \"@babel/runtime/helpers/esm/typeof\";\nimport { generate as generateColor } from '@ant-design/colors';\nimport camelCase from 'lodash.camelcase';\nimport { updateCSS } from \"rc-util/es/Dom/dynamicCSS\";\nimport { getShadowRoot } from \"rc-util/es/Dom/shadow\";\nimport warn from \"rc-util/es/warning\";\nimport React, { useContext, useEffect } from 'react';\nimport IconContext from \"./components/Context\";\nexport function warning(valid, message) {\n warn(valid, \"[@ant-design/icons] \".concat(message));\n}\nexport function isIconDefinition(target) {\n return _typeof(target) === 'object' && typeof target.name === 'string' && typeof target.theme === 'string' && (_typeof(target.icon) === 'object' || typeof target.icon === 'function');\n}\nexport function normalizeAttrs() {\n var attrs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n return Object.keys(attrs).reduce(function (acc, key) {\n var val = attrs[key];\n switch (key) {\n case 'class':\n acc.className = val;\n delete acc.class;\n break;\n default:\n delete acc[key];\n acc[camelCase(key)] = val;\n }\n return acc;\n }, {});\n}\nexport function generate(node, key, rootProps) {\n if (!rootProps) {\n return /*#__PURE__*/React.createElement(node.tag, _objectSpread({\n key: key\n }, normalizeAttrs(node.attrs)), (node.children || []).map(function (child, index) {\n return generate(child, \"\".concat(key, \"-\").concat(node.tag, \"-\").concat(index));\n }));\n }\n return /*#__PURE__*/React.createElement(node.tag, _objectSpread(_objectSpread({\n key: key\n }, normalizeAttrs(node.attrs)), rootProps), (node.children || []).map(function (child, index) {\n return generate(child, \"\".concat(key, \"-\").concat(node.tag, \"-\").concat(index));\n }));\n}\nexport function getSecondaryColor(primaryColor) {\n // choose the second color\n return generateColor(primaryColor)[0];\n}\nexport function normalizeTwoToneColors(twoToneColor) {\n if (!twoToneColor) {\n return [];\n }\n return Array.isArray(twoToneColor) ? twoToneColor : [twoToneColor];\n}\n\n// These props make sure that the SVG behaviours like general text.\n// Reference: https://blog.prototypr.io/align-svg-icons-to-text-and-say-goodbye-to-font-icons-d44b3d7b26b4\nexport var svgBaseProps = {\n width: '1em',\n height: '1em',\n fill: 'currentColor',\n 'aria-hidden': 'true',\n focusable: 'false'\n};\nexport var iconStyles = \"\\n.anticon {\\n display: inline-block;\\n color: inherit;\\n font-style: normal;\\n line-height: 0;\\n text-align: center;\\n text-transform: none;\\n vertical-align: -0.125em;\\n text-rendering: optimizeLegibility;\\n -webkit-font-smoothing: antialiased;\\n -moz-osx-font-smoothing: grayscale;\\n}\\n\\n.anticon > * {\\n line-height: 1;\\n}\\n\\n.anticon svg {\\n display: inline-block;\\n}\\n\\n.anticon::before {\\n display: none;\\n}\\n\\n.anticon .anticon-icon {\\n display: block;\\n}\\n\\n.anticon[tabindex] {\\n cursor: pointer;\\n}\\n\\n.anticon-spin::before,\\n.anticon-spin {\\n display: inline-block;\\n -webkit-animation: loadingCircle 1s infinite linear;\\n animation: loadingCircle 1s infinite linear;\\n}\\n\\n@-webkit-keyframes loadingCircle {\\n 100% {\\n -webkit-transform: rotate(360deg);\\n transform: rotate(360deg);\\n }\\n}\\n\\n@keyframes loadingCircle {\\n 100% {\\n -webkit-transform: rotate(360deg);\\n transform: rotate(360deg);\\n }\\n}\\n\";\nexport var useInsertStyles = function useInsertStyles(eleRef) {\n var _useContext = useContext(IconContext),\n csp = _useContext.csp,\n prefixCls = _useContext.prefixCls;\n var mergedStyleStr = iconStyles;\n if (prefixCls) {\n mergedStyleStr = mergedStyleStr.replace(/anticon/g, prefixCls);\n }\n useEffect(function () {\n var ele = eleRef.current;\n var shadowRoot = getShadowRoot(ele);\n updateCSS(mergedStyleStr, '@ant-design-icons', {\n prepend: true,\n csp: csp,\n attachTo: shadowRoot\n });\n }, []);\n};","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _objectSpread from \"@babel/runtime/helpers/esm/objectSpread2\";\nvar _excluded = [\"icon\", \"className\", \"onClick\", \"style\", \"primaryColor\", \"secondaryColor\"];\nimport * as React from 'react';\nimport { generate, getSecondaryColor, isIconDefinition, warning, useInsertStyles } from \"../utils\";\nvar twoToneColorPalette = {\n primaryColor: '#333',\n secondaryColor: '#E6E6E6',\n calculated: false\n};\nfunction setTwoToneColors(_ref) {\n var primaryColor = _ref.primaryColor,\n secondaryColor = _ref.secondaryColor;\n twoToneColorPalette.primaryColor = primaryColor;\n twoToneColorPalette.secondaryColor = secondaryColor || getSecondaryColor(primaryColor);\n twoToneColorPalette.calculated = !!secondaryColor;\n}\nfunction getTwoToneColors() {\n return _objectSpread({}, twoToneColorPalette);\n}\nvar IconBase = function IconBase(props) {\n var icon = props.icon,\n className = props.className,\n onClick = props.onClick,\n style = props.style,\n primaryColor = props.primaryColor,\n secondaryColor = props.secondaryColor,\n restProps = _objectWithoutProperties(props, _excluded);\n var svgRef = React.useRef();\n var colors = twoToneColorPalette;\n if (primaryColor) {\n colors = {\n primaryColor: primaryColor,\n secondaryColor: secondaryColor || getSecondaryColor(primaryColor)\n };\n }\n useInsertStyles(svgRef);\n warning(isIconDefinition(icon), \"icon should be icon definiton, but got \".concat(icon));\n if (!isIconDefinition(icon)) {\n return null;\n }\n var target = icon;\n if (target && typeof target.icon === 'function') {\n target = _objectSpread(_objectSpread({}, target), {}, {\n icon: target.icon(colors.primaryColor, colors.secondaryColor)\n });\n }\n return generate(target.icon, \"svg-\".concat(target.name), _objectSpread(_objectSpread({\n className: className,\n onClick: onClick,\n style: style,\n 'data-icon': target.name,\n width: '1em',\n height: '1em',\n fill: 'currentColor',\n 'aria-hidden': 'true'\n }, restProps), {}, {\n ref: svgRef\n }));\n};\nIconBase.displayName = 'IconReact';\nIconBase.getTwoToneColors = getTwoToneColors;\nIconBase.setTwoToneColors = setTwoToneColors;\nexport default IconBase;","import _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport ReactIcon from \"./IconBase\";\nimport { normalizeTwoToneColors } from \"../utils\";\nexport function setTwoToneColor(twoToneColor) {\n var _normalizeTwoToneColo = normalizeTwoToneColors(twoToneColor),\n _normalizeTwoToneColo2 = _slicedToArray(_normalizeTwoToneColo, 2),\n primaryColor = _normalizeTwoToneColo2[0],\n secondaryColor = _normalizeTwoToneColo2[1];\n return ReactIcon.setTwoToneColors({\n primaryColor: primaryColor,\n secondaryColor: secondaryColor\n });\n}\nexport function getTwoToneColor() {\n var colors = ReactIcon.getTwoToneColors();\n if (!colors.calculated) {\n return colors.primaryColor;\n }\n return [colors.primaryColor, colors.secondaryColor];\n}","'use client';\n\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nvar _excluded = [\"className\", \"icon\", \"spin\", \"rotate\", \"tabIndex\", \"onClick\", \"twoToneColor\"];\nimport * as React from 'react';\nimport classNames from 'classnames';\nimport { blue } from '@ant-design/colors';\nimport Context from \"./Context\";\nimport ReactIcon from \"./IconBase\";\nimport { getTwoToneColor, setTwoToneColor } from \"./twoTonePrimaryColor\";\nimport { normalizeTwoToneColors } from \"../utils\";\n// Initial setting\n// should move it to antd main repo?\nsetTwoToneColor(blue.primary);\n\n// https://github.com/DefinitelyTyped/DefinitelyTyped/issues/34757#issuecomment-488848720\n\nvar Icon = /*#__PURE__*/React.forwardRef(function (props, ref) {\n var _classNames;\n var className = props.className,\n icon = props.icon,\n spin = props.spin,\n rotate = props.rotate,\n tabIndex = props.tabIndex,\n onClick = props.onClick,\n twoToneColor = props.twoToneColor,\n restProps = _objectWithoutProperties(props, _excluded);\n var _React$useContext = React.useContext(Context),\n _React$useContext$pre = _React$useContext.prefixCls,\n prefixCls = _React$useContext$pre === void 0 ? 'anticon' : _React$useContext$pre,\n rootClassName = _React$useContext.rootClassName;\n var classString = classNames(rootClassName, prefixCls, (_classNames = {}, _defineProperty(_classNames, \"\".concat(prefixCls, \"-\").concat(icon.name), !!icon.name), _defineProperty(_classNames, \"\".concat(prefixCls, \"-spin\"), !!spin || icon.name === 'loading'), _classNames), className);\n var iconTabIndex = tabIndex;\n if (iconTabIndex === undefined && onClick) {\n iconTabIndex = -1;\n }\n var svgStyle = rotate ? {\n msTransform: \"rotate(\".concat(rotate, \"deg)\"),\n transform: \"rotate(\".concat(rotate, \"deg)\")\n } : undefined;\n var _normalizeTwoToneColo = normalizeTwoToneColors(twoToneColor),\n _normalizeTwoToneColo2 = _slicedToArray(_normalizeTwoToneColo, 2),\n primaryColor = _normalizeTwoToneColo2[0],\n secondaryColor = _normalizeTwoToneColo2[1];\n return /*#__PURE__*/React.createElement(\"span\", _extends({\n role: \"img\",\n \"aria-label\": icon.name\n }, restProps, {\n ref: ref,\n tabIndex: iconTabIndex,\n onClick: onClick,\n className: classString\n }), /*#__PURE__*/React.createElement(ReactIcon, {\n icon: icon,\n primaryColor: primaryColor,\n secondaryColor: secondaryColor,\n style: svgStyle\n }));\n});\nIcon.displayName = 'AntdIcon';\nIcon.getTwoToneColor = getTwoToneColor;\nIcon.setTwoToneColor = setTwoToneColor;\nexport default Icon;","import { createContext } from 'react';\nvar IconContext = /*#__PURE__*/createContext({});\nexport default IconContext;","// This icon file is generated automatically.\nvar CheckCircleFilled = { \"icon\": { \"tag\": \"svg\", \"attrs\": { \"viewBox\": \"64 64 896 896\", \"focusable\": \"false\" }, \"children\": [{ \"tag\": \"path\", \"attrs\": { \"d\": \"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm193.5 301.7l-210.6 292a31.8 31.8 0 01-51.7 0L318.5 484.9c-3.8-5.3 0-12.7 6.5-12.7h46.9c10.2 0 19.9 4.9 25.9 13.3l71.2 98.8 157.2-218c6-8.3 15.6-13.3 25.9-13.3H699c6.5 0 10.3 7.4 6.5 12.7z\" } }] }, \"name\": \"check-circle\", \"theme\": \"filled\" };\nexport default CheckCircleFilled;\n","import _extends from \"@babel/runtime/helpers/esm/extends\";\n// GENERATE BY ./scripts/generate.ts\n// DON NOT EDIT IT MANUALLY\n\nimport * as React from 'react';\nimport CheckCircleFilledSvg from \"@ant-design/icons-svg/es/asn/CheckCircleFilled\";\nimport AntdIcon from \"../components/AntdIcon\";\nvar CheckCircleFilled = function CheckCircleFilled(props, ref) {\n return /*#__PURE__*/React.createElement(AntdIcon, _extends({}, props, {\n ref: ref,\n icon: CheckCircleFilledSvg\n }));\n};\nif (process.env.NODE_ENV !== 'production') {\n CheckCircleFilled.displayName = 'CheckCircleFilled';\n}\nexport default /*#__PURE__*/React.forwardRef(CheckCircleFilled);","// This icon file is generated automatically.\nvar CheckOutlined = { \"icon\": { \"tag\": \"svg\", \"attrs\": { \"viewBox\": \"64 64 896 896\", \"focusable\": \"false\" }, \"children\": [{ \"tag\": \"path\", \"attrs\": { \"d\": \"M912 190h-69.9c-9.8 0-19.1 4.5-25.1 12.2L404.7 724.5 207 474a32 32 0 00-25.1-12.2H112c-6.7 0-10.4 7.7-6.3 12.9l273.9 347c12.8 16.2 37.4 16.2 50.3 0l488.4-618.9c4.1-5.1.4-12.8-6.3-12.8z\" } }] }, \"name\": \"check\", \"theme\": \"outlined\" };\nexport default CheckOutlined;\n","import _extends from \"@babel/runtime/helpers/esm/extends\";\n// GENERATE BY ./scripts/generate.ts\n// DON NOT EDIT IT MANUALLY\n\nimport * as React from 'react';\nimport CheckOutlinedSvg from \"@ant-design/icons-svg/es/asn/CheckOutlined\";\nimport AntdIcon from \"../components/AntdIcon\";\nvar CheckOutlined = function CheckOutlined(props, ref) {\n return /*#__PURE__*/React.createElement(AntdIcon, _extends({}, props, {\n ref: ref,\n icon: CheckOutlinedSvg\n }));\n};\nif (process.env.NODE_ENV !== 'production') {\n CheckOutlined.displayName = 'CheckOutlined';\n}\nexport default /*#__PURE__*/React.forwardRef(CheckOutlined);","// This icon file is generated automatically.\nvar CloseCircleFilled = { \"icon\": { \"tag\": \"svg\", \"attrs\": { \"fill-rule\": \"evenodd\", \"viewBox\": \"64 64 896 896\", \"focusable\": \"false\" }, \"children\": [{ \"tag\": \"path\", \"attrs\": { \"d\": \"M512 64c247.4 0 448 200.6 448 448S759.4 960 512 960 64 759.4 64 512 264.6 64 512 64zm127.98 274.82h-.04l-.08.06L512 466.75 384.14 338.88c-.04-.05-.06-.06-.08-.06a.12.12 0 00-.07 0c-.03 0-.05.01-.09.05l-45.02 45.02a.2.2 0 00-.05.09.12.12 0 000 .07v.02a.27.27 0 00.06.06L466.75 512 338.88 639.86c-.05.04-.06.06-.06.08a.12.12 0 000 .07c0 .03.01.05.05.09l45.02 45.02a.2.2 0 00.09.05.12.12 0 00.07 0c.02 0 .04-.01.08-.05L512 557.25l127.86 127.87c.04.04.06.05.08.05a.12.12 0 00.07 0c.03 0 .05-.01.09-.05l45.02-45.02a.2.2 0 00.05-.09.12.12 0 000-.07v-.02a.27.27 0 00-.05-.06L557.25 512l127.87-127.86c.04-.04.05-.06.05-.08a.12.12 0 000-.07c0-.03-.01-.05-.05-.09l-45.02-45.02a.2.2 0 00-.09-.05.12.12 0 00-.07 0z\" } }] }, \"name\": \"close-circle\", \"theme\": \"filled\" };\nexport default CloseCircleFilled;\n","import _extends from \"@babel/runtime/helpers/esm/extends\";\n// GENERATE BY ./scripts/generate.ts\n// DON NOT EDIT IT MANUALLY\n\nimport * as React from 'react';\nimport CloseCircleFilledSvg from \"@ant-design/icons-svg/es/asn/CloseCircleFilled\";\nimport AntdIcon from \"../components/AntdIcon\";\nvar CloseCircleFilled = function CloseCircleFilled(props, ref) {\n return /*#__PURE__*/React.createElement(AntdIcon, _extends({}, props, {\n ref: ref,\n icon: CloseCircleFilledSvg\n }));\n};\nif (process.env.NODE_ENV !== 'production') {\n CloseCircleFilled.displayName = 'CloseCircleFilled';\n}\nexport default /*#__PURE__*/React.forwardRef(CloseCircleFilled);","// This icon file is generated automatically.\nvar CloseOutlined = { \"icon\": { \"tag\": \"svg\", \"attrs\": { \"fill-rule\": \"evenodd\", \"viewBox\": \"64 64 896 896\", \"focusable\": \"false\" }, \"children\": [{ \"tag\": \"path\", \"attrs\": { \"d\": \"M799.86 166.31c.02 0 .04.02.08.06l57.69 57.7c.04.03.05.05.06.08a.12.12 0 010 .06c0 .03-.02.05-.06.09L569.93 512l287.7 287.7c.04.04.05.06.06.09a.12.12 0 010 .07c0 .02-.02.04-.06.08l-57.7 57.69c-.03.04-.05.05-.07.06a.12.12 0 01-.07 0c-.03 0-.05-.02-.09-.06L512 569.93l-287.7 287.7c-.04.04-.06.05-.09.06a.12.12 0 01-.07 0c-.02 0-.04-.02-.08-.06l-57.69-57.7c-.04-.03-.05-.05-.06-.07a.12.12 0 010-.07c0-.03.02-.05.06-.09L454.07 512l-287.7-287.7c-.04-.04-.05-.06-.06-.09a.12.12 0 010-.07c0-.02.02-.04.06-.08l57.7-57.69c.03-.04.05-.05.07-.06a.12.12 0 01.07 0c.03 0 .05.02.09.06L512 454.07l287.7-287.7c.04-.04.06-.05.09-.06a.12.12 0 01.07 0z\" } }] }, \"name\": \"close\", \"theme\": \"outlined\" };\nexport default CloseOutlined;\n","import _extends from \"@babel/runtime/helpers/esm/extends\";\n// GENERATE BY ./scripts/generate.ts\n// DON NOT EDIT IT MANUALLY\n\nimport * as React from 'react';\nimport CloseOutlinedSvg from \"@ant-design/icons-svg/es/asn/CloseOutlined\";\nimport AntdIcon from \"../components/AntdIcon\";\nvar CloseOutlined = function CloseOutlined(props, ref) {\n return /*#__PURE__*/React.createElement(AntdIcon, _extends({}, props, {\n ref: ref,\n icon: CloseOutlinedSvg\n }));\n};\nif (process.env.NODE_ENV !== 'production') {\n CloseOutlined.displayName = 'CloseOutlined';\n}\nexport default /*#__PURE__*/React.forwardRef(CloseOutlined);","// This icon file is generated automatically.\nvar DownOutlined = { \"icon\": { \"tag\": \"svg\", \"attrs\": { \"viewBox\": \"64 64 896 896\", \"focusable\": \"false\" }, \"children\": [{ \"tag\": \"path\", \"attrs\": { \"d\": \"M884 256h-75c-5.1 0-9.9 2.5-12.9 6.6L512 654.2 227.9 262.6c-3-4.1-7.8-6.6-12.9-6.6h-75c-6.5 0-10.3 7.4-6.5 12.7l352.6 486.1c12.8 17.6 39 17.6 51.7 0l352.6-486.1c3.9-5.3.1-12.7-6.4-12.7z\" } }] }, \"name\": \"down\", \"theme\": \"outlined\" };\nexport default DownOutlined;\n","import _extends from \"@babel/runtime/helpers/esm/extends\";\n// GENERATE BY ./scripts/generate.ts\n// DON NOT EDIT IT MANUALLY\n\nimport * as React from 'react';\nimport DownOutlinedSvg from \"@ant-design/icons-svg/es/asn/DownOutlined\";\nimport AntdIcon from \"../components/AntdIcon\";\nvar DownOutlined = function DownOutlined(props, ref) {\n return /*#__PURE__*/React.createElement(AntdIcon, _extends({}, props, {\n ref: ref,\n icon: DownOutlinedSvg\n }));\n};\nif (process.env.NODE_ENV !== 'production') {\n DownOutlined.displayName = 'DownOutlined';\n}\nexport default /*#__PURE__*/React.forwardRef(DownOutlined);","// This icon file is generated automatically.\nvar EllipsisOutlined = { \"icon\": { \"tag\": \"svg\", \"attrs\": { \"viewBox\": \"64 64 896 896\", \"focusable\": \"false\" }, \"children\": [{ \"tag\": \"path\", \"attrs\": { \"d\": \"M176 511a56 56 0 10112 0 56 56 0 10-112 0zm280 0a56 56 0 10112 0 56 56 0 10-112 0zm280 0a56 56 0 10112 0 56 56 0 10-112 0z\" } }] }, \"name\": \"ellipsis\", \"theme\": \"outlined\" };\nexport default EllipsisOutlined;\n","import _extends from \"@babel/runtime/helpers/esm/extends\";\n// GENERATE BY ./scripts/generate.ts\n// DON NOT EDIT IT MANUALLY\n\nimport * as React from 'react';\nimport EllipsisOutlinedSvg from \"@ant-design/icons-svg/es/asn/EllipsisOutlined\";\nimport AntdIcon from \"../components/AntdIcon\";\nvar EllipsisOutlined = function EllipsisOutlined(props, ref) {\n return /*#__PURE__*/React.createElement(AntdIcon, _extends({}, props, {\n ref: ref,\n icon: EllipsisOutlinedSvg\n }));\n};\nif (process.env.NODE_ENV !== 'production') {\n EllipsisOutlined.displayName = 'EllipsisOutlined';\n}\nexport default /*#__PURE__*/React.forwardRef(EllipsisOutlined);","// This icon file is generated automatically.\nvar ExclamationCircleFilled = { \"icon\": { \"tag\": \"svg\", \"attrs\": { \"viewBox\": \"64 64 896 896\", \"focusable\": \"false\" }, \"children\": [{ \"tag\": \"path\", \"attrs\": { \"d\": \"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm-32 232c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v272c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V296zm32 440a48.01 48.01 0 010-96 48.01 48.01 0 010 96z\" } }] }, \"name\": \"exclamation-circle\", \"theme\": \"filled\" };\nexport default ExclamationCircleFilled;\n","import _extends from \"@babel/runtime/helpers/esm/extends\";\n// GENERATE BY ./scripts/generate.ts\n// DON NOT EDIT IT MANUALLY\n\nimport * as React from 'react';\nimport ExclamationCircleFilledSvg from \"@ant-design/icons-svg/es/asn/ExclamationCircleFilled\";\nimport AntdIcon from \"../components/AntdIcon\";\nvar ExclamationCircleFilled = function ExclamationCircleFilled(props, ref) {\n return /*#__PURE__*/React.createElement(AntdIcon, _extends({}, props, {\n ref: ref,\n icon: ExclamationCircleFilledSvg\n }));\n};\nif (process.env.NODE_ENV !== 'production') {\n ExclamationCircleFilled.displayName = 'ExclamationCircleFilled';\n}\nexport default /*#__PURE__*/React.forwardRef(ExclamationCircleFilled);","// This icon file is generated automatically.\nvar InfoCircleFilled = { \"icon\": { \"tag\": \"svg\", \"attrs\": { \"viewBox\": \"64 64 896 896\", \"focusable\": \"false\" }, \"children\": [{ \"tag\": \"path\", \"attrs\": { \"d\": \"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm32 664c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V456c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v272zm-32-344a48.01 48.01 0 010-96 48.01 48.01 0 010 96z\" } }] }, \"name\": \"info-circle\", \"theme\": \"filled\" };\nexport default InfoCircleFilled;\n","import _extends from \"@babel/runtime/helpers/esm/extends\";\n// GENERATE BY ./scripts/generate.ts\n// DON NOT EDIT IT MANUALLY\n\nimport * as React from 'react';\nimport InfoCircleFilledSvg from \"@ant-design/icons-svg/es/asn/InfoCircleFilled\";\nimport AntdIcon from \"../components/AntdIcon\";\nvar InfoCircleFilled = function InfoCircleFilled(props, ref) {\n return /*#__PURE__*/React.createElement(AntdIcon, _extends({}, props, {\n ref: ref,\n icon: InfoCircleFilledSvg\n }));\n};\nif (process.env.NODE_ENV !== 'production') {\n InfoCircleFilled.displayName = 'InfoCircleFilled';\n}\nexport default /*#__PURE__*/React.forwardRef(InfoCircleFilled);","// This icon file is generated automatically.\nvar LeftOutlined = { \"icon\": { \"tag\": \"svg\", \"attrs\": { \"viewBox\": \"64 64 896 896\", \"focusable\": \"false\" }, \"children\": [{ \"tag\": \"path\", \"attrs\": { \"d\": \"M724 218.3V141c0-6.7-7.7-10.4-12.9-6.3L260.3 486.8a31.86 31.86 0 000 50.3l450.8 352.1c5.3 4.1 12.9.4 12.9-6.3v-77.3c0-4.9-2.3-9.6-6.1-12.6l-360-281 360-281.1c3.8-3 6.1-7.7 6.1-12.6z\" } }] }, \"name\": \"left\", \"theme\": \"outlined\" };\nexport default LeftOutlined;\n","import _extends from \"@babel/runtime/helpers/esm/extends\";\n// GENERATE BY ./scripts/generate.ts\n// DON NOT EDIT IT MANUALLY\n\nimport * as React from 'react';\nimport LeftOutlinedSvg from \"@ant-design/icons-svg/es/asn/LeftOutlined\";\nimport AntdIcon from \"../components/AntdIcon\";\nvar LeftOutlined = function LeftOutlined(props, ref) {\n return /*#__PURE__*/React.createElement(AntdIcon, _extends({}, props, {\n ref: ref,\n icon: LeftOutlinedSvg\n }));\n};\nif (process.env.NODE_ENV !== 'production') {\n LeftOutlined.displayName = 'LeftOutlined';\n}\nexport default /*#__PURE__*/React.forwardRef(LeftOutlined);","// This icon file is generated automatically.\nvar LoadingOutlined = { \"icon\": { \"tag\": \"svg\", \"attrs\": { \"viewBox\": \"0 0 1024 1024\", \"focusable\": \"false\" }, \"children\": [{ \"tag\": \"path\", \"attrs\": { \"d\": \"M988 548c-19.9 0-36-16.1-36-36 0-59.4-11.6-117-34.6-171.3a440.45 440.45 0 00-94.3-139.9 437.71 437.71 0 00-139.9-94.3C629 83.6 571.4 72 512 72c-19.9 0-36-16.1-36-36s16.1-36 36-36c69.1 0 136.2 13.5 199.3 40.3C772.3 66 827 103 874 150c47 47 83.9 101.8 109.7 162.7 26.7 63.1 40.2 130.2 40.2 199.3.1 19.9-16 36-35.9 36z\" } }] }, \"name\": \"loading\", \"theme\": \"outlined\" };\nexport default LoadingOutlined;\n","import _extends from \"@babel/runtime/helpers/esm/extends\";\n// GENERATE BY ./scripts/generate.ts\n// DON NOT EDIT IT MANUALLY\n\nimport * as React from 'react';\nimport LoadingOutlinedSvg from \"@ant-design/icons-svg/es/asn/LoadingOutlined\";\nimport AntdIcon from \"../components/AntdIcon\";\nvar LoadingOutlined = function LoadingOutlined(props, ref) {\n return /*#__PURE__*/React.createElement(AntdIcon, _extends({}, props, {\n ref: ref,\n icon: LoadingOutlinedSvg\n }));\n};\nif (process.env.NODE_ENV !== 'production') {\n LoadingOutlined.displayName = 'LoadingOutlined';\n}\nexport default /*#__PURE__*/React.forwardRef(LoadingOutlined);","// This icon file is generated automatically.\nvar RightOutlined = { \"icon\": { \"tag\": \"svg\", \"attrs\": { \"viewBox\": \"64 64 896 896\", \"focusable\": \"false\" }, \"children\": [{ \"tag\": \"path\", \"attrs\": { \"d\": \"M765.7 486.8L314.9 134.7A7.97 7.97 0 00302 141v77.3c0 4.9 2.3 9.6 6.1 12.6l360 281.1-360 281.1c-3.9 3-6.1 7.7-6.1 12.6V883c0 6.7 7.7 10.4 12.9 6.3l450.8-352.1a31.96 31.96 0 000-50.4z\" } }] }, \"name\": \"right\", \"theme\": \"outlined\" };\nexport default RightOutlined;\n","import _extends from \"@babel/runtime/helpers/esm/extends\";\n// GENERATE BY ./scripts/generate.ts\n// DON NOT EDIT IT MANUALLY\n\nimport * as React from 'react';\nimport RightOutlinedSvg from \"@ant-design/icons-svg/es/asn/RightOutlined\";\nimport AntdIcon from \"../components/AntdIcon\";\nvar RightOutlined = function RightOutlined(props, ref) {\n return /*#__PURE__*/React.createElement(AntdIcon, _extends({}, props, {\n ref: ref,\n icon: RightOutlinedSvg\n }));\n};\nif (process.env.NODE_ENV !== 'production') {\n RightOutlined.displayName = 'RightOutlined';\n}\nexport default /*#__PURE__*/React.forwardRef(RightOutlined);","// This icon file is generated automatically.\nvar SearchOutlined = { \"icon\": { \"tag\": \"svg\", \"attrs\": { \"viewBox\": \"64 64 896 896\", \"focusable\": \"false\" }, \"children\": [{ \"tag\": \"path\", \"attrs\": { \"d\": \"M909.6 854.5L649.9 594.8C690.2 542.7 712 479 712 412c0-80.2-31.3-155.4-87.9-212.1-56.6-56.7-132-87.9-212.1-87.9s-155.5 31.3-212.1 87.9C143.2 256.5 112 331.8 112 412c0 80.1 31.3 155.5 87.9 212.1C256.5 680.8 331.8 712 412 712c67 0 130.6-21.8 182.7-62l259.7 259.6a8.2 8.2 0 0011.6 0l43.6-43.5a8.2 8.2 0 000-11.6zM570.4 570.4C528 612.7 471.8 636 412 636s-116-23.3-158.4-65.6C211.3 528 188 471.8 188 412s23.3-116.1 65.6-158.4C296 211.3 352.2 188 412 188s116.1 23.2 158.4 65.6S636 352.2 636 412s-23.3 116.1-65.6 158.4z\" } }] }, \"name\": \"search\", \"theme\": \"outlined\" };\nexport default SearchOutlined;\n","import _extends from \"@babel/runtime/helpers/esm/extends\";\n// GENERATE BY ./scripts/generate.ts\n// DON NOT EDIT IT MANUALLY\n\nimport * as React from 'react';\nimport SearchOutlinedSvg from \"@ant-design/icons-svg/es/asn/SearchOutlined\";\nimport AntdIcon from \"../components/AntdIcon\";\nvar SearchOutlined = function SearchOutlined(props, ref) {\n return /*#__PURE__*/React.createElement(AntdIcon, _extends({}, props, {\n ref: ref,\n icon: SearchOutlinedSvg\n }));\n};\nif (process.env.NODE_ENV !== 'production') {\n SearchOutlined.displayName = 'SearchOutlined';\n}\nexport default /*#__PURE__*/React.forwardRef(SearchOutlined);","import { bound01, pad2 } from './util';\n// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:\n// \n/**\n * Handle bounds / percentage checking to conform to CSS color spec\n * \n * *Assumes:* r, g, b in [0, 255] or [0, 1]\n * *Returns:* { r, g, b } in [0, 255]\n */\nexport function rgbToRgb(r, g, b) {\n return {\n r: bound01(r, 255) * 255,\n g: bound01(g, 255) * 255,\n b: bound01(b, 255) * 255,\n };\n}\n/**\n * Converts an RGB color value to HSL.\n * *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]\n * *Returns:* { h, s, l } in [0,1]\n */\nexport function rgbToHsl(r, g, b) {\n r = bound01(r, 255);\n g = bound01(g, 255);\n b = bound01(b, 255);\n var max = Math.max(r, g, b);\n var min = Math.min(r, g, b);\n var h = 0;\n var s = 0;\n var l = (max + min) / 2;\n if (max === min) {\n s = 0;\n h = 0; // achromatic\n }\n else {\n var d = max - min;\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\n switch (max) {\n case r:\n h = (g - b) / d + (g < b ? 6 : 0);\n break;\n case g:\n h = (b - r) / d + 2;\n break;\n case b:\n h = (r - g) / d + 4;\n break;\n default:\n break;\n }\n h /= 6;\n }\n return { h: h, s: s, l: l };\n}\nfunction hue2rgb(p, q, t) {\n if (t < 0) {\n t += 1;\n }\n if (t > 1) {\n t -= 1;\n }\n if (t < 1 / 6) {\n return p + (q - p) * (6 * t);\n }\n if (t < 1 / 2) {\n return q;\n }\n if (t < 2 / 3) {\n return p + (q - p) * (2 / 3 - t) * 6;\n }\n return p;\n}\n/**\n * Converts an HSL color value to RGB.\n *\n * *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]\n * *Returns:* { r, g, b } in the set [0, 255]\n */\nexport function hslToRgb(h, s, l) {\n var r;\n var g;\n var b;\n h = bound01(h, 360);\n s = bound01(s, 100);\n l = bound01(l, 100);\n if (s === 0) {\n // achromatic\n g = l;\n b = l;\n r = l;\n }\n else {\n var q = l < 0.5 ? l * (1 + s) : l + s - l * s;\n var p = 2 * l - q;\n r = hue2rgb(p, q, h + 1 / 3);\n g = hue2rgb(p, q, h);\n b = hue2rgb(p, q, h - 1 / 3);\n }\n return { r: r * 255, g: g * 255, b: b * 255 };\n}\n/**\n * Converts an RGB color value to HSV\n *\n * *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]\n * *Returns:* { h, s, v } in [0,1]\n */\nexport function rgbToHsv(r, g, b) {\n r = bound01(r, 255);\n g = bound01(g, 255);\n b = bound01(b, 255);\n var max = Math.max(r, g, b);\n var min = Math.min(r, g, b);\n var h = 0;\n var v = max;\n var d = max - min;\n var s = max === 0 ? 0 : d / max;\n if (max === min) {\n h = 0; // achromatic\n }\n else {\n switch (max) {\n case r:\n h = (g - b) / d + (g < b ? 6 : 0);\n break;\n case g:\n h = (b - r) / d + 2;\n break;\n case b:\n h = (r - g) / d + 4;\n break;\n default:\n break;\n }\n h /= 6;\n }\n return { h: h, s: s, v: v };\n}\n/**\n * Converts an HSV color value to RGB.\n *\n * *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]\n * *Returns:* { r, g, b } in the set [0, 255]\n */\nexport function hsvToRgb(h, s, v) {\n h = bound01(h, 360) * 6;\n s = bound01(s, 100);\n v = bound01(v, 100);\n var i = Math.floor(h);\n var f = h - i;\n var p = v * (1 - s);\n var q = v * (1 - f * s);\n var t = v * (1 - (1 - f) * s);\n var mod = i % 6;\n var r = [v, q, p, p, t, v][mod];\n var g = [t, v, v, q, p, p][mod];\n var b = [p, p, t, v, v, q][mod];\n return { r: r * 255, g: g * 255, b: b * 255 };\n}\n/**\n * Converts an RGB color to hex\n *\n * Assumes r, g, and b are contained in the set [0, 255]\n * Returns a 3 or 6 character hex\n */\nexport function rgbToHex(r, g, b, allow3Char) {\n var hex = [\n pad2(Math.round(r).toString(16)),\n pad2(Math.round(g).toString(16)),\n pad2(Math.round(b).toString(16)),\n ];\n // Return a 3 character hex if possible\n if (allow3Char &&\n hex[0].startsWith(hex[0].charAt(1)) &&\n hex[1].startsWith(hex[1].charAt(1)) &&\n hex[2].startsWith(hex[2].charAt(1))) {\n return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);\n }\n return hex.join('');\n}\n/**\n * Converts an RGBA color plus alpha transparency to hex\n *\n * Assumes r, g, b are contained in the set [0, 255] and\n * a in [0, 1]. Returns a 4 or 8 character rgba hex\n */\n// eslint-disable-next-line max-params\nexport function rgbaToHex(r, g, b, a, allow4Char) {\n var hex = [\n pad2(Math.round(r).toString(16)),\n pad2(Math.round(g).toString(16)),\n pad2(Math.round(b).toString(16)),\n pad2(convertDecimalToHex(a)),\n ];\n // Return a 4 character hex if possible\n if (allow4Char &&\n hex[0].startsWith(hex[0].charAt(1)) &&\n hex[1].startsWith(hex[1].charAt(1)) &&\n hex[2].startsWith(hex[2].charAt(1)) &&\n hex[3].startsWith(hex[3].charAt(1))) {\n return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);\n }\n return hex.join('');\n}\n/**\n * Converts an RGBA color to an ARGB Hex8 string\n * Rarely used, but required for \"toFilter()\"\n */\nexport function rgbaToArgbHex(r, g, b, a) {\n var hex = [\n pad2(convertDecimalToHex(a)),\n pad2(Math.round(r).toString(16)),\n pad2(Math.round(g).toString(16)),\n pad2(Math.round(b).toString(16)),\n ];\n return hex.join('');\n}\n/** Converts a decimal to a hex value */\nexport function convertDecimalToHex(d) {\n return Math.round(parseFloat(d) * 255).toString(16);\n}\n/** Converts a hex value to a decimal */\nexport function convertHexToDecimal(h) {\n return parseIntFromHex(h) / 255;\n}\n/** Parse a base-16 hex value into a base-10 integer */\nexport function parseIntFromHex(val) {\n return parseInt(val, 16);\n}\nexport function numberInputToObject(color) {\n return {\n r: color >> 16,\n g: (color & 0xff00) >> 8,\n b: color & 0xff,\n };\n}\n","// https://github.com/bahamas10/css-color-names/blob/master/css-color-names.json\n/**\n * @hidden\n */\nexport var names = {\n aliceblue: '#f0f8ff',\n antiquewhite: '#faebd7',\n aqua: '#00ffff',\n aquamarine: '#7fffd4',\n azure: '#f0ffff',\n beige: '#f5f5dc',\n bisque: '#ffe4c4',\n black: '#000000',\n blanchedalmond: '#ffebcd',\n blue: '#0000ff',\n blueviolet: '#8a2be2',\n brown: '#a52a2a',\n burlywood: '#deb887',\n cadetblue: '#5f9ea0',\n chartreuse: '#7fff00',\n chocolate: '#d2691e',\n coral: '#ff7f50',\n cornflowerblue: '#6495ed',\n cornsilk: '#fff8dc',\n crimson: '#dc143c',\n cyan: '#00ffff',\n darkblue: '#00008b',\n darkcyan: '#008b8b',\n darkgoldenrod: '#b8860b',\n darkgray: '#a9a9a9',\n darkgreen: '#006400',\n darkgrey: '#a9a9a9',\n darkkhaki: '#bdb76b',\n darkmagenta: '#8b008b',\n darkolivegreen: '#556b2f',\n darkorange: '#ff8c00',\n darkorchid: '#9932cc',\n darkred: '#8b0000',\n darksalmon: '#e9967a',\n darkseagreen: '#8fbc8f',\n darkslateblue: '#483d8b',\n darkslategray: '#2f4f4f',\n darkslategrey: '#2f4f4f',\n darkturquoise: '#00ced1',\n darkviolet: '#9400d3',\n deeppink: '#ff1493',\n deepskyblue: '#00bfff',\n dimgray: '#696969',\n dimgrey: '#696969',\n dodgerblue: '#1e90ff',\n firebrick: '#b22222',\n floralwhite: '#fffaf0',\n forestgreen: '#228b22',\n fuchsia: '#ff00ff',\n gainsboro: '#dcdcdc',\n ghostwhite: '#f8f8ff',\n goldenrod: '#daa520',\n gold: '#ffd700',\n gray: '#808080',\n green: '#008000',\n greenyellow: '#adff2f',\n grey: '#808080',\n honeydew: '#f0fff0',\n hotpink: '#ff69b4',\n indianred: '#cd5c5c',\n indigo: '#4b0082',\n ivory: '#fffff0',\n khaki: '#f0e68c',\n lavenderblush: '#fff0f5',\n lavender: '#e6e6fa',\n lawngreen: '#7cfc00',\n lemonchiffon: '#fffacd',\n lightblue: '#add8e6',\n lightcoral: '#f08080',\n lightcyan: '#e0ffff',\n lightgoldenrodyellow: '#fafad2',\n lightgray: '#d3d3d3',\n lightgreen: '#90ee90',\n lightgrey: '#d3d3d3',\n lightpink: '#ffb6c1',\n lightsalmon: '#ffa07a',\n lightseagreen: '#20b2aa',\n lightskyblue: '#87cefa',\n lightslategray: '#778899',\n lightslategrey: '#778899',\n lightsteelblue: '#b0c4de',\n lightyellow: '#ffffe0',\n lime: '#00ff00',\n limegreen: '#32cd32',\n linen: '#faf0e6',\n magenta: '#ff00ff',\n maroon: '#800000',\n mediumaquamarine: '#66cdaa',\n mediumblue: '#0000cd',\n mediumorchid: '#ba55d3',\n mediumpurple: '#9370db',\n mediumseagreen: '#3cb371',\n mediumslateblue: '#7b68ee',\n mediumspringgreen: '#00fa9a',\n mediumturquoise: '#48d1cc',\n mediumvioletred: '#c71585',\n midnightblue: '#191970',\n mintcream: '#f5fffa',\n mistyrose: '#ffe4e1',\n moccasin: '#ffe4b5',\n navajowhite: '#ffdead',\n navy: '#000080',\n oldlace: '#fdf5e6',\n olive: '#808000',\n olivedrab: '#6b8e23',\n orange: '#ffa500',\n orangered: '#ff4500',\n orchid: '#da70d6',\n palegoldenrod: '#eee8aa',\n palegreen: '#98fb98',\n paleturquoise: '#afeeee',\n palevioletred: '#db7093',\n papayawhip: '#ffefd5',\n peachpuff: '#ffdab9',\n peru: '#cd853f',\n pink: '#ffc0cb',\n plum: '#dda0dd',\n powderblue: '#b0e0e6',\n purple: '#800080',\n rebeccapurple: '#663399',\n red: '#ff0000',\n rosybrown: '#bc8f8f',\n royalblue: '#4169e1',\n saddlebrown: '#8b4513',\n salmon: '#fa8072',\n sandybrown: '#f4a460',\n seagreen: '#2e8b57',\n seashell: '#fff5ee',\n sienna: '#a0522d',\n silver: '#c0c0c0',\n skyblue: '#87ceeb',\n slateblue: '#6a5acd',\n slategray: '#708090',\n slategrey: '#708090',\n snow: '#fffafa',\n springgreen: '#00ff7f',\n steelblue: '#4682b4',\n tan: '#d2b48c',\n teal: '#008080',\n thistle: '#d8bfd8',\n tomato: '#ff6347',\n turquoise: '#40e0d0',\n violet: '#ee82ee',\n wheat: '#f5deb3',\n white: '#ffffff',\n whitesmoke: '#f5f5f5',\n yellow: '#ffff00',\n yellowgreen: '#9acd32',\n};\n","/* eslint-disable @typescript-eslint/no-redundant-type-constituents */\nimport { convertHexToDecimal, hslToRgb, hsvToRgb, parseIntFromHex, rgbToRgb } from './conversion';\nimport { names } from './css-color-names';\nimport { boundAlpha, convertToPercentage } from './util';\n/**\n * Given a string or object, convert that input to RGB\n *\n * Possible string inputs:\n * ```\n * \"red\"\n * \"#f00\" or \"f00\"\n * \"#ff0000\" or \"ff0000\"\n * \"#ff000000\" or \"ff000000\"\n * \"rgb 255 0 0\" or \"rgb (255, 0, 0)\"\n * \"rgb 1.0 0 0\" or \"rgb (1, 0, 0)\"\n * \"rgba (255, 0, 0, 1)\" or \"rgba 255, 0, 0, 1\"\n * \"rgba (1.0, 0, 0, 1)\" or \"rgba 1.0, 0, 0, 1\"\n * \"hsl(0, 100%, 50%)\" or \"hsl 0 100% 50%\"\n * \"hsla(0, 100%, 50%, 1)\" or \"hsla 0 100% 50%, 1\"\n * \"hsv(0, 100%, 100%)\" or \"hsv 0 100% 100%\"\n * ```\n */\nexport function inputToRGB(color) {\n var rgb = { r: 0, g: 0, b: 0 };\n var a = 1;\n var s = null;\n var v = null;\n var l = null;\n var ok = false;\n var format = false;\n if (typeof color === 'string') {\n color = stringInputToObject(color);\n }\n if (typeof color === 'object') {\n if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {\n rgb = rgbToRgb(color.r, color.g, color.b);\n ok = true;\n format = String(color.r).substr(-1) === '%' ? 'prgb' : 'rgb';\n }\n else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {\n s = convertToPercentage(color.s);\n v = convertToPercentage(color.v);\n rgb = hsvToRgb(color.h, s, v);\n ok = true;\n format = 'hsv';\n }\n else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {\n s = convertToPercentage(color.s);\n l = convertToPercentage(color.l);\n rgb = hslToRgb(color.h, s, l);\n ok = true;\n format = 'hsl';\n }\n if (Object.prototype.hasOwnProperty.call(color, 'a')) {\n a = color.a;\n }\n }\n a = boundAlpha(a);\n return {\n ok: ok,\n format: color.format || format,\n r: Math.min(255, Math.max(rgb.r, 0)),\n g: Math.min(255, Math.max(rgb.g, 0)),\n b: Math.min(255, Math.max(rgb.b, 0)),\n a: a,\n };\n}\n// \nvar CSS_INTEGER = '[-\\\\+]?\\\\d+%?';\n// \nvar CSS_NUMBER = '[-\\\\+]?\\\\d*\\\\.\\\\d+%?';\n// Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.\nvar CSS_UNIT = \"(?:\".concat(CSS_NUMBER, \")|(?:\").concat(CSS_INTEGER, \")\");\n// Actual matching.\n// Parentheses and commas are optional, but not required.\n// Whitespace can take the place of commas or opening paren\nvar PERMISSIVE_MATCH3 = \"[\\\\s|\\\\(]+(\".concat(CSS_UNIT, \")[,|\\\\s]+(\").concat(CSS_UNIT, \")[,|\\\\s]+(\").concat(CSS_UNIT, \")\\\\s*\\\\)?\");\nvar PERMISSIVE_MATCH4 = \"[\\\\s|\\\\(]+(\".concat(CSS_UNIT, \")[,|\\\\s]+(\").concat(CSS_UNIT, \")[,|\\\\s]+(\").concat(CSS_UNIT, \")[,|\\\\s]+(\").concat(CSS_UNIT, \")\\\\s*\\\\)?\");\nvar matchers = {\n CSS_UNIT: new RegExp(CSS_UNIT),\n rgb: new RegExp('rgb' + PERMISSIVE_MATCH3),\n rgba: new RegExp('rgba' + PERMISSIVE_MATCH4),\n hsl: new RegExp('hsl' + PERMISSIVE_MATCH3),\n hsla: new RegExp('hsla' + PERMISSIVE_MATCH4),\n hsv: new RegExp('hsv' + PERMISSIVE_MATCH3),\n hsva: new RegExp('hsva' + PERMISSIVE_MATCH4),\n hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,\n hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,\n hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,\n hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,\n};\n/**\n * Permissive string parsing. Take in a number of formats, and output an object\n * based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`\n */\nexport function stringInputToObject(color) {\n color = color.trim().toLowerCase();\n if (color.length === 0) {\n return false;\n }\n var named = false;\n if (names[color]) {\n color = names[color];\n named = true;\n }\n else if (color === 'transparent') {\n return { r: 0, g: 0, b: 0, a: 0, format: 'name' };\n }\n // Try to match string input using regular expressions.\n // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]\n // Just return an object and let the conversion functions handle that.\n // This way the result will be the same whether the tinycolor is initialized with string or object.\n var match = matchers.rgb.exec(color);\n if (match) {\n return { r: match[1], g: match[2], b: match[3] };\n }\n match = matchers.rgba.exec(color);\n if (match) {\n return { r: match[1], g: match[2], b: match[3], a: match[4] };\n }\n match = matchers.hsl.exec(color);\n if (match) {\n return { h: match[1], s: match[2], l: match[3] };\n }\n match = matchers.hsla.exec(color);\n if (match) {\n return { h: match[1], s: match[2], l: match[3], a: match[4] };\n }\n match = matchers.hsv.exec(color);\n if (match) {\n return { h: match[1], s: match[2], v: match[3] };\n }\n match = matchers.hsva.exec(color);\n if (match) {\n return { h: match[1], s: match[2], v: match[3], a: match[4] };\n }\n match = matchers.hex8.exec(color);\n if (match) {\n return {\n r: parseIntFromHex(match[1]),\n g: parseIntFromHex(match[2]),\n b: parseIntFromHex(match[3]),\n a: convertHexToDecimal(match[4]),\n format: named ? 'name' : 'hex8',\n };\n }\n match = matchers.hex6.exec(color);\n if (match) {\n return {\n r: parseIntFromHex(match[1]),\n g: parseIntFromHex(match[2]),\n b: parseIntFromHex(match[3]),\n format: named ? 'name' : 'hex',\n };\n }\n match = matchers.hex4.exec(color);\n if (match) {\n return {\n r: parseIntFromHex(match[1] + match[1]),\n g: parseIntFromHex(match[2] + match[2]),\n b: parseIntFromHex(match[3] + match[3]),\n a: convertHexToDecimal(match[4] + match[4]),\n format: named ? 'name' : 'hex8',\n };\n }\n match = matchers.hex3.exec(color);\n if (match) {\n return {\n r: parseIntFromHex(match[1] + match[1]),\n g: parseIntFromHex(match[2] + match[2]),\n b: parseIntFromHex(match[3] + match[3]),\n format: named ? 'name' : 'hex',\n };\n }\n return false;\n}\n/**\n * Check to see if it looks like a CSS unit\n * (see `matchers` above for definition).\n */\nexport function isValidCSSUnit(color) {\n return Boolean(matchers.CSS_UNIT.exec(String(color)));\n}\n","import { numberInputToObject, rgbaToHex, rgbToHex, rgbToHsl, rgbToHsv } from './conversion';\nimport { names } from './css-color-names';\nimport { inputToRGB } from './format-input';\nimport { bound01, boundAlpha, clamp01 } from './util';\nvar TinyColor = /** @class */ (function () {\n function TinyColor(color, opts) {\n if (color === void 0) { color = ''; }\n if (opts === void 0) { opts = {}; }\n var _a;\n // If input is already a tinycolor, return itself\n if (color instanceof TinyColor) {\n // eslint-disable-next-line no-constructor-return\n return color;\n }\n if (typeof color === 'number') {\n color = numberInputToObject(color);\n }\n this.originalInput = color;\n var rgb = inputToRGB(color);\n this.originalInput = color;\n this.r = rgb.r;\n this.g = rgb.g;\n this.b = rgb.b;\n this.a = rgb.a;\n this.roundA = Math.round(100 * this.a) / 100;\n this.format = (_a = opts.format) !== null && _a !== void 0 ? _a : rgb.format;\n this.gradientType = opts.gradientType;\n // Don't let the range of [0,255] come back in [0,1].\n // Potentially lose a little bit of precision here, but will fix issues where\n // .5 gets interpreted as half of the total, instead of half of 1\n // If it was supposed to be 128, this was already taken care of by `inputToRgb`\n if (this.r < 1) {\n this.r = Math.round(this.r);\n }\n if (this.g < 1) {\n this.g = Math.round(this.g);\n }\n if (this.b < 1) {\n this.b = Math.round(this.b);\n }\n this.isValid = rgb.ok;\n }\n TinyColor.prototype.isDark = function () {\n return this.getBrightness() < 128;\n };\n TinyColor.prototype.isLight = function () {\n return !this.isDark();\n };\n /**\n * Returns the perceived brightness of the color, from 0-255.\n */\n TinyColor.prototype.getBrightness = function () {\n // http://www.w3.org/TR/AERT#color-contrast\n var rgb = this.toRgb();\n return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;\n };\n /**\n * Returns the perceived luminance of a color, from 0-1.\n */\n TinyColor.prototype.getLuminance = function () {\n // http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef\n var rgb = this.toRgb();\n var R;\n var G;\n var B;\n var RsRGB = rgb.r / 255;\n var GsRGB = rgb.g / 255;\n var BsRGB = rgb.b / 255;\n if (RsRGB <= 0.03928) {\n R = RsRGB / 12.92;\n }\n else {\n // eslint-disable-next-line prefer-exponentiation-operator\n R = Math.pow((RsRGB + 0.055) / 1.055, 2.4);\n }\n if (GsRGB <= 0.03928) {\n G = GsRGB / 12.92;\n }\n else {\n // eslint-disable-next-line prefer-exponentiation-operator\n G = Math.pow((GsRGB + 0.055) / 1.055, 2.4);\n }\n if (BsRGB <= 0.03928) {\n B = BsRGB / 12.92;\n }\n else {\n // eslint-disable-next-line prefer-exponentiation-operator\n B = Math.pow((BsRGB + 0.055) / 1.055, 2.4);\n }\n return 0.2126 * R + 0.7152 * G + 0.0722 * B;\n };\n /**\n * Returns the alpha value of a color, from 0-1.\n */\n TinyColor.prototype.getAlpha = function () {\n return this.a;\n };\n /**\n * Sets the alpha value on the current color.\n *\n * @param alpha - The new alpha value. The accepted range is 0-1.\n */\n TinyColor.prototype.setAlpha = function (alpha) {\n this.a = boundAlpha(alpha);\n this.roundA = Math.round(100 * this.a) / 100;\n return this;\n };\n /**\n * Returns whether the color is monochrome.\n */\n TinyColor.prototype.isMonochrome = function () {\n var s = this.toHsl().s;\n return s === 0;\n };\n /**\n * Returns the object as a HSVA object.\n */\n TinyColor.prototype.toHsv = function () {\n var hsv = rgbToHsv(this.r, this.g, this.b);\n return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this.a };\n };\n /**\n * Returns the hsva values interpolated into a string with the following format:\n * \"hsva(xxx, xxx, xxx, xx)\".\n */\n TinyColor.prototype.toHsvString = function () {\n var hsv = rgbToHsv(this.r, this.g, this.b);\n var h = Math.round(hsv.h * 360);\n var s = Math.round(hsv.s * 100);\n var v = Math.round(hsv.v * 100);\n return this.a === 1 ? \"hsv(\".concat(h, \", \").concat(s, \"%, \").concat(v, \"%)\") : \"hsva(\".concat(h, \", \").concat(s, \"%, \").concat(v, \"%, \").concat(this.roundA, \")\");\n };\n /**\n * Returns the object as a HSLA object.\n */\n TinyColor.prototype.toHsl = function () {\n var hsl = rgbToHsl(this.r, this.g, this.b);\n return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this.a };\n };\n /**\n * Returns the hsla values interpolated into a string with the following format:\n * \"hsla(xxx, xxx, xxx, xx)\".\n */\n TinyColor.prototype.toHslString = function () {\n var hsl = rgbToHsl(this.r, this.g, this.b);\n var h = Math.round(hsl.h * 360);\n var s = Math.round(hsl.s * 100);\n var l = Math.round(hsl.l * 100);\n return this.a === 1 ? \"hsl(\".concat(h, \", \").concat(s, \"%, \").concat(l, \"%)\") : \"hsla(\".concat(h, \", \").concat(s, \"%, \").concat(l, \"%, \").concat(this.roundA, \")\");\n };\n /**\n * Returns the hex value of the color.\n * @param allow3Char will shorten hex value to 3 char if possible\n */\n TinyColor.prototype.toHex = function (allow3Char) {\n if (allow3Char === void 0) { allow3Char = false; }\n return rgbToHex(this.r, this.g, this.b, allow3Char);\n };\n /**\n * Returns the hex value of the color -with a # prefixed.\n * @param allow3Char will shorten hex value to 3 char if possible\n */\n TinyColor.prototype.toHexString = function (allow3Char) {\n if (allow3Char === void 0) { allow3Char = false; }\n return '#' + this.toHex(allow3Char);\n };\n /**\n * Returns the hex 8 value of the color.\n * @param allow4Char will shorten hex value to 4 char if possible\n */\n TinyColor.prototype.toHex8 = function (allow4Char) {\n if (allow4Char === void 0) { allow4Char = false; }\n return rgbaToHex(this.r, this.g, this.b, this.a, allow4Char);\n };\n /**\n * Returns the hex 8 value of the color -with a # prefixed.\n * @param allow4Char will shorten hex value to 4 char if possible\n */\n TinyColor.prototype.toHex8String = function (allow4Char) {\n if (allow4Char === void 0) { allow4Char = false; }\n return '#' + this.toHex8(allow4Char);\n };\n /**\n * Returns the shorter hex value of the color depends on its alpha -with a # prefixed.\n * @param allowShortChar will shorten hex value to 3 or 4 char if possible\n */\n TinyColor.prototype.toHexShortString = function (allowShortChar) {\n if (allowShortChar === void 0) { allowShortChar = false; }\n return this.a === 1 ? this.toHexString(allowShortChar) : this.toHex8String(allowShortChar);\n };\n /**\n * Returns the object as a RGBA object.\n */\n TinyColor.prototype.toRgb = function () {\n return {\n r: Math.round(this.r),\n g: Math.round(this.g),\n b: Math.round(this.b),\n a: this.a,\n };\n };\n /**\n * Returns the RGBA values interpolated into a string with the following format:\n * \"RGBA(xxx, xxx, xxx, xx)\".\n */\n TinyColor.prototype.toRgbString = function () {\n var r = Math.round(this.r);\n var g = Math.round(this.g);\n var b = Math.round(this.b);\n return this.a === 1 ? \"rgb(\".concat(r, \", \").concat(g, \", \").concat(b, \")\") : \"rgba(\".concat(r, \", \").concat(g, \", \").concat(b, \", \").concat(this.roundA, \")\");\n };\n /**\n * Returns the object as a RGBA object.\n */\n TinyColor.prototype.toPercentageRgb = function () {\n var fmt = function (x) { return \"\".concat(Math.round(bound01(x, 255) * 100), \"%\"); };\n return {\n r: fmt(this.r),\n g: fmt(this.g),\n b: fmt(this.b),\n a: this.a,\n };\n };\n /**\n * Returns the RGBA relative values interpolated into a string\n */\n TinyColor.prototype.toPercentageRgbString = function () {\n var rnd = function (x) { return Math.round(bound01(x, 255) * 100); };\n return this.a === 1\n ? \"rgb(\".concat(rnd(this.r), \"%, \").concat(rnd(this.g), \"%, \").concat(rnd(this.b), \"%)\")\n : \"rgba(\".concat(rnd(this.r), \"%, \").concat(rnd(this.g), \"%, \").concat(rnd(this.b), \"%, \").concat(this.roundA, \")\");\n };\n /**\n * The 'real' name of the color -if there is one.\n */\n TinyColor.prototype.toName = function () {\n if (this.a === 0) {\n return 'transparent';\n }\n if (this.a < 1) {\n return false;\n }\n var hex = '#' + rgbToHex(this.r, this.g, this.b, false);\n for (var _i = 0, _a = Object.entries(names); _i < _a.length; _i++) {\n var _b = _a[_i], key = _b[0], value = _b[1];\n if (hex === value) {\n return key;\n }\n }\n return false;\n };\n TinyColor.prototype.toString = function (format) {\n var formatSet = Boolean(format);\n format = format !== null && format !== void 0 ? format : this.format;\n var formattedString = false;\n var hasAlpha = this.a < 1 && this.a >= 0;\n var needsAlphaFormat = !formatSet && hasAlpha && (format.startsWith('hex') || format === 'name');\n if (needsAlphaFormat) {\n // Special case for \"transparent\", all other non-alpha formats\n // will return rgba when there is transparency.\n if (format === 'name' && this.a === 0) {\n return this.toName();\n }\n return this.toRgbString();\n }\n if (format === 'rgb') {\n formattedString = this.toRgbString();\n }\n if (format === 'prgb') {\n formattedString = this.toPercentageRgbString();\n }\n if (format === 'hex' || format === 'hex6') {\n formattedString = this.toHexString();\n }\n if (format === 'hex3') {\n formattedString = this.toHexString(true);\n }\n if (format === 'hex4') {\n formattedString = this.toHex8String(true);\n }\n if (format === 'hex8') {\n formattedString = this.toHex8String();\n }\n if (format === 'name') {\n formattedString = this.toName();\n }\n if (format === 'hsl') {\n formattedString = this.toHslString();\n }\n if (format === 'hsv') {\n formattedString = this.toHsvString();\n }\n return formattedString || this.toHexString();\n };\n TinyColor.prototype.toNumber = function () {\n return (Math.round(this.r) << 16) + (Math.round(this.g) << 8) + Math.round(this.b);\n };\n TinyColor.prototype.clone = function () {\n return new TinyColor(this.toString());\n };\n /**\n * Lighten the color a given amount. Providing 100 will always return white.\n * @param amount - valid between 1-100\n */\n TinyColor.prototype.lighten = function (amount) {\n if (amount === void 0) { amount = 10; }\n var hsl = this.toHsl();\n hsl.l += amount / 100;\n hsl.l = clamp01(hsl.l);\n return new TinyColor(hsl);\n };\n /**\n * Brighten the color a given amount, from 0 to 100.\n * @param amount - valid between 1-100\n */\n TinyColor.prototype.brighten = function (amount) {\n if (amount === void 0) { amount = 10; }\n var rgb = this.toRgb();\n rgb.r = Math.max(0, Math.min(255, rgb.r - Math.round(255 * -(amount / 100))));\n rgb.g = Math.max(0, Math.min(255, rgb.g - Math.round(255 * -(amount / 100))));\n rgb.b = Math.max(0, Math.min(255, rgb.b - Math.round(255 * -(amount / 100))));\n return new TinyColor(rgb);\n };\n /**\n * Darken the color a given amount, from 0 to 100.\n * Providing 100 will always return black.\n * @param amount - valid between 1-100\n */\n TinyColor.prototype.darken = function (amount) {\n if (amount === void 0) { amount = 10; }\n var hsl = this.toHsl();\n hsl.l -= amount / 100;\n hsl.l = clamp01(hsl.l);\n return new TinyColor(hsl);\n };\n /**\n * Mix the color with pure white, from 0 to 100.\n * Providing 0 will do nothing, providing 100 will always return white.\n * @param amount - valid between 1-100\n */\n TinyColor.prototype.tint = function (amount) {\n if (amount === void 0) { amount = 10; }\n return this.mix('white', amount);\n };\n /**\n * Mix the color with pure black, from 0 to 100.\n * Providing 0 will do nothing, providing 100 will always return black.\n * @param amount - valid between 1-100\n */\n TinyColor.prototype.shade = function (amount) {\n if (amount === void 0) { amount = 10; }\n return this.mix('black', amount);\n };\n /**\n * Desaturate the color a given amount, from 0 to 100.\n * Providing 100 will is the same as calling greyscale\n * @param amount - valid between 1-100\n */\n TinyColor.prototype.desaturate = function (amount) {\n if (amount === void 0) { amount = 10; }\n var hsl = this.toHsl();\n hsl.s -= amount / 100;\n hsl.s = clamp01(hsl.s);\n return new TinyColor(hsl);\n };\n /**\n * Saturate the color a given amount, from 0 to 100.\n * @param amount - valid between 1-100\n */\n TinyColor.prototype.saturate = function (amount) {\n if (amount === void 0) { amount = 10; }\n var hsl = this.toHsl();\n hsl.s += amount / 100;\n hsl.s = clamp01(hsl.s);\n return new TinyColor(hsl);\n };\n /**\n * Completely desaturates a color into greyscale.\n * Same as calling `desaturate(100)`\n */\n TinyColor.prototype.greyscale = function () {\n return this.desaturate(100);\n };\n /**\n * Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.\n * Values outside of this range will be wrapped into this range.\n */\n TinyColor.prototype.spin = function (amount) {\n var hsl = this.toHsl();\n var hue = (hsl.h + amount) % 360;\n hsl.h = hue < 0 ? 360 + hue : hue;\n return new TinyColor(hsl);\n };\n /**\n * Mix the current color a given amount with another color, from 0 to 100.\n * 0 means no mixing (return current color).\n */\n TinyColor.prototype.mix = function (color, amount) {\n if (amount === void 0) { amount = 50; }\n var rgb1 = this.toRgb();\n var rgb2 = new TinyColor(color).toRgb();\n var p = amount / 100;\n var rgba = {\n r: (rgb2.r - rgb1.r) * p + rgb1.r,\n g: (rgb2.g - rgb1.g) * p + rgb1.g,\n b: (rgb2.b - rgb1.b) * p + rgb1.b,\n a: (rgb2.a - rgb1.a) * p + rgb1.a,\n };\n return new TinyColor(rgba);\n };\n TinyColor.prototype.analogous = function (results, slices) {\n if (results === void 0) { results = 6; }\n if (slices === void 0) { slices = 30; }\n var hsl = this.toHsl();\n var part = 360 / slices;\n var ret = [this];\n for (hsl.h = (hsl.h - ((part * results) >> 1) + 720) % 360; --results;) {\n hsl.h = (hsl.h + part) % 360;\n ret.push(new TinyColor(hsl));\n }\n return ret;\n };\n /**\n * taken from https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js\n */\n TinyColor.prototype.complement = function () {\n var hsl = this.toHsl();\n hsl.h = (hsl.h + 180) % 360;\n return new TinyColor(hsl);\n };\n TinyColor.prototype.monochromatic = function (results) {\n if (results === void 0) { results = 6; }\n var hsv = this.toHsv();\n var h = hsv.h;\n var s = hsv.s;\n var v = hsv.v;\n var res = [];\n var modification = 1 / results;\n while (results--) {\n res.push(new TinyColor({ h: h, s: s, v: v }));\n v = (v + modification) % 1;\n }\n return res;\n };\n TinyColor.prototype.splitcomplement = function () {\n var hsl = this.toHsl();\n var h = hsl.h;\n return [\n this,\n new TinyColor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l }),\n new TinyColor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l }),\n ];\n };\n /**\n * Compute how the color would appear on a background\n */\n TinyColor.prototype.onBackground = function (background) {\n var fg = this.toRgb();\n var bg = new TinyColor(background).toRgb();\n var alpha = fg.a + bg.a * (1 - fg.a);\n return new TinyColor({\n r: (fg.r * fg.a + bg.r * bg.a * (1 - fg.a)) / alpha,\n g: (fg.g * fg.a + bg.g * bg.a * (1 - fg.a)) / alpha,\n b: (fg.b * fg.a + bg.b * bg.a * (1 - fg.a)) / alpha,\n a: alpha,\n });\n };\n /**\n * Alias for `polyad(3)`\n */\n TinyColor.prototype.triad = function () {\n return this.polyad(3);\n };\n /**\n * Alias for `polyad(4)`\n */\n TinyColor.prototype.tetrad = function () {\n return this.polyad(4);\n };\n /**\n * Get polyad colors, like (for 1, 2, 3, 4, 5, 6, 7, 8, etc...)\n * monad, dyad, triad, tetrad, pentad, hexad, heptad, octad, etc...\n */\n TinyColor.prototype.polyad = function (n) {\n var hsl = this.toHsl();\n var h = hsl.h;\n var result = [this];\n var increment = 360 / n;\n for (var i = 1; i < n; i++) {\n result.push(new TinyColor({ h: (h + i * increment) % 360, s: hsl.s, l: hsl.l }));\n }\n return result;\n };\n /**\n * compare color vs current color\n */\n TinyColor.prototype.equals = function (color) {\n return this.toRgbString() === new TinyColor(color).toRgbString();\n };\n return TinyColor;\n}());\nexport { TinyColor };\n// kept for backwards compatability with v1\nexport function tinycolor(color, opts) {\n if (color === void 0) { color = ''; }\n if (opts === void 0) { opts = {}; }\n return new TinyColor(color, opts);\n}\n","/**\n * Take input from [0, n] and return it as [0, 1]\n * @hidden\n */\nexport function bound01(n, max) {\n if (isOnePointZero(n)) {\n n = '100%';\n }\n var isPercent = isPercentage(n);\n n = max === 360 ? n : Math.min(max, Math.max(0, parseFloat(n)));\n // Automatically convert percentage into number\n if (isPercent) {\n n = parseInt(String(n * max), 10) / 100;\n }\n // Handle floating point rounding errors\n if (Math.abs(n - max) < 0.000001) {\n return 1;\n }\n // Convert into [0, 1] range if it isn't already\n if (max === 360) {\n // If n is a hue given in degrees,\n // wrap around out-of-range values into [0, 360] range\n // then convert into [0, 1].\n n = (n < 0 ? (n % max) + max : n % max) / parseFloat(String(max));\n }\n else {\n // If n not a hue given in degrees\n // Convert into [0, 1] range if it isn't already.\n n = (n % max) / parseFloat(String(max));\n }\n return n;\n}\n/**\n * Force a number between 0 and 1\n * @hidden\n */\nexport function clamp01(val) {\n return Math.min(1, Math.max(0, val));\n}\n/**\n * Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1\n * \n * @hidden\n */\nexport function isOnePointZero(n) {\n return typeof n === 'string' && n.indexOf('.') !== -1 && parseFloat(n) === 1;\n}\n/**\n * Check to see if string passed in is a percentage\n * @hidden\n */\nexport function isPercentage(n) {\n return typeof n === 'string' && n.indexOf('%') !== -1;\n}\n/**\n * Return a valid alpha value [0,1] with all invalid values being set to 1\n * @hidden\n */\nexport function boundAlpha(a) {\n a = parseFloat(a);\n if (isNaN(a) || a < 0 || a > 1) {\n a = 1;\n }\n return a;\n}\n/**\n * Replace a decimal with it's percentage value\n * @hidden\n */\nexport function convertToPercentage(n) {\n if (n <= 1) {\n return \"\".concat(Number(n) * 100, \"%\");\n }\n return n;\n}\n/**\n * Force a hex value to have 2 characters\n * @hidden\n */\nexport function pad2(c) {\n return c.length === 1 ? '0' + c : String(c);\n}\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\nimport { __assign, __extends } from \"tslib\";\r\nimport { dateNow } from '@microsoft/applicationinsights-core-js';\r\nimport * as React from 'react';\r\n/**\r\n * Higher-order component base class to hook Application Insights tracking\r\n * in a React component's lifecycle.\r\n */\r\nvar AITrackedComponentBase = /** @class */ (function (_super) {\r\n __extends(AITrackedComponentBase, _super);\r\n function AITrackedComponentBase(props, reactPlugin, componentName) {\r\n var _this = _super.call(this, props) || this;\r\n _this._mountTimestamp = 0;\r\n _this._firstActiveTimestamp = 0;\r\n _this._idleStartTimestamp = 0;\r\n _this._lastActiveTimestamp = 0;\r\n _this._totalIdleTime = 0;\r\n _this._idleCount = 0;\r\n _this._idleTimeout = 5000;\r\n _this.trackActivity = function (e) {\r\n if (_this._firstActiveTimestamp === 0) {\r\n _this._firstActiveTimestamp = dateNow();\r\n _this._lastActiveTimestamp = _this._firstActiveTimestamp;\r\n }\r\n else {\r\n _this._lastActiveTimestamp = dateNow();\r\n }\r\n if (_this._idleStartTimestamp > 0) {\r\n var lastIdleTime = _this._lastActiveTimestamp - _this._idleStartTimestamp;\r\n _this._totalIdleTime += lastIdleTime;\r\n _this._idleStartTimestamp = 0;\r\n }\r\n };\r\n _this._reactPlugin = reactPlugin;\r\n _this._componentName = componentName;\r\n return _this;\r\n }\r\n AITrackedComponentBase.prototype.componentDidMount = function () {\r\n var _this = this;\r\n this._mountTimestamp = dateNow();\r\n this._firstActiveTimestamp = 0;\r\n this._totalIdleTime = 0;\r\n this._lastActiveTimestamp = 0;\r\n this._idleStartTimestamp = 0;\r\n this._idleCount = 0;\r\n this._intervalId = setInterval(function () {\r\n if (_this._lastActiveTimestamp > 0 && _this._idleStartTimestamp === 0 && dateNow() - _this._lastActiveTimestamp >= _this._idleTimeout) {\r\n _this._idleStartTimestamp = dateNow();\r\n _this._idleCount++;\r\n }\r\n }, 100);\r\n };\r\n AITrackedComponentBase.prototype.componentWillUnmount = function () {\r\n if (this._mountTimestamp === 0) {\r\n throw new Error('withAITracking:componentWillUnmount: mountTimestamp is not initialized.');\r\n }\r\n if (this._intervalId) {\r\n clearInterval(this._intervalId);\r\n }\r\n if (this._firstActiveTimestamp === 0) {\r\n return;\r\n }\r\n var engagementTime = this.getEngagementTimeSeconds();\r\n var metricData = {\r\n average: engagementTime,\r\n name: 'React Component Engaged Time (seconds)',\r\n sampleCount: 1\r\n };\r\n var additionalProperties = { 'Component Name': this._componentName };\r\n this._reactPlugin.trackMetric(metricData, additionalProperties);\r\n };\r\n AITrackedComponentBase.prototype.getEngagementTimeSeconds = function () {\r\n return (dateNow() - this._firstActiveTimestamp - this._totalIdleTime - this._idleCount * this._idleTimeout) / 1000;\r\n };\r\n return AITrackedComponentBase;\r\n}(React.Component));\r\nexport { AITrackedComponentBase };\r\n/**\r\n * Higher-order component function to hook Application Insights tracking\r\n * in a React component's lifecycle.\r\n *\r\n * @param reactPlugin ReactPlugin instance\r\n * @param Component the React component to be instrumented\r\n * @param componentName (optional) component name\r\n * @param className (optional) className of the HOC div\r\n */\r\nexport default function withAITracking(reactPlugin, Component, componentName, className) {\r\n if (componentName === undefined || componentName === null || typeof componentName !== 'string') {\r\n componentName = Component.prototype &&\r\n Component.prototype.constructor &&\r\n Component.prototype.constructor.name ||\r\n 'Unknown';\r\n }\r\n if (className === undefined || className === null || typeof className !== 'string') {\r\n className = '';\r\n }\r\n return /** @class */ (function (_super) {\r\n __extends(class_1, _super);\r\n function class_1(props) {\r\n return _super.call(this, props, reactPlugin, componentName) || this;\r\n }\r\n class_1.prototype.render = function () {\r\n return (React.createElement(\"div\", { onKeyDown: this.trackActivity, onMouseMove: this.trackActivity, onScroll: this.trackActivity, onMouseDown: this.trackActivity, onTouchStart: this.trackActivity, onTouchMove: this.trackActivity, className: className },\r\n React.createElement(Component, __assign({}, this.props))));\r\n };\r\n return class_1;\r\n }(AITrackedComponentBase));\r\n}\r\n//# sourceMappingURL=withAITracking.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nexport const strShimFunction = \"function\";\r\nexport const strShimObject = \"object\";\r\nexport const strShimUndefined = \"undefined\";\r\nexport const strShimPrototype = \"prototype\";\r\nexport const strDefault = \"default\";\r\n\r\nexport const ObjClass = Object;\r\nexport const ObjProto = ObjClass[strShimPrototype];\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { getGlobal, objAssign, objCreate, objDefineProp, objHasOwnProperty, throwTypeError } from \"@nevware21/ts-utils\";\r\nimport {\r\n ObjClass, ObjProto,\r\n strDefault, strShimFunction, strShimPrototype\r\n} from \"./Constants\";\r\n\r\n// Most of these functions have been directly shamelessly \"lifted\" from the https://github.com/@microsoft/tslib and\r\n// modified to be ES5 compatible and applying several minification and tree-shaking techniques so that Application Insights\r\n// can successfully use TypeScript \"importHelpers\" which imports tslib during compilation but it will use these at runtime\r\n// Which is also why all of the functions have not been included as Application Insights currently doesn't use or require\r\n// them.\r\n\r\nexport const SymbolObj = (getGlobal()||{})[\"Symbol\"];\r\nexport const ReflectObj = (getGlobal()||{})[\"Reflect\"];\r\nexport const __hasReflect = !!ReflectObj;\r\n\r\nconst strDecorate = \"decorate\";\r\nconst strMetadata = \"metadata\";\r\nconst strGetOwnPropertySymbols = \"getOwnPropertySymbols\";\r\nconst strIterator = \"iterator\";\r\nconst strHasOwnProperty = \"hasOwnProperty\";\r\n\r\nexport declare type ObjAssignFunc = (t: any, ...sources:any[]) => any;\r\n\r\nexport var __objAssignFnImpl: ObjAssignFunc = function(t: any): any {\r\n // tslint:disable-next-line: ban-comma-operator\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) {\r\n if (ObjProto[strHasOwnProperty].call(s, p)) {\r\n (t as any)[p] = s[p];\r\n }\r\n }\r\n }\r\n return t;\r\n};\r\n\r\nexport var __assignFn: ObjAssignFunc = objAssign || __objAssignFnImpl;\r\n\r\n// tslint:disable-next-line: only-arrow-functions\r\nvar extendStaticsFn = function(d: any, b: any): any {\r\n extendStaticsFn = ObjClass[\"setPrototypeOf\"] ||\r\n // tslint:disable-next-line: only-arrow-functions\r\n ({ __proto__: [] } instanceof Array && function (d: any, b: any) {\r\n d.__proto__ = b;\r\n }) ||\r\n // tslint:disable-next-line: only-arrow-functions\r\n function (d: any, b: any) {\r\n for (var p in b) {\r\n if (b[strHasOwnProperty](p)) {\r\n d[p] = b[p];\r\n }\r\n }\r\n };\r\n return extendStaticsFn(d, b);\r\n};\r\n\r\nexport function __extendsFn(d: any, b: any) {\r\n if (typeof b !== strShimFunction && b !== null) {\r\n throwTypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n }\r\n extendStaticsFn(d, b);\r\n function __(this: any) {\r\n this.constructor = d;\r\n }\r\n // tslint:disable-next-line: ban-comma-operator\r\n d[strShimPrototype] = b === null ? objCreate(b) : (__[strShimPrototype] = b[strShimPrototype], new (__ as any)());\r\n}\r\n\r\nexport function __restFn(s: any, e: any) {\r\n var t = {};\r\n for (var k in s) {\r\n if (objHasOwnProperty(s, k) && e.indexOf(k) < 0) {\r\n t[k] = s[k];\r\n }\r\n }\r\n if (s != null && typeof ObjClass[strGetOwnPropertySymbols] === strShimFunction) {\r\n for (var i = 0, p = ObjClass[strGetOwnPropertySymbols](s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && ObjProto[\"propertyIsEnumerable\"].call(s, p[i])) {\r\n t[p[i]] = s[p[i]];\r\n }\r\n }\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorateFn(decorators: any, target: any, key: any, desc: any) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = ObjClass[\"getOwnPropertyDescriptor\"](target, key) : desc, d;\r\n if (__hasReflect && typeof ReflectObj[strDecorate] === strShimFunction) {\r\n r = ReflectObj[strDecorate](decorators, target, key, desc);\r\n } else {\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n // eslint-disable-next-line no-cond-assign\r\n if (d = decorators[i]) {\r\n r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n }\r\n }\r\n }\r\n\r\n // tslint:disable-next-line:ban-comma-operator\r\n return c > 3 && r && objDefineProp(target, key, r), r;\r\n}\r\n\r\nexport function __paramFn(paramIndex: number, decorator: Function) {\r\n return function (target: any, key: any) {\r\n decorator(target, key, paramIndex);\r\n }\r\n}\r\n\r\nexport function __metadataFn(metadataKey: any, metadataValue: any) {\r\n if (__hasReflect && ReflectObj[strMetadata] === strShimFunction) {\r\n return ReflectObj[strMetadata](metadataKey, metadataValue);\r\n }\r\n}\r\n\r\nexport function __exportStarFn(m: any, o: any) {\r\n for (var p in m) {\r\n if (p !== strDefault && !objHasOwnProperty(o, p)) {\r\n __createBindingFn(o, m, p);\r\n }\r\n }\r\n}\r\n\r\nexport function __createBindingFn(o: any, m: any, k: any, k2?: any) {\r\n if (k2 === undefined) {\r\n k2 = k;\r\n }\r\n \r\n if (!!objDefineProp) {\r\n objDefineProp(o, k2, {\r\n enumerable: true,\r\n get() {\r\n return m[k];\r\n }\r\n });\r\n } else {\r\n o[k2] = m[k];\r\n }\r\n}\r\n\r\nexport function __valuesFn(o: any) {\r\n var s = typeof SymbolObj === strShimFunction && SymbolObj[strIterator], m = s && o[s], i = 0;\r\n if (m) {\r\n return m.call(o);\r\n }\r\n\r\n if (o && typeof o.length === \"number\") {\r\n return {\r\n next () {\r\n if (o && i >= o.length) {\r\n o = void 0;\r\n }\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n }\r\n\r\n throwTypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __readFn(o: any, n: any) {\r\n var m = typeof SymbolObj === strShimFunction && o[SymbolObj[strIterator]];\r\n if (!m) {\r\n return o;\r\n }\r\n\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) {\r\n ar.push(r.value);\r\n }\r\n } catch (error) {\r\n e = {\r\n error\r\n };\r\n } finally {\r\n try {\r\n // tslint:disable-next-line:no-conditional-assignment\r\n if (r && !r.done && (m = i[\"return\"])) {\r\n m.call(i);\r\n }\r\n } finally {\r\n if (e) {\r\n // eslint-disable-next-line no-unsafe-finally\r\n throw e.error;\r\n }\r\n }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArraysFn() {\r\n var theArgs = arguments;\r\n // Calculate new total size\r\n for (var s = 0, i = 0, il = theArgs.length; i < il; i++) {\r\n s += theArgs[i].length;\r\n }\r\n\r\n // Create new full array\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++) {\r\n for (var a = theArgs[i], j = 0, jl = a.length; j < jl; j++, k++) {\r\n r[k] = a[j];\r\n }\r\n }\r\n\r\n return r;\r\n}\r\n\r\nexport function __spreadArrayFn(to: any, from: any) {\r\n for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) {\r\n to[j] = from[i];\r\n }\r\n\r\n return to;\r\n}\r\n\r\nexport function __makeTemplateObjectFn(cooked: any, raw: any) {\r\n if (objDefineProp) {\r\n objDefineProp(cooked, \"raw\", { value: raw });\r\n } else {\r\n cooked.raw = raw;\r\n }\r\n\r\n return cooked;\r\n}\r\n\r\nexport function __importStarFn(mod: any) {\r\n if (mod && mod.__esModule) {\r\n return mod;\r\n }\r\n\r\n var result = {};\r\n if (mod != null) {\r\n for (var k in mod) {\r\n if (k !== strDefault && Object.prototype.hasOwnProperty.call(mod, k)) {\r\n __createBindingFn(result, mod, k);\r\n }\r\n }\r\n }\r\n\r\n // Set default module\r\n if (!!objDefineProp) {\r\n objDefineProp( result, strDefault, { enumerable: true, value: mod });\r\n } else {\r\n result[strDefault] = mod;\r\n }\r\n\r\n return result;\r\n}\r\n\r\nexport function __importDefaultFn(mod:any) {\r\n return (mod && mod.__esModule) ? mod : { strDefault: mod };\r\n}\r\n","/*\r\n * @nevware21/ts-utils\r\n * https://github.com/nevware21/ts-utils\r\n *\r\n * Copyright (c) 2022 Nevware21\r\n * Licensed under the MIT license.\r\n */\r\n\r\nimport { ArrCls, BOOLEAN, FUNCTION, NULL_VALUE, NUMBER, OBJECT, ObjProto, STRING, UNDEFINED, UNDEF_VALUE } from \"../internal/constants\";\r\nimport { safeGet } from \"./safe_get\";\r\n\r\nconst PRIMITIVE_TYPES = [ STRING, NUMBER, BOOLEAN, UNDEFINED, \"symbol\", \"bigint\" ];\r\n\r\n/**\r\n * @ignore\r\n * @internal\r\n * Create and returns a function that will return `true` if the argument passed\r\n * to it matches the provided type.\r\n * @param theType - The type to match against the `typeof value`\r\n * @returns A function which takes a single argument and returns a boolean\r\n */\r\nexport function _createIs(theType: string): (value: any) => value is T {\r\n return function (value: any): value is T {\r\n return typeof value === theType;\r\n }\r\n}\r\n\r\n/**\r\n * @ignore\r\n * @internal\r\n * Create and returns a function that will return `true` if the argument passed\r\n * to it matches the object type specified based on {@link objToString}.\r\n * @param - The object name to match for the `objToString(value)`\r\n * @returns A function which takes a single argument and returns a boolean\r\n */\r\nexport function _createObjIs(theName: string): (value: any) => value is T {\r\n const theType = \"[object \" + theName + \"]\";\r\n return function (value: any): value is T {\r\n return !!(value && objToString(value) === theType);\r\n }\r\n}\r\n\r\n/**\r\n * The `objToString()` method returns a string representing the object. This explicitly\r\n * always calls the `Object.prototype.toString()` method.\r\n *\r\n * An object's toString() method is most commonly invoked when that object undergoes:\r\n * - explicit type conversion to a string (for example, String(myObject))\r\n * - implicit type coercion into a string (for example, myObject + \"hello world\")\r\n *\r\n * @group Object\r\n * @param value - The object to be converted into a string\r\n * @returns A string representation of the object\r\n * @example\r\n * ```ts\r\n * objToString(new Date()); // [object Date]\r\n * objToString(new String()); // [object String]\r\n *\r\n * // Math has its Symbol.toStringTag\r\n * objToString(Math); // [object Math]\r\n *\r\n * objToString(undefined); // [object Undefined]\r\n * objToString(null); // [object Null]\r\n * ```\r\n */\r\nexport function objToString(value: any): string {\r\n return ObjProto.toString.call(value);\r\n}\r\n\r\n/**\r\n * Validate if the provided value object is of the expected type\r\n * @group Type Identity\r\n * @param value - The value to check\r\n * @param theType - The expected type name as a string\r\n * @returns `true` if the value matches the provided type\r\n */\r\nexport function isTypeof(value: any, theType: string): boolean {\r\n return typeof value === theType;\r\n}\r\n\r\n/**\r\n * Checks if the provided value is undefined or contains the string value \"undefined\",\r\n * if you want to consider the string value as undefined see {@link isStrictUndefined}\r\n * @group Type Identity\r\n * @group Value Check\r\n * @param value - The value to check\r\n * @returns true if the value is undefined or \"undefined\", otherwise false\r\n * @example\r\n * ```ts\r\n * isUndefined(undefined); // true\r\n * isUndefined(\"undefined\"); // true\r\n *\r\n * isUndefined(null); // false\r\n * isUndefined(\"null\"); // false\r\n * isUndefined(\"1\"); // false\r\n * isUndefined(\"aa\"); // false\r\n * isUndefined(new Date()); // false\r\n * isUndefined(1); // false\r\n * isUndefined(\"\"); // false\r\n * isUndefined(_dummyFunction); // false\r\n * isUndefined([]); // false\r\n * isUndefined(new Array(1)); // false\r\n * isUndefined(true); // false\r\n * isUndefined(false); // false\r\n * isUndefined(\"true\"); // false\r\n * isUndefined(\"false\"); // false\r\n * isUndefined(new Boolean(true)); // false\r\n * isUndefined(new Boolean(false)); // false\r\n * isUndefined(new Boolean(\"true\")); // false\r\n * isUndefined(new Boolean(\"false\")); // false\r\n * isUndefined(Boolean(true)); // false\r\n * isUndefined(Boolean(false)); // false\r\n * isUndefined(Boolean(\"true\")); // false\r\n * isUndefined(Boolean(\"false\")); // false\r\n * isUndefined(new RegExp(\"\")); // false\r\n * isUndefined(new ArrayBuffer(0)); // false\r\n * isUndefined(new Error(\"Test Error\"));// false\r\n * isUndefined(new TypeError(\"Test TypeError\")); // false\r\n * isUndefined(new TestError(\"Test TestError\")); // false\r\n * isUndefined(_dummyError()); // false\r\n * isUndefined(Promise.reject()); // false\r\n * isUndefined(Promise.resolve()); // false\r\n * isUndefined(new Promise(() => {})); // false\r\n * isUndefined(_simplePromise()); // false\r\n * isUndefined(_simplePromiseLike()); // false\r\n * isUndefined(Object.create(null)); // false\r\n * isUndefined(polyObjCreate(null)); // false\r\n * ```\r\n */\r\nexport function isUndefined(value: any) {\r\n return typeof value === UNDEFINED || value === UNDEFINED;\r\n}\r\n\r\n/**\r\n * Checks if the provided value is undefined, a string value of \"undefined\" is NOT considered\r\n * to be undefined.\r\n * @group Type Identity\r\n * @group Value Check\r\n * @param value - The value to check\r\n * @returns true if the typeof value === UNDEFINED\r\n * @example\r\n * ```ts\r\n * isStrictUndefined(undefined); // true\r\n *\r\n * isStrictUndefined(null); // false\r\n * isStrictUndefined(\"null\"); // false\r\n * isStrictUndefined(\"undefined\"); // false\r\n * isStrictUndefined(\"1\"); // false\r\n * isStrictUndefined(\"aa\"); // false\r\n * isStrictUndefined(new Date()); // false\r\n * isStrictUndefined(0); // false\r\n * isStrictUndefined(1); // false\r\n * isStrictUndefined(\"\"); // false\r\n * ```\r\n */\r\nexport function isStrictUndefined(arg: any): arg is undefined {\r\n return !isDefined(arg);\r\n}\r\n\r\n/**\r\n * Checks if the provided value is null, undefined or contains the string value of \"undefined\".\r\n * @group Type Identity\r\n * @group Value Check\r\n * @param value - The value to check\r\n * @returns `true` if the value is `null` or `undefined`\r\n * @example\r\n * ```ts\r\n * isNullOrUndefined(null); // true\r\n * isNullOrUndefined(undefined); // true\r\n * isNullOrUndefined(\"undefined\"); // true\r\n *\r\n * let value = null;\r\n * isNullOrUndefined(value); // true\r\n * let value = undefined;\r\n * isNullOrUndefined(value); // true\r\n *\r\n * isNullOrUndefined(\"\"); // false\r\n * isNullOrUndefined(0); // false\r\n * isNullOrUndefined(new Date()); // false\r\n * isNullOrUndefined(true); // false\r\n * isNullOrUndefined(false); // false\r\n * ```\r\n */\r\nexport function isNullOrUndefined(value: any): boolean {\r\n return value === NULL_VALUE || isUndefined(value);\r\n}\r\n\r\n/**\r\n * Checks if the provided value is null, undefined only, a string value of \"undefined\" is NOT considered\r\n * to be undefined.\r\n * @group Type Identity\r\n * @group Value Check\r\n * @param value - The value to check\r\n * @returns\r\n * @example\r\n * ```ts\r\n * isStrictNullOrUndefined(null); // true\r\n * isStrictNullOrUndefined(undefined); // true\r\n * isStrictNullOrUndefined(\"undefined\"); // false\r\n *\r\n * let value = null;\r\n * isStrictNullOrUndefined(value); // true\r\n * let value = undefined;\r\n * isStrictNullOrUndefined(value); // true\r\n *\r\n * isStrictNullOrUndefined(\"\"); // false\r\n * isStrictNullOrUndefined(0); // false\r\n * isStrictNullOrUndefined(new Date()); // false\r\n * isStrictNullOrUndefined(true); // false\r\n * isStrictNullOrUndefined(false); // false\r\n * ```\r\n */\r\nexport function isStrictNullOrUndefined(value: any): boolean {\r\n return value === NULL_VALUE || !isDefined(value);\r\n}\r\n\r\n/**\r\n * Checks if the passed value is defined, which means it has any value and is not undefined.\r\n * A string value of \"undefined\" is considered to be defined.\r\n * @group Value Check\r\n * @param arg - The value to check\r\n * @returns true if arg has a value (is not === undefined)\r\n * @example\r\n * ```ts\r\n * isDefined(null); // false\r\n * isDefined(undefined); // false\r\n * isDefined(\"undefined\"); // true\r\n *\r\n * let value = null;\r\n * isDefined(value); // false\r\n * let value = undefined;\r\n * isDefined(value); // false\r\n *\r\n * isDefined(\"\"); // true\r\n * isDefined(0); // true\r\n * isDefined(new Date()); // true\r\n * isDefined(true); // true\r\n * isDefined(false); // true\r\n * ```\r\n */\r\nexport function isDefined(arg: any): boolean {\r\n return !!arg || arg !== UNDEF_VALUE;\r\n}\r\n\r\n/**\r\n * Identifies whether the provided value is a JavaScript [primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive)\r\n * which is when is it not an object and has no methods or properties. There are 7 primitive data types:\r\n * - string\r\n * - number\r\n * - bigint\r\n * - boolean\r\n * - undefined\r\n * - null\r\n * - symbol\r\n *\r\n * Most of the time, a primitive value is represented directly at the lowest level of the language implementation.\r\n *\r\n * All primitives are immutable; that is, they cannot be altered. It is important not to confuse a primitive itself\r\n * with a variable assigned a primitive value. The variable may be reassigned to a new value, but the existing value\r\n * can not be changed in the ways that objects, arrays, and functions can be altered. The language does not offer\r\n * utilities to mutate primitive values.\r\n * @since 0.4.4\r\n * @group Type Identity\r\n * @param value - The value to check whether it's a primitive value\r\n * @example\r\n * ```ts\r\n * isPrimitive(null); // true\r\n * isPrimitive(undefined); // true\r\n * isPrimitive(\"null\"); // true\r\n * isPrimitive(\"undefined\"); // true\r\n * isPrimitive(\"1\"); // true\r\n * isPrimitive(\"aa\"); // true\r\n * isPrimitive(1); // true\r\n * isPrimitive(Number(2)); // true\r\n * isPrimitive(\"\"); // true\r\n * isPrimitive(String(\"\")); // true\r\n * isPrimitive(true); // true\r\n * isPrimitive(false); // true\r\n * isPrimitive(\"true\"); // true\r\n * isPrimitive(\"false\"); // true\r\n * isPrimitive(BigInt(42)); // true\r\n * isPrimitive(Symbol.for(\"Hello\")); // true\r\n *\r\n * isPrimitive(new String(\"aa\")); // false\r\n * isPrimitive(new Date()); // false\r\n * isPrimitive(_dummyFunction); // false\r\n * isPrimitive([]); // false\r\n * isPrimitive(new Array(1)); // false\r\n * isPrimitive(new Boolean(true)); // false\r\n * isPrimitive(new Boolean(false)); // false\r\n * isPrimitive(new Boolean(\"true\")); // false\r\n * isPrimitive(new Boolean(\"false\")); // false\r\n * ```\r\n */\r\nexport const isPrimitive = (value: any): value is string | number | bigint | boolean | undefined | symbol | null => {\r\n return value === NULL_VALUE || isPrimitiveType(typeof value);\r\n};\r\n\r\n/**\r\n * Identifies whether the provided value is a JavaScript [primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive)\r\n * which is when is it not an object and has no methods or properties. There are 6 primitive data types:\r\n * - string\r\n * - number\r\n * - bigint\r\n * - boolean\r\n * - undefined\r\n * - symbol\r\n *\r\n * Most of the time, a primitive value is represented directly at the lowest level of the language implementation.\r\n *\r\n * All primitives are immutable; that is, they cannot be altered. It is important not to confuse a primitive itself\r\n * with a variable assigned a primitive value. The variable may be reassigned to a new value, but the existing value\r\n * can not be changed in the ways that objects, arrays, and functions can be altered. The language does not offer\r\n * utilities to mutate primitive values.\r\n * @since 0.9.6\r\n * @group Type Identity\r\n * @param theType - The type as a string value to be checked whther it's a primitive type, this should be the value\r\n * returned from `typeof value`.\r\n * @example\r\n * ```ts\r\n * isPrimitiveType(null); // false\r\n * isPrimitiveType(undefined); // false\r\n * isPrimitiveType(\"null\"); // false\r\n * isPrimitiveType(\"undefined\"); // false\r\n * isPrimitiveType(\"1\"); // false\r\n * isPrimitiveType(\"aa\"); // false\r\n * isPrimitiveType(1); // false\r\n * isPrimitiveType(Number(2)); // false\r\n * isPrimitiveType(\"\"); // false\r\n * isPrimitiveType(String(\"\")); // false\r\n * isPrimitiveType(true); // false\r\n * isPrimitiveType(false); // false\r\n * isPrimitiveType(\"true\"); // false\r\n * isPrimitiveType(\"false\"); // false\r\n * isPrimitiveType(BigInt(42)); // false\r\n * isPrimitiveType(Symbol.for(\"Hello\")); // false\r\n *\r\n * isPrimitiveType(\"string\"); // true\r\n * isPrimitiveType(\"number\"); // true\r\n * isPrimitiveType(\"boolean\"); // true\r\n * isPrimitiveType(\"undefined\"); // true\r\n * isPrimitiveType(\"symbol\"); // true\r\n * isPrimitiveType(\"bigint\"); // true\r\n * ```\r\n */\r\nexport const isPrimitiveType = (theType: string): boolean => {\r\n return theType !== OBJECT && PRIMITIVE_TYPES.indexOf(theType) !== -1;\r\n};\r\n\r\n/**\r\n * Checks to see if the past value is a string value\r\n * @group Type Identity\r\n * @group String\r\n * @param value - The value to check\r\n * @returns\r\n * @example\r\n * ```ts\r\n * isString(\"\"); // true\r\n * isString(\"null\"); // true\r\n * isString(\"undefined\"); // true\r\n * isString(String(\"\")); // true\r\n *\r\n * isString(null); // false\r\n * isString(undefined); // false\r\n * isString(0); // false\r\n * ```\r\n */\r\nexport const isString: (value: any) => value is string = _createIs(STRING);\r\n\r\n/**\r\n * Checks to see if the past value is a function value\r\n * @group Type Identity\r\n * @param value - The value to check\r\n * @returns\r\n * @example\r\n * ```ts\r\n * function myFunction() { }\r\n * isFunction(null); // false\r\n * isFunction(undefined); // false\r\n * isFunction(\"null\"); // false\r\n * isFunction(\"undefined\"); // false\r\n * isFunction(\"1\"); // false\r\n * isFunction(\"aa\"); // false\r\n * isFunction(new Date()); // false\r\n * isFunction(1); // false\r\n * isFunction(\"\"); // false\r\n * isFunction(myFunction); // true\r\n * isFunction([]); // false\r\n * isFunction(new Array(1)); // false\r\n * ```\r\n */\r\nexport const isFunction: (value: any) => value is Function = _createIs(FUNCTION);\r\n\r\n/**\r\n * Checks to see if the past value is an object value\r\n * @group Type Identity\r\n * @group Object\r\n * @typeParam T - The object type, defaults to any\r\n * @param value - The value to check\r\n * @returns\r\n */\r\nexport function isObject(value: T): value is T {\r\n if (!value && isNullOrUndefined(value)) {\r\n return false;\r\n }\r\n\r\n return !!value && typeof value === OBJECT;\r\n}\r\n\r\n/**\r\n * Checks if the type of value is an Array.\r\n *\r\n * @group Type Identity\r\n * @group Array\r\n * @param {any} value - Value to be checked.\r\n * @return {boolean} True if the value is a Array, false otherwise.\r\n * @example\r\n * ```ts\r\n * import { isArray, isObject } from \"@nevware21/ts-utils\";\r\n *\r\n * function performAction(value: any) {\r\n * if (isArray(value) || isObject(value)) {\r\n * // Do something\r\n * } else {\r\n * // Do something else\r\n * }\r\n * }\r\n * ```\r\n */\r\nexport const isArray: (arg: any) => arg is Array = ArrCls.isArray;\r\n\r\n/**\r\n * Check if an object is of type Date\r\n * @group Type Identity\r\n * @example\r\n * ```ts\r\n * import { isDate } from \"@nevware21/ts-utils\";\r\n *\r\n * let _theDate = null;\r\n *\r\n * function getSetDate(newDate?: any) {\r\n * _theDate = isDate(newDate) ? newDate : new Date();\r\n *\r\n * return _theDate;\r\n * }\r\n * ```\r\n */\r\nexport const isDate: (value: any) => value is Date = _createObjIs(\"Date\");\r\n\r\n/**\r\n * Checks if the type of value is a number.\r\n * @group Type Identity\r\n * @param {any} value - Value to be checked.\r\n * @return {boolean} True if the value is a number, false otherwise.\r\n */\r\nexport const isNumber: (value: any) => value is number = _createIs(NUMBER);\r\n\r\n/**\r\n * Checks if the type of value is a boolean.\r\n * @group Type Identity\r\n * @param {any} value - Value to be checked.\r\n * @return {boolean} True if the value is a boolean, false otherwise.\r\n */\r\nexport const isBoolean: (value: any) => value is boolean = _createIs(BOOLEAN);\r\n\r\n/**\r\n * Determines if a value is a regular expression object.\r\n * @group Type Identity\r\n * @param {*} value Reference to check.\r\n * @returns {boolean} True if `value` is a `RegExp`.\r\n */\r\nexport const isRegExp: (value: any) => value is RegExp = _createObjIs(\"RegExp\");\r\n\r\n/**\r\n * Checks if the type of value is a File object.\r\n * @group Type Identity\r\n * @param {any} value - Value to be checked.\r\n * @return {boolean} True if the value is a File, false otherwise.\r\n */\r\nexport const isFile: (value: any) => value is File = _createObjIs(\"File\");\r\n\r\n/**\r\n * Checks if the type of value is a FormData object.\r\n * @group Type Identity\r\n * @param {any} value - Value to be checked.\r\n * @return {boolean} True if the value is a FormData, false otherwise.\r\n */\r\nexport const isFormData: (value: any) => value is FormData = _createObjIs(\"FormData\");\r\n\r\n/**\r\n * Checks if the type of value is a Blob object.\r\n * @group Type Identity\r\n * @param {any} value - Value to be checked.\r\n * @return {boolean} True if the value is a Blob, false otherwise.\r\n */\r\nexport const isBlob: (value: any) => value is Blob = _createObjIs(\"Blob\");\r\n\r\n/**\r\n * Checks if the type of value is a ArrayBuffer object.\r\n * @group Type Identity\r\n * @param {any} value - Value to be checked.\r\n * @return {boolean} True if the value is a ArrayBuffer, false otherwise.\r\n */\r\nexport const isArrayBuffer: (value: any) => value is ArrayBuffer = _createObjIs(\"ArrayBuffer\");\r\n\r\n/**\r\n * Checks if the type of value is a Error object.\r\n * @group Type Identity\r\n * @group Error\r\n * @param {any} value - Value to be checked.\r\n * @return {boolean} True if the value is a Error, false otherwise.\r\n */\r\nexport const isError: (value: any) => value is Error = _createObjIs