From e1a71fbb988a9e3bd09b5c9fafaf7c230072535d Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Tue, 20 May 2025 22:29:22 +0000 Subject: [PATCH 01/22] Initial plan for issue From d1ffffcd3da87b96ee64268fd69d7fe7b926cd22 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Tue, 20 May 2025 22:41:52 +0000 Subject: [PATCH 02/22] Fix Safari SecurityError when Block All Cookies is set Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- .../src/Interfaces/Context/IApplication.ts | 2 +- .../src/Interfaces/Context/IDevice.ts | 2 +- .../src/Interfaces/Context/IInternal.ts | 2 +- .../src/Interfaces/Context/ILocation.ts | 2 +- .../src/Interfaces/Context/ISample.ts | 2 +- .../src/Interfaces/Context/ISession.ts | 2 +- .../src/Interfaces/Context/ITelemetryTrace.ts | 2 +- .../src/Interfaces/Context/IUser.ts | 2 +- .../src/Interfaces/Context/IWeb.ts | 2 +- .../Interfaces/Contracts/ContextTagKeys.ts | 2 +- .../src/Interfaces/Contracts/DataPointType.ts | 2 +- .../src/Interfaces/Contracts/IData.ts | 2 +- .../src/Interfaces/Contracts/SeverityLevel.ts | 2 +- .../src/Interfaces/ICorrelationConfig.ts | 2 +- .../IPageViewPerformanceTelemetry.ts | 2 +- .../src/Interfaces/IPropertiesPlugin.ts | 2 +- .../src/Interfaces/IStorageBuffer.ts | 2 +- .../src/Interfaces/PartAExtensions.ts | 2 +- .../src/Interfaces/Telemetry/IEnvelope.ts | 2 +- .../src/Interfaces/Telemetry/ISerializable.ts | 2 +- .../src/RequestResponseHeaders.ts | 1 - .../src/StorageHelperFuncs.ts | 77 ++++++++++++++++--- 22 files changed, 87 insertions(+), 31 deletions(-) diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IApplication.ts b/shared/AppInsightsCommon/src/Interfaces/Context/IApplication.ts index 59cc2cb87..19c4f1cb6 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Context/IApplication.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Context/IApplication.ts @@ -11,4 +11,4 @@ export interface IApplication { * The application build version. */ build: string; -} \ No newline at end of file +} diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IDevice.ts b/shared/AppInsightsCommon/src/Interfaces/Context/IDevice.ts index 8e5c5fcb2..21140cdaa 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Context/IDevice.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Context/IDevice.ts @@ -25,4 +25,4 @@ export interface IDevice { * The IP address. */ ip: string; -} \ No newline at end of file +} diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IInternal.ts b/shared/AppInsightsCommon/src/Interfaces/Context/IInternal.ts index b68d23324..5279f5df2 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Context/IInternal.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Context/IInternal.ts @@ -26,4 +26,4 @@ export interface IInternal { * Identifies the source of the sdk script */ sdkSrc: string; -} \ No newline at end of file +} diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/ILocation.ts b/shared/AppInsightsCommon/src/Interfaces/Context/ILocation.ts index 411c3505b..8f1b00dee 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Context/ILocation.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Context/ILocation.ts @@ -6,4 +6,4 @@ export interface ILocation { * Client IP address for reverse lookup */ ip: string; -} \ No newline at end of file +} diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/ISample.ts b/shared/AppInsightsCommon/src/Interfaces/Context/ISample.ts index cc46225ef..fef4ff9dd 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Context/ISample.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Context/ISample.ts @@ -10,4 +10,4 @@ export interface ISample { sampleRate: number; isSampledIn(envelope: ITelemetryItem): boolean; -} \ No newline at end of file +} diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/ISession.ts b/shared/AppInsightsCommon/src/Interfaces/Context/ISession.ts index f76229544..0413c6606 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Context/ISession.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Context/ISession.ts @@ -19,4 +19,4 @@ export interface ISession { * Per the spec the ID will be regenerated if more than renewalSpan milliseconds elapse from this time with no activity. */ renewalDate?: number; -} \ No newline at end of file +} diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/ITelemetryTrace.ts b/shared/AppInsightsCommon/src/Interfaces/Context/ITelemetryTrace.ts index 4b12ebf00..523a852f2 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Context/ITelemetryTrace.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Context/ITelemetryTrace.ts @@ -30,4 +30,4 @@ export interface ITelemetryTrace { } export interface ITraceState { -} \ No newline at end of file +} diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IUser.ts b/shared/AppInsightsCommon/src/Interfaces/Context/IUser.ts index f75b667c7..2b185dd65 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Context/IUser.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Context/IUser.ts @@ -47,4 +47,4 @@ export interface IUserContext extends IUser { setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string, storeInCookie?: boolean): void; clearAuthenticatedUserContext(): void; update (userId?: string): void; -} \ No newline at end of file +} diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IWeb.ts b/shared/AppInsightsCommon/src/Interfaces/Context/IWeb.ts index 2aad34697..5632c5642 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Context/IWeb.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Context/IWeb.ts @@ -36,4 +36,4 @@ export interface IWeb { * Current domain. Leverages Window.location.hostname. populated to properties bag */ domain: string; -} \ No newline at end of file +} diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/ContextTagKeys.ts b/shared/AppInsightsCommon/src/Interfaces/Contracts/ContextTagKeys.ts index c02da207c..47ca597ea 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/ContextTagKeys.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/ContextTagKeys.ts @@ -296,4 +296,4 @@ export class ContextTagKeys extends createClassFromInterface({ constructor() { super(); } -} \ No newline at end of file +} diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/DataPointType.ts b/shared/AppInsightsCommon/src/Interfaces/Contracts/DataPointType.ts index 83eb92e19..8a4892d3f 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/DataPointType.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/DataPointType.ts @@ -7,4 +7,4 @@ export const enum DataPointType { Measurement = 0, Aggregation = 1 -} \ No newline at end of file +} diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IData.ts b/shared/AppInsightsCommon/src/Interfaces/Contracts/IData.ts index 444c0a21a..70cc41c2c 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/IData.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/IData.ts @@ -16,4 +16,4 @@ export interface IData extends IBase { * Container for data item (B section). */ baseData: TDomain; -} \ No newline at end of file +} diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/SeverityLevel.ts b/shared/AppInsightsCommon/src/Interfaces/Contracts/SeverityLevel.ts index 14aa4c474..e53963a9c 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/SeverityLevel.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/SeverityLevel.ts @@ -25,4 +25,4 @@ export const SeverityLevel = createEnumStyle({ Critical: eSeverityLevel.Critical }); -export type SeverityLevel = number | eSeverityLevel; \ No newline at end of file +export type SeverityLevel = number | eSeverityLevel; diff --git a/shared/AppInsightsCommon/src/Interfaces/ICorrelationConfig.ts b/shared/AppInsightsCommon/src/Interfaces/ICorrelationConfig.ts index 1f1de850c..c0be0ed45 100644 --- a/shared/AppInsightsCommon/src/Interfaces/ICorrelationConfig.ts +++ b/shared/AppInsightsCommon/src/Interfaces/ICorrelationConfig.ts @@ -97,4 +97,4 @@ export interface ICorrelationConfig { * should not be excluded. */ addIntEndpoints?: boolean; -} \ No newline at end of file +} diff --git a/shared/AppInsightsCommon/src/Interfaces/IPageViewPerformanceTelemetry.ts b/shared/AppInsightsCommon/src/Interfaces/IPageViewPerformanceTelemetry.ts index 044b3d908..e90738873 100644 --- a/shared/AppInsightsCommon/src/Interfaces/IPageViewPerformanceTelemetry.ts +++ b/shared/AppInsightsCommon/src/Interfaces/IPageViewPerformanceTelemetry.ts @@ -58,4 +58,4 @@ export interface IPageViewPerformanceTelemetryInternal extends IPageViewPerforma * Duration in miliseconds */ durationMs?: number; -} \ No newline at end of file +} diff --git a/shared/AppInsightsCommon/src/Interfaces/IPropertiesPlugin.ts b/shared/AppInsightsCommon/src/Interfaces/IPropertiesPlugin.ts index f539abf52..bd1aade29 100644 --- a/shared/AppInsightsCommon/src/Interfaces/IPropertiesPlugin.ts +++ b/shared/AppInsightsCommon/src/Interfaces/IPropertiesPlugin.ts @@ -5,4 +5,4 @@ import { ITelemetryContext } from "./ITelemetryContext"; export interface IPropertiesPlugin { readonly context: ITelemetryContext; -} \ No newline at end of file +} diff --git a/shared/AppInsightsCommon/src/Interfaces/IStorageBuffer.ts b/shared/AppInsightsCommon/src/Interfaces/IStorageBuffer.ts index c65cb1e85..5e575a922 100644 --- a/shared/AppInsightsCommon/src/Interfaces/IStorageBuffer.ts +++ b/shared/AppInsightsCommon/src/Interfaces/IStorageBuffer.ts @@ -16,4 +16,4 @@ export interface IStorageBuffer { * Sets the stored value for a given key */ setItem(logger: IDiagnosticLogger, name: string, data: string): boolean; -} \ No newline at end of file +} diff --git a/shared/AppInsightsCommon/src/Interfaces/PartAExtensions.ts b/shared/AppInsightsCommon/src/Interfaces/PartAExtensions.ts index 1aa523099..506a7a400 100644 --- a/shared/AppInsightsCommon/src/Interfaces/PartAExtensions.ts +++ b/shared/AppInsightsCommon/src/Interfaces/PartAExtensions.ts @@ -11,4 +11,4 @@ export const Extensions = { SDKExt: "sdk" }; -export let CtxTagKeys = new ContextTagKeys(); \ No newline at end of file +export let CtxTagKeys = new ContextTagKeys(); diff --git a/shared/AppInsightsCommon/src/Interfaces/Telemetry/IEnvelope.ts b/shared/AppInsightsCommon/src/Interfaces/Telemetry/IEnvelope.ts index ef58264b3..28e0e3c20 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Telemetry/IEnvelope.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Telemetry/IEnvelope.ts @@ -44,4 +44,4 @@ export interface IEnvelope extends ISerializable { * Telemetry data item. */ data: any; -} \ No newline at end of file +} diff --git a/shared/AppInsightsCommon/src/Interfaces/Telemetry/ISerializable.ts b/shared/AppInsightsCommon/src/Interfaces/Telemetry/ISerializable.ts index 71db06e0c..94420c19d 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Telemetry/ISerializable.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Telemetry/ISerializable.ts @@ -8,4 +8,4 @@ export interface ISerializable { * for each field defines whether the field is required or not. */ aiDataContract: any; -} \ No newline at end of file +} diff --git a/shared/AppInsightsCommon/src/RequestResponseHeaders.ts b/shared/AppInsightsCommon/src/RequestResponseHeaders.ts index 88ed828fc..78ceda3fa 100644 --- a/shared/AppInsightsCommon/src/RequestResponseHeaders.ts +++ b/shared/AppInsightsCommon/src/RequestResponseHeaders.ts @@ -93,4 +93,3 @@ export const RequestHeaders = createValueMap Date: Tue, 20 May 2025 23:43:02 +0000 Subject: [PATCH 03/22] Fix PR comments on StorageHelperFuncs.ts Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- shared/AppInsightsCommon/src/StorageHelperFuncs.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts index d654876c8..6f9f6904a 100644 --- a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts +++ b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts @@ -5,6 +5,7 @@ import { IDiagnosticLogger, _eInternalMessageId, _throwInternal, dumpObj, eLoggingSeverity, getExceptionName, getGlobal, getGlobalInst, isNullOrUndefined, objForEachKey } from "@microsoft/applicationinsights-core-js"; +import { objGetOwnPropertyDescriptor } from "@nevware21/ts-utils"; import { StorageType } from "./Enums"; let _canUseLocalStorage: boolean = undefined; @@ -33,21 +34,21 @@ function _canSafelyAccessStorage(storageType: StorageType): boolean { const storageTypeName = storageType === StorageType.LocalStorage ? "localStorage" : "sessionStorage"; try { - // First, check if window exists - if (isNullOrUndefined(getGlobal())) { + // First, check if window exists and get the global object once + const gbl: any = getGlobal(); + if (isNullOrUndefined(gbl)) { return false; } // Try to indirectly check if the property exists and is accessible // This avoids direct property access that might throw in Safari with "Block All Cookies" enabled - const gbl: any = getGlobal(); // Some browsers throw when accessing the property descriptors with getOwnPropertyDescriptor // Others throw when directly accessing the storage objects // This approach tries both methods safely try { // Method 1: Try using property descriptor - safer in Safari with cookies blocked - const descriptor = Object.getOwnPropertyDescriptor(gbl, storageTypeName); + const descriptor = objGetOwnPropertyDescriptor(gbl, storageTypeName); if (!descriptor || !descriptor.get) { return false; } From 16f3b92d7102170f9d7d3a43f99cbfb90ff1c14d Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 21 May 2025 00:03:21 +0000 Subject: [PATCH 04/22] Remove newline changes from interface files per PR feedback Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- shared/AppInsightsCommon/src/Interfaces/Context/IApplication.ts | 2 +- shared/AppInsightsCommon/src/Interfaces/Context/IDevice.ts | 2 +- shared/AppInsightsCommon/src/Interfaces/Context/IInternal.ts | 2 +- shared/AppInsightsCommon/src/Interfaces/Context/ILocation.ts | 2 +- shared/AppInsightsCommon/src/Interfaces/Context/ISample.ts | 2 +- shared/AppInsightsCommon/src/Interfaces/Context/ISession.ts | 2 +- .../AppInsightsCommon/src/Interfaces/Context/ITelemetryTrace.ts | 2 +- shared/AppInsightsCommon/src/Interfaces/Context/IUser.ts | 2 +- shared/AppInsightsCommon/src/Interfaces/Context/IWeb.ts | 2 +- .../src/Interfaces/Contracts/ContextTagKeys.ts | 2 +- .../AppInsightsCommon/src/Interfaces/Contracts/DataPointType.ts | 2 +- shared/AppInsightsCommon/src/Interfaces/Contracts/IData.ts | 2 +- .../AppInsightsCommon/src/Interfaces/Contracts/SeverityLevel.ts | 2 +- shared/AppInsightsCommon/src/Interfaces/ICorrelationConfig.ts | 2 +- .../src/Interfaces/IPageViewPerformanceTelemetry.ts | 2 +- shared/AppInsightsCommon/src/Interfaces/IPropertiesPlugin.ts | 2 +- shared/AppInsightsCommon/src/Interfaces/IStorageBuffer.ts | 2 +- shared/AppInsightsCommon/src/Interfaces/PartAExtensions.ts | 2 +- shared/AppInsightsCommon/src/Interfaces/Telemetry/IEnvelope.ts | 2 +- .../AppInsightsCommon/src/Interfaces/Telemetry/ISerializable.ts | 2 +- shared/AppInsightsCommon/src/RequestResponseHeaders.ts | 2 +- 21 files changed, 21 insertions(+), 21 deletions(-) diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IApplication.ts b/shared/AppInsightsCommon/src/Interfaces/Context/IApplication.ts index 19c4f1cb6..59cc2cb87 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Context/IApplication.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Context/IApplication.ts @@ -11,4 +11,4 @@ export interface IApplication { * The application build version. */ build: string; -} +} \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IDevice.ts b/shared/AppInsightsCommon/src/Interfaces/Context/IDevice.ts index 21140cdaa..8e5c5fcb2 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Context/IDevice.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Context/IDevice.ts @@ -25,4 +25,4 @@ export interface IDevice { * The IP address. */ ip: string; -} +} \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IInternal.ts b/shared/AppInsightsCommon/src/Interfaces/Context/IInternal.ts index 5279f5df2..b68d23324 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Context/IInternal.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Context/IInternal.ts @@ -26,4 +26,4 @@ export interface IInternal { * Identifies the source of the sdk script */ sdkSrc: string; -} +} \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/ILocation.ts b/shared/AppInsightsCommon/src/Interfaces/Context/ILocation.ts index 8f1b00dee..411c3505b 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Context/ILocation.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Context/ILocation.ts @@ -6,4 +6,4 @@ export interface ILocation { * Client IP address for reverse lookup */ ip: string; -} +} \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/ISample.ts b/shared/AppInsightsCommon/src/Interfaces/Context/ISample.ts index fef4ff9dd..cc46225ef 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Context/ISample.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Context/ISample.ts @@ -10,4 +10,4 @@ export interface ISample { sampleRate: number; isSampledIn(envelope: ITelemetryItem): boolean; -} +} \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/ISession.ts b/shared/AppInsightsCommon/src/Interfaces/Context/ISession.ts index 0413c6606..f76229544 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Context/ISession.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Context/ISession.ts @@ -19,4 +19,4 @@ export interface ISession { * Per the spec the ID will be regenerated if more than renewalSpan milliseconds elapse from this time with no activity. */ renewalDate?: number; -} +} \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/ITelemetryTrace.ts b/shared/AppInsightsCommon/src/Interfaces/Context/ITelemetryTrace.ts index 523a852f2..4b12ebf00 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Context/ITelemetryTrace.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Context/ITelemetryTrace.ts @@ -30,4 +30,4 @@ export interface ITelemetryTrace { } export interface ITraceState { -} +} \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IUser.ts b/shared/AppInsightsCommon/src/Interfaces/Context/IUser.ts index 2b185dd65..f75b667c7 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Context/IUser.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Context/IUser.ts @@ -47,4 +47,4 @@ export interface IUserContext extends IUser { setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string, storeInCookie?: boolean): void; clearAuthenticatedUserContext(): void; update (userId?: string): void; -} +} \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IWeb.ts b/shared/AppInsightsCommon/src/Interfaces/Context/IWeb.ts index 5632c5642..2aad34697 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Context/IWeb.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Context/IWeb.ts @@ -36,4 +36,4 @@ export interface IWeb { * Current domain. Leverages Window.location.hostname. populated to properties bag */ domain: string; -} +} \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/ContextTagKeys.ts b/shared/AppInsightsCommon/src/Interfaces/Contracts/ContextTagKeys.ts index 47ca597ea..c02da207c 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/ContextTagKeys.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/ContextTagKeys.ts @@ -296,4 +296,4 @@ export class ContextTagKeys extends createClassFromInterface({ constructor() { super(); } -} +} \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/DataPointType.ts b/shared/AppInsightsCommon/src/Interfaces/Contracts/DataPointType.ts index 8a4892d3f..83eb92e19 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/DataPointType.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/DataPointType.ts @@ -7,4 +7,4 @@ export const enum DataPointType { Measurement = 0, Aggregation = 1 -} +} \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IData.ts b/shared/AppInsightsCommon/src/Interfaces/Contracts/IData.ts index 70cc41c2c..444c0a21a 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/IData.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/IData.ts @@ -16,4 +16,4 @@ export interface IData extends IBase { * Container for data item (B section). */ baseData: TDomain; -} +} \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/SeverityLevel.ts b/shared/AppInsightsCommon/src/Interfaces/Contracts/SeverityLevel.ts index e53963a9c..14aa4c474 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/SeverityLevel.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/SeverityLevel.ts @@ -25,4 +25,4 @@ export const SeverityLevel = createEnumStyle({ Critical: eSeverityLevel.Critical }); -export type SeverityLevel = number | eSeverityLevel; +export type SeverityLevel = number | eSeverityLevel; \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Interfaces/ICorrelationConfig.ts b/shared/AppInsightsCommon/src/Interfaces/ICorrelationConfig.ts index c0be0ed45..1f1de850c 100644 --- a/shared/AppInsightsCommon/src/Interfaces/ICorrelationConfig.ts +++ b/shared/AppInsightsCommon/src/Interfaces/ICorrelationConfig.ts @@ -97,4 +97,4 @@ export interface ICorrelationConfig { * should not be excluded. */ addIntEndpoints?: boolean; -} +} \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Interfaces/IPageViewPerformanceTelemetry.ts b/shared/AppInsightsCommon/src/Interfaces/IPageViewPerformanceTelemetry.ts index e90738873..044b3d908 100644 --- a/shared/AppInsightsCommon/src/Interfaces/IPageViewPerformanceTelemetry.ts +++ b/shared/AppInsightsCommon/src/Interfaces/IPageViewPerformanceTelemetry.ts @@ -58,4 +58,4 @@ export interface IPageViewPerformanceTelemetryInternal extends IPageViewPerforma * Duration in miliseconds */ durationMs?: number; -} +} \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Interfaces/IPropertiesPlugin.ts b/shared/AppInsightsCommon/src/Interfaces/IPropertiesPlugin.ts index bd1aade29..f539abf52 100644 --- a/shared/AppInsightsCommon/src/Interfaces/IPropertiesPlugin.ts +++ b/shared/AppInsightsCommon/src/Interfaces/IPropertiesPlugin.ts @@ -5,4 +5,4 @@ import { ITelemetryContext } from "./ITelemetryContext"; export interface IPropertiesPlugin { readonly context: ITelemetryContext; -} +} \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Interfaces/IStorageBuffer.ts b/shared/AppInsightsCommon/src/Interfaces/IStorageBuffer.ts index 5e575a922..c65cb1e85 100644 --- a/shared/AppInsightsCommon/src/Interfaces/IStorageBuffer.ts +++ b/shared/AppInsightsCommon/src/Interfaces/IStorageBuffer.ts @@ -16,4 +16,4 @@ export interface IStorageBuffer { * Sets the stored value for a given key */ setItem(logger: IDiagnosticLogger, name: string, data: string): boolean; -} +} \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Interfaces/PartAExtensions.ts b/shared/AppInsightsCommon/src/Interfaces/PartAExtensions.ts index 506a7a400..1aa523099 100644 --- a/shared/AppInsightsCommon/src/Interfaces/PartAExtensions.ts +++ b/shared/AppInsightsCommon/src/Interfaces/PartAExtensions.ts @@ -11,4 +11,4 @@ export const Extensions = { SDKExt: "sdk" }; -export let CtxTagKeys = new ContextTagKeys(); +export let CtxTagKeys = new ContextTagKeys(); \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Interfaces/Telemetry/IEnvelope.ts b/shared/AppInsightsCommon/src/Interfaces/Telemetry/IEnvelope.ts index 28e0e3c20..ef58264b3 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Telemetry/IEnvelope.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Telemetry/IEnvelope.ts @@ -44,4 +44,4 @@ export interface IEnvelope extends ISerializable { * Telemetry data item. */ data: any; -} +} \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/Interfaces/Telemetry/ISerializable.ts b/shared/AppInsightsCommon/src/Interfaces/Telemetry/ISerializable.ts index 94420c19d..71db06e0c 100644 --- a/shared/AppInsightsCommon/src/Interfaces/Telemetry/ISerializable.ts +++ b/shared/AppInsightsCommon/src/Interfaces/Telemetry/ISerializable.ts @@ -8,4 +8,4 @@ export interface ISerializable { * for each field defines whether the field is required or not. */ aiDataContract: any; -} +} \ No newline at end of file diff --git a/shared/AppInsightsCommon/src/RequestResponseHeaders.ts b/shared/AppInsightsCommon/src/RequestResponseHeaders.ts index 78ceda3fa..f191186dc 100644 --- a/shared/AppInsightsCommon/src/RequestResponseHeaders.ts +++ b/shared/AppInsightsCommon/src/RequestResponseHeaders.ts @@ -92,4 +92,4 @@ export const RequestHeaders = createValueMap Date: Wed, 21 May 2025 16:31:50 +0000 Subject: [PATCH 05/22] Refactor storage helper functions to use single return statements per feedback Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- .../src/ConnectionStringParser.js | 42 + shared/AppInsightsCommon/src/Constants.js | 20 + .../AppInsightsCommon/src/DomHelperFuncs.js | 20 + shared/AppInsightsCommon/src/Enums.js | 28 + shared/AppInsightsCommon/src/HelperFuncs.js | 50 ++ .../src/Interfaces/ConnectionString.js | 2 + .../src/Interfaces/Context/IApplication.js | 4 + .../src/Interfaces/Context/IDevice.js | 4 + .../src/Interfaces/Context/IInternal.js | 4 + .../src/Interfaces/Context/ILocation.js | 4 + .../Interfaces/Context/IOperatingSystem.js | 4 + .../src/Interfaces/Context/ISample.js | 4 + .../src/Interfaces/Context/ISession.js | 4 + .../src/Interfaces/Context/ISessionManager.js | 4 + .../src/Interfaces/Context/ITelemetryTrace.js | 4 + .../src/Interfaces/Context/IUser.js | 4 + .../src/Interfaces/Context/IWeb.js | 4 + .../Interfaces/Contracts/AvailabilityData.js | 47 ++ .../Interfaces/Contracts/ContextTagKeys.js | 101 +++ .../src/Interfaces/Contracts/DataPointType.js | 4 + .../Interfaces/Contracts/DependencyKind.js | 4 + .../Contracts/DependencySourceType.js | 4 + .../src/Interfaces/Contracts/IBase.js | 4 + .../src/Interfaces/Contracts/IData.js | 4 + .../src/Interfaces/Contracts/IDataPoint.js | 2 + .../src/Interfaces/Contracts/IDomain.js | 4 + .../src/Interfaces/Contracts/IEnvelope.js | 41 + .../src/Interfaces/Contracts/IEventData.js | 4 + .../Interfaces/Contracts/IExceptionData.js | 4 + .../Interfaces/Contracts/IExceptionDetails.js | 4 + .../src/Interfaces/Contracts/IMessageData.js | 4 + .../src/Interfaces/Contracts/IMetricData.js | 4 + .../src/Interfaces/Contracts/IPageViewData.js | 4 + .../Interfaces/Contracts/IPageViewPerfData.js | 4 + .../Contracts/IRemoteDependencyData.js | 4 + .../src/Interfaces/Contracts/IStackFrame.js | 4 + .../src/Interfaces/Contracts/RequestData.js | 41 + .../src/Interfaces/Contracts/SeverityLevel.js | 16 + .../src/Interfaces/IAppInsights.js | 4 + .../src/Interfaces/IConfig.js | 23 + .../src/Interfaces/ICorrelationConfig.js | 4 + .../src/Interfaces/IDependencyTelemetry.js | 4 + .../src/Interfaces/IEventTelemetry.js | 2 + .../src/Interfaces/IExceptionTelemetry.js | 4 + .../src/Interfaces/IMetricTelemetry.js | 2 + .../IPageViewPerformanceTelemetry.js | 2 + .../src/Interfaces/IPageViewTelemetry.js | 2 + .../src/Interfaces/IPartC.js | 4 + .../src/Interfaces/IPropertiesPlugin.js | 4 + .../src/Interfaces/IRequestContext.js | 2 + .../src/Interfaces/IStorageBuffer.js | 2 + .../src/Interfaces/ITelemetryContext.js | 4 + .../src/Interfaces/IThrottleMgr.js | 2 + .../src/Interfaces/ITraceTelemetry.js | 4 + .../src/Interfaces/PartAExtensions.js | 15 + .../src/Interfaces/Telemetry/IEnvelope.js | 4 + .../src/Interfaces/Telemetry/ISerializable.js | 4 + shared/AppInsightsCommon/src/Offline.js | 135 +++ .../src/RequestResponseHeaders.js | 17 + .../src/StorageHelperFuncs.js | 249 ++++++ .../src/StorageHelperFuncs.ts | 90 +- .../src/Telemetry/Common/Data.js | 23 + .../src/Telemetry/Common/DataPoint.js | 27 + .../src/Telemetry/Common/DataSanitizer.js | 133 +++ .../src/Telemetry/Common/Envelope.js | 35 + .../AppInsightsCommon/src/Telemetry/Event.js | 29 + .../src/Telemetry/Exception.js | 767 ++++++++++++++++++ .../AppInsightsCommon/src/Telemetry/Metric.js | 36 + .../src/Telemetry/PageView.js | 38 + .../src/Telemetry/PageViewPerformance.js | 45 + .../src/Telemetry/RemoteDependencyData.js | 59 ++ .../AppInsightsCommon/src/Telemetry/Trace.js | 33 + .../src/TelemetryItemCreator.js | 64 ++ shared/AppInsightsCommon/src/ThrottleMgr.js | 385 +++++++++ .../AppInsightsCommon/src/UrlHelperFuncs.js | 92 +++ shared/AppInsightsCommon/src/Util.js | 204 +++++ .../src/applicationinsights-common.js | 120 +++ 77 files changed, 3142 insertions(+), 45 deletions(-) create mode 100644 shared/AppInsightsCommon/src/ConnectionStringParser.js create mode 100644 shared/AppInsightsCommon/src/Constants.js create mode 100644 shared/AppInsightsCommon/src/DomHelperFuncs.js create mode 100644 shared/AppInsightsCommon/src/Enums.js create mode 100644 shared/AppInsightsCommon/src/HelperFuncs.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/ConnectionString.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/IApplication.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/IDevice.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/IInternal.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/ILocation.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/IOperatingSystem.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/ISample.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/ISession.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/ISessionManager.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/ITelemetryTrace.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/IUser.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/IWeb.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/AvailabilityData.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/ContextTagKeys.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/DataPointType.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/DependencyKind.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/DependencySourceType.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IBase.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IData.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IDataPoint.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IDomain.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IEnvelope.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IEventData.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IExceptionData.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IExceptionDetails.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IMessageData.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IMetricData.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IPageViewData.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IPageViewPerfData.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IRemoteDependencyData.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IStackFrame.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/RequestData.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/SeverityLevel.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/IAppInsights.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/IConfig.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/ICorrelationConfig.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/IDependencyTelemetry.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/IEventTelemetry.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/IExceptionTelemetry.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/IMetricTelemetry.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/IPageViewPerformanceTelemetry.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/IPageViewTelemetry.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/IPartC.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/IPropertiesPlugin.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/IRequestContext.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/IStorageBuffer.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/ITelemetryContext.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/IThrottleMgr.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/ITraceTelemetry.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/PartAExtensions.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Telemetry/IEnvelope.js create mode 100644 shared/AppInsightsCommon/src/Interfaces/Telemetry/ISerializable.js create mode 100644 shared/AppInsightsCommon/src/Offline.js create mode 100644 shared/AppInsightsCommon/src/RequestResponseHeaders.js create mode 100644 shared/AppInsightsCommon/src/StorageHelperFuncs.js create mode 100644 shared/AppInsightsCommon/src/Telemetry/Common/Data.js create mode 100644 shared/AppInsightsCommon/src/Telemetry/Common/DataPoint.js create mode 100644 shared/AppInsightsCommon/src/Telemetry/Common/DataSanitizer.js create mode 100644 shared/AppInsightsCommon/src/Telemetry/Common/Envelope.js create mode 100644 shared/AppInsightsCommon/src/Telemetry/Event.js create mode 100644 shared/AppInsightsCommon/src/Telemetry/Exception.js create mode 100644 shared/AppInsightsCommon/src/Telemetry/Metric.js create mode 100644 shared/AppInsightsCommon/src/Telemetry/PageView.js create mode 100644 shared/AppInsightsCommon/src/Telemetry/PageViewPerformance.js create mode 100644 shared/AppInsightsCommon/src/Telemetry/RemoteDependencyData.js create mode 100644 shared/AppInsightsCommon/src/Telemetry/Trace.js create mode 100644 shared/AppInsightsCommon/src/TelemetryItemCreator.js create mode 100644 shared/AppInsightsCommon/src/ThrottleMgr.js create mode 100644 shared/AppInsightsCommon/src/UrlHelperFuncs.js create mode 100644 shared/AppInsightsCommon/src/Util.js create mode 100644 shared/AppInsightsCommon/src/applicationinsights-common.js diff --git a/shared/AppInsightsCommon/src/ConnectionStringParser.js b/shared/AppInsightsCommon/src/ConnectionStringParser.js new file mode 100644 index 000000000..ea30ee875 --- /dev/null +++ b/shared/AppInsightsCommon/src/ConnectionStringParser.js @@ -0,0 +1,42 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConnectionStringParser = void 0; +exports.parseConnectionString = parseConnectionString; +var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); +var Constants_1 = require("./Constants"); +var _FIELDS_SEPARATOR = ";"; +var _FIELD_KEY_VALUE_SEPARATOR = "="; +function parseConnectionString(connectionString) { + if (!connectionString) { + return {}; + } + var kvPairs = connectionString.split(_FIELDS_SEPARATOR); + var result = (0, applicationinsights_core_js_1.arrReduce)(kvPairs, function (fields, kv) { + var kvParts = kv.split(_FIELD_KEY_VALUE_SEPARATOR); + if (kvParts.length === 2) { // only save fields with valid formats + var key = kvParts[0].toLowerCase(); + var value = kvParts[1]; + fields[key] = value; + } + return fields; + }, {}); + if ((0, applicationinsights_core_js_1.objKeys)(result).length > 0) { + // this is a valid connection string, so parse the results + if (result.endpointsuffix) { + // apply the default endpoints + var locationPrefix = result.location ? result.location + "." : ""; + result.ingestionendpoint = result.ingestionendpoint || ("https://" + locationPrefix + "dc." + result.endpointsuffix); + } + // apply user override endpoint or the default endpoints + result.ingestionendpoint = result.ingestionendpoint || Constants_1.DEFAULT_BREEZE_ENDPOINT; + if ((0, applicationinsights_core_js_1.strEndsWith)(result.ingestionendpoint, "/")) { + result.ingestionendpoint = result.ingestionendpoint.slice(0, -1); + } + } + return result; +} +exports.ConnectionStringParser = { + parse: parseConnectionString +}; diff --git a/shared/AppInsightsCommon/src/Constants.js b/shared/AppInsightsCommon/src/Constants.js new file mode 100644 index 000000000..15c48ea28 --- /dev/null +++ b/shared/AppInsightsCommon/src/Constants.js @@ -0,0 +1,20 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.strIkey = exports.strNotSpecified = exports.DEFAULT_BREEZE_PATH = exports.DEFAULT_BREEZE_ENDPOINT = exports.HttpMethod = exports.ProcessLegacy = exports.SampleRate = exports.DisabledPropertyName = void 0; +/** + * This is an internal property used to cause internal (reporting) requests to be ignored from reporting + * additional telemetry, to handle polyfil implementations ALL urls used with a disabled request will + * also be ignored for future requests even when this property is not provided. + * Tagging as Ignore as this is an internal value and is not expected to be used outside of the SDK + * @ignore + */ +exports.DisabledPropertyName = "Microsoft_ApplicationInsights_BypassAjaxInstrumentation"; +exports.SampleRate = "sampleRate"; +exports.ProcessLegacy = "ProcessLegacy"; +exports.HttpMethod = "http.method"; +exports.DEFAULT_BREEZE_ENDPOINT = "https://dc.services.visualstudio.com"; +exports.DEFAULT_BREEZE_PATH = "/v2/track"; +exports.strNotSpecified = "not_specified"; +exports.strIkey = "iKey"; diff --git a/shared/AppInsightsCommon/src/DomHelperFuncs.js b/shared/AppInsightsCommon/src/DomHelperFuncs.js new file mode 100644 index 000000000..f3b24f2a0 --- /dev/null +++ b/shared/AppInsightsCommon/src/DomHelperFuncs.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createDomEvent = createDomEvent; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); +function createDomEvent(eventName) { + var event = null; + if ((0, applicationinsights_core_js_1.isFunction)(Event)) { // Use Event constructor when available + event = new Event(eventName); + } + else { // Event has no constructor in IE + var doc = (0, applicationinsights_core_js_1.getDocument)(); + if (doc && doc.createEvent) { + event = doc.createEvent("Event"); + event.initEvent(eventName, true, true); + } + } + return event; +} diff --git a/shared/AppInsightsCommon/src/Enums.js b/shared/AppInsightsCommon/src/Enums.js new file mode 100644 index 000000000..312b69173 --- /dev/null +++ b/shared/AppInsightsCommon/src/Enums.js @@ -0,0 +1,28 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EventPersistence = exports.DistributedTracingModes = exports.StorageType = void 0; +var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); +exports.StorageType = (0, applicationinsights_core_js_1.createEnumStyle)({ + LocalStorage: 0 /* eStorageType.LocalStorage */, + SessionStorage: 1 /* eStorageType.SessionStorage */ +}); +exports.DistributedTracingModes = (0, applicationinsights_core_js_1.createEnumStyle)({ + AI: 0 /* eDistributedTracingModes.AI */, + AI_AND_W3C: 1 /* eDistributedTracingModes.AI_AND_W3C */, + W3C: 2 /* eDistributedTracingModes.W3C */ +}); +/** + * The EventPersistence contains a set of values that specify the event's persistence. + */ +exports.EventPersistence = (0, applicationinsights_core_js_1.createEnumStyle)({ + /** + * Normal persistence. + */ + Normal: 1 /* EventPersistenceValue.Normal */, + /** + * Critical persistence. + */ + Critical: 2 /* EventPersistenceValue.Critical */ +}); diff --git a/shared/AppInsightsCommon/src/HelperFuncs.js b/shared/AppInsightsCommon/src/HelperFuncs.js new file mode 100644 index 000000000..787e4c068 --- /dev/null +++ b/shared/AppInsightsCommon/src/HelperFuncs.js @@ -0,0 +1,50 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.stringToBoolOrDefault = stringToBoolOrDefault; +exports.msToTimeSpan = msToTimeSpan; +exports.getExtensionByName = getExtensionByName; +exports.isCrossOriginError = isCrossOriginError; +var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); +var ts_utils_1 = require("@nevware21/ts-utils"); +var strEmpty = ""; +function stringToBoolOrDefault(str, defaultValue) { + if (defaultValue === void 0) { defaultValue = false; } + if (str === undefined || str === null) { + return defaultValue; + } + return str.toString().toLowerCase() === "true"; +} +/** + * Convert ms to c# time span format + */ +function msToTimeSpan(totalms) { + if (isNaN(totalms) || totalms < 0) { + totalms = 0; + } + totalms = (0, ts_utils_1.mathRound)(totalms); + var ms = strEmpty + totalms % 1000; + var sec = strEmpty + (0, ts_utils_1.mathFloor)(totalms / 1000) % 60; + var min = strEmpty + (0, ts_utils_1.mathFloor)(totalms / (1000 * 60)) % 60; + var hour = strEmpty + (0, ts_utils_1.mathFloor)(totalms / (1000 * 60 * 60)) % 24; + var days = (0, ts_utils_1.mathFloor)(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 + "." : strEmpty) + hour + ":" + min + ":" + sec + "." + ms; +} +function getExtensionByName(extensions, identifier) { + var extension = null; + (0, applicationinsights_core_js_1.arrForEach)(extensions, function (value) { + if (value.identifier === identifier) { + extension = value; + return -1; + } + }); + return extension; +} +function isCrossOriginError(message, url, lineNumber, columnNumber, error) { + return !error && (0, applicationinsights_core_js_1.isString)(message) && (message === "Script error." || message === "Script error"); +} diff --git a/shared/AppInsightsCommon/src/Interfaces/ConnectionString.js b/shared/AppInsightsCommon/src/Interfaces/ConnectionString.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/ConnectionString.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IApplication.js b/shared/AppInsightsCommon/src/Interfaces/Context/IApplication.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Context/IApplication.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IDevice.js b/shared/AppInsightsCommon/src/Interfaces/Context/IDevice.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Context/IDevice.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IInternal.js b/shared/AppInsightsCommon/src/Interfaces/Context/IInternal.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Context/IInternal.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/ILocation.js b/shared/AppInsightsCommon/src/Interfaces/Context/ILocation.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Context/ILocation.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IOperatingSystem.js b/shared/AppInsightsCommon/src/Interfaces/Context/IOperatingSystem.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Context/IOperatingSystem.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/ISample.js b/shared/AppInsightsCommon/src/Interfaces/Context/ISample.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Context/ISample.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/ISession.js b/shared/AppInsightsCommon/src/Interfaces/Context/ISession.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Context/ISession.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/ISessionManager.js b/shared/AppInsightsCommon/src/Interfaces/Context/ISessionManager.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Context/ISessionManager.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/ITelemetryTrace.js b/shared/AppInsightsCommon/src/Interfaces/Context/ITelemetryTrace.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Context/ITelemetryTrace.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IUser.js b/shared/AppInsightsCommon/src/Interfaces/Context/IUser.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Context/IUser.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IWeb.js b/shared/AppInsightsCommon/src/Interfaces/Context/IWeb.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Context/IWeb.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/AvailabilityData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/AvailabilityData.js new file mode 100644 index 000000000..49f67e643 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/AvailabilityData.js @@ -0,0 +1,47 @@ +"use strict"; +// // Copyright (c) Microsoft Corporation. All rights reserved. +// // Licensed under the MIT License. +// // THIS FILE WAS AUTOGENERATED +// import { Domain } from "./Domain"; +// "use strict"; +// /** +// * Instances of AvailabilityData represent the result of executing an availability test. +// */ +// export class AvailabilityData implements Domain { +// /** +// * Schema version +// */ +// public ver: number = 2; +// /** +// * Identifier of a test run. Use it to correlate steps of test run and telemetry generated by the service. +// */ +// public id: string; +// /** +// * Name of the test that these availability results represent. +// */ +// public name: string; +// /** +// * Duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. +// */ +// public duration: string; +// /** +// * Success flag. +// */ +// public success: boolean; +// /** +// * Name of the location where the test was run from. +// */ +// public runLocation: string; +// /** +// * Diagnostic message for the result. +// */ +// public message: string; +// /** +// * Collection of custom properties. +// */ +// public properties: any = {}; +// /** +// * Collection of custom measurements. +// */ +// public measurements: any = {}; +// } diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/ContextTagKeys.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/ContextTagKeys.js new file mode 100644 index 000000000..bf51992e7 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/ContextTagKeys.js @@ -0,0 +1,101 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ContextTagKeys = void 0; +var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); +function _aiNameFunc(baseName) { + var aiName = "ai." + baseName + "."; + return function (name) { + return aiName + name; + }; +} +var _aiApplication = _aiNameFunc("application"); +var _aiDevice = _aiNameFunc("device"); +var _aiLocation = _aiNameFunc("location"); +var _aiOperation = _aiNameFunc("operation"); +var _aiSession = _aiNameFunc("session"); +var _aiUser = _aiNameFunc("user"); +var _aiCloud = _aiNameFunc("cloud"); +var _aiInternal = _aiNameFunc("internal"); +var ContextTagKeys = /** @class */ (function (_super) { + __extends(ContextTagKeys, _super); + function ContextTagKeys() { + return _super.call(this) || this; + } + return ContextTagKeys; +}((0, applicationinsights_core_js_1.createClassFromInterface)({ + applicationVersion: _aiApplication("ver"), + applicationBuild: _aiApplication("build"), + applicationTypeId: _aiApplication("typeId"), + applicationId: _aiApplication("applicationId"), + applicationLayer: _aiApplication("layer"), + deviceId: _aiDevice("id"), + deviceIp: _aiDevice("ip"), + deviceLanguage: _aiDevice("language"), + deviceLocale: _aiDevice("locale"), + deviceModel: _aiDevice("model"), + deviceFriendlyName: _aiDevice("friendlyName"), + deviceNetwork: _aiDevice("network"), + deviceNetworkName: _aiDevice("networkName"), + deviceOEMName: _aiDevice("oemName"), + deviceOS: _aiDevice("os"), + deviceOSVersion: _aiDevice("osVersion"), + deviceRoleInstance: _aiDevice("roleInstance"), + deviceRoleName: _aiDevice("roleName"), + deviceScreenResolution: _aiDevice("screenResolution"), + deviceType: _aiDevice("type"), + deviceMachineName: _aiDevice("machineName"), + deviceVMName: _aiDevice("vmName"), + deviceBrowser: _aiDevice("browser"), + deviceBrowserVersion: _aiDevice("browserVersion"), + locationIp: _aiLocation("ip"), + locationCountry: _aiLocation("country"), + locationProvince: _aiLocation("province"), + locationCity: _aiLocation("city"), + operationId: _aiOperation("id"), + operationName: _aiOperation("name"), + operationParentId: _aiOperation("parentId"), + operationRootId: _aiOperation("rootId"), + operationSyntheticSource: _aiOperation("syntheticSource"), + operationCorrelationVector: _aiOperation("correlationVector"), + sessionId: _aiSession("id"), + sessionIsFirst: _aiSession("isFirst"), + sessionIsNew: _aiSession("isNew"), + userAccountAcquisitionDate: _aiUser("accountAcquisitionDate"), + userAccountId: _aiUser("accountId"), + userAgent: _aiUser("userAgent"), + userId: _aiUser("id"), + userStoreRegion: _aiUser("storeRegion"), + userAuthUserId: _aiUser("authUserId"), + userAnonymousUserAcquisitionDate: _aiUser("anonUserAcquisitionDate"), + userAuthenticatedUserAcquisitionDate: _aiUser("authUserAcquisitionDate"), + cloudName: _aiCloud("name"), + cloudRole: _aiCloud("role"), + cloudRoleVer: _aiCloud("roleVer"), + cloudRoleInstance: _aiCloud("roleInstance"), + cloudEnvironment: _aiCloud("environment"), + cloudLocation: _aiCloud("location"), + cloudDeploymentUnit: _aiCloud("deploymentUnit"), + internalNodeName: _aiInternal("nodeName"), + internalSdkVersion: _aiInternal("sdkVersion"), + internalAgentVersion: _aiInternal("agentVersion"), + internalSnippet: _aiInternal("snippet"), + internalSdkSrc: _aiInternal("sdkSrc") +}))); +exports.ContextTagKeys = ContextTagKeys; diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/DataPointType.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/DataPointType.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/DataPointType.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/DependencyKind.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/DependencyKind.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/DependencyKind.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/DependencySourceType.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/DependencySourceType.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/DependencySourceType.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IBase.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IBase.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/IBase.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IData.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/IData.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IDataPoint.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IDataPoint.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/IDataPoint.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IDomain.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IDomain.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/IDomain.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IEnvelope.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IEnvelope.js new file mode 100644 index 000000000..fabeadf18 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/IEnvelope.js @@ -0,0 +1,41 @@ +"use strict"; +// // Copyright (c) Microsoft Corporation. All rights reserved. +// // Licensed under the MIT License. +// import { IBase } from "./IBase"; +// /** +// * System variables for a telemetry item. +// */ +// export interface IEnvelope { +// /** +// * Envelope version. For internal use only. By assigning this the default, it will not be serialized within the payload unless changed to a value other than #1. +// */ +// ver: number; /* 1 */ +// /** +// * Type name of telemetry data item. +// */ +// name: string; +// /** +// * Event date time when telemetry item was created. This is the wall clock time on the client when the event was generated. There is no guarantee that the client's time is accurate. This field must be formatted in UTC ISO 8601 format, with a trailing 'Z' character, as described publicly on https://en.wikipedia.org/wiki/ISO_8601#UTC. Note: the number of decimal seconds digits provided are variable (and unspecified). Consumers should handle this, i.e. managed code consumers should not use format 'O' for parsing as it specifies a fixed length. Example: 2009-06-15T13:45:30.0000000Z. +// */ +// time: string; +// /** +// * Sampling rate used in application. This telemetry item represents 1 / sampleRate actual telemetry items. +// */ +// sampleRate: number; /* 100.0 */ +// /** +// * Sequence field used to track absolute order of uploaded events. +// */ +// seq: string; +// /** +// * The application's instrumentation key. The key is typically represented as a GUID, but there are cases when it is not a guid. No code should rely on iKey being a GUID. Instrumentation key is case insensitive. +// */ +// iKey: string; +// /** +// * Key/value collection of context properties. See ContextTagKeys for information on available properties. +// */ +// tags: any; /* {} */ +// /** +// * Telemetry data item. +// */ +// data: IBase; +// } diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IEventData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IEventData.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/IEventData.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IExceptionData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IExceptionData.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/IExceptionData.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IExceptionDetails.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IExceptionDetails.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/IExceptionDetails.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IMessageData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IMessageData.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/IMessageData.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IMetricData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IMetricData.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/IMetricData.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IPageViewData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IPageViewData.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/IPageViewData.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IPageViewPerfData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IPageViewPerfData.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/IPageViewPerfData.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IRemoteDependencyData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IRemoteDependencyData.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/IRemoteDependencyData.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IStackFrame.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IStackFrame.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/IStackFrame.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/RequestData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/RequestData.js new file mode 100644 index 000000000..c55d93431 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/RequestData.js @@ -0,0 +1,41 @@ +"use strict"; +// // Copyright (c) Microsoft Corporation. All rights reserved. +// // Licensed under the MIT License. +// import { IDomain } from "./IDomain"; +// /** +// * An instance of Request represents completion of an external request to the application to do work and contains a summary of that request execution and the results. +// */ +// export class RequestData implements IDomain { +// /** +// * Schema version +// */ +// public ver: number = 2; +// /** +// * Identifier of a request call instance. Used for correlation between request and other telemetry items. +// */ +// public id: string; +// /** +// * Source of the request. Examples are the instrumentation key of the caller or the ip address of the caller. +// */ +// public source: string; +// /** +// * Name of the request. Represents code path taken to process request. Low cardinality value to allow better grouping of requests. For HTTP requests it represents the HTTP method and URL path template like 'GET /values/{id}'. +// */ +// public name: string; +// /** +// * Indication of successful or unsuccessful call. +// */ +// public success: boolean; +// /** +// * Request URL with all query string parameters. +// */ +// public url: string; +// /** +// * Collection of custom properties. +// */ +// public properties: any = {}; +// /** +// * Collection of custom measurements. +// */ +// public measurements: any = {}; +// } diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/SeverityLevel.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/SeverityLevel.js new file mode 100644 index 000000000..8dc647530 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Contracts/SeverityLevel.js @@ -0,0 +1,16 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SeverityLevel = void 0; +var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); +/** + * Defines the level of severity for the event. + */ +exports.SeverityLevel = (0, applicationinsights_core_js_1.createEnumStyle)({ + Verbose: 0 /* eSeverityLevel.Verbose */, + Information: 1 /* eSeverityLevel.Information */, + Warning: 2 /* eSeverityLevel.Warning */, + Error: 3 /* eSeverityLevel.Error */, + Critical: 4 /* eSeverityLevel.Critical */ +}); diff --git a/shared/AppInsightsCommon/src/Interfaces/IAppInsights.js b/shared/AppInsightsCommon/src/Interfaces/IAppInsights.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/IAppInsights.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IConfig.js b/shared/AppInsightsCommon/src/Interfaces/IConfig.js new file mode 100644 index 000000000..40b392795 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/IConfig.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConfigurationManager = void 0; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); +var ConfigurationManager = /** @class */ (function () { + function ConfigurationManager() { + } + ConfigurationManager.getConfig = function (config, field, identifier, defaultValue) { + if (defaultValue === void 0) { defaultValue = false; } + var configValue; + if (identifier && config.extensionConfig && config.extensionConfig[identifier] && !(0, applicationinsights_core_js_1.isNullOrUndefined)(config.extensionConfig[identifier][field])) { + configValue = config.extensionConfig[identifier][field]; + } + else { + configValue = config[field]; + } + return !(0, applicationinsights_core_js_1.isNullOrUndefined)(configValue) ? configValue : defaultValue; + }; + return ConfigurationManager; +}()); +exports.ConfigurationManager = ConfigurationManager; diff --git a/shared/AppInsightsCommon/src/Interfaces/ICorrelationConfig.js b/shared/AppInsightsCommon/src/Interfaces/ICorrelationConfig.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/ICorrelationConfig.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IDependencyTelemetry.js b/shared/AppInsightsCommon/src/Interfaces/IDependencyTelemetry.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/IDependencyTelemetry.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IEventTelemetry.js b/shared/AppInsightsCommon/src/Interfaces/IEventTelemetry.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/IEventTelemetry.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IExceptionTelemetry.js b/shared/AppInsightsCommon/src/Interfaces/IExceptionTelemetry.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/IExceptionTelemetry.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IMetricTelemetry.js b/shared/AppInsightsCommon/src/Interfaces/IMetricTelemetry.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/IMetricTelemetry.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IPageViewPerformanceTelemetry.js b/shared/AppInsightsCommon/src/Interfaces/IPageViewPerformanceTelemetry.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/IPageViewPerformanceTelemetry.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IPageViewTelemetry.js b/shared/AppInsightsCommon/src/Interfaces/IPageViewTelemetry.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/IPageViewTelemetry.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IPartC.js b/shared/AppInsightsCommon/src/Interfaces/IPartC.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/IPartC.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IPropertiesPlugin.js b/shared/AppInsightsCommon/src/Interfaces/IPropertiesPlugin.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/IPropertiesPlugin.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IRequestContext.js b/shared/AppInsightsCommon/src/Interfaces/IRequestContext.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/IRequestContext.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IStorageBuffer.js b/shared/AppInsightsCommon/src/Interfaces/IStorageBuffer.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/IStorageBuffer.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/ITelemetryContext.js b/shared/AppInsightsCommon/src/Interfaces/ITelemetryContext.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/ITelemetryContext.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IThrottleMgr.js b/shared/AppInsightsCommon/src/Interfaces/IThrottleMgr.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/IThrottleMgr.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/ITraceTelemetry.js b/shared/AppInsightsCommon/src/Interfaces/ITraceTelemetry.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/ITraceTelemetry.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/PartAExtensions.js b/shared/AppInsightsCommon/src/Interfaces/PartAExtensions.js new file mode 100644 index 000000000..001937f25 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/PartAExtensions.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CtxTagKeys = exports.Extensions = void 0; +var ContextTagKeys_1 = require("./Contracts/ContextTagKeys"); +exports.Extensions = { + UserExt: "user", + DeviceExt: "device", + TraceExt: "trace", + WebExt: "web", + AppExt: "app", + OSExt: "os", + SessionExt: "ses", + SDKExt: "sdk" +}; +exports.CtxTagKeys = new ContextTagKeys_1.ContextTagKeys(); diff --git a/shared/AppInsightsCommon/src/Interfaces/Telemetry/IEnvelope.js b/shared/AppInsightsCommon/src/Interfaces/Telemetry/IEnvelope.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Telemetry/IEnvelope.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Telemetry/ISerializable.js b/shared/AppInsightsCommon/src/Interfaces/Telemetry/ISerializable.js new file mode 100644 index 000000000..ea6e29471 --- /dev/null +++ b/shared/AppInsightsCommon/src/Interfaces/Telemetry/ISerializable.js @@ -0,0 +1,4 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Offline.js b/shared/AppInsightsCommon/src/Offline.js new file mode 100644 index 000000000..5ecb17f98 --- /dev/null +++ b/shared/AppInsightsCommon/src/Offline.js @@ -0,0 +1,135 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createOfflineListener = createOfflineListener; +var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); +function _disableEvents(target, evtNamespace) { + (0, applicationinsights_core_js_1.eventOff)(target, null, null, evtNamespace); +} +/** + * Create a new OfflineListener instance to monitor browser online / offline events + * @param parentEvtNamespace - The parent event namespace to append to any specific events for this instance + */ +function createOfflineListener(parentEvtNamespace) { + var _document = (0, applicationinsights_core_js_1.getDocument)(); + var _navigator = (0, applicationinsights_core_js_1.getNavigator)(); // Gets the window.navigator or workerNavigator depending on the global + var _isListening = false; + var listenerList = []; + // Set the initial state + // rState is changed by the browser, both via events and when we check the navigator.onLine property + var rState = 1 /* eOfflineValue.Online */; + if (_navigator && !(0, applicationinsights_core_js_1.isNullOrUndefined)(_navigator.onLine) && !_navigator.onLine) { // navigator.onLine is undefined in react-native + rState = 2 /* eOfflineValue.Offline */; + } + // ustate is changed by the user calling setOnlineState + var uState = 0 /* eOfflineValue.Unknown */; + // current state would be updated each time rState or uState is changed + // it is a resolved value of rState and uState + var _currentState = calCurrentState(); + var _evtNamespace = (0, applicationinsights_core_js_1.mergeEvtNamespace)((0, applicationinsights_core_js_1.createUniqueNamespace)("OfflineListener"), parentEvtNamespace); + try { + if (_enableEvents((0, applicationinsights_core_js_1.getWindow)())) { + _isListening = true; + } + if (_document) { + // Also attach to the document.body or document + var target = _document.body || _document; + if (target.ononline) { + if (_enableEvents(target)) { + _isListening = true; + } + } + } + } + catch (e) { + // this makes react-native less angry + _isListening = false; + } + function _enableEvents(target) { + var enabled = false; + if (target) { + enabled = (0, applicationinsights_core_js_1.eventOn)(target, "online", _setOnline, _evtNamespace); + if (enabled) { + (0, applicationinsights_core_js_1.eventOn)(target, "offline", _setOffline, _evtNamespace); + } + } + return enabled; + } + function _isOnline() { + return _currentState; + } + function calCurrentState() { + if (uState === 2 /* eOfflineValue.Offline */ || rState === 2 /* eOfflineValue.Offline */) { + return false; + } + return true; // if both unknown, then we assume the network is good + } + function listnerNoticeCheck() { + // we were offline and are now online or we were online and now offline + var newState = calCurrentState(); + if (_currentState !== newState) { + _currentState = newState; // use the resolved state to update + // send all the callbacks with the current state + (0, applicationinsights_core_js_1.arrForEach)(listenerList, function (callback) { + var offlineState = { + isOnline: _currentState, + rState: rState, + uState: uState + }; + try { + callback(offlineState); + } + catch (e) { + // Do nothing, just making sure we run all of the callbacks + } + }); + } + } + function setOnlineState(newState) { + uState = newState; + listnerNoticeCheck(); + } + function _setOnline() { + rState = 1 /* eOfflineValue.Online */; + listnerNoticeCheck(); + } + function _setOffline() { + rState = 2 /* eOfflineValue.Offline */; + listnerNoticeCheck(); + } + function _unload() { + var win = (0, applicationinsights_core_js_1.getWindow)(); + if (win && _isListening) { + _disableEvents(win, _evtNamespace); + if (_document) { + // Also attach to the document.body or document + var target = _document.body || _document; + if (!(0, applicationinsights_core_js_1.isUndefined)(target.ononline)) { + _disableEvents(target, _evtNamespace); + } + } + _isListening = false; + } + } + function addListener(callback) { + listenerList.push(callback); + // Define rm as an instance of IUnloadHook + return { + rm: function () { + var index = listenerList.indexOf(callback); + if (index > -1) { + return listenerList.splice(index, 1); + } + else { + return; + } + } + }; + } + return { + isOnline: _isOnline, + isListening: function () { return _isListening; }, + unload: _unload, + addListener: addListener, + setOnlineState: setOnlineState + }; +} diff --git a/shared/AppInsightsCommon/src/RequestResponseHeaders.js b/shared/AppInsightsCommon/src/RequestResponseHeaders.js new file mode 100644 index 000000000..af3e1a6ed --- /dev/null +++ b/shared/AppInsightsCommon/src/RequestResponseHeaders.js @@ -0,0 +1,17 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RequestHeaders = void 0; +var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); +exports.RequestHeaders = (0, applicationinsights_core_js_1.createValueMap)({ + requestContextHeader: [0 /* eRequestHeaders.requestContextHeader */, "Request-Context"], + requestContextTargetKey: [1 /* eRequestHeaders.requestContextTargetKey */, "appId"], + requestContextAppIdFormat: [2 /* eRequestHeaders.requestContextAppIdFormat */, "appId=cid-v1:"], + requestIdHeader: [3 /* eRequestHeaders.requestIdHeader */, "Request-Id"], + traceParentHeader: [4 /* eRequestHeaders.traceParentHeader */, "traceparent"], + traceStateHeader: [5 /* eRequestHeaders.traceStateHeader */, "tracestate"], // currently not used + sdkContextHeader: [6 /* eRequestHeaders.sdkContextHeader */, "Sdk-Context"], + sdkContextHeaderAppIdRequest: [7 /* eRequestHeaders.sdkContextHeaderAppIdRequest */, "appId"], + requestContextHeaderLowerCase: [8 /* eRequestHeaders.requestContextHeaderLowerCase */, "request-context"] +}); diff --git a/shared/AppInsightsCommon/src/StorageHelperFuncs.js b/shared/AppInsightsCommon/src/StorageHelperFuncs.js new file mode 100644 index 000000000..dab70bdec --- /dev/null +++ b/shared/AppInsightsCommon/src/StorageHelperFuncs.js @@ -0,0 +1,249 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.utlDisableStorage = utlDisableStorage; +exports.utlSetStoragePrefix = utlSetStoragePrefix; +exports.utlEnableStorage = utlEnableStorage; +exports.utlCanUseLocalStorage = utlCanUseLocalStorage; +exports.utlGetLocalStorage = utlGetLocalStorage; +exports.utlSetLocalStorage = utlSetLocalStorage; +exports.utlRemoveStorage = utlRemoveStorage; +exports.utlCanUseSessionStorage = utlCanUseSessionStorage; +exports.utlGetSessionStorageKeys = utlGetSessionStorageKeys; +exports.utlGetSessionStorage = utlGetSessionStorage; +exports.utlSetSessionStorage = utlSetSessionStorage; +exports.utlRemoveSessionStorage = utlRemoveSessionStorage; +var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); +var ts_utils_1 = require("@nevware21/ts-utils"); +var Enums_1 = require("./Enums"); +var _canUseLocalStorage = undefined; +var _canUseSessionStorage = undefined; +var _storagePrefix = ""; +/** + * Gets the localStorage object if available + * @returns {Storage} - Returns the storage object if available else returns null + */ +function _getLocalStorageObject() { + if (utlCanUseLocalStorage()) { + return _getVerifiedStorageObject(Enums_1.StorageType.LocalStorage); + } + return null; +} +/** + * Safely checks if storage object (localStorage or sessionStorage) is available and accessible + * This helps prevent SecurityError in some browsers (e.g., Safari) when cookies are blocked + * @param storageType - Type of storage + * @returns {boolean} Returns whether storage object is safely accessible + */ +function _canSafelyAccessStorage(storageType) { + var storageTypeName = storageType === Enums_1.StorageType.LocalStorage ? "localStorage" : "sessionStorage"; + var result = true; + try { + // First, check if window exists and get the global object once + var gbl = (0, applicationinsights_core_js_1.getGlobal)(); + if ((0, applicationinsights_core_js_1.isNullOrUndefined)(gbl)) { + result = false; + } + else { + // Try to indirectly check if the property exists and is accessible + // This avoids direct property access that might throw in Safari with "Block All Cookies" enabled + // Some browsers throw when accessing the property descriptors with getOwnPropertyDescriptor + // Others throw when directly accessing the storage objects + // This approach tries both methods safely + try { + // Method 1: Try using property descriptor - safer in Safari with cookies blocked + var descriptor = (0, ts_utils_1.objGetOwnPropertyDescriptor)(gbl, storageTypeName); + if (!descriptor || !descriptor.get) { + result = false; + } + } + catch (e) { + // If the above fails, attempt a direct access inside a try-catch + try { + var storage = gbl[storageTypeName]; + if (!storage) { + result = false; + } + } + catch (e) { + // If both approaches fail, storage cannot be safely accessed + result = false; + } + } + } + } + catch (e) { + result = false; + } + return result; +} +/** + * 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 + * @returns {Storage} Returns storage object verified that it is usable + */ +function _getVerifiedStorageObject(storageType) { + var result = null; + try { + // First check if we can safely access the storage object + if (_canSafelyAccessStorage(storageType)) { + var storageTypeName = storageType === Enums_1.StorageType.LocalStorage ? "localStorage" : "sessionStorage"; + // Now we can safely try to use the storage + try { + var uid = (new Date).toString(); + var storage = (0, applicationinsights_core_js_1.getGlobalInst)(storageTypeName); + var name_1 = _storagePrefix + uid; + storage.setItem(name_1, uid); + var fail = storage.getItem(name_1) !== uid; + storage.removeItem(name_1); + if (!fail) { + result = storage; + } + } + catch (exception) { + // Storage exists but can't be used (quota exceeded, etc.) + } + } + } + catch (exception) { + // Catch any unexpected errors + } + return result; +} +/** + * Gets the sessionStorage object if available + * @returns {Storage} - Returns the storage object if available else returns null + */ +function _getSessionStorageObject() { + if (utlCanUseSessionStorage()) { + return _getVerifiedStorageObject(Enums_1.StorageType.SessionStorage); + } + return null; +} +/** + * Disables the global SDK usage of local or session storage if available + */ +function utlDisableStorage() { + _canUseLocalStorage = false; + _canUseSessionStorage = false; +} +function utlSetStoragePrefix(storagePrefix) { + _storagePrefix = storagePrefix || ""; +} +/** + * Re-enables the global SDK usage of local or session storage if available + */ +function utlEnableStorage() { + _canUseLocalStorage = utlCanUseLocalStorage(true); + _canUseSessionStorage = utlCanUseSessionStorage(true); +} +/** + * Returns whether LocalStorage can be used, if the reset parameter is passed a true this will override + * any previous disable calls. + * @param reset - Should the usage be reset and determined only based on whether LocalStorage is available + */ +function utlCanUseLocalStorage(reset) { + if (reset || _canUseLocalStorage === undefined) { + _canUseLocalStorage = !!_getVerifiedStorageObject(Enums_1.StorageType.LocalStorage); + } + return _canUseLocalStorage; +} +function utlGetLocalStorage(logger, name) { + var storage = _getLocalStorageObject(); + if (storage !== null) { + try { + return storage.getItem(name); + } + catch (e) { + _canUseLocalStorage = false; + (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.BrowserCannotReadLocalStorage, "Browser failed read of local storage. " + (0, applicationinsights_core_js_1.getExceptionName)(e), { exception: (0, applicationinsights_core_js_1.dumpObj)(e) }); + } + } + return null; +} +function utlSetLocalStorage(logger, name, data) { + var storage = _getLocalStorageObject(); + if (storage !== null) { + try { + storage.setItem(name, data); + return true; + } + catch (e) { + _canUseLocalStorage = false; + (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.BrowserCannotWriteLocalStorage, "Browser failed write to local storage. " + (0, applicationinsights_core_js_1.getExceptionName)(e), { exception: (0, applicationinsights_core_js_1.dumpObj)(e) }); + } + } + return false; +} +function utlRemoveStorage(logger, name) { + var storage = _getLocalStorageObject(); + if (storage !== null) { + try { + storage.removeItem(name); + return true; + } + catch (e) { + _canUseLocalStorage = false; + (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.BrowserFailedRemovalFromLocalStorage, "Browser failed removal of local storage item. " + (0, applicationinsights_core_js_1.getExceptionName)(e), { exception: (0, applicationinsights_core_js_1.dumpObj)(e) }); + } + } + return false; +} +function utlCanUseSessionStorage(reset) { + if (reset || _canUseSessionStorage === undefined) { + _canUseSessionStorage = !!_getVerifiedStorageObject(Enums_1.StorageType.SessionStorage); + } + return _canUseSessionStorage; +} +function utlGetSessionStorageKeys() { + var keys = []; + if (utlCanUseSessionStorage()) { + (0, applicationinsights_core_js_1.objForEachKey)((0, applicationinsights_core_js_1.getGlobalInst)("sessionStorage"), function (key) { + keys.push(key); + }); + } + return keys; +} +function utlGetSessionStorage(logger, name) { + var storage = _getSessionStorageObject(); + if (storage !== null) { + try { + return storage.getItem(name); + } + catch (e) { + _canUseSessionStorage = false; + (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.BrowserCannotReadSessionStorage, "Browser failed read of session storage. " + (0, applicationinsights_core_js_1.getExceptionName)(e), { exception: (0, applicationinsights_core_js_1.dumpObj)(e) }); + } + } + return null; +} +function utlSetSessionStorage(logger, name, data) { + var storage = _getSessionStorageObject(); + if (storage !== null) { + try { + storage.setItem(name, data); + return true; + } + catch (e) { + _canUseSessionStorage = false; + (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.BrowserCannotWriteSessionStorage, "Browser failed write to session storage. " + (0, applicationinsights_core_js_1.getExceptionName)(e), { exception: (0, applicationinsights_core_js_1.dumpObj)(e) }); + } + } + return false; +} +function utlRemoveSessionStorage(logger, name) { + var storage = _getSessionStorageObject(); + if (storage !== null) { + try { + storage.removeItem(name); + return true; + } + catch (e) { + _canUseSessionStorage = false; + (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.BrowserFailedRemovalFromSessionStorage, "Browser failed removal of session storage item. " + (0, applicationinsights_core_js_1.getExceptionName)(e), { exception: (0, applicationinsights_core_js_1.dumpObj)(e) }); + } + } + return false; +} diff --git a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts index 6f9f6904a..faa5723db 100644 --- a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts +++ b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts @@ -32,43 +32,44 @@ function _getLocalStorageObject(): Storage { */ function _canSafelyAccessStorage(storageType: StorageType): boolean { const storageTypeName = storageType === StorageType.LocalStorage ? "localStorage" : "sessionStorage"; + let result = true; try { // First, check if window exists and get the global object once const gbl: any = getGlobal(); if (isNullOrUndefined(gbl)) { - return false; - } - - // Try to indirectly check if the property exists and is accessible - // This avoids direct property access that might throw in Safari with "Block All Cookies" enabled - - // Some browsers throw when accessing the property descriptors with getOwnPropertyDescriptor - // Others throw when directly accessing the storage objects - // This approach tries both methods safely - try { - // Method 1: Try using property descriptor - safer in Safari with cookies blocked - const descriptor = objGetOwnPropertyDescriptor(gbl, storageTypeName); - if (!descriptor || !descriptor.get) { - return false; - } - } catch (e) { - // If the above fails, attempt a direct access inside a try-catch + result = false; + } else { + // Try to indirectly check if the property exists and is accessible + // This avoids direct property access that might throw in Safari with "Block All Cookies" enabled + + // Some browsers throw when accessing the property descriptors with getOwnPropertyDescriptor + // Others throw when directly accessing the storage objects + // This approach tries both methods safely try { - const storage = gbl[storageTypeName]; - if (!storage) { - return false; + // Method 1: Try using property descriptor - safer in Safari with cookies blocked + const descriptor = objGetOwnPropertyDescriptor(gbl, storageTypeName); + if (!descriptor || !descriptor.get) { + result = false; } } catch (e) { - // If both approaches fail, storage cannot be safely accessed - return false; + // If the above fails, attempt a direct access inside a try-catch + try { + const storage = gbl[storageTypeName]; + if (!storage) { + result = false; + } + } catch (e) { + // If both approaches fail, storage cannot be safely accessed + result = false; + } } } - - return true; } catch (e) { - return false; + result = false; } + + return result; } /** @@ -78,34 +79,33 @@ function _canSafelyAccessStorage(storageType: StorageType): boolean { * @returns {Storage} Returns storage object verified that it is usable */ function _getVerifiedStorageObject(storageType: StorageType): Storage { + let result = null; + try { // First check if we can safely access the storage object - if (!_canSafelyAccessStorage(storageType)) { - return null; - } - - const storageTypeName = storageType === StorageType.LocalStorage ? "localStorage" : "sessionStorage"; - - // Now we can safely try to use the storage - try { - let uid = (new Date).toString(); - let storage: Storage = getGlobalInst(storageTypeName); - let name:string = _storagePrefix + uid; - storage.setItem(name, uid); - let fail = storage.getItem(name) !== uid; - storage.removeItem(name); - if (!fail) { - return storage; + if (_canSafelyAccessStorage(storageType)) { + const storageTypeName = storageType === StorageType.LocalStorage ? "localStorage" : "sessionStorage"; + + // Now we can safely try to use the storage + try { + let uid = (new Date).toString(); + let storage: Storage = getGlobalInst(storageTypeName); + let name:string = _storagePrefix + uid; + storage.setItem(name, uid); + let fail = storage.getItem(name) !== uid; + storage.removeItem(name); + if (!fail) { + result = storage; + } + } catch (exception) { + // Storage exists but can't be used (quota exceeded, etc.) } - } catch (exception) { - // Storage exists but can't be used (quota exceeded, etc.) - return null; } } catch (exception) { // Catch any unexpected errors } - return null; + return result; } /** diff --git a/shared/AppInsightsCommon/src/Telemetry/Common/Data.js b/shared/AppInsightsCommon/src/Telemetry/Common/Data.js new file mode 100644 index 000000000..9465d2ced --- /dev/null +++ b/shared/AppInsightsCommon/src/Telemetry/Common/Data.js @@ -0,0 +1,23 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Data = void 0; +var Data = /** @class */ (function () { + /** + * Constructs a new instance of telemetry data. + */ + function Data(baseType, data) { + /** + * The data contract for serializing this object. + */ + this.aiDataContract = { + baseType: 1 /* FieldType.Required */, + baseData: 1 /* FieldType.Required */ + }; + this.baseType = baseType; + this.baseData = data; + } + return Data; +}()); +exports.Data = Data; diff --git a/shared/AppInsightsCommon/src/Telemetry/Common/DataPoint.js b/shared/AppInsightsCommon/src/Telemetry/Common/DataPoint.js new file mode 100644 index 000000000..67b0eaeee --- /dev/null +++ b/shared/AppInsightsCommon/src/Telemetry/Common/DataPoint.js @@ -0,0 +1,27 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DataPoint = void 0; +var DataPoint = /** @class */ (function () { + function DataPoint() { + /** + * The data contract for serializing this object. + */ + this.aiDataContract = { + name: 1 /* FieldType.Required */, + kind: 0 /* FieldType.Default */, + value: 1 /* FieldType.Required */, + count: 0 /* FieldType.Default */, + min: 0 /* FieldType.Default */, + max: 0 /* FieldType.Default */, + stdDev: 0 /* FieldType.Default */ + }; + /** + * Metric type. Single measurement or the aggregated value. + */ + this.kind = 0 /* DataPointType.Measurement */; + } + return DataPoint; +}()); +exports.DataPoint = DataPoint; diff --git a/shared/AppInsightsCommon/src/Telemetry/Common/DataSanitizer.js b/shared/AppInsightsCommon/src/Telemetry/Common/DataSanitizer.js new file mode 100644 index 000000000..9fbd92593 --- /dev/null +++ b/shared/AppInsightsCommon/src/Telemetry/Common/DataSanitizer.js @@ -0,0 +1,133 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.dataSanitizeKeyAndAddUniqueness = dataSanitizeKeyAndAddUniqueness; +exports.dataSanitizeKey = dataSanitizeKey; +exports.dataSanitizeString = dataSanitizeString; +exports.dataSanitizeUrl = dataSanitizeUrl; +exports.dataSanitizeMessage = dataSanitizeMessage; +exports.dataSanitizeException = dataSanitizeException; +exports.dataSanitizeProperties = dataSanitizeProperties; +exports.dataSanitizeMeasurements = dataSanitizeMeasurements; +exports.dataSanitizeId = dataSanitizeId; +exports.dataSanitizeInput = dataSanitizeInput; +exports.dsPadNumber = dsPadNumber; +var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); +var ts_utils_1 = require("@nevware21/ts-utils"); +function dataSanitizeKeyAndAddUniqueness(logger, key, map) { + var origLength = key.length; + var field = dataSanitizeKey(logger, key); + // validation truncated the length. We need to add uniqueness + if (field.length !== origLength) { + var i = 0; + var uniqueField = field; + while (map[uniqueField] !== undefined) { + i++; + uniqueField = (0, ts_utils_1.strSubstring)(field, 0, 150 /* DataSanitizerValues.MAX_NAME_LENGTH */ - 3) + dsPadNumber(i); + } + field = uniqueField; + } + return field; +} +function dataSanitizeKey(logger, name) { + var nameTrunc; + if (name) { + // Remove any leading or trailing whitespace + name = (0, applicationinsights_core_js_1.strTrim)((0, ts_utils_1.asString)(name)); + // truncate the string to 150 chars + if (name.length > 150 /* DataSanitizerValues.MAX_NAME_LENGTH */) { + nameTrunc = (0, ts_utils_1.strSubstring)(name, 0, 150 /* DataSanitizerValues.MAX_NAME_LENGTH */); + (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.NameTooLong, "name is too long. It has been truncated to " + 150 /* DataSanitizerValues.MAX_NAME_LENGTH */ + " characters.", { name: name }, true); + } + } + return nameTrunc || name; +} +function dataSanitizeString(logger, value, maxLength) { + if (maxLength === void 0) { maxLength = 1024 /* DataSanitizerValues.MAX_STRING_LENGTH */; } + var valueTrunc; + if (value) { + maxLength = maxLength ? maxLength : 1024 /* DataSanitizerValues.MAX_STRING_LENGTH */; // in case default parameters dont work + value = (0, applicationinsights_core_js_1.strTrim)((0, ts_utils_1.asString)(value)); + if (value.length > maxLength) { + valueTrunc = (0, ts_utils_1.strSubstring)(value, 0, maxLength); + (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.StringValueTooLong, "string value is too long. It has been truncated to " + maxLength + " characters.", { value: value }, true); + } + } + return valueTrunc || value; +} +function dataSanitizeUrl(logger, url) { + return dataSanitizeInput(logger, url, 2048 /* DataSanitizerValues.MAX_URL_LENGTH */, applicationinsights_core_js_1._eInternalMessageId.UrlTooLong); +} +function dataSanitizeMessage(logger, message) { + var messageTrunc; + if (message) { + if (message.length > 32768 /* DataSanitizerValues.MAX_MESSAGE_LENGTH */) { + messageTrunc = (0, ts_utils_1.strSubstring)(message, 0, 32768 /* DataSanitizerValues.MAX_MESSAGE_LENGTH */); + (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.MessageTruncated, "message is too long, it has been truncated to " + 32768 /* DataSanitizerValues.MAX_MESSAGE_LENGTH */ + " characters.", { message: message }, true); + } + } + return messageTrunc || message; +} +function dataSanitizeException(logger, exception) { + var exceptionTrunc; + if (exception) { + // Make surte its a string + var value = "" + exception; + if (value.length > 32768 /* DataSanitizerValues.MAX_EXCEPTION_LENGTH */) { + exceptionTrunc = (0, ts_utils_1.strSubstring)(value, 0, 32768 /* DataSanitizerValues.MAX_EXCEPTION_LENGTH */); + (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.ExceptionTruncated, "exception is too long, it has been truncated to " + 32768 /* DataSanitizerValues.MAX_EXCEPTION_LENGTH */ + " characters.", { exception: exception }, true); + } + } + return exceptionTrunc || exception; +} +function dataSanitizeProperties(logger, properties) { + if (properties) { + var tempProps_1 = {}; + (0, applicationinsights_core_js_1.objForEachKey)(properties, function (prop, value) { + if ((0, applicationinsights_core_js_1.isObject)(value) && (0, applicationinsights_core_js_1.hasJSON)()) { + // Stringify any part C properties + try { + value = (0, applicationinsights_core_js_1.getJSON)().stringify(value); + } + catch (e) { + (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.CannotSerializeObjectNonSerializable, "custom property is not valid", { exception: e }, true); + } + } + value = dataSanitizeString(logger, value, 8192 /* DataSanitizerValues.MAX_PROPERTY_LENGTH */); + prop = dataSanitizeKeyAndAddUniqueness(logger, prop, tempProps_1); + tempProps_1[prop] = value; + }); + properties = tempProps_1; + } + return properties; +} +function dataSanitizeMeasurements(logger, measurements) { + if (measurements) { + var tempMeasurements_1 = {}; + (0, applicationinsights_core_js_1.objForEachKey)(measurements, function (measure, value) { + measure = dataSanitizeKeyAndAddUniqueness(logger, measure, tempMeasurements_1); + tempMeasurements_1[measure] = value; + }); + measurements = tempMeasurements_1; + } + return measurements; +} +function dataSanitizeId(logger, id) { + return id ? dataSanitizeInput(logger, id, 128 /* DataSanitizerValues.MAX_ID_LENGTH */, applicationinsights_core_js_1._eInternalMessageId.IdTooLong).toString() : id; +} +function dataSanitizeInput(logger, input, maxLength, _msgId) { + var inputTrunc; + if (input) { + input = (0, applicationinsights_core_js_1.strTrim)((0, ts_utils_1.asString)(input)); + if (input.length > maxLength) { + inputTrunc = (0, ts_utils_1.strSubstring)(input, 0, maxLength); + (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, _msgId, "input is too long, it has been truncated to " + maxLength + " characters.", { data: input }, true); + } + } + return inputTrunc || input; +} +function dsPadNumber(num) { + var s = "00" + num; + return (0, ts_utils_1.strSubstr)(s, s.length - 3); +} diff --git a/shared/AppInsightsCommon/src/Telemetry/Common/Envelope.js b/shared/AppInsightsCommon/src/Telemetry/Common/Envelope.js new file mode 100644 index 000000000..dc9c667f4 --- /dev/null +++ b/shared/AppInsightsCommon/src/Telemetry/Common/Envelope.js @@ -0,0 +1,35 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Envelope = void 0; +var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); +var Constants_1 = require("../../Constants"); +var DataSanitizer_1 = require("./DataSanitizer"); +var Envelope = /** @class */ (function () { + /** + * Constructs a new instance of telemetry data. + */ + function Envelope(logger, data, name) { + var _this = this; + var _self = this; + _self.ver = 1; + _self.sampleRate = 100.0; + _self.tags = {}; + _self.name = (0, DataSanitizer_1.dataSanitizeString)(logger, name) || Constants_1.strNotSpecified; + _self.data = data; + _self.time = (0, applicationinsights_core_js_1.toISOString)(new Date()); + _self.aiDataContract = { + time: 1 /* FieldType.Required */, + iKey: 1 /* FieldType.Required */, + name: 1 /* FieldType.Required */, + sampleRate: function () { + return (_this.sampleRate === 100) ? 4 /* FieldType.Hidden */ : 1 /* FieldType.Required */; + }, + tags: 1 /* FieldType.Required */, + data: 1 /* FieldType.Required */ + }; + } + return Envelope; +}()); +exports.Envelope = Envelope; diff --git a/shared/AppInsightsCommon/src/Telemetry/Event.js b/shared/AppInsightsCommon/src/Telemetry/Event.js new file mode 100644 index 000000000..a39a7d891 --- /dev/null +++ b/shared/AppInsightsCommon/src/Telemetry/Event.js @@ -0,0 +1,29 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Event = void 0; +var Constants_1 = require("../Constants"); +var DataSanitizer_1 = require("./Common/DataSanitizer"); +var Event = /** @class */ (function () { + /** + * Constructs a new instance of the EventTelemetry object + */ + function Event(logger, name, properties, measurements) { + this.aiDataContract = { + ver: 1 /* FieldType.Required */, + name: 1 /* FieldType.Required */, + properties: 0 /* FieldType.Default */, + measurements: 0 /* FieldType.Default */ + }; + var _self = this; + _self.ver = 2; + _self.name = (0, DataSanitizer_1.dataSanitizeString)(logger, name) || Constants_1.strNotSpecified; + _self.properties = (0, DataSanitizer_1.dataSanitizeProperties)(logger, properties); + _self.measurements = (0, DataSanitizer_1.dataSanitizeMeasurements)(logger, measurements); + } + Event.envelopeType = "Microsoft.ApplicationInsights.{0}.Event"; + Event.dataType = "EventData"; + return Event; +}()); +exports.Event = Event; diff --git a/shared/AppInsightsCommon/src/Telemetry/Exception.js b/shared/AppInsightsCommon/src/Telemetry/Exception.js new file mode 100644 index 000000000..1b9d990d0 --- /dev/null +++ b/shared/AppInsightsCommon/src/Telemetry/Exception.js @@ -0,0 +1,767 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Exception = void 0; +exports._formatErrorCode = _formatErrorCode; +exports._createExceptionDetails = _createExceptionDetails; +exports._createExDetailsFromInterface = _createExDetailsFromInterface; +exports._extractStackFrame = _extractStackFrame; +exports._parsedFrameToInterface = _parsedFrameToInterface; +var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); +var ts_utils_1 = require("@nevware21/ts-utils"); +var Constants_1 = require("../Constants"); +var DataSanitizer_1 = require("./Common/DataSanitizer"); +// These Regex covers the following patterns +// 1. Chrome/Firefox/IE/Edge: +// at functionName (filename:lineNumber:columnNumber) +// at functionName (filename:lineNumber) +// at filename:lineNumber:columnNumber +// at filename:lineNumber +// at functionName@filename:lineNumber:columnNumber +// 2. Safari / Opera: +// functionName@filename:lineNumber:columnNumber +// functionName@filename:lineNumber +// filename:lineNumber:columnNumber +// filename:lineNumber +// Line ## of scriptname script filename:lineNumber:columnNumber +// Line ## of scriptname script filename +// 3. IE/Edge (Additional formats) +// at functionName@filename:lineNumber +var STACKFRAME_BASE_SIZE = 58; // '{"method":"","level":,"assembly":"","fileName":"","line":}'.length +/** + * Check if the string conforms to what looks like a stack frame line and not just a general message + * comment or other non-stack related info. + * + * This should be used to filter out any leading "message" lines from a stack trace, before attempting to parse + * the individual stack frames. Once you have estabilsted the start of the stack frames you can then use the + * FULL_STACK_FRAME_1, FULL_STACK_FRAME_2, FULL_STACK_FRAME_3, and EXTRACT_FILENAME to parse the individual + * stack frames to extract the method, filename, line number, and column number. + * These may still provide invalid matches, so the sequence of execution is important to avoid providing + * an invalid parsed stack. + */ +var IS_FRAME = /^\s{0,50}(from\s|at\s|Line\s{1,5}\d{1,10}\s{1,5}of|\w{1,50}@\w{1,80}|[^\(\s\n]+:[0-9\?]+(?::[0-9\?]+)?)/; +/** + * Parse a well formed stack frame with both the line and column numbers + * ---------------------------------- + * **Primary focus of the matching** + * - at functionName (filename:lineNumber:columnNumber) + * - at filename:lineNumber:columnNumber + * - at functionName@filename:lineNumber:columnNumber + * - functionName (filename:lineNumber:columnNumber) + * - filename:lineNumber:columnNumber + * - functionName@filename:lineNumber:columnNumber + */ +var FULL_STACK_FRAME_1 = /^(?:\s{0,50}at)?\s{0,50}([^\@\()\s]+)?\s{0,50}(?:\s|\@|\()\s{0,5}([^\(\s\n\]]+):([0-9\?]+):([0-9\?]+)\)?$/; +/** + * Parse a well formed stack frame with only a line number. + * ---------------------------------- + * > Note: this WILL also match with line and column number, but the line number is included with the filename + * > you should attempt to match with FULL_STACK_FRAME_1 first. + * + * **Primary focus of the matching (run FULL_STACK_FRAME_1 first)** + * - at functionName (filename:lineNumber) + * - at filename:lineNumber + * - at functionName@filename:lineNumber + * - functionName (filename:lineNumber) + * - filename:lineNumber + * - functionName@filename:lineNumber + * + * **Secondary matches** + * - at functionName (filename:lineNumber:columnNumber) + * - at filename:lineNumber:columnNumber + * - at functionName@filename:lineNumber:columnNumber + * - functionName (filename:lineNumber:columnNumber) + * - filename:lineNumber:columnNumber + * - functionName@filename:lineNumber:columnNumber + */ +var FULL_STACK_FRAME_2 = /^(?:\s{0,50}at)?\s{0,50}([^\@\()\s]+)?\s{0,50}(?:\s|\@|\()\s{0,5}([^\(\s\n\]]+):([0-9\?]+)\)?$/; +/** + * Attempt to Parse a frame that doesn't include a line or column number. + * ---------------------------------- + * > Note: this WILL also match lines with a line or line and column number, you should attempt to match with + * both FULL_STACK_FRAME_1 and FULL_STACK_FRAME_2 first to avoid false positives. + * + * **Unexpected Invalid Matches** (Matches that should be avoided -- by using the FULL_STACK_FRAME_1 and FULL_STACK_FRAME_2 first) + * - at https://localhost:44365/static/node_bundles/@microsoft/blah/js/bundle.js:144112:27 + * - at https://localhost:44365/static/node_bundles/@microsoft/blah/js/bundle.js:144112:27 + * + * **Primary focus of the matching (run FULL_STACK_FRAME_1 first)** + * - at functionName@filename + * - at functionName (filename) + * - at functionName filename + * - at filename <- Will actuall match this as the "method" and not the filename (care should be taken to avoid this) + * - functionName@filename + * - functionName (filename) + * - functionName filename + * - functionName + * + * **Secondary matches** (The line and column numbers will be included with the matched filename) + * - at functionName (filename:lineNumber:columnNumber) + * - at functionName (filename:lineNumber) + * - at filename:lineNumber:columnNumber + * - at filename:lineNumber + * - at functionName@filename:lineNumber:columnNumber + * - at functionName@filename:lineNumber + * - functionName (filename:lineNumber:columnNumber) + * - functionName (filename:lineNumber) + * - filename:lineNumber:columnNumber + * - filename:lineNumber + * - functionName@filename:lineNumber:columnNumber + * - functionName@filename:lineNumber + */ +var FULL_STACK_FRAME_3 = /^(?:\s{0,50}at)?\s{0,50}([^\@\()\s]+)?\s{0,50}(?:\s|\@|\()\s{0,5}([^\(\s\n\)\]]+)\)?$/; +/** + * Attempt to extract the filename (with or without line and column numbers) from a string. + * ---------------------------------- + * > Note: this will only match the filename (with any line or column numbers) and will + * > return what looks like the filename, however, it will also match random strings that + * > look like a filename, so care should be taken to ensure that the filename is actually + * > a filename before using it. + * > + * > It is recommended to use this in conjunction with the FULL_STACK_FRAME_1, FULL_STACK_FRAME_2, and FULL_STACK_FRAME_3 + * > to ensure first to reduce false matches, if all of these fail then you can use this to extract the filename from a random + * > strings to identify any potential filename from a known stack frame line. + * + * **Known Invalid matching** + * + * This regex will basically match any "final" string of a line or one that is trailed by a comma, so this should not + * be used as the "only" matching regex, but rather as a final fallback to extract the filename from a string. + * If you are certain that the string line is a stack frame and not part of the exception message (lines before the stack) + * or trailing comments, then you can use this to extract the filename and then further parse with PARSE_FILENAME_LINE_COL + * and PARSE_FILENAME_LINE_ONLY to extract any potential the line and column numbers. + * + * **Primary focus of the matching** + * - at (anonymous) @ VM60:1 + * - Line 21 of linked script file://localhost/C:/Temp/stacktrace.js + * - Line 11 of inline#1 script in http://localhost:3000/static/js/main.206f4846.js:2:296748 + * - Line 68 of inline#2 script in file://localhost/teststack.html + * - at Global code (http://example.com/stacktrace.js:11:1) + */ +var EXTRACT_FILENAME = /(?:^|\(|\s{0,10}[\w\)]+\@)?([^\(\n\s\]\)]+)(?:\:([0-9]+)(?:\:([0-9]+))?)?\)?(?:,|$)/; +/** + * Attempt to extract the filename, line number, and column number from a string. + */ +var PARSE_FILENAME_LINE_COL = /([^\(\s\n]+):([0-9]+):([0-9]+)$/; +/** + * Attempt to extract the filename and line number from a string. + */ +var PARSE_FILENAME_LINE_ONLY = /([^\(\s\n]+):([0-9]+)$/; +var NoMethod = ""; +var strError = "error"; +var strStack = "stack"; +var strStackDetails = "stackDetails"; +var strErrorSrc = "errorSrc"; +var strMessage = "message"; +var strDescription = "description"; +var _parseSequence = [ + { re: FULL_STACK_FRAME_1, len: 5, m: 1, fn: 2, ln: 3, col: 4 }, + { chk: _ignoreNative, pre: _scrubAnonymous, re: FULL_STACK_FRAME_2, len: 4, m: 1, fn: 2, ln: 3 }, + { re: FULL_STACK_FRAME_3, len: 3, m: 1, fn: 2, hdl: _handleFilename }, + { re: EXTRACT_FILENAME, len: 2, fn: 1, hdl: _handleFilename } +]; +function _scrubAnonymous(frame) { + return frame.replace(/(\(anonymous\))/, ""); +} +function _ignoreNative(frame) { + return (0, ts_utils_1.strIndexOf)(frame, "[native") < 0; +} +function _stringify(value, convertToString) { + var result = value; + if (result && !(0, applicationinsights_core_js_1.isString)(result)) { + if (JSON && JSON.stringify) { + result = JSON.stringify(value); + if (convertToString && (!result || result === "{}")) { + if ((0, applicationinsights_core_js_1.isFunction)(value.toString)) { + result = value.toString(); + } + else { + result = "" + value; + } + } + } + else { + result = "" + value + " - (Missing JSON.stringify)"; + } + } + return result || ""; +} +function _formatMessage(theEvent, errorType) { + var evtMessage = theEvent; + if (theEvent) { + if (evtMessage && !(0, applicationinsights_core_js_1.isString)(evtMessage)) { + evtMessage = theEvent[strMessage] || theEvent[strDescription] || evtMessage; + } + // Make sure the message is a string + if (evtMessage && !(0, applicationinsights_core_js_1.isString)(evtMessage)) { + // tslint:disable-next-line: prefer-conditional-expression + evtMessage = _stringify(evtMessage, true); + } + if (theEvent["filename"]) { + // Looks like an event object with filename + evtMessage = evtMessage + " @" + (theEvent["filename"] || "") + ":" + (theEvent["lineno"] || "?") + ":" + (theEvent["colno"] || "?"); + } + } + // Automatically add the error type to the message if it does already appear to be present + if (errorType && errorType !== "String" && errorType !== "Object" && errorType !== "Error" && (0, ts_utils_1.strIndexOf)(evtMessage || "", errorType) === -1) { + evtMessage = errorType + ": " + evtMessage; + } + return evtMessage || ""; +} +function _isExceptionDetailsInternal(value) { + try { + if ((0, applicationinsights_core_js_1.isObject)(value)) { + return "hasFullStack" in value && "typeName" in value; + } + } + catch (e) { + // This can happen with some native browser objects, but should not happen for the type we are checking for + } + return false; +} +function _isExceptionInternal(value) { + try { + if ((0, applicationinsights_core_js_1.isObject)(value)) { + return ("ver" in value && "exceptions" in value && "properties" in value); + } + } + catch (e) { + // This can happen with some native browser objects, but should not happen for the type we are checking for + } + return false; +} +function _isStackDetails(details) { + return details && details.src && (0, applicationinsights_core_js_1.isString)(details.src) && details.obj && (0, applicationinsights_core_js_1.isArray)(details.obj); +} +function _convertStackObj(errorStack) { + var src = errorStack || ""; + if (!(0, applicationinsights_core_js_1.isString)(src)) { + if ((0, applicationinsights_core_js_1.isString)(src[strStack])) { + src = src[strStack]; + } + else { + src = "" + src; + } + } + var items = src.split("\n"); + return { + src: src, + obj: items + }; +} +function _getOperaStack(errorMessage) { + var stack = []; + var lines = errorMessage.split("\n"); + for (var lp = 0; lp < lines.length; lp++) { + var entry = lines[lp]; + if (lines[lp + 1]) { + entry += "@" + lines[lp + 1]; + lp++; + } + stack.push(entry); + } + return { + src: errorMessage, + obj: stack + }; +} +function _getStackFromErrorObj(errorObj) { + var details = null; + if (errorObj) { + try { + /* Using bracket notation is support older browsers (IE 7/8 -- dont remember the version) that throw when using dot + notation for undefined objects and we don't want to loose the error from being reported */ + if (errorObj[strStack]) { + // Chrome/Firefox + details = _convertStackObj(errorObj[strStack]); + } + else if (errorObj[strError] && errorObj[strError][strStack]) { + // Edge error event provides the stack and error object + details = _convertStackObj(errorObj[strError][strStack]); + } + else if (errorObj["exception"] && errorObj.exception[strStack]) { + details = _convertStackObj(errorObj.exception[strStack]); + } + else if (_isStackDetails(errorObj)) { + details = errorObj; + } + else if (_isStackDetails(errorObj[strStackDetails])) { + details = errorObj[strStackDetails]; + } + else if ((0, ts_utils_1.getWindow)() && (0, ts_utils_1.getWindow)()["opera"] && errorObj[strMessage]) { + // Opera + details = _getOperaStack(errorObj.message); + } + else if (errorObj["reason"] && errorObj.reason[strStack]) { + // UnhandledPromiseRejection + details = _convertStackObj(errorObj.reason[strStack]); + } + else if ((0, applicationinsights_core_js_1.isString)(errorObj)) { + details = _convertStackObj(errorObj); + } + else { + var evtMessage = errorObj[strMessage] || errorObj[strDescription] || ""; + if ((0, applicationinsights_core_js_1.isString)(errorObj[strErrorSrc])) { + if (evtMessage) { + evtMessage += "\n"; + } + evtMessage += " from " + errorObj[strErrorSrc]; + } + if (evtMessage) { + details = _convertStackObj(evtMessage); + } + } + } + catch (e) { + // something unexpected happened so to avoid failing to report any error lets swallow the exception + // and fallback to the callee/caller method + details = _convertStackObj(e); + } + } + return details || { + src: "", + obj: null + }; +} +function _formatStackTrace(stackDetails) { + var stack = ""; + if (stackDetails) { + if (stackDetails.obj) { + stack = stackDetails.obj.join("\n"); + } + else { + stack = stackDetails.src || ""; + } + } + return stack; +} +function _parseStack(stack) { + var parsedStack; + var frames = stack.obj; + if (frames && frames.length > 0) { + parsedStack = []; + var level_1 = 0; + var foundStackStart_1 = false; + var totalSizeInBytes_1 = 0; + (0, applicationinsights_core_js_1.arrForEach)(frames, function (frame) { + if (foundStackStart_1 || _isStackFrame(frame)) { + var theFrame = (0, ts_utils_1.asString)(frame); + // Once we have found the first stack frame we treat the rest of the lines as part of the stack + foundStackStart_1 = true; + var parsedFrame = _extractStackFrame(theFrame, level_1); + if (parsedFrame) { + totalSizeInBytes_1 += parsedFrame.sizeInBytes; + parsedStack.push(parsedFrame); + level_1++; + } + } + }); + // DP Constraint - exception parsed stack must be < 32KB + // remove frames from the middle to meet the threshold + var exceptionParsedStackThreshold = 32 * 1024; + if (totalSizeInBytes_1 > exceptionParsedStackThreshold) { + var left = 0; + var right = parsedStack.length - 1; + var size = 0; + var acceptedLeft = left; + var acceptedRight = right; + while (left < right) { + // check size + var lSize = parsedStack[left].sizeInBytes; + var rSize = parsedStack[right].sizeInBytes; + size += lSize + rSize; + if (size > exceptionParsedStackThreshold) { + // remove extra frames from the middle + var howMany = acceptedRight - acceptedLeft + 1; + parsedStack.splice(acceptedLeft, howMany); + break; + } + // update pointers + acceptedLeft = left; + acceptedRight = right; + left++; + right--; + } + } + } + return parsedStack; +} +function _getErrorType(errorType) { + // Gets the Error Type by passing the constructor (used to get the true type of native error object). + var typeName = ""; + if (errorType) { + typeName = errorType.typeName || errorType.name || ""; + if (!typeName) { + try { + var funcNameRegex = /function (.{1,200})\(/; + var results = (funcNameRegex).exec((errorType).constructor.toString()); + typeName = (results && results.length > 1) ? results[1] : ""; + } + catch (e) { + // eslint-disable-next-line no-empty -- Ignoring any failures as nothing we can do + } + } + } + return typeName; +} +/** + * Formats the provided errorObj for display and reporting, it may be a String, Object, integer or undefined depending on the browser. + * @param errorObj - The supplied errorObj + */ +function _formatErrorCode(errorObj) { + if (errorObj) { + try { + if (!(0, applicationinsights_core_js_1.isString)(errorObj)) { + var errorType = _getErrorType(errorObj); + var result = _stringify(errorObj, false); + if (!result || result === "{}") { + if (errorObj[strError]) { + // Looks like an MS Error Event + errorObj = errorObj[strError]; + errorType = _getErrorType(errorObj); + } + result = _stringify(errorObj, true); + } + if ((0, ts_utils_1.strIndexOf)(result, errorType) !== 0 && errorType !== "String") { + return errorType + ":" + result; + } + return result; + } + } + catch (e) { + // eslint-disable-next-line no-empty -- Ignoring any failures as nothing we can do + } + } + // Fallback to just letting the object format itself into a string + return "" + (errorObj || ""); +} +var Exception = /** @class */ (function () { + /** + * Constructs a new instance of the ExceptionTelemetry object + */ + function Exception(logger, exception, properties, measurements, severityLevel, id) { + this.aiDataContract = { + ver: 1 /* FieldType.Required */, + exceptions: 1 /* FieldType.Required */, + severityLevel: 0 /* FieldType.Default */, + properties: 0 /* FieldType.Default */, + measurements: 0 /* FieldType.Default */ + }; + var _self = this; + _self.ver = 2; // TODO: handle the CS"4.0" ==> breeze 2 conversion in a better way + if (!_isExceptionInternal(exception)) { + if (!properties) { + properties = {}; + } + if (id) { + properties.id = id; + } + _self.exceptions = [_createExceptionDetails(logger, exception, properties)]; + _self.properties = (0, DataSanitizer_1.dataSanitizeProperties)(logger, properties); + _self.measurements = (0, DataSanitizer_1.dataSanitizeMeasurements)(logger, measurements); + if (severityLevel) { + _self.severityLevel = severityLevel; + } + if (id) { + _self.id = id; + } + } + else { + _self.exceptions = exception.exceptions || []; + _self.properties = exception.properties; + _self.measurements = exception.measurements; + if (exception.severityLevel) { + _self.severityLevel = exception.severityLevel; + } + if (exception.id) { + _self.id = exception.id; + exception.properties.id = exception.id; + } + if (exception.problemGroup) { + _self.problemGroup = exception.problemGroup; + } + // bool/int types, use isNullOrUndefined + if (!(0, applicationinsights_core_js_1.isNullOrUndefined)(exception.isManual)) { + _self.isManual = exception.isManual; + } + } + } + Exception.CreateAutoException = function (message, url, lineNumber, columnNumber, error, evt, stack, errorSrc) { + var errorType = _getErrorType(error || evt || message); + return { + message: _formatMessage(message, errorType), + url: url, + lineNumber: lineNumber, + columnNumber: columnNumber, + error: _formatErrorCode(error || evt || message), + evt: _formatErrorCode(evt || message), + typeName: errorType, + stackDetails: _getStackFromErrorObj(stack || error || evt), + errorSrc: errorSrc + }; + }; + Exception.CreateFromInterface = function (logger, exception, properties, measurements) { + var exceptions = exception.exceptions + && (0, applicationinsights_core_js_1.arrMap)(exception.exceptions, function (ex) { return _createExDetailsFromInterface(logger, ex); }); + var exceptionData = new Exception(logger, __assign(__assign({}, exception), { exceptions: exceptions }), properties, measurements); + return exceptionData; + }; + Exception.prototype.toInterface = function () { + var _a = this, exceptions = _a.exceptions, properties = _a.properties, measurements = _a.measurements, severityLevel = _a.severityLevel, problemGroup = _a.problemGroup, id = _a.id, isManual = _a.isManual; + var exceptionDetailsInterface = exceptions instanceof Array + && (0, applicationinsights_core_js_1.arrMap)(exceptions, function (exception) { return exception.toInterface(); }) + || undefined; + return { + ver: "4.0", // TODO: handle the CS"4.0" ==> breeze 2 conversion in a better way + exceptions: exceptionDetailsInterface, + severityLevel: severityLevel, + properties: properties, + measurements: measurements, + problemGroup: problemGroup, + id: id, + isManual: isManual + }; + }; + /** + * Creates a simple exception with 1 stack frame. Useful for manual constracting of exception. + */ + Exception.CreateSimpleException = function (message, typeName, assembly, fileName, details, line) { + return { + exceptions: [ + { + hasFullStack: true, + message: message, + stack: details, + typeName: typeName + } + ] + }; + }; + Exception.envelopeType = "Microsoft.ApplicationInsights.{0}.Exception"; + Exception.dataType = "ExceptionData"; + Exception.formatError = _formatErrorCode; + return Exception; +}()); +exports.Exception = Exception; +var exDetailsAiDataContract = (0, ts_utils_1.objFreeze)({ + id: 0 /* FieldType.Default */, + outerId: 0 /* FieldType.Default */, + typeName: 1 /* FieldType.Required */, + message: 1 /* FieldType.Required */, + hasFullStack: 0 /* FieldType.Default */, + stack: 0 /* FieldType.Default */, + parsedStack: 2 /* FieldType.Array */ +}); +function _toInterface() { + var _self = this; + var parsedStack = (0, applicationinsights_core_js_1.isArray)(_self.parsedStack) + && (0, applicationinsights_core_js_1.arrMap)(_self.parsedStack, function (frame) { return _parsedFrameToInterface(frame); }); + var exceptionDetailsInterface = { + id: _self.id, + outerId: _self.outerId, + typeName: _self.typeName, + message: _self.message, + hasFullStack: _self.hasFullStack, + stack: _self[strStack], + parsedStack: parsedStack || undefined + }; + return exceptionDetailsInterface; +} +function _createExceptionDetails(logger, exception, properties) { + var id; + var outerId; + var typeName; + var message; + var hasFullStack; + var theStack; + var parsedStack; + if (!_isExceptionDetailsInternal(exception)) { + var error = exception; + var evt = error && error.evt; + if (!(0, applicationinsights_core_js_1.isError)(error)) { + error = error[strError] || evt || error; + } + typeName = (0, DataSanitizer_1.dataSanitizeString)(logger, _getErrorType(error)) || Constants_1.strNotSpecified; + message = (0, DataSanitizer_1.dataSanitizeMessage)(logger, _formatMessage(exception || error, typeName)) || Constants_1.strNotSpecified; + var stack = exception[strStackDetails] || _getStackFromErrorObj(exception); + parsedStack = _parseStack(stack); + // after parsedStack is inited, iterate over each frame object, sanitize its assembly field + if ((0, applicationinsights_core_js_1.isArray)(parsedStack)) { + (0, applicationinsights_core_js_1.arrMap)(parsedStack, function (frame) { + frame.assembly = (0, DataSanitizer_1.dataSanitizeString)(logger, frame.assembly); + frame.fileName = (0, DataSanitizer_1.dataSanitizeString)(logger, frame.fileName); + }); + } + theStack = (0, DataSanitizer_1.dataSanitizeException)(logger, _formatStackTrace(stack)); + hasFullStack = (0, applicationinsights_core_js_1.isArray)(parsedStack) && parsedStack.length > 0; + if (properties) { + properties.typeName = properties.typeName || typeName; + } + } + else { + typeName = exception.typeName; + message = exception.message; + theStack = exception[strStack]; + parsedStack = exception.parsedStack || []; + hasFullStack = exception.hasFullStack; + } + return { + aiDataContract: exDetailsAiDataContract, + id: id, + outerId: outerId, + typeName: typeName, + message: message, + hasFullStack: hasFullStack, + stack: theStack, + parsedStack: parsedStack, + toInterface: _toInterface + }; +} +function _createExDetailsFromInterface(logger, exception) { + var parsedStack = ((0, applicationinsights_core_js_1.isArray)(exception.parsedStack) + && (0, applicationinsights_core_js_1.arrMap)(exception.parsedStack, function (frame) { return _stackFrameFromInterface(frame); })) + || exception.parsedStack; + var exceptionDetails = _createExceptionDetails(logger, __assign(__assign({}, exception), { parsedStack: parsedStack })); + return exceptionDetails; +} +function _parseFilename(theFrame, fileName) { + var lineCol = fileName.match(PARSE_FILENAME_LINE_COL); + if (lineCol && lineCol.length >= 4) { + theFrame.fileName = lineCol[1]; + theFrame.line = parseInt(lineCol[2]); + } + else { + var lineNo = fileName.match(PARSE_FILENAME_LINE_ONLY); + if (lineNo && lineNo.length >= 3) { + theFrame.fileName = lineNo[1]; + theFrame.line = parseInt(lineNo[2]); + } + else { + theFrame.fileName = fileName; + } + } +} +function _handleFilename(theFrame, sequence, matches) { + var filename = theFrame.fileName; + if (sequence.fn && matches && matches.length > sequence.fn) { + if (sequence.ln && matches.length > sequence.ln) { + filename = (0, applicationinsights_core_js_1.strTrim)(matches[sequence.fn] || ""); + theFrame.line = parseInt((0, applicationinsights_core_js_1.strTrim)(matches[sequence.ln] || "")) || 0; + } + else { + filename = (0, applicationinsights_core_js_1.strTrim)(matches[sequence.fn] || ""); + } + } + if (filename) { + _parseFilename(theFrame, filename); + } +} +function _isStackFrame(frame) { + var result = false; + if (frame && (0, applicationinsights_core_js_1.isString)(frame)) { + var trimmedFrame = (0, applicationinsights_core_js_1.strTrim)(frame); + if (trimmedFrame) { + result = IS_FRAME.test(trimmedFrame); + } + } + return result; +} +var stackFrameAiDataContract = (0, ts_utils_1.objFreeze)({ + level: 1 /* FieldType.Required */, + method: 1 /* FieldType.Required */, + assembly: 0 /* FieldType.Default */, + fileName: 0 /* FieldType.Default */, + line: 0 /* FieldType.Default */ +}); +function _extractStackFrame(frame, level) { + var theFrame; + if (frame && (0, applicationinsights_core_js_1.isString)(frame) && (0, applicationinsights_core_js_1.strTrim)(frame)) { + theFrame = { + aiDataContract: stackFrameAiDataContract, + level: level, + assembly: (0, applicationinsights_core_js_1.strTrim)(frame), + method: NoMethod, + fileName: "", + line: 0, + sizeInBytes: 0 + }; + var idx = 0; + while (idx < _parseSequence.length) { + var sequence = _parseSequence[idx]; + if (sequence.chk && !sequence.chk(frame)) { + break; + } + if (sequence.pre) { + frame = sequence.pre(frame); + } + // Attempt to "parse" the stack frame + var matches = frame.match(sequence.re); + if (matches && matches.length >= sequence.len) { + if (sequence.m) { + theFrame.method = (0, applicationinsights_core_js_1.strTrim)(matches[sequence.m] || NoMethod); + } + if (sequence.hdl) { + // Run any custom handler + sequence.hdl(theFrame, sequence, matches); + } + else if (sequence.fn) { + if (sequence.ln) { + theFrame.fileName = (0, applicationinsights_core_js_1.strTrim)(matches[sequence.fn] || ""); + theFrame.line = parseInt((0, applicationinsights_core_js_1.strTrim)(matches[sequence.ln] || "")) || 0; + } + else { + _parseFilename(theFrame, matches[sequence.fn] || ""); + } + } + // We found a match so stop looking + break; + } + idx++; + } + } + return _populateFrameSizeInBytes(theFrame); +} +function _stackFrameFromInterface(frame) { + var parsedFrame = { + aiDataContract: stackFrameAiDataContract, + level: frame.level, + method: frame.method, + assembly: frame.assembly, + fileName: frame.fileName, + line: frame.line, + sizeInBytes: 0 + }; + return _populateFrameSizeInBytes(parsedFrame); +} +function _populateFrameSizeInBytes(frame) { + var sizeInBytes = STACKFRAME_BASE_SIZE; + if (frame) { + sizeInBytes += frame.method.length; + sizeInBytes += frame.assembly.length; + sizeInBytes += frame.fileName.length; + sizeInBytes += frame.level.toString().length; + sizeInBytes += frame.line.toString().length; + frame.sizeInBytes = sizeInBytes; + } + return frame; +} +function _parsedFrameToInterface(frame) { + return { + level: frame.level, + method: frame.method, + assembly: frame.assembly, + fileName: frame.fileName, + line: frame.line + }; +} diff --git a/shared/AppInsightsCommon/src/Telemetry/Metric.js b/shared/AppInsightsCommon/src/Telemetry/Metric.js new file mode 100644 index 000000000..01116c6f0 --- /dev/null +++ b/shared/AppInsightsCommon/src/Telemetry/Metric.js @@ -0,0 +1,36 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Metric = void 0; +var Constants_1 = require("../Constants"); +var DataPoint_1 = require("./Common/DataPoint"); +var DataSanitizer_1 = require("./Common/DataSanitizer"); +var Metric = /** @class */ (function () { + /** + * Constructs a new instance of the MetricTelemetry object + */ + function Metric(logger, name, value, count, min, max, stdDev, properties, measurements) { + this.aiDataContract = { + ver: 1 /* FieldType.Required */, + metrics: 1 /* FieldType.Required */, + properties: 0 /* FieldType.Default */ + }; + var _self = this; + _self.ver = 2; + var dataPoint = new DataPoint_1.DataPoint(); + dataPoint.count = count > 0 ? count : undefined; + dataPoint.max = isNaN(max) || max === null ? undefined : max; + dataPoint.min = isNaN(min) || min === null ? undefined : min; + dataPoint.name = (0, DataSanitizer_1.dataSanitizeString)(logger, name) || Constants_1.strNotSpecified; + dataPoint.value = value; + dataPoint.stdDev = isNaN(stdDev) || stdDev === null ? undefined : stdDev; + _self.metrics = [dataPoint]; + _self.properties = (0, DataSanitizer_1.dataSanitizeProperties)(logger, properties); + _self.measurements = (0, DataSanitizer_1.dataSanitizeMeasurements)(logger, measurements); + } + Metric.envelopeType = "Microsoft.ApplicationInsights.{0}.Metric"; + Metric.dataType = "MetricData"; + return Metric; +}()); +exports.Metric = Metric; diff --git a/shared/AppInsightsCommon/src/Telemetry/PageView.js b/shared/AppInsightsCommon/src/Telemetry/PageView.js new file mode 100644 index 000000000..1de8e98b3 --- /dev/null +++ b/shared/AppInsightsCommon/src/Telemetry/PageView.js @@ -0,0 +1,38 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PageView = void 0; +var Constants_1 = require("../Constants"); +var HelperFuncs_1 = require("../HelperFuncs"); +var DataSanitizer_1 = require("./Common/DataSanitizer"); +var PageView = /** @class */ (function () { + /** + * Constructs a new instance of the PageEventTelemetry object + */ + function PageView(logger, name, url, durationMs, properties, measurements, id) { + this.aiDataContract = { + ver: 1 /* FieldType.Required */, + name: 0 /* FieldType.Default */, + url: 0 /* FieldType.Default */, + duration: 0 /* FieldType.Default */, + properties: 0 /* FieldType.Default */, + measurements: 0 /* FieldType.Default */, + id: 0 /* FieldType.Default */ + }; + var _self = this; + _self.ver = 2; + _self.id = (0, DataSanitizer_1.dataSanitizeId)(logger, id); + _self.url = (0, DataSanitizer_1.dataSanitizeUrl)(logger, url); + _self.name = (0, DataSanitizer_1.dataSanitizeString)(logger, name) || Constants_1.strNotSpecified; + if (!isNaN(durationMs)) { + _self.duration = (0, HelperFuncs_1.msToTimeSpan)(durationMs); + } + _self.properties = (0, DataSanitizer_1.dataSanitizeProperties)(logger, properties); + _self.measurements = (0, DataSanitizer_1.dataSanitizeMeasurements)(logger, measurements); + } + PageView.envelopeType = "Microsoft.ApplicationInsights.{0}.Pageview"; + PageView.dataType = "PageviewData"; + return PageView; +}()); +exports.PageView = PageView; diff --git a/shared/AppInsightsCommon/src/Telemetry/PageViewPerformance.js b/shared/AppInsightsCommon/src/Telemetry/PageViewPerformance.js new file mode 100644 index 000000000..b7e78819f --- /dev/null +++ b/shared/AppInsightsCommon/src/Telemetry/PageViewPerformance.js @@ -0,0 +1,45 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PageViewPerformance = void 0; +var Constants_1 = require("../Constants"); +var DataSanitizer_1 = require("./Common/DataSanitizer"); +var PageViewPerformance = /** @class */ (function () { + /** + * Constructs a new instance of the PageEventTelemetry object + */ + function PageViewPerformance(logger, name, url, unused, properties, measurements, cs4BaseData) { + this.aiDataContract = { + ver: 1 /* FieldType.Required */, + name: 0 /* FieldType.Default */, + url: 0 /* FieldType.Default */, + duration: 0 /* FieldType.Default */, + perfTotal: 0 /* FieldType.Default */, + networkConnect: 0 /* FieldType.Default */, + sentRequest: 0 /* FieldType.Default */, + receivedResponse: 0 /* FieldType.Default */, + domProcessing: 0 /* FieldType.Default */, + properties: 0 /* FieldType.Default */, + measurements: 0 /* FieldType.Default */ + }; + var _self = this; + _self.ver = 2; + _self.url = (0, DataSanitizer_1.dataSanitizeUrl)(logger, url); + _self.name = (0, DataSanitizer_1.dataSanitizeString)(logger, name) || Constants_1.strNotSpecified; + _self.properties = (0, DataSanitizer_1.dataSanitizeProperties)(logger, properties); + _self.measurements = (0, DataSanitizer_1.dataSanitizeMeasurements)(logger, measurements); + if (cs4BaseData) { + _self.domProcessing = cs4BaseData.domProcessing; + _self.duration = cs4BaseData.duration; + _self.networkConnect = cs4BaseData.networkConnect; + _self.perfTotal = cs4BaseData.perfTotal; + _self.receivedResponse = cs4BaseData.receivedResponse; + _self.sentRequest = cs4BaseData.sentRequest; + } + } + PageViewPerformance.envelopeType = "Microsoft.ApplicationInsights.{0}.PageviewPerformance"; + PageViewPerformance.dataType = "PageviewPerformanceData"; + return PageViewPerformance; +}()); +exports.PageViewPerformance = PageViewPerformance; diff --git a/shared/AppInsightsCommon/src/Telemetry/RemoteDependencyData.js b/shared/AppInsightsCommon/src/Telemetry/RemoteDependencyData.js new file mode 100644 index 000000000..96a722524 --- /dev/null +++ b/shared/AppInsightsCommon/src/Telemetry/RemoteDependencyData.js @@ -0,0 +1,59 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RemoteDependencyData = void 0; +var HelperFuncs_1 = require("../HelperFuncs"); +var Util_1 = require("../Util"); +var DataSanitizer_1 = require("./Common/DataSanitizer"); +var RemoteDependencyData = /** @class */ (function () { + /** + * Constructs a new instance of the RemoteDependencyData object + */ + function RemoteDependencyData(logger, id, absoluteUrl, commandName, value, success, resultCode, method, requestAPI, correlationContext, properties, measurements) { + if (requestAPI === void 0) { requestAPI = "Ajax"; } + this.aiDataContract = { + id: 1 /* FieldType.Required */, + ver: 1 /* FieldType.Required */, + name: 0 /* FieldType.Default */, + resultCode: 0 /* FieldType.Default */, + duration: 0 /* FieldType.Default */, + success: 0 /* FieldType.Default */, + data: 0 /* FieldType.Default */, + target: 0 /* FieldType.Default */, + type: 0 /* FieldType.Default */, + properties: 0 /* FieldType.Default */, + measurements: 0 /* FieldType.Default */, + kind: 0 /* FieldType.Default */, + value: 0 /* FieldType.Default */, + count: 0 /* FieldType.Default */, + min: 0 /* FieldType.Default */, + max: 0 /* FieldType.Default */, + stdDev: 0 /* FieldType.Default */, + dependencyKind: 0 /* FieldType.Default */, + dependencySource: 0 /* FieldType.Default */, + commandName: 0 /* FieldType.Default */, + dependencyTypeName: 0 /* FieldType.Default */ + }; + var _self = this; + _self.ver = 2; + _self.id = id; + _self.duration = (0, HelperFuncs_1.msToTimeSpan)(value); + _self.success = success; + _self.resultCode = resultCode + ""; + _self.type = (0, DataSanitizer_1.dataSanitizeString)(logger, requestAPI); + var dependencyFields = (0, Util_1.AjaxHelperParseDependencyPath)(logger, absoluteUrl, method, commandName); + _self.data = (0, DataSanitizer_1.dataSanitizeUrl)(logger, commandName) || dependencyFields.data; // get a value from hosturl if commandName not available + _self.target = (0, DataSanitizer_1.dataSanitizeString)(logger, dependencyFields.target); + if (correlationContext) { + _self.target = "".concat(_self.target, " | ").concat(correlationContext); + } + _self.name = (0, DataSanitizer_1.dataSanitizeString)(logger, dependencyFields.name); + _self.properties = (0, DataSanitizer_1.dataSanitizeProperties)(logger, properties); + _self.measurements = (0, DataSanitizer_1.dataSanitizeMeasurements)(logger, measurements); + } + RemoteDependencyData.envelopeType = "Microsoft.ApplicationInsights.{0}.RemoteDependency"; + RemoteDependencyData.dataType = "RemoteDependencyData"; + return RemoteDependencyData; +}()); +exports.RemoteDependencyData = RemoteDependencyData; diff --git a/shared/AppInsightsCommon/src/Telemetry/Trace.js b/shared/AppInsightsCommon/src/Telemetry/Trace.js new file mode 100644 index 000000000..f561c323d --- /dev/null +++ b/shared/AppInsightsCommon/src/Telemetry/Trace.js @@ -0,0 +1,33 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Trace = void 0; +var Constants_1 = require("../Constants"); +var DataSanitizer_1 = require("./Common/DataSanitizer"); +var Trace = /** @class */ (function () { + /** + * Constructs a new instance of the TraceTelemetry object + */ + function Trace(logger, message, severityLevel, properties, measurements) { + this.aiDataContract = { + ver: 1 /* FieldType.Required */, + message: 1 /* FieldType.Required */, + severityLevel: 0 /* FieldType.Default */, + properties: 0 /* FieldType.Default */ + }; + var _self = this; + _self.ver = 2; + message = message || Constants_1.strNotSpecified; + _self.message = (0, DataSanitizer_1.dataSanitizeMessage)(logger, message); + _self.properties = (0, DataSanitizer_1.dataSanitizeProperties)(logger, properties); + _self.measurements = (0, DataSanitizer_1.dataSanitizeMeasurements)(logger, measurements); + if (severityLevel) { + _self.severityLevel = severityLevel; + } + } + Trace.envelopeType = "Microsoft.ApplicationInsights.{0}.Message"; + Trace.dataType = "MessageData"; + return Trace; +}()); +exports.Trace = Trace; diff --git a/shared/AppInsightsCommon/src/TelemetryItemCreator.js b/shared/AppInsightsCommon/src/TelemetryItemCreator.js new file mode 100644 index 000000000..aed6396a3 --- /dev/null +++ b/shared/AppInsightsCommon/src/TelemetryItemCreator.js @@ -0,0 +1,64 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TelemetryItemCreator = void 0; +exports.createTelemetryItem = createTelemetryItem; +var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); +var Constants_1 = require("./Constants"); +var DataSanitizer_1 = require("./Telemetry/Common/DataSanitizer"); +/** + * Create a telemetry item that the 1DS channel understands + * @param item - domain specific properties; part B + * @param baseType - telemetry item type. ie PageViewData + * @param envelopeName - Name of the envelope, e.g., `Microsoft.ApplicationInsights.\.PageView`. + * @param customProperties - user defined custom properties; part C + * @param systemProperties - system properties that are added to the context; part A + * @returns ITelemetryItem that is sent to channel + */ +function createTelemetryItem(item, baseType, envelopeName, logger, customProperties, systemProperties) { + envelopeName = (0, DataSanitizer_1.dataSanitizeString)(logger, envelopeName) || Constants_1.strNotSpecified; + if ((0, applicationinsights_core_js_1.isNullOrUndefined)(item) || + (0, applicationinsights_core_js_1.isNullOrUndefined)(baseType) || + (0, applicationinsights_core_js_1.isNullOrUndefined)(envelopeName)) { + (0, applicationinsights_core_js_1.throwError)("Input doesn't contain all required fields"); + } + var iKey = ""; + if (item[Constants_1.strIkey]) { + iKey = item[Constants_1.strIkey]; + delete item[Constants_1.strIkey]; + } + var telemetryItem = { + name: envelopeName, + time: (0, applicationinsights_core_js_1.toISOString)(new Date()), + iKey: iKey, // this will be set in TelemetryContext + ext: systemProperties ? systemProperties : {}, // part A + tags: [], + data: {}, + baseType: baseType, + baseData: item // Part B + }; + // Part C + if (!(0, applicationinsights_core_js_1.isNullOrUndefined)(customProperties)) { + (0, applicationinsights_core_js_1.objForEachKey)(customProperties, function (prop, value) { + telemetryItem.data[prop] = value; + }); + } + return telemetryItem; +} +var TelemetryItemCreator = /** @class */ (function () { + function TelemetryItemCreator() { + } + /** + * Create a telemetry item that the 1DS channel understands + * @param item - domain specific properties; part B + * @param baseType - telemetry item type. ie PageViewData + * @param envelopeName - Name of the envelope (e.g., Microsoft.ApplicationInsights.[instrumentationKey].PageView). + * @param customProperties - user defined custom properties; part C + * @param systemProperties - system properties that are added to the context; part A + * @returns ITelemetryItem that is sent to channel + */ + TelemetryItemCreator.create = createTelemetryItem; + return TelemetryItemCreator; +}()); +exports.TelemetryItemCreator = TelemetryItemCreator; diff --git a/shared/AppInsightsCommon/src/ThrottleMgr.js b/shared/AppInsightsCommon/src/ThrottleMgr.js new file mode 100644 index 000000000..048e2e45c --- /dev/null +++ b/shared/AppInsightsCommon/src/ThrottleMgr.js @@ -0,0 +1,385 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ThrottleMgr = void 0; +var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); +var ts_utils_1 = require("@nevware21/ts-utils"); +var StorageHelperFuncs_1 = require("./StorageHelperFuncs"); +var THROTTLE_STORAGE_PREFIX = "appInsightsThrottle"; +var ThrottleMgr = /** @class */ (function () { + function ThrottleMgr(core, namePrefix) { + var _self = this; + var _canUseLocalStorage; + var _logger; + var _config; + var _localStorageObj; + var _isTriggered; //_isTriggered is to make sure that we only trigger throttle once a day + var _namePrefix; + var _queue; + var _isReady = false; + var _isSpecificDaysGiven = false; + _initConfig(); + // Special internal method to allow the unit tests and DebugPlugin to hook embedded objects + _self["_getDbgPlgTargets"] = function () { + return [_queue]; + }; + _self.getConfig = function () { + return _config; + }; + /** + * Check if it is the correct day to send message. + * If _isTriggered is true, even if canThrottle returns true, message will not be sent, + * because we only allow triggering sendMessage() once a day. + * @returns if the current date is the valid date to send message + */ + _self.canThrottle = function (msgId) { + var localObj = _getLocalStorageObjByKey(msgId); + var cfg = _getCfgByKey(msgId); + return _canThrottle(cfg, _canUseLocalStorage, localObj); + }; + /** + * Check if throttle is triggered on current day(UTC) + * if canThrottle returns false, isTriggered will return false + * @returns if throttle is triggered on current day(UTC) + */ + _self.isTriggered = function (msgId) { + return _isTrigger(msgId); + }; + /** + * Before isReady set to true, all message will be stored in queue. + * Message will only be sent out after isReady set to true. + * Initial and default value: false + * @returns isReady state + */ + _self.isReady = function () { + return _isReady; + }; + /** + * Flush all message with given message key in queue with isReady state set to true. + * @returns if message queue is flushed + */ + _self.flush = function (msgId) { + try { + var queue = _getQueueByKey(msgId); + if (queue && queue.length > 0) { + var items = queue.slice(0); + _queue[msgId] = []; + (0, ts_utils_1.arrForEach)(items, function (item) { + _flushMessage(item.msgID, item.message, item.severity, false); + }); + return true; + } + } + catch (err) { + // eslint-disable-next-line no-empty + } + return false; + }; + /** + * Flush all message in queue with isReady state set to true. + * @returns if message queue is flushed + */ + _self.flushAll = function () { + try { + if (_queue) { + var result_1 = true; + (0, ts_utils_1.objForEachKey)(_queue, function (key) { + var isFlushed = _self.flush(parseInt(key)); + result_1 = result_1 && isFlushed; + }); + return result_1; + } + } + catch (err) { + // eslint-disable-next-line no-empty + } + return false; + }; + /** + * Set isReady State + * if isReady set to true, message queue will be flushed automatically. + * @param isReady - isReady State + * @pa + * @returns if message queue is flushed + */ + _self.onReadyState = function (isReady, flushAll) { + if (flushAll === void 0) { flushAll = true; } + _isReady = (0, applicationinsights_core_js_1.isNullOrUndefined)(isReady) ? true : isReady; + if (_isReady && flushAll) { + return _self.flushAll(); + } + return null; + }; + _self.sendMessage = function (msgID, message, severity) { + return _flushMessage(msgID, message, severity, true); + }; + function _flushMessage(msgID, message, severity, saveUnsentMsg) { + if (_isReady) { + var isSampledIn = _canSampledIn(msgID); + if (!isSampledIn) { + return; + } + var cfg = _getCfgByKey(msgID); + var localStorageObj = _getLocalStorageObjByKey(msgID); + var canThrottle = _canThrottle(cfg, _canUseLocalStorage, localStorageObj); + var throttled = false; + var number = 0; + var isTriggered = _isTrigger(msgID); + try { + if (canThrottle && !isTriggered) { + number = (0, ts_utils_1.mathMin)(cfg.limit.maxSendNumber, localStorageObj.count + 1); + localStorageObj.count = 0; + throttled = true; + _isTriggered[msgID] = true; + localStorageObj.preTriggerDate = new Date(); + } + else { + _isTriggered[msgID] = canThrottle; + localStorageObj.count += 1; + } + var localStorageName = _getLocalStorageName(msgID); + _resetLocalStorage(_logger, localStorageName, localStorageObj); + for (var i = 0; i < number; i++) { + _sendMessage(msgID, _logger, message, severity); + } + } + catch (e) { + // eslint-disable-next-line no-empty + } + return { + isThrottled: throttled, + throttleNum: number + }; + } + else { + if (!!saveUnsentMsg) { + var queue = _getQueueByKey(msgID); + queue.push({ + msgID: msgID, + message: message, + severity: severity + }); + } + } + return null; + } + function _initConfig() { + _logger = (0, applicationinsights_core_js_1.safeGetLogger)(core); + _isTriggered = {}; + _localStorageObj = {}; + _queue = {}; + _config = {}; + _setCfgByKey(applicationinsights_core_js_1._eInternalMessageId.DefaultThrottleMsgKey); + _namePrefix = (0, applicationinsights_core_js_1.isNotNullOrUndefined)(namePrefix) ? namePrefix : ""; + core.addUnloadHook((0, applicationinsights_core_js_1.onConfigChange)(core.config, function (details) { + var coreConfig = details.cfg; + _canUseLocalStorage = (0, StorageHelperFuncs_1.utlCanUseLocalStorage)(); + var configMgr = coreConfig.throttleMgrCfg || {}; + (0, ts_utils_1.objForEachKey)(configMgr, function (key, cfg) { + _setCfgByKey(parseInt(key), cfg); + }); + })); + } + function _getCfgByKey(msgID) { + return _config[msgID] || _config[applicationinsights_core_js_1._eInternalMessageId.DefaultThrottleMsgKey]; + } + function _setCfgByKey(msgID, config) { + var _a, _b; + try { + var cfg = config || {}; + var curCfg = {}; + curCfg.disabled = !!cfg.disabled; + var configInterval = cfg.interval || {}; + _isSpecificDaysGiven = (configInterval === null || configInterval === void 0 ? void 0 : configInterval.daysOfMonth) && (configInterval === null || configInterval === void 0 ? void 0 : configInterval.daysOfMonth.length) > 0; + curCfg.interval = _getIntervalConfig(configInterval); + var limit = { + samplingRate: ((_a = cfg.limit) === null || _a === void 0 ? void 0 : _a.samplingRate) || 100, + // dafault: every time sent only 1 event + maxSendNumber: ((_b = cfg.limit) === null || _b === void 0 ? void 0 : _b.maxSendNumber) || 1 + }; + curCfg.limit = limit; + _config[msgID] = curCfg; + } + catch (e) { + // eslint-disable-next-line no-empty + } + } + function _getIntervalConfig(interval) { + interval = interval || {}; + var monthInterval = interval === null || interval === void 0 ? void 0 : interval.monthInterval; + var dayInterval = interval === null || interval === void 0 ? void 0 : interval.dayInterval; + // default: send data every 3 month each year + if ((0, applicationinsights_core_js_1.isNullOrUndefined)(monthInterval) && (0, applicationinsights_core_js_1.isNullOrUndefined)(dayInterval)) { + interval.monthInterval = 3; + if (!_isSpecificDaysGiven) { + // default: send data on 28th + interval.daysOfMonth = [28]; + _isSpecificDaysGiven = true; + } + } + interval = { + // dafault: sent every three months + monthInterval: interval === null || interval === void 0 ? void 0 : interval.monthInterval, + dayInterval: interval === null || interval === void 0 ? void 0 : interval.dayInterval, + daysOfMonth: interval === null || interval === void 0 ? void 0 : interval.daysOfMonth + }; + return interval; + } + function _canThrottle(config, canUseLocalStorage, localStorageObj) { + if (config && !config.disabled && canUseLocalStorage && (0, applicationinsights_core_js_1.isNotNullOrUndefined)(localStorageObj)) { + var curDate = _getThrottleDate(); + var date = localStorageObj.date; + var interval = config.interval; + var monthCheck = 1; + if (interval === null || interval === void 0 ? void 0 : interval.monthInterval) { + var monthExpand = (curDate.getUTCFullYear() - date.getUTCFullYear()) * 12 + curDate.getUTCMonth() - date.getUTCMonth(); + monthCheck = _checkInterval(interval.monthInterval, 0, monthExpand); + } + var dayCheck = 1; + if (_isSpecificDaysGiven) { + dayCheck = (0, applicationinsights_core_js_1.arrIndexOf)(interval.daysOfMonth, curDate.getUTCDate()); + } + else if (interval === null || interval === void 0 ? void 0 : interval.dayInterval) { + var daySpan = (0, ts_utils_1.mathFloor)((curDate.getTime() - date.getTime()) / 86400000); + dayCheck = _checkInterval(interval.dayInterval, 0, daySpan); + } + return monthCheck >= 0 && dayCheck >= 0; + } + return false; + } + function _getLocalStorageName(msgKey, prefix) { + var fix = (0, applicationinsights_core_js_1.isNotNullOrUndefined)(prefix) ? prefix : ""; + if (msgKey) { + return THROTTLE_STORAGE_PREFIX + fix + "-" + msgKey; + } + return null; + } + // returns if throttle is triggered on current Date + function _isTriggeredOnCurDate(preTriggerDate) { + try { + if (preTriggerDate) { + var curDate = new Date(); + return preTriggerDate.getUTCFullYear() === curDate.getUTCFullYear() && + preTriggerDate.getUTCMonth() === curDate.getUTCMonth() && + preTriggerDate.getUTCDate() === curDate.getUTCDate(); + } + } + catch (e) { + // eslint-disable-next-line no-empty + } + return false; + } + // transfer local storage string value to object that identifies start date, current count and preTriggerDate + function _getLocalStorageObj(value, logger, storageName) { + try { + var storageObj = { + date: _getThrottleDate(), + count: 0 + }; + if (value) { + var obj = JSON.parse(value); + var curObj = { + date: _getThrottleDate(obj.date) || storageObj.date, + count: obj.count || storageObj.count, + preTriggerDate: obj.preTriggerDate ? _getThrottleDate(obj.preTriggerDate) : undefined + }; + return curObj; + } + else { + _resetLocalStorage(logger, storageName, storageObj); + return storageObj; + } + } + catch (e) { + // eslint-disable-next-line no-empty + } + return null; + } + // if datestr is not defined, current date will be returned + function _getThrottleDate(dateStr) { + // if new Date() can't be created through the provided dateStr, null will be returned. + try { + if (dateStr) { + var date = new Date(dateStr); + //make sure it is a valid Date Object + if (!isNaN(date.getDate())) { + return date; + } + } + else { + return new Date(); + } + } + catch (e) { + // eslint-disable-next-line no-empty + } + return null; + } + function _resetLocalStorage(logger, storageName, obj) { + try { + return (0, StorageHelperFuncs_1.utlSetLocalStorage)(logger, storageName, (0, applicationinsights_core_js_1.strTrim)(JSON.stringify(obj))); + } + catch (e) { + // eslint-disable-next-line no-empty + } + return false; + } + function _checkInterval(interval, start, current) { + if (interval <= 0) { + return 1; + } + // count from start year + return (current >= start) && (current - start) % interval == 0 ? (0, ts_utils_1.mathFloor)((current - start) / interval) + 1 : -1; + } + function _sendMessage(msgID, logger, message, severity) { + (0, applicationinsights_core_js_1._throwInternal)(logger, severity || applicationinsights_core_js_1.eLoggingSeverity.CRITICAL, msgID, message); + } + // NOTE: config.limit.samplingRate is set to 4 decimal places, + // so config.limit.samplingRate = 1 means 0.0001% + function _canSampledIn(msgID) { + try { + var cfg = _getCfgByKey(msgID); + return (0, applicationinsights_core_js_1.randomValue)(1000000) <= cfg.limit.samplingRate; + } + catch (e) { + // eslint-disable-next-line no-empty + } + return false; + } + function _getLocalStorageObjByKey(key) { + try { + var curObj = _localStorageObj[key]; + if (!curObj) { + var localStorageName = _getLocalStorageName(key, _namePrefix); + curObj = _getLocalStorageObj((0, StorageHelperFuncs_1.utlGetLocalStorage)(_logger, localStorageName), _logger, localStorageName); + _localStorageObj[key] = curObj; + } + return _localStorageObj[key]; + } + catch (e) { + // eslint-disable-next-line no-empty + } + return null; + } + function _isTrigger(key) { + var isTrigger = _isTriggered[key]; + if ((0, applicationinsights_core_js_1.isNullOrUndefined)(isTrigger)) { + isTrigger = false; + var localStorageObj = _getLocalStorageObjByKey(key); + if (localStorageObj) { + isTrigger = _isTriggeredOnCurDate(localStorageObj.preTriggerDate); + } + _isTriggered[key] = isTrigger; + } + return _isTriggered[key]; + } + function _getQueueByKey(key) { + _queue = _queue || {}; + if ((0, applicationinsights_core_js_1.isNullOrUndefined)(_queue[key])) { + _queue[key] = []; + } + return _queue[key]; + } + } + return ThrottleMgr; +}()); +exports.ThrottleMgr = ThrottleMgr; diff --git a/shared/AppInsightsCommon/src/UrlHelperFuncs.js b/shared/AppInsightsCommon/src/UrlHelperFuncs.js new file mode 100644 index 000000000..2306da816 --- /dev/null +++ b/shared/AppInsightsCommon/src/UrlHelperFuncs.js @@ -0,0 +1,92 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.urlParseUrl = urlParseUrl; +exports.urlGetAbsoluteUrl = urlGetAbsoluteUrl; +exports.urlGetPathName = urlGetPathName; +exports.urlGetCompleteUrl = urlGetCompleteUrl; +exports.urlParseHost = urlParseHost; +exports.urlParseFullHost = urlParseFullHost; +var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); +var _document = (0, applicationinsights_core_js_1.getDocument)() || {}; +var _htmlAnchorIdx = 0; +// Use an array of temporary values as it's possible for multiple calls to parseUrl() will be called with different URLs +// Using a cache size of 5 for now as it current depth usage is at least 2, so adding a minor buffer to handle future updates +var _htmlAnchorElement = [null, null, null, null, null]; +function urlParseUrl(url) { + var anchorIdx = _htmlAnchorIdx; + var anchorCache = _htmlAnchorElement; + var tempAnchor = anchorCache[anchorIdx]; + if (!_document.createElement) { + // Always create the temp instance if createElement is not available + tempAnchor = { host: urlParseHost(url, true) }; + } + else if (!anchorCache[anchorIdx]) { + // Create and cache the unattached anchor instance + tempAnchor = anchorCache[anchorIdx] = _document.createElement("a"); + } + tempAnchor.href = url; + // Move the cache index forward + anchorIdx++; + if (anchorIdx >= anchorCache.length) { + anchorIdx = 0; + } + _htmlAnchorIdx = anchorIdx; + return tempAnchor; +} +function urlGetAbsoluteUrl(url) { + var result; + var a = urlParseUrl(url); + if (a) { + result = a.href; + } + return result; +} +function urlGetPathName(url) { + var result; + var a = urlParseUrl(url); + if (a) { + result = a.pathname; + } + return result; +} +function urlGetCompleteUrl(method, absoluteUrl) { + if (method) { + return method.toUpperCase() + " " + absoluteUrl; + } + return absoluteUrl; +} +// Fallback method to grab host from url if document.createElement method is not available +function urlParseHost(url, inclPort) { + var fullHost = urlParseFullHost(url, inclPort) || ""; + if (fullHost) { + var match = fullHost.match(/(www\d{0,5}\.)?([^\/:]{1,256})(:\d{1,20})?/i); + if (match != null && match.length > 3 && (0, applicationinsights_core_js_1.isString)(match[2]) && match[2].length > 0) { + return match[2] + (match[3] || ""); + } + } + return fullHost; +} +function urlParseFullHost(url, inclPort) { + var result = null; + if (url) { + var match = url.match(/(\w{1,150}):\/\/([^\/:]{1,256})(:\d{1,20})?/i); + if (match != null && match.length > 2 && (0, applicationinsights_core_js_1.isString)(match[2]) && match[2].length > 0) { + result = match[2] || ""; + if (inclPort && match.length > 2) { + var protocol = (match[1] || "").toLowerCase(); + var port = match[3] || ""; + // IE includes the standard port so pass it off if it's the same as the protocol + if (protocol === "http" && port === ":80") { + port = ""; + } + else if (protocol === "https" && port === ":443") { + port = ""; + } + result += port; + } + } + } + return result; +} diff --git a/shared/AppInsightsCommon/src/Util.js b/shared/AppInsightsCommon/src/Util.js new file mode 100644 index 000000000..b77e5a391 --- /dev/null +++ b/shared/AppInsightsCommon/src/Util.js @@ -0,0 +1,204 @@ +"use strict"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isInternalApplicationInsightsEndpoint = isInternalApplicationInsightsEndpoint; +exports.correlationIdSetPrefix = correlationIdSetPrefix; +exports.correlationIdGetPrefix = correlationIdGetPrefix; +exports.correlationIdCanIncludeCorrelationHeader = correlationIdCanIncludeCorrelationHeader; +exports.correlationIdGetCorrelationContext = correlationIdGetCorrelationContext; +exports.correlationIdGetCorrelationContextValue = correlationIdGetCorrelationContextValue; +exports.AjaxHelperParseDependencyPath = AjaxHelperParseDependencyPath; +exports.dateTimeUtilsNow = dateTimeUtilsNow; +exports.dateTimeUtilsDuration = dateTimeUtilsDuration; +exports.createDistributedTraceContextFromTrace = createDistributedTraceContextFromTrace; +var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); +var ts_utils_1 = require("@nevware21/ts-utils"); +var Constants_1 = require("./Constants"); +var RequestResponseHeaders_1 = require("./RequestResponseHeaders"); +var DataSanitizer_1 = require("./Telemetry/Common/DataSanitizer"); +var UrlHelperFuncs_1 = require("./UrlHelperFuncs"); +// listing only non-geo specific locations +var _internalEndpoints = [ + Constants_1.DEFAULT_BREEZE_ENDPOINT + Constants_1.DEFAULT_BREEZE_PATH, + "https://breeze.aimon.applicationinsights.io" + Constants_1.DEFAULT_BREEZE_PATH, + "https://dc-int.services.visualstudio.com" + Constants_1.DEFAULT_BREEZE_PATH +]; +var _correlationIdPrefix = "cid-v1:"; +function isInternalApplicationInsightsEndpoint(endpointUrl) { + return (0, applicationinsights_core_js_1.arrIndexOf)(_internalEndpoints, endpointUrl.toLowerCase()) !== -1; +} +function correlationIdSetPrefix(prefix) { + _correlationIdPrefix = prefix; +} +function correlationIdGetPrefix() { + return _correlationIdPrefix; +} +/** + * Checks if a request url is not on a excluded domain list and if it is safe to add correlation headers. + * Headers are always included if the current domain matches the request domain. If they do not match (CORS), + * they are regex-ed across correlationHeaderDomains and correlationHeaderExcludedDomains to determine if headers are included. + * Some environments don't give information on currentHost via window.location.host (e.g. Cordova). In these cases, the user must + * manually supply domains to include correlation headers on. Else, no headers will be included at all. + */ +function correlationIdCanIncludeCorrelationHeader(config, requestUrl, currentHost) { + if (!requestUrl || (config && config.disableCorrelationHeaders)) { + return false; + } + if (config && config.correlationHeaderExcludePatterns) { + for (var i = 0; i < config.correlationHeaderExcludePatterns.length; i++) { + if (config.correlationHeaderExcludePatterns[i].test(requestUrl)) { + return false; + } + } + } + var requestHost = (0, UrlHelperFuncs_1.urlParseUrl)(requestUrl).host.toLowerCase(); + if (requestHost && ((0, ts_utils_1.strIndexOf)(requestHost, ":443") !== -1 || (0, ts_utils_1.strIndexOf)(requestHost, ":80") !== -1)) { + // [Bug #1260] IE can include the port even for http and https URLs so if present + // try and parse it to remove if it matches the default protocol port + requestHost = ((0, UrlHelperFuncs_1.urlParseFullHost)(requestUrl, true) || "").toLowerCase(); + } + if ((!config || !config.enableCorsCorrelation) && (requestHost && requestHost !== currentHost)) { + return false; + } + var includedDomains = config && config.correlationHeaderDomains; + if (includedDomains) { + var matchExists_1; + (0, applicationinsights_core_js_1.arrForEach)(includedDomains, function (domain) { + var regex = new RegExp(domain.toLowerCase().replace(/\\/g, "\\\\").replace(/\./g, "\\.").replace(/\*/g, ".*")); + matchExists_1 = matchExists_1 || regex.test(requestHost); + }); + if (!matchExists_1) { + return false; + } + } + var excludedDomains = config && config.correlationHeaderExcludedDomains; + if (!excludedDomains || excludedDomains.length === 0) { + return true; + } + for (var i = 0; i < excludedDomains.length; i++) { + var regex = new RegExp(excludedDomains[i].toLowerCase().replace(/\\/g, "\\\\").replace(/\./g, "\\.").replace(/\*/g, ".*")); + if (regex.test(requestHost)) { + return false; + } + } + // if we don't know anything about the requestHost, require the user to use included/excludedDomains. + // Previously we always returned false for a falsy requestHost + return requestHost && requestHost.length > 0; +} +/** + * Combines target appId and target role name from response header. + */ +function correlationIdGetCorrelationContext(responseHeader) { + if (responseHeader) { + var correlationId = correlationIdGetCorrelationContextValue(responseHeader, RequestResponseHeaders_1.RequestHeaders[1 /* eRequestHeaders.requestContextTargetKey */]); + if (correlationId && correlationId !== _correlationIdPrefix) { + return correlationId; + } + } +} +/** + * Gets key from correlation response header + */ +function correlationIdGetCorrelationContextValue(responseHeader, key) { + if (responseHeader) { + var keyValues = responseHeader.split(","); + for (var i = 0; i < keyValues.length; ++i) { + var keyValue = keyValues[i].split("="); + if (keyValue.length === 2 && keyValue[0] === key) { + return keyValue[1]; + } + } + } +} +function AjaxHelperParseDependencyPath(logger, absoluteUrl, method, commandName) { + var target, name = commandName, data = commandName; + if (absoluteUrl && absoluteUrl.length > 0) { + var parsedUrl = (0, UrlHelperFuncs_1.urlParseUrl)(absoluteUrl); + target = parsedUrl.host; + if (!name) { + if (parsedUrl.pathname != null) { + var pathName = (parsedUrl.pathname.length === 0) ? "/" : parsedUrl.pathname; + if (pathName.charAt(0) !== "/") { + pathName = "/" + pathName; + } + data = parsedUrl.pathname; + name = (0, DataSanitizer_1.dataSanitizeString)(logger, method ? method + " " + pathName : pathName); + } + else { + name = (0, DataSanitizer_1.dataSanitizeString)(logger, absoluteUrl); + } + } + } + else { + target = commandName; + name = commandName; + } + return { + target: target, + name: name, + data: data + }; +} +function dateTimeUtilsNow() { + // returns the window or webworker performance object + var perf = (0, applicationinsights_core_js_1.getPerformance)(); + if (perf && perf.now && perf.timing) { + var now = perf.now() + perf.timing.navigationStart; + // Known issue with IE where this calculation can be negative, so if it is then ignore and fallback + if (now > 0) { + return now; + } + } + return (0, applicationinsights_core_js_1.dateNow)(); +} +function dateTimeUtilsDuration(start, end) { + var result = null; + if (start !== 0 && end !== 0 && !(0, applicationinsights_core_js_1.isNullOrUndefined)(start) && !(0, applicationinsights_core_js_1.isNullOrUndefined)(end)) { + result = end - start; + } + return result; +} +/** + * Creates a IDistributedTraceContext from an optional telemetryTrace + * @param telemetryTrace - The telemetryTrace instance that is being wrapped + * @param parentCtx - An optional parent distributed trace instance, almost always undefined as this scenario is only used in the case of multiple property handlers. + * @returns A new IDistributedTraceContext instance that is backed by the telemetryTrace or temporary object + */ +function createDistributedTraceContextFromTrace(telemetryTrace, parentCtx) { + var trace = telemetryTrace || {}; + return { + getName: function () { + return trace.name; + }, + setName: function (newValue) { + parentCtx && parentCtx.setName(newValue); + trace.name = newValue; + }, + getTraceId: function () { + return trace.traceID; + }, + setTraceId: function (newValue) { + parentCtx && parentCtx.setTraceId(newValue); + if ((0, applicationinsights_core_js_1.isValidTraceId)(newValue)) { + trace.traceID = newValue; + } + }, + getSpanId: function () { + return trace.parentID; + }, + setSpanId: function (newValue) { + parentCtx && parentCtx.setSpanId(newValue); + if ((0, applicationinsights_core_js_1.isValidSpanId)(newValue)) { + trace.parentID = newValue; + } + }, + getTraceFlags: function () { + return trace.traceFlags; + }, + setTraceFlags: function (newTraceFlags) { + parentCtx && parentCtx.setTraceFlags(newTraceFlags); + trace.traceFlags = newTraceFlags; + } + }; +} diff --git a/shared/AppInsightsCommon/src/applicationinsights-common.js b/shared/AppInsightsCommon/src/applicationinsights-common.js new file mode 100644 index 000000000..e02cf3eff --- /dev/null +++ b/shared/AppInsightsCommon/src/applicationinsights-common.js @@ -0,0 +1,120 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.stringToBoolOrDefault = exports.EventPersistence = exports.DistributedTracingModes = exports.Extensions = exports.CtxTagKeys = exports.createTelemetryItem = exports.TelemetryItemCreator = exports.dsPadNumber = exports.dataSanitizeInput = exports.dataSanitizeId = exports.dataSanitizeMeasurements = exports.dataSanitizeProperties = exports.dataSanitizeException = exports.dataSanitizeMessage = exports.dataSanitizeUrl = exports.dataSanitizeString = exports.dataSanitizeKey = exports.dataSanitizeKeyAndAddUniqueness = exports.ContextTagKeys = exports.ConfigurationManager = exports.SeverityLevel = exports.Data = exports.PageViewPerformance = exports.Trace = exports.RemoteDependencyData = exports.PageView = exports.Metric = exports.Exception = exports.Event = exports.Envelope = exports.strNotSpecified = exports.DEFAULT_BREEZE_PATH = exports.DEFAULT_BREEZE_ENDPOINT = exports.HttpMethod = exports.SampleRate = exports.ProcessLegacy = exports.DisabledPropertyName = exports.RequestHeaders = exports.ConnectionStringParser = exports.parseConnectionString = exports.ThrottleMgr = exports.createDistributedTraceContextFromTrace = exports.isInternalApplicationInsightsEndpoint = exports.dateTimeUtilsDuration = exports.dateTimeUtilsNow = exports.correlationIdGetCorrelationContextValue = exports.correlationIdGetCorrelationContext = exports.correlationIdCanIncludeCorrelationHeader = exports.correlationIdGetPrefix = exports.correlationIdSetPrefix = void 0; +exports.AnalyticsPluginIdentifier = exports.BreezeChannelIdentifier = exports.PropertiesPluginIdentifier = exports.createOfflineListener = exports.urlParseFullHost = exports.urlParseHost = exports.urlGetCompleteUrl = exports.urlGetPathName = exports.urlGetAbsoluteUrl = exports.urlParseUrl = exports.utlSetStoragePrefix = exports.utlRemoveSessionStorage = exports.utlSetSessionStorage = exports.utlGetSessionStorage = exports.utlGetSessionStorageKeys = exports.utlCanUseSessionStorage = exports.utlRemoveStorage = exports.utlSetLocalStorage = exports.utlGetLocalStorage = exports.utlCanUseLocalStorage = exports.utlEnableStorage = exports.utlDisableStorage = exports.createDomEvent = exports.findAllScripts = exports.findW3cTraceParent = exports.formatTraceParent = exports.isSampledFlag = exports.isValidTraceParent = exports.isValidSpanId = exports.isValidTraceId = exports.parseTraceParent = exports.createTraceParent = exports.ITraceParent = exports.isBeaconApiSupported = exports.isCrossOriginError = exports.getExtensionByName = exports.msToTimeSpan = void 0; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the +var Util_1 = require("./Util"); +Object.defineProperty(exports, "correlationIdSetPrefix", { enumerable: true, get: function () { return Util_1.correlationIdSetPrefix; } }); +Object.defineProperty(exports, "correlationIdGetPrefix", { enumerable: true, get: function () { return Util_1.correlationIdGetPrefix; } }); +Object.defineProperty(exports, "correlationIdCanIncludeCorrelationHeader", { enumerable: true, get: function () { return Util_1.correlationIdCanIncludeCorrelationHeader; } }); +Object.defineProperty(exports, "correlationIdGetCorrelationContext", { enumerable: true, get: function () { return Util_1.correlationIdGetCorrelationContext; } }); +Object.defineProperty(exports, "correlationIdGetCorrelationContextValue", { enumerable: true, get: function () { return Util_1.correlationIdGetCorrelationContextValue; } }); +Object.defineProperty(exports, "dateTimeUtilsNow", { enumerable: true, get: function () { return Util_1.dateTimeUtilsNow; } }); +Object.defineProperty(exports, "dateTimeUtilsDuration", { enumerable: true, get: function () { return Util_1.dateTimeUtilsDuration; } }); +Object.defineProperty(exports, "isInternalApplicationInsightsEndpoint", { enumerable: true, get: function () { return Util_1.isInternalApplicationInsightsEndpoint; } }); +Object.defineProperty(exports, "createDistributedTraceContextFromTrace", { enumerable: true, get: function () { return Util_1.createDistributedTraceContextFromTrace; } }); +var ThrottleMgr_1 = require("./ThrottleMgr"); +Object.defineProperty(exports, "ThrottleMgr", { enumerable: true, get: function () { return ThrottleMgr_1.ThrottleMgr; } }); +var ConnectionStringParser_1 = require("./ConnectionStringParser"); +Object.defineProperty(exports, "parseConnectionString", { enumerable: true, get: function () { return ConnectionStringParser_1.parseConnectionString; } }); +Object.defineProperty(exports, "ConnectionStringParser", { enumerable: true, get: function () { return ConnectionStringParser_1.ConnectionStringParser; } }); +var RequestResponseHeaders_1 = require("./RequestResponseHeaders"); +Object.defineProperty(exports, "RequestHeaders", { enumerable: true, get: function () { return RequestResponseHeaders_1.RequestHeaders; } }); +var Constants_1 = require("./Constants"); +Object.defineProperty(exports, "DisabledPropertyName", { enumerable: true, get: function () { return Constants_1.DisabledPropertyName; } }); +Object.defineProperty(exports, "ProcessLegacy", { enumerable: true, get: function () { return Constants_1.ProcessLegacy; } }); +Object.defineProperty(exports, "SampleRate", { enumerable: true, get: function () { return Constants_1.SampleRate; } }); +Object.defineProperty(exports, "HttpMethod", { enumerable: true, get: function () { return Constants_1.HttpMethod; } }); +Object.defineProperty(exports, "DEFAULT_BREEZE_ENDPOINT", { enumerable: true, get: function () { return Constants_1.DEFAULT_BREEZE_ENDPOINT; } }); +Object.defineProperty(exports, "DEFAULT_BREEZE_PATH", { enumerable: true, get: function () { return Constants_1.DEFAULT_BREEZE_PATH; } }); +Object.defineProperty(exports, "strNotSpecified", { enumerable: true, get: function () { return Constants_1.strNotSpecified; } }); +var Envelope_1 = require("./Telemetry/Common/Envelope"); +Object.defineProperty(exports, "Envelope", { enumerable: true, get: function () { return Envelope_1.Envelope; } }); +var Event_1 = require("./Telemetry/Event"); +Object.defineProperty(exports, "Event", { enumerable: true, get: function () { return Event_1.Event; } }); +var Exception_1 = require("./Telemetry/Exception"); +Object.defineProperty(exports, "Exception", { enumerable: true, get: function () { return Exception_1.Exception; } }); +var Metric_1 = require("./Telemetry/Metric"); +Object.defineProperty(exports, "Metric", { enumerable: true, get: function () { return Metric_1.Metric; } }); +var PageView_1 = require("./Telemetry/PageView"); +Object.defineProperty(exports, "PageView", { enumerable: true, get: function () { return PageView_1.PageView; } }); +var RemoteDependencyData_1 = require("./Telemetry/RemoteDependencyData"); +Object.defineProperty(exports, "RemoteDependencyData", { enumerable: true, get: function () { return RemoteDependencyData_1.RemoteDependencyData; } }); +var Trace_1 = require("./Telemetry/Trace"); +Object.defineProperty(exports, "Trace", { enumerable: true, get: function () { return Trace_1.Trace; } }); +var PageViewPerformance_1 = require("./Telemetry/PageViewPerformance"); +Object.defineProperty(exports, "PageViewPerformance", { enumerable: true, get: function () { return PageViewPerformance_1.PageViewPerformance; } }); +var Data_1 = require("./Telemetry/Common/Data"); +Object.defineProperty(exports, "Data", { enumerable: true, get: function () { return Data_1.Data; } }); +var SeverityLevel_1 = require("./Interfaces/Contracts/SeverityLevel"); +Object.defineProperty(exports, "SeverityLevel", { enumerable: true, get: function () { return SeverityLevel_1.SeverityLevel; } }); +var IConfig_1 = require("./Interfaces/IConfig"); +Object.defineProperty(exports, "ConfigurationManager", { enumerable: true, get: function () { return IConfig_1.ConfigurationManager; } }); +var ContextTagKeys_1 = require("./Interfaces/Contracts/ContextTagKeys"); +Object.defineProperty(exports, "ContextTagKeys", { enumerable: true, get: function () { return ContextTagKeys_1.ContextTagKeys; } }); +var DataSanitizer_1 = require("./Telemetry/Common/DataSanitizer"); +Object.defineProperty(exports, "dataSanitizeKeyAndAddUniqueness", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeKeyAndAddUniqueness; } }); +Object.defineProperty(exports, "dataSanitizeKey", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeKey; } }); +Object.defineProperty(exports, "dataSanitizeString", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeString; } }); +Object.defineProperty(exports, "dataSanitizeUrl", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeUrl; } }); +Object.defineProperty(exports, "dataSanitizeMessage", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeMessage; } }); +Object.defineProperty(exports, "dataSanitizeException", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeException; } }); +Object.defineProperty(exports, "dataSanitizeProperties", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeProperties; } }); +Object.defineProperty(exports, "dataSanitizeMeasurements", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeMeasurements; } }); +Object.defineProperty(exports, "dataSanitizeId", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeId; } }); +Object.defineProperty(exports, "dataSanitizeInput", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeInput; } }); +Object.defineProperty(exports, "dsPadNumber", { enumerable: true, get: function () { return DataSanitizer_1.dsPadNumber; } }); +var TelemetryItemCreator_1 = require("./TelemetryItemCreator"); +Object.defineProperty(exports, "TelemetryItemCreator", { enumerable: true, get: function () { return TelemetryItemCreator_1.TelemetryItemCreator; } }); +Object.defineProperty(exports, "createTelemetryItem", { enumerable: true, get: function () { return TelemetryItemCreator_1.createTelemetryItem; } }); +var PartAExtensions_1 = require("./Interfaces/PartAExtensions"); +Object.defineProperty(exports, "CtxTagKeys", { enumerable: true, get: function () { return PartAExtensions_1.CtxTagKeys; } }); +Object.defineProperty(exports, "Extensions", { enumerable: true, get: function () { return PartAExtensions_1.Extensions; } }); +var Enums_1 = require("./Enums"); +Object.defineProperty(exports, "DistributedTracingModes", { enumerable: true, get: function () { return Enums_1.DistributedTracingModes; } }); +Object.defineProperty(exports, "EventPersistence", { enumerable: true, get: function () { return Enums_1.EventPersistence; } }); +var HelperFuncs_1 = require("./HelperFuncs"); +Object.defineProperty(exports, "stringToBoolOrDefault", { enumerable: true, get: function () { return HelperFuncs_1.stringToBoolOrDefault; } }); +Object.defineProperty(exports, "msToTimeSpan", { enumerable: true, get: function () { return HelperFuncs_1.msToTimeSpan; } }); +Object.defineProperty(exports, "getExtensionByName", { enumerable: true, get: function () { return HelperFuncs_1.getExtensionByName; } }); +Object.defineProperty(exports, "isCrossOriginError", { enumerable: true, get: function () { return HelperFuncs_1.isCrossOriginError; } }); +var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); +Object.defineProperty(exports, "isBeaconApiSupported", { enumerable: true, get: function () { return applicationinsights_core_js_1.isBeaconsSupported; } }); +Object.defineProperty(exports, "ITraceParent", { enumerable: true, get: function () { return applicationinsights_core_js_1.ITraceParent; } }); +Object.defineProperty(exports, "createTraceParent", { enumerable: true, get: function () { return applicationinsights_core_js_1.createTraceParent; } }); +Object.defineProperty(exports, "parseTraceParent", { enumerable: true, get: function () { return applicationinsights_core_js_1.parseTraceParent; } }); +Object.defineProperty(exports, "isValidTraceId", { enumerable: true, get: function () { return applicationinsights_core_js_1.isValidTraceId; } }); +Object.defineProperty(exports, "isValidSpanId", { enumerable: true, get: function () { return applicationinsights_core_js_1.isValidSpanId; } }); +Object.defineProperty(exports, "isValidTraceParent", { enumerable: true, get: function () { return applicationinsights_core_js_1.isValidTraceParent; } }); +Object.defineProperty(exports, "isSampledFlag", { enumerable: true, get: function () { return applicationinsights_core_js_1.isSampledFlag; } }); +Object.defineProperty(exports, "formatTraceParent", { enumerable: true, get: function () { return applicationinsights_core_js_1.formatTraceParent; } }); +Object.defineProperty(exports, "findW3cTraceParent", { enumerable: true, get: function () { return applicationinsights_core_js_1.findW3cTraceParent; } }); +Object.defineProperty(exports, "findAllScripts", { enumerable: true, get: function () { return applicationinsights_core_js_1.findAllScripts; } }); +var DomHelperFuncs_1 = require("./DomHelperFuncs"); +Object.defineProperty(exports, "createDomEvent", { enumerable: true, get: function () { return DomHelperFuncs_1.createDomEvent; } }); +var StorageHelperFuncs_1 = require("./StorageHelperFuncs"); +Object.defineProperty(exports, "utlDisableStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlDisableStorage; } }); +Object.defineProperty(exports, "utlEnableStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlEnableStorage; } }); +Object.defineProperty(exports, "utlCanUseLocalStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlCanUseLocalStorage; } }); +Object.defineProperty(exports, "utlGetLocalStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlGetLocalStorage; } }); +Object.defineProperty(exports, "utlSetLocalStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlSetLocalStorage; } }); +Object.defineProperty(exports, "utlRemoveStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlRemoveStorage; } }); +Object.defineProperty(exports, "utlCanUseSessionStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlCanUseSessionStorage; } }); +Object.defineProperty(exports, "utlGetSessionStorageKeys", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlGetSessionStorageKeys; } }); +Object.defineProperty(exports, "utlGetSessionStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlGetSessionStorage; } }); +Object.defineProperty(exports, "utlSetSessionStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlSetSessionStorage; } }); +Object.defineProperty(exports, "utlRemoveSessionStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlRemoveSessionStorage; } }); +Object.defineProperty(exports, "utlSetStoragePrefix", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlSetStoragePrefix; } }); +var UrlHelperFuncs_1 = require("./UrlHelperFuncs"); +Object.defineProperty(exports, "urlParseUrl", { enumerable: true, get: function () { return UrlHelperFuncs_1.urlParseUrl; } }); +Object.defineProperty(exports, "urlGetAbsoluteUrl", { enumerable: true, get: function () { return UrlHelperFuncs_1.urlGetAbsoluteUrl; } }); +Object.defineProperty(exports, "urlGetPathName", { enumerable: true, get: function () { return UrlHelperFuncs_1.urlGetPathName; } }); +Object.defineProperty(exports, "urlGetCompleteUrl", { enumerable: true, get: function () { return UrlHelperFuncs_1.urlGetCompleteUrl; } }); +Object.defineProperty(exports, "urlParseHost", { enumerable: true, get: function () { return UrlHelperFuncs_1.urlParseHost; } }); +Object.defineProperty(exports, "urlParseFullHost", { enumerable: true, get: function () { return UrlHelperFuncs_1.urlParseFullHost; } }); +var Offline_1 = require("./Offline"); +Object.defineProperty(exports, "createOfflineListener", { enumerable: true, get: function () { return Offline_1.createOfflineListener; } }); +exports.PropertiesPluginIdentifier = "AppInsightsPropertiesPlugin"; +exports.BreezeChannelIdentifier = "AppInsightsChannelPlugin"; +exports.AnalyticsPluginIdentifier = "ApplicationInsightsAnalytics"; From fd68d94e3fceddba29fe81899f51a4368fe84ca2 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 21 May 2025 17:08:01 +0000 Subject: [PATCH 06/22] Remove generated JS files from PR per feedback Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- .../src/ConnectionStringParser.js | 42 - shared/AppInsightsCommon/src/Constants.js | 20 - .../AppInsightsCommon/src/DomHelperFuncs.js | 20 - shared/AppInsightsCommon/src/Enums.js | 28 - shared/AppInsightsCommon/src/HelperFuncs.js | 50 -- .../src/Interfaces/ConnectionString.js | 2 - .../src/Interfaces/Context/IApplication.js | 4 - .../src/Interfaces/Context/IDevice.js | 4 - .../src/Interfaces/Context/IInternal.js | 4 - .../src/Interfaces/Context/ILocation.js | 4 - .../Interfaces/Context/IOperatingSystem.js | 4 - .../src/Interfaces/Context/ISample.js | 4 - .../src/Interfaces/Context/ISession.js | 4 - .../src/Interfaces/Context/ISessionManager.js | 4 - .../src/Interfaces/Context/ITelemetryTrace.js | 4 - .../src/Interfaces/Context/IUser.js | 4 - .../src/Interfaces/Context/IWeb.js | 4 - .../Interfaces/Contracts/AvailabilityData.js | 47 -- .../Interfaces/Contracts/ContextTagKeys.js | 101 --- .../src/Interfaces/Contracts/DataPointType.js | 4 - .../Interfaces/Contracts/DependencyKind.js | 4 - .../Contracts/DependencySourceType.js | 4 - .../src/Interfaces/Contracts/IBase.js | 4 - .../src/Interfaces/Contracts/IData.js | 4 - .../src/Interfaces/Contracts/IDataPoint.js | 2 - .../src/Interfaces/Contracts/IDomain.js | 4 - .../src/Interfaces/Contracts/IEnvelope.js | 41 - .../src/Interfaces/Contracts/IEventData.js | 4 - .../Interfaces/Contracts/IExceptionData.js | 4 - .../Interfaces/Contracts/IExceptionDetails.js | 4 - .../src/Interfaces/Contracts/IMessageData.js | 4 - .../src/Interfaces/Contracts/IMetricData.js | 4 - .../src/Interfaces/Contracts/IPageViewData.js | 4 - .../Interfaces/Contracts/IPageViewPerfData.js | 4 - .../Contracts/IRemoteDependencyData.js | 4 - .../src/Interfaces/Contracts/IStackFrame.js | 4 - .../src/Interfaces/Contracts/RequestData.js | 41 - .../src/Interfaces/Contracts/SeverityLevel.js | 16 - .../src/Interfaces/IAppInsights.js | 4 - .../src/Interfaces/IConfig.js | 23 - .../src/Interfaces/ICorrelationConfig.js | 4 - .../src/Interfaces/IDependencyTelemetry.js | 4 - .../src/Interfaces/IEventTelemetry.js | 2 - .../src/Interfaces/IExceptionTelemetry.js | 4 - .../src/Interfaces/IMetricTelemetry.js | 2 - .../IPageViewPerformanceTelemetry.js | 2 - .../src/Interfaces/IPageViewTelemetry.js | 2 - .../src/Interfaces/IPartC.js | 4 - .../src/Interfaces/IPropertiesPlugin.js | 4 - .../src/Interfaces/IRequestContext.js | 2 - .../src/Interfaces/IStorageBuffer.js | 2 - .../src/Interfaces/ITelemetryContext.js | 4 - .../src/Interfaces/IThrottleMgr.js | 2 - .../src/Interfaces/ITraceTelemetry.js | 4 - .../src/Interfaces/PartAExtensions.js | 15 - .../src/Interfaces/Telemetry/IEnvelope.js | 4 - .../src/Interfaces/Telemetry/ISerializable.js | 4 - shared/AppInsightsCommon/src/Offline.js | 135 --- .../src/RequestResponseHeaders.js | 17 - .../src/StorageHelperFuncs.js | 249 ------ .../src/Telemetry/Common/Data.js | 23 - .../src/Telemetry/Common/DataPoint.js | 27 - .../src/Telemetry/Common/DataSanitizer.js | 133 --- .../src/Telemetry/Common/Envelope.js | 35 - .../AppInsightsCommon/src/Telemetry/Event.js | 29 - .../src/Telemetry/Exception.js | 767 ------------------ .../AppInsightsCommon/src/Telemetry/Metric.js | 36 - .../src/Telemetry/PageView.js | 38 - .../src/Telemetry/PageViewPerformance.js | 45 - .../src/Telemetry/RemoteDependencyData.js | 59 -- .../AppInsightsCommon/src/Telemetry/Trace.js | 33 - .../src/TelemetryItemCreator.js | 64 -- shared/AppInsightsCommon/src/ThrottleMgr.js | 385 --------- .../AppInsightsCommon/src/UrlHelperFuncs.js | 92 --- shared/AppInsightsCommon/src/Util.js | 204 ----- .../src/applicationinsights-common.js | 120 --- 76 files changed, 3097 deletions(-) delete mode 100644 shared/AppInsightsCommon/src/ConnectionStringParser.js delete mode 100644 shared/AppInsightsCommon/src/Constants.js delete mode 100644 shared/AppInsightsCommon/src/DomHelperFuncs.js delete mode 100644 shared/AppInsightsCommon/src/Enums.js delete mode 100644 shared/AppInsightsCommon/src/HelperFuncs.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/ConnectionString.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/IApplication.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/IDevice.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/IInternal.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/ILocation.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/IOperatingSystem.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/ISample.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/ISession.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/ISessionManager.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/ITelemetryTrace.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/IUser.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Context/IWeb.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/AvailabilityData.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/ContextTagKeys.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/DataPointType.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/DependencyKind.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/DependencySourceType.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IBase.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IData.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IDataPoint.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IDomain.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IEnvelope.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IEventData.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IExceptionData.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IExceptionDetails.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IMessageData.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IMetricData.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IPageViewData.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IPageViewPerfData.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IRemoteDependencyData.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/IStackFrame.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/RequestData.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Contracts/SeverityLevel.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/IAppInsights.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/IConfig.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/ICorrelationConfig.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/IDependencyTelemetry.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/IEventTelemetry.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/IExceptionTelemetry.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/IMetricTelemetry.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/IPageViewPerformanceTelemetry.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/IPageViewTelemetry.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/IPartC.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/IPropertiesPlugin.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/IRequestContext.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/IStorageBuffer.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/ITelemetryContext.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/IThrottleMgr.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/ITraceTelemetry.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/PartAExtensions.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Telemetry/IEnvelope.js delete mode 100644 shared/AppInsightsCommon/src/Interfaces/Telemetry/ISerializable.js delete mode 100644 shared/AppInsightsCommon/src/Offline.js delete mode 100644 shared/AppInsightsCommon/src/RequestResponseHeaders.js delete mode 100644 shared/AppInsightsCommon/src/StorageHelperFuncs.js delete mode 100644 shared/AppInsightsCommon/src/Telemetry/Common/Data.js delete mode 100644 shared/AppInsightsCommon/src/Telemetry/Common/DataPoint.js delete mode 100644 shared/AppInsightsCommon/src/Telemetry/Common/DataSanitizer.js delete mode 100644 shared/AppInsightsCommon/src/Telemetry/Common/Envelope.js delete mode 100644 shared/AppInsightsCommon/src/Telemetry/Event.js delete mode 100644 shared/AppInsightsCommon/src/Telemetry/Exception.js delete mode 100644 shared/AppInsightsCommon/src/Telemetry/Metric.js delete mode 100644 shared/AppInsightsCommon/src/Telemetry/PageView.js delete mode 100644 shared/AppInsightsCommon/src/Telemetry/PageViewPerformance.js delete mode 100644 shared/AppInsightsCommon/src/Telemetry/RemoteDependencyData.js delete mode 100644 shared/AppInsightsCommon/src/Telemetry/Trace.js delete mode 100644 shared/AppInsightsCommon/src/TelemetryItemCreator.js delete mode 100644 shared/AppInsightsCommon/src/ThrottleMgr.js delete mode 100644 shared/AppInsightsCommon/src/UrlHelperFuncs.js delete mode 100644 shared/AppInsightsCommon/src/Util.js delete mode 100644 shared/AppInsightsCommon/src/applicationinsights-common.js diff --git a/shared/AppInsightsCommon/src/ConnectionStringParser.js b/shared/AppInsightsCommon/src/ConnectionStringParser.js deleted file mode 100644 index ea30ee875..000000000 --- a/shared/AppInsightsCommon/src/ConnectionStringParser.js +++ /dev/null @@ -1,42 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConnectionStringParser = void 0; -exports.parseConnectionString = parseConnectionString; -var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); -var Constants_1 = require("./Constants"); -var _FIELDS_SEPARATOR = ";"; -var _FIELD_KEY_VALUE_SEPARATOR = "="; -function parseConnectionString(connectionString) { - if (!connectionString) { - return {}; - } - var kvPairs = connectionString.split(_FIELDS_SEPARATOR); - var result = (0, applicationinsights_core_js_1.arrReduce)(kvPairs, function (fields, kv) { - var kvParts = kv.split(_FIELD_KEY_VALUE_SEPARATOR); - if (kvParts.length === 2) { // only save fields with valid formats - var key = kvParts[0].toLowerCase(); - var value = kvParts[1]; - fields[key] = value; - } - return fields; - }, {}); - if ((0, applicationinsights_core_js_1.objKeys)(result).length > 0) { - // this is a valid connection string, so parse the results - if (result.endpointsuffix) { - // apply the default endpoints - var locationPrefix = result.location ? result.location + "." : ""; - result.ingestionendpoint = result.ingestionendpoint || ("https://" + locationPrefix + "dc." + result.endpointsuffix); - } - // apply user override endpoint or the default endpoints - result.ingestionendpoint = result.ingestionendpoint || Constants_1.DEFAULT_BREEZE_ENDPOINT; - if ((0, applicationinsights_core_js_1.strEndsWith)(result.ingestionendpoint, "/")) { - result.ingestionendpoint = result.ingestionendpoint.slice(0, -1); - } - } - return result; -} -exports.ConnectionStringParser = { - parse: parseConnectionString -}; diff --git a/shared/AppInsightsCommon/src/Constants.js b/shared/AppInsightsCommon/src/Constants.js deleted file mode 100644 index 15c48ea28..000000000 --- a/shared/AppInsightsCommon/src/Constants.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.strIkey = exports.strNotSpecified = exports.DEFAULT_BREEZE_PATH = exports.DEFAULT_BREEZE_ENDPOINT = exports.HttpMethod = exports.ProcessLegacy = exports.SampleRate = exports.DisabledPropertyName = void 0; -/** - * This is an internal property used to cause internal (reporting) requests to be ignored from reporting - * additional telemetry, to handle polyfil implementations ALL urls used with a disabled request will - * also be ignored for future requests even when this property is not provided. - * Tagging as Ignore as this is an internal value and is not expected to be used outside of the SDK - * @ignore - */ -exports.DisabledPropertyName = "Microsoft_ApplicationInsights_BypassAjaxInstrumentation"; -exports.SampleRate = "sampleRate"; -exports.ProcessLegacy = "ProcessLegacy"; -exports.HttpMethod = "http.method"; -exports.DEFAULT_BREEZE_ENDPOINT = "https://dc.services.visualstudio.com"; -exports.DEFAULT_BREEZE_PATH = "/v2/track"; -exports.strNotSpecified = "not_specified"; -exports.strIkey = "iKey"; diff --git a/shared/AppInsightsCommon/src/DomHelperFuncs.js b/shared/AppInsightsCommon/src/DomHelperFuncs.js deleted file mode 100644 index f3b24f2a0..000000000 --- a/shared/AppInsightsCommon/src/DomHelperFuncs.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createDomEvent = createDomEvent; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); -function createDomEvent(eventName) { - var event = null; - if ((0, applicationinsights_core_js_1.isFunction)(Event)) { // Use Event constructor when available - event = new Event(eventName); - } - else { // Event has no constructor in IE - var doc = (0, applicationinsights_core_js_1.getDocument)(); - if (doc && doc.createEvent) { - event = doc.createEvent("Event"); - event.initEvent(eventName, true, true); - } - } - return event; -} diff --git a/shared/AppInsightsCommon/src/Enums.js b/shared/AppInsightsCommon/src/Enums.js deleted file mode 100644 index 312b69173..000000000 --- a/shared/AppInsightsCommon/src/Enums.js +++ /dev/null @@ -1,28 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.EventPersistence = exports.DistributedTracingModes = exports.StorageType = void 0; -var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); -exports.StorageType = (0, applicationinsights_core_js_1.createEnumStyle)({ - LocalStorage: 0 /* eStorageType.LocalStorage */, - SessionStorage: 1 /* eStorageType.SessionStorage */ -}); -exports.DistributedTracingModes = (0, applicationinsights_core_js_1.createEnumStyle)({ - AI: 0 /* eDistributedTracingModes.AI */, - AI_AND_W3C: 1 /* eDistributedTracingModes.AI_AND_W3C */, - W3C: 2 /* eDistributedTracingModes.W3C */ -}); -/** - * The EventPersistence contains a set of values that specify the event's persistence. - */ -exports.EventPersistence = (0, applicationinsights_core_js_1.createEnumStyle)({ - /** - * Normal persistence. - */ - Normal: 1 /* EventPersistenceValue.Normal */, - /** - * Critical persistence. - */ - Critical: 2 /* EventPersistenceValue.Critical */ -}); diff --git a/shared/AppInsightsCommon/src/HelperFuncs.js b/shared/AppInsightsCommon/src/HelperFuncs.js deleted file mode 100644 index 787e4c068..000000000 --- a/shared/AppInsightsCommon/src/HelperFuncs.js +++ /dev/null @@ -1,50 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.stringToBoolOrDefault = stringToBoolOrDefault; -exports.msToTimeSpan = msToTimeSpan; -exports.getExtensionByName = getExtensionByName; -exports.isCrossOriginError = isCrossOriginError; -var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); -var ts_utils_1 = require("@nevware21/ts-utils"); -var strEmpty = ""; -function stringToBoolOrDefault(str, defaultValue) { - if (defaultValue === void 0) { defaultValue = false; } - if (str === undefined || str === null) { - return defaultValue; - } - return str.toString().toLowerCase() === "true"; -} -/** - * Convert ms to c# time span format - */ -function msToTimeSpan(totalms) { - if (isNaN(totalms) || totalms < 0) { - totalms = 0; - } - totalms = (0, ts_utils_1.mathRound)(totalms); - var ms = strEmpty + totalms % 1000; - var sec = strEmpty + (0, ts_utils_1.mathFloor)(totalms / 1000) % 60; - var min = strEmpty + (0, ts_utils_1.mathFloor)(totalms / (1000 * 60)) % 60; - var hour = strEmpty + (0, ts_utils_1.mathFloor)(totalms / (1000 * 60 * 60)) % 24; - var days = (0, ts_utils_1.mathFloor)(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 + "." : strEmpty) + hour + ":" + min + ":" + sec + "." + ms; -} -function getExtensionByName(extensions, identifier) { - var extension = null; - (0, applicationinsights_core_js_1.arrForEach)(extensions, function (value) { - if (value.identifier === identifier) { - extension = value; - return -1; - } - }); - return extension; -} -function isCrossOriginError(message, url, lineNumber, columnNumber, error) { - return !error && (0, applicationinsights_core_js_1.isString)(message) && (message === "Script error." || message === "Script error"); -} diff --git a/shared/AppInsightsCommon/src/Interfaces/ConnectionString.js b/shared/AppInsightsCommon/src/Interfaces/ConnectionString.js deleted file mode 100644 index c8ad2e549..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/ConnectionString.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IApplication.js b/shared/AppInsightsCommon/src/Interfaces/Context/IApplication.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Context/IApplication.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IDevice.js b/shared/AppInsightsCommon/src/Interfaces/Context/IDevice.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Context/IDevice.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IInternal.js b/shared/AppInsightsCommon/src/Interfaces/Context/IInternal.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Context/IInternal.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/ILocation.js b/shared/AppInsightsCommon/src/Interfaces/Context/ILocation.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Context/ILocation.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IOperatingSystem.js b/shared/AppInsightsCommon/src/Interfaces/Context/IOperatingSystem.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Context/IOperatingSystem.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/ISample.js b/shared/AppInsightsCommon/src/Interfaces/Context/ISample.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Context/ISample.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/ISession.js b/shared/AppInsightsCommon/src/Interfaces/Context/ISession.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Context/ISession.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/ISessionManager.js b/shared/AppInsightsCommon/src/Interfaces/Context/ISessionManager.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Context/ISessionManager.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/ITelemetryTrace.js b/shared/AppInsightsCommon/src/Interfaces/Context/ITelemetryTrace.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Context/ITelemetryTrace.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IUser.js b/shared/AppInsightsCommon/src/Interfaces/Context/IUser.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Context/IUser.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Context/IWeb.js b/shared/AppInsightsCommon/src/Interfaces/Context/IWeb.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Context/IWeb.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/AvailabilityData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/AvailabilityData.js deleted file mode 100644 index 49f67e643..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/AvailabilityData.js +++ /dev/null @@ -1,47 +0,0 @@ -"use strict"; -// // Copyright (c) Microsoft Corporation. All rights reserved. -// // Licensed under the MIT License. -// // THIS FILE WAS AUTOGENERATED -// import { Domain } from "./Domain"; -// "use strict"; -// /** -// * Instances of AvailabilityData represent the result of executing an availability test. -// */ -// export class AvailabilityData implements Domain { -// /** -// * Schema version -// */ -// public ver: number = 2; -// /** -// * Identifier of a test run. Use it to correlate steps of test run and telemetry generated by the service. -// */ -// public id: string; -// /** -// * Name of the test that these availability results represent. -// */ -// public name: string; -// /** -// * Duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. -// */ -// public duration: string; -// /** -// * Success flag. -// */ -// public success: boolean; -// /** -// * Name of the location where the test was run from. -// */ -// public runLocation: string; -// /** -// * Diagnostic message for the result. -// */ -// public message: string; -// /** -// * Collection of custom properties. -// */ -// public properties: any = {}; -// /** -// * Collection of custom measurements. -// */ -// public measurements: any = {}; -// } diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/ContextTagKeys.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/ContextTagKeys.js deleted file mode 100644 index bf51992e7..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/ContextTagKeys.js +++ /dev/null @@ -1,101 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ContextTagKeys = void 0; -var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); -function _aiNameFunc(baseName) { - var aiName = "ai." + baseName + "."; - return function (name) { - return aiName + name; - }; -} -var _aiApplication = _aiNameFunc("application"); -var _aiDevice = _aiNameFunc("device"); -var _aiLocation = _aiNameFunc("location"); -var _aiOperation = _aiNameFunc("operation"); -var _aiSession = _aiNameFunc("session"); -var _aiUser = _aiNameFunc("user"); -var _aiCloud = _aiNameFunc("cloud"); -var _aiInternal = _aiNameFunc("internal"); -var ContextTagKeys = /** @class */ (function (_super) { - __extends(ContextTagKeys, _super); - function ContextTagKeys() { - return _super.call(this) || this; - } - return ContextTagKeys; -}((0, applicationinsights_core_js_1.createClassFromInterface)({ - applicationVersion: _aiApplication("ver"), - applicationBuild: _aiApplication("build"), - applicationTypeId: _aiApplication("typeId"), - applicationId: _aiApplication("applicationId"), - applicationLayer: _aiApplication("layer"), - deviceId: _aiDevice("id"), - deviceIp: _aiDevice("ip"), - deviceLanguage: _aiDevice("language"), - deviceLocale: _aiDevice("locale"), - deviceModel: _aiDevice("model"), - deviceFriendlyName: _aiDevice("friendlyName"), - deviceNetwork: _aiDevice("network"), - deviceNetworkName: _aiDevice("networkName"), - deviceOEMName: _aiDevice("oemName"), - deviceOS: _aiDevice("os"), - deviceOSVersion: _aiDevice("osVersion"), - deviceRoleInstance: _aiDevice("roleInstance"), - deviceRoleName: _aiDevice("roleName"), - deviceScreenResolution: _aiDevice("screenResolution"), - deviceType: _aiDevice("type"), - deviceMachineName: _aiDevice("machineName"), - deviceVMName: _aiDevice("vmName"), - deviceBrowser: _aiDevice("browser"), - deviceBrowserVersion: _aiDevice("browserVersion"), - locationIp: _aiLocation("ip"), - locationCountry: _aiLocation("country"), - locationProvince: _aiLocation("province"), - locationCity: _aiLocation("city"), - operationId: _aiOperation("id"), - operationName: _aiOperation("name"), - operationParentId: _aiOperation("parentId"), - operationRootId: _aiOperation("rootId"), - operationSyntheticSource: _aiOperation("syntheticSource"), - operationCorrelationVector: _aiOperation("correlationVector"), - sessionId: _aiSession("id"), - sessionIsFirst: _aiSession("isFirst"), - sessionIsNew: _aiSession("isNew"), - userAccountAcquisitionDate: _aiUser("accountAcquisitionDate"), - userAccountId: _aiUser("accountId"), - userAgent: _aiUser("userAgent"), - userId: _aiUser("id"), - userStoreRegion: _aiUser("storeRegion"), - userAuthUserId: _aiUser("authUserId"), - userAnonymousUserAcquisitionDate: _aiUser("anonUserAcquisitionDate"), - userAuthenticatedUserAcquisitionDate: _aiUser("authUserAcquisitionDate"), - cloudName: _aiCloud("name"), - cloudRole: _aiCloud("role"), - cloudRoleVer: _aiCloud("roleVer"), - cloudRoleInstance: _aiCloud("roleInstance"), - cloudEnvironment: _aiCloud("environment"), - cloudLocation: _aiCloud("location"), - cloudDeploymentUnit: _aiCloud("deploymentUnit"), - internalNodeName: _aiInternal("nodeName"), - internalSdkVersion: _aiInternal("sdkVersion"), - internalAgentVersion: _aiInternal("agentVersion"), - internalSnippet: _aiInternal("snippet"), - internalSdkSrc: _aiInternal("sdkSrc") -}))); -exports.ContextTagKeys = ContextTagKeys; diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/DataPointType.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/DataPointType.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/DataPointType.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/DependencyKind.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/DependencyKind.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/DependencyKind.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/DependencySourceType.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/DependencySourceType.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/DependencySourceType.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IBase.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IBase.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/IBase.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IData.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/IData.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IDataPoint.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IDataPoint.js deleted file mode 100644 index c8ad2e549..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/IDataPoint.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IDomain.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IDomain.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/IDomain.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IEnvelope.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IEnvelope.js deleted file mode 100644 index fabeadf18..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/IEnvelope.js +++ /dev/null @@ -1,41 +0,0 @@ -"use strict"; -// // Copyright (c) Microsoft Corporation. All rights reserved. -// // Licensed under the MIT License. -// import { IBase } from "./IBase"; -// /** -// * System variables for a telemetry item. -// */ -// export interface IEnvelope { -// /** -// * Envelope version. For internal use only. By assigning this the default, it will not be serialized within the payload unless changed to a value other than #1. -// */ -// ver: number; /* 1 */ -// /** -// * Type name of telemetry data item. -// */ -// name: string; -// /** -// * Event date time when telemetry item was created. This is the wall clock time on the client when the event was generated. There is no guarantee that the client's time is accurate. This field must be formatted in UTC ISO 8601 format, with a trailing 'Z' character, as described publicly on https://en.wikipedia.org/wiki/ISO_8601#UTC. Note: the number of decimal seconds digits provided are variable (and unspecified). Consumers should handle this, i.e. managed code consumers should not use format 'O' for parsing as it specifies a fixed length. Example: 2009-06-15T13:45:30.0000000Z. -// */ -// time: string; -// /** -// * Sampling rate used in application. This telemetry item represents 1 / sampleRate actual telemetry items. -// */ -// sampleRate: number; /* 100.0 */ -// /** -// * Sequence field used to track absolute order of uploaded events. -// */ -// seq: string; -// /** -// * The application's instrumentation key. The key is typically represented as a GUID, but there are cases when it is not a guid. No code should rely on iKey being a GUID. Instrumentation key is case insensitive. -// */ -// iKey: string; -// /** -// * Key/value collection of context properties. See ContextTagKeys for information on available properties. -// */ -// tags: any; /* {} */ -// /** -// * Telemetry data item. -// */ -// data: IBase; -// } diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IEventData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IEventData.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/IEventData.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IExceptionData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IExceptionData.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/IExceptionData.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IExceptionDetails.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IExceptionDetails.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/IExceptionDetails.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IMessageData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IMessageData.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/IMessageData.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IMetricData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IMetricData.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/IMetricData.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IPageViewData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IPageViewData.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/IPageViewData.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IPageViewPerfData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IPageViewPerfData.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/IPageViewPerfData.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IRemoteDependencyData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IRemoteDependencyData.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/IRemoteDependencyData.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/IStackFrame.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/IStackFrame.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/IStackFrame.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/RequestData.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/RequestData.js deleted file mode 100644 index c55d93431..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/RequestData.js +++ /dev/null @@ -1,41 +0,0 @@ -"use strict"; -// // Copyright (c) Microsoft Corporation. All rights reserved. -// // Licensed under the MIT License. -// import { IDomain } from "./IDomain"; -// /** -// * An instance of Request represents completion of an external request to the application to do work and contains a summary of that request execution and the results. -// */ -// export class RequestData implements IDomain { -// /** -// * Schema version -// */ -// public ver: number = 2; -// /** -// * Identifier of a request call instance. Used for correlation between request and other telemetry items. -// */ -// public id: string; -// /** -// * Source of the request. Examples are the instrumentation key of the caller or the ip address of the caller. -// */ -// public source: string; -// /** -// * Name of the request. Represents code path taken to process request. Low cardinality value to allow better grouping of requests. For HTTP requests it represents the HTTP method and URL path template like 'GET /values/{id}'. -// */ -// public name: string; -// /** -// * Indication of successful or unsuccessful call. -// */ -// public success: boolean; -// /** -// * Request URL with all query string parameters. -// */ -// public url: string; -// /** -// * Collection of custom properties. -// */ -// public properties: any = {}; -// /** -// * Collection of custom measurements. -// */ -// public measurements: any = {}; -// } diff --git a/shared/AppInsightsCommon/src/Interfaces/Contracts/SeverityLevel.js b/shared/AppInsightsCommon/src/Interfaces/Contracts/SeverityLevel.js deleted file mode 100644 index 8dc647530..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Contracts/SeverityLevel.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SeverityLevel = void 0; -var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); -/** - * Defines the level of severity for the event. - */ -exports.SeverityLevel = (0, applicationinsights_core_js_1.createEnumStyle)({ - Verbose: 0 /* eSeverityLevel.Verbose */, - Information: 1 /* eSeverityLevel.Information */, - Warning: 2 /* eSeverityLevel.Warning */, - Error: 3 /* eSeverityLevel.Error */, - Critical: 4 /* eSeverityLevel.Critical */ -}); diff --git a/shared/AppInsightsCommon/src/Interfaces/IAppInsights.js b/shared/AppInsightsCommon/src/Interfaces/IAppInsights.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/IAppInsights.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IConfig.js b/shared/AppInsightsCommon/src/Interfaces/IConfig.js deleted file mode 100644 index 40b392795..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/IConfig.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConfigurationManager = void 0; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); -var ConfigurationManager = /** @class */ (function () { - function ConfigurationManager() { - } - ConfigurationManager.getConfig = function (config, field, identifier, defaultValue) { - if (defaultValue === void 0) { defaultValue = false; } - var configValue; - if (identifier && config.extensionConfig && config.extensionConfig[identifier] && !(0, applicationinsights_core_js_1.isNullOrUndefined)(config.extensionConfig[identifier][field])) { - configValue = config.extensionConfig[identifier][field]; - } - else { - configValue = config[field]; - } - return !(0, applicationinsights_core_js_1.isNullOrUndefined)(configValue) ? configValue : defaultValue; - }; - return ConfigurationManager; -}()); -exports.ConfigurationManager = ConfigurationManager; diff --git a/shared/AppInsightsCommon/src/Interfaces/ICorrelationConfig.js b/shared/AppInsightsCommon/src/Interfaces/ICorrelationConfig.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/ICorrelationConfig.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IDependencyTelemetry.js b/shared/AppInsightsCommon/src/Interfaces/IDependencyTelemetry.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/IDependencyTelemetry.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IEventTelemetry.js b/shared/AppInsightsCommon/src/Interfaces/IEventTelemetry.js deleted file mode 100644 index c8ad2e549..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/IEventTelemetry.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IExceptionTelemetry.js b/shared/AppInsightsCommon/src/Interfaces/IExceptionTelemetry.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/IExceptionTelemetry.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IMetricTelemetry.js b/shared/AppInsightsCommon/src/Interfaces/IMetricTelemetry.js deleted file mode 100644 index c8ad2e549..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/IMetricTelemetry.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IPageViewPerformanceTelemetry.js b/shared/AppInsightsCommon/src/Interfaces/IPageViewPerformanceTelemetry.js deleted file mode 100644 index c8ad2e549..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/IPageViewPerformanceTelemetry.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IPageViewTelemetry.js b/shared/AppInsightsCommon/src/Interfaces/IPageViewTelemetry.js deleted file mode 100644 index c8ad2e549..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/IPageViewTelemetry.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IPartC.js b/shared/AppInsightsCommon/src/Interfaces/IPartC.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/IPartC.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IPropertiesPlugin.js b/shared/AppInsightsCommon/src/Interfaces/IPropertiesPlugin.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/IPropertiesPlugin.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IRequestContext.js b/shared/AppInsightsCommon/src/Interfaces/IRequestContext.js deleted file mode 100644 index c8ad2e549..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/IRequestContext.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IStorageBuffer.js b/shared/AppInsightsCommon/src/Interfaces/IStorageBuffer.js deleted file mode 100644 index c8ad2e549..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/IStorageBuffer.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/ITelemetryContext.js b/shared/AppInsightsCommon/src/Interfaces/ITelemetryContext.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/ITelemetryContext.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/IThrottleMgr.js b/shared/AppInsightsCommon/src/Interfaces/IThrottleMgr.js deleted file mode 100644 index c8ad2e549..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/IThrottleMgr.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/ITraceTelemetry.js b/shared/AppInsightsCommon/src/Interfaces/ITraceTelemetry.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/ITraceTelemetry.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/PartAExtensions.js b/shared/AppInsightsCommon/src/Interfaces/PartAExtensions.js deleted file mode 100644 index 001937f25..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/PartAExtensions.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CtxTagKeys = exports.Extensions = void 0; -var ContextTagKeys_1 = require("./Contracts/ContextTagKeys"); -exports.Extensions = { - UserExt: "user", - DeviceExt: "device", - TraceExt: "trace", - WebExt: "web", - AppExt: "app", - OSExt: "os", - SessionExt: "ses", - SDKExt: "sdk" -}; -exports.CtxTagKeys = new ContextTagKeys_1.ContextTagKeys(); diff --git a/shared/AppInsightsCommon/src/Interfaces/Telemetry/IEnvelope.js b/shared/AppInsightsCommon/src/Interfaces/Telemetry/IEnvelope.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Telemetry/IEnvelope.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Interfaces/Telemetry/ISerializable.js b/shared/AppInsightsCommon/src/Interfaces/Telemetry/ISerializable.js deleted file mode 100644 index ea6e29471..000000000 --- a/shared/AppInsightsCommon/src/Interfaces/Telemetry/ISerializable.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/shared/AppInsightsCommon/src/Offline.js b/shared/AppInsightsCommon/src/Offline.js deleted file mode 100644 index 5ecb17f98..000000000 --- a/shared/AppInsightsCommon/src/Offline.js +++ /dev/null @@ -1,135 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createOfflineListener = createOfflineListener; -var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); -function _disableEvents(target, evtNamespace) { - (0, applicationinsights_core_js_1.eventOff)(target, null, null, evtNamespace); -} -/** - * Create a new OfflineListener instance to monitor browser online / offline events - * @param parentEvtNamespace - The parent event namespace to append to any specific events for this instance - */ -function createOfflineListener(parentEvtNamespace) { - var _document = (0, applicationinsights_core_js_1.getDocument)(); - var _navigator = (0, applicationinsights_core_js_1.getNavigator)(); // Gets the window.navigator or workerNavigator depending on the global - var _isListening = false; - var listenerList = []; - // Set the initial state - // rState is changed by the browser, both via events and when we check the navigator.onLine property - var rState = 1 /* eOfflineValue.Online */; - if (_navigator && !(0, applicationinsights_core_js_1.isNullOrUndefined)(_navigator.onLine) && !_navigator.onLine) { // navigator.onLine is undefined in react-native - rState = 2 /* eOfflineValue.Offline */; - } - // ustate is changed by the user calling setOnlineState - var uState = 0 /* eOfflineValue.Unknown */; - // current state would be updated each time rState or uState is changed - // it is a resolved value of rState and uState - var _currentState = calCurrentState(); - var _evtNamespace = (0, applicationinsights_core_js_1.mergeEvtNamespace)((0, applicationinsights_core_js_1.createUniqueNamespace)("OfflineListener"), parentEvtNamespace); - try { - if (_enableEvents((0, applicationinsights_core_js_1.getWindow)())) { - _isListening = true; - } - if (_document) { - // Also attach to the document.body or document - var target = _document.body || _document; - if (target.ononline) { - if (_enableEvents(target)) { - _isListening = true; - } - } - } - } - catch (e) { - // this makes react-native less angry - _isListening = false; - } - function _enableEvents(target) { - var enabled = false; - if (target) { - enabled = (0, applicationinsights_core_js_1.eventOn)(target, "online", _setOnline, _evtNamespace); - if (enabled) { - (0, applicationinsights_core_js_1.eventOn)(target, "offline", _setOffline, _evtNamespace); - } - } - return enabled; - } - function _isOnline() { - return _currentState; - } - function calCurrentState() { - if (uState === 2 /* eOfflineValue.Offline */ || rState === 2 /* eOfflineValue.Offline */) { - return false; - } - return true; // if both unknown, then we assume the network is good - } - function listnerNoticeCheck() { - // we were offline and are now online or we were online and now offline - var newState = calCurrentState(); - if (_currentState !== newState) { - _currentState = newState; // use the resolved state to update - // send all the callbacks with the current state - (0, applicationinsights_core_js_1.arrForEach)(listenerList, function (callback) { - var offlineState = { - isOnline: _currentState, - rState: rState, - uState: uState - }; - try { - callback(offlineState); - } - catch (e) { - // Do nothing, just making sure we run all of the callbacks - } - }); - } - } - function setOnlineState(newState) { - uState = newState; - listnerNoticeCheck(); - } - function _setOnline() { - rState = 1 /* eOfflineValue.Online */; - listnerNoticeCheck(); - } - function _setOffline() { - rState = 2 /* eOfflineValue.Offline */; - listnerNoticeCheck(); - } - function _unload() { - var win = (0, applicationinsights_core_js_1.getWindow)(); - if (win && _isListening) { - _disableEvents(win, _evtNamespace); - if (_document) { - // Also attach to the document.body or document - var target = _document.body || _document; - if (!(0, applicationinsights_core_js_1.isUndefined)(target.ononline)) { - _disableEvents(target, _evtNamespace); - } - } - _isListening = false; - } - } - function addListener(callback) { - listenerList.push(callback); - // Define rm as an instance of IUnloadHook - return { - rm: function () { - var index = listenerList.indexOf(callback); - if (index > -1) { - return listenerList.splice(index, 1); - } - else { - return; - } - } - }; - } - return { - isOnline: _isOnline, - isListening: function () { return _isListening; }, - unload: _unload, - addListener: addListener, - setOnlineState: setOnlineState - }; -} diff --git a/shared/AppInsightsCommon/src/RequestResponseHeaders.js b/shared/AppInsightsCommon/src/RequestResponseHeaders.js deleted file mode 100644 index af3e1a6ed..000000000 --- a/shared/AppInsightsCommon/src/RequestResponseHeaders.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RequestHeaders = void 0; -var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); -exports.RequestHeaders = (0, applicationinsights_core_js_1.createValueMap)({ - requestContextHeader: [0 /* eRequestHeaders.requestContextHeader */, "Request-Context"], - requestContextTargetKey: [1 /* eRequestHeaders.requestContextTargetKey */, "appId"], - requestContextAppIdFormat: [2 /* eRequestHeaders.requestContextAppIdFormat */, "appId=cid-v1:"], - requestIdHeader: [3 /* eRequestHeaders.requestIdHeader */, "Request-Id"], - traceParentHeader: [4 /* eRequestHeaders.traceParentHeader */, "traceparent"], - traceStateHeader: [5 /* eRequestHeaders.traceStateHeader */, "tracestate"], // currently not used - sdkContextHeader: [6 /* eRequestHeaders.sdkContextHeader */, "Sdk-Context"], - sdkContextHeaderAppIdRequest: [7 /* eRequestHeaders.sdkContextHeaderAppIdRequest */, "appId"], - requestContextHeaderLowerCase: [8 /* eRequestHeaders.requestContextHeaderLowerCase */, "request-context"] -}); diff --git a/shared/AppInsightsCommon/src/StorageHelperFuncs.js b/shared/AppInsightsCommon/src/StorageHelperFuncs.js deleted file mode 100644 index dab70bdec..000000000 --- a/shared/AppInsightsCommon/src/StorageHelperFuncs.js +++ /dev/null @@ -1,249 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.utlDisableStorage = utlDisableStorage; -exports.utlSetStoragePrefix = utlSetStoragePrefix; -exports.utlEnableStorage = utlEnableStorage; -exports.utlCanUseLocalStorage = utlCanUseLocalStorage; -exports.utlGetLocalStorage = utlGetLocalStorage; -exports.utlSetLocalStorage = utlSetLocalStorage; -exports.utlRemoveStorage = utlRemoveStorage; -exports.utlCanUseSessionStorage = utlCanUseSessionStorage; -exports.utlGetSessionStorageKeys = utlGetSessionStorageKeys; -exports.utlGetSessionStorage = utlGetSessionStorage; -exports.utlSetSessionStorage = utlSetSessionStorage; -exports.utlRemoveSessionStorage = utlRemoveSessionStorage; -var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); -var ts_utils_1 = require("@nevware21/ts-utils"); -var Enums_1 = require("./Enums"); -var _canUseLocalStorage = undefined; -var _canUseSessionStorage = undefined; -var _storagePrefix = ""; -/** - * Gets the localStorage object if available - * @returns {Storage} - Returns the storage object if available else returns null - */ -function _getLocalStorageObject() { - if (utlCanUseLocalStorage()) { - return _getVerifiedStorageObject(Enums_1.StorageType.LocalStorage); - } - return null; -} -/** - * Safely checks if storage object (localStorage or sessionStorage) is available and accessible - * This helps prevent SecurityError in some browsers (e.g., Safari) when cookies are blocked - * @param storageType - Type of storage - * @returns {boolean} Returns whether storage object is safely accessible - */ -function _canSafelyAccessStorage(storageType) { - var storageTypeName = storageType === Enums_1.StorageType.LocalStorage ? "localStorage" : "sessionStorage"; - var result = true; - try { - // First, check if window exists and get the global object once - var gbl = (0, applicationinsights_core_js_1.getGlobal)(); - if ((0, applicationinsights_core_js_1.isNullOrUndefined)(gbl)) { - result = false; - } - else { - // Try to indirectly check if the property exists and is accessible - // This avoids direct property access that might throw in Safari with "Block All Cookies" enabled - // Some browsers throw when accessing the property descriptors with getOwnPropertyDescriptor - // Others throw when directly accessing the storage objects - // This approach tries both methods safely - try { - // Method 1: Try using property descriptor - safer in Safari with cookies blocked - var descriptor = (0, ts_utils_1.objGetOwnPropertyDescriptor)(gbl, storageTypeName); - if (!descriptor || !descriptor.get) { - result = false; - } - } - catch (e) { - // If the above fails, attempt a direct access inside a try-catch - try { - var storage = gbl[storageTypeName]; - if (!storage) { - result = false; - } - } - catch (e) { - // If both approaches fail, storage cannot be safely accessed - result = false; - } - } - } - } - catch (e) { - result = false; - } - return result; -} -/** - * 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 - * @returns {Storage} Returns storage object verified that it is usable - */ -function _getVerifiedStorageObject(storageType) { - var result = null; - try { - // First check if we can safely access the storage object - if (_canSafelyAccessStorage(storageType)) { - var storageTypeName = storageType === Enums_1.StorageType.LocalStorage ? "localStorage" : "sessionStorage"; - // Now we can safely try to use the storage - try { - var uid = (new Date).toString(); - var storage = (0, applicationinsights_core_js_1.getGlobalInst)(storageTypeName); - var name_1 = _storagePrefix + uid; - storage.setItem(name_1, uid); - var fail = storage.getItem(name_1) !== uid; - storage.removeItem(name_1); - if (!fail) { - result = storage; - } - } - catch (exception) { - // Storage exists but can't be used (quota exceeded, etc.) - } - } - } - catch (exception) { - // Catch any unexpected errors - } - return result; -} -/** - * Gets the sessionStorage object if available - * @returns {Storage} - Returns the storage object if available else returns null - */ -function _getSessionStorageObject() { - if (utlCanUseSessionStorage()) { - return _getVerifiedStorageObject(Enums_1.StorageType.SessionStorage); - } - return null; -} -/** - * Disables the global SDK usage of local or session storage if available - */ -function utlDisableStorage() { - _canUseLocalStorage = false; - _canUseSessionStorage = false; -} -function utlSetStoragePrefix(storagePrefix) { - _storagePrefix = storagePrefix || ""; -} -/** - * Re-enables the global SDK usage of local or session storage if available - */ -function utlEnableStorage() { - _canUseLocalStorage = utlCanUseLocalStorage(true); - _canUseSessionStorage = utlCanUseSessionStorage(true); -} -/** - * Returns whether LocalStorage can be used, if the reset parameter is passed a true this will override - * any previous disable calls. - * @param reset - Should the usage be reset and determined only based on whether LocalStorage is available - */ -function utlCanUseLocalStorage(reset) { - if (reset || _canUseLocalStorage === undefined) { - _canUseLocalStorage = !!_getVerifiedStorageObject(Enums_1.StorageType.LocalStorage); - } - return _canUseLocalStorage; -} -function utlGetLocalStorage(logger, name) { - var storage = _getLocalStorageObject(); - if (storage !== null) { - try { - return storage.getItem(name); - } - catch (e) { - _canUseLocalStorage = false; - (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.BrowserCannotReadLocalStorage, "Browser failed read of local storage. " + (0, applicationinsights_core_js_1.getExceptionName)(e), { exception: (0, applicationinsights_core_js_1.dumpObj)(e) }); - } - } - return null; -} -function utlSetLocalStorage(logger, name, data) { - var storage = _getLocalStorageObject(); - if (storage !== null) { - try { - storage.setItem(name, data); - return true; - } - catch (e) { - _canUseLocalStorage = false; - (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.BrowserCannotWriteLocalStorage, "Browser failed write to local storage. " + (0, applicationinsights_core_js_1.getExceptionName)(e), { exception: (0, applicationinsights_core_js_1.dumpObj)(e) }); - } - } - return false; -} -function utlRemoveStorage(logger, name) { - var storage = _getLocalStorageObject(); - if (storage !== null) { - try { - storage.removeItem(name); - return true; - } - catch (e) { - _canUseLocalStorage = false; - (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.BrowserFailedRemovalFromLocalStorage, "Browser failed removal of local storage item. " + (0, applicationinsights_core_js_1.getExceptionName)(e), { exception: (0, applicationinsights_core_js_1.dumpObj)(e) }); - } - } - return false; -} -function utlCanUseSessionStorage(reset) { - if (reset || _canUseSessionStorage === undefined) { - _canUseSessionStorage = !!_getVerifiedStorageObject(Enums_1.StorageType.SessionStorage); - } - return _canUseSessionStorage; -} -function utlGetSessionStorageKeys() { - var keys = []; - if (utlCanUseSessionStorage()) { - (0, applicationinsights_core_js_1.objForEachKey)((0, applicationinsights_core_js_1.getGlobalInst)("sessionStorage"), function (key) { - keys.push(key); - }); - } - return keys; -} -function utlGetSessionStorage(logger, name) { - var storage = _getSessionStorageObject(); - if (storage !== null) { - try { - return storage.getItem(name); - } - catch (e) { - _canUseSessionStorage = false; - (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.BrowserCannotReadSessionStorage, "Browser failed read of session storage. " + (0, applicationinsights_core_js_1.getExceptionName)(e), { exception: (0, applicationinsights_core_js_1.dumpObj)(e) }); - } - } - return null; -} -function utlSetSessionStorage(logger, name, data) { - var storage = _getSessionStorageObject(); - if (storage !== null) { - try { - storage.setItem(name, data); - return true; - } - catch (e) { - _canUseSessionStorage = false; - (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.BrowserCannotWriteSessionStorage, "Browser failed write to session storage. " + (0, applicationinsights_core_js_1.getExceptionName)(e), { exception: (0, applicationinsights_core_js_1.dumpObj)(e) }); - } - } - return false; -} -function utlRemoveSessionStorage(logger, name) { - var storage = _getSessionStorageObject(); - if (storage !== null) { - try { - storage.removeItem(name); - return true; - } - catch (e) { - _canUseSessionStorage = false; - (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.BrowserFailedRemovalFromSessionStorage, "Browser failed removal of session storage item. " + (0, applicationinsights_core_js_1.getExceptionName)(e), { exception: (0, applicationinsights_core_js_1.dumpObj)(e) }); - } - } - return false; -} diff --git a/shared/AppInsightsCommon/src/Telemetry/Common/Data.js b/shared/AppInsightsCommon/src/Telemetry/Common/Data.js deleted file mode 100644 index 9465d2ced..000000000 --- a/shared/AppInsightsCommon/src/Telemetry/Common/Data.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Data = void 0; -var Data = /** @class */ (function () { - /** - * Constructs a new instance of telemetry data. - */ - function Data(baseType, data) { - /** - * The data contract for serializing this object. - */ - this.aiDataContract = { - baseType: 1 /* FieldType.Required */, - baseData: 1 /* FieldType.Required */ - }; - this.baseType = baseType; - this.baseData = data; - } - return Data; -}()); -exports.Data = Data; diff --git a/shared/AppInsightsCommon/src/Telemetry/Common/DataPoint.js b/shared/AppInsightsCommon/src/Telemetry/Common/DataPoint.js deleted file mode 100644 index 67b0eaeee..000000000 --- a/shared/AppInsightsCommon/src/Telemetry/Common/DataPoint.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DataPoint = void 0; -var DataPoint = /** @class */ (function () { - function DataPoint() { - /** - * The data contract for serializing this object. - */ - this.aiDataContract = { - name: 1 /* FieldType.Required */, - kind: 0 /* FieldType.Default */, - value: 1 /* FieldType.Required */, - count: 0 /* FieldType.Default */, - min: 0 /* FieldType.Default */, - max: 0 /* FieldType.Default */, - stdDev: 0 /* FieldType.Default */ - }; - /** - * Metric type. Single measurement or the aggregated value. - */ - this.kind = 0 /* DataPointType.Measurement */; - } - return DataPoint; -}()); -exports.DataPoint = DataPoint; diff --git a/shared/AppInsightsCommon/src/Telemetry/Common/DataSanitizer.js b/shared/AppInsightsCommon/src/Telemetry/Common/DataSanitizer.js deleted file mode 100644 index 9fbd92593..000000000 --- a/shared/AppInsightsCommon/src/Telemetry/Common/DataSanitizer.js +++ /dev/null @@ -1,133 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.dataSanitizeKeyAndAddUniqueness = dataSanitizeKeyAndAddUniqueness; -exports.dataSanitizeKey = dataSanitizeKey; -exports.dataSanitizeString = dataSanitizeString; -exports.dataSanitizeUrl = dataSanitizeUrl; -exports.dataSanitizeMessage = dataSanitizeMessage; -exports.dataSanitizeException = dataSanitizeException; -exports.dataSanitizeProperties = dataSanitizeProperties; -exports.dataSanitizeMeasurements = dataSanitizeMeasurements; -exports.dataSanitizeId = dataSanitizeId; -exports.dataSanitizeInput = dataSanitizeInput; -exports.dsPadNumber = dsPadNumber; -var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); -var ts_utils_1 = require("@nevware21/ts-utils"); -function dataSanitizeKeyAndAddUniqueness(logger, key, map) { - var origLength = key.length; - var field = dataSanitizeKey(logger, key); - // validation truncated the length. We need to add uniqueness - if (field.length !== origLength) { - var i = 0; - var uniqueField = field; - while (map[uniqueField] !== undefined) { - i++; - uniqueField = (0, ts_utils_1.strSubstring)(field, 0, 150 /* DataSanitizerValues.MAX_NAME_LENGTH */ - 3) + dsPadNumber(i); - } - field = uniqueField; - } - return field; -} -function dataSanitizeKey(logger, name) { - var nameTrunc; - if (name) { - // Remove any leading or trailing whitespace - name = (0, applicationinsights_core_js_1.strTrim)((0, ts_utils_1.asString)(name)); - // truncate the string to 150 chars - if (name.length > 150 /* DataSanitizerValues.MAX_NAME_LENGTH */) { - nameTrunc = (0, ts_utils_1.strSubstring)(name, 0, 150 /* DataSanitizerValues.MAX_NAME_LENGTH */); - (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.NameTooLong, "name is too long. It has been truncated to " + 150 /* DataSanitizerValues.MAX_NAME_LENGTH */ + " characters.", { name: name }, true); - } - } - return nameTrunc || name; -} -function dataSanitizeString(logger, value, maxLength) { - if (maxLength === void 0) { maxLength = 1024 /* DataSanitizerValues.MAX_STRING_LENGTH */; } - var valueTrunc; - if (value) { - maxLength = maxLength ? maxLength : 1024 /* DataSanitizerValues.MAX_STRING_LENGTH */; // in case default parameters dont work - value = (0, applicationinsights_core_js_1.strTrim)((0, ts_utils_1.asString)(value)); - if (value.length > maxLength) { - valueTrunc = (0, ts_utils_1.strSubstring)(value, 0, maxLength); - (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.StringValueTooLong, "string value is too long. It has been truncated to " + maxLength + " characters.", { value: value }, true); - } - } - return valueTrunc || value; -} -function dataSanitizeUrl(logger, url) { - return dataSanitizeInput(logger, url, 2048 /* DataSanitizerValues.MAX_URL_LENGTH */, applicationinsights_core_js_1._eInternalMessageId.UrlTooLong); -} -function dataSanitizeMessage(logger, message) { - var messageTrunc; - if (message) { - if (message.length > 32768 /* DataSanitizerValues.MAX_MESSAGE_LENGTH */) { - messageTrunc = (0, ts_utils_1.strSubstring)(message, 0, 32768 /* DataSanitizerValues.MAX_MESSAGE_LENGTH */); - (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.MessageTruncated, "message is too long, it has been truncated to " + 32768 /* DataSanitizerValues.MAX_MESSAGE_LENGTH */ + " characters.", { message: message }, true); - } - } - return messageTrunc || message; -} -function dataSanitizeException(logger, exception) { - var exceptionTrunc; - if (exception) { - // Make surte its a string - var value = "" + exception; - if (value.length > 32768 /* DataSanitizerValues.MAX_EXCEPTION_LENGTH */) { - exceptionTrunc = (0, ts_utils_1.strSubstring)(value, 0, 32768 /* DataSanitizerValues.MAX_EXCEPTION_LENGTH */); - (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.ExceptionTruncated, "exception is too long, it has been truncated to " + 32768 /* DataSanitizerValues.MAX_EXCEPTION_LENGTH */ + " characters.", { exception: exception }, true); - } - } - return exceptionTrunc || exception; -} -function dataSanitizeProperties(logger, properties) { - if (properties) { - var tempProps_1 = {}; - (0, applicationinsights_core_js_1.objForEachKey)(properties, function (prop, value) { - if ((0, applicationinsights_core_js_1.isObject)(value) && (0, applicationinsights_core_js_1.hasJSON)()) { - // Stringify any part C properties - try { - value = (0, applicationinsights_core_js_1.getJSON)().stringify(value); - } - catch (e) { - (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, applicationinsights_core_js_1._eInternalMessageId.CannotSerializeObjectNonSerializable, "custom property is not valid", { exception: e }, true); - } - } - value = dataSanitizeString(logger, value, 8192 /* DataSanitizerValues.MAX_PROPERTY_LENGTH */); - prop = dataSanitizeKeyAndAddUniqueness(logger, prop, tempProps_1); - tempProps_1[prop] = value; - }); - properties = tempProps_1; - } - return properties; -} -function dataSanitizeMeasurements(logger, measurements) { - if (measurements) { - var tempMeasurements_1 = {}; - (0, applicationinsights_core_js_1.objForEachKey)(measurements, function (measure, value) { - measure = dataSanitizeKeyAndAddUniqueness(logger, measure, tempMeasurements_1); - tempMeasurements_1[measure] = value; - }); - measurements = tempMeasurements_1; - } - return measurements; -} -function dataSanitizeId(logger, id) { - return id ? dataSanitizeInput(logger, id, 128 /* DataSanitizerValues.MAX_ID_LENGTH */, applicationinsights_core_js_1._eInternalMessageId.IdTooLong).toString() : id; -} -function dataSanitizeInput(logger, input, maxLength, _msgId) { - var inputTrunc; - if (input) { - input = (0, applicationinsights_core_js_1.strTrim)((0, ts_utils_1.asString)(input)); - if (input.length > maxLength) { - inputTrunc = (0, ts_utils_1.strSubstring)(input, 0, maxLength); - (0, applicationinsights_core_js_1._throwInternal)(logger, applicationinsights_core_js_1.eLoggingSeverity.WARNING, _msgId, "input is too long, it has been truncated to " + maxLength + " characters.", { data: input }, true); - } - } - return inputTrunc || input; -} -function dsPadNumber(num) { - var s = "00" + num; - return (0, ts_utils_1.strSubstr)(s, s.length - 3); -} diff --git a/shared/AppInsightsCommon/src/Telemetry/Common/Envelope.js b/shared/AppInsightsCommon/src/Telemetry/Common/Envelope.js deleted file mode 100644 index dc9c667f4..000000000 --- a/shared/AppInsightsCommon/src/Telemetry/Common/Envelope.js +++ /dev/null @@ -1,35 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Envelope = void 0; -var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); -var Constants_1 = require("../../Constants"); -var DataSanitizer_1 = require("./DataSanitizer"); -var Envelope = /** @class */ (function () { - /** - * Constructs a new instance of telemetry data. - */ - function Envelope(logger, data, name) { - var _this = this; - var _self = this; - _self.ver = 1; - _self.sampleRate = 100.0; - _self.tags = {}; - _self.name = (0, DataSanitizer_1.dataSanitizeString)(logger, name) || Constants_1.strNotSpecified; - _self.data = data; - _self.time = (0, applicationinsights_core_js_1.toISOString)(new Date()); - _self.aiDataContract = { - time: 1 /* FieldType.Required */, - iKey: 1 /* FieldType.Required */, - name: 1 /* FieldType.Required */, - sampleRate: function () { - return (_this.sampleRate === 100) ? 4 /* FieldType.Hidden */ : 1 /* FieldType.Required */; - }, - tags: 1 /* FieldType.Required */, - data: 1 /* FieldType.Required */ - }; - } - return Envelope; -}()); -exports.Envelope = Envelope; diff --git a/shared/AppInsightsCommon/src/Telemetry/Event.js b/shared/AppInsightsCommon/src/Telemetry/Event.js deleted file mode 100644 index a39a7d891..000000000 --- a/shared/AppInsightsCommon/src/Telemetry/Event.js +++ /dev/null @@ -1,29 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Event = void 0; -var Constants_1 = require("../Constants"); -var DataSanitizer_1 = require("./Common/DataSanitizer"); -var Event = /** @class */ (function () { - /** - * Constructs a new instance of the EventTelemetry object - */ - function Event(logger, name, properties, measurements) { - this.aiDataContract = { - ver: 1 /* FieldType.Required */, - name: 1 /* FieldType.Required */, - properties: 0 /* FieldType.Default */, - measurements: 0 /* FieldType.Default */ - }; - var _self = this; - _self.ver = 2; - _self.name = (0, DataSanitizer_1.dataSanitizeString)(logger, name) || Constants_1.strNotSpecified; - _self.properties = (0, DataSanitizer_1.dataSanitizeProperties)(logger, properties); - _self.measurements = (0, DataSanitizer_1.dataSanitizeMeasurements)(logger, measurements); - } - Event.envelopeType = "Microsoft.ApplicationInsights.{0}.Event"; - Event.dataType = "EventData"; - return Event; -}()); -exports.Event = Event; diff --git a/shared/AppInsightsCommon/src/Telemetry/Exception.js b/shared/AppInsightsCommon/src/Telemetry/Exception.js deleted file mode 100644 index 1b9d990d0..000000000 --- a/shared/AppInsightsCommon/src/Telemetry/Exception.js +++ /dev/null @@ -1,767 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -var __assign = (this && this.__assign) || function () { - __assign = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Exception = void 0; -exports._formatErrorCode = _formatErrorCode; -exports._createExceptionDetails = _createExceptionDetails; -exports._createExDetailsFromInterface = _createExDetailsFromInterface; -exports._extractStackFrame = _extractStackFrame; -exports._parsedFrameToInterface = _parsedFrameToInterface; -var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); -var ts_utils_1 = require("@nevware21/ts-utils"); -var Constants_1 = require("../Constants"); -var DataSanitizer_1 = require("./Common/DataSanitizer"); -// These Regex covers the following patterns -// 1. Chrome/Firefox/IE/Edge: -// at functionName (filename:lineNumber:columnNumber) -// at functionName (filename:lineNumber) -// at filename:lineNumber:columnNumber -// at filename:lineNumber -// at functionName@filename:lineNumber:columnNumber -// 2. Safari / Opera: -// functionName@filename:lineNumber:columnNumber -// functionName@filename:lineNumber -// filename:lineNumber:columnNumber -// filename:lineNumber -// Line ## of scriptname script filename:lineNumber:columnNumber -// Line ## of scriptname script filename -// 3. IE/Edge (Additional formats) -// at functionName@filename:lineNumber -var STACKFRAME_BASE_SIZE = 58; // '{"method":"","level":,"assembly":"","fileName":"","line":}'.length -/** - * Check if the string conforms to what looks like a stack frame line and not just a general message - * comment or other non-stack related info. - * - * This should be used to filter out any leading "message" lines from a stack trace, before attempting to parse - * the individual stack frames. Once you have estabilsted the start of the stack frames you can then use the - * FULL_STACK_FRAME_1, FULL_STACK_FRAME_2, FULL_STACK_FRAME_3, and EXTRACT_FILENAME to parse the individual - * stack frames to extract the method, filename, line number, and column number. - * These may still provide invalid matches, so the sequence of execution is important to avoid providing - * an invalid parsed stack. - */ -var IS_FRAME = /^\s{0,50}(from\s|at\s|Line\s{1,5}\d{1,10}\s{1,5}of|\w{1,50}@\w{1,80}|[^\(\s\n]+:[0-9\?]+(?::[0-9\?]+)?)/; -/** - * Parse a well formed stack frame with both the line and column numbers - * ---------------------------------- - * **Primary focus of the matching** - * - at functionName (filename:lineNumber:columnNumber) - * - at filename:lineNumber:columnNumber - * - at functionName@filename:lineNumber:columnNumber - * - functionName (filename:lineNumber:columnNumber) - * - filename:lineNumber:columnNumber - * - functionName@filename:lineNumber:columnNumber - */ -var FULL_STACK_FRAME_1 = /^(?:\s{0,50}at)?\s{0,50}([^\@\()\s]+)?\s{0,50}(?:\s|\@|\()\s{0,5}([^\(\s\n\]]+):([0-9\?]+):([0-9\?]+)\)?$/; -/** - * Parse a well formed stack frame with only a line number. - * ---------------------------------- - * > Note: this WILL also match with line and column number, but the line number is included with the filename - * > you should attempt to match with FULL_STACK_FRAME_1 first. - * - * **Primary focus of the matching (run FULL_STACK_FRAME_1 first)** - * - at functionName (filename:lineNumber) - * - at filename:lineNumber - * - at functionName@filename:lineNumber - * - functionName (filename:lineNumber) - * - filename:lineNumber - * - functionName@filename:lineNumber - * - * **Secondary matches** - * - at functionName (filename:lineNumber:columnNumber) - * - at filename:lineNumber:columnNumber - * - at functionName@filename:lineNumber:columnNumber - * - functionName (filename:lineNumber:columnNumber) - * - filename:lineNumber:columnNumber - * - functionName@filename:lineNumber:columnNumber - */ -var FULL_STACK_FRAME_2 = /^(?:\s{0,50}at)?\s{0,50}([^\@\()\s]+)?\s{0,50}(?:\s|\@|\()\s{0,5}([^\(\s\n\]]+):([0-9\?]+)\)?$/; -/** - * Attempt to Parse a frame that doesn't include a line or column number. - * ---------------------------------- - * > Note: this WILL also match lines with a line or line and column number, you should attempt to match with - * both FULL_STACK_FRAME_1 and FULL_STACK_FRAME_2 first to avoid false positives. - * - * **Unexpected Invalid Matches** (Matches that should be avoided -- by using the FULL_STACK_FRAME_1 and FULL_STACK_FRAME_2 first) - * - at https://localhost:44365/static/node_bundles/@microsoft/blah/js/bundle.js:144112:27 - * - at https://localhost:44365/static/node_bundles/@microsoft/blah/js/bundle.js:144112:27 - * - * **Primary focus of the matching (run FULL_STACK_FRAME_1 first)** - * - at functionName@filename - * - at functionName (filename) - * - at functionName filename - * - at filename <- Will actuall match this as the "method" and not the filename (care should be taken to avoid this) - * - functionName@filename - * - functionName (filename) - * - functionName filename - * - functionName - * - * **Secondary matches** (The line and column numbers will be included with the matched filename) - * - at functionName (filename:lineNumber:columnNumber) - * - at functionName (filename:lineNumber) - * - at filename:lineNumber:columnNumber - * - at filename:lineNumber - * - at functionName@filename:lineNumber:columnNumber - * - at functionName@filename:lineNumber - * - functionName (filename:lineNumber:columnNumber) - * - functionName (filename:lineNumber) - * - filename:lineNumber:columnNumber - * - filename:lineNumber - * - functionName@filename:lineNumber:columnNumber - * - functionName@filename:lineNumber - */ -var FULL_STACK_FRAME_3 = /^(?:\s{0,50}at)?\s{0,50}([^\@\()\s]+)?\s{0,50}(?:\s|\@|\()\s{0,5}([^\(\s\n\)\]]+)\)?$/; -/** - * Attempt to extract the filename (with or without line and column numbers) from a string. - * ---------------------------------- - * > Note: this will only match the filename (with any line or column numbers) and will - * > return what looks like the filename, however, it will also match random strings that - * > look like a filename, so care should be taken to ensure that the filename is actually - * > a filename before using it. - * > - * > It is recommended to use this in conjunction with the FULL_STACK_FRAME_1, FULL_STACK_FRAME_2, and FULL_STACK_FRAME_3 - * > to ensure first to reduce false matches, if all of these fail then you can use this to extract the filename from a random - * > strings to identify any potential filename from a known stack frame line. - * - * **Known Invalid matching** - * - * This regex will basically match any "final" string of a line or one that is trailed by a comma, so this should not - * be used as the "only" matching regex, but rather as a final fallback to extract the filename from a string. - * If you are certain that the string line is a stack frame and not part of the exception message (lines before the stack) - * or trailing comments, then you can use this to extract the filename and then further parse with PARSE_FILENAME_LINE_COL - * and PARSE_FILENAME_LINE_ONLY to extract any potential the line and column numbers. - * - * **Primary focus of the matching** - * - at (anonymous) @ VM60:1 - * - Line 21 of linked script file://localhost/C:/Temp/stacktrace.js - * - Line 11 of inline#1 script in http://localhost:3000/static/js/main.206f4846.js:2:296748 - * - Line 68 of inline#2 script in file://localhost/teststack.html - * - at Global code (http://example.com/stacktrace.js:11:1) - */ -var EXTRACT_FILENAME = /(?:^|\(|\s{0,10}[\w\)]+\@)?([^\(\n\s\]\)]+)(?:\:([0-9]+)(?:\:([0-9]+))?)?\)?(?:,|$)/; -/** - * Attempt to extract the filename, line number, and column number from a string. - */ -var PARSE_FILENAME_LINE_COL = /([^\(\s\n]+):([0-9]+):([0-9]+)$/; -/** - * Attempt to extract the filename and line number from a string. - */ -var PARSE_FILENAME_LINE_ONLY = /([^\(\s\n]+):([0-9]+)$/; -var NoMethod = ""; -var strError = "error"; -var strStack = "stack"; -var strStackDetails = "stackDetails"; -var strErrorSrc = "errorSrc"; -var strMessage = "message"; -var strDescription = "description"; -var _parseSequence = [ - { re: FULL_STACK_FRAME_1, len: 5, m: 1, fn: 2, ln: 3, col: 4 }, - { chk: _ignoreNative, pre: _scrubAnonymous, re: FULL_STACK_FRAME_2, len: 4, m: 1, fn: 2, ln: 3 }, - { re: FULL_STACK_FRAME_3, len: 3, m: 1, fn: 2, hdl: _handleFilename }, - { re: EXTRACT_FILENAME, len: 2, fn: 1, hdl: _handleFilename } -]; -function _scrubAnonymous(frame) { - return frame.replace(/(\(anonymous\))/, ""); -} -function _ignoreNative(frame) { - return (0, ts_utils_1.strIndexOf)(frame, "[native") < 0; -} -function _stringify(value, convertToString) { - var result = value; - if (result && !(0, applicationinsights_core_js_1.isString)(result)) { - if (JSON && JSON.stringify) { - result = JSON.stringify(value); - if (convertToString && (!result || result === "{}")) { - if ((0, applicationinsights_core_js_1.isFunction)(value.toString)) { - result = value.toString(); - } - else { - result = "" + value; - } - } - } - else { - result = "" + value + " - (Missing JSON.stringify)"; - } - } - return result || ""; -} -function _formatMessage(theEvent, errorType) { - var evtMessage = theEvent; - if (theEvent) { - if (evtMessage && !(0, applicationinsights_core_js_1.isString)(evtMessage)) { - evtMessage = theEvent[strMessage] || theEvent[strDescription] || evtMessage; - } - // Make sure the message is a string - if (evtMessage && !(0, applicationinsights_core_js_1.isString)(evtMessage)) { - // tslint:disable-next-line: prefer-conditional-expression - evtMessage = _stringify(evtMessage, true); - } - if (theEvent["filename"]) { - // Looks like an event object with filename - evtMessage = evtMessage + " @" + (theEvent["filename"] || "") + ":" + (theEvent["lineno"] || "?") + ":" + (theEvent["colno"] || "?"); - } - } - // Automatically add the error type to the message if it does already appear to be present - if (errorType && errorType !== "String" && errorType !== "Object" && errorType !== "Error" && (0, ts_utils_1.strIndexOf)(evtMessage || "", errorType) === -1) { - evtMessage = errorType + ": " + evtMessage; - } - return evtMessage || ""; -} -function _isExceptionDetailsInternal(value) { - try { - if ((0, applicationinsights_core_js_1.isObject)(value)) { - return "hasFullStack" in value && "typeName" in value; - } - } - catch (e) { - // This can happen with some native browser objects, but should not happen for the type we are checking for - } - return false; -} -function _isExceptionInternal(value) { - try { - if ((0, applicationinsights_core_js_1.isObject)(value)) { - return ("ver" in value && "exceptions" in value && "properties" in value); - } - } - catch (e) { - // This can happen with some native browser objects, but should not happen for the type we are checking for - } - return false; -} -function _isStackDetails(details) { - return details && details.src && (0, applicationinsights_core_js_1.isString)(details.src) && details.obj && (0, applicationinsights_core_js_1.isArray)(details.obj); -} -function _convertStackObj(errorStack) { - var src = errorStack || ""; - if (!(0, applicationinsights_core_js_1.isString)(src)) { - if ((0, applicationinsights_core_js_1.isString)(src[strStack])) { - src = src[strStack]; - } - else { - src = "" + src; - } - } - var items = src.split("\n"); - return { - src: src, - obj: items - }; -} -function _getOperaStack(errorMessage) { - var stack = []; - var lines = errorMessage.split("\n"); - for (var lp = 0; lp < lines.length; lp++) { - var entry = lines[lp]; - if (lines[lp + 1]) { - entry += "@" + lines[lp + 1]; - lp++; - } - stack.push(entry); - } - return { - src: errorMessage, - obj: stack - }; -} -function _getStackFromErrorObj(errorObj) { - var details = null; - if (errorObj) { - try { - /* Using bracket notation is support older browsers (IE 7/8 -- dont remember the version) that throw when using dot - notation for undefined objects and we don't want to loose the error from being reported */ - if (errorObj[strStack]) { - // Chrome/Firefox - details = _convertStackObj(errorObj[strStack]); - } - else if (errorObj[strError] && errorObj[strError][strStack]) { - // Edge error event provides the stack and error object - details = _convertStackObj(errorObj[strError][strStack]); - } - else if (errorObj["exception"] && errorObj.exception[strStack]) { - details = _convertStackObj(errorObj.exception[strStack]); - } - else if (_isStackDetails(errorObj)) { - details = errorObj; - } - else if (_isStackDetails(errorObj[strStackDetails])) { - details = errorObj[strStackDetails]; - } - else if ((0, ts_utils_1.getWindow)() && (0, ts_utils_1.getWindow)()["opera"] && errorObj[strMessage]) { - // Opera - details = _getOperaStack(errorObj.message); - } - else if (errorObj["reason"] && errorObj.reason[strStack]) { - // UnhandledPromiseRejection - details = _convertStackObj(errorObj.reason[strStack]); - } - else if ((0, applicationinsights_core_js_1.isString)(errorObj)) { - details = _convertStackObj(errorObj); - } - else { - var evtMessage = errorObj[strMessage] || errorObj[strDescription] || ""; - if ((0, applicationinsights_core_js_1.isString)(errorObj[strErrorSrc])) { - if (evtMessage) { - evtMessage += "\n"; - } - evtMessage += " from " + errorObj[strErrorSrc]; - } - if (evtMessage) { - details = _convertStackObj(evtMessage); - } - } - } - catch (e) { - // something unexpected happened so to avoid failing to report any error lets swallow the exception - // and fallback to the callee/caller method - details = _convertStackObj(e); - } - } - return details || { - src: "", - obj: null - }; -} -function _formatStackTrace(stackDetails) { - var stack = ""; - if (stackDetails) { - if (stackDetails.obj) { - stack = stackDetails.obj.join("\n"); - } - else { - stack = stackDetails.src || ""; - } - } - return stack; -} -function _parseStack(stack) { - var parsedStack; - var frames = stack.obj; - if (frames && frames.length > 0) { - parsedStack = []; - var level_1 = 0; - var foundStackStart_1 = false; - var totalSizeInBytes_1 = 0; - (0, applicationinsights_core_js_1.arrForEach)(frames, function (frame) { - if (foundStackStart_1 || _isStackFrame(frame)) { - var theFrame = (0, ts_utils_1.asString)(frame); - // Once we have found the first stack frame we treat the rest of the lines as part of the stack - foundStackStart_1 = true; - var parsedFrame = _extractStackFrame(theFrame, level_1); - if (parsedFrame) { - totalSizeInBytes_1 += parsedFrame.sizeInBytes; - parsedStack.push(parsedFrame); - level_1++; - } - } - }); - // DP Constraint - exception parsed stack must be < 32KB - // remove frames from the middle to meet the threshold - var exceptionParsedStackThreshold = 32 * 1024; - if (totalSizeInBytes_1 > exceptionParsedStackThreshold) { - var left = 0; - var right = parsedStack.length - 1; - var size = 0; - var acceptedLeft = left; - var acceptedRight = right; - while (left < right) { - // check size - var lSize = parsedStack[left].sizeInBytes; - var rSize = parsedStack[right].sizeInBytes; - size += lSize + rSize; - if (size > exceptionParsedStackThreshold) { - // remove extra frames from the middle - var howMany = acceptedRight - acceptedLeft + 1; - parsedStack.splice(acceptedLeft, howMany); - break; - } - // update pointers - acceptedLeft = left; - acceptedRight = right; - left++; - right--; - } - } - } - return parsedStack; -} -function _getErrorType(errorType) { - // Gets the Error Type by passing the constructor (used to get the true type of native error object). - var typeName = ""; - if (errorType) { - typeName = errorType.typeName || errorType.name || ""; - if (!typeName) { - try { - var funcNameRegex = /function (.{1,200})\(/; - var results = (funcNameRegex).exec((errorType).constructor.toString()); - typeName = (results && results.length > 1) ? results[1] : ""; - } - catch (e) { - // eslint-disable-next-line no-empty -- Ignoring any failures as nothing we can do - } - } - } - return typeName; -} -/** - * Formats the provided errorObj for display and reporting, it may be a String, Object, integer or undefined depending on the browser. - * @param errorObj - The supplied errorObj - */ -function _formatErrorCode(errorObj) { - if (errorObj) { - try { - if (!(0, applicationinsights_core_js_1.isString)(errorObj)) { - var errorType = _getErrorType(errorObj); - var result = _stringify(errorObj, false); - if (!result || result === "{}") { - if (errorObj[strError]) { - // Looks like an MS Error Event - errorObj = errorObj[strError]; - errorType = _getErrorType(errorObj); - } - result = _stringify(errorObj, true); - } - if ((0, ts_utils_1.strIndexOf)(result, errorType) !== 0 && errorType !== "String") { - return errorType + ":" + result; - } - return result; - } - } - catch (e) { - // eslint-disable-next-line no-empty -- Ignoring any failures as nothing we can do - } - } - // Fallback to just letting the object format itself into a string - return "" + (errorObj || ""); -} -var Exception = /** @class */ (function () { - /** - * Constructs a new instance of the ExceptionTelemetry object - */ - function Exception(logger, exception, properties, measurements, severityLevel, id) { - this.aiDataContract = { - ver: 1 /* FieldType.Required */, - exceptions: 1 /* FieldType.Required */, - severityLevel: 0 /* FieldType.Default */, - properties: 0 /* FieldType.Default */, - measurements: 0 /* FieldType.Default */ - }; - var _self = this; - _self.ver = 2; // TODO: handle the CS"4.0" ==> breeze 2 conversion in a better way - if (!_isExceptionInternal(exception)) { - if (!properties) { - properties = {}; - } - if (id) { - properties.id = id; - } - _self.exceptions = [_createExceptionDetails(logger, exception, properties)]; - _self.properties = (0, DataSanitizer_1.dataSanitizeProperties)(logger, properties); - _self.measurements = (0, DataSanitizer_1.dataSanitizeMeasurements)(logger, measurements); - if (severityLevel) { - _self.severityLevel = severityLevel; - } - if (id) { - _self.id = id; - } - } - else { - _self.exceptions = exception.exceptions || []; - _self.properties = exception.properties; - _self.measurements = exception.measurements; - if (exception.severityLevel) { - _self.severityLevel = exception.severityLevel; - } - if (exception.id) { - _self.id = exception.id; - exception.properties.id = exception.id; - } - if (exception.problemGroup) { - _self.problemGroup = exception.problemGroup; - } - // bool/int types, use isNullOrUndefined - if (!(0, applicationinsights_core_js_1.isNullOrUndefined)(exception.isManual)) { - _self.isManual = exception.isManual; - } - } - } - Exception.CreateAutoException = function (message, url, lineNumber, columnNumber, error, evt, stack, errorSrc) { - var errorType = _getErrorType(error || evt || message); - return { - message: _formatMessage(message, errorType), - url: url, - lineNumber: lineNumber, - columnNumber: columnNumber, - error: _formatErrorCode(error || evt || message), - evt: _formatErrorCode(evt || message), - typeName: errorType, - stackDetails: _getStackFromErrorObj(stack || error || evt), - errorSrc: errorSrc - }; - }; - Exception.CreateFromInterface = function (logger, exception, properties, measurements) { - var exceptions = exception.exceptions - && (0, applicationinsights_core_js_1.arrMap)(exception.exceptions, function (ex) { return _createExDetailsFromInterface(logger, ex); }); - var exceptionData = new Exception(logger, __assign(__assign({}, exception), { exceptions: exceptions }), properties, measurements); - return exceptionData; - }; - Exception.prototype.toInterface = function () { - var _a = this, exceptions = _a.exceptions, properties = _a.properties, measurements = _a.measurements, severityLevel = _a.severityLevel, problemGroup = _a.problemGroup, id = _a.id, isManual = _a.isManual; - var exceptionDetailsInterface = exceptions instanceof Array - && (0, applicationinsights_core_js_1.arrMap)(exceptions, function (exception) { return exception.toInterface(); }) - || undefined; - return { - ver: "4.0", // TODO: handle the CS"4.0" ==> breeze 2 conversion in a better way - exceptions: exceptionDetailsInterface, - severityLevel: severityLevel, - properties: properties, - measurements: measurements, - problemGroup: problemGroup, - id: id, - isManual: isManual - }; - }; - /** - * Creates a simple exception with 1 stack frame. Useful for manual constracting of exception. - */ - Exception.CreateSimpleException = function (message, typeName, assembly, fileName, details, line) { - return { - exceptions: [ - { - hasFullStack: true, - message: message, - stack: details, - typeName: typeName - } - ] - }; - }; - Exception.envelopeType = "Microsoft.ApplicationInsights.{0}.Exception"; - Exception.dataType = "ExceptionData"; - Exception.formatError = _formatErrorCode; - return Exception; -}()); -exports.Exception = Exception; -var exDetailsAiDataContract = (0, ts_utils_1.objFreeze)({ - id: 0 /* FieldType.Default */, - outerId: 0 /* FieldType.Default */, - typeName: 1 /* FieldType.Required */, - message: 1 /* FieldType.Required */, - hasFullStack: 0 /* FieldType.Default */, - stack: 0 /* FieldType.Default */, - parsedStack: 2 /* FieldType.Array */ -}); -function _toInterface() { - var _self = this; - var parsedStack = (0, applicationinsights_core_js_1.isArray)(_self.parsedStack) - && (0, applicationinsights_core_js_1.arrMap)(_self.parsedStack, function (frame) { return _parsedFrameToInterface(frame); }); - var exceptionDetailsInterface = { - id: _self.id, - outerId: _self.outerId, - typeName: _self.typeName, - message: _self.message, - hasFullStack: _self.hasFullStack, - stack: _self[strStack], - parsedStack: parsedStack || undefined - }; - return exceptionDetailsInterface; -} -function _createExceptionDetails(logger, exception, properties) { - var id; - var outerId; - var typeName; - var message; - var hasFullStack; - var theStack; - var parsedStack; - if (!_isExceptionDetailsInternal(exception)) { - var error = exception; - var evt = error && error.evt; - if (!(0, applicationinsights_core_js_1.isError)(error)) { - error = error[strError] || evt || error; - } - typeName = (0, DataSanitizer_1.dataSanitizeString)(logger, _getErrorType(error)) || Constants_1.strNotSpecified; - message = (0, DataSanitizer_1.dataSanitizeMessage)(logger, _formatMessage(exception || error, typeName)) || Constants_1.strNotSpecified; - var stack = exception[strStackDetails] || _getStackFromErrorObj(exception); - parsedStack = _parseStack(stack); - // after parsedStack is inited, iterate over each frame object, sanitize its assembly field - if ((0, applicationinsights_core_js_1.isArray)(parsedStack)) { - (0, applicationinsights_core_js_1.arrMap)(parsedStack, function (frame) { - frame.assembly = (0, DataSanitizer_1.dataSanitizeString)(logger, frame.assembly); - frame.fileName = (0, DataSanitizer_1.dataSanitizeString)(logger, frame.fileName); - }); - } - theStack = (0, DataSanitizer_1.dataSanitizeException)(logger, _formatStackTrace(stack)); - hasFullStack = (0, applicationinsights_core_js_1.isArray)(parsedStack) && parsedStack.length > 0; - if (properties) { - properties.typeName = properties.typeName || typeName; - } - } - else { - typeName = exception.typeName; - message = exception.message; - theStack = exception[strStack]; - parsedStack = exception.parsedStack || []; - hasFullStack = exception.hasFullStack; - } - return { - aiDataContract: exDetailsAiDataContract, - id: id, - outerId: outerId, - typeName: typeName, - message: message, - hasFullStack: hasFullStack, - stack: theStack, - parsedStack: parsedStack, - toInterface: _toInterface - }; -} -function _createExDetailsFromInterface(logger, exception) { - var parsedStack = ((0, applicationinsights_core_js_1.isArray)(exception.parsedStack) - && (0, applicationinsights_core_js_1.arrMap)(exception.parsedStack, function (frame) { return _stackFrameFromInterface(frame); })) - || exception.parsedStack; - var exceptionDetails = _createExceptionDetails(logger, __assign(__assign({}, exception), { parsedStack: parsedStack })); - return exceptionDetails; -} -function _parseFilename(theFrame, fileName) { - var lineCol = fileName.match(PARSE_FILENAME_LINE_COL); - if (lineCol && lineCol.length >= 4) { - theFrame.fileName = lineCol[1]; - theFrame.line = parseInt(lineCol[2]); - } - else { - var lineNo = fileName.match(PARSE_FILENAME_LINE_ONLY); - if (lineNo && lineNo.length >= 3) { - theFrame.fileName = lineNo[1]; - theFrame.line = parseInt(lineNo[2]); - } - else { - theFrame.fileName = fileName; - } - } -} -function _handleFilename(theFrame, sequence, matches) { - var filename = theFrame.fileName; - if (sequence.fn && matches && matches.length > sequence.fn) { - if (sequence.ln && matches.length > sequence.ln) { - filename = (0, applicationinsights_core_js_1.strTrim)(matches[sequence.fn] || ""); - theFrame.line = parseInt((0, applicationinsights_core_js_1.strTrim)(matches[sequence.ln] || "")) || 0; - } - else { - filename = (0, applicationinsights_core_js_1.strTrim)(matches[sequence.fn] || ""); - } - } - if (filename) { - _parseFilename(theFrame, filename); - } -} -function _isStackFrame(frame) { - var result = false; - if (frame && (0, applicationinsights_core_js_1.isString)(frame)) { - var trimmedFrame = (0, applicationinsights_core_js_1.strTrim)(frame); - if (trimmedFrame) { - result = IS_FRAME.test(trimmedFrame); - } - } - return result; -} -var stackFrameAiDataContract = (0, ts_utils_1.objFreeze)({ - level: 1 /* FieldType.Required */, - method: 1 /* FieldType.Required */, - assembly: 0 /* FieldType.Default */, - fileName: 0 /* FieldType.Default */, - line: 0 /* FieldType.Default */ -}); -function _extractStackFrame(frame, level) { - var theFrame; - if (frame && (0, applicationinsights_core_js_1.isString)(frame) && (0, applicationinsights_core_js_1.strTrim)(frame)) { - theFrame = { - aiDataContract: stackFrameAiDataContract, - level: level, - assembly: (0, applicationinsights_core_js_1.strTrim)(frame), - method: NoMethod, - fileName: "", - line: 0, - sizeInBytes: 0 - }; - var idx = 0; - while (idx < _parseSequence.length) { - var sequence = _parseSequence[idx]; - if (sequence.chk && !sequence.chk(frame)) { - break; - } - if (sequence.pre) { - frame = sequence.pre(frame); - } - // Attempt to "parse" the stack frame - var matches = frame.match(sequence.re); - if (matches && matches.length >= sequence.len) { - if (sequence.m) { - theFrame.method = (0, applicationinsights_core_js_1.strTrim)(matches[sequence.m] || NoMethod); - } - if (sequence.hdl) { - // Run any custom handler - sequence.hdl(theFrame, sequence, matches); - } - else if (sequence.fn) { - if (sequence.ln) { - theFrame.fileName = (0, applicationinsights_core_js_1.strTrim)(matches[sequence.fn] || ""); - theFrame.line = parseInt((0, applicationinsights_core_js_1.strTrim)(matches[sequence.ln] || "")) || 0; - } - else { - _parseFilename(theFrame, matches[sequence.fn] || ""); - } - } - // We found a match so stop looking - break; - } - idx++; - } - } - return _populateFrameSizeInBytes(theFrame); -} -function _stackFrameFromInterface(frame) { - var parsedFrame = { - aiDataContract: stackFrameAiDataContract, - level: frame.level, - method: frame.method, - assembly: frame.assembly, - fileName: frame.fileName, - line: frame.line, - sizeInBytes: 0 - }; - return _populateFrameSizeInBytes(parsedFrame); -} -function _populateFrameSizeInBytes(frame) { - var sizeInBytes = STACKFRAME_BASE_SIZE; - if (frame) { - sizeInBytes += frame.method.length; - sizeInBytes += frame.assembly.length; - sizeInBytes += frame.fileName.length; - sizeInBytes += frame.level.toString().length; - sizeInBytes += frame.line.toString().length; - frame.sizeInBytes = sizeInBytes; - } - return frame; -} -function _parsedFrameToInterface(frame) { - return { - level: frame.level, - method: frame.method, - assembly: frame.assembly, - fileName: frame.fileName, - line: frame.line - }; -} diff --git a/shared/AppInsightsCommon/src/Telemetry/Metric.js b/shared/AppInsightsCommon/src/Telemetry/Metric.js deleted file mode 100644 index 01116c6f0..000000000 --- a/shared/AppInsightsCommon/src/Telemetry/Metric.js +++ /dev/null @@ -1,36 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Metric = void 0; -var Constants_1 = require("../Constants"); -var DataPoint_1 = require("./Common/DataPoint"); -var DataSanitizer_1 = require("./Common/DataSanitizer"); -var Metric = /** @class */ (function () { - /** - * Constructs a new instance of the MetricTelemetry object - */ - function Metric(logger, name, value, count, min, max, stdDev, properties, measurements) { - this.aiDataContract = { - ver: 1 /* FieldType.Required */, - metrics: 1 /* FieldType.Required */, - properties: 0 /* FieldType.Default */ - }; - var _self = this; - _self.ver = 2; - var dataPoint = new DataPoint_1.DataPoint(); - dataPoint.count = count > 0 ? count : undefined; - dataPoint.max = isNaN(max) || max === null ? undefined : max; - dataPoint.min = isNaN(min) || min === null ? undefined : min; - dataPoint.name = (0, DataSanitizer_1.dataSanitizeString)(logger, name) || Constants_1.strNotSpecified; - dataPoint.value = value; - dataPoint.stdDev = isNaN(stdDev) || stdDev === null ? undefined : stdDev; - _self.metrics = [dataPoint]; - _self.properties = (0, DataSanitizer_1.dataSanitizeProperties)(logger, properties); - _self.measurements = (0, DataSanitizer_1.dataSanitizeMeasurements)(logger, measurements); - } - Metric.envelopeType = "Microsoft.ApplicationInsights.{0}.Metric"; - Metric.dataType = "MetricData"; - return Metric; -}()); -exports.Metric = Metric; diff --git a/shared/AppInsightsCommon/src/Telemetry/PageView.js b/shared/AppInsightsCommon/src/Telemetry/PageView.js deleted file mode 100644 index 1de8e98b3..000000000 --- a/shared/AppInsightsCommon/src/Telemetry/PageView.js +++ /dev/null @@ -1,38 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PageView = void 0; -var Constants_1 = require("../Constants"); -var HelperFuncs_1 = require("../HelperFuncs"); -var DataSanitizer_1 = require("./Common/DataSanitizer"); -var PageView = /** @class */ (function () { - /** - * Constructs a new instance of the PageEventTelemetry object - */ - function PageView(logger, name, url, durationMs, properties, measurements, id) { - this.aiDataContract = { - ver: 1 /* FieldType.Required */, - name: 0 /* FieldType.Default */, - url: 0 /* FieldType.Default */, - duration: 0 /* FieldType.Default */, - properties: 0 /* FieldType.Default */, - measurements: 0 /* FieldType.Default */, - id: 0 /* FieldType.Default */ - }; - var _self = this; - _self.ver = 2; - _self.id = (0, DataSanitizer_1.dataSanitizeId)(logger, id); - _self.url = (0, DataSanitizer_1.dataSanitizeUrl)(logger, url); - _self.name = (0, DataSanitizer_1.dataSanitizeString)(logger, name) || Constants_1.strNotSpecified; - if (!isNaN(durationMs)) { - _self.duration = (0, HelperFuncs_1.msToTimeSpan)(durationMs); - } - _self.properties = (0, DataSanitizer_1.dataSanitizeProperties)(logger, properties); - _self.measurements = (0, DataSanitizer_1.dataSanitizeMeasurements)(logger, measurements); - } - PageView.envelopeType = "Microsoft.ApplicationInsights.{0}.Pageview"; - PageView.dataType = "PageviewData"; - return PageView; -}()); -exports.PageView = PageView; diff --git a/shared/AppInsightsCommon/src/Telemetry/PageViewPerformance.js b/shared/AppInsightsCommon/src/Telemetry/PageViewPerformance.js deleted file mode 100644 index b7e78819f..000000000 --- a/shared/AppInsightsCommon/src/Telemetry/PageViewPerformance.js +++ /dev/null @@ -1,45 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PageViewPerformance = void 0; -var Constants_1 = require("../Constants"); -var DataSanitizer_1 = require("./Common/DataSanitizer"); -var PageViewPerformance = /** @class */ (function () { - /** - * Constructs a new instance of the PageEventTelemetry object - */ - function PageViewPerformance(logger, name, url, unused, properties, measurements, cs4BaseData) { - this.aiDataContract = { - ver: 1 /* FieldType.Required */, - name: 0 /* FieldType.Default */, - url: 0 /* FieldType.Default */, - duration: 0 /* FieldType.Default */, - perfTotal: 0 /* FieldType.Default */, - networkConnect: 0 /* FieldType.Default */, - sentRequest: 0 /* FieldType.Default */, - receivedResponse: 0 /* FieldType.Default */, - domProcessing: 0 /* FieldType.Default */, - properties: 0 /* FieldType.Default */, - measurements: 0 /* FieldType.Default */ - }; - var _self = this; - _self.ver = 2; - _self.url = (0, DataSanitizer_1.dataSanitizeUrl)(logger, url); - _self.name = (0, DataSanitizer_1.dataSanitizeString)(logger, name) || Constants_1.strNotSpecified; - _self.properties = (0, DataSanitizer_1.dataSanitizeProperties)(logger, properties); - _self.measurements = (0, DataSanitizer_1.dataSanitizeMeasurements)(logger, measurements); - if (cs4BaseData) { - _self.domProcessing = cs4BaseData.domProcessing; - _self.duration = cs4BaseData.duration; - _self.networkConnect = cs4BaseData.networkConnect; - _self.perfTotal = cs4BaseData.perfTotal; - _self.receivedResponse = cs4BaseData.receivedResponse; - _self.sentRequest = cs4BaseData.sentRequest; - } - } - PageViewPerformance.envelopeType = "Microsoft.ApplicationInsights.{0}.PageviewPerformance"; - PageViewPerformance.dataType = "PageviewPerformanceData"; - return PageViewPerformance; -}()); -exports.PageViewPerformance = PageViewPerformance; diff --git a/shared/AppInsightsCommon/src/Telemetry/RemoteDependencyData.js b/shared/AppInsightsCommon/src/Telemetry/RemoteDependencyData.js deleted file mode 100644 index 96a722524..000000000 --- a/shared/AppInsightsCommon/src/Telemetry/RemoteDependencyData.js +++ /dev/null @@ -1,59 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RemoteDependencyData = void 0; -var HelperFuncs_1 = require("../HelperFuncs"); -var Util_1 = require("../Util"); -var DataSanitizer_1 = require("./Common/DataSanitizer"); -var RemoteDependencyData = /** @class */ (function () { - /** - * Constructs a new instance of the RemoteDependencyData object - */ - function RemoteDependencyData(logger, id, absoluteUrl, commandName, value, success, resultCode, method, requestAPI, correlationContext, properties, measurements) { - if (requestAPI === void 0) { requestAPI = "Ajax"; } - this.aiDataContract = { - id: 1 /* FieldType.Required */, - ver: 1 /* FieldType.Required */, - name: 0 /* FieldType.Default */, - resultCode: 0 /* FieldType.Default */, - duration: 0 /* FieldType.Default */, - success: 0 /* FieldType.Default */, - data: 0 /* FieldType.Default */, - target: 0 /* FieldType.Default */, - type: 0 /* FieldType.Default */, - properties: 0 /* FieldType.Default */, - measurements: 0 /* FieldType.Default */, - kind: 0 /* FieldType.Default */, - value: 0 /* FieldType.Default */, - count: 0 /* FieldType.Default */, - min: 0 /* FieldType.Default */, - max: 0 /* FieldType.Default */, - stdDev: 0 /* FieldType.Default */, - dependencyKind: 0 /* FieldType.Default */, - dependencySource: 0 /* FieldType.Default */, - commandName: 0 /* FieldType.Default */, - dependencyTypeName: 0 /* FieldType.Default */ - }; - var _self = this; - _self.ver = 2; - _self.id = id; - _self.duration = (0, HelperFuncs_1.msToTimeSpan)(value); - _self.success = success; - _self.resultCode = resultCode + ""; - _self.type = (0, DataSanitizer_1.dataSanitizeString)(logger, requestAPI); - var dependencyFields = (0, Util_1.AjaxHelperParseDependencyPath)(logger, absoluteUrl, method, commandName); - _self.data = (0, DataSanitizer_1.dataSanitizeUrl)(logger, commandName) || dependencyFields.data; // get a value from hosturl if commandName not available - _self.target = (0, DataSanitizer_1.dataSanitizeString)(logger, dependencyFields.target); - if (correlationContext) { - _self.target = "".concat(_self.target, " | ").concat(correlationContext); - } - _self.name = (0, DataSanitizer_1.dataSanitizeString)(logger, dependencyFields.name); - _self.properties = (0, DataSanitizer_1.dataSanitizeProperties)(logger, properties); - _self.measurements = (0, DataSanitizer_1.dataSanitizeMeasurements)(logger, measurements); - } - RemoteDependencyData.envelopeType = "Microsoft.ApplicationInsights.{0}.RemoteDependency"; - RemoteDependencyData.dataType = "RemoteDependencyData"; - return RemoteDependencyData; -}()); -exports.RemoteDependencyData = RemoteDependencyData; diff --git a/shared/AppInsightsCommon/src/Telemetry/Trace.js b/shared/AppInsightsCommon/src/Telemetry/Trace.js deleted file mode 100644 index f561c323d..000000000 --- a/shared/AppInsightsCommon/src/Telemetry/Trace.js +++ /dev/null @@ -1,33 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Trace = void 0; -var Constants_1 = require("../Constants"); -var DataSanitizer_1 = require("./Common/DataSanitizer"); -var Trace = /** @class */ (function () { - /** - * Constructs a new instance of the TraceTelemetry object - */ - function Trace(logger, message, severityLevel, properties, measurements) { - this.aiDataContract = { - ver: 1 /* FieldType.Required */, - message: 1 /* FieldType.Required */, - severityLevel: 0 /* FieldType.Default */, - properties: 0 /* FieldType.Default */ - }; - var _self = this; - _self.ver = 2; - message = message || Constants_1.strNotSpecified; - _self.message = (0, DataSanitizer_1.dataSanitizeMessage)(logger, message); - _self.properties = (0, DataSanitizer_1.dataSanitizeProperties)(logger, properties); - _self.measurements = (0, DataSanitizer_1.dataSanitizeMeasurements)(logger, measurements); - if (severityLevel) { - _self.severityLevel = severityLevel; - } - } - Trace.envelopeType = "Microsoft.ApplicationInsights.{0}.Message"; - Trace.dataType = "MessageData"; - return Trace; -}()); -exports.Trace = Trace; diff --git a/shared/AppInsightsCommon/src/TelemetryItemCreator.js b/shared/AppInsightsCommon/src/TelemetryItemCreator.js deleted file mode 100644 index aed6396a3..000000000 --- a/shared/AppInsightsCommon/src/TelemetryItemCreator.js +++ /dev/null @@ -1,64 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TelemetryItemCreator = void 0; -exports.createTelemetryItem = createTelemetryItem; -var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); -var Constants_1 = require("./Constants"); -var DataSanitizer_1 = require("./Telemetry/Common/DataSanitizer"); -/** - * Create a telemetry item that the 1DS channel understands - * @param item - domain specific properties; part B - * @param baseType - telemetry item type. ie PageViewData - * @param envelopeName - Name of the envelope, e.g., `Microsoft.ApplicationInsights.\.PageView`. - * @param customProperties - user defined custom properties; part C - * @param systemProperties - system properties that are added to the context; part A - * @returns ITelemetryItem that is sent to channel - */ -function createTelemetryItem(item, baseType, envelopeName, logger, customProperties, systemProperties) { - envelopeName = (0, DataSanitizer_1.dataSanitizeString)(logger, envelopeName) || Constants_1.strNotSpecified; - if ((0, applicationinsights_core_js_1.isNullOrUndefined)(item) || - (0, applicationinsights_core_js_1.isNullOrUndefined)(baseType) || - (0, applicationinsights_core_js_1.isNullOrUndefined)(envelopeName)) { - (0, applicationinsights_core_js_1.throwError)("Input doesn't contain all required fields"); - } - var iKey = ""; - if (item[Constants_1.strIkey]) { - iKey = item[Constants_1.strIkey]; - delete item[Constants_1.strIkey]; - } - var telemetryItem = { - name: envelopeName, - time: (0, applicationinsights_core_js_1.toISOString)(new Date()), - iKey: iKey, // this will be set in TelemetryContext - ext: systemProperties ? systemProperties : {}, // part A - tags: [], - data: {}, - baseType: baseType, - baseData: item // Part B - }; - // Part C - if (!(0, applicationinsights_core_js_1.isNullOrUndefined)(customProperties)) { - (0, applicationinsights_core_js_1.objForEachKey)(customProperties, function (prop, value) { - telemetryItem.data[prop] = value; - }); - } - return telemetryItem; -} -var TelemetryItemCreator = /** @class */ (function () { - function TelemetryItemCreator() { - } - /** - * Create a telemetry item that the 1DS channel understands - * @param item - domain specific properties; part B - * @param baseType - telemetry item type. ie PageViewData - * @param envelopeName - Name of the envelope (e.g., Microsoft.ApplicationInsights.[instrumentationKey].PageView). - * @param customProperties - user defined custom properties; part C - * @param systemProperties - system properties that are added to the context; part A - * @returns ITelemetryItem that is sent to channel - */ - TelemetryItemCreator.create = createTelemetryItem; - return TelemetryItemCreator; -}()); -exports.TelemetryItemCreator = TelemetryItemCreator; diff --git a/shared/AppInsightsCommon/src/ThrottleMgr.js b/shared/AppInsightsCommon/src/ThrottleMgr.js deleted file mode 100644 index 048e2e45c..000000000 --- a/shared/AppInsightsCommon/src/ThrottleMgr.js +++ /dev/null @@ -1,385 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ThrottleMgr = void 0; -var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); -var ts_utils_1 = require("@nevware21/ts-utils"); -var StorageHelperFuncs_1 = require("./StorageHelperFuncs"); -var THROTTLE_STORAGE_PREFIX = "appInsightsThrottle"; -var ThrottleMgr = /** @class */ (function () { - function ThrottleMgr(core, namePrefix) { - var _self = this; - var _canUseLocalStorage; - var _logger; - var _config; - var _localStorageObj; - var _isTriggered; //_isTriggered is to make sure that we only trigger throttle once a day - var _namePrefix; - var _queue; - var _isReady = false; - var _isSpecificDaysGiven = false; - _initConfig(); - // Special internal method to allow the unit tests and DebugPlugin to hook embedded objects - _self["_getDbgPlgTargets"] = function () { - return [_queue]; - }; - _self.getConfig = function () { - return _config; - }; - /** - * Check if it is the correct day to send message. - * If _isTriggered is true, even if canThrottle returns true, message will not be sent, - * because we only allow triggering sendMessage() once a day. - * @returns if the current date is the valid date to send message - */ - _self.canThrottle = function (msgId) { - var localObj = _getLocalStorageObjByKey(msgId); - var cfg = _getCfgByKey(msgId); - return _canThrottle(cfg, _canUseLocalStorage, localObj); - }; - /** - * Check if throttle is triggered on current day(UTC) - * if canThrottle returns false, isTriggered will return false - * @returns if throttle is triggered on current day(UTC) - */ - _self.isTriggered = function (msgId) { - return _isTrigger(msgId); - }; - /** - * Before isReady set to true, all message will be stored in queue. - * Message will only be sent out after isReady set to true. - * Initial and default value: false - * @returns isReady state - */ - _self.isReady = function () { - return _isReady; - }; - /** - * Flush all message with given message key in queue with isReady state set to true. - * @returns if message queue is flushed - */ - _self.flush = function (msgId) { - try { - var queue = _getQueueByKey(msgId); - if (queue && queue.length > 0) { - var items = queue.slice(0); - _queue[msgId] = []; - (0, ts_utils_1.arrForEach)(items, function (item) { - _flushMessage(item.msgID, item.message, item.severity, false); - }); - return true; - } - } - catch (err) { - // eslint-disable-next-line no-empty - } - return false; - }; - /** - * Flush all message in queue with isReady state set to true. - * @returns if message queue is flushed - */ - _self.flushAll = function () { - try { - if (_queue) { - var result_1 = true; - (0, ts_utils_1.objForEachKey)(_queue, function (key) { - var isFlushed = _self.flush(parseInt(key)); - result_1 = result_1 && isFlushed; - }); - return result_1; - } - } - catch (err) { - // eslint-disable-next-line no-empty - } - return false; - }; - /** - * Set isReady State - * if isReady set to true, message queue will be flushed automatically. - * @param isReady - isReady State - * @pa - * @returns if message queue is flushed - */ - _self.onReadyState = function (isReady, flushAll) { - if (flushAll === void 0) { flushAll = true; } - _isReady = (0, applicationinsights_core_js_1.isNullOrUndefined)(isReady) ? true : isReady; - if (_isReady && flushAll) { - return _self.flushAll(); - } - return null; - }; - _self.sendMessage = function (msgID, message, severity) { - return _flushMessage(msgID, message, severity, true); - }; - function _flushMessage(msgID, message, severity, saveUnsentMsg) { - if (_isReady) { - var isSampledIn = _canSampledIn(msgID); - if (!isSampledIn) { - return; - } - var cfg = _getCfgByKey(msgID); - var localStorageObj = _getLocalStorageObjByKey(msgID); - var canThrottle = _canThrottle(cfg, _canUseLocalStorage, localStorageObj); - var throttled = false; - var number = 0; - var isTriggered = _isTrigger(msgID); - try { - if (canThrottle && !isTriggered) { - number = (0, ts_utils_1.mathMin)(cfg.limit.maxSendNumber, localStorageObj.count + 1); - localStorageObj.count = 0; - throttled = true; - _isTriggered[msgID] = true; - localStorageObj.preTriggerDate = new Date(); - } - else { - _isTriggered[msgID] = canThrottle; - localStorageObj.count += 1; - } - var localStorageName = _getLocalStorageName(msgID); - _resetLocalStorage(_logger, localStorageName, localStorageObj); - for (var i = 0; i < number; i++) { - _sendMessage(msgID, _logger, message, severity); - } - } - catch (e) { - // eslint-disable-next-line no-empty - } - return { - isThrottled: throttled, - throttleNum: number - }; - } - else { - if (!!saveUnsentMsg) { - var queue = _getQueueByKey(msgID); - queue.push({ - msgID: msgID, - message: message, - severity: severity - }); - } - } - return null; - } - function _initConfig() { - _logger = (0, applicationinsights_core_js_1.safeGetLogger)(core); - _isTriggered = {}; - _localStorageObj = {}; - _queue = {}; - _config = {}; - _setCfgByKey(applicationinsights_core_js_1._eInternalMessageId.DefaultThrottleMsgKey); - _namePrefix = (0, applicationinsights_core_js_1.isNotNullOrUndefined)(namePrefix) ? namePrefix : ""; - core.addUnloadHook((0, applicationinsights_core_js_1.onConfigChange)(core.config, function (details) { - var coreConfig = details.cfg; - _canUseLocalStorage = (0, StorageHelperFuncs_1.utlCanUseLocalStorage)(); - var configMgr = coreConfig.throttleMgrCfg || {}; - (0, ts_utils_1.objForEachKey)(configMgr, function (key, cfg) { - _setCfgByKey(parseInt(key), cfg); - }); - })); - } - function _getCfgByKey(msgID) { - return _config[msgID] || _config[applicationinsights_core_js_1._eInternalMessageId.DefaultThrottleMsgKey]; - } - function _setCfgByKey(msgID, config) { - var _a, _b; - try { - var cfg = config || {}; - var curCfg = {}; - curCfg.disabled = !!cfg.disabled; - var configInterval = cfg.interval || {}; - _isSpecificDaysGiven = (configInterval === null || configInterval === void 0 ? void 0 : configInterval.daysOfMonth) && (configInterval === null || configInterval === void 0 ? void 0 : configInterval.daysOfMonth.length) > 0; - curCfg.interval = _getIntervalConfig(configInterval); - var limit = { - samplingRate: ((_a = cfg.limit) === null || _a === void 0 ? void 0 : _a.samplingRate) || 100, - // dafault: every time sent only 1 event - maxSendNumber: ((_b = cfg.limit) === null || _b === void 0 ? void 0 : _b.maxSendNumber) || 1 - }; - curCfg.limit = limit; - _config[msgID] = curCfg; - } - catch (e) { - // eslint-disable-next-line no-empty - } - } - function _getIntervalConfig(interval) { - interval = interval || {}; - var monthInterval = interval === null || interval === void 0 ? void 0 : interval.monthInterval; - var dayInterval = interval === null || interval === void 0 ? void 0 : interval.dayInterval; - // default: send data every 3 month each year - if ((0, applicationinsights_core_js_1.isNullOrUndefined)(monthInterval) && (0, applicationinsights_core_js_1.isNullOrUndefined)(dayInterval)) { - interval.monthInterval = 3; - if (!_isSpecificDaysGiven) { - // default: send data on 28th - interval.daysOfMonth = [28]; - _isSpecificDaysGiven = true; - } - } - interval = { - // dafault: sent every three months - monthInterval: interval === null || interval === void 0 ? void 0 : interval.monthInterval, - dayInterval: interval === null || interval === void 0 ? void 0 : interval.dayInterval, - daysOfMonth: interval === null || interval === void 0 ? void 0 : interval.daysOfMonth - }; - return interval; - } - function _canThrottle(config, canUseLocalStorage, localStorageObj) { - if (config && !config.disabled && canUseLocalStorage && (0, applicationinsights_core_js_1.isNotNullOrUndefined)(localStorageObj)) { - var curDate = _getThrottleDate(); - var date = localStorageObj.date; - var interval = config.interval; - var monthCheck = 1; - if (interval === null || interval === void 0 ? void 0 : interval.monthInterval) { - var monthExpand = (curDate.getUTCFullYear() - date.getUTCFullYear()) * 12 + curDate.getUTCMonth() - date.getUTCMonth(); - monthCheck = _checkInterval(interval.monthInterval, 0, monthExpand); - } - var dayCheck = 1; - if (_isSpecificDaysGiven) { - dayCheck = (0, applicationinsights_core_js_1.arrIndexOf)(interval.daysOfMonth, curDate.getUTCDate()); - } - else if (interval === null || interval === void 0 ? void 0 : interval.dayInterval) { - var daySpan = (0, ts_utils_1.mathFloor)((curDate.getTime() - date.getTime()) / 86400000); - dayCheck = _checkInterval(interval.dayInterval, 0, daySpan); - } - return monthCheck >= 0 && dayCheck >= 0; - } - return false; - } - function _getLocalStorageName(msgKey, prefix) { - var fix = (0, applicationinsights_core_js_1.isNotNullOrUndefined)(prefix) ? prefix : ""; - if (msgKey) { - return THROTTLE_STORAGE_PREFIX + fix + "-" + msgKey; - } - return null; - } - // returns if throttle is triggered on current Date - function _isTriggeredOnCurDate(preTriggerDate) { - try { - if (preTriggerDate) { - var curDate = new Date(); - return preTriggerDate.getUTCFullYear() === curDate.getUTCFullYear() && - preTriggerDate.getUTCMonth() === curDate.getUTCMonth() && - preTriggerDate.getUTCDate() === curDate.getUTCDate(); - } - } - catch (e) { - // eslint-disable-next-line no-empty - } - return false; - } - // transfer local storage string value to object that identifies start date, current count and preTriggerDate - function _getLocalStorageObj(value, logger, storageName) { - try { - var storageObj = { - date: _getThrottleDate(), - count: 0 - }; - if (value) { - var obj = JSON.parse(value); - var curObj = { - date: _getThrottleDate(obj.date) || storageObj.date, - count: obj.count || storageObj.count, - preTriggerDate: obj.preTriggerDate ? _getThrottleDate(obj.preTriggerDate) : undefined - }; - return curObj; - } - else { - _resetLocalStorage(logger, storageName, storageObj); - return storageObj; - } - } - catch (e) { - // eslint-disable-next-line no-empty - } - return null; - } - // if datestr is not defined, current date will be returned - function _getThrottleDate(dateStr) { - // if new Date() can't be created through the provided dateStr, null will be returned. - try { - if (dateStr) { - var date = new Date(dateStr); - //make sure it is a valid Date Object - if (!isNaN(date.getDate())) { - return date; - } - } - else { - return new Date(); - } - } - catch (e) { - // eslint-disable-next-line no-empty - } - return null; - } - function _resetLocalStorage(logger, storageName, obj) { - try { - return (0, StorageHelperFuncs_1.utlSetLocalStorage)(logger, storageName, (0, applicationinsights_core_js_1.strTrim)(JSON.stringify(obj))); - } - catch (e) { - // eslint-disable-next-line no-empty - } - return false; - } - function _checkInterval(interval, start, current) { - if (interval <= 0) { - return 1; - } - // count from start year - return (current >= start) && (current - start) % interval == 0 ? (0, ts_utils_1.mathFloor)((current - start) / interval) + 1 : -1; - } - function _sendMessage(msgID, logger, message, severity) { - (0, applicationinsights_core_js_1._throwInternal)(logger, severity || applicationinsights_core_js_1.eLoggingSeverity.CRITICAL, msgID, message); - } - // NOTE: config.limit.samplingRate is set to 4 decimal places, - // so config.limit.samplingRate = 1 means 0.0001% - function _canSampledIn(msgID) { - try { - var cfg = _getCfgByKey(msgID); - return (0, applicationinsights_core_js_1.randomValue)(1000000) <= cfg.limit.samplingRate; - } - catch (e) { - // eslint-disable-next-line no-empty - } - return false; - } - function _getLocalStorageObjByKey(key) { - try { - var curObj = _localStorageObj[key]; - if (!curObj) { - var localStorageName = _getLocalStorageName(key, _namePrefix); - curObj = _getLocalStorageObj((0, StorageHelperFuncs_1.utlGetLocalStorage)(_logger, localStorageName), _logger, localStorageName); - _localStorageObj[key] = curObj; - } - return _localStorageObj[key]; - } - catch (e) { - // eslint-disable-next-line no-empty - } - return null; - } - function _isTrigger(key) { - var isTrigger = _isTriggered[key]; - if ((0, applicationinsights_core_js_1.isNullOrUndefined)(isTrigger)) { - isTrigger = false; - var localStorageObj = _getLocalStorageObjByKey(key); - if (localStorageObj) { - isTrigger = _isTriggeredOnCurDate(localStorageObj.preTriggerDate); - } - _isTriggered[key] = isTrigger; - } - return _isTriggered[key]; - } - function _getQueueByKey(key) { - _queue = _queue || {}; - if ((0, applicationinsights_core_js_1.isNullOrUndefined)(_queue[key])) { - _queue[key] = []; - } - return _queue[key]; - } - } - return ThrottleMgr; -}()); -exports.ThrottleMgr = ThrottleMgr; diff --git a/shared/AppInsightsCommon/src/UrlHelperFuncs.js b/shared/AppInsightsCommon/src/UrlHelperFuncs.js deleted file mode 100644 index 2306da816..000000000 --- a/shared/AppInsightsCommon/src/UrlHelperFuncs.js +++ /dev/null @@ -1,92 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.urlParseUrl = urlParseUrl; -exports.urlGetAbsoluteUrl = urlGetAbsoluteUrl; -exports.urlGetPathName = urlGetPathName; -exports.urlGetCompleteUrl = urlGetCompleteUrl; -exports.urlParseHost = urlParseHost; -exports.urlParseFullHost = urlParseFullHost; -var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); -var _document = (0, applicationinsights_core_js_1.getDocument)() || {}; -var _htmlAnchorIdx = 0; -// Use an array of temporary values as it's possible for multiple calls to parseUrl() will be called with different URLs -// Using a cache size of 5 for now as it current depth usage is at least 2, so adding a minor buffer to handle future updates -var _htmlAnchorElement = [null, null, null, null, null]; -function urlParseUrl(url) { - var anchorIdx = _htmlAnchorIdx; - var anchorCache = _htmlAnchorElement; - var tempAnchor = anchorCache[anchorIdx]; - if (!_document.createElement) { - // Always create the temp instance if createElement is not available - tempAnchor = { host: urlParseHost(url, true) }; - } - else if (!anchorCache[anchorIdx]) { - // Create and cache the unattached anchor instance - tempAnchor = anchorCache[anchorIdx] = _document.createElement("a"); - } - tempAnchor.href = url; - // Move the cache index forward - anchorIdx++; - if (anchorIdx >= anchorCache.length) { - anchorIdx = 0; - } - _htmlAnchorIdx = anchorIdx; - return tempAnchor; -} -function urlGetAbsoluteUrl(url) { - var result; - var a = urlParseUrl(url); - if (a) { - result = a.href; - } - return result; -} -function urlGetPathName(url) { - var result; - var a = urlParseUrl(url); - if (a) { - result = a.pathname; - } - return result; -} -function urlGetCompleteUrl(method, absoluteUrl) { - if (method) { - return method.toUpperCase() + " " + absoluteUrl; - } - return absoluteUrl; -} -// Fallback method to grab host from url if document.createElement method is not available -function urlParseHost(url, inclPort) { - var fullHost = urlParseFullHost(url, inclPort) || ""; - if (fullHost) { - var match = fullHost.match(/(www\d{0,5}\.)?([^\/:]{1,256})(:\d{1,20})?/i); - if (match != null && match.length > 3 && (0, applicationinsights_core_js_1.isString)(match[2]) && match[2].length > 0) { - return match[2] + (match[3] || ""); - } - } - return fullHost; -} -function urlParseFullHost(url, inclPort) { - var result = null; - if (url) { - var match = url.match(/(\w{1,150}):\/\/([^\/:]{1,256})(:\d{1,20})?/i); - if (match != null && match.length > 2 && (0, applicationinsights_core_js_1.isString)(match[2]) && match[2].length > 0) { - result = match[2] || ""; - if (inclPort && match.length > 2) { - var protocol = (match[1] || "").toLowerCase(); - var port = match[3] || ""; - // IE includes the standard port so pass it off if it's the same as the protocol - if (protocol === "http" && port === ":80") { - port = ""; - } - else if (protocol === "https" && port === ":443") { - port = ""; - } - result += port; - } - } - } - return result; -} diff --git a/shared/AppInsightsCommon/src/Util.js b/shared/AppInsightsCommon/src/Util.js deleted file mode 100644 index b77e5a391..000000000 --- a/shared/AppInsightsCommon/src/Util.js +++ /dev/null @@ -1,204 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isInternalApplicationInsightsEndpoint = isInternalApplicationInsightsEndpoint; -exports.correlationIdSetPrefix = correlationIdSetPrefix; -exports.correlationIdGetPrefix = correlationIdGetPrefix; -exports.correlationIdCanIncludeCorrelationHeader = correlationIdCanIncludeCorrelationHeader; -exports.correlationIdGetCorrelationContext = correlationIdGetCorrelationContext; -exports.correlationIdGetCorrelationContextValue = correlationIdGetCorrelationContextValue; -exports.AjaxHelperParseDependencyPath = AjaxHelperParseDependencyPath; -exports.dateTimeUtilsNow = dateTimeUtilsNow; -exports.dateTimeUtilsDuration = dateTimeUtilsDuration; -exports.createDistributedTraceContextFromTrace = createDistributedTraceContextFromTrace; -var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); -var ts_utils_1 = require("@nevware21/ts-utils"); -var Constants_1 = require("./Constants"); -var RequestResponseHeaders_1 = require("./RequestResponseHeaders"); -var DataSanitizer_1 = require("./Telemetry/Common/DataSanitizer"); -var UrlHelperFuncs_1 = require("./UrlHelperFuncs"); -// listing only non-geo specific locations -var _internalEndpoints = [ - Constants_1.DEFAULT_BREEZE_ENDPOINT + Constants_1.DEFAULT_BREEZE_PATH, - "https://breeze.aimon.applicationinsights.io" + Constants_1.DEFAULT_BREEZE_PATH, - "https://dc-int.services.visualstudio.com" + Constants_1.DEFAULT_BREEZE_PATH -]; -var _correlationIdPrefix = "cid-v1:"; -function isInternalApplicationInsightsEndpoint(endpointUrl) { - return (0, applicationinsights_core_js_1.arrIndexOf)(_internalEndpoints, endpointUrl.toLowerCase()) !== -1; -} -function correlationIdSetPrefix(prefix) { - _correlationIdPrefix = prefix; -} -function correlationIdGetPrefix() { - return _correlationIdPrefix; -} -/** - * Checks if a request url is not on a excluded domain list and if it is safe to add correlation headers. - * Headers are always included if the current domain matches the request domain. If they do not match (CORS), - * they are regex-ed across correlationHeaderDomains and correlationHeaderExcludedDomains to determine if headers are included. - * Some environments don't give information on currentHost via window.location.host (e.g. Cordova). In these cases, the user must - * manually supply domains to include correlation headers on. Else, no headers will be included at all. - */ -function correlationIdCanIncludeCorrelationHeader(config, requestUrl, currentHost) { - if (!requestUrl || (config && config.disableCorrelationHeaders)) { - return false; - } - if (config && config.correlationHeaderExcludePatterns) { - for (var i = 0; i < config.correlationHeaderExcludePatterns.length; i++) { - if (config.correlationHeaderExcludePatterns[i].test(requestUrl)) { - return false; - } - } - } - var requestHost = (0, UrlHelperFuncs_1.urlParseUrl)(requestUrl).host.toLowerCase(); - if (requestHost && ((0, ts_utils_1.strIndexOf)(requestHost, ":443") !== -1 || (0, ts_utils_1.strIndexOf)(requestHost, ":80") !== -1)) { - // [Bug #1260] IE can include the port even for http and https URLs so if present - // try and parse it to remove if it matches the default protocol port - requestHost = ((0, UrlHelperFuncs_1.urlParseFullHost)(requestUrl, true) || "").toLowerCase(); - } - if ((!config || !config.enableCorsCorrelation) && (requestHost && requestHost !== currentHost)) { - return false; - } - var includedDomains = config && config.correlationHeaderDomains; - if (includedDomains) { - var matchExists_1; - (0, applicationinsights_core_js_1.arrForEach)(includedDomains, function (domain) { - var regex = new RegExp(domain.toLowerCase().replace(/\\/g, "\\\\").replace(/\./g, "\\.").replace(/\*/g, ".*")); - matchExists_1 = matchExists_1 || regex.test(requestHost); - }); - if (!matchExists_1) { - return false; - } - } - var excludedDomains = config && config.correlationHeaderExcludedDomains; - if (!excludedDomains || excludedDomains.length === 0) { - return true; - } - for (var i = 0; i < excludedDomains.length; i++) { - var regex = new RegExp(excludedDomains[i].toLowerCase().replace(/\\/g, "\\\\").replace(/\./g, "\\.").replace(/\*/g, ".*")); - if (regex.test(requestHost)) { - return false; - } - } - // if we don't know anything about the requestHost, require the user to use included/excludedDomains. - // Previously we always returned false for a falsy requestHost - return requestHost && requestHost.length > 0; -} -/** - * Combines target appId and target role name from response header. - */ -function correlationIdGetCorrelationContext(responseHeader) { - if (responseHeader) { - var correlationId = correlationIdGetCorrelationContextValue(responseHeader, RequestResponseHeaders_1.RequestHeaders[1 /* eRequestHeaders.requestContextTargetKey */]); - if (correlationId && correlationId !== _correlationIdPrefix) { - return correlationId; - } - } -} -/** - * Gets key from correlation response header - */ -function correlationIdGetCorrelationContextValue(responseHeader, key) { - if (responseHeader) { - var keyValues = responseHeader.split(","); - for (var i = 0; i < keyValues.length; ++i) { - var keyValue = keyValues[i].split("="); - if (keyValue.length === 2 && keyValue[0] === key) { - return keyValue[1]; - } - } - } -} -function AjaxHelperParseDependencyPath(logger, absoluteUrl, method, commandName) { - var target, name = commandName, data = commandName; - if (absoluteUrl && absoluteUrl.length > 0) { - var parsedUrl = (0, UrlHelperFuncs_1.urlParseUrl)(absoluteUrl); - target = parsedUrl.host; - if (!name) { - if (parsedUrl.pathname != null) { - var pathName = (parsedUrl.pathname.length === 0) ? "/" : parsedUrl.pathname; - if (pathName.charAt(0) !== "/") { - pathName = "/" + pathName; - } - data = parsedUrl.pathname; - name = (0, DataSanitizer_1.dataSanitizeString)(logger, method ? method + " " + pathName : pathName); - } - else { - name = (0, DataSanitizer_1.dataSanitizeString)(logger, absoluteUrl); - } - } - } - else { - target = commandName; - name = commandName; - } - return { - target: target, - name: name, - data: data - }; -} -function dateTimeUtilsNow() { - // returns the window or webworker performance object - var perf = (0, applicationinsights_core_js_1.getPerformance)(); - if (perf && perf.now && perf.timing) { - var now = perf.now() + perf.timing.navigationStart; - // Known issue with IE where this calculation can be negative, so if it is then ignore and fallback - if (now > 0) { - return now; - } - } - return (0, applicationinsights_core_js_1.dateNow)(); -} -function dateTimeUtilsDuration(start, end) { - var result = null; - if (start !== 0 && end !== 0 && !(0, applicationinsights_core_js_1.isNullOrUndefined)(start) && !(0, applicationinsights_core_js_1.isNullOrUndefined)(end)) { - result = end - start; - } - return result; -} -/** - * Creates a IDistributedTraceContext from an optional telemetryTrace - * @param telemetryTrace - The telemetryTrace instance that is being wrapped - * @param parentCtx - An optional parent distributed trace instance, almost always undefined as this scenario is only used in the case of multiple property handlers. - * @returns A new IDistributedTraceContext instance that is backed by the telemetryTrace or temporary object - */ -function createDistributedTraceContextFromTrace(telemetryTrace, parentCtx) { - var trace = telemetryTrace || {}; - return { - getName: function () { - return trace.name; - }, - setName: function (newValue) { - parentCtx && parentCtx.setName(newValue); - trace.name = newValue; - }, - getTraceId: function () { - return trace.traceID; - }, - setTraceId: function (newValue) { - parentCtx && parentCtx.setTraceId(newValue); - if ((0, applicationinsights_core_js_1.isValidTraceId)(newValue)) { - trace.traceID = newValue; - } - }, - getSpanId: function () { - return trace.parentID; - }, - setSpanId: function (newValue) { - parentCtx && parentCtx.setSpanId(newValue); - if ((0, applicationinsights_core_js_1.isValidSpanId)(newValue)) { - trace.parentID = newValue; - } - }, - getTraceFlags: function () { - return trace.traceFlags; - }, - setTraceFlags: function (newTraceFlags) { - parentCtx && parentCtx.setTraceFlags(newTraceFlags); - trace.traceFlags = newTraceFlags; - } - }; -} diff --git a/shared/AppInsightsCommon/src/applicationinsights-common.js b/shared/AppInsightsCommon/src/applicationinsights-common.js deleted file mode 100644 index e02cf3eff..000000000 --- a/shared/AppInsightsCommon/src/applicationinsights-common.js +++ /dev/null @@ -1,120 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.stringToBoolOrDefault = exports.EventPersistence = exports.DistributedTracingModes = exports.Extensions = exports.CtxTagKeys = exports.createTelemetryItem = exports.TelemetryItemCreator = exports.dsPadNumber = exports.dataSanitizeInput = exports.dataSanitizeId = exports.dataSanitizeMeasurements = exports.dataSanitizeProperties = exports.dataSanitizeException = exports.dataSanitizeMessage = exports.dataSanitizeUrl = exports.dataSanitizeString = exports.dataSanitizeKey = exports.dataSanitizeKeyAndAddUniqueness = exports.ContextTagKeys = exports.ConfigurationManager = exports.SeverityLevel = exports.Data = exports.PageViewPerformance = exports.Trace = exports.RemoteDependencyData = exports.PageView = exports.Metric = exports.Exception = exports.Event = exports.Envelope = exports.strNotSpecified = exports.DEFAULT_BREEZE_PATH = exports.DEFAULT_BREEZE_ENDPOINT = exports.HttpMethod = exports.SampleRate = exports.ProcessLegacy = exports.DisabledPropertyName = exports.RequestHeaders = exports.ConnectionStringParser = exports.parseConnectionString = exports.ThrottleMgr = exports.createDistributedTraceContextFromTrace = exports.isInternalApplicationInsightsEndpoint = exports.dateTimeUtilsDuration = exports.dateTimeUtilsNow = exports.correlationIdGetCorrelationContextValue = exports.correlationIdGetCorrelationContext = exports.correlationIdCanIncludeCorrelationHeader = exports.correlationIdGetPrefix = exports.correlationIdSetPrefix = void 0; -exports.AnalyticsPluginIdentifier = exports.BreezeChannelIdentifier = exports.PropertiesPluginIdentifier = exports.createOfflineListener = exports.urlParseFullHost = exports.urlParseHost = exports.urlGetCompleteUrl = exports.urlGetPathName = exports.urlGetAbsoluteUrl = exports.urlParseUrl = exports.utlSetStoragePrefix = exports.utlRemoveSessionStorage = exports.utlSetSessionStorage = exports.utlGetSessionStorage = exports.utlGetSessionStorageKeys = exports.utlCanUseSessionStorage = exports.utlRemoveStorage = exports.utlSetLocalStorage = exports.utlGetLocalStorage = exports.utlCanUseLocalStorage = exports.utlEnableStorage = exports.utlDisableStorage = exports.createDomEvent = exports.findAllScripts = exports.findW3cTraceParent = exports.formatTraceParent = exports.isSampledFlag = exports.isValidTraceParent = exports.isValidSpanId = exports.isValidTraceId = exports.parseTraceParent = exports.createTraceParent = exports.ITraceParent = exports.isBeaconApiSupported = exports.isCrossOriginError = exports.getExtensionByName = exports.msToTimeSpan = void 0; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the -var Util_1 = require("./Util"); -Object.defineProperty(exports, "correlationIdSetPrefix", { enumerable: true, get: function () { return Util_1.correlationIdSetPrefix; } }); -Object.defineProperty(exports, "correlationIdGetPrefix", { enumerable: true, get: function () { return Util_1.correlationIdGetPrefix; } }); -Object.defineProperty(exports, "correlationIdCanIncludeCorrelationHeader", { enumerable: true, get: function () { return Util_1.correlationIdCanIncludeCorrelationHeader; } }); -Object.defineProperty(exports, "correlationIdGetCorrelationContext", { enumerable: true, get: function () { return Util_1.correlationIdGetCorrelationContext; } }); -Object.defineProperty(exports, "correlationIdGetCorrelationContextValue", { enumerable: true, get: function () { return Util_1.correlationIdGetCorrelationContextValue; } }); -Object.defineProperty(exports, "dateTimeUtilsNow", { enumerable: true, get: function () { return Util_1.dateTimeUtilsNow; } }); -Object.defineProperty(exports, "dateTimeUtilsDuration", { enumerable: true, get: function () { return Util_1.dateTimeUtilsDuration; } }); -Object.defineProperty(exports, "isInternalApplicationInsightsEndpoint", { enumerable: true, get: function () { return Util_1.isInternalApplicationInsightsEndpoint; } }); -Object.defineProperty(exports, "createDistributedTraceContextFromTrace", { enumerable: true, get: function () { return Util_1.createDistributedTraceContextFromTrace; } }); -var ThrottleMgr_1 = require("./ThrottleMgr"); -Object.defineProperty(exports, "ThrottleMgr", { enumerable: true, get: function () { return ThrottleMgr_1.ThrottleMgr; } }); -var ConnectionStringParser_1 = require("./ConnectionStringParser"); -Object.defineProperty(exports, "parseConnectionString", { enumerable: true, get: function () { return ConnectionStringParser_1.parseConnectionString; } }); -Object.defineProperty(exports, "ConnectionStringParser", { enumerable: true, get: function () { return ConnectionStringParser_1.ConnectionStringParser; } }); -var RequestResponseHeaders_1 = require("./RequestResponseHeaders"); -Object.defineProperty(exports, "RequestHeaders", { enumerable: true, get: function () { return RequestResponseHeaders_1.RequestHeaders; } }); -var Constants_1 = require("./Constants"); -Object.defineProperty(exports, "DisabledPropertyName", { enumerable: true, get: function () { return Constants_1.DisabledPropertyName; } }); -Object.defineProperty(exports, "ProcessLegacy", { enumerable: true, get: function () { return Constants_1.ProcessLegacy; } }); -Object.defineProperty(exports, "SampleRate", { enumerable: true, get: function () { return Constants_1.SampleRate; } }); -Object.defineProperty(exports, "HttpMethod", { enumerable: true, get: function () { return Constants_1.HttpMethod; } }); -Object.defineProperty(exports, "DEFAULT_BREEZE_ENDPOINT", { enumerable: true, get: function () { return Constants_1.DEFAULT_BREEZE_ENDPOINT; } }); -Object.defineProperty(exports, "DEFAULT_BREEZE_PATH", { enumerable: true, get: function () { return Constants_1.DEFAULT_BREEZE_PATH; } }); -Object.defineProperty(exports, "strNotSpecified", { enumerable: true, get: function () { return Constants_1.strNotSpecified; } }); -var Envelope_1 = require("./Telemetry/Common/Envelope"); -Object.defineProperty(exports, "Envelope", { enumerable: true, get: function () { return Envelope_1.Envelope; } }); -var Event_1 = require("./Telemetry/Event"); -Object.defineProperty(exports, "Event", { enumerable: true, get: function () { return Event_1.Event; } }); -var Exception_1 = require("./Telemetry/Exception"); -Object.defineProperty(exports, "Exception", { enumerable: true, get: function () { return Exception_1.Exception; } }); -var Metric_1 = require("./Telemetry/Metric"); -Object.defineProperty(exports, "Metric", { enumerable: true, get: function () { return Metric_1.Metric; } }); -var PageView_1 = require("./Telemetry/PageView"); -Object.defineProperty(exports, "PageView", { enumerable: true, get: function () { return PageView_1.PageView; } }); -var RemoteDependencyData_1 = require("./Telemetry/RemoteDependencyData"); -Object.defineProperty(exports, "RemoteDependencyData", { enumerable: true, get: function () { return RemoteDependencyData_1.RemoteDependencyData; } }); -var Trace_1 = require("./Telemetry/Trace"); -Object.defineProperty(exports, "Trace", { enumerable: true, get: function () { return Trace_1.Trace; } }); -var PageViewPerformance_1 = require("./Telemetry/PageViewPerformance"); -Object.defineProperty(exports, "PageViewPerformance", { enumerable: true, get: function () { return PageViewPerformance_1.PageViewPerformance; } }); -var Data_1 = require("./Telemetry/Common/Data"); -Object.defineProperty(exports, "Data", { enumerable: true, get: function () { return Data_1.Data; } }); -var SeverityLevel_1 = require("./Interfaces/Contracts/SeverityLevel"); -Object.defineProperty(exports, "SeverityLevel", { enumerable: true, get: function () { return SeverityLevel_1.SeverityLevel; } }); -var IConfig_1 = require("./Interfaces/IConfig"); -Object.defineProperty(exports, "ConfigurationManager", { enumerable: true, get: function () { return IConfig_1.ConfigurationManager; } }); -var ContextTagKeys_1 = require("./Interfaces/Contracts/ContextTagKeys"); -Object.defineProperty(exports, "ContextTagKeys", { enumerable: true, get: function () { return ContextTagKeys_1.ContextTagKeys; } }); -var DataSanitizer_1 = require("./Telemetry/Common/DataSanitizer"); -Object.defineProperty(exports, "dataSanitizeKeyAndAddUniqueness", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeKeyAndAddUniqueness; } }); -Object.defineProperty(exports, "dataSanitizeKey", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeKey; } }); -Object.defineProperty(exports, "dataSanitizeString", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeString; } }); -Object.defineProperty(exports, "dataSanitizeUrl", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeUrl; } }); -Object.defineProperty(exports, "dataSanitizeMessage", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeMessage; } }); -Object.defineProperty(exports, "dataSanitizeException", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeException; } }); -Object.defineProperty(exports, "dataSanitizeProperties", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeProperties; } }); -Object.defineProperty(exports, "dataSanitizeMeasurements", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeMeasurements; } }); -Object.defineProperty(exports, "dataSanitizeId", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeId; } }); -Object.defineProperty(exports, "dataSanitizeInput", { enumerable: true, get: function () { return DataSanitizer_1.dataSanitizeInput; } }); -Object.defineProperty(exports, "dsPadNumber", { enumerable: true, get: function () { return DataSanitizer_1.dsPadNumber; } }); -var TelemetryItemCreator_1 = require("./TelemetryItemCreator"); -Object.defineProperty(exports, "TelemetryItemCreator", { enumerable: true, get: function () { return TelemetryItemCreator_1.TelemetryItemCreator; } }); -Object.defineProperty(exports, "createTelemetryItem", { enumerable: true, get: function () { return TelemetryItemCreator_1.createTelemetryItem; } }); -var PartAExtensions_1 = require("./Interfaces/PartAExtensions"); -Object.defineProperty(exports, "CtxTagKeys", { enumerable: true, get: function () { return PartAExtensions_1.CtxTagKeys; } }); -Object.defineProperty(exports, "Extensions", { enumerable: true, get: function () { return PartAExtensions_1.Extensions; } }); -var Enums_1 = require("./Enums"); -Object.defineProperty(exports, "DistributedTracingModes", { enumerable: true, get: function () { return Enums_1.DistributedTracingModes; } }); -Object.defineProperty(exports, "EventPersistence", { enumerable: true, get: function () { return Enums_1.EventPersistence; } }); -var HelperFuncs_1 = require("./HelperFuncs"); -Object.defineProperty(exports, "stringToBoolOrDefault", { enumerable: true, get: function () { return HelperFuncs_1.stringToBoolOrDefault; } }); -Object.defineProperty(exports, "msToTimeSpan", { enumerable: true, get: function () { return HelperFuncs_1.msToTimeSpan; } }); -Object.defineProperty(exports, "getExtensionByName", { enumerable: true, get: function () { return HelperFuncs_1.getExtensionByName; } }); -Object.defineProperty(exports, "isCrossOriginError", { enumerable: true, get: function () { return HelperFuncs_1.isCrossOriginError; } }); -var applicationinsights_core_js_1 = require("@microsoft/applicationinsights-core-js"); -Object.defineProperty(exports, "isBeaconApiSupported", { enumerable: true, get: function () { return applicationinsights_core_js_1.isBeaconsSupported; } }); -Object.defineProperty(exports, "ITraceParent", { enumerable: true, get: function () { return applicationinsights_core_js_1.ITraceParent; } }); -Object.defineProperty(exports, "createTraceParent", { enumerable: true, get: function () { return applicationinsights_core_js_1.createTraceParent; } }); -Object.defineProperty(exports, "parseTraceParent", { enumerable: true, get: function () { return applicationinsights_core_js_1.parseTraceParent; } }); -Object.defineProperty(exports, "isValidTraceId", { enumerable: true, get: function () { return applicationinsights_core_js_1.isValidTraceId; } }); -Object.defineProperty(exports, "isValidSpanId", { enumerable: true, get: function () { return applicationinsights_core_js_1.isValidSpanId; } }); -Object.defineProperty(exports, "isValidTraceParent", { enumerable: true, get: function () { return applicationinsights_core_js_1.isValidTraceParent; } }); -Object.defineProperty(exports, "isSampledFlag", { enumerable: true, get: function () { return applicationinsights_core_js_1.isSampledFlag; } }); -Object.defineProperty(exports, "formatTraceParent", { enumerable: true, get: function () { return applicationinsights_core_js_1.formatTraceParent; } }); -Object.defineProperty(exports, "findW3cTraceParent", { enumerable: true, get: function () { return applicationinsights_core_js_1.findW3cTraceParent; } }); -Object.defineProperty(exports, "findAllScripts", { enumerable: true, get: function () { return applicationinsights_core_js_1.findAllScripts; } }); -var DomHelperFuncs_1 = require("./DomHelperFuncs"); -Object.defineProperty(exports, "createDomEvent", { enumerable: true, get: function () { return DomHelperFuncs_1.createDomEvent; } }); -var StorageHelperFuncs_1 = require("./StorageHelperFuncs"); -Object.defineProperty(exports, "utlDisableStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlDisableStorage; } }); -Object.defineProperty(exports, "utlEnableStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlEnableStorage; } }); -Object.defineProperty(exports, "utlCanUseLocalStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlCanUseLocalStorage; } }); -Object.defineProperty(exports, "utlGetLocalStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlGetLocalStorage; } }); -Object.defineProperty(exports, "utlSetLocalStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlSetLocalStorage; } }); -Object.defineProperty(exports, "utlRemoveStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlRemoveStorage; } }); -Object.defineProperty(exports, "utlCanUseSessionStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlCanUseSessionStorage; } }); -Object.defineProperty(exports, "utlGetSessionStorageKeys", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlGetSessionStorageKeys; } }); -Object.defineProperty(exports, "utlGetSessionStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlGetSessionStorage; } }); -Object.defineProperty(exports, "utlSetSessionStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlSetSessionStorage; } }); -Object.defineProperty(exports, "utlRemoveSessionStorage", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlRemoveSessionStorage; } }); -Object.defineProperty(exports, "utlSetStoragePrefix", { enumerable: true, get: function () { return StorageHelperFuncs_1.utlSetStoragePrefix; } }); -var UrlHelperFuncs_1 = require("./UrlHelperFuncs"); -Object.defineProperty(exports, "urlParseUrl", { enumerable: true, get: function () { return UrlHelperFuncs_1.urlParseUrl; } }); -Object.defineProperty(exports, "urlGetAbsoluteUrl", { enumerable: true, get: function () { return UrlHelperFuncs_1.urlGetAbsoluteUrl; } }); -Object.defineProperty(exports, "urlGetPathName", { enumerable: true, get: function () { return UrlHelperFuncs_1.urlGetPathName; } }); -Object.defineProperty(exports, "urlGetCompleteUrl", { enumerable: true, get: function () { return UrlHelperFuncs_1.urlGetCompleteUrl; } }); -Object.defineProperty(exports, "urlParseHost", { enumerable: true, get: function () { return UrlHelperFuncs_1.urlParseHost; } }); -Object.defineProperty(exports, "urlParseFullHost", { enumerable: true, get: function () { return UrlHelperFuncs_1.urlParseFullHost; } }); -var Offline_1 = require("./Offline"); -Object.defineProperty(exports, "createOfflineListener", { enumerable: true, get: function () { return Offline_1.createOfflineListener; } }); -exports.PropertiesPluginIdentifier = "AppInsightsPropertiesPlugin"; -exports.BreezeChannelIdentifier = "AppInsightsChannelPlugin"; -exports.AnalyticsPluginIdentifier = "ApplicationInsightsAnalytics"; From 831c9b431273103b5cfae05c1652004860e3a5b4 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 21 May 2025 18:53:56 +0000 Subject: [PATCH 07/22] Remove RequestResponseHeaders.ts from PR per reviewer feedback Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- shared/AppInsightsCommon/src/RequestResponseHeaders.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/shared/AppInsightsCommon/src/RequestResponseHeaders.ts b/shared/AppInsightsCommon/src/RequestResponseHeaders.ts index f191186dc..88ed828fc 100644 --- a/shared/AppInsightsCommon/src/RequestResponseHeaders.ts +++ b/shared/AppInsightsCommon/src/RequestResponseHeaders.ts @@ -92,4 +92,5 @@ export const RequestHeaders = createValueMap Date: Wed, 21 May 2025 19:22:02 +0000 Subject: [PATCH 08/22] Pass resolved string to _canSafelyAccessStorage per PR feedback Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- shared/AppInsightsCommon/src/StorageHelperFuncs.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts index faa5723db..73f6b1203 100644 --- a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts +++ b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts @@ -27,11 +27,10 @@ function _getLocalStorageObject(): Storage { /** * Safely checks if storage object (localStorage or sessionStorage) is available and accessible * This helps prevent SecurityError in some browsers (e.g., Safari) when cookies are blocked - * @param storageType - Type of storage + * @param storageTypeName - Name of storage type ("localStorage" or "sessionStorage") * @returns {boolean} Returns whether storage object is safely accessible */ -function _canSafelyAccessStorage(storageType: StorageType): boolean { - const storageTypeName = storageType === StorageType.LocalStorage ? "localStorage" : "sessionStorage"; +function _canSafelyAccessStorage(storageTypeName: string): boolean { let result = true; try { @@ -82,10 +81,11 @@ function _getVerifiedStorageObject(storageType: StorageType): Storage { let result = null; try { + // Determine storage type name once + const storageTypeName = storageType === StorageType.LocalStorage ? "localStorage" : "sessionStorage"; + // First check if we can safely access the storage object - if (_canSafelyAccessStorage(storageType)) { - const storageTypeName = storageType === StorageType.LocalStorage ? "localStorage" : "sessionStorage"; - + if (_canSafelyAccessStorage(storageTypeName)) { // Now we can safely try to use the storage try { let uid = (new Date).toString(); From d2cd04d165587e7ff6238b90e241029ceff79732 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 21 May 2025 19:30:07 +0000 Subject: [PATCH 09/22] Merge _canSafelyAccessStorage function into _getVerifiedStorageObject Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- .../src/StorageHelperFuncs.ts | 89 +++++++++---------- 1 file changed, 40 insertions(+), 49 deletions(-) diff --git a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts index 73f6b1203..0098c5087 100644 --- a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts +++ b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts @@ -24,53 +24,6 @@ function _getLocalStorageObject(): Storage { return null; } -/** - * Safely checks if storage object (localStorage or sessionStorage) is available and accessible - * This helps prevent SecurityError in some browsers (e.g., Safari) when cookies are blocked - * @param storageTypeName - Name of storage type ("localStorage" or "sessionStorage") - * @returns {boolean} Returns whether storage object is safely accessible - */ -function _canSafelyAccessStorage(storageTypeName: string): boolean { - let result = true; - - try { - // First, check if window exists and get the global object once - const gbl: any = getGlobal(); - if (isNullOrUndefined(gbl)) { - result = false; - } else { - // Try to indirectly check if the property exists and is accessible - // This avoids direct property access that might throw in Safari with "Block All Cookies" enabled - - // Some browsers throw when accessing the property descriptors with getOwnPropertyDescriptor - // Others throw when directly accessing the storage objects - // This approach tries both methods safely - try { - // Method 1: Try using property descriptor - safer in Safari with cookies blocked - const descriptor = objGetOwnPropertyDescriptor(gbl, storageTypeName); - if (!descriptor || !descriptor.get) { - result = false; - } - } catch (e) { - // If the above fails, attempt a direct access inside a try-catch - try { - const storage = gbl[storageTypeName]; - if (!storage) { - result = false; - } - } catch (e) { - // If both approaches fail, storage cannot be safely accessed - result = false; - } - } - } - } catch (e) { - result = false; - } - - return result; -} - /** * Tests storage object (localStorage or sessionStorage) to verify that it is usable * More details here: https://mathiasbynens.be/notes/localstorage-pattern @@ -84,8 +37,46 @@ function _getVerifiedStorageObject(storageType: StorageType): Storage { // Determine storage type name once const storageTypeName = storageType === StorageType.LocalStorage ? "localStorage" : "sessionStorage"; - // First check if we can safely access the storage object - if (_canSafelyAccessStorage(storageTypeName)) { + // Check if we can safely access the storage object + let canAccessStorage = true; + + try { + // First, check if window exists and get the global object once + const gbl: any = getGlobal(); + if (isNullOrUndefined(gbl)) { + canAccessStorage = false; + } else { + // Try to indirectly check if the property exists and is accessible + // This avoids direct property access that might throw in Safari with "Block All Cookies" enabled + + // Some browsers throw when accessing the property descriptors with getOwnPropertyDescriptor + // Others throw when directly accessing the storage objects + // This approach tries both methods safely + try { + // Method 1: Try using property descriptor - safer in Safari with cookies blocked + const descriptor = objGetOwnPropertyDescriptor(gbl, storageTypeName); + if (!descriptor || !descriptor.get) { + canAccessStorage = false; + } + } catch (e) { + // If the above fails, attempt a direct access inside a try-catch + try { + const storage = gbl[storageTypeName]; + if (!storage) { + canAccessStorage = false; + } + } catch (e) { + // If both approaches fail, storage cannot be safely accessed + canAccessStorage = false; + } + } + } + } catch (e) { + canAccessStorage = false; + } + + // Only proceed if storage can be safely accessed + if (canAccessStorage) { // Now we can safely try to use the storage try { let uid = (new Date).toString(); From 93c0f44e32f9e806c352f38780ce5a6ee3e67a04 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Thu, 22 May 2025 18:49:08 +0000 Subject: [PATCH 10/22] Simplify storage access code with default-false approach Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- .../src/StorageHelperFuncs.ts | 71 +++++++------------ 1 file changed, 27 insertions(+), 44 deletions(-) diff --git a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts index 0098c5087..cf4d98815 100644 --- a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts +++ b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts @@ -32,70 +32,53 @@ function _getLocalStorageObject(): Storage { */ function _getVerifiedStorageObject(storageType: StorageType): Storage { let result = null; + const storageTypeName = storageType === StorageType.LocalStorage ? "localStorage" : "sessionStorage"; try { - // Determine storage type name once - const storageTypeName = storageType === StorageType.LocalStorage ? "localStorage" : "sessionStorage"; + // Default to false - assume storage is not available + let canAccessStorage = false; + const gbl = getGlobal(); - // Check if we can safely access the storage object - let canAccessStorage = true; - - try { - // First, check if window exists and get the global object once - const gbl: any = getGlobal(); - if (isNullOrUndefined(gbl)) { - canAccessStorage = false; - } else { - // Try to indirectly check if the property exists and is accessible - // This avoids direct property access that might throw in Safari with "Block All Cookies" enabled - - // Some browsers throw when accessing the property descriptors with getOwnPropertyDescriptor - // Others throw when directly accessing the storage objects - // This approach tries both methods safely + // Only proceed if we have a global object + if (!isNullOrUndefined(gbl)) { + // Try the safest method first (property descriptor) + try { + const descriptor = objGetOwnPropertyDescriptor(gbl, storageTypeName); + if (descriptor && descriptor.get) { + canAccessStorage = true; + } + } catch (e) { + // If descriptor check fails, try direct access try { - // Method 1: Try using property descriptor - safer in Safari with cookies blocked - const descriptor = objGetOwnPropertyDescriptor(gbl, storageTypeName); - if (!descriptor || !descriptor.get) { - canAccessStorage = false; - } + canAccessStorage = !!gbl[storageTypeName]; } catch (e) { - // If the above fails, attempt a direct access inside a try-catch - try { - const storage = gbl[storageTypeName]; - if (!storage) { - canAccessStorage = false; - } - } catch (e) { - // If both approaches fail, storage cannot be safely accessed - canAccessStorage = false; - } + // Both checks failed, storage is not accessible } } - } catch (e) { - canAccessStorage = false; } - // Only proceed if storage can be safely accessed + // If we determined storage might be accessible, verify it works if (canAccessStorage) { - // Now we can safely try to use the storage try { - let uid = (new Date).toString(); - let storage: Storage = getGlobalInst(storageTypeName); - let name:string = _storagePrefix + uid; + const uid = (new Date).toString(); + const storage: Storage = getGlobalInst(storageTypeName); + const name = _storagePrefix + uid; + storage.setItem(name, uid); - let fail = storage.getItem(name) !== uid; + const success = storage.getItem(name) === uid; storage.removeItem(name); - if (!fail) { + + if (success) { result = storage; } - } catch (exception) { + } catch (e) { // Storage exists but can't be used (quota exceeded, etc.) } } - } catch (exception) { + } catch (e) { // Catch any unexpected errors } - + return result; } From cdf088ac2594816f52e004272fff030d37ba8279 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Thu, 22 May 2025 20:52:57 +0000 Subject: [PATCH 11/22] Remove unnecessary nested try-catch for direct storage access Co-authored-by: JacksonWeber <47067795+JacksonWeber@users.noreply.github.com> --- shared/AppInsightsCommon/src/StorageHelperFuncs.ts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts index cf4d98815..0560026a2 100644 --- a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts +++ b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts @@ -49,11 +49,8 @@ function _getVerifiedStorageObject(storageType: StorageType): Storage { } } catch (e) { // If descriptor check fails, try direct access - try { - canAccessStorage = !!gbl[storageTypeName]; - } catch (e) { - // Both checks failed, storage is not accessible - } + // This will be caught by the outer try-catch if it fails + canAccessStorage = !!gbl[storageTypeName]; } } From cee30cdb1ff34e7a60c8c1f62fe00c6d3362548e Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 23 May 2025 17:30:18 +0000 Subject: [PATCH 12/22] Add caching to storage verification to reduce test item creation Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- .../src/StorageHelperFuncs.ts | 275 +++++++++++------- 1 file changed, 168 insertions(+), 107 deletions(-) diff --git a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts index 0560026a2..266e555c6 100644 --- a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts +++ b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts @@ -5,20 +5,24 @@ import { IDiagnosticLogger, _eInternalMessageId, _throwInternal, dumpObj, eLoggingSeverity, getExceptionName, getGlobal, getGlobalInst, isNullOrUndefined, objForEachKey } from "@microsoft/applicationinsights-core-js"; -import { objGetOwnPropertyDescriptor } from "@nevware21/ts-utils"; +import { ICachedValue, createCachedValue, objGetOwnPropertyDescriptor } from "@nevware21/ts-utils"; import { StorageType } from "./Enums"; let _canUseLocalStorage: boolean = undefined; let _canUseSessionStorage: boolean = undefined; let _storagePrefix: string = ""; +// Create cached values for verified storage objects to avoid repeated checks +const _verifiedLocalStorage: ICachedValue = createCachedValue(null); +const _verifiedSessionStorage: ICachedValue = createCachedValue(null); + /** * Gets the localStorage object if available * @returns {Storage} - Returns the storage object if available else returns null */ function _getLocalStorageObject(): Storage { if (utlCanUseLocalStorage()) { - return _getVerifiedStorageObject(StorageType.LocalStorage); + return _verifiedLocalStorage.value(() => _getVerifiedStorageObject(StorageType.LocalStorage)); } return null; @@ -85,28 +89,82 @@ function _getVerifiedStorageObject(storageType: StorageType): Storage { */ function _getSessionStorageObject(): Storage { if (utlCanUseSessionStorage()) { - return _getVerifiedStorageObject(StorageType.SessionStorage); + return _verifiedSessionStorage.value(() => _getVerifiedStorageObject(StorageType.SessionStorage)); } return null; } +/** + * Helper function to safely wrap storage operations in try/catch + * and reset cache if an operation fails + * @param storageFn - Function that performs a storage operation + * @param storageType - Type of storage being accessed + * @param fallbackValue - Value to return if operation fails + * @param logger - Optional logger for error reporting + * @returns Result of the storage operation or the fallback value + */ +function _safeStorageOperation(storageFn: () => T, storageType: StorageType, fallbackValue: T, logger?: IDiagnosticLogger, errorMessageId?: _eInternalMessageId, errorMessage?: string): T { + try { + return storageFn(); + } catch (e) { + // If operation fails, invalidate the cache + if (storageType === StorageType.LocalStorage) { + _canUseLocalStorage = false; + _verifiedLocalStorage.reset(); + + // Log error if logger is provided + if (logger && errorMessageId) { + _throwInternal( + logger, + eLoggingSeverity.WARNING, + errorMessageId, + errorMessage + " " + getExceptionName(e), + { exception: dumpObj(e) } + ); + } + } else { + _canUseSessionStorage = false; + _verifiedSessionStorage.reset(); + + // Log error if logger is provided + if (logger && errorMessageId) { + _throwInternal( + logger, + eLoggingSeverity.WARNING, + errorMessageId, + errorMessage + " " + getExceptionName(e), + { exception: dumpObj(e) } + ); + } + } + return fallbackValue; + } +} + /** * Disables the global SDK usage of local or session storage if available */ export function utlDisableStorage() { _canUseLocalStorage = false; _canUseSessionStorage = false; + _verifiedLocalStorage.reset(); + _verifiedSessionStorage.reset(); } export function utlSetStoragePrefix(storagePrefix: string) { _storagePrefix = storagePrefix || ""; + // Reset the cached storage instances since prefix changed + _verifiedLocalStorage.reset(); + _verifiedSessionStorage.reset(); } /** * Re-enables the global SDK usage of local or session storage if available */ export function utlEnableStorage() { + _verifiedLocalStorage.reset(); + _verifiedSessionStorage.reset(); _canUseLocalStorage = utlCanUseLocalStorage(true); _canUseSessionStorage = utlCanUseSessionStorage(true); } @@ -119,140 +177,143 @@ export function utlEnableStorage() { export function utlCanUseLocalStorage(reset?: boolean): boolean { if (reset || _canUseLocalStorage === undefined) { _canUseLocalStorage = !!_getVerifiedStorageObject(StorageType.LocalStorage); + if (_canUseLocalStorage) { + _verifiedLocalStorage.reset(); // Force recalculation if needed + } } return _canUseLocalStorage; } export function utlGetLocalStorage(logger: IDiagnosticLogger, name: string): string { - const storage = _getLocalStorageObject(); - if (storage !== null) { - try { - return storage.getItem(name); - } catch (e) { - _canUseLocalStorage = false; - - _throwInternal(logger, - eLoggingSeverity.WARNING, - _eInternalMessageId.BrowserCannotReadLocalStorage, - "Browser failed read of local storage. " + getExceptionName(e), - { exception: dumpObj(e) }); - } - } - return null; + return _safeStorageOperation( + () => { + const storage = _getLocalStorageObject(); + if (storage !== null) { + return storage.getItem(name); + } + return null; + }, + StorageType.LocalStorage, + null, + logger, + _eInternalMessageId.BrowserCannotReadLocalStorage, + "Browser failed read of local storage." + ); } export function utlSetLocalStorage(logger: IDiagnosticLogger, name: string, data: string): boolean { - const storage = _getLocalStorageObject(); - if (storage !== null) { - try { - storage.setItem(name, data); - return true; - } catch (e) { - _canUseLocalStorage = false; - - _throwInternal(logger, - eLoggingSeverity.WARNING, - _eInternalMessageId.BrowserCannotWriteLocalStorage, - "Browser failed write to local storage. " + getExceptionName(e), - { exception: dumpObj(e) }); - } - } - return false; + return _safeStorageOperation( + () => { + const storage = _getLocalStorageObject(); + if (storage !== null) { + storage.setItem(name, data); + return true; + } + return false; + }, + StorageType.LocalStorage, + false, + logger, + _eInternalMessageId.BrowserCannotWriteLocalStorage, + "Browser failed write to local storage." + ); } export function utlRemoveStorage(logger: IDiagnosticLogger, name: string): boolean { - const storage = _getLocalStorageObject(); - if (storage !== null) { - try { - storage.removeItem(name); - return true; - } catch (e) { - _canUseLocalStorage = false; - - _throwInternal(logger, - eLoggingSeverity.WARNING, - _eInternalMessageId.BrowserFailedRemovalFromLocalStorage, - "Browser failed removal of local storage item. " + getExceptionName(e), - { exception: dumpObj(e) }); - } - } - return false; + return _safeStorageOperation( + () => { + const storage = _getLocalStorageObject(); + if (storage !== null) { + storage.removeItem(name); + return true; + } + return false; + }, + StorageType.LocalStorage, + false, + logger, + _eInternalMessageId.BrowserFailedRemovalFromLocalStorage, + "Browser failed removal of local storage item." + ); } export function utlCanUseSessionStorage(reset?: boolean): boolean { if (reset || _canUseSessionStorage === undefined) { _canUseSessionStorage = !!_getVerifiedStorageObject(StorageType.SessionStorage); + if (_canUseSessionStorage) { + _verifiedSessionStorage.reset(); // Force recalculation if needed + } } return _canUseSessionStorage; } export function utlGetSessionStorageKeys(): string[] { - const keys: string[] = []; - - if (utlCanUseSessionStorage()) { - objForEachKey(getGlobalInst("sessionStorage"), (key) => { - keys.push(key); - }); - } - - return keys; + return _safeStorageOperation( + () => { + const keys: string[] = []; + if (utlCanUseSessionStorage()) { + objForEachKey(getGlobalInst("sessionStorage"), (key) => { + keys.push(key); + }); + } + return keys; + }, + StorageType.SessionStorage, + [] + ); } export function utlGetSessionStorage(logger: IDiagnosticLogger, name: string): string { - const storage = _getSessionStorageObject(); - if (storage !== null) { - try { - return storage.getItem(name); - } catch (e) { - _canUseSessionStorage = false; - - _throwInternal(logger, - eLoggingSeverity.WARNING, - _eInternalMessageId.BrowserCannotReadSessionStorage, - "Browser failed read of session storage. " + getExceptionName(e), - { exception: dumpObj(e) }); - } - } - return null; + return _safeStorageOperation( + () => { + const storage = _getSessionStorageObject(); + if (storage !== null) { + return storage.getItem(name); + } + return null; + }, + StorageType.SessionStorage, + null, + logger, + _eInternalMessageId.BrowserCannotReadSessionStorage, + "Browser failed read of session storage." + ); } export function utlSetSessionStorage(logger: IDiagnosticLogger, name: string, data: string): boolean { - const storage = _getSessionStorageObject(); - if (storage !== null) { - try { - storage.setItem(name, data); - return true; - } catch (e) { - _canUseSessionStorage = false; - - _throwInternal(logger, - eLoggingSeverity.WARNING, - _eInternalMessageId.BrowserCannotWriteSessionStorage, - "Browser failed write to session storage. " + getExceptionName(e), - { exception: dumpObj(e) }); - } - } - return false; + return _safeStorageOperation( + () => { + const storage = _getSessionStorageObject(); + if (storage !== null) { + storage.setItem(name, data); + return true; + } + return false; + }, + StorageType.SessionStorage, + false, + logger, + _eInternalMessageId.BrowserCannotWriteSessionStorage, + "Browser failed write to session storage." + ); } export function utlRemoveSessionStorage(logger: IDiagnosticLogger, name: string): boolean { - const storage = _getSessionStorageObject(); - if (storage !== null) { - try { - storage.removeItem(name); - return true; - } catch (e) { - _canUseSessionStorage = false; - - _throwInternal(logger, - eLoggingSeverity.WARNING, - _eInternalMessageId.BrowserFailedRemovalFromSessionStorage, - "Browser failed removal of session storage item. " + getExceptionName(e), - { exception: dumpObj(e) }); - } - } - - return false; + return _safeStorageOperation( + () => { + const storage = _getSessionStorageObject(); + if (storage !== null) { + storage.removeItem(name); + return true; + } + return false; + }, + StorageType.SessionStorage, + false, + logger, + _eInternalMessageId.BrowserFailedRemovalFromSessionStorage, + "Browser failed removal of session storage item." + ); } From 9e5c98504b4d77fc114ede524585e55fab77e933 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 23 May 2025 23:05:55 +0000 Subject: [PATCH 13/22] Update storage caching to use createCachedValue instead of reset Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- .../src/StorageHelperFuncs.ts | 54 +++++++++---------- 1 file changed, 24 insertions(+), 30 deletions(-) diff --git a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts index 266e555c6..dfd18f0ea 100644 --- a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts +++ b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts @@ -8,24 +8,20 @@ import { import { ICachedValue, createCachedValue, objGetOwnPropertyDescriptor } from "@nevware21/ts-utils"; import { StorageType } from "./Enums"; -let _canUseLocalStorage: boolean = undefined; -let _canUseSessionStorage: boolean = undefined; +let _canUseLocalStorage: boolean = null; +let _canUseSessionStorage: boolean = null; let _storagePrefix: string = ""; // Create cached values for verified storage objects to avoid repeated checks -const _verifiedLocalStorage: ICachedValue = createCachedValue(null); -const _verifiedSessionStorage: ICachedValue = createCachedValue(null); +let _verifiedLocalStorage: ICachedValue = createCachedValue(null); +let _verifiedSessionStorage: ICachedValue = createCachedValue(null); /** * Gets the localStorage object if available * @returns {Storage} - Returns the storage object if available else returns null */ function _getLocalStorageObject(): Storage { - if (utlCanUseLocalStorage()) { - return _verifiedLocalStorage.value(() => _getVerifiedStorageObject(StorageType.LocalStorage)); - } - - return null; + return _verifiedLocalStorage.value(() => _getVerifiedStorageObject(StorageType.LocalStorage)); } /** @@ -88,11 +84,7 @@ function _getVerifiedStorageObject(storageType: StorageType): Storage { * @returns {Storage} - Returns the storage object if available else returns null */ function _getSessionStorageObject(): Storage { - if (utlCanUseSessionStorage()) { - return _verifiedSessionStorage.value(() => _getVerifiedStorageObject(StorageType.SessionStorage)); - } - - return null; + return _verifiedSessionStorage.value(() => _getVerifiedStorageObject(StorageType.SessionStorage)); } /** @@ -111,7 +103,7 @@ function _safeStorageOperation(storageFn: () => T, storageType: StorageType, // If operation fails, invalidate the cache if (storageType === StorageType.LocalStorage) { _canUseLocalStorage = false; - _verifiedLocalStorage.reset(); + _verifiedLocalStorage = createCachedValue(null); // Log error if logger is provided if (logger && errorMessageId) { @@ -125,7 +117,7 @@ function _safeStorageOperation(storageFn: () => T, storageType: StorageType, } } else { _canUseSessionStorage = false; - _verifiedSessionStorage.reset(); + _verifiedSessionStorage = createCachedValue(null); // Log error if logger is provided if (logger && errorMessageId) { @@ -148,23 +140,23 @@ function _safeStorageOperation(storageFn: () => T, storageType: StorageType, export function utlDisableStorage() { _canUseLocalStorage = false; _canUseSessionStorage = false; - _verifiedLocalStorage.reset(); - _verifiedSessionStorage.reset(); + _verifiedLocalStorage = createCachedValue(null); + _verifiedSessionStorage = createCachedValue(null); } export function utlSetStoragePrefix(storagePrefix: string) { _storagePrefix = storagePrefix || ""; // Reset the cached storage instances since prefix changed - _verifiedLocalStorage.reset(); - _verifiedSessionStorage.reset(); + _verifiedLocalStorage = createCachedValue(null); + _verifiedSessionStorage = createCachedValue(null); } /** * Re-enables the global SDK usage of local or session storage if available */ export function utlEnableStorage() { - _verifiedLocalStorage.reset(); - _verifiedSessionStorage.reset(); + _verifiedLocalStorage = createCachedValue(null); + _verifiedSessionStorage = createCachedValue(null); _canUseLocalStorage = utlCanUseLocalStorage(true); _canUseSessionStorage = utlCanUseSessionStorage(true); } @@ -175,10 +167,11 @@ export function utlEnableStorage() { * @param reset - Should the usage be reset and determined only based on whether LocalStorage is available */ export function utlCanUseLocalStorage(reset?: boolean): boolean { - if (reset || _canUseLocalStorage === undefined) { - _canUseLocalStorage = !!_getVerifiedStorageObject(StorageType.LocalStorage); - if (_canUseLocalStorage) { - _verifiedLocalStorage.reset(); // Force recalculation if needed + if (reset || _canUseLocalStorage === null) { + const storage = _getVerifiedStorageObject(StorageType.LocalStorage); + _canUseLocalStorage = !!storage; + if (_canUseLocalStorage && !_verifiedLocalStorage.v) { + _verifiedLocalStorage = createCachedValue(storage); } } @@ -239,10 +232,11 @@ export function utlRemoveStorage(logger: IDiagnosticLogger, name: string): boole } export function utlCanUseSessionStorage(reset?: boolean): boolean { - if (reset || _canUseSessionStorage === undefined) { - _canUseSessionStorage = !!_getVerifiedStorageObject(StorageType.SessionStorage); - if (_canUseSessionStorage) { - _verifiedSessionStorage.reset(); // Force recalculation if needed + if (reset || _canUseSessionStorage === null) { + const storage = _getVerifiedStorageObject(StorageType.SessionStorage); + _canUseSessionStorage = !!storage; + if (_canUseSessionStorage && !_verifiedSessionStorage.v) { + _verifiedSessionStorage = createCachedValue(storage); } } From d0ee829ad14a80c39cb30a0dc728a21cfa4da1a0 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 23 May 2025 23:59:38 +0000 Subject: [PATCH 14/22] Remove _canUseLocalStorage and _canUseSessionStorage flags, add storage wrapper with error handling Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- .../src/StorageHelperFuncs.ts | 139 +++++++++++++----- 1 file changed, 106 insertions(+), 33 deletions(-) diff --git a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts index dfd18f0ea..c8fb2b1f5 100644 --- a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts +++ b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts @@ -8,20 +8,21 @@ import { import { ICachedValue, createCachedValue, objGetOwnPropertyDescriptor } from "@nevware21/ts-utils"; import { StorageType } from "./Enums"; -let _canUseLocalStorage: boolean = null; -let _canUseSessionStorage: boolean = null; let _storagePrefix: string = ""; // Create cached values for verified storage objects to avoid repeated checks -let _verifiedLocalStorage: ICachedValue = createCachedValue(null); -let _verifiedSessionStorage: ICachedValue = createCachedValue(null); +let _verifiedLocalStorage: ICachedValue = null; +let _verifiedSessionStorage: ICachedValue = null; /** * Gets the localStorage object if available * @returns {Storage} - Returns the storage object if available else returns null */ function _getLocalStorageObject(): Storage { - return _verifiedLocalStorage.value(() => _getVerifiedStorageObject(StorageType.LocalStorage)); + if (!_verifiedLocalStorage) { + _verifiedLocalStorage = createCachedValue(_getVerifiedStorageObject(StorageType.LocalStorage)); + } + return _verifiedLocalStorage.v; } /** @@ -66,7 +67,87 @@ function _getVerifiedStorageObject(storageType: StorageType): Storage { storage.removeItem(name); if (success) { - result = storage; + // Create a wrapped storage object that handles errors + const originalStorage = storage; + const wrappedStorage = { + getItem: function(key: string): string { + try { + return originalStorage.getItem(key); + } catch (e) { + // Reset the cached storage on error + if (storageType === StorageType.LocalStorage) { + _verifiedLocalStorage = null; + } else { + _verifiedSessionStorage = null; + } + return null; + } + }, + setItem: function(key: string, value: string): void { + try { + originalStorage.setItem(key, value); + } catch (e) { + // Reset the cached storage on error + if (storageType === StorageType.LocalStorage) { + _verifiedLocalStorage = null; + } else { + _verifiedSessionStorage = null; + } + } + }, + removeItem: function(key: string): void { + try { + originalStorage.removeItem(key); + } catch (e) { + // Reset the cached storage on error + if (storageType === StorageType.LocalStorage) { + _verifiedLocalStorage = null; + } else { + _verifiedSessionStorage = null; + } + } + }, + clear: function(): void { + try { + originalStorage.clear(); + } catch (e) { + // Reset the cached storage on error + if (storageType === StorageType.LocalStorage) { + _verifiedLocalStorage = null; + } else { + _verifiedSessionStorage = null; + } + } + }, + key: function(index: number): string { + try { + return originalStorage.key(index); + } catch (e) { + // Reset the cached storage on error + if (storageType === StorageType.LocalStorage) { + _verifiedLocalStorage = null; + } else { + _verifiedSessionStorage = null; + } + return null; + } + }, + get length(): number { + try { + return originalStorage.length; + } catch (e) { + // Reset the cached storage on error + if (storageType === StorageType.LocalStorage) { + _verifiedLocalStorage = null; + } else { + _verifiedSessionStorage = null; + } + return 0; + } + } + }; + + result = wrappedStorage as Storage; } } catch (e) { // Storage exists but can't be used (quota exceeded, etc.) @@ -84,7 +165,10 @@ function _getVerifiedStorageObject(storageType: StorageType): Storage { * @returns {Storage} - Returns the storage object if available else returns null */ function _getSessionStorageObject(): Storage { - return _verifiedSessionStorage.value(() => _getVerifiedStorageObject(StorageType.SessionStorage)); + if (!_verifiedSessionStorage) { + _verifiedSessionStorage = createCachedValue(_getVerifiedStorageObject(StorageType.SessionStorage)); + } + return _verifiedSessionStorage.v; } /** @@ -102,8 +186,7 @@ function _safeStorageOperation(storageFn: () => T, storageType: StorageType, } catch (e) { // If operation fails, invalidate the cache if (storageType === StorageType.LocalStorage) { - _canUseLocalStorage = false; - _verifiedLocalStorage = createCachedValue(null); + _verifiedLocalStorage = null; // Log error if logger is provided if (logger && errorMessageId) { @@ -116,8 +199,7 @@ function _safeStorageOperation(storageFn: () => T, storageType: StorageType, ); } } else { - _canUseSessionStorage = false; - _verifiedSessionStorage = createCachedValue(null); + _verifiedSessionStorage = null; // Log error if logger is provided if (logger && errorMessageId) { @@ -138,8 +220,6 @@ function _safeStorageOperation(storageFn: () => T, storageType: StorageType, * Disables the global SDK usage of local or session storage if available */ export function utlDisableStorage() { - _canUseLocalStorage = false; - _canUseSessionStorage = false; _verifiedLocalStorage = createCachedValue(null); _verifiedSessionStorage = createCachedValue(null); } @@ -147,18 +227,19 @@ export function utlDisableStorage() { export function utlSetStoragePrefix(storagePrefix: string) { _storagePrefix = storagePrefix || ""; // Reset the cached storage instances since prefix changed - _verifiedLocalStorage = createCachedValue(null); - _verifiedSessionStorage = createCachedValue(null); + _verifiedLocalStorage = null; + _verifiedSessionStorage = null; } /** * Re-enables the global SDK usage of local or session storage if available */ export function utlEnableStorage() { - _verifiedLocalStorage = createCachedValue(null); - _verifiedSessionStorage = createCachedValue(null); - _canUseLocalStorage = utlCanUseLocalStorage(true); - _canUseSessionStorage = utlCanUseSessionStorage(true); + _verifiedLocalStorage = null; + _verifiedSessionStorage = null; + // Force recheck of storage availability + utlCanUseLocalStorage(true); + utlCanUseSessionStorage(true); } /** @@ -167,15 +248,11 @@ export function utlEnableStorage() { * @param reset - Should the usage be reset and determined only based on whether LocalStorage is available */ export function utlCanUseLocalStorage(reset?: boolean): boolean { - if (reset || _canUseLocalStorage === null) { - const storage = _getVerifiedStorageObject(StorageType.LocalStorage); - _canUseLocalStorage = !!storage; - if (_canUseLocalStorage && !_verifiedLocalStorage.v) { - _verifiedLocalStorage = createCachedValue(storage); - } + if (reset || !_verifiedLocalStorage) { + _verifiedLocalStorage = createCachedValue(_getVerifiedStorageObject(StorageType.LocalStorage)); } - return _canUseLocalStorage; + return !!(_verifiedLocalStorage && _verifiedLocalStorage.v); } export function utlGetLocalStorage(logger: IDiagnosticLogger, name: string): string { @@ -232,15 +309,11 @@ export function utlRemoveStorage(logger: IDiagnosticLogger, name: string): boole } export function utlCanUseSessionStorage(reset?: boolean): boolean { - if (reset || _canUseSessionStorage === null) { - const storage = _getVerifiedStorageObject(StorageType.SessionStorage); - _canUseSessionStorage = !!storage; - if (_canUseSessionStorage && !_verifiedSessionStorage.v) { - _verifiedSessionStorage = createCachedValue(storage); - } + if (reset || !_verifiedSessionStorage) { + _verifiedSessionStorage = createCachedValue(_getVerifiedStorageObject(StorageType.SessionStorage)); } - return _canUseSessionStorage; + return !!(_verifiedSessionStorage && _verifiedSessionStorage.v); } export function utlGetSessionStorageKeys(): string[] { From 2274771083e93c9d17c9c97207aa555d33915312 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 24 May 2025 00:39:11 +0000 Subject: [PATCH 15/22] Don't reset cached storage on getItem and read operations Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- .../src/StorageHelperFuncs.ts | 21 +++---------------- 1 file changed, 3 insertions(+), 18 deletions(-) diff --git a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts index c8fb2b1f5..edaba7d9d 100644 --- a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts +++ b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts @@ -74,12 +74,7 @@ function _getVerifiedStorageObject(storageType: StorageType): Storage { try { return originalStorage.getItem(key); } catch (e) { - // Reset the cached storage on error - if (storageType === StorageType.LocalStorage) { - _verifiedLocalStorage = null; - } else { - _verifiedSessionStorage = null; - } + // Don't reset on get operations return null; } }, @@ -123,12 +118,7 @@ function _getVerifiedStorageObject(storageType: StorageType): Storage { try { return originalStorage.key(index); } catch (e) { - // Reset the cached storage on error - if (storageType === StorageType.LocalStorage) { - _verifiedLocalStorage = null; - } else { - _verifiedSessionStorage = null; - } + // Don't reset on get operations return null; } }, @@ -136,12 +126,7 @@ function _getVerifiedStorageObject(storageType: StorageType): Storage { try { return originalStorage.length; } catch (e) { - // Reset the cached storage on error - if (storageType === StorageType.LocalStorage) { - _verifiedLocalStorage = null; - } else { - _verifiedSessionStorage = null; - } + // Don't reset on get operations return 0; } } From 59362d42e3e2f76bc0b38aedf71f664ee908d6e6 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 24 May 2025 00:49:35 +0000 Subject: [PATCH 16/22] Simplify storage wrapper and remove redundant code Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- .../src/StorageHelperFuncs.ts | 289 ++++++++---------- 1 file changed, 126 insertions(+), 163 deletions(-) diff --git a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts index edaba7d9d..4413d32a3 100644 --- a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts +++ b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts @@ -67,17 +67,33 @@ function _getVerifiedStorageObject(storageType: StorageType): Storage { storage.removeItem(name); if (success) { - // Create a wrapped storage object that handles errors + // Create a wrapped storage object that protects write operations const originalStorage = storage; const wrappedStorage = { + // Read operations - don't reset cache on error getItem: function(key: string): string { try { return originalStorage.getItem(key); } catch (e) { - // Don't reset on get operations return null; } }, + key: function(index: number): string { + try { + return originalStorage.key(index); + } catch (e) { + return null; + } + }, + get length(): number { + try { + return originalStorage.length; + } catch (e) { + return 0; + } + }, + + // Write operations - reset cache on error setItem: function(key: string, value: string): void { try { originalStorage.setItem(key, value); @@ -113,22 +129,6 @@ function _getVerifiedStorageObject(storageType: StorageType): Storage { _verifiedSessionStorage = null; } } - }, - key: function(index: number): string { - try { - return originalStorage.key(index); - } catch (e) { - // Don't reset on get operations - return null; - } - }, - get length(): number { - try { - return originalStorage.length; - } catch (e) { - // Don't reset on get operations - return 0; - } } }; @@ -156,50 +156,7 @@ function _getSessionStorageObject(): Storage { return _verifiedSessionStorage.v; } -/** - * Helper function to safely wrap storage operations in try/catch - * and reset cache if an operation fails - * @param storageFn - Function that performs a storage operation - * @param storageType - Type of storage being accessed - * @param fallbackValue - Value to return if operation fails - * @param logger - Optional logger for error reporting - * @returns Result of the storage operation or the fallback value - */ -function _safeStorageOperation(storageFn: () => T, storageType: StorageType, fallbackValue: T, logger?: IDiagnosticLogger, errorMessageId?: _eInternalMessageId, errorMessage?: string): T { - try { - return storageFn(); - } catch (e) { - // If operation fails, invalidate the cache - if (storageType === StorageType.LocalStorage) { - _verifiedLocalStorage = null; - - // Log error if logger is provided - if (logger && errorMessageId) { - _throwInternal( - logger, - eLoggingSeverity.WARNING, - errorMessageId, - errorMessage + " " + getExceptionName(e), - { exception: dumpObj(e) } - ); - } - } else { - _verifiedSessionStorage = null; - - // Log error if logger is provided - if (logger && errorMessageId) { - _throwInternal( - logger, - eLoggingSeverity.WARNING, - errorMessageId, - errorMessage + " " + getExceptionName(e), - { exception: dumpObj(e) } - ); - } - } - return fallbackValue; - } -} + /** * Disables the global SDK usage of local or session storage if available @@ -241,56 +198,59 @@ export function utlCanUseLocalStorage(reset?: boolean): boolean { } export function utlGetLocalStorage(logger: IDiagnosticLogger, name: string): string { - return _safeStorageOperation( - () => { - const storage = _getLocalStorageObject(); - if (storage !== null) { - return storage.getItem(name); - } - return null; - }, - StorageType.LocalStorage, - null, - logger, - _eInternalMessageId.BrowserCannotReadLocalStorage, - "Browser failed read of local storage." - ); + try { + const storage = _getLocalStorageObject(); + if (storage !== null) { + return storage.getItem(name); + } + } catch (e) { + _throwInternal( + logger, + eLoggingSeverity.WARNING, + _eInternalMessageId.BrowserCannotReadLocalStorage, + "Browser failed read of local storage. " + getExceptionName(e), + { exception: dumpObj(e) } + ); + } + return null; } export function utlSetLocalStorage(logger: IDiagnosticLogger, name: string, data: string): boolean { - return _safeStorageOperation( - () => { - const storage = _getLocalStorageObject(); - if (storage !== null) { - storage.setItem(name, data); - return true; - } - return false; - }, - StorageType.LocalStorage, - false, - logger, - _eInternalMessageId.BrowserCannotWriteLocalStorage, - "Browser failed write to local storage." - ); + try { + const storage = _getLocalStorageObject(); + if (storage !== null) { + storage.setItem(name, data); + return true; + } + } catch (e) { + _throwInternal( + logger, + eLoggingSeverity.WARNING, + _eInternalMessageId.BrowserCannotWriteLocalStorage, + "Browser failed write to local storage. " + getExceptionName(e), + { exception: dumpObj(e) } + ); + } + return false; } export function utlRemoveStorage(logger: IDiagnosticLogger, name: string): boolean { - return _safeStorageOperation( - () => { - const storage = _getLocalStorageObject(); - if (storage !== null) { - storage.removeItem(name); - return true; - } - return false; - }, - StorageType.LocalStorage, - false, - logger, - _eInternalMessageId.BrowserFailedRemovalFromLocalStorage, - "Browser failed removal of local storage item." - ); + try { + const storage = _getLocalStorageObject(); + if (storage !== null) { + storage.removeItem(name); + return true; + } + } catch (e) { + _throwInternal( + logger, + eLoggingSeverity.WARNING, + _eInternalMessageId.BrowserFailedRemovalFromLocalStorage, + "Browser failed removal of local storage item. " + getExceptionName(e), + { exception: dumpObj(e) } + ); + } + return false; } export function utlCanUseSessionStorage(reset?: boolean): boolean { @@ -302,70 +262,73 @@ export function utlCanUseSessionStorage(reset?: boolean): boolean { } export function utlGetSessionStorageKeys(): string[] { - return _safeStorageOperation( - () => { - const keys: string[] = []; - if (utlCanUseSessionStorage()) { - objForEachKey(getGlobalInst("sessionStorage"), (key) => { - keys.push(key); - }); - } - return keys; - }, - StorageType.SessionStorage, - [] - ); + try { + const keys: string[] = []; + if (utlCanUseSessionStorage()) { + objForEachKey(getGlobalInst("sessionStorage"), (key) => { + keys.push(key); + }); + } + return keys; + } catch (e) { + // Invalidate session storage on any error + _verifiedSessionStorage = null; + return []; + } } export function utlGetSessionStorage(logger: IDiagnosticLogger, name: string): string { - return _safeStorageOperation( - () => { - const storage = _getSessionStorageObject(); - if (storage !== null) { - return storage.getItem(name); - } - return null; - }, - StorageType.SessionStorage, - null, - logger, - _eInternalMessageId.BrowserCannotReadSessionStorage, - "Browser failed read of session storage." - ); + try { + const storage = _getSessionStorageObject(); + if (storage !== null) { + return storage.getItem(name); + } + } catch (e) { + _throwInternal( + logger, + eLoggingSeverity.WARNING, + _eInternalMessageId.BrowserCannotReadSessionStorage, + "Browser failed read of session storage. " + getExceptionName(e), + { exception: dumpObj(e) } + ); + } + return null; } export function utlSetSessionStorage(logger: IDiagnosticLogger, name: string, data: string): boolean { - return _safeStorageOperation( - () => { - const storage = _getSessionStorageObject(); - if (storage !== null) { - storage.setItem(name, data); - return true; - } - return false; - }, - StorageType.SessionStorage, - false, - logger, - _eInternalMessageId.BrowserCannotWriteSessionStorage, - "Browser failed write to session storage." - ); + try { + const storage = _getSessionStorageObject(); + if (storage !== null) { + storage.setItem(name, data); + return true; + } + } catch (e) { + _throwInternal( + logger, + eLoggingSeverity.WARNING, + _eInternalMessageId.BrowserCannotWriteSessionStorage, + "Browser failed write to session storage. " + getExceptionName(e), + { exception: dumpObj(e) } + ); + } + return false; } export function utlRemoveSessionStorage(logger: IDiagnosticLogger, name: string): boolean { - return _safeStorageOperation( - () => { - const storage = _getSessionStorageObject(); - if (storage !== null) { - storage.removeItem(name); - return true; - } - return false; - }, - StorageType.SessionStorage, - false, - logger, - _eInternalMessageId.BrowserFailedRemovalFromSessionStorage, - "Browser failed removal of session storage item." - ); + try { + const storage = _getSessionStorageObject(); + if (storage !== null) { + storage.removeItem(name); + return true; + } + } catch (e) { + _throwInternal( + logger, + eLoggingSeverity.WARNING, + _eInternalMessageId.BrowserFailedRemovalFromSessionStorage, + "Browser failed removal of session storage item. " + getExceptionName(e), + { exception: dumpObj(e) } + ); + } + return false; } From b9789afe8e87e37a7b169ac5ed4fe10aa5753a13 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 24 May 2025 02:29:41 +0000 Subject: [PATCH 17/22] Use existing helper functions in utlCanUseLocalStorage/SessionStorage Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- .../AppInsightsCommon/src/StorageHelperFuncs.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts index 4413d32a3..7078be95f 100644 --- a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts +++ b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts @@ -190,11 +190,11 @@ export function utlEnableStorage() { * @param reset - Should the usage be reset and determined only based on whether LocalStorage is available */ export function utlCanUseLocalStorage(reset?: boolean): boolean { - if (reset || !_verifiedLocalStorage) { - _verifiedLocalStorage = createCachedValue(_getVerifiedStorageObject(StorageType.LocalStorage)); + if (reset) { + _verifiedLocalStorage = null; } - - return !!(_verifiedLocalStorage && _verifiedLocalStorage.v); + + return !!_getLocalStorageObject(); } export function utlGetLocalStorage(logger: IDiagnosticLogger, name: string): string { @@ -254,11 +254,11 @@ export function utlRemoveStorage(logger: IDiagnosticLogger, name: string): boole } export function utlCanUseSessionStorage(reset?: boolean): boolean { - if (reset || !_verifiedSessionStorage) { - _verifiedSessionStorage = createCachedValue(_getVerifiedStorageObject(StorageType.SessionStorage)); + if (reset) { + _verifiedSessionStorage = null; } - - return !!(_verifiedSessionStorage && _verifiedSessionStorage.v); + + return !!_getSessionStorageObject(); } export function utlGetSessionStorageKeys(): string[] { From e7754716ed5e6491b834e2f3ed73892e6851af5a Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 24 May 2025 02:40:02 +0000 Subject: [PATCH 18/22] Refactor storage helper functions to reduce code duplication and fix dead code Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- .../src/StorageHelperFuncs.ts | 197 +++++------------- 1 file changed, 54 insertions(+), 143 deletions(-) diff --git a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts index 7078be95f..b961cf179 100644 --- a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts +++ b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts @@ -69,67 +69,38 @@ function _getVerifiedStorageObject(storageType: StorageType): Storage { if (success) { // Create a wrapped storage object that protects write operations const originalStorage = storage; - const wrappedStorage = { - // Read operations - don't reset cache on error - getItem: function(key: string): string { - try { - return originalStorage.getItem(key); - } catch (e) { - return null; - } - }, - key: function(index: number): string { - try { - return originalStorage.key(index); - } catch (e) { - return null; - } - }, - get length(): number { + + // Helper to create storage operation methods with consistent error handling + const _createStorageOperation = function(operationName: string, resetOnError: boolean, defaultValue?: T): Function { + return function(...args: any[]): T { try { - return originalStorage.length; + return originalStorage[operationName].apply(originalStorage, args); } catch (e) { - return 0; + // Reset cache on error for write operations only + if (resetOnError) { + if (storageType === StorageType.LocalStorage) { + _verifiedLocalStorage = null; + } else { + _verifiedSessionStorage = null; + } + } + return defaultValue; } + }; + } + + const wrappedStorage = { + // Read operations - don't reset cache on error + getItem: _createStorageOperation("getItem", false, null), + key: _createStorageOperation("key", false, null), + get length(): number { + return _createStorageOperation("length", false, 0)(); }, // Write operations - reset cache on error - setItem: function(key: string, value: string): void { - try { - originalStorage.setItem(key, value); - } catch (e) { - // Reset the cached storage on error - if (storageType === StorageType.LocalStorage) { - _verifiedLocalStorage = null; - } else { - _verifiedSessionStorage = null; - } - } - }, - removeItem: function(key: string): void { - try { - originalStorage.removeItem(key); - } catch (e) { - // Reset the cached storage on error - if (storageType === StorageType.LocalStorage) { - _verifiedLocalStorage = null; - } else { - _verifiedSessionStorage = null; - } - } - }, - clear: function(): void { - try { - originalStorage.clear(); - } catch (e) { - // Reset the cached storage on error - if (storageType === StorageType.LocalStorage) { - _verifiedLocalStorage = null; - } else { - _verifiedSessionStorage = null; - } - } - } + setItem: _createStorageOperation("setItem", true), + removeItem: _createStorageOperation("removeItem", true), + clear: _createStorageOperation("clear", true) }; result = wrappedStorage as Storage; @@ -198,57 +169,27 @@ export function utlCanUseLocalStorage(reset?: boolean): boolean { } export function utlGetLocalStorage(logger: IDiagnosticLogger, name: string): string { - try { - const storage = _getLocalStorageObject(); - if (storage !== null) { - return storage.getItem(name); - } - } catch (e) { - _throwInternal( - logger, - eLoggingSeverity.WARNING, - _eInternalMessageId.BrowserCannotReadLocalStorage, - "Browser failed read of local storage. " + getExceptionName(e), - { exception: dumpObj(e) } - ); + const storage = _getLocalStorageObject(); + if (storage !== null) { + return storage.getItem(name); } return null; } export function utlSetLocalStorage(logger: IDiagnosticLogger, name: string, data: string): boolean { - try { - const storage = _getLocalStorageObject(); - if (storage !== null) { - storage.setItem(name, data); - return true; - } - } catch (e) { - _throwInternal( - logger, - eLoggingSeverity.WARNING, - _eInternalMessageId.BrowserCannotWriteLocalStorage, - "Browser failed write to local storage. " + getExceptionName(e), - { exception: dumpObj(e) } - ); + const storage = _getLocalStorageObject(); + if (storage !== null) { + storage.setItem(name, data); + return true; } return false; } export function utlRemoveStorage(logger: IDiagnosticLogger, name: string): boolean { - try { - const storage = _getLocalStorageObject(); - if (storage !== null) { - storage.removeItem(name); - return true; - } - } catch (e) { - _throwInternal( - logger, - eLoggingSeverity.WARNING, - _eInternalMessageId.BrowserFailedRemovalFromLocalStorage, - "Browser failed removal of local storage item. " + getExceptionName(e), - { exception: dumpObj(e) } - ); + const storage = _getLocalStorageObject(); + if (storage !== null) { + storage.removeItem(name); + return true; } return false; } @@ -262,73 +203,43 @@ export function utlCanUseSessionStorage(reset?: boolean): boolean { } export function utlGetSessionStorageKeys(): string[] { - try { + if (utlCanUseSessionStorage()) { const keys: string[] = []; - if (utlCanUseSessionStorage()) { + try { objForEachKey(getGlobalInst("sessionStorage"), (key) => { keys.push(key); }); + } catch (e) { + // Invalidate session storage on any error + _verifiedSessionStorage = null; } return keys; - } catch (e) { - // Invalidate session storage on any error - _verifiedSessionStorage = null; - return []; } + return []; } export function utlGetSessionStorage(logger: IDiagnosticLogger, name: string): string { - try { - const storage = _getSessionStorageObject(); - if (storage !== null) { - return storage.getItem(name); - } - } catch (e) { - _throwInternal( - logger, - eLoggingSeverity.WARNING, - _eInternalMessageId.BrowserCannotReadSessionStorage, - "Browser failed read of session storage. " + getExceptionName(e), - { exception: dumpObj(e) } - ); + const storage = _getSessionStorageObject(); + if (storage !== null) { + return storage.getItem(name); } return null; } export function utlSetSessionStorage(logger: IDiagnosticLogger, name: string, data: string): boolean { - try { - const storage = _getSessionStorageObject(); - if (storage !== null) { - storage.setItem(name, data); - return true; - } - } catch (e) { - _throwInternal( - logger, - eLoggingSeverity.WARNING, - _eInternalMessageId.BrowserCannotWriteSessionStorage, - "Browser failed write to session storage. " + getExceptionName(e), - { exception: dumpObj(e) } - ); + const storage = _getSessionStorageObject(); + if (storage !== null) { + storage.setItem(name, data); + return true; } return false; } export function utlRemoveSessionStorage(logger: IDiagnosticLogger, name: string): boolean { - try { - const storage = _getSessionStorageObject(); - if (storage !== null) { - storage.removeItem(name); - return true; - } - } catch (e) { - _throwInternal( - logger, - eLoggingSeverity.WARNING, - _eInternalMessageId.BrowserFailedRemovalFromSessionStorage, - "Browser failed removal of session storage item. " + getExceptionName(e), - { exception: dumpObj(e) } - ); + const storage = _getSessionStorageObject(); + if (storage !== null) { + storage.removeItem(name); + return true; } return false; } From 7e32aa3f6c5658d1c6f7432d681b1b1d043a78c3 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Tue, 27 May 2025 22:49:00 +0000 Subject: [PATCH 19/22] Address PR comments for StorageHelperFuncs.ts Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- .../src/StorageHelperFuncs.ts | 63 +++++++++++-------- 1 file changed, 37 insertions(+), 26 deletions(-) diff --git a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts index b961cf179..5f00f186f 100644 --- a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts +++ b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts @@ -60,6 +60,9 @@ function _getVerifiedStorageObject(storageType: StorageType): Storage { try { const uid = (new Date).toString(); const storage: Storage = getGlobalInst(storageTypeName); + if (!storage) { + return null; + } const name = _storagePrefix + uid; storage.setItem(name, uid); @@ -73,19 +76,8 @@ function _getVerifiedStorageObject(storageType: StorageType): Storage { // Helper to create storage operation methods with consistent error handling const _createStorageOperation = function(operationName: string, resetOnError: boolean, defaultValue?: T): Function { return function(...args: any[]): T { - try { - return originalStorage[operationName].apply(originalStorage, args); - } catch (e) { - // Reset cache on error for write operations only - if (resetOnError) { - if (storageType === StorageType.LocalStorage) { - _verifiedLocalStorage = null; - } else { - _verifiedSessionStorage = null; - } - } - return defaultValue; - } + // Let exceptions propagate to the caller + return originalStorage[operationName].apply(originalStorage, args); }; } @@ -148,8 +140,6 @@ export function utlSetStoragePrefix(storagePrefix: string) { * Re-enables the global SDK usage of local or session storage if available */ export function utlEnableStorage() { - _verifiedLocalStorage = null; - _verifiedSessionStorage = null; // Force recheck of storage availability utlCanUseLocalStorage(true); utlCanUseSessionStorage(true); @@ -219,27 +209,48 @@ export function utlGetSessionStorageKeys(): string[] { } export function utlGetSessionStorage(logger: IDiagnosticLogger, name: string): string { - const storage = _getSessionStorageObject(); - if (storage !== null) { - return storage.getItem(name); + try { + const storage = _getSessionStorageObject(); + if (storage !== null) { + return storage.getItem(name); + } + } catch (e) { + _throwInternal(logger, eLoggingSeverity.WARNING, + _eInternalMessageId.FailedToGetSessionStorageItem, + "Failed to get session storage: " + getExceptionName(e), + { exception: dumpObj(e) }); } return null; } export function utlSetSessionStorage(logger: IDiagnosticLogger, name: string, data: string): boolean { - const storage = _getSessionStorageObject(); - if (storage !== null) { - storage.setItem(name, data); - return true; + try { + const storage = _getSessionStorageObject(); + if (storage !== null) { + storage.setItem(name, data); + return true; + } + } catch (e) { + _throwInternal(logger, eLoggingSeverity.WARNING, + _eInternalMessageId.FailedToSetSessionStorageItem, + "Failed to set session storage: " + getExceptionName(e), + { exception: dumpObj(e) }); } return false; } export function utlRemoveSessionStorage(logger: IDiagnosticLogger, name: string): boolean { - const storage = _getSessionStorageObject(); - if (storage !== null) { - storage.removeItem(name); - return true; + try { + const storage = _getSessionStorageObject(); + if (storage !== null) { + storage.removeItem(name); + return true; + } + } catch (e) { + _throwInternal(logger, eLoggingSeverity.WARNING, + _eInternalMessageId.FailedToRemoveSessionStorageItem, + "Failed to remove session storage: " + getExceptionName(e), + { exception: dumpObj(e) }); } return false; } From ec8154390ad6cd173b39d24dba1425741d41dfb4 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 28 May 2025 18:56:02 +0000 Subject: [PATCH 20/22] Refactor storage functions per PR feedback Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- .../src/StorageHelperFuncs.ts | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts index 5f00f186f..79e1b194c 100644 --- a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts +++ b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts @@ -76,8 +76,22 @@ function _getVerifiedStorageObject(storageType: StorageType): Storage { // Helper to create storage operation methods with consistent error handling const _createStorageOperation = function(operationName: string, resetOnError: boolean, defaultValue?: T): Function { return function(...args: any[]): T { - // Let exceptions propagate to the caller - return originalStorage[operationName].apply(originalStorage, args); + try { + // Execute the operation but allow exceptions to propagate after handling + return originalStorage[operationName].apply(originalStorage, args); + } catch (e) { + // Log or handle the error as needed + if (resetOnError) { + // Reset the verified storage on write errors + if (storageType === StorageType.LocalStorage) { + _verifiedLocalStorage = null; + } else { + _verifiedSessionStorage = null; + } + } + // Rethrow the exception to the caller + throw e; + } }; } @@ -155,7 +169,8 @@ export function utlCanUseLocalStorage(reset?: boolean): boolean { _verifiedLocalStorage = null; } - return !!_getLocalStorageObject(); + const storage = _getLocalStorageObject(); + return !!storage; } export function utlGetLocalStorage(logger: IDiagnosticLogger, name: string): string { @@ -189,7 +204,8 @@ export function utlCanUseSessionStorage(reset?: boolean): boolean { _verifiedSessionStorage = null; } - return !!_getSessionStorageObject(); + const storage = _getSessionStorageObject(); + return !!storage; } export function utlGetSessionStorageKeys(): string[] { From 23f5e509e9624e202e9bfee407c83ca7962d406e Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 28 May 2025 20:19:07 +0000 Subject: [PATCH 21/22] Refactor utlCanUseLocalStorage and utlCanUseSessionStorage to include _throwInternal Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- common/config/rush/npm-shrinkwrap.json | 140 +++++++++++------- .../src/StorageHelperFuncs.ts | 30 +++- 2 files changed, 114 insertions(+), 56 deletions(-) diff --git a/common/config/rush/npm-shrinkwrap.json b/common/config/rush/npm-shrinkwrap.json index e58f83e89..0313947d5 100644 --- a/common/config/rush/npm-shrinkwrap.json +++ b/common/config/rush/npm-shrinkwrap.json @@ -1716,9 +1716,9 @@ "integrity": "sha512-II+C1wgzUia0g+tGAH+PBb4XiTm8/C/i6sN23r21NNskBYOYrv+qnW0tFQ/IxZzKVwrK4CTglf8YO3poJUclQA==" }, "node_modules/@types/react": { - "version": "16.14.64", - "resolved": "https://registry.npmjs.org/@types/react/-/react-16.14.64.tgz", - "integrity": "sha512-CcJ89hvLdpjYzV9QHYAbD2IVggc8RYEd7Km40HzJPuN3TiKv9sfSNYXj8zohrIGJPiKMClMIXJE+XJX1qZXpnw==", + "version": "16.14.65", + "resolved": "https://registry.npmjs.org/@types/react/-/react-16.14.65.tgz", + "integrity": "sha512-Guc3kE+W8LrQB9I3bF3blvNH15dXFIVIHIJTqrF8cp5XI/3IJcHGo4C3sJNPb8Zx49aofXKnAGIKyonE4f7XWg==", "dependencies": { "@types/prop-types": "*", "@types/scheduler": "^0.16", @@ -1763,16 +1763,16 @@ } }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.32.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.32.1.tgz", - "integrity": "sha512-6u6Plg9nP/J1GRpe/vcjjabo6Uc5YQPAMxsgQyGC/I0RuukiG1wIe3+Vtg3IrSCVJDmqK3j8adrtzXSENRtFgg==", + "version": "8.33.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.33.0.tgz", + "integrity": "sha512-CACyQuqSHt7ma3Ns601xykeBK/rDeZa3w6IS6UtMQbixO5DWy+8TilKkviGDH6jtWCo8FGRKEK5cLLkPvEammQ==", "peer": true, "dependencies": { "@eslint-community/regexpp": "^4.10.0", - "@typescript-eslint/scope-manager": "8.32.1", - "@typescript-eslint/type-utils": "8.32.1", - "@typescript-eslint/utils": "8.32.1", - "@typescript-eslint/visitor-keys": "8.32.1", + "@typescript-eslint/scope-manager": "8.33.0", + "@typescript-eslint/type-utils": "8.33.0", + "@typescript-eslint/utils": "8.33.0", + "@typescript-eslint/visitor-keys": "8.33.0", "graphemer": "^1.4.0", "ignore": "^7.0.0", "natural-compare": "^1.4.0", @@ -1786,21 +1786,21 @@ "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "@typescript-eslint/parser": "^8.0.0 || ^8.0.0-alpha.0", + "@typescript-eslint/parser": "^8.33.0", "eslint": "^8.57.0 || ^9.0.0", "typescript": ">=4.8.4 <5.9.0" } }, "node_modules/@typescript-eslint/parser": { - "version": "8.32.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.32.1.tgz", - "integrity": "sha512-LKMrmwCPoLhM45Z00O1ulb6jwyVr2kr3XJp+G+tSEZcbauNnScewcQwtJqXDhXeYPDEjZ8C1SjXm015CirEmGg==", + "version": "8.33.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.33.0.tgz", + "integrity": "sha512-JaehZvf6m0yqYp34+RVnihBAChkqeH+tqqhS0GuX1qgPpwLvmTPheKEs6OeCK6hVJgXZHJ2vbjnC9j119auStQ==", "peer": true, "dependencies": { - "@typescript-eslint/scope-manager": "8.32.1", - "@typescript-eslint/types": "8.32.1", - "@typescript-eslint/typescript-estree": "8.32.1", - "@typescript-eslint/visitor-keys": "8.32.1", + "@typescript-eslint/scope-manager": "8.33.0", + "@typescript-eslint/types": "8.33.0", + "@typescript-eslint/typescript-estree": "8.33.0", + "@typescript-eslint/visitor-keys": "8.33.0", "debug": "^4.3.4" }, "engines": { @@ -1815,14 +1815,32 @@ "typescript": ">=4.8.4 <5.9.0" } }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.33.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.33.0.tgz", + "integrity": "sha512-d1hz0u9l6N+u/gcrk6s6gYdl7/+pp8yHheRTqP6X5hVDKALEaTn8WfGiit7G511yueBEL3OpOEpD+3/MBdoN+A==", + "peer": true, + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.33.0", + "@typescript-eslint/types": "^8.33.0", + "debug": "^4.3.4" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, "node_modules/@typescript-eslint/scope-manager": { - "version": "8.32.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.32.1.tgz", - "integrity": "sha512-7IsIaIDeZn7kffk7qXC3o6Z4UblZJKV3UBpkvRNpr5NSyLji7tvTcvmnMNYuYLyh26mN8W723xpo3i4MlD33vA==", + "version": "8.33.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.33.0.tgz", + "integrity": "sha512-LMi/oqrzpqxyO72ltP+dBSP6V0xiUb4saY7WLtxSfiNEBI8m321LLVFU9/QDJxjDQG9/tjSqKz/E3380TEqSTw==", "peer": true, "dependencies": { - "@typescript-eslint/types": "8.32.1", - "@typescript-eslint/visitor-keys": "8.32.1" + "@typescript-eslint/types": "8.33.0", + "@typescript-eslint/visitor-keys": "8.33.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -1832,14 +1850,30 @@ "url": "https://opencollective.com/typescript-eslint" } }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.33.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.33.0.tgz", + "integrity": "sha512-sTkETlbqhEoiFmGr1gsdq5HyVbSOF0145SYDJ/EQmXHtKViCaGvnyLqWFFHtEXoS0J1yU8Wyou2UGmgW88fEug==", + "peer": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <5.9.0" + } + }, "node_modules/@typescript-eslint/type-utils": { - "version": "8.32.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.32.1.tgz", - "integrity": "sha512-mv9YpQGA8iIsl5KyUPi+FGLm7+bA4fgXaeRcFKRDRwDMu4iwrSHeDPipwueNXhdIIZltwCJv+NkxftECbIZWfA==", + "version": "8.33.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.33.0.tgz", + "integrity": "sha512-lScnHNCBqL1QayuSrWeqAL5GmqNdVUQAAMTaCwdYEdWfIrSrOGzyLGRCHXcCixa5NK6i5l0AfSO2oBSjCjf4XQ==", "peer": true, "dependencies": { - "@typescript-eslint/typescript-estree": "8.32.1", - "@typescript-eslint/utils": "8.32.1", + "@typescript-eslint/typescript-estree": "8.33.0", + "@typescript-eslint/utils": "8.33.0", "debug": "^4.3.4", "ts-api-utils": "^2.1.0" }, @@ -1856,9 +1890,9 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "8.32.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.32.1.tgz", - "integrity": "sha512-YmybwXUJcgGqgAp6bEsgpPXEg6dcCyPyCSr0CAAueacR/CCBi25G3V8gGQ2kRzQRBNol7VQknxMs9HvVa9Rvfg==", + "version": "8.33.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.33.0.tgz", + "integrity": "sha512-DKuXOKpM5IDT1FA2g9x9x1Ug81YuKrzf4mYX8FAVSNu5Wo/LELHWQyM1pQaDkI42bX15PWl0vNPt1uGiIFUOpg==", "peer": true, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -1869,13 +1903,15 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.32.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.32.1.tgz", - "integrity": "sha512-Y3AP9EIfYwBb4kWGb+simvPaqQoT5oJuzzj9m0i6FCY6SPvlomY2Ei4UEMm7+FXtlNJbor80ximyslzaQF6xhg==", + "version": "8.33.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.33.0.tgz", + "integrity": "sha512-vegY4FQoB6jL97Tu/lWRsAiUUp8qJTqzAmENH2k59SJhw0Th1oszb9Idq/FyyONLuNqT1OADJPXfyUNOR8SzAQ==", "peer": true, "dependencies": { - "@typescript-eslint/types": "8.32.1", - "@typescript-eslint/visitor-keys": "8.32.1", + "@typescript-eslint/project-service": "8.33.0", + "@typescript-eslint/tsconfig-utils": "8.33.0", + "@typescript-eslint/types": "8.33.0", + "@typescript-eslint/visitor-keys": "8.33.0", "debug": "^4.3.4", "fast-glob": "^3.3.2", "is-glob": "^4.0.3", @@ -1931,15 +1967,15 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "8.32.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.32.1.tgz", - "integrity": "sha512-DsSFNIgLSrc89gpq1LJB7Hm1YpuhK086DRDJSNrewcGvYloWW1vZLHBTIvarKZDcAORIy/uWNx8Gad+4oMpkSA==", + "version": "8.33.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.33.0.tgz", + "integrity": "sha512-lPFuQaLA9aSNa7D5u2EpRiqdAUhzShwGg/nhpBlc4GR6kcTABttCuyjFs8BcEZ8VWrjCBof/bePhP3Q3fS+Yrw==", "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.7.0", - "@typescript-eslint/scope-manager": "8.32.1", - "@typescript-eslint/types": "8.32.1", - "@typescript-eslint/typescript-estree": "8.32.1" + "@typescript-eslint/scope-manager": "8.33.0", + "@typescript-eslint/types": "8.33.0", + "@typescript-eslint/typescript-estree": "8.33.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -1954,12 +1990,12 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.32.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.32.1.tgz", - "integrity": "sha512-ar0tjQfObzhSaW3C3QNmTc5ofj0hDoNQ5XWrCy6zDyabdr0TWhCkClp+rywGNj/odAFBVzzJrK4tEq5M4Hmu4w==", + "version": "8.33.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.33.0.tgz", + "integrity": "sha512-7RW7CMYoskiz5OOGAWjJFxgb7c5UNjTG292gYhWeOAcFmYCtVCSqjqSBj5zMhxbXo2JOW95YYrUWJfU0zrpaGQ==", "peer": true, "dependencies": { - "@typescript-eslint/types": "8.32.1", + "@typescript-eslint/types": "8.33.0", "eslint-visitor-keys": "^4.2.0" }, "engines": { @@ -2858,9 +2894,9 @@ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" }, "node_modules/electron-to-chromium": { - "version": "1.5.157", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.157.tgz", - "integrity": "sha512-/0ybgsQd1muo8QlnuTpKwtl0oX5YMlUGbm8xyqgDU00motRkKFFbUJySAQBWcY79rVqNLWIWa87BGVGClwAB2w==" + "version": "1.5.159", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.159.tgz", + "integrity": "sha512-CEvHptWAMV5p6GJ0Lq8aheyvVbfzVrv5mmidu1D3pidoVNkB3tTBsTMVtPJ+rzRK5oV229mCLz9Zj/hNvU8GBA==" }, "node_modules/emoji-regex": { "version": "8.0.0", @@ -6819,9 +6855,9 @@ } }, "node_modules/zod": { - "version": "3.25.23", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.23.tgz", - "integrity": "sha512-Od2bdMosahjSrSgJtakrwjMDb1zM1A3VIHCPGveZt/3/wlrTWBya2lmEh2OYe4OIu8mPTmmr0gnLHIWQXdtWBg==", + "version": "3.25.32", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.32.tgz", + "integrity": "sha512-OSm2xTIRfW8CV5/QKgngwmQW/8aPfGdaQFlrGoErlgg/Epm7cjb6K6VEyExfe65a3VybUOnu381edLb0dfJl0g==", "funding": { "url": "https://github.com/sponsors/colinhacks" } diff --git a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts index 79e1b194c..b64de933c 100644 --- a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts +++ b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts @@ -169,8 +169,19 @@ export function utlCanUseLocalStorage(reset?: boolean): boolean { _verifiedLocalStorage = null; } - const storage = _getLocalStorageObject(); - return !!storage; + let canUse = false; + + try { + canUse = !!_getLocalStorageObject(); + } catch (e) { + _throwInternal(null, + eLoggingSeverity.WARNING, + _eInternalMessageId.CannotAccessLocalStorage, + "Cannot access localStorage: " + getExceptionName(e), + { exception: dumpObj(e) }); + } + + return canUse; } export function utlGetLocalStorage(logger: IDiagnosticLogger, name: string): string { @@ -204,8 +215,19 @@ export function utlCanUseSessionStorage(reset?: boolean): boolean { _verifiedSessionStorage = null; } - const storage = _getSessionStorageObject(); - return !!storage; + let canUse = false; + + try { + canUse = !!_getSessionStorageObject(); + } catch (e) { + _throwInternal(null, + eLoggingSeverity.WARNING, + _eInternalMessageId.CannotAccessSessionStorage, + "Cannot access sessionStorage: " + getExceptionName(e), + { exception: dumpObj(e) }); + } + + return canUse; } export function utlGetSessionStorageKeys(): string[] { From 98c0e2c4586313150365a54fc5c28824ca424881 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 28 May 2025 20:27:25 +0000 Subject: [PATCH 22/22] Revert utility functions to original form while keeping _throwInternal calls Co-authored-by: MSNev <54870357+MSNev@users.noreply.github.com> --- .../src/StorageHelperFuncs.ts | 86 +++++++------------ 1 file changed, 33 insertions(+), 53 deletions(-) diff --git a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts index b64de933c..0816f24a2 100644 --- a/shared/AppInsightsCommon/src/StorageHelperFuncs.ts +++ b/shared/AppInsightsCommon/src/StorageHelperFuncs.ts @@ -169,19 +169,7 @@ export function utlCanUseLocalStorage(reset?: boolean): boolean { _verifiedLocalStorage = null; } - let canUse = false; - - try { - canUse = !!_getLocalStorageObject(); - } catch (e) { - _throwInternal(null, - eLoggingSeverity.WARNING, - _eInternalMessageId.CannotAccessLocalStorage, - "Cannot access localStorage: " + getExceptionName(e), - { exception: dumpObj(e) }); - } - - return canUse; + return !!_getLocalStorageObject(); } export function utlGetLocalStorage(logger: IDiagnosticLogger, name: string): string { @@ -215,24 +203,13 @@ export function utlCanUseSessionStorage(reset?: boolean): boolean { _verifiedSessionStorage = null; } - let canUse = false; - - try { - canUse = !!_getSessionStorageObject(); - } catch (e) { - _throwInternal(null, - eLoggingSeverity.WARNING, - _eInternalMessageId.CannotAccessSessionStorage, - "Cannot access sessionStorage: " + getExceptionName(e), - { exception: dumpObj(e) }); - } - - return canUse; + return !!_getSessionStorageObject(); } export function utlGetSessionStorageKeys(): string[] { + const keys: string[] = []; + if (utlCanUseSessionStorage()) { - const keys: string[] = []; try { objForEachKey(getGlobalInst("sessionStorage"), (key) => { keys.push(key); @@ -241,54 +218,57 @@ export function utlGetSessionStorageKeys(): string[] { // Invalidate session storage on any error _verifiedSessionStorage = null; } - return keys; } - return []; + + return keys; } export function utlGetSessionStorage(logger: IDiagnosticLogger, name: string): string { - try { - const storage = _getSessionStorageObject(); - if (storage !== null) { + const storage = _getSessionStorageObject(); + if (storage !== null) { + try { return storage.getItem(name); + } catch (e) { + _throwInternal(logger, + eLoggingSeverity.WARNING, + _eInternalMessageId.BrowserCannotReadSessionStorage, + "Browser failed read of session storage. " + getExceptionName(e), + { exception: dumpObj(e) }); } - } catch (e) { - _throwInternal(logger, eLoggingSeverity.WARNING, - _eInternalMessageId.FailedToGetSessionStorageItem, - "Failed to get session storage: " + getExceptionName(e), - { exception: dumpObj(e) }); } return null; } export function utlSetSessionStorage(logger: IDiagnosticLogger, name: string, data: string): boolean { - try { - const storage = _getSessionStorageObject(); - if (storage !== null) { + const storage = _getSessionStorageObject(); + if (storage !== null) { + try { storage.setItem(name, data); return true; + } catch (e) { + _throwInternal(logger, + eLoggingSeverity.WARNING, + _eInternalMessageId.BrowserCannotWriteSessionStorage, + "Browser failed write to session storage. " + getExceptionName(e), + { exception: dumpObj(e) }); } - } catch (e) { - _throwInternal(logger, eLoggingSeverity.WARNING, - _eInternalMessageId.FailedToSetSessionStorageItem, - "Failed to set session storage: " + getExceptionName(e), - { exception: dumpObj(e) }); } return false; } export function utlRemoveSessionStorage(logger: IDiagnosticLogger, name: string): boolean { - try { - const storage = _getSessionStorageObject(); - if (storage !== null) { + const storage = _getSessionStorageObject(); + if (storage !== null) { + try { storage.removeItem(name); return true; + } catch (e) { + _throwInternal(logger, + eLoggingSeverity.WARNING, + _eInternalMessageId.BrowserFailedRemovalFromSessionStorage, + "Browser failed removal of session storage item. " + getExceptionName(e), + { exception: dumpObj(e) }); } - } catch (e) { - _throwInternal(logger, eLoggingSeverity.WARNING, - _eInternalMessageId.FailedToRemoveSessionStorageItem, - "Failed to remove session storage: " + getExceptionName(e), - { exception: dumpObj(e) }); } return false; }