/*
 * Application Insights JavaScript SDK - Dependencies Plugin, 3.3.9-nightly3.2505-37
 * Copyright (c) Microsoft and contributors. All rights reserved.
 */


var _a;
import { __assignFn as __assign, __extendsFn as __extends } from "@microsoft/applicationinsights-shims";
import dynamicProto from "@microsoft/dynamicproto-js";
import { DisabledPropertyName, PropertiesPluginIdentifier, RemoteDependencyData, RequestHeaders, correlationIdCanIncludeCorrelationHeader, correlationIdGetCorrelationContext, createDistributedTraceContextFromTrace, createTelemetryItem, createTraceParent, dateTimeUtilsNow, formatTraceParent, isInternalApplicationInsightsEndpoint } from "@microsoft/applicationinsights-common";
import { BaseTelemetryPlugin, InstrumentFunc, InstrumentProto, _throwInternal, arrForEach, createProcessTelemetryContext, createUniqueNamespace, dumpObj, eventOn, generateW3CId, getExceptionName, getGlobal, getIEVersion, getLocation, getPerformance, isFunction, isNullOrUndefined, isString, isXhrSupported, mergeEvtNamespace, onConfigChange, strPrototype, strTrim } from "@microsoft/applicationinsights-core-js";
import { isWebWorker, objFreeze, scheduleTimeout, strIndexOf, strSplit, strSubstr } from "@nevware21/ts-utils";
import { STR_PROPERTIES } from "./InternalConstants";
import { _DYN_ABORTED, _DYN_AJAX_DIAGNOSTICS_MES14, _DYN_AJAX_PERF_LOOKUP_DEL8, _DYN_CONTEXT, _DYN_CORE, _DYN_CORRELATION_CONTEXT, _DYN_DISABLE_AJAX_TRACKIN7, _DYN_DISABLE_FETCH_TRACKI9, _DYN_ENABLE_AJAX_ERROR_ST3, _DYN_ENABLE_AJAX_PERF_TRA4, _DYN_ENABLE_REQUEST_HEADE2, _DYN_ENABLE_RESPONSE_HEAD10, _DYN_ERROR_STATUS_TEXT, _DYN_EXCLUDE_REQUEST_FROM6, _DYN_GET_ABSOLUTE_URL, _DYN_GET_ALL_RESPONSE_HEA13, _DYN_GET_PART_APROPS, _DYN_GET_TRACE_FLAGS, _DYN_GET_TRACE_ID, _DYN_HEADERS, _DYN_HEADER_MAP, _DYN_INCLUDE_CORRELATION_0, _DYN_LENGTH, _DYN_MAX_AJAX_CALLS_PER_V5, _DYN_METHOD, _DYN_PERF_MARK, _DYN_PERF_TIMING, _DYN_REQUEST_HEADERS, _DYN_REQUEST_SENT_TIME, _DYN_REQUEST_URL, _DYN_RESPONSE_FINISHED_TI12, _DYN_RESPONSE_TEXT, _DYN_SET_REQUEST_HEADER, _DYN_SPAN_ID, _DYN_START_TIME, _DYN_STATE_CHANGE_ATTACHE11, _DYN_STATUS, _DYN_STATUS_TEXT, _DYN_TO_LOWER_CASE, _DYN_TRACE_FLAGS, _DYN_TRACE_ID, _DYN_TRACK_DEPENDENCY_DAT1, _DYN__ADD_HOOK, _DYN__CREATE_TRACK_ITEM } from "./__DynamicConstants";
import { ajaxRecord } from "./ajaxRecord";
// const AJAX_MONITOR_PREFIX = "ai.ajxmn.";
var strDiagLog = "diagLog";
var AJAX_DATA_CONTAINER = "_ajaxData";
var STR_FETCH = "fetch";
var ERROR_HEADER = "Failed to monitor XMLHttpRequest";
var ERROR_PREFIX = ", monitoring data for this ajax call ";
var ERROR_POSTFIX = ERROR_PREFIX + "may be incorrect.";
var ERROR_NOT_SENT = ERROR_PREFIX + "won't be sent.";
var CORRELATION_HEADER_ERROR = "Failed to get Request-Context correlation header as it may be not included in the response or not accessible.";
var CUSTOM_REQUEST_CONTEXT_ERROR = "Failed to add custom defined request context as configured call back may missing a null check.";
var FAILED_TO_CALCULATE_DURATION_ERROR = "Failed to calculate the duration of the ";
// Using a global value so that to handle same iKey with multiple app insights instances (mostly for testing)
var _markCount = 0;
/** @Ignore */
function _supportsFetch() {
    var _global = getGlobal();
    if (!_global ||
        isNullOrUndefined(_global.Request) ||
        isNullOrUndefined(_global.Request[strPrototype]) ||
        isNullOrUndefined(_global[STR_FETCH])) {
        return null;
    }
    return _global[STR_FETCH];
}
/**
 * Determines whether ajax monitoring can be enabled on this document
 * @returns True if Ajax monitoring is supported on this page, otherwise false
 * @ignore
 */
function _supportsAjaxMonitoring(ajaxMonitorInstance, ajaxDataId) {
    var _a;
    var result = false;
    if (isXhrSupported()) {
        var proto = XMLHttpRequest[strPrototype];
        result = !isNullOrUndefined(proto) &&
            !isNullOrUndefined(proto.open) && // eslint-disable-line security/detect-non-literal-fs-filename -- false positive
            !isNullOrUndefined(proto.send) &&
            !isNullOrUndefined(proto.abort);
    }
    var ieVer = getIEVersion();
    if (ieVer && ieVer < 9) {
        result = false;
    }
    if (result) {
        // Disable if the XmlHttpRequest can't be extended or hooked
        try {
            var xhr = new XMLHttpRequest();
            var xhrData = {
                xh: [],
                i: (_a = {},
                    _a[ajaxDataId] = {},
                    _a)
            };
            xhr[AJAX_DATA_CONTAINER] = xhrData;
            // Check that we can update the prototype
            var theOpen = XMLHttpRequest[strPrototype].open;
            XMLHttpRequest[strPrototype].open = theOpen;
        }
        catch (e) {
            // We can't decorate the xhr object so disable monitoring
            result = false;
            _throwInternalCritical(ajaxMonitorInstance, 15 /* _eInternalMessageId.FailedMonitorAjaxOpen */, "Failed to enable XMLHttpRequest monitoring, extension is not supported", {
                exception: dumpObj(e)
            });
        }
    }
    return result;
}
/**
 * Internal helper to fetch the SDK instance tracking data for this XHR request
 * @param xhr
 * @param ajaxDataId
 * @returns
 */
var _getAjaxData = function (xhr, ajaxDataId) {
    if (xhr && ajaxDataId && xhr[AJAX_DATA_CONTAINER]) {
        return (xhr[AJAX_DATA_CONTAINER].i || {})[ajaxDataId];
    }
    return null;
};
/**
 * @ignore
 * Internal helper to track the singleton shared tracking headers, so we can attempt to not create headers
 * that might cause an issue if multiple values are populated.
 * @param xhr - The instrumented XHR instance
 */
var _addSharedXhrHeaders = function (xhr, name, value) {
    if (xhr) {
        var headers = (xhr[AJAX_DATA_CONTAINER] || {}).xh;
        if (headers) {
            headers.push({
                n: name,
                v: value
            });
        }
    }
};
var _isHeaderSet = function (xhr, name) {
    var isPresent = false;
    if (xhr) {
        var headers = (xhr[AJAX_DATA_CONTAINER] || {}).xh;
        if (headers) {
            arrForEach(headers, function (header) {
                if (header.n === name) {
                    isPresent = true;
                    return -1;
                }
            });
        }
    }
    return isPresent;
};
/** @Ignore */
function _getFailedAjaxDiagnosticsMessage(xhr, ajaxDataId) {
    var result = "";
    try {
        var ajaxData = _getAjaxData(xhr, ajaxDataId);
        if (ajaxData && ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */]) {
            result += "(url: '" + ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */] + "')";
        }
    }
    catch (e) {
        // eslint-disable-next-line no-empty
    }
    return result;
}
/** @ignore */
function _throwInternalCritical(ajaxMonitorInstance, msgId, message, properties, isUserAct) {
    _throwInternal(ajaxMonitorInstance[strDiagLog](), 1 /* eLoggingSeverity.CRITICAL */, msgId, message, properties, isUserAct);
}
/** @ignore */
function _throwInternalWarning(ajaxMonitorInstance, msgId, message, properties, isUserAct) {
    _throwInternal(ajaxMonitorInstance[strDiagLog](), 2 /* eLoggingSeverity.WARNING */, msgId, message, properties, isUserAct);
}
/** @Ignore */
function _createErrorCallbackFunc(ajaxMonitorInstance, internalMessage, message) {
    // tslint:disable-next-line
    return function (callDetails) {
        var _a;
        _throwInternalCritical(ajaxMonitorInstance, internalMessage, message, (_a = {},
            _a[_DYN_AJAX_DIAGNOSTICS_MES14 /* @min:ajaxDiagnosticsMessage */] = _getFailedAjaxDiagnosticsMessage(callDetails.inst, ajaxMonitorInstance._ajaxDataId),
            _a.exception = dumpObj(callDetails.err),
            _a));
    };
}
function _indexOf(value, match) {
    if (value && match) {
        return strIndexOf(value, match);
    }
    return -1;
}
function _addHandler(container, id, theFunc) {
    var theHandler = {
        id: id,
        fn: theFunc
    };
    container.push(theHandler);
    return {
        remove: function () {
            arrForEach(container, function (initializer, idx) {
                if (initializer.id === theHandler.id) {
                    container.splice(idx, 1);
                    return -1;
                }
            });
        }
    };
}
function _processDependencyContainer(core, container, details, message) {
    var result = true;
    arrForEach(container, function (theFunc, idx) {
        try {
            if (theFunc.fn.call(null, details) === false) {
                result = false;
            }
        }
        catch (e) {
            _throwInternal(core && core.logger, 1 /* eLoggingSeverity.CRITICAL */, 64 /* _eInternalMessageId.TelemetryInitializerFailed */, "Dependency " + message + " [#" + idx + "] failed: " + getExceptionName(e), { exception: dumpObj(e) }, true);
        }
    });
    return result;
}
function _processDependencyListeners(listeners, core, ajaxData, xhr, input, init) {
    var initializersCount = listeners[_DYN_LENGTH /* @min:%2elength */];
    var result = true;
    if (initializersCount > 0) {
        var details = {
            core: core,
            xhr: xhr,
            input: input,
            init: init,
            traceId: ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */],
            spanId: ajaxData[_DYN_SPAN_ID /* @min:%2espanID */],
            traceFlags: ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */],
            context: ajaxData[_DYN_CONTEXT /* @min:%2econtext */] || {},
            aborted: !!ajaxData[_DYN_ABORTED /* @min:%2eaborted */]
        };
        result = _processDependencyContainer(core, listeners, details, "listener");
        ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */] = details.traceId;
        ajaxData[_DYN_SPAN_ID /* @min:%2espanID */] = details.spanId;
        ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = details[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */];
        ajaxData[_DYN_CONTEXT /* @min:%2econtext */] = details[_DYN_CONTEXT /* @min:%2econtext */];
    }
    return result;
}
var BLOB_CORE = "*.blob.core.";
export var DfltAjaxCorrelationHeaderExDomains = objFreeze([
    BLOB_CORE + "windows.net",
    BLOB_CORE + "chinacloudapi.cn",
    BLOB_CORE + "cloudapi.de",
    BLOB_CORE + "usgovcloudapi.net"
]);
var _internalExcludeEndpoints = [
    /https:\/\/[^\/]*(\.pipe\.aria|aria\.pipe|events\.data|collector\.azure)\.[^\/]+\/(OneCollector\/1|Collector\/3)\.0/i
];
var _defaultConfig = objFreeze((_a = {},
    _a[_DYN_MAX_AJAX_CALLS_PER_V5 /* @min:maxAjaxCallsPerView */] = 500,
    _a[_DYN_DISABLE_AJAX_TRACKIN7 /* @min:disableAjaxTracking */] = false,
    _a[_DYN_DISABLE_FETCH_TRACKI9 /* @min:disableFetchTracking */] = false,
    _a[_DYN_EXCLUDE_REQUEST_FROM6 /* @min:excludeRequestFromAutoTrackingPatterns */] = undefined,
    _a.disableCorrelationHeaders = false,
    _a.distributedTracingMode = 1 /* eDistributedTracingModes.AI_AND_W3C */,
    _a.correlationHeaderExcludedDomains = DfltAjaxCorrelationHeaderExDomains,
    _a.correlationHeaderDomains = undefined,
    _a.correlationHeaderExcludePatterns = undefined,
    _a.appId = undefined,
    _a.enableCorsCorrelation = false,
    _a[_DYN_ENABLE_REQUEST_HEADE2 /* @min:enableRequestHeaderTracking */] = false,
    _a[_DYN_ENABLE_RESPONSE_HEAD10 /* @min:enableResponseHeaderTracking */] = false,
    _a[_DYN_ENABLE_AJAX_ERROR_ST3 /* @min:enableAjaxErrorStatusText */] = false,
    _a[_DYN_ENABLE_AJAX_PERF_TRA4 /* @min:enableAjaxPerfTracking */] = false,
    _a.maxAjaxPerfLookupAttempts = 3,
    _a[_DYN_AJAX_PERF_LOOKUP_DEL8 /* @min:ajaxPerfLookupDelay */] = 25,
    _a.ignoreHeaders = [
        "Authorization",
        "X-API-Key",
        "WWW-Authenticate"
    ],
    _a.addRequestContext = undefined,
    _a.addIntEndpoints = true,
    _a));
var AjaxMonitor = /** @class */ (function (_super) {
    __extends(AjaxMonitor, _super);
    function AjaxMonitor() {
        var _this = _super.call(this) || this;
        _this.identifier = AjaxMonitor.identifier;
        _this.priority = 120;
        var _fetchInitialized; // fetch monitoring initialized
        var _xhrInitialized; // XHR monitoring initialized
        var _currentWindowHost;
        var _extensionConfig;
        var _enableRequestHeaderTracking;
        var _enableAjaxErrorStatusText;
        var _trackAjaxAttempts;
        var _context;
        var _isUsingW3CHeaders;
        var _isUsingAIHeaders;
        var _markPrefix;
        var _enableAjaxPerfTracking;
        var _maxAjaxCallsPerView;
        var _enableResponseHeaderTracking;
        var _disabledUrls;
        var _disableAjaxTracking;
        var _disableFetchTracking;
        var _excludeRequestFromAutoTrackingPatterns;
        var _addRequestContext;
        var _evtNamespace;
        var _ajaxDataId;
        var _dependencyHandlerId;
        var _dependencyListeners;
        var _dependencyInitializers;
        var _ignoreHeaders;
        var _maxAjaxPerfLookupAttempts;
        var _ajaxPerfLookupDelay;
        var _distributedTracingMode;
        var _appId;
        var _polyfillInitialized;
        dynamicProto(AjaxMonitor, _this, function (_self, _base) {
            var _addHook = _base[_DYN__ADD_HOOK /* @min:%2e_addHook */];
            _initDefaults();
            _self.initialize = function (config, core, extensions, pluginChain) {
                if (!_self.isInitialized()) {
                    _base.initialize(config, core, extensions, pluginChain);
                    _evtNamespace = mergeEvtNamespace(createUniqueNamespace("ajax"), core && core.evtNamespace && core.evtNamespace());
                    _populateDefaults(config);
                    _instrumentXhr();
                    _instrumentFetch();
                    _populateContext();
                }
            };
            _self._doTeardown = function () {
                _initDefaults();
            };
            _self.trackDependencyData = function (dependency, properties) {
                _reportDependencyInternal(_dependencyInitializers, _self[_DYN_CORE /* @min:%2ecore */], null, dependency, properties);
            };
            _self[_DYN_INCLUDE_CORRELATION_0 /* @min:%2eincludeCorrelationHeaders */] = function (ajaxData, input, init, xhr) {
                // Test Hook to allow the overriding of the location host
                var currentWindowHost = _self["_currentWindowHost"] || _currentWindowHost;
                if (_processDependencyListeners(_dependencyListeners, _self[_DYN_CORE /* @min:%2ecore */], ajaxData, xhr, input, init)) {
                    if (input || input === "") { // Fetch
                        if (correlationIdCanIncludeCorrelationHeader(_extensionConfig, ajaxData[_DYN_GET_ABSOLUTE_URL /* @min:%2egetAbsoluteUrl */](), currentWindowHost)) {
                            if (!init) {
                                init = {};
                            }
                            // init headers override original request headers
                            // so, if they exist use only them, otherwise use request's because they should have been applied in the first place
                            // not using original request headers will result in them being lost
                            var headers = new Headers(init[_DYN_HEADERS /* @min:%2eheaders */] || (input instanceof Request ? (input[_DYN_HEADERS /* @min:%2eheaders */] || {}) : {}));
                            if (_isUsingAIHeaders) {
                                var id = "|" + ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */] + "." + ajaxData[_DYN_SPAN_ID /* @min:%2espanID */];
                                headers.set(RequestHeaders[3 /* eRequestHeaders.requestIdHeader */], id);
                                if (_enableRequestHeaderTracking) {
                                    ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[3 /* eRequestHeaders.requestIdHeader */]] = id;
                                }
                            }
                            var appId = _appId || (_context && _context.appId());
                            if (appId) {
                                headers.set(RequestHeaders[0 /* eRequestHeaders.requestContextHeader */], RequestHeaders[2 /* eRequestHeaders.requestContextAppIdFormat */] + appId);
                                if (_enableRequestHeaderTracking) {
                                    ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[0 /* eRequestHeaders.requestContextHeader */]] = RequestHeaders[2 /* eRequestHeaders.requestContextAppIdFormat */] + appId;
                                }
                            }
                            if (_isUsingW3CHeaders) {
                                var traceFlags = ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */];
                                if (isNullOrUndefined(traceFlags)) {
                                    traceFlags = 0x01;
                                }
                                var traceParent = formatTraceParent(createTraceParent(ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */], ajaxData[_DYN_SPAN_ID /* @min:%2espanID */], traceFlags));
                                headers.set(RequestHeaders[4 /* eRequestHeaders.traceParentHeader */], traceParent);
                                if (_enableRequestHeaderTracking) {
                                    ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[4 /* eRequestHeaders.traceParentHeader */]] = traceParent;
                                }
                            }
                            init[_DYN_HEADERS /* @min:%2eheaders */] = headers;
                        }
                        return init;
                    }
                    else if (xhr) { // XHR
                        if (correlationIdCanIncludeCorrelationHeader(_extensionConfig, ajaxData[_DYN_GET_ABSOLUTE_URL /* @min:%2egetAbsoluteUrl */](), currentWindowHost)) {
                            if (_isUsingAIHeaders) {
                                if (!_isHeaderSet(xhr, RequestHeaders[3 /* eRequestHeaders.requestIdHeader */])) {
                                    var id = "|" + ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */] + "." + ajaxData[_DYN_SPAN_ID /* @min:%2espanID */];
                                    xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](RequestHeaders[3 /* eRequestHeaders.requestIdHeader */], id);
                                    if (_enableRequestHeaderTracking) {
                                        ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[3 /* eRequestHeaders.requestIdHeader */]] = id;
                                    }
                                }
                                else {
                                    _throwInternalWarning(_self, 71 /* _eInternalMessageId.FailedMonitorAjaxSetRequestHeader */, "Unable to set [" + RequestHeaders[3 /* eRequestHeaders.requestIdHeader */] + "] as it has already been set by another instance");
                                }
                            }
                            var appId = _appId || (_context && _context.appId());
                            if (appId) {
                                if (!_isHeaderSet(xhr, RequestHeaders[0 /* eRequestHeaders.requestContextHeader */])) {
                                    xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](RequestHeaders[0 /* eRequestHeaders.requestContextHeader */], RequestHeaders[2 /* eRequestHeaders.requestContextAppIdFormat */] + appId);
                                    if (_enableRequestHeaderTracking) {
                                        ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[0 /* eRequestHeaders.requestContextHeader */]] = RequestHeaders[2 /* eRequestHeaders.requestContextAppIdFormat */] + appId;
                                    }
                                }
                                else {
                                    _throwInternalWarning(_self, 71 /* _eInternalMessageId.FailedMonitorAjaxSetRequestHeader */, "Unable to set [" + RequestHeaders[0 /* eRequestHeaders.requestContextHeader */] + "] as it has already been set by another instance");
                                }
                            }
                            if (_isUsingW3CHeaders) {
                                var traceFlags = ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */];
                                if (isNullOrUndefined(traceFlags)) {
                                    traceFlags = 0x01;
                                }
                                if (!_isHeaderSet(xhr, RequestHeaders[4 /* eRequestHeaders.traceParentHeader */])) {
                                    var traceParent = formatTraceParent(createTraceParent(ajaxData[_DYN_TRACE_ID /* @min:%2etraceID */], ajaxData[_DYN_SPAN_ID /* @min:%2espanID */], traceFlags));
                                    xhr[_DYN_SET_REQUEST_HEADER /* @min:%2esetRequestHeader */](RequestHeaders[4 /* eRequestHeaders.traceParentHeader */], traceParent);
                                    if (_enableRequestHeaderTracking) {
                                        ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][RequestHeaders[4 /* eRequestHeaders.traceParentHeader */]] = traceParent;
                                    }
                                }
                                else {
                                    _throwInternalWarning(_self, 71 /* _eInternalMessageId.FailedMonitorAjaxSetRequestHeader */, "Unable to set [" + RequestHeaders[4 /* eRequestHeaders.traceParentHeader */] + "] as it has already been set by another instance");
                                }
                            }
                        }
                        return xhr;
                    }
                }
                return undefined;
            };
            _self[_DYN_TRACK_DEPENDENCY_DAT1 /* @min:%2etrackDependencyDataInternal */] = function (dependency, properties, systemProperties) {
                if (_maxAjaxCallsPerView === -1 || _trackAjaxAttempts < _maxAjaxCallsPerView) {
                    // Hack since expected format in w3c mode is |abc.def.
                    // Non-w3c format is |abc.def
                    // @todo Remove if better solution is available, e.g. handle in portal
                    if ((_distributedTracingMode === 2 /* eDistributedTracingModes.W3C */
                        || _distributedTracingMode === 1 /* eDistributedTracingModes.AI_AND_W3C */)
                        && typeof dependency.id === "string" && dependency.id[dependency.id[_DYN_LENGTH /* @min:%2elength */] - 1] !== ".") {
                        dependency.id += ".";
                    }
                    if (isNullOrUndefined(dependency[_DYN_START_TIME /* @min:%2estartTime */])) {
                        dependency[_DYN_START_TIME /* @min:%2estartTime */] = new Date();
                    }
                    var item = createTelemetryItem(dependency, RemoteDependencyData.dataType, RemoteDependencyData.envelopeType, _self[strDiagLog](), properties, systemProperties);
                    _self[_DYN_CORE /* @min:%2ecore */].track(item);
                }
                else if (_trackAjaxAttempts === _maxAjaxCallsPerView) {
                    _throwInternalCritical(_self, 55 /* _eInternalMessageId.MaxAjaxPerPVExceeded */, "Maximum ajax per page view limit reached, ajax monitoring is paused until the next trackPageView(). In order to increase the limit set the maxAjaxCallsPerView configuration parameter.", true);
                }
                ++_trackAjaxAttempts;
            };
            _self.addDependencyListener = function (dependencyListener) {
                return _addHandler(_dependencyListeners, _dependencyHandlerId++, dependencyListener);
            };
            _self.addDependencyInitializer = function (dependencyInitializer) {
                return _addHandler(_dependencyInitializers, _dependencyHandlerId++, dependencyInitializer);
            };
            function _initDefaults() {
                var location = getLocation();
                _fetchInitialized = false; // fetch monitoring initialized
                _xhrInitialized = false; // XHR monitoring initialized
                _polyfillInitialized = false; // polyfill monitoring initialized
                _currentWindowHost = location && location.host && location.host[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();
                _extensionConfig = null;
                _enableRequestHeaderTracking = false;
                _enableAjaxErrorStatusText = false;
                _trackAjaxAttempts = 0;
                _context = null;
                _isUsingW3CHeaders = false;
                _isUsingAIHeaders = false;
                _markPrefix = null;
                _enableAjaxPerfTracking = false;
                _maxAjaxCallsPerView = 0;
                _enableResponseHeaderTracking = false;
                _disabledUrls = {};
                _disableAjaxTracking = false;
                _disableFetchTracking = false;
                _excludeRequestFromAutoTrackingPatterns = null;
                _addRequestContext = null;
                _evtNamespace = null;
                _dependencyHandlerId = 0;
                _dependencyListeners = [];
                _dependencyInitializers = [];
                _ajaxDataId = createUniqueNamespace("ajaxData");
                _self._ajaxDataId = _ajaxDataId;
                _ignoreHeaders = null;
                _maxAjaxPerfLookupAttempts = 1;
                _ajaxPerfLookupDelay = 1;
                _distributedTracingMode = 1 /* eDistributedTracingModes.AI_AND_W3C */;
                _appId = null;
            }
            function _populateDefaults(config) {
                _self[_DYN__ADD_HOOK /* @min:%2e_addHook */](onConfigChange(config, function (details) {
                    var config = details.cfg;
                    var ctx = createProcessTelemetryContext(null, config, _self[_DYN_CORE /* @min:%2ecore */]);
                    _extensionConfig = ctx.getExtCfg(AjaxMonitor.identifier, _defaultConfig);
                    _distributedTracingMode = _extensionConfig.distributedTracingMode;
                    _enableRequestHeaderTracking = _extensionConfig[_DYN_ENABLE_REQUEST_HEADE2 /* @min:%2eenableRequestHeaderTracking */];
                    _enableAjaxErrorStatusText = _extensionConfig[_DYN_ENABLE_AJAX_ERROR_ST3 /* @min:%2eenableAjaxErrorStatusText */];
                    _enableAjaxPerfTracking = _extensionConfig[_DYN_ENABLE_AJAX_PERF_TRA4 /* @min:%2eenableAjaxPerfTracking */];
                    _maxAjaxCallsPerView = _extensionConfig[_DYN_MAX_AJAX_CALLS_PER_V5 /* @min:%2emaxAjaxCallsPerView */];
                    _excludeRequestFromAutoTrackingPatterns = [].concat(_extensionConfig[_DYN_EXCLUDE_REQUEST_FROM6 /* @min:%2eexcludeRequestFromAutoTrackingPatterns */] || [], _extensionConfig.addIntEndpoints !== false ? _internalExcludeEndpoints : []);
                    _addRequestContext = _extensionConfig.addRequestContext;
                    _isUsingAIHeaders = _distributedTracingMode === 0 /* eDistributedTracingModes.AI */ || _distributedTracingMode === 1 /* eDistributedTracingModes.AI_AND_W3C */;
                    _isUsingW3CHeaders = _distributedTracingMode === 1 /* eDistributedTracingModes.AI_AND_W3C */ || _distributedTracingMode === 2 /* eDistributedTracingModes.W3C */;
                    if (_enableAjaxPerfTracking) {
                        _markPrefix = _ajaxDataId;
                    }
                    _disableAjaxTracking = !!_extensionConfig[_DYN_DISABLE_AJAX_TRACKIN7 /* @min:%2edisableAjaxTracking */];
                    _maxAjaxPerfLookupAttempts = _extensionConfig.maxAjaxPerfLookupAttempts;
                    _ajaxPerfLookupDelay = _extensionConfig[_DYN_AJAX_PERF_LOOKUP_DEL8 /* @min:%2eajaxPerfLookupDelay */];
                    _ignoreHeaders = _extensionConfig.ignoreHeaders;
                    _appId = _extensionConfig.appId;
                }));
            }
            function _populateContext() {
                var propExt = _self[_DYN_CORE /* @min:%2ecore */].getPlugin(PropertiesPluginIdentifier);
                if (propExt) {
                    _context = propExt.plugin[_DYN_CONTEXT /* @min:%2econtext */]; // we could move IPropertiesPlugin to common as well
                }
            }
            // discard the header if it's defined as ignoreHeaders in ICorrelationConfig
            function _canIncludeHeaders(header) {
                var rlt = true;
                if (header || _ignoreHeaders) {
                    arrForEach(_ignoreHeaders, (function (key) {
                        if (key[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]() === header[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]()) {
                            rlt = false;
                            return -1;
                        }
                    }));
                }
                return rlt;
            }
            // Fetch Stuff
            function _instrumentFetch() {
                var fetch = _supportsFetch();
                if (!fetch) {
                    return;
                }
                var global = getGlobal();
                var isPolyfill = fetch.polyfill;
                _self[_DYN__ADD_HOOK /* @min:%2e_addHook */](onConfigChange(_extensionConfig, function () {
                    _disableFetchTracking = !!_extensionConfig[_DYN_DISABLE_FETCH_TRACKI9 /* @min:%2edisableFetchTracking */];
                    _enableResponseHeaderTracking = _extensionConfig[_DYN_ENABLE_RESPONSE_HEAD10 /* @min:%2eenableResponseHeaderTracking */];
                    if (!_disableFetchTracking && !_fetchInitialized) {
                        _addHook(InstrumentFunc(global, STR_FETCH, {
                            ns: _evtNamespace,
                            // Add request hook
                            req: function (callDetails, input, init) {
                                var fetchData;
                                if (!_disableFetchTracking && _fetchInitialized &&
                                    !_isDisabledRequest(null, input, init) &&
                                    // If we have a polyfil and XHR instrumented then let XHR report otherwise we get duplicates
                                    !(isPolyfill && _xhrInitialized)) {
                                    var ctx = callDetails.ctx();
                                    fetchData = _createFetchRecord(input, init);
                                    var newInit = _self[_DYN_INCLUDE_CORRELATION_0 /* @min:%2eincludeCorrelationHeaders */](fetchData, input, init);
                                    if (newInit !== init) {
                                        callDetails.set(1, newInit);
                                    }
                                    ctx.data = fetchData;
                                }
                            },
                            rsp: function (callDetails, input) {
                                if (!_disableFetchTracking) {
                                    var fetchData_1 = callDetails.ctx().data;
                                    if (fetchData_1) {
                                        // Replace the result with the new promise from this code
                                        callDetails.rslt = callDetails.rslt.then(function (response) {
                                            _reportFetchMetrics(callDetails, (response || {})[_DYN_STATUS /* @min:%2estatus */], input, response, fetchData_1, function () {
                                                var _a;
                                                var ajaxResponse = (_a = {
                                                        statusText: (response || {})[_DYN_STATUS_TEXT /* @min:%2estatusText */],
                                                        headerMap: null
                                                    },
                                                    _a[_DYN_CORRELATION_CONTEXT /* @min:correlationContext */] = _getFetchCorrelationContext(response),
                                                    _a);
                                                if (_enableResponseHeaderTracking && response) {
                                                    var responseHeaderMap_1 = {};
                                                    response.headers.forEach(function (value, name) {
                                                        if (_canIncludeHeaders(name)) {
                                                            responseHeaderMap_1[name] = value;
                                                        }
                                                    });
                                                    ajaxResponse[_DYN_HEADER_MAP /* @min:%2eheaderMap */] = responseHeaderMap_1;
                                                }
                                                return ajaxResponse;
                                            });
                                            return response;
                                        })
                                            .catch(function (reason) {
                                            _reportFetchMetrics(callDetails, 0, input, null, fetchData_1, null, { error: reason.message || dumpObj(reason) });
                                            throw reason;
                                        });
                                    }
                                }
                            },
                            // Create an error callback to report any hook errors
                            hkErr: _createErrorCallbackFunc(_self, 15 /* _eInternalMessageId.FailedMonitorAjaxOpen */, "Failed to monitor Window.fetch" + ERROR_POSTFIX)
                        }, true, isWebWorker()));
                        _fetchInitialized = true;
                    }
                    else if (isPolyfill && !_polyfillInitialized) {
                        // If fetch is a polyfill we need to capture the request to ensure that we correctly track
                        // disabled request URLS (i.e. internal urls) to ensure we don't end up in a constant loop
                        // of reporting ourselves, for example React Native uses a polyfill for fetch
                        // Note: Polyfill implementations that don't support the "polyfill" tag are not supported
                        // the workaround is to add a polyfill property to your fetch implementation before initializing
                        // App Insights
                        _addHook(InstrumentFunc(global, STR_FETCH, {
                            ns: _evtNamespace,
                            req: function (callDetails, input, init) {
                                // Just call so that we record any disabled URL
                                _isDisabledRequest(null, input, init);
                            }
                        }));
                        _polyfillInitialized = true;
                    }
                }));
                if (isPolyfill) {
                    // retag the instrumented fetch with the same polyfill settings this is mostly for testing
                    // But also supports multiple App Insights usages
                    global[STR_FETCH].polyfill = isPolyfill;
                }
            }
            function _hookProto(target, funcName, callbacks) {
                _addHook(InstrumentProto(target, funcName, callbacks));
            }
            function _instrumentXhr() {
                if (!_supportsAjaxMonitoring(_self, _ajaxDataId)) {
                    return;
                }
                _self[_DYN__ADD_HOOK /* @min:%2e_addHook */](onConfigChange(_extensionConfig, function () {
                    _disableAjaxTracking = !!_extensionConfig[_DYN_DISABLE_AJAX_TRACKIN7 /* @min:%2edisableAjaxTracking */];
                    _enableRequestHeaderTracking = _extensionConfig[_DYN_ENABLE_REQUEST_HEADE2 /* @min:%2eenableRequestHeaderTracking */];
                    if (!_disableAjaxTracking && !_xhrInitialized) {
                        // Instrument open
                        _hookProto(XMLHttpRequest, "open", {
                            ns: _evtNamespace,
                            req: function (callDetails, method, url, async) {
                                if (!_disableAjaxTracking) {
                                    var xhr = callDetails.inst;
                                    var ajaxData = _getAjaxData(xhr, _ajaxDataId);
                                    if (!_isDisabledRequest(xhr, url) && _isMonitoredXhrInstance(xhr, ajaxData, true)) {
                                        if (!ajaxData || !ajaxData.xhrMonitoringState.openDone) {
                                            // Only create a single ajaxData (even when multiple AI instances are running)
                                            ajaxData = _openHandler(xhr, method, url, async);
                                        }
                                        // always attach to the on ready state change (required for handling multiple instances)
                                        _attachToOnReadyStateChange(xhr, ajaxData);
                                    }
                                }
                            },
                            hkErr: _createErrorCallbackFunc(_self, 15 /* _eInternalMessageId.FailedMonitorAjaxOpen */, ERROR_HEADER + ".open" + ERROR_POSTFIX)
                        });
                        // Instrument send
                        _hookProto(XMLHttpRequest, "send", {
                            ns: _evtNamespace,
                            req: function (callDetails, context) {
                                if (!_disableAjaxTracking) {
                                    var xhr = callDetails.inst;
                                    var ajaxData = _getAjaxData(xhr, _ajaxDataId);
                                    if (_isMonitoredXhrInstance(xhr, ajaxData) && !ajaxData.xhrMonitoringState.sendDone) {
                                        _createMarkId("xhr", ajaxData);
                                        ajaxData[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */] = dateTimeUtilsNow();
                                        _self[_DYN_INCLUDE_CORRELATION_0 /* @min:%2eincludeCorrelationHeaders */](ajaxData, undefined, undefined, xhr);
                                        ajaxData.xhrMonitoringState.sendDone = true;
                                    }
                                }
                            },
                            hkErr: _createErrorCallbackFunc(_self, 17 /* _eInternalMessageId.FailedMonitorAjaxSend */, ERROR_HEADER + ERROR_POSTFIX)
                        });
                        // Instrument abort
                        _hookProto(XMLHttpRequest, "abort", {
                            ns: _evtNamespace,
                            req: function (callDetails) {
                                if (!_disableAjaxTracking) {
                                    var xhr = callDetails.inst;
                                    var ajaxData = _getAjaxData(xhr, _ajaxDataId);
                                    if (_isMonitoredXhrInstance(xhr, ajaxData) && !ajaxData.xhrMonitoringState.abortDone) {
                                        ajaxData[_DYN_ABORTED /* @min:%2eaborted */] = 1;
                                        ajaxData.xhrMonitoringState.abortDone = true;
                                    }
                                }
                            },
                            hkErr: _createErrorCallbackFunc(_self, 13 /* _eInternalMessageId.FailedMonitorAjaxAbort */, ERROR_HEADER + ".abort" + ERROR_POSTFIX)
                        });
                        // Instrument setRequestHeader
                        _hookProto(XMLHttpRequest, "setRequestHeader", {
                            ns: _evtNamespace,
                            req: function (callDetails, header, value) {
                                if (!_disableAjaxTracking) {
                                    var xhr = callDetails.inst;
                                    var ajaxData = _getAjaxData(xhr, _ajaxDataId);
                                    if (ajaxData && _isMonitoredXhrInstance(xhr, ajaxData)) {
                                        _addSharedXhrHeaders(xhr, header, value);
                                        if (_enableRequestHeaderTracking && _canIncludeHeaders(header)) {
                                            ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */][header] = value;
                                        }
                                    }
                                }
                            },
                            hkErr: _createErrorCallbackFunc(_self, 71 /* _eInternalMessageId.FailedMonitorAjaxSetRequestHeader */, ERROR_HEADER + ".setRequestHeader" + ERROR_POSTFIX)
                        });
                        _xhrInitialized = true;
                    }
                }));
            }
            function _isDisabledRequest(xhr, request, init) {
                var isDisabled = false;
                var theUrl = ((!isString(request) ? (request || {}).url || "" : request) || "")[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */]();
                // check excludeRequestFromAutoTrackingPatterns before stripping off any query string
                arrForEach(_excludeRequestFromAutoTrackingPatterns, function (regex) {
                    var theRegex = regex;
                    if (isString(regex)) {
                        theRegex = new RegExp(regex);
                    }
                    if (!isDisabled) {
                        isDisabled = theRegex.test(theUrl);
                    }
                });
                // if request url matches with exclude regex pattern, return true and no need to check for headers
                if (isDisabled) {
                    return isDisabled;
                }
                var idx = _indexOf(theUrl, "?");
                var idx2 = _indexOf(theUrl, "#");
                if (idx === -1 || (idx2 !== -1 && idx2 < idx)) {
                    idx = idx2;
                }
                if (idx !== -1) {
                    // Strip off any Query string
                    theUrl = theUrl.substring(0, idx);
                }
                // check that this instance is not not used by ajax call performed inside client side monitoring to send data to collector
                if (!isNullOrUndefined(xhr)) {
                    // Look on the XMLHttpRequest of the URL string value
                    isDisabled = xhr[DisabledPropertyName] === true || theUrl[DisabledPropertyName] === true;
                }
                else if (!isNullOrUndefined(request)) { // fetch
                    // Look for DisabledPropertyName in either Request or RequestInit
                    isDisabled = (typeof request === "object" ? request[DisabledPropertyName] === true : false) ||
                        (init ? init[DisabledPropertyName] === true : false);
                }
                // Also add extra check just in case the XHR or fetch objects where not decorated with the DisableProperty due to sealing or freezing
                if (!isDisabled && theUrl && isInternalApplicationInsightsEndpoint(theUrl)) {
                    isDisabled = true;
                }
                if (isDisabled) {
                    // Add the disabled url if not present
                    if (!_disabledUrls[theUrl]) {
                        _disabledUrls[theUrl] = 1;
                    }
                }
                else {
                    // Check to see if the url is listed as disabled
                    if (_disabledUrls[theUrl]) {
                        isDisabled = true;
                    }
                }
                return isDisabled;
            }
            /// <summary>Verifies that particular instance of XMLHttpRequest needs to be monitored</summary>
            /// <param name="excludeAjaxDataValidation">Optional parameter. True if ajaxData must be excluded from verification</param>
            /// <returns type="bool">True if instance needs to be monitored, otherwise false</returns>
            function _isMonitoredXhrInstance(xhr, ajaxData, excludeAjaxDataValidation) {
                var ajaxValidation = true;
                var initialized = _xhrInitialized;
                if (!isNullOrUndefined(xhr)) {
                    ajaxValidation = excludeAjaxDataValidation === true || !isNullOrUndefined(ajaxData);
                }
                // checking to see that all interested functions on xhr were instrumented
                return initialized
                    // checking on ajaxData to see that it was not removed in user code
                    && ajaxValidation;
            }
            function _getDistributedTraceCtx() {
                var distributedTraceCtx = null;
                if (_self[_DYN_CORE /* @min:%2ecore */] && _self[_DYN_CORE /* @min:%2ecore */].getTraceCtx) {
                    distributedTraceCtx = _self[_DYN_CORE /* @min:%2ecore */].getTraceCtx(false);
                }
                // Fall back
                if (!distributedTraceCtx && _context && _context.telemetryTrace) {
                    distributedTraceCtx = createDistributedTraceContextFromTrace(_context.telemetryTrace);
                }
                return distributedTraceCtx;
            }
            function _openHandler(xhr, method, url, async) {
                var _a;
                var distributedTraceCtx = _getDistributedTraceCtx();
                var traceID = (distributedTraceCtx && distributedTraceCtx[_DYN_GET_TRACE_ID /* @min:%2egetTraceId */]()) || generateW3CId();
                var spanID = strSubstr(generateW3CId(), 0, 16);
                var xhrRequestData = xhr[AJAX_DATA_CONTAINER] = (xhr[AJAX_DATA_CONTAINER] || { xh: [], i: {} });
                var ajaxDataCntr = xhrRequestData.i = (xhrRequestData.i || {});
                var ajaxData = ajaxDataCntr[_ajaxDataId] = (ajaxDataCntr[_ajaxDataId] || new ajaxRecord(traceID, spanID, _self[strDiagLog](), (_a = _self.core) === null || _a === void 0 ? void 0 : _a.getTraceCtx()));
                ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = distributedTraceCtx && distributedTraceCtx[_DYN_GET_TRACE_FLAGS /* @min:%2egetTraceFlags */]();
                ajaxData[_DYN_METHOD /* @min:%2emethod */] = method;
                ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */] = url;
                ajaxData.xhrMonitoringState.openDone = true;
                ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */] = {};
                ajaxData.async = async;
                ajaxData[_DYN_ERROR_STATUS_TEXT /* @min:%2eerrorStatusText */] = _enableAjaxErrorStatusText;
                return ajaxData;
            }
            function _attachToOnReadyStateChange(xhr, ajaxData) {
                ajaxData.xhrMonitoringState[_DYN_STATE_CHANGE_ATTACHE11 /* @min:%2estateChangeAttached */] = eventOn(xhr, "readystatechange", function () {
                    var _a;
                    try {
                        if (xhr && xhr.readyState === 4 && _isMonitoredXhrInstance(xhr, ajaxData)) {
                            _onAjaxComplete(xhr);
                        }
                    }
                    catch (e) {
                        var exceptionText = dumpObj(e);
                        // ignore messages with c00c023f, as this a known IE9 XHR abort issue
                        if (!exceptionText || _indexOf(exceptionText[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */](), "c00c023f") === -1) {
                            _throwInternalCritical(_self, 16 /* _eInternalMessageId.FailedMonitorAjaxRSC */, ERROR_HEADER + " 'readystatechange' event handler" + ERROR_POSTFIX, (_a = {},
                                _a[_DYN_AJAX_DIAGNOSTICS_MES14 /* @min:ajaxDiagnosticsMessage */] = _getFailedAjaxDiagnosticsMessage(xhr, _ajaxDataId),
                                _a.exception = exceptionText,
                                _a));
                        }
                    }
                }, _evtNamespace);
            }
            function _getResponseText(xhr) {
                try {
                    var responseType = xhr.responseType;
                    if (responseType === "" || responseType === "text") {
                        // As per the specification responseText is only valid if the type is an empty string or "text"
                        return xhr[_DYN_RESPONSE_TEXT /* @min:%2eresponseText */];
                    }
                }
                catch (e) {
                    // This shouldn't happen because of the above check -- but just in case, so just ignore
                }
                return null;
            }
            function _onAjaxComplete(xhr) {
                var ajaxData = _getAjaxData(xhr, _ajaxDataId);
                ajaxData[_DYN_RESPONSE_FINISHED_TI12 /* @min:%2eresponseFinishedTime */] = dateTimeUtilsNow();
                ajaxData[_DYN_STATUS /* @min:%2estatus */] = xhr[_DYN_STATUS /* @min:%2estatus */];
                function _reportXhrError(e, failedProps) {
                    var errorProps = failedProps || {};
                    errorProps["ajaxDiagnosticsMessage"] = _getFailedAjaxDiagnosticsMessage(xhr, _ajaxDataId);
                    if (e) {
                        errorProps["exception"] = dumpObj(e);
                    }
                    _throwInternalWarning(_self, 14 /* _eInternalMessageId.FailedMonitorAjaxDur */, FAILED_TO_CALCULATE_DURATION_ERROR + "ajax call" + ERROR_NOT_SENT, errorProps);
                }
                _findPerfResourceEntry("xmlhttprequest", ajaxData, function () {
                    try {
                        var dependency = ajaxData[_DYN__CREATE_TRACK_ITEM /* @min:%2eCreateTrackItem */]("Ajax", _enableRequestHeaderTracking, function () {
                            var _a;
                            var ajaxResponse = (_a = {
                                    statusText: xhr[_DYN_STATUS_TEXT /* @min:%2estatusText */],
                                    headerMap: null
                                },
                                _a[_DYN_CORRELATION_CONTEXT /* @min:correlationContext */] = _getAjaxCorrelationContext(xhr),
                                _a.type = xhr.responseType,
                                _a[_DYN_RESPONSE_TEXT /* @min:responseText */] = _getResponseText(xhr),
                                _a.response = xhr.response,
                                _a);
                            if (_enableResponseHeaderTracking) {
                                var headers = xhr[_DYN_GET_ALL_RESPONSE_HEA13 /* @min:%2egetAllResponseHeaders */]();
                                if (headers) {
                                    // xhr.getAllResponseHeaders() method returns all the response headers, separated by CRLF, as a string or null
                                    // the regex converts the header string into an array of individual headers
                                    var arr = strTrim(headers).split(/[\r\n]+/);
                                    var responseHeaderMap_2 = {};
                                    arrForEach(arr, function (line) {
                                        var parts = line.split(": ");
                                        var header = parts.shift();
                                        var value = parts.join(": ");
                                        if (_canIncludeHeaders(header)) {
                                            responseHeaderMap_2[header] = value;
                                        }
                                    });
                                    ajaxResponse[_DYN_HEADER_MAP /* @min:%2eheaderMap */] = responseHeaderMap_2;
                                }
                            }
                            return ajaxResponse;
                        });
                        var properties = void 0;
                        try {
                            if (!!_addRequestContext) {
                                properties = _addRequestContext({ status: xhr[_DYN_STATUS /* @min:%2estatus */], xhr: xhr });
                            }
                        }
                        catch (e) {
                            _throwInternalWarning(_self, 104 /* _eInternalMessageId.FailedAddingCustomDefinedRequestContext */, CUSTOM_REQUEST_CONTEXT_ERROR);
                        }
                        if (dependency) {
                            if (properties !== undefined) {
                                dependency[STR_PROPERTIES /* @min:%2eproperties */] = __assign(__assign({}, dependency.properties), properties);
                            }
                            var sysProperties = ajaxData[_DYN_GET_PART_APROPS /* @min:%2egetPartAProps */]();
                            _reportDependencyInternal(_dependencyInitializers, _self[_DYN_CORE /* @min:%2ecore */], ajaxData, dependency, null, sysProperties);
                        }
                        else {
                            _reportXhrError(null, {
                                requestSentTime: ajaxData[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */],
                                responseFinishedTime: ajaxData[_DYN_RESPONSE_FINISHED_TI12 /* @min:%2eresponseFinishedTime */]
                            });
                        }
                    }
                    finally {
                        // cleanup telemetry data
                        try {
                            var xhrRequestData = (xhr[AJAX_DATA_CONTAINER] || { i: {} });
                            var ajaxDataCntr = (xhrRequestData.i || {});
                            if (ajaxDataCntr[_ajaxDataId]) {
                                ajaxDataCntr[_ajaxDataId] = null;
                            }
                        }
                        catch (e) {
                            // May throw in environments that prevent extension or freeze xhr
                        }
                    }
                }, function (e) {
                    _reportXhrError(e, null);
                });
            }
            function _getAjaxCorrelationContext(xhr) {
                var _a;
                try {
                    var responseHeadersString = xhr[_DYN_GET_ALL_RESPONSE_HEA13 /* @min:%2egetAllResponseHeaders */]();
                    if (responseHeadersString !== null) {
                        var index = _indexOf(responseHeadersString[_DYN_TO_LOWER_CASE /* @min:%2etoLowerCase */](), RequestHeaders[8 /* eRequestHeaders.requestContextHeaderLowerCase */]);
                        if (index !== -1) {
                            var responseHeader = xhr.getResponseHeader(RequestHeaders[0 /* eRequestHeaders.requestContextHeader */]);
                            return correlationIdGetCorrelationContext(responseHeader);
                        }
                    }
                }
                catch (e) {
                    _throwInternalWarning(_self, 18 /* _eInternalMessageId.FailedMonitorAjaxGetCorrelationHeader */, CORRELATION_HEADER_ERROR, (_a = {},
                        _a[_DYN_AJAX_DIAGNOSTICS_MES14 /* @min:ajaxDiagnosticsMessage */] = _getFailedAjaxDiagnosticsMessage(xhr, _ajaxDataId),
                        _a.exception = dumpObj(e),
                        _a));
                }
            }
            function _createMarkId(type, ajaxData) {
                if (ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */] && _markPrefix && _enableAjaxPerfTracking) {
                    var performance_1 = getPerformance();
                    if (performance_1 && isFunction(performance_1.mark)) {
                        _markCount++;
                        var markId = _markPrefix + type + "#" + _markCount;
                        performance_1.mark(markId);
                        var entries = performance_1.getEntriesByName(markId);
                        if (entries && entries[_DYN_LENGTH /* @min:%2elength */] === 1) {
                            ajaxData[_DYN_PERF_MARK /* @min:%2eperfMark */] = entries[0];
                        }
                    }
                }
            }
            function _findPerfResourceEntry(initiatorType, ajaxData, trackCallback, reportError) {
                var perfMark = ajaxData[_DYN_PERF_MARK /* @min:%2eperfMark */];
                var performance = getPerformance();
                var maxAttempts = _maxAjaxPerfLookupAttempts;
                var retryDelay = _ajaxPerfLookupDelay;
                var requestUrl = ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */];
                var attempt = 0;
                (function locateResourceTiming() {
                    try {
                        if (performance && perfMark) {
                            attempt++;
                            var perfTiming = null;
                            var entries = performance.getEntries();
                            for (var lp = entries[_DYN_LENGTH /* @min:%2elength */] - 1; lp >= 0; lp--) {
                                var entry = entries[lp];
                                if (entry) {
                                    if (entry.entryType === "resource") {
                                        if (entry.initiatorType === initiatorType &&
                                            (_indexOf(entry.name, requestUrl) !== -1 || _indexOf(requestUrl, entry.name) !== -1)) {
                                            perfTiming = entry;
                                        }
                                    }
                                    else if (entry.entryType === "mark" && entry.name === perfMark.name) {
                                        // We hit the start event
                                        ajaxData[_DYN_PERF_TIMING /* @min:%2eperfTiming */] = perfTiming;
                                        break;
                                    }
                                    if (entry[_DYN_START_TIME /* @min:%2estartTime */] < perfMark[_DYN_START_TIME /* @min:%2estartTime */] - 1000) {
                                        // Fallback to try and reduce the time spent looking for the perf entry
                                        break;
                                    }
                                }
                            }
                        }
                        if (!perfMark || // - we don't have a perfMark or
                            ajaxData[_DYN_PERF_TIMING /* @min:%2eperfTiming */] || // - we have not found the perf entry or
                            attempt >= maxAttempts || // - we have tried too many attempts or
                            ajaxData.async === false) { // - this is a sync request
                            if (perfMark && isFunction(performance.clearMarks)) {
                                // Remove the mark so we don't fill up the performance resources too much
                                performance.clearMarks(perfMark.name);
                            }
                            ajaxData.perfAttempts = attempt;
                            // just continue and report the track event
                            trackCallback();
                        }
                        else {
                            // We need to wait for the browser to populate the window.performance entry
                            // This needs to be at least 1ms as waiting <= 1 (on firefox) is not enough time for fetch or xhr,
                            // this is a scheduling issue for the browser implementation
                            scheduleTimeout(locateResourceTiming, retryDelay);
                        }
                    }
                    catch (e) {
                        reportError(e);
                    }
                })();
            }
            function _createFetchRecord(input, init) {
                var _a;
                var distributedTraceCtx = _getDistributedTraceCtx();
                var traceID = (distributedTraceCtx && distributedTraceCtx[_DYN_GET_TRACE_ID /* @min:%2egetTraceId */]()) || generateW3CId();
                var spanID = strSubstr(generateW3CId(), 0, 16);
                var ajaxData = new ajaxRecord(traceID, spanID, _self[strDiagLog](), (_a = _self.core) === null || _a === void 0 ? void 0 : _a.getTraceCtx());
                ajaxData[_DYN_TRACE_FLAGS /* @min:%2etraceFlags */] = distributedTraceCtx && distributedTraceCtx[_DYN_GET_TRACE_FLAGS /* @min:%2egetTraceFlags */]();
                ajaxData[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */] = dateTimeUtilsNow();
                ajaxData[_DYN_ERROR_STATUS_TEXT /* @min:%2eerrorStatusText */] = _enableAjaxErrorStatusText;
                var requestUrl;
                if (input instanceof Request) {
                    requestUrl = (input || {}).url || "";
                }
                else {
                    requestUrl = input;
                }
                if (requestUrl === "") {
                    var location_1 = getLocation();
                    if (location_1 && location_1.href) {
                        requestUrl = strSplit(location_1.href, "#")[0];
                    }
                }
                ajaxData[_DYN_REQUEST_URL /* @min:%2erequestUrl */] = requestUrl;
                var method = "GET";
                if (init && init[_DYN_METHOD /* @min:%2emethod */]) {
                    method = init[_DYN_METHOD /* @min:%2emethod */];
                }
                else if (input && input instanceof Request) {
                    method = input[_DYN_METHOD /* @min:%2emethod */];
                }
                ajaxData[_DYN_METHOD /* @min:%2emethod */] = method;
                var requestHeaders = {};
                if (_enableRequestHeaderTracking) {
                    var headers = new Headers((init ? init[_DYN_HEADERS /* @min:%2eheaders */] : 0) || (input instanceof Request ? (input[_DYN_HEADERS /* @min:%2eheaders */] || {}) : {}));
                    headers.forEach(function (value, key) {
                        if (_canIncludeHeaders(key)) {
                            requestHeaders[key] = value;
                        }
                    });
                }
                ajaxData[_DYN_REQUEST_HEADERS /* @min:%2erequestHeaders */] = requestHeaders;
                _createMarkId(STR_FETCH, ajaxData);
                return ajaxData;
            }
            function _getFailedFetchDiagnosticsMessage(input) {
                var result = "";
                try {
                    if (!isNullOrUndefined(input)) {
                        if (typeof (input) === "string") {
                            result += "(url: '".concat(input, "')");
                        }
                        else {
                            result += "(url: '".concat(input.url, "')");
                        }
                    }
                }
                catch (e) {
                    _throwInternalCritical(_self, 15 /* _eInternalMessageId.FailedMonitorAjaxOpen */, "Failed to grab failed fetch diagnostics message", { exception: dumpObj(e) });
                }
                return result;
            }
            function _reportFetchMetrics(callDetails, status, input, response, ajaxData, getResponse, properties) {
                if (!ajaxData) {
                    return;
                }
                function _reportFetchError(msgId, e, failedProps) {
                    var errorProps = failedProps || {};
                    errorProps["fetchDiagnosticsMessage"] = _getFailedFetchDiagnosticsMessage(input);
                    if (e) {
                        errorProps["exception"] = dumpObj(e);
                    }
                    _throwInternalWarning(_self, msgId, FAILED_TO_CALCULATE_DURATION_ERROR + "fetch call" + ERROR_NOT_SENT, errorProps);
                }
                ajaxData[_DYN_RESPONSE_FINISHED_TI12 /* @min:%2eresponseFinishedTime */] = dateTimeUtilsNow();
                ajaxData[_DYN_STATUS /* @min:%2estatus */] = status;
                _findPerfResourceEntry(STR_FETCH, ajaxData, function () {
                    var dependency = ajaxData[_DYN__CREATE_TRACK_ITEM /* @min:%2eCreateTrackItem */]("Fetch", _enableRequestHeaderTracking, getResponse);
                    var properties;
                    try {
                        if (!!_addRequestContext) {
                            properties = _addRequestContext({ status: status, request: input, response: response });
                        }
                    }
                    catch (e) {
                        _throwInternalWarning(_self, 104 /* _eInternalMessageId.FailedAddingCustomDefinedRequestContext */, CUSTOM_REQUEST_CONTEXT_ERROR);
                    }
                    if (dependency) {
                        if (properties !== undefined) {
                            dependency[STR_PROPERTIES /* @min:%2eproperties */] = __assign(__assign({}, dependency.properties), properties);
                        }
                        var sysProperties = ajaxData[_DYN_GET_PART_APROPS /* @min:%2egetPartAProps */]();
                        _reportDependencyInternal(_dependencyInitializers, _self[_DYN_CORE /* @min:%2ecore */], ajaxData, dependency, null, sysProperties);
                    }
                    else {
                        _reportFetchError(14 /* _eInternalMessageId.FailedMonitorAjaxDur */, null, {
                            requestSentTime: ajaxData[_DYN_REQUEST_SENT_TIME /* @min:%2erequestSentTime */],
                            responseFinishedTime: ajaxData[_DYN_RESPONSE_FINISHED_TI12 /* @min:%2eresponseFinishedTime */]
                        });
                    }
                }, function (e) {
                    _reportFetchError(18 /* _eInternalMessageId.FailedMonitorAjaxGetCorrelationHeader */, e, null);
                });
            }
            function _getFetchCorrelationContext(response) {
                if (response && response[_DYN_HEADERS /* @min:%2eheaders */]) {
                    try {
                        var responseHeader = response[_DYN_HEADERS /* @min:%2eheaders */].get(RequestHeaders[0 /* eRequestHeaders.requestContextHeader */]);
                        return correlationIdGetCorrelationContext(responseHeader);
                    }
                    catch (e) {
                        _throwInternalWarning(_self, 18 /* _eInternalMessageId.FailedMonitorAjaxGetCorrelationHeader */, CORRELATION_HEADER_ERROR, {
                            fetchDiagnosticsMessage: _getFailedFetchDiagnosticsMessage(response),
                            exception: dumpObj(e)
                        });
                    }
                }
            }
            function _reportDependencyInternal(initializers, core, ajaxData, dependency, properties, systemProperties) {
                var result = true;
                var initializersCount = initializers[_DYN_LENGTH /* @min:%2elength */];
                if (initializersCount > 0) {
                    var details = {
                        item: dependency,
                        properties: properties,
                        sysProperties: systemProperties,
                        context: ajaxData ? ajaxData[_DYN_CONTEXT /* @min:%2econtext */] : null,
                        aborted: ajaxData ? !!ajaxData[_DYN_ABORTED /* @min:%2eaborted */] : false
                    };
                    result = _processDependencyContainer(core, initializers, details, "initializer");
                }
                if (result) {
                    _self[_DYN_TRACK_DEPENDENCY_DAT1 /* @min:%2etrackDependencyDataInternal */](dependency, properties, systemProperties);
                }
            }
        });
        return _this;
    }
// Removed Stub for AjaxMonitor.prototype.initialize.
    AjaxMonitor.prototype.processTelemetry = function (item, itemCtx) {
        this.processNext(item, itemCtx);
    };
// Removed Stub for AjaxMonitor.prototype.trackDependencyData.
// Removed Stub for AjaxMonitor.prototype.includeCorrelationHeaders.
// Removed Stub for AjaxMonitor.prototype.addDependencyListener.
    /**
     * Add an dependency telemetry initializer callback function to allow populating additional properties or drop the request.
     * It is called after the dependency call has completed and any available performance details are available. A dependency
     * initializer is similar to the TelemetryInitializer function but it allows you to block the reporting of the dependency
     * request so that it doesn't count against the `maxAjaxCallsPerView`.
     * @param dependencyInitializer - The Dependency Telemetry Initializer function
     * @returns - A IDependencyInitializerHandler to enable the initializer to be removed
     */
    AjaxMonitor.prototype.addDependencyInitializer = function (dependencyInitializer) {
        return null;
    };
// Removed Stub for AjaxMonitor.prototype.trackDependencyDataInternal.
    AjaxMonitor.identifier = "AjaxDependencyPlugin";
    return AjaxMonitor;
}(BaseTelemetryPlugin));
export { AjaxMonitor };
//# sourceMappingURL=ajax.js.map