UNPKG

applicationinsights-js

Version:
960 lines (959 loc) 307 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. var Microsoft; (function (Microsoft) { var ApplicationInsights; (function (ApplicationInsights) { "use strict"; })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); })(Microsoft || (Microsoft = {})); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // THIS FILE WAS AUTOGENERATED var Microsoft; (function (Microsoft) { var Telemetry; (function (Telemetry) { "use strict"; /** * Data struct to contain only C section with custom fields. */ var Base = /** @class */ (function () { function Base() { } return Base; }()); Telemetry.Base = Base; })(Telemetry = Microsoft.Telemetry || (Microsoft.Telemetry = {})); })(Microsoft || (Microsoft = {})); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // THIS FILE WAS AUTOGENERATED /// <reference path="Base.ts" /> var Microsoft; (function (Microsoft) { var Telemetry; (function (Telemetry) { "use strict"; /** * System variables for a telemetry item. */ var Envelope = /** @class */ (function () { function Envelope() { this.ver = 1; this.sampleRate = 100.0; this.tags = {}; } return Envelope; }()); Telemetry.Envelope = Envelope; })(Telemetry = Microsoft.Telemetry || (Microsoft.Telemetry = {})); })(Microsoft || (Microsoft = {})); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. var Microsoft; (function (Microsoft) { var ApplicationInsights; (function (ApplicationInsights) { var Context; (function (Context) { "use strict"; })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); })(Microsoft || (Microsoft = {})); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. var Microsoft; (function (Microsoft) { var ApplicationInsights; (function (ApplicationInsights) { var Context; (function (Context) { "use strict"; })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); })(Microsoft || (Microsoft = {})); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. var Microsoft; (function (Microsoft) { var ApplicationInsights; (function (ApplicationInsights) { var Context; (function (Context) { "use strict"; })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); })(Microsoft || (Microsoft = {})); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. var Microsoft; (function (Microsoft) { var ApplicationInsights; (function (ApplicationInsights) { var Context; (function (Context) { "use strict"; })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); })(Microsoft || (Microsoft = {})); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. var Microsoft; (function (Microsoft) { var ApplicationInsights; (function (ApplicationInsights) { var Context; (function (Context) { "use strict"; })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); })(Microsoft || (Microsoft = {})); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. var Microsoft; (function (Microsoft) { var ApplicationInsights; (function (ApplicationInsights) { var Context; (function (Context) { "use strict"; })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); })(Microsoft || (Microsoft = {})); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. var Microsoft; (function (Microsoft) { var ApplicationInsights; (function (ApplicationInsights) { var Context; (function (Context) { "use strict"; })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); })(Microsoft || (Microsoft = {})); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. var Microsoft; (function (Microsoft) { var ApplicationInsights; (function (ApplicationInsights) { var Context; (function (Context) { "use strict"; })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); })(Microsoft || (Microsoft = {})); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. var Microsoft; (function (Microsoft) { var ApplicationInsights; (function (ApplicationInsights) { "use strict"; })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); })(Microsoft || (Microsoft = {})); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /// <reference path="./ISerializable.ts" /> var Microsoft; (function (Microsoft) { var ApplicationInsights; (function (ApplicationInsights) { "use strict"; })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); })(Microsoft || (Microsoft = {})); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /// <reference path="./Contracts/Generated/Envelope.ts" /> /// <reference path="./Context/IApplication.ts"/> /// <reference path="./Context/IDevice.ts"/> /// <reference path="./Context/IInternal.ts"/> /// <reference path="./Context/ILocation.ts"/> /// <reference path="./Context/IOperation.ts"/> /// <reference path="./Context/ISample.ts"/> /// <reference path="./Context/IUser.ts"/> /// <reference path="./Context/ISession.ts"/> /// <reference path="./Telemetry/IEnvelope.ts"/> var Microsoft; (function (Microsoft) { var ApplicationInsights; (function (ApplicationInsights) { "use strict"; })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); })(Microsoft || (Microsoft = {})); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // THIS FILE WAS AUTOGENERATED var AI; (function (AI) { "use strict"; /** * Defines the level of severity for the event. */ var SeverityLevel; (function (SeverityLevel) { SeverityLevel[SeverityLevel["Verbose"] = 0] = "Verbose"; SeverityLevel[SeverityLevel["Information"] = 1] = "Information"; SeverityLevel[SeverityLevel["Warning"] = 2] = "Warning"; SeverityLevel[SeverityLevel["Error"] = 3] = "Error"; SeverityLevel[SeverityLevel["Critical"] = 4] = "Critical"; })(SeverityLevel = AI.SeverityLevel || (AI.SeverityLevel = {})); })(AI || (AI = {})); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /// <reference path="./IConfig.ts" /> /// <reference path="./ITelemetryContext.ts" /> /// <reference path="./Contracts/Generated/SeverityLevel.ts" /> var Microsoft; (function (Microsoft) { var ApplicationInsights; (function (ApplicationInsights) { "use strict"; })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); })(Microsoft || (Microsoft = {})); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. var Microsoft; (function (Microsoft) { var ApplicationInsights; (function (ApplicationInsights) { var LoggingSeverity; (function (LoggingSeverity) { /** * Error will be sent as internal telemetry */ LoggingSeverity[LoggingSeverity["CRITICAL"] = 0] = "CRITICAL"; /** * Error will NOT be sent as internal telemetry, and will only be shown in browser console */ LoggingSeverity[LoggingSeverity["WARNING"] = 1] = "WARNING"; })(LoggingSeverity = ApplicationInsights.LoggingSeverity || (ApplicationInsights.LoggingSeverity = {})); /** * Internal message ID. Please create a new one for every conceptually different message. Please keep alphabetically ordered */ var _InternalMessageId; (function (_InternalMessageId) { // Non user actionable _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["FailedMonitorAjaxGetCorrelationHeader"] = 18] = "FailedMonitorAjaxGetCorrelationHeader"; _InternalMessageId[_InternalMessageId["FailedToAddHandlerForOnBeforeUnload"] = 19] = "FailedToAddHandlerForOnBeforeUnload"; _InternalMessageId[_InternalMessageId["FailedToSendQueuedTelemetry"] = 20] = "FailedToSendQueuedTelemetry"; _InternalMessageId[_InternalMessageId["FailedToReportDataLoss"] = 21] = "FailedToReportDataLoss"; _InternalMessageId[_InternalMessageId["FlushFailed"] = 22] = "FlushFailed"; _InternalMessageId[_InternalMessageId["MessageLimitPerPVExceeded"] = 23] = "MessageLimitPerPVExceeded"; _InternalMessageId[_InternalMessageId["MissingRequiredFieldSpecification"] = 24] = "MissingRequiredFieldSpecification"; _InternalMessageId[_InternalMessageId["NavigationTimingNotSupported"] = 25] = "NavigationTimingNotSupported"; _InternalMessageId[_InternalMessageId["OnError"] = 26] = "OnError"; _InternalMessageId[_InternalMessageId["SessionRenewalDateIsZero"] = 27] = "SessionRenewalDateIsZero"; _InternalMessageId[_InternalMessageId["SenderNotInitialized"] = 28] = "SenderNotInitialized"; _InternalMessageId[_InternalMessageId["StartTrackEventFailed"] = 29] = "StartTrackEventFailed"; _InternalMessageId[_InternalMessageId["StopTrackEventFailed"] = 30] = "StopTrackEventFailed"; _InternalMessageId[_InternalMessageId["StartTrackFailed"] = 31] = "StartTrackFailed"; _InternalMessageId[_InternalMessageId["StopTrackFailed"] = 32] = "StopTrackFailed"; _InternalMessageId[_InternalMessageId["TelemetrySampledAndNotSent"] = 33] = "TelemetrySampledAndNotSent"; _InternalMessageId[_InternalMessageId["TrackEventFailed"] = 34] = "TrackEventFailed"; _InternalMessageId[_InternalMessageId["TrackExceptionFailed"] = 35] = "TrackExceptionFailed"; _InternalMessageId[_InternalMessageId["TrackMetricFailed"] = 36] = "TrackMetricFailed"; _InternalMessageId[_InternalMessageId["TrackPVFailed"] = 37] = "TrackPVFailed"; _InternalMessageId[_InternalMessageId["TrackPVFailedCalc"] = 38] = "TrackPVFailedCalc"; _InternalMessageId[_InternalMessageId["TrackTraceFailed"] = 39] = "TrackTraceFailed"; _InternalMessageId[_InternalMessageId["TransmissionFailed"] = 40] = "TransmissionFailed"; _InternalMessageId[_InternalMessageId["FailedToSetStorageBuffer"] = 41] = "FailedToSetStorageBuffer"; _InternalMessageId[_InternalMessageId["FailedToRestoreStorageBuffer"] = 42] = "FailedToRestoreStorageBuffer"; _InternalMessageId[_InternalMessageId["InvalidBackendResponse"] = 43] = "InvalidBackendResponse"; _InternalMessageId[_InternalMessageId["FailedToFixDepricatedValues"] = 44] = "FailedToFixDepricatedValues"; _InternalMessageId[_InternalMessageId["InvalidDurationValue"] = 45] = "InvalidDurationValue"; // User actionable _InternalMessageId[_InternalMessageId["CannotSerializeObject"] = 46] = "CannotSerializeObject"; _InternalMessageId[_InternalMessageId["CannotSerializeObjectNonSerializable"] = 47] = "CannotSerializeObjectNonSerializable"; _InternalMessageId[_InternalMessageId["CircularReferenceDetected"] = 48] = "CircularReferenceDetected"; _InternalMessageId[_InternalMessageId["ClearAuthContextFailed"] = 49] = "ClearAuthContextFailed"; _InternalMessageId[_InternalMessageId["ExceptionTruncated"] = 50] = "ExceptionTruncated"; _InternalMessageId[_InternalMessageId["IllegalCharsInName"] = 51] = "IllegalCharsInName"; _InternalMessageId[_InternalMessageId["ItemNotInArray"] = 52] = "ItemNotInArray"; _InternalMessageId[_InternalMessageId["MaxAjaxPerPVExceeded"] = 53] = "MaxAjaxPerPVExceeded"; _InternalMessageId[_InternalMessageId["MessageTruncated"] = 54] = "MessageTruncated"; _InternalMessageId[_InternalMessageId["NameTooLong"] = 55] = "NameTooLong"; _InternalMessageId[_InternalMessageId["SampleRateOutOfRange"] = 56] = "SampleRateOutOfRange"; _InternalMessageId[_InternalMessageId["SetAuthContextFailed"] = 57] = "SetAuthContextFailed"; _InternalMessageId[_InternalMessageId["SetAuthContextFailedAccountName"] = 58] = "SetAuthContextFailedAccountName"; _InternalMessageId[_InternalMessageId["StringValueTooLong"] = 59] = "StringValueTooLong"; _InternalMessageId[_InternalMessageId["StartCalledMoreThanOnce"] = 60] = "StartCalledMoreThanOnce"; _InternalMessageId[_InternalMessageId["StopCalledWithoutStart"] = 61] = "StopCalledWithoutStart"; _InternalMessageId[_InternalMessageId["TelemetryInitializerFailed"] = 62] = "TelemetryInitializerFailed"; _InternalMessageId[_InternalMessageId["TrackArgumentsNotSpecified"] = 63] = "TrackArgumentsNotSpecified"; _InternalMessageId[_InternalMessageId["UrlTooLong"] = 64] = "UrlTooLong"; _InternalMessageId[_InternalMessageId["SessionStorageBufferFull"] = 65] = "SessionStorageBufferFull"; _InternalMessageId[_InternalMessageId["CannotAccessCookie"] = 66] = "CannotAccessCookie"; _InternalMessageId[_InternalMessageId["IdTooLong"] = 67] = "IdTooLong"; })(_InternalMessageId = ApplicationInsights._InternalMessageId || (ApplicationInsights._InternalMessageId = {})); var _InternalLogMessage = /** @class */ (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, "") + "\""; }; /** * For user non actionable traces use AI Internal prefix. */ _InternalLogMessage.AiNonUserActionablePrefix = "AI (Internal): "; /** * Prefix of the traces in portal. */ _InternalLogMessage.AiUserActionablePrefix = "AI: "; return _InternalLogMessage; }()); ApplicationInsights._InternalLogMessage = _InternalLogMessage; var _InternalLogging = /** @class */ (function () { function _InternalLogging() { } /** * This method will throw exceptions in debug mode or attempt to log the error as a console warning. * @param severity {LoggingSeverity} - The severity of the log message * @param message {_InternalLogMessage} - The log message. */ _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) { // check if this message type was already logged to console for this page view and if so, don't log it again var messageKey = _InternalMessageId[message.messageId]; if (!this._messageLogged[messageKey] || this.verboseLogging()) { this.warnToConsole(message.message); this._messageLogged[messageKey] = true; } } else { // don't log internal AI traces in the console, unless the verbose logging is enabled if (this.verboseLogging()) { this.warnToConsole(message.message); } } this.logInternalMessage(severity, message); } } } }; /** * This will write a warning to the console if possible * @param message {string} - The warning 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); } } }; /** * Resets the internal message count */ _InternalLogging.resetInternalMessageCount = function () { this._messageCount = 0; this._messageLogged = {}; }; /** * Clears the list of records indicating that internal message type was already logged */ _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]); } } } }; /** * Sets the limit for the number of internal events before they are throttled * @param limit {number} - The throttle limit to set for internal events */ _InternalLogging.setMaxInternalMessageLimit = function (limit) { if (!limit) { throw new Error('limit cannot be undefined.'); } this.MAX_INTERNAL_MESSAGE_LIMIT = limit; }; /** * Logs a message to the internal queue. * @param severity {LoggingSeverity} - The severity of the log message * @param message {_InternalLogMessage} - The message to log. */ _InternalLogging.logInternalMessage = function (severity, message) { if (this._areInternalMessagesThrottled()) { return; } // check if this message type was already logged for this session and if so, don't log it again 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 the session storage is not available, limit to only one message type per page view if (this._messageLogged[messageKey]) { logMessage = false; } else { this._messageLogged[messageKey] = true; } } if (logMessage) { // Push the event in the internal queue if (this.verboseLogging() || severity === LoggingSeverity.CRITICAL) { this.queue.push(message); this._messageCount++; } // When throttle limit reached, send a special event 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); } } }; /** * Indicates whether the internal events are throttled */ _InternalLogging._areInternalMessagesThrottled = function () { return this._messageCount >= this.MAX_INTERNAL_MESSAGE_LIMIT; }; /** * Session storage key for the prefix for the key indicating message type already logged */ _InternalLogging.AIInternalMessagePrefix = "AITR_"; /** * When this is true the SDK will throw exceptions to aid in debugging. */ _InternalLogging.enableDebugExceptions = function () { return false; }; /** * When this is true the SDK will log more messages to aid in debugging. */ _InternalLogging.verboseLogging = function () { return false; }; /** * The internal logging queue */ _InternalLogging.queue = []; /** * The maximum number of internal messages allowed to be sent per page view */ _InternalLogging.MAX_INTERNAL_MESSAGE_LIMIT = 25; /** * Count of internal messages sent */ _InternalLogging._messageCount = 0; /** * Holds information about what message types were already logged to console or sent to server. */ _InternalLogging._messageLogged = {}; return _InternalLogging; }()); ApplicationInsights._InternalLogging = _InternalLogging; })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); })(Microsoft || (Microsoft = {})); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. var Microsoft; (function (Microsoft) { var ApplicationInsights; (function (ApplicationInsights) { "use strict"; var UtilHelpers = /** @class */ (function () { function UtilHelpers() { } /** * generate random id string */ UtilHelpers.newId = function () { var base64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var result = ""; // tslint:disable-next-line:insecure-random var random = Math.random() * 1073741824; //5 symbols in base64, almost maxint while (random > 0) { var char = base64chars.charAt(random % 64); result += char; random = Math.floor(random / 64); } return result; }; return UtilHelpers; }()); ApplicationInsights.UtilHelpers = UtilHelpers; })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); })(Microsoft || (Microsoft = {})); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /// <reference path="./Logging.ts" /> /// <reference path="./UtilHelpers.ts" /> function _endsWith(value, search) { var len = value.length; var start = len - search.length; return value.substring(start >= 0 ? start : 0, len) === search; } var Microsoft; (function (Microsoft) { var ApplicationInsights; (function (ApplicationInsights) { /** * Type of storage to differentiate between local storage and session storage */ var StorageType; (function (StorageType) { StorageType[StorageType["LocalStorage"] = 0] = "LocalStorage"; StorageType[StorageType["SessionStorage"] = 1] = "SessionStorage"; })(StorageType || (StorageType = {})); var Util = /** @class */ (function () { function Util() { } /* * Force the SDK not to use local and session storage */ Util.disableStorage = function () { Util._canUseLocalStorage = false; Util._canUseSessionStorage = false; }; /** * Gets the localStorage object if available * @return {Storage} - Returns the storage object if available else returns null */ Util._getLocalStorageObject = function () { if (Util.canUseLocalStorage()) { return Util._getVerifiedStorageObject(StorageType.LocalStorage); } return null; }; /** * Tests storage object (localStorage or sessionStorage) to verify that it is usable * More details here: https://mathiasbynens.be/notes/localstorage-pattern * @param storageType Type of storage * @return {Storage} Returns storage object verified that it is usable */ 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; }; /** * Checks if endpoint URL is application insights internal injestion service URL. * * @param endpointUrl Endpoint URL to check. * @returns {boolean} True if if endpoint URL is application insights internal injestion service URL. */ Util.isInternalApplicationInsightsEndpoint = function (endpointUrl) { return Util._internalEndpoints.indexOf(endpointUrl.toLowerCase()) !== -1; }; /** * Check if the browser supports local storage. * * @returns {boolean} True if local storage is supported. */ Util.canUseLocalStorage = function () { if (Util._canUseLocalStorage === undefined) { Util._canUseLocalStorage = !!Util._getVerifiedStorageObject(StorageType.LocalStorage); } return Util._canUseLocalStorage; }; /** * Get an object from the browser's local storage * * @param {string} name - the name of the object to get from storage * @returns {string} The contents of the storage object with the given name. Null if storage is not supported. */ 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; }; /** * Set the contents of an object in the browser's local storage * * @param {string} name - the name of the object to set in storage * @param {string} data - the contents of the object to set in storage * @returns {boolean} True if the storage object could be written. */ 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; }; /** * Remove an object from the browser's local storage * * @param {string} name - the name of the object to remove from storage * @returns {boolean} True if the storage object could be removed. */ 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; }; /** * Gets the sessionStorage object if available * @return {Storage} - Returns the storage object if available else returns null */ Util._getSessionStorageObject = function () { if (Util.canUseSessionStorage()) { return Util._getVerifiedStorageObject(StorageType.SessionStorage); } return null; }; /** * Check if the browser supports session storage. * * @returns {boolean} True if session storage is supported. */ Util.canUseSessionStorage = function () { if (Util._canUseSessionStorage === undefined) { Util._canUseSessionStorage = !!Util._getVerifiedStorageObject(StorageType.SessionStorage); } return Util._canUseSessionStorage; }; /** * Gets the list of session storage keys * * @returns {string[]} List of session storage keys */ Util.getSessionStorageKeys = function () { var keys = []; if (Util.canUseSessionStorage()) { for (var key in window.sessionStorage) { keys.push(key); } } return keys; }; /** * Get an object from the browser's session storage * * @param {string} name - the name of the object to get from storage * @returns {string} The contents of the storage object with the given name. Null if storage is not supported. */ 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; }; /** * Set the contents of an object in the browser's session storage * * @param {string} name - the name of the object to set in storage * @param {string} data - the contents of the object to set in storage * @returns {boolean} True if the storage object could be written. */ 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; }; /** * Remove an object from the browser's session storage * * @param {string} name - the name of the object to remove from storage * @returns {boolean} True if the storage object could be removed. */ 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; }; /* * Force the SDK not to store and read any data from cookies */ Util.disableCookies = function () { Util._canUseCookies = false; }; /* * helper method to tell if document.cookie object is available */ 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.disallowsSameSiteNone = function (userAgent) { if (typeof userAgent !== "string") { return false; } // Cover all iOS based browsers here. This includes: // - Safari on iOS 12 for iPhone, iPod Touch, iPad // - WkWebview on iOS 12 for iPhone, iPod Touch, iPad // - Chrome on iOS 12 for iPhone, iPod Touch, iPad // All of which are broken by SameSite=None, because they use the iOS networking stack if (userAgent.indexOf("CPU iPhone OS 12") !== -1 || userAgent.indexOf("iPad; CPU OS 12") !== -1) { return true; } // Cover Mac OS X based browsers that use the Mac OS networking stack. This includes: // - Safari on Mac OS X // This does not include: // - Internal browser on Mac OS X // - Chrome on Mac OS X // - Chromium on Mac OS X // Because they do not use the Mac OS networking stack. if (userAgent.indexOf("Macintosh; Intel Mac OS X 10_14") !== -1 && userAgent.indexOf("Version/") !== -1 && userAgent.indexOf("Safari") !== -1) { return true; } // Cover Mac OS X internal browsers that use the Mac OS networking stack. This includes: // - Internal browser on Mac OS X // This does not include: // - Safari on Mac OS X // - Chrome on Mac OS X // - Chromium on Mac OS X // Because they do not use the Mac OS networking stack. if (userAgent.indexOf("Macintosh; Intel Mac OS X 10_14") !== -1 && _endsWith(userAgent, "AppleWebKit/605.1.15 (KHTML, like Gecko)")) { return true; } // Cover Chrome 50-69, because some versions are broken by SameSite=None, and none in this range require it. // Note: this covers some pre-Chromium Edge versions, but pre-Chromim Edge does not require SameSite=None, so this is fine. // Note: this regex applies to Windows, Mac OS X, and Linux, deliberately. if (userAgent.indexOf("Chrome/5") !== -1 || userAgent.indexOf("Chrome/6") !== -1) { return true; } // Unreal Engine runs Chromium 59, but does not advertise as Chrome until 4.23. Treat versions of Unreal // that don't specify their Chrome version as lacking support for SameSite=None. if (userAgent.indexOf("UnrealEngine") !== -1 && userAgent.indexOf("Chrome") === -1) { return true; } // UCBrowser < 12.13.2 ignores Set-Cookie headers with SameSite=None // NB: this rule isn't complete - you need regex to make a complete rule. // See: https://www.chromium.org/updates/same-site/incompatible-clients if (userAgent.indexOf("UCBrowser/12") !== -1 || userAgent.indexOf("UCBrowser/11") !== -1) { return true; } return false; }; /** * helper method to set userId and sessionId cookie */ 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._uaDisallowsSameSiteNone === null) { if (typeof navigator !== "undefined") { Util._uaDisallowsSameSiteNone = Util.disallowsSameSiteNone(navigator.userAgent); } } if (!Util._uaDisallowsSameSiteNone) { value = value + ";SameSite=None"; // SameSite can only be changed on secure pages and browsers that support samesite=None setting } } 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"; }; /** * helper method to access userId and sessionId cookie */ 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; }; /** * Deletes a cookie by setting it's expiration time in the past. * @param name - The name of the cookie to delete. */ Util.deleteCookie = function (name) { if (Util.canUseCookies()) { // Setting the expiration date in the past immediately removes the cookie Util.document.cookie = name + "=;path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT;"; } }; /** * helper method to trim strings (IE8 does not implement String.prototype.trim) */ Util.trim = function (str) { if (typeof str !== "string") return str; return str.replace(/^\s+|\s+$/g, ""); }; /** * generate random id string */ Util.newId = function () { return ApplicationInsights.UtilHelpers.newId(); }; /** * Check if an object is of type Array */ Util.isArray = function (obj) { return Object.prototype.toString.call(obj) === "[object Array]"; }; /** * Check if an object is of type Error */ Util.isError = function (obj) { return Object.prototype.toString.call(obj) === "[object Error]"; }; /** * Check if an object is of type Date */ Util.isDate = function (obj) { return Object.prototype.toString.call(obj) === "[object Date]"; }; /** * Convert a date to I.S.O. format in IE8 */ 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) {