/*!
 * Application Insights JavaScript SDK - Channel, 3.3.10
 * Copyright (c) Microsoft and contributors. All rights reserved.
 */
(function (global, factory) {
    var undef = "undefined";
    var nsKey, key, nm, theExports = {}, modName = "es5_applicationinsights_channel_js_3_3_10", msMod="__ms$mod__";
    var mods={}, modDetail=mods[modName]={}, ver="3.3.10";
    var baseNs=global, nsKey="Microsoft", baseNs=baseNs[nsKey]=(baseNs[nsKey]||{});
    // Versioned namespace "Microsoft.ApplicationInsights3"
    var exportNs=baseNs, nsKey="ApplicationInsights3", exportNs=exportNs[nsKey]=(exportNs[nsKey]||{});
    // Global namespace "Microsoft.ApplicationInsights"
    var destNs=baseNs, nsKey="ApplicationInsights", destNs=destNs[nsKey]=(destNs[nsKey]||{});
    var expNsDetail=(exportNs[msMod]=(exportNs[msMod] || {})), expNameVer=(expNsDetail["v"]=(expNsDetail["v"] || []));
    var destNsDetail=(destNs[msMod]=(destNs[msMod] || {})), destNameVer=(destNsDetail["v"]=(destNsDetail["v"] || []));
    (destNsDetail["o"]=(destNsDetail["o"] || [])).push(mods);
    factory(theExports);
    for(var key in theExports) {
        // Always set the imported value into the "export" versioned namespace (last-write wins)
        nm="x", exportNs[key]=theExports[key], expNameVer[key]=ver;
        // Copy over any named element that is not already present (first-write wins)
        typeof destNs[key]===undef ? (nm="n", destNs[key]=theExports[key]) && (destNameVer[key]=ver) : !destNameVer[key] && (destNameVer[key]="---");
        (modDetail[nm] = (modDetail[nm] || [])).push(key);
    }
})(this, (function (exports) {
'use strict';


var strShimFunction = "function";
var strShimObject = "object";
var strShimUndefined = "undefined";
var strShimPrototype = "prototype";
var ObjClass$1 = Object;
var ObjProto$1 = ObjClass$1[strShimPrototype];

/*! https://github.com/nevware21/ts-utils v0.12.5 */
/*#__NO_SIDE_EFFECTS__*/
function _pureAssign(func1, func2) {
    return func1 || func2;
}
/*#__NO_SIDE_EFFECTS__*/
function _pureRef(value, name) {
    return value[name];
}
var UNDEF_VALUE = undefined;
var NULL_VALUE = null;
var EMPTY = "";
var FUNCTION = "function";
var OBJECT = "object";
var PROTOTYPE = "prototype";
var __PROTO__ = "__proto__";
var UNDEFINED = "undefined";
var CONSTRUCTOR = "constructor";
var SYMBOL = "Symbol";
var LENGTH = "length";
var NAME = "name";
var CALL = "call";
var TO_STRING = "toString";
var GET_OWN_PROPERTY_DESCRIPTOR = "getOwnPropertyDescriptor";
var ObjClass = ( /*#__PURE__*/_pureAssign(Object));
var ObjProto = ( /*#__PURE__*/_pureRef(ObjClass, PROTOTYPE));
var StrCls = ( /*#__PURE__*/_pureAssign(String));
var StrProto = ( /*#__PURE__*/_pureRef(StrCls, PROTOTYPE));
var MathCls = ( /*#__PURE__*/_pureAssign(Math));
var ArrCls = ( /*#__PURE__*/_pureAssign(Array));
var ArrProto = ( /*#__PURE__*/_pureRef(ArrCls, PROTOTYPE));
var ArrSlice = ( /*#__PURE__*/_pureRef(ArrProto, "slice"));
var POLYFILL_TAG = "_polyfill";
var POLYFILL_TYPE_NAME = "__nw21$polytype__";
function safe(func, argArray) {
    try {
        return {
            v: func.apply(this, argArray)
        };
    }
    catch (e) {
        return { e: e };
    }
}
/*#__NO_SIDE_EFFECTS__*/
function safeGet(cb, defValue, argArray) {
    var result = safe(cb, argArray);
    return result.e ? defValue : result.v;
}
/*#__NO_SIDE_EFFECTS__*/
function _createIs(theType) {
    return function (value) {
        return typeof value === theType;
    };
}
/*#__NO_SIDE_EFFECTS__*/
function _createObjIs(theName) {
    var theType = "[object " + theName + "]";
    return function (value) {
        return !!(value && objToString(value) === theType);
    };
}
/*#__NO_SIDE_EFFECTS__*/
function objToString(value) {
    return ObjProto[TO_STRING].call(value);
}
/*#__NO_SIDE_EFFECTS__*/
function isUndefined(value) {
    return typeof value === UNDEFINED || value === UNDEFINED;
}
/*#__NO_SIDE_EFFECTS__*/
function isStrictUndefined(arg) {
    return arg === UNDEF_VALUE;
}
/*#__NO_SIDE_EFFECTS__*/
function isNullOrUndefined(value) {
    return value === NULL_VALUE || isUndefined(value);
}
/*#__NO_SIDE_EFFECTS__*/
function isStrictNullOrUndefined(value) {
    return value === NULL_VALUE || value === UNDEF_VALUE;
}
/*#__NO_SIDE_EFFECTS__*/
function isDefined(arg) {
    return !!arg || arg !== UNDEF_VALUE;
}
var isString = ( /*#__PURE__*/_createIs("string"));
var isFunction = ( /*#__PURE__*/_createIs(FUNCTION));
/*#__NO_SIDE_EFFECTS__*/
function isObject(value) {
    if (!value && isNullOrUndefined(value)) {
        return false;
    }
    return !!value && typeof value === OBJECT;
}
var isArray = ( /* #__PURE__*/_pureRef(ArrCls, "isArray"));
var isNumber = ( /*#__PURE__*/_createIs("number"));
var isBoolean = ( /*#__PURE__*/_createIs("boolean"));
var isError = ( /*#__PURE__*/_createObjIs("Error"));
/*#__NO_SIDE_EFFECTS__*/
function isPromiseLike(value) {
    return !!(value && value.then && isFunction(value.then));
}
/*#__NO_SIDE_EFFECTS__*/
function isTruthy(value) {
    return !(!value || safeGet(function () { return !(value && (0 + value)); }, !value));
}
function _returnNothing() {
    return;
}
function _returnFalse() {
    return false;
}
var asString = ( /*#__PURE__*/_pureAssign(StrCls));
var ERROR_TYPE = "[object Error]";
/*#__NO_SIDE_EFFECTS__*/
function dumpObj(object, format) {
    var propertyValueDump = EMPTY;
    var objType = ObjProto[TO_STRING][CALL](object);
    if (objType === ERROR_TYPE) {
        object = { stack: asString(object.stack), message: asString(object.message), name: asString(object.name) };
    }
    try {
        propertyValueDump = JSON.stringify(object, NULL_VALUE, format ? ((typeof format === "number") ? format : 4) : UNDEF_VALUE);
        propertyValueDump = (propertyValueDump ? propertyValueDump.replace(/"(\w+)"\s*:\s{0,1}/g, "$1: ") : NULL_VALUE) || asString(object);
    }
    catch (e) {
        propertyValueDump = " - " + dumpObj(e, format);
    }
    return objType + ": " + propertyValueDump;
}
function throwTypeError(message) {
    throw new TypeError(message);
}
function _throwIfNullOrUndefined(obj) {
    if (isStrictNullOrUndefined(obj)) {
        throwTypeError("Cannot convert undefined or null to object");
    }
}
/*#__NO_SIDE_EFFECTS__*/
function objHasOwnProperty(obj, prop) {
    return !!obj && ObjProto.hasOwnProperty[CALL](obj, prop);
}
var _objGetOwnPropertyDescriptor$2 = ( /*#__PURE__*/_pureAssign(( /*#__PURE__*/_pureRef(ObjClass, GET_OWN_PROPERTY_DESCRIPTOR)), _returnNothing));
var objHasOwn = ( /*#__PURE__*/_pureAssign(( /*#__PURE__*/_pureRef(ObjClass, "hasOwn")), polyObjHasOwn));
/*#__NO_SIDE_EFFECTS__*/
function polyObjHasOwn(obj, prop) {
    _throwIfNullOrUndefined(obj);
    return objHasOwnProperty(obj, prop) || !!_objGetOwnPropertyDescriptor$2(obj, prop);
}
function objForEachKey(theObject, callbackfn, thisArg) {
    if (theObject && (isObject(theObject) || isFunction(theObject))) {
        for (var prop in theObject) {
            if (objHasOwn(theObject, prop)) {
                if (callbackfn[CALL](thisArg || theObject, prop, theObject[prop]) === -1) {
                    break;
                }
            }
        }
    }
}
function arrForEach(theArray, callbackfn, thisArg) {
    if (theArray) {
        var len = theArray[LENGTH] >>> 0;
        for (var idx = 0; idx < len; idx++) {
            if (idx in theArray) {
                if (callbackfn[CALL](thisArg || theArray, theArray[idx], idx, theArray) === -1) {
                    break;
                }
            }
        }
    }
}
var _unwrapFunction = ( _unwrapFunctionWithPoly);
/*#__NO_SIDE_EFFECTS__*/
function _unwrapFunctionWithPoly(funcName, clsProto, polyFunc) {
    var clsFn = clsProto ? clsProto[funcName] : NULL_VALUE;
    return function (thisArg) {
        var theFunc = (thisArg ? thisArg[funcName] : NULL_VALUE) || clsFn;
        if (theFunc || polyFunc) {
            var theArgs = arguments;
            return (theFunc || polyFunc).apply(thisArg, theFunc ? ArrSlice[CALL](theArgs, 1) : theArgs);
        }
        throwTypeError("\"" + asString(funcName) + "\" not defined for " + dumpObj(thisArg));
    };
}
var _objGetOwnPropertyDescriptor$1 = ( /*#__PURE__*/_pureAssign(( /*#__PURE__*/_pureRef(ObjClass, GET_OWN_PROPERTY_DESCRIPTOR)), _returnNothing));
var propMap = {
    e: "enumerable",
    c: "configurable",
    v: "value",
    w: "writable",
    g: "get",
    s: "set"
};
/*#__NO_SIDE_EFFECTS__*/
function _createProp(value) {
    var prop = {};
    prop[propMap["c"]] = true;
    prop[propMap["e"]] = true;
    if (value.l) {
        prop.get = function () { return value.l.v; };
        var desc = _objGetOwnPropertyDescriptor$1(value.l, "v");
        if (desc && desc.set) {
            prop.set = function (newValue) {
                value.l.v = newValue;
            };
        }
    }
    objForEachKey(value, function (key, value) {
        prop[propMap[key]] = isStrictUndefined(value) ? prop[propMap[key]] : value;
    });
    return prop;
}
var objDefineProp = ( /*#__PURE__*/_pureRef(ObjClass, "defineProperty"));
var objDefineProperties = ( /*#__PURE__*/_pureRef(ObjClass, "defineProperties"));
function objDefine(target, key, propDesc) {
    return objDefineProp(target, key, _createProp(propDesc));
}
/*#__NO_SIDE_EFFECTS__*/
function _createKeyValueMap(values, keyType, valueType, completeFn, writable) {
    var theMap = {};
    objForEachKey(values, function (key, value) {
        _assignMapValue(theMap, key, keyType ? value : key);
        _assignMapValue(theMap, value, valueType ? value : key);
    });
    return completeFn ? completeFn(theMap) : theMap;
}
function _assignMapValue(theMap, key, value, writable) {
    objDefineProp(theMap, key, {
        value: value,
        enumerable: true,
        writable: false
    });
}
var objIsFrozen = ( /*#__PURE__*/_pureAssign(( /*#__PURE__*/_pureRef(ObjClass, "isFrozen")), _returnFalse));
var _objFreeze = ( /*#__PURE__*/_pureRef(ObjClass, "freeze"));
function _doNothing(value) {
    return value;
}
/*#__NO_SIDE_EFFECTS__*/
function _getProto(value) {
    _throwIfNullOrUndefined(value);
    return value[__PROTO__] || NULL_VALUE;
}
var objAssign = ( /*#__PURE__*/_pureRef(ObjClass, "assign"));
var objKeys = ( /*#__PURE__*/_pureRef(ObjClass, "keys"));
function _deepFreeze(val, visited) {
    if ((isArray(val) || isObject(val) || isFunction(val)) && !objIsFrozen(val)) {
        for (var lp = 0; lp < visited.length; lp++) {
            if (visited[lp] === val) {
                return val;
            }
        }
        visited.push(val);
        objForEachKey(val, function (_key, propValue) {
            _deepFreeze(propValue, visited);
        });
        objFreeze(val);
    }
    return val;
}
function objDeepFreeze(value) {
    return _objFreeze ? _deepFreeze(value, []) : value;
}
var objFreeze = ( /*#__PURE__*/_pureAssign(_objFreeze, _doNothing));
var objGetPrototypeOf = ( /*#__PURE__*/_pureAssign(( /*#__PURE__*/_pureRef(ObjClass, "getPrototypeOf")), _getProto));
/*#__NO_SIDE_EFFECTS__*/
function createEnum(values) {
    return _createKeyValueMap(values, 1 , 0 , objFreeze);
}
/*#__NO_SIDE_EFFECTS__*/
function createEnumKeyMap(values) {
    return _createKeyValueMap(values, 0 , 0 , objFreeze);
}
/*#__NO_SIDE_EFFECTS__*/
function createSimpleMap(values) {
    var mapClass = {};
    objForEachKey(values, function (key, value) {
        _assignMapValue(mapClass, key, value[1]);
        _assignMapValue(mapClass, value[0], value[1]);
    });
    return objFreeze(mapClass);
}
/*#__NO_SIDE_EFFECTS__*/
function createTypeMap(values) {
    return createSimpleMap(values);
}
var _wellKnownSymbolMap = ( /*#__PURE__*/createEnumKeyMap({
    asyncIterator: 0 ,
    hasInstance: 1 ,
    isConcatSpreadable: 2 ,
    iterator: 3 ,
    match: 4 ,
    matchAll: 5 ,
    replace: 6 ,
    search: 7 ,
    species: 8 ,
    split: 9 ,
    toPrimitive: 10 ,
    toStringTag: 11 ,
    unscopables: 12
}));
var GLOBAL_CONFIG_KEY = "__tsUtils$gblCfg";
var _globalCfg;
/*#__NO_SIDE_EFFECTS__*/
function _getGlobalValue() {
    var result;
    if (typeof globalThis !== UNDEFINED) {
        result = globalThis;
    }
    if (!result && typeof self !== UNDEFINED) {
        result = self;
    }
    if (!result && typeof window !== UNDEFINED) {
        result = window;
    }
    if (!result && typeof global !== UNDEFINED) {
        result = global;
    }
    return result;
}
/*#__NO_SIDE_EFFECTS__*/
function _getGlobalConfig() {
    if (!_globalCfg) {
        var gbl = safe(_getGlobalValue).v || {};
        _globalCfg = gbl[GLOBAL_CONFIG_KEY] = gbl[GLOBAL_CONFIG_KEY] || {};
    }
    return _globalCfg;
}
var mathMin = ( /*#__PURE__*/_pureRef(MathCls, "min"));
var mathMax = ( /*#__PURE__*/_pureRef(MathCls, "max"));
var strSlice = ( /*#__PURE__*/_unwrapFunction("slice", StrProto));
var strSubstring = ( /*#__PURE__*/_unwrapFunction("substring", StrProto));
var strSubstr = ( /*#__PURE__*/_unwrapFunctionWithPoly("substr", StrProto, polyStrSubstr));
/*#__NO_SIDE_EFFECTS__*/
function polyStrSubstr(value, start, length) {
    _throwIfNullOrUndefined(value);
    if (length < 0) {
        return EMPTY;
    }
    start = start || 0;
    if (start < 0) {
        start = mathMax(start + value[LENGTH], 0);
    }
    if (isUndefined(length)) {
        return strSlice(value, start);
    }
    return strSlice(value, start, start + length);
}
function _tagAsPolyfill(target, polyfillTypeName) {
    if (target) {
        safe(function () {
            target[POLYFILL_TAG] = true;
            target[POLYFILL_TYPE_NAME] = polyfillTypeName;
        });
        safe(objDefine, [target, POLYFILL_TAG, {
                v: true,
                w: false,
                e: false
            }]);
        safe(objDefine, [target, POLYFILL_TYPE_NAME, {
                v: polyfillTypeName,
                w: false,
                e: false
            }]);
    }
    return target;
}
var objCreate = ( /* #__PURE__*/_pureAssign(( /* #__PURE__*/_pureRef(ObjClass, "create")), polyObjCreate));
/*#__NO_SIDE_EFFECTS__*/
function polyObjCreate(obj, properties) {
    var newObj = null;
    function tempFunc() { }
    if (!isStrictNullOrUndefined(obj)) {
        var type = typeof obj;
        if (type !== OBJECT && type !== FUNCTION) {
            throwTypeError("Prototype must be an Object or function: " + dumpObj(obj));
        }
        tempFunc[PROTOTYPE] = obj;
        safe(function () {
            tempFunc[__PROTO__] = obj;
        });
        newObj = new tempFunc();
    }
    else {
        newObj = {};
    }
    if (properties) {
        safe(objDefineProperties, [newObj, properties]);
    }
    return newObj;
}
/*#__NO_SIDE_EFFECTS__*/
function utcNow() {
    return (Date.now || polyUtcNow)();
}
/*#__NO_SIDE_EFFECTS__*/
function polyUtcNow() {
    return new Date().getTime();
}
function fnApply(fn, thisArg, argArray) {
    return fn.apply(thisArg, argArray);
}
var _globalLazyTestHooks;
function _initTestHooks() {
    _globalLazyTestHooks = _getGlobalConfig();
}
/*#__NO_SIDE_EFFECTS__*/
function getLazy(cb, argArray) {
    var lazyValue = {};
    !_globalLazyTestHooks && _initTestHooks();
    lazyValue.b = _globalLazyTestHooks.lzy;
    objDefineProp(lazyValue, "v", {
        configurable: true,
        get: function () {
            var result = fnApply(cb, null, argArray);
            if (!_globalLazyTestHooks.lzy) {
                objDefineProp(lazyValue, "v", {
                    value: result
                });
            }
            lazyValue.b = _globalLazyTestHooks.lzy;
            return result;
        }
    });
    return lazyValue;
}
var mathRandom = ( /*#__PURE__*/_pureRef(MathCls, "random"));
var _uniqueInstanceId = ( /*#__PURE__*/getLazy(function () {
    var value = (utcNow().toString(36).slice(2));
    while (value.length < 16) {
        value += mathRandom().toString(36).slice(2);
    }
    value = value.substring(0, 16);
    return value;
}));
var UNIQUE_REGISTRY_ID = "_urid";
var POLY_SYM = "$nw21sym";
var _polySymbols;
var _polyId = 0;
/*#__NO_SIDE_EFFECTS__*/
function _globalSymbolRegistry() {
    if (!_polySymbols) {
        var gblCfg = _getGlobalConfig();
        _polySymbols = gblCfg.gblSym = gblCfg.gblSym || { k: {}, s: {} };
    }
    return _polySymbols;
}
var _wellKnownSymbolCache;
/*#__NO_SIDE_EFFECTS__*/
function polyNewSymbol(description) {
    var uniqueId = "_" + _polyId++ + "_" + _uniqueInstanceId.v;
    var symString = SYMBOL + "(" + description + ")";
    function _setProp(name, value) {
        objDefine(theSymbol, name, {
            v: value,
            e: false,
            w: false
        });
    }
    var theSymbol = objCreate(null);
    _setProp("description", asString(description));
    _setProp(TO_STRING, function () { return symString + POLY_SYM + uniqueId; });
    _setProp("valueOf", function () { return theSymbol; });
    _setProp("v", symString);
    _setProp("_uid", uniqueId);
    return _tagAsPolyfill(theSymbol, "symbol");
}
/*#__NO_SIDE_EFFECTS__*/
function polySymbolFor(key) {
    var registry = _globalSymbolRegistry();
    if (!objHasOwn(registry.k, key)) {
        var newSymbol_1 = polyNewSymbol(key);
        var regId_1 = objKeys(registry.s).length;
        newSymbol_1[UNIQUE_REGISTRY_ID] = function () { return regId_1 + "_" + newSymbol_1[TO_STRING](); };
        registry.k[key] = newSymbol_1;
        registry.s[newSymbol_1[UNIQUE_REGISTRY_ID]()] = asString(key);
    }
    return registry.k[key];
}
/*#__NO_SIDE_EFFECTS__*/
function polyGetKnownSymbol(name) {
    !_wellKnownSymbolCache && (_wellKnownSymbolCache = {});
    var result;
    var knownName = _wellKnownSymbolMap[name];
    if (knownName) {
        result = _wellKnownSymbolCache[knownName] = _wellKnownSymbolCache[knownName] || polyNewSymbol(SYMBOL + "." + knownName);
    }
    return result;
}
/*#__NO_SIDE_EFFECTS__*/
function createCachedValue(value) {
    return objDefineProp({
        toJSON: function () { return value; }
    }, "v", { value: value });
}
var WINDOW = "window";
var _cachedGlobal;
function _getGlobalInstFn(getFn, theArgs) {
    var cachedValue;
    return function () {
        !_globalLazyTestHooks && _initTestHooks();
        if (!cachedValue || _globalLazyTestHooks.lzy) {
            cachedValue = createCachedValue(safe(getFn, theArgs).v);
        }
        return cachedValue.v;
    };
}
function getGlobal(useCached) {
    !_globalLazyTestHooks && _initTestHooks();
    if (!_cachedGlobal || useCached === false || _globalLazyTestHooks.lzy) {
        _cachedGlobal = createCachedValue(safe(_getGlobalValue).v || NULL_VALUE);
    }
    return _cachedGlobal.v;
}
/*#__NO_SIDE_EFFECTS__*/
function getInst(name, useCached) {
    var gbl;
    if (!_cachedGlobal || useCached === false) {
        gbl = getGlobal(useCached);
    }
    else {
        gbl = _cachedGlobal.v;
    }
    if (gbl && gbl[name]) {
        return gbl[name];
    }
    if (name === WINDOW) {
        try {
            return window;
        }
        catch (e) {
        }
    }
    return NULL_VALUE;
}
var getDocument = ( /*#__PURE__*/_getGlobalInstFn(getInst, ["document"]));
/*#__NO_SIDE_EFFECTS__*/
function hasWindow() {
    return !!( /*#__PURE__*/getWindow());
}
var getWindow = ( /*#__PURE__*/_getGlobalInstFn(getInst, [WINDOW]));
/*#__NO_SIDE_EFFECTS__*/
function hasNavigator() {
    return !!( /*#__PURE__*/getNavigator());
}
var getNavigator = ( /*#__PURE__*/_getGlobalInstFn(getInst, ["navigator"]));
var isNode = ( /*#__PURE__*/_getGlobalInstFn(function () {
    return !!( safe(function () { return (process && (process.versions || {}).node); }).v);
}));
var _symbol;
var _symbolFor;
/*#__NO_SIDE_EFFECTS__*/
function _initSymbol() {
    _symbol = ( /*#__PURE__*/createCachedValue(safe((getInst), [SYMBOL]).v));
    return _symbol;
}
function _getSymbolKey(key) {
    var gblSym = ((!_globalLazyTestHooks.lzy ? _symbol : 0) || _initSymbol());
    return (gblSym.v ? gblSym.v[key] : UNDEF_VALUE);
}
/*#__NO_SIDE_EFFECTS__*/
function hasSymbol() {
    return !!( /*#__PURE__*/getSymbol());
}
/*#__NO_SIDE_EFFECTS__*/
function getSymbol() {
    !_globalLazyTestHooks && _initTestHooks();
    return ((!_globalLazyTestHooks.lzy ? _symbol : 0) || _initSymbol()).v;
}
/*#__NO_SIDE_EFFECTS__*/
function getKnownSymbol(name, noPoly) {
    var knownName = _wellKnownSymbolMap[name];
    !_globalLazyTestHooks && _initTestHooks();
    var sym = ((!_globalLazyTestHooks.lzy ? _symbol : 0) || _initSymbol());
    return sym.v ? sym.v[knownName || name] : (!noPoly ? polyGetKnownSymbol(name) : UNDEF_VALUE);
}
/*#__NO_SIDE_EFFECTS__*/
function newSymbol(description, noPoly) {
    !_globalLazyTestHooks && _initTestHooks();
    var sym = ((!_globalLazyTestHooks.lzy ? _symbol : 0) || _initSymbol());
    return sym.v ? sym.v(description) : (!noPoly ? polyNewSymbol(description) : NULL_VALUE);
}
/*#__NO_SIDE_EFFECTS__*/
function symbolFor(key) {
    !_globalLazyTestHooks && _initTestHooks();
    _symbolFor = ((!_globalLazyTestHooks.lzy ? _symbolFor : 0) || ( /*#__PURE__*/createCachedValue(safe((_getSymbolKey), ["for"]).v)));
    return (_symbolFor.v || polySymbolFor)(key);
}
/*#__NO_SIDE_EFFECTS__*/
function isIterator(value) {
    return !!value && isFunction(value.next);
}
/*#__NO_SIDE_EFFECTS__*/
function isIterable(value) {
    return !isStrictNullOrUndefined(value) && isFunction(value[getKnownSymbol(3 )]);
}
var _iterSymbol$1;
function iterForOf(iter, callbackfn, thisArg) {
    if (iter) {
        if (!isIterator(iter)) {
            !_iterSymbol$1 && (_iterSymbol$1 = createCachedValue(getKnownSymbol(3 )));
            iter = iter[_iterSymbol$1.v] ? iter[_iterSymbol$1.v]() : NULL_VALUE;
        }
        if (isIterator(iter)) {
            var err = UNDEF_VALUE;
            var iterResult = UNDEF_VALUE;
            try {
                var count = 0;
                while (!(iterResult = iter.next()).done) {
                    if (callbackfn[CALL](thisArg || iter, iterResult.value, count, iter) === -1) {
                        break;
                    }
                    count++;
                }
            }
            catch (failed) {
                err = { e: failed };
                if (iter.throw) {
                    iterResult = NULL_VALUE;
                    iter.throw(err);
                }
            }
            finally {
                try {
                    if (iterResult && !iterResult.done) {
                        iter.return && iter.return(iterResult);
                    }
                }
                finally {
                    if (err) {
                        throw err.e;
                    }
                }
            }
        }
    }
}
function arrAppend(target, elms) {
    if (!isUndefined(elms) && target) {
        if (isArray(elms)) {
            fnApply(target.push, target, elms);
        }
        else if (isIterator(elms) || isIterable(elms)) {
            iterForOf(elms, function (elm) {
                target.push(elm);
            });
        }
        else {
            target.push(elms);
        }
    }
    return target;
}
var arrIndexOf = ( /*#__PURE__*/_unwrapFunction("indexOf", ArrProto));
var arrMap = ( /*#__PURE__*/_unwrapFunction("map", ArrProto));
function arrSlice(theArray, start, end) {
    return ((theArray ? theArray["slice"] : NULL_VALUE) || ArrSlice).apply(theArray, ArrSlice[CALL](arguments, 1));
}
var _isProtoArray;
var objSetPrototypeOf = ( /*#__PURE__*/_pureAssign(( /*#__PURE__*/_pureRef(ObjClass, "setPrototypeOf")), _polyObjSetPrototypeOf));
function _polyObjSetPrototypeOf(obj, proto) {
    var _a;
    !_isProtoArray && (_isProtoArray = createCachedValue((_a = {}, _a[__PROTO__] = [], _a) instanceof Array));
    _isProtoArray.v ? obj[__PROTO__] = proto : objForEachKey(proto, function (key, value) { return obj[key] = value; });
    return obj;
}
/*#__NO_SIDE_EFFECTS__*/
function _createCustomError(name, d, b) {
    safe(objDefine, [d, NAME, { v: name, c: true, e: false }]);
    d = objSetPrototypeOf(d, b);
    function __() {
        this[CONSTRUCTOR] = d;
        safe(objDefine, [this, NAME, { v: name, c: true, e: false }]);
    }
    d[PROTOTYPE] = b === NULL_VALUE ? objCreate(b) : (__[PROTOTYPE] = b[PROTOTYPE], new __());
    return d;
}
function _setName(baseClass, name) {
    name && (baseClass[NAME] = name);
}
/*#__NO_SIDE_EFFECTS__*/
function createCustomError(name, constructCb, errorBase) {
    var theBaseClass = errorBase || Error;
    var orgName = theBaseClass[PROTOTYPE][NAME];
    var captureFn = Error.captureStackTrace;
    return _createCustomError(name, function () {
        var _this = this;
        var theArgs = arguments;
        try {
            safe(_setName, [theBaseClass, name]);
            var _self = fnApply(theBaseClass, _this, ArrSlice[CALL](theArgs)) || _this;
            if (_self !== _this) {
                var orgProto = objGetPrototypeOf(_this);
                if (orgProto !== objGetPrototypeOf(_self)) {
                    objSetPrototypeOf(_self, orgProto);
                }
            }
            captureFn && captureFn(_self, _this[CONSTRUCTOR]);
            constructCb && constructCb(_self, theArgs);
            return _self;
        }
        finally {
            safe(_setName, [theBaseClass, orgName]);
        }
    }, theBaseClass);
}
/*#__NO_SIDE_EFFECTS__*/
function _createTrimFn(exp) {
    return function _doTrim(value) {
        _throwIfNullOrUndefined(value);
        if (value && value.replace) {
            value = value.replace(exp, EMPTY);
        }
        return value;
    };
}
var polyStrTrim = ( /*#__PURE__*/_createTrimFn(/^\s+|(?=\s)\s+$/g));
var strTrim = ( /*#__PURE__*/_unwrapFunctionWithPoly("trim", StrProto, polyStrTrim));
var mathFloor = ( /*#__PURE__*/_pureRef(MathCls, "floor"));
var _fnToString;
var _objCtrFnString;
var _gblWindow;
/*#__NO_SIDE_EFFECTS__*/
function isPlainObject(value) {
    if (!value || typeof value !== OBJECT) {
        return false;
    }
    if (!_gblWindow) {
        _gblWindow = hasWindow() ? getWindow() : true;
    }
    var result = false;
    if (value !== _gblWindow) {
        if (!_objCtrFnString) {
            _fnToString = Function[PROTOTYPE][TO_STRING];
            _objCtrFnString = _fnToString[CALL](ObjClass);
        }
        try {
            var proto = objGetPrototypeOf(value);
            result = !proto;
            if (!result) {
                if (objHasOwnProperty(proto, CONSTRUCTOR)) {
                    proto = proto[CONSTRUCTOR];
                }
                result = !!(proto && typeof proto === FUNCTION && _fnToString[CALL](proto) === _objCtrFnString);
            }
        }
        catch (ex) {
        }
    }
    return result;
}
var mathRound = ( /*#__PURE__*/_pureRef(MathCls, "round"));
var objGetOwnPropertyDescriptor = ( /*#__PURE__*/_pureAssign(( /*#__PURE__*/_pureRef(ObjClass, GET_OWN_PROPERTY_DESCRIPTOR)), _returnNothing));
var strIndexOf = ( /*#__PURE__*/_unwrapFunction("indexOf", StrProto));
var REF = "ref";
var UNREF = "unref";
var HAS_REF = "hasRef";
var ENABLED = "enabled";
/*#__NO_SIDE_EFFECTS__*/
function _createTimerHandler(startTimer, refreshFn, cancelFn) {
    var ref = true;
    var timerId = startTimer ? refreshFn(NULL_VALUE) : NULL_VALUE;
    var theTimerHandler;
    function _unref() {
        ref = false;
        timerId && timerId[UNREF] && timerId[UNREF]();
        return theTimerHandler;
    }
    function _cancel() {
        timerId && cancelFn(timerId);
        timerId = NULL_VALUE;
    }
    function _refresh() {
        timerId = refreshFn(timerId);
        if (!ref) {
            _unref();
        }
        return theTimerHandler;
    }
    function _setEnabled(value) {
        !value && timerId && _cancel();
        value && !timerId && _refresh();
    }
    theTimerHandler = {
        cancel: _cancel,
        refresh: _refresh
    };
    theTimerHandler[HAS_REF] = function () {
        if (timerId && timerId[HAS_REF]) {
            return timerId[HAS_REF]();
        }
        return ref;
    };
    theTimerHandler[REF] = function () {
        ref = true;
        timerId && timerId[REF] && timerId[REF]();
        return theTimerHandler;
    };
    theTimerHandler[UNREF] = _unref;
    theTimerHandler = objDefineProp(theTimerHandler, ENABLED, {
        get: function () { return !!timerId; },
        set: _setEnabled
    });
    return {
        h: theTimerHandler,
        dn: function () {
            timerId = NULL_VALUE;
        }
    };
}
var _setTimeoutFn;
var _clearTimeoutFn;
function _resolveTimeoutFn(timeoutFn) {
    var result = isFunction(timeoutFn) ? timeoutFn : _setTimeoutFn;
    if (!result) {
        var globalOverrides = _getGlobalConfig().tmOut || [];
        if (isArray(globalOverrides) && globalOverrides.length > 0 && isFunction(globalOverrides[0])) {
            result = globalOverrides[0];
        }
    }
    return result || setTimeout;
}
function _resolveClearTimeoutFn(timeoutFn) {
    var result = isFunction(timeoutFn) ? timeoutFn : _clearTimeoutFn;
    if (!result) {
        var globalOverrides = _getGlobalConfig().tmOut || [];
        if (isArray(globalOverrides) && globalOverrides.length > 1 && isFunction(globalOverrides[1])) {
            result = globalOverrides[1];
        }
    }
    return result || clearTimeout;
}
function _createTimeoutWith(startTimer, overrideFn, theArgs) {
    var isArr = isArray(overrideFn);
    var len = isArr ? overrideFn.length : 0;
    var setFn = _resolveTimeoutFn(len > 0 ? overrideFn[0] : (!isArr ? overrideFn : UNDEF_VALUE));
    var clearFn = _resolveClearTimeoutFn(len > 1 ? overrideFn[1] : UNDEF_VALUE);
    var timerFn = theArgs[0];
    theArgs[0] = function () {
        handler.dn();
        fnApply(timerFn, UNDEF_VALUE, ArrSlice[CALL](arguments));
    };
    var handler = _createTimerHandler(startTimer, function (timerId) {
        if (timerId) {
            if (timerId.refresh) {
                timerId.refresh();
                return timerId;
            }
            fnApply(clearFn, UNDEF_VALUE, [timerId]);
        }
        return fnApply(setFn, UNDEF_VALUE, theArgs);
    }, function (timerId) {
        fnApply(clearFn, UNDEF_VALUE, [timerId]);
    });
    return handler.h;
}
function scheduleTimeout(callback, timeout) {
    return _createTimeoutWith(true, UNDEF_VALUE, ArrSlice[CALL](arguments));
}

(getGlobal() || {})["Symbol"];
(getGlobal() || {})["Reflect"];
var strHasOwnProperty = "hasOwnProperty";
var __objAssignFnImpl = function (t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
        s = arguments[i];
        for (var p in s) {
            if (ObjProto$1[strHasOwnProperty].call(s, p)) {
                t[p] = s[p];
            }
        }
    }
    return t;
};
var __assignFn = objAssign || __objAssignFnImpl;
var extendStaticsFn = function (d, b) {
    extendStaticsFn = ObjClass$1["setPrototypeOf"] ||
        ({ __proto__: [] } instanceof Array && function (d, b) {
            d.__proto__ = b;
        }) ||
        function (d, b) {
            for (var p in b) {
                if (b[strHasOwnProperty](p)) {
                    d[p] = b[p];
                }
            }
        };
    return extendStaticsFn(d, b);
};
function __extendsFn(d, b) {
    if (typeof b !== strShimFunction && b !== null) {
        throwTypeError("Class extends value " + String(b) + " is not a constructor or null");
    }
    extendStaticsFn(d, b);
    function __() {
        this.constructor = d;
    }
    d[strShimPrototype] = b === null ? objCreate(b) : (__[strShimPrototype] = b[strShimPrototype], new __());
}

var _a$3;
var Constructor = 'constructor';
var Prototype = 'prototype';
var strFunction = 'function';
var DynInstFuncTable = '_dynInstFuncs';
var DynProxyTag = '_isDynProxy';
var DynClassName = '_dynClass';
var DynClassNamePrefix = '_dynCls$';
var DynInstChkTag = '_dynInstChk';
var DynAllowInstChkTag = DynInstChkTag;
var DynProtoDefaultOptions = '_dfOpts';
var UnknownValue = '_unknown_';
var str__Proto = "__proto__";
var DynProtoBaseProto = "_dyn" + str__Proto;
var DynProtoGlobalSettings = "__dynProto$Gbl";
var DynProtoCurrent = "_dynInstProto";
var strUseBaseInst = 'useBaseInst';
var strSetInstFuncs = 'setInstFuncs';
var Obj = Object;
var _objGetPrototypeOf = Obj["getPrototypeOf"];
var _objGetOwnProps = Obj["getOwnPropertyNames"];
var _gbl = getGlobal();
var _gblInst = _gbl[DynProtoGlobalSettings] || (_gbl[DynProtoGlobalSettings] = {
    o: (_a$3 = {},
        _a$3[strSetInstFuncs] = true,
        _a$3[strUseBaseInst] = true,
        _a$3),
    n: 1000
});
function _isObjectOrArrayPrototype(target) {
    return target && (target === Obj[Prototype] || target === Array[Prototype]);
}
function _isObjectArrayOrFunctionPrototype(target) {
    return _isObjectOrArrayPrototype(target) || target === Function[Prototype];
}
function _getObjProto(target) {
    var newProto;
    if (target) {
        if (_objGetPrototypeOf) {
            return _objGetPrototypeOf(target);
        }
        var curProto = target[str__Proto] || target[Prototype] || (target[Constructor] ? target[Constructor][Prototype] : null);
        newProto = target[DynProtoBaseProto] || curProto;
        if (!objHasOwnProperty(target, DynProtoBaseProto)) {
            delete target[DynProtoCurrent];
            newProto = target[DynProtoBaseProto] = target[DynProtoCurrent] || target[DynProtoBaseProto];
            target[DynProtoCurrent] = curProto;
        }
    }
    return newProto;
}
function _forEachProp(target, func) {
    var props = [];
    if (_objGetOwnProps) {
        props = _objGetOwnProps(target);
    }
    else {
        for (var name_1 in target) {
            if (typeof name_1 === "string" && objHasOwnProperty(target, name_1)) {
                props.push(name_1);
            }
        }
    }
    if (props && props.length > 0) {
        for (var lp = 0; lp < props.length; lp++) {
            func(props[lp]);
        }
    }
}
function _isDynamicCandidate(target, funcName, skipOwn) {
    return (funcName !== Constructor && typeof target[funcName] === strFunction && (skipOwn || objHasOwnProperty(target, funcName)) && funcName !== str__Proto && funcName !== Prototype);
}
function _throwTypeError(message) {
    throwTypeError("DynamicProto: " + message);
}
function _getInstanceFuncs(thisTarget) {
    var instFuncs = objCreate(null);
    _forEachProp(thisTarget, function (name) {
        if (!instFuncs[name] && _isDynamicCandidate(thisTarget, name, false)) {
            instFuncs[name] = thisTarget[name];
        }
    });
    return instFuncs;
}
function _hasVisited(values, value) {
    for (var lp = values.length - 1; lp >= 0; lp--) {
        if (values[lp] === value) {
            return true;
        }
    }
    return false;
}
function _getBaseFuncs(classProto, thisTarget, instFuncs, useBaseInst) {
    function _instFuncProxy(target, funcHost, funcName) {
        var theFunc = funcHost[funcName];
        if (theFunc[DynProxyTag] && useBaseInst) {
            var instFuncTable = target[DynInstFuncTable] || {};
            if (instFuncTable[DynAllowInstChkTag] !== false) {
                theFunc = (instFuncTable[funcHost[DynClassName]] || {})[funcName] || theFunc;
            }
        }
        return function () {
            return theFunc.apply(target, arguments);
        };
    }
    var baseFuncs = objCreate(null);
    _forEachProp(instFuncs, function (name) {
        baseFuncs[name] = _instFuncProxy(thisTarget, instFuncs, name);
    });
    var baseProto = _getObjProto(classProto);
    var visited = [];
    while (baseProto && !_isObjectArrayOrFunctionPrototype(baseProto) && !_hasVisited(visited, baseProto)) {
        _forEachProp(baseProto, function (name) {
            if (!baseFuncs[name] && _isDynamicCandidate(baseProto, name, !_objGetPrototypeOf)) {
                baseFuncs[name] = _instFuncProxy(thisTarget, baseProto, name);
            }
        });
        visited.push(baseProto);
        baseProto = _getObjProto(baseProto);
    }
    return baseFuncs;
}
function _getInstFunc(target, funcName, proto, currentDynProtoProxy) {
    var instFunc = null;
    if (target && objHasOwnProperty(proto, DynClassName)) {
        var instFuncTable = target[DynInstFuncTable] || objCreate(null);
        instFunc = (instFuncTable[proto[DynClassName]] || objCreate(null))[funcName];
        if (!instFunc) {
            _throwTypeError("Missing [" + funcName + "] " + strFunction);
        }
        if (!instFunc[DynInstChkTag] && instFuncTable[DynAllowInstChkTag] !== false) {
            var canAddInst = !objHasOwnProperty(target, funcName);
            var objProto = _getObjProto(target);
            var visited = [];
            while (canAddInst && objProto && !_isObjectArrayOrFunctionPrototype(objProto) && !_hasVisited(visited, objProto)) {
                var protoFunc = objProto[funcName];
                if (protoFunc) {
                    canAddInst = (protoFunc === currentDynProtoProxy);
                    break;
                }
                visited.push(objProto);
                objProto = _getObjProto(objProto);
            }
            try {
                if (canAddInst) {
                    target[funcName] = instFunc;
                }
                instFunc[DynInstChkTag] = 1;
            }
            catch (e) {
                instFuncTable[DynAllowInstChkTag] = false;
            }
        }
    }
    return instFunc;
}
function _getProtoFunc(funcName, proto, currentDynProtoProxy) {
    var protoFunc = proto[funcName];
    if (protoFunc === currentDynProtoProxy) {
        protoFunc = _getObjProto(proto)[funcName];
    }
    if (typeof protoFunc !== strFunction) {
        _throwTypeError("[" + funcName + "] is not a " + strFunction);
    }
    return protoFunc;
}
function _populatePrototype(proto, className, target, baseInstFuncs, setInstanceFunc) {
    function _createDynamicPrototype(proto, funcName) {
        var dynProtoProxy = function () {
            var instFunc = _getInstFunc(this, funcName, proto, dynProtoProxy) || _getProtoFunc(funcName, proto, dynProtoProxy);
            return instFunc.apply(this, arguments);
        };
        dynProtoProxy[DynProxyTag] = 1;
        return dynProtoProxy;
    }
    if (!_isObjectOrArrayPrototype(proto)) {
        var instFuncTable = target[DynInstFuncTable] = target[DynInstFuncTable] || objCreate(null);
        if (!_isObjectOrArrayPrototype(instFuncTable)) {
            var instFuncs_1 = instFuncTable[className] = (instFuncTable[className] || objCreate(null));
            if (instFuncTable[DynAllowInstChkTag] !== false) {
                instFuncTable[DynAllowInstChkTag] = !!setInstanceFunc;
            }
            if (!_isObjectOrArrayPrototype(instFuncs_1)) {
                _forEachProp(target, function (name) {
                    if (_isDynamicCandidate(target, name, false) && target[name] !== baseInstFuncs[name]) {
                        instFuncs_1[name] = target[name];
                        delete target[name];
                        if (!objHasOwnProperty(proto, name) || (proto[name] && !proto[name][DynProxyTag])) {
                            proto[name] = _createDynamicPrototype(proto, name);
                        }
                    }
                });
            }
        }
    }
}
function _checkPrototype(classProto, thisTarget) {
    if (_objGetPrototypeOf) {
        var visited = [];
        var thisProto = _getObjProto(thisTarget);
        while (thisProto && !_isObjectArrayOrFunctionPrototype(thisProto) && !_hasVisited(visited, thisProto)) {
            if (thisProto === classProto) {
                return true;
            }
            visited.push(thisProto);
            thisProto = _getObjProto(thisProto);
        }
        return false;
    }
    return true;
}
function _getObjName(target, unknownValue) {
    if (objHasOwnProperty(target, Prototype)) {
        return target.name || unknownValue || UnknownValue;
    }
    return (((target || {})[Constructor]) || {}).name || unknownValue || UnknownValue;
}
function dynamicProto(theClass, target, delegateFunc, options) {
    if (!objHasOwnProperty(theClass, Prototype)) {
        _throwTypeError("theClass is an invalid class definition.");
    }
    var classProto = theClass[Prototype];
    if (!_checkPrototype(classProto, target)) {
        _throwTypeError("[" + _getObjName(theClass) + "] not in hierarchy of [" + _getObjName(target) + "]");
    }
    var className = null;
    if (objHasOwnProperty(classProto, DynClassName)) {
        className = classProto[DynClassName];
    }
    else {
        className = DynClassNamePrefix + _getObjName(theClass, "_") + "$" + _gblInst.n;
        _gblInst.n++;
        classProto[DynClassName] = className;
    }
    var perfOptions = dynamicProto[DynProtoDefaultOptions];
    var useBaseInst = !!perfOptions[strUseBaseInst];
    if (useBaseInst && options && options[strUseBaseInst] !== undefined) {
        useBaseInst = !!options[strUseBaseInst];
    }
    var instFuncs = _getInstanceFuncs(target);
    var baseFuncs = _getBaseFuncs(classProto, target, instFuncs, useBaseInst);
    delegateFunc(target, baseFuncs);
    var setInstanceFunc = !!_objGetPrototypeOf && !!perfOptions[strSetInstFuncs];
    if (setInstanceFunc && options) {
        setInstanceFunc = !!options[strSetInstFuncs];
    }
    _populatePrototype(classProto, className, target, instFuncs, setInstanceFunc !== false);
}
dynamicProto[DynProtoDefaultOptions] = _gblInst.o;

var createEnumStyle = createEnum;
var createValueMap = createTypeMap;

var ActiveStatus = ( /* @__PURE__ */createEnumStyle({
    NONE: 0 ,
    PENDING: 3 ,
    INACTIVE: 1 ,
    ACTIVE: 2
}));

var _DYN_TO_LOWER_CASE$1 = "toLowerCase";
var _DYN_LENGTH$2 = "length";
var _DYN_WARN_TO_CONSOLE = "warnToConsole";
var _DYN_THROW_INTERNAL = "throwInternal";
var _DYN_WATCH = "watch";
var _DYN_APPLY = "apply";
var _DYN_PUSH$1 = "push";
var _DYN_SPLICE = "splice";
var _DYN_LOGGER = "logger";
var _DYN_CANCEL = "cancel";
var _DYN_INITIALIZE$1 = "initialize";
var _DYN_IDENTIFIER = "identifier";
var _DYN_IS_INITIALIZED = "isInitialized";
var _DYN_GET_PLUGIN = "getPlugin";
var _DYN_NAME$2 = "name";
var _DYN_PROCESS_NEXT = "processNext";
var _DYN_GET_PROCESS_TEL_CONT2 = "getProcessTelContext";
var _DYN_VALUE = "value";
var _DYN_UNLOAD = "unload";
var _DYN_LOGGING_LEVEL_CONSOL4 = "loggingLevelConsole";
var _DYN_CREATE_NEW = "createNew";
var _DYN_TEARDOWN = "teardown";
var _DYN_MESSAGE_ID = "messageId";
var _DYN_MESSAGE$1 = "message";
var _DYN_DIAG_LOG$1 = "diagLog";
var _DYN__DO_TEARDOWN = "_doTeardown";
var _DYN_UPDATE = "update";
var _DYN_GET_NEXT = "getNext";
var _DYN_SET_NEXT_PLUGIN = "setNextPlugin";
var _DYN_USER_AGENT = "userAgent";
var _DYN_SPLIT$1 = "split";
var _DYN_REPLACE = "replace";
var _DYN_SUBSTRING = "substring";
var _DYN_INDEX_OF = "indexOf";
var _DYN_TYPE = "type";
var _DYN_EVT_NAME = "evtName";
var _DYN_STATUS = "status";
var _DYN_GET_ALL_RESPONSE_HEA5 = "getAllResponseHeaders";
var _DYN_IS_CHILD_EVT = "isChildEvt";
var _DYN_DATA$1 = "data";
var _DYN_GET_CTX = "getCtx";
var _DYN_SET_CTX = "setCtx";
var _DYN_ITEMS_RECEIVED$1 = "itemsReceived";
var _DYN_HEADERS = "headers";
var _DYN_URL_STRING = "urlString";
var _DYN_TIMEOUT = "timeout";

var aggregationErrorType;
function throwAggregationError(message, sourceErrors) {
    if (!aggregationErrorType) {
        aggregationErrorType = createCustomError("AggregationError", function (self, args) {
            if (args[_DYN_LENGTH$2 ] > 1) {
                self.errors = args[1];
            }
        });
    }
    var theMessage = message || "One or more errors occurred.";
    arrForEach(sourceErrors, function (srcError, idx) {
        theMessage += "\n".concat(idx, " > ").concat(dumpObj(srcError));
    });
    throw new aggregationErrorType(theMessage, sourceErrors || []);
}

/*!
 * NevWare21 Solutions LLC - ts-async, 0.5.4
 * https://github.com/nevware21/ts-async
 * Copyright (c) NevWare21 Solutions LLC and contributors. All rights reserved.
 * Licensed under the MIT license.
 */
var STR_PROMISE = "Promise";
var REJECTED = "rejected";
function doAwaitResponse(value, cb) {
    return doAwait(value, function (value) {
        return cb ? cb({
            status: "fulfilled",
            rejected: false,
            value: value
        }) : value;
    }, function (reason) {
        return cb ? cb({
            status: REJECTED,
            rejected: true,
            reason: reason
        }) : reason;
    });
}
function doAwait(value, resolveFn, rejectFn, finallyFn) {
    var result = value;
    try {
        if (isPromiseLike(value)) {
            if (resolveFn || rejectFn) {
                result = value.then(resolveFn, rejectFn);
            }
        }
        else {
            try {
                if (resolveFn) {
                    result = resolveFn(value);
                }
            }
            catch (err) {
                if (rejectFn) {
                    result = rejectFn(err);
                }
                else {
                    throw err;
                }
            }
        }
    }
    finally {
        if (finallyFn) {
            doFinally(result, finallyFn);
        }
    }
    return result;
}
function doFinally(value, finallyFn) {
    var result = value;
    if (finallyFn) {
        if (isPromiseLike(value)) {
            if (value.finally) {
                result = value.finally(finallyFn);
            }
            else {
                result = value.then(function (value) {
                    finallyFn();
                    return value;
                }, function (reason) {
                    finallyFn();
                    throw reason;
                });
            }
        }
        else {
            finallyFn();
        }
    }
    return result;
}
var STRING_STATES =  [
    "pending", "resolving", "resolved", REJECTED
];
var DISPATCH_EVENT = "dispatchEvent";
var _hasInitEvent;
function _hasInitEventFn(doc) {
    var evt;
    if (doc && doc.createEvent) {
        evt = doc.createEvent("Event");
    }
    return (!!evt && evt.initEvent);
}
function emitEvent(target, evtName, populateEvent, useNewEvent) {
    var doc = getDocument();
    !_hasInitEvent && (_hasInitEvent = createCachedValue(!!safe(_hasInitEventFn, [doc]).v));
    var theEvt = _hasInitEvent.v ? doc.createEvent("Event") : (useNewEvent ? new Event(evtName) : {});
    populateEvent && populateEvent(theEvt);
    if (_hasInitEvent.v) {
        theEvt.initEvent(evtName, false, true);
    }
    if (theEvt && target[DISPATCH_EVENT]) {
        target[DISPATCH_EVENT](theEvt);
    }
    else {
        var handler = target["on" + evtName];
        if (handler) {
            handler(theEvt);
        }
        else {
            var theConsole = getInst("console");
            theConsole && (theConsole["error"] || theConsole["log"])(evtName, dumpObj(theEvt));
        }
    }
}
var NODE_UNHANDLED_REJECTION = "unhandledRejection";
var UNHANDLED_REJECTION = NODE_UNHANDLED_REJECTION.toLowerCase();
var _unhandledRejectionTimeout = 10;
var _hasPromiseRejectionEvent;
function dumpFnObj(value) {
    if (isFunction(value)) {
        return value.toString();
    }
    return dumpObj(value);
}
function _createPromise(newPromise, processor, executor) {
    var additionalArgs = arrSlice(arguments, 3);
    var _state = 0 ;
    var _hasResolved = false;
    var _settledValue;
    var _queue = [];
    var _handled = false;
    var _unHandledRejectionHandler = null;
    var _thePromise;
    function _then(onResolved, onRejected) {
        try {
            _handled = true;
            _unHandledRejectionHandler && _unHandledRejectionHandler.cancel();
            _unHandledRejectionHandler = null;
            var thenPromise = newPromise(function (resolve, reject) {
                _queue.push(function () {
                    try {
                        var handler = _state === 2  ? onResolved : onRejected;
                        var value = isUndefined(handler) ? _settledValue : (isFunction(handler) ? handler(_settledValue) : handler);
                        if (isPromiseLike(value)) {
                            value.then(resolve, reject);
                        }
                        else if (handler) {
                            resolve(value);
                        }
                        else if (_state === 3 ) {
                            reject(value);
                        }
                        else {
                            resolve(value);
                        }
                    }
                    catch (e) {
                        reject(e);
                    }
                });
                if (_hasResolved) {
                    _processQueue();
                }
            }, additionalArgs);
            return thenPromise;
        }
        finally {
        }
    }
    function _catch(onRejected) {
        return _then(undefined, onRejected);
    }
    function _finally(onFinally) {
        var thenFinally = onFinally;
        var catchFinally = onFinally;
        if (isFunction(onFinally)) {
            thenFinally = function (value) {
                onFinally && onFinally();
                return value;
            };
            catchFinally = function (reason) {
                onFinally && onFinally();
                throw reason;
            };
        }
        return _then(thenFinally, catchFinally);
    }
    function _strState() {
        return STRING_STATES[_state];
    }
    function _processQueue() {
        if (_queue.length > 0) {
            var pending = _queue.slice();
            _queue = [];
            _handled = true;
            _unHandledRejectionHandler && _unHandledRejectionHandler.cancel();
            _unHandledRejectionHandler = null;
            processor(pending);
        }
    }
    function _createSettleIfFn(newState, allowState) {
        return function (theValue) {
            if (_state === allowState) {
                if (newState === 2  && isPromiseLike(theValue)) {
                    _state = 1 ;
                    theValue.then(_createSettleIfFn(2 , 1 ), _createSettleIfFn(3 , 1 ));
                    return;
                }
                _state = newState;
                _hasResolved = true;
                _settledValue = theValue;
                _processQueue();
                if (!_handled && newState === 3  && !_unHandledRejectionHandler) {
                    _unHandledRejectionHandler = scheduleTimeout(_notifyUnhandledRejection, _unhandledRejectionTimeout);
                }
            }
        };
    }
    function _notifyUnhandledRejection() {
        if (!_handled) {
            _handled = true;
            if (isNode()) {
                process.emit(NODE_UNHANDLED_REJECTION, _settledValue, _thePromise);
            }
            else {
                var gbl = getWindow() || getGlobal();
                !_hasPromiseRejectionEvent && (_hasPromiseRejectionEvent = createCachedValue(safe((getInst), [STR_PROMISE + "RejectionEvent"]).v));
                emitEvent(gbl, UNHANDLED_REJECTION, function (theEvt) {
                    objDefine(theEvt, "promise", { g: function () { return _thePromise; } });
                    theEvt.reason = _settledValue;
                    return theEvt;
                }, !!_hasPromiseRejectionEvent.v);
            }
        }
    }
    _thePromise = {
        then: _then,
        "catch": _catch,
        finally: _finally
    };
    objDefineProp(_thePromise, "state", {
        get: _strState
    });
    if (hasSymbol()) {
        _thePromise[getKnownSymbol(11 )] = "IPromise";
    }
    function _toString() {
        return "IPromise" + ("") + " " + _strState() + (_hasResolved ? (" - " + dumpFnObj(_settledValue)) : "") + ("");
    }
    _thePromise.toString = _toString;
    (function _initialize() {
        if (!isFunction(executor)) {
            throwTypeError(STR_PROMISE + ": executor is not a function - " + dumpFnObj(executor));
        }
        var _rejectFn = _createSettleIfFn(3 , 0 );
        try {
            executor.call(_thePromise, _createSettleIfFn(2 , 0 ), _rejectFn);
        }
        catch (e) {
            _rejectFn(e);
        }
    })();
    return _thePromise;
}
function syncItemProcessor(pending) {
    arrForEach(pending, function (fn) {
        try {
            fn();
        }
        catch (e) {
        }
    });
}
function timeoutItemProcessor(timeout) {
    var callbackTimeout = isNumber(timeout) ? timeout : 0;
    return function (pending) {
        scheduleTimeout(function () {
            syncItemProcessor(pending);
        }, callbackTimeout);
    };
}
function createAsyncPromise(executor, timeout) {
    return _createPromise(createAsyncPromise, timeoutItemProcessor(timeout), executor, timeout);
}
var _promiseCls;
function createNativePromise(executor, timeout) {
    !_promiseCls && (_promiseCls = createCachedValue((safe(getInst, [STR_PROMISE]).v) || null));
    var PrmCls = _promiseCls.v;
    if (!PrmCls) {
        return createAsyncPromise(executor);
    }
    if (!isFunction(executor)) {
        throwTypeError(STR_PROMISE + ": executor is not a function - " + dumpObj(executor));
    }
    var _state = 0 ;
    function _strState() {
        return STRING_STATES[_state];
    }
    var thePromise = new PrmCls(function (resolve, reject) {
        function _resolve(value) {
            _state = 2 ;
            resolve(value);
        }
        function _reject(reason) {
            _state = 3 ;
            reject(reason);
        }
        executor(_resolve, _reject);
    });
    objDefineProp(thePromise, "state", {
        get: _strState
    });
    return thePromise;
}
var _promiseCreator;
function createPromise(executor, timeout) {
    !_promiseCreator && (_promiseCreator = createCachedValue(createNativePromise));
    return _promiseCreator.v.call(this, executor, timeout);
}

var UNDEFINED_VALUE$1 = undefined;
var STR_EMPTY$1 = "";
var STR_CORE = "core";
var STR_DISABLED = "disabled";
var STR_EXTENSION_CONFIG = "extensionConfig";
var STR_PROCESS_TELEMETRY = "processTelemetry";
var STR_PRIORITY = "priority";
var STR_GET_PERF_MGR = "getPerfMgr";
var STR_NOT_DYNAMIC_ERROR = "Not dynamic - ";
var STR_REDACTED = "REDACTED";
var DEFAULT_SENSITIVE_PARAMS = ["sig", "Signature", "AWSAccessKeyId", "X-Goog-Signature"];

var rCamelCase = /-([a-z])/g;
var rNormalizeInvalid = /([^\w\d_$])/g;
var rLeadingNumeric = /^(\d+[\w\d_$])/;
function isNotNullOrUndefined(value) {
    return !isNullOrUndefined(value);
}
function normalizeJsName(name) {
    var value = name;
    if (value && isString(value)) {
        value = value[_DYN_REPLACE ](rCamelCase, function (_all, letter) {
            return letter.toUpperCase();
        });
        value = value[_DYN_REPLACE ](rNormalizeInvalid, "_");
        value = value[_DYN_REPLACE ](rLeadingNumeric, function (_all, match) {
            return "_" + match;
        });
    }
    return value;
}
function strContains(value, search) {
    if (value && search) {
        return strIndexOf(value, search) !== -1;
    }
    return false;
}
function toISOString(date) {
    return date && date.toISOString() || "";
}
function getExceptionName(object) {
    if (isError(object)) {
        return object[_DYN_NAME$2 ];
    }
    return STR_EMPTY$1;
}
function setValue(target, field, value, valChk, srcChk) {
    var theValue = value;
    if (target) {
        theValue = target[field];
        if (theValue !== value && (!srcChk || srcChk(theValue)) && (!valChk || valChk(value))) {
            theValue = value;
            target[field] = theValue;
        }
    }
    return theValue;
}
function _createProxyFunction(source, funcName) {
    var srcFunc = null;
    var src = null;
    if (isFunction(source)) {
        srcFunc = source;
    }
    else {
        src = source;
    }
    return function () {
        var originalArguments = arguments;
        if (srcFunc) {
            src = srcFunc();
        }
        if (src) {
            return src[funcName][_DYN_APPLY ](src, originalArguments);
        }
    };
}
function proxyFunctionAs(target, name, source, theFunc, overwriteTarget) {
    if (target && name && source) {
        if (overwriteTarget !== false || isUndefined(target[name])) {
            target[name] = _createProxyFunction(source, theFunc);
        }
    }
}
function createClassFromInterface(defaults) {
    return /** @class */ (function () {
        function class_1() {
            var _this = this;
            if (defaults) {
                objForEachKey(defaults, function (field, value) {
                    _this[field] = value;
                });
            }
        }
        return class_1;
    }());
}
function optimizeObject(theObject) {
    if (theObject && objAssign) {
        theObject = ObjClass$1(objAssign({}, theObject));
    }
    return theObject;
}
function objExtend(obj1, obj2, obj3, obj4, obj5, obj6) {
    var theArgs = arguments;
    var extended = theArgs[0] || {};
    var argLen = theArgs[_DYN_LENGTH$2 ];
    var deep = false;
    var idx = 1;
    if (argLen > 0 && isBoolean(extended)) {
        deep = extended;
        extended = theArgs[idx] || {};
        idx++;
    }
    if (!isObject(extended)) {
        extended = {};
    }
    for (; idx < argLen; idx++) {
        var arg = theArgs[idx];
        var isArgArray = isArray(arg);
        var isArgObj = isObject(arg);
        for (var prop in arg) {
            var propOk = (isArgArray && (prop in arg)) || (isArgObj && objHasOwn(arg, prop));
            if (!propOk) {
                continue;
            }
            var newValue = arg[prop];
            var isNewArray = void 0;
            if (deep && newValue && ((isNewArray = isArray(newValue)) || isPlainObject(newValue))) {
                var clone = extended[prop];
                if (isNewArray) {
                    if (!isArray(clone)) {
                        clone = [];
                    }
                }
                else if (!isPlainObject(clone)) {
                    clone = {};
                }
                newValue = objExtend(deep, clone, newValue);
            }
            if (newValue !== undefined) {
                extended[prop] = newValue;
            }
        }
    }
    return extended;
}
function isFeatureEnabled(feature, cfg, sdkDefaultState) {
    var ft = cfg && cfg.featureOptIn && cfg.featureOptIn[feature];
    if (feature && ft) {
        var mode = ft.mode;
        if (mode === 3 ) {
            return true;
        }
        else if (mode === 2 ) {
            return false;
        }
    }
    return sdkDefaultState;
}
function getResponseText(xhr) {
    try {
        return xhr.responseText;
    }
    catch (e) {
    }
    return null;
}
function formatErrorMessageXdr(xdr, message) {
    if (xdr) {
        return "XDomainRequest,Response:" + getResponseText(xdr) || "";
    }
    return message;
}
function formatErrorMessageXhr(xhr, message) {
    if (xhr) {
        return "XMLHttpRequest,Status:" + xhr[_DYN_STATUS ] + ",Response:" + getResponseText(xhr) || xhr.response || "";
    }
    return message;
}
function prependTransports(theTransports, newTransports) {
    if (newTransports) {
        if (isNumber(newTransports)) {
            theTransports = [newTransports].concat(theTransports);
        }
        else if (isArray(newTransports)) {
            theTransports = newTransports.concat(theTransports);
        }
    }
    return theTransports;
}
var strDisabledPropertyName = "Microsoft_ApplicationInsights_BypassAjaxInstrumentation";
var strWithCredentials = "withCredentials";
var strTimeout = "timeout";
function openXhr(method, urlString, withCredentials, disabled, isSync, timeout) {
    if (disabled === void 0) { disabled = false; }
    if (isSync === void 0) { isSync = false; }
    function _wrapSetXhrProp(xhr, prop, value) {
        try {
            xhr[prop] = value;
        }
        catch (e) {
        }
    }
    var xhr = new XMLHttpRequest();
    if (disabled) {
        _wrapSetXhrProp(xhr, strDisabledPropertyName, disabled);
    }
    if (withCredentials) {
        _wrapSetXhrProp(xhr, strWithCredentials, withCredentials);
    }
    xhr.open(method, urlString, !isSync);
    if (withCredentials) {
        _wrapSetXhrProp(xhr, strWithCredentials, withCredentials);
    }
    if (!isSync && timeout) {
        _wrapSetXhrProp(xhr, strTimeout, timeout);
    }
    return xhr;
}
function convertAllHeadersToMap(headersString) {
    var headers = {};
    if (isString(headersString)) {
        var headersArray = strTrim(headersString)[_DYN_SPLIT$1 ](/[\r\n]+/);
        arrForEach(headersArray, function (headerEntry) {
            if (headerEntry) {
                var idx = headerEntry[_DYN_INDEX_OF ](": ");
                if (idx !== -1) {
                    var header = strTrim(headerEntry.substring(0, idx))[_DYN_TO_LOWER_CASE$1 ]();
                    var value = strTrim(headerEntry[_DYN_SUBSTRING ](idx + 1));
                    headers[header] = value;
                }
                else {
                    headers[strTrim(headerEntry)] = 1;
                }
            }
        });
    }
    return headers;
}
function _appendHeader(theHeaders, xhr, name) {
    if (!theHeaders[name] && xhr && xhr.getResponseHeader) {
        var value = xhr.getResponseHeader(name);
        if (value) {
            theHeaders[name] = strTrim(value);
        }
    }
    return theHeaders;
}
var STR_KILL_DURATION_HEADER = "kill-duration";
var STR_KILL_DURATION_SECONDS_HEADER = "kill-duration-seconds";
var STR_TIME_DELTA_HEADER = "time-delta-millis";
function _getAllResponseHeaders(xhr, isOneDs) {
    var theHeaders = {};
    if (!xhr[_DYN_GET_ALL_RESPONSE_HEA5 ]) {
        if (!!isOneDs) {
            theHeaders = _appendHeader(theHeaders, xhr, STR_TIME_DELTA_HEADER);
            theHeaders = _appendHeader(theHeaders, xhr, STR_KILL_DURATION_HEADER);
            theHeaders = _appendHeader(theHeaders, xhr, STR_KILL_DURATION_SECONDS_HEADER);
        }
    }
    else {
        theHeaders = convertAllHeadersToMap(xhr[_DYN_GET_ALL_RESPONSE_HEA5 ]());
    }
    return theHeaders;
}

var strDocumentMode = "documentMode";
var strLocation = "location";
var strConsole = "console";
var strJSON = "JSON";
var strCrypto = "crypto";
var strMsCrypto = "msCrypto";
var strMsie = "msie";
var strTrident = "trident/";
var strXMLHttpRequest = "XMLHttpRequest";
var _isTrident = null;
var _navUserAgentCheck = null;
var _enableMocks = false;
var _useXDomainRequest = null;
var _beaconsSupported = null;
function _hasProperty(theClass, property) {
    var supported = false;
    if (theClass) {
        try {
            supported = property in theClass;
            if (!supported) {
                var proto = theClass[strShimPrototype];
                if (proto) {
                    supported = property in proto;
                }
            }
        }
        catch (e) {
        }
        if (!supported) {
            try {
                var tmp = new theClass();
                supported = !isUndefined(tmp[property]);
            }
            catch (e) {
            }
        }
    }
    return supported;
}
function getLocation(checkForMock) {
    if (checkForMock && _enableMocks) {
        var mockLocation = getInst("__mockLocation");
        if (mockLocation) {
            return mockLocation;
        }
    }
    if (typeof location === strShimObject && location) {
        return location;
    }
    return getInst(strLocation);
}
function getConsole() {
    if (typeof console !== strShimUndefined) {
        return console;
    }
    return getInst(strConsole);
}
function hasJSON() {
    return Boolean((typeof JSON === strShimObject && JSON) || getInst(strJSON) !== null);
}
function getJSON() {
    if (hasJSON()) {
        return JSON || getInst(strJSON);
    }
    return null;
}
function getCrypto() {
    return getInst(strCrypto);
}
function getMsCrypto() {
    return getInst(strMsCrypto);
}
function isIE() {
    var nav = getNavigator();
    if (nav && (nav[_DYN_USER_AGENT ] !== _navUserAgentCheck || _isTrident === null)) {
        _navUserAgentCheck = nav[_DYN_USER_AGENT ];
        var userAgent = (_navUserAgentCheck || STR_EMPTY$1)[_DYN_TO_LOWER_CASE$1 ]();
        _isTrident = (strContains(userAgent, strMsie) || strContains(userAgent, strTrident));
    }
    return _isTrident;
}
function getIEVersion(userAgentStr) {
    if (userAgentStr === void 0) { userAgentStr = null; }
    if (!userAgentStr) {
        var navigator_1 = getNavigator() || {};
        userAgentStr = navigator_1 ? (navigator_1.userAgent || STR_EMPTY$1)[_DYN_TO_LOWER_CASE$1 ]() : STR_EMPTY$1;
    }
    var ua = (userAgentStr || STR_EMPTY$1)[_DYN_TO_LOWER_CASE$1 ]();
    if (strContains(ua, strMsie)) {
        var doc = getDocument() || {};
        return mathMax(parseInt(ua[_DYN_SPLIT$1 ](strMsie)[1]), (doc[strDocumentMode] || 0));
    }
    else if (strContains(ua, strTrident)) {
        var tridentVer = parseInt(ua[_DYN_SPLIT$1 ](strTrident)[1]);
        if (tridentVer) {
            return tridentVer + 4;
        }
    }
    return null;
}
function isBeaconsSupported(useCached) {
    if (_beaconsSupported === null || useCached === false) {
        _beaconsSupported = hasNavigator() && Boolean(getNavigator().sendBeacon);
    }
    return _beaconsSupported;
}
function isFetchSupported(withKeepAlive) {
    var isSupported = false;
    try {
        isSupported = !!getInst("fetch");
        var request = getInst("Request");
        if (isSupported && withKeepAlive && request) {
            isSupported = _hasProperty(request, "keepalive");
        }
    }
    catch (e) {
    }
    return isSupported;
}
function useXDomainRequest() {
    if (_useXDomainRequest === null) {
        _useXDomainRequest = (typeof XDomainRequest !== strShimUndefined);
        if (_useXDomainRequest && isXhrSupported()) {
            _useXDomainRequest = _useXDomainRequest && !_hasProperty(getInst(strXMLHttpRequest), "withCredentials");
        }
    }
    return _useXDomainRequest;
}
function isXhrSupported() {
    var isSupported = false;
    try {
        var xmlHttpRequest = getInst(strXMLHttpRequest);
        isSupported = !!xmlHttpRequest;
    }
    catch (e) {
    }
    return isSupported;
}
function redactUserInfo(url) {
    return url.replace(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^:@]{1,200}):([^@]{1,200})@(.*)$/, "$1REDACTED:REDACTED@$4");
}
function redactQueryParameters(url, config) {
    var sensitiveParams;
    var questionMarkIndex = strIndexOf(url, "?");
    if (questionMarkIndex === -1) {
        return url;
    }
    if (config && config.redactQueryParams) {
        sensitiveParams = DEFAULT_SENSITIVE_PARAMS.concat(config.redactQueryParams);
    }
    else {
        sensitiveParams = DEFAULT_SENSITIVE_PARAMS;
    }
    var baseUrl = strSubstring(url, 0, questionMarkIndex + 1);
    var queryString = strSubstring(url, questionMarkIndex + 1);
    var fragment = STR_EMPTY$1;
    var hashIndex = strIndexOf(queryString, "#");
    if (hashIndex !== -1) {
        fragment = strSubstring(queryString, hashIndex);
        queryString = strSubstring(queryString, 0, hashIndex);
    }
    var hasPotentialSensitiveParam = false;
    for (var i = 0; i < sensitiveParams[_DYN_LENGTH$2 ]; i++) {
        var paramCheck = sensitiveParams[i] + "=";
        if (strIndexOf(queryString, paramCheck) !== -1) {
            hasPotentialSensitiveParam = true;
            break;
        }
    }
    if (!hasPotentialSensitiveParam) {
        return url;
    }
    var resultParts = [];
    var anyParamRedacted = false;
    if (queryString && queryString[_DYN_LENGTH$2 ]) {
        var pairs = queryString[_DYN_SPLIT$1 ]("&");
        for (var i = 0; i < pairs[_DYN_LENGTH$2 ]; i++) {
            var pair = pairs[i];
            if (!pair) {
                continue;
            }
            var equalsIndex = strIndexOf(pair, "=");
            if (equalsIndex === -1) {
                resultParts[_DYN_PUSH$1 ](pair);
            }
            else {
                var paramName = pair[_DYN_SUBSTRING ](0, equalsIndex);
                var paramValue = pair[_DYN_SUBSTRING ](equalsIndex + 1);
                if (paramValue === STR_EMPTY$1) {
                    resultParts[_DYN_PUSH$1 ](pair);
                }
                else {
                    var shouldRedact = false;
                    for (var j = 0; j < sensitiveParams[_DYN_LENGTH$2 ]; j++) {
                        if (paramName === sensitiveParams[j]) {
                            shouldRedact = true;
                            anyParamRedacted = true;
                            break;
                        }
                    }
                    if (shouldRedact) {
                        resultParts[_DYN_PUSH$1 ](paramName + "=" + STR_REDACTED);
                    }
                    else {
                        resultParts[_DYN_PUSH$1 ](pair);
                    }
                }
            }
        }
    }
    if (!anyParamRedacted) {
        return url;
    }
    return baseUrl + resultParts.join("&") + fragment;
}
function fieldRedaction(input, config) {
    if (!input || input[_DYN_INDEX_OF ](" ") !== -1) {
        return input;
    }
    var isRedactionDisabled = config && config.redactUrls === false;
    if (isRedactionDisabled) {
        return input;
    }
    var hasCredentials = strIndexOf(input, "@") !== -1;
    var hasQueryParams = strIndexOf(input, "?") !== -1;
    if (!hasCredentials && !hasQueryParams) {
        return input;
    }
    try {
        var result = input;
        if (hasCredentials) {
            result = redactUserInfo(input);
        }
        if (hasQueryParams) {
            result = redactQueryParameters(result, config);
        }
        return result;
    }
    catch (e) {
        return input;
    }
}

var UInt32Mask = 0x100000000;
var MaxUInt32 = 0xffffffff;
var SEED1 = 123456789;
var SEED2 = 987654321;
var _mwcSeeded = false;
var _mwcW = SEED1;
var _mwcZ = SEED2;
function _mwcSeed(seedValue) {
    if (seedValue < 0) {
        seedValue >>>= 0;
    }
    _mwcW = (SEED1 + seedValue) & MaxUInt32;
    _mwcZ = (SEED2 - seedValue) & MaxUInt32;
    _mwcSeeded = true;
}
function _autoSeedMwc() {
    try {
        var now = utcNow() & 0x7fffffff;
        _mwcSeed(((Math.random() * UInt32Mask) ^ now) + now);
    }
    catch (e) {
    }
}
function random32(signed) {
    var value = 0;
    var c = getCrypto() || getMsCrypto();
    if (c && c.getRandomValues) {
        value = c.getRandomValues(new Uint32Array(1))[0] & MaxUInt32;
    }
    if (value === 0 && isIE()) {
        if (!_mwcSeeded) {
            _autoSeedMwc();
        }
        value = mwcRandom32() & MaxUInt32;
    }
    if (value === 0) {
        value = mathFloor((UInt32Mask * Math.random()) | 0);
    }
    if (!signed) {
        value >>>= 0;
    }
    return value;
}
function mwcRandom32(signed) {
    _mwcZ = (36969 * (_mwcZ & 0xFFFF) + (_mwcZ >> 16)) & MaxUInt32;
    _mwcW = (18000 * (_mwcW & 0xFFFF) + (_mwcW >> 16)) & MaxUInt32;
    var value = (((_mwcZ << 16) + (_mwcW & 0xFFFF)) >>> 0) & MaxUInt32 | 0;
    if (!signed) {
        value >>>= 0;
    }
    return value;
}
function newId(maxLength) {
    if (maxLength === void 0) { maxLength = 22; }
    var base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var number = random32() >>> 0;
    var chars = 0;
    var result = STR_EMPTY$1;
    while (result[_DYN_LENGTH$2 ] < maxLength) {
        chars++;
        result += base64chars.charAt(number & 0x3F);
        number >>>= 6;
        if (chars === 5) {
            number = (((random32() << 2) & 0xFFFFFFFF) | (number & 0x03)) >>> 0;
            chars = 0;
        }
    }
    return result;
}

var version = '3.3.10';
var instanceName = "." + newId(6);
var _dataUid = 0;
function _canAcceptData(target) {
    return target.nodeType === 1 || target.nodeType === 9 || !(+target.nodeType);
}
function _getCache(data, target) {
    var theCache = target[data.id];
    if (!theCache) {
        theCache = {};
        try {
            if (_canAcceptData(target)) {
                objDefine(target, data.id, {
                    e: false,
                    v: theCache
                });
            }
        }
        catch (e) {
        }
    }
    return theCache;
}
function createUniqueNamespace(name, includeVersion) {
    if (includeVersion === void 0) { includeVersion = false; }
    return normalizeJsName(name + (_dataUid++) + (includeVersion ? "." + version : STR_EMPTY$1) + instanceName);
}
function createElmNodeData(name) {
    var data = {
        id: createUniqueNamespace("_aiData-" + (name || STR_EMPTY$1) + "." + version),
        accept: function (target) {
            return _canAcceptData(target);
        },
        get: function (target, name, defValue, addDefault) {
            var theCache = target[data.id];
            if (!theCache) {
                if (addDefault) {
                    theCache = _getCache(data, target);
                    theCache[normalizeJsName(name)] = defValue;
                }
                return defValue;
            }
            return theCache[normalizeJsName(name)];
        },
        kill: function (target, name) {
            if (target && target[name]) {
                try {
                    delete target[name];
                }
                catch (e) {
                }
            }
        }
    };
    return data;
}

function _isConfigDefaults(value) {
    return (value && isObject(value) && !isArray(value) && (value.isVal || value.fb || objHasOwn(value, "v") || objHasOwn(value, "mrg") || objHasOwn(value, "ref") || value.set));
}
function _getDefault(dynamicHandler, theConfig, cfgDefaults) {
    var defValue;
    var isDefaultValid = cfgDefaults.dfVal || isDefined;
    if (theConfig && cfgDefaults.fb) {
        var fallbacks = cfgDefaults.fb;
        if (!isArray(fallbacks)) {
            fallbacks = [fallbacks];
        }
        for (var lp = 0; lp < fallbacks[_DYN_LENGTH$2 ]; lp++) {
            var fallback = fallbacks[lp];
            var fbValue = theConfig[fallback];
            if (isDefaultValid(fbValue)) {
                defValue = fbValue;
            }
            else if (dynamicHandler) {
                fbValue = dynamicHandler.cfg[fallback];
                if (isDefaultValid(fbValue)) {
                    defValue = fbValue;
                }
                dynamicHandler.set(dynamicHandler.cfg, asString(fallback), fbValue);
            }
            if (isDefaultValid(defValue)) {
                break;
            }
        }
    }
    if (!isDefaultValid(defValue) && isDefaultValid(cfgDefaults.v)) {
        defValue = cfgDefaults.v;
    }
    return defValue;
}
function _resolveDefaultValue(dynamicHandler, theConfig, cfgDefaults) {
    var theValue = cfgDefaults;
    if (cfgDefaults && _isConfigDefaults(cfgDefaults)) {
        theValue = _getDefault(dynamicHandler, theConfig, cfgDefaults);
    }
    if (theValue) {
        if (_isConfigDefaults(theValue)) {
            theValue = _resolveDefaultValue(dynamicHandler, theConfig, theValue);
        }
        var newValue_1;
        if (isArray(theValue)) {
            newValue_1 = [];
            newValue_1[_DYN_LENGTH$2 ] = theValue[_DYN_LENGTH$2 ];
        }
        else if (isPlainObject(theValue)) {
            newValue_1 = {};
        }
        if (newValue_1) {
            objForEachKey(theValue, function (key, value) {
                if (value && _isConfigDefaults(value)) {
                    value = _resolveDefaultValue(dynamicHandler, theConfig, value);
                }
                newValue_1[key] = value;
            });
            theValue = newValue_1;
        }
    }
    return theValue;
}
function _applyDefaultValue(dynamicHandler, theConfig, name, defaultValue) {
    var isValid;
    var setFn;
    var defValue;
    var cfgDefaults = defaultValue;
    var mergeDf;
    var reference;
    var readOnly;
    var blkDynamicValue;
    if (_isConfigDefaults(cfgDefaults)) {
        isValid = cfgDefaults.isVal;
        setFn = cfgDefaults.set;
        readOnly = cfgDefaults.rdOnly;
        blkDynamicValue = cfgDefaults.blkVal;
        mergeDf = cfgDefaults.mrg;
        reference = cfgDefaults.ref;
        if (!reference && isUndefined(reference)) {
            reference = !!mergeDf;
        }
        defValue = _getDefault(dynamicHandler, theConfig, cfgDefaults);
    }
    else {
        defValue = defaultValue;
    }
    if (blkDynamicValue) {
        dynamicHandler.blkVal(theConfig, name);
    }
    var theValue;
    var usingDefault = true;
    var cfgValue = theConfig[name];
    if (cfgValue || !isNullOrUndefined(cfgValue)) {
        theValue = cfgValue;
        usingDefault = false;
        if (isValid && theValue !== defValue && !isValid(theValue)) {
            theValue = defValue;
            usingDefault = true;
        }
        if (setFn) {
            theValue = setFn(theValue, defValue, theConfig);
            usingDefault = theValue === defValue;
        }
    }
    if (!usingDefault) {
        if (isPlainObject(theValue) || isArray(defValue)) {
            if (mergeDf && defValue && (isPlainObject(defValue) || isArray(defValue))) {
                objForEachKey(defValue, function (dfName, dfValue) {
                    _applyDefaultValue(dynamicHandler, theValue, dfName, dfValue);
                });
            }
        }
    }
    else if (defValue) {
        theValue = _resolveDefaultValue(dynamicHandler, theConfig, defValue);
    }
    else {
        theValue = defValue;
    }
    dynamicHandler.set(theConfig, name, theValue);
    if (reference) {
        dynamicHandler.ref(theConfig, name);
    }
    if (readOnly) {
        dynamicHandler.rdOnly(theConfig, name);
    }
}

var CFG_HANDLER_LINK = symbolFor("[[ai_dynCfg_1]]");
var BLOCK_DYNAMIC = symbolFor("[[ai_blkDynCfg_1]]");
var FORCE_DYNAMIC = symbolFor("[[ai_frcDynCfg_1]]");
function _cfgDeepCopy(source) {
    if (source) {
        var target_1;
        if (isArray(source)) {
            target_1 = [];
            target_1[_DYN_LENGTH$2 ] = source[_DYN_LENGTH$2 ];
        }
        else if (isPlainObject(source)) {
            target_1 = {};
        }
        if (target_1) {
            objForEachKey(source, function (key, value) {
                target_1[key] = _cfgDeepCopy(value);
            });
            return target_1;
        }
    }
    return source;
}
function getDynamicConfigHandler(value) {
    if (value) {
        var handler = value[CFG_HANDLER_LINK] || value;
        if (handler.cfg && (handler.cfg === value || handler.cfg[CFG_HANDLER_LINK] === handler)) {
            return handler;
        }
    }
    return null;
}
function blockDynamicConversion(value) {
    if (value && (isPlainObject(value) || isArray(value))) {
        try {
            value[BLOCK_DYNAMIC] = true;
        }
        catch (e) {
        }
    }
    return value;
}
function _canMakeDynamic(getFunc, state, value) {
    var result = false;
    if (value && !getFunc[state.blkVal]) {
        result = value[FORCE_DYNAMIC];
        if (!result && !value[BLOCK_DYNAMIC]) {
            result = isPlainObject(value) || isArray(value);
        }
    }
    return result;
}
function throwInvalidAccess(message) {
    throwTypeError("InvalidAccess:" + message);
}

var arrayMethodsToPatch = [
    "push",
    "pop",
    "shift",
    "unshift",
    "splice"
];
var _throwDynamicError = function (logger, name, desc, e) {
    logger && logger[_DYN_THROW_INTERNAL ](3 , 108 , "".concat(desc, " [").concat(name, "] failed - ") + dumpObj(e));
};
function _patchArray(state, target, name) {
    if (isArray(target)) {
        arrForEach(arrayMethodsToPatch, function (method) {
            var orgMethod = target[method];
            target[method] = function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                var result = orgMethod[_DYN_APPLY ](this, args);
                _makeDynamicObject(state, target, name, "Patching");
                return result;
            };
        });
    }
}
function _getOwnPropGetter(target, name) {
    var propDesc = objGetOwnPropertyDescriptor(target, name);
    return propDesc && propDesc.get;
}
function _createDynamicProperty(state, theConfig, name, value) {
    var detail = {
        n: name,
        h: [],
        trk: function (handler) {
            if (handler && handler.fn) {
                if (arrIndexOf(detail.h, handler) === -1) {
                    detail.h[_DYN_PUSH$1 ](handler);
                }
                state.trk(handler, detail);
            }
        },
        clr: function (handler) {
            var idx = arrIndexOf(detail.h, handler);
            if (idx !== -1) {
                detail.h[_DYN_SPLICE ](idx, 1);
            }
        }
    };
    var checkDynamic = true;
    var isObjectOrArray = false;
    function _getProperty() {
        if (checkDynamic) {
            isObjectOrArray = isObjectOrArray || _canMakeDynamic(_getProperty, state, value);
            if (value && !value[CFG_HANDLER_LINK] && isObjectOrArray) {
                value = _makeDynamicObject(state, value, name, "Converting");
            }
            checkDynamic = false;
        }
        var activeHandler = state.act;
        if (activeHandler) {
            detail.trk(activeHandler);
        }
        return value;
    }
    _getProperty[state.prop] = {
        chng: function () {
            state.add(detail);
        }
    };
    function _setProperty(newValue) {
        if (value !== newValue) {
            if (!!_getProperty[state.ro] && !state.upd) {
                throwInvalidAccess("[" + name + "] is read-only:" + dumpObj(theConfig));
            }
            if (checkDynamic) {
                isObjectOrArray = isObjectOrArray || _canMakeDynamic(_getProperty, state, value);
                checkDynamic = false;
            }
            var isReferenced = isObjectOrArray && _getProperty[state.rf];
            if (isObjectOrArray) {
                if (isReferenced) {
                    objForEachKey(value, function (key) {
                        value[key] = newValue ? newValue[key] : UNDEFINED_VALUE$1;
                    });
                    try {
                        objForEachKey(newValue, function (key, theValue) {
                            _setDynamicProperty(state, value, key, theValue);
                        });
                        newValue = value;
                    }
                    catch (e) {
                        _throwDynamicError((state.hdlr || {})[_DYN_LOGGER ], name, "Assigning", e);
                        isObjectOrArray = false;
                    }
                }
                else if (value && value[CFG_HANDLER_LINK]) {
                    objForEachKey(value, function (key) {
                        var getter = _getOwnPropGetter(value, key);
                        if (getter) {
                            var valueState = getter[state.prop];
                            valueState && valueState.chng();
                        }
                    });
                }
            }
            if (newValue !== value) {
                var newIsObjectOrArray = newValue && _canMakeDynamic(_getProperty, state, newValue);
                if (!isReferenced && newIsObjectOrArray) {
                    newValue = _makeDynamicObject(state, newValue, name, "Converting");
                }
                value = newValue;
                isObjectOrArray = newIsObjectOrArray;
            }
            state.add(detail);
        }
    }
    objDefine(theConfig, detail.n, { g: _getProperty, s: _setProperty });
}
function _setDynamicProperty(state, target, name, value) {
    if (target) {
        var getter = _getOwnPropGetter(target, name);
        var isDynamic = getter && !!getter[state.prop];
        if (!isDynamic) {
            _createDynamicProperty(state, target, name, value);
        }
        else {
            target[name] = value;
        }
    }
    return target;
}
function _setDynamicPropertyState(state, target, name, flags) {
    if (target) {
        var getter = _getOwnPropGetter(target, name);
        var isDynamic = getter && !!getter[state.prop];
        var inPlace = flags && flags[0 ];
        var rdOnly = flags && flags[1 ];
        var blkProp = flags && flags[2 ];
        if (!isDynamic) {
            if (blkProp) {
                try {
                    blockDynamicConversion(target);
                }
                catch (e) {
                    _throwDynamicError((state.hdlr || {})[_DYN_LOGGER ], name, "Blocking", e);
                }
            }
            try {
                _setDynamicProperty(state, target, name, target[name]);
                getter = _getOwnPropGetter(target, name);
            }
            catch (e) {
                _throwDynamicError((state.hdlr || {})[_DYN_LOGGER ], name, "State", e);
            }
        }
        if (inPlace) {
            getter[state.rf] = inPlace;
        }
        if (rdOnly) {
            getter[state.ro] = rdOnly;
        }
        if (blkProp) {
            getter[state.blkVal] = true;
        }
    }
    return target;
}
function _makeDynamicObject(state, target, name, desc) {
    try {
        objForEachKey(target, function (key, value) {
            _setDynamicProperty(state, target, key, value);
        });
        if (!target[CFG_HANDLER_LINK]) {
            objDefineProp(target, CFG_HANDLER_LINK, {
                get: function () {
                    return state.hdlr;
                }
            });
            _patchArray(state, target, name);
        }
    }
    catch (e) {
        _throwDynamicError((state.hdlr || {})[_DYN_LOGGER ], name, desc, e);
    }
    return target;
}

var symPrefix = "[[ai_";
var symPostfix = "]]";
function _createState(cfgHandler) {
    var dynamicPropertySymbol = newSymbol(symPrefix + "get" + cfgHandler.uid + symPostfix);
    var dynamicPropertyReadOnly = newSymbol(symPrefix + "ro" + cfgHandler.uid + symPostfix);
    var dynamicPropertyReferenced = newSymbol(symPrefix + "rf" + cfgHandler.uid + symPostfix);
    var dynamicPropertyBlockValue = newSymbol(symPrefix + "blkVal" + cfgHandler.uid + symPostfix);
    var dynamicPropertyDetail = newSymbol(symPrefix + "dtl" + cfgHandler.uid + symPostfix);
    var _waitingHandlers = null;
    var _watcherTimer = null;
    var theState;
    function _useHandler(activeHandler, callback) {
        var prevWatcher = theState.act;
        try {
            theState.act = activeHandler;
            if (activeHandler && activeHandler[dynamicPropertyDetail]) {
                arrForEach(activeHandler[dynamicPropertyDetail], function (detail) {
                    detail.clr(activeHandler);
                });
                activeHandler[dynamicPropertyDetail] = [];
            }
            callback({
                cfg: cfgHandler.cfg,
                set: cfgHandler.set.bind(cfgHandler),
                setDf: cfgHandler.setDf.bind(cfgHandler),
                ref: cfgHandler.ref.bind(cfgHandler),
                rdOnly: cfgHandler.rdOnly.bind(cfgHandler)
            });
        }
        catch (e) {
            var logger = cfgHandler[_DYN_LOGGER ];
            if (logger) {
                logger[_DYN_THROW_INTERNAL ](1 , 107 , dumpObj(e));
            }
            throw e;
        }
        finally {
            theState.act = prevWatcher || null;
        }
    }
    function _notifyWatchers() {
        if (_waitingHandlers) {
            var notifyHandlers = _waitingHandlers;
            _waitingHandlers = null;
            _watcherTimer && _watcherTimer[_DYN_CANCEL ]();
            _watcherTimer = null;
            var watcherFailures_1 = [];
            arrForEach(notifyHandlers, function (handler) {
                if (handler) {
                    if (handler[dynamicPropertyDetail]) {
                        arrForEach(handler[dynamicPropertyDetail], function (detail) {
                            detail.clr(handler);
                        });
                        handler[dynamicPropertyDetail] = null;
                    }
                    if (handler.fn) {
                        try {
                            _useHandler(handler, handler.fn);
                        }
                        catch (e) {
                            watcherFailures_1[_DYN_PUSH$1 ](e);
                        }
                    }
                }
            });
            if (_waitingHandlers) {
                try {
                    _notifyWatchers();
                }
                catch (e) {
                    watcherFailures_1[_DYN_PUSH$1 ](e);
                }
            }
            if (watcherFailures_1[_DYN_LENGTH$2 ] > 0) {
                throwAggregationError("Watcher error(s): ", watcherFailures_1);
            }
        }
    }
    function _addWatcher(detail) {
        if (detail && detail.h[_DYN_LENGTH$2 ] > 0) {
            if (!_waitingHandlers) {
                _waitingHandlers = [];
            }
            if (!_watcherTimer) {
                _watcherTimer = scheduleTimeout(function () {
                    _watcherTimer = null;
                    _notifyWatchers();
                }, 0);
            }
            for (var idx = 0; idx < detail.h[_DYN_LENGTH$2 ]; idx++) {
                var handler = detail.h[idx];
                if (handler && arrIndexOf(_waitingHandlers, handler) === -1) {
                    _waitingHandlers[_DYN_PUSH$1 ](handler);
                }
            }
        }
    }
    function _trackHandler(handler, detail) {
        if (handler) {
            var details = handler[dynamicPropertyDetail] = handler[dynamicPropertyDetail] || [];
            if (arrIndexOf(details, detail) === -1) {
                details[_DYN_PUSH$1 ](detail);
            }
        }
    }
    theState = {
        prop: dynamicPropertySymbol,
        ro: dynamicPropertyReadOnly,
        rf: dynamicPropertyReferenced,
        blkVal: dynamicPropertyBlockValue,
        hdlr: cfgHandler,
        add: _addWatcher,
        notify: _notifyWatchers,
        use: _useHandler,
        trk: _trackHandler
    };
    return theState;
}

function _createAndUseHandler(state, configHandler) {
    var handler = {
        fn: configHandler,
        rm: function () {
            handler.fn = null;
            state = null;
            configHandler = null;
        }
    };
    objDefine(handler, "toJSON", { v: function () { return "WatcherHandler" + (handler.fn ? "" : "[X]"); } });
    state.use(handler, configHandler);
    return handler;
}
function _createDynamicHandler(logger, target, inPlace) {
    var dynamicHandler = getDynamicConfigHandler(target);
    if (dynamicHandler) {
        return dynamicHandler;
    }
    var uid = createUniqueNamespace("dyncfg", true);
    var newTarget = (target && inPlace !== false) ? target : _cfgDeepCopy(target);
    var theState;
    function _notifyWatchers() {
        theState.notify();
    }
    function _setValue(target, name, value) {
        try {
            target = _setDynamicProperty(theState, target, name, value);
        }
        catch (e) {
            _throwDynamicError(logger, name, "Setting value", e);
        }
        return target[name];
    }
    function _watch(configHandler) {
        return _createAndUseHandler(theState, configHandler);
    }
    function _block(configHandler, allowUpdate) {
        theState.use(null, function (details) {
            var prevUpd = theState.upd;
            try {
                if (!isUndefined(allowUpdate)) {
                    theState.upd = allowUpdate;
                }
                configHandler(details);
            }
            finally {
                theState.upd = prevUpd;
            }
        });
    }
    function _ref(target, name) {
        var _a;
        return _setDynamicPropertyState(theState, target, name, (_a = {}, _a[0 ] = true, _a))[name];
    }
    function _rdOnly(target, name) {
        var _a;
        return _setDynamicPropertyState(theState, target, name, (_a = {}, _a[1 ] = true, _a))[name];
    }
    function _blkPropValue(target, name) {
        var _a;
        return _setDynamicPropertyState(theState, target, name, (_a = {}, _a[2 ] = true, _a))[name];
    }
    function _applyDefaults(theConfig, defaultValues) {
        if (defaultValues) {
            objForEachKey(defaultValues, function (name, value) {
                _applyDefaultValue(cfgHandler, theConfig, name, value);
            });
        }
        return theConfig;
    }
    var cfgHandler = {
        uid: null,
        cfg: newTarget,
        logger: logger,
        notify: _notifyWatchers,
        set: _setValue,
        setDf: _applyDefaults,
        watch: _watch,
        ref: _ref,
        rdOnly: _rdOnly,
        blkVal: _blkPropValue,
        _block: _block
    };
    objDefine(cfgHandler, "uid", {
        c: false,
        e: false,
        w: false,
        v: uid
    });
    theState = _createState(cfgHandler);
    _makeDynamicObject(theState, newTarget, "config", "Creating");
    return cfgHandler;
}
function _logInvalidAccess(logger, message) {
    if (logger) {
        logger[_DYN_WARN_TO_CONSOLE ](message);
        logger[_DYN_THROW_INTERNAL ](2 , 108 , message);
    }
    else {
        throwInvalidAccess(message);
    }
}
function createDynamicConfig(config, defaultConfig, logger, inPlace) {
    var dynamicHandler = _createDynamicHandler(logger, config || {}, inPlace);
    if (defaultConfig) {
        dynamicHandler.setDf(dynamicHandler.cfg, defaultConfig);
    }
    return dynamicHandler;
}
function onConfigChange(config, configHandler, logger) {
    var handler = config[CFG_HANDLER_LINK] || config;
    if (handler.cfg && (handler.cfg === config || handler.cfg[CFG_HANDLER_LINK] === handler)) {
        return handler[_DYN_WATCH ](configHandler);
    }
    _logInvalidAccess(logger, STR_NOT_DYNAMIC_ERROR + dumpObj(config));
    return createDynamicConfig(config, null, logger)[_DYN_WATCH ](configHandler);
}

function runTargetUnload(target, isAsync) {
    if (target && target[_DYN_UNLOAD ]) {
        return target[_DYN_UNLOAD ](isAsync);
    }
}

var DisabledPropertyName = "Microsoft_ApplicationInsights_BypassAjaxInstrumentation";

function _stringToBoolOrDefault(theValue, defaultValue, theConfig) {
    if (!theValue && isNullOrUndefined(theValue)) {
        return defaultValue;
    }
    if (isBoolean(theValue)) {
        return theValue;
    }
    return asString(theValue)[_DYN_TO_LOWER_CASE$1 ]() === "true";
}
function cfgDfValidate(validator, defaultValue, fallBackName) {
    return {
        fb: fallBackName,
        isVal: validator,
        v: defaultValue
    };
}
function cfgDfBoolean(defaultValue, fallBackName) {
    return {
        fb: fallBackName,
        set: _stringToBoolOrDefault,
        v: !!defaultValue
    };
}

var _aiNamespace = null;
function _getExtensionNamespace() {
    var target = getInst("Microsoft");
    if (target) {
        _aiNamespace = target["ApplicationInsights"];
    }
    return _aiNamespace;
}
function getDebugExt(config) {
    var ns = _aiNamespace;
    if (!ns && config.disableDbgExt !== true) {
        ns = _aiNamespace || _getExtensionNamespace();
    }
    return ns ? ns["ChromeDbgExt"] : null;
}

var _a$2;
var STR_WARN_TO_CONSOLE = "warnToConsole";
var AiNonUserActionablePrefix = "AI (Internal): ";
var AiUserActionablePrefix = "AI: ";
var AIInternalMessagePrefix = "AITR_";
var defaultValues$1 = {
    loggingLevelConsole: 0,
    loggingLevelTelemetry: 1,
    maxMessageLimit: 25,
    enableDebug: false
};
var _logFuncs = (_a$2 = {},
    _a$2[0 ] = null,
    _a$2[1 ] = "errorToConsole",
    _a$2[2 ] = STR_WARN_TO_CONSOLE,
    _a$2[3 ] = "debugToConsole",
    _a$2);
function _sanitizeDiagnosticText(text) {
    if (text) {
        return "\"" + text[_DYN_REPLACE ](/\"/g, STR_EMPTY$1) + "\"";
    }
    return STR_EMPTY$1;
}
function _logToConsole(func, message) {
    var theConsole = getConsole();
    if (!!theConsole) {
        var logFunc = "log";
        if (theConsole[func]) {
            logFunc = func;
        }
        if (isFunction(theConsole[logFunc])) {
            theConsole[logFunc](message);
        }
    }
}
var _InternalLogMessage = /** @class */ (function () {
    function _InternalLogMessage(msgId, msg, isUserAct, properties) {
        if (isUserAct === void 0) { isUserAct = false; }
        var _self = this;
        _self[_DYN_MESSAGE_ID ] = msgId;
        _self[_DYN_MESSAGE$1 ] =
            (isUserAct ? AiUserActionablePrefix : AiNonUserActionablePrefix) +
                msgId;
        var strProps = STR_EMPTY$1;
        if (hasJSON()) {
            strProps = getJSON().stringify(properties);
        }
        var diagnosticText = (msg ? " message:" + _sanitizeDiagnosticText(msg) : STR_EMPTY$1) +
            (properties ? " props:" + _sanitizeDiagnosticText(strProps) : STR_EMPTY$1);
        _self[_DYN_MESSAGE$1 ] += diagnosticText;
    }
    _InternalLogMessage.dataType = "MessageData";
    return _InternalLogMessage;
}());
function safeGetLogger(core, config) {
    return (core || {})[_DYN_LOGGER ] || new DiagnosticLogger(config);
}
var DiagnosticLogger = /** @class */ (function () {
    function DiagnosticLogger(config) {
        this.identifier = "DiagnosticLogger";
        this.queue = [];
        var _messageCount = 0;
        var _messageLogged = {};
        var _loggingLevelConsole;
        var _loggingLevelTelemetry;
        var _maxInternalMessageLimit;
        var _enableDebug;
        var _unloadHandler;
        dynamicProto(DiagnosticLogger, this, function (_self) {
            _unloadHandler = _setDefaultsFromConfig(config || {});
            _self.consoleLoggingLevel = function () { return _loggingLevelConsole; };
            _self[_DYN_THROW_INTERNAL ] = function (severity, msgId, msg, properties, isUserAct) {
                if (isUserAct === void 0) { isUserAct = false; }
                var message = new _InternalLogMessage(msgId, msg, isUserAct, properties);
                if (_enableDebug) {
                    throw dumpObj(message);
                }
                else {
                    var logFunc = _logFuncs[severity] || STR_WARN_TO_CONSOLE;
                    if (!isUndefined(message[_DYN_MESSAGE$1 ])) {
                        if (isUserAct) {
                            var messageKey = +message[_DYN_MESSAGE_ID ];
                            if (!_messageLogged[messageKey] && _loggingLevelConsole >= severity) {
                                _self[logFunc](message[_DYN_MESSAGE$1 ]);
                                _messageLogged[messageKey] = true;
                            }
                        }
                        else {
                            if (_loggingLevelConsole >= severity) {
                                _self[logFunc](message[_DYN_MESSAGE$1 ]);
                            }
                        }
                        _logInternalMessage(severity, message);
                    }
                    else {
                        _debugExtMsg("throw" + (severity === 1  ? "Critical" : "Warning"), message);
                    }
                }
            };
            _self.debugToConsole = function (message) {
                _logToConsole("debug", message);
                _debugExtMsg("warning", message);
            };
            _self[_DYN_WARN_TO_CONSOLE ] = function (message) {
                _logToConsole("warn", message);
                _debugExtMsg("warning", message);
            };
            _self.errorToConsole = function (message) {
                _logToConsole("error", message);
                _debugExtMsg("error", message);
            };
            _self.resetInternalMessageCount = function () {
                _messageCount = 0;
                _messageLogged = {};
            };
            _self.logInternalMessage = _logInternalMessage;
            _self[_DYN_UNLOAD ] = function (isAsync) {
                _unloadHandler && _unloadHandler.rm();
                _unloadHandler = null;
            };
            function _logInternalMessage(severity, message) {
                if (_areInternalMessagesThrottled()) {
                    return;
                }
                var logMessage = true;
                var messageKey = AIInternalMessagePrefix + message[_DYN_MESSAGE_ID ];
                if (_messageLogged[messageKey]) {
                    logMessage = false;
                }
                else {
                    _messageLogged[messageKey] = true;
                }
                if (logMessage) {
                    if (severity <= _loggingLevelTelemetry) {
                        _self.queue[_DYN_PUSH$1 ](message);
                        _messageCount++;
                        _debugExtMsg((severity === 1  ? "error" : "warn"), message);
                    }
                    if (_messageCount === _maxInternalMessageLimit) {
                        var throttleLimitMessage = "Internal events throttle limit per PageView reached for this app.";
                        var throttleMessage = new _InternalLogMessage(23 , throttleLimitMessage, false);
                        _self.queue[_DYN_PUSH$1 ](throttleMessage);
                        if (severity === 1 ) {
                            _self.errorToConsole(throttleLimitMessage);
                        }
                        else {
                            _self[_DYN_WARN_TO_CONSOLE ](throttleLimitMessage);
                        }
                    }
                }
            }
            function _setDefaultsFromConfig(config) {
                return onConfigChange(createDynamicConfig(config, defaultValues$1, _self).cfg, function (details) {
                    var config = details.cfg;
                    _loggingLevelConsole = config[_DYN_LOGGING_LEVEL_CONSOL4 ];
                    _loggingLevelTelemetry = config.loggingLevelTelemetry;
                    _maxInternalMessageLimit = config.maxMessageLimit;
                    _enableDebug = config.enableDebug;
                });
            }
            function _areInternalMessagesThrottled() {
                return _messageCount >= _maxInternalMessageLimit;
            }
            function _debugExtMsg(name, data) {
                var dbgExt = getDebugExt(config || {});
                if (dbgExt && dbgExt[_DYN_DIAG_LOG$1 ]) {
                    dbgExt[_DYN_DIAG_LOG$1 ](name, data);
                }
            }
        });
    }
    DiagnosticLogger.__ieDyn=1;
    return DiagnosticLogger;
}());
function _getLogger(logger) {
    return (logger || new DiagnosticLogger());
}
function _throwInternal(logger, severity, msgId, msg, properties, isUserAct) {
    if (isUserAct === void 0) { isUserAct = false; }
    _getLogger(logger)[_DYN_THROW_INTERNAL ](severity, msgId, msg, properties, isUserAct);
}
function _warnToConsole(logger, message) {
    _getLogger(logger)[_DYN_WARN_TO_CONSOLE ](message);
}

var strExecutionContextKey = "ctx";
var strParentContextKey = "ParentContextKey";
var strChildrenContextKey = "ChildrenContextKey";
var PerfEvent = /** @class */ (function () {
    function PerfEvent(name, payloadDetails, isAsync) {
        var _self = this;
        _self.start = utcNow();
        _self[_DYN_NAME$2 ] = name;
        _self.isAsync = isAsync;
        _self[_DYN_IS_CHILD_EVT ] = function () { return false; };
        if (isFunction(payloadDetails)) {
            var theDetails_1;
            objDefine(_self, "payload", {
                g: function () {
                    if (!theDetails_1 && isFunction(payloadDetails)) {
                        theDetails_1 = payloadDetails();
                        payloadDetails = null;
                    }
                    return theDetails_1;
                }
            });
        }
        _self[_DYN_GET_CTX ] = function (key) {
            if (key) {
                if (key === PerfEvent[strParentContextKey] || key === PerfEvent[strChildrenContextKey]) {
                    return _self[key];
                }
                return (_self[strExecutionContextKey] || {})[key];
            }
            return null;
        };
        _self[_DYN_SET_CTX ] = function (key, value) {
            if (key) {
                if (key === PerfEvent[strParentContextKey]) {
                    if (!_self[key]) {
                        _self[_DYN_IS_CHILD_EVT ] = function () { return true; };
                    }
                    _self[key] = value;
                }
                else if (key === PerfEvent[strChildrenContextKey]) {
                    _self[key] = value;
                }
                else {
                    var ctx = _self[strExecutionContextKey] = _self[strExecutionContextKey] || {};
                    ctx[key] = value;
                }
            }
        };
        _self.complete = function () {
            var childTime = 0;
            var childEvts = _self[_DYN_GET_CTX ](PerfEvent[strChildrenContextKey]);
            if (isArray(childEvts)) {
                for (var lp = 0; lp < childEvts[_DYN_LENGTH$2 ]; lp++) {
                    var childEvt = childEvts[lp];
                    if (childEvt) {
                        childTime += childEvt.time;
                    }
                }
            }
            _self.time = utcNow() - _self.start;
            _self.exTime = _self.time - childTime;
            _self.complete = function () { };
        };
    }
    PerfEvent.ParentContextKey = "parent";
    PerfEvent.ChildrenContextKey = "childEvts";
    return PerfEvent;
}());
var doPerfActiveKey = "CoreUtils.doPerf";
function doPerf(mgrSource, getSource, func, details, isAsync) {
    if (mgrSource) {
        var perfMgr = mgrSource;
        if (perfMgr[STR_GET_PERF_MGR]) {
            perfMgr = perfMgr[STR_GET_PERF_MGR]();
        }
        if (perfMgr) {
            var perfEvt = void 0;
            var currentActive = perfMgr[_DYN_GET_CTX ](doPerfActiveKey);
            try {
                perfEvt = perfMgr.create(getSource(), details, isAsync);
                if (perfEvt) {
                    if (currentActive && perfEvt[_DYN_SET_CTX ]) {
                        perfEvt[_DYN_SET_CTX ](PerfEvent[strParentContextKey], currentActive);
                        if (currentActive[_DYN_GET_CTX ] && currentActive[_DYN_SET_CTX ]) {
                            var children = currentActive[_DYN_GET_CTX ](PerfEvent[strChildrenContextKey]);
                            if (!children) {
                                children = [];
                                currentActive[_DYN_SET_CTX ](PerfEvent[strChildrenContextKey], children);
                            }
                            children[_DYN_PUSH$1 ](perfEvt);
                        }
                    }
                    perfMgr[_DYN_SET_CTX ](doPerfActiveKey, perfEvt);
                    return func(perfEvt);
                }
            }
            catch (ex) {
                if (perfEvt && perfEvt[_DYN_SET_CTX ]) {
                    perfEvt[_DYN_SET_CTX ]("exception", ex);
                }
            }
            finally {
                if (perfEvt) {
                    perfMgr.fire(perfEvt);
                }
                perfMgr[_DYN_SET_CTX ](doPerfActiveKey, currentActive);
            }
        }
    }
    return func();
}

var pluginStateData = createElmNodeData("plugin");
function _getPluginState(plugin) {
    return pluginStateData.get(plugin, "state", {}, true);
}

var strTelemetryPluginChain = "TelemetryPluginChain";
var strHasRunFlags = "_hasRun";
var strGetTelCtx = "_getTelCtx";
var _chainId = 0;
function _getNextProxyStart(proxy, core, startAt) {
    while (proxy) {
        if (proxy[_DYN_GET_PLUGIN ]() === startAt) {
            return proxy;
        }
        proxy = proxy[_DYN_GET_NEXT ]();
    }
    return createTelemetryProxyChain([startAt], core.config || {}, core);
}
function _createInternalContext(telemetryChain, dynamicHandler, core, startAt) {
    var _nextProxy = null;
    var _onComplete = [];
    if (!dynamicHandler) {
        dynamicHandler = createDynamicConfig({}, null, core[_DYN_LOGGER ]);
    }
    if (startAt !== null) {
        _nextProxy = startAt ? _getNextProxyStart(telemetryChain, core, startAt) : telemetryChain;
    }
    var context = {
        _next: _moveNext,
        ctx: {
            core: function () {
                return core;
            },
            diagLog: function () {
                return safeGetLogger(core, dynamicHandler.cfg);
            },
            getCfg: function () {
                return dynamicHandler.cfg;
            },
            getExtCfg: _resolveExtCfg,
            getConfig: _getConfig,
            hasNext: function () {
                return !!_nextProxy;
            },
            getNext: function () {
                return _nextProxy;
            },
            setNext: function (nextPlugin) {
                _nextProxy = nextPlugin;
            },
            iterate: _iterateChain,
            onComplete: _addOnComplete
        }
    };
    function _addOnComplete(onComplete, that) {
        var args = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            args[_i - 2] = arguments[_i];
        }
        if (onComplete) {
            _onComplete[_DYN_PUSH$1 ]({
                func: onComplete,
                self: !isUndefined(that) ? that : context.ctx,
                args: args
            });
        }
    }
    function _moveNext() {
        var nextProxy = _nextProxy;
        _nextProxy = nextProxy ? nextProxy[_DYN_GET_NEXT ]() : null;
        if (!nextProxy) {
            var onComplete = _onComplete;
            if (onComplete && onComplete[_DYN_LENGTH$2 ] > 0) {
                arrForEach(onComplete, function (completeDetails) {
                    try {
                        completeDetails.func.call(completeDetails.self, completeDetails.args);
                    }
                    catch (e) {
                        _throwInternal(core[_DYN_LOGGER ], 2 , 73 , "Unexpected Exception during onComplete - " + dumpObj(e));
                    }
                });
                _onComplete = [];
            }
        }
        return nextProxy;
    }
    function _getExtCfg(identifier, createIfMissing) {
        var idCfg = null;
        var cfg = dynamicHandler.cfg;
        if (cfg && identifier) {
            var extCfg = cfg[STR_EXTENSION_CONFIG ];
            if (!extCfg && createIfMissing) {
                extCfg = {};
            }
            cfg[STR_EXTENSION_CONFIG] = extCfg;
            extCfg = dynamicHandler.ref(cfg, STR_EXTENSION_CONFIG);
            if (extCfg) {
                idCfg = extCfg[identifier];
                if (!idCfg && createIfMissing) {
                    idCfg = {};
                }
                extCfg[identifier] = idCfg;
                idCfg = dynamicHandler.ref(extCfg, identifier);
            }
        }
        return idCfg;
    }
    function _resolveExtCfg(identifier, defaultValues) {
        var newConfig = _getExtCfg(identifier, true);
        if (defaultValues) {
            objForEachKey(defaultValues, function (field, defaultValue) {
                if (isNullOrUndefined(newConfig[field])) {
                    var cfgValue = dynamicHandler.cfg[field];
                    if (cfgValue || !isNullOrUndefined(cfgValue)) {
                        newConfig[field] = cfgValue;
                    }
                }
                _applyDefaultValue(dynamicHandler, newConfig, field, defaultValue);
            });
        }
        return dynamicHandler.setDf(newConfig, defaultValues);
    }
    function _getConfig(identifier, field, defaultValue) {
        if (defaultValue === void 0) { defaultValue = false; }
        var theValue;
        var extConfig = _getExtCfg(identifier, false);
        var rootConfig = dynamicHandler.cfg;
        if (extConfig && (extConfig[field] || !isNullOrUndefined(extConfig[field]))) {
            theValue = extConfig[field];
        }
        else if (rootConfig[field] || !isNullOrUndefined(rootConfig[field])) {
            theValue = rootConfig[field];
        }
        return (theValue || !isNullOrUndefined(theValue)) ? theValue : defaultValue;
    }
    function _iterateChain(cb) {
        var nextPlugin;
        while (!!(nextPlugin = context._next())) {
            var plugin = nextPlugin[_DYN_GET_PLUGIN ]();
            if (plugin) {
                cb(plugin);
            }
        }
    }
    return context;
}
function createProcessTelemetryContext(telemetryChain, cfg, core, startAt) {
    var config = createDynamicConfig(cfg);
    var internalContext = _createInternalContext(telemetryChain, config, core, startAt);
    var context = internalContext.ctx;
    function _processNext(env) {
        var nextPlugin = internalContext._next();
        if (nextPlugin) {
            nextPlugin[STR_PROCESS_TELEMETRY ](env, context);
        }
        return !nextPlugin;
    }
    function _createNew(plugins, startAt) {
        if (plugins === void 0) { plugins = null; }
        if (isArray(plugins)) {
            plugins = createTelemetryProxyChain(plugins, config.cfg, core, startAt);
        }
        return createProcessTelemetryContext(plugins || context[_DYN_GET_NEXT ](), config.cfg, core, startAt);
    }
    context[_DYN_PROCESS_NEXT ] = _processNext;
    context[_DYN_CREATE_NEW ] = _createNew;
    return context;
}
function createProcessTelemetryUnloadContext(telemetryChain, core, startAt) {
    var config = createDynamicConfig(core.config);
    var internalContext = _createInternalContext(telemetryChain, config, core, startAt);
    var context = internalContext.ctx;
    function _processNext(unloadState) {
        var nextPlugin = internalContext._next();
        nextPlugin && nextPlugin[_DYN_UNLOAD ](context, unloadState);
        return !nextPlugin;
    }
    function _createNew(plugins, startAt) {
        if (plugins === void 0) { plugins = null; }
        if (isArray(plugins)) {
            plugins = createTelemetryProxyChain(plugins, config.cfg, core, startAt);
        }
        return createProcessTelemetryUnloadContext(plugins || context[_DYN_GET_NEXT ](), core, startAt);
    }
    context[_DYN_PROCESS_NEXT ] = _processNext;
    context[_DYN_CREATE_NEW ] = _createNew;
    return context;
}
function createProcessTelemetryUpdateContext(telemetryChain, core, startAt) {
    var config = createDynamicConfig(core.config);
    var internalContext = _createInternalContext(telemetryChain, config, core, startAt);
    var context = internalContext.ctx;
    function _processNext(updateState) {
        return context.iterate(function (plugin) {
            if (isFunction(plugin[_DYN_UPDATE ])) {
                plugin[_DYN_UPDATE ](context, updateState);
            }
        });
    }
    function _createNew(plugins, startAt) {
        if (plugins === void 0) { plugins = null; }
        if (isArray(plugins)) {
            plugins = createTelemetryProxyChain(plugins, config.cfg, core, startAt);
        }
        return createProcessTelemetryUpdateContext(plugins || context[_DYN_GET_NEXT ](), core, startAt);
    }
    context[_DYN_PROCESS_NEXT ] = _processNext;
    context[_DYN_CREATE_NEW ] = _createNew;
    return context;
}
function createTelemetryProxyChain(plugins, config, core, startAt) {
    var firstProxy = null;
    var add = startAt ? false : true;
    if (isArray(plugins) && plugins[_DYN_LENGTH$2 ] > 0) {
        var lastProxy_1 = null;
        arrForEach(plugins, function (thePlugin) {
            if (!add && startAt === thePlugin) {
                add = true;
            }
            if (add && thePlugin && isFunction(thePlugin[STR_PROCESS_TELEMETRY ])) {
                var newProxy = createTelemetryPluginProxy(thePlugin, config, core);
                if (!firstProxy) {
                    firstProxy = newProxy;
                }
                if (lastProxy_1) {
                    lastProxy_1._setNext(newProxy);
                }
                lastProxy_1 = newProxy;
            }
        });
    }
    if (startAt && !firstProxy) {
        return createTelemetryProxyChain([startAt], config, core);
    }
    return firstProxy;
}
function createTelemetryPluginProxy(plugin, config, core) {
    var nextProxy = null;
    var hasProcessTelemetry = isFunction(plugin[STR_PROCESS_TELEMETRY ]);
    var hasSetNext = isFunction(plugin[_DYN_SET_NEXT_PLUGIN ]);
    var chainId;
    if (plugin) {
        chainId = plugin[_DYN_IDENTIFIER ] + "-" + plugin[STR_PRIORITY ] + "-" + _chainId++;
    }
    else {
        chainId = "Unknown-0-" + _chainId++;
    }
    var proxyChain = {
        getPlugin: function () {
            return plugin;
        },
        getNext: function () {
            return nextProxy;
        },
        processTelemetry: _processTelemetry,
        unload: _unloadPlugin,
        update: _updatePlugin,
        _id: chainId,
        _setNext: function (nextPlugin) {
            nextProxy = nextPlugin;
        }
    };
    function _getTelCtx() {
        var itemCtx;
        if (plugin && isFunction(plugin[strGetTelCtx])) {
            itemCtx = plugin[strGetTelCtx]();
        }
        if (!itemCtx) {
            itemCtx = createProcessTelemetryContext(proxyChain, config, core);
        }
        return itemCtx;
    }
    function _processChain(itemCtx, processPluginFn, name, details, isAsync) {
        var hasRun = false;
        var identifier = plugin ? plugin[_DYN_IDENTIFIER ] : strTelemetryPluginChain;
        var hasRunContext = itemCtx[strHasRunFlags];
        if (!hasRunContext) {
            hasRunContext = itemCtx[strHasRunFlags] = {};
        }
        itemCtx.setNext(nextProxy);
        if (plugin) {
            doPerf(itemCtx[STR_CORE ](), function () { return identifier + ":" + name; }, function () {
                hasRunContext[chainId] = true;
                try {
                    var nextId = nextProxy ? nextProxy._id : STR_EMPTY$1;
                    if (nextId) {
                        hasRunContext[nextId] = false;
                    }
                    hasRun = processPluginFn(itemCtx);
                }
                catch (error) {
                    var hasNextRun = nextProxy ? hasRunContext[nextProxy._id] : true;
                    if (hasNextRun) {
                        hasRun = true;
                    }
                    if (!nextProxy || !hasNextRun) {
                        _throwInternal(itemCtx[_DYN_DIAG_LOG$1 ](), 1 , 73 , "Plugin [" + identifier + "] failed during " + name + " - " + dumpObj(error) + ", run flags: " + dumpObj(hasRunContext));
                    }
                }
            }, details, isAsync);
        }
        return hasRun;
    }
    function _processTelemetry(env, itemCtx) {
        itemCtx = itemCtx || _getTelCtx();
        function _callProcessTelemetry(itemCtx) {
            if (!plugin || !hasProcessTelemetry) {
                return false;
            }
            var pluginState = _getPluginState(plugin);
            if (pluginState[_DYN_TEARDOWN ] || pluginState[STR_DISABLED]) {
                return false;
            }
            if (hasSetNext) {
                plugin[_DYN_SET_NEXT_PLUGIN ](nextProxy);
            }
            plugin[STR_PROCESS_TELEMETRY ](env, itemCtx);
            return true;
        }
        if (!_processChain(itemCtx, _callProcessTelemetry, "processTelemetry", function () { return ({ item: env }); }, !(env.sync))) {
            itemCtx[_DYN_PROCESS_NEXT ](env);
        }
    }
    function _unloadPlugin(unloadCtx, unloadState) {
        function _callTeardown() {
            var hasRun = false;
            if (plugin) {
                var pluginState = _getPluginState(plugin);
                var pluginCore = plugin[STR_CORE] || pluginState[STR_CORE ];
                if (plugin && (!pluginCore || pluginCore === unloadCtx.core()) && !pluginState[_DYN_TEARDOWN ]) {
                    pluginState[STR_CORE ] = null;
                    pluginState[_DYN_TEARDOWN ] = true;
                    pluginState[_DYN_IS_INITIALIZED ] = false;
                    if (plugin[_DYN_TEARDOWN ] && plugin[_DYN_TEARDOWN ](unloadCtx, unloadState) === true) {
                        hasRun = true;
                    }
                }
            }
            return hasRun;
        }
        if (!_processChain(unloadCtx, _callTeardown, "unload", function () { }, unloadState.isAsync)) {
            unloadCtx[_DYN_PROCESS_NEXT ](unloadState);
        }
    }
    function _updatePlugin(updateCtx, updateState) {
        function _callUpdate() {
            var hasRun = false;
            if (plugin) {
                var pluginState = _getPluginState(plugin);
                var pluginCore = plugin[STR_CORE] || pluginState[STR_CORE ];
                if (plugin && (!pluginCore || pluginCore === updateCtx.core()) && !pluginState[_DYN_TEARDOWN ]) {
                    if (plugin[_DYN_UPDATE ] && plugin[_DYN_UPDATE ](updateCtx, updateState) === true) {
                        hasRun = true;
                    }
                }
            }
            return hasRun;
        }
        if (!_processChain(updateCtx, _callUpdate, "update", function () { }, false)) {
            updateCtx[_DYN_PROCESS_NEXT ](updateState);
        }
    }
    return objFreeze(proxyChain);
}

function createUnloadHandlerContainer() {
    var handlers = [];
    function _addHandler(handler) {
        if (handler) {
            handlers[_DYN_PUSH$1 ](handler);
        }
    }
    function _runHandlers(unloadCtx, unloadState) {
        arrForEach(handlers, function (handler) {
            try {
                handler(unloadCtx, unloadState);
            }
            catch (e) {
                _throwInternal(unloadCtx[_DYN_DIAG_LOG$1 ](), 2 , 73 , "Unexpected error calling unload handler - " + dumpObj(e));
            }
        });
        handlers = [];
    }
    return {
        add: _addHandler,
        run: _runHandlers
    };
}

function createUnloadHookContainer() {
    var _hooks = [];
    function _doUnload(logger) {
        var oldHooks = _hooks;
        _hooks = [];
        arrForEach(oldHooks, function (fn) {
            try {
                (fn.rm || fn.remove).call(fn);
            }
            catch (e) {
                _throwInternal(logger, 2 , 73 , "Unloading:" + dumpObj(e));
            }
        });
    }
    function _addHook(hooks) {
        if (hooks) {
            arrAppend(_hooks, hooks);
        }
    }
    return {
        run: _doUnload,
        add: _addHook
    };
}

var _a$1;
var strGetPlugin = "getPlugin";
var defaultValues = (_a$1 = {},
    _a$1[STR_EXTENSION_CONFIG] = { isVal: isNotNullOrUndefined, v: {} },
    _a$1);
var BaseTelemetryPlugin = /** @class */ (function () {
    function BaseTelemetryPlugin() {
        var _self = this;
        var _isinitialized;
        var _rootCtx;
        var _nextPlugin;
        var _unloadHandlerContainer;
        var _hookContainer;
        _initDefaults();
        dynamicProto(BaseTelemetryPlugin, _self, function (_self) {
            _self[_DYN_INITIALIZE$1 ] = function (config, core, extensions, pluginChain) {
                _setDefaults(config, core, pluginChain);
                _isinitialized = true;
            };
            _self[_DYN_TEARDOWN ] = function (unloadCtx, unloadState) {
                var core = _self[STR_CORE ];
                if (!core || (unloadCtx && core !== unloadCtx[STR_CORE ]())) {
                    return;
                }
                var result;
                var unloadDone = false;
                var theUnloadCtx = unloadCtx || createProcessTelemetryUnloadContext(null, core, _nextPlugin && _nextPlugin[strGetPlugin] ? _nextPlugin[strGetPlugin]() : _nextPlugin);
                var theUnloadState = unloadState || {
                    reason: 0 ,
                    isAsync: false
                };
                function _unloadCallback() {
                    if (!unloadDone) {
                        unloadDone = true;
                        _unloadHandlerContainer.run(theUnloadCtx, unloadState);
                        _hookContainer.run(theUnloadCtx[_DYN_DIAG_LOG$1 ]());
                        if (result === true) {
                            theUnloadCtx[_DYN_PROCESS_NEXT ](theUnloadState);
                        }
                        _initDefaults();
                    }
                }
                if (!_self[_DYN__DO_TEARDOWN ] || _self[_DYN__DO_TEARDOWN ](theUnloadCtx, theUnloadState, _unloadCallback) !== true) {
                    _unloadCallback();
                }
                else {
                    result = true;
                }
                return result;
            };
            _self[_DYN_UPDATE ] = function (updateCtx, updateState) {
                var core = _self[STR_CORE ];
                if (!core || (updateCtx && core !== updateCtx[STR_CORE ]())) {
                    return;
                }
                var result;
                var updateDone = false;
                var theUpdateCtx = updateCtx || createProcessTelemetryUpdateContext(null, core, _nextPlugin && _nextPlugin[strGetPlugin] ? _nextPlugin[strGetPlugin]() : _nextPlugin);
                var theUpdateState = updateState || {
                    reason: 0
                };
                function _updateCallback() {
                    if (!updateDone) {
                        updateDone = true;
                        _setDefaults(theUpdateCtx.getCfg(), theUpdateCtx.core(), theUpdateCtx[_DYN_GET_NEXT ]());
                    }
                }
                if (!_self._doUpdate || _self._doUpdate(theUpdateCtx, theUpdateState, _updateCallback) !== true) {
                    _updateCallback();
                }
                else {
                    result = true;
                }
                return result;
            };
            proxyFunctionAs(_self, "_addUnloadCb", function () { return _unloadHandlerContainer; }, "add");
            proxyFunctionAs(_self, "_addHook", function () { return _hookContainer; }, "add");
            objDefine(_self, "_unloadHooks", { g: function () { return _hookContainer; } });
        });
        _self[_DYN_DIAG_LOG$1 ] = function (itemCtx) {
            return _getTelCtx(itemCtx)[_DYN_DIAG_LOG$1 ]();
        };
        _self[_DYN_IS_INITIALIZED ] = function () {
            return _isinitialized;
        };
        _self.setInitialized = function (isInitialized) {
            _isinitialized = isInitialized;
        };
        _self[_DYN_SET_NEXT_PLUGIN ] = function (next) {
            _nextPlugin = next;
        };
        _self[_DYN_PROCESS_NEXT ] = function (env, itemCtx) {
            if (itemCtx) {
                itemCtx[_DYN_PROCESS_NEXT ](env);
            }
            else if (_nextPlugin && isFunction(_nextPlugin[STR_PROCESS_TELEMETRY ])) {
                _nextPlugin[STR_PROCESS_TELEMETRY ](env, null);
            }
        };
        _self._getTelCtx = _getTelCtx;
        function _getTelCtx(currentCtx) {
            if (currentCtx === void 0) { currentCtx = null; }
            var itemCtx = currentCtx;
            if (!itemCtx) {
                var rootCtx = _rootCtx || createProcessTelemetryContext(null, {}, _self[STR_CORE ]);
                if (_nextPlugin && _nextPlugin[strGetPlugin]) {
                    itemCtx = rootCtx[_DYN_CREATE_NEW ](null, _nextPlugin[strGetPlugin]);
                }
                else {
                    itemCtx = rootCtx[_DYN_CREATE_NEW ](null, _nextPlugin);
                }
            }
            return itemCtx;
        }
        function _setDefaults(config, core, pluginChain) {
            createDynamicConfig(config, defaultValues, safeGetLogger(core));
            if (!pluginChain && core) {
                pluginChain = core[_DYN_GET_PROCESS_TEL_CONT2 ]()[_DYN_GET_NEXT ]();
            }
            var nextPlugin = _nextPlugin;
            if (_nextPlugin && _nextPlugin[strGetPlugin]) {
                nextPlugin = _nextPlugin[strGetPlugin]();
            }
            _self[STR_CORE ] = core;
            _rootCtx = createProcessTelemetryContext(pluginChain, config, core, nextPlugin);
        }
        function _initDefaults() {
            _isinitialized = false;
            _self[STR_CORE ] = null;
            _rootCtx = null;
            _nextPlugin = null;
            _hookContainer = createUnloadHookContainer();
            _unloadHandlerContainer = createUnloadHandlerContainer();
        }
    }
    BaseTelemetryPlugin.__ieDyn=1;
    return BaseTelemetryPlugin;
}());

function parseResponse(response, diagLog) {
    try {
        if (response && response !== "") {
            var result = getJSON().parse(response);
            if (result && result[_DYN_ITEMS_RECEIVED$1 ] && result[_DYN_ITEMS_RECEIVED$1 ] >= result.itemsAccepted &&
                result.itemsReceived - result.itemsAccepted === result.errors[_DYN_LENGTH$2 ]) {
                return result;
            }
        }
    }
    catch (e) {
        _throwInternal(diagLog, 1 , 43 , "Cannot parse the response. " + (e[_DYN_NAME$2 ] || dumpObj(e)), {
            response: response
        });
    }
    return null;
}

var STR_EMPTY = "";
var STR_NO_RESPONSE_BODY = "NoResponseBody";
var _noResponseQs = "&" + STR_NO_RESPONSE_BODY + "=true";
var STR_POST_METHOD = "POST";
var SenderPostManager = /** @class */ (function () {
    function SenderPostManager() {
        var _syncFetchPayload = 0;
        var _enableSendPromise;
        var _isInitialized;
        var _diagLog;
        var _isOneDs;
        var _onCompleteFuncs;
        var _disableCredentials;
        var _fetchCredentials;
        var _fallbackInst;
        var _disableXhr;
        var _disableBeacon;
        var _disableBeaconSync;
        var _disableFetchKeepAlive;
        var _addNoResponse;
        var _timeoutWrapper;
        dynamicProto(SenderPostManager, this, function (_self, _base) {
            var _sendCredentials = true;
            _initDefaults();
            _self[_DYN_INITIALIZE$1 ] = function (config, diagLog) {
                _diagLog = diagLog;
                if (_isInitialized) {
                    _throwInternal(_diagLog, 1 , 28 , "Sender is already initialized");
                }
                _self.SetConfig(config);
                _isInitialized = true;
            };
            _self["_getDbgPlgTargets"] = function () {
                return [_isInitialized, _isOneDs, _disableCredentials, _enableSendPromise];
            };
            _self.SetConfig = function (config) {
                try {
                    _onCompleteFuncs = config.senderOnCompleteCallBack || {};
                    _disableCredentials = !!config.disableCredentials;
                    _fetchCredentials = config.fetchCredentials;
                    _isOneDs = !!config.isOneDs;
                    _enableSendPromise = !!config.enableSendPromise;
                    _disableXhr = !!config.disableXhr;
                    _disableBeacon = !!config.disableBeacon;
                    _disableBeaconSync = !!config.disableBeaconSync;
                    _timeoutWrapper = config.timeWrapper;
                    _addNoResponse = !!config.addNoResponse;
                    _disableFetchKeepAlive = !!config.disableFetchKeepAlive;
                    _fallbackInst = { sendPOST: _xhrSender };
                    if (!_isOneDs) {
                        _sendCredentials = false;
                    }
                    if (_disableCredentials) {
                        var location_1 = getLocation();
                        if (location_1 && location_1.protocol && location_1.protocol[_DYN_TO_LOWER_CASE$1 ]() === "file:") {
                            _sendCredentials = false;
                        }
                    }
                    return true;
                }
                catch (e) {
                }
                return false;
            };
            _self.getSyncFetchPayload = function () {
                return _syncFetchPayload;
            };
            _self.getSenderInst = function (transports, sync) {
                if (transports && transports[_DYN_LENGTH$2 ]) {
                    return _getSenderInterface(transports, sync);
                }
                return null;
            };
            _self.getFallbackInst = function () {
                return _fallbackInst;
            };
            _self[_DYN__DO_TEARDOWN ] = function (unloadCtx, unloadState) {
                _initDefaults();
            };
            _self.preparePayload = function (callback, zipPayload, payload, isSync) {
                if (!zipPayload || isSync || !payload[_DYN_DATA$1 ]) {
                    callback(payload);
                    return;
                }
                try {
                    var csStream = getInst("CompressionStream");
                    if (!isFunction(csStream)) {
                        callback(payload);
                        return;
                    }
                    var body = new ReadableStream({
                        start: function (controller) {
                            controller.enqueue(isString(payload[_DYN_DATA$1 ]) ? new TextEncoder().encode(payload[_DYN_DATA$1 ]) : payload[_DYN_DATA$1 ]);
                            controller.close();
                        }
                    });
                    var compressedStream = body.pipeThrough(new csStream("gzip"));
                    var reader_1 = compressedStream.getReader();
                    var chunks_1 = [];
                    var totalLength_1 = 0;
                    var callbackCalled_1 = false;
                    doAwaitResponse(reader_1.read(), function processChunk(response) {
                        if (!callbackCalled_1 && !response.rejected) {
                            var result = response[_DYN_VALUE ];
                            if (!result.done) {
                                chunks_1[_DYN_PUSH$1 ](result[_DYN_VALUE ]);
                                totalLength_1 += result.value[_DYN_LENGTH$2 ];
                                return doAwaitResponse(reader_1.read(), processChunk);
                            }
                            var combined = new Uint8Array(totalLength_1);
                            var offset = 0;
                            for (var _i = 0, chunks_2 = chunks_1; _i < chunks_2.length; _i++) {
                                var chunk = chunks_2[_i];
                                combined.set(chunk, offset);
                                offset += chunk[_DYN_LENGTH$2 ];
                            }
                            payload[_DYN_DATA$1 ] = combined;
                            payload[_DYN_HEADERS ]["Content-Encoding"] = "gzip";
                            payload._chunkCount = chunks_1[_DYN_LENGTH$2 ];
                        }
                        if (!callbackCalled_1) {
                            callbackCalled_1 = true;
                            callback(payload);
                        }
                    });
                    return reader_1;
                }
                catch (error) {
                    callback(payload);
                    return;
                }
            };
            function _onSuccess(res, onComplete) {
                _doOnComplete(onComplete, 200, {}, res);
            }
            function _onError(message, onComplete) {
                _throwInternal(_diagLog, 2 , 26 , "Failed to send telemetry.", { message: message });
                _doOnComplete(onComplete, 400, {});
            }
            function _onNoPayloadUrl(onComplete) {
                _onError("No endpoint url is provided for the batch", onComplete);
            }
            function _getSenderInterface(transports, syncSupport) {
                var transportType = 0 ;
                var sendPostFunc = null;
                var lp = 0;
                while (sendPostFunc == null && lp < transports[_DYN_LENGTH$2 ]) {
                    transportType = transports[lp];
                    if (!_disableXhr && transportType === 1 ) {
                        if (useXDomainRequest()) {
                            sendPostFunc = _xdrSender;
                        }
                        else if (isXhrSupported()) {
                            sendPostFunc = _xhrSender;
                        }
                    }
                    else if (transportType === 2  && isFetchSupported(syncSupport) && (!syncSupport || !_disableFetchKeepAlive)) {
                        sendPostFunc = _doFetchSender;
                    }
                    else if (transportType === 3  && isBeaconsSupported() && (syncSupport ? !_disableBeaconSync : !_disableBeacon)) {
                        sendPostFunc = _beaconSender;
                    }
                    lp++;
                }
                if (sendPostFunc) {
                    return {
                        _transport: transportType,
                        _isSync: syncSupport,
                        sendPOST: sendPostFunc
                    };
                }
                return null;
            }
            function _doOnComplete(oncomplete, status, headers, response) {
                try {
                    oncomplete && oncomplete(status, headers, response);
                }
                catch (e) {
                }
            }
            function _doBeaconSend(payload, oncomplete) {
                var nav = getNavigator();
                var url = payload[_DYN_URL_STRING ];
                if (!url) {
                    _onNoPayloadUrl(oncomplete);
                    return true;
                }
                url = payload[_DYN_URL_STRING ] + (_addNoResponse ? _noResponseQs : STR_EMPTY);
                var data = payload[_DYN_DATA$1 ];
                var plainTextBatch = _isOneDs ? data : new Blob([data], { type: "text/plain;charset=UTF-8" });
                var queued = nav.sendBeacon(url, plainTextBatch);
                return queued;
            }
            function _beaconSender(payload, oncomplete, sync) {
                var data = payload[_DYN_DATA$1 ];
                try {
                    if (data) {
                        if (!_doBeaconSend(payload, oncomplete)) {
                            var onRetry = _onCompleteFuncs && _onCompleteFuncs.beaconOnRetry;
                            if (onRetry && isFunction(onRetry)) {
                                onRetry(payload, oncomplete, _doBeaconSend);
                            }
                            else {
                                _fallbackInst && _fallbackInst.sendPOST(payload, oncomplete, true);
                                _throwInternal(_diagLog, 2 , 40 , ". " + "Failed to send telemetry with Beacon API, retried with normal sender.");
                            }
                        }
                        else {
                            _onSuccess(STR_EMPTY, oncomplete);
                        }
                    }
                }
                catch (e) {
                    _isOneDs && _warnToConsole(_diagLog, "Failed to send telemetry using sendBeacon API. Ex:" + dumpObj(e));
                    _doOnComplete(oncomplete, _isOneDs ? 0 : 400, {}, STR_EMPTY);
                }
                return;
            }
            function _xhrSender(payload, oncomplete, sync) {
                var thePromise;
                var resolveFunc;
                var rejectFunc;
                var headers = payload[_DYN_HEADERS ] || {};
                if (!sync && _enableSendPromise) {
                    thePromise = createPromise(function (resolve, reject) {
                        resolveFunc = resolve;
                        rejectFunc = reject;
                    });
                }
                if (_isOneDs && sync && payload.disableXhrSync) {
                    sync = false;
                }
                var endPointUrl = payload[_DYN_URL_STRING ];
                if (!endPointUrl) {
                    _onNoPayloadUrl(oncomplete);
                    resolveFunc && resolveFunc(false);
                    return;
                }
                var xhr = openXhr(STR_POST_METHOD, endPointUrl, _sendCredentials, true, sync, payload[_DYN_TIMEOUT ]);
                if (!_isOneDs) {
                    xhr.setRequestHeader("Content-type", "application/json");
                }
                arrForEach(objKeys(headers), function (headerName) {
                    xhr.setRequestHeader(headerName, headers[headerName]);
                });
                xhr.onreadystatechange = function () {
                    if (!_isOneDs) {
                        _doOnReadyFunc(xhr);
                        if (xhr.readyState === 4) {
                            resolveFunc && resolveFunc(true);
                        }
                    }
                };
                xhr.onload = function () {
                    if (_isOneDs) {
                        _doOnReadyFunc(xhr);
                    }
                };
                function _doOnReadyFunc(xhr) {
                    var onReadyFunc = _onCompleteFuncs && _onCompleteFuncs.xhrOnComplete;
                    var onReadyFuncExist = onReadyFunc && isFunction(onReadyFunc);
                    if (onReadyFuncExist) {
                        onReadyFunc(xhr, oncomplete, payload);
                    }
                    else {
                        var response = getResponseText(xhr);
                        _doOnComplete(oncomplete, xhr[_DYN_STATUS ], _getAllResponseHeaders(xhr, _isOneDs), response);
                    }
                }
                xhr.onerror = function (event) {
                    _doOnComplete(oncomplete, _isOneDs ? xhr[_DYN_STATUS ] : 400, _getAllResponseHeaders(xhr, _isOneDs), _isOneDs ? STR_EMPTY : formatErrorMessageXhr(xhr));
                    rejectFunc && rejectFunc(event);
                };
                xhr.ontimeout = function () {
                    _doOnComplete(oncomplete, _isOneDs ? xhr[_DYN_STATUS ] : 500, _getAllResponseHeaders(xhr, _isOneDs), _isOneDs ? STR_EMPTY : formatErrorMessageXhr(xhr));
                    resolveFunc && resolveFunc(false);
                };
                xhr.send(payload[_DYN_DATA$1 ]);
                return thePromise;
            }
            function _doFetchSender(payload, oncomplete, sync) {
                var _a;
                var endPointUrl = payload[_DYN_URL_STRING ];
                var batch = payload[_DYN_DATA$1 ];
                var plainTextBatch = _isOneDs ? batch : new Blob([batch], { type: "application/json" });
                var thePromise;
                var resolveFunc;
                var rejectFunc;
                var requestHeaders = new Headers();
                var batchLength = batch[_DYN_LENGTH$2 ];
                var ignoreResponse = false;
                var responseHandled = false;
                var headers = payload[_DYN_HEADERS ] || {};
                var init = (_a = {
                        method: STR_POST_METHOD,
                        body: plainTextBatch
                    },
                    _a[DisabledPropertyName] = true
                ,
                    _a);
                if (payload.headers && objKeys(payload.headers)[_DYN_LENGTH$2 ] > 0) {
                    arrForEach(objKeys(headers), function (headerName) {
                        requestHeaders.append(headerName, headers[headerName]);
                    });
                    init[_DYN_HEADERS ] = requestHeaders;
                }
                if (_fetchCredentials) {
                    init.credentials = _fetchCredentials;
                }
                else if (_sendCredentials && _isOneDs) {
                    init.credentials = "include";
                }
                if (sync) {
                    init.keepalive = true;
                    _syncFetchPayload += batchLength;
                    if (_isOneDs) {
                        if (payload["_sendReason"] === 2 ) {
                            ignoreResponse = true;
                            if (_addNoResponse) {
                                endPointUrl += _noResponseQs;
                            }
                        }
                    }
                    else {
                        ignoreResponse = true;
                    }
                }
                var request = new Request(endPointUrl, init);
                try {
                    request[DisabledPropertyName] = true;
                }
                catch (e) {
                }
                if (!sync && _enableSendPromise) {
                    thePromise = createPromise(function (resolve, reject) {
                        resolveFunc = resolve;
                        rejectFunc = reject;
                    });
                }
                if (!endPointUrl) {
                    _onNoPayloadUrl(oncomplete);
                    resolveFunc && resolveFunc(false);
                    return;
                }
                function _handleError(res, statusCode) {
                    if (statusCode) {
                        _doOnComplete(oncomplete, _isOneDs ? 0 : statusCode, {}, _isOneDs ? STR_EMPTY : res);
                    }
                    else {
                        _doOnComplete(oncomplete, _isOneDs ? 0 : 400, {}, _isOneDs ? STR_EMPTY : res);
                    }
                }
                function _onFetchComplete(response, payload, value) {
                    var status = response[_DYN_STATUS ];
                    var onCompleteFunc = _onCompleteFuncs.fetchOnComplete;
                    if (onCompleteFunc && isFunction(onCompleteFunc)) {
                        onCompleteFunc(response, oncomplete, value || STR_EMPTY, payload);
                    }
                    else {
                        _doOnComplete(oncomplete, status, {}, value || STR_EMPTY);
                    }
                }
                try {
                    doAwaitResponse(fetch(_isOneDs ? endPointUrl : request, _isOneDs ? init : null), function (result) {
                        if (sync) {
                            _syncFetchPayload -= batchLength;
                            batchLength = 0;
                        }
                        if (!responseHandled) {
                            responseHandled = true;
                            if (!result.rejected) {
                                var response_1 = result[_DYN_VALUE ];
                                try {
                                    if (!_isOneDs && !response_1.ok) {
                                        if (response_1[_DYN_STATUS ]) {
                                            _handleError(response_1.statusText, response_1[_DYN_STATUS ]);
                                        }
                                        else {
                                            _handleError(response_1.statusText, 499);
                                        }
                                        resolveFunc && resolveFunc(false);
                                    }
                                    else {
                                        if (_isOneDs && !response_1.body) {
                                            _onFetchComplete(response_1, null, STR_EMPTY);
                                            resolveFunc && resolveFunc(true);
                                        }
                                        else {
                                            doAwaitResponse(response_1.text(), function (resp) {
                                                _onFetchComplete(response_1, payload, resp[_DYN_VALUE ]);
                                                resolveFunc && resolveFunc(true);
                                            });
                                        }
                                    }
                                }
                                catch (e) {
                                    if (response_1 && response_1[_DYN_STATUS ]) {
                                        _handleError(dumpObj(e), response_1[_DYN_STATUS ]);
                                    }
                                    else {
                                        _handleError(dumpObj(e), 499);
                                    }
                                    rejectFunc && rejectFunc(e);
                                }
                            }
                            else {
                                _handleError(result.reason && result.reason[_DYN_MESSAGE$1 ], 499);
                                rejectFunc && rejectFunc(result.reason);
                            }
                        }
                    });
                }
                catch (e) {
                    if (!responseHandled) {
                        _handleError(dumpObj(e), 499);
                        rejectFunc && rejectFunc(e);
                    }
                }
                if (ignoreResponse && !responseHandled) {
                    responseHandled = true;
                    _doOnComplete(oncomplete, 200, {});
                    resolveFunc && resolveFunc(true);
                }
                if (_isOneDs && !responseHandled && payload[_DYN_TIMEOUT ] > 0) {
                    _timeoutWrapper && _timeoutWrapper.set(function () {
                        if (!responseHandled) {
                            responseHandled = true;
                            _doOnComplete(oncomplete, 500, {});
                            resolveFunc && resolveFunc(true);
                        }
                    }, payload[_DYN_TIMEOUT ]);
                }
                return thePromise;
            }
            function _xdrSender(payload, oncomplete, sync) {
                var _window = getWindow();
                var xdr = new XDomainRequest();
                var data = payload[_DYN_DATA$1 ];
                xdr.onload = function () {
                    var response = getResponseText(xdr);
                    var onloadFunc = _onCompleteFuncs && _onCompleteFuncs.xdrOnComplete;
                    if (onloadFunc && isFunction(onloadFunc)) {
                        onloadFunc(xdr, oncomplete, payload);
                    }
                    else {
                        _doOnComplete(oncomplete, 200, {}, response);
                    }
                };
                xdr.onerror = function () {
                    _doOnComplete(oncomplete, 400, {}, _isOneDs ? STR_EMPTY : formatErrorMessageXdr(xdr));
                };
                xdr.ontimeout = function () {
                    _doOnComplete(oncomplete, 500, {});
                };
                xdr.onprogress = function () { };
                var hostingProtocol = _window && _window.location && _window.location.protocol || "";
                var endpoint = payload[_DYN_URL_STRING ];
                if (!endpoint) {
                    _onNoPayloadUrl(oncomplete);
                    return;
                }
                if (!_isOneDs && endpoint.lastIndexOf(hostingProtocol, 0) !== 0) {
                    var msg = "Cannot send XDomain request. The endpoint URL protocol doesn't match the hosting page protocol.";
                    _throwInternal(_diagLog, 2 , 40 , ". " + msg);
                    _onError(msg, oncomplete);
                    return;
                }
                var endpointUrl = _isOneDs ? endpoint : endpoint[_DYN_REPLACE ](/^(https?:)/, "");
                xdr.open(STR_POST_METHOD, endpointUrl);
                if (payload[_DYN_TIMEOUT ]) {
                    xdr[_DYN_TIMEOUT ] = payload[_DYN_TIMEOUT ];
                }
                xdr.send(data);
                if (_isOneDs && sync) {
                    _timeoutWrapper && _timeoutWrapper.set(function () {
                        xdr.send(data);
                    }, 0);
                }
                else {
                    xdr.send(data);
                }
            }
            function _initDefaults() {
                _syncFetchPayload = 0;
                _isInitialized = false;
                _enableSendPromise = false;
                _diagLog = null;
                _isOneDs = null;
                _onCompleteFuncs = null;
                _disableCredentials = null;
                _fetchCredentials = null;
                _fallbackInst = null;
                _disableXhr = false;
                _disableBeacon = false;
                _disableBeaconSync = false;
                _disableFetchKeepAlive = false;
                _addNoResponse = false;
                _timeoutWrapper = null;
            }
        });
    }
    SenderPostManager.__ieDyn=1;
    return SenderPostManager;
}());

var strOnPrefix = "on";
var strAttachEvent = "attachEvent";
var strAddEventHelper = "addEventListener";
var strDetachEvent = "detachEvent";
var strRemoveEventListener = "removeEventListener";
var strEvents = "events";
createUniqueNamespace("aiEvtPageHide");
createUniqueNamespace("aiEvtPageShow");
var rRemoveEmptyNs = /\.[\.]+/g;
var rRemoveTrailingEmptyNs = /[\.]+$/;
var _guid = 1;
var elmNodeData = createElmNodeData("events");
var eventNamespace = /^([^.]*)(?:\.(.+)|)/;
function _normalizeNamespace(name) {
    if (name && name[_DYN_REPLACE ]) {
        return name[_DYN_REPLACE ](/^[\s\.]+|(?=[\s\.])[\.\s]+$/g, STR_EMPTY$1);
    }
    return name;
}
function _getEvtNamespace(eventName, evtNamespace) {
    if (evtNamespace) {
        var theNamespace_1 = STR_EMPTY$1;
        if (isArray(evtNamespace)) {
            theNamespace_1 = STR_EMPTY$1;
            arrForEach(evtNamespace, function (name) {
                name = _normalizeNamespace(name);
                if (name) {
                    if (name[0] !== ".") {
                        name = "." + name;
                    }
                    theNamespace_1 += name;
                }
            });
        }
        else {
            theNamespace_1 = _normalizeNamespace(evtNamespace);
        }
        if (theNamespace_1) {
            if (theNamespace_1[0] !== ".") {
                theNamespace_1 = "." + theNamespace_1;
            }
            eventName = (eventName || STR_EMPTY$1) + theNamespace_1;
        }
    }
    var parsedEvent = (eventNamespace.exec(eventName || STR_EMPTY$1) || []);
    return {
        type: parsedEvent[1],
        ns: ((parsedEvent[2] || STR_EMPTY$1).replace(rRemoveEmptyNs, ".").replace(rRemoveTrailingEmptyNs, STR_EMPTY$1)[_DYN_SPLIT$1 ](".").sort()).join(".")
    };
}
function _getRegisteredEvents(target, evtName, addDefault) {
    if (addDefault === void 0) { addDefault = true; }
    var aiEvts = elmNodeData.get(target, strEvents, {}, addDefault);
    var registeredEvents = aiEvts[evtName];
    if (!registeredEvents) {
        registeredEvents = aiEvts[evtName] = [];
    }
    return registeredEvents;
}
function _doDetach(obj, evtName, handlerRef, useCapture) {
    if (obj && evtName && evtName[_DYN_TYPE ]) {
        if (obj[strRemoveEventListener]) {
            obj[strRemoveEventListener](evtName[_DYN_TYPE ], handlerRef, useCapture);
        }
        else if (obj[strDetachEvent]) {
            obj[strDetachEvent](strOnPrefix + evtName[_DYN_TYPE ], handlerRef);
        }
    }
}
function _doAttach(obj, evtName, handlerRef, useCapture) {
    var result = false;
    if (obj && evtName && evtName[_DYN_TYPE ] && handlerRef) {
        if (obj[strAddEventHelper]) {
            obj[strAddEventHelper](evtName[_DYN_TYPE ], handlerRef, useCapture);
            result = true;
        }
        else if (obj[strAttachEvent]) {
            obj[strAttachEvent](strOnPrefix + evtName[_DYN_TYPE ], handlerRef);
            result = true;
        }
    }
    return result;
}
function _doUnregister(target, events, evtName, unRegFn) {
    var idx = events[_DYN_LENGTH$2 ];
    while (idx--) {
        var theEvent = events[idx];
        if (theEvent) {
            if (!evtName.ns || evtName.ns === theEvent[_DYN_EVT_NAME ].ns) {
                if (!unRegFn || unRegFn(theEvent)) {
                    _doDetach(target, theEvent[_DYN_EVT_NAME ], theEvent.handler, theEvent.capture);
                    events[_DYN_SPLICE ](idx, 1);
                }
            }
        }
    }
}
function _unregisterEvents(target, evtName, unRegFn) {
    if (evtName[_DYN_TYPE ]) {
        _doUnregister(target, _getRegisteredEvents(target, evtName[_DYN_TYPE ]), evtName, unRegFn);
    }
    else {
        var eventCache = elmNodeData.get(target, strEvents, {});
        objForEachKey(eventCache, function (evtType, events) {
            _doUnregister(target, events, evtName, unRegFn);
        });
        if (objKeys(eventCache)[_DYN_LENGTH$2 ] === 0) {
            elmNodeData.kill(target, strEvents);
        }
    }
}
function mergeEvtNamespace(theNamespace, namespaces) {
    var newNamespaces;
    if (namespaces) {
        if (isArray(namespaces)) {
            newNamespaces = [theNamespace].concat(namespaces);
        }
        else {
            newNamespaces = [theNamespace, namespaces];
        }
        newNamespaces = (_getEvtNamespace("xx", newNamespaces).ns)[_DYN_SPLIT$1 ](".");
    }
    else {
        newNamespaces = theNamespace;
    }
    return newNamespaces;
}
function eventOn(target, eventName, handlerRef, evtNamespace, useCapture) {
    if (useCapture === void 0) { useCapture = false; }
    var result = false;
    if (target) {
        try {
            var evtName = _getEvtNamespace(eventName, evtNamespace);
            result = _doAttach(target, evtName, handlerRef, useCapture);
            if (result && elmNodeData.accept(target)) {
                var registeredEvent = {
                    guid: _guid++,
                    evtName: evtName,
                    handler: handlerRef,
                    capture: useCapture
                };
                _getRegisteredEvents(target, evtName.type)[_DYN_PUSH$1 ](registeredEvent);
            }
        }
        catch (e) {
        }
    }
    return result;
}
function eventOff(target, eventName, handlerRef, evtNamespace, useCapture) {
    if (useCapture === void 0) { useCapture = false; }
    if (target) {
        try {
            var evtName_1 = _getEvtNamespace(eventName, evtNamespace);
            var found_1 = false;
            _unregisterEvents(target, evtName_1, function (regEvent) {
                if ((evtName_1.ns && !handlerRef) || regEvent.handler === handlerRef) {
                    found_1 = true;
                    return true;
                }
                return false;
            });
            if (!found_1) {
                _doDetach(target, evtName_1, handlerRef, useCapture);
            }
        }
        catch (e) {
        }
    }
}

var SampleRate = "sampleRate";
var ProcessLegacy = "ProcessLegacy";
var HttpMethod = "http.method";
var DEFAULT_BREEZE_ENDPOINT = "https://dc.services.visualstudio.com";
var DEFAULT_BREEZE_PATH = "/v2/track";
var strNotSpecified = "not_specified";

var RequestHeaders = ( /* @__PURE__ */createValueMap({
    requestContextHeader: [0 , "Request-Context"],
    requestContextTargetKey: [1 , "appId"],
    requestContextAppIdFormat: [2 , "appId=cid-v1:"],
    requestIdHeader: [3 , "Request-Id"],
    traceParentHeader: [4 , "traceparent"],
    traceStateHeader: [5 , "tracestate"],
    sdkContextHeader: [6 , "Sdk-Context"],
    sdkContextHeaderAppIdRequest: [7 , "appId"],
    requestContextHeaderLowerCase: [8 , "request-context"]
}));

var _DYN_SPLIT = "split";
var _DYN_LENGTH$1 = "length";
var _DYN_TO_LOWER_CASE = "toLowerCase";
var _DYN_TO_STRING$1 = "toString";
var _DYN_REMOVE_ITEM = "removeItem";
var _DYN_MESSAGE = "message";
var _DYN_COUNT$1 = "count";
var _DYN_STRINGIFY$1 = "stringify";
var _DYN_PATHNAME = "pathname";
var _DYN_MATCH = "match";
var _DYN_NAME$1 = "name";
var _DYN_PROPERTIES = "properties";
var _DYN_MEASUREMENTS$1 = "measurements";
var _DYN_SIZE_IN_BYTES = "sizeInBytes";
var _DYN_TYPE_NAME = "typeName";
var _DYN_EXCEPTIONS = "exceptions";
var _DYN_SEVERITY_LEVEL = "severityLevel";
var _DYN_PROBLEM_GROUP = "problemGroup";
var _DYN_PARSED_STACK = "parsedStack";
var _DYN_HAS_FULL_STACK = "hasFullStack";
var _DYN_ASSEMBLY = "assembly";
var _DYN_FILE_NAME = "fileName";
var _DYN_LINE = "line";
var _DYN_AI_DATA_CONTRACT = "aiDataContract";
var _DYN_DURATION = "duration";

function dataSanitizeKeyAndAddUniqueness(logger, key, map) {
    var origLength = key[_DYN_LENGTH$1 ];
    var field = dataSanitizeKey(logger, key);
    if (field[_DYN_LENGTH$1 ] !== origLength) {
        var i = 0;
        var uniqueField = field;
        while (map[uniqueField] !== undefined) {
            i++;
            uniqueField = strSubstring(field, 0, 150  - 3) + dsPadNumber(i);
        }
        field = uniqueField;
    }
    return field;
}
function dataSanitizeKey(logger, name) {
    var nameTrunc;
    if (name) {
        name = strTrim(asString(name));
        if (name[_DYN_LENGTH$1 ] > 150 ) {
            nameTrunc = strSubstring(name, 0, 150 );
            _throwInternal(logger, 2 , 57 , "name is too long.  It has been truncated to " + 150  + " characters.", { name: name }, true);
        }
    }
    return nameTrunc || name;
}
function dataSanitizeString(logger, value, maxLength) {
    if (maxLength === void 0) { maxLength = 1024 ; }
    var valueTrunc;
    if (value) {
        maxLength = maxLength ? maxLength : 1024 ;
        value = strTrim(asString(value));
        if (value[_DYN_LENGTH$1 ] > maxLength) {
            valueTrunc = strSubstring(value, 0, maxLength);
            _throwInternal(logger, 2 , 61 , "string value is too long. It has been truncated to " + maxLength + " characters.", { value: value }, true);
        }
    }
    return valueTrunc || value;
}
function dataSanitizeUrl(logger, url, config) {
    if (isString(url)) {
        url = fieldRedaction(url, config);
    }
    return dataSanitizeInput(logger, url, 2048 , 66 );
}
function dataSanitizeMessage(logger, message) {
    var messageTrunc;
    if (message) {
        if (message[_DYN_LENGTH$1 ] > 32768 ) {
            messageTrunc = strSubstring(message, 0, 32768 );
            _throwInternal(logger, 2 , 56 , "message is too long, it has been truncated to " + 32768  + " characters.", { message: message }, true);
        }
    }
    return messageTrunc || message;
}
function dataSanitizeException(logger, exception) {
    var exceptionTrunc;
    if (exception) {
        var value = "" + exception;
        if (value[_DYN_LENGTH$1 ] > 32768 ) {
            exceptionTrunc = strSubstring(value, 0, 32768 );
            _throwInternal(logger, 2 , 52 , "exception is too long, it has been truncated to " + 32768  + " characters.", { exception: exception }, true);
        }
    }
    return exceptionTrunc || exception;
}
function dataSanitizeProperties(logger, properties) {
    if (properties) {
        var tempProps_1 = {};
        objForEachKey(properties, function (prop, value) {
            if (isObject(value) && hasJSON()) {
                try {
                    value = getJSON()[_DYN_STRINGIFY$1 ](value);
                }
                catch (e) {
                    _throwInternal(logger, 2 , 49 , "custom property is not valid", { exception: e }, true);
                }
            }
            value = dataSanitizeString(logger, value, 8192 );
            prop = dataSanitizeKeyAndAddUniqueness(logger, prop, tempProps_1);
            tempProps_1[prop] = value;
        });
        properties = tempProps_1;
    }
    return properties;
}
function dataSanitizeMeasurements(logger, measurements) {
    if (measurements) {
        var tempMeasurements_1 = {};
        objForEachKey(measurements, function (measure, value) {
            measure = dataSanitizeKeyAndAddUniqueness(logger, measure, tempMeasurements_1);
            tempMeasurements_1[measure] = value;
        });
        measurements = tempMeasurements_1;
    }
    return measurements;
}
function dataSanitizeId(logger, id) {
    return id ? dataSanitizeInput(logger, id, 128 , 69 )[_DYN_TO_STRING$1 ]() : id;
}
function dataSanitizeInput(logger, input, maxLength, _msgId) {
    var inputTrunc;
    if (input) {
        input = strTrim(asString(input));
        if (input[_DYN_LENGTH$1 ] > maxLength) {
            inputTrunc = strSubstring(input, 0, maxLength);
            _throwInternal(logger, 2 , _msgId, "input is too long, it has been truncated to " + maxLength + " characters.", { data: input }, true);
        }
    }
    return inputTrunc || input;
}
function dsPadNumber(num) {
    var s = "00" + num;
    return strSubstr(s, s[_DYN_LENGTH$1 ] - 3);
}

var _document = getDocument() || {};
var _htmlAnchorIdx = 0;
var _htmlAnchorElement = [null, null, null, null, null];
function urlParseUrl(url) {
    var anchorIdx = _htmlAnchorIdx;
    var anchorCache = _htmlAnchorElement;
    var tempAnchor = anchorCache[anchorIdx];
    if (!_document.createElement) {
        tempAnchor = { host: urlParseHost(url, true) };
    }
    else if (!anchorCache[anchorIdx]) {
        tempAnchor = anchorCache[anchorIdx] = _document.createElement("a");
    }
    tempAnchor.href = url;
    anchorIdx++;
    if (anchorIdx >= anchorCache[_DYN_LENGTH$1 ]) {
        anchorIdx = 0;
    }
    _htmlAnchorIdx = anchorIdx;
    return tempAnchor;
}
function urlParseHost(url, inclPort) {
    var fullHost = urlParseFullHost(url, inclPort) || "";
    if (fullHost) {
        var match = fullHost[_DYN_MATCH ](/(www\d{0,5}\.)?([^\/:]{1,256})(:\d{1,20})?/i);
        if (match != null && match[_DYN_LENGTH$1 ] > 3 && isString(match[2]) && match[2][_DYN_LENGTH$1 ] > 0) {
            return match[2] + (match[3] || "");
        }
    }
    return fullHost;
}
function urlParseFullHost(url, inclPort) {
    var result = null;
    if (url) {
        var match = url[_DYN_MATCH ](/(\w{1,150}):\/\/([^\/:]{1,256})(:\d{1,20})?/i);
        if (match != null && match[_DYN_LENGTH$1 ] > 2 && isString(match[2]) && match[2][_DYN_LENGTH$1 ] > 0) {
            result = match[2] || "";
            if (inclPort && match[_DYN_LENGTH$1 ] > 2) {
                var protocol = (match[1] || "")[_DYN_TO_LOWER_CASE ]();
                var port = match[3] || "";
                if (protocol === "http" && port === ":80") {
                    port = "";
                }
                else if (protocol === "https" && port === ":443") {
                    port = "";
                }
                result += port;
            }
        }
    }
    return result;
}

var _internalEndpoints = [
    DEFAULT_BREEZE_ENDPOINT + DEFAULT_BREEZE_PATH,
    "https://breeze.aimon.applicationinsights.io" + DEFAULT_BREEZE_PATH,
    "https://dc-int.services.visualstudio.com" + DEFAULT_BREEZE_PATH
];
function isInternalApplicationInsightsEndpoint(endpointUrl) {
    return arrIndexOf(_internalEndpoints, endpointUrl[_DYN_TO_LOWER_CASE ]()) !== -1;
}
function AjaxHelperParseDependencyPath(logger, absoluteUrl, method, commandName) {
    var target, name = commandName, data = commandName;
    if (absoluteUrl && absoluteUrl[_DYN_LENGTH$1 ] > 0) {
        var parsedUrl = urlParseUrl(absoluteUrl);
        target = parsedUrl.host;
        if (!name) {
            if (parsedUrl[_DYN_PATHNAME ] != null) {
                var pathName = (parsedUrl.pathname[_DYN_LENGTH$1 ] === 0) ? "/" : parsedUrl[_DYN_PATHNAME ];
                if (pathName.charAt(0) !== "/") {
                    pathName = "/" + pathName;
                }
                data = parsedUrl[_DYN_PATHNAME ];
                name = dataSanitizeString(logger, method ? method + " " + pathName : pathName);
            }
            else {
                name = dataSanitizeString(logger, absoluteUrl);
            }
        }
    }
    else {
        target = commandName;
        name = commandName;
    }
    return {
        target: target,
        name: name,
        data: data
    };
}

var StorageType = ( /* @__PURE__ */createEnumStyle({
    LocalStorage: 0 ,
    SessionStorage: 1
}));

var _canUseSessionStorage = undefined;
var _storagePrefix = "";
function _getVerifiedStorageObject(storageType) {
    try {
        if (isNullOrUndefined(getGlobal())) {
            return null;
        }
        var uid = (new Date)[_DYN_TO_STRING$1 ]();
        var storage = getInst(storageType === StorageType.LocalStorage ? "localStorage" : "sessionStorage");
        var name_1 = _storagePrefix + uid;
        storage.setItem(name_1, uid);
        var fail = storage.getItem(name_1) !== uid;
        storage[_DYN_REMOVE_ITEM ](name_1);
        if (!fail) {
            return storage;
        }
    }
    catch (exception) {
    }
    return null;
}
function _getSessionStorageObject() {
    if (utlCanUseSessionStorage()) {
        return _getVerifiedStorageObject(StorageType.SessionStorage);
    }
    return null;
}
function utlSetStoragePrefix(storagePrefix) {
    _storagePrefix = storagePrefix || "";
}
function utlCanUseSessionStorage(reset) {
    if (reset || _canUseSessionStorage === undefined) {
        _canUseSessionStorage = !!_getVerifiedStorageObject(StorageType.SessionStorage);
    }
    return _canUseSessionStorage;
}
function utlGetSessionStorage(logger, name) {
    var storage = _getSessionStorageObject();
    if (storage !== null) {
        try {
            return storage.getItem(name);
        }
        catch (e) {
            _canUseSessionStorage = false;
            _throwInternal(logger, 2 , 2 , "Browser failed read of session storage. " + getExceptionName(e), { exception: dumpObj(e) });
        }
    }
    return null;
}
function utlSetSessionStorage(logger, name, data) {
    var storage = _getSessionStorageObject();
    if (storage !== null) {
        try {
            storage.setItem(name, data);
            return true;
        }
        catch (e) {
            _canUseSessionStorage = false;
            _throwInternal(logger, 2 , 4 , "Browser failed write to session storage. " + getExceptionName(e), { exception: dumpObj(e) });
        }
    }
    return false;
}
function utlRemoveSessionStorage(logger, name) {
    var storage = _getSessionStorageObject();
    if (storage !== null) {
        try {
            storage[_DYN_REMOVE_ITEM ](name);
            return true;
        }
        catch (e) {
            _canUseSessionStorage = false;
            _throwInternal(logger, 2 , 6 , "Browser failed removal of session storage item. " + getExceptionName(e), { exception: dumpObj(e) });
        }
    }
    return false;
}

var Envelope = /** @class */ (function () {
    function Envelope(logger, data, name) {
        var _this = this;
        var _self = this;
        _self.ver = 1;
        _self.sampleRate = 100.0;
        _self.tags = {};
        _self[_DYN_NAME$1 ] = dataSanitizeString(logger, name) || strNotSpecified;
        _self.data = data;
        _self.time = toISOString(new Date());
        _self[_DYN_AI_DATA_CONTRACT ] = {
            time: 1 ,
            iKey: 1 ,
            name: 1 ,
            sampleRate: function () {
                return (_this.sampleRate === 100) ? 4  : 1 ;
            },
            tags: 1 ,
            data: 1
        };
    }
    return Envelope;
}());

var Event$1 = /** @class */ (function () {
    function Event(logger, name, properties, measurements) {
        this.aiDataContract = {
            ver: 1 ,
            name: 1 ,
            properties: 0 ,
            measurements: 0
        };
        var _self = this;
        _self.ver = 2;
        _self[_DYN_NAME$1 ] = dataSanitizeString(logger, name) || strNotSpecified;
        _self[_DYN_PROPERTIES ] = dataSanitizeProperties(logger, properties);
        _self[_DYN_MEASUREMENTS$1 ] = dataSanitizeMeasurements(logger, measurements);
    }
    Event.envelopeType = "Microsoft.ApplicationInsights.{0}.Event";
    Event.dataType = "EventData";
    return Event;
}());

var STACKFRAME_BASE_SIZE = 58;
var IS_FRAME = /^\s{0,50}(from\s|at\s|Line\s{1,5}\d{1,10}\s{1,5}of|\w{1,50}@\w{1,80}|[^\(\s\n]+:[0-9\?]+(?::[0-9\?]+)?)/;
var FULL_STACK_FRAME_1 = /^(?:\s{0,50}at)?\s{0,50}([^\@\()\s]+)?\s{0,50}(?:\s|\@|\()\s{0,5}([^\(\s\n\]]+):([0-9\?]+):([0-9\?]+)\)?$/;
var FULL_STACK_FRAME_2 = /^(?:\s{0,50}at)?\s{0,50}([^\@\()\s]+)?\s{0,50}(?:\s|\@|\()\s{0,5}([^\(\s\n\]]+):([0-9\?]+)\)?$/;
var FULL_STACK_FRAME_3 = /^(?:\s{0,50}at)?\s{0,50}([^\@\()\s]+)?\s{0,50}(?:\s|\@|\()\s{0,5}([^\(\s\n\)\]]+)\)?$/;
var EXTRACT_FILENAME = /(?:^|\(|\s{0,10}[\w\)]+\@)?([^\(\n\s\]\)]+)(?:\:([0-9]+)(?:\:([0-9]+))?)?\)?(?:,|$)/;
var PARSE_FILENAME_LINE_COL = /([^\(\s\n]+):([0-9]+):([0-9]+)$/;
var PARSE_FILENAME_LINE_ONLY = /([^\(\s\n]+):([0-9]+)$/;
var NoMethod = "<no_method>";
var strError = "error";
var strStack = "stack";
var strStackDetails = "stackDetails";
var strErrorSrc = "errorSrc";
var strMessage = "message";
var strDescription = "description";
var _parseSequence = [
    { re: FULL_STACK_FRAME_1, len: 5, m: 1, fn: 2, ln: 3, col: 4 },
    { chk: _ignoreNative, pre: _scrubAnonymous, re: FULL_STACK_FRAME_2, len: 4, m: 1, fn: 2, ln: 3 },
    { re: FULL_STACK_FRAME_3, len: 3, m: 1, fn: 2, hdl: _handleFilename },
    { re: EXTRACT_FILENAME, len: 2, fn: 1, hdl: _handleFilename }
];
function _scrubAnonymous(frame) {
    return frame.replace(/(\(anonymous\))/, "<anonymous>");
}
function _ignoreNative(frame) {
    return strIndexOf(frame, "[native") < 0;
}
function _stringify(value, convertToString) {
    var result = value;
    if (result && !isString(result)) {
        if (JSON && JSON[_DYN_STRINGIFY$1 ]) {
            result = JSON[_DYN_STRINGIFY$1 ](value);
            if (convertToString && (!result || result === "{}")) {
                if (isFunction(value[_DYN_TO_STRING$1 ])) {
                    result = value[_DYN_TO_STRING$1 ]();
                }
                else {
                    result = "" + value;
                }
            }
        }
        else {
            result = "" + value + " - (Missing JSON.stringify)";
        }
    }
    return result || "";
}
function _formatMessage(theEvent, errorType) {
    var evtMessage = theEvent;
    if (theEvent) {
        if (evtMessage && !isString(evtMessage)) {
            evtMessage = theEvent[strMessage] || theEvent[strDescription] || evtMessage;
        }
        if (evtMessage && !isString(evtMessage)) {
            evtMessage = _stringify(evtMessage, true);
        }
        if (theEvent["filename"]) {
            evtMessage = evtMessage + " @" + (theEvent["filename"] || "") + ":" + (theEvent["lineno"] || "?") + ":" + (theEvent["colno"] || "?");
        }
    }
    if (errorType && errorType !== "String" && errorType !== "Object" && errorType !== "Error" && strIndexOf(evtMessage || "", errorType) === -1) {
        evtMessage = errorType + ": " + evtMessage;
    }
    return evtMessage || "";
}
function _isExceptionDetailsInternal(value) {
    try {
        if (isObject(value)) {
            return "hasFullStack" in value && "typeName" in value;
        }
    }
    catch (e) {
    }
    return false;
}
function _isExceptionInternal(value) {
    try {
        if (isObject(value)) {
            return ("ver" in value && "exceptions" in value && "properties" in value);
        }
    }
    catch (e) {
    }
    return false;
}
function _isStackDetails(details) {
    return details && details.src && isString(details.src) && details.obj && isArray(details.obj);
}
function _convertStackObj(errorStack) {
    var src = errorStack || "";
    if (!isString(src)) {
        if (isString(src[strStack])) {
            src = src[strStack];
        }
        else {
            src = "" + src;
        }
    }
    var items = src[_DYN_SPLIT ]("\n");
    return {
        src: src,
        obj: items
    };
}
function _getOperaStack(errorMessage) {
    var stack = [];
    var lines = errorMessage[_DYN_SPLIT ]("\n");
    for (var lp = 0; lp < lines[_DYN_LENGTH$1 ]; lp++) {
        var entry = lines[lp];
        if (lines[lp + 1]) {
            entry += "@" + lines[lp + 1];
            lp++;
        }
        stack.push(entry);
    }
    return {
        src: errorMessage,
        obj: stack
    };
}
function _getStackFromErrorObj(errorObj) {
    var details = null;
    if (errorObj) {
        try {
            if (errorObj[strStack]) {
                details = _convertStackObj(errorObj[strStack]);
            }
            else if (errorObj[strError] && errorObj[strError][strStack]) {
                details = _convertStackObj(errorObj[strError][strStack]);
            }
            else if (errorObj["exception"] && errorObj.exception[strStack]) {
                details = _convertStackObj(errorObj.exception[strStack]);
            }
            else if (_isStackDetails(errorObj)) {
                details = errorObj;
            }
            else if (_isStackDetails(errorObj[strStackDetails])) {
                details = errorObj[strStackDetails];
            }
            else if (getWindow() && getWindow()["opera"] && errorObj[strMessage]) {
                details = _getOperaStack(errorObj[_DYN_MESSAGE ]);
            }
            else if (errorObj["reason"] && errorObj.reason[strStack]) {
                details = _convertStackObj(errorObj.reason[strStack]);
            }
            else if (isString(errorObj)) {
                details = _convertStackObj(errorObj);
            }
            else {
                var evtMessage = errorObj[strMessage] || errorObj[strDescription] || "";
                if (isString(errorObj[strErrorSrc])) {
                    if (evtMessage) {
                        evtMessage += "\n";
                    }
                    evtMessage += " from " + errorObj[strErrorSrc];
                }
                if (evtMessage) {
                    details = _convertStackObj(evtMessage);
                }
            }
        }
        catch (e) {
            details = _convertStackObj(e);
        }
    }
    return details || {
        src: "",
        obj: null
    };
}
function _formatStackTrace(stackDetails) {
    var stack = "";
    if (stackDetails) {
        if (stackDetails.obj) {
            stack = stackDetails.obj.join("\n");
        }
        else {
            stack = stackDetails.src || "";
        }
    }
    return stack;
}
function _parseStack(stack) {
    var parsedStack;
    var frames = stack.obj;
    if (frames && frames[_DYN_LENGTH$1 ] > 0) {
        parsedStack = [];
        var level_1 = 0;
        var foundStackStart_1 = false;
        var totalSizeInBytes_1 = 0;
        arrForEach(frames, function (frame) {
            if (foundStackStart_1 || _isStackFrame(frame)) {
                var theFrame = asString(frame);
                foundStackStart_1 = true;
                var parsedFrame = _extractStackFrame(theFrame, level_1);
                if (parsedFrame) {
                    totalSizeInBytes_1 += parsedFrame[_DYN_SIZE_IN_BYTES ];
                    parsedStack.push(parsedFrame);
                    level_1++;
                }
            }
        });
        var exceptionParsedStackThreshold = 32 * 1024;
        if (totalSizeInBytes_1 > exceptionParsedStackThreshold) {
            var left = 0;
            var right = parsedStack[_DYN_LENGTH$1 ] - 1;
            var size = 0;
            var acceptedLeft = left;
            var acceptedRight = right;
            while (left < right) {
                var lSize = parsedStack[left][_DYN_SIZE_IN_BYTES ];
                var rSize = parsedStack[right][_DYN_SIZE_IN_BYTES ];
                size += lSize + rSize;
                if (size > exceptionParsedStackThreshold) {
                    var howMany = acceptedRight - acceptedLeft + 1;
                    parsedStack.splice(acceptedLeft, howMany);
                    break;
                }
                acceptedLeft = left;
                acceptedRight = right;
                left++;
                right--;
            }
        }
    }
    return parsedStack;
}
function _getErrorType(errorType) {
    var typeName = "";
    if (errorType) {
        typeName = errorType.typeName || errorType[_DYN_NAME$1 ] || "";
        if (!typeName) {
            try {
                var funcNameRegex = /function (.{1,200})\(/;
                var results = (funcNameRegex).exec((errorType).constructor[_DYN_TO_STRING$1 ]());
                typeName = (results && results[_DYN_LENGTH$1 ] > 1) ? results[1] : "";
            }
            catch (e) {
            }
        }
    }
    return typeName;
}
function _formatErrorCode(errorObj) {
    if (errorObj) {
        try {
            if (!isString(errorObj)) {
                var errorType = _getErrorType(errorObj);
                var result = _stringify(errorObj, false);
                if (!result || result === "{}") {
                    if (errorObj[strError]) {
                        errorObj = errorObj[strError];
                        errorType = _getErrorType(errorObj);
                    }
                    result = _stringify(errorObj, true);
                }
                if (strIndexOf(result, errorType) !== 0 && errorType !== "String") {
                    return errorType + ":" + result;
                }
                return result;
            }
        }
        catch (e) {
        }
    }
    return "" + (errorObj || "");
}
var Exception = /** @class */ (function () {
    function Exception(logger, exception, properties, measurements, severityLevel, id) {
        this.aiDataContract = {
            ver: 1 ,
            exceptions: 1 ,
            severityLevel: 0 ,
            properties: 0 ,
            measurements: 0
        };
        var _self = this;
        _self.ver = 2;
        if (!_isExceptionInternal(exception)) {
            if (!properties) {
                properties = {};
            }
            if (id) {
                properties.id = id;
            }
            _self[_DYN_EXCEPTIONS ] = [_createExceptionDetails(logger, exception, properties)];
            _self[_DYN_PROPERTIES ] = dataSanitizeProperties(logger, properties);
            _self[_DYN_MEASUREMENTS$1 ] = dataSanitizeMeasurements(logger, measurements);
            if (severityLevel) {
                _self[_DYN_SEVERITY_LEVEL ] = severityLevel;
            }
            if (id) {
                _self.id = id;
            }
        }
        else {
            _self[_DYN_EXCEPTIONS ] = exception[_DYN_EXCEPTIONS ] || [];
            _self[_DYN_PROPERTIES ] = exception[_DYN_PROPERTIES ];
            _self[_DYN_MEASUREMENTS$1 ] = exception[_DYN_MEASUREMENTS$1 ];
            if (exception[_DYN_SEVERITY_LEVEL ]) {
                _self[_DYN_SEVERITY_LEVEL ] = exception[_DYN_SEVERITY_LEVEL ];
            }
            if (exception.id) {
                _self.id = exception.id;
                exception[_DYN_PROPERTIES ].id = exception.id;
            }
            if (exception[_DYN_PROBLEM_GROUP ]) {
                _self[_DYN_PROBLEM_GROUP ] = exception[_DYN_PROBLEM_GROUP ];
            }
            if (!isNullOrUndefined(exception.isManual)) {
                _self.isManual = exception.isManual;
            }
        }
    }
    Exception.CreateAutoException = function (message, url, lineNumber, columnNumber, error, evt, stack, errorSrc) {
        var errorType = _getErrorType(error || evt || message);
        return {
            message: _formatMessage(message, errorType),
            url: url,
            lineNumber: lineNumber,
            columnNumber: columnNumber,
            error: _formatErrorCode(error || evt || message),
            evt: _formatErrorCode(evt || message),
            typeName: errorType,
            stackDetails: _getStackFromErrorObj(stack || error || evt),
            errorSrc: errorSrc
        };
    };
    Exception.CreateFromInterface = function (logger, exception, properties, measurements) {
        var exceptions = exception[_DYN_EXCEPTIONS ]
            && arrMap(exception[_DYN_EXCEPTIONS ], function (ex) { return _createExDetailsFromInterface(logger, ex); });
        var exceptionData = new Exception(logger, __assignFn(__assignFn({}, exception), { exceptions: exceptions }), properties, measurements);
        return exceptionData;
    };
    Exception.prototype.toInterface = function () {
        var _a = this, exceptions = _a.exceptions, properties = _a.properties, measurements = _a.measurements, severityLevel = _a.severityLevel, problemGroup = _a.problemGroup, id = _a.id, isManual = _a.isManual;
        var exceptionDetailsInterface = exceptions instanceof Array
            && arrMap(exceptions, function (exception) { return exception.toInterface(); })
            || undefined;
        return {
            ver: "4.0",
            exceptions: exceptionDetailsInterface,
            severityLevel: severityLevel,
            properties: properties,
            measurements: measurements,
            problemGroup: problemGroup,
            id: id,
            isManual: isManual
        };
    };
    Exception.CreateSimpleException = function (message, typeName, assembly, fileName, details, line) {
        var _a;
        return {
            exceptions: [
                (_a = {},
                    _a[_DYN_HAS_FULL_STACK ] = true,
                    _a.message = message,
                    _a.stack = details,
                    _a.typeName = typeName,
                    _a)
            ]
        };
    };
    Exception.envelopeType = "Microsoft.ApplicationInsights.{0}.Exception";
    Exception.dataType = "ExceptionData";
    Exception.formatError = _formatErrorCode;
    return Exception;
}());
var exDetailsAiDataContract = objFreeze({
    id: 0 ,
    outerId: 0 ,
    typeName: 1 ,
    message: 1 ,
    hasFullStack: 0 ,
    stack: 0 ,
    parsedStack: 2
});
function _toInterface() {
    var _self = this;
    var parsedStack = isArray(_self[_DYN_PARSED_STACK ])
        && arrMap(_self[_DYN_PARSED_STACK ], function (frame) { return _parsedFrameToInterface(frame); });
    var exceptionDetailsInterface = {
        id: _self.id,
        outerId: _self.outerId,
        typeName: _self[_DYN_TYPE_NAME ],
        message: _self[_DYN_MESSAGE ],
        hasFullStack: _self[_DYN_HAS_FULL_STACK ],
        stack: _self[strStack],
        parsedStack: parsedStack || undefined
    };
    return exceptionDetailsInterface;
}
function _createExceptionDetails(logger, exception, properties) {
    var _a;
    var id;
    var outerId;
    var typeName;
    var message;
    var hasFullStack;
    var theStack;
    var parsedStack;
    if (!_isExceptionDetailsInternal(exception)) {
        var error = exception;
        var evt = error && error.evt;
        if (!isError(error)) {
            error = error[strError] || evt || error;
        }
        typeName = dataSanitizeString(logger, _getErrorType(error)) || strNotSpecified;
        message = dataSanitizeMessage(logger, _formatMessage(exception || error, typeName)) || strNotSpecified;
        var stack = exception[strStackDetails] || _getStackFromErrorObj(exception);
        parsedStack = _parseStack(stack);
        if (isArray(parsedStack)) {
            arrMap(parsedStack, function (frame) {
                frame[_DYN_ASSEMBLY ] = dataSanitizeString(logger, frame[_DYN_ASSEMBLY ]);
                frame[_DYN_FILE_NAME ] = dataSanitizeString(logger, frame[_DYN_FILE_NAME ]);
            });
        }
        theStack = dataSanitizeException(logger, _formatStackTrace(stack));
        hasFullStack = isArray(parsedStack) && parsedStack[_DYN_LENGTH$1 ] > 0;
        if (properties) {
            properties[_DYN_TYPE_NAME ] = properties[_DYN_TYPE_NAME ] || typeName;
        }
    }
    else {
        typeName = exception[_DYN_TYPE_NAME ];
        message = exception[_DYN_MESSAGE ];
        theStack = exception[strStack];
        parsedStack = exception[_DYN_PARSED_STACK ] || [];
        hasFullStack = exception[_DYN_HAS_FULL_STACK ];
    }
    return _a = {},
        _a[_DYN_AI_DATA_CONTRACT ] = exDetailsAiDataContract,
        _a.id = id,
        _a.outerId = outerId,
        _a.typeName = typeName,
        _a.message = message,
        _a[_DYN_HAS_FULL_STACK ] = hasFullStack,
        _a.stack = theStack,
        _a.parsedStack = parsedStack,
        _a.toInterface = _toInterface,
        _a;
}
function _createExDetailsFromInterface(logger, exception) {
    var parsedStack = (isArray(exception[_DYN_PARSED_STACK ])
        && arrMap(exception[_DYN_PARSED_STACK ], function (frame) { return _stackFrameFromInterface(frame); }))
        || exception[_DYN_PARSED_STACK ];
    var exceptionDetails = _createExceptionDetails(logger, __assignFn(__assignFn({}, exception), { parsedStack: parsedStack }));
    return exceptionDetails;
}
function _parseFilename(theFrame, fileName) {
    var lineCol = fileName[_DYN_MATCH ](PARSE_FILENAME_LINE_COL);
    if (lineCol && lineCol[_DYN_LENGTH$1 ] >= 4) {
        theFrame[_DYN_FILE_NAME ] = lineCol[1];
        theFrame[_DYN_LINE ] = parseInt(lineCol[2]);
    }
    else {
        var lineNo = fileName[_DYN_MATCH ](PARSE_FILENAME_LINE_ONLY);
        if (lineNo && lineNo[_DYN_LENGTH$1 ] >= 3) {
            theFrame[_DYN_FILE_NAME ] = lineNo[1];
            theFrame[_DYN_LINE ] = parseInt(lineNo[2]);
        }
        else {
            theFrame[_DYN_FILE_NAME ] = fileName;
        }
    }
}
function _handleFilename(theFrame, sequence, matches) {
    var filename = theFrame[_DYN_FILE_NAME ];
    if (sequence.fn && matches && matches[_DYN_LENGTH$1 ] > sequence.fn) {
        if (sequence.ln && matches[_DYN_LENGTH$1 ] > sequence.ln) {
            filename = strTrim(matches[sequence.fn] || "");
            theFrame[_DYN_LINE ] = parseInt(strTrim(matches[sequence.ln] || "")) || 0;
        }
        else {
            filename = strTrim(matches[sequence.fn] || "");
        }
    }
    if (filename) {
        _parseFilename(theFrame, filename);
    }
}
function _isStackFrame(frame) {
    var result = false;
    if (frame && isString(frame)) {
        var trimmedFrame = strTrim(frame);
        if (trimmedFrame) {
            result = IS_FRAME.test(trimmedFrame);
        }
    }
    return result;
}
var stackFrameAiDataContract = objFreeze({
    level: 1 ,
    method: 1 ,
    assembly: 0 ,
    fileName: 0 ,
    line: 0
});
function _extractStackFrame(frame, level) {
    var _a;
    var theFrame;
    if (frame && isString(frame) && strTrim(frame)) {
        theFrame = (_a = {},
            _a[_DYN_AI_DATA_CONTRACT ] = stackFrameAiDataContract,
            _a.level = level,
            _a.assembly = strTrim(frame),
            _a.method = NoMethod,
            _a.fileName = "",
            _a.line = 0,
            _a.sizeInBytes = 0,
            _a);
        var idx = 0;
        while (idx < _parseSequence[_DYN_LENGTH$1 ]) {
            var sequence = _parseSequence[idx];
            if (sequence.chk && !sequence.chk(frame)) {
                break;
            }
            if (sequence.pre) {
                frame = sequence.pre(frame);
            }
            var matches = frame[_DYN_MATCH ](sequence.re);
            if (matches && matches[_DYN_LENGTH$1 ] >= sequence.len) {
                if (sequence.m) {
                    theFrame.method = strTrim(matches[sequence.m] || NoMethod);
                }
                if (sequence.hdl) {
                    sequence.hdl(theFrame, sequence, matches);
                }
                else if (sequence.fn) {
                    if (sequence.ln) {
                        theFrame[_DYN_FILE_NAME ] = strTrim(matches[sequence.fn] || "");
                        theFrame[_DYN_LINE ] = parseInt(strTrim(matches[sequence.ln] || "")) || 0;
                    }
                    else {
                        _parseFilename(theFrame, matches[sequence.fn] || "");
                    }
                }
                break;
            }
            idx++;
        }
    }
    return _populateFrameSizeInBytes(theFrame);
}
function _stackFrameFromInterface(frame) {
    var _a;
    var parsedFrame = (_a = {},
        _a[_DYN_AI_DATA_CONTRACT ] = stackFrameAiDataContract,
        _a.level = frame.level,
        _a.method = frame.method,
        _a.assembly = frame[_DYN_ASSEMBLY ],
        _a.fileName = frame[_DYN_FILE_NAME ],
        _a.line = frame[_DYN_LINE ],
        _a.sizeInBytes = 0,
        _a);
    return _populateFrameSizeInBytes(parsedFrame);
}
function _populateFrameSizeInBytes(frame) {
    var sizeInBytes = STACKFRAME_BASE_SIZE;
    if (frame) {
        sizeInBytes += frame.method[_DYN_LENGTH$1 ];
        sizeInBytes += frame.assembly[_DYN_LENGTH$1 ];
        sizeInBytes += frame.fileName[_DYN_LENGTH$1 ];
        sizeInBytes += frame.level.toString()[_DYN_LENGTH$1 ];
        sizeInBytes += frame.line.toString()[_DYN_LENGTH$1 ];
        frame[_DYN_SIZE_IN_BYTES ] = sizeInBytes;
    }
    return frame;
}
function _parsedFrameToInterface(frame) {
    return {
        level: frame.level,
        method: frame.method,
        assembly: frame[_DYN_ASSEMBLY ],
        fileName: frame[_DYN_FILE_NAME ],
        line: frame[_DYN_LINE ]
    };
}

var DataPoint = /** @class */ (function () {
    function DataPoint() {
        this.aiDataContract = {
            name: 1 ,
            kind: 0 ,
            value: 1 ,
            count: 0 ,
            min: 0 ,
            max: 0 ,
            stdDev: 0
        };
        this.kind = 0 ;
    }
    return DataPoint;
}());

var Metric = /** @class */ (function () {
    function Metric(logger, name, value, count, min, max, stdDev, properties, measurements) {
        this.aiDataContract = {
            ver: 1 ,
            metrics: 1 ,
            properties: 0
        };
        var _self = this;
        _self.ver = 2;
        var dataPoint = new DataPoint();
        dataPoint[_DYN_COUNT$1 ] = count > 0 ? count : undefined;
        dataPoint.max = isNaN(max) || max === null ? undefined : max;
        dataPoint.min = isNaN(min) || min === null ? undefined : min;
        dataPoint[_DYN_NAME$1 ] = dataSanitizeString(logger, name) || strNotSpecified;
        dataPoint.value = value;
        dataPoint.stdDev = isNaN(stdDev) || stdDev === null ? undefined : stdDev;
        _self.metrics = [dataPoint];
        _self[_DYN_PROPERTIES ] = dataSanitizeProperties(logger, properties);
        _self[_DYN_MEASUREMENTS$1 ] = dataSanitizeMeasurements(logger, measurements);
    }
    Metric.envelopeType = "Microsoft.ApplicationInsights.{0}.Metric";
    Metric.dataType = "MetricData";
    return Metric;
}());

var strEmpty = "";
function msToTimeSpan(totalms) {
    if (isNaN(totalms) || totalms < 0) {
        totalms = 0;
    }
    totalms = mathRound(totalms);
    var ms = strEmpty + totalms % 1000;
    var sec = strEmpty + mathFloor(totalms / 1000) % 60;
    var min = strEmpty + mathFloor(totalms / (1000 * 60)) % 60;
    var hour = strEmpty + mathFloor(totalms / (1000 * 60 * 60)) % 24;
    var days = mathFloor(totalms / (1000 * 60 * 60 * 24));
    ms = ms[_DYN_LENGTH$1 ] === 1 ? "00" + ms : ms[_DYN_LENGTH$1 ] === 2 ? "0" + ms : ms;
    sec = sec[_DYN_LENGTH$1 ] < 2 ? "0" + sec : sec;
    min = min[_DYN_LENGTH$1 ] < 2 ? "0" + min : min;
    hour = hour[_DYN_LENGTH$1 ] < 2 ? "0" + hour : hour;
    return (days > 0 ? days + "." : strEmpty) + hour + ":" + min + ":" + sec + "." + ms;
}

var PageView = /** @class */ (function () {
    function PageView(logger, name, url, durationMs, properties, measurements, id) {
        this.aiDataContract = {
            ver: 1 ,
            name: 0 ,
            url: 0 ,
            duration: 0 ,
            properties: 0 ,
            measurements: 0 ,
            id: 0
        };
        var _self = this;
        _self.ver = 2;
        _self.id = dataSanitizeId(logger, id);
        _self.url = dataSanitizeUrl(logger, url);
        _self[_DYN_NAME$1 ] = dataSanitizeString(logger, name) || strNotSpecified;
        if (!isNaN(durationMs)) {
            _self[_DYN_DURATION ] = msToTimeSpan(durationMs);
        }
        _self[_DYN_PROPERTIES ] = dataSanitizeProperties(logger, properties);
        _self[_DYN_MEASUREMENTS$1 ] = dataSanitizeMeasurements(logger, measurements);
    }
    PageView.envelopeType = "Microsoft.ApplicationInsights.{0}.Pageview";
    PageView.dataType = "PageviewData";
    return PageView;
}());

var RemoteDependencyData = /** @class */ (function () {
    function RemoteDependencyData(logger, id, absoluteUrl, commandName, value, success, resultCode, method, requestAPI, correlationContext, properties, measurements) {
        if (requestAPI === void 0) { requestAPI = "Ajax"; }
        this.aiDataContract = {
            id: 1 ,
            ver: 1 ,
            name: 0 ,
            resultCode: 0 ,
            duration: 0 ,
            success: 0 ,
            data: 0 ,
            target: 0 ,
            type: 0 ,
            properties: 0 ,
            measurements: 0 ,
            kind: 0 ,
            value: 0 ,
            count: 0 ,
            min: 0 ,
            max: 0 ,
            stdDev: 0 ,
            dependencyKind: 0 ,
            dependencySource: 0 ,
            commandName: 0 ,
            dependencyTypeName: 0
        };
        var _self = this;
        _self.ver = 2;
        _self.id = id;
        _self[_DYN_DURATION ] = msToTimeSpan(value);
        _self.success = success;
        _self.resultCode = resultCode + "";
        _self.type = dataSanitizeString(logger, requestAPI);
        var dependencyFields = AjaxHelperParseDependencyPath(logger, absoluteUrl, method, commandName);
        _self.data = dataSanitizeUrl(logger, commandName) || dependencyFields.data;
        _self.target = dataSanitizeString(logger, dependencyFields.target);
        if (correlationContext) {
            _self.target = "".concat(_self.target, " | ").concat(correlationContext);
        }
        _self[_DYN_NAME$1 ] = dataSanitizeString(logger, dependencyFields[_DYN_NAME$1 ]);
        _self[_DYN_PROPERTIES ] = dataSanitizeProperties(logger, properties);
        _self[_DYN_MEASUREMENTS$1 ] = dataSanitizeMeasurements(logger, measurements);
    }
    RemoteDependencyData.envelopeType = "Microsoft.ApplicationInsights.{0}.RemoteDependency";
    RemoteDependencyData.dataType = "RemoteDependencyData";
    return RemoteDependencyData;
}());

var Trace = /** @class */ (function () {
    function Trace(logger, message, severityLevel, properties, measurements) {
        this.aiDataContract = {
            ver: 1 ,
            message: 1 ,
            severityLevel: 0 ,
            properties: 0
        };
        var _self = this;
        _self.ver = 2;
        message = message || strNotSpecified;
        _self[_DYN_MESSAGE ] = dataSanitizeMessage(logger, message);
        _self[_DYN_PROPERTIES ] = dataSanitizeProperties(logger, properties);
        _self[_DYN_MEASUREMENTS$1 ] = dataSanitizeMeasurements(logger, measurements);
        if (severityLevel) {
            _self[_DYN_SEVERITY_LEVEL ] = severityLevel;
        }
    }
    Trace.envelopeType = "Microsoft.ApplicationInsights.{0}.Message";
    Trace.dataType = "MessageData";
    return Trace;
}());

var PageViewPerformance = /** @class */ (function () {
    function PageViewPerformance(logger, name, url, unused, properties, measurements, cs4BaseData) {
        this.aiDataContract = {
            ver: 1 ,
            name: 0 ,
            url: 0 ,
            duration: 0 ,
            perfTotal: 0 ,
            networkConnect: 0 ,
            sentRequest: 0 ,
            receivedResponse: 0 ,
            domProcessing: 0 ,
            properties: 0 ,
            measurements: 0
        };
        var _self = this;
        _self.ver = 2;
        _self.url = dataSanitizeUrl(logger, url);
        _self[_DYN_NAME$1 ] = dataSanitizeString(logger, name) || strNotSpecified;
        _self[_DYN_PROPERTIES ] = dataSanitizeProperties(logger, properties);
        _self[_DYN_MEASUREMENTS$1 ] = dataSanitizeMeasurements(logger, measurements);
        if (cs4BaseData) {
            _self.domProcessing = cs4BaseData.domProcessing;
            _self[_DYN_DURATION ] = cs4BaseData[_DYN_DURATION ];
            _self.networkConnect = cs4BaseData.networkConnect;
            _self.perfTotal = cs4BaseData.perfTotal;
            _self.receivedResponse = cs4BaseData.receivedResponse;
            _self.sentRequest = cs4BaseData.sentRequest;
        }
    }
    PageViewPerformance.envelopeType = "Microsoft.ApplicationInsights.{0}.PageviewPerformance";
    PageViewPerformance.dataType = "PageviewPerformanceData";
    return PageViewPerformance;
}());

var Data = /** @class */ (function () {
    function Data(baseType, data) {
        this.aiDataContract = {
            baseType: 1 ,
            baseData: 1
        };
        this.baseType = baseType;
        this.baseData = data;
    }
    return Data;
}());

function _aiNameFunc(baseName) {
    var aiName = "ai." + baseName + ".";
    return function (name) {
        return aiName + name;
    };
}
var _aiApplication = _aiNameFunc("application");
var _aiDevice = _aiNameFunc("device");
var _aiLocation = _aiNameFunc("location");
var _aiOperation = _aiNameFunc("operation");
var _aiSession = _aiNameFunc("session");
var _aiUser = _aiNameFunc("user");
var _aiCloud = _aiNameFunc("cloud");
var _aiInternal = _aiNameFunc("internal");
var ContextTagKeys = /** @class */ (function (_super) {
    __extendsFn(ContextTagKeys, _super);
    function ContextTagKeys() {
        return _super.call(this) || this;
    }
    return ContextTagKeys;
}(createClassFromInterface({
    applicationVersion: _aiApplication("ver"),
    applicationBuild: _aiApplication("build"),
    applicationTypeId: _aiApplication("typeId"),
    applicationId: _aiApplication("applicationId"),
    applicationLayer: _aiApplication("layer"),
    deviceId: _aiDevice("id"),
    deviceIp: _aiDevice("ip"),
    deviceLanguage: _aiDevice("language"),
    deviceLocale: _aiDevice("locale"),
    deviceModel: _aiDevice("model"),
    deviceFriendlyName: _aiDevice("friendlyName"),
    deviceNetwork: _aiDevice("network"),
    deviceNetworkName: _aiDevice("networkName"),
    deviceOEMName: _aiDevice("oemName"),
    deviceOS: _aiDevice("os"),
    deviceOSVersion: _aiDevice("osVersion"),
    deviceRoleInstance: _aiDevice("roleInstance"),
    deviceRoleName: _aiDevice("roleName"),
    deviceScreenResolution: _aiDevice("screenResolution"),
    deviceType: _aiDevice("type"),
    deviceMachineName: _aiDevice("machineName"),
    deviceVMName: _aiDevice("vmName"),
    deviceBrowser: _aiDevice("browser"),
    deviceBrowserVersion: _aiDevice("browserVersion"),
    locationIp: _aiLocation("ip"),
    locationCountry: _aiLocation("country"),
    locationProvince: _aiLocation("province"),
    locationCity: _aiLocation("city"),
    operationId: _aiOperation("id"),
    operationName: _aiOperation("name"),
    operationParentId: _aiOperation("parentId"),
    operationRootId: _aiOperation("rootId"),
    operationSyntheticSource: _aiOperation("syntheticSource"),
    operationCorrelationVector: _aiOperation("correlationVector"),
    sessionId: _aiSession("id"),
    sessionIsFirst: _aiSession("isFirst"),
    sessionIsNew: _aiSession("isNew"),
    userAccountAcquisitionDate: _aiUser("accountAcquisitionDate"),
    userAccountId: _aiUser("accountId"),
    userAgent: _aiUser("userAgent"),
    userId: _aiUser("id"),
    userStoreRegion: _aiUser("storeRegion"),
    userAuthUserId: _aiUser("authUserId"),
    userAnonymousUserAcquisitionDate: _aiUser("anonUserAcquisitionDate"),
    userAuthenticatedUserAcquisitionDate: _aiUser("authUserAcquisitionDate"),
    cloudName: _aiCloud("name"),
    cloudRole: _aiCloud("role"),
    cloudRoleVer: _aiCloud("roleVer"),
    cloudRoleInstance: _aiCloud("roleInstance"),
    cloudEnvironment: _aiCloud("environment"),
    cloudLocation: _aiCloud("location"),
    cloudDeploymentUnit: _aiCloud("deploymentUnit"),
    internalNodeName: _aiInternal("nodeName"),
    internalSdkVersion: _aiInternal("sdkVersion"),
    internalAgentVersion: _aiInternal("agentVersion"),
    internalSnippet: _aiInternal("snippet"),
    internalSdkSrc: _aiInternal("sdkSrc")
})));

var CtxTagKeys = new ContextTagKeys();

function _disableEvents(target, evtNamespace) {
    eventOff(target, null, null, evtNamespace);
}
function createOfflineListener(parentEvtNamespace) {
    var _document = getDocument();
    var _navigator = getNavigator();
    var _isListening = false;
    var listenerList = [];
    var rState = 1 ;
    if (_navigator && !isNullOrUndefined(_navigator.onLine) && !_navigator.onLine) {
        rState = 2 ;
    }
    var uState = 0 ;
    var _currentState = calCurrentState();
    var _evtNamespace = mergeEvtNamespace(createUniqueNamespace("OfflineListener"), parentEvtNamespace);
    try {
        if (_enableEvents(getWindow())) {
            _isListening = true;
        }
        if (_document) {
            var target = _document.body || _document;
            if (target.ononline) {
                if (_enableEvents(target)) {
                    _isListening = true;
                }
            }
        }
    }
    catch (e) {
        _isListening = false;
    }
    function _enableEvents(target) {
        var enabled = false;
        if (target) {
            enabled = eventOn(target, "online", _setOnline, _evtNamespace);
            if (enabled) {
                eventOn(target, "offline", _setOffline, _evtNamespace);
            }
        }
        return enabled;
    }
    function _isOnline() {
        return _currentState;
    }
    function calCurrentState() {
        if (uState === 2  || rState === 2 ) {
            return false;
        }
        return true;
    }
    function listnerNoticeCheck() {
        var newState = calCurrentState();
        if (_currentState !== newState) {
            _currentState = newState;
            arrForEach(listenerList, function (callback) {
                var offlineState = {
                    isOnline: _currentState,
                    rState: rState,
                    uState: uState
                };
                try {
                    callback(offlineState);
                }
                catch (e) {
                }
            });
        }
    }
    function setOnlineState(newState) {
        uState = newState;
        listnerNoticeCheck();
    }
    function _setOnline() {
        rState = 1 ;
        listnerNoticeCheck();
    }
    function _setOffline() {
        rState = 2 ;
        listnerNoticeCheck();
    }
    function _unload() {
        var win = getWindow();
        if (win && _isListening) {
            _disableEvents(win, _evtNamespace);
            if (_document) {
                var target = _document.body || _document;
                if (!isUndefined(target.ononline)) {
                    _disableEvents(target, _evtNamespace);
                }
            }
            _isListening = false;
        }
    }
    function addListener(callback) {
        listenerList.push(callback);
        return {
            rm: function () {
                var index = listenerList.indexOf(callback);
                if (index > -1) {
                    return listenerList.splice(index, 1);
                }
                else {
                    return;
                }
            }
        };
    }
    return {
        isOnline: _isOnline,
        isListening: function () { return _isListening; },
        unload: _unload,
        addListener: addListener,
        setOnlineState: setOnlineState
    };
}

var BreezeChannelIdentifier = "AppInsightsChannelPlugin";

var STR_DURATION = "duration";

var _DYN_TAGS = "tags";
var _DYN_DEVICE_TYPE = "deviceType";
var _DYN_DATA = "data";
var _DYN_NAME = "name";
var _DYN_TRACE_ID = "traceID";
var _DYN_LENGTH = "length";
var _DYN_STRINGIFY = "stringify";
var _DYN_MEASUREMENTS = "measurements";
var _DYN_DATA_TYPE = "dataType";
var _DYN_ENVELOPE_TYPE = "envelopeType";
var _DYN_TO_STRING = "toString";
var _DYN_ENQUEUE = "enqueue";
var _DYN_COUNT = "count";
var _DYN_PUSH = "push";
var _DYN_EMIT_LINE_DELIMITED_0 = "emitLineDelimitedJson";
var _DYN_CLEAR = "clear";
var _DYN_MARK_AS_SENT = "markAsSent";
var _DYN_CLEAR_SENT = "clearSent";
var _DYN_BUFFER_OVERRIDE = "bufferOverride";
var _DYN__BUFFER__KEY = "BUFFER_KEY";
var _DYN__SENT__BUFFER__KEY = "SENT_BUFFER_KEY";
var _DYN_CONCAT = "concat";
var _DYN__MAX__BUFFER__SIZE = "MAX_BUFFER_SIZE";
var _DYN_TRIGGER_SEND = "triggerSend";
var _DYN_DIAG_LOG = "diagLog";
var _DYN_INITIALIZE = "initialize";
var _DYN__SENDER = "_sender";
var _DYN_ENDPOINT_URL = "endpointUrl";
var _DYN_INSTRUMENTATION_KEY = "instrumentationKey";
var _DYN_CUSTOM_HEADERS = "customHeaders";
var _DYN_MAX_BATCH_SIZE_IN_BY1 = "maxBatchSizeInBytes";
var _DYN_ONUNLOAD_DISABLE_BEA2 = "onunloadDisableBeacon";
var _DYN_IS_BEACON_API_DISABL3 = "isBeaconApiDisabled";
var _DYN_ALWAYS_USE_XHR_OVERR4 = "alwaysUseXhrOverride";
var _DYN_ENABLE_SESSION_STORA5 = "enableSessionStorageBuffer";
var _DYN__BUFFER = "_buffer";
var _DYN_ONUNLOAD_DISABLE_FET6 = "onunloadDisableFetch";
var _DYN_DISABLE_SEND_BEACON_7 = "disableSendBeaconSplit";
var _DYN_GET_SENDER_INST = "getSenderInst";
var _DYN__ON_ERROR = "_onError";
var _DYN__ON_PARTIAL_SUCCESS = "_onPartialSuccess";
var _DYN__ON_SUCCESS = "_onSuccess";
var _DYN_ITEMS_RECEIVED = "itemsReceived";
var _DYN_ITEMS_ACCEPTED = "itemsAccepted";
var _DYN_BASE_TYPE = "baseType";
var _DYN_SAMPLE_RATE = "sampleRate";
var _DYN_GET_HASH_CODE_SCORE = "getHashCodeScore";

var strBaseType = "baseType";
var strBaseData = "baseData";
var strProperties = "properties";
var strTrue = "true";
function _setValueIf(target, field, value) {
    return setValue(target, field, value, isTruthy);
}
function _extractPartAExtensions(logger, item, env) {
    var envTags = env[_DYN_TAGS ] = env[_DYN_TAGS ] || {};
    var itmExt = item.ext = item.ext || {};
    var itmTags = item[_DYN_TAGS ] = item[_DYN_TAGS ] || [];
    var extUser = itmExt.user;
    if (extUser) {
        _setValueIf(envTags, CtxTagKeys.userAuthUserId, extUser.authId);
        _setValueIf(envTags, CtxTagKeys.userId, extUser.id || extUser.localId);
    }
    var extApp = itmExt.app;
    if (extApp) {
        _setValueIf(envTags, CtxTagKeys.sessionId, extApp.sesId);
    }
    var extDevice = itmExt.device;
    if (extDevice) {
        _setValueIf(envTags, CtxTagKeys.deviceId, extDevice.id || extDevice.localId);
        _setValueIf(envTags, CtxTagKeys[_DYN_DEVICE_TYPE ], extDevice.deviceClass);
        _setValueIf(envTags, CtxTagKeys.deviceIp, extDevice.ip);
        _setValueIf(envTags, CtxTagKeys.deviceModel, extDevice.model);
        _setValueIf(envTags, CtxTagKeys[_DYN_DEVICE_TYPE ], extDevice[_DYN_DEVICE_TYPE ]);
    }
    var web = item.ext.web;
    if (web) {
        _setValueIf(envTags, CtxTagKeys.deviceLanguage, web.browserLang);
        _setValueIf(envTags, CtxTagKeys.deviceBrowserVersion, web.browserVer);
        _setValueIf(envTags, CtxTagKeys.deviceBrowser, web.browser);
        var envData = env[_DYN_DATA ] = env[_DYN_DATA ] || {};
        var envBaseData = envData[strBaseData] = envData[strBaseData] || {};
        var envProps = envBaseData[strProperties] = envBaseData[strProperties] || {};
        _setValueIf(envProps, "domain", web.domain);
        _setValueIf(envProps, "isManual", web.isManual ? strTrue : null);
        _setValueIf(envProps, "screenRes", web.screenRes);
        _setValueIf(envProps, "userConsent", web.userConsent ? strTrue : null);
    }
    var extOs = itmExt.os;
    if (extOs) {
        _setValueIf(envTags, CtxTagKeys.deviceOS, extOs[_DYN_NAME ]);
        _setValueIf(envTags, CtxTagKeys.deviceOSVersion, extOs.osVer);
    }
    var extTrace = itmExt.trace;
    if (extTrace) {
        _setValueIf(envTags, CtxTagKeys.operationParentId, extTrace.parentID);
        _setValueIf(envTags, CtxTagKeys.operationName, dataSanitizeString(logger, extTrace[_DYN_NAME ]));
        _setValueIf(envTags, CtxTagKeys.operationId, extTrace[_DYN_TRACE_ID ]);
    }
    var tgs = {};
    for (var i = itmTags[_DYN_LENGTH ] - 1; i >= 0; i--) {
        var tg = itmTags[i];
        objForEachKey(tg, function (key, value) {
            tgs[key] = value;
        });
        itmTags.splice(i, 1);
    }
    objForEachKey(itmTags, function (tg, value) {
        tgs[tg] = value;
    });
    var theTags = __assignFn(__assignFn({}, envTags), tgs);
    if (!theTags[CtxTagKeys.internalSdkVersion]) {
        theTags[CtxTagKeys.internalSdkVersion] = dataSanitizeString(logger, "javascript:".concat(EnvelopeCreator.Version), 64);
    }
    env[_DYN_TAGS ] = optimizeObject(theTags);
}
function _extractPropsAndMeasurements(data, properties, measurements) {
    if (!isNullOrUndefined(data)) {
        objForEachKey(data, function (key, value) {
            if (isNumber(value)) {
                measurements[key] = value;
            }
            else if (isString(value)) {
                properties[key] = value;
            }
            else if (hasJSON()) {
                properties[key] = getJSON()[_DYN_STRINGIFY ](value);
            }
        });
    }
}
function _convertPropsUndefinedToCustomDefinedValue(properties, customUndefinedValue) {
    if (!isNullOrUndefined(properties)) {
        objForEachKey(properties, function (key, value) {
            properties[key] = value || customUndefinedValue;
        });
    }
}
function _createEnvelope(logger, envelopeType, telemetryItem, data) {
    var envelope = new Envelope(logger, data, envelopeType);
    _setValueIf(envelope, "sampleRate", telemetryItem[SampleRate]);
    if ((telemetryItem[strBaseData] || {}).startTime) {
        envelope.time = toISOString(telemetryItem[strBaseData].startTime);
    }
    envelope.iKey = telemetryItem.iKey;
    var iKeyNoDashes = telemetryItem.iKey.replace(/-/g, "");
    envelope[_DYN_NAME ] = envelope[_DYN_NAME ].replace("{0}", iKeyNoDashes);
    _extractPartAExtensions(logger, telemetryItem, envelope);
    telemetryItem[_DYN_TAGS ] = telemetryItem[_DYN_TAGS ] || [];
    return optimizeObject(envelope);
}
function EnvelopeCreatorInit(logger, telemetryItem) {
    if (isNullOrUndefined(telemetryItem[strBaseData])) {
        _throwInternal(logger, 1 , 46 , "telemetryItem.baseData cannot be null.");
    }
}
var EnvelopeCreator = {
    Version: '3.3.10'
};
function DependencyEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {
    EnvelopeCreatorInit(logger, telemetryItem);
    var customMeasurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS ] || {};
    var customProperties = telemetryItem[strBaseData][strProperties] || {};
    _extractPropsAndMeasurements(telemetryItem[_DYN_DATA ], customProperties, customMeasurements);
    if (!isNullOrUndefined(customUndefinedValue)) {
        _convertPropsUndefinedToCustomDefinedValue(customProperties, customUndefinedValue);
    }
    var bd = telemetryItem[strBaseData];
    if (isNullOrUndefined(bd)) {
        _warnToConsole(logger, "Invalid input for dependency data");
        return null;
    }
    var method = bd[strProperties] && bd[strProperties][HttpMethod] ? bd[strProperties][HttpMethod] : "GET";
    var remoteDepData = new RemoteDependencyData(logger, bd.id, bd.target, bd[_DYN_NAME ], bd[STR_DURATION ], bd.success, bd.responseCode, method, bd.type, bd.correlationContext, customProperties, customMeasurements);
    var data = new Data(RemoteDependencyData[_DYN_DATA_TYPE ], remoteDepData);
    return _createEnvelope(logger, RemoteDependencyData[_DYN_ENVELOPE_TYPE ], telemetryItem, data);
}
function EventEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {
    EnvelopeCreatorInit(logger, telemetryItem);
    var customProperties = {};
    var customMeasurements = {};
    if (telemetryItem[strBaseType] !== Event$1[_DYN_DATA_TYPE ]) {
        customProperties["baseTypeSource"] = telemetryItem[strBaseType];
    }
    if (telemetryItem[strBaseType] === Event$1[_DYN_DATA_TYPE ]) {
        customProperties = telemetryItem[strBaseData][strProperties] || {};
        customMeasurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS ] || {};
    }
    else {
        if (telemetryItem[strBaseData]) {
            _extractPropsAndMeasurements(telemetryItem[strBaseData], customProperties, customMeasurements);
        }
    }
    _extractPropsAndMeasurements(telemetryItem[_DYN_DATA ], customProperties, customMeasurements);
    if (!isNullOrUndefined(customUndefinedValue)) {
        _convertPropsUndefinedToCustomDefinedValue(customProperties, customUndefinedValue);
    }
    var eventName = telemetryItem[strBaseData][_DYN_NAME ];
    var eventData = new Event$1(logger, eventName, customProperties, customMeasurements);
    var data = new Data(Event$1[_DYN_DATA_TYPE ], eventData);
    return _createEnvelope(logger, Event$1[_DYN_ENVELOPE_TYPE ], telemetryItem, data);
}
function ExceptionEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {
    EnvelopeCreatorInit(logger, telemetryItem);
    var customMeasurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS ] || {};
    var customProperties = telemetryItem[strBaseData][strProperties] || {};
    _extractPropsAndMeasurements(telemetryItem[_DYN_DATA ], customProperties, customMeasurements);
    if (!isNullOrUndefined(customUndefinedValue)) {
        _convertPropsUndefinedToCustomDefinedValue(customProperties, customUndefinedValue);
    }
    var bd = telemetryItem[strBaseData];
    var exData = Exception.CreateFromInterface(logger, bd, customProperties, customMeasurements);
    var data = new Data(Exception[_DYN_DATA_TYPE ], exData);
    return _createEnvelope(logger, Exception[_DYN_ENVELOPE_TYPE ], telemetryItem, data);
}
function MetricEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {
    EnvelopeCreatorInit(logger, telemetryItem);
    var baseData = telemetryItem[strBaseData];
    var props = baseData[strProperties] || {};
    var measurements = baseData[_DYN_MEASUREMENTS ] || {};
    _extractPropsAndMeasurements(telemetryItem[_DYN_DATA ], props, measurements);
    if (!isNullOrUndefined(customUndefinedValue)) {
        _convertPropsUndefinedToCustomDefinedValue(props, customUndefinedValue);
    }
    var baseMetricData = new Metric(logger, baseData[_DYN_NAME ], baseData.average, baseData.sampleCount, baseData.min, baseData.max, baseData.stdDev, props, measurements);
    var data = new Data(Metric[_DYN_DATA_TYPE ], baseMetricData);
    return _createEnvelope(logger, Metric[_DYN_ENVELOPE_TYPE ], telemetryItem, data);
}
function PageViewEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {
    EnvelopeCreatorInit(logger, telemetryItem);
    var duration;
    var baseData = telemetryItem[strBaseData];
    if (!isNullOrUndefined(baseData) &&
        !isNullOrUndefined(baseData[strProperties]) &&
        !isNullOrUndefined(baseData[strProperties][STR_DURATION])) {
        duration = baseData[strProperties][STR_DURATION];
        delete baseData[strProperties][STR_DURATION];
    }
    else if (!isNullOrUndefined(telemetryItem[_DYN_DATA ]) &&
        !isNullOrUndefined(telemetryItem[_DYN_DATA ][STR_DURATION])) {
        duration = telemetryItem[_DYN_DATA ][STR_DURATION];
        delete telemetryItem[_DYN_DATA ][STR_DURATION];
    }
    var bd = telemetryItem[strBaseData];
    var currentContextId;
    if (((telemetryItem.ext || {}).trace || {})[_DYN_TRACE_ID ]) {
        currentContextId = telemetryItem.ext.trace[_DYN_TRACE_ID ];
    }
    var id = bd.id || currentContextId;
    var name = bd[_DYN_NAME ];
    var url = bd.uri;
    var properties = bd[strProperties] || {};
    var measurements = bd[_DYN_MEASUREMENTS ] || {};
    if (!isNullOrUndefined(bd.refUri)) {
        properties["refUri"] = bd.refUri;
    }
    if (!isNullOrUndefined(bd.pageType)) {
        properties["pageType"] = bd.pageType;
    }
    if (!isNullOrUndefined(bd.isLoggedIn)) {
        properties["isLoggedIn"] = bd.isLoggedIn[_DYN_TO_STRING ]();
    }
    if (!isNullOrUndefined(bd[strProperties])) {
        var pageTags = bd[strProperties];
        objForEachKey(pageTags, function (key, value) {
            properties[key] = value;
        });
    }
    _extractPropsAndMeasurements(telemetryItem[_DYN_DATA ], properties, measurements);
    if (!isNullOrUndefined(customUndefinedValue)) {
        _convertPropsUndefinedToCustomDefinedValue(properties, customUndefinedValue);
    }
    var pageViewData = new PageView(logger, name, url, duration, properties, measurements, id);
    var data = new Data(PageView[_DYN_DATA_TYPE ], pageViewData);
    return _createEnvelope(logger, PageView[_DYN_ENVELOPE_TYPE ], telemetryItem, data);
}
function PageViewPerformanceEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {
    EnvelopeCreatorInit(logger, telemetryItem);
    var bd = telemetryItem[strBaseData];
    var name = bd[_DYN_NAME ];
    var url = bd.uri || bd.url;
    var properties = bd[strProperties] || {};
    var measurements = bd[_DYN_MEASUREMENTS ] || {};
    _extractPropsAndMeasurements(telemetryItem[_DYN_DATA ], properties, measurements);
    if (!isNullOrUndefined(customUndefinedValue)) {
        _convertPropsUndefinedToCustomDefinedValue(properties, customUndefinedValue);
    }
    var baseData = new PageViewPerformance(logger, name, url, undefined, properties, measurements, bd);
    var data = new Data(PageViewPerformance[_DYN_DATA_TYPE ], baseData);
    return _createEnvelope(logger, PageViewPerformance[_DYN_ENVELOPE_TYPE ], telemetryItem, data);
}
function TraceEnvelopeCreator(logger, telemetryItem, customUndefinedValue) {
    EnvelopeCreatorInit(logger, telemetryItem);
    var message = telemetryItem[strBaseData].message;
    var severityLevel = telemetryItem[strBaseData].severityLevel;
    var props = telemetryItem[strBaseData][strProperties] || {};
    var measurements = telemetryItem[strBaseData][_DYN_MEASUREMENTS ] || {};
    _extractPropsAndMeasurements(telemetryItem[_DYN_DATA ], props, measurements);
    if (!isNullOrUndefined(customUndefinedValue)) {
        _convertPropsUndefinedToCustomDefinedValue(props, customUndefinedValue);
    }
    var baseData = new Trace(logger, message, severityLevel, props, measurements);
    var data = new Data(Trace[_DYN_DATA_TYPE ], baseData);
    return _createEnvelope(logger, Trace[_DYN_ENVELOPE_TYPE ], telemetryItem, data);
}

var BaseSendBuffer = /** @class */ (function () {
    function BaseSendBuffer(logger, config) {
        var _buffer = [];
        var _bufferFullMessageSent = false;
        var _maxRetryCnt = config.maxRetryCnt;
        this._get = function () {
            return _buffer;
        };
        this._set = function (buffer) {
            _buffer = buffer;
            return _buffer;
        };
        dynamicProto(BaseSendBuffer, this, function (_self) {
            _self[_DYN_ENQUEUE ] = function (payload) {
                if (_self[_DYN_COUNT ]() >= config.eventsLimitInMem) {
                    if (!_bufferFullMessageSent) {
                        _throwInternal(logger, 2 , 105 , "Maximum in-memory buffer size reached: " + _self[_DYN_COUNT ](), true);
                        _bufferFullMessageSent = true;
                    }
                    return;
                }
                payload.cnt = payload.cnt || 0;
                if (!isNullOrUndefined(_maxRetryCnt)) {
                    if (payload.cnt > _maxRetryCnt) {
                        return;
                    }
                }
                _buffer[_DYN_PUSH ](payload);
                return;
            };
            _self[_DYN_COUNT ] = function () {
                return _buffer[_DYN_LENGTH ];
            };
            _self.size = function () {
                var size = _buffer[_DYN_LENGTH ];
                for (var lp = 0; lp < _buffer[_DYN_LENGTH ]; lp++) {
                    size += (_buffer[lp].item)[_DYN_LENGTH ];
                }
                if (!config[_DYN_EMIT_LINE_DELIMITED_0 ]) {
                    size += 2;
                }
                return size;
            };
            _self[_DYN_CLEAR ] = function () {
                _buffer = [];
                _bufferFullMessageSent = false;
            };
            _self.getItems = function () {
                return _buffer.slice(0);
            };
            _self.batchPayloads = function (payloads) {
                if (payloads && payloads[_DYN_LENGTH ] > 0) {
                    var payloadStr_1 = [];
                    arrForEach(payloads, function (payload) {
                        payloadStr_1[_DYN_PUSH ](payload.item);
                    });
                    var batch = config[_DYN_EMIT_LINE_DELIMITED_0 ] ?
                        payloadStr_1.join("\n") :
                        "[" + payloadStr_1.join(",") + "]";
                    return batch;
                }
                return null;
            };
            _self.createNew = function (newLogger, newConfig, canUseSessionStorage) {
                var items = _buffer.slice(0);
                newLogger = newLogger || logger;
                newConfig = newConfig || {};
                var newBuffer = !!canUseSessionStorage ? new SessionStorageSendBuffer(newLogger, newConfig) : new ArraySendBuffer(newLogger, newConfig);
                arrForEach(items, function (payload) {
                    newBuffer[_DYN_ENQUEUE ](payload);
                });
                return newBuffer;
            };
        });
    }
    BaseSendBuffer.__ieDyn=1;
    return BaseSendBuffer;
}());
var ArraySendBuffer = /** @class */ (function (_super) {
    __extendsFn(ArraySendBuffer, _super);
    function ArraySendBuffer(logger, config) {
        var _this = _super.call(this, logger, config) || this;
        dynamicProto(ArraySendBuffer, _this, function (_self, _base) {
            _self[_DYN_MARK_AS_SENT ] = function (payload) {
                _base[_DYN_CLEAR ]();
            };
            _self[_DYN_CLEAR_SENT ] = function (payload) {
            };
        });
        return _this;
    }
    ArraySendBuffer.__ieDyn=1;
    return ArraySendBuffer;
}(BaseSendBuffer));
var PREVIOUS_KEYS = ["AI_buffer", "AI_sentBuffer"];
var SessionStorageSendBuffer = /** @class */ (function (_super) {
    __extendsFn(SessionStorageSendBuffer, _super);
    function SessionStorageSendBuffer(logger, config) {
        var _this = _super.call(this, logger, config) || this;
        var _bufferFullMessageSent = false;
        var _namePrefix = config === null || config === void 0 ? void 0 : config.namePrefix;
        var _b = config[_DYN_BUFFER_OVERRIDE ] || { getItem: utlGetSessionStorage, setItem: utlSetSessionStorage }, getItem = _b.getItem, setItem = _b.setItem;
        var _maxRetryCnt = config.maxRetryCnt;
        dynamicProto(SessionStorageSendBuffer, _this, function (_self, _base) {
            var bufferItems = _getBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY ]);
            var itemsInSentBuffer = _getBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY ]);
            var previousItems = _getPreviousEvents();
            var notDeliveredItems = itemsInSentBuffer[_DYN_CONCAT ](previousItems);
            var buffer = _self._set(bufferItems[_DYN_CONCAT ](notDeliveredItems));
            if (buffer[_DYN_LENGTH ] > SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE ]) {
                buffer[_DYN_LENGTH ] = SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE ];
            }
            _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY ], []);
            _setBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY ], buffer);
            _self[_DYN_ENQUEUE ] = function (payload) {
                if (_self[_DYN_COUNT ]() >= SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE ]) {
                    if (!_bufferFullMessageSent) {
                        _throwInternal(logger, 2 , 67 , "Maximum buffer size reached: " + _self[_DYN_COUNT ](), true);
                        _bufferFullMessageSent = true;
                    }
                    return;
                }
                payload.cnt = payload.cnt || 0;
                if (!isNullOrUndefined(_maxRetryCnt)) {
                    if (payload.cnt > _maxRetryCnt) {
                        return;
                    }
                }
                _base[_DYN_ENQUEUE ](payload);
                _setBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY ], _self._get());
            };
            _self[_DYN_CLEAR ] = function () {
                _base[_DYN_CLEAR ]();
                _setBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY ], _self._get());
                _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY ], []);
                _bufferFullMessageSent = false;
            };
            _self[_DYN_MARK_AS_SENT ] = function (payload) {
                _setBuffer(SessionStorageSendBuffer[_DYN__BUFFER__KEY ], _self._set(_removePayloadsFromBuffer(payload, _self._get())));
                var sentElements = _getBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY ]);
                if (sentElements instanceof Array && payload instanceof Array) {
                    sentElements = sentElements[_DYN_CONCAT ](payload);
                    if (sentElements[_DYN_LENGTH ] > SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE ]) {
                        _throwInternal(logger, 1 , 67 , "Sent buffer reached its maximum size: " + sentElements[_DYN_LENGTH ], true);
                        sentElements[_DYN_LENGTH ] = SessionStorageSendBuffer[_DYN__MAX__BUFFER__SIZE ];
                    }
                    _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY ], sentElements);
                }
            };
            _self[_DYN_CLEAR_SENT ] = function (payload) {
                var sentElements = _getBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY ]);
                sentElements = _removePayloadsFromBuffer(payload, sentElements);
                _setBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY ], sentElements);
            };
            _self.createNew = function (newLogger, newConfig, canUseSessionStorage) {
                canUseSessionStorage = !!canUseSessionStorage;
                var unsentItems = _self._get().slice(0);
                var sentItems = _getBuffer(SessionStorageSendBuffer[_DYN__SENT__BUFFER__KEY ]).slice(0);
                newLogger = newLogger || logger;
                newConfig = newConfig || {};
                _self[_DYN_CLEAR ]();
                var newBuffer = canUseSessionStorage ? new SessionStorageSendBuffer(newLogger, newConfig) : new ArraySendBuffer(newLogger, newConfig);
                arrForEach(unsentItems, function (payload) {
                    newBuffer[_DYN_ENQUEUE ](payload);
                });
                if (canUseSessionStorage) {
                    newBuffer[_DYN_MARK_AS_SENT ](sentItems);
                }
                return newBuffer;
            };
            function _removePayloadsFromBuffer(payloads, buffer) {
                var remaining = [];
                var payloadStr = [];
                arrForEach(payloads, function (payload) {
                    payloadStr[_DYN_PUSH ](payload.item);
                });
                arrForEach(buffer, function (value) {
                    if (!isFunction(value) && arrIndexOf(payloadStr, value.item) === -1) {
                        remaining[_DYN_PUSH ](value);
                    }
                });
                return remaining;
            }
            function _getBuffer(key) {
                var prefixedKey = key;
                prefixedKey = _namePrefix ? _namePrefix + "_" + prefixedKey : prefixedKey;
                return _getBufferBase(prefixedKey);
            }
            function _getBufferBase(key) {
                try {
                    var bufferJson = getItem(logger, key);
                    if (bufferJson) {
                        var buffer_1 = getJSON().parse(bufferJson);
                        if (isString(buffer_1)) {
                            buffer_1 = getJSON().parse(buffer_1);
                        }
                        if (buffer_1 && isArray(buffer_1)) {
                            return buffer_1;
                        }
                    }
                }
                catch (e) {
                    _throwInternal(logger, 1 , 42 , " storage key: " + key + ", " + getExceptionName(e), { exception: dumpObj(e) });
                }
                return [];
            }
            function _setBuffer(key, buffer) {
                var prefixedKey = key;
                try {
                    prefixedKey = _namePrefix ? _namePrefix + "_" + prefixedKey : prefixedKey;
                    var bufferJson = JSON[_DYN_STRINGIFY ](buffer);
                    setItem(logger, prefixedKey, bufferJson);
                }
                catch (e) {
                    setItem(logger, prefixedKey, JSON[_DYN_STRINGIFY ]([]));
                    _throwInternal(logger, 2 , 41 , " storage key: " + prefixedKey + ", " + getExceptionName(e) + ". Buffer cleared", { exception: dumpObj(e) });
                }
            }
            function _getPreviousEvents() {
                var items = [];
                try {
                    arrForEach(PREVIOUS_KEYS, function (key) {
                        var events = _getItemsFromPreviousKey(key);
                        items = items[_DYN_CONCAT ](events);
                        if (_namePrefix) {
                            var prefixedKey = _namePrefix + "_" + key;
                            var prefixEvents = _getItemsFromPreviousKey(prefixedKey);
                            items = items[_DYN_CONCAT ](prefixEvents);
                        }
                    });
                    return items;
                }
                catch (e) {
                    _throwInternal(logger, 2 , 41 , "Transfer events from previous buffers: " + getExceptionName(e) + ". previous Buffer items can not be removed", { exception: dumpObj(e) });
                }
                return [];
            }
            function _getItemsFromPreviousKey(key) {
                try {
                    var items = _getBufferBase(key);
                    var transFormedItems_1 = [];
                    arrForEach(items, function (item) {
                        var internalItem = {
                            item: item,
                            cnt: 0
                        };
                        transFormedItems_1[_DYN_PUSH ](internalItem);
                    });
                    utlRemoveSessionStorage(logger, key);
                    return transFormedItems_1;
                }
                catch (e) {
                }
                return [];
            }
        });
        return _this;
    }
    var _a;
    _a = SessionStorageSendBuffer;
    SessionStorageSendBuffer.VERSION = "_1";
    SessionStorageSendBuffer.BUFFER_KEY = "AI_buffer" + _a.VERSION;
    SessionStorageSendBuffer.SENT_BUFFER_KEY = "AI_sentBuffer" + _a.VERSION;
    SessionStorageSendBuffer.MAX_BUFFER_SIZE = 2000;
    return SessionStorageSendBuffer;
}(BaseSendBuffer));

var Serializer = /** @class */ (function () {
    function Serializer(logger) {
        dynamicProto(Serializer, this, function (_self) {
            _self.serialize = function (input) {
                var output = _serializeObject(input, "root");
                try {
                    return getJSON()[_DYN_STRINGIFY ](output);
                }
                catch (e) {
                    _throwInternal(logger, 1 , 48 , (e && isFunction(e[_DYN_TO_STRING ])) ? e[_DYN_TO_STRING ]() : "Error serializing object", null, true);
                }
            };
            function _serializeObject(source, name) {
                var circularReferenceCheck = "__aiCircularRefCheck";
                var output = {};
                if (!source) {
                    _throwInternal(logger, 1 , 48 , "cannot serialize object because it is null or undefined", { name: name }, true);
                    return output;
                }
                if (source[circularReferenceCheck]) {
                    _throwInternal(logger, 2 , 50 , "Circular reference detected while serializing object", { name: name }, true);
                    return output;
                }
                if (!source.aiDataContract) {
                    if (name === "measurements") {
                        output = _serializeStringMap(source, "number", name);
                    }
                    else if (name === "properties") {
                        output = _serializeStringMap(source, "string", name);
                    }
                    else if (name === "tags") {
                        output = _serializeStringMap(source, "string", name);
                    }
                    else if (isArray(source)) {
                        output = _serializeArray(source, name);
                    }
                    else {
                        _throwInternal(logger, 2 , 49 , "Attempting to serialize an object which does not implement ISerializable", { name: name }, true);
                        try {
                            getJSON()[_DYN_STRINGIFY ](source);
                            output = source;
                        }
                        catch (e) {
                            _throwInternal(logger, 1 , 48 , (e && isFunction(e[_DYN_TO_STRING ])) ? e[_DYN_TO_STRING ]() : "Error serializing object", null, true);
                        }
                    }
                    return output;
                }
                source[circularReferenceCheck] = true;
                objForEachKey(source.aiDataContract, function (field, contract) {
                    var isRequired = (isFunction(contract)) ? (contract() & 1 ) : (contract & 1 );
                    var isHidden = (isFunction(contract)) ? (contract() & 4 ) : (contract & 4 );
                    var isArray = contract & 2 ;
                    var isPresent = source[field] !== undefined;
                    var isObj = isObject(source[field]) && source[field] !== null;
                    if (isRequired && !isPresent && !isArray) {
                        _throwInternal(logger, 1 , 24 , "Missing required field specification. The field is required but not present on source", { field: field, name: name });
                    }
                    else if (!isHidden) {
                        var value = void 0;
                        if (isObj) {
                            if (isArray) {
                                value = _serializeArray(source[field], field);
                            }
                            else {
                                value = _serializeObject(source[field], field);
                            }
                        }
                        else {
                            value = source[field];
                        }
                        if (value !== undefined) {
                            output[field] = value;
                        }
                    }
                });
                delete source[circularReferenceCheck];
                return output;
            }
            function _serializeArray(sources, name) {
                var output;
                if (!!sources) {
                    if (!isArray(sources)) {
                        _throwInternal(logger, 1 , 54 , "This field was specified as an array in the contract but the item is not an array.\r\n", { name: name }, true);
                    }
                    else {
                        output = [];
                        for (var i = 0; i < sources[_DYN_LENGTH ]; i++) {
                            var source = sources[i];
                            var item = _serializeObject(source, name + "[" + i + "]");
                            output[_DYN_PUSH ](item);
                        }
                    }
                }
                return output;
            }
            function _serializeStringMap(map, expectedType, name) {
                var output;
                if (map) {
                    output = {};
                    objForEachKey(map, function (field, value) {
                        if (expectedType === "string") {
                            if (value === undefined) {
                                output[field] = "undefined";
                            }
                            else if (value === null) {
                                output[field] = "null";
                            }
                            else if (!value[_DYN_TO_STRING ]) {
                                output[field] = "invalid field: toString() is not defined.";
                            }
                            else {
                                output[field] = value[_DYN_TO_STRING ]();
                            }
                        }
                        else if (expectedType === "number") {
                            if (value === undefined) {
                                output[field] = "undefined";
                            }
                            else if (value === null) {
                                output[field] = "null";
                            }
                            else {
                                var num = parseFloat(value);
                                output[field] = num;
                            }
                        }
                        else {
                            output[field] = "invalid field: " + name + " is of unknown type.";
                            _throwInternal(logger, 1 , output[field], null, true);
                        }
                    });
                }
                return output;
            }
        });
    }
    Serializer.__ieDyn=1;
    return Serializer;
}());

var MIN_INPUT_LENGTH = 8;
var HashCodeScoreGenerator = /** @class */ (function () {
    function HashCodeScoreGenerator() {
    }
    HashCodeScoreGenerator.prototype.getHashCodeScore = function (key) {
        var score = this.getHashCode(key) / HashCodeScoreGenerator.INT_MAX_VALUE;
        return score * 100;
    };
    HashCodeScoreGenerator.prototype.getHashCode = function (input) {
        if (input === "") {
            return 0;
        }
        while (input[_DYN_LENGTH ] < MIN_INPUT_LENGTH) {
            input = input[_DYN_CONCAT ](input);
        }
        var hash = 5381;
        for (var i = 0; i < input[_DYN_LENGTH ]; ++i) {
            hash = ((hash << 5) + hash) + input.charCodeAt(i);
            hash = hash & hash;
        }
        return Math.abs(hash);
    };
    HashCodeScoreGenerator.INT_MAX_VALUE = 2147483647;
    return HashCodeScoreGenerator;
}());

var SamplingScoreGenerator = /** @class */ (function () {
    function SamplingScoreGenerator() {
        var _self = this;
        var hashCodeGenerator = new HashCodeScoreGenerator();
        var keys = new ContextTagKeys();
        _self.getSamplingScore = function (item) {
            var score = 0;
            if (item[_DYN_TAGS ] && item[_DYN_TAGS ][keys.userId]) {
                score = hashCodeGenerator.getHashCodeScore(item[_DYN_TAGS ][keys.userId]);
            }
            else if (item.ext && item.ext.user && item.ext.user.id) {
                score = hashCodeGenerator[_DYN_GET_HASH_CODE_SCORE ](item.ext.user.id);
            }
            else if (item[_DYN_TAGS ] && item[_DYN_TAGS ][keys.operationId]) {
                score = hashCodeGenerator.getHashCodeScore(item[_DYN_TAGS ][keys.operationId]);
            }
            else if (item.ext && item.ext.telemetryTrace && item.ext.telemetryTrace[_DYN_TRACE_ID ]) {
                score = hashCodeGenerator.getHashCodeScore(item.ext.telemetryTrace[_DYN_TRACE_ID ]);
            }
            else {
                score = (Math.random() * 100);
            }
            return score;
        };
    }
    return SamplingScoreGenerator;
}());

var Sample = /** @class */ (function () {
    function Sample(sampleRate, logger) {
        this.INT_MAX_VALUE = 2147483647;
        var _logger = logger || safeGetLogger(null);
        if (sampleRate > 100 || sampleRate < 0) {
            _logger.throwInternal(2 , 58 , "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);
            sampleRate = 100;
        }
        this[_DYN_SAMPLE_RATE ] = sampleRate;
        this.samplingScoreGenerator = new SamplingScoreGenerator();
    }
    Sample.prototype.isSampledIn = function (envelope) {
        var samplingPercentage = this[_DYN_SAMPLE_RATE ];
        var isSampledIn = false;
        if (samplingPercentage === null || samplingPercentage === undefined || samplingPercentage >= 100) {
            return true;
        }
        else if (envelope.baseType === Metric[_DYN_DATA_TYPE ]) {
            return true;
        }
        isSampledIn = this.samplingScoreGenerator.getSamplingScore(envelope) < samplingPercentage;
        return isSampledIn;
    };
    return Sample;
}());

var _a, _b;
var UNDEFINED_VALUE = undefined;
var EMPTY_STR = "";
var FetchSyncRequestSizeLimitBytes = 65000;
function _getResponseText(xhr) {
    try {
        return xhr.responseText;
    }
    catch (e) {
    }
    return null;
}
function isOverrideFn(httpXHROverride) {
    return httpXHROverride && httpXHROverride.sendPOST;
}
var defaultAppInsightsChannelConfig = objDeepFreeze((_a = {
        endpointUrl: cfgDfValidate(isTruthy, DEFAULT_BREEZE_ENDPOINT + DEFAULT_BREEZE_PATH)
    },
    _a[_DYN_EMIT_LINE_DELIMITED_0 ] = cfgDfBoolean(),
    _a.maxBatchInterval = 15000,
    _a[_DYN_MAX_BATCH_SIZE_IN_BY1 ] = 102400,
    _a.disableTelemetry = cfgDfBoolean(),
    _a[_DYN_ENABLE_SESSION_STORA5 ] = cfgDfBoolean(true),
    _a.isRetryDisabled = cfgDfBoolean(),
    _a[_DYN_IS_BEACON_API_DISABL3 ] = cfgDfBoolean(true),
    _a[_DYN_DISABLE_SEND_BEACON_7 ] = cfgDfBoolean(true),
    _a.disableXhr = cfgDfBoolean(),
    _a[_DYN_ONUNLOAD_DISABLE_FET6 ] = cfgDfBoolean(),
    _a[_DYN_ONUNLOAD_DISABLE_BEA2 ] = cfgDfBoolean(),
    _a[_DYN_INSTRUMENTATION_KEY ] = UNDEFINED_VALUE,
    _a.namePrefix = UNDEFINED_VALUE,
    _a.samplingPercentage = cfgDfValidate(_chkSampling, 100),
    _a[_DYN_CUSTOM_HEADERS ] = UNDEFINED_VALUE,
    _a.convertUndefined = UNDEFINED_VALUE,
    _a.eventsLimitInMem = 10000,
    _a[_DYN_BUFFER_OVERRIDE ] = false,
    _a.httpXHROverride = { isVal: isOverrideFn, v: UNDEFINED_VALUE },
    _a[_DYN_ALWAYS_USE_XHR_OVERR4 ] = cfgDfBoolean(),
    _a.transports = UNDEFINED_VALUE,
    _a.retryCodes = UNDEFINED_VALUE,
    _a.corsPolicy = UNDEFINED_VALUE,
    _a.maxRetryCnt = { isVal: isNumber, v: 10 },
    _a));
var CrossOriginResourcePolicyHeader = "X-Set-Cross-Origin-Resource-Policy";
function _chkSampling(value) {
    return !isNaN(value) && value > 0 && value <= 100;
}
var EnvelopeTypeCreator = (_b = {},
    _b[Event$1.dataType] = EventEnvelopeCreator,
    _b[Trace.dataType] = TraceEnvelopeCreator,
    _b[PageView.dataType] = PageViewEnvelopeCreator,
    _b[PageViewPerformance.dataType] = PageViewPerformanceEnvelopeCreator,
    _b[Exception.dataType] = ExceptionEnvelopeCreator,
    _b[Metric.dataType] = MetricEnvelopeCreator,
    _b[RemoteDependencyData.dataType] = DependencyEnvelopeCreator,
    _b);
var Sender = /** @class */ (function (_super) {
    __extendsFn(Sender, _super);
    function Sender() {
        var _this = _super.call(this) || this;
        _this.priority = 1001;
        _this.identifier = BreezeChannelIdentifier;
        var _consecutiveErrors;
        var _retryAt;
        var _paused;
        var _timeoutHandle;
        var _serializer;
        var _stamp_specific_redirects;
        var _headers;
        var _syncFetchPayload = 0;
        var _syncUnloadSender;
        var _offlineListener;
        var _evtNamespace;
        var _endpointUrl;
        var _orgEndpointUrl;
        var _maxBatchSizeInBytes;
        var _beaconSupported;
        var _beaconOnUnloadSupported;
        var _beaconNormalSupported;
        var _customHeaders;
        var _disableTelemetry;
        var _instrumentationKey;
        var _convertUndefined;
        var _isRetryDisabled;
        var _maxBatchInterval;
        var _sessionStorageUsed;
        var _bufferOverrideUsed;
        var _namePrefix;
        var _enableSendPromise;
        var _alwaysUseCustomSend;
        var _disableXhr;
        var _fetchKeepAlive;
        var _xhrSend;
        var _fallbackSend;
        var _disableBeaconSplit;
        var _sendPostMgr;
        var _retryCodes;
        var _zipPayload;
        dynamicProto(Sender, _this, function (_self, _base) {
            _initDefaults();
            _self.pause = function () {
                _clearScheduledTimer();
                _paused = true;
            };
            _self.resume = function () {
                if (_paused) {
                    _paused = false;
                    _retryAt = null;
                    _checkMaxSize();
                    _setupTimer();
                }
            };
            _self.flush = function (isAsync, callBack, sendReason) {
                if (isAsync === void 0) { isAsync = true; }
                if (!_paused) {
                    _clearScheduledTimer();
                    try {
                        var result_1 = _self[_DYN_TRIGGER_SEND ](isAsync, null, sendReason || 1 );
                        return doAwaitResponse(result_1, function (rsp) {
                            if (callBack) {
                                callBack(!rsp.rejected);
                                return true;
                            }
                            if (isAsync) {
                                return createPromise(function (resolve) {
                                    resolve(!rsp.rejected);
                                });
                            }
                            return result_1;
                        });
                    }
                    catch (e) {
                        _throwInternal(_self[_DYN_DIAG_LOG ](), 1 , 22 , "flush failed, telemetry will not be collected: " + getExceptionName(e), { exception: dumpObj(e) });
                    }
                }
            };
            _self.onunloadFlush = function () {
                if (!_paused) {
                    if (_beaconSupported || _alwaysUseCustomSend) {
                        try {
                            return _self[_DYN_TRIGGER_SEND ](true, _doUnloadSend, 2 );
                        }
                        catch (e) {
                            _throwInternal(_self[_DYN_DIAG_LOG ](), 1 , 20 , "failed to flush with beacon sender on page unload, telemetry will not be collected: " + getExceptionName(e), { exception: dumpObj(e) });
                        }
                    }
                    else {
                        _self.flush(false);
                    }
                }
            };
            _self.addHeader = function (name, value) {
                _headers[name] = value;
            };
            _self[_DYN_INITIALIZE ] = function (config, core, extensions, pluginChain) {
                if (_self.isInitialized()) {
                    _throwInternal(_self[_DYN_DIAG_LOG ](), 1 , 28 , "Sender is already initialized");
                }
                _base[_DYN_INITIALIZE ](config, core, extensions, pluginChain);
                var identifier = _self.identifier;
                _serializer = new Serializer(core.logger);
                _consecutiveErrors = 0;
                _retryAt = null;
                _self[_DYN__SENDER ] = null;
                _stamp_specific_redirects = 0;
                var diagLog = _self[_DYN_DIAG_LOG ]();
                _evtNamespace = mergeEvtNamespace(createUniqueNamespace("Sender"), core.evtNamespace && core.evtNamespace());
                _offlineListener = createOfflineListener(_evtNamespace);
                _self._addHook(onConfigChange(config, function (details) {
                    var config = details.cfg;
                    if (config.storagePrefix) {
                        utlSetStoragePrefix(config.storagePrefix);
                    }
                    var ctx = createProcessTelemetryContext(null, config, core);
                    var senderConfig = ctx.getExtCfg(identifier, defaultAppInsightsChannelConfig);
                    var curExtUrl = senderConfig[_DYN_ENDPOINT_URL ];
                    if (_endpointUrl && curExtUrl === _endpointUrl) {
                        var coreUrl = config[_DYN_ENDPOINT_URL ];
                        if (coreUrl && coreUrl !== curExtUrl) {
                            senderConfig[_DYN_ENDPOINT_URL ] = coreUrl;
                        }
                    }
                    var csStream = getInst("CompressionStream");
                    _zipPayload = isFeatureEnabled("zipPayload", config, false);
                    if (!isFunction(csStream)) {
                        _zipPayload = false;
                    }
                    var corsPolicy = senderConfig.corsPolicy;
                    if (corsPolicy) {
                        if (corsPolicy === "same-origin" || corsPolicy === "same-site" || corsPolicy === "cross-origin") {
                            _this.addHeader(CrossOriginResourcePolicyHeader, corsPolicy);
                        }
                    }
                    else {
                        delete _headers[CrossOriginResourcePolicyHeader];
                    }
                    if (isPromiseLike(senderConfig[_DYN_INSTRUMENTATION_KEY ])) {
                        senderConfig[_DYN_INSTRUMENTATION_KEY ] = config[_DYN_INSTRUMENTATION_KEY ];
                    }
                    objDefine(_self, "_senderConfig", {
                        g: function () {
                            return senderConfig;
                        }
                    });
                    if (_orgEndpointUrl !== senderConfig[_DYN_ENDPOINT_URL ]) {
                        _endpointUrl = _orgEndpointUrl = senderConfig[_DYN_ENDPOINT_URL ];
                    }
                    if (core.activeStatus() === ActiveStatus.PENDING) {
                        _self.pause();
                    }
                    else if (core.activeStatus() === ActiveStatus.ACTIVE) {
                        _self.resume();
                    }
                    if (_customHeaders && _customHeaders !== senderConfig[_DYN_CUSTOM_HEADERS ]) {
                        arrForEach(_customHeaders, function (customHeader) {
                            delete _headers[customHeader.header];
                        });
                    }
                    _maxBatchSizeInBytes = senderConfig[_DYN_MAX_BATCH_SIZE_IN_BY1 ];
                    _beaconSupported = (senderConfig[_DYN_ONUNLOAD_DISABLE_BEA2 ] === false || senderConfig[_DYN_IS_BEACON_API_DISABL3 ] === false) && isBeaconsSupported();
                    _beaconOnUnloadSupported = senderConfig[_DYN_ONUNLOAD_DISABLE_BEA2 ] === false && isBeaconsSupported();
                    _beaconNormalSupported = senderConfig[_DYN_IS_BEACON_API_DISABL3 ] === false && isBeaconsSupported();
                    _alwaysUseCustomSend = senderConfig[_DYN_ALWAYS_USE_XHR_OVERR4 ];
                    _disableXhr = !!senderConfig.disableXhr;
                    _retryCodes = senderConfig.retryCodes;
                    var bufferOverride = senderConfig[_DYN_BUFFER_OVERRIDE ];
                    var canUseSessionStorage = !!senderConfig[_DYN_ENABLE_SESSION_STORA5 ] &&
                        (!!bufferOverride || utlCanUseSessionStorage());
                    var namePrefix = senderConfig.namePrefix;
                    var shouldUpdate = (canUseSessionStorage !== _sessionStorageUsed)
                        || (canUseSessionStorage && (_namePrefix !== namePrefix))
                        || (canUseSessionStorage && (_bufferOverrideUsed !== bufferOverride));
                    if (_self[_DYN__BUFFER ]) {
                        if (shouldUpdate) {
                            try {
                                _self[_DYN__BUFFER ] = _self[_DYN__BUFFER ].createNew(diagLog, senderConfig, canUseSessionStorage);
                            }
                            catch (e) {
                                _throwInternal(_self[_DYN_DIAG_LOG ](), 1 , 12 , "failed to transfer telemetry to different buffer storage, telemetry will be lost: " + getExceptionName(e), { exception: dumpObj(e) });
                            }
                        }
                        _checkMaxSize();
                    }
                    else {
                        _self[_DYN__BUFFER ] = canUseSessionStorage
                            ? new SessionStorageSendBuffer(diagLog, senderConfig) : new ArraySendBuffer(diagLog, senderConfig);
                    }
                    _namePrefix = namePrefix;
                    _sessionStorageUsed = canUseSessionStorage;
                    _bufferOverrideUsed = bufferOverride;
                    _fetchKeepAlive = !senderConfig[_DYN_ONUNLOAD_DISABLE_FET6 ] && isFetchSupported(true);
                    _disableBeaconSplit = !!senderConfig[_DYN_DISABLE_SEND_BEACON_7 ];
                    _self._sample = new Sample(senderConfig.samplingPercentage, diagLog);
                    _instrumentationKey = senderConfig[_DYN_INSTRUMENTATION_KEY ];
                    if (!isPromiseLike(_instrumentationKey) && !_validateInstrumentationKey(_instrumentationKey, config)) {
                        _throwInternal(diagLog, 1 , 100 , "Invalid Instrumentation key " + _instrumentationKey);
                    }
                    _customHeaders = senderConfig[_DYN_CUSTOM_HEADERS ];
                    if (isString(_endpointUrl) && !isInternalApplicationInsightsEndpoint(_endpointUrl) && _customHeaders && _customHeaders[_DYN_LENGTH ] > 0) {
                        arrForEach(_customHeaders, function (customHeader) {
                            _this.addHeader(customHeader.header, customHeader.value);
                        });
                    }
                    else {
                        _customHeaders = null;
                    }
                    _enableSendPromise = senderConfig.enableSendPromise;
                    var sendPostConfig = _getSendPostMgrConfig();
                    if (!_sendPostMgr) {
                        _sendPostMgr = new SenderPostManager();
                        _sendPostMgr[_DYN_INITIALIZE ](sendPostConfig, diagLog);
                    }
                    else {
                        _sendPostMgr.SetConfig(sendPostConfig);
                    }
                    var customInterface = senderConfig.httpXHROverride;
                    var httpInterface = null;
                    var syncInterface = null;
                    var theTransports = prependTransports([3 , 1 , 2 ], senderConfig.transports);
                    httpInterface = _sendPostMgr && _sendPostMgr[_DYN_GET_SENDER_INST ](theTransports, false);
                    var xhrInterface = _sendPostMgr && _sendPostMgr.getFallbackInst();
                    _xhrSend = function (payload, isAsync) {
                        return _doSend(xhrInterface, payload, isAsync);
                    };
                    _fallbackSend = function (payload, isAsync) {
                        return _doSend(xhrInterface, payload, isAsync, false);
                    };
                    httpInterface = _alwaysUseCustomSend ? customInterface : (httpInterface || customInterface || xhrInterface);
                    _self[_DYN__SENDER ] = function (payload, isAsync) {
                        return _doSend(httpInterface, payload, isAsync);
                    };
                    if (_fetchKeepAlive) {
                        _syncUnloadSender = _fetchKeepAliveSender;
                    }
                    var syncTransports = prependTransports([3 , 1 ], senderConfig.unloadTransports);
                    if (!_fetchKeepAlive) {
                        syncTransports = syncTransports.filter(function (transport) { return transport !== 2 ; });
                    }
                    syncInterface = _sendPostMgr && _sendPostMgr[_DYN_GET_SENDER_INST ](syncTransports, true);
                    syncInterface = _alwaysUseCustomSend ? customInterface : (syncInterface || customInterface);
                    if ((_alwaysUseCustomSend || senderConfig.unloadTransports || !_syncUnloadSender) && syncInterface) {
                        _syncUnloadSender = function (payload, isAsync) {
                            return _doSend(syncInterface, payload, isAsync);
                        };
                    }
                    if (!_syncUnloadSender) {
                        _syncUnloadSender = _xhrSend;
                    }
                    _disableTelemetry = senderConfig.disableTelemetry;
                    _convertUndefined = senderConfig.convertUndefined || UNDEFINED_VALUE;
                    _isRetryDisabled = senderConfig.isRetryDisabled;
                    _maxBatchInterval = senderConfig.maxBatchInterval;
                }));
            };
            _self.processTelemetry = function (telemetryItem, itemCtx) {
                itemCtx = _self._getTelCtx(itemCtx);
                var diagLogger = itemCtx[_DYN_DIAG_LOG ]();
                try {
                    var isValidate = _validate(telemetryItem, diagLogger);
                    if (!isValidate) {
                        return;
                    }
                    var aiEnvelope = _getEnvelope(telemetryItem, diagLogger);
                    if (!aiEnvelope) {
                        return;
                    }
                    var payload = _serializer.serialize(aiEnvelope);
                    var buffer = _self[_DYN__BUFFER ];
                    _checkMaxSize(payload);
                    var payloadItem = {
                        item: payload,
                        cnt: 0
                    };
                    buffer[_DYN_ENQUEUE ](payloadItem);
                    _setupTimer();
                }
                catch (e) {
                    _throwInternal(diagLogger, 2 , 12 , "Failed adding telemetry to the sender's buffer, some telemetry will be lost: " + getExceptionName(e), { exception: dumpObj(e) });
                }
                _self.processNext(telemetryItem, itemCtx);
            };
            _self.isCompletelyIdle = function () {
                return !_paused && _syncFetchPayload === 0 && _self._buffer[_DYN_COUNT ]() === 0;
            };
            _self.getOfflineListener = function () {
                return _offlineListener;
            };
            _self._xhrReadyStateChange = function (xhr, payload, countOfItemsInPayload) {
                if (_isStringArr(payload)) {
                    return;
                }
                return _xhrReadyStateChange(xhr, payload, countOfItemsInPayload);
            };
            _self[_DYN_TRIGGER_SEND ] = function (isAsync, forcedSender, sendReason) {
                if (isAsync === void 0) { isAsync = true; }
                var result;
                if (!_paused) {
                    try {
                        var buffer = _self[_DYN__BUFFER ];
                        if (!_disableTelemetry) {
                            if (buffer[_DYN_COUNT ]() > 0) {
                                var payload = buffer.getItems();
                                _notifySendRequest(sendReason || 0 , isAsync);
                                if (forcedSender) {
                                    result = forcedSender.call(_self, payload, isAsync);
                                }
                                else {
                                    result = _self[_DYN__SENDER ](payload, isAsync);
                                }
                            }
                        }
                        else {
                            buffer[_DYN_CLEAR ]();
                        }
                        _clearScheduledTimer();
                    }
                    catch (e) {
                        var ieVer = getIEVersion();
                        if (!ieVer || ieVer > 9) {
                            _throwInternal(_self[_DYN_DIAG_LOG ](), 1 , 40 , "Telemetry transmission failed, some telemetry will be lost: " + getExceptionName(e), { exception: dumpObj(e) });
                        }
                    }
                }
                return result;
            };
            _self.getOfflineSupport = function () {
                return {
                    getUrl: function () {
                        return _endpointUrl;
                    },
                    createPayload: _createPayload,
                    serialize: _serialize,
                    batch: _batch,
                    shouldProcess: function (evt) {
                        return !!_validate(evt);
                    }
                };
            };
            _self._doTeardown = function (unloadCtx, unloadState) {
                _self.onunloadFlush();
                runTargetUnload(_offlineListener, false);
                _initDefaults();
            };
            _self[_DYN__ON_ERROR ] = function (payload, message, event) {
                if (_isStringArr(payload)) {
                    return;
                }
                return _onError(payload, message);
            };
            _self[_DYN__ON_PARTIAL_SUCCESS ] = function (payload, results) {
                if (_isStringArr(payload)) {
                    return;
                }
                return _onPartialSuccess(payload, results);
            };
            _self[_DYN__ON_SUCCESS ] = function (payload, countOfItemsInPayload) {
                if (_isStringArr(payload)) {
                    return;
                }
                return _onSuccess(payload);
            };
            _self._xdrOnLoad = function (xdr, payload) {
                if (_isStringArr(payload)) {
                    return;
                }
                return _xdrOnLoad(xdr, payload);
            };
            function _xdrOnLoad(xdr, payload) {
                var responseText = _getResponseText(xdr);
                if (xdr && (responseText + "" === "200" || responseText === "")) {
                    _consecutiveErrors = 0;
                    _self[_DYN__ON_SUCCESS ](payload, 0);
                }
                else {
                    var results = parseResponse(responseText);
                    if (results && results[_DYN_ITEMS_RECEIVED ] && results[_DYN_ITEMS_RECEIVED ] > results[_DYN_ITEMS_ACCEPTED ]
                        && !_isRetryDisabled) {
                        _self[_DYN__ON_PARTIAL_SUCCESS ](payload, results);
                    }
                    else {
                        _self[_DYN__ON_ERROR ](payload, formatErrorMessageXdr(xdr));
                    }
                }
            }
            function _getSendPostMgrConfig() {
                try {
                    var onCompleteFuncs = {
                        xdrOnComplete: function (xdr, oncomplete, payload) {
                            var payloadArr = _getPayloadArr(payload);
                            if (!payloadArr) {
                                return;
                            }
                            return _xdrOnLoad(xdr, payloadArr);
                        },
                        fetchOnComplete: function (response, onComplete, resValue, payload) {
                            var payloadArr = _getPayloadArr(payload);
                            if (!payloadArr) {
                                return;
                            }
                            return _checkResponsStatus(response.status, payloadArr, response.url, payloadArr[_DYN_LENGTH ], response.statusText, resValue || "");
                        },
                        xhrOnComplete: function (request, oncomplete, payload) {
                            var payloadArr = _getPayloadArr(payload);
                            if (!payloadArr) {
                                return;
                            }
                            return _xhrReadyStateChange(request, payloadArr, payloadArr[_DYN_LENGTH ]);
                        },
                        beaconOnRetry: function (data, onComplete, canSend) {
                            return _onBeaconRetry(data, onComplete, canSend);
                        }
                    };
                    var config = {
                        enableSendPromise: _enableSendPromise,
                        isOneDs: false,
                        disableCredentials: false,
                        disableXhr: _disableXhr,
                        disableBeacon: !_beaconNormalSupported,
                        disableBeaconSync: !_beaconOnUnloadSupported,
                        senderOnCompleteCallBack: onCompleteFuncs
                    };
                    return config;
                }
                catch (e) {
                }
                return null;
            }
            function _xhrReadyStateChange(xhr, payload, countOfItemsInPayload) {
                if (xhr.readyState === 4) {
                    _checkResponsStatus(xhr.status, payload, xhr.responseURL, countOfItemsInPayload, formatErrorMessageXhr(xhr), _getResponseText(xhr) || xhr.response);
                }
            }
            function _onError(payload, message, event) {
                _throwInternal(_self[_DYN_DIAG_LOG ](), 2 , 26 , "Failed to send telemetry.", { message: message });
                _self._buffer && _self._buffer[_DYN_CLEAR_SENT ](payload);
            }
            function _onPartialSuccess(payload, results) {
                var failed = [];
                var retry = [];
                var errors = results.errors.reverse();
                for (var _i = 0, errors_1 = errors; _i < errors_1.length; _i++) {
                    var error = errors_1[_i];
                    var extracted = payload.splice(error.index, 1)[0];
                    if (_isRetriable(error.statusCode)) {
                        retry[_DYN_PUSH ](extracted);
                    }
                    else {
                        failed[_DYN_PUSH ](extracted);
                    }
                }
                if (payload[_DYN_LENGTH ] > 0) {
                    _self[_DYN__ON_SUCCESS ](payload, results[_DYN_ITEMS_ACCEPTED ]);
                }
                if (failed[_DYN_LENGTH ] > 0) {
                    _self[_DYN__ON_ERROR ](failed, formatErrorMessageXhr(null, ["partial success", results[_DYN_ITEMS_ACCEPTED ], "of", results.itemsReceived].join(" ")));
                }
                if (retry[_DYN_LENGTH ] > 0) {
                    _resendPayload(retry);
                    _throwInternal(_self[_DYN_DIAG_LOG ](), 2 , 40 , "Partial success. " +
                        "Delivered: " + payload[_DYN_LENGTH ] + ", Failed: " + failed[_DYN_LENGTH ] +
                        ". Will retry to send " + retry[_DYN_LENGTH ] + " our of " + results[_DYN_ITEMS_RECEIVED ] + " items");
                }
            }
            function _onSuccess(payload, countOfItemsInPayload) {
                _self._buffer && _self._buffer[_DYN_CLEAR_SENT ](payload);
            }
            function _getPayloadArr(payload) {
                try {
                    if (payload) {
                        var internalPayload = payload;
                        var arr = internalPayload.oriPayload;
                        if (arr && arr[_DYN_LENGTH ]) {
                            return arr;
                        }
                        return null;
                    }
                }
                catch (e) {
                }
                return null;
            }
            function _validate(telemetryItem, diagLogger) {
                if (_disableTelemetry) {
                    return false;
                }
                if (!telemetryItem) {
                    diagLogger && _throwInternal(diagLogger, 1 , 7 , "Cannot send empty telemetry");
                    return false;
                }
                if (telemetryItem.baseData && !telemetryItem[_DYN_BASE_TYPE ]) {
                    diagLogger && _throwInternal(diagLogger, 1 , 70 , "Cannot send telemetry without baseData and baseType");
                    return false;
                }
                if (!telemetryItem[_DYN_BASE_TYPE ]) {
                    telemetryItem[_DYN_BASE_TYPE ] = "EventData";
                }
                if (!_self[_DYN__SENDER ]) {
                    diagLogger && _throwInternal(diagLogger, 1 , 28 , "Sender was not initialized");
                    return false;
                }
                if (!_isSampledIn(telemetryItem)) {
                    diagLogger && _throwInternal(diagLogger, 2 , 33 , "Telemetry item was sampled out and not sent", { SampleRate: _self._sample[_DYN_SAMPLE_RATE ] });
                    return false;
                }
                else {
                    telemetryItem[SampleRate] = _self._sample[_DYN_SAMPLE_RATE ];
                }
                return true;
            }
            function _getEnvelope(telemetryItem, diagLogger) {
                var defaultEnvelopeIkey = telemetryItem.iKey || _instrumentationKey;
                var aiEnvelope = Sender.constructEnvelope(telemetryItem, defaultEnvelopeIkey, diagLogger, _convertUndefined);
                if (!aiEnvelope) {
                    _throwInternal(diagLogger, 1 , 47 , "Unable to create an AppInsights envelope");
                    return;
                }
                var doNotSendItem = false;
                if (telemetryItem[_DYN_TAGS ] && telemetryItem[_DYN_TAGS ][ProcessLegacy]) {
                    arrForEach(telemetryItem[_DYN_TAGS ][ProcessLegacy], function (callBack) {
                        try {
                            if (callBack && callBack(aiEnvelope) === false) {
                                doNotSendItem = true;
                                _warnToConsole(diagLogger, "Telemetry processor check returns false");
                            }
                        }
                        catch (e) {
                            _throwInternal(diagLogger, 1 , 64 , "One of telemetry initializers failed, telemetry item will not be sent: " + getExceptionName(e), { exception: dumpObj(e) }, true);
                        }
                    });
                    delete telemetryItem[_DYN_TAGS ][ProcessLegacy];
                }
                if (doNotSendItem) {
                    return;
                }
                return aiEnvelope;
            }
            function _serialize(item) {
                var rlt = EMPTY_STR;
                var diagLogger = _self[_DYN_DIAG_LOG ]();
                try {
                    var valid = _validate(item, diagLogger);
                    var envelope = null;
                    if (valid) {
                        envelope = _getEnvelope(item, diagLogger);
                    }
                    if (envelope) {
                        rlt = _serializer.serialize(envelope);
                    }
                }
                catch (e) {
                }
                return rlt;
            }
            function _batch(arr) {
                var rlt = EMPTY_STR;
                if (arr && arr[_DYN_LENGTH ]) {
                    rlt = "[" + arr.join(",") + "]";
                }
                return rlt;
            }
            function _createPayload(data) {
                var headers = _getHeaders();
                return {
                    urlString: _endpointUrl,
                    data: data,
                    headers: headers
                };
            }
            function _isSampledIn(envelope) {
                return _self._sample.isSampledIn(envelope);
            }
            function _getOnComplete(payload, status, headers, response) {
                if (status === 200 && payload) {
                    _self._onSuccess(payload, payload[_DYN_LENGTH ]);
                }
                else {
                    response && _self[_DYN__ON_ERROR ](payload, response);
                }
            }
            function _doSend(sendInterface, payload, isAsync, markAsSent) {
                if (markAsSent === void 0) { markAsSent = true; }
                var onComplete = function (status, headers, response) {
                    return _getOnComplete(payload, status, headers, response);
                };
                var payloadData = _getPayload(payload);
                var sendPostFunc = sendInterface && sendInterface.sendPOST;
                if (sendPostFunc && payloadData) {
                    if (markAsSent) {
                        _self._buffer[_DYN_MARK_AS_SENT ](payload);
                    }
                    var result_2;
                    var callbackExecuted_1 = false;
                    var resolveFn_1;
                    var rejectFn_1;
                    _sendPostMgr.preparePayload(function (processedPayload) {
                        result_2 = sendPostFunc(processedPayload, onComplete, !isAsync);
                        callbackExecuted_1 = true;
                        if (resolveFn_1) {
                            doAwait(result_2, resolveFn_1, rejectFn_1);
                        }
                    }, _zipPayload, payloadData, !isAsync);
                    if (callbackExecuted_1) {
                        return result_2;
                    }
                    return createPromise(function (resolve, reject) {
                        resolveFn_1 = resolve;
                        rejectFn_1 = reject;
                    });
                }
                return null;
            }
            function _getPayload(payload) {
                if (isArray(payload) && payload[_DYN_LENGTH ] > 0) {
                    var batch = _self[_DYN__BUFFER ].batchPayloads(payload);
                    var headers = _getHeaders();
                    var payloadData = {
                        data: batch,
                        urlString: _endpointUrl,
                        headers: headers,
                        disableXhrSync: _disableXhr,
                        disableFetchKeepAlive: !_fetchKeepAlive,
                        oriPayload: payload
                    };
                    return payloadData;
                }
                return null;
            }
            function _getHeaders() {
                try {
                    var headers = _headers || {};
                    if (isInternalApplicationInsightsEndpoint(_endpointUrl)) {
                        headers[RequestHeaders[6 ]] = RequestHeaders[7 ];
                    }
                    return headers;
                }
                catch (e) {
                }
                return null;
            }
            function _checkMaxSize(incomingPayload) {
                var incomingSize = incomingPayload ? incomingPayload[_DYN_LENGTH ] : 0;
                if ((_self[_DYN__BUFFER ].size() + incomingSize) > _maxBatchSizeInBytes) {
                    if (!_offlineListener || _offlineListener.isOnline()) {
                        _self[_DYN_TRIGGER_SEND ](true, null, 10 );
                    }
                    return true;
                }
                return false;
            }
            function _checkResponsStatus(status, payload, responseUrl, countOfItemsInPayload, errorMessage, res) {
                var response = null;
                if (!_self._appId) {
                    response = parseResponse(res);
                    if (response && response.appId) {
                        _self._appId = response.appId;
                    }
                }
                if ((status < 200 || status >= 300) && status !== 0) {
                    if (status === 301 || status === 307 || status === 308) {
                        if (!_checkAndUpdateEndPointUrl(responseUrl)) {
                            _self[_DYN__ON_ERROR ](payload, errorMessage);
                            return;
                        }
                    }
                    if (_offlineListener && !_offlineListener.isOnline()) {
                        if (!_isRetryDisabled) {
                            var offlineBackOffMultiplier = 10;
                            _resendPayload(payload, offlineBackOffMultiplier);
                            _throwInternal(_self[_DYN_DIAG_LOG ](), 2 , 40 , ". Offline - Response Code: ".concat(status, ". Offline status: ").concat(!_offlineListener.isOnline(), ". Will retry to send ").concat(payload.length, " items."));
                        }
                        return;
                    }
                    if (!_isRetryDisabled && _isRetriable(status)) {
                        _resendPayload(payload);
                        _throwInternal(_self[_DYN_DIAG_LOG ](), 2 , 40 , ". " +
                            "Response code " + status + ". Will retry to send " + payload[_DYN_LENGTH ] + " items.");
                    }
                    else {
                        _self[_DYN__ON_ERROR ](payload, errorMessage);
                    }
                }
                else {
                    _checkAndUpdateEndPointUrl(responseUrl);
                    if (status === 206) {
                        if (!response) {
                            response = parseResponse(res);
                        }
                        if (response && !_isRetryDisabled) {
                            _self[_DYN__ON_PARTIAL_SUCCESS ](payload, response);
                        }
                        else {
                            _self[_DYN__ON_ERROR ](payload, errorMessage);
                        }
                    }
                    else {
                        _consecutiveErrors = 0;
                        _self[_DYN__ON_SUCCESS ](payload, countOfItemsInPayload);
                    }
                }
            }
            function _checkAndUpdateEndPointUrl(responseUrl) {
                if (_stamp_specific_redirects >= 10) {
                    return false;
                }
                if (!isNullOrUndefined(responseUrl) && responseUrl !== "") {
                    if (responseUrl !== _endpointUrl) {
                        _endpointUrl = responseUrl;
                        ++_stamp_specific_redirects;
                        return true;
                    }
                }
                return false;
            }
            function _doUnloadSend(payload, isAsync) {
                if (_syncUnloadSender) {
                    _syncUnloadSender(payload, false);
                }
                else {
                    var beaconInst = _sendPostMgr && _sendPostMgr[_DYN_GET_SENDER_INST ]([3 ], true);
                    return _doSend(beaconInst, payload, isAsync);
                }
            }
            function _onBeaconRetry(payload, onComplete, canSend) {
                var internalPayload = payload;
                var data = internalPayload && internalPayload.oriPayload;
                if (!_disableBeaconSplit) {
                    var droppedPayload = [];
                    for (var lp = 0; lp < data[_DYN_LENGTH ]; lp++) {
                        var thePayload = data[lp];
                        var arr = [thePayload];
                        var item = _getPayload(arr);
                        if (!canSend(item, onComplete)) {
                            droppedPayload[_DYN_PUSH ](thePayload);
                        }
                        else {
                            _self._onSuccess(arr, arr[_DYN_LENGTH ]);
                        }
                    }
                    if (droppedPayload[_DYN_LENGTH ] > 0) {
                        _fallbackSend && _fallbackSend(droppedPayload, true);
                        _throwInternal(_self[_DYN_DIAG_LOG ](), 2 , 40 , ". " + "Failed to send telemetry with Beacon API, retried with normal sender.");
                    }
                }
                else {
                    _fallbackSend && _fallbackSend(data, true);
                    _throwInternal(_self[_DYN_DIAG_LOG ](), 2 , 40 , ". " + "Failed to send telemetry with Beacon API, retried with normal sender.");
                }
            }
            function _isStringArr(arr) {
                try {
                    if (arr && arr[_DYN_LENGTH ]) {
                        return (isString(arr[0]));
                    }
                }
                catch (e) {
                }
                return null;
            }
            function _fetchKeepAliveSender(payload, isAsync) {
                var transport = null;
                if (isArray(payload)) {
                    var payloadSize = payload[_DYN_LENGTH ];
                    for (var lp = 0; lp < payload[_DYN_LENGTH ]; lp++) {
                        payloadSize += payload[lp].item[_DYN_LENGTH ];
                    }
                    var syncFetchPayload = _sendPostMgr.getSyncFetchPayload();
                    if ((syncFetchPayload + payloadSize) <= FetchSyncRequestSizeLimitBytes) {
                        transport = 2 ;
                    }
                    else if (isBeaconsSupported()) {
                        transport = 3 ;
                    }
                    else {
                        transport = 1 ;
                        _throwInternal(_self[_DYN_DIAG_LOG ](), 2 , 40 , ". " + "Failed to send telemetry with Beacon API, retried with xhrSender.");
                    }
                    var inst = _sendPostMgr && _sendPostMgr[_DYN_GET_SENDER_INST ]([transport], true);
                    return _doSend(inst, payload, isAsync);
                }
                return null;
            }
            function _resendPayload(payload, linearFactor) {
                if (linearFactor === void 0) { linearFactor = 1; }
                if (!payload || payload[_DYN_LENGTH ] === 0) {
                    return;
                }
                var buffer = _self[_DYN__BUFFER ];
                buffer[_DYN_CLEAR_SENT ](payload);
                _consecutiveErrors++;
                for (var _i = 0, payload_1 = payload; _i < payload_1.length; _i++) {
                    var item = payload_1[_i];
                    item.cnt = item.cnt || 0;
                    item.cnt++;
                    buffer[_DYN_ENQUEUE ](item);
                }
                _setRetryTime(linearFactor);
                _setupTimer();
            }
            function _setRetryTime(linearFactor) {
                var SlotDelayInSeconds = 10;
                var delayInSeconds;
                if (_consecutiveErrors <= 1) {
                    delayInSeconds = SlotDelayInSeconds;
                }
                else {
                    var backOffSlot = (Math.pow(2, _consecutiveErrors) - 1) / 2;
                    var backOffDelay = mathFloor(Math.random() * backOffSlot * SlotDelayInSeconds) + 1;
                    backOffDelay = linearFactor * backOffDelay;
                    delayInSeconds = mathMax(mathMin(backOffDelay, 3600), SlotDelayInSeconds);
                }
                var retryAfterTimeSpan = utcNow() + (delayInSeconds * 1000);
                _retryAt = retryAfterTimeSpan;
            }
            function _setupTimer() {
                if (!_timeoutHandle && !_paused) {
                    var retryInterval = _retryAt ? mathMax(0, _retryAt - utcNow()) : 0;
                    var timerValue = mathMax(_maxBatchInterval, retryInterval);
                    _timeoutHandle = scheduleTimeout(function () {
                        _timeoutHandle = null;
                        _self[_DYN_TRIGGER_SEND ](true, null, 1 );
                    }, timerValue);
                }
            }
            function _clearScheduledTimer() {
                _timeoutHandle && _timeoutHandle.cancel();
                _timeoutHandle = null;
                _retryAt = null;
            }
            function _isRetriable(statusCode) {
                if (!isNullOrUndefined(_retryCodes)) {
                    return _retryCodes[_DYN_LENGTH ] && _retryCodes.indexOf(statusCode) > -1;
                }
                return statusCode === 401
                    || statusCode === 408
                    || statusCode === 429
                    || statusCode === 500
                    || statusCode === 502
                    || statusCode === 503
                    || statusCode === 504;
            }
            function _getNotifyMgr() {
                var func = "getNotifyMgr";
                var result;
                var core = _self.core;
                if (core) {
                    if (core[func]) {
                        result = core[func]();
                    }
                    else {
                        result = core["_notificationManager"];
                    }
                }
                return result;
            }
            function _notifySendRequest(sendRequest, isAsync) {
                var manager = _getNotifyMgr();
                if (manager && manager.eventsSendRequest) {
                    try {
                        manager.eventsSendRequest(sendRequest, isAsync);
                    }
                    catch (e) {
                        _throwInternal(_self[_DYN_DIAG_LOG ](), 1 , 74 , "send request notification failed: " + getExceptionName(e), { exception: dumpObj(e) });
                    }
                }
            }
            function _validateInstrumentationKey(instrumentationKey, config) {
                var disableValidation = config.disableInstrumentationKeyValidation;
                var disableIKeyValidationFlag = isNullOrUndefined(disableValidation) ? false : disableValidation;
                if (disableIKeyValidationFlag) {
                    return true;
                }
                var UUID_Regex = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$";
                var regexp = new RegExp(UUID_Regex);
                return regexp.test(instrumentationKey);
            }
            function _initDefaults() {
                _self[_DYN__SENDER ] = null;
                _self[_DYN__BUFFER ] = null;
                _self._appId = null;
                _self._sample = null;
                _headers = {};
                _offlineListener = null;
                _consecutiveErrors = 0;
                _retryAt = null;
                _paused = false;
                _timeoutHandle = null;
                _serializer = null;
                _stamp_specific_redirects = 0;
                _syncFetchPayload = 0;
                _syncUnloadSender = null;
                _evtNamespace = null;
                _endpointUrl = null;
                _orgEndpointUrl = null;
                _maxBatchSizeInBytes = 0;
                _beaconSupported = false;
                _customHeaders = null;
                _disableTelemetry = false;
                _instrumentationKey = null;
                _convertUndefined = UNDEFINED_VALUE;
                _isRetryDisabled = false;
                _sessionStorageUsed = null;
                _namePrefix = UNDEFINED_VALUE;
                _disableXhr = false;
                _fetchKeepAlive = false;
                _disableBeaconSplit = false;
                _xhrSend = null;
                _fallbackSend = null;
                _sendPostMgr = null;
                objDefine(_self, "_senderConfig", {
                    g: function () {
                        return objExtend({}, defaultAppInsightsChannelConfig);
                    }
                });
            }
        });
        return _this;
    }
    Sender.constructEnvelope = function (orig, iKey, logger, convertUndefined) {
        var envelope;
        if (iKey !== orig.iKey && !isNullOrUndefined(iKey)) {
            envelope = __assignFn(__assignFn({}, orig), { iKey: iKey });
        }
        else {
            envelope = orig;
        }
        var creator = EnvelopeTypeCreator[envelope.baseType] || EventEnvelopeCreator;
        return creator(logger, envelope, convertUndefined);
    };
    return Sender;
}(BaseTelemetryPlugin));

exports.Sender = Sender;

}));
//# sourceMappingURL=applicationinsights-channel-js.3.3.10.gbl.js.map
