@textback/notification-widget
Version:
TODO: Give a short introduction of your project. Let this section explain the objectives or the motivation behind this project.
924 lines (923 loc) • 223 kB
JavaScript
//!!!ES5 syntax
//patched version to work without garbage in global scope - by textback team - search for textback in code to see what changed
window.TextBack = window.TextBack || {};
// window.TextBack.NotificationWidget = window.TextBack.NotificationWidget || {};
// var context = window.TextBack.NotificationWidget;
var context = window.TextBack;
//textback end
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Microsoft;
(function (Microsoft) {
var ApplicationInsights;
(function (ApplicationInsights) {
(function (LoggingSeverity) {
LoggingSeverity[LoggingSeverity["CRITICAL"] = 0] = "CRITICAL";
LoggingSeverity[LoggingSeverity["WARNING"] = 1] = "WARNING";
})(ApplicationInsights.LoggingSeverity || (ApplicationInsights.LoggingSeverity = {}));
var LoggingSeverity = ApplicationInsights.LoggingSeverity;
(function (_InternalMessageId) {
_InternalMessageId[_InternalMessageId["BrowserDoesNotSupportLocalStorage"] = 0] = "BrowserDoesNotSupportLocalStorage";
_InternalMessageId[_InternalMessageId["BrowserCannotReadLocalStorage"] = 1] = "BrowserCannotReadLocalStorage";
_InternalMessageId[_InternalMessageId["BrowserCannotReadSessionStorage"] = 2] = "BrowserCannotReadSessionStorage";
_InternalMessageId[_InternalMessageId["BrowserCannotWriteLocalStorage"] = 3] = "BrowserCannotWriteLocalStorage";
_InternalMessageId[_InternalMessageId["BrowserCannotWriteSessionStorage"] = 4] = "BrowserCannotWriteSessionStorage";
_InternalMessageId[_InternalMessageId["BrowserFailedRemovalFromLocalStorage"] = 5] = "BrowserFailedRemovalFromLocalStorage";
_InternalMessageId[_InternalMessageId["BrowserFailedRemovalFromSessionStorage"] = 6] = "BrowserFailedRemovalFromSessionStorage";
_InternalMessageId[_InternalMessageId["CannotSendEmptyTelemetry"] = 7] = "CannotSendEmptyTelemetry";
_InternalMessageId[_InternalMessageId["ClientPerformanceMathError"] = 8] = "ClientPerformanceMathError";
_InternalMessageId[_InternalMessageId["ErrorParsingAISessionCookie"] = 9] = "ErrorParsingAISessionCookie";
_InternalMessageId[_InternalMessageId["ErrorPVCalc"] = 10] = "ErrorPVCalc";
_InternalMessageId[_InternalMessageId["ExceptionWhileLoggingError"] = 11] = "ExceptionWhileLoggingError";
_InternalMessageId[_InternalMessageId["FailedAddingTelemetryToBuffer"] = 12] = "FailedAddingTelemetryToBuffer";
_InternalMessageId[_InternalMessageId["FailedMonitorAjaxAbort"] = 13] = "FailedMonitorAjaxAbort";
_InternalMessageId[_InternalMessageId["FailedMonitorAjaxDur"] = 14] = "FailedMonitorAjaxDur";
_InternalMessageId[_InternalMessageId["FailedMonitorAjaxOpen"] = 15] = "FailedMonitorAjaxOpen";
_InternalMessageId[_InternalMessageId["FailedMonitorAjaxRSC"] = 16] = "FailedMonitorAjaxRSC";
_InternalMessageId[_InternalMessageId["FailedMonitorAjaxSend"] = 17] = "FailedMonitorAjaxSend";
_InternalMessageId[_InternalMessageId["FailedToAddHandlerForOnBeforeUnload"] = 18] = "FailedToAddHandlerForOnBeforeUnload";
_InternalMessageId[_InternalMessageId["FailedToSendQueuedTelemetry"] = 19] = "FailedToSendQueuedTelemetry";
_InternalMessageId[_InternalMessageId["FailedToReportDataLoss"] = 20] = "FailedToReportDataLoss";
_InternalMessageId[_InternalMessageId["FlushFailed"] = 21] = "FlushFailed";
_InternalMessageId[_InternalMessageId["MessageLimitPerPVExceeded"] = 22] = "MessageLimitPerPVExceeded";
_InternalMessageId[_InternalMessageId["MissingRequiredFieldSpecification"] = 23] = "MissingRequiredFieldSpecification";
_InternalMessageId[_InternalMessageId["NavigationTimingNotSupported"] = 24] = "NavigationTimingNotSupported";
_InternalMessageId[_InternalMessageId["OnError"] = 25] = "OnError";
_InternalMessageId[_InternalMessageId["SessionRenewalDateIsZero"] = 26] = "SessionRenewalDateIsZero";
_InternalMessageId[_InternalMessageId["SenderNotInitialized"] = 27] = "SenderNotInitialized";
_InternalMessageId[_InternalMessageId["StartTrackEventFailed"] = 28] = "StartTrackEventFailed";
_InternalMessageId[_InternalMessageId["StopTrackEventFailed"] = 29] = "StopTrackEventFailed";
_InternalMessageId[_InternalMessageId["StartTrackFailed"] = 30] = "StartTrackFailed";
_InternalMessageId[_InternalMessageId["StopTrackFailed"] = 31] = "StopTrackFailed";
_InternalMessageId[_InternalMessageId["TelemetrySampledAndNotSent"] = 32] = "TelemetrySampledAndNotSent";
_InternalMessageId[_InternalMessageId["TrackEventFailed"] = 33] = "TrackEventFailed";
_InternalMessageId[_InternalMessageId["TrackExceptionFailed"] = 34] = "TrackExceptionFailed";
_InternalMessageId[_InternalMessageId["TrackMetricFailed"] = 35] = "TrackMetricFailed";
_InternalMessageId[_InternalMessageId["TrackPVFailed"] = 36] = "TrackPVFailed";
_InternalMessageId[_InternalMessageId["TrackPVFailedCalc"] = 37] = "TrackPVFailedCalc";
_InternalMessageId[_InternalMessageId["TrackTraceFailed"] = 38] = "TrackTraceFailed";
_InternalMessageId[_InternalMessageId["TransmissionFailed"] = 39] = "TransmissionFailed";
_InternalMessageId[_InternalMessageId["FailedToSetStorageBuffer"] = 40] = "FailedToSetStorageBuffer";
_InternalMessageId[_InternalMessageId["FailedToRestoreStorageBuffer"] = 41] = "FailedToRestoreStorageBuffer";
_InternalMessageId[_InternalMessageId["InvalidBackendResponse"] = 42] = "InvalidBackendResponse";
_InternalMessageId[_InternalMessageId["FailedToFixDepricatedValues"] = 43] = "FailedToFixDepricatedValues";
_InternalMessageId[_InternalMessageId["InvalidDurationValue"] = 44] = "InvalidDurationValue";
_InternalMessageId[_InternalMessageId["CannotSerializeObject"] = 45] = "CannotSerializeObject";
_InternalMessageId[_InternalMessageId["CannotSerializeObjectNonSerializable"] = 46] = "CannotSerializeObjectNonSerializable";
_InternalMessageId[_InternalMessageId["CircularReferenceDetected"] = 47] = "CircularReferenceDetected";
_InternalMessageId[_InternalMessageId["ClearAuthContextFailed"] = 48] = "ClearAuthContextFailed";
_InternalMessageId[_InternalMessageId["ExceptionTruncated"] = 49] = "ExceptionTruncated";
_InternalMessageId[_InternalMessageId["IllegalCharsInName"] = 50] = "IllegalCharsInName";
_InternalMessageId[_InternalMessageId["ItemNotInArray"] = 51] = "ItemNotInArray";
_InternalMessageId[_InternalMessageId["MaxAjaxPerPVExceeded"] = 52] = "MaxAjaxPerPVExceeded";
_InternalMessageId[_InternalMessageId["MessageTruncated"] = 53] = "MessageTruncated";
_InternalMessageId[_InternalMessageId["NameTooLong"] = 54] = "NameTooLong";
_InternalMessageId[_InternalMessageId["SampleRateOutOfRange"] = 55] = "SampleRateOutOfRange";
_InternalMessageId[_InternalMessageId["SetAuthContextFailed"] = 56] = "SetAuthContextFailed";
_InternalMessageId[_InternalMessageId["SetAuthContextFailedAccountName"] = 57] = "SetAuthContextFailedAccountName";
_InternalMessageId[_InternalMessageId["StringValueTooLong"] = 58] = "StringValueTooLong";
_InternalMessageId[_InternalMessageId["StartCalledMoreThanOnce"] = 59] = "StartCalledMoreThanOnce";
_InternalMessageId[_InternalMessageId["StopCalledWithoutStart"] = 60] = "StopCalledWithoutStart";
_InternalMessageId[_InternalMessageId["TelemetryInitializerFailed"] = 61] = "TelemetryInitializerFailed";
_InternalMessageId[_InternalMessageId["TrackArgumentsNotSpecified"] = 62] = "TrackArgumentsNotSpecified";
_InternalMessageId[_InternalMessageId["UrlTooLong"] = 63] = "UrlTooLong";
_InternalMessageId[_InternalMessageId["SessionStorageBufferFull"] = 64] = "SessionStorageBufferFull";
_InternalMessageId[_InternalMessageId["CannotAccessCookie"] = 65] = "CannotAccessCookie";
})(ApplicationInsights._InternalMessageId || (ApplicationInsights._InternalMessageId = {}));
var _InternalMessageId = ApplicationInsights._InternalMessageId;
var _InternalLogMessage = (function () {
function _InternalLogMessage(msgId, msg, isUserAct, properties) {
if (isUserAct === void 0) { isUserAct = false; }
this.messageId = msgId;
this.message =
(isUserAct ? _InternalLogMessage.AiUserActionablePrefix : _InternalLogMessage.AiNonUserActionablePrefix) +
_InternalMessageId[msgId].toString();
var diagnosticText = (msg ? " message:" + _InternalLogMessage.sanitizeDiagnosticText(msg) : "") +
(properties ? " props:" + _InternalLogMessage.sanitizeDiagnosticText(JSON.stringify(properties)) : "");
this.message += diagnosticText;
}
_InternalLogMessage.sanitizeDiagnosticText = function (text) {
return "\"" + text.replace(/\"/g, "") + "\"";
};
_InternalLogMessage.AiNonUserActionablePrefix = "AI (Internal): ";
_InternalLogMessage.AiUserActionablePrefix = "AI: ";
return _InternalLogMessage;
}());
ApplicationInsights._InternalLogMessage = _InternalLogMessage;
var _InternalLogging = (function () {
function _InternalLogging() {
}
_InternalLogging.throwInternal = function (severity, msgId, msg, properties, isUserAct) {
if (isUserAct === void 0) { isUserAct = false; }
var message = new _InternalLogMessage(msgId, msg, isUserAct, properties);
if (this.enableDebugExceptions()) {
throw message;
}
else {
if (typeof (message) !== "undefined" && !!message) {
if (typeof (message.message) !== "undefined") {
if (isUserAct) {
var messageKey = _InternalMessageId[message.messageId];
if (!this._messageLogged[messageKey] || this.verboseLogging()) {
this.warnToConsole(message.message);
this._messageLogged[messageKey] = true;
}
}
else {
if (this.verboseLogging()) {
this.warnToConsole(message.message);
}
}
this.logInternalMessage(severity, message);
}
}
}
};
_InternalLogging.warnToConsole = function (message) {
if (typeof console !== "undefined" && !!console) {
if (typeof console.warn === "function") {
console.warn(message);
}
else if (typeof console.log === "function") {
console.log(message);
}
}
};
_InternalLogging.resetInternalMessageCount = function () {
this._messageCount = 0;
this._messageLogged = {};
};
_InternalLogging.clearInternalMessageLoggedTypes = function () {
if (ApplicationInsights.Util.canUseSessionStorage()) {
var sessionStorageKeys = ApplicationInsights.Util.getSessionStorageKeys();
for (var i = 0; i < sessionStorageKeys.length; i++) {
if (sessionStorageKeys[i].indexOf(_InternalLogging.AIInternalMessagePrefix) === 0) {
ApplicationInsights.Util.removeSessionStorage(sessionStorageKeys[i]);
}
}
}
};
_InternalLogging.setMaxInternalMessageLimit = function (limit) {
if (!limit) {
throw new Error('limit cannot be undefined.');
}
this.MAX_INTERNAL_MESSAGE_LIMIT = limit;
};
_InternalLogging.logInternalMessage = function (severity, message) {
if (this._areInternalMessagesThrottled()) {
return;
}
var logMessage = true;
var messageKey = _InternalLogging.AIInternalMessagePrefix + _InternalMessageId[message.messageId];
if (ApplicationInsights.Util.canUseSessionStorage()) {
var internalMessageTypeLogRecord = ApplicationInsights.Util.getSessionStorage(messageKey);
if (internalMessageTypeLogRecord) {
logMessage = false;
}
else {
ApplicationInsights.Util.setSessionStorage(messageKey, "1");
}
}
else {
if (this._messageLogged[messageKey]) {
logMessage = false;
}
else {
this._messageLogged[messageKey] = true;
}
}
if (logMessage) {
if (this.verboseLogging() || severity === LoggingSeverity.CRITICAL) {
this.queue.push(message);
this._messageCount++;
}
if (this._messageCount == this.MAX_INTERNAL_MESSAGE_LIMIT) {
var throttleLimitMessage = "Internal events throttle limit per PageView reached for this app.";
var throttleMessage = new _InternalLogMessage(_InternalMessageId.MessageLimitPerPVExceeded, throttleLimitMessage, false);
this.queue.push(throttleMessage);
this.warnToConsole(throttleLimitMessage);
}
}
};
_InternalLogging._areInternalMessagesThrottled = function () {
return this._messageCount >= this.MAX_INTERNAL_MESSAGE_LIMIT;
};
_InternalLogging.AIInternalMessagePrefix = "AITR_";
_InternalLogging.enableDebugExceptions = function () { return false; };
_InternalLogging.verboseLogging = function () { return false; };
_InternalLogging.queue = [];
_InternalLogging.MAX_INTERNAL_MESSAGE_LIMIT = 25;
_InternalLogging._messageCount = 0;
_InternalLogging._messageLogged = {};
return _InternalLogging;
}());
ApplicationInsights._InternalLogging = _InternalLogging;
})(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
})(Microsoft || (Microsoft = {}));
var Microsoft;
(function (Microsoft) {
var ApplicationInsights;
(function (ApplicationInsights) {
var StorageType;
(function (StorageType) {
StorageType[StorageType["LocalStorage"] = 0] = "LocalStorage";
StorageType[StorageType["SessionStorage"] = 1] = "SessionStorage";
})(StorageType || (StorageType = {}));
var Util = (function () {
function Util() {
}
Util.disableStorage = function () {
Util._canUseLocalStorage = false;
Util._canUseSessionStorage = false;
};
Util._getLocalStorageObject = function () {
if (Util.canUseLocalStorage()) {
return Util._getVerifiedStorageObject(StorageType.LocalStorage);
}
return null;
};
Util._getVerifiedStorageObject = function (storageType) {
var storage = null;
var fail;
var uid;
try {
uid = new Date;
storage = storageType === StorageType.LocalStorage ? window.localStorage : window.sessionStorage;
storage.setItem(uid, uid);
fail = storage.getItem(uid) != uid;
storage.removeItem(uid);
if (fail) {
storage = null;
}
}
catch (exception) {
storage = null;
}
return storage;
};
Util.canUseLocalStorage = function () {
if (Util._canUseLocalStorage === undefined) {
Util._canUseLocalStorage = !!Util._getVerifiedStorageObject(StorageType.LocalStorage);
}
return Util._canUseLocalStorage;
};
Util.getStorage = function (name) {
var storage = Util._getLocalStorageObject();
if (storage !== null) {
try {
return storage.getItem(name);
}
catch (e) {
Util._canUseLocalStorage = false;
ApplicationInsights._InternalLogging.throwInternal(ApplicationInsights.LoggingSeverity.WARNING, ApplicationInsights._InternalMessageId.BrowserCannotReadLocalStorage, "Browser failed read of local storage. " + Util.getExceptionName(e), { exception: Util.dump(e) });
}
}
return null;
};
Util.setStorage = function (name, data) {
var storage = Util._getLocalStorageObject();
if (storage !== null) {
try {
storage.setItem(name, data);
return true;
}
catch (e) {
Util._canUseLocalStorage = false;
ApplicationInsights._InternalLogging.throwInternal(ApplicationInsights.LoggingSeverity.WARNING, ApplicationInsights._InternalMessageId.BrowserCannotWriteLocalStorage, "Browser failed write to local storage. " + Util.getExceptionName(e), { exception: Util.dump(e) });
}
}
return false;
};
Util.removeStorage = function (name) {
var storage = Util._getLocalStorageObject();
if (storage !== null) {
try {
storage.removeItem(name);
return true;
}
catch (e) {
Util._canUseLocalStorage = false;
ApplicationInsights._InternalLogging.throwInternal(ApplicationInsights.LoggingSeverity.WARNING, ApplicationInsights._InternalMessageId.BrowserFailedRemovalFromLocalStorage, "Browser failed removal of local storage item. " + Util.getExceptionName(e), { exception: Util.dump(e) });
}
}
return false;
};
Util._getSessionStorageObject = function () {
if (Util.canUseSessionStorage()) {
return Util._getVerifiedStorageObject(StorageType.SessionStorage);
}
return null;
};
Util.canUseSessionStorage = function () {
if (Util._canUseSessionStorage === undefined) {
Util._canUseSessionStorage = !!Util._getVerifiedStorageObject(StorageType.SessionStorage);
}
return Util._canUseSessionStorage;
};
Util.getSessionStorageKeys = function () {
var keys = [];
if (Util.canUseSessionStorage()) {
for (var key in window.sessionStorage) {
keys.push(key);
}
}
return keys;
};
Util.getSessionStorage = function (name) {
var storage = Util._getSessionStorageObject();
if (storage !== null) {
try {
return storage.getItem(name);
}
catch (e) {
Util._canUseSessionStorage = false;
ApplicationInsights._InternalLogging.throwInternal(ApplicationInsights.LoggingSeverity.WARNING, ApplicationInsights._InternalMessageId.BrowserCannotReadSessionStorage, "Browser failed read of session storage. " + Util.getExceptionName(e), { exception: Util.dump(e) });
}
}
return null;
};
Util.setSessionStorage = function (name, data) {
var storage = Util._getSessionStorageObject();
if (storage !== null) {
try {
storage.setItem(name, data);
return true;
}
catch (e) {
Util._canUseSessionStorage = false;
ApplicationInsights._InternalLogging.throwInternal(ApplicationInsights.LoggingSeverity.WARNING, ApplicationInsights._InternalMessageId.BrowserCannotWriteSessionStorage, "Browser failed write to session storage. " + Util.getExceptionName(e), { exception: Util.dump(e) });
}
}
return false;
};
Util.removeSessionStorage = function (name) {
var storage = Util._getSessionStorageObject();
if (storage !== null) {
try {
storage.removeItem(name);
return true;
}
catch (e) {
Util._canUseSessionStorage = false;
ApplicationInsights._InternalLogging.throwInternal(ApplicationInsights.LoggingSeverity.WARNING, ApplicationInsights._InternalMessageId.BrowserFailedRemovalFromSessionStorage, "Browser failed removal of session storage item. " + Util.getExceptionName(e), { exception: Util.dump(e) });
}
}
return false;
};
Util.disableCookies = function () {
Util._canUseCookies = false;
};
Util.canUseCookies = function () {
if (Util._canUseCookies === undefined) {
Util._canUseCookies = false;
try {
Util._canUseCookies = Util.document.cookie !== undefined;
}
catch (e) {
ApplicationInsights._InternalLogging.throwInternal(ApplicationInsights.LoggingSeverity.WARNING, ApplicationInsights._InternalMessageId.CannotAccessCookie, "Cannot access document.cookie - " + Util.getExceptionName(e), { exception: Util.dump(e) });
}
;
}
return Util._canUseCookies;
};
Util.setCookie = function (name, value, domain) {
var domainAttrib = "";
var secureAttrib = "";
if (domain) {
domainAttrib = ";domain=" + domain;
}
if (Util.document.location && Util.document.location.protocol === "https:") {
secureAttrib = ";secure";
}
if (Util.canUseCookies()) {
Util.document.cookie = name + "=" + value + domainAttrib + ";path=/" + secureAttrib;
}
};
Util.stringToBoolOrDefault = function (str, defaultValue) {
if (defaultValue === void 0) { defaultValue = false; }
if (str === undefined || str === null) {
return defaultValue;
}
return str.toString().toLowerCase() === "true";
};
Util.getCookie = function (name) {
if (!Util.canUseCookies()) {
return;
}
var value = "";
if (name && name.length) {
var cookieName = name + "=";
var cookies = Util.document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
cookie = Util.trim(cookie);
if (cookie && cookie.indexOf(cookieName) === 0) {
value = cookie.substring(cookieName.length, cookies[i].length);
break;
}
}
}
return value;
};
Util.deleteCookie = function (name) {
if (Util.canUseCookies()) {
Util.document.cookie = name + "=;path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}
};
Util.trim = function (str) {
if (typeof str !== "string")
return str;
return str.replace(/^\s+|\s+$/g, "");
};
Util.newId = function () {
var base64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var result = "";
var random = Math.random() * 1073741824;
while (random > 0) {
var char = base64chars.charAt(random % 64);
result += char;
random = Math.floor(random / 64);
}
return result;
};
Util.isArray = function (obj) {
return Object.prototype.toString.call(obj) === "[object Array]";
};
Util.isError = function (obj) {
return Object.prototype.toString.call(obj) === "[object Error]";
};
Util.isDate = function (obj) {
return Object.prototype.toString.call(obj) === "[object Date]";
};
Util.toISOStringForIE8 = function (date) {
if (Util.isDate(date)) {
if (Date.prototype.toISOString) {
return date.toISOString();
}
else {
var pad = function (number) {
var r = String(number);
if (r.length === 1) {
r = "0" + r;
}
return r;
};
return date.getUTCFullYear()
+ "-" + pad(date.getUTCMonth() + 1)
+ "-" + pad(date.getUTCDate())
+ "T" + pad(date.getUTCHours())
+ ":" + pad(date.getUTCMinutes())
+ ":" + pad(date.getUTCSeconds())
+ "." + String((date.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5)
+ "Z";
}
}
};
Util.getIEVersion = function (userAgentStr) {
if (userAgentStr === void 0) { userAgentStr = null; }
var myNav = userAgentStr ? userAgentStr.toLowerCase() : navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : null;
};
Util.msToTimeSpan = function (totalms) {
if (isNaN(totalms) || totalms < 0) {
totalms = 0;
}
totalms = Math.round(totalms);
var ms = "" + totalms % 1000;
var sec = "" + Math.floor(totalms / 1000) % 60;
var min = "" + Math.floor(totalms / (1000 * 60)) % 60;
var hour = "" + Math.floor(totalms / (1000 * 60 * 60)) % 24;
var days = Math.floor(totalms / (1000 * 60 * 60 * 24));
ms = ms.length === 1 ? "00" + ms : ms.length === 2 ? "0" + ms : ms;
sec = sec.length < 2 ? "0" + sec : sec;
min = min.length < 2 ? "0" + min : min;
hour = hour.length < 2 ? "0" + hour : hour;
return (days > 0 ? days + "." : "") + hour + ":" + min + ":" + sec + "." + ms;
};
Util.isCrossOriginError = function (message, url, lineNumber, columnNumber, error) {
return (message === "Script error." || message === "Script error") && !error;
};
Util.dump = function (object) {
var objectTypeDump = Object.prototype.toString.call(object);
var propertyValueDump = JSON.stringify(object);
if (objectTypeDump === "[object Error]") {
propertyValueDump = "{ stack: '" + object.stack + "', message: '" + object.message + "', name: '" + object.name + "'";
}
return objectTypeDump + propertyValueDump;
};
Util.getExceptionName = function (object) {
var objectTypeDump = Object.prototype.toString.call(object);
if (objectTypeDump === "[object Error]") {
return object.name;
}
return "";
};
Util.addEventHandler = function (eventName, callback) {
if (!window || typeof eventName !== 'string' || typeof callback !== 'function') {
return false;
}
var verbEventName = 'on' + eventName;
if (window.addEventListener) {
window.addEventListener(eventName, callback, false);
}
else if (window["attachEvent"]) {
window["attachEvent"].call(verbEventName, callback);
}
else {
return false;
}
return true;
};
Util.IsBeaconApiSupported = function () {
return ('sendBeacon' in navigator && navigator.sendBeacon);
};
Util.document = typeof document !== "undefined" ? document : {};
Util._canUseCookies = undefined;
Util._canUseLocalStorage = undefined;
Util._canUseSessionStorage = undefined;
Util.NotSpecified = "not_specified";
return Util;
}());
ApplicationInsights.Util = Util;
var UrlHelper = (function () {
function UrlHelper() {
}
UrlHelper.parseUrl = function (url) {
if (!UrlHelper.htmlAnchorElement) {
UrlHelper.htmlAnchorElement = !!UrlHelper.document.createElement ? UrlHelper.document.createElement('a') : {};
}
UrlHelper.htmlAnchorElement.href = url;
return UrlHelper.htmlAnchorElement;
};
UrlHelper.getAbsoluteUrl = function (url) {
var result;
var a = UrlHelper.parseUrl(url);
if (a) {
result = a.href;
}
return result;
};
UrlHelper.getPathName = function (url) {
var result;
var a = UrlHelper.parseUrl(url);
if (a) {
result = a.pathname;
}
return result;
};
UrlHelper.getCompleteUrl = function (method, absoluteUrl) {
if (method) {
return method.toUpperCase() + " " + absoluteUrl;
}
else {
return absoluteUrl;
}
};
UrlHelper.document = typeof document !== "undefined" ? document : {};
return UrlHelper;
}());
ApplicationInsights.UrlHelper = UrlHelper;
})(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
})(Microsoft || (Microsoft = {}));
var Microsoft;
(function (Microsoft) {
var ApplicationInsights;
(function (ApplicationInsights) {
"use strict";
var extensions = (function () {
function extensions() {
}
extensions.IsNullOrUndefined = function (obj) {
return typeof (obj) === "undefined" || obj === null;
};
return extensions;
}());
ApplicationInsights.extensions = extensions;
var stringUtils = (function () {
function stringUtils() {
}
stringUtils.GetLength = function (strObject) {
var res = 0;
if (!extensions.IsNullOrUndefined(strObject)) {
var stringified = "";
try {
stringified = strObject.toString();
}
catch (ex) {
}
res = stringified.length;
res = isNaN(res) ? 0 : res;
}
return res;
};
return stringUtils;
}());
ApplicationInsights.stringUtils = stringUtils;
var dateTime = (function () {
function dateTime() {
}
dateTime.Now = (window.performance && window.performance.now && window.performance.timing) ?
function () {
return window.performance.now() + window.performance.timing.navigationStart;
}
:
function () {
return new Date().getTime();
};
dateTime.GetDuration = function (start, end) {
var result = null;
if (start !== 0 && end !== 0 && !extensions.IsNullOrUndefined(start) && !extensions.IsNullOrUndefined(end)) {
result = end - start;
}
return result;
};
return dateTime;
}());
ApplicationInsights.dateTime = dateTime;
var EventHelper = (function () {
function EventHelper() {
}
EventHelper.AttachEvent = function (obj, eventNameWithoutOn, handlerRef) {
var result = false;
if (!extensions.IsNullOrUndefined(obj)) {
if (!extensions.IsNullOrUndefined(obj.attachEvent)) {
obj.attachEvent("on" + eventNameWithoutOn, handlerRef);
result = true;
}
else {
if (!extensions.IsNullOrUndefined(obj.addEventListener)) {
obj.addEventListener(eventNameWithoutOn, handlerRef, false);
result = true;
}
}
}
return result;
};
EventHelper.DetachEvent = function (obj, eventNameWithoutOn, handlerRef) {
if (!extensions.IsNullOrUndefined(obj)) {
if (!extensions.IsNullOrUndefined(obj.detachEvent)) {
obj.detachEvent("on" + eventNameWithoutOn, handlerRef);
}
else {
if (!extensions.IsNullOrUndefined(obj.removeEventListener)) {
obj.removeEventListener(eventNameWithoutOn, handlerRef, false);
}
}
}
};
return EventHelper;
}());
ApplicationInsights.EventHelper = EventHelper;
})(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
})(Microsoft || (Microsoft = {}));
var Microsoft;
(function (Microsoft) {
var ApplicationInsights;
(function (ApplicationInsights) {
"use strict";
var XHRMonitoringState = (function () {
function XHRMonitoringState() {
this.openDone = false;
this.setRequestHeaderDone = false;
this.sendDone = false;
this.abortDone = false;
this.onreadystatechangeCallbackAttached = false;
}
return XHRMonitoringState;
}());
ApplicationInsights.XHRMonitoringState = XHRMonitoringState;
var ajaxRecord = (function () {
function ajaxRecord(id) {
this.completed = false;
this.requestHeadersSize = null;
this.ttfb = null;
this.responseReceivingDuration = null;
this.callbackDuration = null;
this.ajaxTotalDuration = null;
this.aborted = null;
this.pageUrl = null;
this.requestUrl = null;
this.requestSize = 0;
this.method = null;
this.status = null;
this.requestSentTime = null;
this.responseStartedTime = null;
this.responseFinishedTime = null;
this.callbackFinishedTime = null;
this.endTime = null;
this.originalOnreadystatechage = null;
this.xhrMonitoringState = new XHRMonitoringState();
this.clientFailure = 0;
this.CalculateMetrics = function () {
var self = this;
self.ajaxTotalDuration = Math.round(ApplicationInsights.dateTime.GetDuration(self.requestSentTime, self.responseFinishedTime) * 1000) / 1000;
};
this.id = id;
}
ajaxRecord.prototype.getAbsoluteUrl = function () {
return this.requestUrl ? ApplicationInsights.UrlHelper.getAbsoluteUrl(this.requestUrl) : null;
};
ajaxRecord.prototype.getPathName = function () {
return this.requestUrl ? ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeUrl(ApplicationInsights.UrlHelper.getCompleteUrl(this.method, this.requestUrl)) : null;
};
return ajaxRecord;
}());
ApplicationInsights.ajaxRecord = ajaxRecord;
;
})(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
})(Microsoft || (Microsoft = {}));
;
var Microsoft;
(function (Microsoft) {
var ApplicationInsights;
(function (ApplicationInsights) {
"use strict";
var AjaxMonitor = (function () {
function AjaxMonitor(appInsights) {
this.currentWindowHost = window.location.host;
this.appInsights = appInsights;
this.initialized = false;
this.Init();
}
AjaxMonitor.prototype.Init = function () {
if (this.supportsMonitoring()) {
this.instrumentOpen();
this.instrumentSend();
this.instrumentAbort();
this.initialized = true;
}
};
AjaxMonitor.prototype.isMonitoredInstance = function (xhr, excludeAjaxDataValidation) {
return this.initialized
&& (excludeAjaxDataValidation === true || !ApplicationInsights.extensions.IsNullOrUndefined(xhr.ajaxData))
&& xhr[AjaxMonitor.DisabledPropertyName] !== true;
};
AjaxMonitor.prototype.supportsMonitoring = function () {
var result = false;
if (!ApplicationInsights.extensions.IsNullOrUndefined(XMLHttpRequest)) {
result = true;
}
return result;
};
AjaxMonitor.prototype.instrumentOpen = function () {
var originalOpen = XMLHttpRequest.prototype.open;
var ajaxMonitorInstance = this;
XMLHttpRequest.prototype.open = function (method, url, async) {
try {
if (ajaxMonitorInstance.isMonitoredInstance(this, true) &&
(!this.ajaxData ||
!this.ajaxData.xhrMonitoringState.openDone)) {
ajaxMonitorInstance.openHandler(this, method, url, async);
}
}
catch (e) {
ApplicationInsights._InternalLogging.throwInternal(ApplicationInsights.LoggingSeverity.CRITICAL, ApplicationInsights._InternalMessageId.FailedMonitorAjaxOpen, "Failed to monitor XMLHttpRequest.open, monitoring data for this ajax call may be incorrect.", {
ajaxDiagnosticsMessage: AjaxMonitor.getFailedAjaxDiagnosticsMessage(this),
exception: Microsoft.ApplicationInsights.Util.dump(e)
});
}
return originalOpen.apply(this, arguments);
};
};
AjaxMonitor.prototype.openHandler = function (xhr, method, url, async) {
var ajaxData = new ApplicationInsights.ajaxRecord(ApplicationInsights.Util.newId());
ajaxData.method = method;
ajaxData.requestUrl = url;
ajaxData.xhrMonitoringState.openDone = true;
xhr.ajaxData = ajaxData;
this.attachToOnReadyStateChange(xhr);
};
AjaxMonitor.getFailedAjaxDiagnosticsMessage = function (xhr) {
var result = "";
try {
if (!ApplicationInsights.extensions.IsNullOrUndefined(xhr) &&
!ApplicationInsights.extensions.IsNullOrUndefined(xhr.ajaxData) &&
!ApplicationInsights.extensions.IsNullOrUndefined(xhr.ajaxData.requestUrl)) {
result += "(url: '" + xhr.ajaxData.requestUrl + "')";
}
}
catch (e) { }
return result;
};
AjaxMonitor.prototype.instrumentSend = function () {
var originalSend = XMLHttpRequest.prototype.send;
var ajaxMonitorInstance = this;
XMLHttpRequest.prototype.send = function (content) {
try {
if (ajaxMonitorInstance.isMonitoredInstance(this) && !this.ajaxData.xhrMonitoringState.sendDone) {
ajaxMonitorInstance.sendHandler(this, content);
}
}
catch (e) {
ApplicationInsights._InternalLogging.throwInternal(ApplicationInsights.LoggingSeverity.CRITICAL, ApplicationInsights._InternalMessageId.FailedMonitorAjaxSend, "Failed to monitor XMLHttpRequest, monitoring data for this ajax call may be incorrect.", {
ajaxDiagnosticsMessage: AjaxMonitor.getFailedAjaxDiagnosticsMessage(this),
exception: Microsoft.ApplicationInsights.Util.dump(e)
});
}
return originalSend.apply(this, arguments);
};
};
AjaxMonitor.prototype.sendHandler = function (xhr, content) {
xhr.ajaxData.requestSentTime = ApplicationInsights.dateTime.Now();
if (!this.appInsights.config.disableCorrelationHeaders && (ApplicationInsights.UrlHelper.parseUrl(xhr.ajaxData.getAbsoluteUrl()).host == this.currentWindowHost)) {
var rootId = this.appInsights.context.operation.id;
xhr.setRequestHeader("x-ms-request-root-id", rootId);
xhr.setRequestHeader("x-ms-request-id", xhr.ajaxData.id);
}
xhr.ajaxData.xhrMonitoringState.sendDone = true;
};
AjaxMonitor.prototype.instrumentAbort = function () {
var originalAbort = XMLHttpRequest.prototype.abort;
var ajaxMonitorInstance = this;
XMLHttpRequest.prototype.abort = function () {
try {
if (ajaxMonitorInstance.isMonitoredInstance(this) && !this.ajaxData.xhrMonitoringState.abortDone) {
this.ajaxData.aborted = 1;
this.ajaxData.xhrMonitoringState.abortDone = true;
}
}
catch (e) {
ApplicationInsights._InternalLogging.throwInternal(ApplicationInsights.LoggingSeverity.CRITICAL, ApplicationInsights._InternalMessageId.FailedMonitorAjaxAbort, "Failed to monitor XMLHttpRequest.abort, monitoring data for this ajax call may be incorrect.", {
ajaxDiagnosticsMessage: AjaxMonitor.getFailedAjaxDiagnosticsMessage(this),
exception: Microsoft.ApplicationInsights.Util.dump(e)
});
}
return originalAbort.apply(this, arguments);
};
};
AjaxMonitor.prototype.attachToOnReadyStateChange = function (xhr) {
var ajaxMonitorInstance = this;
xhr.ajaxData.xhrMonitoringState.onreadystatechangeCallbackAttached = ApplicationInsights.EventHelper.AttachEvent(xhr, "readystatechange", function () {
try {
if (ajaxMonitorInstance.isMonitoredInstance(xhr)) {
if (xhr.readyState === 4) {
ajaxMonitorInstance.onAjaxComplete(xhr);
}
}
}
catch (e) {
var exceptionText = Microsoft.ApplicationInsights.Util.dump(e);
if (!exceptionText || exceptionText.toLowerCase().indexOf("c00c023f") == -1) {
ApplicationInsights._InternalLogging.throwInternal(ApplicationInsights.LoggingSeverity.CRITICAL, ApplicationInsights._InternalMessageId.FailedMonitorAjaxRSC, "Failed to monitor XMLHttpRequest 'readystatechange' event handler, monitoring data for this ajax call may be incorrect.", {
ajaxDiagnosticsMessage: AjaxMonitor.getFailedAjaxDiagnosticsMessage(xhr),
exception: Microsoft.ApplicationInsights.Util.dump(e)
});
}
}
});
};
AjaxMonitor.prototype.onAjaxComplete = function (xhr) {
xhr.ajaxData.responseFinishedTime = ApplicationInsights.dateTime.Now();
xhr.ajaxData.status = xhr.status;
xhr.ajaxData.CalculateMetrics();
if (xhr.ajaxData.ajaxTotalDuration < 0) {
ApplicationInsights._InternalLogging.throwInternal(ApplicationInsights.LoggingSeverity.WARNING, ApplicationInsights._InternalMessageId.FailedMonitorAjaxDur, "Failed to calculate the duration of the ajax call, monitoring data for this ajax call won't be sent.", {
ajaxDiagnosticsMessage: AjaxMonitor.getFailedAjaxDiagnosticsMessage(xhr),
requestSentTime: xhr.ajaxData.requestSentTime,
responseFinishedTime: xhr.ajaxData.responseFinishedTime
});
}
else {
this.appInsights.trackDependency(xhr.ajaxData.id, xhr.ajaxData.method, xhr.ajaxData.getAbsoluteUrl(), xhr.ajaxData.getPathName(), xhr.ajaxData.ajaxTotalDuration, (+(xhr.ajaxData.status)) >= 200 && (+(xhr.ajaxData.status)) < 400, +xhr.ajaxData.status);
xhr.ajaxData = null;
}
};
AjaxMonitor.instrumentedByAppInsightsName = "InstrumentedByAppInsights";
AjaxMonitor.DisabledPropertyName = "Microsoft_ApplicationInsights_BypassAjaxInstrumentation";
return AjaxMonitor;
}());
ApplicationInsights.AjaxMonitor = AjaxMonitor;
})(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {}));
})(Microsoft || (Microsoft = {}));
var Microsoft;
(function (Microsoft) {
var ApplicationInsights;
(function (ApplicationInsights) {
var HashCodeScoreGenerator = (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.length < HashCodeScoreGenerator.MIN_INPUT_LENGTH) {
input = input.concat(input);
}
var hash = 5381;
for (var i = 0; i < input.length; ++i) {
hash = ((hash << 5) + hash) + input.charCodeAt(i);
hash = hash & hash;
}
return Math.abs(hash);
};
HashCodeScoreGenerator.INT_MAX_VALUE = 2147483647;
HashCodeScoreGenerator.MIN_INPUT_LENGTH = 8;
return HashCodeScoreGenerator;
}());